wyrm-mcp 7.11.0 → 7.12.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.
- package/dist/context-ranking.js +1 -1
- package/dist/handlers/capture.js +58 -58
- package/dist/harvest.js +5 -5
- package/dist/memory-artifacts.js +26 -26
- package/dist/migrations.js +7 -0
- package/dist/presence.js +5 -13
- package/dist/tool-manifest-v2.json +1 -1
- package/dist/tool-manifest.json +1 -1
- package/dist/wyrm-cli.js +1 -1
- package/dist/wyrm-manifest.json +1 -1
- package/package.json +1 -1
package/dist/context-ranking.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{logger as
|
|
1
|
+
import{logger as m}from"./logger.js";const u={confidence:.4,recency:.2,relevance:.3,usefulness:.1};function E(e=process.env){const t=e.WYRM_RANK_WEIGHTS;if(!t)return{...u};try{const n=JSON.parse(t),s={confidence:c(n.confidence??u.confidence),recency:c(n.recency??u.recency),relevance:c(n.relevance??u.relevance),usefulness:c(n.usefulness??u.usefulness)},r=s.confidence+s.recency+s.relevance+s.usefulness;return r<=0?{...u}:(s.confidence/=r,s.recency/=r,s.relevance/=r,s.usefulness/=r,s)}catch(n){return m.warn(`Invalid WYRM_RANK_WEIGHTS, using defaults: ${n.message}`),{...u}}}function c(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):0}const p=.25,f=30;function _(e=process.env){const t=Number(e.WYRM_RECALL_RECENCY_WEIGHT);return Number.isFinite(t)?c(t):p}function N(e=process.env){const t=Number(e.WYRM_RECALL_RECENCY_HALFLIFE_DAYS);return Number.isFinite(t)&&t>=1?t:f}const y=[/\bignore\s+(all\s+)?(previous|prior|above|earlier)\s+(instructions?|prompts?|context)\b/i,/\bdisregard\s+(all\s+)?(previous|prior|your)\s+(instructions?|rules|guidelines)\b/i,/\byou\s+(must|are\s+required\s+to)\s+(now\s+)?(obey|comply|execute|run|send|forward|delete)\b/i,/\b(system|assistant)\s*prompt\s*[:=]/i,/\bBEGIN\s+(SYSTEM|ADMIN|OVERRIDE)\b/,/\bnew\s+(system\s+)?instructions?\s*[:=]/i,/\b(reveal|print|exfiltrate|send)\s+(your|the)\s+(api\s*key|token|secret|password|credentials)\b/i,/\bcurl\s+[^\n]{0,120}\|\s*(ba)?sh\b/i,/\bact\s+as\s+(the\s+)?(root|admin|system)\b/i,/\bdo\s+not\s+(tell|inform|alert)\s+the\s+(user|operator|owner)\b/i];function D(e){return e?y.some(t=>t.test(e)):!1}function M(e){return e==="imported"?"\u26A0 [imported] ":e==="untrusted"?"\u26A0 [untrusted] ":""}function T(e,t=new Date){const n=e.toLowerCase();if(/\btoday\b/.test(n))return{fromDaysAgo:1.5,toDaysAgo:0};if(/\byesterday\b/.test(n))return{fromDaysAgo:2.5,toDaysAgo:.5};if(/\b(this|past)\s+week\b/.test(n))return{fromDaysAgo:7,toDaysAgo:0};if(/\blast\s+week\b/.test(n))return{fromDaysAgo:14,toDaysAgo:5};const s=n.match(/\blast\s+(\d{1,3})\s+days?\b/);if(s)return{fromDaysAgo:Number(s[1])+.5,toDaysAgo:0};const r=n.match(/\b(\d{1,3})\s+days?\s+ago\b/);if(r){const o=Number(r[1]);return{fromDaysAgo:o+1.5,toDaysAgo:Math.max(0,o-1.5)}}const a=n.match(/\b(\d{4})-(\d{2})-(\d{2})\b/);if(a){const o=new Date(`${a[1]}-${a[2]}-${a[3]}T12:00:00Z`).getTime();if(Number.isFinite(o)){const i=(t.getTime()-o)/864e5;return{fromDaysAgo:i+1,toDaysAgo:Math.max(0,i-1)}}}return null}function x(e=process.env){const t=Number(e.WYRM_RECALL_TEMPORAL_WEIGHT);return Number.isFinite(t)?c(t):.5}function R(e,t,n,s=new Date){const r=c(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,o=a?new Date(a).getTime():NaN;if(!Number.isFinite(o))return 1-r;const i=(s.getTime()-o)/864e5;return i<=t.fromDaysAgo&&i>=t.toDaysAgo?1:1-r}function h(e=process.env){const t=Number(e.WYRM_RECALL_USEFULNESS_WEIGHT);return Number.isFinite(t)?Math.max(0,Math.min(.5,t)):.15}function w(e,t,n){const s=Math.max(0,Math.min(.5,n));if(s===0||!e||e<=0)return 1;const r=Math.max(0,Math.min(1,(t??0)/e));return 1+s*r*Math.min(1,e/3)}function L(e,t,n,s=new Date){const r=c(t);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,o=a?new Date(a).getTime():NaN;if(!Number.isFinite(o))return 1-r;const i=Math.max(0,(s.getTime()-o)/864e5),l=n>=1?n:f;return 1-r+r*Math.pow(2,-i/l)}const b=.5,A=/^\s*\[auto:(precompact|sessionend|sessionstart)/i;function v(e){return e&&A.test(e)?b:0}function F(e,t,n=new Date){const s=c(e.confidence??.5),r=c(e.usefulness??.5),a=c(e.relevance??.5),o=e.updatedAt?Math.max(0,(n.getTime()-new Date(e.updatedAt).getTime())/(1440*60*1e3)):1/0,i=Number.isFinite(o)?Math.exp(-o/30):0,l=s*t.confidence+i*t.recency+a*t.relevance+r*t.usefulness,d=c(e.sourcePenalty??0);return c(l*(1-d))}export{b as AUTO_SUMMARY_PENALTY,f as DEFAULT_RECALL_RECENCY_HALFLIFE_DAYS,p as DEFAULT_RECALL_RECENCY_WEIGHT,u as DEFAULT_WEIGHTS,v as autoSummaryPenalty,T as extractTemporalWindow,E as loadWeightsFromEnv,D as looksInjectionShaped,N as recallRecencyHalfLifeDays,_ as recallRecencyWeight,x as recallTemporalWeight,h as recallUsefulnessWeight,L as recencyMultiplier,F as score,R as temporalMultiplier,M as trustMarker,w as usefulnessMultiplier};
|
package/dist/handlers/capture.js
CHANGED
|
@@ -1,78 +1,78 @@
|
|
|
1
|
-
import{join as
|
|
1
|
+
import{join as K}from"path";import{createHash as O}from"crypto";import{TOOL_ANNOTATIONS as D}from"../tool-annotations.js";import{renderResult as S,withGlyph as E,renderErrorResponse as R,validationErrorBody as C}from"../render.js";import{ValidationError as J,asEnum as Y}from"../validate.js";import{daemonOr as L}from"../daemon-writer.js";import{classifyCapture as Q}from"../capture.js";import{recordWrite as A}from"../receipts.js";import{extractCandidates as F,candidateToArtifact as N,escapeLikePattern as M}from"../auto-capture.js";import{parseTrace as X,segmentsToText as G}from"../trace-harvest.js";import{getActor as V,runWithActor as z}from"./boundary.js";import{harvestProjects as Z}from"../harvest.js";import{readFileSync as U,readdirSync as ee,statSync as W}from"fs";import{join as H}from"path";import{homedir as te}from"os";import{readSpecDir as re,specTaskSignature as ie}from"../spec-kit.js";const ve=[{name:"wyrm_capture",description:"Use to save anything worth keeping - the single write funnel. Auto-classifies notes, decisions, and lessons into quest, ground truth, or memory; risky writes queue for wyrm_review. mode=direct (store a proven pattern or lesson learned so future agents reuse it), extract (pull memories from a conversation transcript or freeform text), trace (harvest a session JSONL / tool-call log into run-tagged review candidates), session (close out a work session into reusable knowledge), artifacts (harvest a repo's READMEs and recent commits into durable facts), import source=git|pr|rules, spec (turn a tasks.md into tracked work items), checklist. Keywords: remember this, jot down, write down, future reference.",inputSchema:{type:"object",properties:{content:{type:"string",description:"classify/rules"},project_id:{type:"number",description:"classify/import/spec"},tags:{type:"array",items:{type:"string"}},mode:{type:"string",enum:["auto","quest","truth","memory","classify","direct","extract","trace","session","artifacts","import","spec","checklist"],description:"quest|truth|memory force the type"},source:{type:"string",enum:["git","pr","rules"],description:"import"},projectPath:{type:"string",description:"non-classify"},kind:{type:"string",description:"direct"},problem:{type:"string",description:"direct"},validatedFix:{type:"string",description:"direct"},text:{type:"string",description:"extract"},sessionId:{type:"string",description:"session"},candidates:{type:"array",items:{type:"object"},description:"session"},dryRun:{type:"boolean",description:"artifacts"},commits:{type:"array",items:{type:"object"},description:"import git"},title:{type:"string",description:"import pr"},body:{type:"string",description:"import pr"},specDir:{type:"string",description:"spec"},problemType:{type:"string",description:"checklist"},whenToUse:{type:"string",description:"checklist"},steps:{type:"array",items:{type:"string"},description:"checklist"}},required:[]},outputSchema:{type:"object",properties:{status:{type:"string",enum:["captured","queued_for_review"]},type:{type:"string"},subtype:{type:"string"},confidence:{type:"number"},reasoning:{type:"string"},id:{type:"integer"},ref:{type:"string"},needs_review:{type:"boolean"},reason:{type:"string"},artifact_id:{type:"integer"},conflicts_with:{type:"array"},advisory_conflicts:{type:"array"}},required:["status"]},annotations:D.wyrm_capture,aliases:[],handler:async($,{store:b,raw:x,memory:w,truths:l,cache:h})=>{const{content:a,project_id:g,projectPath:n,tags:f,mode:p}=$;if(typeof a!="string"||!a.trim()){const r=$;return r.problem||r.validated_fix||r.validatedFix||r.kind?R(C("wyrm_capture","mode","you passed pattern/lesson fields (kind/problem/validated_fix) \u2014 set mode:'direct' to store them as a distilled artifact.")):R(C("wyrm_capture","content","content is required for auto capture (or use mode:'direct' with problem + validated_fix)."))}let v=Q(a);p&&p!=="auto"&&(v={type:p,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[p]??p,confidence:100,reasoning:`Mode override: ${p}`});const{type:d,subtype:s,confidence:u,reasoning:o}=v,e=g??(n?b.getProject(n)?.id??null:null);let i=0,y="",j=!1,t;if(d==="quest"){if(e===null)return R(C("wyrm_capture","projectPath","is required for quest capture"));i=(await L("quest_add",e,{title:a.slice(0,200),description:"",priority:"medium",tags:f?.join(",")},()=>b.addQuest(e,a.slice(0,200),"","medium",f?.join(",")))).id,y="quest",h.invalidate("wyrm_all_quests"),h.invalidate("wyrm_stats")}else if(d==="truth"){if(e===null)return R(C("wyrm_capture","projectPath","is required for truth capture"));if(u>=80){const r=s??"other",P=l.getCurrent(e).filter(c=>c.category===r);if(P.length>0){const c={kind:"pattern",problem:`Potential conflict with ${P.length} existing truth(s) in category "${r}"`,validatedFix:a,whyItWorked:"Pending review \u2014 possible supersession",tags:f??[],confidence:u/100,needsReview:1},k=await L("artifact_add",e,c,()=>w.add(e,c)),q=A(x(),{tool:"wyrm_capture",outcome:"queued",refTable:"mem",refId:k.id,reason:`conflict_check \u2014 possible supersession of ${P.length} truth(s); review to activate`,projectId:e});return S({status:"queued_for_review",reason:"conflict_check",artifact_id:k.id,conflicts_with:P.map(T=>({id:T.id,content:T.value.slice(0,80)})),receipt:q})}}if(p!=="truth"&&u<100){const r={kind:"pattern",problem:a,validatedFix:"",whyItWorked:"",tags:f??[],confidence:u/100,needsReview:1};i=(await L("artifact_add",e,r,()=>w.add(e,r))).id,y="mem",j=!0}else{const r={category:"decision",key:a.slice(0,60),value:a};i=(await L("truth_set",e,r,()=>l.set(e,r))).id,y="truth",h.invalidate("wyrm_truth_get"),h.invalidate("wyrm_context_build")}}else{if(e===null)return R(C("wyrm_capture","projectPath","is required for memory capture"));const r=u>=75,I={kind:s,problem:a,validatedFix:"",whyItWorked:"",tags:f??[],confidence:u/100,needsReview:r?0:1};if(i=(await L("artifact_add",e,I,()=>w.add(e,I))).id,y="mem",j=!r,s==="heuristic"&&u>=75&&e!==null)try{const c=a.replace(/['"*]/g," ").trim().split(/\s+/).slice(0,5).join(" "),k=x().prepare(`
|
|
2
2
|
SELECT a.id, a.problem FROM memory_artifacts a
|
|
3
3
|
JOIN memory_artifacts_fts ON a.id = memory_artifacts_fts.rowid
|
|
4
4
|
WHERE memory_artifacts_fts MATCH ? AND a.project_id = ? AND a.kind = 'heuristic' AND a.needs_review = 0
|
|
5
5
|
LIMIT 3
|
|
6
|
-
`).all(
|
|
7
|
-
Confidence: ${
|
|
8
|
-
ID: ${
|
|
9
|
-
`+E(
|
|
10
|
-
|
|
11
|
-
`+E(
|
|
12
|
-
`+
|
|
13
|
-
`)),
|
|
14
|
-
|
|
15
|
-
`;return
|
|
16
|
-
`,
|
|
17
|
-
`,
|
|
18
|
-
`,
|
|
19
|
-
`),
|
|
20
|
-
`),
|
|
21
|
-
`,
|
|
22
|
-
`),
|
|
23
|
-
`);return E(
|
|
24
|
-
${
|
|
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:
|
|
27
|
-
`);return E(
|
|
6
|
+
`).all(c,e);k.length>0&&(t=k.map(q=>({id:q.id,content:q.problem.slice(0,80)})))}catch{}}const _=A(x(),{tool:"wyrm_capture",outcome:j?"queued":"stored",refTable:y,refId:i,reason:j?`needs_review (confidence ${u}%) \u2014 review to activate`:void 0,projectId:e??void 0}),m={status:"captured",type:d,subtype:s,confidence:u,reasoning:o,id:i,ref:`${y}:${i}`,needs_review:j,receipt:_,...t&&t.length>0?{advisory_conflicts:t}:{}};return S(m,(r,I)=>{let P=`Captured as ${r.type}: ${r.subtype}
|
|
7
|
+
Confidence: ${r.confidence}% | ${r.reasoning}
|
|
8
|
+
ID: ${r.ref}`;r.needs_review&&(P+=`
|
|
9
|
+
`+E(I.warn,"Stored for review -- run `wyrm_review` to activate"));const c=r.advisory_conflicts;return c&&c.length>0&&(P+=`
|
|
10
|
+
|
|
11
|
+
`+E(I.warn,`Advisory: ${c.length} similar heuristic(s) found:`)+`
|
|
12
|
+
`+c.map(k=>` ${I.bullet} [${k.id}] ${k.content}`).join(`
|
|
13
|
+
`)),P})}},{name:"wyrm_remember",description:"Store a distilled knowledge artifact \u2014 proven patterns, lessons learned, anti-patterns, and reasoning traces. These are recalled automatically by wyrm_context_build to help AI models apply past knowledge to new tasks. Example: wyrm_remember({ projectPath: '/home/user/api', kind: 'anti_pattern', problem: 'Jest suite hung after adding the SSE server', validatedFix: 'close() the server in afterAll \u2014 its keep-alive timer held the event loop open', whyItWorked: 'open handles block jest exit', outcome: 'positive', tags: ['jest', 'sse'] })",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project this knowledge belongs to"},kind:{type:"string",enum:["reasoning_trace","lesson","pattern","anti_pattern","heuristic"],description:"reasoning_trace: a solved problem with steps; lesson: a general insight; pattern: a proven approach; anti_pattern: what NOT to do; heuristic: a rule of thumb"},problem:{type:"string",description:"What was being solved or observed (be specific and searchable)"},constraints:{type:"string",description:"What conditions or constraints applied"},validatedFix:{type:"string",description:"What actually worked \u2014 the validated solution or approach"},whyItWorked:{type:"string",description:"The insight behind WHY this worked (key for transfer learning)"},outcome:{type:"string",enum:["positive","negative","neutral"],description:"Was this approach successful?"},tags:{type:"array",items:{type:"string"},description:"Searchable tags (e.g. ['auth', 'rate-limit', 'typescript'])"},confidence:{type:"number",description:"Confidence level 0.0\u20131.0 (default: 1.0)"},sourceSessionId:{type:"number",description:"Session ID where this was discovered (optional)"}},required:["projectPath","kind","problem"]},outputSchema:{type:"object",properties:{id:{type:"integer"},kind:{type:"string",enum:["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]},problem:{type:"string"},validated_fix:{type:["string","null"]},why_it_worked:{type:["string","null"]},confidence:{type:"number"},tags:{type:["string","null"]}},required:["id","kind","problem","validated_fix","why_it_worked","confidence","tags"]},annotations:D.wyrm_remember,aliases:[],handler:async($,{store:b,memory:x,raw:w})=>{const{projectPath:l,kind:h,problem:a,constraints:g,outcome:n,tags:f,confidence:p,sourceSessionId:v}=$,d=$,s=d.validatedFix??d.validated_fix,u=d.whyItWorked??d.why_it_worked,o=Y("kind",h,["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]);if(o===void 0)throw new J("kind","is required");const e=b.getProject(l);if(!e)return R(C("wyrm_remember","projectPath","project not found"));const i={kind:o,problem:a,constraints:g,validatedFix:s,whyItWorked:u,outcome:n,tags:f,confidence:p,sourceSessionId:v},y=await L("artifact_add",e.id,i,()=>x.add(e.id,i)),j=A(w(),{tool:"wyrm_remember",outcome:y.needs_review===1?"queued":"stored",refTable:"mem",refId:y.id,reason:y.needs_review===1?"needs_review \u2014 hidden until approved":void 0,source:y.created_by,projectId:e.id}),t={id:y.id,kind:y.kind,problem:y.problem,validated_fix:y.validated_fix??null,why_it_worked:y.why_it_worked??null,confidence:y.confidence,tags:y.tags??null,receipt:j};return S(t,(_,m)=>{let r=E(m.brand,"**Memory Stored**")+`
|
|
14
|
+
|
|
15
|
+
`;return r+=`${m.bullet} **Kind:** ${_.kind}
|
|
16
|
+
`,r+=`${m.bullet} **ID:** ${_.id}
|
|
17
|
+
`,r+=`${m.bullet} **Problem:** ${_.problem}
|
|
18
|
+
`,_.validated_fix&&(r+=`${m.bullet} **Solution:** ${_.validated_fix}
|
|
19
|
+
`),_.why_it_worked&&(r+=`${m.bullet} **Why it worked:** ${_.why_it_worked}
|
|
20
|
+
`),r+=`${m.bullet} **Confidence:** ${(_.confidence*100).toFixed(0)}%
|
|
21
|
+
`,_.tags&&(r+=`${m.bullet} **Tags:** ${_.tags}
|
|
22
|
+
`),r+="\n_Use `wyrm_recall` to retrieve similar memories, or `wyrm_context_build` to assemble a task brief._",r})}},{name:"wyrm_auto_capture",description:"Auto-extract durable memories from freeform text (a session transcript, notes, a chat) into the REVIEW QUEUE. A LOCAL extractor \u2014 a configurable Ollama model (WYRM_EXTRACT_MODEL / the `model` arg) if set, else a deterministic heuristic \u2014 pulls out truths, failures, decisions, patterns, and lessons as needs_review candidates; approve/reject with wyrm_review (nothing auto-trusted). Closes the 'just talk, it remembers' gap without a cloud LLM. Deduped + idempotent. Example: wyrm_auto_capture({ projectPath: '/home/user/api', text: 'Deploy failed twice because wrangler.toml pointed at the old KV id; switched to the new binding and decided to pin binding names in CI.' })",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project to file the extracted candidates under"},text:{type:"string",description:"Freeform text to extract durable memories from"},model:{type:"string",description:"Optional Ollama model for extraction (overrides WYRM_EXTRACT_MODEL); omit for deterministic extraction"}},required:["projectPath","text"]},outputSchema:{type:"object",properties:{method:{type:"string"},model:{type:["string","null"]},added:{type:"integer"},skipped:{type:"integer"},candidates:{type:"array",items:{type:"object",properties:{kind:{type:"string"},text:{type:"string"}},required:["kind","text"]}}},required:["method","model","added","skipped","candidates"]},annotations:D.wyrm_auto_capture,aliases:[],handler:async($,{store:b,raw:x,memory:w,cache:l})=>{const{projectPath:h,text:a,model:g}=$,n=b.getProject(h);if(!n)return R(C("wyrm_auto_capture","projectPath","project not found"));if(!a||a.trim().length<20)return R(C("wyrm_auto_capture","text","must be at least 20 characters"));const{candidates:f,method:p,model:v}=await F(a,{model:g}),d=x();let s=0,u=0;for(const e of f){const i=N(e),y=i.tags[i.tags.length-1];if(d.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(n.id,"%"+M(y)+"%")){u++,A(d,{tool:"wyrm_auto_capture",outcome:"dropped",reason:"dedup \u2014 already captured",source:"auto-extract",projectId:n.id});continue}const j=w.add(n.id,{kind:i.kind,problem:i.problem,tags:i.tags,confidence:i.confidence,needsReview:1,createdBy:"auto-extract"});A(d,{tool:"wyrm_auto_capture",outcome:"queued",refTable:"mem",refId:j.id,reason:"needs_review \u2014 auto-extracted; review to activate",source:"auto-extract",projectId:n.id}),s++}s>0&&l.invalidate();const o={method:p,model:v??null,added:s,skipped:u,receipt:{outcome:s>0?"queued":"dropped",reason:`${s} queued for review, ${u} dropped as duplicates`},candidates:f.slice(0,8).map(e=>({kind:e.kind,text:e.text.slice(0,80)}))};return S(o,(e,i)=>{const y=e.candidates.map(j=>` ${i.bullet} [${j.kind}] ${j.text}`).join(`
|
|
23
|
+
`);return E(i.brand,`Auto-capture (${e.method}${e.model?` - ${e.model}`:""}) -- ${e.added} candidate(s) -> review queue, ${e.skipped} already present.`)+`
|
|
24
|
+
${y}
|
|
25
|
+
|
|
26
|
+
Approve/reject with wyrm_review.`})}},{name:"wyrm_capture_trace",description:"Harvest a harness's working trace into run-tagged review-queue candidates \u2014 OFFLINE. Ingests a Claude Code session transcript (JSONL), a ~/.dragon/traces file/dir, or WYRM_TRACE_TOOL_CALLS event output. The SAME local extractor as auto-capture (Ollama WYRM_EXTRACT_MODEL if set, else deterministic \u2014 never a cloud LLM) pulls durable truths/failures/decisions/patterns/lessons; secrets (API keys, tokens, passwords) are REDACTED before anything is stored; candidates land needs_review=1 stamped with the run_id (arg or ambient envelope). Approve/reject with wyrm_review; deduped + idempotent. Pass `trace` (inline text) OR `path` (a trace file or the ~/.dragon/traces dir). Reached via wyrm_capture({ mode: 'trace' }).",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project to file the candidates under"},trace:{type:"string",description:"Inline trace text (JSONL transcript / dragon records / tool-call events)"},path:{type:"string",description:"Path to a trace file, or the ~/.dragon/traces directory (newest file is read); omit ~ for absolute"},format:{type:"string",enum:["auto","claude-jsonl","dragon","tool-calls"],description:"Trace format (default auto-detect)"},run_id:{type:"string",description:"Tag candidates with this run (default: ambient envelope run_id)"},model:{type:"string",description:"Optional Ollama model for extraction (overrides WYRM_EXTRACT_MODEL); omit for deterministic"}},required:["projectPath"]},outputSchema:{type:"object",properties:{method:{type:"string"},model:{type:["string","null"]},format:{type:"string"},source:{type:"string"},run_id:{type:["string","null"]},segments:{type:"integer"},added:{type:"integer"},skipped:{type:"integer"},candidates:{type:"array",items:{type:"object",properties:{kind:{type:"string"},text:{type:"string"}},required:["kind","text"]}}},required:["method","model","format","source","run_id","segments","added","skipped","candidates"]},annotations:D.wyrm_capture_trace,aliases:[],handler:async($,{store:b,raw:x,memory:w,cache:l})=>{const{projectPath:h,trace:a,path:g,format:n,run_id:f,model:p}=$,v=b.getProject(h);if(!v)return R(C("wyrm_capture_trace","projectPath","project not found"));const d=V(),s=typeof f=="string"&&f.trim()?f.trim().slice(0,64):d.run_id;let u="",o="inline";if(typeof a=="string"&&a.trim())u=a,o="inline";else if(typeof g=="string"&&g.trim()){let c=g.trim();(c==="~"||c.startsWith("~/"))&&(c=H(te(),c.slice(1)));try{if(W(c).isDirectory()){const q=ee(c).map(T=>H(c,T)).filter(T=>{try{return W(T).isFile()}catch{return!1}}).sort((T,B)=>W(B).mtimeMs-W(T).mtimeMs);if(q.length===0)return R(C("wyrm_capture_trace","path","no trace files in directory"));u=U(q[0],"utf-8"),o=q[0]}else u=U(c,"utf-8"),o=c}catch(k){return R(C("wyrm_capture_trace","path",`could not read trace path: ${k.message}`))}}else return R(C("wyrm_capture_trace","trace","provide inline trace or path to trace file"));const{segments:e,format:i}=X(u,n??"auto"),y=G(e);if(y.trim().length<20){const c={method:"deterministic",model:null,format:i,source:o,run_id:s,segments:e.length,added:0,skipped:0,candidates:[]};return S(c,(k,q)=>E(q.brand,`Trace harvest (${k.format}) -- no durable content extracted from ${k.segments} segment(s).`))}const{candidates:j,method:t,model:_}=await F(y,{model:p}),m=x();let r=0,I=0;for(const c of j){const k=N(c),q=k.tags[k.tags.length-1];if(m.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(v.id,"%"+M(q)+"%")){I++;continue}const T=s?[...k.tags,"trace",`run:${s}`]:[...k.tags,"trace"];z({agent_id:d.agent_id,run_id:s,source:s?"param":d.source},()=>w.add(v.id,{kind:k.kind,problem:k.problem,tags:T,confidence:k.confidence,needsReview:1,createdBy:"trace-harvest"})),r++}r>0&&l.invalidate();const P={method:t,model:_??null,format:i,source:o,run_id:s,segments:e.length,added:r,skipped:I,candidates:j.slice(0,8).map(c=>({kind:c.kind,text:c.text.slice(0,80)}))};return S(P,(c,k)=>{const q=c.candidates.map(T=>` ${k.bullet} [${T.kind}] ${T.text}`).join(`
|
|
27
|
+
`);return E(k.brand,`Trace harvest (${c.format}, ${c.method}${c.model?` - ${c.model}`:""}) -- ${c.segments} segment(s) -> ${c.added} candidate(s) to review queue, ${c.skipped} already present${c.run_id?` [run:${c.run_id}]`:""}.`)+(q?`
|
|
28
28
|
${q}`:"")+`
|
|
29
29
|
|
|
30
|
-
Approve/reject with wyrm_review.`})}},{name:"wyrm_distill",description:"Distill a work session into candidate memory artifacts for review. Parses the session's objectives, decisions, and outcomes into structured artifacts (lessons, patterns, anti-patterns) and queues them for approval via wyrm_review. Use at session end to extract institutional knowledge.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root path"},sessionId:{type:"string",description:"Session ID to distill"},candidates:{type:"array",description:"Pre-parsed candidate artifacts to store for review",items:{type:"object",properties:{kind:{type:"string",enum:["lesson","pattern","anti_pattern","heuristic","reasoning_trace"]},title:{type:"string"},content:{type:"string"},tags:{type:"array",items:{type:"string"}},confidence:{type:"number"}},required:["kind","title","content"]}}},required:["projectPath","candidates"]},outputSchema:{type:"object",properties:{count:{type:"integer"},artifacts:{type:"array",items:{type:"object",properties:{id:{type:"integer"},kind:{type:"string"},title:{type:"string"}},required:["id","kind","title"]}}},required:["count","artifacts"]},annotations:
|
|
30
|
+
Approve/reject with wyrm_review.`})}},{name:"wyrm_distill",description:"Distill a work session into candidate memory artifacts for review. Parses the session's objectives, decisions, and outcomes into structured artifacts (lessons, patterns, anti-patterns) and queues them for approval via wyrm_review. Use at session end to extract institutional knowledge.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root path"},sessionId:{type:"string",description:"Session ID to distill"},candidates:{type:"array",description:"Pre-parsed candidate artifacts to store for review",items:{type:"object",properties:{kind:{type:"string",enum:["lesson","pattern","anti_pattern","heuristic","reasoning_trace"]},title:{type:"string"},content:{type:"string"},tags:{type:"array",items:{type:"string"}},confidence:{type:"number"}},required:["kind","title","content"]}}},required:["projectPath","candidates"]},outputSchema:{type:"object",properties:{count:{type:"integer"},artifacts:{type:"array",items:{type:"object",properties:{id:{type:"integer"},kind:{type:"string"},title:{type:"string"}},required:["id","kind","title"]}}},required:["count","artifacts"]},annotations:D.wyrm_distill,aliases:[],handler:($,{store:b,memory:x})=>{const{projectPath:w,candidates:l}=$,h=b.getProject(w);if(!h)return{content:[{type:"text",text:`Project not found: ${w}`}],isError:!0};if(!l||l.length===0)return{content:[{type:"text",text:`**Distill**
|
|
31
31
|
|
|
32
|
-
No candidates provided. Provide an array of candidate artifacts to distill.`}],isError:!0};const a=[];for(const
|
|
32
|
+
No candidates provided. Provide an array of candidate artifacts to distill.`}],isError:!0};const a=[];for(const n of l){const f=x.add(h.id,{kind:n.kind,problem:n.title,validatedFix:n.content,tags:n.tags??[],confidence:n.confidence??.7,needsReview:1});a.push({id:f.id,kind:n.kind,title:n.title})}const g={count:a.length,artifacts:a};return S(g,(n,f)=>{let p=E(f.brand,`**Distillation Complete** -- ${n.count} artifact${n.count!==1?"s":""} queued for review`)+`
|
|
33
33
|
|
|
34
|
-
`;return
|
|
35
|
-
`),
|
|
36
|
-
Indexed ${
|
|
37
|
-
`),
|
|
38
|
-
`);return E(
|
|
39
|
-
${
|
|
34
|
+
`;return p+=n.artifacts.map(v=>`${f.bullet} [#${v.id}] **${v.kind}**: ${v.title}`).join(`
|
|
35
|
+
`),p+="\n\nUse `wyrm_review` with each ID to approve or reject.",p})}},{name:"wyrm_harvest",description:"Auto-populate memory from artifacts you already produce. Walks a project (or ALL registered projects) and harvests durable facts from its docs (README/CLAUDE/AGENTS/ARCHITECTURE) plus recent commit subjects (git log) into the REVIEW QUEUE \u2014 approve/reject with wyrm_review, nothing is auto-trusted. Idempotent (re-runs skip what's already harvested). Use dryRun to preview. The fix for a thin corpus.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Harvest one project; omit to harvest ALL registered projects"},dryRun:{type:"boolean",description:"Preview what would be harvested without writing anything"},gitLimit:{type:"number",description:"How many recent commits to scan per project (default 30, max 200)"},includeCode:{type:"boolean",description:"Also harvest CODE: tech-stack facts from manifests (package.json/Cargo.toml/\u2026) + TODO/FIXME markers into the review queue, AND index code symbols (functions/classes/types) for search. Heavier \u2014 scope to one project for the full code pass."}}},outputSchema:{type:"object",properties:{dry_run:{type:"boolean"},projects_scanned:{type:"integer"},added:{type:"integer"},skipped:{type:"integer"},top:{type:"array",items:{type:"object",properties:{project:{type:"string"},added:{type:"integer"},skipped:{type:"integer"}},required:["project","added","skipped"]}},sample:{type:"array",items:{type:"string"}},code_symbols:{type:["object","null"],properties:{symbols:{type:"integer"},projects:{type:"integer"},files:{type:"integer"}},required:["symbols","projects","files"]}},required:["dry_run","projects_scanned","added","skipped","top","sample","code_symbols"]},annotations:D.wyrm_harvest,aliases:[],handler:($,{store:b,raw:x,memory:w,symbols:l,cache:h})=>{const{projectPath:a,dryRun:g,gitLimit:n,includeCode:f}=$,p=x(),v={existsBySig:(t,_)=>!!p.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(t,"%"+M(_)+"%"),addCandidate:(t,_)=>{const m=w.add(t,{kind:_.kind,problem:_.text,tags:[..._.tags,_.sig],confidence:_.confidence,needsReview:1,createdBy:"harvest"});A(p,{tool:"wyrm_harvest",outcome:"queued",refTable:"mem",refId:m.id,reason:"needs_review \u2014 harvested; review to activate",source:"harvest",projectId:t})},onSkip:t=>{A(p,{tool:"wyrm_harvest",outcome:"dropped",reason:"dedup \u2014 signature already harvested",source:"harvest",projectId:t})}};let d;if(a){const t=b.getProject(a);if(!t)return{content:[{type:"text",text:"Project not found"}],isError:!0};d=[{id:t.id,name:t.name,path:t.path}]}else d=b.getAllProjects(500).map(t=>({id:t.id,name:t.name,path:t.path}));const{reports:s,totalAdded:u,totalSkipped:o}=Z(v,d,{dryRun:g,gitLimit:n,includeCode:f});!g&&u>0&&h.invalidate();let e=null;if(f&&!g){let t=0,_=0,m=0;for(const r of d)try{const I=l.indexProject(r.id,r.path);t+=I.files,_+=I.symbols,m++}catch{}e={symbols:_,projects:m,files:t}}const i=s.filter(t=>t.added>0).sort((t,_)=>_.added-t.added).slice(0,15).map(t=>({project:t.project,added:t.added,skipped:t.skipped})),y=s.flatMap(t=>t.sample??[]).slice(0,6),j={dry_run:!!g,projects_scanned:d.length,added:u,skipped:o,top:i,sample:y,code_symbols:e};return S(j,(t,_)=>{const m=t.code_symbols?`
|
|
36
|
+
Indexed ${t.code_symbols.symbols} code symbols across ${t.code_symbols.projects} project(s) (${t.code_symbols.files} files) -> searchable via wyrm_symbol_search.`:"",r=t.top.map(P=>` +${String(P.added).padStart(3)} (skip ${P.skipped}) ${P.project}`).join(`
|
|
37
|
+
`),I=t.sample.map(P=>` ${_.bullet} ${P}`).join(`
|
|
38
|
+
`);return E(_.brand,`Harvest ${t.dry_run?"(dry run) ":""}-- ${t.added} candidate(s) -> review queue across ${t.projects_scanned} project(s); ${t.skipped} already present.`)+`${m}
|
|
39
|
+
${r}`+(I?`
|
|
40
40
|
|
|
41
41
|
Sample:
|
|
42
|
-
${
|
|
42
|
+
${I}`:"")+`
|
|
43
43
|
|
|
44
|
-
Approve/reject with wyrm_review.`})}},{name:"wyrm_import_git",description:"Import a list of commits into the Wyrm memory review queue. Useful for onboarding a project's history or capturing recent work.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},commits:{type:"array",description:"Array of commit objects",items:{type:"object",properties:{message:{type:"string"},diff_summary:{type:"string"},author:{type:"string"},date:{type:"string"}},required:["message"]}},auto_approve:{type:"boolean",description:"Skip review queue and activate immediately (default: false)"}},required:["project_id","commits"]},outputSchema:{type:"object",properties:{captured:{type:"integer"},skipped:{type:"integer"},auto_approved:{type:"boolean"}},required:["captured","skipped","auto_approved"]},annotations:
|
|
45
|
-
${
|
|
44
|
+
Approve/reject with wyrm_review.`})}},{name:"wyrm_import_git",description:"Import a list of commits into the Wyrm memory review queue. Useful for onboarding a project's history or capturing recent work.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},commits:{type:"array",description:"Array of commit objects",items:{type:"object",properties:{message:{type:"string"},diff_summary:{type:"string"},author:{type:"string"},date:{type:"string"}},required:["message"]}},auto_approve:{type:"boolean",description:"Skip review queue and activate immediately (default: false)"}},required:["project_id","commits"]},outputSchema:{type:"object",properties:{captured:{type:"integer"},skipped:{type:"integer"},auto_approved:{type:"boolean"}},required:["captured","skipped","auto_approved"]},annotations:D.wyrm_import_git,aliases:[],handler:($,{store:b,memory:x,raw:w})=>{const{project_id:l,commits:h,auto_approve:a}=$;if(!b.getProjectById(l))return{content:[{type:"text",text:`Project ID ${l} not found.`}],isError:!0};let n=0,f=0;const p=w();for(const d of h){const s=d.message??"";if(/^Merge /i.test(s)){f++;continue}if(/^(chore|bump|release|version)/i.test(s)){f++;continue}const u="gi:"+O("sha1").update(`${s}
|
|
45
|
+
${d.diff_summary??""}`).digest("hex").slice(0,16);if(p.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(l,"%"+M(u)+"%")){f++,A(p,{tool:"wyrm_import_git",outcome:"dropped",reason:"dedup \u2014 this commit was already imported (gi: signature match)",source:"import:git",projectId:l});continue}let o="pattern";/^fix(\(.+\))?:/i.test(s)?o="lesson":/^feat(\(.+\))?:/i.test(s)?o="pattern":/^refactor(\(.+\))?:/i.test(s)&&(o="heuristic");const e=s.split(":")[0]??"commit",i=x.add(l,{kind:o,problem:s,validatedFix:d.diff_summary??"",whyItWorked:`Committed by ${d.author??"unknown"} on ${d.date??"unknown"}`,tags:["git","commit",e.toLowerCase(),u],confidence:.6,needsReview:a?0:1});A(p,{tool:"wyrm_import_git",outcome:a?"stored":"queued",refTable:"mem",refId:i.id,reason:a?void 0:"needs_review \u2014 imported; review to activate",source:"import:git",projectId:l}),n++}return S({captured:n,skipped:f,auto_approved:!!a},(d,s)=>E(s.brand,"**Git Import Complete**")+`
|
|
46
46
|
|
|
47
|
-
${
|
|
48
|
-
${
|
|
49
|
-
${
|
|
47
|
+
${s.bullet} **Captured:** ${d.captured}
|
|
48
|
+
${s.bullet} **Skipped:** ${d.skipped} (merges/chores)
|
|
49
|
+
${s.bullet} **Review needed:** ${d.auto_approved?"No (auto-approved)":`Yes -- run \`wyrm_review\` to activate ${d.captured} artifact${d.captured!==1?"s":""}`}`)}},{name:"wyrm_import_pr",description:"Import a pull request (title, body, review comments) into the Wyrm memory review queue to extract patterns and heuristics.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},title:{type:"string",description:"PR title"},body:{type:"string",description:"PR description / body"},review_comments:{type:"array",items:{type:"string"},description:"Review comment strings"},auto_approve:{type:"boolean",description:"Skip review queue (default: false)"}},required:["project_id","title","body"]},outputSchema:{type:"object",properties:{created:{type:"integer"},auto_approved:{type:"boolean"}},required:["created","auto_approved"]},annotations:D.wyrm_import_pr,aliases:[],handler:($,{store:b,memory:x,raw:w})=>{const{project_id:l,title:h,body:a,review_comments:g,auto_approve:n}=$;if(!b.getProjectById(l))return{content:[{type:"text",text:`Project ID ${l} not found.`}],isError:!0};let p=0,v=0;const d=n?0:1,s=w(),u=(e,i,y)=>{const j="pr:"+O("sha1").update(i).digest("hex").slice(0,16);if(s.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(l,"%"+M(j)+"%")){v++,A(s,{tool:"wyrm_import_pr",outcome:"dropped",reason:"dedup \u2014 already imported (pr: signature)",source:"import:pr",projectId:l});return}const t=x.add(l,{kind:e,problem:i,validatedFix:"",whyItWorked:"",tags:[...y,j],confidence:.65,needsReview:d,createdBy:"import:pr"});A(s,{tool:"wyrm_import_pr",outcome:n?"stored":"queued",refTable:"mem",refId:t.id,reason:n?void 0:"needs_review \u2014 imported; review to activate",source:"import:pr",projectId:l}),p++};u("pattern",`${h}
|
|
50
50
|
|
|
51
|
-
${
|
|
51
|
+
${a}`,["git","pr"]);for(const e of g??[])/\b(should|must|always|never|prefer|avoid|use|don't)\b/i.test(e)&&u("heuristic",e,["git","pr","review"]);return S({created:p,skipped:v,auto_approved:!!n},(e,i)=>E(i.brand,"**PR Import Complete**")+`
|
|
52
52
|
|
|
53
|
-
${
|
|
54
|
-
${
|
|
53
|
+
${i.bullet} **Artifacts created:** ${e.created}
|
|
54
|
+
${i.bullet} **Review needed:** ${e.auto_approved?"No (auto-approved)":"Yes -- run `wyrm_review` to activate"}`)}},{name:"wyrm_import_rules",description:"Import a .cursorrules / copilot-instructions file into Wyrm. Parses by section and creates ground truths (for constraint/rule language) or memory artifacts (for general guidelines).",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},content:{type:"string",description:"Full text of the rules file"},format:{type:"string",enum:["cursorrules","copilot","plain"],description:"Source format (default: plain)"},source_file:{type:"string",description:"Filename for provenance (optional)"}},required:["project_id","content"]},outputSchema:{type:"object",properties:{format:{type:"string"},source:{type:"string"},truths_created:{type:"integer"},artifacts_created:{type:"integer"}},required:["format","source","truths_created","artifacts_created"]},annotations:D.wyrm_import_rules,aliases:[],handler:async($,{store:b,memory:x,truths:w,raw:l})=>{const{project_id:h,content:a,format:g,source_file:n}=$;if(!b.getProjectById(h))return{content:[{type:"text",text:`Project ID ${h} not found.`}],isError:!0};const p=g??"plain",v=n??"rules",d=["imported",p,v],s=a.split(/\n(?=#)/),u=a.split(/\n\n+/),o=(s.length>=u.length?s:u).map(m=>m.trim()).filter(m=>m.length>=15);let e=0,i=0,y=0;const{isConfigShapedTruth:j}=await import("../metabolize.js"),t=l();for(const m of o){const r=m.slice(0,50).replace(/\n/g," ");if(/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(m)&&!j(r,m)){const I=w.set(h,{category:"constraint",key:r,value:m,source:v});A(t,{tool:"wyrm_import_rules",outcome:"stored",refTable:"truth",refId:I.id,source:"import:rules",projectId:h}),e++}else{const I=x.add(h,{kind:"heuristic",problem:m,validatedFix:"",whyItWorked:"",tags:d,confidence:.7,needsReview:1,createdBy:"import:rules"});j(r,m)&&y++,A(t,{tool:"wyrm_import_rules",outcome:"queued",refTable:"mem",refId:I.id,reason:j(r,m)?"truth-shape lint \u2014 config shape routed to review":"needs_review \u2014 imported; review to activate",source:"import:rules",projectId:h}),i++}}return S({format:p,source:v,truths_created:e,artifacts_created:i,linted:y},(m,r)=>E(r.brand,`**Rules Import Complete** (${m.format})`)+`
|
|
55
55
|
|
|
56
|
-
${
|
|
57
|
-
${
|
|
58
|
-
${
|
|
56
|
+
${r.bullet} **Ground truths created:** ${m.truths_created} (active immediately)
|
|
57
|
+
${r.bullet} **Memory artifacts created:** ${m.artifacts_created} (pending review)
|
|
58
|
+
${r.bullet} **Source:** ${m.source}
|
|
59
59
|
|
|
60
|
-
Run \`wyrm_review\` to approve the memory artifacts.`)}},{name:"wyrm_spec_register",description:"Make spec-kit Wyrm-native. Reads a spec directory (spec.md title/summary + tasks.md task list) and creates one Wyrm quest per task, linked to a project, with a stored spec\u2192project link. Idempotent \u2014 re-running updates the same quests (deduped by a per-spec-task signature) instead of duplicating.",inputSchema:{type:"object",properties:{specDir:{type:"string",description:"Absolute path to the spec directory (e.g. '.../dragon-platform/specs/001-ghostmesh')"},projectPath:{type:"string",description:"Path of the Wyrm project to attach the spec + quests to (must already be registered)"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Priority for the generated quests (default 'medium')"}},required:["specDir","projectPath"]},outputSchema:{type:"object",properties:{spec_dir:{type:"string"},title:{type:["string","null"]},project:{type:"string"},tasks_parsed:{type:"integer"},quests_created:{type:"integer"},quests_updated:{type:"integer"},quest_ids:{type:"array",items:{type:"integer"}}},required:["spec_dir","title","project","tasks_parsed","quests_created","quests_updated","quest_ids"]},annotations:
|
|
60
|
+
Run \`wyrm_review\` to approve the memory artifacts.`)}},{name:"wyrm_spec_register",description:"Make spec-kit Wyrm-native. Reads a spec directory (spec.md title/summary + tasks.md task list) and creates one Wyrm quest per task, linked to a project, with a stored spec\u2192project link. Idempotent \u2014 re-running updates the same quests (deduped by a per-spec-task signature) instead of duplicating.",inputSchema:{type:"object",properties:{specDir:{type:"string",description:"Absolute path to the spec directory (e.g. '.../dragon-platform/specs/001-ghostmesh')"},projectPath:{type:"string",description:"Path of the Wyrm project to attach the spec + quests to (must already be registered)"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Priority for the generated quests (default 'medium')"}},required:["specDir","projectPath"]},outputSchema:{type:"object",properties:{spec_dir:{type:"string"},title:{type:["string","null"]},project:{type:"string"},tasks_parsed:{type:"integer"},quests_created:{type:"integer"},quests_updated:{type:"integer"},quest_ids:{type:"array",items:{type:"integer"}}},required:["spec_dir","title","project","tasks_parsed","quests_created","quests_updated","quest_ids"]},annotations:D.wyrm_spec_register,aliases:[],handler:($,{store:b,indexing:x})=>{const{specDir:w,projectPath:l,priority:h}=$,a=["specDir","projectPath"].filter(o=>{const e=$[o];return!e&&e!==0&&e!==!1});if(a.length>0)return{content:[{type:"text",text:`Missing required arguments: ${a.join(", ")}`}],isError:!0};const g=b.getProject(l);if(!g)return{content:[{type:"text",text:`**Spec Register**: Project not found at "${l}". Register it first (wyrm_scan_projects / wyrm_session_start).`}],isError:!0};const n=re(w);if(n.tasks.length===0){const o={spec_dir:w,title:n.title??null,project:g.name,tasks_parsed:0,quests_created:0,quests_updated:0,quest_ids:[]};return S(o,(e,i)=>E(i.brand,`**Spec Register**: No tasks found in ${K(e.spec_dir,"tasks.md")}. Nothing to create.`))}const f=h||"medium";let p=0,v=0;const d=[];for(const o of n.tasks){const e=ie(w,o.id),i=`${o.id}: ${o.title}`,y=e,j=b.findQuestBySpecSignature(g.id,e);if(j)b.updateQuestFields(j.id,{title:i,tags:y}),d.push(j.id),v++;else{const t=b.addQuest(g.id,i,`spec-kit task from ${w}`,f,y);x()?.enqueue("quest",t.id,g.id),d.push(t.id),p++}}const s=b.upsertSpec(g.id,w,n.title,n.summary,n.tasks.length),u={spec_dir:s.spec_dir,title:s.title??null,project:g.name,tasks_parsed:n.tasks.length,quests_created:p,quests_updated:v,quest_ids:d};return S(u,(o,e)=>{let i=E(e.brand,"**Spec Registered**")+`
|
|
61
61
|
|
|
62
|
-
`;return
|
|
63
|
-
`,
|
|
64
|
-
`),
|
|
65
|
-
`,
|
|
66
|
-
`,
|
|
67
|
-
`,
|
|
68
|
-
`,
|
|
62
|
+
`;return i+=`Spec: ${o.title||"(untitled)"}
|
|
63
|
+
`,s.summary&&(i+=`Summary: ${s.summary}
|
|
64
|
+
`),i+=`Dir: ${o.spec_dir}
|
|
65
|
+
`,i+=`Project: ${o.project}
|
|
66
|
+
`,i+=`Tasks parsed: ${o.tasks_parsed}
|
|
67
|
+
`,i+=`Quests created: ${o.quests_created} - updated: ${o.quests_updated}
|
|
68
|
+
`,i+=`
|
|
69
69
|
\`\`\`json
|
|
70
|
-
${JSON.stringify({spec:
|
|
71
|
-
\`\`\``,
|
|
70
|
+
${JSON.stringify({spec:o.spec_dir,title:o.title,project:o.project,tasksParsed:o.tasks_parsed,questsCreated:o.quests_created,questsUpdated:o.quests_updated,questIds:o.quest_ids},null,2)}
|
|
71
|
+
\`\`\``,i})}},{name:"wyrm_scaffold_save",description:"Save a reasoning scaffold \u2014 a structured checklist that guides step-by-step thinking for a specific problem type. Scaffolds are automatically surfaced by wyrm_context_build when the task matches, helping AI models apply proven reasoning patterns.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project path (optional, null for global scaffolds)"},problemType:{type:"string",description:"Short slug for the problem type (e.g. 'api-design', 'security-review', 'db-migration')"},description:{type:"string",description:"What kind of task this scaffold helps with"},whenToUse:{type:"string",description:"Conditions that indicate this scaffold should be applied"},steps:{type:"array",items:{type:"string"},description:"Ordered checklist steps to follow"},verificationSteps:{type:"array",items:{type:"string"},description:"Steps to verify the work is correct"},doNotApplyIf:{type:"string",description:"Conditions where this scaffold does NOT apply"},tags:{type:"array",items:{type:"string"},description:"Searchable tags"}},required:["problemType","description","whenToUse","steps"]},outputSchema:{type:"object",properties:{id:{type:"integer"},problem_type:{type:"string"},description:{type:"string"},steps:{type:"integer"}},required:["id","problem_type","description","steps"]},annotations:D.wyrm_scaffold_save,aliases:[],handler:($,{store:b,scaffolds:x,cache:w})=>{const{projectPath:l,problemType:h,description:a,whenToUse:g,steps:n,verificationSteps:f,doNotApplyIf:p,tags:v}=$,d=l?b.getProject(l)?.id??void 0:void 0,s=x.save({projectId:d,problemType:h,description:a,whenToUse:g,steps:n,verificationSteps:f??void 0,doNotApplyIf:p?[p]:void 0,tags:v??[]});w.invalidate("wyrm_scaffold_get"),w.invalidate("wyrm_context_build");const u={id:s.id,problem_type:h,description:a,steps:n.length};return S(u,(o,e)=>E(e.brand,"**Reasoning Scaffold Saved**")+`
|
|
72
72
|
|
|
73
|
-
${e.bullet} **Problem Type:** ${
|
|
74
|
-
${e.bullet} **Description:** ${
|
|
75
|
-
${e.bullet} **Steps:** ${
|
|
76
|
-
${e.bullet} **ID:** ${
|
|
73
|
+
${e.bullet} **Problem Type:** ${o.problem_type}
|
|
74
|
+
${e.bullet} **Description:** ${o.description}
|
|
75
|
+
${e.bullet} **Steps:** ${o.steps} checklist items
|
|
76
|
+
${e.bullet} **ID:** ${o.id}
|
|
77
77
|
|
|
78
|
-
This scaffold will be surfaced by \`wyrm_context_build\` when tasks match "${
|
|
78
|
+
This scaffold will be surfaced by \`wyrm_context_build\` when tasks match "${o.problem_type}".`)}}];export{ve as captureToolSpecs};
|
package/dist/harvest.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{execFileSync as m}from"child_process";import{readFileSync as h,existsSync as g}from"fs";import{join as
|
|
2
|
-
`).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#")&&!a.startsWith("|")&&!a.startsWith("```")).slice(0,3).join(" ").replace(d,"").replace(/\s+/g," ");if(!r||
|
|
3
|
-
`)){const t=
|
|
4
|
-
`).map(i=>i.trim()).filter(Boolean).slice(0,6).join(" ").replace(/\s+/g," ").slice(0,400);t&&
|
|
5
|
-
`)){if(t>=25)break;const d=i.trim();if(!d)continue;const r=d.match(/^([^:]+):(\d+):(.*)$/);if(!r)continue;const
|
|
1
|
+
import{execFileSync as m}from"child_process";import{readFileSync as h,existsSync as g}from"fs";import{join as u}from"path";import{createHash as x}from"crypto";const $=["README.md","CLAUDE.md","AGENTS.md","ARCHITECTURE.md"],k=40,p=o=>x("sha1").update(o).digest("hex").slice(0,8);function y(o){const n=[];for(const c of $){const e=u(o,c);if(!g(e))continue;let s;try{s=h(e,"utf-8")}catch{continue}for(const t of s.split(/\n(?=#{1,4}\s)/)){const i=t.match(/^#{1,4}\s+(.+)/);if(!i)continue;const d=/[\x00-\x1f\x7f]/g,r=i[1].replace(/[#*`]/g,"").replace(d,"").trim(),f=t.slice(i[0].length).split(`
|
|
2
|
+
`).map(a=>a.trim()).filter(a=>a&&!a.startsWith("#")&&!a.startsWith("|")&&!a.startsWith("```")).slice(0,3).join(" ").replace(d,"").replace(/\s+/g," ");if(!r||f.length<24)continue;const l=`${r}: ${f}`.slice(0,600);if(n.push({kind:"lesson",text:l,source:`doc:${c}`,sig:`doc:${c}:${p(l)}`,tags:["harvest","doc",c],confidence:.6}),n.length>=k)return n}}return n}const S=/^(merge|wip|typo|fixup|squash|amend|\.+|chore: lint|format)\b/i;function C(o,n=30){if(!g(u(o,".git")))return[];let c;try{c=m("git",["-C",o,"log",`-n${Math.max(1,Math.min(n,200))}`,"--no-merges","--pretty=%h%x09%s"],{encoding:"utf-8",timeout:5e3})}catch{return[]}const e=[];for(const s of c.split(`
|
|
3
|
+
`)){const t=s.trim();if(!t)continue;const i=t.indexOf(" ");if(i<0)continue;const d=t.slice(0,i),r=t.slice(i+1).trim();r.length<8||S.test(r)||e.push({kind:"pattern",text:r.slice(0,300),source:"git",sig:`git:${d}`,tags:["harvest","git",`sha:${d}`],confidence:.45})}return e}function v(o){const n=[],c=u(o,"package.json");if(g(c))try{const e=JSON.parse(h(c,"utf-8")),s=Object.keys({...e.dependencies,...e.devDependencies}).slice(0,16),t=Object.keys(e.scripts??{}).slice(0,10);if(s.length||t.length){const i=`Stack (package.json): ${s.join(", ")||"\u2014"}${t.length?` \xB7 scripts: ${t.join(", ")}`:""}`.slice(0,600);n.push({kind:"lesson",text:i,source:"code:package.json",sig:`code:pkg:${p(i)}`,tags:["harvest","code","stack"],confidence:.6})}}catch{}for(const e of["Cargo.toml","composer.json","requirements.txt","pyproject.toml","go.mod","wrangler.toml"]){const s=u(o,e);if(g(s))try{const t=h(s,"utf-8").split(`
|
|
4
|
+
`).map(i=>i.trim()).filter(Boolean).slice(0,6).join(" ").replace(/\s+/g," ").slice(0,400);t&&n.push({kind:"lesson",text:`Stack (${e}): ${t}`,source:`code:${e}`,sig:`code:${e}:${p(t)}`,tags:["harvest","code","stack"],confidence:.55})}catch{}}if(g(u(o,".git")))try{const e=m("git",["-C",o,"grep","-nIE","\\b(TODO|FIXME|HACK|XXX)\\b","--","*.ts","*.tsx","*.js","*.py","*.rs","*.go","*.php","*.rb"],{encoding:"utf-8",timeout:6e3,maxBuffer:4194304}),s=/[\x00-\x1f\x7f]/g;let t=0;for(const i of e.split(`
|
|
5
|
+
`)){if(t>=25)break;const d=i.trim();if(!d)continue;const r=d.match(/^([^:]+):(\d+):(.*)$/);if(!r)continue;const f=r[3].trim().replace(s,"").slice(0,200);if(f.length<8)continue;const l=`${r[1]}:${r[2]} \u2014 ${f}`;n.push({kind:"anti_pattern",text:l,source:"code:todo",sig:`code:todo:${r[1]}:${r[2]}:${p(f)}`,tags:["harvest","code","todo"],confidence:.4}),t++}}catch{}return n}function b(o,n,c={}){const e=y(n.path),s=C(n.path,c.gitLimit??30),t=c.includeCode?v(n.path):[],i=[...e,...s,...t];let d=0,r=0;const f=[],l=new Set;for(const a of i){if(l.has(a.sig)||o.existsBySig(n.id,a.sig)){r++,c.dryRun||o.onSkip?.(n.id,a);continue}l.add(a.sig),c.dryRun||o.addCandidate(n.id,a),d++,f.length<5&&f.push(`[${a.source}] ${a.text.slice(0,80)}`)}return{project:n.name,docFacts:e.length,commits:s.length,codeSignals:t.length,added:d,skipped:r,sample:f}}function j(o,n,c={}){const e=n.map(s=>b(o,s,c));return{reports:e,totalAdded:e.reduce((s,t)=>s+t.added,0),totalSkipped:e.reduce((s,t)=>s+t.skipped,0)}}export{v as harvestCodeSignals,y as harvestDocFacts,C as harvestGitCommits,b as harvestProject,j as harvestProjects};
|
package/dist/memory-artifacts.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import{emitEvent as
|
|
1
|
+
import{emitEvent as ee}from"./events.js";import{sanitizeFtsQuery as B,buildFtsMatchQuery as P}from"./security.js";import{getActor as te}from"./handlers/boundary.js";import{buildPage as ne,DEFAULT_PAGE_SIZE as se}from"./keyset.js";import{rerankConfigured as ie,rerankCandidates as re}from"./rerank.js";import{autoSummaryPenalty as K,recallRecencyWeight as Y,recallRecencyHalfLifeDays as j,recencyMultiplier as V,extractTemporalWindow as z,recallTemporalWeight as G,temporalMultiplier as X,recallUsefulnessWeight as J,usefulnessMultiplier as Q,looksInjectionShaped as ae,trustMarker as ce}from"./context-ranking.js";const Z=40,oe=10,de=.3;class Ee{db;vectorStore;setVectorStore(t){this.vectorStore=t}getVectorStore(){return this.vectorStore}constructor(t){this.db=t}indexArtifact(t){if(!this.vectorStore)return;const e=`${t.problem}${t.validated_fix?" "+t.validated_fix:""}`.slice(0,2e3);this.vectorStore.addVector(e,"artifact",t.id,t.project_id).catch(()=>{})}add(t,e){if(typeof e.problem!="string"||!e.problem.trim())throw new Error("memory.add: 'problem' is required (a non-empty string).");const n=e.tags?.length?e.tags.join(","):null,i=te(),r=e.createdBy??"local",a=e.sourceTrust??(r.startsWith("bridge:")?"operator":r.startsWith("import:")||(n??"").includes("imported_from:")?"imported":"agent"),c=this.db.prepare(`
|
|
2
2
|
INSERT INTO memory_artifacts
|
|
3
3
|
(project_id, kind, problem, constraints, validated_fix, why_it_worked,
|
|
4
|
-
outcome, source_session_id, tags, confidence, needs_review, created_by, agent_id, run_id)
|
|
5
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
6
|
-
`).run(t,e.kind,e.problem.trim(),e.constraints?.trim()??null,e.validatedFix?.trim()??null,e.whyItWorked?.trim()??null,e.outcome??"neutral",e.sourceSessionId??null,n,e.confidence??1,e.needsReview??0,
|
|
4
|
+
outcome, source_session_id, tags, confidence, needs_review, created_by, agent_id, run_id, source_trust)
|
|
5
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
6
|
+
`).run(t,e.kind,e.problem.trim(),e.constraints?.trim()??null,e.validatedFix?.trim()??null,e.whyItWorked?.trim()??null,e.outcome??"neutral",e.sourceSessionId??null,n,e.confidence??1,e.needsReview??0,r,i.agent_id,i.run_id,a),s=this.get(c.lastInsertRowid);return e.needsReview||(ee(this.db,{projectId:t,kind:"capture",refTable:"memory_artifacts",refId:s.id,isShared:!!s.is_shared}),this.indexArtifact(s)),s}get(t){return this.db.prepare("SELECT * FROM memory_artifacts WHERE id = ?").get(t)??null}update(t,e){return this.db.prepare(`
|
|
7
7
|
UPDATE memory_artifacts SET
|
|
8
8
|
confidence = COALESCE(?, confidence),
|
|
9
9
|
validated_fix = COALESCE(?, validated_fix),
|
|
@@ -22,17 +22,17 @@ import{emitEvent as V}from"./events.js";import{sanitizeFtsQuery as $,buildFtsMat
|
|
|
22
22
|
END,
|
|
23
23
|
updated_at = datetime('now')
|
|
24
24
|
WHERE id = ?
|
|
25
|
-
`).run(e?1:0,t)}recall(t,e,n={}){const i=n.limit??10,r=n.minConfidence??0,
|
|
25
|
+
`).run(e?1:0,t)}recall(t,e,n={}){const i=n.limit??10,r=n.minConfidence??0,a=this.searchByFts(t,e,Z,n.kind,r),c=this.searchByTags(t,e,Z,n.kind,r),s=new Set,h=[];a.forEach((o,l)=>{s.add(o.id),h.push({artifact:o,inFts:!0,inTag:!1,ftsRank:l})});for(const o of c)if(!s.has(o.id))s.add(o.id),h.push({artifact:o,inFts:!1,inTag:!0});else{const l=h.find(v=>v.artifact.id===o.id);l&&(l.inTag=!0)}return h.filter(({artifact:o})=>o.confidence>=r).map(({artifact:o,inFts:l,inTag:v,ftsRank:g})=>{let A;if(l){const u=1-(g??0)/(a.length+1);A=(v?.7:.55)+.45*u}else A=.4;A*=o.confidence,o.outcome==="positive"&&(A*=1.1);const M=(Date.now()-new Date(o.last_validated_at).getTime())/(1e3*60*60*24),C=Math.max(.5,1-M/180);return A*=C,{artifact:o,relevance_score:Math.min(1,A),match_type:l&&v?"both":l?"fts":"tag"}}).sort((o,l)=>l.relevance_score-o.relevance_score).slice(0,i)}async recallHybrid(t,e,n={}){const i=n.limit??10,r=n.minConfidence??0,a=n.rerank===!0&&ie(),c=Math.min(Math.max(i*2,20),50),s=a?c:i;if(!this.vectorStore)return this.recall(t,e,n);const h=Math.max(50,s*5),_=Date.now(),o=this.searchByFts(t,e,h,n.kind,r),l=Date.now()-_,v=Date.now();let g=[];try{g=(await this.vectorStore.search(e,h,t,["artifact"])).map(p=>({id:p.content_id,s:p.similarity}))}catch{}const A=Date.now()-v;if(g.length===0)return this.recall(t,e,n);const M=Date.now(),C=60,u=Number(process.env.WYRM_RERANK_ALPHA),E=Number.isFinite(u)?Math.max(0,Math.min(1,u)):.7,R=new Map;if(process.env.WYRM_RERANK_FUSION==="rrf")o.forEach((f,p)=>R.set(f.id,(R.get(f.id)??0)+1/(C+p+1))),g.forEach((f,p)=>R.set(f.id,(R.get(f.id)??0)+1/(C+p+1)));else{const f=o.length+1;o.forEach((L,q)=>R.set(L.id,(R.get(L.id)??0)+(1-E)*(1-q/f)));const p=g.map(L=>L.s),y=Math.min(...p),F=Math.max(...p),T=F-y;g.forEach(L=>R.set(L.id,(R.get(L.id)??0)+E*(T>1e-9?(L.s-y)/T:1)))}const O=new Set(o.map(f=>f.id)),N=new Set(g.map(f=>f.id)),$=new Map(o.map(f=>[f.id,f])),w=[...R.entries()].sort((f,p)=>p[1]-f[1]),H=Y(),W=j(),d=G(),m=d>0?z(e):null,S=J(),k=new Date,b=Math.min(w.length,Math.max(s*4,50)),D=[];for(const[f,p]of w.slice(0,b)){const y=$.get(f)??this.get(f)??void 0;if(!y||y.confidence<r||y.needs_review===1||y.supersedes_id!=null||n.kind&&y.kind!==n.kind)continue;const F=y.updated_at??y.created_at;let T=p*V(F,H,W,k);m&&(T*=X(y.created_at,m,d,k)),T*=Q(y.reuse_count,y.reuse_success_count,S),D.push({id:f,s:T,art:y})}D.sort((f,p)=>p.s-f.s);const x=D[0]?.s??1,I=[];for(const{id:f,s:p,art:y}of D){if(I.length>=s)break;const F=O.has(f)&&N.has(f)?"hybrid":N.has(f)?"vector":"fts";I.push({artifact:y,relevance_score:Math.min(1,p/x),match_type:F})}const U=Date.now()-M;if(a&&I.length>0){const f=Date.now(),p=await this.rerankResults(e,I);return n.onStats?.({ftsMs:l,vectorMs:A,fusionMs:U,rerankMs:Date.now()-f,candidates:I.length}),p.slice(0,i)}return n.onStats?.({ftsMs:l,vectorMs:A,fusionMs:U,candidates:I.length}),I}async rerankResults(t,e){const n=e.map(s=>({id:s.artifact.id,text:`${s.artifact.problem}${s.artifact.validated_fix?" "+s.artifact.validated_fix:""}`.slice(0,2e3)})),i=await re(t,n);if(!i)return e;const r=new Map(e.map(s=>[s.artifact.id,s])),a=[],c=i.length;return i.forEach((s,h)=>{const _=r.get(s.id);_&&a.push({..._,relevance_score:c>0?(c-h)/c:_.relevance_score})}),a}async recallHybridGlobal(t,e={}){const n=e.limit??10,i=e.minConfidence??0,r=Math.max(50,n*5),a=this.searchByFtsGlobal(t,r,e.kind,i),c=()=>a.slice(0,n).map((d,m)=>({artifact:d,relevance_score:1-m/(a.length+1),match_type:"fts"}));if(!this.vectorStore)return c();let s=[];try{s=(await this.vectorStore.search(t,r,void 0,["artifact"])).map(m=>({id:m.content_id,s:m.similarity}))}catch{}if(s.length===0)return c();const h=60,_=Number(process.env.WYRM_RERANK_ALPHA),o=Number.isFinite(_)?Math.max(0,Math.min(1,_)):.7,l=new Map;if(process.env.WYRM_RERANK_FUSION==="rrf")a.forEach((d,m)=>l.set(d.id,(l.get(d.id)??0)+1/(h+m+1))),s.forEach((d,m)=>l.set(d.id,(l.get(d.id)??0)+1/(h+m+1)));else{const d=a.length+1;a.forEach((D,x)=>l.set(D.id,(l.get(D.id)??0)+(1-o)*(1-x/d)));const m=s.map(D=>D.s),S=Math.min(...m),k=Math.max(...m),b=k-S;s.forEach(D=>l.set(D.id,(l.get(D.id)??0)+o*(b>1e-9?(D.s-S)/b:1)))}const v=new Set(a.map(d=>d.id)),g=new Set(s.map(d=>d.id)),A=new Map(a.map(d=>[d.id,d])),M=[...l.entries()].sort((d,m)=>m[1]-d[1]),C=Y(),u=j(),E=G(),R=E>0?z(t):null,O=J(),N=new Date,$=Math.min(M.length,Math.max(n*4,50)),w=[];for(const[d,m]of M.slice(0,$)){const S=A.get(d)??this.get(d)??void 0;if(!S||S.confidence<i||S.needs_review===1||S.supersedes_id!=null||e.kind&&S.kind!==e.kind)continue;const k=S.updated_at??S.created_at;let b=m*V(k,C,u,N);R&&(b*=X(S.created_at,R,E,N)),b*=Q(S.reuse_count,S.reuse_success_count,O),w.push({id:d,s:b,art:S})}w.sort((d,m)=>m.s-d.s);const H=w[0]?.s??1,W=[];for(const{id:d,s:m,art:S}of w){if(W.length>=n)break;const k=v.has(d)&&g.has(d)?"hybrid":g.has(d)?"vector":"fts";W.push({artifact:S,relevance_score:Math.min(1,m/H),match_type:k})}return W}searchByFtsGlobal(t,e,n,i=0){if(!this.db)return[];let r="";try{const s=B(t);r=s?P(s):""}catch{return[]}if(!r)return[];const a=n?"AND a.kind = ?":"",c=[r,i];n&&c.push(n),c.push(e);try{return this.db.prepare(`
|
|
26
26
|
SELECT a.* FROM memory_artifacts a
|
|
27
27
|
JOIN memory_artifacts_fts ON a.id = memory_artifacts_fts.rowid
|
|
28
28
|
WHERE memory_artifacts_fts MATCH ?
|
|
29
29
|
AND a.confidence >= ?
|
|
30
30
|
AND a.supersedes_id IS NULL
|
|
31
31
|
AND a.needs_review = 0
|
|
32
|
-
${
|
|
32
|
+
${a}
|
|
33
33
|
ORDER BY rank, a.confidence DESC
|
|
34
34
|
LIMIT ?
|
|
35
|
-
`).all(...
|
|
35
|
+
`).all(...c)}catch{return[]}}searchByFts(t,e,n,i,r=0){let a="";try{const h=B(e);a=h?P(h):""}catch{return this.listRecent(t,n,i)}if(!a)return this.listRecent(t,n,i);const c=i?"AND a.kind = ?":"",s=[a,t,r];i&&s.push(i),s.push(n);try{return this.db.prepare(`
|
|
36
36
|
SELECT a.* FROM memory_artifacts a
|
|
37
37
|
JOIN memory_artifacts_fts ON a.id = memory_artifacts_fts.rowid
|
|
38
38
|
WHERE memory_artifacts_fts MATCH ?
|
|
@@ -40,46 +40,46 @@ import{emitEvent as V}from"./events.js";import{sanitizeFtsQuery as $,buildFtsMat
|
|
|
40
40
|
AND a.confidence >= ?
|
|
41
41
|
AND a.supersedes_id IS NULL
|
|
42
42
|
AND a.needs_review = 0
|
|
43
|
-
${
|
|
43
|
+
${c}
|
|
44
44
|
ORDER BY rank, a.confidence DESC
|
|
45
45
|
LIMIT ?
|
|
46
|
-
`).all(...
|
|
46
|
+
`).all(...s)}catch{return this.listRecent(t,n,i)}}searchByTags(t,e,n,i,r=0){const a=e.toLowerCase().split(/\s+/).filter(l=>l.length>2);if(!a.length)return[];const c=l=>l.replace(/[%_\\]/g,"\\$&"),s=a.map(()=>"LOWER(tags) LIKE ? ESCAPE '\\'").join(" OR "),h=a.map(l=>`%${c(l)}%`),_=i?"AND kind = ?":"",o=[t,r,...h];return i&&o.push(i),o.push(n),this.db.prepare(`
|
|
47
47
|
SELECT * FROM memory_artifacts
|
|
48
48
|
WHERE project_id = ? AND confidence >= ? AND supersedes_id IS NULL
|
|
49
49
|
AND needs_review = 0
|
|
50
|
-
AND (${
|
|
51
|
-
${
|
|
50
|
+
AND (${s})
|
|
51
|
+
${_}
|
|
52
52
|
ORDER BY confidence DESC, reuse_success_count DESC
|
|
53
53
|
LIMIT ?
|
|
54
|
-
`).all(...
|
|
54
|
+
`).all(...o)}listRecent(t,e=20,n){const i=n?"AND kind = ?":"",r=[t];return n&&r.push(n),r.push(e),this.db.prepare(`
|
|
55
55
|
SELECT * FROM memory_artifacts
|
|
56
56
|
WHERE project_id = ? AND supersedes_id IS NULL AND needs_review = 0
|
|
57
57
|
${i}
|
|
58
58
|
ORDER BY confidence DESC, created_at DESC
|
|
59
59
|
LIMIT ?
|
|
60
|
-
`).all(...r)}buildContextBrief(t,e,n={}){const i=n.kinds??["pattern","heuristic","reasoning_trace","lesson","anti_pattern"],r=n.maxItems??
|
|
61
|
-
_Constraints:_ ${
|
|
62
|
-
_Solution:_ ${
|
|
63
|
-
_Why it worked:_ ${
|
|
64
|
-
_Note: This approach failed \u2014 avoid it_`),
|
|
60
|
+
`).all(...r)}buildContextBrief(t,e,n={}){const i=n.kinds??["pattern","heuristic","reasoning_trace","lesson","anti_pattern"],r=n.maxItems??oe,a=n.minConfidence??de,c=this.recall(t,e,{limit:r*2,minConfidence:a});c.sort((u,E)=>(K(u.artifact.problem)>0?1:0)-(K(E.artifact.problem)>0?1:0));const s=[],_=c.filter(u=>{const E=u.artifact.source_trust;return(E==="imported"||E==="untrusted")&&ae(`${u.artifact.problem} ${u.artifact.validated_fix??""}`)?(s.push(u.artifact.id),!1):!0}).filter(u=>i.includes(u.artifact.kind)).slice(0,r),o=new Map;for(const u of _){const E=o.get(u.artifact.kind)??[];E.push(u),o.set(u.artifact.kind,E)}const l={pattern:"\u2705 Proven Patterns",heuristic:"\u{1F4A1} Heuristics",reasoning_trace:"\u{1F9E0} Past Reasoning",lesson:"\u{1F4DA} Lessons Learned",anti_pattern:"\u26A0\uFE0F Anti-Patterns to Avoid"},v=["pattern","heuristic","reasoning_trace","lesson","anti_pattern"],g=[],A=[];let M=0;for(const u of v){if(!i.includes(u))continue;const E=o.get(u)??[];if(!E.length)continue;const R=[];for(const O of E){if(M>=r)break;const N=O.artifact;let w=`${ce(N.source_trust)}**Problem:** ${N.problem}`;N.constraints&&(w+=`
|
|
61
|
+
_Constraints:_ ${N.constraints}`),N.validated_fix&&(w+=`
|
|
62
|
+
_Solution:_ ${N.validated_fix}`),N.why_it_worked&&(w+=`
|
|
63
|
+
_Why it worked:_ ${N.why_it_worked}`),N.outcome==="negative"&&(w+=`
|
|
64
|
+
_Note: This approach failed \u2014 avoid it_`),R.push(w),A.push(N.id),M++}R.length&&g.push({heading:l[u],items:R,source:u})}let C="";if(g.length>0){C+=`---
|
|
65
65
|
## \u{F115D} Memory Brief
|
|
66
66
|
_Relevant past knowledge from Wyrm:_
|
|
67
67
|
|
|
68
|
-
`;for(const
|
|
69
|
-
`;for(const
|
|
70
|
-
`;
|
|
71
|
-
`}
|
|
72
|
-
`}return{sections:
|
|
68
|
+
`;for(const u of g){C+=`### ${u.heading}
|
|
69
|
+
`;for(const E of u.items)C+=`- ${E}
|
|
70
|
+
`;C+=`
|
|
71
|
+
`}C+=`---
|
|
72
|
+
`}return{sections:g,text:C,sourceIds:A}}getStats(t){const e=this.db.prepare("SELECT COUNT(*) as n FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NULL").get(t).n,n=this.db.prepare("SELECT COUNT(*) as n FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NOT NULL").get(t).n,i=this.db.prepare("SELECT AVG(confidence) as v FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NULL").get(t).v??0,r=this.db.prepare("SELECT kind, COUNT(*) as cnt FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NULL GROUP BY kind").all(t),a={};for(const c of r)a[c.kind]=c.cnt;return{total:e,byKind:a,avgConfidence:Math.round(i*100)/100,supersededCount:n}}listAll(t,e={}){const n=e.kind?"AND kind = ?":"",i=e.includeSuperseded?"":"AND supersedes_id IS NULL",r=[t];return e.kind&&r.push(e.kind),r.push(e.limit??50),this.db.prepare(`
|
|
73
73
|
SELECT * FROM memory_artifacts
|
|
74
74
|
WHERE project_id = ? ${n} ${i}
|
|
75
75
|
ORDER BY confidence DESC, created_at DESC
|
|
76
76
|
LIMIT ?
|
|
77
|
-
`).all(...r)}listPage(t,e={pageSize:
|
|
77
|
+
`).all(...r)}listPage(t,e={pageSize:se}){const n=e.kind?"AND kind = ?":"",i=e.includeSuperseded?"":"AND supersedes_id IS NULL",r="AND needs_review = 0",a=[t];e.kind&&a.push(e.kind);let c="";if(e.after){const _=Number(e.after.sortKey);Number.isFinite(_)&&(c="AND (confidence < ? OR (confidence = ? AND id < ?))",a.push(_,_,e.after.id))}const s=e.pageSize+1;a.push(s);const h=this.db.prepare(`
|
|
78
78
|
SELECT * FROM memory_artifacts
|
|
79
|
-
WHERE project_id = ? ${n} ${i} ${r} ${
|
|
79
|
+
WHERE project_id = ? ${n} ${i} ${r} ${c}
|
|
80
80
|
ORDER BY confidence DESC, id DESC
|
|
81
81
|
LIMIT ?
|
|
82
|
-
`).all(...
|
|
82
|
+
`).all(...a);return ne(h,e.pageSize,_=>({sortKey:String(_.confidence),id:_.id}))}pruneStale(t={}){const e=t.minConfidence??.3,n=t.olderThanDays??90,i=t.dryRun??!0,r=t.projectId!=null,a=[e,`-${n} days`];r&&a.push(t.projectId);const c=this.db.prepare(`
|
|
83
83
|
SELECT id, kind, problem, confidence, last_accessed_at
|
|
84
84
|
FROM memory_artifacts
|
|
85
85
|
WHERE confidence < ?
|
|
@@ -89,4 +89,4 @@ _Relevant past knowledge from Wyrm:_
|
|
|
89
89
|
${r?"AND project_id = ?":""}
|
|
90
90
|
ORDER BY confidence ASC
|
|
91
91
|
LIMIT 500
|
|
92
|
-
`).all(...
|
|
92
|
+
`).all(...a);return i||c.length===0?{candidates:c,deleted:0,dryRun:i}:{candidates:c,deleted:this.deleteArtifacts(c.map(s=>s.id)),dryRun:i}}deleteArtifacts(t){if(t.length===0)return 0;const e=t.map(()=>"?").join(",");return this.db.prepare(`DELETE FROM memory_artifacts WHERE id IN (${e}) AND needs_review = 0`).run(...t).changes}}export{Ee as MemoryArtifacts};
|
package/dist/migrations.js
CHANGED
|
@@ -1113,6 +1113,13 @@ const n=[{version:1,description:"Baseline schema \u2014 projects, sessions, ques
|
|
|
1113
1113
|
);
|
|
1114
1114
|
CREATE INDEX IF NOT EXISTS idx_write_ledger_ts ON write_ledger(ts);
|
|
1115
1115
|
CREATE INDEX IF NOT EXISTS idx_write_ledger_tool ON write_ledger(tool, ts);
|
|
1116
|
+
`)}},{version:33,description:"v8 F5 \u2014 source_trust provenance lane on memory artifacts (v8-A5): operator > agent > imported > untrusted. Conservative backfill: bridge:* (the operator's own daily record) \u2192 operator; import:*/imported_from tags \u2192 imported; everything else stays agent. Unknown NEVER backfills to operator.",up:e=>{e.prepare("PRAGMA table_info(memory_artifacts)").all().some(E=>E.name==="source_trust")||e.exec(`
|
|
1117
|
+
ALTER TABLE memory_artifacts ADD COLUMN source_trust TEXT NOT NULL DEFAULT 'agent'
|
|
1118
|
+
CHECK (source_trust IN ('operator', 'agent', 'imported', 'untrusted'));
|
|
1119
|
+
`),e.exec(`
|
|
1120
|
+
UPDATE memory_artifacts SET source_trust = 'operator' WHERE created_by LIKE 'bridge:%';
|
|
1121
|
+
UPDATE memory_artifacts SET source_trust = 'imported'
|
|
1122
|
+
WHERE created_by LIKE 'import:%' OR tags LIKE '%imported_from:%';
|
|
1116
1123
|
`)}}];function d(e){e.exec(`
|
|
1117
1124
|
CREATE TABLE IF NOT EXISTS schema_versions (
|
|
1118
1125
|
version INTEGER PRIMARY KEY,
|
package/dist/presence.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{readFileSync as
|
|
1
|
+
import{readFileSync as u}from"node:fs";import{getActor as c}from"./handlers/boundary.js";function _(r){if(!Number.isInteger(r)||r<=0)return null;try{const e=u(`/proc/${r}/stat`,"utf8");return e.slice(e.lastIndexOf(")")+2).trimEnd().split(" ")[19]??null}catch{return null}}function o(r,e){const t=_(r);return t!==null&&t===e}function d(r){try{const t=r.metadata?JSON.parse(r.metadata):null;if(t&&typeof t.pid=="number"&&typeof t.pid_start=="string")return o(t.pid,t.pid_start)?"alive-pid":"dead-pid"}catch{}return(Date.now()-new Date(r.last_heartbeat.replace(" ","T")+"Z").getTime())/1e3<r.ttl_seconds?"alive-ttl":"stale"}class g{db;constructor(e){this.db=e}membershipRole(e,t){if(!e)return null;try{return this.db.prepare("SELECT role FROM run_agents WHERE run_id = ? AND agent_id = ?").get(e,t)?.role??null}catch{return null}}announce(e){const t=e.metadata?JSON.stringify(e.metadata):null,n=c().run_id,a=e.role??this.membershipRole(n,e.agent_id);return this.db.prepare(`
|
|
2
2
|
INSERT INTO agent_presence
|
|
3
3
|
(agent_id, agent_kind, project_id, current_file, current_symbol,
|
|
4
4
|
current_quest_id, ttl_seconds, metadata, run_id, role)
|
|
@@ -14,23 +14,15 @@ import{readFileSync as l}from"node:fs";import{getActor as s}from"./handlers/boun
|
|
|
14
14
|
run_id = excluded.run_id,
|
|
15
15
|
role = excluded.role,
|
|
16
16
|
last_heartbeat = datetime('now')
|
|
17
|
-
`).run(e.agent_id,e.agent_kind,e.project_id??null,e.current_file??null,e.current_symbol??null,e.current_quest_id??null,e.ttl_seconds??300,t,n,a),this.get(e.agent_id)}get(e){return this.db.prepare("SELECT * FROM agent_presence WHERE agent_id = ?").get(e)??null}liveAgents(e){const t=e==null
|
|
18
|
-
WHERE (julianday('now') - julianday(last_heartbeat)) * 86400 < ttl_seconds
|
|
19
|
-
ORDER BY last_heartbeat DESC`:`SELECT * FROM agent_presence
|
|
20
|
-
WHERE project_id = ?
|
|
21
|
-
AND (julianday('now') - julianday(last_heartbeat)) * 86400 < ttl_seconds
|
|
22
|
-
ORDER BY last_heartbeat DESC`;return e==null?this.db.prepare(t).all():this.db.prepare(t).all(e)}agentsOnFile(e){return this.db.prepare(`
|
|
17
|
+
`).run(e.agent_id,e.agent_kind,e.project_id??null,e.current_file??null,e.current_symbol??null,e.current_quest_id??null,e.ttl_seconds??300,t,n,a),this.get(e.agent_id)}get(e){return this.db.prepare("SELECT * FROM agent_presence WHERE agent_id = ?").get(e)??null}liveAgents(e){const t=e==null?"SELECT * FROM agent_presence ORDER BY last_heartbeat DESC":"SELECT * FROM agent_presence WHERE project_id = ? ORDER BY last_heartbeat DESC";return(e==null?this.db.prepare(t).all():this.db.prepare(t).all(e)).filter(a=>{const s=d(a);return s==="alive-pid"||s==="alive-ttl"})}agentsOnFile(e){return this.db.prepare(`
|
|
23
18
|
SELECT * FROM agent_presence
|
|
24
19
|
WHERE current_file = ?
|
|
25
20
|
AND (julianday('now') - julianday(last_heartbeat)) * 86400 < ttl_seconds
|
|
26
21
|
ORDER BY last_heartbeat DESC
|
|
27
|
-
`).all(e)}release(e){return this.db.prepare("DELETE FROM quest_claims WHERE agent_id = ?").run(e),this.db.prepare("DELETE FROM agent_presence WHERE agent_id = ?").run(e).changes>0}reap(){const e=this.db.prepare(`
|
|
28
|
-
DELETE FROM agent_presence
|
|
29
|
-
WHERE (julianday('now') - julianday(last_heartbeat)) * 86400 >= ttl_seconds
|
|
30
|
-
`).run(),t=this.db.prepare(`
|
|
22
|
+
`).all(e)}release(e){return this.db.prepare("DELETE FROM quest_claims WHERE agent_id = ?").run(e),this.db.prepare("DELETE FROM agent_presence WHERE agent_id = ?").run(e).changes>0}reap(){const e=this.db.prepare("SELECT * FROM agent_presence").all(),t=this.db.prepare("DELETE FROM agent_presence WHERE id = ?");let n=0;for(const l of e){const i=d(l);(i==="dead-pid"||i==="stale")&&(t.run(l.id),n++)}const a={changes:n},s=this.db.prepare(`
|
|
31
23
|
DELETE FROM quest_claims
|
|
32
24
|
WHERE (julianday('now') - julianday(claimed_at)) * 86400 >= claim_ttl_seconds
|
|
33
|
-
`).run();return{presence:
|
|
25
|
+
`).run();return{presence:a.changes,claims:s.changes}}claimQuest(e,t,n=1800){this.reap();try{const a=c().run_id;return this.db.prepare(`
|
|
34
26
|
INSERT INTO quest_claims (quest_id, agent_id, claim_ttl_seconds, run_id, role)
|
|
35
27
|
VALUES (?, ?, ?, ?, ?)
|
|
36
28
|
`).run(e,t,n,a,this.membershipRole(a,t)),this.getClaim(e)}catch{return null}}releaseRunClaims(e){return this.db.prepare("DELETE FROM quest_claims WHERE run_id = ?").run(e).changes}releaseClaim(e,t){return this.db.prepare(`
|
|
@@ -48,4 +40,4 @@ import{readFileSync as l}from"node:fs";import{getActor as s}from"./handlers/boun
|
|
|
48
40
|
JOIN agent_presence p ON p.agent_id = c.agent_id
|
|
49
41
|
WHERE q.project_id = ?
|
|
50
42
|
ORDER BY c.claimed_at DESC
|
|
51
|
-
`;return e==null?this.db.prepare(t).all():this.db.prepare(t).all(e)}}export{
|
|
43
|
+
`;return e==null?this.db.prepare(t).all():this.db.prepare(t).all(e)}}export{g as AgentPresence,o as pidAlive,d as presenceLiveness,_ as processStartTime};
|
package/dist/tool-manifest.json
CHANGED
package/dist/wyrm-cli.js
CHANGED
|
@@ -42,7 +42,7 @@ import{join as q,dirname as ne}from"path";import{homedir as Te}from"os";import{e
|
|
|
42
42
|
`+String(i.value).slice(0,500)),console.log(d.bold("Created: ")+i.created_at);break}case"session":{const i=s.prepare("SELECT * FROM sessions WHERE id = ?").get(t);if(!i){m(`Session ${t} not found`);break}console.log(d.bold("Date: ")+i.date),console.log(d.bold("Objectives: ")+`
|
|
43
43
|
`+i.objectives),i.completed&&console.log(d.bold("Completed: ")+`
|
|
44
44
|
`+i.completed),i.notes&&console.log(d.bold("Notes: ")+`
|
|
45
|
-
`+i.notes);break}default:m(`Unknown type prefix: ${r}. Use mem|quest|truth|data|session`)}n.close()}async function Je(l){const{positional:a,flags:e}=C(l),r=a[0];r||(m('Usage: wyrm capture "<content>" [--project <name>] [--mode auto|quest|truth|memory]'),process.exit(1));const o=e.project,t=e.mode,n=_(),s=n.getDatabase();let i=null;if(o){const k=x(n,o);k||(m(`Project not found: ${o}`),n.close(),process.exit(1)),i=k.id}let p=We(r);t&&t!=="auto"&&(p={type:t,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[t]??t,confidence:100,reasoning:`Mode override: ${t}`});const{type:c,subtype:f,confidence:g,reasoning:u}=p;(c==="quest"||c==="truth"||c==="memory")&&i===null&&(m('A --project is required to capture. Use: wyrm capture "<text>" --project <name>'),n.close(),process.exit(1));let h=0,y="",w=!1;const $=new G(s),R=new pe(s);if(me(R,new ue(s)),c==="quest")h=n.addQuest(i,r.slice(0,200),"","medium").id,y="quest";else if(c==="truth")t!=="truth"&&g<100?(h=$.add(i,{kind:"pattern",problem:r,confidence:g/100,needsReview:1}).id,y="mem",w=!0):(h=R.set(i,{category:"decision",key:r.slice(0,60),value:r}).id,y="truth");else{const k=g>=75;h=$.add(i,{kind:f,problem:r,confidence:g/100,needsReview:k?0:1}).id,y="mem",k||(w=!0)}const{recordWrite:j}=await import("./receipts.js"),E=j(s,{tool:"wyrm_capture",outcome:w?"queued":"stored",refTable:y,refId:h,reason:w?`needs_review (
|
|
45
|
+
`+i.notes);break}default:m(`Unknown type prefix: ${r}. Use mem|quest|truth|data|session`)}n.close()}async function Je(l){const{positional:a,flags:e}=C(l),r=a[0];r||(m('Usage: wyrm capture "<content>" [--project <name>] [--mode auto|quest|truth|memory]'),process.exit(1));const o=e.project,t=e.mode,n=_(),s=n.getDatabase();let i=null;if(o){const k=x(n,o);k||(m(`Project not found: ${o}`),n.close(),process.exit(1)),i=k.id}let p=We(r);t&&t!=="auto"&&(p={type:t,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[t]??t,confidence:100,reasoning:`Mode override: ${t}`});const{type:c,subtype:f,confidence:g,reasoning:u}=p;(c==="quest"||c==="truth"||c==="memory")&&i===null&&(m('A --project is required to capture. Use: wyrm capture "<text>" --project <name>'),n.close(),process.exit(1));let h=0,y="",w=!1;const $=new G(s),R=new pe(s);if(me(R,new ue(s)),c==="quest")h=n.addQuest(i,r.slice(0,200),"","medium").id,y="quest";else if(c==="truth")t!=="truth"&&g<100?(h=$.add(i,{kind:"pattern",problem:r,confidence:g/100,needsReview:1}).id,y="mem",w=!0):(h=R.set(i,{category:"decision",key:r.slice(0,60),value:r}).id,y="truth");else{const k=g>=75;h=$.add(i,{kind:f,problem:r,confidence:g/100,needsReview:k?0:1}).id,y="mem",k||(w=!0)}const{recordWrite:j}=await import("./receipts.js"),E=j(s,{tool:"wyrm_capture",outcome:w?"queued":"stored",refTable:y,refId:h,reason:w?`needs_review (confidence ${g}%) \u2014 review to activate`:void 0,source:"cli",projectId:i??void 0});n.close(),b(`Captured as ${c}: ${f}`),console.log(`${d.dim("Confidence:")} ${g}% | ${d.dim(u)}`),console.log(`${d.dim("ID:")} ${y}:${h}`),w&&console.log(`${Y.warning} Stored for review \u2014 run ${d.cyan("wyrm review")} to activate`),console.log(`receipt: ${E.outcome} ${E.ref??""}${E.reason?` \u2014 ${E.reason}`:""}`)}async function ze(l){const{flags:a}=C(l);if(a.writes!==!0){m("Usage: wyrm digest --writes [--since <days>] [--json]"),process.exitCode=1;return}const e=Number(a.since)>=1?Number(a.since):1,{buildWriteDigest:r}=await import("./receipts.js"),o=_();try{const t=r(o.getDatabase(),e);if(a.json===!0){process.stdout.write(JSON.stringify(t)+`
|
|
46
46
|
`);return}if(S(`Write digest \u2014 last ${t.since}`),console.log(`${d.bold("Total writes:")} ${t.total} ${d.bold("Outcomes:")} ${Object.entries(t.byOutcome).map(([n,s])=>`${n} ${s}`).join(" \xB7 ")||"none"}`),console.log(`${d.bold("Review queue:")} ${t.reviewQueueDepth} awaiting review${t.reviewQueueDepth>0?d.dim(" (invisible to recall until approved)"):""}`),t.byTool.length>0&&console.log(P(["Tool","Outcome","N"],t.byTool.map(n=>[n.tool,n.outcome,String(n.n)]))),t.reasons.length>0){console.log(d.bold("Non-stored reasons:"));for(const n of t.reasons)console.log(` ${n.outcome} \xD7${n.n} \u2014 ${n.reason.slice(0,110)}`)}t.bySource.length>0&&console.log(d.bold("By source: ")+t.bySource.map(n=>`${n.source} ${n.n}`).join(" \xB7 "))}finally{o.close()}}async function Qe(l){const{flags:a}=C(l),e=T(a.session,0),r=a.path,o=a.project,t=T(a["max-chars"],6e3),n=a.quiet===!0,s=console.log;console.log=()=>{};const i=_();try{const p=new Me(i.getDatabase());let c=e;if(c<=0){let u=r?i.getProject(r):void 0;if(!u&&o&&(u=x(i,o)??void 0),u||(u=i.getProject(process.cwd())),!u){n||process.stderr.write(`wyrm rehydrate: no Wyrm project for this directory, nothing to restore.
|
|
47
47
|
`);return}const h=i.getRecentSessions(u.id,1);if(h.length===0){n||process.stderr.write(`wyrm rehydrate: project "${u.name}" has no prior sessions yet.
|
|
48
48
|
`);return}c=h[0].id}const f=p.rehydrate(c);if(!f){n||process.stderr.write(`wyrm rehydrate: session ${c} not found.
|
package/dist/wyrm-manifest.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wyrm-mcp",
|
|
3
|
-
"version": "7.
|
|
3
|
+
"version": "7.12.0",
|
|
4
4
|
"mcpName": "lk.ghosts/wyrm",
|
|
5
5
|
"description": "Local-first persistent memory for AI agents over MCP. Ground truths, negative learning (recorded failures block repeats), decision causality, hybrid recall, live memory streams, run-attributed fleet memory — a structured SQLite memory on your machine, no cloud or LLM required. Claude / Copilot / Cursor / Windsurf / Codex.",
|
|
6
6
|
"type": "module",
|