wyrm-mcp 7.7.0 → 7.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- import{logger as d}from"./logger.js";const o={confidence:.4,recency:.2,relevance:.3,usefulness:.1};function v(e=process.env){const r=e.WYRM_RANK_WEIGHTS;if(!r)return{...o};try{const s=JSON.parse(r),n={confidence:c(s.confidence??o.confidence),recency:c(s.recency??o.recency),relevance:c(s.relevance??o.relevance),usefulness:c(s.usefulness??o.usefulness)},t=n.confidence+n.recency+n.relevance+n.usefulness;return t<=0?{...o}:(n.confidence/=t,n.recency/=t,n.relevance/=t,n.usefulness/=t,n)}catch(s){return d.warn(`Invalid WYRM_RANK_WEIGHTS, using defaults: ${s.message}`),{...o}}}function c(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}const p=.5,y=/^\s*\[auto:(precompact|sessionend|sessionstart)/i;function A(e){return e&&y.test(e)?p:0}function M(e,r,s=new Date){const n=c(e.confidence??.5),t=c(e.usefulness??.5),a=c(e.relevance??.5),u=e.updatedAt?Math.max(0,(s.getTime()-new Date(e.updatedAt).getTime())/(1440*60*1e3)):1/0,f=Number.isFinite(u)?Math.exp(-u/30):0,i=n*r.confidence+f*r.recency+a*r.relevance+t*r.usefulness,l=c(e.sourcePenalty??0);return c(i*(1-l))}export{p as AUTO_SUMMARY_PENALTY,o as DEFAULT_WEIGHTS,A as autoSummaryPenalty,v as loadWeightsFromEnv,M as score};
1
+ import{logger as _}from"./logger.js";const o={confidence:.4,recency:.2,relevance:.3,usefulness:.1};function R(e=process.env){const n=e.WYRM_RANK_WEIGHTS;if(!n)return{...o};try{const t=JSON.parse(n),c={confidence:s(t.confidence??o.confidence),recency:s(t.recency??o.recency),relevance:s(t.relevance??o.relevance),usefulness:s(t.usefulness??o.usefulness)},r=c.confidence+c.recency+c.relevance+c.usefulness;return r<=0?{...o}:(c.confidence/=r,c.recency/=r,c.relevance/=r,c.usefulness/=r,c)}catch(t){return _.warn(`Invalid WYRM_RANK_WEIGHTS, using defaults: ${t.message}`),{...o}}}function s(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}const d=.25,f=30;function N(e=process.env){const n=Number(e.WYRM_RECALL_RECENCY_WEIGHT);return Number.isFinite(n)?s(n):d}function L(e=process.env){const n=Number(e.WYRM_RECALL_RECENCY_HALFLIFE_DAYS);return Number.isFinite(n)&&n>=1?n:f}function T(e,n,t,c=new Date){const r=s(n);if(r===0)return 1;const a=e&&/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(e)?e.replace(" ","T")+"Z":e,u=a?new Date(a).getTime():NaN;if(!Number.isFinite(u))return 1-r;const i=Math.max(0,(c.getTime()-u)/864e5),l=t>=1?t:f;return 1-r+r*Math.pow(2,-i/l)}const p=.5,A=/^\s*\[auto:(precompact|sessionend|sessionstart)/i;function M(e){return e&&A.test(e)?p:0}function m(e,n,t=new Date){const c=s(e.confidence??.5),r=s(e.usefulness??.5),a=s(e.relevance??.5),u=e.updatedAt?Math.max(0,(t.getTime()-new Date(e.updatedAt).getTime())/(1440*60*1e3)):1/0,i=Number.isFinite(u)?Math.exp(-u/30):0,l=c*n.confidence+i*n.recency+a*n.relevance+r*n.usefulness,E=s(e.sourcePenalty??0);return s(l*(1-E))}export{p as AUTO_SUMMARY_PENALTY,f as DEFAULT_RECALL_RECENCY_HALFLIFE_DAYS,d as DEFAULT_RECALL_RECENCY_WEIGHT,o as DEFAULT_WEIGHTS,M as autoSummaryPenalty,R as loadWeightsFromEnv,L as recallRecencyHalfLifeDays,N as recallRecencyWeight,T as recencyMultiplier,m as score};
@@ -1,73 +1,73 @@
1
- import{join as H}from"path";import{TOOL_ANNOTATIONS as A}from"../tool-annotations.js";import{renderResult as S,withGlyph as I,renderErrorResponse as E,validationErrorBody as T}from"../render.js";import{ValidationError as B,asEnum as K}from"../validate.js";import{daemonOr as D}from"../daemon-writer.js";import{classifyCapture as J}from"../capture.js";import{extractCandidates as W,candidateToArtifact as O,escapeLikePattern as L}from"../auto-capture.js";import{parseTrace as Y,segmentsToText as Q}from"../trace-harvest.js";import{getActor as X,runWithActor as G}from"./boundary.js";import{harvestProjects as V}from"../harvest.js";import{readFileSync as F,readdirSync as z,statSync as M}from"fs";import{join as N}from"path";import{homedir as Z}from"os";import{readSpecDir as ee,specTaskSignature as te}from"../spec-kit.js";const he=[{name:"wyrm_capture",description:"Use to save anything worth keeping - the single write funnel. Auto-classifies notes, decisions, and lessons into quest, ground truth, or memory; risky writes queue for wyrm_review. mode=direct (store a proven pattern or lesson learned so future agents reuse it), extract (pull memories from a conversation transcript or freeform text), trace (harvest a session JSONL / tool-call log into run-tagged review candidates), session (close out a work session into reusable knowledge), artifacts (harvest a repo's READMEs and recent commits into durable facts), import source=git|pr|rules, spec (turn a tasks.md into tracked work items), checklist. Keywords: remember this, jot down, write down, future reference.",inputSchema:{type:"object",properties:{content:{type:"string",description:"classify/rules"},project_id:{type:"number",description:"classify/import/spec"},tags:{type:"array",items:{type:"string"}},mode:{type:"string",enum:["auto","quest","truth","memory","classify","direct","extract","trace","session","artifacts","import","spec","checklist"],description:"quest|truth|memory force the type"},source:{type:"string",enum:["git","pr","rules"],description:"import"},projectPath:{type:"string",description:"non-classify"},kind:{type:"string",description:"direct"},problem:{type:"string",description:"direct"},validatedFix:{type:"string",description:"direct"},text:{type:"string",description:"extract"},sessionId:{type:"string",description:"session"},candidates:{type:"array",items:{type:"object"},description:"session"},dryRun:{type:"boolean",description:"artifacts"},commits:{type:"array",items:{type:"object"},description:"import git"},title:{type:"string",description:"import pr"},body:{type:"string",description:"import pr"},specDir:{type:"string",description:"spec"},problemType:{type:"string",description:"checklist"},whenToUse:{type:"string",description:"checklist"},steps:{type:"array",items:{type:"string"},description:"checklist"}},required:[]},outputSchema:{type:"object",properties:{status:{type:"string",enum:["captured","queued_for_review"]},type:{type:"string"},subtype:{type:"string"},confidence:{type:"number"},reasoning:{type:"string"},id:{type:"integer"},ref:{type:"string"},needs_review:{type:"boolean"},reason:{type:"string"},artifact_id:{type:"integer"},conflicts_with:{type:"array"},advisory_conflicts:{type:"array"}},required:["status"]},annotations:A.wyrm_capture,aliases:[],handler:async(j,{store:v,raw:b,memory:u,truths:h,cache:w})=>{const{content:n,project_id:m,projectPath:o,tags:y,mode:i}=j;if(typeof n!="string"||!n.trim()){const f=j;return f.problem||f.validated_fix||f.validatedFix||f.kind?E(T("wyrm_capture","mode","you passed pattern/lesson fields (kind/problem/validated_fix) \u2014 set mode:'direct' to store them as a distilled artifact.")):E(T("wyrm_capture","content","content is required for auto capture (or use mode:'direct' with problem + validated_fix)."))}let d=J(n);i&&i!=="auto"&&(d={type:i,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[i]??i,confidence:100,reasoning:`Mode override: ${i}`});const{type:p,subtype:c,confidence:g,reasoning:r}=d,e=m??(o?v.getProject(o)?.id??null:null);let a=0,s="",_=!1,t;if(p==="quest"){if(e===null)return E(T("wyrm_capture","projectPath","is required for quest capture"));a=(await D("quest_add",e,{title:n.slice(0,200),description:"",priority:"medium",tags:y?.join(",")},()=>v.addQuest(e,n.slice(0,200),"","medium",y?.join(",")))).id,s="quest",w.invalidate("wyrm_all_quests"),w.invalidate("wyrm_stats")}else if(p==="truth"){if(e===null)return E(T("wyrm_capture","projectPath","is required for truth capture"));if(g>=80){const f=c??"other",q=h.getCurrent(e).filter(x=>x.category===f);if(q.length>0){const x={kind:"pattern",problem:`Potential conflict with ${q.length} existing truth(s) in category "${f}"`,validatedFix:n,whyItWorked:"Pending review \u2014 possible supersession",tags:y??[],confidence:g/100,needsReview:1},l=await D("artifact_add",e,x,()=>u.add(e,x));return S({status:"queued_for_review",reason:"conflict_check",artifact_id:l.id,conflicts_with:q.map(k=>({id:k.id,content:k.value.slice(0,80)}))})}}if(i!=="truth"&&g<100){const f={kind:"pattern",problem:n,validatedFix:"",whyItWorked:"",tags:y??[],confidence:g/100,needsReview:1};a=(await D("artifact_add",e,f,()=>u.add(e,f))).id,s="mem",_=!0}else{const f={category:"decision",key:n.slice(0,60),value:n};a=(await D("truth_set",e,f,()=>h.set(e,f))).id,s="truth",w.invalidate("wyrm_truth_get"),w.invalidate("wyrm_context_build")}}else{if(e===null)return E(T("wyrm_capture","projectPath","is required for memory capture"));const f=g>=75,P={kind:c,problem:n,validatedFix:"",whyItWorked:"",tags:y??[],confidence:g/100,needsReview:f?0:1};if(a=(await D("artifact_add",e,P,()=>u.add(e,P))).id,s="mem",_=!f,c==="heuristic"&&g>=75&&e!==null)try{const x=n.replace(/['"*]/g," ").trim().split(/\s+/).slice(0,5).join(" "),l=b().prepare(`
1
+ import{join as H}from"path";import{TOOL_ANNOTATIONS as A}from"../tool-annotations.js";import{renderResult as S,withGlyph as I,renderErrorResponse as E,validationErrorBody as T}from"../render.js";import{ValidationError as B,asEnum as K}from"../validate.js";import{daemonOr as D}from"../daemon-writer.js";import{classifyCapture as J}from"../capture.js";import{extractCandidates as W,candidateToArtifact as O,escapeLikePattern as L}from"../auto-capture.js";import{parseTrace as Y,segmentsToText as Q}from"../trace-harvest.js";import{getActor as X,runWithActor as G}from"./boundary.js";import{harvestProjects as V}from"../harvest.js";import{readFileSync as F,readdirSync as z,statSync as M}from"fs";import{join as N}from"path";import{homedir as Z}from"os";import{readSpecDir as ee,specTaskSignature as te}from"../spec-kit.js";const he=[{name:"wyrm_capture",description:"Use to save anything worth keeping - the single write funnel. Auto-classifies notes, decisions, and lessons into quest, ground truth, or memory; risky writes queue for wyrm_review. mode=direct (store a proven pattern or lesson learned so future agents reuse it), extract (pull memories from a conversation transcript or freeform text), trace (harvest a session JSONL / tool-call log into run-tagged review candidates), session (close out a work session into reusable knowledge), artifacts (harvest a repo's READMEs and recent commits into durable facts), import source=git|pr|rules, spec (turn a tasks.md into tracked work items), checklist. Keywords: remember this, jot down, write down, future reference.",inputSchema:{type:"object",properties:{content:{type:"string",description:"classify/rules"},project_id:{type:"number",description:"classify/import/spec"},tags:{type:"array",items:{type:"string"}},mode:{type:"string",enum:["auto","quest","truth","memory","classify","direct","extract","trace","session","artifacts","import","spec","checklist"],description:"quest|truth|memory force the type"},source:{type:"string",enum:["git","pr","rules"],description:"import"},projectPath:{type:"string",description:"non-classify"},kind:{type:"string",description:"direct"},problem:{type:"string",description:"direct"},validatedFix:{type:"string",description:"direct"},text:{type:"string",description:"extract"},sessionId:{type:"string",description:"session"},candidates:{type:"array",items:{type:"object"},description:"session"},dryRun:{type:"boolean",description:"artifacts"},commits:{type:"array",items:{type:"object"},description:"import git"},title:{type:"string",description:"import pr"},body:{type:"string",description:"import pr"},specDir:{type:"string",description:"spec"},problemType:{type:"string",description:"checklist"},whenToUse:{type:"string",description:"checklist"},steps:{type:"array",items:{type:"string"},description:"checklist"}},required:[]},outputSchema:{type:"object",properties:{status:{type:"string",enum:["captured","queued_for_review"]},type:{type:"string"},subtype:{type:"string"},confidence:{type:"number"},reasoning:{type:"string"},id:{type:"integer"},ref:{type:"string"},needs_review:{type:"boolean"},reason:{type:"string"},artifact_id:{type:"integer"},conflicts_with:{type:"array"},advisory_conflicts:{type:"array"}},required:["status"]},annotations:A.wyrm_capture,aliases:[],handler:async(b,{store:j,raw:k,memory:l,truths:g,cache:w})=>{const{content:a,project_id:u,projectPath:o,tags:m,mode:s}=b;if(typeof a!="string"||!a.trim()){const f=b;return f.problem||f.validated_fix||f.validatedFix||f.kind?E(T("wyrm_capture","mode","you passed pattern/lesson fields (kind/problem/validated_fix) \u2014 set mode:'direct' to store them as a distilled artifact.")):E(T("wyrm_capture","content","content is required for auto capture (or use mode:'direct' with problem + validated_fix)."))}let n=J(a);s&&s!=="auto"&&(n={type:s,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[s]??s,confidence:100,reasoning:`Mode override: ${s}`});const{type:d,subtype:c,confidence:v,reasoning:r}=n,e=u??(o?j.getProject(o)?.id??null:null);let i=0,y="",h=!1,t;if(d==="quest"){if(e===null)return E(T("wyrm_capture","projectPath","is required for quest capture"));i=(await D("quest_add",e,{title:a.slice(0,200),description:"",priority:"medium",tags:m?.join(",")},()=>j.addQuest(e,a.slice(0,200),"","medium",m?.join(",")))).id,y="quest",w.invalidate("wyrm_all_quests"),w.invalidate("wyrm_stats")}else if(d==="truth"){if(e===null)return E(T("wyrm_capture","projectPath","is required for truth capture"));if(v>=80){const f=c??"other",q=g.getCurrent(e).filter(x=>x.category===f);if(q.length>0){const x={kind:"pattern",problem:`Potential conflict with ${q.length} existing truth(s) in category "${f}"`,validatedFix:a,whyItWorked:"Pending review \u2014 possible supersession",tags:m??[],confidence:v/100,needsReview:1},p=await D("artifact_add",e,x,()=>l.add(e,x));return S({status:"queued_for_review",reason:"conflict_check",artifact_id:p.id,conflicts_with:q.map($=>({id:$.id,content:$.value.slice(0,80)}))})}}if(s!=="truth"&&v<100){const f={kind:"pattern",problem:a,validatedFix:"",whyItWorked:"",tags:m??[],confidence:v/100,needsReview:1};i=(await D("artifact_add",e,f,()=>l.add(e,f))).id,y="mem",h=!0}else{const f={category:"decision",key:a.slice(0,60),value:a};i=(await D("truth_set",e,f,()=>g.set(e,f))).id,y="truth",w.invalidate("wyrm_truth_get"),w.invalidate("wyrm_context_build")}}else{if(e===null)return E(T("wyrm_capture","projectPath","is required for memory capture"));const f=v>=75,P={kind:c,problem:a,validatedFix:"",whyItWorked:"",tags:m??[],confidence:v/100,needsReview:f?0:1};if(i=(await D("artifact_add",e,P,()=>l.add(e,P))).id,y="mem",h=!f,c==="heuristic"&&v>=75&&e!==null)try{const x=a.replace(/['"*]/g," ").trim().split(/\s+/).slice(0,5).join(" "),p=k().prepare(`
2
2
  SELECT a.id, a.problem FROM memory_artifacts a
3
3
  JOIN memory_artifacts_fts fts ON a.id = fts.rowid
4
4
  WHERE fts MATCH ? AND a.project_id = ? AND a.kind = 'heuristic' AND a.needs_review = 0
5
5
  LIMIT 3
6
- `).all(x,e);l.length>0&&(t=l.map(k=>({id:k.id,content:k.problem.slice(0,80)})))}catch{}}const $={status:"captured",type:p,subtype:c,confidence:g,reasoning:r,id:a,ref:`${s}:${a}`,needs_review:_,...t&&t.length>0?{advisory_conflicts:t}:{}};return S($,(f,P)=>{let q=`Captured as ${f.type}: ${f.subtype}
6
+ `).all(x,e);p.length>0&&(t=p.map($=>({id:$.id,content:$.problem.slice(0,80)})))}catch{}}const _={status:"captured",type:d,subtype:c,confidence:v,reasoning:r,id:i,ref:`${y}:${i}`,needs_review:h,...t&&t.length>0?{advisory_conflicts:t}:{}};return S(_,(f,P)=>{let q=`Captured as ${f.type}: ${f.subtype}
7
7
  Confidence: ${f.confidence}% | ${f.reasoning}
8
8
  ID: ${f.ref}`;f.needs_review&&(q+=`
9
9
  `+I(P.warn,"Stored for review -- run `wyrm_review` to activate"));const x=f.advisory_conflicts;return x&&x.length>0&&(q+=`
10
10
 
11
11
  `+I(P.warn,`Advisory: ${x.length} similar heuristic(s) found:`)+`
12
- `+x.map(l=>` ${P.bullet} [${l.id}] ${l.content}`).join(`
13
- `)),q})}},{name:"wyrm_remember",description:"Store a distilled knowledge artifact \u2014 proven patterns, lessons learned, anti-patterns, and reasoning traces. These are recalled automatically by wyrm_context_build to help AI models apply past knowledge to new tasks. Example: wyrm_remember({ projectPath: '/home/user/api', kind: 'anti_pattern', problem: 'Jest suite hung after adding the SSE server', validatedFix: 'close() the server in afterAll \u2014 its keep-alive timer held the event loop open', whyItWorked: 'open handles block jest exit', outcome: 'positive', tags: ['jest', 'sse'] })",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project this knowledge belongs to"},kind:{type:"string",enum:["reasoning_trace","lesson","pattern","anti_pattern","heuristic"],description:"reasoning_trace: a solved problem with steps; lesson: a general insight; pattern: a proven approach; anti_pattern: what NOT to do; heuristic: a rule of thumb"},problem:{type:"string",description:"What was being solved or observed (be specific and searchable)"},constraints:{type:"string",description:"What conditions or constraints applied"},validatedFix:{type:"string",description:"What actually worked \u2014 the validated solution or approach"},whyItWorked:{type:"string",description:"The insight behind WHY this worked (key for transfer learning)"},outcome:{type:"string",enum:["positive","negative","neutral"],description:"Was this approach successful?"},tags:{type:"array",items:{type:"string"},description:"Searchable tags (e.g. ['auth', 'rate-limit', 'typescript'])"},confidence:{type:"number",description:"Confidence level 0.0\u20131.0 (default: 1.0)"},sourceSessionId:{type:"number",description:"Session ID where this was discovered (optional)"}},required:["projectPath","kind","problem"]},outputSchema:{type:"object",properties:{id:{type:"integer"},kind:{type:"string",enum:["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]},problem:{type:"string"},validated_fix:{type:["string","null"]},why_it_worked:{type:["string","null"]},confidence:{type:"number"},tags:{type:["string","null"]}},required:["id","kind","problem","validated_fix","why_it_worked","confidence","tags"]},annotations:A.wyrm_remember,aliases:[],handler:async(j,{store:v,memory:b})=>{const{projectPath:u,kind:h,problem:w,constraints:n,validatedFix:m,whyItWorked:o,outcome:y,tags:i,confidence:d,sourceSessionId:p}=j,c=K("kind",h,["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]);if(c===void 0)throw new B("kind","is required");const g=v.getProject(u);if(!g)return E(T("wyrm_remember","projectPath","project not found"));const r={kind:c,problem:w,constraints:n,validatedFix:m,whyItWorked:o,outcome:y,tags:i,confidence:d,sourceSessionId:p},e=await D("artifact_add",g.id,r,()=>b.add(g.id,r)),a={id:e.id,kind:e.kind,problem:e.problem,validated_fix:e.validated_fix??null,why_it_worked:e.why_it_worked??null,confidence:e.confidence,tags:e.tags??null};return S(a,(s,_)=>{let t=I(_.brand,"**Memory Stored**")+`
14
-
15
- `;return t+=`${_.bullet} **Kind:** ${s.kind}
16
- `,t+=`${_.bullet} **ID:** ${s.id}
17
- `,t+=`${_.bullet} **Problem:** ${s.problem}
18
- `,s.validated_fix&&(t+=`${_.bullet} **Solution:** ${s.validated_fix}
19
- `),s.why_it_worked&&(t+=`${_.bullet} **Why it worked:** ${s.why_it_worked}
20
- `),t+=`${_.bullet} **Confidence:** ${(s.confidence*100).toFixed(0)}%
21
- `,s.tags&&(t+=`${_.bullet} **Tags:** ${s.tags}
22
- `),t+="\n_Use `wyrm_recall` to retrieve similar memories, or `wyrm_context_build` to assemble a task brief._",t})}},{name:"wyrm_auto_capture",description:"Auto-extract durable memories from freeform text (a session transcript, notes, a chat) into the REVIEW QUEUE. A LOCAL extractor \u2014 a configurable Ollama model (WYRM_EXTRACT_MODEL / the `model` arg) if set, else a deterministic heuristic \u2014 pulls out truths, failures, decisions, patterns, and lessons as needs_review candidates; approve/reject with wyrm_review (nothing auto-trusted). Closes the 'just talk, it remembers' gap without a cloud LLM. Deduped + idempotent. Example: wyrm_auto_capture({ projectPath: '/home/user/api', text: 'Deploy failed twice because wrangler.toml pointed at the old KV id; switched to the new binding and decided to pin binding names in CI.' })",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project to file the extracted candidates under"},text:{type:"string",description:"Freeform text to extract durable memories from"},model:{type:"string",description:"Optional Ollama model for extraction (overrides WYRM_EXTRACT_MODEL); omit for deterministic extraction"}},required:["projectPath","text"]},outputSchema:{type:"object",properties:{method:{type:"string"},model:{type:["string","null"]},added:{type:"integer"},skipped:{type:"integer"},candidates:{type:"array",items:{type:"object",properties:{kind:{type:"string"},text:{type:"string"}},required:["kind","text"]}}},required:["method","model","added","skipped","candidates"]},annotations:A.wyrm_auto_capture,aliases:[],handler:async(j,{store:v,raw:b,memory:u,cache:h})=>{const{projectPath:w,text:n,model:m}=j,o=v.getProject(w);if(!o)return E(T("wyrm_auto_capture","projectPath","project not found"));if(!n||n.trim().length<20)return E(T("wyrm_auto_capture","text","must be at least 20 characters"));const{candidates:y,method:i,model:d}=await W(n,{model:m}),p=b();let c=0,g=0;for(const e of y){const a=O(e),s=a.tags[a.tags.length-1];if(p.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(o.id,"%"+L(s)+"%")){g++;continue}u.add(o.id,{kind:a.kind,problem:a.problem,tags:a.tags,confidence:a.confidence,needsReview:1,createdBy:"auto-extract"}),c++}c>0&&h.invalidate();const r={method:i,model:d??null,added:c,skipped:g,candidates:y.slice(0,8).map(e=>({kind:e.kind,text:e.text.slice(0,80)}))};return S(r,(e,a)=>{const s=e.candidates.map(_=>` ${a.bullet} [${_.kind}] ${_.text}`).join(`
23
- `);return I(a.brand,`Auto-capture (${e.method}${e.model?` - ${e.model}`:""}) -- ${e.added} candidate(s) -> review queue, ${e.skipped} already present.`)+`
24
- ${s}
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:A.wyrm_capture_trace,aliases:[],handler:async(j,{store:v,raw:b,memory:u,cache:h})=>{const{projectPath:w,trace:n,path:m,format:o,run_id:y,model:i}=j,d=v.getProject(w);if(!d)return E(T("wyrm_capture_trace","projectPath","project not found"));const p=X(),c=typeof y=="string"&&y.trim()?y.trim().slice(0,64):p.run_id;let g="",r="inline";if(typeof n=="string"&&n.trim())g=n,r="inline";else if(typeof m=="string"&&m.trim()){let l=m.trim();(l==="~"||l.startsWith("~/"))&&(l=N(Z(),l.slice(1)));try{if(M(l).isDirectory()){const C=z(l).map(R=>N(l,R)).filter(R=>{try{return M(R).isFile()}catch{return!1}}).sort((R,U)=>M(U).mtimeMs-M(R).mtimeMs);if(C.length===0)return E(T("wyrm_capture_trace","path","no trace files in directory"));g=F(C[0],"utf-8"),r=C[0]}else g=F(l,"utf-8"),r=l}catch(k){return E(T("wyrm_capture_trace","path",`could not read trace path: ${k.message}`))}}else return E(T("wyrm_capture_trace","trace","provide inline trace or path to trace file"));const{segments:e,format:a}=Y(g,o??"auto"),s=Q(e);if(s.trim().length<20){const l={method:"deterministic",model:null,format:a,source:r,run_id:c,segments:e.length,added:0,skipped:0,candidates:[]};return S(l,(k,C)=>I(C.brand,`Trace harvest (${k.format}) -- no durable content extracted from ${k.segments} segment(s).`))}const{candidates:_,method:t,model:$}=await W(s,{model:i}),f=b();let P=0,q=0;for(const l of _){const k=O(l),C=k.tags[k.tags.length-1];if(f.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(d.id,"%"+L(C)+"%")){q++;continue}const R=c?[...k.tags,"trace",`run:${c}`]:[...k.tags,"trace"];G({agent_id:p.agent_id,run_id:c,source:c?"param":p.source},()=>u.add(d.id,{kind:k.kind,problem:k.problem,tags:R,confidence:k.confidence,needsReview:1,createdBy:"trace-harvest"})),P++}P>0&&h.invalidate();const x={method:t,model:$??null,format:a,source:r,run_id:c,segments:e.length,added:P,skipped:q,candidates:_.slice(0,8).map(l=>({kind:l.kind,text:l.text.slice(0,80)}))};return S(x,(l,k)=>{const C=l.candidates.map(R=>` ${k.bullet} [${R.kind}] ${R.text}`).join(`
27
- `);return I(k.brand,`Trace harvest (${l.format}, ${l.method}${l.model?` - ${l.model}`:""}) -- ${l.segments} segment(s) -> ${l.added} candidate(s) to review queue, ${l.skipped} already present${l.run_id?` [run:${l.run_id}]`:""}.`)+(C?`
12
+ `+x.map(p=>` ${P.bullet} [${p.id}] ${p.content}`).join(`
13
+ `)),q})}},{name:"wyrm_remember",description:"Store a distilled knowledge artifact \u2014 proven patterns, lessons learned, anti-patterns, and reasoning traces. These are recalled automatically by wyrm_context_build to help AI models apply past knowledge to new tasks. Example: wyrm_remember({ projectPath: '/home/user/api', kind: 'anti_pattern', problem: 'Jest suite hung after adding the SSE server', validatedFix: 'close() the server in afterAll \u2014 its keep-alive timer held the event loop open', whyItWorked: 'open handles block jest exit', outcome: 'positive', tags: ['jest', 'sse'] })",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project this knowledge belongs to"},kind:{type:"string",enum:["reasoning_trace","lesson","pattern","anti_pattern","heuristic"],description:"reasoning_trace: a solved problem with steps; lesson: a general insight; pattern: a proven approach; anti_pattern: what NOT to do; heuristic: a rule of thumb"},problem:{type:"string",description:"What was being solved or observed (be specific and searchable)"},constraints:{type:"string",description:"What conditions or constraints applied"},validatedFix:{type:"string",description:"What actually worked \u2014 the validated solution or approach"},whyItWorked:{type:"string",description:"The insight behind WHY this worked (key for transfer learning)"},outcome:{type:"string",enum:["positive","negative","neutral"],description:"Was this approach successful?"},tags:{type:"array",items:{type:"string"},description:"Searchable tags (e.g. ['auth', 'rate-limit', 'typescript'])"},confidence:{type:"number",description:"Confidence level 0.0\u20131.0 (default: 1.0)"},sourceSessionId:{type:"number",description:"Session ID where this was discovered (optional)"}},required:["projectPath","kind","problem"]},outputSchema:{type:"object",properties:{id:{type:"integer"},kind:{type:"string",enum:["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]},problem:{type:"string"},validated_fix:{type:["string","null"]},why_it_worked:{type:["string","null"]},confidence:{type:"number"},tags:{type:["string","null"]}},required:["id","kind","problem","validated_fix","why_it_worked","confidence","tags"]},annotations:A.wyrm_remember,aliases:[],handler:async(b,{store:j,memory:k})=>{const{projectPath:l,kind:g,problem:w,constraints:a,outcome:u,tags:o,confidence:m,sourceSessionId:s}=b,n=b,d=n.validatedFix??n.validated_fix,c=n.whyItWorked??n.why_it_worked,v=K("kind",g,["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]);if(v===void 0)throw new B("kind","is required");const r=j.getProject(l);if(!r)return E(T("wyrm_remember","projectPath","project not found"));const e={kind:v,problem:w,constraints:a,validatedFix:d,whyItWorked:c,outcome:u,tags:o,confidence:m,sourceSessionId:s},i=await D("artifact_add",r.id,e,()=>k.add(r.id,e)),y={id:i.id,kind:i.kind,problem:i.problem,validated_fix:i.validated_fix??null,why_it_worked:i.why_it_worked??null,confidence:i.confidence,tags:i.tags??null};return S(y,(h,t)=>{let _=I(t.brand,"**Memory Stored**")+`
14
+
15
+ `;return _+=`${t.bullet} **Kind:** ${h.kind}
16
+ `,_+=`${t.bullet} **ID:** ${h.id}
17
+ `,_+=`${t.bullet} **Problem:** ${h.problem}
18
+ `,h.validated_fix&&(_+=`${t.bullet} **Solution:** ${h.validated_fix}
19
+ `),h.why_it_worked&&(_+=`${t.bullet} **Why it worked:** ${h.why_it_worked}
20
+ `),_+=`${t.bullet} **Confidence:** ${(h.confidence*100).toFixed(0)}%
21
+ `,h.tags&&(_+=`${t.bullet} **Tags:** ${h.tags}
22
+ `),_+="\n_Use `wyrm_recall` to retrieve similar memories, or `wyrm_context_build` to assemble a task brief._",_})}},{name:"wyrm_auto_capture",description:"Auto-extract durable memories from freeform text (a session transcript, notes, a chat) into the REVIEW QUEUE. A LOCAL extractor \u2014 a configurable Ollama model (WYRM_EXTRACT_MODEL / the `model` arg) if set, else a deterministic heuristic \u2014 pulls out truths, failures, decisions, patterns, and lessons as needs_review candidates; approve/reject with wyrm_review (nothing auto-trusted). Closes the 'just talk, it remembers' gap without a cloud LLM. Deduped + idempotent. Example: wyrm_auto_capture({ projectPath: '/home/user/api', text: 'Deploy failed twice because wrangler.toml pointed at the old KV id; switched to the new binding and decided to pin binding names in CI.' })",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project to file the extracted candidates under"},text:{type:"string",description:"Freeform text to extract durable memories from"},model:{type:"string",description:"Optional Ollama model for extraction (overrides WYRM_EXTRACT_MODEL); omit for deterministic extraction"}},required:["projectPath","text"]},outputSchema:{type:"object",properties:{method:{type:"string"},model:{type:["string","null"]},added:{type:"integer"},skipped:{type:"integer"},candidates:{type:"array",items:{type:"object",properties:{kind:{type:"string"},text:{type:"string"}},required:["kind","text"]}}},required:["method","model","added","skipped","candidates"]},annotations:A.wyrm_auto_capture,aliases:[],handler:async(b,{store:j,raw:k,memory:l,cache:g})=>{const{projectPath:w,text:a,model:u}=b,o=j.getProject(w);if(!o)return E(T("wyrm_auto_capture","projectPath","project not found"));if(!a||a.trim().length<20)return E(T("wyrm_auto_capture","text","must be at least 20 characters"));const{candidates:m,method:s,model:n}=await W(a,{model:u}),d=k();let c=0,v=0;for(const e of m){const i=O(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(o.id,"%"+L(y)+"%")){v++;continue}l.add(o.id,{kind:i.kind,problem:i.problem,tags:i.tags,confidence:i.confidence,needsReview:1,createdBy:"auto-extract"}),c++}c>0&&g.invalidate();const r={method:s,model:n??null,added:c,skipped:v,candidates:m.slice(0,8).map(e=>({kind:e.kind,text:e.text.slice(0,80)}))};return S(r,(e,i)=>{const y=e.candidates.map(h=>` ${i.bullet} [${h.kind}] ${h.text}`).join(`
23
+ `);return I(i.brand,`Auto-capture (${e.method}${e.model?` - ${e.model}`:""}) -- ${e.added} candidate(s) -> review queue, ${e.skipped} already present.`)+`
24
+ ${y}
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:A.wyrm_capture_trace,aliases:[],handler:async(b,{store:j,raw:k,memory:l,cache:g})=>{const{projectPath:w,trace:a,path:u,format:o,run_id:m,model:s}=b,n=j.getProject(w);if(!n)return E(T("wyrm_capture_trace","projectPath","project not found"));const d=X(),c=typeof m=="string"&&m.trim()?m.trim().slice(0,64):d.run_id;let v="",r="inline";if(typeof a=="string"&&a.trim())v=a,r="inline";else if(typeof u=="string"&&u.trim()){let p=u.trim();(p==="~"||p.startsWith("~/"))&&(p=N(Z(),p.slice(1)));try{if(M(p).isDirectory()){const C=z(p).map(R=>N(p,R)).filter(R=>{try{return M(R).isFile()}catch{return!1}}).sort((R,U)=>M(U).mtimeMs-M(R).mtimeMs);if(C.length===0)return E(T("wyrm_capture_trace","path","no trace files in directory"));v=F(C[0],"utf-8"),r=C[0]}else v=F(p,"utf-8"),r=p}catch($){return E(T("wyrm_capture_trace","path",`could not read trace path: ${$.message}`))}}else return E(T("wyrm_capture_trace","trace","provide inline trace or path to trace file"));const{segments:e,format:i}=Y(v,o??"auto"),y=Q(e);if(y.trim().length<20){const p={method:"deterministic",model:null,format:i,source:r,run_id:c,segments:e.length,added:0,skipped:0,candidates:[]};return S(p,($,C)=>I(C.brand,`Trace harvest (${$.format}) -- no durable content extracted from ${$.segments} segment(s).`))}const{candidates:h,method:t,model:_}=await W(y,{model:s}),f=k();let P=0,q=0;for(const p of h){const $=O(p),C=$.tags[$.tags.length-1];if(f.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(n.id,"%"+L(C)+"%")){q++;continue}const R=c?[...$.tags,"trace",`run:${c}`]:[...$.tags,"trace"];G({agent_id:d.agent_id,run_id:c,source:c?"param":d.source},()=>l.add(n.id,{kind:$.kind,problem:$.problem,tags:R,confidence:$.confidence,needsReview:1,createdBy:"trace-harvest"})),P++}P>0&&g.invalidate();const x={method:t,model:_??null,format:i,source:r,run_id:c,segments:e.length,added:P,skipped:q,candidates:h.slice(0,8).map(p=>({kind:p.kind,text:p.text.slice(0,80)}))};return S(x,(p,$)=>{const C=p.candidates.map(R=>` ${$.bullet} [${R.kind}] ${R.text}`).join(`
27
+ `);return I($.brand,`Trace harvest (${p.format}, ${p.method}${p.model?` - ${p.model}`:""}) -- ${p.segments} segment(s) -> ${p.added} candidate(s) to review queue, ${p.skipped} already present${p.run_id?` [run:${p.run_id}]`:""}.`)+(C?`
28
28
  ${C}`:"")+`
29
29
 
30
- Approve/reject with wyrm_review.`})}},{name:"wyrm_distill",description:"Distill a work session into candidate memory artifacts for review. Parses the session's objectives, decisions, and outcomes into structured artifacts (lessons, patterns, anti-patterns) and queues them for approval via wyrm_review. Use at session end to extract institutional knowledge.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root path"},sessionId:{type:"string",description:"Session ID to distill"},candidates:{type:"array",description:"Pre-parsed candidate artifacts to store for review",items:{type:"object",properties:{kind:{type:"string",enum:["lesson","pattern","anti_pattern","heuristic","reasoning_trace"]},title:{type:"string"},content:{type:"string"},tags:{type:"array",items:{type:"string"}},confidence:{type:"number"}},required:["kind","title","content"]}}},required:["projectPath","candidates"]},outputSchema:{type:"object",properties:{count:{type:"integer"},artifacts:{type:"array",items:{type:"object",properties:{id:{type:"integer"},kind:{type:"string"},title:{type:"string"}},required:["id","kind","title"]}}},required:["count","artifacts"]},annotations:A.wyrm_distill,aliases:[],handler:(j,{store:v,memory:b})=>{const{projectPath:u,candidates:h}=j,w=v.getProject(u);if(!w)return{content:[{type:"text",text:`Project not found: ${u}`}],isError:!0};if(!h||h.length===0)return{content:[{type:"text",text:`**Distill**
30
+ Approve/reject with wyrm_review.`})}},{name:"wyrm_distill",description:"Distill a work session into candidate memory artifacts for review. Parses the session's objectives, decisions, and outcomes into structured artifacts (lessons, patterns, anti-patterns) and queues them for approval via wyrm_review. Use at session end to extract institutional knowledge.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root path"},sessionId:{type:"string",description:"Session ID to distill"},candidates:{type:"array",description:"Pre-parsed candidate artifacts to store for review",items:{type:"object",properties:{kind:{type:"string",enum:["lesson","pattern","anti_pattern","heuristic","reasoning_trace"]},title:{type:"string"},content:{type:"string"},tags:{type:"array",items:{type:"string"}},confidence:{type:"number"}},required:["kind","title","content"]}}},required:["projectPath","candidates"]},outputSchema:{type:"object",properties:{count:{type:"integer"},artifacts:{type:"array",items:{type:"object",properties:{id:{type:"integer"},kind:{type:"string"},title:{type:"string"}},required:["id","kind","title"]}}},required:["count","artifacts"]},annotations:A.wyrm_distill,aliases:[],handler:(b,{store:j,memory:k})=>{const{projectPath:l,candidates:g}=b,w=j.getProject(l);if(!w)return{content:[{type:"text",text:`Project not found: ${l}`}],isError:!0};if(!g||g.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 n=[];for(const o of h){const y=b.add(w.id,{kind:o.kind,problem:o.title,validatedFix:o.content,tags:o.tags??[],confidence:o.confidence??.7,needsReview:1});n.push({id:y.id,kind:o.kind,title:o.title})}const m={count:n.length,artifacts:n};return S(m,(o,y)=>{let i=I(y.brand,`**Distillation Complete** -- ${o.count} artifact${o.count!==1?"s":""} queued for review`)+`
32
+ No candidates provided. Provide an array of candidate artifacts to distill.`}],isError:!0};const a=[];for(const o of g){const m=k.add(w.id,{kind:o.kind,problem:o.title,validatedFix:o.content,tags:o.tags??[],confidence:o.confidence??.7,needsReview:1});a.push({id:m.id,kind:o.kind,title:o.title})}const u={count:a.length,artifacts:a};return S(u,(o,m)=>{let s=I(m.brand,`**Distillation Complete** -- ${o.count} artifact${o.count!==1?"s":""} queued for review`)+`
33
33
 
34
- `;return i+=o.artifacts.map(d=>`${y.bullet} [#${d.id}] **${d.kind}**: ${d.title}`).join(`
35
- `),i+="\n\nUse `wyrm_review` with each ID to approve or reject.",i})}},{name:"wyrm_harvest",description:"Auto-populate memory from artifacts you already produce. Walks a project (or ALL registered projects) and harvests durable facts from its docs (README/CLAUDE/AGENTS/ARCHITECTURE) plus recent commit subjects (git log) into the REVIEW QUEUE \u2014 approve/reject with wyrm_review, nothing is auto-trusted. Idempotent (re-runs skip what's already harvested). Use dryRun to preview. The fix for a thin corpus.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Harvest one project; omit to harvest ALL registered projects"},dryRun:{type:"boolean",description:"Preview what would be harvested without writing anything"},gitLimit:{type:"number",description:"How many recent commits to scan per project (default 30, max 200)"},includeCode:{type:"boolean",description:"Also harvest CODE: tech-stack facts from manifests (package.json/Cargo.toml/\u2026) + TODO/FIXME markers into the review queue, AND index code symbols (functions/classes/types) for search. Heavier \u2014 scope to one project for the full code pass."}}},outputSchema:{type:"object",properties:{dry_run:{type:"boolean"},projects_scanned:{type:"integer"},added:{type:"integer"},skipped:{type:"integer"},top:{type:"array",items:{type:"object",properties:{project:{type:"string"},added:{type:"integer"},skipped:{type:"integer"}},required:["project","added","skipped"]}},sample:{type:"array",items:{type:"string"}},code_symbols:{type:["object","null"],properties:{symbols:{type:"integer"},projects:{type:"integer"},files:{type:"integer"}},required:["symbols","projects","files"]}},required:["dry_run","projects_scanned","added","skipped","top","sample","code_symbols"]},annotations:A.wyrm_harvest,aliases:[],handler:(j,{store:v,raw:b,memory:u,symbols:h,cache:w})=>{const{projectPath:n,dryRun:m,gitLimit:o,includeCode:y}=j,i=b(),d={existsBySig:(t,$)=>!!i.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(t,"%"+L($)+"%"),addCandidate:(t,$)=>{u.add(t,{kind:$.kind,problem:$.text,tags:[...$.tags,$.sig],confidence:$.confidence,needsReview:1,createdBy:"harvest"})}};let p;if(n){const t=v.getProject(n);if(!t)return{content:[{type:"text",text:"Project not found"}],isError:!0};p=[{id:t.id,name:t.name,path:t.path}]}else p=v.getAllProjects(500).map(t=>({id:t.id,name:t.name,path:t.path}));const{reports:c,totalAdded:g,totalSkipped:r}=V(d,p,{dryRun:m,gitLimit:o,includeCode:y});!m&&g>0&&w.invalidate();let e=null;if(y&&!m){let t=0,$=0,f=0;for(const P of p)try{const q=h.indexProject(P.id,P.path);t+=q.files,$+=q.symbols,f++}catch{}e={symbols:$,projects:f,files:t}}const a=c.filter(t=>t.added>0).sort((t,$)=>$.added-t.added).slice(0,15).map(t=>({project:t.project,added:t.added,skipped:t.skipped})),s=c.flatMap(t=>t.sample??[]).slice(0,6),_={dry_run:!!m,projects_scanned:p.length,added:g,skipped:r,top:a,sample:s,code_symbols:e};return S(_,(t,$)=>{const f=t.code_symbols?`
34
+ `;return s+=o.artifacts.map(n=>`${m.bullet} [#${n.id}] **${n.kind}**: ${n.title}`).join(`
35
+ `),s+="\n\nUse `wyrm_review` with each ID to approve or reject.",s})}},{name:"wyrm_harvest",description:"Auto-populate memory from artifacts you already produce. Walks a project (or ALL registered projects) and harvests durable facts from its docs (README/CLAUDE/AGENTS/ARCHITECTURE) plus recent commit subjects (git log) into the REVIEW QUEUE \u2014 approve/reject with wyrm_review, nothing is auto-trusted. Idempotent (re-runs skip what's already harvested). Use dryRun to preview. The fix for a thin corpus.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Harvest one project; omit to harvest ALL registered projects"},dryRun:{type:"boolean",description:"Preview what would be harvested without writing anything"},gitLimit:{type:"number",description:"How many recent commits to scan per project (default 30, max 200)"},includeCode:{type:"boolean",description:"Also harvest CODE: tech-stack facts from manifests (package.json/Cargo.toml/\u2026) + TODO/FIXME markers into the review queue, AND index code symbols (functions/classes/types) for search. Heavier \u2014 scope to one project for the full code pass."}}},outputSchema:{type:"object",properties:{dry_run:{type:"boolean"},projects_scanned:{type:"integer"},added:{type:"integer"},skipped:{type:"integer"},top:{type:"array",items:{type:"object",properties:{project:{type:"string"},added:{type:"integer"},skipped:{type:"integer"}},required:["project","added","skipped"]}},sample:{type:"array",items:{type:"string"}},code_symbols:{type:["object","null"],properties:{symbols:{type:"integer"},projects:{type:"integer"},files:{type:"integer"}},required:["symbols","projects","files"]}},required:["dry_run","projects_scanned","added","skipped","top","sample","code_symbols"]},annotations:A.wyrm_harvest,aliases:[],handler:(b,{store:j,raw:k,memory:l,symbols:g,cache:w})=>{const{projectPath:a,dryRun:u,gitLimit:o,includeCode:m}=b,s=k(),n={existsBySig:(t,_)=>!!s.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(t,"%"+L(_)+"%"),addCandidate:(t,_)=>{l.add(t,{kind:_.kind,problem:_.text,tags:[..._.tags,_.sig],confidence:_.confidence,needsReview:1,createdBy:"harvest"})}};let d;if(a){const t=j.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=j.getAllProjects(500).map(t=>({id:t.id,name:t.name,path:t.path}));const{reports:c,totalAdded:v,totalSkipped:r}=V(n,d,{dryRun:u,gitLimit:o,includeCode:m});!u&&v>0&&w.invalidate();let e=null;if(m&&!u){let t=0,_=0,f=0;for(const P of d)try{const q=g.indexProject(P.id,P.path);t+=q.files,_+=q.symbols,f++}catch{}e={symbols:_,projects:f,files:t}}const i=c.filter(t=>t.added>0).sort((t,_)=>_.added-t.added).slice(0,15).map(t=>({project:t.project,added:t.added,skipped:t.skipped})),y=c.flatMap(t=>t.sample??[]).slice(0,6),h={dry_run:!!u,projects_scanned:d.length,added:v,skipped:r,top:i,sample:y,code_symbols:e};return S(h,(t,_)=>{const f=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.`:"",P=t.top.map(x=>` +${String(x.added).padStart(3)} (skip ${x.skipped}) ${x.project}`).join(`
37
- `),q=t.sample.map(x=>` ${$.bullet} ${x}`).join(`
38
- `);return I($.brand,`Harvest ${t.dry_run?"(dry run) ":""}-- ${t.added} candidate(s) -> review queue across ${t.projects_scanned} project(s); ${t.skipped} already present.`)+`${f}
37
+ `),q=t.sample.map(x=>` ${_.bullet} ${x}`).join(`
38
+ `);return I(_.brand,`Harvest ${t.dry_run?"(dry run) ":""}-- ${t.added} candidate(s) -> review queue across ${t.projects_scanned} project(s); ${t.skipped} already present.`)+`${f}
39
39
  ${P}`+(q?`
40
40
 
41
41
  Sample:
42
42
  ${q}`:"")+`
43
43
 
44
- Approve/reject with wyrm_review.`})}},{name:"wyrm_import_git",description:"Import a list of commits into the Wyrm memory review queue. Useful for onboarding a project's history or capturing recent work.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},commits:{type:"array",description:"Array of commit objects",items:{type:"object",properties:{message:{type:"string"},diff_summary:{type:"string"},author:{type:"string"},date:{type:"string"}},required:["message"]}},auto_approve:{type:"boolean",description:"Skip review queue and activate immediately (default: false)"}},required:["project_id","commits"]},outputSchema:{type:"object",properties:{captured:{type:"integer"},skipped:{type:"integer"},auto_approved:{type:"boolean"}},required:["captured","skipped","auto_approved"]},annotations:A.wyrm_import_git,aliases:[],handler:(j,{store:v,memory:b})=>{const{project_id:u,commits:h,auto_approve:w}=j;if(!v.getProjectById(u))return{content:[{type:"text",text:`Project ID ${u} not found.`}],isError:!0};let m=0,o=0;for(const i of h){const d=i.message??"";if(/^Merge /i.test(d)){o++;continue}if(/^(chore|bump|release|version)/i.test(d)){o++;continue}let p="pattern";/^fix(\(.+\))?:/i.test(d)?p="lesson":/^feat(\(.+\))?:/i.test(d)?p="pattern":/^refactor(\(.+\))?:/i.test(d)&&(p="heuristic");const c=d.split(":")[0]??"commit";b.add(u,{kind:p,problem:d,validatedFix:i.diff_summary??"",whyItWorked:`Committed by ${i.author??"unknown"} on ${i.date??"unknown"}`,tags:["git","commit",c.toLowerCase()],confidence:.6,needsReview:w?0:1}),m++}return S({captured:m,skipped:o,auto_approved:!!w},(i,d)=>I(d.brand,"**Git Import Complete**")+`
44
+ Approve/reject with wyrm_review.`})}},{name:"wyrm_import_git",description:"Import a list of commits into the Wyrm memory review queue. Useful for onboarding a project's history or capturing recent work.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},commits:{type:"array",description:"Array of commit objects",items:{type:"object",properties:{message:{type:"string"},diff_summary:{type:"string"},author:{type:"string"},date:{type:"string"}},required:["message"]}},auto_approve:{type:"boolean",description:"Skip review queue and activate immediately (default: false)"}},required:["project_id","commits"]},outputSchema:{type:"object",properties:{captured:{type:"integer"},skipped:{type:"integer"},auto_approved:{type:"boolean"}},required:["captured","skipped","auto_approved"]},annotations:A.wyrm_import_git,aliases:[],handler:(b,{store:j,memory:k})=>{const{project_id:l,commits:g,auto_approve:w}=b;if(!j.getProjectById(l))return{content:[{type:"text",text:`Project ID ${l} not found.`}],isError:!0};let u=0,o=0;for(const s of g){const n=s.message??"";if(/^Merge /i.test(n)){o++;continue}if(/^(chore|bump|release|version)/i.test(n)){o++;continue}let d="pattern";/^fix(\(.+\))?:/i.test(n)?d="lesson":/^feat(\(.+\))?:/i.test(n)?d="pattern":/^refactor(\(.+\))?:/i.test(n)&&(d="heuristic");const c=n.split(":")[0]??"commit";k.add(l,{kind:d,problem:n,validatedFix:s.diff_summary??"",whyItWorked:`Committed by ${s.author??"unknown"} on ${s.date??"unknown"}`,tags:["git","commit",c.toLowerCase()],confidence:.6,needsReview:w?0:1}),u++}return S({captured:u,skipped:o,auto_approved:!!w},(s,n)=>I(n.brand,"**Git Import Complete**")+`
45
45
 
46
- ${d.bullet} **Captured:** ${i.captured}
47
- ${d.bullet} **Skipped:** ${i.skipped} (merges/chores)
48
- ${d.bullet} **Review needed:** ${i.auto_approved?"No (auto-approved)":`Yes -- run \`wyrm_review\` to activate ${i.captured} artifact${i.captured!==1?"s":""}`}`)}},{name:"wyrm_import_pr",description:"Import a pull request (title, body, review comments) into the Wyrm memory review queue to extract patterns and heuristics.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description / body"},review_comments:{type:"array",items:{type:"string"},description:"Review comment strings"},auto_approve:{type:"boolean",description:"Skip review queue (default: false)"}},required:["project_id","title","body"]},outputSchema:{type:"object",properties:{created:{type:"integer"},auto_approved:{type:"boolean"}},required:["created","auto_approved"]},annotations:A.wyrm_import_pr,aliases:[],handler:(j,{store:v,memory:b})=>{const{project_id:u,title:h,body:w,review_comments:n,auto_approve:m}=j;if(!v.getProjectById(u))return{content:[{type:"text",text:`Project ID ${u} not found.`}],isError:!0};let y=0;const i=m?0:1;b.add(u,{kind:"pattern",problem:`${h}
46
+ ${n.bullet} **Captured:** ${s.captured}
47
+ ${n.bullet} **Skipped:** ${s.skipped} (merges/chores)
48
+ ${n.bullet} **Review needed:** ${s.auto_approved?"No (auto-approved)":`Yes -- run \`wyrm_review\` to activate ${s.captured} artifact${s.captured!==1?"s":""}`}`)}},{name:"wyrm_import_pr",description:"Import a pull request (title, body, review comments) into the Wyrm memory review queue to extract patterns and heuristics.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description / body"},review_comments:{type:"array",items:{type:"string"},description:"Review comment strings"},auto_approve:{type:"boolean",description:"Skip review queue (default: false)"}},required:["project_id","title","body"]},outputSchema:{type:"object",properties:{created:{type:"integer"},auto_approved:{type:"boolean"}},required:["created","auto_approved"]},annotations:A.wyrm_import_pr,aliases:[],handler:(b,{store:j,memory:k})=>{const{project_id:l,title:g,body:w,review_comments:a,auto_approve:u}=b;if(!j.getProjectById(l))return{content:[{type:"text",text:`Project ID ${l} not found.`}],isError:!0};let m=0;const s=u?0:1;k.add(l,{kind:"pattern",problem:`${g}
49
49
 
50
- ${w}`,validatedFix:"",whyItWorked:"",tags:["git","pr"],confidence:.65,needsReview:i}),y++;for(const p of n??[])/\b(should|must|always|never|prefer|avoid|use|don't)\b/i.test(p)&&(b.add(u,{kind:"heuristic",problem:p,validatedFix:"",whyItWorked:"",tags:["git","pr","review"],confidence:.65,needsReview:i}),y++);return S({created:y,auto_approved:!!m},(p,c)=>I(c.brand,"**PR Import Complete**")+`
50
+ ${w}`,validatedFix:"",whyItWorked:"",tags:["git","pr"],confidence:.65,needsReview:s}),m++;for(const d of a??[])/\b(should|must|always|never|prefer|avoid|use|don't)\b/i.test(d)&&(k.add(l,{kind:"heuristic",problem:d,validatedFix:"",whyItWorked:"",tags:["git","pr","review"],confidence:.65,needsReview:s}),m++);return S({created:m,auto_approved:!!u},(d,c)=>I(c.brand,"**PR Import Complete**")+`
51
51
 
52
- ${c.bullet} **Artifacts created:** ${p.created}
53
- ${c.bullet} **Review needed:** ${p.auto_approved?"No (auto-approved)":"Yes -- run `wyrm_review` to activate"}`)}},{name:"wyrm_import_rules",description:"Import a .cursorrules / copilot-instructions file into Wyrm. Parses by section and creates ground truths (for constraint/rule language) or memory artifacts (for general guidelines).",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},content:{type:"string",description:"Full text of the rules file"},format:{type:"string",enum:["cursorrules","copilot","plain"],description:"Source format (default: plain)"},source_file:{type:"string",description:"Filename for provenance (optional)"}},required:["project_id","content"]},outputSchema:{type:"object",properties:{format:{type:"string"},source:{type:"string"},truths_created:{type:"integer"},artifacts_created:{type:"integer"}},required:["format","source","truths_created","artifacts_created"]},annotations:A.wyrm_import_rules,aliases:[],handler:(j,{store:v,memory:b,truths:u})=>{const{project_id:h,content:w,format:n,source_file:m}=j;if(!v.getProjectById(h))return{content:[{type:"text",text:`Project ID ${h} not found.`}],isError:!0};const y=n??"plain",i=m??"rules",d=["imported",y,i],p=w.split(/\n(?=#)/),c=w.split(/\n\n+/),g=(p.length>=c.length?p:c).map(s=>s.trim()).filter(s=>s.length>=15);let r=0,e=0;for(const s of g)/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(s)?(u.set(h,{category:"constraint",key:s.slice(0,50).replace(/\n/g," "),value:s,source:i}),r++):(b.add(h,{kind:"heuristic",problem:s,validatedFix:"",whyItWorked:"",tags:d,confidence:.7,needsReview:1}),e++);return S({format:y,source:i,truths_created:r,artifacts_created:e},(s,_)=>I(_.brand,`**Rules Import Complete** (${s.format})`)+`
52
+ ${c.bullet} **Artifacts created:** ${d.created}
53
+ ${c.bullet} **Review needed:** ${d.auto_approved?"No (auto-approved)":"Yes -- run `wyrm_review` to activate"}`)}},{name:"wyrm_import_rules",description:"Import a .cursorrules / copilot-instructions file into Wyrm. Parses by section and creates ground truths (for constraint/rule language) or memory artifacts (for general guidelines).",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},content:{type:"string",description:"Full text of the rules file"},format:{type:"string",enum:["cursorrules","copilot","plain"],description:"Source format (default: plain)"},source_file:{type:"string",description:"Filename for provenance (optional)"}},required:["project_id","content"]},outputSchema:{type:"object",properties:{format:{type:"string"},source:{type:"string"},truths_created:{type:"integer"},artifacts_created:{type:"integer"}},required:["format","source","truths_created","artifacts_created"]},annotations:A.wyrm_import_rules,aliases:[],handler:(b,{store:j,memory:k,truths:l})=>{const{project_id:g,content:w,format:a,source_file:u}=b;if(!j.getProjectById(g))return{content:[{type:"text",text:`Project ID ${g} not found.`}],isError:!0};const m=a??"plain",s=u??"rules",n=["imported",m,s],d=w.split(/\n(?=#)/),c=w.split(/\n\n+/),v=(d.length>=c.length?d:c).map(y=>y.trim()).filter(y=>y.length>=15);let r=0,e=0;for(const y of v)/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(y)?(l.set(g,{category:"constraint",key:y.slice(0,50).replace(/\n/g," "),value:y,source:s}),r++):(k.add(g,{kind:"heuristic",problem:y,validatedFix:"",whyItWorked:"",tags:n,confidence:.7,needsReview:1}),e++);return S({format:m,source:s,truths_created:r,artifacts_created:e},(y,h)=>I(h.brand,`**Rules Import Complete** (${y.format})`)+`
54
54
 
55
- ${_.bullet} **Ground truths created:** ${s.truths_created} (active immediately)
56
- ${_.bullet} **Memory artifacts created:** ${s.artifacts_created} (pending review)
57
- ${_.bullet} **Source:** ${s.source}
55
+ ${h.bullet} **Ground truths created:** ${y.truths_created} (active immediately)
56
+ ${h.bullet} **Memory artifacts created:** ${y.artifacts_created} (pending review)
57
+ ${h.bullet} **Source:** ${y.source}
58
58
 
59
- Run \`wyrm_review\` to approve the memory artifacts.`)}},{name:"wyrm_spec_register",description:"Make spec-kit Wyrm-native. Reads a spec directory (spec.md title/summary + tasks.md task list) and creates one Wyrm quest per task, linked to a project, with a stored spec\u2192project link. Idempotent \u2014 re-running updates the same quests (deduped by a per-spec-task signature) instead of duplicating.",inputSchema:{type:"object",properties:{specDir:{type:"string",description:"Absolute path to the spec directory (e.g. '.../dragon-platform/specs/001-ghostmesh')"},projectPath:{type:"string",description:"Path of the Wyrm project to attach the spec + quests to (must already be registered)"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Priority for the generated quests (default 'medium')"}},required:["specDir","projectPath"]},outputSchema:{type:"object",properties:{spec_dir:{type:"string"},title:{type:["string","null"]},project:{type:"string"},tasks_parsed:{type:"integer"},quests_created:{type:"integer"},quests_updated:{type:"integer"},quest_ids:{type:"array",items:{type:"integer"}}},required:["spec_dir","title","project","tasks_parsed","quests_created","quests_updated","quest_ids"]},annotations:A.wyrm_spec_register,aliases:[],handler:(j,{store:v,indexing:b})=>{const{specDir:u,projectPath:h,priority:w}=j,n=["specDir","projectPath"].filter(r=>{const e=j[r];return!e&&e!==0&&e!==!1});if(n.length>0)return{content:[{type:"text",text:`Missing required arguments: ${n.join(", ")}`}],isError:!0};const m=v.getProject(h);if(!m)return{content:[{type:"text",text:`**Spec Register**: Project not found at "${h}". Register it first (wyrm_scan_projects / wyrm_session_start).`}],isError:!0};const o=ee(u);if(o.tasks.length===0){const r={spec_dir:u,title:o.title??null,project:m.name,tasks_parsed:0,quests_created:0,quests_updated:0,quest_ids:[]};return S(r,(e,a)=>I(a.brand,`**Spec Register**: No tasks found in ${H(e.spec_dir,"tasks.md")}. Nothing to create.`))}const y=w||"medium";let i=0,d=0;const p=[];for(const r of o.tasks){const e=te(u,r.id),a=`${r.id}: ${r.title}`,s=e,_=v.findQuestBySpecSignature(m.id,e);if(_)v.updateQuestFields(_.id,{title:a,tags:s}),p.push(_.id),d++;else{const t=v.addQuest(m.id,a,`spec-kit task from ${u}`,y,s);b()?.enqueue("quest",t.id,m.id),p.push(t.id),i++}}const c=v.upsertSpec(m.id,u,o.title,o.summary,o.tasks.length),g={spec_dir:c.spec_dir,title:c.title??null,project:m.name,tasks_parsed:o.tasks.length,quests_created:i,quests_updated:d,quest_ids:p};return S(g,(r,e)=>{let a=I(e.brand,"**Spec Registered**")+`
59
+ Run \`wyrm_review\` to approve the memory artifacts.`)}},{name:"wyrm_spec_register",description:"Make spec-kit Wyrm-native. Reads a spec directory (spec.md title/summary + tasks.md task list) and creates one Wyrm quest per task, linked to a project, with a stored spec\u2192project link. Idempotent \u2014 re-running updates the same quests (deduped by a per-spec-task signature) instead of duplicating.",inputSchema:{type:"object",properties:{specDir:{type:"string",description:"Absolute path to the spec directory (e.g. '.../dragon-platform/specs/001-ghostmesh')"},projectPath:{type:"string",description:"Path of the Wyrm project to attach the spec + quests to (must already be registered)"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Priority for the generated quests (default 'medium')"}},required:["specDir","projectPath"]},outputSchema:{type:"object",properties:{spec_dir:{type:"string"},title:{type:["string","null"]},project:{type:"string"},tasks_parsed:{type:"integer"},quests_created:{type:"integer"},quests_updated:{type:"integer"},quest_ids:{type:"array",items:{type:"integer"}}},required:["spec_dir","title","project","tasks_parsed","quests_created","quests_updated","quest_ids"]},annotations:A.wyrm_spec_register,aliases:[],handler:(b,{store:j,indexing:k})=>{const{specDir:l,projectPath:g,priority:w}=b,a=["specDir","projectPath"].filter(r=>{const e=b[r];return!e&&e!==0&&e!==!1});if(a.length>0)return{content:[{type:"text",text:`Missing required arguments: ${a.join(", ")}`}],isError:!0};const u=j.getProject(g);if(!u)return{content:[{type:"text",text:`**Spec Register**: Project not found at "${g}". Register it first (wyrm_scan_projects / wyrm_session_start).`}],isError:!0};const o=ee(l);if(o.tasks.length===0){const r={spec_dir:l,title:o.title??null,project:u.name,tasks_parsed:0,quests_created:0,quests_updated:0,quest_ids:[]};return S(r,(e,i)=>I(i.brand,`**Spec Register**: No tasks found in ${H(e.spec_dir,"tasks.md")}. Nothing to create.`))}const m=w||"medium";let s=0,n=0;const d=[];for(const r of o.tasks){const e=te(l,r.id),i=`${r.id}: ${r.title}`,y=e,h=j.findQuestBySpecSignature(u.id,e);if(h)j.updateQuestFields(h.id,{title:i,tags:y}),d.push(h.id),n++;else{const t=j.addQuest(u.id,i,`spec-kit task from ${l}`,m,y);k()?.enqueue("quest",t.id,u.id),d.push(t.id),s++}}const c=j.upsertSpec(u.id,l,o.title,o.summary,o.tasks.length),v={spec_dir:c.spec_dir,title:c.title??null,project:u.name,tasks_parsed:o.tasks.length,quests_created:s,quests_updated:n,quest_ids:d};return S(v,(r,e)=>{let i=I(e.brand,"**Spec Registered**")+`
60
60
 
61
- `;return a+=`Spec: ${r.title||"(untitled)"}
62
- `,c.summary&&(a+=`Summary: ${c.summary}
63
- `),a+=`Dir: ${r.spec_dir}
64
- `,a+=`Project: ${r.project}
65
- `,a+=`Tasks parsed: ${r.tasks_parsed}
66
- `,a+=`Quests created: ${r.quests_created} - updated: ${r.quests_updated}
67
- `,a+=`
61
+ `;return i+=`Spec: ${r.title||"(untitled)"}
62
+ `,c.summary&&(i+=`Summary: ${c.summary}
63
+ `),i+=`Dir: ${r.spec_dir}
64
+ `,i+=`Project: ${r.project}
65
+ `,i+=`Tasks parsed: ${r.tasks_parsed}
66
+ `,i+=`Quests created: ${r.quests_created} - updated: ${r.quests_updated}
67
+ `,i+=`
68
68
  \`\`\`json
69
69
  ${JSON.stringify({spec:r.spec_dir,title:r.title,project:r.project,tasksParsed:r.tasks_parsed,questsCreated:r.quests_created,questsUpdated:r.quests_updated,questIds:r.quest_ids},null,2)}
70
- \`\`\``,a})}},{name:"wyrm_scaffold_save",description:"Save a reasoning scaffold \u2014 a structured checklist that guides step-by-step thinking for a specific problem type. Scaffolds are automatically surfaced by wyrm_context_build when the task matches, helping AI models apply proven reasoning patterns.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project path (optional, null for global scaffolds)"},problemType:{type:"string",description:"Short slug for the problem type (e.g. 'api-design', 'security-review', 'db-migration')"},description:{type:"string",description:"What kind of task this scaffold helps with"},whenToUse:{type:"string",description:"Conditions that indicate this scaffold should be applied"},steps:{type:"array",items:{type:"string"},description:"Ordered checklist steps to follow"},verificationSteps:{type:"array",items:{type:"string"},description:"Steps to verify the work is correct"},doNotApplyIf:{type:"string",description:"Conditions where this scaffold does NOT apply"},tags:{type:"array",items:{type:"string"},description:"Searchable tags"}},required:["problemType","description","whenToUse","steps"]},outputSchema:{type:"object",properties:{id:{type:"integer"},problem_type:{type:"string"},description:{type:"string"},steps:{type:"integer"}},required:["id","problem_type","description","steps"]},annotations:A.wyrm_scaffold_save,aliases:[],handler:(j,{store:v,scaffolds:b,cache:u})=>{const{projectPath:h,problemType:w,description:n,whenToUse:m,steps:o,verificationSteps:y,doNotApplyIf:i,tags:d}=j,p=h?v.getProject(h)?.id??void 0:void 0,c=b.save({projectId:p,problemType:w,description:n,whenToUse:m,steps:o,verificationSteps:y??void 0,doNotApplyIf:i?[i]:void 0,tags:d??[]});u.invalidate("wyrm_scaffold_get"),u.invalidate("wyrm_context_build");const g={id:c.id,problem_type:w,description:n,steps:o.length};return S(g,(r,e)=>I(e.brand,"**Reasoning Scaffold Saved**")+`
70
+ \`\`\``,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:A.wyrm_scaffold_save,aliases:[],handler:(b,{store:j,scaffolds:k,cache:l})=>{const{projectPath:g,problemType:w,description:a,whenToUse:u,steps:o,verificationSteps:m,doNotApplyIf:s,tags:n}=b,d=g?j.getProject(g)?.id??void 0:void 0,c=k.save({projectId:d,problemType:w,description:a,whenToUse:u,steps:o,verificationSteps:m??void 0,doNotApplyIf:s?[s]:void 0,tags:n??[]});l.invalidate("wyrm_scaffold_get"),l.invalidate("wyrm_context_build");const v={id:c.id,problem_type:w,description:a,steps:o.length};return S(v,(r,e)=>I(e.brand,"**Reasoning Scaffold Saved**")+`
71
71
 
72
72
  ${e.bullet} **Problem Type:** ${r.problem_type}
73
73
  ${e.bullet} **Description:** ${r.description}
@@ -1,40 +1,41 @@
1
- import{basename as X}from"path";import{createHash as Z}from"crypto";import{blockText as G}from"./types.js";import{TOOL_ANNOTATIONS as T}from"../tool-annotations.js";import{renderResult as x,withGlyph as O,cacheKeyFor as N}from"../render.js";import{computeStaleness as ee}from"../intelligence.js";import{ValidationError as te,asInt as se,asString as ne}from"../validate.js";import{sanitizeActorId as oe}from"./boundary.js";import{makeEstimator as ie}from"../token-budget.js";function J(e){return!e||!e.thread.trim()?null:`### \u{1F9F5} Where We Left Off _(the living thread \u2014 what we were working on and thinking about)_
1
+ import{basename as X}from"path";import{createHash as Z}from"crypto";import{blockText as Q}from"./types.js";import{TOOL_ANNOTATIONS as T}from"../tool-annotations.js";import{renderResult as x,withGlyph as O,cacheKeyFor as N}from"../render.js";import{computeStaleness as ee}from"../intelligence.js";import{ValidationError as te,asInt as se,asString as ne}from"../validate.js";import{sanitizeActorId as ie}from"./boundary.js";import{makeEstimator as oe}from"../token-budget.js";function G(e){return!e||!e.thread.trim()?null:`### \u{1F9F5} Where We Left Off _(the living thread \u2014 what we were working on and thinking about)_
2
2
  `+`_updated ${e.updated_at}${e.updated_by?" \xB7 "+e.updated_by:""} \xB7 ${e.turn_count} turn(s)_`+`
3
3
 
4
- `+e.thread.slice(-1800)}const re={tech_stack:"\u{1F6E0}\uFE0F Tech Stack",architecture:"\u{1F3D7}\uFE0F Architecture",constraint:"\u{1F6A7} Constraints",decision:"\u{1F4CB} Decisions",contact:"\u{1F464} Contacts",other:"\u{1F4CC} Other Facts"};function Q(e,t){let n=`### \u{1F4DA} Project Ground Truths _(treat as authoritative \u2014 do not infer or contradict)_
5
- `;const s=new Map;for(const o of e)s.has(o.category)||s.set(o.category,[]),s.get(o.category).push(o);for(const[o,i]of s){n+=`**${re[o]??o}:**
6
- `;for(const c of i){let p="";if(t){const u=ee(c);u!==null&&u>.7&&(p="[\u26A0\uFE0F STALE] ")}n+=`- ${p}**${c.key}:** ${c.value}${c.rationale?` _(${c.rationale})_`:""}
7
- `}}return n}const V=`
4
+ `+e.thread.slice(-1800)}const re={tech_stack:"\u{1F6E0}\uFE0F Tech Stack",architecture:"\u{1F3D7}\uFE0F Architecture",constraint:"\u{1F6A7} Constraints",decision:"\u{1F4CB} Decisions",contact:"\u{1F464} Contacts",other:"\u{1F4CC} Other Facts"};function J(e,t){let s=`### \u{1F4DA} Project Ground Truths _(treat as authoritative \u2014 do not infer or contradict)_
5
+ `;const n=new Map;for(const i of e)n.has(i.category)||n.set(i.category,[]),n.get(i.category).push(i);for(const[i,o]of n){s+=`**${re[i]??i}:**
6
+ `;for(const c of o){let p="";if(t){const u=ee(c);u!==null&&u>.7&&(p="[\u26A0\uFE0F STALE] ")}s+=`- ${p}**${c.key}:** ${c.value}${c.rationale?` _(${c.rationale})_`:""}
7
+ `}}return s}const V=`
8
8
  SELECT * FROM quests
9
9
  WHERE project_id = ? AND status = 'pending'
10
10
  ORDER BY
11
11
  CASE priority WHEN 'critical' THEN 1 WHEN 'high' THEN 2 WHEN 'medium' THEN 3 ELSE 4 END,
12
12
  id
13
13
  LIMIT 5
14
- `;function Y(e){const t={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F7E2}"};let n=`### \u{1F3AF} Active Quests
15
- `;for(const s of e)n+=`- ${t[s.priority]??"\u2022"} #${s.id}: ${s.title}
16
- `;return n}function q(e,t,n,s){return n?e.getProjectById(n):s?t.prepare("SELECT * FROM projects WHERE LOWER(name) LIKE LOWER(?) LIMIT 1").get(`%${s}%`):t.prepare(`
14
+ `;function Y(e){const t={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F7E2}"};let s=`### \u{1F3AF} Active Quests
15
+ `;for(const n of e)s+=`- ${t[n.priority]??"\u2022"} #${n.id}: ${n.title}
16
+ `;return s}function q(e,t,s,n){return s?e.getProjectById(s):n?t.prepare("SELECT * FROM projects WHERE LOWER(name) LIKE LOWER(?) LIMIT 1").get(`%${n}%`):t.prepare(`
17
17
  SELECT p.* FROM projects p
18
18
  JOIN sessions s ON s.project_id = p.id
19
19
  ORDER BY s.created_at DESC LIMIT 1
20
20
  `).get()}function P(e){const t=e.getAllProjects(20);return t.length===0?{content:[{type:"text",text:"No projects found. Run `wyrm_scan_projects` first."}],isError:!0}:{content:[{type:"text",text:`Project not found. Available projects:
21
- ${t.map(s=>`- ${s.name} (ID: ${s.id})`).join(`
22
- `)}`}],isError:!0}}const K=(e,t)=>{const n=e.session_id!==null?`
23
- Session logged: #${e.session_id}`:"";return O(t.brand,`Wyrm primed for **${e.project_name}** | ${e.truth_count} truth${e.truth_count!==1?"s":""} - ${e.quest_count} quest${e.quest_count!==1?"s":""} - ${e.memory_count} memor${e.memory_count!==1?"ies":"y"}${n}`)},L=(e,t)=>{const n=K(e,t);return e.sections.length>0?e.sections.map(s=>s.text).join(`
21
+ ${t.map(n=>`- ${n.name} (ID: ${n.id})`).join(`
22
+ `)}`}],isError:!0}}const K=(e,t)=>{const s=e.session_id!==null?`
23
+ Session logged: #${e.session_id}`:"";return O(t.brand,`Wyrm primed for **${e.project_name}** | ${e.truth_count} truth${e.truth_count!==1?"s":""} - ${e.quest_count} quest${e.quest_count!==1?"s":""} - ${e.memory_count} memor${e.memory_count!==1?"ies":"y"}${s}`)},L=(e,t)=>{const s=K(e,t);return e.sections.length>0?e.sections.map(n=>n.text).join(`
24
24
 
25
25
  ---
26
26
 
27
27
  `)+`
28
28
 
29
- `+n:n+`
29
+ `+s:s+`
30
30
 
31
- _No memory stored yet -- start working and Wyrm will learn._`},A={summary:K};async function D(e,t,n){try{const{logSavings:s}=await import("../statusline.js"),o=G(n.content[0]).length,i=Math.round(o/4),c=e.prepare("SELECT id FROM sessions WHERE project_id = ? ORDER BY created_at DESC LIMIT 1").get(t);s(e,"wyrm_session_prime","recovered_context",i,c?.id)}catch{}}const ce={continuity:{path:"continuity",tool:"wyrm_session_prime"},truths:{path:"truths",tool:"wyrm_truth_get"},scaffold:{path:"scaffolds",tool:"wyrm_context_build"},memory:{path:"memory",tool:"wyrm_recall"},quests:{path:"quests",tool:"wyrm_all_quests"}},ae=48,de=1200;async function pe(e,{store:t,raw:n,memory:s,truths:o,scaffolds:i,cache:c}){const{project_id:p,project_name:u,task:a,log_session:f}=e,r=oe(e.run_id);if(r===null)throw new te("run_id",'must be <=64 printable-ASCII chars (no ";")');const m=ne("role",e.role,{maxLen:200})??"",j=se("token_budget",e.token_budget,{min:1})??de,_=n(),$=()=>_.prepare("SELECT body_json FROM run_briefs WHERE run_id = ? AND role = ?").get(r,m),y=p||u?q(t,_,p,u):void 0;if((p||u)&&!y)return P(t);let g=$();if(g&&y){const d=JSON.parse(g.body_json);if(d.project_id!==y.id)return{content:[{type:"text",text:`Fleet brief for (run ${r}, role '${m}') is pinned to project '${d.project_name}' (ID: ${d.project_id}) \u2014 refusing to serve it for requested project '${y.name}' (ID: ${y.id}). Use a distinct role for a second project, or prime without run_id.`}],isError:!0}}if(!g){const d=y??q(t,_,p,u);if(!d)return P(t);const l=[],k=J(t.getContinuity(d.id));k&&l.push({kind:"continuity",text:k});const v=o.getCurrent(d.id);v.length>0&&l.push({kind:"truths",text:Q(v,!1).slice(0,1200)});const w=a??(m||void 0);if(w){const S=i.findBest(w,d.id,.3);S&&l.push({kind:"scaffold",text:i.formatForContext(S,1500)})}const B=s.buildContextBrief(d.id,w??"general",{maxItems:10,minConfidence:.3});B.text&&l.push({kind:"memory",text:B.text.slice(0,2e3)});const I=_.prepare(V).all(d.id);I.length>0&&l.push({kind:"quests",text:Y(I).slice(0,800)});const M=ie(),R=[];let C=ae;for(const S of l){const W=M.count(S.text)+2;if(C+W<=j)R.push(S),C+=W;else{const H=ce[S.kind]??{path:S.kind,tool:"wyrm_search"},U=`[beyond token_budget] wyrm://project/${d.id}/${H.path} -- fetch via ${H.tool}`;R.push({kind:S.kind,text:U}),C+=M.count(U)+2}}let F=null;f&&(F=t.createSession(d.id,{objectives:a??"Session started via wyrm_session_prime",summary:""}).id);const z={project_id:d.id,project_name:d.name,truth_count:o.getStats(d.id).current,quest_count:I.length,memory_count:s.getStats(d.id).total,session_id:F,sections:R,run_id:r,role:m,token_budget:j};_.prepare("INSERT OR IGNORE INTO run_briefs (run_id, role, body_json, token_budget) VALUES (?, ?, ?, ?)").run(r,m,JSON.stringify(z),j),g=$()}const h=JSON.parse(g.body_json),b=x(h,L,A);if(e.for_spawn===!0){const d=x(h,L,{...A,exemptStructured:!0}),l=G(d.content[0]),k=Z("sha256").update(l,"utf8").digest("hex"),v={project_id:h.project_id,project_name:h.project_name,session_id:h.session_id??null,sections:h.sections,for_spawn:!0,run_id:r,role:m,brief:l,brief_hash:k,brief_chars:l.length,cache_key:{table:"run_briefs",run_id:r,role:m}};await D(_,h.project_id,d);const w={content:[{type:"text",text:l}],structuredContent:v};return c.set(N("wyrm_session_prime",JSON.stringify(e)),w,3e4),w}return await D(_,h.project_id,b),c.set(N("wyrm_session_prime",JSON.stringify(e)),b,3e4),b}const Se=[{name:"wyrm_session_start",description:"Start or continue a session for a project",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project path"},objectives:{type:"string",description:"Session objectives"}},required:["projectPath"]},outputSchema:{type:"object",properties:{session_id:{type:"integer"},project:{type:"string"},date:{type:"string"},objectives:{type:["string","null"]}},required:["session_id","project","date","objectives"]},annotations:T.wyrm_session_start,aliases:[],handler:(e,{store:t})=>{const{projectPath:n,objectives:s}=e;let o=t.getProject(n);o||(o=t.registerProject(X(n),n));let i=t.getTodaySession(o.id);i?s&&(i=t.updateSession(i.id,{objectives:i.objectives?`${i.objectives}
32
- ${s}`:s})):i=t.createSession(o.id,{objectives:s||""}),t.archiveOldSessions(o.id,10);const c={session_id:i.id,project:o.name,date:i.date,objectives:i.objectives||null};return x(c,(p,u)=>O(u.brand,`Session ${p.session_id} for ${p.project}`)+`
31
+ _No memory stored yet -- start working and Wyrm will learn._`},A={summary:K};async function D(e,t,s){try{const{logSavings:n}=await import("../statusline.js"),i=Q(s.content[0]).length,o=Math.round(i/4),c=e.prepare("SELECT id FROM sessions WHERE project_id = ? ORDER BY created_at DESC LIMIT 1").get(t);n(e,"wyrm_session_prime","recovered_context",o,c?.id)}catch{}}const ce={continuity:{path:"continuity",tool:"wyrm_session_prime"},truths:{path:"truths",tool:"wyrm_truth_get"},scaffold:{path:"scaffolds",tool:"wyrm_context_build"},memory:{path:"memory",tool:"wyrm_recall"},quests:{path:"quests",tool:"wyrm_all_quests"}},ae=48,de=1200;async function pe(e,{store:t,raw:s,memory:n,truths:i,scaffolds:o,cache:c}){const{project_id:p,project_name:u,task:a,log_session:f}=e,r=ie(e.run_id);if(r===null)throw new te("run_id",'must be <=64 printable-ASCII chars (no ";")');const m=ne("role",e.role,{maxLen:200})??"",g=se("token_budget",e.token_budget,{min:1})??de,_=s(),v=()=>_.prepare("SELECT body_json FROM run_briefs WHERE run_id = ? AND role = ?").get(r,m),y=p||u?q(t,_,p,u):void 0;if((p||u)&&!y)return P(t);let S=v();if(S&&y){const d=JSON.parse(S.body_json);if(d.project_id!==y.id)return{content:[{type:"text",text:`Fleet brief for (run ${r}, role '${m}') is pinned to project '${d.project_name}' (ID: ${d.project_id}) \u2014 refusing to serve it for requested project '${y.name}' (ID: ${y.id}). Use a distinct role for a second project, or prime without run_id.`}],isError:!0}}if(!S){const d=y??q(t,_,p,u);if(!d)return P(t);const l=[],$=G(t.getContinuity(d.id));$&&l.push({kind:"continuity",text:$});const k=i.getCurrent(d.id);k.length>0&&l.push({kind:"truths",text:J(k,!1).slice(0,1200)});const w=a??(m||void 0);if(w){const b=o.findBest(w,d.id,.3);b&&l.push({kind:"scaffold",text:o.formatForContext(b,1500)})}const M=n.buildContextBrief(d.id,w??"general",{maxItems:10,minConfidence:.3});M.text&&l.push({kind:"memory",text:M.text.slice(0,2e3)});const I=_.prepare(V).all(d.id);I.length>0&&l.push({kind:"quests",text:Y(I).slice(0,800)});const B=oe(),R=[];let C=ae;for(const b of l){const W=B.count(b.text)+2;if(C+W<=g)R.push(b),C+=W;else{const H=ce[b.kind]??{path:b.kind,tool:"wyrm_search"},U=`[beyond token_budget] wyrm://project/${d.id}/${H.path} -- fetch via ${H.tool}`;R.push({kind:b.kind,text:U}),C+=B.count(U)+2}}let F=null;f&&(F=t.createSession(d.id,{objectives:a??"Session started via wyrm_session_prime",summary:""}).id);const z={project_id:d.id,project_name:d.name,truth_count:i.getStats(d.id).current,quest_count:I.length,memory_count:n.getStats(d.id).total,session_id:F,sections:R,run_id:r,role:m,token_budget:g};_.prepare("INSERT OR IGNORE INTO run_briefs (run_id, role, body_json, token_budget) VALUES (?, ?, ?, ?)").run(r,m,JSON.stringify(z),g),S=v()}const h=JSON.parse(S.body_json),E=x(h,L,A);if(e.for_spawn===!0){const d=x(h,L,{...A,exemptStructured:!0}),l=Q(d.content[0]),$=Z("sha256").update(l,"utf8").digest("hex"),k={project_id:h.project_id,project_name:h.project_name,session_id:h.session_id??null,sections:h.sections,for_spawn:!0,run_id:r,role:m,brief:l,brief_hash:$,brief_chars:l.length,cache_key:{table:"run_briefs",run_id:r,role:m}};await D(_,h.project_id,d);const w={content:[{type:"text",text:l}],structuredContent:k};return c.set(N("wyrm_session_prime",JSON.stringify(e)),w,3e4),w}return await D(_,h.project_id,E),c.set(N("wyrm_session_prime",JSON.stringify(e)),E,3e4),E}const Se=[{name:"wyrm_session_start",description:"Start or continue a session for a project",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project path"},objectives:{type:"string",description:"Session objectives"}},required:["projectPath"]},outputSchema:{type:"object",properties:{session_id:{type:"integer"},project:{type:"string"},date:{type:"string"},objectives:{type:["string","null"]}},required:["session_id","project","date","objectives"]},annotations:T.wyrm_session_start,aliases:[],handler:(e,{store:t})=>{const{projectPath:s,objectives:n}=e;let i=t.getProject(s);i||(i=t.registerProject(X(s),s));let o=t.getTodaySession(i.id);o?n&&(o=t.updateSession(o.id,{objectives:o.objectives?`${o.objectives}
32
+ ${n}`:n})):o=t.createSession(i.id,{objectives:n||""}),t.archiveOldSessions(i.id,10);const c={session_id:o.id,project:i.name,date:o.date,objectives:o.objectives||null};return x(c,(p,u)=>O(u.brand,`Session ${p.session_id} for ${p.project}`)+`
33
33
  **Date:** ${p.date}
34
- **Objectives:** ${p.objectives??"None set"}`)}},{name:"wyrm_session_update",description:"Update the current session with completed work, issues, or notes",inputSchema:{type:"object",properties:{projectPath:{type:"string"},completed:{type:"string",description:"What was completed"},issues:{type:"string"},commits:{type:"string",description:"Git commits made"},notes:{type:"string"}},required:["projectPath"]},outputSchema:{type:"object",properties:{session_id:{type:"integer"},project:{type:"string"},updated:{type:"array",items:{type:"string",enum:["completed","issues","commits","notes"]}}},required:["session_id","project","updated"]},annotations:T.wyrm_session_update,aliases:[],handler:(e,{store:t,indexing:n})=>{const{projectPath:s,completed:o,issues:i,commits:c,notes:p}=e,u=t.getProject(s);if(!u)return{content:[{type:"text",text:"Project not found"}],isError:!0};let a=t.getTodaySession(u.id);a||(a=t.createSession(u.id,{}));const f={};o&&(f.completed=a.completed?`${a.completed}
35
- ${o}`:o),i&&(f.issues=a.issues?`${a.issues}
36
- ${i}`:i),c&&(f.commits=a.commits?`${a.commits}
34
+ **Objectives:** ${p.objectives??"None set"}`)}},{name:"wyrm_session_update",description:"Update the current session with completed work, issues, or notes",inputSchema:{type:"object",properties:{projectPath:{type:"string"},completed:{type:"string",description:"What was completed"},issues:{type:"string"},commits:{type:"string",description:"Git commits made"},notes:{type:"string"}},required:["projectPath"]},outputSchema:{type:"object",properties:{session_id:{type:"integer"},project:{type:"string"},updated:{type:"array",items:{type:"string",enum:["completed","issues","commits","notes"]}}},required:["session_id","project","updated"]},annotations:T.wyrm_session_update,aliases:[],handler:(e,{store:t,indexing:s})=>{const{projectPath:n,completed:i,issues:o,commits:c,notes:p}=e,u=t.getProject(n);if(!u)return{content:[{type:"text",text:"Project not found"}],isError:!0};let a=t.getTodaySession(u.id);a||(a=t.createSession(u.id,{}));const f={};i&&(f.completed=a.completed?`${a.completed}
35
+ ${i}`:i),o&&(f.issues=a.issues?`${a.issues}
36
+ ${o}`:o),c&&(f.commits=a.commits?`${a.commits}
37
37
  ${c}`:c),p&&(f.notes=a.notes?`${a.notes}
38
- ${p}`:p),a=t.updateSession(a.id,f);const r=[o,i,p].filter(Boolean).join(" \xB7 ");r&&t.updateContinuity(u.id,r,"session_update"),n()?.enqueue("session",a.id,u.id);const m={session_id:a.id,project:u.name,updated:Object.keys(f)};return x(m,(j,_)=>O(_.brand,`Session updated for ${j.project}`))}},{name:"wyrm_session_rehydrate",description:"Lossless session rehydration. Given a past session ID, returns a complete briefing markdown a fresh AI agent can ingest to inherit prior state: objectives, completed work, notes, summary, current ground truths, open quests, validated patterns (artifacts), unresolved failure patterns. Cross-session continuity no other AI memory tool offers.",inputSchema:{type:"object",properties:{session_id:{type:"number",description:"ID of the session to rehydrate"},include_artifacts:{type:"boolean",description:"Include memory artifacts (default true)"},include_failures:{type:"boolean",description:"Include unresolved failure patterns (default true)"},max_truth_chars:{type:"number",description:"Cap on chars used for ground truths (default 2000)"}},required:["session_id"]},outputSchema:{type:"object",properties:{session_id:{type:"integer"},project_name:{type:"string"},project_path:{type:"string"},briefing_markdown:{type:"string"},context_chars:{type:"integer"},attached:{type:"object",properties:{quests:{type:"integer"},truths:{type:"integer"},artifacts:{type:"integer"},failures:{type:"integer"}},required:["quests","truths","artifacts","failures"]}},required:["session_id","project_name","project_path","briefing_markdown","context_chars","attached"]},annotations:T.wyrm_session_rehydrate,aliases:[],handler:(e,{rehydration:t})=>{const{session_id:n,include_artifacts:s,include_failures:o,max_truth_chars:i}=e,c=t.rehydrate(n,{include_artifacts:s,include_failures:o,max_truth_chars:i});return c?x({...c},p=>p.briefing_markdown,{exemptStructured:!0}):{content:[{type:"text",text:`Session #${n} not found.`}],isError:!0}}},{name:"wyrm_session_prime",description:"Use first at session start - load everything you need to know before starting work, and catch me up on where we left off last time: ground truths, memory brief, reasoning scaffold, and active quests in one call. First call every agent makes in a run.",inputSchema:{type:"object",properties:{project_id:{type:"number"},project_name:{type:"string"},task:{type:"string",description:"Drives scaffold + memory selection"},log_session:{type:"boolean",description:"Also log a session row"},run_id:{type:"string",description:"Fleet: brief cached per (run_id, role)"},role:{type:"string"},token_budget:{type:"number"},for_spawn:{type:"boolean"}}},outputSchema:{type:"object",properties:{project_id:{type:"integer"},project_name:{type:"string"},session_id:{type:["integer","null"]},sections:{type:"array",items:{type:"object",properties:{kind:{type:"string"},text:{type:"string"}},required:["kind","text"]}}},required:["project_id","project_name","session_id","sections"]},annotations:T.wyrm_session_prime,aliases:[],handler:async(e,{store:t,raw:n,memory:s,truths:o,scaffolds:i,cache:c})=>{const{project_id:p,project_name:u,task:a,log_session:f}=e;if(e.run_id!==void 0&&e.run_id!==null)return pe(e,{store:t,raw:n,memory:s,truths:o,scaffolds:i,cache:c});const r=q(t,n(),p,u);if(!r)return P(t);const m=[],j=J(t.getContinuity(r.id));j&&m.push({kind:"continuity",text:j});const _=o.getCurrent(r.id);if(_.length>0&&m.push({kind:"truths",text:Q(_,!0).slice(0,1200)}),a){const E=i.findBest(a,r.id,.3);E&&m.push({kind:"scaffold",text:i.formatForContext(E,1500)})}const $=s.buildContextBrief(r.id,a??"general",{maxItems:10,minConfidence:.3});$.text&&m.push({kind:"memory",text:$.text.slice(0,2e3)});const y=n().prepare(V).all(r.id);y.length>0&&m.push({kind:"quests",text:Y(y).slice(0,800)});try{const{vaultAdvisory:E}=await import("../vault.js"),d=E();d.length>0&&m.push({kind:"vault",text:`### \u{1F510} Credential Vault
38
+ ${p}`:p),a=t.updateSession(a.id,f);const r=[i,o,p].filter(Boolean).join(" \xB7 ");r&&t.updateContinuity(u.id,r,"session_update"),s()?.enqueue("session",a.id,u.id);const m={session_id:a.id,project:u.name,updated:Object.keys(f)};return x(m,(g,_)=>O(_.brand,`Session updated for ${g.project}`))}},{name:"wyrm_session_rehydrate",description:"Lossless session rehydration. Given a past session ID, returns a complete briefing markdown a fresh AI agent can ingest to inherit prior state: objectives, completed work, notes, summary, current ground truths, open quests, validated patterns (artifacts), unresolved failure patterns. Cross-session continuity no other AI memory tool offers.",inputSchema:{type:"object",properties:{session_id:{type:"number",description:"ID of the session to rehydrate"},include_artifacts:{type:"boolean",description:"Include memory artifacts (default true)"},include_failures:{type:"boolean",description:"Include unresolved failure patterns (default true)"},max_truth_chars:{type:"number",description:"Cap on chars used for ground truths (default 2000)"}},required:["session_id"]},outputSchema:{type:"object",properties:{session_id:{type:"integer"},project_name:{type:"string"},project_path:{type:"string"},briefing_markdown:{type:"string"},context_chars:{type:"integer"},attached:{type:"object",properties:{quests:{type:"integer"},truths:{type:"integer"},artifacts:{type:"integer"},failures:{type:"integer"}},required:["quests","truths","artifacts","failures"]}},required:["session_id","project_name","project_path","briefing_markdown","context_chars","attached"]},annotations:T.wyrm_session_rehydrate,aliases:[],handler:(e,{rehydration:t})=>{const{session_id:s,include_artifacts:n,include_failures:i,max_truth_chars:o}=e,c=t.rehydrate(s,{include_artifacts:n,include_failures:i,max_truth_chars:o});return c?x({...c},p=>p.briefing_markdown,{exemptStructured:!0}):{content:[{type:"text",text:`Session #${s} not found.`}],isError:!0}}},{name:"wyrm_session_prime",description:"Use first at session start - load everything you need to know before starting work, and catch me up on where we left off last time: ground truths, memory brief, reasoning scaffold, and active quests in one call. First call every agent makes in a run.",inputSchema:{type:"object",properties:{project_id:{type:"number"},project_name:{type:"string"},task:{type:"string",description:"Drives scaffold + memory selection"},log_session:{type:"boolean",description:"Also log a session row"},run_id:{type:"string",description:"Fleet: brief cached per (run_id, role)"},role:{type:"string"},token_budget:{type:"number"},for_spawn:{type:"boolean"}}},outputSchema:{type:"object",properties:{project_id:{type:"integer"},project_name:{type:"string"},session_id:{type:["integer","null"]},sections:{type:"array",items:{type:"object",properties:{kind:{type:"string"},text:{type:"string"}},required:["kind","text"]}}},required:["project_id","project_name","session_id","sections"]},annotations:T.wyrm_session_prime,aliases:[],handler:async(e,{store:t,raw:s,memory:n,truths:i,scaffolds:o,cache:c})=>{const{project_id:p,project_name:u,task:a,log_session:f}=e;if(e.run_id!==void 0&&e.run_id!==null)return pe(e,{store:t,raw:s,memory:n,truths:i,scaffolds:o,cache:c});const r=q(t,s(),p,u);if(!r)return P(t);const m=[],g=G(t.getContinuity(r.id));g&&m.push({kind:"continuity",text:g});const _=i.getCurrent(r.id);if(_.length>0&&m.push({kind:"truths",text:J(_,!0).slice(0,1200)}),a){const j=o.findBest(a,r.id,.3);j&&m.push({kind:"scaffold",text:o.formatForContext(j,1500)})}const v=n.buildContextBrief(r.id,a??"general",{maxItems:10,minConfidence:.3});v.text&&m.push({kind:"memory",text:v.text.slice(0,2e3)});const y=s().prepare(V).all(r.id);y.length>0&&m.push({kind:"quests",text:Y(y).slice(0,800)});try{const j=s().prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE project_id = ? AND needs_review = 1").get(r.id).n;j>0&&m.push({kind:"review_queue",text:`### \u{1F4E5} Review Queue
39
+ ${j} captured memor${j===1?"y awaits":"ies await"} review (wyrm_review) \u2014 queued memory is invisible to recall until approved.`})}catch{}try{const{vaultAdvisory:j}=await import("../vault.js"),d=j();d.length>0&&m.push({kind:"vault",text:`### \u{1F510} Credential Vault
39
40
  `+d.map(l=>`- ${l}`).join(`
40
- `)})}catch{}let g=null;f&&(g=t.createSession(r.id,{objectives:a??"Session started via wyrm_session_prime",summary:""}).id);const h={project_id:r.id,project_name:r.name,truth_count:o.getStats(r.id).current,quest_count:y.length,memory_count:s.getStats(r.id).total,session_id:g,sections:m},b=x(h,L,A);return await D(n(),r.id,b),c.set(N("wyrm_session_prime",JSON.stringify(e)),b,3e4),b}}];export{Se as sessionToolSpecs};
41
+ `)})}catch{}let S=null;f&&(S=t.createSession(r.id,{objectives:a??"Session started via wyrm_session_prime",summary:""}).id);const h={project_id:r.id,project_name:r.name,truth_count:i.getStats(r.id).current,quest_count:y.length,memory_count:n.getStats(r.id).total,session_id:S,sections:m},E=x(h,L,A);return await D(s(),r.id,E),c.set(N("wyrm_session_prime",JSON.stringify(e)),E,3e4),E}}];export{Se as sessionToolSpecs};
@@ -1 +1 @@
1
- import{ValidationError as a}from"../validate.js";const m={wyrm_quest:{discriminator:"action",ownCase:!1,routes:{add:"wyrm_quest_add",complete:"wyrm_quest_complete",claim:"wyrm_quest_claim",release:"wyrm_quest_release",list:"wyrm_all_quests"}},wyrm_session:{discriminator:"action",ownCase:!1,routes:{start:"wyrm_session_start",update:"wyrm_session_update",rehydrate:"wyrm_session_rehydrate"}},wyrm_skill:{discriminator:"action",ownCase:!1,routes:{list:"wyrm_skill_list",search:"wyrm_skill_search",get:"wyrm_skill_get",register:"wyrm_skill_register",create:"wyrm_skill_create",activate:"wyrm_skill_activate",deactivate:"wyrm_skill_deactivate",graph:"wyrm_skill_graph",stats:"wyrm_skill_stats",delete:"wyrm_skill_delete"}},wyrm_entity:{discriminator:"action",ownCase:!1,routes:{search:"wyrm_entity_search",add:"wyrm_entity_add",link:"wyrm_entity_link",merge:"wyrm_entity_merge",path:"wyrm_entity_path",graph:"wyrm_entity_graph"}},wyrm_decision_trace:{discriminator:"action",ownCase:!1,routes:{upstream:"wyrm_decision_upstream",downstream:"wyrm_decision_downstream",invalidate:"wyrm_decision_invalidate"}},wyrm_goal:{discriminator:"action",ownCase:!1,routes:{list:"wyrm_goal_list",set:"wyrm_goal_set",complete:"wyrm_goal_complete",pause:"wyrm_goal_pause",resume:"wyrm_goal_resume",abandon:"wyrm_goal_abandon",iterations:"wyrm_goal_iterations"}},wyrm_presence:{discriminator:"action",ownCase:!1,routes:{list:"wyrm_presence_list",announce:"wyrm_presence_announce",release:"wyrm_presence_release"}},wyrm_mcp:{discriminator:"action",ownCase:!1,routes:{list:"wyrm_mcp_list",register:"wyrm_mcp_register",tools:"wyrm_mcp_tools",disable:"wyrm_mcp_disable"}},wyrm_audit:{discriminator:"action",ownCase:!1,routes:{log:"wyrm_audit_log",export:"wyrm_audit_export",verify:"wyrm_audit_verify"}},wyrm_project:{discriminator:"action",ownCase:!1,routes:{list:"wyrm_list_projects",context:"wyrm_project_context",scan:"wyrm_scan_projects",sync:"wyrm_sync"}},wyrm_design_token:{discriminator:"action",ownCase:!1,routes:{get:"wyrm_token_get",set:"wyrm_token_set",delete:"wyrm_token_delete"}},wyrm_reference:{discriminator:"action",ownCase:!1,routes:{list:"wyrm_reference_list",add:"wyrm_reference_add",search:"wyrm_reference_search"}},wyrm_replication:{discriminator:"action",ownCase:!0,routes:{conflicts:"wyrm_sync_conflicts",resolve:"wyrm_sync_resolve",publish:"wyrm_events_publish",since:"wyrm_events_since",subscribe:"wyrm_events_subscribe",replicate:"wyrm_events_replicate"}},wyrm_capture:{discriminator:"mode",ownCase:!0,routes:{classify:"wyrm_capture",direct:"wyrm_remember",extract:"wyrm_auto_capture",trace:"wyrm_capture_trace",session:"wyrm_distill",artifacts:"wyrm_harvest",import:{key:"source",routes:{git:"wyrm_import_git",pr:"wyrm_import_pr",rules:"wyrm_import_rules"}},spec:"wyrm_spec_register",checklist:"wyrm_scaffold_save"}}},c=[{name:"wyrm_quest",description:"Use for project tasks and todos - action=add (add a todo or work item), complete (mark a task as done), claim (lock a quest so other agents don't duplicate the work; TTL lease stamped with agent_id/run_id), release, list (what's still open on my plate across all projects). The fleet coordination primitive.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["add","complete","claim","release","list"]},projectPath:{type:"string",description:"add"},title:{type:"string",description:"add"},description:{type:"string"},priority:{type:"string",description:"critical|high|medium|low"},tags:{type:"string",description:"add"},questId:{type:"number",description:"complete"},quest_id:{type:"number",description:"claim/release"},agent_id:{type:"string",description:"claim/release"},ttl_seconds:{type:"number",description:"claim"}},required:["action"]}},{name:"wyrm_session",description:"Use to track working sessions - action=start (start tracking a new working session on a repo), update (log what you just finished: completed work, issues, commits), rehydrate (the full briefing from a past session so a fresh agent can take over).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["start","update","rehydrate"]},projectPath:{type:"string",description:"start/update"},objectives:{type:"string"},completed:{type:"string",description:"update"},issues:{type:"string"},commits:{type:"string",description:"update"},notes:{type:"string"},session_id:{type:"number",description:"rehydrate"}},required:["action"]}},{name:"wyrm_skill",description:"Use for reusable playbooks (skills) - do we already have a playbook for this? action=list (the playbooks and capabilities registered on this machine), search, get, register, create (package what you just learned into a reusable skill), activate, deactivate, graph (governance tree), stats, delete.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","search","get","register","create","activate","deactivate","graph","stats","delete"]},name:{type:"string",description:"skill name"},description:{type:"string",description:"register/create"},skillPath:{type:"string",description:"register"},body:{type:"string",description:"create"},query:{type:"string"},category:{type:"string",description:"list/register/create"},tier:{type:"string",description:"atomic|mega|god"},limit:{type:"number",description:"search"}},required:["action"]}},{name:"wyrm_entity",description:"Use for the knowledge graph - action=add (a person, vendor, service, or concept), link (record that Alice maintains the deploy pipeline: who maintains, uses, or depends on what), search, merge (destructive), path (how two entities or services are related to each other), graph (show everything connected to an entity, N hops).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["search","add","link","merge","path","graph"]},projectPath:{type:"string"},name:{type:"string",description:"add"},type:{type:"string",description:"add/search"},source:{type:"string",description:"link/merge/path"},target:{type:"string",description:"link/merge/path"},relationship:{type:"string",description:"link: uses|depends_on"},query:{type:"string"},entity:{type:"string",description:"graph"},depth:{type:"number",description:"graph"},limit:{type:"number",description:"search"}},required:["action"]}},{name:"wyrm_decision_trace",description:"Use to trace decision causality - action=upstream (why did we pick this? walk me through the reasoning chain back to its sources), downstream (if that assumption turns out to be wrong, what else breaks - the blast radius), invalidate (a foundational fact was wrong: flag everything we built on top of it, cascading).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["upstream","downstream","invalidate"]},kind:{type:"string",enum:["truth","artifact","quest","session","data"]},id:{type:"number"},reason:{type:"string",description:"invalidate"}},required:["action"]}},{name:"wyrm_goal",description:"Use for persistent goals the wyrm-loop daemon pursues autonomously - action=set (define with success criteria), list, complete, pause, resume, abandon, iterations (the OODA pursuit history).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","set","complete","pause","resume","abandon","iterations"]},title:{type:"string"},description:{type:"string"},success_criteria:{type:"string",description:"set: definition of done"},priority:{type:"string",description:"set: critical|high|medium|low"},projectPath:{type:"string"},id:{type:"number",description:"complete/pause/resume/abandon"},goal_id:{type:"number",description:"iterations"}},required:["action"]}},{name:"wyrm_presence",description:"Use for multi-agent presence - who else is working on this right now? action=list, announce (I'm online and working on X; a TTL heartbeat orchestrators and other agents see), release (clean exit: clears presence and drops any quest claims held).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","announce","release"]},agent_id:{type:"string"},agent_kind:{type:"string",description:"announce: claude|codex|human"},projectPath:{type:"string"},current_file:{type:"string",description:"announce"},ttl_seconds:{type:"number",description:"announce"}},required:["action"]}},{name:"wyrm_mcp",description:"Use to manage outbound MCP servers Wyrm can call - action=register (command, args, env), list, tools (one-shot tools/list), disable. Call a registered server's tools via wyrm_call_external.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","register","tools","disable"]},server_name:{type:"string"},command:{type:"string",description:"register: executable"},args:{type:"array",items:{type:"string"},description:"register: argv"},env:{type:"object",description:"register"}},required:["action"]}},{name:"wyrm_audit",description:"Use for the tamper-evident audit chain - action=log (append a tamper-evident, hash-chained record of an admin action), export (the audit history as an offline-verifiable bundle for a compliance review), verify (prove the audit trail hasn't been tampered with).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["log","export","verify"]},event_kind:{type:"string",description:"log: tool_call etc"},actor:{type:"string"},projectPath:{type:"string"},payload:{type:"object",description:"log"},range_start:{type:"string",description:"export"},range_end:{type:"string",description:"export"}},required:["action"]}},{name:"wyrm_project",description:"Use for the project registry and cross-project landscape - action=list, context (one project's memory overview), scan (discover and register git repos under a directory), sync (DB rows to per-project .wyrm folders).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","context","scan","sync"]},search:{type:"string",description:"list"},limit:{type:"number"},projectPath:{type:"string",description:"context/sync"},projectName:{type:"string",description:"context"},path:{type:"string",description:"scan"},watch:{type:"boolean",description:"scan"},recursive:{type:"boolean"},direction:{type:"string",description:"sync: import|export|both"}},required:["action"]}},{name:"wyrm_design_token",description:"Use for the project's design system - store and read the values the brand uses: color, type, spacing, motion, shadow, radius, breakpoint. action=set (upsert a primary color or spacing value), get (what values does this design system use?), delete.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get","set","delete"]},projectPath:{type:"string"},category:{type:"string",enum:["color","type","spacing","motion","shadow","radius","breakpoint","custom"]},key:{type:"string",description:"set/delete"},value:{type:"string",description:"set"}},required:["action"]}},{name:"wyrm_reference",description:"Use for design references and visual inspiration - action=add (clip a website, image, palette, or snippet to keep for later projects), search (find that inspiration link I saved a while back), list.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","add","search"]},projectPath:{type:"string",description:"Omit for global"},kind:{type:"string",enum:["url","image","palette","snippet"],description:"add"},location:{type:"string",description:"add: URL/path/inline"},title:{type:"string"},tags:{type:"string",description:"add"},query:{type:"string",description:"search"},limit:{type:"number"}},required:["action"]}}];function g(){return c.map(r=>({...r}))}const w=c.map(r=>r.name).sort();function h(r,i){const e=m[r];if(!e)return{tool:r,args:i};const s=i[e.discriminator],t=typeof s=="string"?e.routes[s]:void 0;if(t===void 0){if(e.ownCase)return{tool:r,args:i};throw new a(e.discriminator,`must be one of: ${Object.keys(e.routes).join(", ")}`)}if(typeof t=="string"){const{[e.discriminator]:u,...d}=i;return{tool:t,args:d}}const n=i[t.key],o=typeof n=="string"?t.routes[n]:void 0;if(o===void 0)throw new a(t.key,`${e.discriminator}=${String(s)} requires ${t.key} \u2014 one of: ${Object.keys(t.routes).join(", ")}`);const{[e.discriminator]:y,[t.key]:l,...p}=i;return{tool:o,args:p}}export{m as SHIM_ROUTES,w as SHIM_TOOL_NAMES,h as resolveShimCall,g as shimToolDefs};
1
+ import{ValidationError as a}from"../validate.js";const m={wyrm_quest:{discriminator:"action",ownCase:!1,routes:{add:"wyrm_quest_add",complete:"wyrm_quest_complete",claim:"wyrm_quest_claim",release:"wyrm_quest_release",list:"wyrm_all_quests"}},wyrm_session:{discriminator:"action",ownCase:!1,routes:{start:"wyrm_session_start",update:"wyrm_session_update",rehydrate:"wyrm_session_rehydrate"}},wyrm_skill:{discriminator:"action",ownCase:!1,routes:{list:"wyrm_skill_list",search:"wyrm_skill_search",get:"wyrm_skill_get",register:"wyrm_skill_register",create:"wyrm_skill_create",activate:"wyrm_skill_activate",deactivate:"wyrm_skill_deactivate",graph:"wyrm_skill_graph",stats:"wyrm_skill_stats",delete:"wyrm_skill_delete"}},wyrm_entity:{discriminator:"action",ownCase:!1,routes:{search:"wyrm_entity_search",add:"wyrm_entity_add",link:"wyrm_entity_link",merge:"wyrm_entity_merge",path:"wyrm_entity_path",graph:"wyrm_entity_graph"}},wyrm_decision_trace:{discriminator:"action",ownCase:!1,routes:{upstream:"wyrm_decision_upstream",downstream:"wyrm_decision_downstream",invalidate:"wyrm_decision_invalidate"}},wyrm_goal:{discriminator:"action",ownCase:!1,routes:{list:"wyrm_goal_list",set:"wyrm_goal_set",complete:"wyrm_goal_complete",pause:"wyrm_goal_pause",resume:"wyrm_goal_resume",abandon:"wyrm_goal_abandon",iterations:"wyrm_goal_iterations"}},wyrm_presence:{discriminator:"action",ownCase:!1,routes:{list:"wyrm_presence_list",announce:"wyrm_presence_announce",release:"wyrm_presence_release"}},wyrm_mcp:{discriminator:"action",ownCase:!1,routes:{list:"wyrm_mcp_list",register:"wyrm_mcp_register",tools:"wyrm_mcp_tools",disable:"wyrm_mcp_disable"}},wyrm_audit:{discriminator:"action",ownCase:!1,routes:{log:"wyrm_audit_log",export:"wyrm_audit_export",verify:"wyrm_audit_verify"}},wyrm_project:{discriminator:"action",ownCase:!1,routes:{list:"wyrm_list_projects",context:"wyrm_project_context",scan:"wyrm_scan_projects",sync:"wyrm_sync"}},wyrm_design_token:{discriminator:"action",ownCase:!1,routes:{get:"wyrm_token_get",set:"wyrm_token_set",delete:"wyrm_token_delete"}},wyrm_reference:{discriminator:"action",ownCase:!1,routes:{list:"wyrm_reference_list",add:"wyrm_reference_add",search:"wyrm_reference_search"}},wyrm_replication:{discriminator:"action",ownCase:!0,routes:{conflicts:"wyrm_sync_conflicts",resolve:"wyrm_sync_resolve",publish:"wyrm_events_publish",since:"wyrm_events_since",subscribe:"wyrm_events_subscribe",replicate:"wyrm_events_replicate"}},wyrm_capture:{discriminator:"mode",ownCase:!0,routes:{classify:"wyrm_capture",direct:"wyrm_remember",extract:"wyrm_auto_capture",trace:"wyrm_capture_trace",session:"wyrm_distill",artifacts:"wyrm_harvest",import:{key:"source",routes:{git:"wyrm_import_git",pr:"wyrm_import_pr",rules:"wyrm_import_rules"}},spec:"wyrm_spec_register",checklist:"wyrm_scaffold_save"}}},c=[{name:"wyrm_quest",description:"Use for project tasks and todos - action=add (add a todo or work item), complete (mark a task as done), claim (lock a quest so other agents don't duplicate the work; TTL lease stamped with agent_id/run_id), release, list (what's still open on my plate across all projects). The fleet coordination primitive.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["add","complete","claim","release","list"]},projectPath:{type:"string",description:"add"},title:{type:"string",description:"add"},description:{type:"string"},priority:{type:"string",description:"critical|high|medium|low"},tags:{type:"string",description:"add"},questId:{type:"number",description:"complete"},quest_id:{type:"number",description:"claim/release"},agent_id:{type:"string",description:"claim/release"},ttl_seconds:{type:"number",description:"claim"}},required:["action"]}},{name:"wyrm_session",description:"Use to track working sessions - action=start (start tracking a new working session on a repo), update (log what you just finished: completed work, issues, commits), rehydrate (the full briefing from a past session so a fresh agent can take over).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["start","update","rehydrate"]},projectPath:{type:"string",description:"start/update"},objectives:{type:"string"},completed:{type:"string",description:"update"},issues:{type:"string"},commits:{type:"string",description:"update"},notes:{type:"string"},session_id:{type:"number",description:"rehydrate"}},required:["action"]}},{name:"wyrm_skill",description:"Use for reusable playbooks (skills) - do we already have a playbook for this? action=list (the playbooks and capabilities registered on this machine), search, get, register, create (package what you just learned into a reusable skill), activate, deactivate, graph (governance tree), stats, delete.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","search","get","register","create","activate","deactivate","graph","stats","delete"]},name:{type:"string",description:"skill name"},description:{type:"string",description:"register/create"},skillPath:{type:"string",description:"register"},body:{type:"string",description:"create"},query:{type:"string"},category:{type:"string",description:"list/register/create"},tier:{type:"string",description:"atomic|mega|god|fable"},limit:{type:"number",description:"search"}},required:["action"]}},{name:"wyrm_entity",description:"Use for the knowledge graph - action=add (a person, vendor, service, or concept), link (record that Alice maintains the deploy pipeline: who maintains, uses, or depends on what), search, merge (destructive), path (how two entities or services are related to each other), graph (show everything connected to an entity, N hops).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["search","add","link","merge","path","graph"]},projectPath:{type:"string"},name:{type:"string",description:"add"},type:{type:"string",description:"add/search"},source:{type:"string",description:"link/merge/path"},target:{type:"string",description:"link/merge/path"},relationship:{type:"string",description:"link: uses|depends_on"},query:{type:"string"},entity:{type:"string",description:"graph"},depth:{type:"number",description:"graph"},limit:{type:"number",description:"search"}},required:["action"]}},{name:"wyrm_decision_trace",description:"Use to trace decision causality - action=upstream (why did we pick this? walk me through the reasoning chain back to its sources), downstream (if that assumption turns out to be wrong, what else breaks - the blast radius), invalidate (a foundational fact was wrong: flag everything we built on top of it, cascading).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["upstream","downstream","invalidate"]},kind:{type:"string",enum:["truth","artifact","quest","session","data"]},id:{type:"number"},reason:{type:"string",description:"invalidate"}},required:["action"]}},{name:"wyrm_goal",description:"Use for persistent goals the wyrm-loop daemon pursues autonomously - action=set (define with success criteria), list, complete, pause, resume, abandon, iterations (the OODA pursuit history).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","set","complete","pause","resume","abandon","iterations"]},title:{type:"string"},description:{type:"string"},success_criteria:{type:"string",description:"set: definition of done"},priority:{type:"string",description:"set: critical|high|medium|low"},projectPath:{type:"string"},id:{type:"number",description:"complete/pause/resume/abandon"},goal_id:{type:"number",description:"iterations"}},required:["action"]}},{name:"wyrm_presence",description:"Use for multi-agent presence - who else is working on this right now? action=list, announce (I'm online and working on X; a TTL heartbeat orchestrators and other agents see), release (clean exit: clears presence and drops any quest claims held).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","announce","release"]},agent_id:{type:"string"},agent_kind:{type:"string",description:"announce: claude|codex|human"},projectPath:{type:"string"},current_file:{type:"string",description:"announce"},ttl_seconds:{type:"number",description:"announce"}},required:["action"]}},{name:"wyrm_mcp",description:"Use to manage outbound MCP servers Wyrm can call - action=register (command, args, env), list, tools (one-shot tools/list), disable. Call a registered server's tools via wyrm_call_external.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","register","tools","disable"]},server_name:{type:"string"},command:{type:"string",description:"register: executable"},args:{type:"array",items:{type:"string"},description:"register: argv"},env:{type:"object",description:"register"}},required:["action"]}},{name:"wyrm_audit",description:"Use for the tamper-evident audit chain - action=log (append a tamper-evident, hash-chained record of an admin action), export (the audit history as an offline-verifiable bundle for a compliance review), verify (prove the audit trail hasn't been tampered with).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["log","export","verify"]},event_kind:{type:"string",description:"log: tool_call etc"},actor:{type:"string"},projectPath:{type:"string"},payload:{type:"object",description:"log"},range_start:{type:"string",description:"export"},range_end:{type:"string",description:"export"}},required:["action"]}},{name:"wyrm_project",description:"Use for the project registry and cross-project landscape - action=list, context (one project's memory overview), scan (discover and register git repos under a directory), sync (DB rows to per-project .wyrm folders).",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","context","scan","sync"]},search:{type:"string",description:"list"},limit:{type:"number"},projectPath:{type:"string",description:"context/sync"},projectName:{type:"string",description:"context"},path:{type:"string",description:"scan"},watch:{type:"boolean",description:"scan"},recursive:{type:"boolean"},direction:{type:"string",description:"sync: import|export|both"}},required:["action"]}},{name:"wyrm_design_token",description:"Use for the project's design system - store and read the values the brand uses: color, type, spacing, motion, shadow, radius, breakpoint. action=set (upsert a primary color or spacing value), get (what values does this design system use?), delete.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get","set","delete"]},projectPath:{type:"string"},category:{type:"string",enum:["color","type","spacing","motion","shadow","radius","breakpoint","custom"]},key:{type:"string",description:"set/delete"},value:{type:"string",description:"set"}},required:["action"]}},{name:"wyrm_reference",description:"Use for design references and visual inspiration - action=add (clip a website, image, palette, or snippet to keep for later projects), search (find that inspiration link I saved a while back), list.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["list","add","search"]},projectPath:{type:"string",description:"Omit for global"},kind:{type:"string",enum:["url","image","palette","snippet"],description:"add"},location:{type:"string",description:"add: URL/path/inline"},title:{type:"string"},tags:{type:"string",description:"add"},query:{type:"string",description:"search"},limit:{type:"number"}},required:["action"]}}];function g(){return c.map(r=>({...r}))}const w=c.map(r=>r.name).sort();function h(r,i){const e=m[r];if(!e)return{tool:r,args:i};const s=i[e.discriminator],t=typeof s=="string"?e.routes[s]:void 0;if(t===void 0){if(e.ownCase)return{tool:r,args:i};throw new a(e.discriminator,`must be one of: ${Object.keys(e.routes).join(", ")}`)}if(typeof t=="string"){const{[e.discriminator]:u,...d}=i;return{tool:t,args:d}}const n=i[t.key],o=typeof n=="string"?t.routes[n]:void 0;if(o===void 0)throw new a(t.key,`${e.discriminator}=${String(s)} requires ${t.key} \u2014 one of: ${Object.keys(t.routes).join(", ")}`);const{[e.discriminator]:y,[t.key]:l,...p}=i;return{tool:o,args:p}}export{m as SHIM_ROUTES,w as SHIM_TOOL_NAMES,h as resolveShimCall,g as shimToolDefs};