wyrm-mcp 8.5.5 → 8.5.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -43,6 +43,8 @@ npm install -g wyrm-mcp # install
43
43
  wyrm-setup # wire it into your AI clients, then restart them
44
44
  ```
45
45
 
46
+ > **On npm v12+**, npm denies dependency install scripts by default, which skips `better-sqlite3`'s native build — the install *succeeds* but `wyrm` then fails with *"Could not locate the bindings file"*. Install with the build allow-listed instead: `npm install -g wyrm-mcp --allow-scripts=wyrm-mcp,better-sqlite3` (`wyrm update` already does this for you). See [TROUBLESHOOTING.md](https://github.com/Ghosts-Protocol-Pvt-Ltd/Wyrm/blob/main/TROUBLESHOOTING.md).
47
+
46
48
  Then, from inside your client, ask it to call `wyrm_capabilities` to confirm the connection. The everyday loop is four steps the agent runs on its own once the habit sets in:
47
49
 
48
50
  ```
@@ -1,63 +1,63 @@
1
- import{join as K}from"path";import{createHash as O}from"crypto";import{TOOL_ANNOTATIONS as D}from"../tool-annotations.js";import{renderResult as S,withGlyph as E,renderErrorResponse as R,validationErrorBody as C}from"../render.js";import{ValidationError as J,asEnum as Y}from"../validate.js";import{daemonOr as L}from"../daemon-writer.js";import{classifyCapture as Q}from"../capture.js";import{recordWrite as A}from"../receipts.js";import{extractCandidates as F,candidateToArtifact as N,escapeLikePattern as M}from"../auto-capture.js";import{parseTrace as X,segmentsToText as G}from"../trace-harvest.js";import{getActor as V,runWithActor as z}from"./boundary.js";import{harvestProjects as Z}from"../harvest.js";import{readFileSync as U,readdirSync as ee,statSync as W}from"fs";import{join as H}from"path";import{homedir as te}from"os";import{readSpecDir as re,specTaskSignature as ie}from"../spec-kit.js";const ve=[{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:D.wyrm_capture,aliases:[],handler:async($,{store:b,raw:x,memory:w,truths:l,cache:h})=>{const{content:a,project_id:g,projectPath:n,tags:f,mode:p}=$;if(typeof a!="string"||!a.trim()){const r=$;return r.problem||r.validated_fix||r.validatedFix||r.kind?R(C("wyrm_capture","mode","you passed pattern/lesson fields (kind/problem/validated_fix) \u2014 set mode:'direct' to store them as a distilled artifact.")):R(C("wyrm_capture","content","content is required for auto capture (or use mode:'direct' with problem + validated_fix)."))}let v=Q(a);p&&p!=="auto"&&(v={type:p,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[p]??p,confidence:100,reasoning:`Mode override: ${p}`});const{type:d,subtype:s,confidence:u,reasoning:o}=v,e=g??(n?b.getProject(n)?.id??null:null);let i=0,y="",j=!1,t;if(d==="quest"){if(e===null)return R(C("wyrm_capture","projectPath","is required for quest capture"));i=(await L("quest_add",e,{title:a.slice(0,200),description:"",priority:"medium",tags:f?.join(",")},()=>b.addQuest(e,a.slice(0,200),"","medium",f?.join(",")))).id,y="quest",h.invalidate("wyrm_all_quests"),h.invalidate("wyrm_stats")}else if(d==="truth"){if(e===null)return R(C("wyrm_capture","projectPath","is required for truth capture"));if(u>=80){const r=s??"other",P=l.getCurrent(e).filter(c=>c.category===r);if(P.length>0){const c={kind:"pattern",problem:`Potential conflict with ${P.length} existing truth(s) in category "${r}"`,validatedFix:a,whyItWorked:"Pending review \u2014 possible supersession",tags:f??[],confidence:u/100,needsReview:1},k=await L("artifact_add",e,c,()=>w.add(e,c)),q=A(x(),{tool:"wyrm_capture",outcome:"queued",refTable:"mem",refId:k.id,reason:`conflict_check \u2014 possible supersession of ${P.length} truth(s); review to activate`,projectId:e});return S({status:"queued_for_review",reason:"conflict_check",artifact_id:k.id,conflicts_with:P.map(T=>({id:T.id,content:T.value.slice(0,80)})),receipt:q})}}if(p!=="truth"&&u<100){const r={kind:"pattern",problem:a,validatedFix:"",whyItWorked:"",tags:f??[],confidence:u/100,needsReview:1};i=(await L("artifact_add",e,r,()=>w.add(e,r))).id,y="mem",j=!0}else{const r={category:"decision",key:a.slice(0,60),value:a};i=(await L("truth_set",e,r,()=>l.set(e,r))).id,y="truth",h.invalidate("wyrm_truth_get"),h.invalidate("wyrm_context_build")}}else{if(e===null)return R(C("wyrm_capture","projectPath","is required for memory capture"));const r=u>=75,I={kind:s,problem:a,validatedFix:"",whyItWorked:"",tags:f??[],confidence:u/100,needsReview:r?0:1};if(i=(await L("artifact_add",e,I,()=>w.add(e,I))).id,y="mem",j=!r,s==="heuristic"&&u>=75&&e!==null)try{const c=a.replace(/['"*]/g," ").trim().split(/\s+/).slice(0,5).join(" "),k=x().prepare(`
1
+ import{join as J}from"path";import{createHash as O}from"crypto";import{TOOL_ANNOTATIONS as D}from"../tool-annotations.js";import{renderResult as S,withGlyph as E,renderErrorResponse as R,validationErrorBody as C}from"../render.js";import{ValidationError as Y,asEnum as Q,asTags as F}from"../validate.js";import{daemonOr as L}from"../daemon-writer.js";import{classifyCapture as X}from"../capture.js";import{recordWrite as A}from"../receipts.js";import{extractCandidates as N,candidateToArtifact as U,escapeLikePattern as M}from"../auto-capture.js";import{parseTrace as G,segmentsToText as V}from"../trace-harvest.js";import{getActor as z,runWithActor as Z}from"./boundary.js";import{harvestProjects as ee}from"../harvest.js";import{readFileSync as H,readdirSync as te,statSync as W}from"fs";import{join as B}from"path";import{homedir as re}from"os";import{readSpecDir as ie,specTaskSignature as se}from"../spec-kit.js";const je=[{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:D.wyrm_capture,aliases:[],handler:async(k,{store:b,raw:x,memory:w,truths:p,cache:h})=>{const{content:a,project_id:g,projectPath:n,mode:m}=k,y=F("tags",k.tags);if(typeof a!="string"||!a.trim()){const r=k;return r.problem||r.validated_fix||r.validatedFix||r.kind?R(C("wyrm_capture","mode","you passed pattern/lesson fields (kind/problem/validated_fix) \u2014 set mode:'direct' to store them as a distilled artifact.")):R(C("wyrm_capture","content","content is required for auto capture (or use mode:'direct' with problem + validated_fix)."))}let v=X(a);m&&m!=="auto"&&(v={type:m,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[m]??m,confidence:100,reasoning:`Mode override: ${m}`});const{type:d,subtype:s,confidence:l,reasoning:o}=v,e=g??(n?b.getProject(n)?.id??null:null);let i=0,f="",j=!1,t;if(d==="quest"){if(e===null)return R(C("wyrm_capture","projectPath","is required for quest capture"));i=(await L("quest_add",e,{title:a.slice(0,200),description:"",priority:"medium",tags:y?.join(",")},()=>b.addQuest(e,a.slice(0,200),"","medium",y?.join(",")))).id,f="quest",h.invalidate("wyrm_all_quests"),h.invalidate("wyrm_stats")}else if(d==="truth"){if(e===null)return R(C("wyrm_capture","projectPath","is required for truth capture"));if(l>=80){const r=s??"other",P=p.getCurrent(e).filter(c=>c.category===r);if(P.length>0){const c={kind:"pattern",problem:`Potential conflict with ${P.length} existing truth(s) in category "${r}"`,validatedFix:a,whyItWorked:"Pending review \u2014 possible supersession",tags:y??[],confidence:l/100,needsReview:1},$=await L("artifact_add",e,c,()=>w.add(e,c)),q=A(x(),{tool:"wyrm_capture",outcome:"queued",refTable:"mem",refId:$.id,reason:`conflict_check \u2014 possible supersession of ${P.length} truth(s); review to activate`,projectId:e});return S({status:"queued_for_review",reason:"conflict_check",artifact_id:$.id,conflicts_with:P.map(T=>({id:T.id,content:T.value.slice(0,80)})),receipt:q})}}if(m!=="truth"&&l<100){const r={kind:"pattern",problem:a,validatedFix:"",whyItWorked:"",tags:y??[],confidence:l/100,needsReview:1};i=(await L("artifact_add",e,r,()=>w.add(e,r))).id,f="mem",j=!0}else{const r={category:"decision",key:a.slice(0,60),value:a};i=(await L("truth_set",e,r,()=>p.set(e,r))).id,f="truth",h.invalidate("wyrm_truth_get"),h.invalidate("wyrm_context_build")}}else{if(e===null)return R(C("wyrm_capture","projectPath","is required for memory capture"));const r=l>=75,I={kind:s,problem:a,validatedFix:"",whyItWorked:"",tags:y??[],confidence:l/100,needsReview:r?0:1};if(i=(await L("artifact_add",e,I,()=>w.add(e,I))).id,f="mem",j=!r,s==="heuristic"&&l>=75&&e!==null)try{const c=a.replace(/['"*]/g," ").trim().split(/\s+/).slice(0,5).join(" "),$=x().prepare(`
2
2
  SELECT a.id, a.problem FROM memory_artifacts a
3
3
  JOIN memory_artifacts_fts ON a.id = memory_artifacts_fts.rowid
4
4
  WHERE memory_artifacts_fts MATCH ? AND a.project_id = ? AND a.kind = 'heuristic' AND a.needs_review = 0
5
5
  LIMIT 3
6
- `).all(c,e);k.length>0&&(t=k.map(q=>({id:q.id,content:q.problem.slice(0,80)})))}catch{}}const _=A(x(),{tool:"wyrm_capture",outcome:j?"queued":"stored",refTable:y,refId:i,reason:j?`needs_review (confidence ${u}%) \u2014 review to activate`:void 0,projectId:e??void 0}),m={status:"captured",type:d,subtype:s,confidence:u,reasoning:o,id:i,ref:`${y}:${i}`,needs_review:j,receipt:_,...t&&t.length>0?{advisory_conflicts:t}:{}};return S(m,(r,I)=>{let P=`Captured as ${r.type}: ${r.subtype}
6
+ `).all(c,e);$.length>0&&(t=$.map(q=>({id:q.id,content:q.problem.slice(0,80)})))}catch{}}const _=A(x(),{tool:"wyrm_capture",outcome:j?"queued":"stored",refTable:f,refId:i,reason:j?`needs_review (confidence ${l}%) \u2014 review to activate`:void 0,projectId:e??void 0}),u={status:"captured",type:d,subtype:s,confidence:l,reasoning:o,id:i,ref:`${f}:${i}`,needs_review:j,receipt:_,...t&&t.length>0?{advisory_conflicts:t}:{}};return S(u,(r,I)=>{let P=`Captured as ${r.type}: ${r.subtype}
7
7
  Confidence: ${r.confidence}% | ${r.reasoning}
8
8
  ID: ${r.ref}`;r.needs_review&&(P+=`
9
9
  `+E(I.warn,"Stored for review -- run `wyrm_review` to activate"));const c=r.advisory_conflicts;return c&&c.length>0&&(P+=`
10
10
 
11
11
  `+E(I.warn,`Advisory: ${c.length} similar heuristic(s) found:`)+`
12
- `+c.map(k=>` ${I.bullet} [${k.id}] ${k.content}`).join(`
13
- `)),P})}},{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:D.wyrm_remember,aliases:[],handler:async($,{store:b,memory:x,raw:w})=>{const{projectPath:l,kind:h,problem:a,constraints:g,outcome:n,tags:f,confidence:p,sourceSessionId:v}=$,d=$,s=d.validatedFix??d.validated_fix,u=d.whyItWorked??d.why_it_worked,o=Y("kind",h,["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]);if(o===void 0)throw new J("kind","is required");const e=b.getProject(l);if(!e)return R(C("wyrm_remember","projectPath","project not found"));const i={kind:o,problem:a,constraints:g,validatedFix:s,whyItWorked:u,outcome:n,tags:f,confidence:p,sourceSessionId:v},y=await L("artifact_add",e.id,i,()=>x.add(e.id,i)),j=A(w(),{tool:"wyrm_remember",outcome:y.needs_review===1?"queued":"stored",refTable:"mem",refId:y.id,reason:y.needs_review===1?"needs_review \u2014 hidden until approved":void 0,source:y.created_by,projectId:e.id}),t={id:y.id,kind:y.kind,problem:y.problem,validated_fix:y.validated_fix??null,why_it_worked:y.why_it_worked??null,confidence:y.confidence,tags:y.tags??null,receipt:j};return S(t,(_,m)=>{let r=E(m.brand,"**Memory Stored**")+`
14
-
15
- `;return r+=`${m.bullet} **Kind:** ${_.kind}
16
- `,r+=`${m.bullet} **ID:** ${_.id}
17
- `,r+=`${m.bullet} **Problem:** ${_.problem}
18
- `,_.validated_fix&&(r+=`${m.bullet} **Solution:** ${_.validated_fix}
19
- `),_.why_it_worked&&(r+=`${m.bullet} **Why it worked:** ${_.why_it_worked}
20
- `),r+=`${m.bullet} **Confidence:** ${(_.confidence*100).toFixed(0)}%
21
- `,_.tags&&(r+=`${m.bullet} **Tags:** ${_.tags}
22
- `),r+="\n_Use `wyrm_recall` to retrieve similar memories, or `wyrm_context_build` to assemble a task brief._",r})}},{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:D.wyrm_auto_capture,aliases:[],handler:async($,{store:b,raw:x,memory:w,cache:l})=>{const{projectPath:h,text:a,model:g}=$,n=b.getProject(h);if(!n)return R(C("wyrm_auto_capture","projectPath","project not found"));if(!a||a.trim().length<20)return R(C("wyrm_auto_capture","text","must be at least 20 characters"));const{candidates:f,method:p,model:v}=await F(a,{model:g}),d=x();let s=0,u=0;for(const e of f){const i=N(e),y=i.tags[i.tags.length-1];if(d.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(n.id,"%"+M(y)+"%")){u++,A(d,{tool:"wyrm_auto_capture",outcome:"dropped",reason:"dedup \u2014 already captured",source:"auto-extract",projectId:n.id});continue}const j=w.add(n.id,{kind:i.kind,problem:i.problem,tags:i.tags,confidence:i.confidence,needsReview:1,createdBy:"auto-extract"});A(d,{tool:"wyrm_auto_capture",outcome:"queued",refTable:"mem",refId:j.id,reason:"needs_review \u2014 auto-extracted; review to activate",source:"auto-extract",projectId:n.id}),s++}s>0&&l.invalidate();const o={method:p,model:v??null,added:s,skipped:u,receipt:{outcome:s>0?"queued":"dropped",reason:`${s} queued for review, ${u} dropped as duplicates`},candidates:f.slice(0,8).map(e=>({kind:e.kind,text:e.text.slice(0,80)}))};return S(o,(e,i)=>{const y=e.candidates.map(j=>` ${i.bullet} [${j.kind}] ${j.text}`).join(`
12
+ `+c.map($=>` ${I.bullet} [${$.id}] ${$.content}`).join(`
13
+ `)),P})}},{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:D.wyrm_remember,aliases:[],handler:async(k,{store:b,memory:x,raw:w})=>{const{projectPath:p,kind:h,problem:a,constraints:g,outcome:n,confidence:m,sourceSessionId:y}=k,v=F("tags",k.tags),d=k,s=d.validatedFix??d.validated_fix,l=d.whyItWorked??d.why_it_worked,o=Q("kind",h,["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]);if(o===void 0)throw new Y("kind","is required");const e=b.getProject(p);if(!e)return R(C("wyrm_remember","projectPath","project not found"));const i={kind:o,problem:a,constraints:g,validatedFix:s,whyItWorked:l,outcome:n,tags:v,confidence:m,sourceSessionId:y},f=await L("artifact_add",e.id,i,()=>x.add(e.id,i)),j=A(w(),{tool:"wyrm_remember",outcome:f.needs_review===1?"queued":"stored",refTable:"mem",refId:f.id,reason:f.needs_review===1?"needs_review \u2014 hidden until approved":void 0,source:f.created_by,projectId:e.id}),t={id:f.id,kind:f.kind,problem:f.problem,validated_fix:f.validated_fix??null,why_it_worked:f.why_it_worked??null,confidence:f.confidence,tags:f.tags??null,receipt:j};return S(t,(_,u)=>{let r=E(u.brand,"**Memory Stored**")+`
14
+
15
+ `;return r+=`${u.bullet} **Kind:** ${_.kind}
16
+ `,r+=`${u.bullet} **ID:** ${_.id}
17
+ `,r+=`${u.bullet} **Problem:** ${_.problem}
18
+ `,_.validated_fix&&(r+=`${u.bullet} **Solution:** ${_.validated_fix}
19
+ `),_.why_it_worked&&(r+=`${u.bullet} **Why it worked:** ${_.why_it_worked}
20
+ `),r+=`${u.bullet} **Confidence:** ${(_.confidence*100).toFixed(0)}%
21
+ `,_.tags&&(r+=`${u.bullet} **Tags:** ${_.tags}
22
+ `),r+="\n_Use `wyrm_recall` to retrieve similar memories, or `wyrm_context_build` to assemble a task brief._",r})}},{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:D.wyrm_auto_capture,aliases:[],handler:async(k,{store:b,raw:x,memory:w,cache:p})=>{const{projectPath:h,text:a,model:g}=k,n=b.getProject(h);if(!n)return R(C("wyrm_auto_capture","projectPath","project not found"));if(!a||a.trim().length<20)return R(C("wyrm_auto_capture","text","must be at least 20 characters"));const{candidates:m,method:y,model:v}=await N(a,{model:g}),d=x();let s=0,l=0;for(const e of m){const i=U(e),f=i.tags[i.tags.length-1];if(d.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(n.id,"%"+M(f)+"%")){l++,A(d,{tool:"wyrm_auto_capture",outcome:"dropped",reason:"dedup \u2014 already captured",source:"auto-extract",projectId:n.id});continue}const j=w.add(n.id,{kind:i.kind,problem:i.problem,tags:i.tags,confidence:i.confidence,needsReview:1,createdBy:"auto-extract"});A(d,{tool:"wyrm_auto_capture",outcome:"queued",refTable:"mem",refId:j.id,reason:"needs_review \u2014 auto-extracted; review to activate",source:"auto-extract",projectId:n.id}),s++}s>0&&p.invalidate();const o={method:y,model:v??null,added:s,skipped:l,receipt:{outcome:s>0?"queued":"dropped",reason:`${s} queued for review, ${l} dropped as duplicates`},candidates:m.slice(0,8).map(e=>({kind:e.kind,text:e.text.slice(0,80)}))};return S(o,(e,i)=>{const f=e.candidates.map(j=>` ${i.bullet} [${j.kind}] ${j.text}`).join(`
23
23
  `);return E(i.brand,`Auto-capture (${e.method}${e.model?` - ${e.model}`:""}) -- ${e.added} candidate(s) -> review queue, ${e.skipped} already present.`)+`
24
- ${y}
24
+ ${f}
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:D.wyrm_capture_trace,aliases:[],handler:async($,{store:b,raw:x,memory:w,cache:l})=>{const{projectPath:h,trace:a,path:g,format:n,run_id:f,model:p}=$,v=b.getProject(h);if(!v)return R(C("wyrm_capture_trace","projectPath","project not found"));const d=V(),s=typeof f=="string"&&f.trim()?f.trim().slice(0,64):d.run_id;let u="",o="inline";if(typeof a=="string"&&a.trim())u=a,o="inline";else if(typeof g=="string"&&g.trim()){let c=g.trim();(c==="~"||c.startsWith("~/"))&&(c=H(te(),c.slice(1)));try{if(W(c).isDirectory()){const q=ee(c).map(T=>H(c,T)).filter(T=>{try{return W(T).isFile()}catch{return!1}}).sort((T,B)=>W(B).mtimeMs-W(T).mtimeMs);if(q.length===0)return R(C("wyrm_capture_trace","path","no trace files in directory"));u=U(q[0],"utf-8"),o=q[0]}else u=U(c,"utf-8"),o=c}catch(k){return R(C("wyrm_capture_trace","path",`could not read trace path: ${k.message}`))}}else return R(C("wyrm_capture_trace","trace","provide inline trace or path to trace file"));const{segments:e,format:i}=X(u,n??"auto"),y=G(e);if(y.trim().length<20){const c={method:"deterministic",model:null,format:i,source:o,run_id:s,segments:e.length,added:0,skipped:0,candidates:[]};return S(c,(k,q)=>E(q.brand,`Trace harvest (${k.format}) -- no durable content extracted from ${k.segments} segment(s).`))}const{candidates:j,method:t,model:_}=await F(y,{model:p}),m=x();let r=0,I=0;for(const c of j){const k=N(c),q=k.tags[k.tags.length-1];if(m.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(v.id,"%"+M(q)+"%")){I++;continue}const T=s?[...k.tags,"trace",`run:${s}`]:[...k.tags,"trace"];z({agent_id:d.agent_id,run_id:s,source:s?"param":d.source},()=>w.add(v.id,{kind:k.kind,problem:k.problem,tags:T,confidence:k.confidence,needsReview:1,createdBy:"trace-harvest"})),r++}r>0&&l.invalidate();const P={method:t,model:_??null,format:i,source:o,run_id:s,segments:e.length,added:r,skipped:I,candidates:j.slice(0,8).map(c=>({kind:c.kind,text:c.text.slice(0,80)}))};return S(P,(c,k)=>{const q=c.candidates.map(T=>` ${k.bullet} [${T.kind}] ${T.text}`).join(`
27
- `);return E(k.brand,`Trace harvest (${c.format}, ${c.method}${c.model?` - ${c.model}`:""}) -- ${c.segments} segment(s) -> ${c.added} candidate(s) to review queue, ${c.skipped} already present${c.run_id?` [run:${c.run_id}]`:""}.`)+(q?`
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:D.wyrm_capture_trace,aliases:[],handler:async(k,{store:b,raw:x,memory:w,cache:p})=>{const{projectPath:h,trace:a,path:g,format:n,run_id:m,model:y}=k,v=b.getProject(h);if(!v)return R(C("wyrm_capture_trace","projectPath","project not found"));const d=z(),s=typeof m=="string"&&m.trim()?m.trim().slice(0,64):d.run_id;let l="",o="inline";if(typeof a=="string"&&a.trim())l=a,o="inline";else if(typeof g=="string"&&g.trim()){let c=g.trim();(c==="~"||c.startsWith("~/"))&&(c=B(re(),c.slice(1)));try{if(W(c).isDirectory()){const q=te(c).map(T=>B(c,T)).filter(T=>{try{return W(T).isFile()}catch{return!1}}).sort((T,K)=>W(K).mtimeMs-W(T).mtimeMs);if(q.length===0)return R(C("wyrm_capture_trace","path","no trace files in directory"));l=H(q[0],"utf-8"),o=q[0]}else l=H(c,"utf-8"),o=c}catch($){return R(C("wyrm_capture_trace","path",`could not read trace path: ${$.message}`))}}else return R(C("wyrm_capture_trace","trace","provide inline trace or path to trace file"));const{segments:e,format:i}=G(l,n??"auto"),f=V(e);if(f.trim().length<20){const c={method:"deterministic",model:null,format:i,source:o,run_id:s,segments:e.length,added:0,skipped:0,candidates:[]};return S(c,($,q)=>E(q.brand,`Trace harvest (${$.format}) -- no durable content extracted from ${$.segments} segment(s).`))}const{candidates:j,method:t,model:_}=await N(f,{model:y}),u=x();let r=0,I=0;for(const c of j){const $=U(c),q=$.tags[$.tags.length-1];if(u.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(v.id,"%"+M(q)+"%")){I++;continue}const T=s?[...$.tags,"trace",`run:${s}`]:[...$.tags,"trace"];Z({agent_id:d.agent_id,run_id:s,source:s?"param":d.source},()=>w.add(v.id,{kind:$.kind,problem:$.problem,tags:T,confidence:$.confidence,needsReview:1,createdBy:"trace-harvest"})),r++}r>0&&p.invalidate();const P={method:t,model:_??null,format:i,source:o,run_id:s,segments:e.length,added:r,skipped:I,candidates:j.slice(0,8).map(c=>({kind:c.kind,text:c.text.slice(0,80)}))};return S(P,(c,$)=>{const q=c.candidates.map(T=>` ${$.bullet} [${T.kind}] ${T.text}`).join(`
27
+ `);return E($.brand,`Trace harvest (${c.format}, ${c.method}${c.model?` - ${c.model}`:""}) -- ${c.segments} segment(s) -> ${c.added} candidate(s) to review queue, ${c.skipped} already present${c.run_id?` [run:${c.run_id}]`:""}.`)+(q?`
28
28
  ${q}`:"")+`
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:D.wyrm_distill,aliases:[],handler:($,{store:b,memory:x})=>{const{projectPath:w,candidates:l}=$,h=b.getProject(w);if(!h)return{content:[{type:"text",text:`Project not found: ${w}`}],isError:!0};if(!l||l.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:D.wyrm_distill,aliases:[],handler:(k,{store:b,memory:x})=>{const{projectPath:w,candidates:p}=k,h=b.getProject(w);if(!h)return{content:[{type:"text",text:`Project not found: ${w}`}],isError:!0};if(!p||p.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 n of l){const f=x.add(h.id,{kind:n.kind,problem:n.title,validatedFix:n.content,tags:n.tags??[],confidence:n.confidence??.7,needsReview:1});a.push({id:f.id,kind:n.kind,title:n.title})}const g={count:a.length,artifacts:a};return S(g,(n,f)=>{let p=E(f.brand,`**Distillation Complete** -- ${n.count} artifact${n.count!==1?"s":""} queued for review`)+`
32
+ No candidates provided. Provide an array of candidate artifacts to distill.`}],isError:!0};const a=[];for(const n of p){const m=x.add(h.id,{kind:n.kind,problem:n.title,validatedFix:n.content,tags:n.tags??[],confidence:n.confidence??.7,needsReview:1});a.push({id:m.id,kind:n.kind,title:n.title})}const g={count:a.length,artifacts:a};return S(g,(n,m)=>{let y=E(m.brand,`**Distillation Complete** -- ${n.count} artifact${n.count!==1?"s":""} queued for review`)+`
33
33
 
34
- `;return p+=n.artifacts.map(v=>`${f.bullet} [#${v.id}] **${v.kind}**: ${v.title}`).join(`
35
- `),p+="\n\nUse `wyrm_review` with each ID to approve or reject.",p})}},{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:D.wyrm_harvest,aliases:[],handler:($,{store:b,raw:x,memory:w,symbols:l,cache:h})=>{const{projectPath:a,dryRun:g,gitLimit:n,includeCode:f}=$,p=x(),v={existsBySig:(t,_)=>!!p.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(t,"%"+M(_)+"%"),addCandidate:(t,_)=>{const m=w.add(t,{kind:_.kind,problem:_.text,tags:[..._.tags,_.sig],confidence:_.confidence,needsReview:1,createdBy:"harvest"});A(p,{tool:"wyrm_harvest",outcome:"queued",refTable:"mem",refId:m.id,reason:"needs_review \u2014 harvested; review to activate",source:"harvest",projectId:t})},onSkip:t=>{A(p,{tool:"wyrm_harvest",outcome:"dropped",reason:"dedup \u2014 signature already harvested",source:"harvest",projectId:t})}};let d;if(a){const t=b.getProject(a);if(!t)return{content:[{type:"text",text:"Project not found"}],isError:!0};d=[{id:t.id,name:t.name,path:t.path}]}else d=b.getAllProjects(500).map(t=>({id:t.id,name:t.name,path:t.path}));const{reports:s,totalAdded:u,totalSkipped:o}=Z(v,d,{dryRun:g,gitLimit:n,includeCode:f});!g&&u>0&&h.invalidate();let e=null;if(f&&!g){let t=0,_=0,m=0;for(const r of d)try{const I=l.indexProject(r.id,r.path);t+=I.files,_+=I.symbols,m++}catch{}e={symbols:_,projects:m,files:t}}const i=s.filter(t=>t.added>0).sort((t,_)=>_.added-t.added).slice(0,15).map(t=>({project:t.project,added:t.added,skipped:t.skipped})),y=s.flatMap(t=>t.sample??[]).slice(0,6),j={dry_run:!!g,projects_scanned:d.length,added:u,skipped:o,top:i,sample:y,code_symbols:e};return S(j,(t,_)=>{const m=t.code_symbols?`
34
+ `;return y+=n.artifacts.map(v=>`${m.bullet} [#${v.id}] **${v.kind}**: ${v.title}`).join(`
35
+ `),y+="\n\nUse `wyrm_review` with each ID to approve or reject.",y})}},{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:D.wyrm_harvest,aliases:[],handler:(k,{store:b,raw:x,memory:w,symbols:p,cache:h})=>{const{projectPath:a,dryRun:g,gitLimit:n,includeCode:m}=k,y=x(),v={existsBySig:(t,_)=>!!y.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(t,"%"+M(_)+"%"),addCandidate:(t,_)=>{const u=w.add(t,{kind:_.kind,problem:_.text,tags:[..._.tags,_.sig],confidence:_.confidence,needsReview:1,createdBy:"harvest"});A(y,{tool:"wyrm_harvest",outcome:"queued",refTable:"mem",refId:u.id,reason:"needs_review \u2014 harvested; review to activate",source:"harvest",projectId:t})},onSkip:t=>{A(y,{tool:"wyrm_harvest",outcome:"dropped",reason:"dedup \u2014 signature already harvested",source:"harvest",projectId:t})}};let d;if(a){const t=b.getProject(a);if(!t)return{content:[{type:"text",text:"Project not found"}],isError:!0};d=[{id:t.id,name:t.name,path:t.path}]}else d=b.getAllProjects(500).map(t=>({id:t.id,name:t.name,path:t.path}));const{reports:s,totalAdded:l,totalSkipped:o}=ee(v,d,{dryRun:g,gitLimit:n,includeCode:m});!g&&l>0&&h.invalidate();let e=null;if(m&&!g){let t=0,_=0,u=0;for(const r of d)try{const I=p.indexProject(r.id,r.path);t+=I.files,_+=I.symbols,u++}catch{}e={symbols:_,projects:u,files:t}}const i=s.filter(t=>t.added>0).sort((t,_)=>_.added-t.added).slice(0,15).map(t=>({project:t.project,added:t.added,skipped:t.skipped})),f=s.flatMap(t=>t.sample??[]).slice(0,6),j={dry_run:!!g,projects_scanned:d.length,added:l,skipped:o,top:i,sample:f,code_symbols:e};return S(j,(t,_)=>{const u=t.code_symbols?`
36
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.`:"",r=t.top.map(P=>` +${String(P.added).padStart(3)} (skip ${P.skipped}) ${P.project}`).join(`
37
37
  `),I=t.sample.map(P=>` ${_.bullet} ${P}`).join(`
38
- `);return E(_.brand,`Harvest ${t.dry_run?"(dry run) ":""}-- ${t.added} candidate(s) -> review queue across ${t.projects_scanned} project(s); ${t.skipped} already present.`)+`${m}
38
+ `);return E(_.brand,`Harvest ${t.dry_run?"(dry run) ":""}-- ${t.added} candidate(s) -> review queue across ${t.projects_scanned} project(s); ${t.skipped} already present.`)+`${u}
39
39
  ${r}`+(I?`
40
40
 
41
41
  Sample:
42
42
  ${I}`:"")+`
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:D.wyrm_import_git,aliases:[],handler:($,{store:b,memory:x,raw:w})=>{const{project_id:l,commits:h,auto_approve:a}=$;if(!b.getProjectById(l))return{content:[{type:"text",text:`Project ID ${l} not found.`}],isError:!0};let n=0,f=0;const p=w();for(const d of h){const s=d.message??"";if(/^Merge /i.test(s)){f++;continue}if(/^(chore|bump|release|version)/i.test(s)){f++;continue}const u="gi:"+O("sha1").update(`${s}
45
- ${d.diff_summary??""}`).digest("hex").slice(0,16);if(p.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(l,"%"+M(u)+"%")){f++,A(p,{tool:"wyrm_import_git",outcome:"dropped",reason:"dedup \u2014 this commit was already imported (gi: signature match)",source:"import:git",projectId:l});continue}let o="pattern";/^fix(\(.+\))?:/i.test(s)?o="lesson":/^feat(\(.+\))?:/i.test(s)?o="pattern":/^refactor(\(.+\))?:/i.test(s)&&(o="heuristic");const e=s.split(":")[0]??"commit",i=x.add(l,{kind:o,problem:s,validatedFix:d.diff_summary??"",whyItWorked:`Committed by ${d.author??"unknown"} on ${d.date??"unknown"}`,tags:["git","commit",e.toLowerCase(),u],confidence:.6,needsReview:a?0:1});A(p,{tool:"wyrm_import_git",outcome:a?"stored":"queued",refTable:"mem",refId:i.id,reason:a?void 0:"needs_review \u2014 imported; review to activate",source:"import:git",projectId:l}),n++}return S({captured:n,skipped:f,auto_approved:!!a},(d,s)=>E(s.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:D.wyrm_import_git,aliases:[],handler:(k,{store:b,memory:x,raw:w})=>{const{project_id:p,commits:h,auto_approve:a}=k;if(!b.getProjectById(p))return{content:[{type:"text",text:`Project ID ${p} not found.`}],isError:!0};let n=0,m=0;const y=w();for(const d of h){const s=d.message??"";if(/^Merge /i.test(s)){m++;continue}if(/^(chore|bump|release|version)/i.test(s)){m++;continue}const l="gi:"+O("sha1").update(`${s}
45
+ ${d.diff_summary??""}`).digest("hex").slice(0,16);if(y.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(p,"%"+M(l)+"%")){m++,A(y,{tool:"wyrm_import_git",outcome:"dropped",reason:"dedup \u2014 this commit was already imported (gi: signature match)",source:"import:git",projectId:p});continue}let o="pattern";/^fix(\(.+\))?:/i.test(s)?o="lesson":/^feat(\(.+\))?:/i.test(s)?o="pattern":/^refactor(\(.+\))?:/i.test(s)&&(o="heuristic");const e=s.split(":")[0]??"commit",i=x.add(p,{kind:o,problem:s,validatedFix:d.diff_summary??"",whyItWorked:`Committed by ${d.author??"unknown"} on ${d.date??"unknown"}`,tags:["git","commit",e.toLowerCase(),l],confidence:.6,needsReview:a?0:1});A(y,{tool:"wyrm_import_git",outcome:a?"stored":"queued",refTable:"mem",refId:i.id,reason:a?void 0:"needs_review \u2014 imported; review to activate",source:"import:git",projectId:p}),n++}return S({captured:n,skipped:m,auto_approved:!!a},(d,s)=>E(s.brand,"**Git Import Complete**")+`
46
46
 
47
47
  ${s.bullet} **Captured:** ${d.captured}
48
48
  ${s.bullet} **Skipped:** ${d.skipped} (merges/chores)
49
- ${s.bullet} **Review needed:** ${d.auto_approved?"No (auto-approved)":`Yes -- run \`wyrm_review\` to activate ${d.captured} artifact${d.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:D.wyrm_import_pr,aliases:[],handler:($,{store:b,memory:x,raw:w})=>{const{project_id:l,title:h,body:a,review_comments:g,auto_approve:n}=$;if(!b.getProjectById(l))return{content:[{type:"text",text:`Project ID ${l} not found.`}],isError:!0};let p=0,v=0;const d=n?0:1,s=w(),u=(e,i,y)=>{const j="pr:"+O("sha1").update(i).digest("hex").slice(0,16);if(s.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(l,"%"+M(j)+"%")){v++,A(s,{tool:"wyrm_import_pr",outcome:"dropped",reason:"dedup \u2014 already imported (pr: signature)",source:"import:pr",projectId:l});return}const t=x.add(l,{kind:e,problem:i,validatedFix:"",whyItWorked:"",tags:[...y,j],confidence:.65,needsReview:d,createdBy:"import:pr"});A(s,{tool:"wyrm_import_pr",outcome:n?"stored":"queued",refTable:"mem",refId:t.id,reason:n?void 0:"needs_review \u2014 imported; review to activate",source:"import:pr",projectId:l}),p++};u("pattern",`${h}
49
+ ${s.bullet} **Review needed:** ${d.auto_approved?"No (auto-approved)":`Yes -- run \`wyrm_review\` to activate ${d.captured} artifact${d.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:D.wyrm_import_pr,aliases:[],handler:(k,{store:b,memory:x,raw:w})=>{const{project_id:p,title:h,body:a,review_comments:g,auto_approve:n}=k;if(!b.getProjectById(p))return{content:[{type:"text",text:`Project ID ${p} not found.`}],isError:!0};let y=0,v=0;const d=n?0:1,s=w(),l=(e,i,f)=>{const j="pr:"+O("sha1").update(i).digest("hex").slice(0,16);if(s.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(p,"%"+M(j)+"%")){v++,A(s,{tool:"wyrm_import_pr",outcome:"dropped",reason:"dedup \u2014 already imported (pr: signature)",source:"import:pr",projectId:p});return}const t=x.add(p,{kind:e,problem:i,validatedFix:"",whyItWorked:"",tags:[...f,j],confidence:.65,needsReview:d,createdBy:"import:pr"});A(s,{tool:"wyrm_import_pr",outcome:n?"stored":"queued",refTable:"mem",refId:t.id,reason:n?void 0:"needs_review \u2014 imported; review to activate",source:"import:pr",projectId:p}),y++};l("pattern",`${h}
50
50
 
51
- ${a}`,["git","pr"]);for(const e of g??[])/\b(should|must|always|never|prefer|avoid|use|don't)\b/i.test(e)&&u("heuristic",e,["git","pr","review"]);return S({created:p,skipped:v,auto_approved:!!n},(e,i)=>E(i.brand,"**PR Import Complete**")+`
51
+ ${a}`,["git","pr"]);for(const e of g??[])/\b(should|must|always|never|prefer|avoid|use|don't)\b/i.test(e)&&l("heuristic",e,["git","pr","review"]);return S({created:y,skipped:v,auto_approved:!!n},(e,i)=>E(i.brand,"**PR Import Complete**")+`
52
52
 
53
53
  ${i.bullet} **Artifacts created:** ${e.created}
54
- ${i.bullet} **Review needed:** ${e.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:D.wyrm_import_rules,aliases:[],handler:async($,{store:b,memory:x,truths:w,raw:l})=>{const{project_id:h,content:a,format:g,source_file:n}=$;if(!b.getProjectById(h))return{content:[{type:"text",text:`Project ID ${h} not found.`}],isError:!0};const p=g??"plain",v=n??"rules",d=["imported",p,v],s=a.split(/\n(?=#)/),u=a.split(/\n\n+/),o=(s.length>=u.length?s:u).map(m=>m.trim()).filter(m=>m.length>=15);let e=0,i=0,y=0;const{isConfigShapedTruth:j}=await import("../metabolize.js"),t=l();for(const m of o){const r=m.slice(0,50).replace(/\n/g," ");if(/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(m)&&!j(r,m)){const I=w.set(h,{category:"constraint",key:r,value:m,source:v});A(t,{tool:"wyrm_import_rules",outcome:"stored",refTable:"truth",refId:I.id,source:"import:rules",projectId:h}),e++}else{const I=x.add(h,{kind:"heuristic",problem:m,validatedFix:"",whyItWorked:"",tags:d,confidence:.7,needsReview:1,createdBy:"import:rules"});j(r,m)&&y++,A(t,{tool:"wyrm_import_rules",outcome:"queued",refTable:"mem",refId:I.id,reason:j(r,m)?"truth-shape lint \u2014 config shape routed to review":"needs_review \u2014 imported; review to activate",source:"import:rules",projectId:h}),i++}}return S({format:p,source:v,truths_created:e,artifacts_created:i,linted:y},(m,r)=>E(r.brand,`**Rules Import Complete** (${m.format})`)+`
54
+ ${i.bullet} **Review needed:** ${e.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:D.wyrm_import_rules,aliases:[],handler:async(k,{store:b,memory:x,truths:w,raw:p})=>{const{project_id:h,content:a,format:g,source_file:n}=k;if(!b.getProjectById(h))return{content:[{type:"text",text:`Project ID ${h} not found.`}],isError:!0};const y=g??"plain",v=n??"rules",d=["imported",y,v],s=a.split(/\n(?=#)/),l=a.split(/\n\n+/),o=(s.length>=l.length?s:l).map(u=>u.trim()).filter(u=>u.length>=15);let e=0,i=0,f=0;const{isConfigShapedTruth:j}=await import("../metabolize.js"),t=p();for(const u of o){const r=u.slice(0,50).replace(/\n/g," ");if(/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(u)&&!j(r,u)){const I=w.set(h,{category:"constraint",key:r,value:u,source:v});A(t,{tool:"wyrm_import_rules",outcome:"stored",refTable:"truth",refId:I.id,source:"import:rules",projectId:h}),e++}else{const I=x.add(h,{kind:"heuristic",problem:u,validatedFix:"",whyItWorked:"",tags:d,confidence:.7,needsReview:1,createdBy:"import:rules"});j(r,u)&&f++,A(t,{tool:"wyrm_import_rules",outcome:"queued",refTable:"mem",refId:I.id,reason:j(r,u)?"truth-shape lint \u2014 config shape routed to review":"needs_review \u2014 imported; review to activate",source:"import:rules",projectId:h}),i++}}return S({format:y,source:v,truths_created:e,artifacts_created:i,linted:f},(u,r)=>E(r.brand,`**Rules Import Complete** (${u.format})`)+`
55
55
 
56
- ${r.bullet} **Ground truths created:** ${m.truths_created} (active immediately)
57
- ${r.bullet} **Memory artifacts created:** ${m.artifacts_created} (pending review)
58
- ${r.bullet} **Source:** ${m.source}
56
+ ${r.bullet} **Ground truths created:** ${u.truths_created} (active immediately)
57
+ ${r.bullet} **Memory artifacts created:** ${u.artifacts_created} (pending review)
58
+ ${r.bullet} **Source:** ${u.source}
59
59
 
60
- 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:D.wyrm_spec_register,aliases:[],handler:($,{store:b,indexing:x})=>{const{specDir:w,projectPath:l,priority:h}=$,a=["specDir","projectPath"].filter(o=>{const e=$[o];return!e&&e!==0&&e!==!1});if(a.length>0)return{content:[{type:"text",text:`Missing required arguments: ${a.join(", ")}`}],isError:!0};const g=b.getProject(l);if(!g)return{content:[{type:"text",text:`**Spec Register**: Project not found at "${l}". Register it first (wyrm_scan_projects / wyrm_session_start).`}],isError:!0};const n=re(w);if(n.tasks.length===0){const o={spec_dir:w,title:n.title??null,project:g.name,tasks_parsed:0,quests_created:0,quests_updated:0,quest_ids:[]};return S(o,(e,i)=>E(i.brand,`**Spec Register**: No tasks found in ${K(e.spec_dir,"tasks.md")}. Nothing to create.`))}const f=h||"medium";let p=0,v=0;const d=[];for(const o of n.tasks){const e=ie(w,o.id),i=`${o.id}: ${o.title}`,y=e,j=b.findQuestBySpecSignature(g.id,e);if(j)b.updateQuestFields(j.id,{title:i,tags:y}),d.push(j.id),v++;else{const t=b.addQuest(g.id,i,`spec-kit task from ${w}`,f,y);x()?.enqueue("quest",t.id,g.id),d.push(t.id),p++}}const s=b.upsertSpec(g.id,w,n.title,n.summary,n.tasks.length),u={spec_dir:s.spec_dir,title:s.title??null,project:g.name,tasks_parsed:n.tasks.length,quests_created:p,quests_updated:v,quest_ids:d};return S(u,(o,e)=>{let i=E(e.brand,"**Spec Registered**")+`
60
+ 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:D.wyrm_spec_register,aliases:[],handler:(k,{store:b,indexing:x})=>{const{specDir:w,projectPath:p,priority:h}=k,a=["specDir","projectPath"].filter(o=>{const e=k[o];return!e&&e!==0&&e!==!1});if(a.length>0)return{content:[{type:"text",text:`Missing required arguments: ${a.join(", ")}`}],isError:!0};const g=b.getProject(p);if(!g)return{content:[{type:"text",text:`**Spec Register**: Project not found at "${p}". Register it first (wyrm_scan_projects / wyrm_session_start).`}],isError:!0};const n=ie(w);if(n.tasks.length===0){const o={spec_dir:w,title:n.title??null,project:g.name,tasks_parsed:0,quests_created:0,quests_updated:0,quest_ids:[]};return S(o,(e,i)=>E(i.brand,`**Spec Register**: No tasks found in ${J(e.spec_dir,"tasks.md")}. Nothing to create.`))}const m=h||"medium";let y=0,v=0;const d=[];for(const o of n.tasks){const e=se(w,o.id),i=`${o.id}: ${o.title}`,f=e,j=b.findQuestBySpecSignature(g.id,e);if(j)b.updateQuestFields(j.id,{title:i,tags:f}),d.push(j.id),v++;else{const t=b.addQuest(g.id,i,`spec-kit task from ${w}`,m,f);x()?.enqueue("quest",t.id,g.id),d.push(t.id),y++}}const s=b.upsertSpec(g.id,w,n.title,n.summary,n.tasks.length),l={spec_dir:s.spec_dir,title:s.title??null,project:g.name,tasks_parsed:n.tasks.length,quests_created:y,quests_updated:v,quest_ids:d};return S(l,(o,e)=>{let i=E(e.brand,"**Spec Registered**")+`
61
61
 
62
62
  `;return i+=`Spec: ${o.title||"(untitled)"}
63
63
  `,s.summary&&(i+=`Summary: ${s.summary}
@@ -68,11 +68,11 @@ Run \`wyrm_review\` to approve the memory artifacts.`)}},{name:"wyrm_spec_regist
68
68
  `,i+=`
69
69
  \`\`\`json
70
70
  ${JSON.stringify({spec:o.spec_dir,title:o.title,project:o.project,tasksParsed:o.tasks_parsed,questsCreated:o.quests_created,questsUpdated:o.quests_updated,questIds:o.quest_ids},null,2)}
71
- \`\`\``,i})}},{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:D.wyrm_scaffold_save,aliases:[],handler:($,{store:b,scaffolds:x,cache:w})=>{const{projectPath:l,problemType:h,description:a,whenToUse:g,steps:n,verificationSteps:f,doNotApplyIf:p,tags:v}=$,d=l?b.getProject(l)?.id??void 0:void 0,s=x.save({projectId:d,problemType:h,description:a,whenToUse:g,steps:n,verificationSteps:f??void 0,doNotApplyIf:p?[p]:void 0,tags:v??[]});w.invalidate("wyrm_scaffold_get"),w.invalidate("wyrm_context_build");const u={id:s.id,problem_type:h,description:a,steps:n.length};return S(u,(o,e)=>E(e.brand,"**Reasoning Scaffold Saved**")+`
71
+ \`\`\``,i})}},{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:D.wyrm_scaffold_save,aliases:[],handler:(k,{store:b,scaffolds:x,cache:w})=>{const{projectPath:p,problemType:h,description:a,whenToUse:g,steps:n,verificationSteps:m,doNotApplyIf:y,tags:v}=k,d=p?b.getProject(p)?.id??void 0:void 0,s=x.save({projectId:d,problemType:h,description:a,whenToUse:g,steps:n,verificationSteps:m??void 0,doNotApplyIf:y?[y]:void 0,tags:v??[]});w.invalidate("wyrm_scaffold_get"),w.invalidate("wyrm_context_build");const l={id:s.id,problem_type:h,description:a,steps:n.length};return S(l,(o,e)=>E(e.brand,"**Reasoning Scaffold Saved**")+`
72
72
 
73
73
  ${e.bullet} **Problem Type:** ${o.problem_type}
74
74
  ${e.bullet} **Description:** ${o.description}
75
75
  ${e.bullet} **Steps:** ${o.steps} checklist items
76
76
  ${e.bullet} **ID:** ${o.id}
77
77
 
78
- This scaffold will be surfaced by \`wyrm_context_build\` when tasks match "${o.problem_type}".`)}}];export{ve as captureToolSpecs};
78
+ This scaffold will be surfaced by \`wyrm_context_build\` when tasks match "${o.problem_type}".`)}}];export{je as captureToolSpecs};
@@ -21,7 +21,7 @@ ${t.errors.map(r=>`- ${r}`).join(`
21
21
  - Checked: ${e.checkedAt} (${e.source})`;return e.updateAvailable&&(r+="\n\nRun `wyrm_self_update` with `confirm: true` to upgrade, or `npm install -g wyrm-mcp@latest` from your shell."),{content:[{type:"text",text:r}]}}},{name:"wyrm_self_update",description:"Run `npm install -g wyrm-mcp@latest` to upgrade. Returns the install transcript. Requires the operator to have write access to the global npm prefix.",inputSchema:{type:"object",properties:{confirm:{type:"boolean",description:"Must be true to actually run the upgrade (safety guard)."}},required:["confirm"]},annotations:l.wyrm_self_update,aliases:[],handler:async(o,c)=>{const{confirm:i=!1}=o;return i?{content:[{type:"text",text:`\u{F115D} **Self-update transcript**
22
22
 
23
23
  \`\`\`
24
- ${await new Promise(t=>{const e=_("npm",["install","-g","wyrm-mcp@latest"],{stdio:["ignore","pipe","pipe"]}),r=[];e.stdout.on("data",s=>r.push(s.toString())),e.stderr.on("data",s=>r.push(s.toString())),e.on("close",s=>{r.push(`
24
+ ${await new Promise(t=>{const e=_("npm",["install","-g","wyrm-mcp@latest","--allow-scripts=wyrm-mcp,better-sqlite3"],{stdio:["ignore","pipe","pipe"]}),r=[];e.stdout.on("data",s=>r.push(s.toString())),e.stderr.on("data",s=>r.push(s.toString())),e.on("close",s=>{r.push(`
25
25
  [exit ${s??"unknown"}]`),t(r.join(""))}),e.on("error",s=>t(`spawn failed: ${s.message}`))})}
26
26
  \`\`\`
27
27
 
@@ -1,18 +1,18 @@
1
- import{readFileSync as T}from"fs";import{homedir as P}from"os";import{join as I,dirname as N}from"node:path";import{STALE_ANCHOR_FLAG as D}from"../failure-patterns.js";import{TOOL_ANNOTATIONS as $}from"../tool-annotations.js";import{renderResult as j,withGlyph as f}from"../render.js";import{asEnum as M,ValidationError as v}from"../validate.js";import{daemonOr as C}from"../daemon-writer.js";import{resolveTargetFile as F}from"../project-resolve.js";let w=null;function Z(){w=null}function L(){const s=process.env.CLAUDE_SETTINGS??I(P(),".claude","settings.json");try{const d=JSON.parse(T(s,"utf-8"));for(const a of Object.values(d.hooks??{}))if(Array.isArray(a)){for(const m of a)for(const o of m?.hooks??[])if(o?.command&&/wyrm-guard/.test(o.command))return!0}}catch{}return!1}function z(){const s=Date.now();if(w&&s-w.at<6e4)return w.line;const d=(process.env.WYRM_GUARD_MODE??"block").toLowerCase(),a=L()&&d==="block"?`
1
+ import{readFileSync as I}from"fs";import{homedir as N}from"os";import{join as D,dirname as M}from"node:path";import{STALE_ANCHOR_FLAG as C}from"../failure-patterns.js";import{TOOL_ANNOTATIONS as j}from"../tool-annotations.js";import{renderResult as q,withGlyph as _}from"../render.js";import{asEnum as O,ValidationError as w}from"../validate.js";import{daemonOr as F}from"../daemon-writer.js";import{resolveTargetFile as L}from"../project-resolve.js";let b=null;function ee(){b=null}function z(){const i=process.env.CLAUDE_SETTINGS??D(N(),".claude","settings.json");try{const p=JSON.parse(I(i,"utf-8"));for(const s of Object.values(p.hooks??{}))if(Array.isArray(s)){for(const y of s)for(const u of y?.hooks??[])if(u?.command&&/wyrm-guard/.test(u.command))return!0}}catch{}return!1}function U(){const i=Date.now();if(b&&i-b.at<6e4)return b.line;const p=(process.env.WYRM_GUARD_MODE??"block").toLowerCase(),s=z()&&p==="block"?`
2
2
 
3
- Enforcement: wyrm-guard hook ACTIVE -- identity-matching repeats of these are hard-blocked at the harness (PreToolUse).`:"\n\nEnforcement: ADVISORY ONLY on this machine -- the wyrm-guard PreToolUse hook is not enforcing (not installed, or WYRM_GUARD_MODE=warn/off). Treat this as a hard stop; run `wyrm guard` to enforce it.";return w={at:s,line:a},a}const U={type:"object",properties:{blocked:{type:"boolean"},matches:{type:"array",items:{type:"object",properties:{id:{type:"integer"},pattern:{type:"string"},scope:{type:"string"},quarantine_scope:{type:"string"},target:{type:"string"},description:{type:"string"},why_failed:{type:["string","null"]},severity:{type:"string"},occurrences:{type:"integer"},last_seen:{type:"string"},recorded_by_agent:{type:"string"},run_id:{type:["string","null"]},match:{type:"string",enum:["exact","fuzzy","target"]},confidence:{type:"number",minimum:0,maximum:1}},required:["id","pattern","scope","quarantine_scope","target","description","why_failed","severity","occurrences","last_seen","recorded_by_agent","run_id","match","confidence"]}},recorded_by_agent:{type:["string","null"]},run_id:{type:["string","null"]},confidence:{type:"number",minimum:0,maximum:1}},required:["blocked","matches","recorded_by_agent","run_id","confidence"]},S={type:["object","null"],properties:{requested:{type:"string"},authorized:{type:"boolean"},changed:{type:"boolean"}},required:["requested","authorized","changed"]};function G(s,d){return s?s.authorized?s.changed?"":` - promote:'${s.requested}' was a no-op (already ${d}-scoped)`:` - promote:'${s.requested}' IGNORED -- caller carries no explicit identity (pass actor/run_id, _meta['wyrm/actor'], or WYRM_AGENT_ID/WYRM_RUN_ID)`:""}const ee=[{name:"wyrm_failure_record",description:"Use when an approach failed or something broke - log the dead end so nobody tries it again. Identical (scope, target, description) coalesces with occurrences++; when the root cause is fixed, stop flagging it via wyrm_failure_resolve. Run-scoped failures quarantine until confirmed.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Global if omitted"},scope:{type:"string",enum:["file","symbol","command","prompt","edit"]},target:{type:"string",description:"File, symbol, command, or prompt"},description:{type:"string",description:"What was tried"},why_failed:{type:"string",description:"Diagnosis if known"},severity:{type:"string",enum:["low","medium","high","critical"]},promote:{type:"string",enum:["project","global"],description:"Widen the tier (explicitly attributed callers only)"}},required:["scope","target","description"]},outputSchema:{type:"object",properties:{id:{type:"integer"},occurrences:{type:"integer"},scope:{type:"string"},target:{type:"string"},quarantine_scope:{type:"string"},run_id:{type:["string","null"]},promote:S},required:["id","occurrences","scope","target","quarantine_scope","run_id","promote"]},annotations:$.wyrm_failure_record,aliases:[],handler:async(s,{store:d,failures:a})=>{const{projectPath:m,scope:o,target:y,description:_,why_failed:g,severity:n,promote:e,files:l}=s,u=M("severity",n,["low","medium","high","critical"]),h=m?d.getProject(m):null,b=o==="file"||o==="symbol"||o==="edit",c=b?F(y,h?.path??null):null,p=c?d.getProjectForPath(N(c))??null:b?null:h??null;let t=await C("failure_record",p?.id??null,{scope:o,target:y,description:_,why_failed:g,severity:u},()=>a.record({project_id:p?.id??null,scope:o,target:y,description:_,why_failed:g,severity:u})),i=0;const q=Array.isArray(l)?l.filter(r=>typeof r=="string"):[],k=q.length>0?q:c?[c]:[];k.length>0&&p?.path&&(i=a.recordAnchors(t.id,p.path,k,t.occurrences===1));let E=null;if(e==="project"||e==="global"){const r=a.promote(t.id,e);r.authorized&&(t=r.row??t),E={requested:e,authorized:r.authorized,changed:r.changed,quarantine_scope:r.row?.quarantine_scope??t.quarantine_scope??null}}const O={id:t.id,occurrences:t.occurrences,scope:o,target:y,quarantine_scope:t.quarantine_scope,run_id:t.run_id??null,promote:E,...i>0?{anchors:i}:{}};return j(O,(r,x)=>{const A=r.run_id?` - ${r.quarantine_scope}-scoped (run ${r.run_id})`:` - ${r.quarantine_scope}-scoped`,R=r.anchors?` - anchored to ${r.anchors} file(s)`:"";return f(x.brand,`Failure #${r.id} recorded (x${r.occurrences}) -- ${r.scope}:${r.target}${A}${R}`+G(r.promote,r.quarantine_scope))})}},{name:"wyrm_failure_check",description:"Use before proposing or executing any fix, command, or approach - did this fail before? Is it a known landmine? Counter-pattern memory: returns unresolved matching failures (empty = safe to proceed); show the mistakes already made on a project with wyrm_failure_list. Subagents: check before retrying anything flagged.",inputSchema:{type:"object",properties:{projectPath:{type:"string"},scope:{type:"string",enum:["file","symbol","command","prompt","edit"]},target:{type:"string"},description:{type:"string"},run_scope:{type:"string",enum:["run","project","global"],description:"Quarantine tier filter (run = same-run only)"}},required:["scope","target","description"]},outputSchema:U,annotations:$.wyrm_failure_check,aliases:[],handler:async(s,{store:d,raw:a,failures:m})=>{const{projectPath:o,scope:y,target:_,description:g,run_scope:n}=s;if(typeof y!="string"||!y)throw new v("scope","is required (e.g. command, edit, approach)");if(typeof _!="string"||!_)throw new v("target","is required (the action/command/code about to run)");if(typeof g!="string"||!g)throw new v("description","is required (what the action does)");const e=o?d.getProject(o):null,l=n==="run"||n==="project"||n==="global"?n:"any";let u=m.checkVerdict(y,_,g,e?.id??null,{runScope:l});const h=m.staleAnchorIds(u.matches,e?.path??null);if(h.size>0){const c=u.matches.map(t=>h.has(t.id)?{...t,stale_anchor:D}:t),p=c.find(t=>!t.stale_anchor);u={...u,blocked:c.some(t=>!t.stale_anchor),matches:c,...p?{recorded_by_agent:p.recorded_by_agent,run_id:p.run_id}:{}}}const b=u.blocked?z():"";if(u.blocked){m.recordBlock(u,e?.id??null);try{const{logSavings:c}=await import("../statusline.js"),p=a(),t=e?p.prepare("SELECT id FROM sessions WHERE project_id = ? ORDER BY created_at DESC LIMIT 1").get(e.id):void 0;c(p,"wyrm_failure_check","blocked_retry",1500*u.matches.length,t?.id)}catch{}}return j(u,(c,p)=>{if(!c.blocked&&c.matches.length===0)return f(p.ok,"No matching failures -- safe to proceed.");const t=c.matches.map(i=>`${f(p.fail,`#${i.id} ${i.scope}:${i.target}`)} -- tried ${i.occurrences}x (${i.severity}); last ${i.last_seen}
4
- ${i.description}`+(i.why_failed?`
5
- Why: ${i.why_failed}`:"")+(i.run_id?`
6
- Recorded by ${i.recorded_by_agent} in run ${i.run_id} (${i.quarantine_scope}-scoped)`:"")+(i.stale_anchor?`
7
- STALE ANCHOR: ${i.stale_anchor}`:"")).join(`
3
+ Enforcement: wyrm-guard hook ACTIVE -- identity-matching repeats of these are hard-blocked at the harness (PreToolUse).`:"\n\nEnforcement: ADVISORY ONLY on this machine -- the wyrm-guard PreToolUse hook is not enforcing (not installed, or WYRM_GUARD_MODE=warn/off). Treat this as a hard stop; run `wyrm guard` to enforce it.";return b={at:i,line:s},s}const G={type:"object",properties:{blocked:{type:"boolean"},matches:{type:"array",items:{type:"object",properties:{id:{type:"integer"},pattern:{type:"string"},scope:{type:"string"},quarantine_scope:{type:"string"},target:{type:"string"},description:{type:"string"},why_failed:{type:["string","null"]},severity:{type:"string"},occurrences:{type:"integer"},last_seen:{type:"string"},recorded_by_agent:{type:"string"},run_id:{type:["string","null"]},match:{type:"string",enum:["exact","fuzzy","target"]},confidence:{type:"number",minimum:0,maximum:1}},required:["id","pattern","scope","quarantine_scope","target","description","why_failed","severity","occurrences","last_seen","recorded_by_agent","run_id","match","confidence"]}},recorded_by_agent:{type:["string","null"]},run_id:{type:["string","null"]},confidence:{type:"number",minimum:0,maximum:1}},required:["blocked","matches","recorded_by_agent","run_id","confidence"]},x={type:["object","null"],properties:{requested:{type:"string"},authorized:{type:"boolean"},changed:{type:"boolean"}},required:["requested","authorized","changed"]};function W(i,p){return i?i.authorized?i.changed?"":` - promote:'${i.requested}' was a no-op (already ${p}-scoped)`:` - promote:'${i.requested}' IGNORED -- caller carries no explicit identity (pass actor/run_id, _meta['wyrm/actor'], or WYRM_AGENT_ID/WYRM_RUN_ID)`:""}const te=[{name:"wyrm_failure_record",description:"Use when an approach failed or something broke - log the dead end so nobody tries it again. Identical (scope, target, description) coalesces with occurrences++; when the root cause is fixed, stop flagging it via wyrm_failure_resolve. Run-scoped failures quarantine until confirmed.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Global if omitted"},scope:{type:"string",enum:["file","symbol","command","prompt","edit"]},target:{type:"string",description:"File, symbol, command, or prompt"},description:{type:"string",description:"What was tried"},why_failed:{type:"string",description:"Diagnosis if known"},severity:{type:"string",enum:["low","medium","high","critical"]},promote:{type:"string",enum:["project","global"],description:"Widen the tier (explicitly attributed callers only)"}},required:["scope","target","description"]},outputSchema:{type:"object",properties:{id:{type:"integer"},occurrences:{type:"integer"},scope:{type:"string"},target:{type:"string"},quarantine_scope:{type:"string"},run_id:{type:["string","null"]},promote:x},required:["id","occurrences","scope","target","quarantine_scope","run_id","promote"]},annotations:j.wyrm_failure_record,aliases:[],handler:async(i,{store:p,failures:s})=>{const{projectPath:y,scope:u,target:d,description:g,why_failed:f,severity:o,promote:e,files:m}=i,n=O("scope",u,["file","symbol","command","prompt","edit"]);if(!n)throw new w("scope","is required (one of: file, symbol, command, prompt, edit)");if(typeof d!="string"||!d)throw new w("target","is required (the action/command/code that failed)");if(typeof g!="string"||!g)throw new w("description","is required (what went wrong)");const h=O("severity",o,["low","medium","high","critical"]),$=y?p.getProject(y):null,l=n==="file"||n==="symbol"||n==="edit",a=l?L(d,$?.path??null):null,c=a?p.getProjectForPath(M(a))??null:l?null:$??null;let t=await F("failure_record",c?.id??null,{scope:n,target:d,description:g,why_failed:f,severity:h},()=>s.record({project_id:c?.id??null,scope:n,target:d,description:g,why_failed:f,severity:h})),v=0;const k=Array.isArray(m)?m.filter(r=>typeof r=="string"):[],E=k.length>0?k:a?[a]:[];E.length>0&&c?.path&&(v=s.recordAnchors(t.id,c.path,E,t.occurrences===1));let S=null;if(e==="project"||e==="global"){const r=s.promote(t.id,e);r.authorized&&(t=r.row??t),S={requested:e,authorized:r.authorized,changed:r.changed,quarantine_scope:r.row?.quarantine_scope??t.quarantine_scope??null}}const A={id:t.id,occurrences:t.occurrences,scope:n,target:d,quarantine_scope:t.quarantine_scope,run_id:t.run_id??null,promote:S,...v>0?{anchors:v}:{}};return q(A,(r,R)=>{const T=r.run_id?` - ${r.quarantine_scope}-scoped (run ${r.run_id})`:` - ${r.quarantine_scope}-scoped`,P=r.anchors?` - anchored to ${r.anchors} file(s)`:"";return _(R.brand,`Failure #${r.id} recorded (x${r.occurrences}) -- ${r.scope}:${r.target}${T}${P}`+W(r.promote,r.quarantine_scope))})}},{name:"wyrm_failure_check",description:"Use before proposing or executing any fix, command, or approach - did this fail before? Is it a known landmine? Counter-pattern memory: returns unresolved matching failures (empty = safe to proceed); show the mistakes already made on a project with wyrm_failure_list. Subagents: check before retrying anything flagged.",inputSchema:{type:"object",properties:{projectPath:{type:"string"},scope:{type:"string",enum:["file","symbol","command","prompt","edit"]},target:{type:"string"},description:{type:"string"},run_scope:{type:"string",enum:["run","project","global"],description:"Quarantine tier filter (run = same-run only)"}},required:["scope","target","description"]},outputSchema:G,annotations:j.wyrm_failure_check,aliases:[],handler:async(i,{store:p,raw:s,failures:y})=>{const{projectPath:u,scope:d,target:g,description:f,run_scope:o}=i;if(typeof d!="string"||!d)throw new w("scope","is required (e.g. command, edit, approach)");if(typeof g!="string"||!g)throw new w("target","is required (the action/command/code about to run)");if(typeof f!="string"||!f)throw new w("description","is required (what the action does)");const e=u?p.getProject(u):null,m=o==="run"||o==="project"||o==="global"?o:"any";let n=y.checkVerdict(d,g,f,e?.id??null,{runScope:m});const h=y.staleAnchorIds(n.matches,e?.path??null);if(h.size>0){const l=n.matches.map(c=>h.has(c.id)?{...c,stale_anchor:C}:c),a=l.find(c=>!c.stale_anchor);n={...n,blocked:l.some(c=>!c.stale_anchor),matches:l,...a?{recorded_by_agent:a.recorded_by_agent,run_id:a.run_id}:{}}}const $=n.blocked?U():"";if(n.blocked){y.recordBlock(n,e?.id??null);try{const{logSavings:l}=await import("../statusline.js"),a=s(),c=e?a.prepare("SELECT id FROM sessions WHERE project_id = ? ORDER BY created_at DESC LIMIT 1").get(e.id):void 0;l(a,"wyrm_failure_check","blocked_retry",1500*n.matches.length,c?.id)}catch{}}return q(n,(l,a)=>{if(!l.blocked&&l.matches.length===0)return _(a.ok,"No matching failures -- safe to proceed.");const c=l.matches.map(t=>`${_(a.fail,`#${t.id} ${t.scope}:${t.target}`)} -- tried ${t.occurrences}x (${t.severity}); last ${t.last_seen}
4
+ ${t.description}`+(t.why_failed?`
5
+ Why: ${t.why_failed}`:"")+(t.run_id?`
6
+ Recorded by ${t.recorded_by_agent} in run ${t.run_id} (${t.quarantine_scope}-scoped)`:"")+(t.stale_anchor?`
7
+ STALE ANCHOR: ${t.stale_anchor}`:"")).join(`
8
8
 
9
- `);return c.blocked?`${f(p.brand,`${c.matches.length} failure(s) match this action:`)}
9
+ `);return l.blocked?`${_(a.brand,`${l.matches.length} failure(s) match this action:`)}
10
10
 
11
- ${t}${b}`:`${f(p.warn,`${c.matches.length} recorded failure(s) match, but their anchored source changed since -- advisory only, re-verify before trusting or dismissing them:`)}
11
+ ${c}${$}`:`${_(a.warn,`${l.matches.length} recorded failure(s) match, but their anchored source changed since -- advisory only, re-verify before trusting or dismissing them:`)}
12
12
 
13
- ${t}`})}},{name:"wyrm_failure_list",description:"List unresolved failures for a project (or globally), most-recent-first.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project path (omit for global)"},limit:{type:"number",description:"Max rows (default 20, max 200)"}}},outputSchema:{type:"object",properties:{count:{type:"integer"},failures:{type:"array",items:{type:"object",properties:{id:{type:"integer"},severity:{type:"string",enum:["low","medium","high","critical"]},scope:{type:"string"},target:{type:"string"},occurrences:{type:"integer"},last_seen:{type:"string"},description:{type:"string"}},required:["id","severity","scope","target","occurrences","last_seen","description"]}}},required:["count","failures"]},annotations:$.wyrm_failure_list,aliases:[],handler:(s,{store:d,failures:a})=>{const{projectPath:m,limit:o}=s,y=m?d.getProject(m):null,_=Math.min(Math.max(1,o??20),200),g=a.list(y?.id??null,_),n={count:g.length,failures:g.map(e=>({id:e.id,severity:e.severity,scope:e.scope,target:e.target,occurrences:e.occurrences,last_seen:e.last_seen,description:e.description}))};return j(n,(e,l)=>{if(e.count===0)return f(l.brand,"No unresolved failures.");const u=e.failures.map(h=>`#${h.id} [${h.severity}] ${h.scope}:${h.target} x${h.occurrences} (last ${h.last_seen})
13
+ ${c}`})}},{name:"wyrm_failure_list",description:"List unresolved failures for a project (or globally), most-recent-first.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project path (omit for global)"},limit:{type:"number",description:"Max rows (default 20, max 200)"}}},outputSchema:{type:"object",properties:{count:{type:"integer"},failures:{type:"array",items:{type:"object",properties:{id:{type:"integer"},severity:{type:"string",enum:["low","medium","high","critical"]},scope:{type:"string"},target:{type:"string"},occurrences:{type:"integer"},last_seen:{type:"string"},description:{type:"string"}},required:["id","severity","scope","target","occurrences","last_seen","description"]}}},required:["count","failures"]},annotations:j.wyrm_failure_list,aliases:[],handler:(i,{store:p,failures:s})=>{const{projectPath:y,limit:u}=i,d=y?p.getProject(y):null,g=Math.min(Math.max(1,u??20),200),f=s.list(d?.id??null,g),o={count:f.length,failures:f.map(e=>({id:e.id,severity:e.severity,scope:e.scope,target:e.target,occurrences:e.occurrences,last_seen:e.last_seen,description:e.description}))};return q(o,(e,m)=>{if(e.count===0)return _(m.brand,"No unresolved failures.");const n=e.failures.map(h=>`#${h.id} [${h.severity}] ${h.scope}:${h.target} x${h.occurrences} (last ${h.last_seen})
14
14
  ${h.description}`).join(`
15
15
 
16
- `);return`${f(l.brand,`${e.count} unresolved failure(s):`)}
16
+ `);return`${_(m.brand,`${e.count} unresolved failure(s):`)}
17
17
 
18
- ${u}`},{summary:(e,l)=>e.count===0?f(l.brand,"No unresolved failures."):f(l.brand,`${e.count} unresolved failure(s):`)})}},{name:"wyrm_failure_resolve",description:"Mark a failure as resolved (the underlying issue was fixed). Keeps history but excludes from check() results.",inputSchema:{type:"object",properties:{id:{type:"number",description:"Failure pattern ID"},note:{type:"string",description:"How it was resolved"},promote:{type:"string",enum:["project","global"],description:"Widen the tier before resolving (same authority rule as wyrm_failure_record)."}},required:["id"]},outputSchema:{type:"object",properties:{id:{type:"integer"},resolved:{type:"boolean",enum:[!0]},promote:S},required:["id","resolved","promote"]},annotations:$.wyrm_failure_resolve,aliases:[],handler:(s,{failures:d})=>{const{id:a,note:m,promote:o}=s;let y=null;if(o==="project"||o==="global"){const n=d.promote(a,o);y={requested:o,authorized:n.authorized,changed:n.changed,quarantine_scope:n.row?.quarantine_scope??null}}return d.resolve(a,m)?j({id:a,resolved:!0,promote:y},(n,e)=>{let l="";return n.promote&&!n.promote.authorized?l=` promote:'${n.promote.requested}' IGNORED -- caller carries no explicit identity.`:n.promote?.changed&&(l=` Promoted to ${n.promote.quarantine_scope}-scoped.`),f(e.ok,`Failure #${n.id} resolved.${l}`)}):{content:[{type:"text",text:`Failure #${a} not found.`}],isError:!0}}}];export{U as FAILURE_CHECK_OUTPUT_SCHEMA,Z as _resetGuardEnforcementCache,ee as failureToolSpecs};
18
+ ${n}`},{summary:(e,m)=>e.count===0?_(m.brand,"No unresolved failures."):_(m.brand,`${e.count} unresolved failure(s):`)})}},{name:"wyrm_failure_resolve",description:"Mark a failure as resolved (the underlying issue was fixed). Keeps history but excludes from check() results.",inputSchema:{type:"object",properties:{id:{type:"number",description:"Failure pattern ID"},note:{type:"string",description:"How it was resolved"},promote:{type:"string",enum:["project","global"],description:"Widen the tier before resolving (same authority rule as wyrm_failure_record)."}},required:["id"]},outputSchema:{type:"object",properties:{id:{type:"integer"},resolved:{type:"boolean",enum:[!0]},promote:x},required:["id","resolved","promote"]},annotations:j.wyrm_failure_resolve,aliases:[],handler:(i,{failures:p})=>{const{id:s,note:y,promote:u}=i;let d=null;if(u==="project"||u==="global"){const o=p.promote(s,u);d={requested:u,authorized:o.authorized,changed:o.changed,quarantine_scope:o.row?.quarantine_scope??null}}return p.resolve(s,y)?q({id:s,resolved:!0,promote:d},(o,e)=>{let m="";return o.promote&&!o.promote.authorized?m=` promote:'${o.promote.requested}' IGNORED -- caller carries no explicit identity.`:o.promote?.changed&&(m=` Promoted to ${o.promote.quarantine_scope}-scoped.`),_(e.ok,`Failure #${o.id} resolved.${m}`)}):{content:[{type:"text",text:`Failure #${s} not found.`}],isError:!0}}}];export{G as FAILURE_CHECK_OUTPUT_SCHEMA,ee as _resetGuardEnforcementCache,te as failureToolSpecs};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contract": "wyrm-cloud-memory-v2",
3
- "version": "8.5.5",
3
+ "version": "8.5.7",
4
4
  "derivedFrom": "standard tier MINUS device-local/egress/subprocess (src/cloud-profile.ts)",
5
5
  "count": 19,
6
6
  "tools": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contract": "wyrm-cloud-memory-v1",
3
- "version": "8.5.5",
3
+ "version": "8.5.7",
4
4
  "tools": [
5
5
  {
6
6
  "name": "wyrm_recall",
package/dist/validate.js CHANGED
@@ -1 +1 @@
1
- class i extends Error{field;constructor(e,n){super(`'${e}' ${n}`),this.name="ValidationError",this.field=e}}const u=r=>r==null;function m(r,e,n={}){if(u(e))return n.default;let t;if(typeof e=="number")t=e;else if(typeof e=="string"&&/^[+-]?\d+$/.test(e.trim()))t=Number(e.trim());else throw new i(r,"must be an integer");if(!Number.isInteger(t))throw new i(r,"must be an integer");if(n.min!==void 0&&t<n.min)throw new i(r,`must be >= ${n.min}`);if(n.max!==void 0&&t>n.max)throw new i(r,`must be <= ${n.max}`);return t}function s(r,e,n={}){const t=m(r,e,n);if(t===void 0)throw new i(r,"is required");return t}function o(r,e,n={}){if(u(e))return n.default;let t;if(typeof e=="number")t=e;else if(typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e)))t=Number(e);else throw new i(r,"must be a number");if(!Number.isFinite(t))throw new i(r,"must be a finite number");if(n.min!==void 0&&t<n.min)throw new i(r,`must be >= ${n.min}`);if(n.max!==void 0&&t>n.max)throw new i(r,`must be <= ${n.max}`);return t}function f(r,e,n={}){if(u(e))return n.default;if(typeof e!="string")throw new i(r,"must be a string");if(n.minLen!==void 0&&e.length<n.minLen)throw new i(r,`must be at least ${n.minLen} characters`);if(n.maxLen!==void 0&&e.length>n.maxLen)throw new i(r,`must be at most ${n.maxLen} characters`);if(n.pattern&&!n.pattern.test(e))throw new i(r,"has an invalid format");return e}function w(r,e,n={}){const t=f(r,e,n);if(t===void 0)throw new i(r,"is required");return t}function h(r,e,n){if(u(e))return n;if(typeof e=="boolean")return e;if(e==="true"||e==="1"||e===1)return!0;if(e==="false"||e==="0"||e===0)return!1;throw new i(r,"must be a boolean")}function b(r,e,n,t){if(u(e))return t;if(typeof e!="string"||!n.includes(e))throw new i(r,`must be one of: ${n.join(", ")}`);return e}function x(r,e,n={}){if(!u(e)){if(!Array.isArray(e))throw new i(r,"must be an array");if(n.maxItems!==void 0&&e.length>n.maxItems)throw new i(r,`must have at most ${n.maxItems} items`);return e.map((t,a)=>{if(typeof t!="string")throw new i(`${r}[${a}]`,"must be a string");if(n.maxLen!==void 0&&t.length>n.maxLen)throw new i(`${r}[${a}]`,`must be at most ${n.maxLen} characters`);return t})}}export{i as ValidationError,h as asBool,b as asEnum,m as asInt,o as asNumber,f as asString,x as asStringArray,s as requireInt,w as requireString};
1
+ class i extends Error{field;constructor(e,n){super(`'${e}' ${n}`),this.name="ValidationError",this.field=e}}const u=r=>r==null;function m(r,e,n={}){if(u(e))return n.default;let t;if(typeof e=="number")t=e;else if(typeof e=="string"&&/^[+-]?\d+$/.test(e.trim()))t=Number(e.trim());else throw new i(r,"must be an integer");if(!Number.isInteger(t))throw new i(r,"must be an integer");if(n.min!==void 0&&t<n.min)throw new i(r,`must be >= ${n.min}`);if(n.max!==void 0&&t>n.max)throw new i(r,`must be <= ${n.max}`);return t}function o(r,e,n={}){const t=m(r,e,n);if(t===void 0)throw new i(r,"is required");return t}function w(r,e,n={}){if(u(e))return n.default;let t;if(typeof e=="number")t=e;else if(typeof e=="string"&&e.trim()!==""&&Number.isFinite(Number(e)))t=Number(e);else throw new i(r,"must be a number");if(!Number.isFinite(t))throw new i(r,"must be a finite number");if(n.min!==void 0&&t<n.min)throw new i(r,`must be >= ${n.min}`);if(n.max!==void 0&&t>n.max)throw new i(r,`must be <= ${n.max}`);return t}function f(r,e,n={}){if(u(e))return n.default;if(typeof e!="string")throw new i(r,"must be a string");if(n.minLen!==void 0&&e.length<n.minLen)throw new i(r,`must be at least ${n.minLen} characters`);if(n.maxLen!==void 0&&e.length>n.maxLen)throw new i(r,`must be at most ${n.maxLen} characters`);if(n.pattern&&!n.pattern.test(e))throw new i(r,"has an invalid format");return e}function h(r,e,n={}){const t=f(r,e,n);if(t===void 0)throw new i(r,"is required");return t}function b(r,e,n){if(u(e))return n;if(typeof e=="boolean")return e;if(e==="true"||e==="1"||e===1)return!0;if(e==="false"||e==="0"||e===0)return!1;throw new i(r,"must be a boolean")}function x(r,e,n,t){if(u(e))return t;if(typeof e!="string"||!n.includes(e))throw new i(r,`must be one of: ${n.join(", ")}`);return e}function c(r,e,n={}){if(u(e))return;const t=typeof e=="string"?e.split(",").map(a=>a.trim()).filter(Boolean):e;if(!Array.isArray(t))throw new i(r,"must be an array of strings (or a comma-separated string)");return s(r,t,n)}function s(r,e,n={}){if(!u(e)){if(!Array.isArray(e))throw new i(r,"must be an array");if(n.maxItems!==void 0&&e.length>n.maxItems)throw new i(r,`must have at most ${n.maxItems} items`);return e.map((t,a)=>{if(typeof t!="string")throw new i(`${r}[${a}]`,"must be a string");if(n.maxLen!==void 0&&t.length>n.maxLen)throw new i(`${r}[${a}]`,`must be at most ${n.maxLen} characters`);return t})}}export{i as ValidationError,b as asBool,x as asEnum,m as asInt,w as asNumber,f as asString,s as asStringArray,c as asTags,o as requireInt,h as requireString};
package/dist/wyrm-cli.js CHANGED
@@ -75,8 +75,8 @@ Delete these ${g.length} artifact(s)? Type CONFIRM to proceed: `,$)});if(h.close
75
75
  Database size: ${d.dbSize}`))}finally{s.close()}}async function St(l){const{positional:c,flags:e}=E(l),i=c[0]??"trend",n=M().version??null,t=j();try{const s=t.getDatabase();if(i==="snapshot"){const o=N(e.kind)||"all",r=[];if((o==="all"||o==="health")&&ce(s,"health",ze(s),n)!=null&&r.push("health"),(o==="all"||o==="effectiveness")&&ce(s,"effectiveness",Qe(s),n)!=null&&r.push("effectiveness"),o==="retrieval"||e.full===!0){const d=await Ct();d&&ce(s,"retrieval",d,n)!=null?r.push("retrieval"):d||console.log(p.dim(" retrieval: bench unavailable (run from the repo with bench/ present) \u2014 skipped"))}r.length?b(`metrics snapshot recorded: ${r.join(", ")} @ ${n??"unknown"}`):m("metrics snapshot: nothing recorded");return}if(i==="trend"){const o=N(e.kind),r=Number(N(e.limit))||14,d=o?[o]:["health","effectiveness","retrieval"];let a=!1;for(const u of d){const g=be(s,u,r);if(!g.length)continue;a=!0,k(`${u} \u2014 ${g.length} snapshot(s)`);const f=jt[u],y=g.slice().reverse().map(h=>[h.captured_at.slice(0,16),h.wyrm_version??"-",...f.map(w=>Et(h.metrics[w]))]);console.log(D(["when","ver",...f],y));for(const h of Xe(g,u))console.log(" "+p.yellow("!")+" "+h)}a||(console.log(p.dim(" No metrics yet. Record the first snapshot: wyrm metrics snapshot")),console.log(p.dim(" (health + effectiveness are cheap; add --full for retrieval recall@k.)")));return}if(i==="show"){const o=N(e.kind)||"health",r=be(s,o,1);if(!r.length){console.log(p.dim(` No ${o} snapshot yet.`));return}k(`latest ${o} @ ${r[0].captured_at} (${r[0].wyrm_version??"-"})`),console.log(JSON.stringify(r[0].metrics,null,2));return}m("Usage: wyrm metrics <snapshot [--kind all|health|effectiveness|retrieval] [--full] | trend [--kind K] [--limit N] | show [--kind K]>"),process.exitCode=1}finally{t.close()}}const jt={health:["memories","vectors","vector_coverage_pct","review_queue","unresolved_failures","provider"],effectiveness:["failure_blocks","rehydrate_calls","recall_calls","tokens_saved_total"],retrieval:["recall_at_1","recall_at_10","mrr","mode","queries"]};function Et(l){return l==null?"-":typeof l=="number"?Number.isInteger(l)?String(l):l.toFixed(3):String(l)}async function Ct(){try{const l=z(Q(import.meta.url)),c=O(l,"..","bench"),e=O(c,"lib","retrieval-eval.mjs"),i=O(c,"eval-corpus.json");if(!L(e)||!L(i))return null;const n=process.env.WYRM_VECTOR_PROVIDER||"none";process.env.WYRM_LIVE_MEMORY="0";const{evaluate:t}=await import(e),{WyrmDB:s}=await import("./database.js"),{MemoryArtifacts:o}=await import("./memory-artifacts.js"),r=JSON.parse(Y(i,"utf8")),d=`/tmp/wyrm-metrics-eval-${process.pid}.db`,a=new s(d);let u;try{u=t(r,a,o,{k:10})}finally{a.close();for(const f of["","-wal","-shm"])try{Le(d+f,{force:!0})}catch{}}const g=u.quality.overall;return{mode:n==="none"?"fts-floor":n,k:10,recall_at_1:g.recall_at_1??null,recall_at_10:g.recall_at_k??null,mrr:g.mrr??null,queries:g.n??u.performance?.queries??null,p50_ms:u.performance?.p50_ms??null,p95_ms:u.performance?.p95_ms??null}}catch{return null}}async function Rt(l){const{resolveEmbeddingState:c}=await import("./providers/embedding-provider.js"),e=j();let i=0;const n=(s,o)=>{console.log(` ${p.green("\u2714")} ${s} \u2014 ${p.dim(o)}`)},t=(s,o,r)=>{i++,console.log(` ${p.red("\u2716")} ${s} \u2014 ${o}`),console.log(` ${p.yellow("fix:")} ${r}`)};try{const s=e.getDatabase();k("wyrm doctor");const o=c();o.reason===""&&o.resolved!=="local"?n("Embedding provider",`${o.resolved} (${o.model})${o.egressHost?` \xB7 egress: ${o.egressHost}`:" \xB7 local"}`):o.resolved==="local"?t("Embedding provider","local-hash (hash-384) is NOT semantic \u2014 test-only vectors",o.fix||"use NVIDIA NIM: set WYRM_VECTOR_PROVIDER=nim + NVIDIA_API_KEY"):o.reason==="ollama_deprecated"?t("Embedding provider","ollama (deprecated \u2014 leaves in the next major)",o.fix):t("Embedding provider",`none (${o.reason})`,o.fix);const r=s.prepare("SELECT COUNT(*) AS n FROM memory_artifacts").get().n;let d=0;try{d=s.prepare("SELECT COUNT(*) AS n FROM vectors").get().n}catch{}o.resolved==="none"||o.resolved==="local"?t("Vector index",`${d} vector(s) / ${r} memories \u2014 recall is FTS5 keyword-only (~59.9% vs 72.2% hybrid recall@10)`,o.fix||"enable a provider, then: wyrm index rebuild"):d===0&&r>0?t("Vector index",`provider '${o.resolved}' is configured but 0 of ${r} memories are indexed`,"wyrm index rebuild"):n("Vector index",`${d} vector(s) over ${r} memories`);try{const g=s.prepare("SELECT COUNT(*) AS n FROM memory_artifacts_fts").get().n;g===r?n("FTS index",`${g}/${r} rows in sync`):t("FTS index",`${g} FTS rows vs ${r} memories \u2014 keyword recall is missing rows`,"INSERT INTO memory_artifacts_fts(memory_artifacts_fts) VALUES('rebuild') via wyrm maintenance")}catch{t("FTS index","memory_artifacts_fts unreadable","wyrm maintenance")}const a=s.prepare("SELECT COUNT(*) AS n FROM failure_patterns WHERE resolved = 0").get().n;n("Failure firewall",`${a} unresolved pattern(s) \xB7 matching = exact signature + FTS5 fuzzy (no vector tier in this build)`);const u=s.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE needs_review = 1").get().n;u>0?t("Review queue",`${u} memor${u===1?"y":"ies"} invisible to recall until approved`,"wyrm review"):n("Review queue","empty");try{const g=s.prepare("SELECT MAX(version) AS v FROM schema_versions").get().v;n("Schema",`migration v${g??0}`)}catch{t("Schema","schema_versions unreadable","wyrm maintenance")}console.log(""),i===0?b("All checks passed \u2014 nothing is silently off."):(m(`${i} check(s) DEGRADED \u2014 the fixes above are exact.`),process.exitCode=1)}finally{e.close()}}async function xt(l){const{positional:c,flags:e}=E(l),i=c[0]??"list",n=j();try{const t=n.getDatabase();if(i==="list"){const s=t.prepare("SELECT id, scope, target, occurrences, last_seen FROM failure_patterns WHERE resolved = 0 ORDER BY last_seen DESC LIMIT 25").all();if(k("Unresolved failures"),!s.length){console.log(p.dim(" none \u2014 the firewall has nothing active."));return}console.log(D(["ID","Scope","Target","Seen","Last seen"],s.map(o=>[String(o.id),o.scope,o.target.slice(0,48),String(o.occurrences),o.last_seen]))),console.log(p.dim(`
76
76
  resolve one: wyrm failure resolve <id>`));return}if(i==="resolve"){const s=Number(c[1]);if(!Number.isInteger(s)||s<=0){m('Usage: wyrm failure resolve <id> [--note "root cause fixed by ..."]'),process.exitCode=1;return}const o=N(e.note);(t.prepare("UPDATE failure_patterns SET resolved = 1, resolution_note = ?, last_seen = datetime('now') WHERE id = ? AND resolved = 0").run(o||"resolved via wyrm failure resolve",s).changes??0)>0?b(`Failure #${s} resolved \u2014 it will no longer flag.`):(m(`No unresolved failure #${s}.`),process.exitCode=1);return}m("Usage: wyrm failure <list|resolve <id> [--note N]>"),process.exitCode=1}finally{n.close()}}async function Tt(l){const{positional:c,flags:e}=E(l),i=c[0]??"list",n=j();try{if(i==="add"){const t=c[1]??process.cwd(),s=Ne(t);if(!L(s)){m(`Path does not exist: ${s}`),process.exitCode=1;return}const o=N(e.name)||Me(s),r=n.registerProject(o,s);b(`Project #${r.id} '${r.name}' registered at ${r.path}`);return}if(i==="list"){const t=n.getAllProjects(50);k("Projects"),console.log(D(["ID","Name","Path"],t.map(s=>[String(s.id),s.name,s.path])));return}m("Usage: wyrm project <add [path] [--name N] | list>"),process.exitCode=1}finally{n.close()}}async function Dt(l){const{positional:c,flags:e}=E(l),i="Usage: wyrm index <setup|rebuild|status> [--provider auto|local|nim|openai|none] [--model M] [--project P] [--dry-run]";if(e.help===!0||typeof e.help=="string"){console.log(i);return}const n=c[0]??"status",{createVectorStore:t}=await import("./vectors.js"),o={provider:e.provider??process.env.WYRM_VECTOR_PROVIDER??"auto",model:e.model,apiKey:e["api-key"]??process.env.OPENAI_API_KEY,ollamaUrl:e["ollama-url"]};if(n==="setup"){const{createProvider:d}=await import("./providers/embedding-provider.js"),a=d(o);if(!await a.isReady()&&o.provider!=="none"){m(`Provider not ready: ${a.name}. Check the configuration and try again.`),process.exitCode=1;return}b(`Vector provider verified: ${a.name} (model ${a.model}, ${a.dimensions}d)`),console.log(p.dim(" The MCP server reads WYRM_VECTOR_PROVIDER (and provider-specific env) at boot \u2014")),console.log(p.dim(` set WYRM_VECTOR_PROVIDER=${a.name==="none"?"none":o.provider} in the server env, then: wyrm index rebuild`));return}const r=j();try{const d=r.getDatabase(),a=t(o,d);if(n==="status"){const u=a.getStats();k("Vector index");const g=[["Provider",u.provider],["Model",u.model],["Vectors",String(u.total)],...Object.entries(u.byType).map(([f,y])=>[` ${f}`,String(y)])];console.log(D(["Field","Value"],g));return}if(n==="rebuild"){const{reindexProjects:u}=await import("./reindex.js"),g=e["dry-run"]===!0,f=e.project;let y;if(f){const $=r.getProject(f)??x(r,f);if(!$){m(`Project not found: ${f}`),process.exitCode=1;return}y=[$.id]}else y=r.getAllProjects(1e3).map($=>$.id);const{indexed:h,skipped:w}=await u(d,a,y,{dryRun:g,onError:($,C)=>m(`${$}: ${JSON.stringify(C)}`)});b(`Reindex ${g?"(dry run) ":""}\u2014 ${y.length} project(s), ${h} indexed, ${w} skipped`);return}m(i),process.exitCode=1}finally{r.close()}}function N(l){return typeof l=="string"?l:""}function It(l){try{return new URL(l).host}catch{return l}}async function Pt(l){const{flags:c}=E(l),{getUpdateStatus:e}=await import("./version-check.js"),i=M().version??"0.0.0",n=j();let t;try{t=await e(n.getDatabase(),i,{force:c.force===!0||c.check===!0})}finally{n.close()}if(k("Wyrm update"),console.log(D(["Field","Value"],[["Current",t.current],["Latest",t.latest??"unknown (offline?)"],["Update available",t.updateAvailable?"yes":"no"],["Checked",`${t.checkedAt} (${t.source})`]])),c.check===!0)return;if(!t.updateAvailable&&c.force!==!0){console.log(p.dim(`
77
77
  Already up to date. (Use --force to reinstall anyway.)`));return}console.log(p.dim(`
78
- Running: npm install -g wyrm-mcp@latest
79
- `));const s=X("npm",["install","-g","wyrm-mcp@latest"],{stdio:"inherit",shell:!1});s.status===0?b("Updated. Restart your MCP clients to pick up the new binary."):(m(`npm install exited with ${s.status??"unknown"}`),process.exitCode=s.status??1)}async function Nt(l){const{positional:c,flags:e}=E(l),i=c[0],n=e.project??process.cwd();if(i==="inject"){const{injectSystemPrompt:t}=await import("./autoconfig.js"),s=typeof e.clients=="string"?e.clients.split(",").map(r=>r.trim()).filter(Boolean):[],o=t(n,s);k("System prompt injection");for(const r of o.injected)console.log(` + ${r}`);for(const r of o.skipped)console.log(p.dim(` o skipped (unknown client): ${r}`));for(const r of o.errors)m(r);o.injected.length>0&&b("AI clients in this project will now call wyrm_session_prime at conversation start."),o.errors.length>0&&(process.exitCode=1);return}if(i==="migrate"){const{migrateProject:t,renderMigrationReport:s}=await import("./migrate-prompt.js"),{WYRM_INJECT_BLOCK:o}=await import("./autoconfig.js"),r=e.apply===!0,d=t({projectPath:n,newBlock:o,apply:r});console.log(s(d,r));return}m("Usage: wyrm prompt inject [--project <path>] [--clients copilot,cursor] | wyrm prompt migrate [--project <path>] [--apply]"),process.exitCode=1}async function Mt(l){const{positional:c,flags:e}=E(l);(c[0]??"report")!=="report"&&(m("Usage: wyrm hours report --from YYYY-MM-DD --to YYYY-MM-DD [--project <name>] [--session-hours H] [--json]"),process.exit(1));const n=e.from,t=e.to;(!n||!t)&&(m("--from and --to are required (YYYY-MM-DD)"),process.exit(1));const{HourLedger:s}=await import("./hours.js"),o=j();try{const r=e.project,d=r?x(o,r):null;if(r&&!d){m(`Project not found: ${r}`),process.exitCode=1;return}const a=new s(o.getDatabase()).report({range_start:n,range_end:t,project_id:d?.id,default_session_hours:ee(e["session-hours"],1)});if(e.json===!0){console.log(JSON.stringify(a,null,2));return}if(k(`Hours ${a.range.start} \u2192 ${a.range.end}`),a.by_project.length===0){console.log(p.dim(" No sessions in range."));return}console.log(D(["Project","Sessions","Hours"],a.by_project.map(u=>[u.project_name,String(u.session_count),u.hours.toFixed(2)]))),console.log(`
78
+ Running: npm install -g wyrm-mcp@latest --allow-scripts=wyrm-mcp,better-sqlite3
79
+ `));const s=X("npm",["install","-g","wyrm-mcp@latest","--allow-scripts=wyrm-mcp,better-sqlite3"],{stdio:"inherit",shell:!1});s.status===0?b("Updated. Restart your MCP clients to pick up the new binary."):(m(`npm install exited with ${s.status??"unknown"}`),process.exitCode=s.status??1)}async function Nt(l){const{positional:c,flags:e}=E(l),i=c[0],n=e.project??process.cwd();if(i==="inject"){const{injectSystemPrompt:t}=await import("./autoconfig.js"),s=typeof e.clients=="string"?e.clients.split(",").map(r=>r.trim()).filter(Boolean):[],o=t(n,s);k("System prompt injection");for(const r of o.injected)console.log(` + ${r}`);for(const r of o.skipped)console.log(p.dim(` o skipped (unknown client): ${r}`));for(const r of o.errors)m(r);o.injected.length>0&&b("AI clients in this project will now call wyrm_session_prime at conversation start."),o.errors.length>0&&(process.exitCode=1);return}if(i==="migrate"){const{migrateProject:t,renderMigrationReport:s}=await import("./migrate-prompt.js"),{WYRM_INJECT_BLOCK:o}=await import("./autoconfig.js"),r=e.apply===!0,d=t({projectPath:n,newBlock:o,apply:r});console.log(s(d,r));return}m("Usage: wyrm prompt inject [--project <path>] [--clients copilot,cursor] | wyrm prompt migrate [--project <path>] [--apply]"),process.exitCode=1}async function Mt(l){const{positional:c,flags:e}=E(l);(c[0]??"report")!=="report"&&(m("Usage: wyrm hours report --from YYYY-MM-DD --to YYYY-MM-DD [--project <name>] [--session-hours H] [--json]"),process.exit(1));const n=e.from,t=e.to;(!n||!t)&&(m("--from and --to are required (YYYY-MM-DD)"),process.exit(1));const{HourLedger:s}=await import("./hours.js"),o=j();try{const r=e.project,d=r?x(o,r):null;if(r&&!d){m(`Project not found: ${r}`),process.exitCode=1;return}const a=new s(o.getDatabase()).report({range_start:n,range_end:t,project_id:d?.id,default_session_hours:ee(e["session-hours"],1)});if(e.json===!0){console.log(JSON.stringify(a,null,2));return}if(k(`Hours ${a.range.start} \u2192 ${a.range.end}`),a.by_project.length===0){console.log(p.dim(" No sessions in range."));return}console.log(D(["Project","Sessions","Hours"],a.by_project.map(u=>[u.project_name,String(u.session_count),u.hours.toFixed(2)]))),console.log(`
80
80
  Total: ${a.total_hours.toFixed(2)}h across ${a.entries.length} session(s)`+(a.estimated_sessions>0?p.dim(` (${a.estimated_sessions} estimated)`):""))}finally{o.close()}}async function Ot(l){const{positional:c,flags:e}=E(l),i=c[0]??"generate",n=e.client,t=ee(e.rate,NaN),s=e.from,o=e.to;(i!=="generate"||!n||!Number.isFinite(t)||!s||!o)&&(m('Usage: wyrm invoice generate --client <name> --rate <usd/hour> --from YYYY-MM-DD --to YYYY-MM-DD [--project <name>] [--number INV-X] [--currency USD] [--notes "\u2026"] [--out <path>]'),process.exit(1));const{HourLedger:r}=await import("./hours.js"),d=j();try{const a=e.project,u=a?x(d,a):null;if(a&&!u){m(`Project not found: ${a}`),process.exitCode=1;return}const g=new r(d.getDatabase()).invoice({client_name:n,hourly_rate_usd:t,range_start:s,range_end:o,project_id:u?.id,invoice_number:e.number,currency:e.currency,notes:e.notes,business_name:e["business-name"],business_address:e["business-address"],business_contact:e["business-contact"],client_address:e["client-address"],default_session_hours:ee(e["session-hours"],1)}),f=e.out;if(f){const{writeFileSync:y}=await import("node:fs");y(f,g+`
81
81
  `,"utf-8"),b(`Invoice written to ${f}`)}else process.stdout.write(g+`
82
82
  `)}finally{d.close()}}async function At(l){const{positional:c,flags:e}=E(l),i=c[0]??"status",{AgentDaemon:n}=await import("./agent-daemon.js"),t=j();try{const s=new n(t.getDatabase());switch(i){case"init":case"start":{const o=Math.max(10,Math.min(I(e.interval,600),86400)),r=s.start({interval_seconds:o,max_steps:e["max-steps"]!==void 0&&I(e["max-steps"],0)||void 0,project_path:e.project,verbose:e.verbose===!0});if(!r.ok){m(`Agent init failed: ${r.error}`),process.exitCode=1;return}const d=r.status;b(`Agent ${d.pid!=null&&d.pid!==r.pid?"already running":"started"} \u2014 pid ${d.pid}`),console.log(` Interval: ${o}s \xB7 Active goals: ${d.active_goals} \xB7 Total iterations: ${d.total_iterations}`),console.log(p.dim(` Log: ${d.log_file}`));return}case"status":{const o=s.status();k("Wyrm agent"),console.log(o.running?` RUNNING \u2014 pid ${o.pid}${o.started_at?` (since ${o.started_at})`:""}`:" NOT RUNNING. Start it with: wyrm agent init"),console.log(` Active goals: ${o.active_goals} \xB7 Total iterations: ${o.total_iterations}`),o.last_action&&console.log(` Last action (${o.last_action.ran_at}): ${o.last_action.summary} [${o.last_action.result_status??"?"}]`),e.log===!0&&(console.log(`
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contract": "wyrm-cloud-memory-v1",
3
- "version": "8.5.5",
3
+ "version": "8.5.7",
4
4
  "generatedBy": "scripts/gen-tool-manifest.mjs (from the dist/ registry modules — never hand-edited)",
5
5
  "tiers": {
6
6
  "core": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wyrm-mcp",
3
- "version": "8.5.5",
3
+ "version": "8.5.7",
4
4
  "mcpName": "lk.ghosts/wyrm",
5
5
  "description": "Local-first persistent memory for AI agents over MCP. Ground truths, negative learning (recorded failures block repeats), decision causality, hybrid recall, live memory streams, run-attributed fleet memory — a structured SQLite memory on your machine, no cloud or LLM required. Claude / Copilot / Cursor / Windsurf / Codex.",
6
6
  "type": "module",