wyrm-mcp 8.7.5 → 8.7.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{Server as ye}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as fe}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as de,GetPromptRequestSchema as ge,ListPromptsRequestSchema as he,ListResourcesRequestSchema as we,ListResourceTemplatesRequestSchema as Se,ListToolsRequestSchema as Re,ReadResourceRequestSchema as ve}from"@modelcontextprotocol/sdk/types.js";import{WyrmDB as ke,resolveDbPath as be}from"./database.js";import{ValidationError as U}from"./validate.js";import{validationErrorResponse as q,cacheKeyFor as Ee}from"./render.js";import{handlerRegistry as h,registryToolDefs as De,applyDeclaredOutputSchemas as Ce,buildStableToolList as Te}from"./handlers/registry.js";import{resolveActorEnvelope as V,runWithActor as $,getActor as Oe,runWithReadCacheKey as xe}from"./handlers/boundary.js";import{resolveAliasCall as Me}from"./handlers/aliases.js";import{resolveShimCall as We,shimToolDefs as Pe}from"./handlers/shims.js";import{getPromptResult as Ae,wyrmPromptList as Ie}from"./handlers/prompts.js";import{listWyrmResources as Ne,listWyrmResourceTemplates as Le,readWyrmResource as Ye,ResourceNotFoundError as je}from"./handlers/resources.js";import{TaskStore as Fe,resolveTaskGate as Be,runLongOp as Ke}from"./tasks.js";import{registerTaskHandlers as Ge,finalizeEarly as He,unwrapOutcome as Ue,applyAdminGate as qe}from"./tasks-dispatch.js";import{ReplicationManager as Ve}from"./replication-daemon.js";import{WYRM_SERVER_INSTRUCTIONS as $e}from"./priority-embed.js";import{WyrmSync as Je}from"./sync.js";import{cache as w,estimateTokens as W}from"./performance.js";import{readFileSync as J,unlinkSync as ze,existsSync as z}from"fs";import{join as Qe}from"path";import{initializeOrchestrator as Xe}from"./auto-orchestrator.js";import{getCrypto as Ze,initializeCrypto as et}from"./crypto.js";import{initVectorSearch as tt}from"./vector-init.js";import{KnowledgeGraph as rt}from"./knowledge-graph.js";import{MemoryArtifacts as ot}from"./memory-artifacts.js";import{GroundTruths as st,ReasoningScaffolds as nt}from"./intelligence.js";import{classifyCapture as qo}from"./capture.js";import{initializeLicense as at,getLicenseInfo as it}from"./license.js";import{refreshRevocations as Q}from"./revocations.js";import{refreshLicenseIfNeeded as X}from"./license-refresh.js";import{activationSatisfied as ct,activationGateResult as mt}from"./activation.js";import{WyrmAnalytics as lt}from"./analytics.js";import{WyrmCloudBackup as pt}from"./cloud-backup.js";import{CloudSyncManager as _t}from"./cloud-sync.js";import{FailurePatterns as ut}from"./failure-patterns.js";import{AgentPresence as yt}from"./presence.js";import{Causality as ft}from"./causality.js";import{wireTruthAutoCascade as dt}from"./truth-cascade.js";import{SymbolGraph as gt}from"./symbols.js";import{HourLedger as ht}from"./hours.js";import{ToolAnalytics as wt}from"./tool-analytics.js";import{Rehydration as St}from"./rehydration.js";import{AuditLog as Rt,loadAuditSignerFromEnv as vt}from"./audit.js";import{retryableWriteCause as kt,busyErrorResponse as bt}from"./sqlite-busy.js";import{SubAgent as Et}from"./sub-agent.js";import{Federation as Dt}from"./federation.js";import{Goals as Ct}from"./goals.js";import{OutboundMcpClient as Tt}from"./mcp-client.js";import{AgentLoop as Ot}from"./agent-loop.js";import{makeInternalDispatch as xt}from"./internal-dispatch.js";import{createUsageTracker as Mt}from"./usage-tracker.js";import{AgentDaemon as Wt}from"./agent-daemon.js";import{emitStartupVersionBanner as Pt}from"./version-check.js";import{resolveProfile as At,filterByProfile as It}from"./tool-profiles.js";import{annotateTools as Nt,elideDefaultAnnotations as Lt}from"./tool-annotations.js";import{applyDeprecationNotices as Yt,noteDeprecatedToolInvocation as jt,isHardCliExile as Ft,cliExileRedirectResponse as Bt}from"./deprecations.js";import{goldenCapture as y}from"./golden.js";import{makeEstimator as Kt}from"./token-budget.js";import{makeRunBudgetedContextBuild as Gt}from"./context-build-budgeted.js";import{assembleThread as Ht}from"./thread-assemble.js";import{getThread as Ut}from"./thread-store.js";import{renderThreadForContext as Z}from"./handlers/thread.js";import{makeRunCompanionBuddy as qt}from"./buddy-runner.js";import{loadWeightsFromEnv as Vt}from"./context-ranking.js";import{SessionSeen as $t}from"./session-seen.js";import{DesignSystem as Jt}from"./design.js";import{fileURLToPath as zt}from"url";import{dirname as Qt,join as ee}from"path";import{readFileSync as Xt,existsSync as Zt}from"fs";const er=137;let P=null;function tr(){return P||(P=new Jt(r.getDatabase())),P}const rr=Kt(),or=Vt();let A=null;function te(){return A||(A=new $t(r.getDatabase())),A}const C=(()=>{try{const e=Qt(zt(import.meta.url));for(const t of[ee(e,"..","package.json"),ee(e,"..","..","package.json")])if(Zt(t)){const s=JSON.parse(Xt(t,"utf-8")).version;if(typeof s=="string")return s}}catch{}return"unknown"})(),r=new ke(be()),sr=new Je(r),re=new rt(r.getDatabase()),R=new ot(r.getDatabase()),v=new st(r.getDatabase()),I=new nt(r.getDatabase()),N=new ut(r.getDatabase()),L=new yt(r.getDatabase()),Y=new ft(r.getDatabase());dt(v,Y);const j=new gt(r.getDatabase()),nr=new ht(r.getDatabase()),k=new wt(r.getDatabase()),ar=Gt({groundTruths:v,scaffoldLib:I,memory:R,toolAnalytics:k,sessionSeen:te,tokenEstimator:rr,rankWeights:or,threadText:e=>{try{return Z(Ht(r.getDatabase(),e))}catch{try{const t=Ut(r.getDatabase(),e);return t?Z(t):""}catch{return""}}}}),oe=new St(r.getDatabase()),ir=new Rt(r.getDatabase(),vt()),cr=new Et(r.getDatabase()),se=new Dt(r.getDatabase()),ne=new Ct(r.getDatabase()),ae={projects:r,goals:ne,getActor:Oe,store:r,raw:()=>r.getDatabase(),memory:R,truths:v,scaffolds:I,failures:N,presence:L,rehydration:oe,graph:re,symbols:j,vectors:()=>T,indexing:()=>K,cache:w,decrypt:e=>B.maybeDecrypt(e),clientSupportsResources:()=>{const e=c.getClientCapabilities()?.experimental;return!!e&&"resources"in e}},F=new Tt(r.getDatabase()),mr=qt({db:r,mcpClient:F,version:C}),lr=new Wt(r.getDatabase()),pr=xt({db:r,failures:N,symbols:j,rehydration:oe,causality:Y,presence:L,federation:se,memory:R,groundTruths:v}),_r=new Ot(r.getDatabase(),F,pr);if(process.env.WYRM_ENCRYPTION_KEY)try{et(process.env.WYRM_ENCRYPTION_KEY)}catch(e){console.error("Wyrm: Failed to initialize encryption:",e)}const B=Ze();let T=null,K=null;{const e=tt(r,R,B);T=e.vectorStore,K=e.indexingPipeline}const ur=Xe({autoOrchestrateEnabled:!0,minConfidenceThreshold:65,maxParallelAgents:6,defaultHaikuBoosting:!0,trackMetrics:!0});at();const O=it();O.tier!=="free"&&console.error(`Wyrm: Licensed \u2014 ${O.tier} tier (expires: ${O.expiresAt||"never"})`);const yr=!!O.key&&!/^(0|false|no|off)$/i.test(process.env.WYRM_LICENSE_REFRESH??"");yr&&(Promise.all([Q(),X()]).catch(()=>{}),setInterval(()=>{Promise.all([Q(),X()]).catch(()=>{})},1440*60*1e3).unref?.());try{const e=process.env.HOME||process.env.USERPROFILE||"",t=Qe(e,".wyrm","bundled-skills.json");if(e&&z(t)){const s=JSON.parse(J(t,"utf-8"));let _=0;for(const i of s.skills)try{if(!z(i.path))continue;const m=J(i.path,"utf-8").match(/^---\s*\n([\s\S]*?)\n---/);let a=i.name,u;if(m){const d=m[1].match(/description:\s*\|?\s*\n([\s\S]*?)(?:\nname:|\nmetadata:|\ncategory:|\ntype:|$)/);d&&(a=d[1].split(`
3
- `).map(E=>E.trim()).filter(Boolean).join(" ").slice(0,500));const S=m[1].match(/category:\s*([^\n]+)/);S&&(u=S[1].trim())}r.registerSkill(i.name,a,i.path,u,"Ghost Protocol",void 0,"bundled"),_++}catch{}_>0&&console.error(`Wyrm: Registered ${_} bundled skill(s) on first start.`);try{ze(t)}catch{}}}catch{}const G=new lt(r.getDatabase()),ie=new pt;process.env.WYRM_R2_ENDPOINT&&process.env.WYRM_R2_ACCESS_KEY&&process.env.WYRM_R2_SECRET_KEY&&ie.configure({endpoint:process.env.WYRM_R2_ENDPOINT,bucket:process.env.WYRM_R2_BUCKET||"wyrm-backups",accessKeyId:process.env.WYRM_R2_ACCESS_KEY,secretAccessKey:process.env.WYRM_R2_SECRET_KEY},process.env.WYRM_ENCRYPTION_KEY);import{fileURLToPath as fr}from"url";import{dirname as dr,join as ce}from"path";const gr=fr(import.meta.url),me=dr(gr),hr=new _t(ce(me,"cloud-sync-entrypoint.js")),wr=new Ve(ce(me,"replication-daemon-entrypoint.js")),{trackUsage:f,getUsageStats:Sr,usageLog:Rr}=Mt(G),vr=new Map;function kr(e,t=!1){return{content:[{type:"text",text:e}]}}const br=new Set(["wyrm_list_projects","wyrm_project_context","wyrm_global_context","wyrm_all_quests","wyrm_data_query","wyrm_data_categories","wyrm_search","wyrm_stats","wyrm_skill_list","wyrm_skill_get","wyrm_skill_search","wyrm_skill_stats","wyrm_orchestration_config","wyrm_orchestration_stats","wyrm_license","wyrm_analytics_dashboard","wyrm_cost_report","wyrm_entity_search","wyrm_entity_graph","wyrm_entity_path","wyrm_truth_get","wyrm_scaffold_get","wyrm_session_prime"]);function Er(e,t){return!(!br.has(e)||e==="wyrm_session_prime"&&(t?.run_id===void 0||t?.run_id===null))}const le=new Set(["wyrm_session_start","wyrm_session_update","wyrm_quest_add","wyrm_quest_complete","wyrm_data_insert","wyrm_data_batch_insert","wyrm_set_global","wyrm_scan_projects","wyrm_sync","wyrm_maintenance","wyrm_vector_setup","wyrm_reindex","wyrm_skill_register","wyrm_skill_delete","wyrm_skill_activate","wyrm_skill_deactivate","wyrm_spec_register","wyrm_activate","wyrm_cloud_backup","wyrm_cloud_sync","wyrm_encrypt_setup","wyrm_entity_add","wyrm_entity_link","wyrm_entity_merge","wyrm_remember","wyrm_recall","wyrm_feedback","wyrm_truth_set","wyrm_scaffold_save","wyrm_distill","wyrm_review","wyrm_capture","wyrm_import_git","wyrm_import_pr","wyrm_import_rules","wyrm_inject_prompt","wyrm_prune","wyrm_sync_export","wyrm_sync_import"]),b=new Fe,c=new ye({name:"wyrm",version:C},{capabilities:{tools:{},prompts:{},resources:{},tasks:{list:{},cancel:{},requests:{tools:{call:{}}}}},instructions:$e}),pe={...ae,db:r,sync:sr,graph:re,memory:R,groundTruths:v,scaffoldLib:I,failures:N,presence:L,causality:Y,symbols:j,hours:nr,toolAnalytics:k,auditLog:ir,subAgent:cr,federation:se,goals:ne,mcpClient:F,agentDaemon:lr,agentLoop:_r,analytics:G,cloudBackup:ie,cloudSyncManager:hr,replicationManager:wr,orchestrator:ur,server:c,wyrmCrypto:B,get vectorStore(){return T},get indexingPipeline(){return K},setVectorStore:e=>{T=e},WYRM_PACKAGE_VERSION:C,WYRM_TOOL_COUNT:er,WRITE_TOOLS:le,usageLog:Rr,responseFingerprints:vr,designSystem:tr,sessionSeen:te,cachedResponse:kr,getUsageStats:Sr,runCompanionBuddy:mr,runBudgetedContextBuild:ar};c.setRequestHandler(Re,async()=>{const e=[...De(),...Pe()],t=At();return{tools:Te(Ce(Yt(Lt(Nt(It(e,t))))))}}),c.setRequestHandler(he,async()=>({prompts:[...Ie()]})),c.setRequestHandler(ge,async e=>{const t=e.params.arguments??{},s=V({args:t,meta:e.params._meta,clientName:c.getClientVersion()?.name});return $(s,()=>Ae(e.params.name,t,ae))}),c.setRequestHandler(we,async()=>({resources:Ne()})),c.setRequestHandler(Se,async()=>({resourceTemplates:Le()})),c.setRequestHandler(ve,async e=>{const t=e.params.uri;try{const s=Ye(t,pe),{nextCursor:_,...i}=s;return _?{contents:[i],_meta:{"wyrm/nextCursor":_}}:{contents:[i]}}catch(s){throw s instanceof je?new Error(s.message):s}}),Ge(c,b),c.setRequestHandler(de,async e=>{const{name:t,arguments:s}=e.params;if(!ct())return mt();const _=V({args:s??{},meta:e.params._meta,clientName:c.getClientVersion()?.name});jt(t);const i=performance.now(),x=JSON.stringify(s||{}),m=W(x);let a,u,d=null;try{const o=Me(t,s??{});o.via?.kind==="cli-exile"&&(d=o.via),{tool:a,args:u}=We(o.tool,o.args)}catch(o){if(o instanceof U){const n=Math.round(performance.now()-i);f({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()});const l=q(t,o.field,o.message);return y({tool:t,args:s,meta:e.params._meta,response:l,outcome:"validation_error",ms:n,dispatch:"switch"}),l}throw o}if(d&&Ft(d.name)){const o=Math.round(performance.now()-i);f({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:o,timestamp:new Date().toISOString()});const n=Bt(d.name);return y({tool:t,args:s,meta:e.params._meta,response:n,outcome:"soft_error",ms:o,dispatch:"switch"}),n}const S=Be(c.getClientCapabilities()?.tasks,e.params),E=qe(b,S,a,o=>{const n=Math.round(performance.now()-i);f({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()}),y({tool:t,args:s,meta:e.params._meta,response:o,outcome:"soft_error",ms:n,dispatch:h.has(a)?"registry":"switch"})});if(E!==null)return E;const _e=a===t?x:JSON.stringify(u),M=Er(a,u??{})?Ee(a,_e):null;if(M){const o=w.get(M);if(o){const n=Math.round(performance.now()-i),l=W(JSON.stringify(o));f({tool:t,tokens_in:m,tokens_out:l,cached:!0,ms:n,timestamp:new Date().toISOString()});const p={...o};return y({tool:t,args:s,meta:e.params._meta,response:p,cached:!0,ms:n,dispatch:h.has(a)?"registry":"switch"}),He(b,S,a,p)}}if(le.has(a)){const o=u?.projectPath;o&&w.invalidate(o),w.invalidate("wyrm_list_projects"),w.invalidate("wyrm_global_context"),w.invalidate("wyrm_all_quests"),w.invalidate("wyrm_stats")}let D;const ue=u||{};try{const o=await $(_,async()=>{const H=h.get(a);return H?await Ke(a,S,b,()=>xe(M,()=>H(ue,pe))):{kind:"inline",result:{content:[{type:"text",text:`Unknown tool: ${a}`}],isError:!0}}}),{wireValue:n,payload:l}=Ue(b,o);D=l;const p=Math.round(performance.now()-i),g=W(JSON.stringify(D));return f({tool:t,tokens_in:m,tokens_out:g,cached:!1,ms:p,timestamp:new Date().toISOString()}),k.log({tool_name:t,args:s,success:!D?.isError,latency_ms:p}),y({tool:t,args:s,meta:e.params._meta,response:D,ms:p,dispatch:h.has(a)?"registry":"switch"}),n}catch(o){const n=Math.round(performance.now()-i);if(o instanceof U){f({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()});const g=q(t,o.field,o.message);return y({tool:t,args:s,meta:e.params._meta,response:g,outcome:"validation_error",ms:n,dispatch:h.has(a)?"registry":"switch"}),g}const l=kt(o);if(l!==null){f({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()}),k.log({tool_name:t,args:s,success:!1,error_message:`WYRM_BUSY[${l}]: ${String(o).slice(0,400)}`,latency_ms:n});const g=bt(t,l);return y({tool:t,args:s,meta:e.params._meta,response:g,outcome:"error",ms:n,dispatch:h.has(a)?"registry":"switch"}),g}f({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()}),k.log({tool_name:t,args:s,success:!1,error_message:String(o).slice(0,500),latency_ms:n});const p={content:[{type:"text",text:`Error: ${o}`}],isError:!0};return y({tool:t,args:s,meta:e.params._meta,response:p,outcome:"error",ms:n,dispatch:h.has(a)?"registry":"switch"}),p}}),process.on("uncaughtException",e=>{try{console.error("Wyrm[uncaughtException]:",e instanceof Error?e.stack:e)}catch{}}),process.on("unhandledRejection",e=>{try{console.error("Wyrm[unhandledRejection]:",e instanceof Error?e.stack:e)}catch{}});async function Dr(){const e=new fe;await c.connect(e),Pt(r.getDatabase(),C).catch(()=>{});const t=()=>{try{G.shutdown()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}Dr().catch(console.error);export{qo as classifyCapture};
2
+ import{Server as fe}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as de}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as ge,GetPromptRequestSchema as he,ListPromptsRequestSchema as we,ListResourcesRequestSchema as Se,ListResourceTemplatesRequestSchema as Re,ListToolsRequestSchema as ve,ReadResourceRequestSchema as ke}from"@modelcontextprotocol/sdk/types.js";import{WyrmDB as be,resolveDbPath as Ee}from"./database.js";import{ValidationError as U}from"./validate.js";import{validationErrorResponse as q,cacheKeyFor as De}from"./render.js";import{handlerRegistry as h,registryToolDefs as Ce,applyDeclaredOutputSchemas as Te,buildStableToolList as Oe}from"./handlers/registry.js";import{resolveActorEnvelope as V,runWithActor as J,getActor as xe,runWithReadCacheKey as Me}from"./handlers/boundary.js";import{resolveAliasCall as We}from"./handlers/aliases.js";import{resolveShimCall as Pe,shimToolDefs as Ae}from"./handlers/shims.js";import{getPromptResult as Ie,wyrmPromptList as Ne}from"./handlers/prompts.js";import{listWyrmResources as Le,listWyrmResourceTemplates as Ye,readWyrmResource as je,ResourceNotFoundError as Fe}from"./handlers/resources.js";import{TaskStore as Be,resolveTaskGate as Ke,runLongOp as Ge}from"./tasks.js";import{registerTaskHandlers as He,finalizeEarly as Ue,unwrapOutcome as qe,applyAdminGate as Ve}from"./tasks-dispatch.js";import{ReplicationManager as Je}from"./replication-daemon.js";import{WYRM_SERVER_INSTRUCTIONS as $e}from"./priority-embed.js";import{WyrmSync as ze}from"./sync.js";import{cache as w,estimateTokens as W}from"./performance.js";import{readFileSync as $,unlinkSync as Qe,existsSync as z}from"fs";import{join as Xe}from"path";import{initializeOrchestrator as Ze}from"./auto-orchestrator.js";import{getCrypto as et,initializeCrypto as tt}from"./crypto.js";import{initVectorSearch as rt}from"./vector-init.js";import{KnowledgeGraph as ot}from"./knowledge-graph.js";import{MemoryArtifacts as st}from"./memory-artifacts.js";import{GroundTruths as nt,ReasoningScaffolds as at}from"./intelligence.js";import{classifyCapture as $o}from"./capture.js";import{initializeLicense as it,getLicenseInfo as ct}from"./license.js";import{refreshRevocations as Q}from"./revocations.js";import{refreshLicenseIfNeeded as X}from"./license-refresh.js";import{activationSatisfied as mt,activationGateResult as lt}from"./activation.js";import{WyrmAnalytics as pt}from"./analytics.js";import{WyrmCloudBackup as _t}from"./cloud-backup.js";import{CloudSyncManager as ut}from"./cloud-sync.js";import{FailurePatterns as yt}from"./failure-patterns.js";import{AgentPresence as ft}from"./presence.js";import{Causality as dt}from"./causality.js";import{wireTruthAutoCascade as gt}from"./truth-cascade.js";import{SymbolGraph as ht}from"./symbols.js";import{HourLedger as wt}from"./hours.js";import{ToolAnalytics as St}from"./tool-analytics.js";import{Rehydration as Rt}from"./rehydration.js";import{AuditLog as vt,loadAuditSignerFromEnv as kt}from"./audit.js";import{retryableWriteCause as bt,busyErrorResponse as Et}from"./sqlite-busy.js";import{SubAgent as Dt}from"./sub-agent.js";import{Federation as Ct}from"./federation.js";import{Goals as Tt}from"./goals.js";import{OutboundMcpClient as Ot}from"./mcp-client.js";import{AgentLoop as xt}from"./agent-loop.js";import{makeInternalDispatch as Mt}from"./internal-dispatch.js";import{createUsageTracker as Wt}from"./usage-tracker.js";import{AgentDaemon as Pt}from"./agent-daemon.js";import{emitStartupVersionBanner as At}from"./version-check.js";import{resolveProfile as It,filterByProfile as Nt}from"./tool-profiles.js";import{annotateTools as Lt,elideDefaultAnnotations as Yt}from"./tool-annotations.js";import{applyDeprecationNotices as jt,noteDeprecatedToolInvocation as Ft,isHardCliExile as Bt,cliExileRedirectResponse as Kt}from"./deprecations.js";import{goldenCapture as f}from"./golden.js";import{makeEstimator as Gt}from"./token-budget.js";import{makeRunBudgetedContextBuild as Ht}from"./context-build-budgeted.js";import{assembleThread as Ut}from"./thread-assemble.js";import{getThread as qt}from"./thread-store.js";import{renderThreadForContext as Z}from"./handlers/thread.js";import{makeRunCompanionBuddy as Vt}from"./buddy-runner.js";import{loadWeightsFromEnv as Jt}from"./context-ranking.js";import{SessionSeen as $t}from"./session-seen.js";import{recordServed as zt}from"./served-records.js";import{DesignSystem as Qt}from"./design.js";import{fileURLToPath as Xt}from"url";import{dirname as Zt,join as ee}from"path";import{readFileSync as er,existsSync as tr}from"fs";const rr=137;let P=null;function or(){return P||(P=new Qt(r.getDatabase())),P}const sr=Gt(),nr=Jt();let A=null;function te(){return A||(A=new $t(r.getDatabase())),A}const C=(()=>{try{const e=Zt(Xt(import.meta.url));for(const t of[ee(e,"..","package.json"),ee(e,"..","..","package.json")])if(tr(t)){const s=JSON.parse(er(t,"utf-8")).version;if(typeof s=="string")return s}}catch{}return"unknown"})(),r=new be(Ee()),ar=new ze(r),re=new ot(r.getDatabase()),R=new st(r.getDatabase()),v=new nt(r.getDatabase()),I=new at(r.getDatabase()),N=new yt(r.getDatabase()),L=new ft(r.getDatabase()),Y=new dt(r.getDatabase());gt(v,Y);const j=new ht(r.getDatabase()),ir=new wt(r.getDatabase()),k=new St(r.getDatabase()),cr=Ht({groundTruths:v,scaffoldLib:I,memory:R,toolAnalytics:k,sessionSeen:te,tokenEstimator:sr,rankWeights:nr,threadText:e=>{try{return Z(Ut(r.getDatabase(),e))}catch{try{const t=qt(r.getDatabase(),e);return t?Z(t):""}catch{return""}}}}),oe=new Rt(r.getDatabase()),mr=new vt(r.getDatabase(),kt()),lr=new Dt(r.getDatabase()),se=new Ct(r.getDatabase()),ne=new Tt(r.getDatabase()),ae={projects:r,goals:ne,getActor:xe,store:r,raw:()=>r.getDatabase(),memory:R,truths:v,scaffolds:I,failures:N,presence:L,rehydration:oe,graph:re,symbols:j,vectors:()=>T,indexing:()=>K,cache:w,decrypt:e=>B.maybeDecrypt(e),clientSupportsResources:()=>{const e=c.getClientCapabilities()?.experimental;return!!e&&"resources"in e}},F=new Ot(r.getDatabase()),pr=Vt({db:r,mcpClient:F,version:C}),_r=new Pt(r.getDatabase()),ur=Mt({db:r,failures:N,symbols:j,rehydration:oe,causality:Y,presence:L,federation:se,memory:R,groundTruths:v}),yr=new xt(r.getDatabase(),F,ur);if(process.env.WYRM_ENCRYPTION_KEY)try{tt(process.env.WYRM_ENCRYPTION_KEY)}catch(e){console.error("Wyrm: Failed to initialize encryption:",e)}const B=et();let T=null,K=null;{const e=rt(r,R,B);T=e.vectorStore,K=e.indexingPipeline}const fr=Ze({autoOrchestrateEnabled:!0,minConfidenceThreshold:65,maxParallelAgents:6,defaultHaikuBoosting:!0,trackMetrics:!0});it();const O=ct();O.tier!=="free"&&console.error(`Wyrm: Licensed \u2014 ${O.tier} tier (expires: ${O.expiresAt||"never"})`);const dr=!!O.key&&!/^(0|false|no|off)$/i.test(process.env.WYRM_LICENSE_REFRESH??"");dr&&(Promise.all([Q(),X()]).catch(()=>{}),setInterval(()=>{Promise.all([Q(),X()]).catch(()=>{})},1440*60*1e3).unref?.());try{const e=process.env.HOME||process.env.USERPROFILE||"",t=Xe(e,".wyrm","bundled-skills.json");if(e&&z(t)){const s=JSON.parse($(t,"utf-8"));let _=0;for(const i of s.skills)try{if(!z(i.path))continue;const m=$(i.path,"utf-8").match(/^---\s*\n([\s\S]*?)\n---/);let a=i.name,u;if(m){const g=m[1].match(/description:\s*\|?\s*\n([\s\S]*?)(?:\nname:|\nmetadata:|\ncategory:|\ntype:|$)/);g&&(a=g[1].split(`
3
+ `).map(E=>E.trim()).filter(Boolean).join(" ").slice(0,500));const S=m[1].match(/category:\s*([^\n]+)/);S&&(u=S[1].trim())}r.registerSkill(i.name,a,i.path,u,"Ghost Protocol",void 0,"bundled"),_++}catch{}_>0&&console.error(`Wyrm: Registered ${_} bundled skill(s) on first start.`);try{Qe(t)}catch{}}}catch{}const G=new pt(r.getDatabase()),ie=new _t;process.env.WYRM_R2_ENDPOINT&&process.env.WYRM_R2_ACCESS_KEY&&process.env.WYRM_R2_SECRET_KEY&&ie.configure({endpoint:process.env.WYRM_R2_ENDPOINT,bucket:process.env.WYRM_R2_BUCKET||"wyrm-backups",accessKeyId:process.env.WYRM_R2_ACCESS_KEY,secretAccessKey:process.env.WYRM_R2_SECRET_KEY},process.env.WYRM_ENCRYPTION_KEY);import{fileURLToPath as gr}from"url";import{dirname as hr,join as ce}from"path";const wr=gr(import.meta.url),me=hr(wr),Sr=new ut(ce(me,"cloud-sync-entrypoint.js")),Rr=new Je(ce(me,"replication-daemon-entrypoint.js")),{trackUsage:d,getUsageStats:vr,usageLog:kr}=Wt(G),br=new Map;function Er(e,t=!1){return{content:[{type:"text",text:e}]}}const Dr=new Set(["wyrm_list_projects","wyrm_project_context","wyrm_global_context","wyrm_all_quests","wyrm_data_query","wyrm_data_categories","wyrm_search","wyrm_stats","wyrm_skill_list","wyrm_skill_get","wyrm_skill_search","wyrm_skill_stats","wyrm_orchestration_config","wyrm_orchestration_stats","wyrm_license","wyrm_analytics_dashboard","wyrm_cost_report","wyrm_entity_search","wyrm_entity_graph","wyrm_entity_path","wyrm_truth_get","wyrm_scaffold_get","wyrm_session_prime"]);function Cr(e,t){return!(!Dr.has(e)||e==="wyrm_session_prime"&&(t?.run_id===void 0||t?.run_id===null))}const le=new Set(["wyrm_session_start","wyrm_session_update","wyrm_quest_add","wyrm_quest_complete","wyrm_data_insert","wyrm_data_batch_insert","wyrm_set_global","wyrm_scan_projects","wyrm_sync","wyrm_maintenance","wyrm_vector_setup","wyrm_reindex","wyrm_skill_register","wyrm_skill_delete","wyrm_skill_activate","wyrm_skill_deactivate","wyrm_spec_register","wyrm_activate","wyrm_cloud_backup","wyrm_cloud_sync","wyrm_encrypt_setup","wyrm_entity_add","wyrm_entity_link","wyrm_entity_merge","wyrm_remember","wyrm_recall","wyrm_feedback","wyrm_truth_set","wyrm_scaffold_save","wyrm_distill","wyrm_review","wyrm_capture","wyrm_import_git","wyrm_import_pr","wyrm_import_rules","wyrm_inject_prompt","wyrm_prune","wyrm_sync_export","wyrm_sync_import"]),b=new Be,c=new fe({name:"wyrm",version:C},{capabilities:{tools:{},prompts:{},resources:{},tasks:{list:{},cancel:{},requests:{tools:{call:{}}}}},instructions:$e}),pe={...ae,db:r,sync:ar,graph:re,memory:R,groundTruths:v,scaffoldLib:I,failures:N,presence:L,causality:Y,symbols:j,hours:ir,toolAnalytics:k,auditLog:mr,subAgent:lr,federation:se,goals:ne,mcpClient:F,agentDaemon:_r,agentLoop:yr,analytics:G,cloudBackup:ie,cloudSyncManager:Sr,replicationManager:Rr,orchestrator:fr,server:c,wyrmCrypto:B,get vectorStore(){return T},get indexingPipeline(){return K},setVectorStore:e=>{T=e},WYRM_PACKAGE_VERSION:C,WYRM_TOOL_COUNT:rr,WRITE_TOOLS:le,usageLog:kr,responseFingerprints:br,designSystem:or,sessionSeen:te,cachedResponse:Er,getUsageStats:vr,runCompanionBuddy:pr,runBudgetedContextBuild:cr};c.setRequestHandler(ve,async()=>{const e=[...Ce(),...Ae()],t=It();return{tools:Oe(Te(jt(Yt(Lt(Nt(e,t))))))}}),c.setRequestHandler(we,async()=>({prompts:[...Ne()]})),c.setRequestHandler(he,async e=>{const t=e.params.arguments??{},s=V({args:t,meta:e.params._meta,clientName:c.getClientVersion()?.name});return J(s,()=>Ie(e.params.name,t,ae))}),c.setRequestHandler(Se,async()=>({resources:Le()})),c.setRequestHandler(Re,async()=>({resourceTemplates:Ye()})),c.setRequestHandler(ke,async e=>{const t=e.params.uri;try{const s=je(t,pe),{nextCursor:_,...i}=s;return _?{contents:[i],_meta:{"wyrm/nextCursor":_}}:{contents:[i]}}catch(s){throw s instanceof Fe?new Error(s.message):s}}),He(c,b),c.setRequestHandler(ge,async e=>{const{name:t,arguments:s}=e.params;if(!mt())return lt();const _=V({args:s??{},meta:e.params._meta,clientName:c.getClientVersion()?.name});Ft(t);const i=performance.now(),x=JSON.stringify(s||{}),m=W(x);let a,u,g=null;try{const o=We(t,s??{});o.via?.kind==="cli-exile"&&(g=o.via),{tool:a,args:u}=Pe(o.tool,o.args)}catch(o){if(o instanceof U){const n=Math.round(performance.now()-i);d({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()});const l=q(t,o.field,o.message);return f({tool:t,args:s,meta:e.params._meta,response:l,outcome:"validation_error",ms:n,dispatch:"switch"}),l}throw o}if(g&&Bt(g.name)){const o=Math.round(performance.now()-i);d({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:o,timestamp:new Date().toISOString()});const n=Kt(g.name);return f({tool:t,args:s,meta:e.params._meta,response:n,outcome:"soft_error",ms:o,dispatch:"switch"}),n}const S=Ke(c.getClientCapabilities()?.tasks,e.params),E=Ve(b,S,a,o=>{const n=Math.round(performance.now()-i);d({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()}),f({tool:t,args:s,meta:e.params._meta,response:o,outcome:"soft_error",ms:n,dispatch:h.has(a)?"registry":"switch"})});if(E!==null)return E;const _e=a===t?x:JSON.stringify(u),M=Cr(a,u??{})?De(a,_e):null;if(M){const o=w.get(M);if(o){const n=Math.round(performance.now()-i),l=W(JSON.stringify(o));d({tool:t,tokens_in:m,tokens_out:l,cached:!0,ms:n,timestamp:new Date().toISOString()});const p={...o};return f({tool:t,args:s,meta:e.params._meta,response:p,cached:!0,ms:n,dispatch:h.has(a)?"registry":"switch"}),Ue(b,S,a,p)}}if(le.has(a)){const o=u?.projectPath;o&&w.invalidate(o),w.invalidate("wyrm_list_projects"),w.invalidate("wyrm_global_context"),w.invalidate("wyrm_all_quests"),w.invalidate("wyrm_stats")}let D;const ue=u||{};try{const o=await J(_,async()=>{const H=h.get(a);return H?await Ge(a,S,b,()=>Me(M,()=>H(ue,pe))):{kind:"inline",result:{content:[{type:"text",text:`Unknown tool: ${a}`}],isError:!0}}}),{wireValue:n,payload:l}=qe(b,o);D=l;const p=Math.round(performance.now()-i),y=JSON.stringify(D),ye=W(y);return zt(r.getDatabase(),y),d({tool:t,tokens_in:m,tokens_out:ye,cached:!1,ms:p,timestamp:new Date().toISOString()}),k.log({tool_name:t,args:s,success:!D?.isError,latency_ms:p}),f({tool:t,args:s,meta:e.params._meta,response:D,ms:p,dispatch:h.has(a)?"registry":"switch"}),n}catch(o){const n=Math.round(performance.now()-i);if(o instanceof U){d({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()});const y=q(t,o.field,o.message);return f({tool:t,args:s,meta:e.params._meta,response:y,outcome:"validation_error",ms:n,dispatch:h.has(a)?"registry":"switch"}),y}const l=bt(o);if(l!==null){d({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()}),k.log({tool_name:t,args:s,success:!1,error_message:`WYRM_BUSY[${l}]: ${String(o).slice(0,400)}`,latency_ms:n});const y=Et(t,l);return f({tool:t,args:s,meta:e.params._meta,response:y,outcome:"error",ms:n,dispatch:h.has(a)?"registry":"switch"}),y}d({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()}),k.log({tool_name:t,args:s,success:!1,error_message:String(o).slice(0,500),latency_ms:n});const p={content:[{type:"text",text:`Error: ${o}`}],isError:!0};return f({tool:t,args:s,meta:e.params._meta,response:p,outcome:"error",ms:n,dispatch:h.has(a)?"registry":"switch"}),p}}),process.on("uncaughtException",e=>{try{console.error("Wyrm[uncaughtException]:",e instanceof Error?e.stack:e)}catch{}}),process.on("unhandledRejection",e=>{try{console.error("Wyrm[unhandledRejection]:",e instanceof Error?e.stack:e)}catch{}});async function Tr(){const e=new de;await c.connect(e),At(r.getDatabase(),C).catch(()=>{});const t=()=>{try{G.shutdown()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}Tr().catch(console.error);export{$o as classifyCapture};
@@ -1,4 +1,4 @@
1
- import{pruneWriteLedger as _}from"./receipts.js";import{metabolizeEnabled as E,metabolizeDefaultEnabled as f,runMetabolize as h}from"./metabolize.js";function R(c,o={}){const{db:n,sessionSeen:d,failures:a,presence:u}=c,{vacuum:p,archiveDays:i}=o,s=[];if(i){const e=n.getAllProjects(1e3);let r=0;for(const t of e)r+=n.archiveOldSessions(t.id,i);s.push(`Archived ${r} old sessions`)}p&&(n.vacuum(),s.push("Vacuumed database"));try{const e=parseInt(process.env.WYRM_SEEN_TTL_DAYS??"7",10),r=d.prune(Number.isFinite(e)&&e>0?e:7);r>0&&s.push(`Pruned ${r} session_seen_artifacts rows older than ${e}d`)}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),r=parseInt(process.env.WYRM_EVENT_MAX_PER_PROJECT??"5000",10),{deleted:t}=n.pruneEvents({olderThanDays:Number.isFinite(e)?e:90,maxPerProject:Number.isFinite(r)?r:5e3});t>0&&s.push(`Pruned ${t} Live Memory events (retention)`)}catch{}try{if(f()){const e=h(n.getDatabase(),{near:E()});e.exactMerged+e.nearCandidatesQueued+e.decayed>0&&s.push(`Metabolize: ${e.exactMerged} exact dupes superseded, ${e.nearCandidatesQueued} near-dup candidates queued, ${e.decayed} stale auto-captures decayed`)}}catch{}try{const e=_(n.getDatabase());e>0&&s.push(`Pruned ${e} write_ledger receipts (retention)`)}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),r=Number.isFinite(e)&&e>0?e:90,t=a.pruneBlocks(r);t>0&&s.push(`Pruned ${t} failure_blocks rows older than ${r}d (retention)`)}catch{}try{const e=u.reap();(e.presence>0||e.claims>0)&&s.push(`Reaped ${e.presence} stale presence row(s) and ${e.claims} expired quest claim(s)`)}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),r=Number.isFinite(e)&&e>0?e:90,t=n.getDatabase().prepare("DELETE FROM run_briefs WHERE created_at < datetime('now', ?)").run(`-${r} days`).changes;t>0&&s.push(`Pruned ${t} run_briefs rows older than ${r}d (retention)`)}catch{}try{const e=parseInt(process.env.WYRM_RUN_BRIEFS_MAX??"512",10),r=Number.isFinite(e)&&e>0?e:512,t=n.getDatabase().prepare(`
1
+ import{pruneWriteLedger as _}from"./receipts.js";import{metabolizeEnabled as E,metabolizeDefaultEnabled as h,runMetabolize as f}from"./metabolize.js";import{ServedRecords as l}from"./served-records.js";function y(c,o={}){const{db:n,sessionSeen:d,failures:a,presence:u}=c,{vacuum:p,archiveDays:i}=o,t=[];if(i){const e=n.getAllProjects(1e3);let r=0;for(const s of e)r+=n.archiveOldSessions(s.id,i);t.push(`Archived ${r} old sessions`)}p&&(n.vacuum(),t.push("Vacuumed database"));try{const e=parseInt(process.env.WYRM_SEEN_TTL_DAYS??"7",10),r=d.prune(Number.isFinite(e)&&e>0?e:7);r>0&&t.push(`Pruned ${r} session_seen_artifacts rows older than ${e}d`)}catch{}try{const e=parseInt(process.env.WYRM_SEEN_TTL_DAYS??"7",10),r=Number.isFinite(e)&&e>0?e:7,s=new l(n.getDatabase()).prune(r);s>0&&t.push(`Pruned ${s} served_records rows older than ${r}d`)}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),r=parseInt(process.env.WYRM_EVENT_MAX_PER_PROJECT??"5000",10),{deleted:s}=n.pruneEvents({olderThanDays:Number.isFinite(e)?e:90,maxPerProject:Number.isFinite(r)?r:5e3});s>0&&t.push(`Pruned ${s} Live Memory events (retention)`)}catch{}try{if(h()){const e=f(n.getDatabase(),{near:E()});e.exactMerged+e.nearCandidatesQueued+e.decayed>0&&t.push(`Metabolize: ${e.exactMerged} exact dupes superseded, ${e.nearCandidatesQueued} near-dup candidates queued, ${e.decayed} stale auto-captures decayed`)}}catch{}try{const e=_(n.getDatabase());e>0&&t.push(`Pruned ${e} write_ledger receipts (retention)`)}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),r=Number.isFinite(e)&&e>0?e:90,s=a.pruneBlocks(r);s>0&&t.push(`Pruned ${s} failure_blocks rows older than ${r}d (retention)`)}catch{}try{const e=u.reap();(e.presence>0||e.claims>0)&&t.push(`Reaped ${e.presence} stale presence row(s) and ${e.claims} expired quest claim(s)`)}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),r=Number.isFinite(e)&&e>0?e:90,s=n.getDatabase().prepare("DELETE FROM run_briefs WHERE created_at < datetime('now', ?)").run(`-${r} days`).changes;s>0&&t.push(`Pruned ${s} run_briefs rows older than ${r}d (retention)`)}catch{}try{const e=parseInt(process.env.WYRM_RUN_BRIEFS_MAX??"512",10),r=Number.isFinite(e)&&e>0?e:512,s=n.getDatabase().prepare(`
2
2
  DELETE FROM run_briefs WHERE rowid IN (
3
3
  SELECT rowid FROM run_briefs ORDER BY created_at DESC, rowid DESC LIMIT -1 OFFSET ?
4
- )`).run(r).changes;t>0&&s.push(`Pruned ${t} run_briefs rows over the ${r}-row cap (WYRM_RUN_BRIEFS_MAX)`)}catch{}try{const e=parseInt(process.env.WYRM_RUN_INACTIVE_HOURS??"24",10),r=a.sweepRunQuarantine({runInactiveHours:Number.isFinite(e)&&e>0?e:24});(r.promoted>0||r.expired>0||r.runs_abandoned>0)&&s.push(`Run-quarantine sweep: promoted ${r.promoted} failure(s), expired ${r.expired} abandoned-run failure(s), TTL-abandoned ${r.runs_abandoned} stalled run(s)`),r.degraded&&s.push(`Run-quarantine sweep: ${r.degraded}`)}catch{}return n.checkpoint(),s.push("Checkpointed WAL"),{lines:s,dbSize:n.getStats().dbSize}}export{R as runMaintenance};
4
+ )`).run(r).changes;s>0&&t.push(`Pruned ${s} run_briefs rows over the ${r}-row cap (WYRM_RUN_BRIEFS_MAX)`)}catch{}try{const e=parseInt(process.env.WYRM_RUN_INACTIVE_HOURS??"24",10),r=a.sweepRunQuarantine({runInactiveHours:Number.isFinite(e)&&e>0?e:24});(r.promoted>0||r.expired>0||r.runs_abandoned>0)&&t.push(`Run-quarantine sweep: promoted ${r.promoted} failure(s), expired ${r.expired} abandoned-run failure(s), TTL-abandoned ${r.runs_abandoned} stalled run(s)`),r.degraded&&t.push(`Run-quarantine sweep: ${r.degraded}`)}catch{}return n.checkpoint(),t.push("Checkpointed WAL"),{lines:t,dbSize:n.getStats().dbSize}}export{y as runMaintenance};
@@ -210,7 +210,7 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
210
210
  timestamp TEXT DEFAULT (datetime('now'))
211
211
  );
212
212
  CREATE INDEX IF NOT EXISTS idx_usage_timestamp ON usage_events(timestamp);
213
- `)}},{version:3,description:"Add visibility and created_by columns for future multi-user support",up:e=>{const s=["sessions","quests","context","data_lake"];for(const t of s){const i=e.prepare(`PRAGMA table_info(${t})`).all().map(T=>T.name);i.includes("visibility")||e.exec(`ALTER TABLE ${t} ADD COLUMN visibility TEXT DEFAULT 'private'`),i.includes("created_by")||e.exec(`ALTER TABLE ${t} ADD COLUMN created_by TEXT DEFAULT 'local'`)}}},{version:4,description:"Knowledge graph \u2014 entities, aliases, relationships with FTS5",up:e=>{e.exec(`
213
+ `)}},{version:3,description:"Add visibility and created_by columns for future multi-user support",up:e=>{const s=["sessions","quests","context","data_lake"];for(const t of s){const E=e.prepare(`PRAGMA table_info(${t})`).all().map(T=>T.name);E.includes("visibility")||e.exec(`ALTER TABLE ${t} ADD COLUMN visibility TEXT DEFAULT 'private'`),E.includes("created_by")||e.exec(`ALTER TABLE ${t} ADD COLUMN created_by TEXT DEFAULT 'local'`)}}},{version:4,description:"Knowledge graph \u2014 entities, aliases, relationships with FTS5",up:e=>{e.exec(`
214
214
  -- Entities: named things that can be linked together
215
215
  CREATE TABLE IF NOT EXISTS entities (
216
216
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -844,7 +844,7 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
844
844
  ON token_savings_log(session_id, timestamp DESC);
845
845
  CREATE INDEX IF NOT EXISTS idx_savings_category
846
846
  ON token_savings_log(category, timestamp DESC);
847
- `);const s=["ground_truths","memory_artifacts","quests","decision_edges","design_references","design_tokens"];for(const t of s)try{if(e.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name==="cross_project_visibility"))continue;e.exec(`
847
+ `);const s=["ground_truths","memory_artifacts","quests","decision_edges","design_references","design_tokens"];for(const t of s)try{if(e.prepare(`PRAGMA table_info(${t})`).all().some(E=>E.name==="cross_project_visibility"))continue;e.exec(`
848
848
  ALTER TABLE ${t} ADD COLUMN cross_project_visibility TEXT NOT NULL DEFAULT 'within'
849
849
  CHECK (cross_project_visibility IN ('within', 'org', 'public'));
850
850
  `)}catch{}}},{version:15,description:"Live Memory v6.4 \u2014 append-only events log + wyrm_meta (device identity)",up:e=>{e.exec(`
@@ -908,7 +908,7 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
908
908
  `)}},{version:17,description:'Backfill cross_project_visibility on decision_edges (migration 14 named a non-existent "decisions" table)',up:e=>{try{e.prepare("PRAGMA table_info(decision_edges)").all().some(t=>t.name==="cross_project_visibility")||e.exec(`
909
909
  ALTER TABLE decision_edges ADD COLUMN cross_project_visibility TEXT NOT NULL DEFAULT 'within'
910
910
  CHECK (cross_project_visibility IN ('within', 'org', 'public'));
911
- `)}catch{}}},{version:18,description:"GOD-SKILL SPEC v2 \u2014 skill tier/governs/composes + spec-kit registry (specs table)",up:e=>{const s=e.prepare("PRAGMA table_info(skills)").all(),t=E=>s.some(i=>i.name===E);t("tier")||e.exec(`
911
+ `)}catch{}}},{version:18,description:"GOD-SKILL SPEC v2 \u2014 skill tier/governs/composes + spec-kit registry (specs table)",up:e=>{const s=e.prepare("PRAGMA table_info(skills)").all(),t=i=>s.some(E=>E.name===i);t("tier")||e.exec(`
912
912
  ALTER TABLE skills ADD COLUMN tier TEXT NOT NULL DEFAULT 'atomic'
913
913
  CHECK (tier IN ('atomic', 'mega', 'god'));
914
914
  `),t("governs")||e.exec("ALTER TABLE skills ADD COLUMN governs TEXT NOT NULL DEFAULT '[]';"),t("composes")||e.exec("ALTER TABLE skills ADD COLUMN composes TEXT NOT NULL DEFAULT '[]';"),e.exec("CREATE INDEX IF NOT EXISTS idx_skills_tier ON skills(tier);"),e.exec(`
@@ -929,8 +929,8 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
929
929
  `)}},{version:19,description:"Grove sync policy: projects.sync_policy gate (private by default) for cloud + federation isolation",up:e=>{e.prepare("PRAGMA table_info(projects)").all().some(a=>a.name==="sync_policy")||e.exec(`
930
930
  ALTER TABLE projects ADD COLUMN sync_policy TEXT NOT NULL DEFAULT 'private'
931
931
  CHECK (sync_policy IN ('private', 'cloud', 'team'));
932
- `);const t=(a,o)=>{try{return e.prepare(`PRAGMA table_info(${a})`).all().some(r=>r.name===o)}catch{return!1}},E=a=>{try{return e.prepare(a).all().map(o=>o.pid)}catch{return[]}},i=new Set;for(const a of["ground_truths","memory_artifacts","quests","design_tokens","design_references"])if(!(!t(a,"cross_project_visibility")||!t(a,"project_id")))for(const o of E(`SELECT DISTINCT project_id AS pid FROM ${a}
933
- WHERE cross_project_visibility IN ('org', 'public') AND project_id IS NOT NULL`))i.add(o);const T=e.prepare("UPDATE projects SET sync_policy = 'cloud' WHERE id = ? AND sync_policy = 'private'");for(const a of i)T.run(a)}},{version:20,description:"v7 F2 (T008) \u2014 run-native provenance: runs + run_agents tables, agent_id/run_id attribution on 9 tables, failure_patterns.quarantine_scope",up:e=>{e.exec(`
932
+ `);const t=(a,o)=>{try{return e.prepare(`PRAGMA table_info(${a})`).all().some(r=>r.name===o)}catch{return!1}},i=a=>{try{return e.prepare(a).all().map(o=>o.pid)}catch{return[]}},E=new Set;for(const a of["ground_truths","memory_artifacts","quests","design_tokens","design_references"])if(!(!t(a,"cross_project_visibility")||!t(a,"project_id")))for(const o of i(`SELECT DISTINCT project_id AS pid FROM ${a}
933
+ WHERE cross_project_visibility IN ('org', 'public') AND project_id IS NOT NULL`))E.add(o);const T=e.prepare("UPDATE projects SET sync_policy = 'cloud' WHERE id = ? AND sync_policy = 'private'");for(const a of E)T.run(a)}},{version:20,description:"v7 F2 (T008) \u2014 run-native provenance: runs + run_agents tables, agent_id/run_id attribution on 9 tables, failure_patterns.quarantine_scope",up:e=>{e.exec(`
934
934
  CREATE TABLE IF NOT EXISTS runs (
935
935
  run_id TEXT PRIMARY KEY,
936
936
  parent_run_id TEXT,
@@ -955,7 +955,7 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
955
955
  FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE
956
956
  );
957
957
  CREATE INDEX IF NOT EXISTS idx_run_agents_agent ON run_agents(agent_id);
958
- `);const s=(E,i)=>{try{return e.prepare(`PRAGMA table_info(${E})`).all().some(T=>T.name===i)}catch{return!1}},t=["memory_artifacts","failure_patterns","decision_edges","ground_truths","quests","sessions","quest_claims","events","audit_log"];for(const E of t)s(E,"agent_id")||e.exec(`ALTER TABLE ${E} ADD COLUMN agent_id TEXT;`),s(E,"run_id")||e.exec(`ALTER TABLE ${E} ADD COLUMN run_id TEXT;`);e.exec(`
958
+ `);const s=(i,E)=>{try{return e.prepare(`PRAGMA table_info(${i})`).all().some(T=>T.name===E)}catch{return!1}},t=["memory_artifacts","failure_patterns","decision_edges","ground_truths","quests","sessions","quest_claims","events","audit_log"];for(const i of t)s(i,"agent_id")||e.exec(`ALTER TABLE ${i} ADD COLUMN agent_id TEXT;`),s(i,"run_id")||e.exec(`ALTER TABLE ${i} ADD COLUMN run_id TEXT;`);e.exec(`
959
959
  CREATE INDEX IF NOT EXISTS idx_failure_run ON failure_patterns(run_id) WHERE run_id IS NOT NULL;
960
960
  CREATE INDEX IF NOT EXISTS idx_events_run ON events(run_id) WHERE run_id IS NOT NULL;
961
961
  CREATE INDEX IF NOT EXISTS idx_artifacts_run ON memory_artifacts(run_id) WHERE run_id IS NOT NULL;
@@ -990,10 +990,10 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
990
990
  created_at TEXT DEFAULT (datetime('now')),
991
991
  PRIMARY KEY (run_id, role)
992
992
  );
993
- `)}},{version:24,description:"v7 F3 (T029) \u2014 claims/presence hardening: role on quest_claims, run_id/role on agent_presence, run-scoped partial indexes",up:e=>{const s=(t,E)=>{try{return e.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===E)}catch{return!1}};s("quest_claims","role")||e.exec("ALTER TABLE quest_claims ADD COLUMN role TEXT;"),s("agent_presence","run_id")||e.exec("ALTER TABLE agent_presence ADD COLUMN run_id TEXT;"),s("agent_presence","role")||e.exec("ALTER TABLE agent_presence ADD COLUMN role TEXT;"),e.exec(`
993
+ `)}},{version:24,description:"v7 F3 (T029) \u2014 claims/presence hardening: role on quest_claims, run_id/role on agent_presence, run-scoped partial indexes",up:e=>{const s=(t,i)=>{try{return e.prepare(`PRAGMA table_info(${t})`).all().some(E=>E.name===i)}catch{return!1}};s("quest_claims","role")||e.exec("ALTER TABLE quest_claims ADD COLUMN role TEXT;"),s("agent_presence","run_id")||e.exec("ALTER TABLE agent_presence ADD COLUMN run_id TEXT;"),s("agent_presence","role")||e.exec("ALTER TABLE agent_presence ADD COLUMN role TEXT;"),e.exec(`
994
994
  CREATE INDEX IF NOT EXISTS idx_quest_claims_run ON quest_claims(run_id) WHERE run_id IS NOT NULL;
995
995
  CREATE INDEX IF NOT EXISTS idx_presence_run ON agent_presence(run_id) WHERE run_id IS NOT NULL;
996
- `)}},{version:25,description:"Skills portability \u2014 store SKILL.md content (+ sha/ts) in the registry and make skills cloud-sync-eligible behind the per-row visibility gate",up:e=>{const s=(t,E)=>{try{return e.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===E)}catch{return!1}};s("skills","content")||e.exec("ALTER TABLE skills ADD COLUMN content TEXT;"),s("skills","content_sha256")||e.exec("ALTER TABLE skills ADD COLUMN content_sha256 TEXT;"),s("skills","content_updated_at")||e.exec("ALTER TABLE skills ADD COLUMN content_updated_at TEXT;"),s("skills","cross_project_visibility")||e.exec("ALTER TABLE skills ADD COLUMN cross_project_visibility TEXT NOT NULL DEFAULT 'within';"),s("skills","is_shared")||e.exec("ALTER TABLE skills ADD COLUMN is_shared INTEGER NOT NULL DEFAULT 0;"),e.exec("CREATE INDEX IF NOT EXISTS idx_skills_visibility ON skills(cross_project_visibility) WHERE cross_project_visibility != 'within';")}},{version:26,description:"Reverse-bridge rejection tombstones \u2014 remember a once-rejected outside-prose sig so the next sweep never re-queues content the operator already deleted",up:e=>{e.exec(`
996
+ `)}},{version:25,description:"Skills portability \u2014 store SKILL.md content (+ sha/ts) in the registry and make skills cloud-sync-eligible behind the per-row visibility gate",up:e=>{const s=(t,i)=>{try{return e.prepare(`PRAGMA table_info(${t})`).all().some(E=>E.name===i)}catch{return!1}};s("skills","content")||e.exec("ALTER TABLE skills ADD COLUMN content TEXT;"),s("skills","content_sha256")||e.exec("ALTER TABLE skills ADD COLUMN content_sha256 TEXT;"),s("skills","content_updated_at")||e.exec("ALTER TABLE skills ADD COLUMN content_updated_at TEXT;"),s("skills","cross_project_visibility")||e.exec("ALTER TABLE skills ADD COLUMN cross_project_visibility TEXT NOT NULL DEFAULT 'within';"),s("skills","is_shared")||e.exec("ALTER TABLE skills ADD COLUMN is_shared INTEGER NOT NULL DEFAULT 0;"),e.exec("CREATE INDEX IF NOT EXISTS idx_skills_visibility ON skills(cross_project_visibility) WHERE cross_project_visibility != 'within';")}},{version:26,description:"Reverse-bridge rejection tombstones \u2014 remember a once-rejected outside-prose sig so the next sweep never re-queues content the operator already deleted",up:e=>{e.exec(`
997
997
  CREATE TABLE IF NOT EXISTS reverse_bridge_tombstones (
998
998
  project_id INTEGER NOT NULL,
999
999
  sig TEXT NOT NULL,
@@ -1130,20 +1130,20 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
1130
1130
  UNIQUE(kind, row_id)
1131
1131
  );
1132
1132
  CREATE INDEX IF NOT EXISTS idx_sync_tombstones_pending ON sync_tombstones(pushed_at_ms);
1133
- `);const s=[["ground_truths","truth"],["memory_artifacts","memory_artifact"],["quests","quest"],["design_tokens","design_token"],["design_references","design_reference"],["skills","skill"]];for(const[t,E]of s)e.exec(`
1133
+ `);const s=[["ground_truths","truth"],["memory_artifacts","memory_artifact"],["quests","quest"],["design_tokens","design_token"],["design_references","design_reference"],["skills","skill"]];for(const[t,i]of s)e.exec(`
1134
1134
  CREATE TRIGGER IF NOT EXISTS trg_tombstone_${t} AFTER DELETE ON ${t}
1135
1135
  BEGIN
1136
1136
  INSERT OR IGNORE INTO sync_tombstones (kind, row_id, deleted_at_ms)
1137
- VALUES ('${E}', CAST(OLD.id AS TEXT), CAST(strftime('%s','now') AS INTEGER) * 1000);
1137
+ VALUES ('${i}', CAST(OLD.id AS TEXT), CAST(strftime('%s','now') AS INTEGER) * 1000);
1138
1138
  END;
1139
- `)}},{version:35,description:"Grove-gate the tombstone triggers (quest #113): a tombstone must record ONLY when the deleted row would have SYNCED, matching the upsert gate exactly (cross_project_visibility IN org/public AND grove sync_policy IN cloud/team). Migration 34 recorded a tombstone for EVERY delete, so a PRIVATE grove's (or unshared skill's) deletion leaked content-free deletion metadata to the cloud as noise. Recreates all 6 triggers gated.",up:e=>{const s=[["ground_truths","truth"],["memory_artifacts","memory_artifact"],["quests","quest"],["design_tokens","design_token"],["design_references","design_reference"],["skills","skill"]];for(const[t,E]of s){e.exec(`DROP TRIGGER IF EXISTS trg_tombstone_${t};`);const i=t==="skills"?"OLD.cross_project_visibility IN ('org','public')":"OLD.cross_project_visibility IN ('org','public') AND (OLD.project_id IS NULL OR (SELECT sync_policy FROM projects WHERE id = OLD.project_id) IN ('cloud','team'))";e.exec(`
1139
+ `)}},{version:35,description:"Grove-gate the tombstone triggers (quest #113): a tombstone must record ONLY when the deleted row would have SYNCED, matching the upsert gate exactly (cross_project_visibility IN org/public AND grove sync_policy IN cloud/team). Migration 34 recorded a tombstone for EVERY delete, so a PRIVATE grove's (or unshared skill's) deletion leaked content-free deletion metadata to the cloud as noise. Recreates all 6 triggers gated.",up:e=>{const s=[["ground_truths","truth"],["memory_artifacts","memory_artifact"],["quests","quest"],["design_tokens","design_token"],["design_references","design_reference"],["skills","skill"]];for(const[t,i]of s){e.exec(`DROP TRIGGER IF EXISTS trg_tombstone_${t};`);const E=t==="skills"?"OLD.cross_project_visibility IN ('org','public')":"OLD.cross_project_visibility IN ('org','public') AND (OLD.project_id IS NULL OR (SELECT sync_policy FROM projects WHERE id = OLD.project_id) IN ('cloud','team'))";e.exec(`
1140
1140
  CREATE TRIGGER trg_tombstone_${t} AFTER DELETE ON ${t}
1141
- WHEN ${i}
1141
+ WHEN ${E}
1142
1142
  BEGIN
1143
1143
  INSERT OR IGNORE INTO sync_tombstones (kind, row_id, deleted_at_ms)
1144
- VALUES ('${E}', CAST(OLD.id AS TEXT), CAST(strftime('%s','now') AS INTEGER) * 1000);
1144
+ VALUES ('${i}', CAST(OLD.id AS TEXT), CAST(strftime('%s','now') AS INTEGER) * 1000);
1145
1145
  END;
1146
- `)}}},{version:36,description:`Add updated_at to quests + design_references so cloud sync can watermark-filter them. Root cause of "sync never settles" (2026-07-17): collectChangedRows skips its incremental time filter for any synced table WITHOUT an updated_at column, so it re-collected ALL org/public quests (101) + design_references every sync, stamping each with Date.now() and re-pushing forever (~1s/row server-side). The 4 other synced tables already have updated_at. This migration adds the column + backfills from the row's real last-change time (normalized via datetime() to the clean "YYYY-MM-DD HH:MM:SS" format strftime expects). No triggers: both tables are external-content FTS5, where a self-UPDATE inside a trigger corrupts the FTS index when an indexed column changes ("database disk image is malformed"). updated_at is stamped in app code on every insert/update instead (database.ts addQuest/updateQuest/dynamic-update, design.ts) \u2014 the same convention the other synced tables use.`,up:e=>{const s=(t,E)=>e.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===E);s("quests","updated_at")||(e.exec("ALTER TABLE quests ADD COLUMN updated_at TEXT"),e.exec("UPDATE quests SET updated_at = datetime(COALESCE(completed_at, created_at, 'now'))")),s("design_references","updated_at")||(e.exec("ALTER TABLE design_references ADD COLUMN updated_at TEXT"),e.exec("UPDATE design_references SET updated_at = datetime('now')"))}},{version:37,description:"Add metrics_snapshots \u2014 the longitudinal flight recorder for Wyrm effectiveness + quality over time. wyrm doctor / stats / benches all measure a MOMENT; nothing timestamped a trend, so a slow degradation (recall drifting as the corpus outgrows the index, vectors quietly off for days, a crucible-caught defect class recurring) was invisible until someone re-ran a tool by hand. One row per (kind, capture): kind=health (corpus/coverage/queue/failures/doctor checks), kind=effectiveness (recall hit-rate, failure-block rate, rehydrate non-empty rate, token savings), kind=retrieval (recall@k from the eval bench). metrics_json keeps the schema flexible so new metrics need no migration. Written nightly (health+effectiveness) + on-demand/per-release (retrieval); read by `wyrm metrics trend`.",up:e=>{e.exec(`
1146
+ `)}}},{version:36,description:`Add updated_at to quests + design_references so cloud sync can watermark-filter them. Root cause of "sync never settles" (2026-07-17): collectChangedRows skips its incremental time filter for any synced table WITHOUT an updated_at column, so it re-collected ALL org/public quests (101) + design_references every sync, stamping each with Date.now() and re-pushing forever (~1s/row server-side). The 4 other synced tables already have updated_at. This migration adds the column + backfills from the row's real last-change time (normalized via datetime() to the clean "YYYY-MM-DD HH:MM:SS" format strftime expects). No triggers: both tables are external-content FTS5, where a self-UPDATE inside a trigger corrupts the FTS index when an indexed column changes ("database disk image is malformed"). updated_at is stamped in app code on every insert/update instead (database.ts addQuest/updateQuest/dynamic-update, design.ts) \u2014 the same convention the other synced tables use.`,up:e=>{const s=(t,i)=>e.prepare(`PRAGMA table_info(${t})`).all().some(E=>E.name===i);s("quests","updated_at")||(e.exec("ALTER TABLE quests ADD COLUMN updated_at TEXT"),e.exec("UPDATE quests SET updated_at = datetime(COALESCE(completed_at, created_at, 'now'))")),s("design_references","updated_at")||(e.exec("ALTER TABLE design_references ADD COLUMN updated_at TEXT"),e.exec("UPDATE design_references SET updated_at = datetime('now')"))}},{version:37,description:"Add metrics_snapshots \u2014 the longitudinal flight recorder for Wyrm effectiveness + quality over time. wyrm doctor / stats / benches all measure a MOMENT; nothing timestamped a trend, so a slow degradation (recall drifting as the corpus outgrows the index, vectors quietly off for days, a crucible-caught defect class recurring) was invisible until someone re-ran a tool by hand. One row per (kind, capture): kind=health (corpus/coverage/queue/failures/doctor checks), kind=effectiveness (recall hit-rate, failure-block rate, rehydrate non-empty rate, token savings), kind=retrieval (recall@k from the eval bench). metrics_json keeps the schema flexible so new metrics need no migration. Written nightly (health+effectiveness) + on-demand/per-release (retrieval); read by `wyrm metrics trend`.",up:e=>{e.exec(`
1147
1147
  CREATE TABLE IF NOT EXISTS metrics_snapshots (
1148
1148
  id INTEGER PRIMARY KEY AUTOINCREMENT,
1149
1149
  captured_at TEXT NOT NULL DEFAULT (datetime('now')),
@@ -1164,10 +1164,10 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
1164
1164
  source_refs TEXT DEFAULT '{}',
1165
1165
  updated_at INTEGER NOT NULL DEFAULT 0
1166
1166
  );
1167
- `)}},{version:39,description:"Firewall target normalization (quest #1033) \u2014 add canonical_target + command_head to failure_patterns so the guard can catch flag-reordered / =-form command repeats (Tier A hard block) and warn on added-flag variants (Tier B advisory). Backfills existing command rows via canonicalizeCommand/commandHead; indexes both keys for range-scan lookups.",up:e=>{const s=e.prepare("PRAGMA table_info(failure_patterns)").all().map(i=>i.name);s.includes("canonical_target")||e.exec("ALTER TABLE failure_patterns ADD COLUMN canonical_target TEXT;"),s.includes("command_head")||e.exec("ALTER TABLE failure_patterns ADD COLUMN command_head TEXT;"),e.exec(`
1167
+ `)}},{version:39,description:"Firewall target normalization (quest #1033) \u2014 add canonical_target + command_head to failure_patterns so the guard can catch flag-reordered / =-form command repeats (Tier A hard block) and warn on added-flag variants (Tier B advisory). Backfills existing command rows via canonicalizeCommand/commandHead; indexes both keys for range-scan lookups.",up:e=>{const s=e.prepare("PRAGMA table_info(failure_patterns)").all().map(E=>E.name);s.includes("canonical_target")||e.exec("ALTER TABLE failure_patterns ADD COLUMN canonical_target TEXT;"),s.includes("command_head")||e.exec("ALTER TABLE failure_patterns ADD COLUMN command_head TEXT;"),e.exec(`
1168
1168
  CREATE INDEX IF NOT EXISTS idx_failure_canonical ON failure_patterns(canonical_target);
1169
1169
  CREATE INDEX IF NOT EXISTS idx_failure_cmdhead ON failure_patterns(command_head);
1170
- `);const t=e.prepare("SELECT id, target FROM failure_patterns WHERE scope = 'command'").all(),E=e.prepare("UPDATE failure_patterns SET canonical_target = ?, command_head = ? WHERE id = ?");for(const i of t)E.run(n(i.target)||null,d(i.target)||null,i.id)}},{version:40,description:"Negotiated Recall NR-1 (specs/negotiated-recall) \u2014 recall_policy: one row per run_id holding the session's recall consent state. mode=full is today's behavior (no filtering); mode=clean mutes the MUTE set (memory_artifacts kind IN (pattern, heuristic) OR outcome=positive) while the firewall (anti_pattern/negative/failure_patterns) and ground_truths stay unaffected by construction, never by an exclusion list; mode=custom governs by muted_ids/challenged_truth_ids alone. muted_ids/challenged_truth_ids are JSON arrays applied in every mode. Table only \u2014 no enforcement here (that lands in NR-3 at the MemoryArtifacts chokepoint); a DB with zero recall_policy rows recalls identically to pre-NR-1.",up:e=>{e.exec(`
1170
+ `);const t=e.prepare("SELECT id, target FROM failure_patterns WHERE scope = 'command'").all(),i=e.prepare("UPDATE failure_patterns SET canonical_target = ?, command_head = ? WHERE id = ?");for(const E of t)i.run(n(E.target)||null,d(E.target)||null,E.id)}},{version:40,description:"Negotiated Recall NR-1 (specs/negotiated-recall) \u2014 recall_policy: one row per run_id holding the session's recall consent state. mode=full is today's behavior (no filtering); mode=clean mutes the MUTE set (memory_artifacts kind IN (pattern, heuristic) OR outcome=positive) while the firewall (anti_pattern/negative/failure_patterns) and ground_truths stay unaffected by construction, never by an exclusion list; mode=custom governs by muted_ids/challenged_truth_ids alone. muted_ids/challenged_truth_ids are JSON arrays applied in every mode. Table only \u2014 no enforcement here (that lands in NR-3 at the MemoryArtifacts chokepoint); a DB with zero recall_policy rows recalls identically to pre-NR-1.",up:e=>{e.exec(`
1171
1171
  CREATE TABLE IF NOT EXISTS recall_policy (
1172
1172
  run_id TEXT PRIMARY KEY,
1173
1173
  mode TEXT NOT NULL DEFAULT 'full'
@@ -1177,10 +1177,18 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
1177
1177
  created_at INTEGER NOT NULL,
1178
1178
  updated_at INTEGER NOT NULL
1179
1179
  );
1180
+ `)}},{version:41,description:"Grounding enforcement \u2014 served_records: the per-connection ledger of which artifacts Wyrm actually handed to a client, so a citation naming a record that was never served can be identified as a fabrication rather than trusted. Keyed by session_key (an opaque per-server-process id), NOT run_id: WYRM_RUN_ID is not present in the MCP server environment, so run_id resolves null at dispatch and every session would collapse into one bucket. Keyed separately from session_seen_artifacts, whose session_id is a caller-supplied integer used for context_build elision and is pruned on its own TTL.",up:e=>{e.exec(`
1181
+ CREATE TABLE IF NOT EXISTS served_records (
1182
+ session_key TEXT NOT NULL,
1183
+ artifact_id INTEGER NOT NULL,
1184
+ artifact_kind TEXT NOT NULL,
1185
+ served_at TEXT NOT NULL DEFAULT (datetime('now')),
1186
+ PRIMARY KEY (session_key, artifact_id, artifact_kind)
1187
+ );
1180
1188
  `)}}];function l(e){e.exec(`
1181
1189
  CREATE TABLE IF NOT EXISTS schema_versions (
1182
1190
  version INTEGER PRIMARY KEY,
1183
1191
  description TEXT NOT NULL,
1184
1192
  applied_at TEXT DEFAULT (datetime('now'))
1185
1193
  );
1186
- `);const s=e.prepare("SELECT COALESCE(MAX(version), 0) as v FROM schema_versions").get().v,t=N.filter(T=>T.version>s).slice().sort((T,a)=>T.version-a.version);if(t.length===0)return[];const E=[],i=e.prepare("INSERT INTO schema_versions (version, description) VALUES (?, ?)");for(const T of t)e.transaction(()=>{T.up(e),i.run(T.version,T.description)})(),E.push(T);return E}function _(e){try{return e.prepare("SELECT COALESCE(MAX(version), 0) as v FROM schema_versions").get().v}catch{return 0}}export{_ as getSchemaVersion,N as migrations,l as runMigrations};
1194
+ `);const s=e.prepare("SELECT COALESCE(MAX(version), 0) as v FROM schema_versions").get().v,t=N.filter(T=>T.version>s).slice().sort((T,a)=>T.version-a.version);if(t.length===0)return[];const i=[],E=e.prepare("INSERT INTO schema_versions (version, description) VALUES (?, ?)");for(const T of t)e.transaction(()=>{T.up(e),E.run(T.version,T.description)})(),i.push(T);return i}function _(e){try{return e.prepare("SELECT COALESCE(MAX(version), 0) as v FROM schema_versions").get().v}catch{return 0}}export{_ as getSchemaVersion,N as migrations,l as runMigrations};
@@ -0,0 +1,5 @@
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(`
2
+ INSERT INTO served_records (session_key, artifact_id, artifact_kind)
3
+ VALUES (?, ?, ?)
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};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contract": "wyrm-cloud-memory-v2",
3
- "version": "8.7.5",
3
+ "version": "8.7.6",
4
4
  "derivedFrom": "standard tier MINUS device-local/egress/subprocess (src/cloud-profile.ts)",
5
5
  "count": 20,
6
6
  "tools": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contract": "wyrm-cloud-memory-v1",
3
- "version": "8.7.5",
3
+ "version": "8.7.6",
4
4
  "tools": [
5
5
  {
6
6
  "name": "wyrm_recall",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contract": "wyrm-cloud-memory-v1",
3
- "version": "8.7.5",
3
+ "version": "8.7.6",
4
4
  "generatedBy": "scripts/gen-tool-manifest.mjs (from the dist/ registry modules — never hand-edited)",
5
5
  "tiers": {
6
6
  "core": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wyrm-mcp",
3
- "version": "8.7.5",
3
+ "version": "8.7.6",
4
4
  "mcpName": "lk.ghosts/wyrm",
5
5
  "description": "Local-first persistent memory for AI agents over MCP. Ground truths, negative learning (recorded failures block repeats), decision causality, hybrid recall, negotiated recall (clean-mode injection you steer), live memory streams, run-attributed fleet memory \u2014 a structured SQLite memory on your machine, no cloud or LLM required. Claude / Copilot / Cursor / Windsurf / Codex.",
6
6
  "type": "module",