wyrm-mcp 9.5.0 → 9.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -3
- package/dist/autoconfig.js +21 -21
- package/dist/database.js +10 -10
- package/dist/event-identity.js +1 -0
- package/dist/event-replication.js +1 -1
- package/dist/events.js +11 -11
- package/dist/federation.js +11 -11
- package/dist/handlers/companion.js +10 -17
- package/dist/http-fast.js +20 -20
- package/dist/lineage.js +18 -11
- package/dist/migrations.js +37 -23
- package/dist/store-readonly.js +1 -1
- package/dist/text-columns.js +1 -1
- package/dist/tool-manifest-v2.json +1 -1
- package/dist/tool-manifest.json +1 -1
- package/dist/version-check.js +4 -4
- package/dist/wyrm-manifest.json +1 -1
- package/package.json +3 -2
- package/scripts/smoke-platform.mjs +1 -1
package/README.md
CHANGED
|
@@ -8,8 +8,9 @@
|
|
|
8
8
|
</p>
|
|
9
9
|
|
|
10
10
|
<p align="center">
|
|
11
|
-
<b>
|
|
12
|
-
|
|
11
|
+
<b>The intelligence layer for AI agents, over MCP.</b><br/>
|
|
12
|
+
Persistent memory is the base: ground truths, recorded failures, decision causality, and hybrid recall.<br/>
|
|
13
|
+
Wyrm acts on that memory. It blocks a repeated mistake, flags a decision whose facts changed, and chooses what the model reads.<br/>
|
|
13
14
|
A structured SQLite memory on your machine. No cloud, no separate LLM.
|
|
14
15
|
</p>
|
|
15
16
|
|
|
@@ -24,7 +25,16 @@
|
|
|
24
25
|
|
|
25
26
|
## What it is
|
|
26
27
|
|
|
27
|
-
Most AI coding sessions start from zero. Wyrm gives the agent a memory that persists across them. It keeps your project's decisions, conventions, open work, and dead-ends in a structured database on your own machine, and hands them back to the model at the start of the next session. An agent connected to Wyrm recalls what was decided last week instead of re-deriving it
|
|
28
|
+
Most AI coding sessions start from zero. Wyrm gives the agent a memory that persists across them. It keeps your project's decisions, conventions, open work, and dead-ends in a structured database on your own machine, and hands them back to the model at the start of the next session. An agent connected to Wyrm recalls what was decided last week instead of re-deriving it.
|
|
29
|
+
|
|
30
|
+
That memory is the base. The intelligence layer is what Wyrm does with it:
|
|
31
|
+
|
|
32
|
+
- **It blocks a repeated mistake before it runs.** When a failure you recorded or confirmed is on record and the agent proposes the same action, the guard hook in Claude Code refuses it and gives the recorded reason. A failure an agent recorded warns until you confirm it. In other clients the agent asks `wyrm_failure_check` before it retries.
|
|
33
|
+
- **It flags decisions when the facts they rest on change.** A decision can be linked to the ground truths behind it. When one of those truths is replaced with a different value, Wyrm marks the decisions that rested on it and warns the agent to re-evaluate when it next looks up their basis.
|
|
34
|
+
- **It lets one agent's recorded failure warn the others.** Every failure is attributed to the agent and run that recorded it, so one worker's dead-end is on record for the rest and warns them before they walk into it.
|
|
35
|
+
- **It chooses what the model reads.** Content from an untrusted source is kept out of the context brief. Since 9.5.0 the session brief is also shaped for the model reading it, for the models whose documented behaviour calls for it; every other model gets the brief unchanged.
|
|
36
|
+
|
|
37
|
+
The firewall and recall are measured, and the numbers are below under [Measured, not asserted](#measured-not-asserted) and [Why Wyrm](#why-wyrm), where the red-team result for the untrusted-content quarantine also sits. The decision flags, the fleet warnings and the per-model brief are described here as behaviour, with no benchmark behind them.
|
|
28
38
|
|
|
29
39
|
It speaks the Model Context Protocol, so it drops into Claude, Cursor, Copilot, Windsurf, and Codex without glue code.
|
|
30
40
|
|
package/dist/autoconfig.js
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
|
-
import{existsSync as l,readFileSync as h,writeFileSync as p,mkdirSync as b,chmodSync as J}from"fs";import{homedir as
|
|
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
2
|
`)[0];break}case"cursor":{const t=P("cursor",["--version"],{encoding:"utf-8",timeout:5e3});if(t.stdout)return t.stdout.split(`
|
|
3
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
|
|
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`+(
|
|
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
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:
|
|
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(
|
|
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 ")),
|
|
10
|
-
`,"utf-8"),{client:t,action:
|
|
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??
|
|
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??
|
|
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
|
|
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
|
|
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
|
|
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(
|
|
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
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
|
|
19
|
-
`,"utf-8")}function ie(){const e=
|
|
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}
|
|
20
20
|
## Wyrm Memory + Agent (auto-managed \u2014 do not edit this section)
|
|
21
21
|
|
|
22
22
|
**Session start** \u2014 call \`wyrm_session_prime\` first to load project context (ground truths, open quests, recent sessions, scaffolds) before responding.
|
|
@@ -37,26 +37,26 @@ import{existsSync as l,readFileSync as h,writeFileSync as p,mkdirSync as b,chmod
|
|
|
37
37
|
|
|
38
38
|
**Know what Wyrm can do** \u2014 call \`wyrm_capabilities\` once per session to get the full feature inventory (counter-patterns, ground truths, scaffolds, agent loop, outbound MCP, federation, audit chain, \u2026). Reach for the right tool the first time instead of re-discovering the surface mid-conversation.
|
|
39
39
|
|
|
40
|
-
**Keep wyrm-mcp current
|
|
40
|
+
**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
41
|
|
|
42
42
|
**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
|
|
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(`
|
|
44
44
|
`)?`
|
|
45
45
|
`:`
|
|
46
46
|
|
|
47
47
|
`;p(r,`${d}${m}${B}
|
|
48
48
|
`,"utf-8")}}else p(r,`${B}
|
|
49
|
-
`,"utf-8");n.injected.push(i)}catch(
|
|
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
50
|
`;)o++;t+=`
|
|
51
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=
|
|
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
53
|
|
|
54
54
|
`;o+=` Detected: ${t.length}/${e.length} AI clients
|
|
55
55
|
`,o+=` Configured: ${n.length}/${t.length} clients
|
|
56
56
|
|
|
57
|
-
`;for(const r of e){const i=r.detected?r.configured?" \u25CF":" \u25D0":" \u25CB",
|
|
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
58
|
`}const s=ie();return s&&(o+=`
|
|
59
59
|
Server: ${s.serverPath}
|
|
60
60
|
`,o+=` DB: ${s.dbPath}
|
|
61
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,
|
|
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};
|
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
|
|
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
|
|
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 = ?"}},
|
|
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(`
|
|
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
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(`
|
|
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=
|
|
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(`
|
|
12
12
|
INSERT INTO projects (name, path, repo, stack, last_commit, branch)
|
|
13
13
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
14
14
|
ON CONFLICT(path) DO UPDATE SET
|
|
@@ -29,7 +29,7 @@ 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}=
|
|
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(`
|
|
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
|
|
@@ -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
|
|
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(`
|
|
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 ${
|
|
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(`
|
|
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,13 +206,13 @@ 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,N,
|
|
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(`
|
|
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}
|
|
213
213
|
ORDER BY rank
|
|
214
214
|
LIMIT ?
|
|
215
|
-
`);return s?n.all(r,s,e):n.all(r,e)}getSkillGraph(t){const e=this.db.prepare("SELECT * FROM skills").all(),s=new Map;for(const o of e)s.set(o.name,o);const r=o=>{if(!o)return[];try{const c=JSON.parse(o);return Array.isArray(c)?c.filter(l=>typeof l=="string"):[]}catch{return[]}},i=(o,c)=>{const l=s.get(o);if(!l)return null;const d=r(l.governs),f=r(l.composes),T={name:l.name,tier:l.tier??"atomic",description:l.description,governs:d,composes:f,children:[]},
|
|
215
|
+
`);return s?n.all(r,s,e):n.all(r,e)}getSkillGraph(t){const e=this.db.prepare("SELECT * FROM skills").all(),s=new Map;for(const o of e)s.set(o.name,o);const r=o=>{if(!o)return[];try{const c=JSON.parse(o);return Array.isArray(c)?c.filter(l=>typeof l=="string"):[]}catch{return[]}},i=(o,c)=>{const l=s.get(o);if(!l)return null;const d=r(l.governs),f=r(l.composes),T={name:l.name,tier:l.tier??"atomic",description:l.description,governs:d,composes:f,children:[]},b=[];if(!c.has(o)){const g=new Set(c).add(o);for(const N of d){const O=i(N,g);O?T.children.push(O):b.push(N)}}return b.length&&(T.missing=b),T};if(t){const o=i(t,new Set);return o?[o]:[]}const n=e.filter(o=>(o.tier??"atomic")==="god").map(o=>o.name).sort(),a=[];for(const o of n){const c=i(o,new Set);c&&a.push(c)}return a}updateSkill(t,e){const s=[],r=[];return e.description!==void 0&&(s.push("description = ?"),r.push(E(e.description))),e.skill_path!==void 0&&(s.push("skill_path = ?"),r.push(e.skill_path)),e.category!==void 0&&(s.push("category = ?"),r.push(e.category)),e.is_active!==void 0&&(s.push("is_active = ?"),r.push(e.is_active?1:0)),e.tags!==void 0&&(s.push("tags = ?"),r.push(E(e.tags))),e.version!==void 0&&(s.push("version = ?"),r.push(e.version)),s.length===0?this.getSkill(t):(s.push("updated_at = datetime('now')"),r.push(t),this.db.prepare(`
|
|
216
216
|
UPDATE skills SET ${s.join(", ")} WHERE name = ? RETURNING *
|
|
217
217
|
`).get(...r))}deleteSkill(t){return this.db.prepare("DELETE FROM skills WHERE name = ?").run(t).changes>0}deactivateSkill(t){return this.updateSkill(t,{is_active:!1})}activateSkill(t){return this.updateSkill(t,{is_active:!0})}getSkillStats(){const t=this.db.prepare("SELECT COUNT(*) as count FROM skills").get().count,e=this.db.prepare("SELECT COUNT(*) as count FROM skills WHERE is_active = 1").get().count,s=this.db.prepare(`
|
|
218
218
|
SELECT category, COUNT(*) as count FROM skills WHERE category IS NOT NULL GROUP BY category
|
|
@@ -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=
|
|
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(`
|
|
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{
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createHash as r}from"node:crypto";const o=256,s=64*1024,i=80,p=/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Cs}]|[^\P{Zs} ]|^ | $/u;function d(e){return typeof e=="string"&&e.length>=1&&e.length<=i&&!p.test(e)}function c(e){return e.normalize("NFKD").replace(/[\p{M}\p{Default_Ignorable_Code_Point}\p{White_Space}\u2800]/gu,"").replace(/[\p{Pd}\u2212]/gu,"-").toLowerCase()}function f(e){let t=e.slice(0,24);return/[\ud800-\udbff]$/.test(t)&&(t=t.slice(0,-1)),t.replace(/[\p{Cc}\p{Cf}\p{Z}\p{Cs}]/gu,"-")}const l=e=>typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:null;function _(e){const t=JSON.stringify([1,e.kind,e.ref_table??null,e.ref_id??null,e.actor??null,e.is_shared?1:0,e.payload_json??null,l(e.created_at),e.agent_id??null,e.run_id??null]);return r("sha256").update(t).digest("hex").slice(0,32)}const n=e=>typeof e=="string"?e.slice(0,o):null;function g(e){const t=e.is_shared?1:0,a=t&&typeof e.payload_json=="string"&&e.payload_json.length<=s?e.payload_json:null;return _({kind:e.kind,ref_table:n(e.ref_table),ref_id:n(e.ref_id),actor:n(e.actor),is_shared:t,payload_json:a,created_at:l(e.created_at),agent_id:null,run_id:null})}export{i as MAX_DEVICE_ID_LEN,o as MAX_EVENT_FIELD_LEN,s as MAX_EVENT_PAYLOAD_BYTES,c as deviceIdSkeleton,f as deviceIdStem,_ as eventContentHash,d as isValidDeviceId,g as relayHash};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{logger as
|
|
1
|
+
import{logger as P}from"./logger.js";import{guardedFetchJson as M,checkPeerUrl as F}from"./repl-guard.js";const E=500,k=e=>`repl:push:${e.baseUrl}:${e.localProjectId}`,N=e=>`repl:pull:${e.baseUrl}:${e.localProjectId}`,L=e=>Number.parseInt(e||"0",10)||0;function O(e){const r={"Content-Type":"application/json"};return e&&(r.Authorization=`Bearer ${e}`),r}function R(e){return{origin_device:e.origin_device,origin_epoch:e.origin_epoch??0,origin_seq:e.origin_seq,cloud_cursor:e.cursor,kind:e.kind,ref_table:e.ref_table,ref_id:e.ref_id,actor:e.actor,is_shared:e.is_shared,payload_json:e.payload_json,created_at:e.created_at}}const C={own_device_over_push:"it names the peer's own device at another epoch, which a store never accepts by this route; the peer takes such events when it pulls from this store",device_id:"the peer does not accept that device id (control, format or stray whitespace characters, or over 80 long)",device_id_lookalike:"that device id reads the same as the peer's own id without being it",epoch:"its origin_epoch is not a non-negative integer",no_channel:"the peer could not tell which caller sent it"},D={device_id:"this version does not accept that device id (control, format or stray whitespace characters, or over 80 long)",device_id_lookalike:"that device id reads the same as this store's own id without being it",epoch:"its origin_epoch is not a non-negative integer"},H=200,j=e=>`repl:push-refused:${e.baseUrl}:${e.localProjectId}`;function T(e,r){try{const i=JSON.parse(e.getMeta(j(r))||"{}");return{cursors:(Array.isArray(i.cursors)?i.cursors.filter(t=>Number.isSafeInteger(t)&&t>0):[]).slice(-H),dropped:Number.isSafeInteger(i.dropped)&&i.dropped>0?i.dropped:0}}catch{return{cursors:[],dropped:0}}}async function q(e,r,i){const o=F(r.baseUrl);if(!o.ok)return{pushed:0,error:`push: ${o.reason}`};const t=L(e.getMeta(k(r))),f=T(e,r),c=[];for(const n of f.cursors){const u=e.eventsForPush(r.localProjectId,n-1,1)[0];u&&u.cursor===n&&c.push(u)}const h=e.eventsForPush(r.localProjectId,t,E-c.length);if(h.length===0&&c.length===0)return f.cursors.length>0&&e.setMeta(j(r),JSON.stringify({cursors:[],dropped:0})),{pushed:0};const y=[...c,...h];try{const n=await M(i,r.baseUrl,"/events",{method:"POST",headers:O(r.token),body:JSON.stringify({project:r.remoteProject,events:y.map(R)})})??{};if(typeof n.e=="string"&&n.e)return{pushed:0,error:`push: peer answered an error: ${n.e.slice(0,200)}`};const u=typeof n.refused=="number"&&n.refused>0?Math.floor(n.refused):0,p=Array.isArray(n.results)&&n.results.length===y.length?n.results:null;if(u>0&&!p)return{pushed:0,refused:u,error:`push: peer refused ${u} event(s) and did not say which; nothing was marked as sent`};h.length>0&&e.setMeta(k(r),String(h[h.length-1].cursor));const g=p?y.filter((_,U)=>p[U]==="refused"):[];if(g.length===0)return(f.cursors.length>0||f.dropped>0)&&e.setMeta(j(r),JSON.stringify({cursors:[],dropped:0})),{pushed:h.length};const l=g.map(_=>_.cursor),v=Math.max(0,l.length-H),w=f.dropped+v;e.setMeta(j(r),JSON.stringify({cursors:l.slice(v),dropped:w}));const S=g[0],s=Array.isArray(n.reasons)&&n.reasons.length===y.length?n.reasons:null,a=s?s[y.indexOf(S)]:null,m=`push: peer refused ${g.length} event(s), first ${S.origin_device}/${S.origin_epoch??0}/${S.origin_seq}: ${C[String(a)]??"the peer did not say why"}; `+(w>0?`${l.length-v} kept for retry, ${w} no longer retried`:"kept for retry");P.warn("live-memory: push refused by peer",{peer:r.baseUrl,refused:g.length,dropped:w});const $=new Set(l);return{pushed:h.filter(_=>!$.has(_.cursor)).length,refused:g.length,error:m}}catch(n){const u=n instanceof Error?n.message:String(n);return P.warn("live-memory: push failed",{peer:r.baseUrl,err:u}),{pushed:0,error:`push: ${u}`}}}const J=200,B=1e6,x=e=>`repl:pull-held:${e.baseUrl}:${e.localProjectId}`,z=new Set(["device_id"]);function K(e,r){try{const i=JSON.parse(e.getMeta(x(r))||"{}"),o=Array.isArray(i)?i:i?.events,t=Array.isArray(i)?0:i?.dropped;return{events:(Array.isArray(o)?o:[]).filter(c=>!!c&&typeof c=="object"&&Number.isSafeInteger(c.cursor)&&!!c.ev&&typeof c.ev=="object").map(c=>({cursor:c.cursor,ev:c.ev,size:JSON.stringify(c.ev).length})).slice(-J),dropped:typeof t=="number"&&Number.isSafeInteger(t)&&t>0?t:0}}catch{return{events:[],dropped:0}}}function X(e){let r=0,i=e.reduce((o,t)=>o+t.size,0);for(;i>B&&e.length>0;){let o=0;for(let t=1;t<e.length;t++)e[t].size>e[o].size&&(o=t);i-=e[o].size,e.splice(o,1),r++}for(;e.length>J;)e.shift(),r++;return r}async function Y(e,r,i){const o=L(e.getMeta(N(r))),t={via:"pull",peer:r.baseUrl},f=s=>e.ingestRemoteEventDetailed?e.ingestRemoteEventDetailed(r.localProjectId,s,t):{result:e.ingestRemoteEvent(r.localProjectId,s,t)};let c=0,h=0,y=0;const n=s=>{s==="inserted"?c++:s==="echo"?y++:h++};let u=null,p=0;const g=K(e,r),l=[];for(const s of g.events){const a=f(s.ev);if(a.result!=="refused"){n(a.result);continue}u??={ev:s.ev,reason:a.reason},z.has(String(a.reason))?l.push(s):p++}let v=g.dropped;const w=()=>{l.length===0&&(v=0),(l.length>0||g.events.length>0||g.dropped>0)&&e.setMeta(x(r),JSON.stringify({events:l.map(({cursor:s,ev:a})=>({cursor:s,ev:a})),dropped:v}))},S=()=>{const s=l.length+p;if(s===0&&v===0)return;const a=[`${l.length} held for retry`];v>0&&a.push(`${v} dropped from the held list (it is full) and not asked for again`),p>0&&a.push(`${p} not held (they can never be accepted)`);const m=u;return`pull: ${s} event(s) from the peer were not accepted`+(m?`, first ${String(m.ev.origin_device)}/${m.ev.origin_epoch??0}/${m.ev.origin_seq}: ${D[String(m.reason)]??"no reason given"}`:"")+`; ${a.join(", ")}`};try{const s=`/events?project=${encodeURIComponent(r.remoteProject)}&since=${o}&limit=${E}&shared=1`,a=await M(i,r.baseUrl,s,{method:"GET",headers:O(r.token)}),m=(Array.isArray(a.events)?a.events:[]).filter(d=>!!d&&typeof d=="object"&&Number.isFinite(d.cursor)).slice(0,E),$=new Set(l.map(d=>d.cursor));let _=o;for(const d of m){const b={...R(d),cloud_cursor:d.cursor},A=f(b);A.result!=="refused"?n(A.result):(u??={ev:b,reason:A.reason},z.has(String(A.reason))?$.has(d.cursor)||(l.push({cursor:d.cursor,ev:b,size:JSON.stringify(b).length}),$.add(d.cursor)):p++),d.cursor>_&&(_=d.cursor)}v+=X(l),e.setMeta(N(r),String(_));const U=S(),I=l.length+p;return w(),U?(P.warn("live-memory: pulled events refused",{peer:r.baseUrl,held:l.length,dropped:v,notHeld:p}),{pulled:c,duplicates:h,echoes:y,refused:I,error:U}):{pulled:c,duplicates:h,echoes:y,refused:I}}catch(s){w();const a=s instanceof Error?s.message:String(s);return P.warn("live-memory: pull failed",{peer:r.baseUrl,err:a}),{pulled:c,duplicates:h,echoes:y,refused:l.length+p,error:`pull: ${a}`}}}async function V(e,r,i){const o=await Y(e,r,i),t=await q(e,r,i),f=[o.error,t.error].filter(c=>!!c);return{pulled:o.pulled,pushed:t.pushed,duplicates:o.duplicates,echoes:o.echoes,refused:o.refused+(t.refused??0),errors:f}}export{J as MAX_HELD_PULL,H as MAX_REFUSED_RETRY,Y as pullPeerEvents,q as pushSharedEvents,V as replicateOnce};
|
package/dist/events.js
CHANGED
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import{logger as
|
|
1
|
+
import{logger as E}from"./logger.js";import{getActor as j}from"./handlers/boundary.js";import{getDeviceId as w,getLineage as M,nextOriginSeq as k}from"./lineage.js";import{redactCredentials as H,redactedJson as q,redactField as R,redactJsonText as W}from"./security.js";import{MAX_EVENT_FIELD_LEN as Y,MAX_EVENT_PAYLOAD_BYTES as P,deviceIdSkeleton as v,eventContentHash as b,isValidDeviceId as X,relayHash as B}from"./event-identity.js";const U=new Set(["capture","session_update","quest","truth","presence","tool_call","failure","decision"]),V=P,u=Y,C=864e5,f=e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=Number.MAX_SAFE_INTEGER,g=(e,t)=>typeof e=="string"?e.slice(0,t):null;function G(){const e=(process.env.WYRM_LIVE_MEMORY||"").toLowerCase();return e!=="0"&&e!=="false"&&e!=="off"}function p(e,t,r,o){const n=typeof e=="number"&&Number.isFinite(e)?Math.floor(e):o;return Math.max(t,Math.min(r,n))}function re(e,t){if(G())try{const{deviceId:r,epoch:o}=M(e),n=t.isShared?1:0;let i=null;if(n&&t.payload!==void 0)try{i=q(t.payload)}catch{i=null}const s=j(),c=t.agentId!==void 0?t.agentId:s.agent_id,d=t.runId!==void 0?t.runId:s.run_id;e.transaction(()=>{const l=k(e,r),a=R(t.refTable??null),_=t.refId!=null?String(t.refId):null,m=R(t.actor??null),S=Date.now();e.prepare(`
|
|
2
2
|
INSERT INTO events
|
|
3
|
-
(origin_device, origin_epoch, origin_seq, project_id, kind, ref_table, ref_id, actor, is_shared, payload_json, created_at, agent_id, run_id)
|
|
4
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5
|
-
`).run(
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
3
|
+
(origin_device, origin_epoch, origin_seq, project_id, kind, ref_table, ref_id, actor, is_shared, payload_json, created_at, agent_id, run_id, received_via, content_hash)
|
|
4
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5
|
+
`).run(r,o,l,String(t.projectId),t.kind,a,_,m,n,i,S,c,d,J,B({kind:t.kind,ref_table:a,ref_id:_,actor:m,is_shared:n,payload_json:i,created_at:S}))})()}catch(r){E.warn("live-memory: emitEvent dropped",{err:r instanceof Error?r.message:String(r)})}}function te(e,t,r=0,o=100){const n=p(o,1,1e3,100),i=p(r,0,Number.MAX_SAFE_INTEGER,0);return e.prepare("SELECT * FROM events WHERE project_id = ? AND cursor > ? ORDER BY cursor ASC LIMIT ?").all(String(t),i,n)}function ne(e,t,r=20){const o=p(r,1,200,20),n=e.prepare("SELECT * FROM events WHERE project_id = ? ORDER BY cursor DESC LIMIT ?").all(String(t),o);return n.reverse(),{cursor:e.prepare("SELECT COALESCE(MAX(cursor), 0) AS c FROM events WHERE project_id = ?").get(String(t)).c,recent:n}}const J="local";function K(e){return!e||typeof e!="object"?null:e.via==="pull"&&typeof e.peer=="string"&&e.peer.trim()?`pull:${H(e.peer.trim()).slice(0,u)}`:e.via==="push"&&typeof e.principal=="string"&&e.principal.trim()?`push:${e.principal.trim().slice(0,u)}`:null}function ie(e,t,r,o){return F(e,t,r,o).result}const h=e=>({result:"refused",reason:e});function F(e,t,r,o){try{const n=K(o);if(!n)return E.warn("live-memory: ingest refused, no channel"),h("no_channel");if(!r||typeof r.origin_device!="string"||!f(r.origin_seq))return{result:"duplicate"};const i=r.origin_device;if(r.origin_epoch!=null&&!f(r.origin_epoch))return h("epoch");const s=r.origin_epoch??0,c=M(e),d=i===c.deviceId;if(d&&s===c.epoch)return{result:"echo"};if(!d){if(!X(i))return h("device_id");if(v(i)===v(c.deviceId))return h("device_id_lookalike")}if(typeof r.kind!="string"||!U.has(r.kind))return{result:"duplicate"};const l=r.is_shared?1:0;let a=l&&typeof r.payload_json=="string"?r.payload_json:null;a&&a.length>V&&(a=null),a&&(a=W(a));const _=Date.now(),m=f(r.created_at)&&r.created_at<=_+C?r.created_at:_,S=f(r.cloud_cursor)?r.cloud_cursor:null,T=g(R(r.ref_table),u),I=g(r.ref_id,u),N=g(R(r.actor),u),y=g(r.agent_id,u),D=g(r.run_id,u),L=b({kind:r.kind,ref_table:T,ref_id:I,actor:N,is_shared:l,payload_json:a,created_at:f(r.created_at)?r.created_at:null,agent_id:y,run_id:D});if(d&&o.via!=="pull")return e.prepare("SELECT 1 FROM events WHERE origin_device = ? AND origin_epoch = ? AND origin_seq = ? AND content_hash = ?").get(i,s,r.origin_seq,L)?{result:"duplicate"}:h("own_device_over_push");let A=!1;return e.transaction(()=>{if(A=e.prepare(`
|
|
6
|
+
INSERT OR IGNORE INTO events
|
|
7
|
+
(origin_device, origin_epoch, origin_seq, cloud_cursor, project_id, kind, ref_table, ref_id, actor, is_shared, payload_json, created_at, agent_id, run_id, received_via, content_hash)
|
|
8
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
9
|
+
`).run(i,s,r.origin_seq,S,String(t),r.kind,T,I,N,l,a,m,y,D,n,L).changes>0,!A)return;const O=e.prepare("SELECT COUNT(*) AS n FROM events WHERE origin_device = ? AND origin_epoch = ? AND origin_seq = ?").get(i,s,r.origin_seq).n;O>1&&(e.prepare("UPDATE events SET origin_conflict = 1 WHERE origin_device = ? AND origin_epoch = ? AND origin_seq = ? AND origin_conflict = 0").run(i,s,r.origin_seq),E.warn("live-memory: two different events claim one origin identity; both kept and marked",{origin_device:i,origin_epoch:s,origin_seq:r.origin_seq,claims:O,via:n}))})(),{result:A?"inserted":"duplicate"}}catch(n){return E.warn("live-memory: ingestRemoteEvent dropped",{err:n instanceof Error?n.message:String(n)}),{result:"duplicate"}}}function oe(e,t,r,o){const n={inserted:0,duplicate:0,echo:0,refused:0,results:[],reasons:[]};for(const i of r){const{result:s,reason:c}=F(e,t,i,{via:"push",principal:o});n.results.push(s),n.reasons.push(s==="refused"?c??null:null),s==="inserted"?n.inserted++:s==="echo"?n.echo++:s==="refused"?n.refused++:n.duplicate++}return n}function se(e,t,r=0,o=200){const n=p(o,1,1e3,200),i=p(r,0,Number.MAX_SAFE_INTEGER,0);try{const c=e.prepare("SELECT sync_policy AS p FROM projects WHERE CAST(id AS TEXT) = ? OR path = ? LIMIT 1").get(String(t),String(t));if(c&&c.p&&c.p!=="team")return[]}catch{}return e.prepare(`
|
|
10
10
|
SELECT * FROM events
|
|
11
11
|
WHERE project_id = ? AND is_shared = 1 AND cursor > ?
|
|
12
12
|
ORDER BY cursor ASC LIMIT ?
|
|
13
|
-
`).all(String(t),i,
|
|
13
|
+
`).all(String(t),i,n).map(({received_via:c,content_hash:d,origin_conflict:l,...a})=>a)}function ce(e,t={}){const r=p(t.olderThanDays,1,3650,90),o=p(t.maxPerProject,1,1e6,5e3);try{if(!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'events'").get())return{deleted:0};let i=0;const s=Date.now()-r*C;i+=e.prepare("DELETE FROM events WHERE created_at < ?").run(s).changes;const c=e.prepare("SELECT project_id FROM events GROUP BY project_id HAVING COUNT(*) > ?").all(o),d=e.prepare(`
|
|
14
14
|
DELETE FROM events WHERE project_id = ? AND cursor <= (
|
|
15
15
|
SELECT cursor FROM events WHERE project_id = ? ORDER BY cursor DESC LIMIT 1 OFFSET ?
|
|
16
16
|
)
|
|
17
|
-
`);for(const{project_id:
|
|
18
|
-
ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(t,
|
|
17
|
+
`);for(const{project_id:l}of c)i+=d.run(l,l,o).changes;return{deleted:i}}catch(n){return E.warn("live-memory: pruneEvents failed",{db:e.name,err:n instanceof Error?n.message:String(n)}),{deleted:0}}}function ae(e,t){return e.prepare("SELECT value FROM wyrm_meta WHERE key = ?").get(t)?.value}function le(e,t,r){e.prepare(`INSERT INTO wyrm_meta (key, value) VALUES (?, ?)
|
|
18
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(t,r)}export{J as LOCAL_CHANNEL,K as channelLabel,re as emitEvent,se as eventsForPush,te as eventsSince,w as getDeviceId,ae as getMeta,oe as ingestPushBatch,ie as ingestRemoteEvent,F as ingestRemoteEventDetailed,G as isLiveMemoryEnabled,ce as pruneEvents,le as setMeta,ne as subscribeEvents};
|
package/dist/federation.js
CHANGED
|
@@ -1,34 +1,34 @@
|
|
|
1
|
-
import{recordGovernanceEvent as
|
|
2
|
-
FROM ${e} t WHERE t.id = ?`).get(r)}catch{return}}shareOutcome(e,r){const
|
|
3
|
-
WHERE is_shared = 1 ${
|
|
1
|
+
import{recordGovernanceEvent as b}from"./governance.js";import{redactInboundRow as k}from"./inbound-redact.js";import{redactCredentials as m}from"./security.js";const g=new WeakSet;function M(a){const e=typeof a?.origin=="string"?a.origin.trim():"",r=typeof a?.principal=="string"?a.principal.trim():"";if(!e)throw new TypeError("authenticatedPeer: origin is required");if(!r)throw new TypeError("authenticatedPeer: principal is required (who the caller authenticated)");if(!Number.isSafeInteger(a?.projectId)||a.projectId<=0)throw new TypeError("authenticatedPeer: projectId must be a positive integer (the local project the pull is bound to)");const i=Object.freeze({origin:e,principal:r,projectId:a.projectId});return g.add(i),i}function S(a){if(!a||typeof a!="object"||!g.has(a))throw new TypeError("federation: an authenticated peer from authenticatedPeer() is required; a bare origin is refused")}const O=5*6e4,A=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})?)?$/;function E(a){if(typeof a!="string")return Number.NaN;const e=A.exec(a);if(!e)return Number.NaN;const[,r,i,t,c="00",n="00",o="00",d="",l="Z"]=e,s=new Date(Date.UTC(Number(r),Number(i)-1,Number(t)));return s.getUTCMonth()!==Number(i)-1||s.getUTCDate()!==Number(t)?Number.NaN:Date.parse(`${r}-${i}-${t}T${c}:${n}:${o}${d?d.slice(0,4):""}${l}`)}const I=a=>a.endsWith("_at")||a==="date",v=864e5,$={sessions:["date","objectives","completed","issues","commits","files_changed","notes","summary","tokens_estimate","is_archived","created_at"],quests:["title","description","priority","status","tags","created_at","completed_at"],ground_truths:["category","key","value","rationale","source","is_current","confidence","last_verified_at","created_at","ttl_days"],memory_artifacts:["kind","problem","constraints","validated_fix","why_it_worked","outcome","tags","confidence","last_validated_at","created_at"],decision_edges:["from_kind","from_id","to_kind","to_id","relation","rationale","confidence","created_at","invalidated_at"]},_={session:{table:"sessions",ts:"created_at"},quest:{table:"quests",ts:"created_at"},truth:{table:"ground_truths",ts:"updated_at"},artifact:{table:"memory_artifacts",ts:"last_accessed_at"},edge:{table:"decision_edges",ts:"created_at"}},C={truth:"ground_truths",memory_artifact:"memory_artifacts",quest:"quests",design_token:"design_tokens",design_reference:"design_references",skill:"skills"};class P{db;constructor(e){this.db=e}share(e,r){const i=_[e];return!i||this.isPrivateGroveRow(i.table,r)?!1:this.db.transaction(()=>{const t=this.db.prepare(`UPDATE ${i.table} SET is_shared = 1 WHERE id = ?`).run(r);return t.changes>0&&b(this.db,"visibility.share",{kind:e,row_id:r,shared:!0}),t.changes>0})()}safeRemoteColumns(e,r){if(!new Set(Object.values(_).map(n=>n.table)).has(e))return[];let t;try{const n=this.db.prepare(`PRAGMA table_info(${e})`).all();t=new Set(n.map(o=>o.name))}catch{return[]}return($[e]??[]).filter(n=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)&&t.has(n)&&n in r)}isPrivateGroveRow(e,r){const i=this.groveOf(e,r);return!i||i.policy==null?!1:i.policy==="private"}groveOf(e,r){try{return this.db.prepare(`SELECT t.project_id AS project_id, (SELECT sync_policy FROM projects WHERE id = t.project_id) AS policy
|
|
2
|
+
FROM ${e} t WHERE t.id = ?`).get(r)}catch{return}}shareOutcome(e,r){const i=_[e];if(!i)return{ok:!1,reason:"not_found"};const t=this.groveOf(i.table,r);return t&&t.policy==="private"?{ok:!1,reason:"private_grove",projectId:t.project_id}:this.share(e,r)?{ok:!0}:{ok:!1,reason:"not_found"}}projectsHasSyncPolicy(){try{return this.db.prepare("PRAGMA table_info(projects)").all().some(e=>e.name==="sync_policy")}catch{return!1}}unshare(e,r){const i=_[e];return i?this.db.transaction(()=>{const t=this.db.prepare(`UPDATE ${i.table} SET is_shared = 0 WHERE id = ?`).run(r);return t.changes>0&&b(this.db,"visibility.share",{kind:e,row_id:r,shared:!1}),t.changes>0})():!1}collectForPush(e,r=500){const i=e??"1970-01-01",t=[],c=this.projectsHasSyncPolicy()?"AND (project_id IS NULL OR project_id IN (SELECT id FROM projects WHERE sync_policy = 'team'))":"";for(const[n,o]of Object.entries(_)){if(t.length>=r)break;const d=n,l=this.db.prepare(`SELECT * FROM ${o.table}
|
|
3
|
+
WHERE is_shared = 1 ${c} AND ${o.ts} > ?
|
|
4
4
|
ORDER BY ${o.ts} ASC
|
|
5
|
-
LIMIT ?`).all(
|
|
5
|
+
LIMIT ?`).all(i,Math.max(1,r-t.length));for(const s of l)t.push({kind:d,id:s.id,project_id:s.project_id??null,payload:s,updated_at:s[o.ts]||new Date().toISOString()})}return t}applyRemote(e,r){if(S(r),!e||typeof e!="object")return{kind:"skipped",reason:"malformed"};if(typeof e.kind!="string"||!Object.hasOwn(_,e.kind))return{kind:"skipped",reason:"malformed"};if(typeof e.id!="number"||!Number.isSafeInteger(e.id)||e.id<=0)return{kind:"skipped",reason:"malformed"};if(!e.payload||typeof e.payload!="object"||Array.isArray(e.payload))return{kind:"skipped",reason:"malformed"};const i=_[e.kind];if(e.project_id!==r.projectId)return{kind:"skipped",reason:"project_mismatch"};const t=E(e.updated_at);if(!Number.isFinite(t))return{kind:"skipped",reason:"bad_timestamp"};const c=Date.now()+O;if(t>c)return{kind:"skipped",reason:"future_timestamp"};const n=k(i.table,e.payload),o=m(r.origin);for(const p of this.safeRemoteColumns(i.table,n)){if(!I(p)||n[p]==null)continue;const u=E(n[p]);if(!Number.isFinite(u))return{kind:"skipped",reason:"bad_timestamp"};if(u>c+(p==="date"?v:0))return{kind:"skipped",reason:"future_timestamp"};if(p===i.ts&&u!==t)return{kind:"skipped",reason:"timestamp_mismatch"}}const d=this.db.prepare(`SELECT ${i.ts} as ts, project_id FROM ${i.table} WHERE id = ?`).get(e.id);if(d&&d.project_id!==r.projectId)return{kind:"skipped",reason:"project_mismatch"};const l=d;if(!l){const p=this.safeRemoteColumns(i.table,n);if(p.length===0)return{kind:"skipped"};if(e.project_id==null)return{kind:"skipped"};const u=["id","project_id",...p],h=u.map(()=>"?").join(","),N=[e.id,e.project_id,...p.map(j=>n[j])];try{return this.db.prepare(`INSERT INTO ${i.table} (${u.join(",")}) VALUES (${h})`).run(...N),{kind:"inserted"}}catch{return{kind:"skipped"}}}const s=E(l.ts);if(Number.isFinite(s)&&s>t){const u=this.db.prepare(`
|
|
6
6
|
INSERT INTO sync_conflicts
|
|
7
7
|
(local_kind, local_id, remote_payload, remote_origin)
|
|
8
8
|
VALUES (?, ?, ?, ?)
|
|
9
|
-
`).run(e.kind,e.id,JSON.stringify(
|
|
9
|
+
`).run(e.kind,e.id,JSON.stringify(n),o).lastInsertRowid;if(e.project_id!=null)try{const h=this.db.prepare(`
|
|
10
10
|
INSERT INTO quests (project_id, title, description, priority, status, tags)
|
|
11
11
|
VALUES (?, ?, ?, 'high', 'pending', 'sync-conflict')
|
|
12
|
-
`).run(e.project_id,`[sync] Resolve conflict on ${e.kind} #${e.id}`,`A remote ${
|
|
12
|
+
`).run(e.project_id,`[sync] Resolve conflict on ${e.kind} #${e.id}`,`A remote ${o} pushed a ${e.kind} that conflicts with a newer local edit. See sync_conflicts row #${u} for the remote payload. Resolve with wyrm_sync_resolve (kept_local | kept_remote | merged).`);this.db.prepare("UPDATE sync_conflicts SET quest_id = ? WHERE id = ?").run(h.lastInsertRowid,u)}catch{}return{kind:"conflict",conflict_id:u}}const f=this.safeRemoteColumns(i.table,n);if(f.length===0)return{kind:"skipped"};const T=f.map(p=>`${p} = ?`).join(", "),R=f.map(p=>n[p]);try{return this.db.prepare(`UPDATE ${i.table} SET ${T} WHERE id = ?`).run(...R,e.id),{kind:"overwritten"}}catch{return{kind:"skipped"}}}recordPush(e,r,i,t){const c=new Date().toISOString();return this.db.prepare(`
|
|
13
13
|
INSERT INTO sync_log
|
|
14
14
|
(direction, remote_origin, kind, count, since_cursor, new_cursor, duration_ms)
|
|
15
15
|
VALUES ('push', ?, 'mixed', ?, ?, ?, ?)
|
|
16
|
-
`).run(
|
|
16
|
+
`).run(m(r),e.length,t??null,c,i),{pushed:e.length,conflicts:0,new_cursor:c,conflict_ids:[]}}applyPull(e,r,i,t){S(r);const c=r.origin,n={};let o=0;for(const l of Array.isArray(e)?e:[]){let s;try{s=this.applyRemote(l,r)}catch{continue}(s.kind==="inserted"||s.kind==="overwritten")&&(o++,n[l.kind]=(n[l.kind]??0)+1)}const d=new Date().toISOString();return this.db.prepare(`
|
|
17
17
|
INSERT INTO sync_log
|
|
18
18
|
(direction, remote_origin, kind, count, since_cursor, new_cursor, duration_ms)
|
|
19
19
|
VALUES ('pull', ?, 'mixed', ?, ?, ?, ?)
|
|
20
|
-
`).run(
|
|
20
|
+
`).run(m(c),o,t??null,d,i),{pulled:o,new_cursor:d,by_kind:n}}latestCursor(e,r){return this.db.prepare(`
|
|
21
21
|
SELECT new_cursor FROM sync_log
|
|
22
22
|
WHERE direction = ? AND remote_origin = ?
|
|
23
23
|
ORDER BY id DESC LIMIT 1
|
|
24
|
-
`).get(e,
|
|
24
|
+
`).get(e,m(r))?.new_cursor??null}unresolvedConflicts(e=50){return this.db.prepare(`
|
|
25
25
|
SELECT id, local_kind, local_id, remote_origin, detected_at, quest_id
|
|
26
26
|
FROM sync_conflicts
|
|
27
27
|
WHERE resolved_at IS NULL
|
|
28
28
|
ORDER BY detected_at DESC LIMIT ?
|
|
29
|
-
`).all(e)}resolveConflict(e,r,
|
|
29
|
+
`).all(e)}resolveConflict(e,r,i){const t=this.db.prepare("SELECT * FROM sync_conflicts WHERE id = ? AND resolved_at IS NULL").get(e);if(!t)return!1;const c=t.source==="cloud"?C[t.local_kind]:_[t.local_kind]?.table;let n=null;if(r==="merged"?n=i??null:r==="kept_remote"&&t.winner!=="remote"?n=JSON.parse(t.remote_payload):r==="kept_local"&&t.winner==="remote"&&t.local_payload&&(n=JSON.parse(t.local_payload)),c&&n){let o=null;if(t.source==="cloud")try{o=new Set(this.db.prepare(`PRAGMA table_info(${c})`).all().map(s=>s.name))}catch{o=new Set}const d=k(c,n),l=Object.keys(d).filter(s=>s!=="id"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)&&(!o||o.has(s)));if(l.length>0){const s=l.map(f=>`${f} = ?`).join(", "),y=l.map(f=>d[f]);try{this.db.prepare(`UPDATE ${c} SET ${s} WHERE id = ?`).run(...y,t.local_id)}catch{}}}if(this.db.prepare(`
|
|
30
30
|
UPDATE sync_conflicts
|
|
31
31
|
SET resolved_at = datetime('now'), resolution = ?
|
|
32
32
|
WHERE id = ?
|
|
33
33
|
`).run(r,e),t.quest_id!=null)try{this.db.prepare(`UPDATE quests SET status = 'completed', completed_at = COALESCE(completed_at, datetime('now')), updated_at = datetime('now')
|
|
34
|
-
WHERE id = ? AND status != 'completed'`).run(t.quest_id)}catch{}return!0}}export{
|
|
34
|
+
WHERE id = ? AND status != 'completed'`).run(t.quest_id)}catch{}return!0}}export{P as Federation,O as REMOTE_CLOCK_SKEW_MS,$ as REMOTE_WRITABLE_COLUMNS,M as authenticatedPeer,E as timestampMs};
|