wyrm-mcp 9.2.2 → 9.2.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.
Files changed (118) hide show
  1. package/dist/activation.js +1 -1
  2. package/dist/agent-loop.js +2 -2
  3. package/dist/audit.js +2 -2
  4. package/dist/autoconfig.js +6 -6
  5. package/dist/backup-cli.js +6 -0
  6. package/dist/backup.js +1 -0
  7. package/dist/bridge.js +1 -1
  8. package/dist/buddy-runner.js +1 -1
  9. package/dist/buddy.js +4 -4
  10. package/dist/capabilities.js +1 -1
  11. package/dist/causality.js +3 -3
  12. package/dist/cloud/cli.js +3 -3
  13. package/dist/cloud/sync-daemon-entrypoint.js +1 -1
  14. package/dist/cloud/sync-engine.js +8 -7
  15. package/dist/cloud-backup.js +4 -4
  16. package/dist/cloud-sync-entrypoint.js +1 -1
  17. package/dist/cloud-sync.js +1 -1
  18. package/dist/connectors/ingest.js +2 -2
  19. package/dist/constellation.js +1 -1
  20. package/dist/context-build-budgeted.js +4 -4
  21. package/dist/context-ranking.js +1 -1
  22. package/dist/daemon-writer.js +1 -1
  23. package/dist/database.js +41 -23
  24. package/dist/design.js +1 -1
  25. package/dist/erasure-cli.js +3 -0
  26. package/dist/erasure-log.js +8 -0
  27. package/dist/erasure.js +1 -0
  28. package/dist/event-replication.js +1 -1
  29. package/dist/events.js +11 -11
  30. package/dist/failure-patterns.js +67 -44
  31. package/dist/federation.js +11 -10
  32. package/dist/governance.js +1 -0
  33. package/dist/handlers/agent.js +4 -4
  34. package/dist/handlers/alias-adapters.js +1 -1
  35. package/dist/handlers/audit.js +1 -1
  36. package/dist/handlers/boundary.js +1 -1
  37. package/dist/handlers/capture.js +54 -52
  38. package/dist/handlers/causality.js +2 -2
  39. package/dist/handlers/cloud.js +9 -9
  40. package/dist/handlers/companion.js +4 -4
  41. package/dist/handlers/entity.js +6 -6
  42. package/dist/handlers/events.js +4 -4
  43. package/dist/handlers/failure.js +15 -12
  44. package/dist/handlers/goals.js +2 -2
  45. package/dist/handlers/intelligence.js +81 -74
  46. package/dist/handlers/mcpclient.js +3 -3
  47. package/dist/handlers/presence.js +1 -1
  48. package/dist/handlers/prompts.js +2 -2
  49. package/dist/handlers/quest.js +11 -4
  50. package/dist/handlers/recall.js +10 -10
  51. package/dist/handlers/resources.js +1 -1
  52. package/dist/handlers/review.js +3 -3
  53. package/dist/handlers/run.js +3 -3
  54. package/dist/handlers/search.js +1 -1
  55. package/dist/handlers/session.js +27 -25
  56. package/dist/handlers/share.js +3 -3
  57. package/dist/handlers/skill.js +2 -2
  58. package/dist/handlers/symbols.js +5 -5
  59. package/dist/handlers/syncops.js +2 -2
  60. package/dist/harvest.js +5 -5
  61. package/dist/hours.js +1 -1
  62. package/dist/http-auth.js +2 -2
  63. package/dist/http-fast.js +17 -17
  64. package/dist/http-projects.js +4 -0
  65. package/dist/http-rate-limit.js +1 -0
  66. package/dist/index-health.js +52 -0
  67. package/dist/index.js +2 -2
  68. package/dist/indexer.js +4 -4
  69. package/dist/intelligence.js +36 -29
  70. package/dist/lane-provenance.js +39 -0
  71. package/dist/license.js +1 -1
  72. package/dist/lineage.js +15 -0
  73. package/dist/live-embedding-state.js +2 -2
  74. package/dist/maintenance.js +2 -2
  75. package/dist/mcp-integrity.js +2 -2
  76. package/dist/memory-artifacts.js +39 -37
  77. package/dist/metabolize.js +9 -7
  78. package/dist/metrics.js +1 -1
  79. package/dist/migrate-prompt.js +1 -1
  80. package/dist/migrations.js +236 -45
  81. package/dist/priority-embed.js +1 -1
  82. package/dist/providers/embedding-provider.js +1 -1
  83. package/dist/readonly-gate.js +1 -1
  84. package/dist/redact-backfill.js +1 -0
  85. package/dist/rehydration.js +30 -20
  86. package/dist/reindex.js +1 -1
  87. package/dist/render-target.js +6 -6
  88. package/dist/repl-guard.js +1 -1
  89. package/dist/replication-daemon-entrypoint.js +1 -1
  90. package/dist/replication-daemon.js +1 -1
  91. package/dist/retention.js +1 -0
  92. package/dist/reverse-bridge.js +6 -6
  93. package/dist/review-sample.js +31 -0
  94. package/dist/security.js +1 -1
  95. package/dist/self-maintenance.js +4 -4
  96. package/dist/served-records.js +8 -2
  97. package/dist/setup-wizard.js +1 -1
  98. package/dist/setup.js +1 -1
  99. package/dist/skill-author.js +2 -2
  100. package/dist/store-open.js +1 -0
  101. package/dist/store-readonly.js +1 -0
  102. package/dist/sub-agent.js +2 -2
  103. package/dist/tool-manifest-v2.json +1 -1
  104. package/dist/tool-manifest.json +1 -1
  105. package/dist/truth-freshness.js +8 -0
  106. package/dist/ui-dashboard.js +4 -4
  107. package/dist/vault.js +1 -1
  108. package/dist/vector-init.js +1 -1
  109. package/dist/vectors.js +4 -3
  110. package/dist/visibility.js +12 -12
  111. package/dist/write-guard.js +1 -0
  112. package/dist/wyrm-cli.js +108 -92
  113. package/dist/wyrm-guard.js +13 -12
  114. package/dist/wyrm-loop.js +3 -3
  115. package/dist/wyrm-manifest.json +1 -1
  116. package/dist/wyrm-memo.js +5 -5
  117. package/package.json +1 -1
  118. package/scripts/hooks/wyrm-session-capture.mjs +3 -0
@@ -1 +1 @@
1
- import{isLoopbackHost as y}from"../receipt.js";import{bundledModelPresent as c}from"./bundled-model.js";import{BundledEmbeddingProvider as _}from"./bundled.js";function m(s){try{const e=new URL(s).hostname.toLowerCase();return y(e)?null:e}catch{return null}}class I{name="local-hash";model="hash-384";dimensions=384;async embed(e){const t=new Float32Array(this.dimensions),r=e.toLowerCase().split(/\s+/);for(let n=0;n<r.length;n++){const i=r[n];for(let a=0;a<i.length;a++){const l=i.charCodeAt(a)*(n+1)*(a+1)%this.dimensions;t[l]+=1/r.length}}const o=Math.sqrt(t.reduce((n,i)=>n+i*i,0));if(o>0)for(let n=0;n<t.length;n++)t[n]/=o;return t}async isReady(){return!0}}class E{name="openai";model;dimensions;remoteHost="api.openai.com";apiKey;timeoutMs;constructor(e,t){this.apiKey=e,this.model=t||"text-embedding-3-small",this.dimensions=this.model.includes("large")?3072:1536;const r=Number(process.env.WYRM_OPENAI_TIMEOUT);this.timeoutMs=Number.isFinite(r)&&r>0?r:8e3}async embed(e){const t=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:this.model}),signal:AbortSignal.timeout(this.timeoutMs)});if(!t.ok){const o=await t.text();throw new Error(`OpenAI embedding API error ${t.status}: ${o}`)}const r=await t.json();return new Float32Array(r.data[0].embedding)}async isReady(){return!!this.apiKey}}class w{name="ollama";model;dimensions;remoteHost;baseUrl;timeoutMs;constructor(e,t){this.baseUrl=e||"http://localhost:11434",this.model=t||"nomic-embed-text",this.dimensions=this.model.includes("mxbai")?1024:768,this.remoteHost=m(this.baseUrl);const r=Number(process.env.WYRM_OLLAMA_TIMEOUT);this.timeoutMs=Number.isFinite(r)&&r>0?r:8e3}async embed(e){const t=await fetch(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,prompt:e}),signal:AbortSignal.timeout(this.timeoutMs)});if(!t.ok){const o=await t.text();throw new Error(`Ollama embedding API error ${t.status}: ${o}`)}const r=await t.json();return new Float32Array(r.embedding)}async isReady(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}}const N={"nvidia/llama-nemotron-embed-1b-v2":"2026-08-25"},b="nvidia/nemotron-3-embed-1b";class h{name="nim";model;remoteHost;dims;baseUrl;apiKey;timeoutMs;static KNOWN_DIMS={"nvidia/nemotron-3-embed-1b":2048,"nvidia/llama-nemotron-embed-vl-1b-v2":2048,"nvidia/llama-nemotron-embed-1b-v2":2048,"nvidia/llama-3.2-nv-embedqa-1b-v2":2048,"nvidia/nv-embedqa-e5-v5":1024,"nvidia/nv-embedqa-mistral-7b-v2":4096,"nvidia/nv-embed-v1":4096};get dimensions(){return this.dims}constructor(e,t,r){this.apiKey=e,this.model=t||process.env.WYRM_NIM_EMBED_MODEL||b,this.baseUrl=(r||process.env.WYRM_NIM_BASE_URL||"https://integrate.api.nvidia.com").replace(/\/+$/,"");const o=Number(process.env.WYRM_NIM_EMBED_DIM);this.dims=Number.isFinite(o)&&o>0?o:h.KNOWN_DIMS[this.model]??2048;const n=Number(process.env.WYRM_NIM_TIMEOUT);this.timeoutMs=Number.isFinite(n)&&n>0?n:8e3,this.remoteHost=m(this.baseUrl)}async embed(e,t="passage"){let r;for(let i=0;;i++){let a=null;try{const l={"Content-Type":"application/json"};if(this.apiKey&&(l.Authorization=`Bearer ${this.apiKey}`),r=await fetch(`${this.baseUrl}/v1/embeddings`,{method:"POST",headers:l,body:JSON.stringify({input:[e],model:this.model,input_type:t,encoding_format:"float",truncate:"END"}),signal:AbortSignal.timeout(this.timeoutMs)}),r.ok||r.status!==429&&r.status<500)break;const p=Number(r.headers?.get?.("retry-after"));a=Number.isFinite(p)&&p>0?Math.min(p*1e3,15e3):500*2**i}catch(l){if(i>=2)throw l;a=500*2**i}if(i>=2)break;await new Promise(l=>{setTimeout(l,a??500)})}if(!r.ok){const i=await r.text();throw new Error(`NIM embedding API error ${r.status}: ${i.slice(0,300)}`)}const n=(await r.json()).data?.[0]?.embedding;if(!Array.isArray(n)||n.length===0)throw new Error("NIM embedding API returned no embedding");return n.length!==this.dims&&(this.dims=n.length),new Float32Array(n)}async isReady(){return this.remoteHost?!!this.apiKey:!0}}class u{name="none";model="none";dimensions=0;async embed(e){return new Float32Array(0)}async isReady(){return!0}}const d="set WYRM_VECTOR_PROVIDER=nim and NVIDIA_API_KEY (or WYRM_NIM_API_KEY) in the server env, then: wyrm index rebuild";function v(s){const e=String(s??"").trim().toLowerCase();return e===""?"auto":e}function f(s){try{return new URL(s),!1}catch{return!0}}function x(s){const e=v(s??process.env.WYRM_VECTOR_PROVIDER);switch(e){case"nim":{const t=process.env.NVIDIA_API_KEY||process.env.WYRM_NIM_API_KEY||"",r=process.env.WYRM_NIM_BASE_URL||"https://integrate.api.nvidia.com";if(f(r))return{requested:e,resolved:"none",model:null,reason:"nim_bad_base_url",fix:"WYRM_NIM_BASE_URL is not a valid URL (needs https://\u2026): "+r,egressHost:null};const o=m(r);if(!t&&o)return{requested:e,resolved:"none",model:null,reason:"nim_missing_key",fix:d,egressHost:null};const n=process.env.WYRM_NIM_EMBED_MODEL||b;return{requested:e,resolved:"nim",model:n,reason:"",fix:"",egressHost:o}}case"openai":return process.env.OPENAI_API_KEY?{requested:e,resolved:"openai",model:"text-embedding-3-small",reason:"",fix:"",egressHost:"api.openai.com"}:{requested:e,resolved:"none",model:null,reason:"openai_missing_key",fix:"set OPENAI_API_KEY, or use the supported provider: "+d,egressHost:null};case"ollama":{const t=process.env.OLLAMA_URL||"http://localhost:11434";return{requested:e,resolved:"ollama",model:process.env.WYRM_EMBED_MODEL||"nomic-embed-text",reason:"ollama_deprecated",fix:"Ollama support is deprecated and leaves in the next major \u2014 "+d,egressHost:m(t),advisory:!0}}case"none":return{requested:e,resolved:"none",model:null,reason:"disabled",fix:"vectors were explicitly disabled; to enable: unset WYRM_VECTOR_PROVIDER and run: wyrm vectors download (local, free) \u2014 or for max recall: "+d,egressHost:null};case"local":return{requested:e,resolved:"local",model:"hash-384",reason:"local_hash_fallback",fix:"local-hash is non-semantic (test only) \u2014 "+d,egressHost:null,advisory:!0};case"auto":return c()?{requested:e,resolved:"bundled",model:"nomic-embed-text-v1.5-int8",reason:"",fix:"",egressHost:null}:{requested:e,resolved:"none",model:null,reason:"no_provider_configured",fix:"run: wyrm vectors download (enables local vector recall, no account needed)",egressHost:null};case"bundled":return c()?{requested:e,resolved:"bundled",model:"nomic-embed-text-v1.5-int8",reason:"",fix:"",egressHost:null}:{requested:e,resolved:"none",model:null,reason:"bundled_model_missing",fix:"run: wyrm vectors download",egressHost:null};default:return{requested:e,resolved:"none",model:null,reason:"no_provider_configured",fix:"unrecognised WYRM_VECTOR_PROVIDER \u2014 unset it and run: wyrm vectors download (local, free), or for max recall: "+d,egressHost:null}}}let M=!1;function O(s){switch(v(s?.provider??process.env.WYRM_VECTOR_PROVIDER)){case"openai":{const t=s?.apiKey||process.env.OPENAI_API_KEY;if(!t)throw new Error("OpenAI provider requires OPENAI_API_KEY");return new E(t,s?.model)}case"ollama":return M||(M=!0,console.error("Wyrm: WYRM_VECTOR_PROVIDER=ollama is deprecated \u2014 the supported embedding provider is NVIDIA NIM ("+d+")")),new w(s?.ollamaUrl||process.env.OLLAMA_URL,s?.model);case"nim":{const t=process.env.NVIDIA_API_KEY||process.env.WYRM_NIM_API_KEY||s?.apiKey||"",r=s?.nimBaseUrl||process.env.WYRM_NIM_BASE_URL||"https://integrate.api.nvidia.com";if(!t&&m(r))throw new Error("NIM provider requires NVIDIA_API_KEY (or WYRM_NIM_API_KEY) for a remote endpoint");return new h(t,s?.model,s?.nimBaseUrl)}case"none":return new u;case"auto":return c()?new _:new u;case"bundled":return c()?new _:new u;case"local":return new I;default:return new u}}function P(s){switch(s.resolved){case"none":return{n:1,label:"keyword"};case"bundled":case"ollama":return{n:2,label:"local vectors"};case"local":return{n:1,label:"keyword (test hash vectors, non-semantic)"};case"nim":return{n:3,label:"max recall"};case"openai":return{n:3,label:"custom (OpenAI)"}}}export{b as DEFAULT_NIM_EMBED_MODEL,I as LocalHashProvider,d as NIM_FIX_LINE,h as NimProvider,u as NoneProvider,w as OllamaProvider,E as OpenAIProvider,N as RETIRED_NIM_EMBED_MODELS,O as createProvider,m as hostIfRemote,v as normalizeProviderKey,x as resolveEmbeddingState,P as tierForResolution};
1
+ import{isLoopbackHost as y}from"../receipt.js";import{bundledModelPresent as c}from"./bundled-model.js";import{BundledEmbeddingProvider as _}from"./bundled.js";function m(s){try{const e=new URL(s).hostname.toLowerCase();return y(e)?null:e}catch{return null}}class I{name="local-hash";model="hash-384";dimensions=384;async embed(e){const t=new Float32Array(this.dimensions),r=e.toLowerCase().split(/\s+/);for(let n=0;n<r.length;n++){const i=r[n];for(let a=0;a<i.length;a++){const l=i.charCodeAt(a)*(n+1)*(a+1)%this.dimensions;t[l]+=1/r.length}}const o=Math.sqrt(t.reduce((n,i)=>n+i*i,0));if(o>0)for(let n=0;n<t.length;n++)t[n]/=o;return t}async isReady(){return!0}}class E{name="openai";model;dimensions;remoteHost="api.openai.com";apiKey;timeoutMs;constructor(e,t){this.apiKey=e,this.model=t||"text-embedding-3-small",this.dimensions=this.model.includes("large")?3072:1536;const r=Number(process.env.WYRM_OPENAI_TIMEOUT);this.timeoutMs=Number.isFinite(r)&&r>0?r:8e3}async embed(e){const t=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({input:e,model:this.model}),signal:AbortSignal.timeout(this.timeoutMs)});if(!t.ok){const o=await t.text();throw new Error(`OpenAI embedding API error ${t.status}: ${o}`)}const r=await t.json();return new Float32Array(r.data[0].embedding)}async isReady(){return!!this.apiKey}}class w{name="ollama";model;dimensions;remoteHost;baseUrl;timeoutMs;constructor(e,t){this.baseUrl=e||"http://localhost:11434",this.model=t||"nomic-embed-text",this.dimensions=this.model.includes("mxbai")?1024:768,this.remoteHost=m(this.baseUrl);const r=Number(process.env.WYRM_OLLAMA_TIMEOUT);this.timeoutMs=Number.isFinite(r)&&r>0?r:8e3}async embed(e){const t=await fetch(`${this.baseUrl}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:this.model,prompt:e}),signal:AbortSignal.timeout(this.timeoutMs)});if(!t.ok){const o=await t.text();throw new Error(`Ollama embedding API error ${t.status}: ${o}`)}const r=await t.json();return new Float32Array(r.embedding)}async isReady(){try{return(await fetch(`${this.baseUrl}/api/tags`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}}const N={"nvidia/llama-nemotron-embed-1b-v2":"2026-08-25"},b="nvidia/nemotron-3-embed-1b";class h{name="nim";model;remoteHost;dims;baseUrl;apiKey;timeoutMs;static KNOWN_DIMS={"nvidia/nemotron-3-embed-1b":2048,"nvidia/llama-nemotron-embed-vl-1b-v2":2048,"nvidia/llama-nemotron-embed-1b-v2":2048,"nvidia/llama-3.2-nv-embedqa-1b-v2":2048,"nvidia/nv-embedqa-e5-v5":1024,"nvidia/nv-embedqa-mistral-7b-v2":4096,"nvidia/nv-embed-v1":4096};get dimensions(){return this.dims}constructor(e,t,r){this.apiKey=e,this.model=t||process.env.WYRM_NIM_EMBED_MODEL||b,this.baseUrl=(r||process.env.WYRM_NIM_BASE_URL||"https://integrate.api.nvidia.com").replace(/\/+$/,"");const o=Number(process.env.WYRM_NIM_EMBED_DIM);this.dims=Number.isFinite(o)&&o>0?o:h.KNOWN_DIMS[this.model]??2048;const n=Number(process.env.WYRM_NIM_TIMEOUT);this.timeoutMs=Number.isFinite(n)&&n>0?n:8e3,this.remoteHost=m(this.baseUrl)}async embed(e,t="passage"){let r;for(let i=0;;i++){let a=null;try{const l={"Content-Type":"application/json"};if(this.apiKey&&(l.Authorization=`Bearer ${this.apiKey}`),r=await fetch(`${this.baseUrl}/v1/embeddings`,{method:"POST",headers:l,body:JSON.stringify({input:[e],model:this.model,input_type:t,encoding_format:"float",truncate:"END"}),signal:AbortSignal.timeout(this.timeoutMs)}),r.ok||r.status!==429&&r.status<500)break;const p=Number(r.headers?.get?.("retry-after"));a=Number.isFinite(p)&&p>0?Math.min(p*1e3,15e3):500*2**i}catch(l){if(i>=2)throw l;a=500*2**i}if(i>=2)break;await new Promise(l=>{setTimeout(l,a??500)})}if(!r.ok){const i=await r.text();throw new Error(`NIM embedding API error ${r.status}: ${i.slice(0,300)}`)}const n=(await r.json()).data?.[0]?.embedding;if(!Array.isArray(n)||n.length===0)throw new Error("NIM embedding API returned no embedding");return n.length!==this.dims&&(this.dims=n.length),new Float32Array(n)}async isReady(){return this.remoteHost?!!this.apiKey:!0}}class u{name="none";model="none";dimensions=0;async embed(e){return new Float32Array(0)}async isReady(){return!0}}const d="set WYRM_VECTOR_PROVIDER=nim and NVIDIA_API_KEY (or WYRM_NIM_API_KEY) in the server env, then: wyrm index rebuild";function v(s){const e=String(s??"").trim().toLowerCase();return e===""?"auto":e}function f(s){try{return new URL(s),!1}catch{return!0}}function x(s){const e=v(s??process.env.WYRM_VECTOR_PROVIDER);switch(e){case"nim":{const t=process.env.NVIDIA_API_KEY||process.env.WYRM_NIM_API_KEY||"",r=process.env.WYRM_NIM_BASE_URL||"https://integrate.api.nvidia.com";if(f(r))return{requested:e,resolved:"none",model:null,reason:"nim_bad_base_url",fix:"WYRM_NIM_BASE_URL is not a valid URL (needs https://\u2026): "+r,egressHost:null};const o=m(r);if(!t&&o)return{requested:e,resolved:"none",model:null,reason:"nim_missing_key",fix:d,egressHost:null};const n=process.env.WYRM_NIM_EMBED_MODEL||b;return{requested:e,resolved:"nim",model:n,reason:"",fix:"",egressHost:o}}case"openai":return process.env.OPENAI_API_KEY?{requested:e,resolved:"openai",model:"text-embedding-3-small",reason:"",fix:"",egressHost:"api.openai.com"}:{requested:e,resolved:"none",model:null,reason:"openai_missing_key",fix:"set OPENAI_API_KEY, or use the supported provider: "+d,egressHost:null};case"ollama":{const t=process.env.OLLAMA_URL||"http://localhost:11434";return{requested:e,resolved:"ollama",model:process.env.WYRM_EMBED_MODEL||"nomic-embed-text",reason:"ollama_deprecated",fix:"Ollama support is deprecated and leaves in the next major; "+d,egressHost:m(t),advisory:!0}}case"none":return{requested:e,resolved:"none",model:null,reason:"disabled",fix:"vectors were explicitly disabled; to enable: unset WYRM_VECTOR_PROVIDER and run: wyrm vectors download (local, free), or for max recall: "+d,egressHost:null};case"local":return{requested:e,resolved:"local",model:"hash-384",reason:"local_hash_fallback",fix:"local-hash is non-semantic (test only); "+d,egressHost:null,advisory:!0};case"auto":return c()?{requested:e,resolved:"bundled",model:"nomic-embed-text-v1.5-int8",reason:"",fix:"",egressHost:null}:{requested:e,resolved:"none",model:null,reason:"no_provider_configured",fix:"run: wyrm vectors download (enables local vector recall, no account needed)",egressHost:null};case"bundled":return c()?{requested:e,resolved:"bundled",model:"nomic-embed-text-v1.5-int8",reason:"",fix:"",egressHost:null}:{requested:e,resolved:"none",model:null,reason:"bundled_model_missing",fix:"run: wyrm vectors download",egressHost:null};default:return{requested:e,resolved:"none",model:null,reason:"no_provider_configured",fix:"unrecognised WYRM_VECTOR_PROVIDER; unset it and run: wyrm vectors download (local, free), or for max recall: "+d,egressHost:null}}}let M=!1;function O(s){switch(v(s?.provider??process.env.WYRM_VECTOR_PROVIDER)){case"openai":{const t=s?.apiKey||process.env.OPENAI_API_KEY;if(!t)throw new Error("OpenAI provider requires OPENAI_API_KEY");return new E(t,s?.model)}case"ollama":return M||(M=!0,console.error("Wyrm: WYRM_VECTOR_PROVIDER=ollama is deprecated; the supported embedding provider is NVIDIA NIM ("+d+")")),new w(s?.ollamaUrl||process.env.OLLAMA_URL,s?.model);case"nim":{const t=process.env.NVIDIA_API_KEY||process.env.WYRM_NIM_API_KEY||s?.apiKey||"",r=s?.nimBaseUrl||process.env.WYRM_NIM_BASE_URL||"https://integrate.api.nvidia.com";if(!t&&m(r))throw new Error("NIM provider requires NVIDIA_API_KEY (or WYRM_NIM_API_KEY) for a remote endpoint");return new h(t,s?.model,s?.nimBaseUrl)}case"none":return new u;case"auto":return c()?new _:new u;case"bundled":return c()?new _:new u;case"local":return new I;default:return new u}}function P(s){switch(s.resolved){case"none":return{n:1,label:"keyword"};case"bundled":case"ollama":return{n:2,label:"local vectors"};case"local":return{n:1,label:"keyword (test hash vectors, non-semantic)"};case"nim":return{n:3,label:"max recall"};case"openai":return{n:3,label:"custom (OpenAI)"}}}export{b as DEFAULT_NIM_EMBED_MODEL,I as LocalHashProvider,d as NIM_FIX_LINE,h as NimProvider,u as NoneProvider,w as OllamaProvider,E as OpenAIProvider,N as RETIRED_NIM_EMBED_MODELS,O as createProvider,m as hostIfRemote,v as normalizeProviderKey,x as resolveEmbeddingState,P as tierForResolution};
@@ -1 +1 @@
1
- const n=new Set(["/sync/push","/events","/events/stream","/ui/homes","/audit"]);function r(t,s){const e=(t||"GET").toUpperCase();return e==="POST"||e==="PUT"||e==="DELETE"||e==="PATCH"||n.has(s)}export{n as READONLY_BLOCKED_READS,r as readonlyBlocks};
1
+ const n=new Set(["/sync/push","/events","/events/stream","/ui/homes","/audit"]);function o(t){const e=(t||"GET").toUpperCase();return e==="POST"||e==="PUT"||e==="DELETE"||e==="PATCH"}function s(t,e){return o(t)||n.has(e)}export{n as READONLY_BLOCKED_READS,o as isWriteMethod,s as readonlyBlocks};
@@ -0,0 +1 @@
1
+ import{redactCredentials as p}from"./security.js";const g=[{table:"ground_truths",columns:["value","rationale"],vectorTypes:[],select:"SELECT id, value, rationale FROM ground_truths",update:"UPDATE ground_truths SET value = ?, rationale = ?, updated_at = datetime('now') WHERE id = ?"},{table:"quests",columns:["title","description"],vectorTypes:["quest","context"],select:"SELECT id, title, description FROM quests",update:"UPDATE quests SET title = ?, description = ?, updated_at = datetime('now') WHERE id = ?"},{table:"sessions",columns:["objectives","completed","issues","notes","summary"],vectorTypes:["session"],select:"SELECT id, objectives, completed, issues, notes, summary FROM sessions",update:"UPDATE sessions SET objectives = ?, completed = ?, issues = ?, notes = ?, summary = ? WHERE id = ?"},{table:"memory_artifacts",columns:["problem","constraints","validated_fix","why_it_worked"],vectorTypes:["artifact"],select:"SELECT id, problem, constraints, validated_fix, why_it_worked FROM memory_artifacts",update:"UPDATE memory_artifacts SET problem = ?, constraints = ?, validated_fix = ?, why_it_worked = ?, updated_at = datetime('now') WHERE id = ?"},{table:"failure_patterns",columns:["description","why_failed","resolution_note"],vectorTypes:[],select:"SELECT id, description, why_failed, resolution_note FROM failure_patterns",update:"UPDATE failure_patterns SET description = ?, why_failed = ?, resolution_note = ? WHERE id = ?"},{table:"tool_call_log",columns:["args_summary","error_message"],vectorTypes:[],select:"SELECT id, args_summary, error_message FROM tool_call_log",update:"UPDATE tool_call_log SET args_summary = ?, error_message = ? WHERE id = ?"},{table:"external_call_log",columns:["args_summary","error_message"],vectorTypes:[],select:"SELECT id, args_summary, error_message FROM external_call_log",update:"UPDATE external_call_log SET args_summary = ?, error_message = ? WHERE id = ?"},{table:"llm_query_log",columns:["query","context_summary","response","error_message"],vectorTypes:[],select:"SELECT id, query, context_summary, response, error_message FROM llm_query_log",update:"UPDATE llm_query_log SET query = ?, context_summary = ?, response = ?, error_message = ? WHERE id = ?"},{table:"usage_events",columns:["error_message"],vectorTypes:[],select:"SELECT id, error_message FROM usage_events WHERE error_message IS NOT NULL",update:"UPDATE usage_events SET error_message = ? WHERE id = ?"}],T="DELETE FROM vectors WHERE content_type = ? AND content_id = ?";function y(r){const e=new Set(r);return{table:"data_lake",columns:["value"],vectorTypes:["note"],select:"SELECT id, category, value FROM data_lake",update:"UPDATE data_lake SET value = ? WHERE id = ?",include:a=>e.has(String(a.category))&&!String(a.value??"").startsWith("ENCRYPTED:")}}function v(r,e){const a=[...g];e.ingestedCategories?.length&&a.push(y(e.ingestedCategories));const i={applied:e.apply,tables:[],vectorsDropped:0};let c=null;if(e.apply)try{c=r.prepare(T)}catch{}for(const t of a){let _;try{_=r.prepare(t.select).all()}catch{continue}const n={table:t.table,scanned:0,rows:0,fields:0},u=[];for(const o of _){if(t.include&&!t.include(o))continue;n.scanned++;let s=0;const d=t.columns.map(m=>{const l=o[m];if(typeof l!="string"||l==="")return l;const E=p(l);return E!==l&&s++,E});s>0&&(n.rows++,n.fields+=s,u.push({id:Number(o.id),values:d}))}if(e.apply&&u.length>0){const o=r.prepare(t.update);r.transaction(()=>{for(const s of u)if(o.run(...s.values,s.id),c)for(const d of t.vectorTypes)i.vectorsDropped+=c.run(d,s.id).changes})()}i.tables.push(n)}return i}export{v as redactBackfill};
@@ -1,19 +1,19 @@
1
- const z=10,P="WYRM_REHYDRATE_MAX_CHARS";function X(i){if(typeof i!="string"||i.length===0)return!1;const e=i.split("_")[0].toLowerCase();return/(?:^|[-.:])(?:cron|scheduled|maintenance)$/.test(e)}const V=/\[IMPORTANT: The user has invoked the "[^"\n]*" skill[^\]]*(?:\]|$)(?:\s*---\r?\n[\s\S]*?(?:\r?\n---[ \t]*(?:\r?\n|$)|$))?/g;function K(i){return i?i.replace(V,"").replace(/\n{3,}/g,`
1
+ import{briefTag as z,checkTruthPaths as J,truthFreshness as Z}from"./truth-freshness.js";import{reviewSampleCounts as tt}from"./review-sample.js";import{looksInjectionShaped as et,trustMarker as rt}from"./context-ranking.js";const st=10,it=5,nt="WYRM_REHYDRATE_MAX_CHARS";function ot(n){if(typeof n!="string"||n.length===0)return!1;const r=n.split("_")[0].toLowerCase();return/(?:^|[-.:])(?:cron|scheduled|maintenance)$/.test(r)}const at=/\[IMPORTANT: The user has invoked the "[^"\n]*" skill[^\]]*(?:\]|$)(?:\s*---\r?\n[\s\S]*?(?:\r?\n---[ \t]*(?:\r?\n|$)|$))?/g;function ct(n){return n?n.replace(at,"").replace(/\n{3,}/g,`
2
2
 
3
- `).trim():""}function f(i,e){return i.length<=e?i:`${i.slice(0,Math.max(0,e-2)).trimEnd()} \u2026`}function E(i){return i.replace(/\s+/g," ").trim()}function _(i){return i.replace(/\r?\n/g,`
4
- `)}class G{budget;lines=[];used=0;constructor(e){this.budget=e}fits(e,a=0){return this.used+e.length+1+a<=this.budget}push(e){this.lines.push(e),this.used+=e.length+1}get chars(){return this.used}remaining(){return this.budget-this.used}}const q=160,b={narrative:.25,truths:.2,failures:.25,artifacts:.15};class J{db;constructor(e){this.db=e}latestSessionId(e,a){let r;try{r=this.db.prepare(`
3
+ `).trim():""}function h(n,r){return n.length<=r?n:`${n.slice(0,Math.max(0,r-2)).trimEnd()} \u2026`}function m(n){return n.replace(/\s+/g," ").trim()}function d(n){return n.replace(/\r?\n/g,`
4
+ `)}class lt{budget;lines=[];used=0;constructor(r){this.budget=r}fits(r,o=0){return this.used+r.length+1+o<=this.budget}push(r){this.lines.push(r),this.used+=r.length+1}get chars(){return this.used}remaining(){return this.budget-this.used}}const ut=160,v={narrative:.25,truths:.2,failures:.25,artifacts:.15};class Et{db;constructor(r){this.db=r}latestSessionId(r,o){let e;try{e=this.db.prepare(`
5
5
  SELECT id, run_id FROM sessions
6
6
  WHERE project_id = ? AND is_archived = 0
7
7
  ORDER BY date DESC, id DESC
8
8
  LIMIT 200
9
- `).all(e)}catch{const o=this.db.prepare("SELECT id FROM sessions WHERE project_id = ? AND is_archived = 0 ORDER BY date DESC, id DESC LIMIT 1").get(e);return o?o.id:null}return r.length===0?null:a?.includeAutomated?r[0].id:(r.find(o=>!X(o.run_id))??r[0]).id}rehydrate(e,a){const r=this.db.prepare("SELECT * FROM sessions WHERE id = ?").get(e);if(!r)return null;const l=this.db.prepare("SELECT name, path FROM projects WHERE id = ?").get(r.project_id);if(!l)return null;const o=a?.include_artifacts??!0,M=a?.include_failures??!0,m=Math.max(200,Math.min(a?.max_truth_chars??2e3,1e4)),u=Math.max(0,Math.min(Math.floor(a?.max_quests??10),100)),g=Number.parseInt(process.env[P]??"",10),h=typeof a?.max_chars=="number"?a.max_chars:Number.isFinite(g)?g:0,n=h>0,d=this.db.prepare(`
9
+ `).all(r)}catch{const c=this.db.prepare("SELECT id FROM sessions WHERE project_id = ? AND is_archived = 0 ORDER BY date DESC, id DESC LIMIT 1").get(r);return c?c.id:null}return e.length===0?null:o?.includeAutomated?e[0].id:(e.find(c=>!ot(c.run_id))??e[0]).id}rehydrate(r,o){const e=this.db.prepare("SELECT * FROM sessions WHERE id = ?").get(r);if(!e)return null;const l=this.db.prepare("SELECT name, path FROM projects WHERE id = ?").get(e.project_id);if(!l)return null;const c=o?.include_artifacts??!0,M=o?.include_failures??!0,$=Math.max(200,Math.min(o?.max_truth_chars??2e3,1e4)),p=Math.max(0,Math.min(Math.floor(o?.max_quests??st),100)),y=Number.parseInt(process.env[nt]??"",10),f=typeof o?.max_chars=="number"?o.max_chars:Number.isFinite(y)?y:0,i=f>0,E=this.db.prepare(`
10
10
  SELECT category, key, value, rationale, confidence, last_verified_at,
11
- ttl_days,
11
+ ttl_days, created_at,
12
12
  CAST((julianday('now') - julianday(last_verified_at)) AS REAL) AS age_days
13
13
  FROM ground_truths
14
14
  WHERE project_id = ? AND is_current = 1
15
15
  ORDER BY category, key
16
- `).all(r.project_id),y=this.db.prepare(`
16
+ `).all(e.project_id),g=this.db.prepare(`
17
17
  SELECT id, title, description, priority, status, tags
18
18
  FROM quests
19
19
  WHERE project_id = ? AND status IN ('pending','in_progress')
@@ -21,26 +21,36 @@ const z=10,P="WYRM_REHYDRATE_MAX_CHARS";function X(i){if(typeof i!="string"||i.l
21
21
  CASE priority WHEN 'critical' THEN 0 WHEN 'high' THEN 1
22
22
  WHEN 'medium' THEN 2 ELSE 3 END,
23
23
  created_at DESC
24
- `).all(r.project_id);let v=[];if(o)try{v=this.db.prepare(`
25
- SELECT id, problem, constraints, validated_fix, why_it_worked, tags
24
+ `).all(e.project_id),R=this.db.prepare(`
25
+ SELECT id, title, priority
26
+ FROM quests
27
+ WHERE project_id = ? AND status = 'parked'
28
+ ORDER BY
29
+ CASE priority WHEN 'critical' THEN 0 WHEN 'high' THEN 1
30
+ WHEN 'medium' THEN 2 ELSE 3 END,
31
+ id
32
+ `).all(e.project_id);let w=[];if(c)try{w=this.db.prepare(`
33
+ SELECT id, problem, constraints, validated_fix, why_it_worked, tags, source_trust
26
34
  FROM memory_artifacts
27
35
  WHERE project_id = ? AND (needs_review = 0 OR needs_review IS NULL)
28
36
  ORDER BY (CASE WHEN problem LIKE '[auto:%' THEN 1 ELSE 0 END), id DESC
29
- LIMIT 20
30
- `).all(r.project_id)}catch{v=[]}let D=[];if(M)try{D=this.db.prepare(`
37
+ LIMIT 40
38
+ `).all(e.project_id)}catch{w=[]}let N=[];if(M)try{N=this.db.prepare(`
31
39
  SELECT id, scope, target, description, why_failed, occurrences, severity, last_seen
32
40
  FROM failure_patterns
33
41
  WHERE (project_id = ? OR project_id IS NULL) AND resolved = 0
34
42
  ORDER BY last_seen DESC LIMIT 15
35
- `).all(r.project_id)}catch{D=[]}const L=["---",`*Rehydrated from session created at ${r.created_at}. Continue from where the prior agent left off.*`],O=L.join(`
36
- `).length+1,s=new G(n?Math.max(0,h-O):1/0);s.push("# Session Rehydration Brief"),s.push(""),s.push(`**Session #${r.id}** \xB7 ${l.name} \xB7 ${r.date}`),s.push(`**Project root:** \`${l.path}\``),s.push("");const C=s.chars;let N=0;const S=t=>n?(N+=t*(s.budget-C),Math.max(0,N-(s.chars-C))):1/0,T=[["Objectives at start",r.objectives],["What was completed",r.completed],["Open issues at session close",r.issues],["Notes",r.notes],["Summary",r.summary]].map(([t,c])=>[t,K(c)]).filter(([,t])=>t.length>0),x=S(b.narrative),H=n&&T.length>0?Math.max(120,Math.floor(x/T.length)-40):1/0;for(const[t,c]of T){const $=`## ${t}`;let p=f(c,H);if(!s.fits(`${$}
37
- ${p}
38
- `)){const R=s.remaining()-$.length-8;if(R<120)continue;p=f(p,R)}s.push($),s.push(p),s.push("")}const W=n?240:Math.max(200,Math.floor(m/2)),A=[];let j=0;for(const t of d){const $=t.ttl_days!=null&&t.age_days>t.ttl_days?" [\u26A0\uFE0F STALE]":"",p=`- **${t.category}.${t.key}**${$}: ${t.value}`+(t.rationale?` *(rationale: ${t.rationale})*`:"")+(t.confidence<1?` *(conf: ${t.confidence})*`:""),R=f(n?E(p):_(p),W);if(j+=R.length,j>m)break;A.push(R)}const k=this.section(s,"## Ground truths for this project",A,d.length-A.length,t=>`- _\u2026 ${t} more truths not shown. Query wyrm_truth_get for the full list._`,S(b.truths)),F=D.map(t=>{const c=`- \u{1F534} #${t.id} [${t.severity}] ${t.scope}:${t.target} \xD7${t.occurrences}`;return n?f(`${c}: ${E(t.description+(t.why_failed?` Why: ${t.why_failed}`:""))}`,240):c+`
39
- ${_(t.description)}`+(t.why_failed?`
40
- Why: ${_(t.why_failed)}`:"")}),B=this.section(s,"## Unresolved failure patterns \u2014 DO NOT repeat these",F,0,t=>`- _\u2026 ${t} more unresolved failure patterns not shown. Run wyrm_failure_check before retrying an approach._`,S(b.failures)),Y=v.slice(0,10).map(t=>{const c=t.validated_fix?` \u2192 ${t.validated_fix.slice(0,n?80:150)}`:"";return n?f(`- **${f(E(t.problem),160)}**${E(c)}`,260):`- **${_(t.problem)}**${_(c)}`}),U=this.section(s,"## Validated patterns (memory artifacts)",Y,0,t=>`- _\u2026 ${t} more patterns not shown. Query wyrm_recall for the rest._`,S(b.artifacts)),I=y.slice(0,u).map(t=>n?f(`- **#${t.id}** [${t.priority}] ${E(t.title)}${t.description?`: ${E(t.description)}`:""}`,200):`- **#${t.id}** [${t.priority}] ${_(t.title)}`+(t.description?`
41
- ${_(t.description.slice(0,200))}`:"")),Q=this.section(s,`## Open quests (${y.length})`,I,y.length-I.length,t=>`- _\u2026 ${t} more open quests not shown. Query wyrm_quest (action: list) for the rest._`,1/0);for(const t of L)s.push(t);const w=s.lines.join(`
42
- `);return{session_id:r.id,project_name:l.name,project_path:l.path,briefing_markdown:w,context_chars:w.length,attached:{quests:Q,truths:k,artifacts:U,failures:B}}}section(e,a,r,l,o,M){const m=r.length+l;if(m===0)return 0;let u=0,g=0;for(let n=0;n<r.length;n++){const d=u===0?`${a}
43
+ `).all(e.project_id)}catch{N=[]}const j=["---",`*Rehydrated from session created at ${e.created_at}. Continue from where the prior agent left off.*`],F=j.join(`
44
+ `).length+1,s=new lt(i?Math.max(0,f-F):1/0);s.push("# Session Rehydration Brief"),s.push(""),s.push(`**Session #${e.id}** \xB7 ${l.name} \xB7 ${e.date}`),s.push(`**Project root:** \`${l.path}\``),s.push("");const C=s.chars;let k=0;const b=t=>i?(k+=t*(s.budget-C),Math.max(0,k-(s.chars-C))):1/0,D=[["Objectives at start",e.objectives],["What was completed",e.completed],["Open issues at session close",e.issues],["Notes",e.notes],["Summary",e.summary]].map(([t,a])=>[t,ct(a)]).filter(([,t])=>t.length>0),B=b(v.narrative),Y=i&&D.length>0?Math.max(120,Math.floor(B/D.length)-40):1/0;for(const[t,a]of D){const u=`## ${t}`;let _=h(a,Y);if(!s.fits(`${u}
45
+ ${_}
46
+ `)){const S=s.remaining()-u.length-8;if(S<120)continue;_=h(_,S)}s.push(u),s.push(_),s.push("")}const P=i?240:Math.max(200,Math.floor($/2)),T=[];let H=0,I=!1;const U=Date.now();for(const t of E){const a=Z(t,U),u=J(`${t.value} ${t.rationale??""}`).dead.length>0;(a.stale||u)&&(I=!0);const _=`- **${t.category}.${t.key}** ${z(a,{deadPath:u})}: ${t.value}`+(t.rationale?` *(rationale: ${t.rationale})*`:"")+(t.confidence<1?` *(conf: ${t.confidence})*`:""),S=h(i?m(_):d(_),P);if(H+=S.length,H>$)break;T.push(S)}const Q=this.section(s,I?"## Ground truths for this project (STALE or path missing: re-verify before relying on it)":"## Ground truths for this project",T,E.length-T.length,t=>`- _\u2026 ${t} more truths not shown. Query wyrm_truth_get for the full list._`,b(v.truths)),X=N.map(t=>{const a=`- \u{1F534} #${t.id} [${t.severity}] ${t.scope}:${t.target} \xD7${t.occurrences}`;return i?h(`${a}: ${m(t.description+(t.why_failed?` Why: ${t.why_failed}`:""))}`,240):a+`
47
+ ${d(t.description)}`+(t.why_failed?`
48
+ Why: ${d(t.why_failed)}`:"")}),K=this.section(s,"## Unresolved failure patterns (DO NOT repeat these)",X,0,t=>`- _\u2026 ${t} more unresolved failure patterns not shown. Run wyrm_failure_check before retrying an approach._`,b(v.failures));let A=0;const V=w.filter(t=>t.source_trust==="untrusted"||t.source_trust==="imported"&&et(`${t.problem} ${t.validated_fix??""}`)?(A++,!1):!0).slice(0,10).map(t=>{const a=t.validated_fix?` \u2192 ${t.validated_fix.slice(0,i?80:150)}`:"",u=rt(t.source_trust??void 0);return i?h(`- ${u}**${h(m(t.problem),160)}**${m(a)}`,260):`- ${u}**${d(t.problem)}**${d(a)}`}),q=this.section(s,"## Validated patterns (memory artifacts)",V,0,t=>`- _\u2026 ${t} more patterns not shown. Query wyrm_recall for the rest._`,b(v.artifacts)),O=g.slice(0,p).map(t=>i?h(`- **#${t.id}** [${t.priority}] ${m(t.title)}${t.description?`: ${m(t.description)}`:""}`,200):`- **#${t.id}** [${t.priority}] ${d(t.title)}`+(t.description?`
49
+ ${d(t.description.slice(0,200))}`:"")),G=this.section(s,R.length>0?`## Open quests (${g.length}; ${R.length} parked)`:`## Open quests (${g.length})`,O,g.length-O.length,t=>`- _\u2026 ${t} more open quests not shown. Query wyrm_quest (action: list) for the rest._`,1/0),x=R.slice(0,it).map(t=>h(`- **#${t.id}** [parked] [${t.priority}] ${i?m(t.title):d(t.title)}`,200));this.section(s,`## Parked quests (${R.length})`,x,R.length-x.length,t=>`- _\u2026 ${t} more parked quests not shown. List them with \`wyrm quest list --parked\`._`,1/0);const L=tt(this.db,e.project_id).unreviewed;if(L>0){const t=`_${L} auto-approved memor${L===1?"y was":"ies were"} sampled for a spot check: wyrm review sample. Nothing is hidden meanwhile._`;s.fits(`${t}
50
+
51
+ `)&&(s.push(t),s.push(""))}for(const t of j)s.push(t);const W=s.lines.join(`
52
+ `);return{session_id:e.id,project_name:l.name,project_path:l.path,briefing_markdown:W,context_chars:W.length,attached:{quests:G,truths:Q,artifacts:q,failures:K},...A>0?{withheld:{artifacts:A}}:{}}}section(r,o,e,l,c,M){const $=e.length+l;if($===0)return 0;let p=0,y=0;for(let i=0;i<e.length;i++){const E=p===0?`${o}
43
53
 
44
- ${r[n]}`:r[n],y=n<r.length-1||l>0;if(g+d.length+1>M||!e.fits(d,y?q:0))break;e.push(d),g+=d.length+1,u++}const h=m-u;if(u===0){const n=`${a}
54
+ ${e[i]}`:e[i],g=i<e.length-1||l>0;if(y+E.length+1>M||!r.fits(E,g?ut:0))break;r.push(E),y+=E.length+1,p++}const f=$-p;if(p===0){const i=`${o}
45
55
 
46
- ${o(h)}`;return e.fits(n)&&(e.push(n),e.push("")),0}return h>0&&e.fits(o(h))&&e.push(o(h)),e.push(""),u}}export{z as DEFAULT_MAX_QUESTS,P as MAX_CHARS_ENV,J as Rehydration,X as isAutomatedRunId,K as stripInjectedPreamble};
56
+ ${c(f)}`;return r.fits(i)&&(r.push(i),r.push("")),0}return f>0&&r.fits(c(f))&&r.push(c(f)),r.push(""),p}}export{it as DEFAULT_MAX_PARKED,st as DEFAULT_MAX_QUESTS,nt as MAX_CHARS_ENV,Et as Rehydration,ot as isAutomatedRunId,ct as stripInjectedPreamble};
package/dist/reindex.js CHANGED
@@ -1 +1 @@
1
- import{homedir as h}from"node:os";import{join as y}from"node:path";async function E(c,d,l,n={}){const a=n.dryRun===!0,f=n.onError??(()=>{});let s=0,r=0;for(const t of l){const p=c.prepare("SELECT id, objectives, completed, notes, summary FROM sessions WHERE project_id = ?").all(t);for(const e of p){const o=[e.objectives,e.completed,e.notes,e.summary].filter(Boolean).join(" ");if(o&&!a)try{await d.addVector(o,"session",e.id,t)?s++:r++}catch(i){f("Reindex session failed",{projectId:t,sessionId:e.id,error:i.message}),r++}else o&&s++}const m=c.prepare("SELECT id, title, description FROM quests WHERE project_id = ?").all(t);for(const e of m){const o=[e.title,e.description].filter(Boolean).join(" ");if(o&&!a)try{await d.addVector(o,"context",e.id,t)?s++:r++}catch(i){f("Reindex quest failed",{projectId:t,questId:e.id,error:i.message}),r++}else o&&s++}const u=c.prepare("SELECT id, problem, validated_fix FROM memory_artifacts WHERE project_id = ? AND needs_review = 0 AND supersedes_id IS NULL").all(t);for(const e of u){const o=[e.problem,e.validated_fix].filter(Boolean).join(" ");if(o&&!a)try{await d.addVector(o,"artifact",e.id,t)?s++:r++}catch(i){f("Reindex artifact failed",{projectId:t,artifactId:e.id,error:i.message}),r++}else o&&s++}}return{indexed:s,skipped:r}}async function j(){const{WyrmDB:c}=await import("./database.js"),d=process.env.WYRM_DB_PATH??y(h(),".wyrm","wyrm.db"),l=new c(d);try{const n=l.getDatabase(),a=n.prepare("SELECT COUNT(*) AS n FROM memory_artifacts").get().n;if(a===0)return null;console.log(` Backfilling vectors for ${a} existing memories...`);const{createVectorStore:f}=await import("./vectors.js"),s=f({provider:"bundled"},n),r=l.getAllProjects(1e3).map(m=>m.id),{indexed:t,skipped:p}=await E(n,s,r,{dryRun:!1});return console.log(` Backfill: ${t} indexed, ${p} skipped.`),{indexed:t,skipped:p}}finally{l.close()}}export{E as reindexProjects,j as runBundledBackfill};
1
+ import{homedir as h}from"node:os";import{join as y}from"node:path";async function E(c,d,l,n={}){const a=n.dryRun===!0,f=n.onError??(()=>{});let o=0,r=0;for(const t of l){const p=c.prepare("SELECT id, objectives, completed, notes, summary FROM sessions WHERE project_id = ?").all(t);for(const e of p){const s=[e.objectives,e.completed,e.notes,e.summary].filter(Boolean).join(" ");if(s&&!a)try{await d.addVector(s,"session",e.id,t)?o++:r++}catch(i){f("Reindex session failed",{projectId:t,sessionId:e.id,error:i.message}),r++}else s&&o++}const m=c.prepare("SELECT id, title, description FROM quests WHERE project_id = ?").all(t);for(const e of m){const s=[e.title,e.description].filter(Boolean).join(" ");if(s&&!a)try{await d.addVector(s,"quest",e.id,t)?o++:r++}catch(i){f("Reindex quest failed",{projectId:t,questId:e.id,error:i.message}),r++}else s&&o++}const u=c.prepare("SELECT id, problem, validated_fix FROM memory_artifacts WHERE project_id = ? AND needs_review = 0 AND supersedes_id IS NULL").all(t);for(const e of u){const s=[e.problem,e.validated_fix].filter(Boolean).join(" ");if(s&&!a)try{await d.addVector(s,"artifact",e.id,t)?o++:r++}catch(i){f("Reindex artifact failed",{projectId:t,artifactId:e.id,error:i.message}),r++}else s&&o++}}return{indexed:o,skipped:r}}async function x(){const{WyrmDB:c}=await import("./database.js"),d=process.env.WYRM_DB_PATH??y(h(),".wyrm","wyrm.db"),l=new c(d);try{const n=l.getDatabase(),a=n.prepare("SELECT COUNT(*) AS n FROM memory_artifacts").get().n;if(a===0)return null;console.log(` Backfilling vectors for ${a} existing memories...`);const{createVectorStore:f}=await import("./vectors.js"),o=f({provider:"bundled"},n),r=l.getAllProjects(1e3).map(m=>m.id),{indexed:t,skipped:p}=await E(n,o,r,{dryRun:!1});return console.log(` Backfill: ${t} indexed, ${p} skipped.`),{indexed:t,skipped:p}}finally{l.close()}}export{E as reindexProjects,x as runBundledBackfill};
@@ -23,15 +23,15 @@ import{existsSync as E,lstatSync as N,mkdirSync as D,readFileSync as k,realpathS
23
23
  FROM failure_patterns
24
24
  WHERE (project_id = ? OR project_id IS NULL) AND resolved = 0
25
25
  ORDER BY last_seen DESC, id DESC LIMIT 50
26
- `).all(r)}catch{return[]}}}}function b(e,r){return{project_id:r.id,project_name:r.name,project_path:r.path,truths:e.truths(r.id),quests:e.quests(r.id),artifacts:e.artifacts(r.id),failures:e.failures(r.id)}}function M(e){return e.truths.length+e.quests.length+e.artifacts.length+e.failures.length}function x(e,r){const n=M(e);return[`<!-- Compiled by Wyrm v${r.wyrm_version} from ${n} memory artifact${n===1?"":"s"}.`,` Project: ${e.project_name}. Compiled at ${r.compiled_at}.`," Edits inside the wyrm:render markers are HARVESTED to the review queue, not lost \u2014"," but they are OVERWRITTEN on the next `wyrm render`; capture durable notes with `wyrm capture`. -->"]}function u(e){return e.replace(/\s*\n\s*/g," ").trim()}function p(e,r){return e.length>r?`${e.slice(0,r-1)}\u2026`:e}function T(e,r){const n=x(e,r),t=[];t.push(`# ${e.project_name} \u2014 Project Memory`),t.push("");const s=O-4,a=[];e.truths.length>0&&a.push({heading:`## Ground truths (${e.truths.length})`,refTool:"wyrm_truth_get",lines:e.truths.map(i=>{const l=i.stale?" [STALE]":"",d=i.confidence<1?` (conf ${i.confidence})`:"";return`- **${i.category}.${i.key}**${l}: ${p(u(i.value),160)}${d}`})}),e.failures.length>0&&a.push({heading:`## Failures \u2014 DO NOT repeat (${e.failures.length})`,refTool:"wyrm_failure_check",lines:e.failures.map(i=>`- [${i.severity}] ${i.scope}:${i.target} \xD7${i.occurrences} \u2014 ${p(u(i.description),140)}`)}),e.quests.length>0&&a.push({heading:`## Open quests (${e.quests.length})`,refTool:"wyrm_quest",lines:e.quests.map(i=>`- #${i.id} [${i.priority}] ${p(u(i.title),140)}`)}),e.artifacts.length>0&&a.push({heading:`## Validated patterns (${e.artifacts.length})`,refTool:"wyrm_recall",lines:e.artifacts.map(i=>`- ${p(u(i.problem),120)}${i.validated_fix?` \u2192 ${p(u(i.validated_fix),120)}`:""}`)});let o=0;for(const i of a){if(o+4>s)break;t.push(i.heading),t.push(""),o+=2;let l=0;for(const d of i.lines){if(o+1+(l<i.lines.length?1:0)+1>s)break;t.push(d),o+=1,l+=1}l<i.lines.length&&(t.push(`- _\u2026 ${i.lines.length-l} more \u2014 query \`${i.refTool}\`._`),o+=1),t.push(""),o+=1}return t.push("---"),t.push("*Full memory: `wyrm recall` / `wyrm session prime`. This file is a deterministic digest.*"),[...n,...t].join(`
27
- `)}function W(e,r){const n=x(e,r),t=[],c=(s,a,o)=>{o.length!==0&&t.push({filename:s,content:[...n,`# ${e.project_name} \u2014 ${a}`,"",...o].join(`
26
+ `).all(r)}catch{return[]}}}}function b(e,r){return{project_id:r.id,project_name:r.name,project_path:r.path,truths:e.truths(r.id),quests:e.quests(r.id),artifacts:e.artifacts(r.id),failures:e.failures(r.id)}}function M(e){return e.truths.length+e.quests.length+e.artifacts.length+e.failures.length}function v(e,r){const n=M(e);return[`<!-- Compiled by Wyrm v${r.wyrm_version} from ${n} memory artifact${n===1?"":"s"}.`,` Project: ${e.project_name}. Compiled at ${r.compiled_at}.`," Edits inside the wyrm:render markers are HARVESTED to the review queue, not lost,"," but they are OVERWRITTEN on the next `wyrm render`; capture durable notes with `wyrm capture`. -->"]}function u(e){return e.replace(/\s*\n\s*/g," ").trim()}function p(e,r){return e.length>r?`${e.slice(0,r-1)}\u2026`:e}function x(e,r){const n=v(e,r),t=[];t.push(`# ${e.project_name}: Project Memory`),t.push("");const s=O-4,a=[];e.truths.length>0&&a.push({heading:`## Ground truths (${e.truths.length})`,refTool:"wyrm_truth_get",lines:e.truths.map(i=>{const l=i.stale?" [STALE]":"",d=i.confidence<1?` (conf ${i.confidence})`:"";return`- **${i.category}.${i.key}**${l}: ${p(u(i.value),160)}${d}`})}),e.failures.length>0&&a.push({heading:`## Failures: DO NOT repeat (${e.failures.length})`,refTool:"wyrm_failure_check",lines:e.failures.map(i=>`- [${i.severity}] ${i.scope}:${i.target} \xD7${i.occurrences}: ${p(u(i.description),140)}`)}),e.quests.length>0&&a.push({heading:`## Open quests (${e.quests.length})`,refTool:"wyrm_quest",lines:e.quests.map(i=>`- #${i.id} [${i.priority}] ${p(u(i.title),140)}`)}),e.artifacts.length>0&&a.push({heading:`## Validated patterns (${e.artifacts.length})`,refTool:"wyrm_recall",lines:e.artifacts.map(i=>`- ${p(u(i.problem),120)}${i.validated_fix?` \u2192 ${p(u(i.validated_fix),120)}`:""}`)});let o=0;for(const i of a){if(o+4>s)break;t.push(i.heading),t.push(""),o+=2;let l=0;for(const d of i.lines){if(o+1+(l<i.lines.length?1:0)+1>s)break;t.push(d),o+=1,l+=1}l<i.lines.length&&(t.push(`- _\u2026 ${i.lines.length-l} more; query \`${i.refTool}\`._`),o+=1),t.push(""),o+=1}return t.push("---"),t.push("*Full memory: `wyrm recall` / `wyrm session prime`. This file is a deterministic digest.*"),[...n,...t].join(`
27
+ `)}function W(e,r){const n=v(e,r),t=[],c=(s,a,o)=>{o.length!==0&&t.push({filename:s,content:[...n,`# ${e.project_name}: ${a}`,"",...o].join(`
28
28
  `)})};return c("truths.md","Ground truths",e.truths.map(s=>{const a=s.stale?" [STALE]":"";return`- **${s.category}.${s.key}**${a}: ${u(s.value)}`+(s.rationale?`
29
29
  - rationale: ${u(s.rationale)}`:"")+(s.confidence<1?`
30
30
  - confidence: ${s.confidence}`:"")})),c("quests.md","Open quests",e.quests.map(s=>`- #${s.id} [${s.priority}] ${u(s.title)}`+(s.description?`
31
31
  - ${u(s.description)}`:""))),c("patterns.md","Validated patterns",e.artifacts.map(s=>`- ${u(s.problem)}`+(s.validated_fix?`
32
- - fix: ${u(s.validated_fix)}`:""))),c("failures.md","Failures \u2014 DO NOT repeat",e.failures.map(s=>`- [${s.severity}] ${s.scope}:${s.target} \xD7${s.occurrences}
33
- - ${u(s.description)}`)),t}function C(e,r){const n=[];if(n.push(`Wyrm memory for ${e.project_name} (compiled by Wyrm v${r.wyrm_version}):`),e.failures.length>0){n.push(""),n.push("Known failures (do not repeat):");for(const t of e.failures.slice(0,5))n.push(`- ${t.scope}:${t.target} \u2014 ${p(u(t.description),120)}`);e.failures.length>5&&n.push(`- (+${e.failures.length-5} more \u2014 wyrm_failure_check)`)}if(e.truths.length>0){n.push(""),n.push("Ground truths:");for(const t of e.truths.slice(0,8))n.push(`- ${t.category}.${t.key}: ${p(u(t.value),120)}`);e.truths.length>8&&n.push(`- (+${e.truths.length-8} more \u2014 wyrm_truth_get)`)}if(e.quests.length>0){n.push(""),n.push("Open quests:");for(const t of e.quests.slice(0,5))n.push(`- #${t.id} [${t.priority}] ${p(u(t.title),100)}`);e.quests.length>5&&n.push(`- (+${e.quests.length-5} more \u2014 wyrm_quest)`)}return n.push(""),n.push("Load full context with wyrm_session_prime. (Wyrm is this session's memory; consult it first.)"),n.join(`
34
- `)}function I(e){switch(e){case"claude":return"CLAUDE.md";case"cursor":return f(".cursor","rules","wyrm-memory.md");case"copilot":return f(".github","copilot-instructions.md");case"agents":return"AGENTS.md";case"windsurf":return f(".windsurf","rules","wyrm-memory.md");case"cline":return f(".clinerules","wyrm-memory.md");case"zed":return".rules";case"gemini":return"GEMINI.md";default:{const r=e;throw new Error(`unknown render client: ${String(r)}`)}}}function q(e,r,n){return{client:e,relPath:I(e),block:T(r,n)}}const j=["claude","cursor","copilot","agents","windsurf","cline","zed","gemini"],v={claude:["CLAUDE.md",".claude"],cursor:[".cursor",".cursorrules"],copilot:[".github/copilot-instructions.md",".github"],agents:["AGENTS.md"],windsurf:[".windsurf",".windsurfrules"],cline:[".clinerules"],zed:[".rules",".zed"],gemini:["GEMINI.md",".gemini"]};function P(e){const r=new Set(e);return j.filter(n=>v[n].some(t=>r.has(t)))}const J=[...new Set(Object.values(v).flat())];function H(e,r){const n=`${$}
32
+ - fix: ${u(s.validated_fix)}`:""))),c("failures.md","Failures (DO NOT repeat)",e.failures.map(s=>`- [${s.severity}] ${s.scope}:${s.target} \xD7${s.occurrences}
33
+ - ${u(s.description)}`)),t}function C(e,r){const n=[];if(n.push(`Wyrm memory for ${e.project_name} (compiled by Wyrm v${r.wyrm_version}):`),e.failures.length>0){n.push(""),n.push("Known failures (do not repeat):");for(const t of e.failures.slice(0,5))n.push(`- ${t.scope}:${t.target}: ${p(u(t.description),120)}`);e.failures.length>5&&n.push(`- (+${e.failures.length-5} more via wyrm_failure_check)`)}if(e.truths.length>0){n.push(""),n.push("Ground truths:");for(const t of e.truths.slice(0,8))n.push(`- ${t.category}.${t.key}: ${p(u(t.value),120)}`);e.truths.length>8&&n.push(`- (+${e.truths.length-8} more via wyrm_truth_get)`)}if(e.quests.length>0){n.push(""),n.push("Open quests:");for(const t of e.quests.slice(0,5))n.push(`- #${t.id} [${t.priority}] ${p(u(t.title),100)}`);e.quests.length>5&&n.push(`- (+${e.quests.length-5} more via wyrm_quest)`)}return n.push(""),n.push("Load full context with wyrm_session_prime. (Wyrm is this session's memory; consult it first.)"),n.join(`
34
+ `)}function I(e){switch(e){case"claude":return"CLAUDE.md";case"cursor":return f(".cursor","rules","wyrm-memory.md");case"copilot":return f(".github","copilot-instructions.md");case"agents":return"AGENTS.md";case"windsurf":return f(".windsurf","rules","wyrm-memory.md");case"cline":return f(".clinerules","wyrm-memory.md");case"zed":return".rules";case"gemini":return"GEMINI.md";default:{const r=e;throw new Error(`unknown render client: ${String(r)}`)}}}function q(e,r,n){return{client:e,relPath:I(e),block:x(r,n)}}const j=["claude","cursor","copilot","agents","windsurf","cline","zed","gemini"],T={claude:["CLAUDE.md",".claude"],cursor:[".cursor",".cursorrules"],copilot:[".github/copilot-instructions.md",".github"],agents:["AGENTS.md"],windsurf:[".windsurf",".windsurfrules"],cline:[".clinerules"],zed:[".rules",".zed"],gemini:["GEMINI.md",".gemini"]};function P(e){const r=new Set(e);return j.filter(n=>T[n].some(t=>r.has(t)))}const J=[...new Set(Object.values(T).flat())];function H(e,r){const n=`${$}
35
35
  ${r}
36
36
  ${h}`;if(!e)return`${n}
37
37
  `;const t=e.indexOf($),c=e.indexOf(h);if(t!==-1&&c!==-1&&c>t){const a=e.slice(0,t),o=e.slice(c+h.length);return`${a}${n}${o}`}const s=e.endsWith(`
@@ -39,4 +39,4 @@ ${h}`;if(!e)return`${n}
39
39
  `:`
40
40
 
41
41
  `;return`${e}${s}${n}
42
- `}function F(e){const r=e.indexOf($),n=e.indexOf(h);return r!==-1&&n!==-1&&n>r}class y extends Error{}const B={existsSync:E,lstatSync:N,realpathSync:L};function G(e,r,n=B){if(m(r))throw new y(`render target must be relative, got absolute: ${r}`);const t=R(e),c=R(t,r),s=w(t,c);if(s===""||s.startsWith("..")||s.startsWith(`..${S}`)||m(s))throw new y(`render target escapes root: ${r}`);let a;try{a=n.realpathSync(t)}catch{return c}if(n.existsSync(c)){let d=!1;try{d=n.lstatSync(c).isSymbolicLink()}catch{d=!1}if(d)throw new y(`render target is a symlink (refusing to follow): ${r}`)}let o=c;for(;!n.existsSync(o);){const d=_(o);if(d===o)break;o=d}let i;try{i=n.realpathSync(o)}catch{return c}const l=w(a,i);if(l===""&&o===t)return c;if(l.startsWith("..")||l.startsWith(`..${S}`)||m(l))throw new y(`render target escapes root via symlink: ${r}`);return c}const Y={existsSync:E,readFileSync:k,writeFileSync:A,mkdirSync:D};function g(e,r,n,t={}){const c=t.fs??Y,s=G(e,r),a=c.existsSync(s),o=a?c.readFileSync(s,"utf-8"):null;if(a&&o!=null&&!F(o)&&!t.force)return{path:s,action:"skipped",reason:"file exists and is not Wyrm-managed (pass force to append)"};const i=H(o,n);return o!=null&&i===o?{path:s,action:"skipped",reason:"unchanged"}:(c.mkdirSync(_(s),{recursive:!0}),c.writeFileSync(s,i,"utf-8"),{path:s,action:a?"updated":"created"})}function K(e,r,n){const t=b(e,r);return{model:t,memoryMd:T(t,n),topics:W(t,n),sessionBrief:C(t,n)}}function Q(e,r,n,t={}){const c=t.rootDir??r.path,s=t.topicsDir??f(".wyrm","memory"),a=K(e,r,n),o=[];o.push(g(c,"MEMORY.md",a.memoryMd,t));for(const i of a.topics)o.push(g(c,f(s,i.filename),i.content,{...t,force:!0}));for(const i of t.clients??[]){const l=q(i,a.model,n);o.push(g(c,l.relPath,l.block,t))}return{plan:a,writes:o}}function X(e=process.env){const r=(e.WYRM_RENDER_WATCH??"").toLowerCase();return r==="1"||r==="true"||r==="yes"}class Z{rendered;constructor(r=0){this.rendered=r}get last(){return this.rendered}advance(r){return!Number.isFinite(r)||r<=this.rendered?!1:(this.rendered=r,!0)}}export{J as ALL_CLIENT_MARKERS,j as ALL_RENDER_CLIENTS,O as MEMORY_MD_LINE_BUDGET,h as RENDER_MARKER_END,$ as RENDER_MARKER_START,Z as RenderCursorTracker,y as RenderPathError,K as buildRenderPlan,I as clientRelPath,b as compileRenderModel,P as detectClients,F as hasWyrmRegion,V as makeRenderDeps,x as provenanceHeader,q as renderForClient,T as renderMemoryMd,C as renderSessionBrief,Q as renderToDisk,W as renderTopicFiles,X as renderWatchEnabled,G as resolveInsideRoot,H as spliceWyrmRegion,g as writeRenderTarget};
42
+ `}function F(e){const r=e.indexOf($),n=e.indexOf(h);return r!==-1&&n!==-1&&n>r}class y extends Error{}const B={existsSync:E,lstatSync:N,realpathSync:L};function G(e,r,n=B){if(m(r))throw new y(`render target must be relative, got absolute: ${r}`);const t=R(e),c=R(t,r),s=w(t,c);if(s===""||s.startsWith("..")||s.startsWith(`..${S}`)||m(s))throw new y(`render target escapes root: ${r}`);let a;try{a=n.realpathSync(t)}catch{return c}if(n.existsSync(c)){let d=!1;try{d=n.lstatSync(c).isSymbolicLink()}catch{d=!1}if(d)throw new y(`render target is a symlink (refusing to follow): ${r}`)}let o=c;for(;!n.existsSync(o);){const d=_(o);if(d===o)break;o=d}let i;try{i=n.realpathSync(o)}catch{return c}const l=w(a,i);if(l===""&&o===t)return c;if(l.startsWith("..")||l.startsWith(`..${S}`)||m(l))throw new y(`render target escapes root via symlink: ${r}`);return c}const Y={existsSync:E,readFileSync:k,writeFileSync:A,mkdirSync:D};function g(e,r,n,t={}){const c=t.fs??Y,s=G(e,r),a=c.existsSync(s),o=a?c.readFileSync(s,"utf-8"):null;if(a&&o!=null&&!F(o)&&!t.force)return{path:s,action:"skipped",reason:"file exists and is not Wyrm-managed (pass force to append)"};const i=H(o,n);return o!=null&&i===o?{path:s,action:"skipped",reason:"unchanged"}:(c.mkdirSync(_(s),{recursive:!0}),c.writeFileSync(s,i,"utf-8"),{path:s,action:a?"updated":"created"})}function K(e,r,n){const t=b(e,r);return{model:t,memoryMd:x(t,n),topics:W(t,n),sessionBrief:C(t,n)}}function Q(e,r,n,t={}){const c=t.rootDir??r.path,s=t.topicsDir??f(".wyrm","memory"),a=K(e,r,n),o=[];o.push(g(c,"MEMORY.md",a.memoryMd,t));for(const i of a.topics)o.push(g(c,f(s,i.filename),i.content,{...t,force:!0}));for(const i of t.clients??[]){const l=q(i,a.model,n);o.push(g(c,l.relPath,l.block,t))}return{plan:a,writes:o}}function X(e=process.env){const r=(e.WYRM_RENDER_WATCH??"").toLowerCase();return r==="1"||r==="true"||r==="yes"}class Z{rendered;constructor(r=0){this.rendered=r}get last(){return this.rendered}advance(r){return!Number.isFinite(r)||r<=this.rendered?!1:(this.rendered=r,!0)}}export{J as ALL_CLIENT_MARKERS,j as ALL_RENDER_CLIENTS,O as MEMORY_MD_LINE_BUDGET,h as RENDER_MARKER_END,$ as RENDER_MARKER_START,Z as RenderCursorTracker,y as RenderPathError,K as buildRenderPlan,I as clientRelPath,b as compileRenderModel,P as detectClients,F as hasWyrmRegion,V as makeRenderDeps,v as provenanceHeader,q as renderForClient,x as renderMemoryMd,C as renderSessionBrief,Q as renderToDisk,W as renderTopicFiles,X as renderWatchEnabled,G as resolveInsideRoot,H as spliceWyrmRegion,g as writeRenderTarget};
@@ -1 +1 @@
1
- import{isIP as p}from"node:net";const w=15e3,E=4*1024*1024;function f(o){const t=o.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(!t||t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal"))return!0;const s=p(t);if(s===4){const e=t.split(".").map(Number);return!!(e.length!==4||e.some(r=>!Number.isInteger(r)||r<0||r>255)||e[0]===127||e[0]===10||e[0]===0||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&e[1]===168||e[0]===100&&e[1]>=64&&e[1]<=127)}if(s===6){if(t==="::1"||t==="::"||t.startsWith("fe80")||t.startsWith("fe9")||t.startsWith("fea")||t.startsWith("feb")||t.startsWith("fc")||t.startsWith("fd"))return!0;if(t.startsWith("::ffff:")){const e=t.slice(7);if(p(e)===4)return f(e);const r=e.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);if(r){const i=parseInt(r[1],16),a=parseInt(r[2],16);return f(`${i>>8&255}.${i&255}.${a>>8&255}.${a&255}`)}return!0}return!!t.startsWith("64:ff9b:")}return!1}function _(o){let t;try{t=new URL(o)}catch{return{ok:!1,reason:"invalid URL"}}return t.protocol!=="http:"&&t.protocol!=="https:"?{ok:!1,reason:`scheme ${t.protocol} not allowed (http/https only)`}:!(process.env.WYRM_REPL_ALLOW_PRIVATE==="1")&&f(t.hostname)?{ok:!1,reason:`host ${t.hostname} is loopback/private/link-local (set WYRM_REPL_ALLOW_PRIVATE=1 for same-host/LAN peers)`}:{ok:!0,url:t}}function R(o){return process.env.WYRM_REPL_ALLOW_ANY_TOKEN_ENV==="1"?/^[A-Z][A-Z0-9_]{0,63}$/.test(o):/^WYRM_[A-Z0-9_]{1,58}$/.test(o)}async function g(o,t,s,e={},r=E,i=w){const a=_(t);if(!a.ok)throw new Error(`peer URL rejected: ${a.reason}`);const u=new AbortController,d=setTimeout(()=>u.abort(),i);try{const n=await o(`${t}${s}`,{...e,redirect:"manual",signal:u.signal});if(n.status>=300&&n.status<400)throw new Error(`peer redirected (${n.status}) \u2014 refused`);if(!n.ok)throw new Error(`peer HTTP ${n.status}`);const c=Number(n.headers?.get?.("content-length")??"");if(Number.isFinite(c)&&c>r)throw new Error("peer response too large (content-length)");if(typeof n.body?.getReader=="function"){const h=await W(n,r);return h?JSON.parse(h):{}}if(typeof n.json=="function")return await n.json();const l=typeof n.text=="function"?await n.text():"";return l?JSON.parse(l):{}}finally{clearTimeout(d)}}async function W(o,t){const s=o.body?.getReader?.();if(!s)return typeof o.text=="function"?o.text():"";let e=0;const r=[];for(;;){const{done:i,value:a}=await s.read();if(i)break;if(a){if(e+=a.length,e>t){try{await s.cancel()}catch{}throw new Error("peer response too large")}r.push(a)}}return Buffer.concat(r).toString("utf8")}export{E as MAX_PEER_RESPONSE_BYTES,w as PEER_FETCH_TIMEOUT_MS,_ as checkPeerUrl,g as guardedFetchJson,f as isBlockedHost,R as isValidTokenEnvName};
1
+ import{isIP as p}from"node:net";const w=15e3,E=4*1024*1024;function f(o){const t=o.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"");if(!t||t==="localhost"||t.endsWith(".localhost")||t.endsWith(".local")||t.endsWith(".internal"))return!0;const s=p(t);if(s===4){const e=t.split(".").map(Number);return!!(e.length!==4||e.some(r=>!Number.isInteger(r)||r<0||r>255)||e[0]===127||e[0]===10||e[0]===0||e[0]===169&&e[1]===254||e[0]===172&&e[1]>=16&&e[1]<=31||e[0]===192&&e[1]===168||e[0]===100&&e[1]>=64&&e[1]<=127)}if(s===6){if(t==="::1"||t==="::"||t.startsWith("fe80")||t.startsWith("fe9")||t.startsWith("fea")||t.startsWith("feb")||t.startsWith("fc")||t.startsWith("fd"))return!0;if(t.startsWith("::ffff:")){const e=t.slice(7);if(p(e)===4)return f(e);const r=e.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);if(r){const i=parseInt(r[1],16),a=parseInt(r[2],16);return f(`${i>>8&255}.${i&255}.${a>>8&255}.${a&255}`)}return!0}return!!t.startsWith("64:ff9b:")}return!1}function _(o){let t;try{t=new URL(o)}catch{return{ok:!1,reason:"invalid URL"}}return t.protocol!=="http:"&&t.protocol!=="https:"?{ok:!1,reason:`scheme ${t.protocol} not allowed (http/https only)`}:!(process.env.WYRM_REPL_ALLOW_PRIVATE==="1")&&f(t.hostname)?{ok:!1,reason:`host ${t.hostname} is loopback/private/link-local (set WYRM_REPL_ALLOW_PRIVATE=1 for same-host/LAN peers)`}:{ok:!0,url:t}}function R(o){return process.env.WYRM_REPL_ALLOW_ANY_TOKEN_ENV==="1"?/^[A-Z][A-Z0-9_]{0,63}$/.test(o):/^WYRM_[A-Z0-9_]{1,58}$/.test(o)}async function g(o,t,s,e={},r=E,i=w){const a=_(t);if(!a.ok)throw new Error(`peer URL rejected: ${a.reason}`);const u=new AbortController,d=setTimeout(()=>u.abort(),i);try{const n=await o(`${t}${s}`,{...e,redirect:"manual",signal:u.signal});if(n.status>=300&&n.status<400)throw new Error(`peer redirected (${n.status}); refused`);if(!n.ok)throw new Error(`peer HTTP ${n.status}`);const c=Number(n.headers?.get?.("content-length")??"");if(Number.isFinite(c)&&c>r)throw new Error("peer response too large (content-length)");if(typeof n.body?.getReader=="function"){const h=await W(n,r);return h?JSON.parse(h):{}}if(typeof n.json=="function")return await n.json();const l=typeof n.text=="function"?await n.text():"";return l?JSON.parse(l):{}}finally{clearTimeout(d)}}async function W(o,t){const s=o.body?.getReader?.();if(!s)return typeof o.text=="function"?o.text():"";let e=0;const r=[];for(;;){const{done:i,value:a}=await s.read();if(i)break;if(a){if(e+=a.length,e>t){try{await s.cancel()}catch{}throw new Error("peer response too large")}r.push(a)}}return Buffer.concat(r).toString("utf8")}export{E as MAX_PEER_RESPONSE_BYTES,w as PEER_FETCH_TIMEOUT_MS,_ as checkPeerUrl,g as guardedFetchJson,f as isBlockedHost,R as isValidTokenEnvName};
@@ -1 +1 @@
1
- import{WyrmDB as n}from"./database.js";import{ReplicationDaemon as t,DEFAULT_INTERVAL_MS as i}from"./replication-daemon.js";async function s(){const o=Number(process.argv[2])||i,e=new n(process.env.WYRM_DB_PATH);e.liveMemoryEnabled()||(console.error("[replication-entrypoint] WYRM_LIVE_MEMORY is off \u2014 refusing to start"),process.exit(2));const r=new t(e,o);console.log(`[replication] started \xB7 interval=${o}ms \xB7 db=${process.env.WYRM_DB_PATH||"~/.wyrm/wyrm.db"}`),await r.run()}s().catch(o=>{console.error("[replication-entrypoint] fatal:",o),process.exit(1)});
1
+ import{WyrmDB as n}from"./database.js";import{ReplicationDaemon as t,DEFAULT_INTERVAL_MS as i}from"./replication-daemon.js";async function s(){const o=Number(process.argv[2])||i,e=new n(process.env.WYRM_DB_PATH);e.liveMemoryEnabled()||(console.error("[replication-entrypoint] WYRM_LIVE_MEMORY is off; refusing to start"),process.exit(2));const r=new t(e,o);console.log(`[replication] started \xB7 interval=${o}ms \xB7 db=${process.env.WYRM_DB_PATH||"~/.wyrm/wyrm.db"}`),await r.run()}s().catch(o=>{console.error("[replication-entrypoint] fatal:",o),process.exit(1)});
@@ -1,2 +1,2 @@
1
- import{spawn as b}from"child_process";import{existsSync as h,readFileSync as j,writeFileSync as M,statSync as I,mkdirSync as _,openSync as N,closeSync as w,unlinkSync as k,renameSync as U}from"fs";import{homedir as T}from"os";import{join as m}from"path";import{replicateOnce as A}from"./event-replication.js";import{checkPeerUrl as R,isValidTokenEnvName as g}from"./repl-guard.js";const l=m(T(),".wyrm"),p=m(l,"wyrm-replication.pid"),c=m(l,"wyrm-replication.log"),E=6e4,v=5e3,x=1e6,L=0,u="repl:peers",S=50;function $(r){if(!r||typeof r.baseUrl!="string")return{ok:!1,reason:"baseUrl required"};const e=R(i(r.baseUrl));return!e.ok&&!/loopback|private|link-local/.test(e.reason)?{ok:!1,reason:e.reason}:!r.projectPath||typeof r.projectPath!="string"?{ok:!1,reason:"projectPath required"}:r.tokenEnv&&!g(r.tokenEnv)?{ok:!1,reason:`tokenEnv must be a WYRM_-prefixed env var name (got ${r.tokenEnv})`}:{ok:!0}}const i=r=>String(r).replace(/\/+$/,"");function d(r){try{const e=r.getMeta(u),n=e?JSON.parse(e):[];return Array.isArray(n)?n:[]}catch{return[]}}function B(r,e){const n=$(e);if(!n.ok)throw new Error(n.reason||"invalid peer");const s={baseUrl:i(e.baseUrl),projectPath:e.projectPath,...e.remoteProject?{remoteProject:e.remoteProject}:{},...e.tokenEnv?{tokenEnv:e.tokenEnv}:{}},t=d(r).filter(o=>!(i(o.baseUrl)===s.baseUrl&&o.projectPath===s.projectPath));return t.push(s),t.length>S&&t.splice(0,t.length-S),r.setMeta(u,JSON.stringify(t)),t}function W(r,e,n){const s=i(e),t=d(r).filter(o=>!(i(o.baseUrl)===s&&o.projectPath===n));return r.setMeta(u,JSON.stringify(t)),t}class q{db;intervalMs;constructor(e,n=E){this.db=e,this.intervalMs=n,P(),this.intervalMs=Math.max(v,n)}async tick(e=globalThis.fetch){if(!this.db.liveMemoryEnabled())return[];const n=d(this.db),s=[];for(const t of n){const o=this.db.getProject(t.projectPath);if(!o){s.push({peer:t.baseUrl,errors:["project not found: "+t.projectPath]});continue}const y=t.tokenEnv&&g(t.tokenEnv)?process.env[t.tokenEnv]:void 0;try{const a=await A(this.db,{baseUrl:i(t.baseUrl),token:y,localProjectId:o.id,remoteProject:t.remoteProject||o.name},e);s.push({peer:t.baseUrl,project:o.name,...a})}catch(a){s.push({peer:t.baseUrl,project:o.name,errors:[a instanceof Error?a.message:String(a)]})}}return s}async run(){f(`replication daemon started \xB7 interval=${this.intervalMs}ms \xB7 peers=${d(this.db).length}`);let e=!1;const n=setInterval(async()=>{if(!e){e=!0;try{const t=await this.tick();for(const o of t)(o.errors.length||(o.pulled||0)+(o.pushed||0)>0)&&f(`tick: ${JSON.stringify(o)}`)}catch(t){f(`tick error: ${t instanceof Error?t.message:String(t)}`)}finally{e=!1}}},this.intervalMs),s=t=>{clearInterval(n),f(`${t} \u2014 shutting down`);try{this.db.close?.()}catch{}process.exit(0)};process.on("SIGTERM",()=>s("SIGTERM")),process.on("SIGINT",()=>s("SIGINT"))}}class z{daemonEntrypoint;constructor(e){this.daemonEntrypoint=e,P()}start(e={}){if(this.isAlive())return{ok:!1,pid:this.readPid(),reason:"already running"};F();const n=Number(e.interval_minutes),s=Number.isFinite(n)&&n>0?Math.round(n*6e4):E,t=N(c,"a");try{const o=b(process.execPath,[this.daemonEntrypoint,String(s)],{detached:!0,stdio:["ignore",t,t],env:{...process.env}});return o.unref(),typeof o.pid!="number"?{ok:!1,reason:"spawn returned no pid"}:(M(p,String(o.pid)),{ok:!0,pid:o.pid})}finally{w(t)}}stop(){if(!this.isAlive())return this.cleanPid(),{ok:!1,reason:"not running"};const e=this.readPid();if(!e)return{ok:!1,reason:"pid file unreadable"};try{return process.kill(e,"SIGTERM"),{ok:!0}}catch(n){return{ok:!1,reason:n instanceof Error?n.message:String(n)}}}status(){const e=this.isAlive();return{running:e,pid:e?this.readPid()??void 0:void 0}}isAlive(){if(!h(p))return!1;const e=this.readPid();if(!e)return!1;try{return process.kill(e,L),!0}catch{return!1}}readPid(){try{const e=Number(j(p,"utf8").trim());return Number.isFinite(e)&&e>0?e:void 0}catch{return}}cleanPid(){try{k(p)}catch{}}}function P(){h(l)||_(l,{recursive:!0})}function f(r){process.stdout.write(`[${new Date().toISOString()}] ${r}
1
+ import{spawn as b}from"child_process";import{existsSync as h,readFileSync as j,writeFileSync as M,statSync as I,mkdirSync as _,openSync as N,closeSync as w,unlinkSync as k,renameSync as U}from"fs";import{homedir as T}from"os";import{join as m}from"path";import{replicateOnce as A}from"./event-replication.js";import{checkPeerUrl as R,isValidTokenEnvName as g}from"./repl-guard.js";const l=m(T(),".wyrm"),p=m(l,"wyrm-replication.pid"),c=m(l,"wyrm-replication.log"),E=6e4,v=5e3,x=1e6,L=0,u="repl:peers",S=50;function $(r){if(!r||typeof r.baseUrl!="string")return{ok:!1,reason:"baseUrl required"};const e=R(i(r.baseUrl));return!e.ok&&!/loopback|private|link-local/.test(e.reason)?{ok:!1,reason:e.reason}:!r.projectPath||typeof r.projectPath!="string"?{ok:!1,reason:"projectPath required"}:r.tokenEnv&&!g(r.tokenEnv)?{ok:!1,reason:`tokenEnv must be a WYRM_-prefixed env var name (got ${r.tokenEnv})`}:{ok:!0}}const i=r=>String(r).replace(/\/+$/,"");function d(r){try{const e=r.getMeta(u),n=e?JSON.parse(e):[];return Array.isArray(n)?n:[]}catch{return[]}}function B(r,e){const n=$(e);if(!n.ok)throw new Error(n.reason||"invalid peer");const s={baseUrl:i(e.baseUrl),projectPath:e.projectPath,...e.remoteProject?{remoteProject:e.remoteProject}:{},...e.tokenEnv?{tokenEnv:e.tokenEnv}:{}},t=d(r).filter(o=>!(i(o.baseUrl)===s.baseUrl&&o.projectPath===s.projectPath));return t.push(s),t.length>S&&t.splice(0,t.length-S),r.setMeta(u,JSON.stringify(t)),t}function W(r,e,n){const s=i(e),t=d(r).filter(o=>!(i(o.baseUrl)===s&&o.projectPath===n));return r.setMeta(u,JSON.stringify(t)),t}class q{db;intervalMs;constructor(e,n=E){this.db=e,this.intervalMs=n,P(),this.intervalMs=Math.max(v,n)}async tick(e=globalThis.fetch){if(!this.db.liveMemoryEnabled())return[];const n=d(this.db),s=[];for(const t of n){const o=this.db.getProject(t.projectPath);if(!o){s.push({peer:t.baseUrl,errors:["project not found: "+t.projectPath]});continue}const y=t.tokenEnv&&g(t.tokenEnv)?process.env[t.tokenEnv]:void 0;try{const a=await A(this.db,{baseUrl:i(t.baseUrl),token:y,localProjectId:o.id,remoteProject:t.remoteProject||o.name},e);s.push({peer:t.baseUrl,project:o.name,...a})}catch(a){s.push({peer:t.baseUrl,project:o.name,errors:[a instanceof Error?a.message:String(a)]})}}return s}async run(){f(`replication daemon started \xB7 interval=${this.intervalMs}ms \xB7 peers=${d(this.db).length}`);let e=!1;const n=setInterval(async()=>{if(!e){e=!0;try{const t=await this.tick();for(const o of t)(o.errors.length||(o.pulled||0)+(o.pushed||0)>0)&&f(`tick: ${JSON.stringify(o)}`)}catch(t){f(`tick error: ${t instanceof Error?t.message:String(t)}`)}finally{e=!1}}},this.intervalMs),s=t=>{clearInterval(n),f(`${t}: shutting down`);try{this.db.close?.()}catch{}process.exit(0)};process.on("SIGTERM",()=>s("SIGTERM")),process.on("SIGINT",()=>s("SIGINT"))}}class z{daemonEntrypoint;constructor(e){this.daemonEntrypoint=e,P()}start(e={}){if(this.isAlive())return{ok:!1,pid:this.readPid(),reason:"already running"};F();const n=Number(e.interval_minutes),s=Number.isFinite(n)&&n>0?Math.round(n*6e4):E,t=N(c,"a");try{const o=b(process.execPath,[this.daemonEntrypoint,String(s)],{detached:!0,stdio:["ignore",t,t],env:{...process.env}});return o.unref(),typeof o.pid!="number"?{ok:!1,reason:"spawn returned no pid"}:(M(p,String(o.pid)),{ok:!0,pid:o.pid})}finally{w(t)}}stop(){if(!this.isAlive())return this.cleanPid(),{ok:!1,reason:"not running"};const e=this.readPid();if(!e)return{ok:!1,reason:"pid file unreadable"};try{return process.kill(e,"SIGTERM"),{ok:!0}}catch(n){return{ok:!1,reason:n instanceof Error?n.message:String(n)}}}status(){const e=this.isAlive();return{running:e,pid:e?this.readPid()??void 0:void 0}}isAlive(){if(!h(p))return!1;const e=this.readPid();if(!e)return!1;try{return process.kill(e,L),!0}catch{return!1}}readPid(){try{const e=Number(j(p,"utf8").trim());return Number.isFinite(e)&&e>0?e:void 0}catch{return}}cleanPid(){try{k(p)}catch{}}}function P(){h(l)||_(l,{recursive:!0})}function f(r){process.stdout.write(`[${new Date().toISOString()}] ${r}
2
2
  `)}function F(){if(h(c))try{if(I(c).size>x){const r=`${c}.1`;try{k(r)}catch{}U(c,r)}}catch{}}export{E as DEFAULT_INTERVAL_MS,v as MIN_INTERVAL_MS,u as PEERS_META_KEY,q as ReplicationDaemon,z as ReplicationManager,B as addPeer,d as listPeers,W as removePeer,$ as validatePeerEntry};
@@ -0,0 +1 @@
1
+ import{getMeta as D,setMeta as A}from"./events.js";import{recordErasure as I}from"./erasure-log.js";import"./governance.js";const w=365,m=7,h="ingest_retention_grace_started_at",R="ingested_transcripts",_=864e5;function v(e,r=process.env){if(typeof e=="number"&&Number.isFinite(e))return e<=0?null:Math.floor(e);const t=(r.WYRM_INGEST_RETAIN_DAYS??"").trim().toLowerCase();if(t==="")return w;if(t==="off"||t==="never")return null;const o=Number(t);return Number.isFinite(o)?o<=0?null:Math.floor(o):w}function N(e){const r=new Set([R]),t=e.getDatabase();try{const o=t.prepare("SELECT DISTINCT category FROM data_lake WHERE category LIKE 'ingested\\_%' ESCAPE '\\'").all();for(const s of o)r.add(s.category)}catch{}try{const o=t.prepare("SELECT value FROM global_context WHERE key = 'connectors'").get();if(o)for(const s of JSON.parse(o.value))typeof s.rawCategory=="string"&&s.rawCategory&&r.add(s.rawCategory)}catch{}return[...r].sort()}function p(e){const r={};for(const t of e)for(const[o,s]of Object.entries(t.counts))r[o]=(r[o]??0)+s;return r}function x(e,r={}){const t=v(r.days),o={status:"disabled",days:t,graceEndsAt:null,categories:[],matched:0,deleted:0,derived:0};if(t===null)return o;const s=e.getDatabase(),g=r.now??new Date,l=N(e),c=l.map(n=>{const a=e.forgetData({dataset:n,olderThanDays:t,dryRun:!0,reason:"retention"});return{category:n,matched:a.matched,deleted:0,counts:a.counts}}),u=c.reduce((n,a)=>n+a.matched,0),E=n=>Object.entries(n).reduce((a,[y,T])=>a+(y==="data_lake"?0:T),0),f=D(s,h),d=f?new Date(Date.parse(f)+m*_).toISOString():null;if(r.dryRun)return{status:"dry-run",days:t,graceEndsAt:d,categories:c,matched:u,deleted:0,derived:E(p(c))};if(!r.skipGrace&&!f){const n=new Date(g.getTime()+m*_).toISOString();return s.transaction(()=>{A(s,h,g.toISOString());const a=c.filter(y=>y.matched>0);I(s,{mode:"preview",reason:"retention",category:a.length===1?a[0].category:l.length===1?l[0]:null,predicate:{older_than_days:t},counts:p(c),actor:r.actor??"maintenance"})})(),{status:"preview",days:t,graceEndsAt:n,categories:c,matched:u,deleted:0,derived:0}}if(!r.skipGrace&&d&&g.getTime()<Date.parse(d))return{status:"grace",days:t,graceEndsAt:d,categories:c,matched:u,deleted:0,derived:0};const i=[];for(const n of c){if(n.matched===0){i.push(n);continue}const a=e.forgetData({dataset:n.category,olderThanDays:t,dryRun:!1,reason:"retention",actor:r.actor??"maintenance"});i.push({category:n.category,matched:a.matched,deleted:a.deleted,counts:a.counts})}const S=i.reduce((n,a)=>n+a.deleted,0);return{status:"enforced",days:t,graceEndsAt:d,categories:i,matched:u,deleted:S,derived:E(p(i))}}function b(e){const r=t=>t?t.slice(0,10):"unknown";switch(e.status){case"preview":return e.matched===0?null:`Ingest retention (${e.days}d): preview recorded, ${e.matched} ingested row(s) would be erased once the ${m}-day grace period ends on ${r(e.graceEndsAt)}; nothing was deleted (wyrm forget --retention --dry-run)`;case"grace":return e.matched>0?`Ingest retention (${e.days}d): grace period until ${r(e.graceEndsAt)}, ${e.matched} ingested row(s) pending; nothing was deleted`:null;case"enforced":return e.deleted>0?`Ingest retention (${e.days}d): erased ${e.deleted} ingested row(s) and ${e.derived} derived row(s); see erasure_log`:null;default:return null}}export{R as DEFAULT_INGEST_CATEGORY,w as DEFAULT_INGEST_RETAIN_DAYS,m as RETENTION_GRACE_DAYS,h as RETENTION_GRACE_KEY,x as enforceIngestRetention,N as ingestedCategories,v as resolveIngestRetainDays,b as retentionLine};
@@ -1,8 +1,8 @@
1
- import{existsSync as R,readFileSync as x}from"fs";import{join as g}from"path";import{RENDER_MARKER_START as h,RENDER_MARKER_END as m,hasWyrmRegion as y,resolveInsideRoot as b}from"./render-target.js";import{extractCandidates as _,candidateToArtifact as S,escapeLikePattern as T}from"./auto-capture.js";function f(r){const t=r.indexOf(h),e=r.indexOf(m);if(t===-1||e===-1||e<=t)return{hasRegion:!1,before:r,region:"",after:""};const i=r.slice(0,t);let n=r.slice(t+h.length,e);const o=r.slice(e+m.length);return n.startsWith(`
1
+ import{existsSync as R,readFileSync as x}from"fs";import{join as g}from"path";import{RENDER_MARKER_START as h,RENDER_MARKER_END as m,hasWyrmRegion as y,resolveInsideRoot as _}from"./render-target.js";import{extractCandidates as b,candidateToArtifact as S,escapeLikePattern as v}from"./auto-capture.js";import{writerEnvelope as T}from"./handlers/boundary.js";function f(r){const t=r.indexOf(h),e=r.indexOf(m);if(t===-1||e===-1||e<=t)return{hasRegion:!1,before:r,region:"",after:""};const i=r.slice(0,t);let n=r.slice(t+h.length,e);const o=r.slice(e+m.length);return n.startsWith(`
2
2
  `)&&(n=n.slice(1)),n.endsWith(`
3
- `)&&(n=n.slice(0,-1)),{hasRegion:!0,before:i,region:n,after:o}}function v(r,t){const e=f(r);return e.hasRegion?e.region.trim()!==t.trim():!1}function W(r,t,e){const i=[],n=f(t);if(!n.hasRegion){const s=t.trim();return s.length>0&&i.push({path:r,zone:"outside",text:s}),i}e!=null&&n.region.trim()!==e.trim()&&i.push({path:r,zone:"region",text:n.region.trim()});const o=`${n.before}
4
- ${n.after}`.trim();return o.length>0&&i.push({path:r,zone:"outside",text:o}),i}async function w(r,t={}){const{candidates:e}=await _(r.text,t),i=[];for(const n of e){const o=S(n),s="rb:"+n.text.toLowerCase().replace(/[\s,]+/g," ").trim().slice(0,64).trim(),c=o.tags.filter(l=>!l.startsWith("ax:"));c.push("reverse-bridge",`zone:${r.zone}`,s),i.push({kind:o.kind,problem:o.problem,tags:c,confidence:o.confidence,sig:s,zone:r.zone})}return i}async function P(r,t,e,i={}){let n=0,o=0;const s=[],c=new Set;for(const l of e){let u=[];try{u=await w(l,i)}catch{continue}for(const a of u){if(c.has(a.sig)||r.existsBySig(t,a.sig)){o++;continue}c.add(a.sig),i.dryRun||r.addCandidate(t,a),n++,s.length<5&&s.push(`[${a.zone}] ${a.problem.slice(0,80)}`)}}return{added:n,skipped:o,sample:s}}function z(r){return{existsBySig(t,e){if(!!r.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(t,"%"+T(e)+"%"))return!0;try{return!!r.prepare("SELECT 1 FROM reverse_bridge_tombstones WHERE project_id = ? AND sig = ? LIMIT 1").get(t,e)}catch{return!1}},addCandidate(t,e){r.prepare(`
3
+ `)&&(n=n.slice(0,-1)),{hasRegion:!0,before:i,region:n,after:o}}function w(r,t){const e=f(r);return e.hasRegion?e.region.trim()!==t.trim():!1}function W(r,t,e){const i=[],n=f(t);if(!n.hasRegion){const s=t.trim();return s.length>0&&i.push({path:r,zone:"outside",text:s}),i}e!=null&&n.region.trim()!==e.trim()&&i.push({path:r,zone:"region",text:n.region.trim()});const o=`${n.before}
4
+ ${n.after}`.trim();return o.length>0&&i.push({path:r,zone:"outside",text:o}),i}async function P(r,t={}){const{candidates:e}=await b(r.text,t),i=[];for(const n of e){const o=S(n),s="rb:"+n.text.toLowerCase().replace(/[\s,]+/g," ").trim().slice(0,64).trim(),c=o.tags.filter(l=>!l.startsWith("ax:"));c.push("reverse-bridge",`zone:${r.zone}`,s),i.push({kind:o.kind,problem:o.problem,tags:c,confidence:o.confidence,sig:s,zone:r.zone})}return i}async function A(r,t,e,i={}){let n=0,o=0;const s=[],c=new Set;for(const l of e){let u=[];try{u=await P(l,i)}catch{continue}for(const a of u){if(c.has(a.sig)||r.existsBySig(t,a.sig)){o++;continue}c.add(a.sig),i.dryRun||r.addCandidate(t,a),n++,s.length<5&&s.push(`[${a.zone}] ${a.problem.slice(0,80)}`)}}return{added:n,skipped:o,sample:s}}function F(r){return{existsBySig(t,e){if(!!r.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(t,"%"+v(e)+"%"))return!0;try{return!!r.prepare("SELECT 1 FROM reverse_bridge_tombstones WHERE project_id = ? AND sig = ? LIMIT 1").get(t,e)}catch{return!1}},addCandidate(t,e){const i=T("reverse-bridge");r.prepare(`
5
5
  INSERT INTO memory_artifacts
6
- (project_id, kind, problem, tags, confidence, needs_review, created_by)
7
- VALUES (?, ?, ?, ?, ?, 1, 'reverse-bridge')
8
- `).run(t,e.kind,e.problem,e.tags.join(","),e.confidence)}}}function C(r){if(!r)return null;for(const t of r.split(",")){const e=t.trim();if(e.startsWith("rb:"))return e}return null}function F(r,t,e){try{r.prepare("INSERT OR IGNORE INTO reverse_bridge_tombstones (project_id, sig) VALUES (?, ?)").run(t,e)}catch{}}function j(r,t,e){if(t==null)return{proceed:!0,reason:"no existing file"};if(!y(t))return{proceed:!0,reason:"no Wyrm region to overwrite"};if(e==null){const n=f(t);return{proceed:!1,pendingEdit:{path:r,zone:"region",text:n.region.trim()},reason:"region present but no last-render record \u2014 harvest before overwrite"}}if(!v(t,e))return{proceed:!0,reason:"region unchanged since last render"};const i=f(t);return{proceed:!1,pendingEdit:{path:r,zone:"region",text:i.region.trim()},reason:"region edited since last render \u2014 harvest the edit before overwriting"}}const A=[{relPath:"MEMORY.md"},{relPath:"CLAUDE.md",client:"claude"},{relPath:"AGENTS.md",client:"agents"},{relPath:g(".cursor","rules","wyrm-memory.md"),client:"cursor"},{relPath:g(".github","copilot-instructions.md"),client:"copilot"}],I={existsSync:R,readFileSync:x};function L(r,t=I){const e=[];for(const{relPath:i}of A){let n;try{n=b(r,i)}catch{continue}let o=!1,s=null;try{o=t.existsSync(n),s=o?t.readFileSync(n,"utf-8"):null}catch{o=!1,s=null}e.push({relPath:i,absPath:n,exists:o,content:s})}return e}async function k(r,t,e,i={}){const n=i.rootDir??t.path,o=L(n,i.fs),s=[];let c=0;for(const d of o){if(!d.exists||d.content==null)continue;const E=Object.prototype.hasOwnProperty.call(e,d.relPath)?e[d.relPath]:null,p=W(d.absPath,d.content,E);p.length>0&&c++,s.push(...p)}const{added:l,skipped:u,sample:a}=await P(r,t.id,s,i);return{filesScanned:o.length,filesWithEdits:c,added:l,skipped:u,sample:a}}function $(r=process.env){const t=(r.WYRM_REVERSE_BRIDGE??"").toLowerCase();if(t==="1"||t==="true"||t==="yes")return!0;const e=(r.WYRM_RENDER_WATCH??"").toLowerCase();return e==="1"||e==="true"||e==="yes"}export{A as WATCHED_MEMORY_FILES,W as detectEdits,w as editToCandidates,j as guardRender,P as harvestEdits,z as makeBridgeDeps,F as recordReverseBridgeRejection,v as regionEditedSinceRender,$ as reverseBridgeEnabled,C as reverseBridgeSigFromTags,L as scanWatchedFiles,f as splitWyrmRegion,k as sweepProject};
6
+ (project_id, kind, problem, tags, confidence, needs_review, created_by, agent_id, run_id)
7
+ VALUES (?, ?, ?, ?, ?, 1, 'reverse-bridge', ?, ?)
8
+ `).run(t,e.kind,e.problem,e.tags.join(","),e.confidence,i.agent_id,i.run_id)}}}function j(r){if(!r)return null;for(const t of r.split(",")){const e=t.trim();if(e.startsWith("rb:"))return e}return null}function k(r,t,e){try{r.prepare("INSERT OR IGNORE INTO reverse_bridge_tombstones (project_id, sig) VALUES (?, ?)").run(t,e)}catch{}}function $(r,t,e){if(t==null)return{proceed:!0,reason:"no existing file"};if(!y(t))return{proceed:!0,reason:"no Wyrm region to overwrite"};if(e==null){const n=f(t);return{proceed:!1,pendingEdit:{path:r,zone:"region",text:n.region.trim()},reason:"region present but no last-render record; harvest before overwrite"}}if(!w(t,e))return{proceed:!0,reason:"region unchanged since last render"};const i=f(t);return{proceed:!1,pendingEdit:{path:r,zone:"region",text:i.region.trim()},reason:"region edited since last render; harvest the edit before overwriting"}}const I=[{relPath:"MEMORY.md"},{relPath:"CLAUDE.md",client:"claude"},{relPath:"AGENTS.md",client:"agents"},{relPath:g(".cursor","rules","wyrm-memory.md"),client:"cursor"},{relPath:g(".github","copilot-instructions.md"),client:"copilot"}],L={existsSync:R,readFileSync:x};function N(r,t=L){const e=[];for(const{relPath:i}of I){let n;try{n=_(r,i)}catch{continue}let o=!1,s=null;try{o=t.existsSync(n),s=o?t.readFileSync(n,"utf-8"):null}catch{o=!1,s=null}e.push({relPath:i,absPath:n,exists:o,content:s})}return e}async function B(r,t,e,i={}){const n=i.rootDir??t.path,o=N(n,i.fs),s=[];let c=0;for(const d of o){if(!d.exists||d.content==null)continue;const E=Object.prototype.hasOwnProperty.call(e,d.relPath)?e[d.relPath]:null,p=W(d.absPath,d.content,E);p.length>0&&c++,s.push(...p)}const{added:l,skipped:u,sample:a}=await A(r,t.id,s,i);return{filesScanned:o.length,filesWithEdits:c,added:l,skipped:u,sample:a}}function H(r=process.env){const t=(r.WYRM_REVERSE_BRIDGE??"").toLowerCase();if(t==="1"||t==="true"||t==="yes")return!0;const e=(r.WYRM_RENDER_WATCH??"").toLowerCase();return e==="1"||e==="true"||e==="yes"}export{I as WATCHED_MEMORY_FILES,W as detectEdits,P as editToCandidates,$ as guardRender,A as harvestEdits,F as makeBridgeDeps,k as recordReverseBridgeRejection,w as regionEditedSinceRender,H as reverseBridgeEnabled,j as reverseBridgeSigFromTags,N as scanWatchedFiles,f as splitWyrmRegion,B as sweepProject};
@@ -0,0 +1,31 @@
1
+ import{recordGovernanceEvent as s,governanceActor as o}from"./governance.js";const a=20,d=5,p=25;function c(t=process.env){const e=t.WYRM_REVIEW_SAMPLE_PER_WEEK;if(e===void 0||e.trim()==="")return a;const r=Number(e);return Number.isInteger(r)&&r>=0?Math.min(r,1e3):a}const E=t=>t==="imported"||t==="untrusted";function m(t,e){const r=c();if(r===0)return!1;const i=E(e.source_trust);if(e.id%(i?d:p)!==0)return!1;const n=Math.floor(r/3);try{return(i?t.prepare(`
2
+ INSERT OR IGNORE INTO review_sample (artifact_id, project_id, lane, week)
3
+ SELECT ?, ?, ?, strftime('%Y-W%W', 'now')
4
+ WHERE (SELECT COUNT(*) FROM review_sample
5
+ WHERE week = strftime('%Y-W%W', 'now') AND lane IN ('imported', 'untrusted')) < ?
6
+ `).run(e.id,e.project_id,e.source_trust,r-n):t.prepare(`
7
+ INSERT OR IGNORE INTO review_sample (artifact_id, project_id, lane, week)
8
+ SELECT ?, ?, ?, strftime('%Y-W%W', 'now')
9
+ WHERE (SELECT COUNT(*) FROM review_sample
10
+ WHERE week = strftime('%Y-W%W', 'now') AND lane IN ('operator', 'agent')) < ?
11
+ `).run(e.id,e.project_id,e.source_trust,n)).changes>0}catch{return!1}}function u(t,e={}){const r=Math.max(1,Math.min(1e3,Math.floor(e.limit??50))),i=e.projectId??null;try{return t.prepare(`
12
+ SELECT s.artifact_id, s.project_id, s.lane, s.week, s.sampled_at, s.reviewed_by, s.reviewed_at, s.verdict,
13
+ a.kind, a.problem
14
+ FROM review_sample s
15
+ LEFT JOIN memory_artifacts a ON a.id = s.artifact_id
16
+ WHERE (? = 1 OR (s.reviewed_at IS NULL AND a.id IS NOT NULL))
17
+ AND (? IS NULL OR s.project_id = ?)
18
+ ORDER BY s.sampled_at ASC, s.id ASC
19
+ LIMIT ?
20
+ `).all(e.includeReviewed?1:0,i,i,r)}catch{return[]}}function R(t,e){const r=e??null;try{const i=t.prepare(`
21
+ SELECT COUNT(*) AS n, MIN(s.sampled_at) AS oldest
22
+ FROM review_sample s JOIN memory_artifacts a ON a.id = s.artifact_id
23
+ WHERE s.reviewed_at IS NULL AND (? IS NULL OR s.project_id = ?)
24
+ `).get(r,r),n=t.prepare(`
25
+ SELECT COUNT(*) AS n FROM review_sample
26
+ WHERE week = strftime('%Y-W%W', 'now') AND (? IS NULL OR project_id = ?)
27
+ `).get(r,r);return{unreviewed:i.n,thisWeek:n.n,oldestUnreviewedAt:i.oldest}}catch{return{unreviewed:0,thisWeek:0,oldestUnreviewedAt:null}}}function f(t,e,r=o()){return t.transaction(()=>{const i=t.prepare(`
28
+ SELECT s.lane, a.id AS present, a.project_id
29
+ FROM review_sample s LEFT JOIN memory_artifacts a ON a.id = s.artifact_id
30
+ WHERE s.artifact_id = ?
31
+ `).get(e);return i?i.present==null?"not_found":(t.prepare("UPDATE review_sample SET reviewed_by = ?, reviewed_at = datetime('now'), verdict = 'kept' WHERE artifact_id = ?").run(r,e),t.prepare("UPDATE memory_artifacts SET reviewed_by = ?, reviewed_at = datetime('now') WHERE id = ?").run(r,e),s(t,"review.sample",{artifact_id:e,verdict:"kept",lane:i.lane},{projectId:i.project_id,actor:r}),"kept"):"not_sampled"})()}function w(t,e,r){try{t.prepare("UPDATE review_sample SET reviewed_by = ?, reviewed_at = datetime('now'), verdict = 'rejected' WHERE artifact_id = ?").run(r,e)}catch{}}export{a as DEFAULT_REVIEW_SAMPLE_PER_WEEK,f as keepSampled,u as listReviewSample,w as markSampleRejected,R as reviewSampleCounts,c as reviewSamplePerWeek,m as sampleAutoApprovedWrite};
package/dist/security.js CHANGED
@@ -1 +1 @@
1
- import{resolve as l,relative as T,normalize as c,sep as m,join as w,dirname as _,isAbsolute as R}from"path";import{existsSync as d,statSync as x,realpathSync as D,lstatSync as I,readlinkSync as L}from"fs";import{homedir as p}from"os";import{createHash as P}from"crypto";const y=[[/\bsk-ant-api[0-9]{2}-[A-Za-z0-9_-]{20,}/g,"[REDACTED]"],[/\bsk-[A-Za-z0-9]{20,}/g,"[REDACTED]"],[/\bnvapi-[A-Za-z0-9_-]{20,}/g,"[REDACTED]"],[/\bgh[pousr]_[A-Za-z0-9]{20,}/g,"[REDACTED]"],[/\bxox[baprs]-[0-9A-Za-z-]{10,}/g,"[REDACTED]"],[/\bAKIA[0-9A-Z]{16}\b/g,"[REDACTED]"],[/\b[sr]k_(?:live|test)_[A-Za-z0-9]{16,}/g,"[REDACTED]"],[/\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])/g,"[REDACTED]"],[/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,"[REDACTED]"],[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,"[REDACTED]"],[/\b[Bb]earer\s+[A-Za-z0-9._~+/-]{20,}=*/g,"Bearer [REDACTED]"],[/\b(pass(?:word|wd)?|secret|api[_-]?key|apikey|token|auth)\b\s*[:=]\s*["']?([^\s"'<>,;]{8,})["']?/gi,e=>e.replace(/([:=]\s*["']?)([^\s"'<>,;]{8,})/,"$1[REDACTED]")]];function O(e){let t=e;for(const[r,n]of y)t=t.replace(r,n);return t}function Z(e=[]){const t=[process.cwd(),w(p(),".wyrm"),...e];if(process.env.WYRM_ALLOWED_PATHS)for(const r of process.env.WYRM_ALLOWED_PATHS.split(":"))r.trim()&&t.push(r.trim());return t.map(r=>c(l(r)))}function H(e,t,r){const n=(e??"").trim();if(!n)throw new i(`${r}: path is required`,"INVALID_PATH");let o=n;if(o==="~"?o=p():o.startsWith("~/")&&(o=w(p(),o.slice(2))),o.includes("\0"))throw new i(`${r}: path contains a null byte`,"INVALID_PATH");const a=c(l(o)),h=f=>t.some(s=>{const A=T(s,f);return A===""||!A.startsWith("..")&&!R(A)});if(!h(a))throw new i(`${r}: path is outside the allowed roots. Allowed: ${t.join(", ")} (extend with WYRM_ALLOWED_PATHS).`,"PATH_NOT_ALLOWED");let u=a;try{let f=null;try{f=I(a)}catch{f=null}if(f?.isSymbolicLink()){const s=l(_(a),L(a));let A=s;try{A=d(s)?D(s):s}catch{}if(!h(c(A)))throw new i(`${r}: path is a symlink pointing outside the allowed roots.`,"PATH_NOT_ALLOWED");u=A}else if(d(a))u=D(a);else{let s=_(a);const A=new Set;for(;!d(s)&&_(s)!==s&&!A.has(s);)A.add(s),s=_(s);d(s)&&(u=w(D(s),T(s,a)))}}catch(f){throw f instanceof i?f:new i(`${r}: path could not be resolved safely`,"PATH_NOT_ALLOWED")}if(!h(c(u)))throw new i(`${r}: path resolves outside the allowed roots via a symlink.`,"PATH_NOT_ALLOWED");return u}function $(e,t){const r=c(l(e)),n=c(l(e,t)),o=T(r,n);if(o.startsWith("..")||o.startsWith(m))throw new i("Path traversal detected","PATH_TRAVERSAL");if(!n.startsWith(r))throw new i("Path traversal detected","PATH_TRAVERSAL");return n}function v(e){try{return d(e)&&x(e).isDirectory()}catch{return!1}}function k(e){const t=c(l(e)),r=[c(l(p(),"Git Projects")),c(l(p(),"Projects")),c(l(p(),"dev")),c(l(p(),"code")),c(l(p(),"repos"))];if(process.env.WYRM_ALLOWED_PATHS){const o=process.env.WYRM_ALLOWED_PATHS.split(":");for(const a of o)r.push(c(l(a)))}if(!r.some(o=>t===o||t.startsWith(o+m)))throw new i("Project path not in allowed directories","INVALID_PROJECT_PATH");if(!v(t))throw new i("Path is not a valid directory","INVALID_DIRECTORY");return t}function M(e){if(!e||typeof e!="string")throw new i("Invalid search query","INVALID_INPUT");const t=e.replace(/[\x00-\x1f\x7f]/g," ").replace(/[*"():^{}[\]\\.@#$%&!?<>~`|;,]/g," ").replace(/\s+/g," ").trim().slice(0,500);if(!t)throw new i("Search query is empty after sanitization","INVALID_INPUT");return t}function V(e){const t=e.replace(/[\x00-\x1f\x7f]/g," ").split(/\s+/).map(r=>r.replace(/"/g,"").trim()).filter(Boolean);return t.length===0?"":t.map(r=>`"${r}"`).join(" OR ")}function Y(e,t=1e4){if(e==null)return"";if(typeof e!="string")throw new i("Expected string input","INVALID_TYPE");return e.slice(0,t)}function B(e,t=0,r=Number.MAX_SAFE_INTEGER){const n=Number(e);if(!Number.isInteger(n))throw new i("Expected integer input","INVALID_TYPE");if(n<t||n>r)throw new i(`Integer out of range [${t}, ${r}]`,"OUT_OF_RANGE");return n}function j(e,t,r){if(e===void 0&&r!==void 0)return r;if(typeof e!="string"||!t.includes(e))throw new i(`Invalid value. Allowed: ${t.join(", ")}`,"INVALID_ENUM");return e}function U(e,t){if(!e||!e.startsWith("Bearer "))return!1;const r=e.slice(7);return!r||r.length<32?!1:N(S(r),t)}function S(e){return P("sha256").update(e).digest("hex")}function N(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}const E=new Map;function G(e,t=100,r=6e4){const n=Date.now();let o=E.get(e);if(E.size>1e4)for(const[a,h]of E)h.resetAt<n&&E.delete(a);return(!o||o.resetAt<n)&&(o={count:0,resetAt:n+r},E.set(e,o)),o.count++,{allowed:o.count<=t,remaining:Math.max(0,t-o.count),resetAt:o.resetAt}}class i extends Error{code;constructor(t,r){super(t),this.name="SecurityError",this.code=r}}const F=1024*1024,g=1e3,K=1e3;function Q(e){if(!Array.isArray(e))throw new i("Expected array for batch operation","INVALID_TYPE");if(e.length>g)throw new i(`Batch size ${e.length} exceeds maximum of ${g}`,"BATCH_TOO_LARGE")}export{g as MAX_BATCH_SIZE,K as MAX_QUERY_RESULTS,F as MAX_REQUEST_SIZE,i as SecurityError,V as buildFtsMatchQuery,G as checkRateLimit,N as constantTimeCompare,S as hashToken,O as redactCredentials,H as resolveUserPath,M as sanitizeFtsQuery,Y as sanitizeString,Z as userPathRoots,U as validateApiKey,Q as validateBatchSize,v as validateDirectory,j as validateEnum,B as validateInt,$ as validatePath,k as validateProjectPath};
1
+ import{resolve as l,relative as _,normalize as c,sep as m,join as T,dirname as E,isAbsolute as y}from"path";import{existsSync as p,statSync as R,realpathSync as D,lstatSync as x,readlinkSync as I}from"fs";import{homedir as A}from"os";import{createHash as L}from"crypto";const P=[[/\bsk-ant-api[0-9]{2}-[A-Za-z0-9_-]{20,}/g,"[REDACTED]"],[/\bsk-[A-Za-z0-9]{20,}/g,"[REDACTED]"],[/\bnvapi-[A-Za-z0-9_-]{20,}/g,"[REDACTED]"],[/\bgh[pousr]_[A-Za-z0-9]{20,}/g,"[REDACTED]"],[/\bxox[baprs]-[0-9A-Za-z-]{10,}/g,"[REDACTED]"],[/\bAKIA[0-9A-Z]{16}\b/g,"[REDACTED]"],[/\b[sr]k_(?:live|test)_[A-Za-z0-9]{16,}/g,"[REDACTED]"],[/\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])/g,"[REDACTED]"],[/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g,"[REDACTED]"],[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,"[REDACTED]"],[/\b[Bb]earer\s+[A-Za-z0-9._~+/-]{20,}=*/g,"Bearer [REDACTED]"],[/\b(pass(?:word|wd)?|secret|api[_-]?key|apikey|token|auth)\b\s*[:=]\s*["']?([^\s"'<>,;]{8,})["']?/gi,e=>e.replace(/([:=]\s*["']?)([^\s"'<>,;]{8,})/,"$1[REDACTED]")]];function $(e){let t=e;for(const[r,o]of P)t=t.replace(r,o);return t}function H(e=[]){const t=[process.cwd(),T(A(),".wyrm"),...e];if(process.env.WYRM_ALLOWED_PATHS)for(const r of process.env.WYRM_ALLOWED_PATHS.split(":"))r.trim()&&t.push(r.trim());return t.map(r=>c(l(r)))}function M(e,t,r){const o=(e??"").trim();if(!o)throw new s(`${r}: path is required`,"INVALID_PATH");let n=o;if(n==="~"?n=A():n.startsWith("~/")&&(n=T(A(),n.slice(2))),n.includes("\0"))throw new s(`${r}: path contains a null byte`,"INVALID_PATH");const a=c(l(n)),u=f=>t.some(i=>{const h=_(i,f);return h===""||!h.startsWith("..")&&!y(h)});if(!u(a))throw new s(`${r}: path is outside the allowed roots. Allowed: ${t.join(", ")} (extend with WYRM_ALLOWED_PATHS).`,"PATH_NOT_ALLOWED");let d=a;try{let f=null;try{f=x(a)}catch{f=null}if(f?.isSymbolicLink()){const i=l(E(a),I(a));let h=i;try{h=p(i)?D(i):i}catch{}if(!u(c(h)))throw new s(`${r}: path is a symlink pointing outside the allowed roots.`,"PATH_NOT_ALLOWED");d=h}else if(p(a))d=D(a);else{let i=E(a);const h=new Set;for(;!p(i)&&E(i)!==i&&!h.has(i);)h.add(i),i=E(i);p(i)&&(d=T(D(i),_(i,a)))}}catch(f){throw f instanceof s?f:new s(`${r}: path could not be resolved safely`,"PATH_NOT_ALLOWED")}if(!u(c(d)))throw new s(`${r}: path resolves outside the allowed roots via a symlink.`,"PATH_NOT_ALLOWED");return d}function V(e,t){const r=c(l(e)),o=c(l(e,t)),n=_(r,o);if(n.startsWith("..")||n.startsWith(m))throw new s("Path traversal detected","PATH_TRAVERSAL");if(!o.startsWith(r))throw new s("Path traversal detected","PATH_TRAVERSAL");return o}function S(e){try{return p(e)&&R(e).isDirectory()}catch{return!1}}function Y(e){const t=c(l(e)),r=[c(l(A(),"Git Projects")),c(l(A(),"Projects")),c(l(A(),"dev")),c(l(A(),"code")),c(l(A(),"repos"))];if(process.env.WYRM_ALLOWED_PATHS){const n=process.env.WYRM_ALLOWED_PATHS.split(":");for(const a of n)r.push(c(l(a)))}if(!r.some(n=>t===n||t.startsWith(n+m)))throw new s("Project path not in allowed directories","INVALID_PROJECT_PATH");if(!S(t))throw new s("Path is not a valid directory","INVALID_DIRECTORY");return t}function B(e){if(!e||typeof e!="string")throw new s("Invalid search query","INVALID_INPUT");const t=e.replace(/[\x00-\x1f\x7f]/g," ").replace(/[*"():^{}[\]\\.@#$%&!?<>~`|;,]/g," ").replace(/\s+/g," ").trim().slice(0,500);if(!t)throw new s("Search query is empty after sanitization","INVALID_INPUT");return t}function k(e){const t=e.replace(/[\x00-\x1f\x7f]/g," ").split(/\s+/).map(o=>o.replace(/"/g,"").trim()).filter(Boolean);if(t.length===0)return"";const r=t.filter(o=>!b(o));return(r.length>0?r:t).map(o=>`"${o}"`).join(" OR ")}const v=new Set(["a","an","the","and","or","but","of","to","in","on","at","by","for","from","with","about","into","as","than","then","so","if","is","are","was","were","be","been","being","am","do","does","did","has","have","had","what","which","who","whom","whose","when","where","why","how","this","that","these","those","it","its","there","here","i","me","my","we","us","our","you","your","he","him","his","she","her","they","them","their","would","should","could","shall"]);function b(e){return!/^(?:[a-z]+|[A-Z][a-z]*)$/.test(e)||e.length>1&&e===e.toUpperCase()?!1:v.has(e.toLowerCase())}function U(e,t=1e4){if(e==null)return"";if(typeof e!="string")throw new s("Expected string input","INVALID_TYPE");return e.slice(0,t)}function j(e,t=0,r=Number.MAX_SAFE_INTEGER){const o=Number(e);if(!Number.isInteger(o))throw new s("Expected integer input","INVALID_TYPE");if(o<t||o>r)throw new s(`Integer out of range [${t}, ${r}]`,"OUT_OF_RANGE");return o}function F(e,t,r){if(e===void 0&&r!==void 0)return r;if(typeof e!="string"||!t.includes(e))throw new s(`Invalid value. Allowed: ${t.join(", ")}`,"INVALID_ENUM");return e}function G(e,t){if(!e||!e.startsWith("Bearer "))return!1;const r=e.slice(7);return!r||r.length<32?!1:N(z(r),t)}function z(e){return L("sha256").update(e).digest("hex")}function N(e,t){if(e.length!==t.length)return!1;let r=0;for(let o=0;o<e.length;o++)r|=e.charCodeAt(o)^t.charCodeAt(o);return r===0}const w=new Map;function K(e,t=100,r=6e4){const o=Date.now();let n=w.get(e);if(w.size>1e4)for(const[a,u]of w)u.resetAt<o&&w.delete(a);return(!n||n.resetAt<o)&&(n={count:0,resetAt:o+r},w.set(e,n)),n.count++,{allowed:n.count<=t,remaining:Math.max(0,t-n.count),resetAt:n.resetAt}}class s extends Error{code;constructor(t,r){super(t),this.name="SecurityError",this.code=r}}const Q=1024*1024,g=1e3,X=1e3;function J(e){if(!Array.isArray(e))throw new s("Expected array for batch operation","INVALID_TYPE");if(e.length>g)throw new s(`Batch size ${e.length} exceeds maximum of ${g}`,"BATCH_TOO_LARGE")}export{g as MAX_BATCH_SIZE,X as MAX_QUERY_RESULTS,Q as MAX_REQUEST_SIZE,s as SecurityError,k as buildFtsMatchQuery,K as checkRateLimit,N as constantTimeCompare,z as hashToken,b as isFtsStopword,$ as redactCredentials,M as resolveUserPath,B as sanitizeFtsQuery,U as sanitizeString,H as userPathRoots,G as validateApiKey,J as validateBatchSize,S as validateDirectory,F as validateEnum,j as validateInt,V as validatePath,Y as validateProjectPath};
@@ -1,7 +1,7 @@
1
- import{SessionSeen as s}from"./session-seen.js";import{FailurePatterns as c}from"./failure-patterns.js";import{AgentPresence as u}from"./presence.js";import{runMaintenance as m}from"./maintenance.js";const i="last_maintenance_at",l=24;function E(t){const e=Number(t.WYRM_MAINTENANCE_INTERVAL_HOURS);return Number.isFinite(e)&&e>0?e:l}function N(t,e,a){const r=new Date(e).toISOString(),n=new Date(e-a*36e5).toISOString();return t.prepare(`
1
+ import{SessionSeen as N}from"./session-seen.js";import{FailurePatterns as M}from"./failure-patterns.js";import{AgentPresence as A}from"./presence.js";import{runMaintenance as p}from"./maintenance.js";import{maybeBackfill as w,runRetainDays as y}from"./index-health.js";const f="last_maintenance_at",T=24;function R(n){const e=Number(n.WYRM_MAINTENANCE_INTERVAL_HOURS);return Number.isFinite(e)&&e>0?e:T}function S(n,e,a){const o=new Date(e).toISOString(),r=new Date(e-a*36e5).toISOString();return n.prepare(`
2
2
  INSERT INTO wyrm_meta (key, value) VALUES (?, ?)
3
3
  ON CONFLICT(key) DO UPDATE SET value = excluded.value
4
4
  WHERE wyrm_meta.value < ?
5
- `).run(i,r,n).changes===1}function S(t){try{return t.prepare("SELECT value FROM wyrm_meta WHERE key = ?").get(i)?.value??null}catch{return null}}function p(t,e=process.env,a=Date.now()){try{if((e.WYRM_AUTO_MAINTENANCE??"1")==="0")return{outcome:"disabled",lines:[]};const r=t.getDatabase();if(!N(r,a,E(e)))return{outcome:"not-due",lines:[]};try{const n=m({db:t,sessionSeen:new s(r),failures:new c(r),presence:new u(r)});return e.WYRM_MAINTENANCE_DEBUG==="1"&&process.stderr.write(`wyrm: automatic maintenance ran, ${n.lines.length} step(s)
6
- `),{outcome:"ran",lines:n.lines}}catch(n){if(e.WYRM_MAINTENANCE_DEBUG==="1"){const o=n instanceof Error?n.message:String(n);process.stderr.write(`wyrm: automatic maintenance failed (retries next interval): ${o.slice(0,200)}
7
- `)}return{outcome:"failed",lines:[]}}}catch{return{outcome:"failed",lines:[]}}}function T(t,e=process.env){setImmediate(()=>{try{p(t,e)}catch{}})}export{i as LAST_MAINTENANCE_KEY,N as claimMaintenanceSlot,S as lastMaintenanceAt,p as maybeRunMaintenance,T as scheduleMaintenanceSweep};
5
+ `).run(f,o,r).changes===1}function O(n){try{return n.prepare("SELECT value FROM wyrm_meta WHERE key = ?").get(f)?.value??null}catch{return null}}function d(n,e=process.env,a=Date.now(),o={}){try{if((e.WYRM_AUTO_MAINTENANCE??"1")==="0")return{outcome:"disabled",lines:[]};const r=n.getDatabase();if(!S(r,a,R(e)))return{outcome:"not-due",lines:[]};try{const t=p({db:n,sessionSeen:new N(r),failures:new M(r),presence:new A(r)},{activeModel:o.activeModel??null,compactGraph:e.WYRM_GRAPH_COMPACT==="1",runRetainDays:y(e)});return e.WYRM_MAINTENANCE_DEBUG==="1"&&process.stderr.write(`wyrm: automatic maintenance ran, ${t.lines.length} step(s)
6
+ `),{outcome:"ran",lines:t.lines}}catch(t){if(e.WYRM_MAINTENANCE_DEBUG==="1"){const s=t instanceof Error?t.message:String(t);process.stderr.write(`wyrm: automatic maintenance failed (retries next interval): ${s.slice(0,200)}
7
+ `)}return{outcome:"failed",lines:[]}}}catch{return{outcome:"failed",lines:[]}}}const C=36e5;function U(n,e=process.env,a={}){if((e.WYRM_AUTO_MAINTENANCE??"1")==="0")return null;const o=a.now??Date.now,r=typeof n=="function"?n:()=>n;let t=!1;const s=()=>{if(t)return;t=!0;let c=null,m=!1,i=null;try{i=r(),c=a.vectors?.()??null,m=d(i,e,o(),{activeModel:c?c.getProvider().model:null}).outcome==="ran"}catch{}if(!m||!c||!i){t=!1;return}let E;try{E=i.getDatabase()}catch{t=!1;return}w(E,c,e).catch(()=>null).finally(()=>{t=!1})};setImmediate(s);const l=Number(e.WYRM_MAINTENANCE_CHECK_MS),_=a.checkEveryMs??(Number.isFinite(l)&&l>=10?l:C),u=setInterval(s,_);return u.unref(),u}export{f as LAST_MAINTENANCE_KEY,S as claimMaintenanceSlot,O as lastMaintenanceAt,d as maybeRunMaintenance,U as scheduleMaintenanceSweep};
@@ -1,5 +1,11 @@
1
- import{randomUUID as f}from"node:crypto";const m=process.env.WYRM_SESSION_KEY??f(),_=[{re:/\b(mem|memory)[ \t]*[:#][ \t]*(\d{1,7})\b/gi,kind:"mem"},{re:/\btruth[ \t]*[:#][ \t]*(\d{1,7})\b/gi,kind:"truth"},{re:/\bquest[ \t]*[:#][ \t]*(\d{1,7})\b/gi,kind:"quest"},{re:/\bfailure[ \t]*[:#][ \t]*(\d{1,7})\b/gi,kind:"failure"}],E=/\(ID:[ \t]*(\d{1,7})\)/gi;function h(i){const t=new Map;if(!i)return[];for(const{re:r,kind:e}of _)if(e)for(const s of i.matchAll(r)){const d=s[2]??s[1],n=Number(d);Number.isFinite(n)&&n>0&&t.set(`${e}:${n}`,{id:n,kind:e})}for(const r of i.matchAll(E)){const e=Number(r[1]);if(!(!Number.isFinite(e)||e<=0))for(const s of["mem","truth","quest","failure"])t.set(`${s}:${e}`,{id:e,kind:s})}return[...t.values()]}let a=null;function l(i,t){try{a||(a=new k(i)),a.recordFromText(m,t)}catch{}}class k{db;constructor(t){this.db=t}record(t,r){if(!r.length)return;const e=this.db.prepare(`
1
+ import{randomUUID as f}from"node:crypto";const _=process.env.WYRM_SESSION_KEY??f(),E=[{re:/\b(mem|memory)[ \t]*[:#][ \t]*(\d{1,7})\b/gi,kind:"mem"},{re:/\btruth[ \t]*[:#][ \t]*(\d{1,7})\b/gi,kind:"truth"},{re:/\bquest[ \t]*[:#][ \t]*(\d{1,7})\b/gi,kind:"quest"},{re:/\bfailure[ \t]*[:#][ \t]*(\d{1,7})\b/gi,kind:"failure"}],m=/\(ID:[ \t]*(\d{1,7})\)/gi;function h(d){const t=new Map;if(!d)return[];for(const{re:r,kind:e}of E)if(e)for(const s of d.matchAll(r)){const c=s[2]??s[1],n=Number(c);Number.isFinite(n)&&n>0&&t.set(`${e}:${n}`,{id:n,kind:e})}for(const r of d.matchAll(m)){const e=Number(r[1]);if(!(!Number.isFinite(e)||e<=0))for(const s of["mem","truth","quest","failure"])t.set(`${s}:${e}`,{id:e,kind:s})}return[...t.values()]}let u=null;function S(d,t){try{u||(u=new k(d)),u.recordFromText(_,t)}catch{}}class k{db;constructor(t){this.db=t}record(t,r){if(!r.length)return;const e=this.db.prepare(`
2
2
  INSERT INTO served_records (session_key, artifact_id, artifact_kind)
3
3
  VALUES (?, ?, ?)
4
4
  ON CONFLICT(session_key, artifact_id, artifact_kind) DO NOTHING
5
- `);this.db.transaction(d=>{for(const n of d)e.run(t,n.id,n.kind)})(r)}recordFromText(t,r){const e=h(r);return this.record(t,e),e.length}attest(t,r){const e=this.db.prepare("SELECT artifact_id, artifact_kind FROM served_records WHERE session_key = ?").all(t),s=new Set(e.map(o=>`${o.artifact_kind}:${o.artifact_id}`)),d=[],n=[],u=new Set;for(const o of r){const c=`${o.kind}:${o.id}`;u.has(c)||(u.add(c),(s.has(c)?d:n).push({id:o.id,kind:o.kind}))}return{served:d,unserved:n,ok:n.length===0}}countFor(t){return this.db.prepare("SELECT COUNT(*) AS n FROM served_records WHERE session_key = ?").get(t).n}prune(t=7){return this.db.prepare("DELETE FROM served_records WHERE served_at < datetime('now', ? || ' days')").run(`-${t}`).changes??0}}export{m as SESSION_KEY,k as ServedRecords,h as extractRefs,l as recordServed};
5
+ `),s=this.servedCountStatement();this.db.transaction(n=>{for(const o of n){const i=e.run(t,o.id,o.kind);s&&i.changes>0&&s.run(o.kind,o.id)}})(r)}servedCountStatement(){try{return this.db.prepare(`
6
+ INSERT INTO served_counts (artifact_kind, artifact_id, served_sessions)
7
+ VALUES (?, ?, 1)
8
+ ON CONFLICT(artifact_kind, artifact_id) DO UPDATE SET
9
+ served_sessions = served_sessions + 1,
10
+ last_served_at = datetime('now')
11
+ `)}catch{return null}}servedCount(t,r){try{return this.db.prepare("SELECT served_sessions AS n FROM served_counts WHERE artifact_kind = ? AND artifact_id = ?").get(t,r)?.n??0}catch{return 0}}recordFromText(t,r){const e=h(r);return this.record(t,e),e.length}attest(t,r){const e=this.db.prepare("SELECT artifact_id, artifact_kind FROM served_records WHERE session_key = ?").all(t),s=new Set(e.map(i=>`${i.artifact_kind}:${i.artifact_id}`)),c=[],n=[],o=new Set;for(const i of r){const a=`${i.kind}:${i.id}`;o.has(a)||(o.add(a),(s.has(a)?c:n).push({id:i.id,kind:i.kind}))}return{served:c,unserved:n,ok:n.length===0}}countFor(t){return this.db.prepare("SELECT COUNT(*) AS n FROM served_records WHERE session_key = ?").get(t).n}prune(t=7){return this.db.prepare("DELETE FROM served_records WHERE served_at < datetime('now', ? || ' days')").run(`-${t}`).changes??0}}export{_ as SESSION_KEY,k as ServedRecords,h as extractRefs,S as recordServed};
@@ -1,4 +1,4 @@
1
- import{c as r,icons as E}from"./cli.js";import{detectClients as I,autoConfigureAll as q,findWyrmServerPath as T,getDefaultDbPath as R}from"./autoconfig.js";const H=[[1,8],[2,16],[4,32],[64,128]],v=[[20,24,30],[70,90,110],[150,170,190],[235,245,255]];function O(o,e){o=o<0?0:o>1?1:o;const i=e.length-1,t=o*i,s=Math.min(t|0,i-1),n=e[s],c=e[s+1],a=t-s;return[n[0]+(c[0]-n[0])*a|0,n[1]+(c[1]-n[1])*a|0,n[2]+(c[2]-n[2])*a|0]}class k{cols;rows;W;H;bits;col;lum;constructor(e,i){this.cols=e,this.rows=i,this.W=e*2,this.H=i*4,this.bits=new Uint8Array(e*i),this.col=new Array(e*i).fill(null),this.lum=new Float32Array(e*i).fill(-1)}clear(){this.bits.fill(0),this.col.fill(null),this.lum.fill(-1)}set(e,i,t,s){if(e|=0,i|=0,e<0||e>=this.W||i<0||i>=this.H)return;const n=(i>>2)*this.cols+(e>>1);this.bits[n]|=H[i&3][e&1],s>this.lum[n]&&(this.lum[n]=s,this.col[n]=t)}ripples(e){this.clear();const i=[[this.W*(.5+.34*Math.sin(e*.7)),this.H*(.5+.34*Math.cos(e*.9))],[this.W*(.5+.4*Math.cos(e*.5)),this.H*(.5+.4*Math.sin(e*1.1))]];for(let t=0;t<this.H;t++)for(let s=0;s<this.W;s++){let n=0;for(const c of i)n+=Math.sin(Math.hypot(s-c[0],t-c[1])*.3-e*3);n/=i.length,n>.5&&this.set(s,t,O((n-.5)/.5,v),n)}}render(e){const i=[];for(let t=0;t<this.rows;t++){let s="";for(let n=0;n<this.cols;n++){const c=t*this.cols+n,a=this.bits[c];if(!a){s+=" ";continue}const f=String.fromCodePoint(10240+a),l=this.col[c]??v[2];s+=e?`\x1B[38;2;${l[0]};${l[1]};${l[2]}m${f}\x1B[0m`:r.dim(f)}i.push(s)}return i}}const M="W Y R M";function W(o,e){const i=Math.min(o.cols-4,72),t=new k(i,5);t.ripples(o.frame*.09);const s=t.render(o.truecolor),n=" ".repeat(Math.max(0,o.cols-i>>1)),c=e==="success"?r.green:r.cyan;return s.map((f,l)=>n+(l===2?C(f,c(r.bold(M)),i,n):f))}function C(o,e,i,t){const s=M.length,n=Math.max(0,i-s>>1);return" ".repeat(n)+e}function d(o,e){const i=z(o).length;return" ".repeat(Math.max(0,e-i>>1))+o}function z(o){return o.replace(/\x1b\[[0-9;]*m/g,"")}const p=o=>r.dim(o);function L(o,e){const i=[""],t=(s="")=>i.push(s);if(o.step==="welcome")W(e,"silver").forEach(s=>t(s)),t(),t(d(r.bold("Wyrm \u2014 memory for your AI"),e.cols)),t(d(r.dim("It remembers your projects so your assistant stops starting from zero."),e.cols)),t(),t(d(p("press Enter to begin \xB7 q to quit"),e.cols));else if(o.step==="about")t(),t(" "+r.bold("What this does")),t(),t(" "+r.dim("\u2022")+" Wyrm is a private memory that lives on "+r.cyan("this computer")+"."),t(" "+r.dim("\u2022")+" Your AI tools read it, so they recall past work, decisions,"),t(" and what already did not work \u2014 across every new chat."),t(" "+r.dim("\u2022")+" Nothing is sent anywhere unless you turn on cloud sync yourself."),t(),t(" Next, Wyrm will look for AI apps you already have and connect them."),t(),t(" "+p("Enter continue \xB7 b back \xB7 q quit"));else if(o.step==="confirm"){t(),t(" "+r.bold("Found these on your computer")),t();const s=o.clients.filter(n=>n.detected);if(s.length===0)t(" "+r.yellow("\u25D0")+" No AI apps detected yet. You can install one and run this again.");else for(const n of s){const c=n.configured?r.success("\u25CF already connected"):r.cyan("\u25D0 will connect");t(` ${n.icon} ${r.bold(D(n.name,18))} ${c}`)}t(),t(" "+r.dim("Wyrm server: ")+r.cyan(P(o.serverPath))),t(" "+r.dim("Memory file: ")+r.cyan(P(o.dbPath))),t(),t(" "+(s.length?p("Enter connect them \xB7 b back \xB7 q quit"):p("Enter finish \xB7 q quit")))}else if(o.step==="working"){t(),t(" "+r.bold("Connecting\u2026")),t();const s="\xB7\u2022\u25CF\u2022"[e.frame%4];t(" "+r.cyan(s)+" "+r.dim("writing each app's config (a backup is saved first)"))}else if(o.step==="done"){W(e,"success").forEach(n=>t(n)),t();const s=(o.results??[]).filter(n=>n.action==="configured"||n.action==="updated");t(d(r.success(`${E.dragon} Wyrm connected to ${s.length} app${s.length===1?"":"s"}`),e.cols));for(const n of s)t(d(r.dim(`${n.client.icon} ${n.client.name}`),e.cols));t(),t(d(r.dim("Open your AI app and it will remember. That's it."),e.cols)),t(),t(d(p("press Enter or q to close"),e.cols))}for(;i.length<e.rows-1;)t();return t(r.dim(" \u2500".padEnd(Math.min(e.cols,40),"\u2500"))),i.join(`
1
+ import{c as r,icons as E}from"./cli.js";import{detectClients as I,autoConfigureAll as q,findWyrmServerPath as T,getDefaultDbPath as R}from"./autoconfig.js";const H=[[1,8],[2,16],[4,32],[64,128]],v=[[20,24,30],[70,90,110],[150,170,190],[235,245,255]];function O(o,e){o=o<0?0:o>1?1:o;const i=e.length-1,t=o*i,s=Math.min(t|0,i-1),n=e[s],c=e[s+1],a=t-s;return[n[0]+(c[0]-n[0])*a|0,n[1]+(c[1]-n[1])*a|0,n[2]+(c[2]-n[2])*a|0]}class k{cols;rows;W;H;bits;col;lum;constructor(e,i){this.cols=e,this.rows=i,this.W=e*2,this.H=i*4,this.bits=new Uint8Array(e*i),this.col=new Array(e*i).fill(null),this.lum=new Float32Array(e*i).fill(-1)}clear(){this.bits.fill(0),this.col.fill(null),this.lum.fill(-1)}set(e,i,t,s){if(e|=0,i|=0,e<0||e>=this.W||i<0||i>=this.H)return;const n=(i>>2)*this.cols+(e>>1);this.bits[n]|=H[i&3][e&1],s>this.lum[n]&&(this.lum[n]=s,this.col[n]=t)}ripples(e){this.clear();const i=[[this.W*(.5+.34*Math.sin(e*.7)),this.H*(.5+.34*Math.cos(e*.9))],[this.W*(.5+.4*Math.cos(e*.5)),this.H*(.5+.4*Math.sin(e*1.1))]];for(let t=0;t<this.H;t++)for(let s=0;s<this.W;s++){let n=0;for(const c of i)n+=Math.sin(Math.hypot(s-c[0],t-c[1])*.3-e*3);n/=i.length,n>.5&&this.set(s,t,O((n-.5)/.5,v),n)}}render(e){const i=[];for(let t=0;t<this.rows;t++){let s="";for(let n=0;n<this.cols;n++){const c=t*this.cols+n,a=this.bits[c];if(!a){s+=" ";continue}const f=String.fromCodePoint(10240+a),l=this.col[c]??v[2];s+=e?`\x1B[38;2;${l[0]};${l[1]};${l[2]}m${f}\x1B[0m`:r.dim(f)}i.push(s)}return i}}const M="W Y R M";function W(o,e){const i=Math.min(o.cols-4,72),t=new k(i,5);t.ripples(o.frame*.09);const s=t.render(o.truecolor),n=" ".repeat(Math.max(0,o.cols-i>>1)),c=e==="success"?r.green:r.cyan;return s.map((f,l)=>n+(l===2?C(f,c(r.bold(M)),i,n):f))}function C(o,e,i,t){const s=M.length,n=Math.max(0,i-s>>1);return" ".repeat(n)+e}function d(o,e){const i=z(o).length;return" ".repeat(Math.max(0,e-i>>1))+o}function z(o){return o.replace(/\x1b\[[0-9;]*m/g,"")}const p=o=>r.dim(o);function L(o,e){const i=[""],t=(s="")=>i.push(s);if(o.step==="welcome")W(e,"silver").forEach(s=>t(s)),t(),t(d(r.bold("Wyrm: memory for your AI"),e.cols)),t(d(r.dim("It remembers your projects so your assistant stops starting from zero."),e.cols)),t(),t(d(p("press Enter to begin \xB7 q to quit"),e.cols));else if(o.step==="about")t(),t(" "+r.bold("What this does")),t(),t(" "+r.dim("\u2022")+" Wyrm is a private memory that lives on "+r.cyan("this computer")+"."),t(" "+r.dim("\u2022")+" Your AI tools read it, so they recall past work, decisions,"),t(" and what already did not work, across every new chat."),t(" "+r.dim("\u2022")+" Nothing is sent anywhere unless you turn on cloud sync yourself."),t(),t(" Next, Wyrm will look for AI apps you already have and connect them."),t(),t(" "+p("Enter continue \xB7 b back \xB7 q quit"));else if(o.step==="confirm"){t(),t(" "+r.bold("Found these on your computer")),t();const s=o.clients.filter(n=>n.detected);if(s.length===0)t(" "+r.yellow("\u25D0")+" No AI apps detected yet. You can install one and run this again.");else for(const n of s){const c=n.configured?r.success("\u25CF already connected"):r.cyan("\u25D0 will connect");t(` ${n.icon} ${r.bold(D(n.name,18))} ${c}`)}t(),t(" "+r.dim("Wyrm server: ")+r.cyan(P(o.serverPath))),t(" "+r.dim("Memory file: ")+r.cyan(P(o.dbPath))),t(),t(" "+(s.length?p("Enter connect them \xB7 b back \xB7 q quit"):p("Enter finish \xB7 q quit")))}else if(o.step==="working"){t(),t(" "+r.bold("Connecting\u2026")),t();const s="\xB7\u2022\u25CF\u2022"[e.frame%4];t(" "+r.cyan(s)+" "+r.dim("writing each app's config (a backup is saved first)"))}else if(o.step==="done"){W(e,"success").forEach(n=>t(n)),t();const s=(o.results??[]).filter(n=>n.action==="configured"||n.action==="updated");t(d(r.success(`${E.dragon} Wyrm connected to ${s.length} app${s.length===1?"":"s"}`),e.cols));for(const n of s)t(d(r.dim(`${n.client.icon} ${n.client.name}`),e.cols));t(),t(d(r.dim("Open your AI app and it will remember. That's it."),e.cols)),t(),t(d(p("press Enter or q to close"),e.cols))}for(;i.length<e.rows-1;)t();return t(r.dim(" \u2500".padEnd(Math.min(e.cols,40),"\u2500"))),i.join(`
2
2
  `)}function D(o,e){return o.length>=e?o.slice(0,e):o+" ".repeat(e-o.length)}function P(o){const e=process.env.HOME??"";return e&&o.startsWith(e)?"~"+o.slice(e.length):o}const F="\x1B[?1049h\x1B[?25l",N="\x1B[?25h\x1B[?1049l";async function _(o={}){const e=process.stdout,i=process.stdin;if(!e.isTTY||!i.isTTY)return!1;const t=/^(truecolor|24bit)$/i.test(process.env.COLORTERM??""),s={step:"welcome",clients:I(),results:null,serverPath:o.serverPath||T(),dbPath:o.dbPath||R()};let n=0,c=!0,a=!0;const f=()=>({cols:e.columns||80,rows:e.rows||24}),l=()=>{const{cols:y,rows:m}=f(),u=L(s,{cols:y,rows:m,frame:n,truecolor:t});e.write("\x1B[?2026h\x1B[H"+u.split(`
3
3
  `).map(g=>g+"\x1B[K").join(`
4
4
  `)+"\x1B[J\x1B[?2026l")},w=()=>{if(c){c=!1;try{i.setRawMode?.(!1)}catch{}i.pause(),e.write(N)}};process.once("exit",w),e.write(F);try{i.setRawMode?.(!0)}catch{}i.resume(),i.setEncoding("utf8");const A=setInterval(()=>{a&&(n++,l())},90),x=()=>l();e.on("resize",x);const $=()=>{clearInterval(A),e.off("resize",x),w()};return await new Promise(y=>{const m=()=>{$(),y(s.results)},u=()=>{a=s.step==="welcome"||s.step==="done"},g=async h=>{if(h===""||h==="q"||h==="\x1B"){m();return}const b=h==="\r"||h===`
package/dist/setup.js CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import{existsSync as $,readFileSync as x}from"node:fs";import{BUNDLED_MODEL_SIZE_LABEL as R}from"./providers/bundled-model.js";import{homedir as y}from"node:os";import{join as S}from"node:path";import{detectClients as C,autoConfigureAll as M,removeFromAll as D,configureSpecific as L,reconfAll as N,getStatusSummary as W,findWyrmServerPath as _,getDefaultDbPath as A,loadWyrmMeta as B,exportServerConfig as j}from"./autoconfig.js";import{c as o,icons as g,BANNER as z,MINI_BANNER as f,printSuccess as O,printError as E,printWarning as T,printSection as d,createDownloadProgress as F}from"./cli.js";import{runWizard as U}from"./setup-wizard.js";function Y(n){const e=n.slice(2);if(e.length===0)return{command:"auto"};const s={command:"auto"};for(let l=0;l<e.length;l++)switch(e[l]){case"--check":case"-c":case"check":case"status":s.command="check";break;case"--remove":case"-r":case"remove":case"uninstall":s.command="remove";break;case"--only":case"-o":case"only":s.command="only",e[l+1]&&(s.clientIds=e[l+1].split(",").map(t=>t.trim()),l++);break;case"--reconf":case"--reconfigure":case"reconf":s.command="reconf";break;case"--list":case"-l":case"list":s.command="list";break;case"--export":case"export":{s.command="export";const t=e[l+1];(t==="stdio"||t==="vscode"||t==="mcp-json")&&(s.exportFormat=t,l++);break}case"--server":case"-s":e[l+1]&&(s.serverPath=e[l+1],l++);break;case"--db":case"-d":e[l+1]&&(s.dbPath=e[l+1],l++);break;case"--wizard":case"wizard":s.command="wizard";break;case"--no-wizard":case"--plain":s.noWizard=!0;break;case"--no-model":s.noModel=!0;break;case"--help":case"-h":case"help":s.command="help";break}return s}function w(n){console.log("");const e=n.filter(c=>c.action==="configured"),s=n.filter(c=>c.action==="updated"),l=n.filter(c=>c.action==="skipped"),t=n.filter(c=>c.action==="failed");for(const c of e)console.log(` ${g.success} ${c.client.icon} ${o.green(c.client.name)} \u2014 ${o.success("configured")}`),c.backup&&console.log(` ${o.dim(`backup \u2192 ${c.backup}`)}`);for(const c of s)console.log(` ${g.sync} ${c.client.icon} ${o.blue(c.client.name)} \u2014 ${o.cyan("updated")}`),c.backup&&console.log(` ${o.dim(`backup \u2192 ${c.backup}`)}`);for(const c of l)console.log(` ${o.dim(` \u25CB ${c.client.icon} ${c.client.name} \u2014 ${c.message}`)}`);for(const c of t)console.log(` ${g.error} ${c.client.icon} ${o.red(c.client.name)} \u2014 ${o.error(c.message)}`);console.log("");const p=[...e,...s].filter(c=>!c.client.id.startsWith("claude-code-")).length;p>0?(console.log(` ${o.success(`${g.dragon} Wyrm connected to ${p} AI client(s)`)}`),console.log(` ${o.dim("Switch AIs anytime \u2014 run wyrm-setup again to reconnect")}`)):t.length>0?console.log(` ${o.error("Some configurations failed. Check errors above.")}`):console.log(` ${o.dim("No AI clients detected. Install one and try again.")}`),console.log("")}function Z(n){return n.split(y()).join("~")}async function b(n,e){const{bundledModelPresent:s,downloadBundledModel:l,BUNDLED_MODEL_SIZE_LABEL:t}=await import("./providers/bundled-model.js"),{resolveEmbeddingState:p,tierForResolution:c}=await import("./providers/embedding-provider.js");if(d("Enabling meaning-based search"),s())console.log(o.dim(" Local embedding model already present."));else if(n)console.log(o.dim(" Skipped (--no-model). Recall is keyword-only until: wyrm vectors download"));else{console.log(o.dim(` Downloading nomic-embed-text-v1.5 (${t}, Apache-2.0, from huggingface.co with models.ghosts.lk as fallback). Skip with --no-model.`));const r=F(process.stdout),P=await l({onProgress:r.onProgress});if(r.finish(),P.ok){O(`Meaning-based search is on (${t}, local, no account).`);const{runBundledBackfill:I}=await import("./reindex.js");await I()}else T(`Could not download the model (${P.error}).`),console.log(o.dim(" Keyword search works fine meanwhile. Retry later: wyrm vectors download"))}d("Health check");const u=p(),i=c(u);console.log(` ${u.resolved!=="none"?"\u2714":"\u25CB"} search: ${i.label} (${u.resolved}${u.model?` \xB7 ${u.model}`:""})`);const k=A();console.log($(k)?` \u2714 memory file: ${Z(k)}`:" \u25CB memory file: created on first run");const a=e.find(r=>r.client.id==="claude-code-hooks");let m;if(a&&(a.action==="configured"||a.action==="updated"))m=!0,console.log(` \u2714 auto-memory hooks: ${a.action==="updated"?"updated":"installed"}`);else if(a&&a.action==="skipped"&&a.client.configured)m=!0,console.log(` \u2714 auto-memory hooks: ${a.message}`);else if(a)m=!1,console.log(` \u25CB auto-memory hooks: ${a.message}`);else{const r=S(y(),".claude","hooks","wyrm-session-capture.mjs");m=$(r),console.log(m?" \u2714 auto-memory hooks: already installed":" \u25CB auto-memory hooks: not installed by this command")}const v=e.find(r=>r.client.id==="claude-code-guard");let h;if(v)h=v.client.configured===!0;else{const r=S(y(),".claude","settings.json");try{h=$(r)&&/wyrm-guard/.test(x(r,"utf-8"))}catch{h=!1}}d("What happens automatically now"),console.log(m?" \u2022 Every session is captured to memory when it ends.":" \u2022 On this client, the model handles capture per server instructions."),console.log(m?" \u2022 Every new session starts with your context restored.":" \u2022 Each session starts by priming from memory (the model calls wyrm_session_prime first)."),console.log(h?" \u2022 The failure firewall blocks repeats of recorded mistakes. Always on.":" \u2022 The failure firewall arms once hooks are installed."),console.log(" \u2022 The store prunes and re-ranks itself daily. No cron, no timer to write."),console.log(" \u2022 The token firewall notes files you read in full twice; wyrm doctor shows what it found."),console.log(` \u2022 Something off? ${o.cyan("wyrm doctor")} fails loudly with the exact fix; ${o.cyan("wyrm report")} is the shareable diagnostic.`),console.log(""),console.log(i.n>=3?`Search: tier ${i.n}/3 (${i.label}).`:i.n===2?`Search: tier ${i.n}/3 (${i.label}). ${o.cyan("wyrm upgrade")} \u2192 max recall.`:`Search: tier ${i.n}/3 (${i.label}). ${o.cyan("wyrm vectors download")} \u2192 local vectors (free, no account); then ${o.cyan("wyrm upgrade")} \u2192 max recall.`)}function H(){console.log(f()),console.log(""),console.log(`${o.bold("Usage:")} wyrm-setup ${o.dim("[command] [options]")}`),console.log(""),console.log(`${o.bold("Commands:")}`),console.log(` ${o.cyan("(no args)")} Auto-detect and configure all AI clients`),console.log(` ${o.cyan("check")} Show current configuration status`),console.log(` ${o.cyan("list")} List all supported AI clients`),console.log(` ${o.cyan("remove")} Remove Wyrm from all AI clients`),console.log(` ${o.cyan("reconf")} Re-configure previously configured clients`),console.log(` ${o.cyan("only X,Y")} Configure specific clients only`),console.log(` ${o.cyan("export [fmt]")} Print a portable config (fmt: mcp-json|vscode|stdio) for any MCP host`),console.log(` ${o.cyan("help")} Show this help message`),console.log(""),console.log(`${o.bold("Options:")}`),console.log(` ${o.cyan("--server P")} Override Wyrm MCP server path`),console.log(` ${o.cyan("--db P")} Override Wyrm database path`),console.log(` ${o.cyan("--no-model")} Skip the one-time local embedding model download (${R}); recall stays keyword-only`),console.log(` ${o.cyan("--plain")} Non-interactive flag flow (no wizard) \u2014 the default when not on a TTY`),console.log(""),console.log(`${o.bold("Client IDs:")}`);const n=C();for(const e of n)console.log(` ${e.icon} ${o.cyan(e.id.padEnd(18))} ${e.name}`);console.log(""),console.log(`${o.bold("Examples:")}`),console.log(` wyrm-setup ${o.dim("# Auto-configure everything")}`),console.log(` wyrm-setup check ${o.dim("# See what's configured")}`),console.log(` wyrm-setup only vscode-copilot,cursor ${o.dim("# Only VS Code + Cursor")}`),console.log(` wyrm-setup --server /path/to/wyrm/dist/index.js ${o.dim("# Custom server path")}`),console.log(` wyrm-setup remove ${o.dim("# Remove from all clients")}`),console.log(` wyrm-setup export stdio > wyrm.json ${o.dim("# Portable config for any MCP host")}`),console.log("")}function J(){console.log(f()),console.log(""),d("Supported AI Clients"),console.log("");const n=C();for(const e of n){const s=e.detected?e.configured?o.success("\u25CF connected"):o.yellow("\u25D0 available"):o.dim("\u25CB not found"),l=e.version?` ${o.dim(`v${e.version}`)}`:"";console.log(` ${e.icon} ${o.bold(e.name.padEnd(20))} ${o.cyan(e.id.padEnd(18))} ${s}${l}`),console.log(` ${o.dim(`Config: ${e.configPath}`)}`)}console.log("")}async function K(){const n=Y(process.argv);if(n.command==="wizard"||n.command==="auto"&&!n.noWizard){const e=await U({serverPath:n.serverPath,dbPath:n.dbPath});if(e===!1)n.command==="wizard"&&(n.command="auto");else if(e===null){console.log(o.dim("Setup aborted, nothing changed."));return}else{await b(n.noModel??!1,e);return}}switch(n.command){case"help":H();break;case"check":{console.log(f()),console.log(""),console.log(W());break}case"list":J();break;case"auto":{console.log(z()),d("Auto-Configure"),console.log("");const e=n.serverPath||_(),s=n.dbPath||A();console.log(` ${g.sword} Server: ${o.cyan(e)}`),console.log(` ${g.treasure} DB: ${o.cyan(s)}`),console.log(""),console.log(` ${o.dim("Scanning for AI clients...")}`);const l=M({serverPath:e,dbPath:s});w(l),await b(n.noModel??!1,l);break}case"only":{(!n.clientIds||n.clientIds.length===0)&&(E("No client IDs specified. Use: wyrm-setup only vscode-copilot,cursor"),process.exit(1)),console.log(f()),d(`Configure: ${n.clientIds.join(", ")}`);const e=L(n.clientIds,{serverPath:n.serverPath,dbPath:n.dbPath});w(e),await b(n.noModel??!1,e);break}case"remove":{console.log(f()),d("Remove Wyrm from AI Clients"),console.log(""),console.log(` ${o.warning("Removing Wyrm configuration from all AI clients...")}`);const e=D(),s=e.filter(t=>t.action==="configured"),l=e.filter(t=>t.action==="skipped");for(const t of s)console.log(` ${g.check} ${t.client.icon} ${t.client.name} \u2014 removed`),t.backup&&console.log(` ${o.dim(`backup \u2192 ${t.backup}`)}`);for(const t of l)console.log(` ${o.dim(` \u25CB ${t.client.icon} ${t.client.name} \u2014 ${t.message}`)}`);console.log(""),s.length>0&&console.log(` ${o.success(`Removed from ${s.length} client(s). Run wyrm-setup to reconnect.`)}`),console.log("");break}case"reconf":{console.log(f()),d("Re-Configure");const e=B();console.log(e?` ${o.dim(`Restoring config for: ${e.configuredClients.join(", ")}`)}`:` ${o.dim("No previous config found \u2014 running full auto-configure")}`);const s=N();w(s);break}case"export":{const e=n.exportFormat??"mcp-json",s=j(e,{serverPath:n.serverPath,dbPath:n.dbPath});process.stderr.write(`${o.dim(`# Wyrm MCP config (${e}). Paste into any MCP-compatible host.`)}
2
+ import{existsSync as $,readFileSync as x}from"node:fs";import{BUNDLED_MODEL_SIZE_LABEL as R}from"./providers/bundled-model.js";import{homedir as y}from"node:os";import{join as S}from"node:path";import{detectClients as C,autoConfigureAll as M,removeFromAll as D,configureSpecific as L,reconfAll as N,getStatusSummary as W,findWyrmServerPath as _,getDefaultDbPath as A,loadWyrmMeta as B,exportServerConfig as j}from"./autoconfig.js";import{c as o,icons as g,BANNER as z,MINI_BANNER as f,printSuccess as O,printError as E,printWarning as T,printSection as d,createDownloadProgress as F}from"./cli.js";import{runWizard as U}from"./setup-wizard.js";function Y(n){const e=n.slice(2);if(e.length===0)return{command:"auto"};const s={command:"auto"};for(let l=0;l<e.length;l++)switch(e[l]){case"--check":case"-c":case"check":case"status":s.command="check";break;case"--remove":case"-r":case"remove":case"uninstall":s.command="remove";break;case"--only":case"-o":case"only":s.command="only",e[l+1]&&(s.clientIds=e[l+1].split(",").map(t=>t.trim()),l++);break;case"--reconf":case"--reconfigure":case"reconf":s.command="reconf";break;case"--list":case"-l":case"list":s.command="list";break;case"--export":case"export":{s.command="export";const t=e[l+1];(t==="stdio"||t==="vscode"||t==="mcp-json")&&(s.exportFormat=t,l++);break}case"--server":case"-s":e[l+1]&&(s.serverPath=e[l+1],l++);break;case"--db":case"-d":e[l+1]&&(s.dbPath=e[l+1],l++);break;case"--wizard":case"wizard":s.command="wizard";break;case"--no-wizard":case"--plain":s.noWizard=!0;break;case"--no-model":s.noModel=!0;break;case"--help":case"-h":case"help":s.command="help";break}return s}function w(n){console.log("");const e=n.filter(c=>c.action==="configured"),s=n.filter(c=>c.action==="updated"),l=n.filter(c=>c.action==="skipped"),t=n.filter(c=>c.action==="failed");for(const c of e)console.log(` ${g.success} ${c.client.icon} ${o.green(c.client.name)}: ${o.success("configured")}`),c.backup&&console.log(` ${o.dim(`backup \u2192 ${c.backup}`)}`);for(const c of s)console.log(` ${g.sync} ${c.client.icon} ${o.blue(c.client.name)}: ${o.cyan("updated")}`),c.backup&&console.log(` ${o.dim(`backup \u2192 ${c.backup}`)}`);for(const c of l)console.log(` ${o.dim(` \u25CB ${c.client.icon} ${c.client.name}: ${c.message}`)}`);for(const c of t)console.log(` ${g.error} ${c.client.icon} ${o.red(c.client.name)}: ${o.error(c.message)}`);console.log("");const p=[...e,...s].filter(c=>!c.client.id.startsWith("claude-code-")).length;p>0?(console.log(` ${o.success(`${g.dragon} Wyrm connected to ${p} AI client(s)`)}`),console.log(` ${o.dim("Switch AIs anytime: run wyrm-setup again to reconnect")}`)):t.length>0?console.log(` ${o.error("Some configurations failed. Check errors above.")}`):console.log(` ${o.dim("No AI clients detected. Install one and try again.")}`),console.log("")}function Z(n){return n.split(y()).join("~")}async function b(n,e){const{bundledModelPresent:s,downloadBundledModel:l,BUNDLED_MODEL_SIZE_LABEL:t}=await import("./providers/bundled-model.js"),{resolveEmbeddingState:p,tierForResolution:c}=await import("./providers/embedding-provider.js");if(d("Enabling meaning-based search"),s())console.log(o.dim(" Local embedding model already present."));else if(n)console.log(o.dim(" Skipped (--no-model). Recall is keyword-only until: wyrm vectors download"));else{console.log(o.dim(` Downloading nomic-embed-text-v1.5 (${t}, Apache-2.0, from huggingface.co with models.ghosts.lk as fallback). Skip with --no-model.`));const r=F(process.stdout),P=await l({onProgress:r.onProgress});if(r.finish(),P.ok){O(`Meaning-based search is on (${t}, local, no account).`);const{runBundledBackfill:I}=await import("./reindex.js");await I()}else T(`Could not download the model (${P.error}).`),console.log(o.dim(" Keyword search works fine meanwhile. Retry later: wyrm vectors download"))}d("Health check");const u=p(),i=c(u);console.log(` ${u.resolved!=="none"?"\u2714":"\u25CB"} search: ${i.label} (${u.resolved}${u.model?` \xB7 ${u.model}`:""})`);const k=A();console.log($(k)?` \u2714 memory file: ${Z(k)}`:" \u25CB memory file: created on first run");const a=e.find(r=>r.client.id==="claude-code-hooks");let m;if(a&&(a.action==="configured"||a.action==="updated"))m=!0,console.log(` \u2714 auto-memory hooks: ${a.action==="updated"?"updated":"installed"}`);else if(a&&a.action==="skipped"&&a.client.configured)m=!0,console.log(` \u2714 auto-memory hooks: ${a.message}`);else if(a)m=!1,console.log(` \u25CB auto-memory hooks: ${a.message}`);else{const r=S(y(),".claude","hooks","wyrm-session-capture.mjs");m=$(r),console.log(m?" \u2714 auto-memory hooks: already installed":" \u25CB auto-memory hooks: not installed by this command")}const v=e.find(r=>r.client.id==="claude-code-guard");let h;if(v)h=v.client.configured===!0;else{const r=S(y(),".claude","settings.json");try{h=$(r)&&/wyrm-guard/.test(x(r,"utf-8"))}catch{h=!1}}d("What happens automatically now"),console.log(m?" \u2022 Every session is captured to memory when it ends.":" \u2022 On this client, the model handles capture per server instructions."),console.log(m?" \u2022 Every new session starts with your context restored.":" \u2022 Each session starts by priming from memory (the model calls wyrm_session_prime first)."),console.log(h?" \u2022 The failure firewall blocks repeats of recorded mistakes. Always on.":" \u2022 The failure firewall arms once hooks are installed."),console.log(" \u2022 The store prunes and re-ranks itself daily. No cron, no timer to write."),console.log(" \u2022 The token firewall notes files you read in full twice; wyrm doctor shows what it found."),console.log(` \u2022 Something off? ${o.cyan("wyrm doctor")} fails loudly with the exact fix; ${o.cyan("wyrm report")} is the shareable diagnostic.`),console.log(""),console.log(i.n>=3?`Search: tier ${i.n}/3 (${i.label}).`:i.n===2?`Search: tier ${i.n}/3 (${i.label}). ${o.cyan("wyrm upgrade")} \u2192 max recall.`:`Search: tier ${i.n}/3 (${i.label}). ${o.cyan("wyrm vectors download")} \u2192 local vectors (free, no account); then ${o.cyan("wyrm upgrade")} \u2192 max recall.`)}function H(){console.log(f()),console.log(""),console.log(`${o.bold("Usage:")} wyrm-setup ${o.dim("[command] [options]")}`),console.log(""),console.log(`${o.bold("Commands:")}`),console.log(` ${o.cyan("(no args)")} Auto-detect and configure all AI clients`),console.log(` ${o.cyan("check")} Show current configuration status`),console.log(` ${o.cyan("list")} List all supported AI clients`),console.log(` ${o.cyan("remove")} Remove Wyrm from all AI clients`),console.log(` ${o.cyan("reconf")} Re-configure previously configured clients`),console.log(` ${o.cyan("only X,Y")} Configure specific clients only`),console.log(` ${o.cyan("export [fmt]")} Print a portable config (fmt: mcp-json|vscode|stdio) for any MCP host`),console.log(` ${o.cyan("help")} Show this help message`),console.log(""),console.log(`${o.bold("Options:")}`),console.log(` ${o.cyan("--server P")} Override Wyrm MCP server path`),console.log(` ${o.cyan("--db P")} Override Wyrm database path`),console.log(` ${o.cyan("--no-model")} Skip the one-time local embedding model download (${R}); recall stays keyword-only`),console.log(` ${o.cyan("--plain")} Non-interactive flag flow (no wizard), the default when not on a TTY`),console.log(""),console.log(`${o.bold("Client IDs:")}`);const n=C();for(const e of n)console.log(` ${e.icon} ${o.cyan(e.id.padEnd(18))} ${e.name}`);console.log(""),console.log(`${o.bold("Examples:")}`),console.log(` wyrm-setup ${o.dim("# Auto-configure everything")}`),console.log(` wyrm-setup check ${o.dim("# See what's configured")}`),console.log(` wyrm-setup only vscode-copilot,cursor ${o.dim("# Only VS Code + Cursor")}`),console.log(` wyrm-setup --server /path/to/wyrm/dist/index.js ${o.dim("# Custom server path")}`),console.log(` wyrm-setup remove ${o.dim("# Remove from all clients")}`),console.log(` wyrm-setup export stdio > wyrm.json ${o.dim("# Portable config for any MCP host")}`),console.log("")}function J(){console.log(f()),console.log(""),d("Supported AI Clients"),console.log("");const n=C();for(const e of n){const s=e.detected?e.configured?o.success("\u25CF connected"):o.yellow("\u25D0 available"):o.dim("\u25CB not found"),l=e.version?` ${o.dim(`v${e.version}`)}`:"";console.log(` ${e.icon} ${o.bold(e.name.padEnd(20))} ${o.cyan(e.id.padEnd(18))} ${s}${l}`),console.log(` ${o.dim(`Config: ${e.configPath}`)}`)}console.log("")}async function K(){const n=Y(process.argv);if(n.command==="wizard"||n.command==="auto"&&!n.noWizard){const e=await U({serverPath:n.serverPath,dbPath:n.dbPath});if(e===!1)n.command==="wizard"&&(n.command="auto");else if(e===null){console.log(o.dim("Setup aborted, nothing changed."));return}else{await b(n.noModel??!1,e);return}}switch(n.command){case"help":H();break;case"check":{console.log(f()),console.log(""),console.log(W());break}case"list":J();break;case"auto":{console.log(z()),d("Auto-Configure"),console.log("");const e=n.serverPath||_(),s=n.dbPath||A();console.log(` ${g.sword} Server: ${o.cyan(e)}`),console.log(` ${g.treasure} DB: ${o.cyan(s)}`),console.log(""),console.log(` ${o.dim("Scanning for AI clients...")}`);const l=M({serverPath:e,dbPath:s});w(l),await b(n.noModel??!1,l);break}case"only":{(!n.clientIds||n.clientIds.length===0)&&(E("No client IDs specified. Use: wyrm-setup only vscode-copilot,cursor"),process.exit(1)),console.log(f()),d(`Configure: ${n.clientIds.join(", ")}`);const e=L(n.clientIds,{serverPath:n.serverPath,dbPath:n.dbPath});w(e),await b(n.noModel??!1,e);break}case"remove":{console.log(f()),d("Remove Wyrm from AI Clients"),console.log(""),console.log(` ${o.warning("Removing Wyrm configuration from all AI clients...")}`);const e=D(),s=e.filter(t=>t.action==="configured"),l=e.filter(t=>t.action==="skipped");for(const t of s)console.log(` ${g.check} ${t.client.icon} ${t.client.name}: removed`),t.backup&&console.log(` ${o.dim(`backup \u2192 ${t.backup}`)}`);for(const t of l)console.log(` ${o.dim(` \u25CB ${t.client.icon} ${t.client.name}: ${t.message}`)}`);console.log(""),s.length>0&&console.log(` ${o.success(`Removed from ${s.length} client(s). Run wyrm-setup to reconnect.`)}`),console.log("");break}case"reconf":{console.log(f()),d("Re-Configure");const e=B();console.log(e?` ${o.dim(`Restoring config for: ${e.configuredClients.join(", ")}`)}`:` ${o.dim("No previous config found; running full auto-configure")}`);const s=N();w(s);break}case"export":{const e=n.exportFormat??"mcp-json",s=j(e,{serverPath:n.serverPath,dbPath:n.dbPath});process.stderr.write(`${o.dim(`# Wyrm MCP config (${e}). Paste into any MCP-compatible host.`)}
3
3
  `),process.stdout.write(JSON.stringify(s,null,2)+`
4
4
  `);break}}}K().catch(n=>{E(`Setup failed: ${n}`),process.exit(1)});