wyrm-mcp 7.6.0 → 7.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import{applyBudget as w,resolveBudget as v}from"./token-budget.js";import{score as p}from"./context-ranking.js";function S(g){const{groundTruths:b,scaffoldLib:h,memory:y,toolAnalytics:$,sessionSeen:u,tokenEstimator:d,rankWeights:f}=g;return function(t){const o=v({callArg:t.maxTokens,envValue:process.env.WYRM_CONTEXT_TOKEN_BUDGET,clientName:null}),x=t.sessionId?u().getSeen(t.sessionId):new Set,a=b.formatForContext(t.project.id),r=d.count(a??"");let m=a??"",k=r;r>o*.5&&!t.strictBudget&&process.stderr.write(`[wyrm_context_build] ground truths consume ${r} of ${o}-token budget \u2014 body will be heavily elided. Pass strict_budget:true to elide truths too.
2
- `),t.strictBudget&&r>o*.5&&(m=(a??"").slice(0,o*2),k=d.count(m));const l=[],c=h.findBest(t.task,t.project.id);if(c){const e=h.formatForContext(c),i=c.scaffold.id;l.push({item:{kind:"scaffold",id:i,title:c.scaffold.problem_type,body:e},key:`scaffold:${i}`,inlineCost:d.count(e),stubCost:20,score:p({confidence:.9,relevance:.9,updatedAt:new Date().toISOString()},f)})}const B=y.recall(t.project.id,t.task,{limit:20,minConfidence:t.minConfidence??.2});for(const e of B){const i=e.artifact;if(t.kinds&&t.kinds.length>0&&!t.kinds.includes(i.kind))continue;const _=[`**${i.kind.toUpperCase()}** \xB7 ${i.problem}`,i.constraints?`Constraints: ${i.constraints}`:"",i.validated_fix?`Fix: ${i.validated_fix}`:"",i.why_it_worked?`Why: ${i.why_it_worked}`:""].filter(Boolean).join(`
3
- `);l.push({item:{kind:"memory",id:i.id,title:i.problem.slice(0,60),body:_},key:`memory:${i.id}`,inlineCost:d.count(_),stubCost:25,score:p({confidence:i.confidence,relevance:e.relevance_score,updatedAt:i.updated_at},f)})}const s=w(l,{budget:o,alreadySeen:x,reserved:t.strictBudget?0:k});t.sessionId&&(u().markBulk(t.sessionId,s.inline.map(e=>({id:e.id,kind:e.kind,mode:"inline"}))),u().markBulk(t.sessionId,s.elided.map(e=>({id:e.item.id,kind:e.item.kind,mode:"stub"}))));const n=[];n.push(`\u{F115D} **Context Brief** \u2014 "${t.task}"`),n.push(""),n.push("## Ground truths (stable preamble)"),n.push(""),n.push(m||"_no ground truths set for this project yet_"),n.push(""),n.push("## Task-relevant memory"),n.push("");for(const e of s.inline)n.push(`### [${e.kind}:${e.id}] ${e.title}`),n.push(e.body),n.push("");if(s.elided.length>0){n.push("## Elided to stubs"),n.push(""),n.push("_Below the budget cutoff or already seen this session. Recall with `wyrm_recall(id)`:_"),n.push("");for(const e of s.elided){const i=e.reason==="seen"?"shown earlier in session":`~${e.stubCost} tokens`;n.push(`- [${e.item.kind}:${e.item.id}] ${e.item.title} \xB7 ${i}`)}n.push("")}n.push("---"),n.push(`_Budget: ${s.tokensInline}/${o} tokens inline \xB7 ${s.elided.length} stub${s.elided.length===1?"":"s"} \xB7 estimator: ${d.source}_`);const C=n.join(`
4
- `);try{$.log({tool_name:"wyrm_context_build",project_id:t.project.id,args:{budget:o,items_total:l.length,items_inline:s.inline.length,items_elided:s.elided.length,tokens_inline:s.tokensInline,tokens_stubs:s.tokensStubs},success:!0,latency_ms:0})}catch{}return{content:[{type:"text",text:C}]}}}export{S as makeRunBudgetedContextBuild};
1
+ import{applyBudget as w,resolveBudget as v}from"./token-budget.js";import{autoSummaryPenalty as T,score as p}from"./context-ranking.js";function E(g){const{groundTruths:y,scaffoldLib:h,memory:b,toolAnalytics:$,sessionSeen:u,tokenEstimator:d,rankWeights:f}=g;return function(t){const o=v({callArg:t.maxTokens,envValue:process.env.WYRM_CONTEXT_TOKEN_BUDGET,clientName:null}),x=t.sessionId?u().getSeen(t.sessionId):new Set,a=y.formatForContext(t.project.id),r=d.count(a??"");let m=a??"",k=r;r>o*.5&&!t.strictBudget&&process.stderr.write(`[wyrm_context_build] ground truths consume ${r} of ${o}-token budget \u2014 body will be heavily elided. Pass strict_budget:true to elide truths too.
2
+ `),t.strictBudget&&r>o*.5&&(m=(a??"").slice(0,o*2),k=d.count(m));const l=[],c=h.findBest(t.task,t.project.id);if(c){const e=h.formatForContext(c),s=c.scaffold.id;l.push({item:{kind:"scaffold",id:s,title:c.scaffold.problem_type,body:e},key:`scaffold:${s}`,inlineCost:d.count(e),stubCost:20,score:p({confidence:.9,relevance:.9,updatedAt:new Date().toISOString()},f)})}const B=b.recall(t.project.id,t.task,{limit:20,minConfidence:t.minConfidence??.2});for(const e of B){const s=e.artifact;if(t.kinds&&t.kinds.length>0&&!t.kinds.includes(s.kind))continue;const _=[`**${s.kind.toUpperCase()}** \xB7 ${s.problem}`,s.constraints?`Constraints: ${s.constraints}`:"",s.validated_fix?`Fix: ${s.validated_fix}`:"",s.why_it_worked?`Why: ${s.why_it_worked}`:""].filter(Boolean).join(`
3
+ `);l.push({item:{kind:"memory",id:s.id,title:s.problem.slice(0,60),body:_},key:`memory:${s.id}`,inlineCost:d.count(_),stubCost:25,score:p({confidence:s.confidence,relevance:e.relevance_score,updatedAt:s.updated_at,sourcePenalty:T(s.problem)},f)})}const i=w(l,{budget:o,alreadySeen:x,reserved:t.strictBudget?0:k});t.sessionId&&(u().markBulk(t.sessionId,i.inline.map(e=>({id:e.id,kind:e.kind,mode:"inline"}))),u().markBulk(t.sessionId,i.elided.map(e=>({id:e.item.id,kind:e.item.kind,mode:"stub"}))));const n=[];n.push(`\u{F115D} **Context Brief** \u2014 "${t.task}"`),n.push(""),n.push("## Ground truths (stable preamble)"),n.push(""),n.push(m||"_no ground truths set for this project yet_"),n.push(""),n.push("## Task-relevant memory"),n.push("");for(const e of i.inline)n.push(`### [${e.kind}:${e.id}] ${e.title}`),n.push(e.body),n.push("");if(i.elided.length>0){n.push("## Elided to stubs"),n.push(""),n.push("_Below the budget cutoff or already seen this session. Recall with `wyrm_recall(id)`:_"),n.push("");for(const e of i.elided){const s=e.reason==="seen"?"shown earlier in session":`~${e.stubCost} tokens`;n.push(`- [${e.item.kind}:${e.item.id}] ${e.item.title} \xB7 ${s}`)}n.push("")}n.push("---"),n.push(`_Budget: ${i.tokensInline}/${o} tokens inline \xB7 ${i.elided.length} stub${i.elided.length===1?"":"s"} \xB7 estimator: ${d.source}_`);const C=n.join(`
4
+ `);try{$.log({tool_name:"wyrm_context_build",project_id:t.project.id,args:{budget:o,items_total:l.length,items_inline:i.inline.length,items_elided:i.elided.length,tokens_inline:i.tokensInline,tokens_stubs:i.tokensStubs},success:!0,latency_ms:0})}catch{}return{content:[{type:"text",text:C}]}}}export{E as makeRunBudgetedContextBuild};
@@ -1 +1 @@
1
- import{logger as l}from"./logger.js";const s={confidence:.4,recency:.2,relevance:.3,usefulness:.1};function p(e=process.env){const r=e.WYRM_RANK_WEIGHTS;if(!r)return{...s};try{const n=JSON.parse(r);return{confidence:c(n.confidence??s.confidence),recency:c(n.recency??s.recency),relevance:c(n.relevance??s.relevance),usefulness:c(n.usefulness??s.usefulness)}}catch(n){return l.warn(`Invalid WYRM_RANK_WEIGHTS, using defaults: ${n.message}`),{...s}}}function c(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}function v(e,r,n=new Date){const t=c(e.confidence??.5),a=c(e.usefulness??.5),u=c(e.relevance??.5),o=e.updatedAt?Math.max(0,(n.getTime()-new Date(e.updatedAt).getTime())/(1440*60*1e3)):1/0,f=Number.isFinite(o)?Math.exp(-o/30):0,i=t*r.confidence+f*r.recency+u*r.relevance+a*r.usefulness;return c(i)}export{s as DEFAULT_WEIGHTS,p as loadWeightsFromEnv,v as score};
1
+ import{logger as d}from"./logger.js";const o={confidence:.4,recency:.2,relevance:.3,usefulness:.1};function v(e=process.env){const r=e.WYRM_RANK_WEIGHTS;if(!r)return{...o};try{const s=JSON.parse(r),n={confidence:c(s.confidence??o.confidence),recency:c(s.recency??o.recency),relevance:c(s.relevance??o.relevance),usefulness:c(s.usefulness??o.usefulness)},t=n.confidence+n.recency+n.relevance+n.usefulness;return t<=0?{...o}:(n.confidence/=t,n.recency/=t,n.relevance/=t,n.usefulness/=t,n)}catch(s){return d.warn(`Invalid WYRM_RANK_WEIGHTS, using defaults: ${s.message}`),{...o}}}function c(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}const p=.5,y=/^\s*\[auto:(precompact|sessionend|sessionstart)/i;function A(e){return e&&y.test(e)?p:0}function M(e,r,s=new Date){const n=c(e.confidence??.5),t=c(e.usefulness??.5),a=c(e.relevance??.5),u=e.updatedAt?Math.max(0,(s.getTime()-new Date(e.updatedAt).getTime())/(1440*60*1e3)):1/0,f=Number.isFinite(u)?Math.exp(-u/30):0,i=n*r.confidence+f*r.recency+a*r.relevance+t*r.usefulness,l=c(e.sourcePenalty??0);return c(i*(1-l))}export{p as AUTO_SUMMARY_PENALTY,o as DEFAULT_WEIGHTS,A as autoSummaryPenalty,v as loadWeightsFromEnv,M as score};
@@ -1,77 +1,77 @@
1
- import{join as H}from"path";import{TOOL_ANNOTATIONS as E}from"../tool-annotations.js";import{renderResult as q,withGlyph as I,renderErrorResponse as C,validationErrorBody as R}from"../render.js";import{ValidationError as B,asEnum as K}from"../validate.js";import{daemonOr as D}from"../daemon-writer.js";import{classifyCapture as J}from"../capture.js";import{extractCandidates as W,candidateToArtifact as O,escapeLikePattern as L}from"../auto-capture.js";import{parseTrace as Y,segmentsToText as Q}from"../trace-harvest.js";import{getActor as X,runWithActor as G}from"./boundary.js";import{harvestProjects as V}from"../harvest.js";import{readFileSync as F,readdirSync as z,statSync as M}from"fs";import{join as N}from"path";import{homedir as Z}from"os";import{readSpecDir as ee,specTaskSignature as te}from"../spec-kit.js";const ge=[{name:"wyrm_capture",description:"Use to save anything worth keeping - the single write funnel. Auto-classifies notes, decisions, and lessons into quest, ground truth, or memory; risky writes queue for wyrm_review. mode=direct (store a proven pattern or lesson learned so future agents reuse it), extract (pull memories from a conversation transcript or freeform text), trace (harvest a session JSONL / tool-call log into run-tagged review candidates), session (close out a work session into reusable knowledge), artifacts (harvest a repo's READMEs and recent commits into durable facts), import source=git|pr|rules, spec (turn a tasks.md into tracked work items), checklist. Keywords: remember this, jot down, write down, future reference.",inputSchema:{type:"object",properties:{content:{type:"string",description:"classify/rules"},project_id:{type:"number",description:"classify/import/spec"},tags:{type:"array",items:{type:"string"}},mode:{type:"string",enum:["auto","quest","truth","memory","classify","direct","extract","trace","session","artifacts","import","spec","checklist"],description:"quest|truth|memory force the type"},source:{type:"string",enum:["git","pr","rules"],description:"import"},projectPath:{type:"string",description:"non-classify"},kind:{type:"string",description:"direct"},problem:{type:"string",description:"direct"},validatedFix:{type:"string",description:"direct"},text:{type:"string",description:"extract"},sessionId:{type:"string",description:"session"},candidates:{type:"array",items:{type:"object"},description:"session"},dryRun:{type:"boolean",description:"artifacts"},commits:{type:"array",items:{type:"object"},description:"import git"},title:{type:"string",description:"import pr"},body:{type:"string",description:"import pr"},specDir:{type:"string",description:"spec"},problemType:{type:"string",description:"checklist"},whenToUse:{type:"string",description:"checklist"},steps:{type:"array",items:{type:"string"},description:"checklist"}},required:[]},outputSchema:{type:"object",properties:{status:{type:"string",enum:["captured","queued_for_review"]},type:{type:"string"},subtype:{type:"string"},confidence:{type:"number"},reasoning:{type:"string"},id:{type:"integer"},ref:{type:"string"},needs_review:{type:"boolean"},reason:{type:"string"},artifact_id:{type:"integer"},conflicts_with:{type:"array"},advisory_conflicts:{type:"array"}},required:["status"]},annotations:E.wyrm_capture,aliases:[],handler:async(j,{store:v,raw:b,memory:u,truths:f,cache:_})=>{const{content:a,project_id:m,projectPath:o,tags:y,mode:i}=j;let d=J(a);i&&i!=="auto"&&(d={type:i,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[i]??i,confidence:100,reasoning:`Mode override: ${i}`});const{type:p,subtype:c,confidence:g,reasoning:r}=d,e=m??(o?v.getProject(o)?.id??null:null);let n=0,s="",h=!1,t;if(p==="quest"){if(e===null)return C(R("wyrm_capture","projectPath","is required for quest capture"));n=(await D("quest_add",e,{title:a.slice(0,200),description:"",priority:"medium",tags:y?.join(",")},()=>v.addQuest(e,a.slice(0,200),"","medium",y?.join(",")))).id,s="quest",_.invalidate("wyrm_all_quests"),_.invalidate("wyrm_stats")}else if(p==="truth"){if(e===null)return C(R("wyrm_capture","projectPath","is required for truth capture"));if(g>=80){const w=c??"other",S=f.getCurrent(e).filter(P=>P.category===w);if(S.length>0){const P={kind:"pattern",problem:`Potential conflict with ${S.length} existing truth(s) in category "${w}"`,validatedFix:a,whyItWorked:"Pending review \u2014 possible supersession",tags:y??[],confidence:g/100,needsReview:1},l=await D("artifact_add",e,P,()=>u.add(e,P));return q({status:"queued_for_review",reason:"conflict_check",artifact_id:l.id,conflicts_with:S.map(k=>({id:k.id,content:k.value.slice(0,80)}))})}}if(i!=="truth"&&g<100){const w={kind:"pattern",problem:a,validatedFix:"",whyItWorked:"",tags:y??[],confidence:g/100,needsReview:1};n=(await D("artifact_add",e,w,()=>u.add(e,w))).id,s="mem",h=!0}else{const w={category:"decision",key:a.slice(0,60),value:a};n=(await D("truth_set",e,w,()=>f.set(e,w))).id,s="truth",_.invalidate("wyrm_truth_get"),_.invalidate("wyrm_context_build")}}else{if(e===null)return C(R("wyrm_capture","projectPath","is required for memory capture"));const w=g>=75,x={kind:c,problem:a,validatedFix:"",whyItWorked:"",tags:y??[],confidence:g/100,needsReview:w?0:1};if(n=(await D("artifact_add",e,x,()=>u.add(e,x))).id,s="mem",h=!w,c==="heuristic"&&g>=75&&e!==null)try{const P=a.replace(/['"*]/g," ").trim().split(/\s+/).slice(0,5).join(" "),l=b().prepare(`
1
+ import{join as H}from"path";import{TOOL_ANNOTATIONS as A}from"../tool-annotations.js";import{renderResult as S,withGlyph as I,renderErrorResponse as E,validationErrorBody as T}from"../render.js";import{ValidationError as B,asEnum as K}from"../validate.js";import{daemonOr as D}from"../daemon-writer.js";import{classifyCapture as J}from"../capture.js";import{extractCandidates as W,candidateToArtifact as O,escapeLikePattern as L}from"../auto-capture.js";import{parseTrace as Y,segmentsToText as Q}from"../trace-harvest.js";import{getActor as X,runWithActor as G}from"./boundary.js";import{harvestProjects as V}from"../harvest.js";import{readFileSync as F,readdirSync as z,statSync as M}from"fs";import{join as N}from"path";import{homedir as Z}from"os";import{readSpecDir as ee,specTaskSignature as te}from"../spec-kit.js";const he=[{name:"wyrm_capture",description:"Use to save anything worth keeping - the single write funnel. Auto-classifies notes, decisions, and lessons into quest, ground truth, or memory; risky writes queue for wyrm_review. mode=direct (store a proven pattern or lesson learned so future agents reuse it), extract (pull memories from a conversation transcript or freeform text), trace (harvest a session JSONL / tool-call log into run-tagged review candidates), session (close out a work session into reusable knowledge), artifacts (harvest a repo's READMEs and recent commits into durable facts), import source=git|pr|rules, spec (turn a tasks.md into tracked work items), checklist. Keywords: remember this, jot down, write down, future reference.",inputSchema:{type:"object",properties:{content:{type:"string",description:"classify/rules"},project_id:{type:"number",description:"classify/import/spec"},tags:{type:"array",items:{type:"string"}},mode:{type:"string",enum:["auto","quest","truth","memory","classify","direct","extract","trace","session","artifacts","import","spec","checklist"],description:"quest|truth|memory force the type"},source:{type:"string",enum:["git","pr","rules"],description:"import"},projectPath:{type:"string",description:"non-classify"},kind:{type:"string",description:"direct"},problem:{type:"string",description:"direct"},validatedFix:{type:"string",description:"direct"},text:{type:"string",description:"extract"},sessionId:{type:"string",description:"session"},candidates:{type:"array",items:{type:"object"},description:"session"},dryRun:{type:"boolean",description:"artifacts"},commits:{type:"array",items:{type:"object"},description:"import git"},title:{type:"string",description:"import pr"},body:{type:"string",description:"import pr"},specDir:{type:"string",description:"spec"},problemType:{type:"string",description:"checklist"},whenToUse:{type:"string",description:"checklist"},steps:{type:"array",items:{type:"string"},description:"checklist"}},required:[]},outputSchema:{type:"object",properties:{status:{type:"string",enum:["captured","queued_for_review"]},type:{type:"string"},subtype:{type:"string"},confidence:{type:"number"},reasoning:{type:"string"},id:{type:"integer"},ref:{type:"string"},needs_review:{type:"boolean"},reason:{type:"string"},artifact_id:{type:"integer"},conflicts_with:{type:"array"},advisory_conflicts:{type:"array"}},required:["status"]},annotations:A.wyrm_capture,aliases:[],handler:async(j,{store:v,raw:b,memory:u,truths:h,cache:w})=>{const{content:n,project_id:m,projectPath:o,tags:y,mode:i}=j;if(typeof n!="string"||!n.trim()){const f=j;return f.problem||f.validated_fix||f.validatedFix||f.kind?E(T("wyrm_capture","mode","you passed pattern/lesson fields (kind/problem/validated_fix) \u2014 set mode:'direct' to store them as a distilled artifact.")):E(T("wyrm_capture","content","content is required for auto capture (or use mode:'direct' with problem + validated_fix)."))}let d=J(n);i&&i!=="auto"&&(d={type:i,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[i]??i,confidence:100,reasoning:`Mode override: ${i}`});const{type:p,subtype:c,confidence:g,reasoning:r}=d,e=m??(o?v.getProject(o)?.id??null:null);let a=0,s="",_=!1,t;if(p==="quest"){if(e===null)return E(T("wyrm_capture","projectPath","is required for quest capture"));a=(await D("quest_add",e,{title:n.slice(0,200),description:"",priority:"medium",tags:y?.join(",")},()=>v.addQuest(e,n.slice(0,200),"","medium",y?.join(",")))).id,s="quest",w.invalidate("wyrm_all_quests"),w.invalidate("wyrm_stats")}else if(p==="truth"){if(e===null)return E(T("wyrm_capture","projectPath","is required for truth capture"));if(g>=80){const f=c??"other",q=h.getCurrent(e).filter(x=>x.category===f);if(q.length>0){const x={kind:"pattern",problem:`Potential conflict with ${q.length} existing truth(s) in category "${f}"`,validatedFix:n,whyItWorked:"Pending review \u2014 possible supersession",tags:y??[],confidence:g/100,needsReview:1},l=await D("artifact_add",e,x,()=>u.add(e,x));return S({status:"queued_for_review",reason:"conflict_check",artifact_id:l.id,conflicts_with:q.map(k=>({id:k.id,content:k.value.slice(0,80)}))})}}if(i!=="truth"&&g<100){const f={kind:"pattern",problem:n,validatedFix:"",whyItWorked:"",tags:y??[],confidence:g/100,needsReview:1};a=(await D("artifact_add",e,f,()=>u.add(e,f))).id,s="mem",_=!0}else{const f={category:"decision",key:n.slice(0,60),value:n};a=(await D("truth_set",e,f,()=>h.set(e,f))).id,s="truth",w.invalidate("wyrm_truth_get"),w.invalidate("wyrm_context_build")}}else{if(e===null)return E(T("wyrm_capture","projectPath","is required for memory capture"));const f=g>=75,P={kind:c,problem:n,validatedFix:"",whyItWorked:"",tags:y??[],confidence:g/100,needsReview:f?0:1};if(a=(await D("artifact_add",e,P,()=>u.add(e,P))).id,s="mem",_=!f,c==="heuristic"&&g>=75&&e!==null)try{const x=n.replace(/['"*]/g," ").trim().split(/\s+/).slice(0,5).join(" "),l=b().prepare(`
2
2
  SELECT a.id, a.problem FROM memory_artifacts a
3
3
  JOIN memory_artifacts_fts fts ON a.id = fts.rowid
4
4
  WHERE fts MATCH ? AND a.project_id = ? AND a.kind = 'heuristic' AND a.needs_review = 0
5
5
  LIMIT 3
6
- `).all(P,e);l.length>0&&(t=l.map(k=>({id:k.id,content:k.problem.slice(0,80)})))}catch{}}const $={status:"captured",type:p,subtype:c,confidence:g,reasoning:r,id:n,ref:`${s}:${n}`,needs_review:h,...t&&t.length>0?{advisory_conflicts:t}:{}};return q($,(w,x)=>{let S=`Captured as ${w.type}: ${w.subtype}
7
- Confidence: ${w.confidence}% | ${w.reasoning}
8
- ID: ${w.ref}`;w.needs_review&&(S+=`
9
- `+I(x.warn,"Stored for review -- run `wyrm_review` to activate"));const P=w.advisory_conflicts;return P&&P.length>0&&(S+=`
10
-
11
- `+I(x.warn,`Advisory: ${P.length} similar heuristic(s) found:`)+`
12
- `+P.map(l=>` ${x.bullet} [${l.id}] ${l.content}`).join(`
13
- `)),S})}},{name:"wyrm_remember",description:"Store a distilled knowledge artifact \u2014 proven patterns, lessons learned, anti-patterns, and reasoning traces. These are recalled automatically by wyrm_context_build to help AI models apply past knowledge to new tasks. Example: wyrm_remember({ projectPath: '/home/user/api', kind: 'anti_pattern', problem: 'Jest suite hung after adding the SSE server', validatedFix: 'close() the server in afterAll \u2014 its keep-alive timer held the event loop open', whyItWorked: 'open handles block jest exit', outcome: 'positive', tags: ['jest', 'sse'] })",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project this knowledge belongs to"},kind:{type:"string",enum:["reasoning_trace","lesson","pattern","anti_pattern","heuristic"],description:"reasoning_trace: a solved problem with steps; lesson: a general insight; pattern: a proven approach; anti_pattern: what NOT to do; heuristic: a rule of thumb"},problem:{type:"string",description:"What was being solved or observed (be specific and searchable)"},constraints:{type:"string",description:"What conditions or constraints applied"},validatedFix:{type:"string",description:"What actually worked \u2014 the validated solution or approach"},whyItWorked:{type:"string",description:"The insight behind WHY this worked (key for transfer learning)"},outcome:{type:"string",enum:["positive","negative","neutral"],description:"Was this approach successful?"},tags:{type:"array",items:{type:"string"},description:"Searchable tags (e.g. ['auth', 'rate-limit', 'typescript'])"},confidence:{type:"number",description:"Confidence level 0.0\u20131.0 (default: 1.0)"},sourceSessionId:{type:"number",description:"Session ID where this was discovered (optional)"}},required:["projectPath","kind","problem"]},outputSchema:{type:"object",properties:{id:{type:"integer"},kind:{type:"string",enum:["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]},problem:{type:"string"},validated_fix:{type:["string","null"]},why_it_worked:{type:["string","null"]},confidence:{type:"number"},tags:{type:["string","null"]}},required:["id","kind","problem","validated_fix","why_it_worked","confidence","tags"]},annotations:E.wyrm_remember,aliases:[],handler:async(j,{store:v,memory:b})=>{const{projectPath:u,kind:f,problem:_,constraints:a,validatedFix:m,whyItWorked:o,outcome:y,tags:i,confidence:d,sourceSessionId:p}=j,c=K("kind",f,["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]);if(c===void 0)throw new B("kind","is required");const g=v.getProject(u);if(!g)return C(R("wyrm_remember","projectPath","project not found"));const r={kind:c,problem:_,constraints:a,validatedFix:m,whyItWorked:o,outcome:y,tags:i,confidence:d,sourceSessionId:p},e=await D("artifact_add",g.id,r,()=>b.add(g.id,r)),n={id:e.id,kind:e.kind,problem:e.problem,validated_fix:e.validated_fix??null,why_it_worked:e.why_it_worked??null,confidence:e.confidence,tags:e.tags??null};return q(n,(s,h)=>{let t=I(h.brand,"**Memory Stored**")+`
14
-
15
- `;return t+=`${h.bullet} **Kind:** ${s.kind}
16
- `,t+=`${h.bullet} **ID:** ${s.id}
17
- `,t+=`${h.bullet} **Problem:** ${s.problem}
18
- `,s.validated_fix&&(t+=`${h.bullet} **Solution:** ${s.validated_fix}
19
- `),s.why_it_worked&&(t+=`${h.bullet} **Why it worked:** ${s.why_it_worked}
20
- `),t+=`${h.bullet} **Confidence:** ${(s.confidence*100).toFixed(0)}%
21
- `,s.tags&&(t+=`${h.bullet} **Tags:** ${s.tags}
22
- `),t+="\n_Use `wyrm_recall` to retrieve similar memories, or `wyrm_context_build` to assemble a task brief._",t})}},{name:"wyrm_auto_capture",description:"Auto-extract durable memories from freeform text (a session transcript, notes, a chat) into the REVIEW QUEUE. A LOCAL extractor \u2014 a configurable Ollama model (WYRM_EXTRACT_MODEL / the `model` arg) if set, else a deterministic heuristic \u2014 pulls out truths, failures, decisions, patterns, and lessons as needs_review candidates; approve/reject with wyrm_review (nothing auto-trusted). Closes the 'just talk, it remembers' gap without a cloud LLM. Deduped + idempotent. Example: wyrm_auto_capture({ projectPath: '/home/user/api', text: 'Deploy failed twice because wrangler.toml pointed at the old KV id; switched to the new binding and decided to pin binding names in CI.' })",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project to file the extracted candidates under"},text:{type:"string",description:"Freeform text to extract durable memories from"},model:{type:"string",description:"Optional Ollama model for extraction (overrides WYRM_EXTRACT_MODEL); omit for deterministic extraction"}},required:["projectPath","text"]},outputSchema:{type:"object",properties:{method:{type:"string"},model:{type:["string","null"]},added:{type:"integer"},skipped:{type:"integer"},candidates:{type:"array",items:{type:"object",properties:{kind:{type:"string"},text:{type:"string"}},required:["kind","text"]}}},required:["method","model","added","skipped","candidates"]},annotations:E.wyrm_auto_capture,aliases:[],handler:async(j,{store:v,raw:b,memory:u,cache:f})=>{const{projectPath:_,text:a,model:m}=j,o=v.getProject(_);if(!o)return C(R("wyrm_auto_capture","projectPath","project not found"));if(!a||a.trim().length<20)return C(R("wyrm_auto_capture","text","must be at least 20 characters"));const{candidates:y,method:i,model:d}=await W(a,{model:m}),p=b();let c=0,g=0;for(const e of y){const n=O(e),s=n.tags[n.tags.length-1];if(p.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(o.id,"%"+L(s)+"%")){g++;continue}u.add(o.id,{kind:n.kind,problem:n.problem,tags:n.tags,confidence:n.confidence,needsReview:1,createdBy:"auto-extract"}),c++}c>0&&f.invalidate();const r={method:i,model:d??null,added:c,skipped:g,candidates:y.slice(0,8).map(e=>({kind:e.kind,text:e.text.slice(0,80)}))};return q(r,(e,n)=>{const s=e.candidates.map(h=>` ${n.bullet} [${h.kind}] ${h.text}`).join(`
23
- `);return I(n.brand,`Auto-capture (${e.method}${e.model?` - ${e.model}`:""}) -- ${e.added} candidate(s) -> review queue, ${e.skipped} already present.`)+`
6
+ `).all(x,e);l.length>0&&(t=l.map(k=>({id:k.id,content:k.problem.slice(0,80)})))}catch{}}const $={status:"captured",type:p,subtype:c,confidence:g,reasoning:r,id:a,ref:`${s}:${a}`,needs_review:_,...t&&t.length>0?{advisory_conflicts:t}:{}};return S($,(f,P)=>{let q=`Captured as ${f.type}: ${f.subtype}
7
+ Confidence: ${f.confidence}% | ${f.reasoning}
8
+ ID: ${f.ref}`;f.needs_review&&(q+=`
9
+ `+I(P.warn,"Stored for review -- run `wyrm_review` to activate"));const x=f.advisory_conflicts;return x&&x.length>0&&(q+=`
10
+
11
+ `+I(P.warn,`Advisory: ${x.length} similar heuristic(s) found:`)+`
12
+ `+x.map(l=>` ${P.bullet} [${l.id}] ${l.content}`).join(`
13
+ `)),q})}},{name:"wyrm_remember",description:"Store a distilled knowledge artifact \u2014 proven patterns, lessons learned, anti-patterns, and reasoning traces. These are recalled automatically by wyrm_context_build to help AI models apply past knowledge to new tasks. Example: wyrm_remember({ projectPath: '/home/user/api', kind: 'anti_pattern', problem: 'Jest suite hung after adding the SSE server', validatedFix: 'close() the server in afterAll \u2014 its keep-alive timer held the event loop open', whyItWorked: 'open handles block jest exit', outcome: 'positive', tags: ['jest', 'sse'] })",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project this knowledge belongs to"},kind:{type:"string",enum:["reasoning_trace","lesson","pattern","anti_pattern","heuristic"],description:"reasoning_trace: a solved problem with steps; lesson: a general insight; pattern: a proven approach; anti_pattern: what NOT to do; heuristic: a rule of thumb"},problem:{type:"string",description:"What was being solved or observed (be specific and searchable)"},constraints:{type:"string",description:"What conditions or constraints applied"},validatedFix:{type:"string",description:"What actually worked \u2014 the validated solution or approach"},whyItWorked:{type:"string",description:"The insight behind WHY this worked (key for transfer learning)"},outcome:{type:"string",enum:["positive","negative","neutral"],description:"Was this approach successful?"},tags:{type:"array",items:{type:"string"},description:"Searchable tags (e.g. ['auth', 'rate-limit', 'typescript'])"},confidence:{type:"number",description:"Confidence level 0.0\u20131.0 (default: 1.0)"},sourceSessionId:{type:"number",description:"Session ID where this was discovered (optional)"}},required:["projectPath","kind","problem"]},outputSchema:{type:"object",properties:{id:{type:"integer"},kind:{type:"string",enum:["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]},problem:{type:"string"},validated_fix:{type:["string","null"]},why_it_worked:{type:["string","null"]},confidence:{type:"number"},tags:{type:["string","null"]}},required:["id","kind","problem","validated_fix","why_it_worked","confidence","tags"]},annotations:A.wyrm_remember,aliases:[],handler:async(j,{store:v,memory:b})=>{const{projectPath:u,kind:h,problem:w,constraints:n,validatedFix:m,whyItWorked:o,outcome:y,tags:i,confidence:d,sourceSessionId:p}=j,c=K("kind",h,["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]);if(c===void 0)throw new B("kind","is required");const g=v.getProject(u);if(!g)return E(T("wyrm_remember","projectPath","project not found"));const r={kind:c,problem:w,constraints:n,validatedFix:m,whyItWorked:o,outcome:y,tags:i,confidence:d,sourceSessionId:p},e=await D("artifact_add",g.id,r,()=>b.add(g.id,r)),a={id:e.id,kind:e.kind,problem:e.problem,validated_fix:e.validated_fix??null,why_it_worked:e.why_it_worked??null,confidence:e.confidence,tags:e.tags??null};return S(a,(s,_)=>{let t=I(_.brand,"**Memory Stored**")+`
14
+
15
+ `;return t+=`${_.bullet} **Kind:** ${s.kind}
16
+ `,t+=`${_.bullet} **ID:** ${s.id}
17
+ `,t+=`${_.bullet} **Problem:** ${s.problem}
18
+ `,s.validated_fix&&(t+=`${_.bullet} **Solution:** ${s.validated_fix}
19
+ `),s.why_it_worked&&(t+=`${_.bullet} **Why it worked:** ${s.why_it_worked}
20
+ `),t+=`${_.bullet} **Confidence:** ${(s.confidence*100).toFixed(0)}%
21
+ `,s.tags&&(t+=`${_.bullet} **Tags:** ${s.tags}
22
+ `),t+="\n_Use `wyrm_recall` to retrieve similar memories, or `wyrm_context_build` to assemble a task brief._",t})}},{name:"wyrm_auto_capture",description:"Auto-extract durable memories from freeform text (a session transcript, notes, a chat) into the REVIEW QUEUE. A LOCAL extractor \u2014 a configurable Ollama model (WYRM_EXTRACT_MODEL / the `model` arg) if set, else a deterministic heuristic \u2014 pulls out truths, failures, decisions, patterns, and lessons as needs_review candidates; approve/reject with wyrm_review (nothing auto-trusted). Closes the 'just talk, it remembers' gap without a cloud LLM. Deduped + idempotent. Example: wyrm_auto_capture({ projectPath: '/home/user/api', text: 'Deploy failed twice because wrangler.toml pointed at the old KV id; switched to the new binding and decided to pin binding names in CI.' })",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project to file the extracted candidates under"},text:{type:"string",description:"Freeform text to extract durable memories from"},model:{type:"string",description:"Optional Ollama model for extraction (overrides WYRM_EXTRACT_MODEL); omit for deterministic extraction"}},required:["projectPath","text"]},outputSchema:{type:"object",properties:{method:{type:"string"},model:{type:["string","null"]},added:{type:"integer"},skipped:{type:"integer"},candidates:{type:"array",items:{type:"object",properties:{kind:{type:"string"},text:{type:"string"}},required:["kind","text"]}}},required:["method","model","added","skipped","candidates"]},annotations:A.wyrm_auto_capture,aliases:[],handler:async(j,{store:v,raw:b,memory:u,cache:h})=>{const{projectPath:w,text:n,model:m}=j,o=v.getProject(w);if(!o)return E(T("wyrm_auto_capture","projectPath","project not found"));if(!n||n.trim().length<20)return E(T("wyrm_auto_capture","text","must be at least 20 characters"));const{candidates:y,method:i,model:d}=await W(n,{model:m}),p=b();let c=0,g=0;for(const e of y){const a=O(e),s=a.tags[a.tags.length-1];if(p.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(o.id,"%"+L(s)+"%")){g++;continue}u.add(o.id,{kind:a.kind,problem:a.problem,tags:a.tags,confidence:a.confidence,needsReview:1,createdBy:"auto-extract"}),c++}c>0&&h.invalidate();const r={method:i,model:d??null,added:c,skipped:g,candidates:y.slice(0,8).map(e=>({kind:e.kind,text:e.text.slice(0,80)}))};return S(r,(e,a)=>{const s=e.candidates.map(_=>` ${a.bullet} [${_.kind}] ${_.text}`).join(`
23
+ `);return I(a.brand,`Auto-capture (${e.method}${e.model?` - ${e.model}`:""}) -- ${e.added} candidate(s) -> review queue, ${e.skipped} already present.`)+`
24
24
  ${s}
25
25
 
26
- Approve/reject with wyrm_review.`})}},{name:"wyrm_capture_trace",description:"Harvest a harness's working trace into run-tagged review-queue candidates \u2014 OFFLINE. Ingests a Claude Code session transcript (JSONL), a ~/.dragon/traces file/dir, or WYRM_TRACE_TOOL_CALLS event output. The SAME local extractor as auto-capture (Ollama WYRM_EXTRACT_MODEL if set, else deterministic \u2014 never a cloud LLM) pulls durable truths/failures/decisions/patterns/lessons; secrets (API keys, tokens, passwords) are REDACTED before anything is stored; candidates land needs_review=1 stamped with the run_id (arg or ambient envelope). Approve/reject with wyrm_review; deduped + idempotent. Pass `trace` (inline text) OR `path` (a trace file or the ~/.dragon/traces dir). Reached via wyrm_capture({ mode: 'trace' }).",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project to file the candidates under"},trace:{type:"string",description:"Inline trace text (JSONL transcript / dragon records / tool-call events)"},path:{type:"string",description:"Path to a trace file, or the ~/.dragon/traces directory (newest file is read); omit ~ for absolute"},format:{type:"string",enum:["auto","claude-jsonl","dragon","tool-calls"],description:"Trace format (default auto-detect)"},run_id:{type:"string",description:"Tag candidates with this run (default: ambient envelope run_id)"},model:{type:"string",description:"Optional Ollama model for extraction (overrides WYRM_EXTRACT_MODEL); omit for deterministic"}},required:["projectPath"]},outputSchema:{type:"object",properties:{method:{type:"string"},model:{type:["string","null"]},format:{type:"string"},source:{type:"string"},run_id:{type:["string","null"]},segments:{type:"integer"},added:{type:"integer"},skipped:{type:"integer"},candidates:{type:"array",items:{type:"object",properties:{kind:{type:"string"},text:{type:"string"}},required:["kind","text"]}}},required:["method","model","format","source","run_id","segments","added","skipped","candidates"]},annotations:E.wyrm_capture_trace,aliases:[],handler:async(j,{store:v,raw:b,memory:u,cache:f})=>{const{projectPath:_,trace:a,path:m,format:o,run_id:y,model:i}=j,d=v.getProject(_);if(!d)return C(R("wyrm_capture_trace","projectPath","project not found"));const p=X(),c=typeof y=="string"&&y.trim()?y.trim().slice(0,64):p.run_id;let g="",r="inline";if(typeof a=="string"&&a.trim())g=a,r="inline";else if(typeof m=="string"&&m.trim()){let l=m.trim();(l==="~"||l.startsWith("~/"))&&(l=N(Z(),l.slice(1)));try{if(M(l).isDirectory()){const T=z(l).map(A=>N(l,A)).filter(A=>{try{return M(A).isFile()}catch{return!1}}).sort((A,U)=>M(U).mtimeMs-M(A).mtimeMs);if(T.length===0)return C(R("wyrm_capture_trace","path","no trace files in directory"));g=F(T[0],"utf-8"),r=T[0]}else g=F(l,"utf-8"),r=l}catch(k){return C(R("wyrm_capture_trace","path",`could not read trace path: ${k.message}`))}}else return C(R("wyrm_capture_trace","trace","provide inline trace or path to trace file"));const{segments:e,format:n}=Y(g,o??"auto"),s=Q(e);if(s.trim().length<20){const l={method:"deterministic",model:null,format:n,source:r,run_id:c,segments:e.length,added:0,skipped:0,candidates:[]};return q(l,(k,T)=>I(T.brand,`Trace harvest (${k.format}) -- no durable content extracted from ${k.segments} segment(s).`))}const{candidates:h,method:t,model:$}=await W(s,{model:i}),w=b();let x=0,S=0;for(const l of h){const k=O(l),T=k.tags[k.tags.length-1];if(w.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(d.id,"%"+L(T)+"%")){S++;continue}const A=c?[...k.tags,"trace",`run:${c}`]:[...k.tags,"trace"];G({agent_id:p.agent_id,run_id:c,source:c?"param":p.source},()=>u.add(d.id,{kind:k.kind,problem:k.problem,tags:A,confidence:k.confidence,needsReview:1,createdBy:"trace-harvest"})),x++}x>0&&f.invalidate();const P={method:t,model:$??null,format:n,source:r,run_id:c,segments:e.length,added:x,skipped:S,candidates:h.slice(0,8).map(l=>({kind:l.kind,text:l.text.slice(0,80)}))};return q(P,(l,k)=>{const T=l.candidates.map(A=>` ${k.bullet} [${A.kind}] ${A.text}`).join(`
27
- `);return I(k.brand,`Trace harvest (${l.format}, ${l.method}${l.model?` - ${l.model}`:""}) -- ${l.segments} segment(s) -> ${l.added} candidate(s) to review queue, ${l.skipped} already present${l.run_id?` [run:${l.run_id}]`:""}.`)+(T?`
28
- ${T}`:"")+`
26
+ Approve/reject with wyrm_review.`})}},{name:"wyrm_capture_trace",description:"Harvest a harness's working trace into run-tagged review-queue candidates \u2014 OFFLINE. Ingests a Claude Code session transcript (JSONL), a ~/.dragon/traces file/dir, or WYRM_TRACE_TOOL_CALLS event output. The SAME local extractor as auto-capture (Ollama WYRM_EXTRACT_MODEL if set, else deterministic \u2014 never a cloud LLM) pulls durable truths/failures/decisions/patterns/lessons; secrets (API keys, tokens, passwords) are REDACTED before anything is stored; candidates land needs_review=1 stamped with the run_id (arg or ambient envelope). Approve/reject with wyrm_review; deduped + idempotent. Pass `trace` (inline text) OR `path` (a trace file or the ~/.dragon/traces dir). Reached via wyrm_capture({ mode: 'trace' }).",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project to file the candidates under"},trace:{type:"string",description:"Inline trace text (JSONL transcript / dragon records / tool-call events)"},path:{type:"string",description:"Path to a trace file, or the ~/.dragon/traces directory (newest file is read); omit ~ for absolute"},format:{type:"string",enum:["auto","claude-jsonl","dragon","tool-calls"],description:"Trace format (default auto-detect)"},run_id:{type:"string",description:"Tag candidates with this run (default: ambient envelope run_id)"},model:{type:"string",description:"Optional Ollama model for extraction (overrides WYRM_EXTRACT_MODEL); omit for deterministic"}},required:["projectPath"]},outputSchema:{type:"object",properties:{method:{type:"string"},model:{type:["string","null"]},format:{type:"string"},source:{type:"string"},run_id:{type:["string","null"]},segments:{type:"integer"},added:{type:"integer"},skipped:{type:"integer"},candidates:{type:"array",items:{type:"object",properties:{kind:{type:"string"},text:{type:"string"}},required:["kind","text"]}}},required:["method","model","format","source","run_id","segments","added","skipped","candidates"]},annotations:A.wyrm_capture_trace,aliases:[],handler:async(j,{store:v,raw:b,memory:u,cache:h})=>{const{projectPath:w,trace:n,path:m,format:o,run_id:y,model:i}=j,d=v.getProject(w);if(!d)return E(T("wyrm_capture_trace","projectPath","project not found"));const p=X(),c=typeof y=="string"&&y.trim()?y.trim().slice(0,64):p.run_id;let g="",r="inline";if(typeof n=="string"&&n.trim())g=n,r="inline";else if(typeof m=="string"&&m.trim()){let l=m.trim();(l==="~"||l.startsWith("~/"))&&(l=N(Z(),l.slice(1)));try{if(M(l).isDirectory()){const C=z(l).map(R=>N(l,R)).filter(R=>{try{return M(R).isFile()}catch{return!1}}).sort((R,U)=>M(U).mtimeMs-M(R).mtimeMs);if(C.length===0)return E(T("wyrm_capture_trace","path","no trace files in directory"));g=F(C[0],"utf-8"),r=C[0]}else g=F(l,"utf-8"),r=l}catch(k){return E(T("wyrm_capture_trace","path",`could not read trace path: ${k.message}`))}}else return E(T("wyrm_capture_trace","trace","provide inline trace or path to trace file"));const{segments:e,format:a}=Y(g,o??"auto"),s=Q(e);if(s.trim().length<20){const l={method:"deterministic",model:null,format:a,source:r,run_id:c,segments:e.length,added:0,skipped:0,candidates:[]};return S(l,(k,C)=>I(C.brand,`Trace harvest (${k.format}) -- no durable content extracted from ${k.segments} segment(s).`))}const{candidates:_,method:t,model:$}=await W(s,{model:i}),f=b();let P=0,q=0;for(const l of _){const k=O(l),C=k.tags[k.tags.length-1];if(f.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(d.id,"%"+L(C)+"%")){q++;continue}const R=c?[...k.tags,"trace",`run:${c}`]:[...k.tags,"trace"];G({agent_id:p.agent_id,run_id:c,source:c?"param":p.source},()=>u.add(d.id,{kind:k.kind,problem:k.problem,tags:R,confidence:k.confidence,needsReview:1,createdBy:"trace-harvest"})),P++}P>0&&h.invalidate();const x={method:t,model:$??null,format:a,source:r,run_id:c,segments:e.length,added:P,skipped:q,candidates:_.slice(0,8).map(l=>({kind:l.kind,text:l.text.slice(0,80)}))};return S(x,(l,k)=>{const C=l.candidates.map(R=>` ${k.bullet} [${R.kind}] ${R.text}`).join(`
27
+ `);return I(k.brand,`Trace harvest (${l.format}, ${l.method}${l.model?` - ${l.model}`:""}) -- ${l.segments} segment(s) -> ${l.added} candidate(s) to review queue, ${l.skipped} already present${l.run_id?` [run:${l.run_id}]`:""}.`)+(C?`
28
+ ${C}`:"")+`
29
29
 
30
- Approve/reject with wyrm_review.`})}},{name:"wyrm_distill",description:"Distill a work session into candidate memory artifacts for review. Parses the session's objectives, decisions, and outcomes into structured artifacts (lessons, patterns, anti-patterns) and queues them for approval via wyrm_review. Use at session end to extract institutional knowledge.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root path"},sessionId:{type:"string",description:"Session ID to distill"},candidates:{type:"array",description:"Pre-parsed candidate artifacts to store for review",items:{type:"object",properties:{kind:{type:"string",enum:["lesson","pattern","anti_pattern","heuristic","reasoning_trace"]},title:{type:"string"},content:{type:"string"},tags:{type:"array",items:{type:"string"}},confidence:{type:"number"}},required:["kind","title","content"]}}},required:["projectPath","candidates"]},outputSchema:{type:"object",properties:{count:{type:"integer"},artifacts:{type:"array",items:{type:"object",properties:{id:{type:"integer"},kind:{type:"string"},title:{type:"string"}},required:["id","kind","title"]}}},required:["count","artifacts"]},annotations:E.wyrm_distill,aliases:[],handler:(j,{store:v,memory:b})=>{const{projectPath:u,candidates:f}=j,_=v.getProject(u);if(!_)return{content:[{type:"text",text:`Project not found: ${u}`}],isError:!0};if(!f||f.length===0)return{content:[{type:"text",text:`**Distill**
30
+ Approve/reject with wyrm_review.`})}},{name:"wyrm_distill",description:"Distill a work session into candidate memory artifacts for review. Parses the session's objectives, decisions, and outcomes into structured artifacts (lessons, patterns, anti-patterns) and queues them for approval via wyrm_review. Use at session end to extract institutional knowledge.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root path"},sessionId:{type:"string",description:"Session ID to distill"},candidates:{type:"array",description:"Pre-parsed candidate artifacts to store for review",items:{type:"object",properties:{kind:{type:"string",enum:["lesson","pattern","anti_pattern","heuristic","reasoning_trace"]},title:{type:"string"},content:{type:"string"},tags:{type:"array",items:{type:"string"}},confidence:{type:"number"}},required:["kind","title","content"]}}},required:["projectPath","candidates"]},outputSchema:{type:"object",properties:{count:{type:"integer"},artifacts:{type:"array",items:{type:"object",properties:{id:{type:"integer"},kind:{type:"string"},title:{type:"string"}},required:["id","kind","title"]}}},required:["count","artifacts"]},annotations:A.wyrm_distill,aliases:[],handler:(j,{store:v,memory:b})=>{const{projectPath:u,candidates:h}=j,w=v.getProject(u);if(!w)return{content:[{type:"text",text:`Project not found: ${u}`}],isError:!0};if(!h||h.length===0)return{content:[{type:"text",text:`**Distill**
31
31
 
32
- No candidates provided. Provide an array of candidate artifacts to distill.`}],isError:!0};const a=[];for(const o of f){const y=b.add(_.id,{kind:o.kind,problem:o.title,validatedFix:o.content,tags:o.tags??[],confidence:o.confidence??.7,needsReview:1});a.push({id:y.id,kind:o.kind,title:o.title})}const m={count:a.length,artifacts:a};return q(m,(o,y)=>{let i=I(y.brand,`**Distillation Complete** -- ${o.count} artifact${o.count!==1?"s":""} queued for review`)+`
32
+ No candidates provided. Provide an array of candidate artifacts to distill.`}],isError:!0};const n=[];for(const o of h){const y=b.add(w.id,{kind:o.kind,problem:o.title,validatedFix:o.content,tags:o.tags??[],confidence:o.confidence??.7,needsReview:1});n.push({id:y.id,kind:o.kind,title:o.title})}const m={count:n.length,artifacts:n};return S(m,(o,y)=>{let i=I(y.brand,`**Distillation Complete** -- ${o.count} artifact${o.count!==1?"s":""} queued for review`)+`
33
33
 
34
34
  `;return i+=o.artifacts.map(d=>`${y.bullet} [#${d.id}] **${d.kind}**: ${d.title}`).join(`
35
- `),i+="\n\nUse `wyrm_review` with each ID to approve or reject.",i})}},{name:"wyrm_harvest",description:"Auto-populate memory from artifacts you already produce. Walks a project (or ALL registered projects) and harvests durable facts from its docs (README/CLAUDE/AGENTS/ARCHITECTURE) plus recent commit subjects (git log) into the REVIEW QUEUE \u2014 approve/reject with wyrm_review, nothing is auto-trusted. Idempotent (re-runs skip what's already harvested). Use dryRun to preview. The fix for a thin corpus.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Harvest one project; omit to harvest ALL registered projects"},dryRun:{type:"boolean",description:"Preview what would be harvested without writing anything"},gitLimit:{type:"number",description:"How many recent commits to scan per project (default 30, max 200)"},includeCode:{type:"boolean",description:"Also harvest CODE: tech-stack facts from manifests (package.json/Cargo.toml/\u2026) + TODO/FIXME markers into the review queue, AND index code symbols (functions/classes/types) for search. Heavier \u2014 scope to one project for the full code pass."}}},outputSchema:{type:"object",properties:{dry_run:{type:"boolean"},projects_scanned:{type:"integer"},added:{type:"integer"},skipped:{type:"integer"},top:{type:"array",items:{type:"object",properties:{project:{type:"string"},added:{type:"integer"},skipped:{type:"integer"}},required:["project","added","skipped"]}},sample:{type:"array",items:{type:"string"}},code_symbols:{type:["object","null"],properties:{symbols:{type:"integer"},projects:{type:"integer"},files:{type:"integer"}},required:["symbols","projects","files"]}},required:["dry_run","projects_scanned","added","skipped","top","sample","code_symbols"]},annotations:E.wyrm_harvest,aliases:[],handler:(j,{store:v,raw:b,memory:u,symbols:f,cache:_})=>{const{projectPath:a,dryRun:m,gitLimit:o,includeCode:y}=j,i=b(),d={existsBySig:(t,$)=>!!i.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(t,"%"+L($)+"%"),addCandidate:(t,$)=>{u.add(t,{kind:$.kind,problem:$.text,tags:[...$.tags,$.sig],confidence:$.confidence,needsReview:1,createdBy:"harvest"})}};let p;if(a){const t=v.getProject(a);if(!t)return{content:[{type:"text",text:"Project not found"}],isError:!0};p=[{id:t.id,name:t.name,path:t.path}]}else p=v.getAllProjects(500).map(t=>({id:t.id,name:t.name,path:t.path}));const{reports:c,totalAdded:g,totalSkipped:r}=V(d,p,{dryRun:m,gitLimit:o,includeCode:y});!m&&g>0&&_.invalidate();let e=null;if(y&&!m){let t=0,$=0,w=0;for(const x of p)try{const S=f.indexProject(x.id,x.path);t+=S.files,$+=S.symbols,w++}catch{}e={symbols:$,projects:w,files:t}}const n=c.filter(t=>t.added>0).sort((t,$)=>$.added-t.added).slice(0,15).map(t=>({project:t.project,added:t.added,skipped:t.skipped})),s=c.flatMap(t=>t.sample??[]).slice(0,6),h={dry_run:!!m,projects_scanned:p.length,added:g,skipped:r,top:n,sample:s,code_symbols:e};return q(h,(t,$)=>{const w=t.code_symbols?`
36
- Indexed ${t.code_symbols.symbols} code symbols across ${t.code_symbols.projects} project(s) (${t.code_symbols.files} files) -> searchable via wyrm_symbol_search.`:"",x=t.top.map(P=>` +${String(P.added).padStart(3)} (skip ${P.skipped}) ${P.project}`).join(`
37
- `),S=t.sample.map(P=>` ${$.bullet} ${P}`).join(`
38
- `);return I($.brand,`Harvest ${t.dry_run?"(dry run) ":""}-- ${t.added} candidate(s) -> review queue across ${t.projects_scanned} project(s); ${t.skipped} already present.`)+`${w}
39
- ${x}`+(S?`
35
+ `),i+="\n\nUse `wyrm_review` with each ID to approve or reject.",i})}},{name:"wyrm_harvest",description:"Auto-populate memory from artifacts you already produce. Walks a project (or ALL registered projects) and harvests durable facts from its docs (README/CLAUDE/AGENTS/ARCHITECTURE) plus recent commit subjects (git log) into the REVIEW QUEUE \u2014 approve/reject with wyrm_review, nothing is auto-trusted. Idempotent (re-runs skip what's already harvested). Use dryRun to preview. The fix for a thin corpus.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Harvest one project; omit to harvest ALL registered projects"},dryRun:{type:"boolean",description:"Preview what would be harvested without writing anything"},gitLimit:{type:"number",description:"How many recent commits to scan per project (default 30, max 200)"},includeCode:{type:"boolean",description:"Also harvest CODE: tech-stack facts from manifests (package.json/Cargo.toml/\u2026) + TODO/FIXME markers into the review queue, AND index code symbols (functions/classes/types) for search. Heavier \u2014 scope to one project for the full code pass."}}},outputSchema:{type:"object",properties:{dry_run:{type:"boolean"},projects_scanned:{type:"integer"},added:{type:"integer"},skipped:{type:"integer"},top:{type:"array",items:{type:"object",properties:{project:{type:"string"},added:{type:"integer"},skipped:{type:"integer"}},required:["project","added","skipped"]}},sample:{type:"array",items:{type:"string"}},code_symbols:{type:["object","null"],properties:{symbols:{type:"integer"},projects:{type:"integer"},files:{type:"integer"}},required:["symbols","projects","files"]}},required:["dry_run","projects_scanned","added","skipped","top","sample","code_symbols"]},annotations:A.wyrm_harvest,aliases:[],handler:(j,{store:v,raw:b,memory:u,symbols:h,cache:w})=>{const{projectPath:n,dryRun:m,gitLimit:o,includeCode:y}=j,i=b(),d={existsBySig:(t,$)=>!!i.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(t,"%"+L($)+"%"),addCandidate:(t,$)=>{u.add(t,{kind:$.kind,problem:$.text,tags:[...$.tags,$.sig],confidence:$.confidence,needsReview:1,createdBy:"harvest"})}};let p;if(n){const t=v.getProject(n);if(!t)return{content:[{type:"text",text:"Project not found"}],isError:!0};p=[{id:t.id,name:t.name,path:t.path}]}else p=v.getAllProjects(500).map(t=>({id:t.id,name:t.name,path:t.path}));const{reports:c,totalAdded:g,totalSkipped:r}=V(d,p,{dryRun:m,gitLimit:o,includeCode:y});!m&&g>0&&w.invalidate();let e=null;if(y&&!m){let t=0,$=0,f=0;for(const P of p)try{const q=h.indexProject(P.id,P.path);t+=q.files,$+=q.symbols,f++}catch{}e={symbols:$,projects:f,files:t}}const a=c.filter(t=>t.added>0).sort((t,$)=>$.added-t.added).slice(0,15).map(t=>({project:t.project,added:t.added,skipped:t.skipped})),s=c.flatMap(t=>t.sample??[]).slice(0,6),_={dry_run:!!m,projects_scanned:p.length,added:g,skipped:r,top:a,sample:s,code_symbols:e};return S(_,(t,$)=>{const f=t.code_symbols?`
36
+ Indexed ${t.code_symbols.symbols} code symbols across ${t.code_symbols.projects} project(s) (${t.code_symbols.files} files) -> searchable via wyrm_symbol_search.`:"",P=t.top.map(x=>` +${String(x.added).padStart(3)} (skip ${x.skipped}) ${x.project}`).join(`
37
+ `),q=t.sample.map(x=>` ${$.bullet} ${x}`).join(`
38
+ `);return I($.brand,`Harvest ${t.dry_run?"(dry run) ":""}-- ${t.added} candidate(s) -> review queue across ${t.projects_scanned} project(s); ${t.skipped} already present.`)+`${f}
39
+ ${P}`+(q?`
40
40
 
41
41
  Sample:
42
- ${S}`:"")+`
42
+ ${q}`:"")+`
43
43
 
44
- Approve/reject with wyrm_review.`})}},{name:"wyrm_import_git",description:"Import a list of commits into the Wyrm memory review queue. Useful for onboarding a project's history or capturing recent work.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},commits:{type:"array",description:"Array of commit objects",items:{type:"object",properties:{message:{type:"string"},diff_summary:{type:"string"},author:{type:"string"},date:{type:"string"}},required:["message"]}},auto_approve:{type:"boolean",description:"Skip review queue and activate immediately (default: false)"}},required:["project_id","commits"]},outputSchema:{type:"object",properties:{captured:{type:"integer"},skipped:{type:"integer"},auto_approved:{type:"boolean"}},required:["captured","skipped","auto_approved"]},annotations:E.wyrm_import_git,aliases:[],handler:(j,{store:v,memory:b})=>{const{project_id:u,commits:f,auto_approve:_}=j;if(!v.getProjectById(u))return{content:[{type:"text",text:`Project ID ${u} not found.`}],isError:!0};let m=0,o=0;for(const i of f){const d=i.message??"";if(/^Merge /i.test(d)){o++;continue}if(/^(chore|bump|release|version)/i.test(d)){o++;continue}let p="pattern";/^fix(\(.+\))?:/i.test(d)?p="lesson":/^feat(\(.+\))?:/i.test(d)?p="pattern":/^refactor(\(.+\))?:/i.test(d)&&(p="heuristic");const c=d.split(":")[0]??"commit";b.add(u,{kind:p,problem:d,validatedFix:i.diff_summary??"",whyItWorked:`Committed by ${i.author??"unknown"} on ${i.date??"unknown"}`,tags:["git","commit",c.toLowerCase()],confidence:.6,needsReview:_?0:1}),m++}return q({captured:m,skipped:o,auto_approved:!!_},(i,d)=>I(d.brand,"**Git Import Complete**")+`
44
+ Approve/reject with wyrm_review.`})}},{name:"wyrm_import_git",description:"Import a list of commits into the Wyrm memory review queue. Useful for onboarding a project's history or capturing recent work.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},commits:{type:"array",description:"Array of commit objects",items:{type:"object",properties:{message:{type:"string"},diff_summary:{type:"string"},author:{type:"string"},date:{type:"string"}},required:["message"]}},auto_approve:{type:"boolean",description:"Skip review queue and activate immediately (default: false)"}},required:["project_id","commits"]},outputSchema:{type:"object",properties:{captured:{type:"integer"},skipped:{type:"integer"},auto_approved:{type:"boolean"}},required:["captured","skipped","auto_approved"]},annotations:A.wyrm_import_git,aliases:[],handler:(j,{store:v,memory:b})=>{const{project_id:u,commits:h,auto_approve:w}=j;if(!v.getProjectById(u))return{content:[{type:"text",text:`Project ID ${u} not found.`}],isError:!0};let m=0,o=0;for(const i of h){const d=i.message??"";if(/^Merge /i.test(d)){o++;continue}if(/^(chore|bump|release|version)/i.test(d)){o++;continue}let p="pattern";/^fix(\(.+\))?:/i.test(d)?p="lesson":/^feat(\(.+\))?:/i.test(d)?p="pattern":/^refactor(\(.+\))?:/i.test(d)&&(p="heuristic");const c=d.split(":")[0]??"commit";b.add(u,{kind:p,problem:d,validatedFix:i.diff_summary??"",whyItWorked:`Committed by ${i.author??"unknown"} on ${i.date??"unknown"}`,tags:["git","commit",c.toLowerCase()],confidence:.6,needsReview:w?0:1}),m++}return S({captured:m,skipped:o,auto_approved:!!w},(i,d)=>I(d.brand,"**Git Import Complete**")+`
45
45
 
46
46
  ${d.bullet} **Captured:** ${i.captured}
47
47
  ${d.bullet} **Skipped:** ${i.skipped} (merges/chores)
48
- ${d.bullet} **Review needed:** ${i.auto_approved?"No (auto-approved)":`Yes -- run \`wyrm_review\` to activate ${i.captured} artifact${i.captured!==1?"s":""}`}`)}},{name:"wyrm_import_pr",description:"Import a pull request (title, body, review comments) into the Wyrm memory review queue to extract patterns and heuristics.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description / body"},review_comments:{type:"array",items:{type:"string"},description:"Review comment strings"},auto_approve:{type:"boolean",description:"Skip review queue (default: false)"}},required:["project_id","title","body"]},outputSchema:{type:"object",properties:{created:{type:"integer"},auto_approved:{type:"boolean"}},required:["created","auto_approved"]},annotations:E.wyrm_import_pr,aliases:[],handler:(j,{store:v,memory:b})=>{const{project_id:u,title:f,body:_,review_comments:a,auto_approve:m}=j;if(!v.getProjectById(u))return{content:[{type:"text",text:`Project ID ${u} not found.`}],isError:!0};let y=0;const i=m?0:1;b.add(u,{kind:"pattern",problem:`${f}
48
+ ${d.bullet} **Review needed:** ${i.auto_approved?"No (auto-approved)":`Yes -- run \`wyrm_review\` to activate ${i.captured} artifact${i.captured!==1?"s":""}`}`)}},{name:"wyrm_import_pr",description:"Import a pull request (title, body, review comments) into the Wyrm memory review queue to extract patterns and heuristics.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description / body"},review_comments:{type:"array",items:{type:"string"},description:"Review comment strings"},auto_approve:{type:"boolean",description:"Skip review queue (default: false)"}},required:["project_id","title","body"]},outputSchema:{type:"object",properties:{created:{type:"integer"},auto_approved:{type:"boolean"}},required:["created","auto_approved"]},annotations:A.wyrm_import_pr,aliases:[],handler:(j,{store:v,memory:b})=>{const{project_id:u,title:h,body:w,review_comments:n,auto_approve:m}=j;if(!v.getProjectById(u))return{content:[{type:"text",text:`Project ID ${u} not found.`}],isError:!0};let y=0;const i=m?0:1;b.add(u,{kind:"pattern",problem:`${h}
49
49
 
50
- ${_}`,validatedFix:"",whyItWorked:"",tags:["git","pr"],confidence:.65,needsReview:i}),y++;for(const p of a??[])/\b(should|must|always|never|prefer|avoid|use|don't)\b/i.test(p)&&(b.add(u,{kind:"heuristic",problem:p,validatedFix:"",whyItWorked:"",tags:["git","pr","review"],confidence:.65,needsReview:i}),y++);return q({created:y,auto_approved:!!m},(p,c)=>I(c.brand,"**PR Import Complete**")+`
50
+ ${w}`,validatedFix:"",whyItWorked:"",tags:["git","pr"],confidence:.65,needsReview:i}),y++;for(const p of n??[])/\b(should|must|always|never|prefer|avoid|use|don't)\b/i.test(p)&&(b.add(u,{kind:"heuristic",problem:p,validatedFix:"",whyItWorked:"",tags:["git","pr","review"],confidence:.65,needsReview:i}),y++);return S({created:y,auto_approved:!!m},(p,c)=>I(c.brand,"**PR Import Complete**")+`
51
51
 
52
52
  ${c.bullet} **Artifacts created:** ${p.created}
53
- ${c.bullet} **Review needed:** ${p.auto_approved?"No (auto-approved)":"Yes -- run `wyrm_review` to activate"}`)}},{name:"wyrm_import_rules",description:"Import a .cursorrules / copilot-instructions file into Wyrm. Parses by section and creates ground truths (for constraint/rule language) or memory artifacts (for general guidelines).",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},content:{type:"string",description:"Full text of the rules file"},format:{type:"string",enum:["cursorrules","copilot","plain"],description:"Source format (default: plain)"},source_file:{type:"string",description:"Filename for provenance (optional)"}},required:["project_id","content"]},outputSchema:{type:"object",properties:{format:{type:"string"},source:{type:"string"},truths_created:{type:"integer"},artifacts_created:{type:"integer"}},required:["format","source","truths_created","artifacts_created"]},annotations:E.wyrm_import_rules,aliases:[],handler:(j,{store:v,memory:b,truths:u})=>{const{project_id:f,content:_,format:a,source_file:m}=j;if(!v.getProjectById(f))return{content:[{type:"text",text:`Project ID ${f} not found.`}],isError:!0};const y=a??"plain",i=m??"rules",d=["imported",y,i],p=_.split(/\n(?=#)/),c=_.split(/\n\n+/),g=(p.length>=c.length?p:c).map(s=>s.trim()).filter(s=>s.length>=15);let r=0,e=0;for(const s of g)/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(s)?(u.set(f,{category:"constraint",key:s.slice(0,50).replace(/\n/g," "),value:s,source:i}),r++):(b.add(f,{kind:"heuristic",problem:s,validatedFix:"",whyItWorked:"",tags:d,confidence:.7,needsReview:1}),e++);return q({format:y,source:i,truths_created:r,artifacts_created:e},(s,h)=>I(h.brand,`**Rules Import Complete** (${s.format})`)+`
53
+ ${c.bullet} **Review needed:** ${p.auto_approved?"No (auto-approved)":"Yes -- run `wyrm_review` to activate"}`)}},{name:"wyrm_import_rules",description:"Import a .cursorrules / copilot-instructions file into Wyrm. Parses by section and creates ground truths (for constraint/rule language) or memory artifacts (for general guidelines).",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},content:{type:"string",description:"Full text of the rules file"},format:{type:"string",enum:["cursorrules","copilot","plain"],description:"Source format (default: plain)"},source_file:{type:"string",description:"Filename for provenance (optional)"}},required:["project_id","content"]},outputSchema:{type:"object",properties:{format:{type:"string"},source:{type:"string"},truths_created:{type:"integer"},artifacts_created:{type:"integer"}},required:["format","source","truths_created","artifacts_created"]},annotations:A.wyrm_import_rules,aliases:[],handler:(j,{store:v,memory:b,truths:u})=>{const{project_id:h,content:w,format:n,source_file:m}=j;if(!v.getProjectById(h))return{content:[{type:"text",text:`Project ID ${h} not found.`}],isError:!0};const y=n??"plain",i=m??"rules",d=["imported",y,i],p=w.split(/\n(?=#)/),c=w.split(/\n\n+/),g=(p.length>=c.length?p:c).map(s=>s.trim()).filter(s=>s.length>=15);let r=0,e=0;for(const s of g)/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(s)?(u.set(h,{category:"constraint",key:s.slice(0,50).replace(/\n/g," "),value:s,source:i}),r++):(b.add(h,{kind:"heuristic",problem:s,validatedFix:"",whyItWorked:"",tags:d,confidence:.7,needsReview:1}),e++);return S({format:y,source:i,truths_created:r,artifacts_created:e},(s,_)=>I(_.brand,`**Rules Import Complete** (${s.format})`)+`
54
54
 
55
- ${h.bullet} **Ground truths created:** ${s.truths_created} (active immediately)
56
- ${h.bullet} **Memory artifacts created:** ${s.artifacts_created} (pending review)
57
- ${h.bullet} **Source:** ${s.source}
55
+ ${_.bullet} **Ground truths created:** ${s.truths_created} (active immediately)
56
+ ${_.bullet} **Memory artifacts created:** ${s.artifacts_created} (pending review)
57
+ ${_.bullet} **Source:** ${s.source}
58
58
 
59
- Run \`wyrm_review\` to approve the memory artifacts.`)}},{name:"wyrm_spec_register",description:"Make spec-kit Wyrm-native. Reads a spec directory (spec.md title/summary + tasks.md task list) and creates one Wyrm quest per task, linked to a project, with a stored spec\u2192project link. Idempotent \u2014 re-running updates the same quests (deduped by a per-spec-task signature) instead of duplicating.",inputSchema:{type:"object",properties:{specDir:{type:"string",description:"Absolute path to the spec directory (e.g. '.../dragon-platform/specs/001-ghostmesh')"},projectPath:{type:"string",description:"Path of the Wyrm project to attach the spec + quests to (must already be registered)"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Priority for the generated quests (default 'medium')"}},required:["specDir","projectPath"]},outputSchema:{type:"object",properties:{spec_dir:{type:"string"},title:{type:["string","null"]},project:{type:"string"},tasks_parsed:{type:"integer"},quests_created:{type:"integer"},quests_updated:{type:"integer"},quest_ids:{type:"array",items:{type:"integer"}}},required:["spec_dir","title","project","tasks_parsed","quests_created","quests_updated","quest_ids"]},annotations:E.wyrm_spec_register,aliases:[],handler:(j,{store:v,indexing:b})=>{const{specDir:u,projectPath:f,priority:_}=j,a=["specDir","projectPath"].filter(r=>{const e=j[r];return!e&&e!==0&&e!==!1});if(a.length>0)return{content:[{type:"text",text:`Missing required arguments: ${a.join(", ")}`}],isError:!0};const m=v.getProject(f);if(!m)return{content:[{type:"text",text:`**Spec Register**: Project not found at "${f}". Register it first (wyrm_scan_projects / wyrm_session_start).`}],isError:!0};const o=ee(u);if(o.tasks.length===0){const r={spec_dir:u,title:o.title??null,project:m.name,tasks_parsed:0,quests_created:0,quests_updated:0,quest_ids:[]};return q(r,(e,n)=>I(n.brand,`**Spec Register**: No tasks found in ${H(e.spec_dir,"tasks.md")}. Nothing to create.`))}const y=_||"medium";let i=0,d=0;const p=[];for(const r of o.tasks){const e=te(u,r.id),n=`${r.id}: ${r.title}`,s=e,h=v.findQuestBySpecSignature(m.id,e);if(h)v.updateQuestFields(h.id,{title:n,tags:s}),p.push(h.id),d++;else{const t=v.addQuest(m.id,n,`spec-kit task from ${u}`,y,s);b()?.enqueue("quest",t.id,m.id),p.push(t.id),i++}}const c=v.upsertSpec(m.id,u,o.title,o.summary,o.tasks.length),g={spec_dir:c.spec_dir,title:c.title??null,project:m.name,tasks_parsed:o.tasks.length,quests_created:i,quests_updated:d,quest_ids:p};return q(g,(r,e)=>{let n=I(e.brand,"**Spec Registered**")+`
59
+ Run \`wyrm_review\` to approve the memory artifacts.`)}},{name:"wyrm_spec_register",description:"Make spec-kit Wyrm-native. Reads a spec directory (spec.md title/summary + tasks.md task list) and creates one Wyrm quest per task, linked to a project, with a stored spec\u2192project link. Idempotent \u2014 re-running updates the same quests (deduped by a per-spec-task signature) instead of duplicating.",inputSchema:{type:"object",properties:{specDir:{type:"string",description:"Absolute path to the spec directory (e.g. '.../dragon-platform/specs/001-ghostmesh')"},projectPath:{type:"string",description:"Path of the Wyrm project to attach the spec + quests to (must already be registered)"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Priority for the generated quests (default 'medium')"}},required:["specDir","projectPath"]},outputSchema:{type:"object",properties:{spec_dir:{type:"string"},title:{type:["string","null"]},project:{type:"string"},tasks_parsed:{type:"integer"},quests_created:{type:"integer"},quests_updated:{type:"integer"},quest_ids:{type:"array",items:{type:"integer"}}},required:["spec_dir","title","project","tasks_parsed","quests_created","quests_updated","quest_ids"]},annotations:A.wyrm_spec_register,aliases:[],handler:(j,{store:v,indexing:b})=>{const{specDir:u,projectPath:h,priority:w}=j,n=["specDir","projectPath"].filter(r=>{const e=j[r];return!e&&e!==0&&e!==!1});if(n.length>0)return{content:[{type:"text",text:`Missing required arguments: ${n.join(", ")}`}],isError:!0};const m=v.getProject(h);if(!m)return{content:[{type:"text",text:`**Spec Register**: Project not found at "${h}". Register it first (wyrm_scan_projects / wyrm_session_start).`}],isError:!0};const o=ee(u);if(o.tasks.length===0){const r={spec_dir:u,title:o.title??null,project:m.name,tasks_parsed:0,quests_created:0,quests_updated:0,quest_ids:[]};return S(r,(e,a)=>I(a.brand,`**Spec Register**: No tasks found in ${H(e.spec_dir,"tasks.md")}. Nothing to create.`))}const y=w||"medium";let i=0,d=0;const p=[];for(const r of o.tasks){const e=te(u,r.id),a=`${r.id}: ${r.title}`,s=e,_=v.findQuestBySpecSignature(m.id,e);if(_)v.updateQuestFields(_.id,{title:a,tags:s}),p.push(_.id),d++;else{const t=v.addQuest(m.id,a,`spec-kit task from ${u}`,y,s);b()?.enqueue("quest",t.id,m.id),p.push(t.id),i++}}const c=v.upsertSpec(m.id,u,o.title,o.summary,o.tasks.length),g={spec_dir:c.spec_dir,title:c.title??null,project:m.name,tasks_parsed:o.tasks.length,quests_created:i,quests_updated:d,quest_ids:p};return S(g,(r,e)=>{let a=I(e.brand,"**Spec Registered**")+`
60
60
 
61
- `;return n+=`Spec: ${r.title||"(untitled)"}
62
- `,c.summary&&(n+=`Summary: ${c.summary}
63
- `),n+=`Dir: ${r.spec_dir}
64
- `,n+=`Project: ${r.project}
65
- `,n+=`Tasks parsed: ${r.tasks_parsed}
66
- `,n+=`Quests created: ${r.quests_created} - updated: ${r.quests_updated}
67
- `,n+=`
61
+ `;return a+=`Spec: ${r.title||"(untitled)"}
62
+ `,c.summary&&(a+=`Summary: ${c.summary}
63
+ `),a+=`Dir: ${r.spec_dir}
64
+ `,a+=`Project: ${r.project}
65
+ `,a+=`Tasks parsed: ${r.tasks_parsed}
66
+ `,a+=`Quests created: ${r.quests_created} - updated: ${r.quests_updated}
67
+ `,a+=`
68
68
  \`\`\`json
69
69
  ${JSON.stringify({spec:r.spec_dir,title:r.title,project:r.project,tasksParsed:r.tasks_parsed,questsCreated:r.quests_created,questsUpdated:r.quests_updated,questIds:r.quest_ids},null,2)}
70
- \`\`\``,n})}},{name:"wyrm_scaffold_save",description:"Save a reasoning scaffold \u2014 a structured checklist that guides step-by-step thinking for a specific problem type. Scaffolds are automatically surfaced by wyrm_context_build when the task matches, helping AI models apply proven reasoning patterns.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project path (optional, null for global scaffolds)"},problemType:{type:"string",description:"Short slug for the problem type (e.g. 'api-design', 'security-review', 'db-migration')"},description:{type:"string",description:"What kind of task this scaffold helps with"},whenToUse:{type:"string",description:"Conditions that indicate this scaffold should be applied"},steps:{type:"array",items:{type:"string"},description:"Ordered checklist steps to follow"},verificationSteps:{type:"array",items:{type:"string"},description:"Steps to verify the work is correct"},doNotApplyIf:{type:"string",description:"Conditions where this scaffold does NOT apply"},tags:{type:"array",items:{type:"string"},description:"Searchable tags"}},required:["problemType","description","whenToUse","steps"]},outputSchema:{type:"object",properties:{id:{type:"integer"},problem_type:{type:"string"},description:{type:"string"},steps:{type:"integer"}},required:["id","problem_type","description","steps"]},annotations:E.wyrm_scaffold_save,aliases:[],handler:(j,{store:v,scaffolds:b,cache:u})=>{const{projectPath:f,problemType:_,description:a,whenToUse:m,steps:o,verificationSteps:y,doNotApplyIf:i,tags:d}=j,p=f?v.getProject(f)?.id??void 0:void 0,c=b.save({projectId:p,problemType:_,description:a,whenToUse:m,steps:o,verificationSteps:y??void 0,doNotApplyIf:i?[i]:void 0,tags:d??[]});u.invalidate("wyrm_scaffold_get"),u.invalidate("wyrm_context_build");const g={id:c.id,problem_type:_,description:a,steps:o.length};return q(g,(r,e)=>I(e.brand,"**Reasoning Scaffold Saved**")+`
70
+ \`\`\``,a})}},{name:"wyrm_scaffold_save",description:"Save a reasoning scaffold \u2014 a structured checklist that guides step-by-step thinking for a specific problem type. Scaffolds are automatically surfaced by wyrm_context_build when the task matches, helping AI models apply proven reasoning patterns.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project path (optional, null for global scaffolds)"},problemType:{type:"string",description:"Short slug for the problem type (e.g. 'api-design', 'security-review', 'db-migration')"},description:{type:"string",description:"What kind of task this scaffold helps with"},whenToUse:{type:"string",description:"Conditions that indicate this scaffold should be applied"},steps:{type:"array",items:{type:"string"},description:"Ordered checklist steps to follow"},verificationSteps:{type:"array",items:{type:"string"},description:"Steps to verify the work is correct"},doNotApplyIf:{type:"string",description:"Conditions where this scaffold does NOT apply"},tags:{type:"array",items:{type:"string"},description:"Searchable tags"}},required:["problemType","description","whenToUse","steps"]},outputSchema:{type:"object",properties:{id:{type:"integer"},problem_type:{type:"string"},description:{type:"string"},steps:{type:"integer"}},required:["id","problem_type","description","steps"]},annotations:A.wyrm_scaffold_save,aliases:[],handler:(j,{store:v,scaffolds:b,cache:u})=>{const{projectPath:h,problemType:w,description:n,whenToUse:m,steps:o,verificationSteps:y,doNotApplyIf:i,tags:d}=j,p=h?v.getProject(h)?.id??void 0:void 0,c=b.save({projectId:p,problemType:w,description:n,whenToUse:m,steps:o,verificationSteps:y??void 0,doNotApplyIf:i?[i]:void 0,tags:d??[]});u.invalidate("wyrm_scaffold_get"),u.invalidate("wyrm_context_build");const g={id:c.id,problem_type:w,description:n,steps:o.length};return S(g,(r,e)=>I(e.brand,"**Reasoning Scaffold Saved**")+`
71
71
 
72
72
  ${e.bullet} **Problem Type:** ${r.problem_type}
73
73
  ${e.bullet} **Description:** ${r.description}
74
74
  ${e.bullet} **Steps:** ${r.steps} checklist items
75
75
  ${e.bullet} **ID:** ${r.id}
76
76
 
77
- This scaffold will be surfaced by \`wyrm_context_build\` when tasks match "${r.problem_type}".`)}}];export{ge as captureToolSpecs};
77
+ This scaffold will be surfaced by \`wyrm_context_build\` when tasks match "${r.problem_type}".`)}}];export{he as captureToolSpecs};
@@ -1,8 +1,8 @@
1
- import{TOOL_ANNOTATIONS as b}from"../tool-annotations.js";import{currentReadCacheKey as I}from"./boundary.js";import{autoConfigureAll as B,findWyrmServerPath as U,getDefaultDbPath as N,getStatusSummary as V,removeFromAll as W}from"../autoconfig.js";import{daemonOr as K}from"../daemon-writer.js";import{renderFailureStats as q}from"../failure-patterns.js";import{computeStaleness as H}from"../intelligence.js";import{logger as z}from"../logger.js";import{runMaintenance as G}from"../maintenance.js";import{cache as _}from"../performance.js";import{createProvider as Y}from"../providers/embedding-provider.js";import{reindexProjects as Q}from"../reindex.js";import{requireString as Z}from"../validate.js";import{createVectorStore as J}from"../vectors.js";const ue=[{name:"wyrm_feedback",description:"Record whether a recalled knowledge artifact was useful. Adjusts confidence over time \u2014 successful reuse boosts it, failure lowers it. Call after applying a recalled pattern or lesson.",inputSchema:{type:"object",properties:{artifactId:{type:"number",description:"ID of the memory artifact (from wyrm_recall results)"},success:{type:"boolean",description:"Was this artifact helpful for the task?"}},required:["artifactId","success"]},annotations:b.wyrm_feedback,aliases:[],handler:async(u,f)=>{const{memory:d}=f,{artifactId:a,success:i}=u,c=d.get(a);if(!c)return{content:[{type:"text",text:`Artifact #${a} not found.`}],isError:!0};d.recordFeedback(a,i);const t=d.get(a);return{content:[{type:"text",text:`\u{F115D} Feedback recorded ${i?"\u2705":"\u274C"}
1
+ import{TOOL_ANNOTATIONS as b}from"../tool-annotations.js";import{currentReadCacheKey as I}from"./boundary.js";import{autoConfigureAll as B,findWyrmServerPath as U,getDefaultDbPath as N,getStatusSummary as V,removeFromAll as W}from"../autoconfig.js";import{daemonOr as q}from"../daemon-writer.js";import{renderFailureStats as K}from"../failure-patterns.js";import{computeStaleness as H}from"../intelligence.js";import{logger as z}from"../logger.js";import{runMaintenance as G}from"../maintenance.js";import{cache as $}from"../performance.js";import{createProvider as Y}from"../providers/embedding-provider.js";import{reindexProjects as Q}from"../reindex.js";import{requireString as Z}from"../validate.js";import{createVectorStore as J}from"../vectors.js";const ue=[{name:"wyrm_feedback",description:"Record whether a recalled knowledge artifact was useful. Adjusts confidence over time \u2014 successful reuse boosts it, failure lowers it. Call after applying a recalled pattern or lesson.",inputSchema:{type:"object",properties:{artifactId:{type:"number",description:"ID of the memory artifact (from wyrm_recall results)"},success:{type:"boolean",description:"Was this artifact helpful for the task?"}},required:["artifactId","success"]},annotations:b.wyrm_feedback,aliases:[],handler:async(u,f)=>{const{memory:d}=f,{artifactId:a,success:c}=u,i=d.get(a);if(!i)return{content:[{type:"text",text:`Artifact #${a} not found.`}],isError:!0};d.recordFeedback(a,c);const t=d.get(a);return{content:[{type:"text",text:`\u{F115D} Feedback recorded ${c?"\u2705":"\u274C"}
2
2
 
3
- - Artifact #${a}: "${c.problem.slice(0,60)}"
3
+ - Artifact #${a}: "${i.problem.slice(0,60)}"
4
4
  - New confidence: ${(t.confidence*100).toFixed(0)}%
5
- - Total uses: ${t.reuse_count} (\u2705 ${t.reuse_success_count} / \u274C ${t.reuse_failure_count})`}]}}},{name:"wyrm_context_build",description:"Use to build a compact context brief for the current task under a token budget - relevant patterns, lessons, and truths in one formatted block; max_tokens elides low-score items to recallable stubs.",inputSchema:{type:"object",properties:{projectPath:{type:"string"},task:{type:"string",description:"The current task"},maxItems:{type:"number",description:"Default 10, max 20"},kinds:{type:"array",items:{type:"string"},description:"Artifact kinds (see wyrm_recall)"},minConfidence:{type:"number",description:"Default 0.3"},max_tokens:{type:"number",description:"Token budget; low-score items elide to stubs"},session_id:{type:"number",description:"Already-seen dedup"},strict_budget:{type:"boolean",description:"Also elide truths over budget"}},required:["projectPath","task"]},annotations:b.wyrm_context_build,aliases:[],handler:async(u,f)=>{const{cachedResponse:d,db:a,groundTruths:i,memory:c,runBudgetedContextBuild:t,scaffoldLib:s}=f,o=u||{},r=I(),{projectPath:e,task:n,maxItems:m,kinds:l,minConfidence:p,max_tokens:y,session_id:g,strict_budget:v}=u,h=a.getProject(e);if(!h)return{content:[{type:"text",text:`Project not found: ${e}`}],isError:!0};if(y!=null&&!process.env.WYRM_DISABLE_TOKEN_BUDGET)return t({project:h,task:n,maxTokens:y,sessionId:g,strictBudget:v===!0,kinds:l,minConfidence:p});const x=[],j=i.formatForContext(h.id);j&&x.push(j.slice(0,1200));const $=s.findBest(n,h.id);if($){const k=s.formatForContext($);x.push(k.slice(0,1500))}const S=c.buildContextBrief(h.id,n,{maxItems:Math.min(m??10,20),kinds:l,minConfidence:p});if(S.sections.length>0){const k=S.text.slice(0,2e3);x.push(k)}if(x.length===0)return{content:[{type:"text",text:`\u{F115D} **Context Brief**
5
+ - Total uses: ${t.reuse_count} (\u2705 ${t.reuse_success_count} / \u274C ${t.reuse_failure_count})`}]}}},{name:"wyrm_context_build",description:"Use to build a compact context brief for the current task under a token budget - relevant patterns, lessons, and truths in one formatted block; max_tokens elides low-score items to recallable stubs.",inputSchema:{type:"object",properties:{projectPath:{type:"string"},task:{type:"string",description:"The current task"},maxItems:{type:"number",description:"Default 10, max 20"},kinds:{type:"array",items:{type:"string"},description:"Artifact kinds (see wyrm_recall)"},minConfidence:{type:"number",description:"Default 0.3"},max_tokens:{type:"number",description:"Token budget; low-score items elide to stubs"},session_id:{type:"number",description:"Already-seen dedup"},strict_budget:{type:"boolean",description:"Also elide truths over budget"}},required:["projectPath","task"]},annotations:b.wyrm_context_build,aliases:[],handler:async(u,f)=>{const{cachedResponse:d,db:a,groundTruths:c,memory:i,runBudgetedContextBuild:t,scaffoldLib:s}=f,o=u||{},r=I(),{projectPath:e,task:n,maxItems:m,kinds:l,minConfidence:p,max_tokens:y,session_id:g,strict_budget:v}=u,h=a.getProject(e);if(!h)return{content:[{type:"text",text:`Project not found: ${e}`}],isError:!0};if(!n||typeof n!="string"||!n.trim())return{content:[{type:"text",text:"wyrm_context_build: 'task' is required \u2014 pass a short description of the current task (not 'query')."}],isError:!0};if(y!=null&&!process.env.WYRM_DISABLE_TOKEN_BUDGET)return t({project:h,task:n,maxTokens:y,sessionId:g,strictBudget:v===!0,kinds:l,minConfidence:p});const x=[],j=c.formatForContext(h.id);j&&x.push(j.slice(0,1200));const _=s.findBest(n,h.id);if(_){const k=s.formatForContext(_);x.push(k.slice(0,1500))}const S=i.buildContextBrief(h.id,n,{maxItems:Math.min(m??10,20),kinds:l,minConfidence:p});if(S.sections.length>0){const k=S.text.slice(0,2e3);x.push(k)}if(x.length===0)return{content:[{type:"text",text:`\u{F115D} **Context Brief**
6
6
 
7
7
  No relevant memory found for this task yet.
8
8
 
@@ -12,9 +12,9 @@ As you work, use \`wyrm_remember\` to store:
12
12
  - \u{1F4A1} Heuristics and shortcuts
13
13
  - \u{1F9E0} Reasoning traces from complex problems
14
14
 
15
- Future context briefs will become richer over time.`}]};const P=c.getStats(h.id),C=i.getStats(h.id),E=`\u{F115D} **Context Brief** \u2014 "${n}"
15
+ Future context briefs will become richer over time.`}]};const P=i.getStats(h.id),C=c.getStats(h.id),E=`\u{F115D} **Context Brief** \u2014 "${n}"
16
16
 
17
- `,T=[];j&&T.push(j.slice(0,1200)),$&&T.push(s.formatForContext($).slice(0,1500));const A=T.length>0?`<!-- cache-stable -->
17
+ `,T=[];j&&T.push(j.slice(0,1200)),_&&T.push(s.formatForContext(_).slice(0,1500));const A=T.length>0?`<!-- cache-stable -->
18
18
  ${T.join(`
19
19
 
20
20
  ---
@@ -26,7 +26,7 @@ ${T.join(`
26
26
 
27
27
  `:"",M=S.sections.length>0?S.text.slice(0,2e3):"";let R=`${E}${A}${M}`;R+=`
28
28
 
29
- _Brief: ${C.current} ground truth${C.current!==1?"s":""}, scaffold: ${$?$.scaffold.problem_type:"none"}, ${P.total} memory artifact${P.total!==1?"s":""}.`,S.sourceIds.length>0?R+=` Memory IDs: [${S.sourceIds.join(", ")}] \u2014 use \`wyrm_feedback\` to rate._`:R+="_";try{const{logSavings:k}=await import("../statusline.js"),O=a.getDatabase(),L=O.prepare("SELECT id FROM sessions WHERE project_id = ? ORDER BY created_at DESC LIMIT 1").get(h.id),D=Math.round(A.length/4);D>0&&k(O,"wyrm_context_build","cached_preamble",Math.round(D*.9),L?.id)}catch{}const F=d(R);return r&&_.set(r,F,1e4),F}},{name:"wyrm_truth_set",description:"Use to lock in a confirmed fact or constraint as project ground truth - architecture, conventions, key decisions. Injected first into every brief; re-setting the same category+key supersedes (history kept).",inputSchema:{type:"object",properties:{projectPath:{type:"string"},category:{type:"string",description:"e.g. architecture, conventions"},key:{type:"string",description:"snake_case key"},value:{type:"string",description:"The statement"},rationale:{type:"string",description:"Why this is true"},source:{type:"string",description:"'user'|'derived'|'observed'|'confirmed'"},confidence:{type:"number",description:"0-1 (default 1.0)"},ttl_days:{type:"number",description:"Stale after N days"}},required:["projectPath","category","key","value"]},annotations:b.wyrm_truth_set,aliases:[],handler:async(u,f)=>{const{db:d,groundTruths:a,presence:i}=f,{projectPath:c,category:t,key:s,value:o,rationale:r,source:e,confidence:n,ttl_days:m}=u,l=Z("category",t,{maxLen:200}),p=d.getProject(c);if(!p)return{content:[{type:"text",text:`Project not found: ${c}`}],isError:!0};const y={category:l,key:s,value:o,rationale:r,source:e,confidence:n??1,ttl_days:m};a.lastCascade=null;const g=await K("truth_set",p.id,y,()=>a.set(p.id,y));_.invalidate("wyrm_truth_get"),_.invalidate("wyrm_context_build");const v=a.lastCascade,h=v&&v.invalidated>0?`
29
+ _Brief: ${C.current} ground truth${C.current!==1?"s":""}, scaffold: ${_?_.scaffold.problem_type:"none"}, ${P.total} memory artifact${P.total!==1?"s":""}.`,S.sourceIds.length>0?R+=` Memory IDs: [${S.sourceIds.join(", ")}] \u2014 use \`wyrm_feedback\` to rate._`:R+="_";try{const{logSavings:k}=await import("../statusline.js"),O=a.getDatabase(),L=O.prepare("SELECT id FROM sessions WHERE project_id = ? ORDER BY created_at DESC LIMIT 1").get(h.id),D=Math.round(A.length/4);D>0&&k(O,"wyrm_context_build","cached_preamble",Math.round(D*.9),L?.id)}catch{}const F=d(R);return r&&$.set(r,F,1e4),F}},{name:"wyrm_truth_set",description:"Use to lock in a confirmed fact or constraint as project ground truth - architecture, conventions, key decisions. Injected first into every brief; re-setting the same category+key supersedes (history kept).",inputSchema:{type:"object",properties:{projectPath:{type:"string"},category:{type:"string",description:"e.g. architecture, conventions"},key:{type:"string",description:"snake_case key"},value:{type:"string",description:"The statement"},rationale:{type:"string",description:"Why this is true"},source:{type:"string",description:"'user'|'derived'|'observed'|'confirmed'"},confidence:{type:"number",description:"0-1 (default 1.0)"},ttl_days:{type:"number",description:"Stale after N days"}},required:["projectPath","category","key","value"]},annotations:b.wyrm_truth_set,aliases:[],handler:async(u,f)=>{const{db:d,groundTruths:a,presence:c}=f,{projectPath:i,category:t,key:s,value:o,rationale:r,source:e,confidence:n,ttl_days:m}=u,l=Z("category",t,{maxLen:200}),p=d.getProject(i);if(!p)return{content:[{type:"text",text:`Project not found: ${i}`}],isError:!0};const y={category:l,key:s,value:o,rationale:r,source:e,confidence:n??1,ttl_days:m};a.lastCascade=null;const g=await q("truth_set",p.id,y,()=>a.set(p.id,y));$.invalidate("wyrm_truth_get"),$.invalidate("wyrm_context_build");const v=a.lastCascade,h=v&&v.invalidated>0?`
30
30
  - **Auto-cascade:** ${v.invalidated} downstream decision edge(s) invalidated (rested on the superseded value \u2014 review with \`wyrm_decision_downstream\`)`:"";return{content:[{type:"text",text:`\u{F115D} **Ground Truth Set** \u2705
31
31
 
32
32
  - **Category:** ${t}
@@ -36,7 +36,7 @@ _Brief: ${C.current} ground truth${C.current!==1?"s":""}, scaffold: ${$?$.scaffo
36
36
  - **TTL:** ${m} days`:""}
37
37
  - **ID:** ${g.id}${h}
38
38
 
39
- This truth will be injected at the top of every \`wyrm_context_build\` response for this project.`}]}}},{name:"wyrm_truth_get",description:"Use to read the established facts and ground rules for a codebase - validated truths the AI should treat as baseline, optionally filtered by category.",inputSchema:{type:"object",properties:{projectPath:{type:"string"},category:{type:"string",description:"Category filter"}},required:["projectPath"]},annotations:b.wyrm_truth_get,aliases:[],handler:async(u,f)=>{const{cachedResponse:d,db:a,groundTruths:i}=f,c=I(),{projectPath:t,category:s}=u,o=a.getProject(t);if(!o)return{content:[{type:"text",text:`Project not found: ${t}`}],isError:!0};const r=i.getCurrent(o.id,s);if(r.length===0)return{content:[{type:"text",text:`\u{F115D} **Ground Truths**
39
+ This truth will be injected at the top of every \`wyrm_context_build\` response for this project.`}]}}},{name:"wyrm_truth_get",description:"Use to read the established facts and ground rules for a codebase - validated truths the AI should treat as baseline, optionally filtered by category.",inputSchema:{type:"object",properties:{projectPath:{type:"string"},category:{type:"string",description:"Category filter"}},required:["projectPath"]},annotations:b.wyrm_truth_get,aliases:[],handler:async(u,f)=>{const{cachedResponse:d,db:a,groundTruths:c}=f,i=I(),{projectPath:t,category:s}=u,o=a.getProject(t);if(!o)return{content:[{type:"text",text:`Project not found: ${t}`}],isError:!0};const r=c.getCurrent(o.id,s);if(r.length===0)return{content:[{type:"text",text:`\u{F115D} **Ground Truths**
40
40
 
41
41
  ${s?`No ground truths in category "${s}" for this project.`:"No ground truths stored yet. Use `wyrm_truth_set` to add validated facts."}`}]};const e=new Map;for(const l of r)e.has(l.category)||e.set(l.category,[]),e.get(l.category).push(l);let n=`\u{F115D} **Ground Truths** \u2014 ${r.length} active
42
42
 
@@ -45,19 +45,19 @@ ${s?`No ground truths in category "${s}" for this project.`:"No ground truths st
45
45
  _${y.rationale}_`),g!==null&&(n+=`
46
46
  _staleness: ${(g*100).toFixed(0)}% (TTL: ${y.ttl_days}d)_`),n+=`
47
47
  `}n+=`
48
- `}const m=d(n);return c&&_.set(c,m,15e3),m}},{name:"wyrm_scaffold_get",description:"Find the best reasoning scaffold for a task description. Returns the most relevant structured checklist, or null if no match meets the confidence threshold.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project path (searches project + global)"},task:{type:"string",description:"Task description to match against scaffolds"},minConfidence:{type:"number",description:"Minimum match confidence 0-1 (default: 0.3)"}},required:["task"]},annotations:b.wyrm_scaffold_get,aliases:[],handler:async(u,f)=>{const{cachedResponse:d,db:a,scaffoldLib:i}=f,c=I(),{projectPath:t,task:s,minConfidence:o}=u,r=t?a.getProject(t)?.id??void 0:void 0,e=i.findBest(s,r,o);if(!e)return{content:[{type:"text",text:`\u{F115D} **Reasoning Scaffold**
48
+ `}const m=d(n);return i&&$.set(i,m,15e3),m}},{name:"wyrm_scaffold_get",description:"Find the best reasoning scaffold for a task description. Returns the most relevant structured checklist, or null if no match meets the confidence threshold.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project path (searches project + global)"},task:{type:"string",description:"Task description to match against scaffolds"},minConfidence:{type:"number",description:"Minimum match confidence 0-1 (default: 0.3)"}},required:["task"]},annotations:b.wyrm_scaffold_get,aliases:[],handler:async(u,f)=>{const{cachedResponse:d,db:a,scaffoldLib:c}=f,i=I(),{projectPath:t,task:s,minConfidence:o}=u,r=t?a.getProject(t)?.id??void 0:void 0,e=c.findBest(s,r,o);if(!e)return{content:[{type:"text",text:`\u{F115D} **Reasoning Scaffold**
49
49
 
50
50
  No scaffold matched for: "${s}"
51
51
 
52
- Use \`wyrm_scaffold_save\` to add scaffolds for this problem type.`}]};const n=i.formatForContext(e),m=d(`\u{F115D} **Reasoning Scaffold Match** (${(e.matchScore*100).toFixed(0)}% confidence)
52
+ Use \`wyrm_scaffold_save\` to add scaffolds for this problem type.`}]};const n=c.formatForContext(e),m=d(`\u{F115D} **Reasoning Scaffold Match** (${(e.matchScore*100).toFixed(0)}% confidence)
53
53
 
54
- ${n}`);return c&&_.set(c,m,15e3),m}},{name:"wyrm_sync",description:"Sync database with .wyrm folders in all projects",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Sync specific project, or all if not specified"},direction:{type:"string",enum:["import","export","both"],description:"Sync direction"}}},annotations:b.wyrm_sync,aliases:[],handler:async(u,f)=>{const{db:d,sync:a}=f,{projectPath:i,direction:c}=u,t=c||"both";let s=0;if(i)d.getProject(i)&&((t==="import"||t==="both")&&a.importFromFolder(i),(t==="export"||t==="both")&&a.exportToFolder(i),s=1);else{const o=d.getAllProjects(1e3);for(const r of o)try{(t==="import"||t==="both")&&a.importFromFolder(r.path),(t==="export"||t==="both")&&a.exportToFolder(r.path),s++}catch{}}return{content:[{type:"text",text:`\u{F115D} Synced ${s} project(s)`}]}}},{name:"wyrm_stats",description:"Use for a health snapshot of the memory database - row counts, vector index coverage, usage.",inputSchema:{type:"object",properties:{view:{type:"string",enum:["failures"],description:"'failures' = prevented-repeat analytics"},projectPath:{type:"string",description:"failures view scope"}}},annotations:b.wyrm_stats,aliases:[],handler:async(u,f)=>{const{WRITE_TOOLS:d,analytics:a,cachedResponse:i,db:c,failures:t,getUsageStats:s,orchestrator:o,vectorStore:r}=f,e=u||{},n=I(),{view:m,projectPath:l}=u;if(m==="failures"){const w=l?c.getProject(l):null,x=t.failureStats({projectId:w?.id??null});return{content:[{type:"text",text:q(x)}],structuredContent:x}}const p=c.getStats(),y=_.stats(),g=s();let v="";if(r){const w=r.getStats(),x=w.byType||{},j=(x.artifact||0)+(x.quest||0)+(x.session||0),$=p.artifacts+p.quests+p.sessions,S=$>0?Math.min(100,j/$*100).toFixed(1):"0";v=`
54
+ ${n}`);return i&&$.set(i,m,15e3),m}},{name:"wyrm_sync",description:"Sync database with .wyrm folders in all projects",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Sync specific project, or all if not specified"},direction:{type:"string",enum:["import","export","both"],description:"Sync direction"}}},annotations:b.wyrm_sync,aliases:[],handler:async(u,f)=>{const{db:d,sync:a}=f,{projectPath:c,direction:i}=u,t=i||"both";let s=0;if(c)d.getProject(c)&&((t==="import"||t==="both")&&a.importFromFolder(c),(t==="export"||t==="both")&&a.exportToFolder(c),s=1);else{const o=d.getAllProjects(1e3);for(const r of o)try{(t==="import"||t==="both")&&a.importFromFolder(r.path),(t==="export"||t==="both")&&a.exportToFolder(r.path),s++}catch{}}return{content:[{type:"text",text:`\u{F115D} Synced ${s} project(s)`}]}}},{name:"wyrm_stats",description:"Use for a health snapshot of the memory database - row counts, vector index coverage, usage.",inputSchema:{type:"object",properties:{view:{type:"string",enum:["failures"],description:"'failures' = prevented-repeat analytics"},projectPath:{type:"string",description:"failures view scope"}}},annotations:b.wyrm_stats,aliases:[],handler:async(u,f)=>{const{WRITE_TOOLS:d,analytics:a,cachedResponse:c,db:i,failures:t,getUsageStats:s,orchestrator:o,vectorStore:r}=f,e=u||{},n=I(),{view:m,projectPath:l}=u;if(m==="failures"){const w=l?i.getProject(l):null,x=t.failureStats({projectId:w?.id??null});return{content:[{type:"text",text:K(x)}],structuredContent:x}}const p=i.getStats(),y=$.stats(),g=s();let v="";if(r){const w=r.getStats(),x=w.byType||{},j=(x.artifact||0)+(x.quest||0)+(x.session||0),_=p.artifacts+p.quests+p.sessions,S=_>0?Math.min(100,j/_*100).toFixed(1):"0";v=`
55
55
  **Vectors:**
56
56
  - **Provider:** ${w.provider} (${w.model})
57
57
  - **Embeddings:** ${w.total} vectors
58
58
  - **Coverage:** ${S}% of embeddable content
59
59
  - **By Type:** ${Object.entries(w.byType).map(([P,C])=>`${P}: ${C}`).join(", ")}
60
- `}const h=i(`\u{F115D} **Wyrm Statistics**
60
+ `}const h=c(`\u{F115D} **Wyrm Statistics**
61
61
 
62
62
  - **Projects:** ${p.projects}
63
63
  - **Sessions:** ${p.sessions}
@@ -67,9 +67,9 @@ ${n}`);return c&&_.set(c,m,15e3),m}},{name:"wyrm_sync",description:"Sync databas
67
67
  - **Database Size:** ${p.dbSize}
68
68
  `+v+`
69
69
  **Cache:** ${y.size} entries | Hit rate: ${g.cacheHitRate}
70
- **Usage:** ${g.totalCalls} calls | ~${g.tokensSaved.toLocaleString()} tokens saved by cache`);return n&&_.set(n,h,15e3),h}},{name:"wyrm_vector_setup",description:"Configure embedding provider and download models. Supports local, OpenAI, and Ollama.",inputSchema:{type:"object",properties:{provider:{type:"string",enum:["auto","local","openai","ollama","none"],description:"Provider: auto-detect, local hash, OpenAI API, Ollama, or none"},model:{type:"string",description:"Model name (e.g., 'text-embedding-3-small' for OpenAI, 'nomic-embed-text' for Ollama)"},apiKey:{type:"string",description:"OpenAI API key (if using openai provider)"},ollamaUrl:{type:"string",description:"Ollama URL (default: http://localhost:11434)"}}},annotations:b.wyrm_vector_setup,aliases:[],handler:async(u,f)=>{const{db:d,indexingPipeline:a,memory:i,setVectorStore:c,vectorStore:t}=f,{provider:s,model:o,apiKey:r,ollamaUrl:e}=u,n={provider:s||"auto",model:o,apiKey:r,ollamaUrl:e};try{const m=Y(n),l=await m.isReady();if(!l&&n.provider!=="none")return{content:[{type:"text",text:`\u274C **Provider Not Ready**
70
+ **Usage:** ${g.totalCalls} calls | ~${g.tokensSaved.toLocaleString()} tokens saved by cache`);return n&&$.set(n,h,15e3),h}},{name:"wyrm_vector_setup",description:"Configure embedding provider and download models. Supports local, OpenAI, and Ollama.",inputSchema:{type:"object",properties:{provider:{type:"string",enum:["auto","local","openai","ollama","none"],description:"Provider: auto-detect, local hash, OpenAI API, Ollama, or none"},model:{type:"string",description:"Model name (e.g., 'text-embedding-3-small' for OpenAI, 'nomic-embed-text' for Ollama)"},apiKey:{type:"string",description:"OpenAI API key (if using openai provider)"},ollamaUrl:{type:"string",description:"Ollama URL (default: http://localhost:11434)"}}},annotations:b.wyrm_vector_setup,aliases:[],handler:async(u,f)=>{const{db:d,indexingPipeline:a,memory:c,setVectorStore:i,vectorStore:t}=f,{provider:s,model:o,apiKey:r,ollamaUrl:e}=u,n={provider:s||"auto",model:o,apiKey:r,ollamaUrl:e};try{const m=Y(n),l=await m.isReady();if(!l&&n.provider!=="none")return{content:[{type:"text",text:`\u274C **Provider Not Ready**
71
71
 
72
- Couldn't connect to ${m.name}. Check your configuration and try again.`}],isError:!0};const p=J(n,d.getDatabase());c(p),i.setVectorStore(p),a&&a.updateStore(p);const y=p.getStats();return{content:[{type:"text",text:`\u2705 **Vector Setup Complete**
72
+ Couldn't connect to ${m.name}. Check your configuration and try again.`}],isError:!0};const p=J(n,d.getDatabase());i(p),c.setVectorStore(p),a&&a.updateStore(p);const y=p.getStats();return{content:[{type:"text",text:`\u2705 **Vector Setup Complete**
73
73
 
74
74
  - **Provider:** ${m.name}
75
75
  - **Model:** ${m.model}
@@ -78,25 +78,25 @@ Couldn't connect to ${m.name}. Check your configuration and try again.`}],isErro
78
78
 
79
79
  _Reindex your projects with wyrm_reindex to generate embeddings._`}]}}catch(m){return{content:[{type:"text",text:`\u274C **Vector Setup Failed**
80
80
 
81
- ${String(m)}`}],isError:!0}}}},{name:"wyrm_reindex",description:"Rebuild embeddings for a project or all projects. Regenerates vectors for sessions, quests, data, and memory artifacts (the latter power hybrid recall).",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project to reindex, or leave empty for all projects"},dryRun:{type:"boolean",description:"Show what would be indexed without making changes"}}},annotations:b.wyrm_reindex,aliases:[],handler:async(u,f)=>{const{db:d,failures:a,vectorStore:i}=f,{projectPath:c,dryRun:t}=u;if(!i)return{content:[{type:"text",text:`\u274C **Vector Indexing Disabled**
81
+ ${String(m)}`}],isError:!0}}}},{name:"wyrm_reindex",description:"Rebuild embeddings for a project or all projects. Regenerates vectors for sessions, quests, data, and memory artifacts (the latter power hybrid recall).",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project to reindex, or leave empty for all projects"},dryRun:{type:"boolean",description:"Show what would be indexed without making changes"}}},annotations:b.wyrm_reindex,aliases:[],handler:async(u,f)=>{const{db:d,failures:a,vectorStore:c}=f,{projectPath:i,dryRun:t}=u;if(!c)return{content:[{type:"text",text:`\u274C **Vector Indexing Disabled**
82
82
 
83
- Run wyrm_vector_setup first to enable vector search.`}],isError:!0};let s=[];if(c){const e=d.getProject(c);if(!e)return{content:[{type:"text",text:`\u274C **Project Not Found:** ${c}`}],isError:!0};s=[e.id]}else s=d.getAllProjects(1e3).map(n=>n.id);const{indexed:o,skipped:r}=await Q(d.getDatabase(),i,s,{dryRun:t,onError:(e,n)=>z.error(e,n)});return{content:[{type:"text",text:`\u{F115D} **Reindexing ${t?"(Dry Run)":"Complete"}**
83
+ Run wyrm_vector_setup first to enable vector search.`}],isError:!0};let s=[];if(i){const e=d.getProject(i);if(!e)return{content:[{type:"text",text:`\u274C **Project Not Found:** ${i}`}],isError:!0};s=[e.id]}else s=d.getAllProjects(1e3).map(n=>n.id);const{indexed:o,skipped:r}=await Q(d.getDatabase(),c,s,{dryRun:t,onError:(e,n)=>z.error(e,n)});return{content:[{type:"text",text:`\u{F115D} **Reindexing ${t?"(Dry Run)":"Complete"}**
84
84
 
85
85
  - **Projects:** ${s.length}
86
86
  - **Indexed:** ${o}
87
87
  - **Skipped:** ${r}
88
88
 
89
- `+(t?"_Run without dryRun to actually index._":"_Vectors are now up to date._")}]}}},{name:"wyrm_maintenance",description:"Use for periodic upkeep of the memory store - archive old sessions, vacuum, prune stale events, sweep run quarantine, rebuild vector embeddings (reindex). Admin-gated, destructive; fleets run it between waves.",inputSchema:{type:"object",properties:{vacuum:{type:"boolean",description:"Reclaim space"},archiveDays:{type:"number",description:"Archive sessions > N days"}}},annotations:b.wyrm_maintenance,aliases:[],handler:async(u,f)=>{const{db:d,failures:a,presence:i,sessionSeen:c}=f,t=u||{},{vacuum:s,archiveDays:o}=u,r=G({db:d,sessionSeen:c(),failures:a,presence:i},{vacuum:s,archiveDays:o});return{content:[{type:"text",text:`\u{F115D} **Maintenance Complete**
89
+ `+(t?"_Run without dryRun to actually index._":"_Vectors are now up to date._")}]}}},{name:"wyrm_maintenance",description:"Use for periodic upkeep of the memory store - archive old sessions, vacuum, prune stale events, sweep run quarantine, rebuild vector embeddings (reindex). Admin-gated, destructive; fleets run it between waves.",inputSchema:{type:"object",properties:{vacuum:{type:"boolean",description:"Reclaim space"},archiveDays:{type:"number",description:"Archive sessions > N days"}}},annotations:b.wyrm_maintenance,aliases:[],handler:async(u,f)=>{const{db:d,failures:a,presence:c,sessionSeen:i}=f,t=u||{},{vacuum:s,archiveDays:o}=u,r=G({db:d,sessionSeen:i(),failures:a,presence:c},{vacuum:s,archiveDays:o});return{content:[{type:"text",text:`\u{F115D} **Maintenance Complete**
90
90
 
91
91
  `+r.lines.map(n=>`- ${n}
92
92
  `).join("")+`
93
- **New Database Size:** ${r.dbSize}`}]}}},{name:"wyrm_setup",description:"Auto-detect installed AI clients (VS Code, Claude Desktop, Cursor, Windsurf, Zed) and configure Wyrm's MCP server in all of them. Run this to connect Wyrm to a new AI or after switching providers.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["configure","check","remove"],description:"Action: configure (default), check status, or remove from all"},serverPath:{type:"string",description:"Override Wyrm server path (auto-detected if empty)"},dbPath:{type:"string",description:"Override database path (default: ~/.wyrm/wyrm.db)"}}},annotations:b.wyrm_setup,aliases:[],handler:async(u,f)=>{const{action:d,serverPath:a,dbPath:i}=u,c=d||"configure";if(c==="check")return{content:[{type:"text",text:V()}]};if(c==="remove"){const e=W();return{content:[{type:"text",text:`\u{F115D} **Wyrm Removed**
93
+ **New Database Size:** ${r.dbSize}`}]}}},{name:"wyrm_setup",description:"Auto-detect installed AI clients (VS Code, Claude Desktop, Cursor, Windsurf, Zed) and configure Wyrm's MCP server in all of them. Run this to connect Wyrm to a new AI or after switching providers.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["configure","check","remove"],description:"Action: configure (default), check status, or remove from all"},serverPath:{type:"string",description:"Override Wyrm server path (auto-detected if empty)"},dbPath:{type:"string",description:"Override database path (default: ~/.wyrm/wyrm.db)"}}},annotations:b.wyrm_setup,aliases:[],handler:async(u,f)=>{const{action:d,serverPath:a,dbPath:c}=u,i=d||"configure";if(i==="check")return{content:[{type:"text",text:V()}]};if(i==="remove"){const e=W();return{content:[{type:"text",text:`\u{F115D} **Wyrm Removed**
94
94
 
95
95
  Removed from ${e.filter(l=>l.action==="configured").length} AI client(s):
96
96
  `+e.map(l=>`- ${l.client.icon} ${l.client.name}: ${l.message}`).join(`
97
97
  `)+`
98
98
 
99
- Run wyrm_setup again to reconnect.`}]}}const t=B({serverPath:a||void 0,dbPath:i||void 0}),s=t.filter(e=>e.action==="configured"||e.action==="updated"),o=t.filter(e=>e.action==="failed");let r=`\u{F115D} **Wyrm Auto-Configure Complete**
99
+ Run wyrm_setup again to reconnect.`}]}}const t=B({serverPath:a||void 0,dbPath:c||void 0}),s=t.filter(e=>e.action==="configured"||e.action==="updated"),o=t.filter(e=>e.action==="failed");let r=`\u{F115D} **Wyrm Auto-Configure Complete**
100
100
 
101
101
  `;r+=`Connected to ${s.length} AI client(s):
102
102
  `;for(const e of t){const n=e.action==="configured"?"\u2705":e.action==="updated"?"\u{1F504}":e.action==="skipped"?"\u25CB":"\u274C";r+=`- ${n} ${e.client.icon} ${e.client.name}: ${e.message}
@@ -106,7 +106,7 @@ Run wyrm_setup again to reconnect.`}]}}const t=B({serverPath:a||void 0,dbPath:i|
106
106
  Server: ${U()}
107
107
  DB: ${N()}`,r+=`
108
108
 
109
- _Switch AIs anytime \u2014 run wyrm_setup again to reconnect._`,{content:[{type:"text",text:r}]}}},{name:"wyrm_usage",description:"View token usage stats, cache hit rates, and estimated cost savings. Helps monitor and optimize AI credit consumption.",inputSchema:{type:"object",properties:{last:{type:"number",description:"Show stats for last N calls (default: all)"},reset:{type:"boolean",description:"Reset usage counters"}}},annotations:b.wyrm_usage,aliases:[],handler:async(u,f)=>{const{cachedResponse:d,getUsageStats:a,responseFingerprints:i,usageLog:c}=f,{last:t,reset:s}=u;if(s)return c.length=0,i.clear(),_.invalidate(),{content:[{type:"text",text:"\u{F115D} Usage counters reset, caches cleared."}]};const o=a(t),r=_.stats();let e=`\u{F115D} **Wyrm Usage Report**
109
+ _Switch AIs anytime \u2014 run wyrm_setup again to reconnect._`,{content:[{type:"text",text:r}]}}},{name:"wyrm_usage",description:"View token usage stats, cache hit rates, and estimated cost savings. Helps monitor and optimize AI credit consumption.",inputSchema:{type:"object",properties:{last:{type:"number",description:"Show stats for last N calls (default: all)"},reset:{type:"boolean",description:"Reset usage counters"}}},annotations:b.wyrm_usage,aliases:[],handler:async(u,f)=>{const{cachedResponse:d,getUsageStats:a,responseFingerprints:c,usageLog:i}=f,{last:t,reset:s}=u;if(s)return i.length=0,c.clear(),$.invalidate(),{content:[{type:"text",text:"\u{F115D} Usage counters reset, caches cleared."}]};const o=a(t),r=$.stats();let e=`\u{F115D} **Wyrm Usage Report**
110
110
 
111
111
  `;if(e+=`## Overview${t?` (last ${t} calls)`:""}
112
112
  `,e+=`- **Total Calls:** ${o.totalCalls}