wyrm-mcp 9.2.0 → 9.2.2

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.
Files changed (66) hide show
  1. package/README.md +2 -0
  2. package/dist/auto-runs.js +1 -0
  3. package/dist/autoconfig.js +3 -3
  4. package/dist/capabilities.js +3 -3
  5. package/dist/causality.js +13 -8
  6. package/dist/cli.js +25 -22
  7. package/dist/cloud/cli.js +3 -3
  8. package/dist/cloud/sync-daemon-entrypoint.js +2 -2
  9. package/dist/cloud/sync-daemon.js +1 -1
  10. package/dist/color.js +1 -0
  11. package/dist/database.js +3 -3
  12. package/dist/deprecations.js +2 -2
  13. package/dist/events.js +6 -6
  14. package/dist/federation.js +10 -10
  15. package/dist/handlers/arg-keys.js +1 -0
  16. package/dist/handlers/capture.js +58 -58
  17. package/dist/handlers/causality.js +8 -8
  18. package/dist/handlers/cloud.js +85 -83
  19. package/dist/handlers/companion.js +10 -10
  20. package/dist/handlers/entity.js +1 -1
  21. package/dist/handlers/events.js +12 -12
  22. package/dist/handlers/failure.js +12 -12
  23. package/dist/handlers/goals.js +4 -4
  24. package/dist/handlers/intelligence.js +63 -63
  25. package/dist/handlers/mcpclient.js +1 -1
  26. package/dist/handlers/presence.js +3 -3
  27. package/dist/handlers/project-arg.js +1 -0
  28. package/dist/handlers/project.js +1 -1
  29. package/dist/handlers/quest.js +5 -3
  30. package/dist/handlers/recall.js +18 -18
  31. package/dist/handlers/registry.js +1 -1
  32. package/dist/handlers/resources.js +1 -1
  33. package/dist/handlers/review.js +3 -3
  34. package/dist/handlers/run.js +3 -3
  35. package/dist/handlers/search.js +3 -3
  36. package/dist/handlers/session.js +24 -24
  37. package/dist/handlers/share.js +5 -5
  38. package/dist/handlers/shims.js +1 -1
  39. package/dist/handlers/thread.js +2 -2
  40. package/dist/http-auth.js +1 -1
  41. package/dist/http-fast.js +15 -15
  42. package/dist/index.js +2 -2
  43. package/dist/logger.js +2 -2
  44. package/dist/receipt.js +1 -1
  45. package/dist/rehydration.js +24 -9
  46. package/dist/render.js +3 -3
  47. package/dist/setup.js +2 -3
  48. package/dist/sqlite-busy.js +1 -1
  49. package/dist/stale-servers.js +2 -0
  50. package/dist/stdio-lifecycle.js +1 -0
  51. package/dist/storage/index.js +3 -3
  52. package/dist/tool-manifest-v2.json +1 -1
  53. package/dist/tool-manifest.json +1 -1
  54. package/dist/ui-dashboard.js +9 -8
  55. package/dist/validate.js +1 -1
  56. package/dist/vault-exec.js +4 -0
  57. package/dist/vault.js +1 -1
  58. package/dist/wyrm-cli.js +105 -142
  59. package/dist/wyrm-manifest.json +3 -3
  60. package/dist/wyrm-ui.js +14 -7
  61. package/dist/wyrm.js +2 -0
  62. package/package.json +6 -4
  63. package/scripts/hooks/wyrm-citation-audit.mjs +155 -46
  64. package/scripts/hooks/wyrm-prompt-context.mjs +300 -0
  65. package/scripts/hooks/wyrm-run-auto.mjs +148 -37
  66. package/scripts/hooks/wyrm-session-rehydrate.mjs +142 -24
@@ -1,33 +1,33 @@
1
- const f={sessions:["date","objectives","completed","issues","commits","files_changed","notes","summary","tokens_estimate","is_archived","created_at"],quests:["title","description","priority","status","tags","created_at","completed_at"],ground_truths:["category","key","value","rationale","source","is_current","confidence","last_verified_at","created_at","ttl_days"],memory_artifacts:["kind","problem","constraints","validated_fix","why_it_worked","outcome","tags","confidence","last_validated_at","created_at"],decision_edges:["from_kind","from_id","to_kind","to_id","relation","rationale","confidence","created_at","invalidated_at"]},d={session:{table:"sessions",ts:"created_at"},quest:{table:"quests",ts:"created_at"},truth:{table:"ground_truths",ts:"updated_at"},artifact:{table:"memory_artifacts",ts:"last_accessed_at"},edge:{table:"decision_edges",ts:"created_at"}};class h{db;constructor(t){this.db=t}share(t,s){const e=d[t];return!e||this.isPrivateGroveRow(e.table,s)?!1:this.db.prepare(`UPDATE ${e.table} SET is_shared = 1 WHERE id = ?`).run(s).changes>0}safeRemoteColumns(t,s){if(!new Set(Object.values(d).map(n=>n.table)).has(t))return[];let r;try{const n=this.db.prepare(`PRAGMA table_info(${t})`).all();r=new Set(n.map(a=>a.name))}catch{return[]}return(f[t]??[]).filter(n=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)&&r.has(n)&&n in s)}isPrivateGroveRow(t,s){try{const e=this.db.prepare(`SELECT (SELECT sync_policy FROM projects WHERE id = t.project_id) AS policy
2
- FROM ${t} t WHERE t.id = ?`).get(s);return!e||e.policy==null?!1:e.policy==="private"}catch{return!1}}projectsHasSyncPolicy(){try{return this.db.prepare("PRAGMA table_info(projects)").all().some(t=>t.name==="sync_policy")}catch{return!1}}unshare(t,s){const e=d[t];return e?this.db.prepare(`UPDATE ${e.table} SET is_shared = 0 WHERE id = ?`).run(s).changes>0:!1}collectForPush(t,s=500){const e=t??"1970-01-01",r=[],c=this.projectsHasSyncPolicy()?"AND (project_id IS NULL OR project_id IN (SELECT id FROM projects WHERE sync_policy = 'team'))":"";for(const[n,a]of Object.entries(d)){if(r.length>=s)break;const l=n,o=this.db.prepare(`SELECT * FROM ${a.table}
1
+ const f={sessions:["date","objectives","completed","issues","commits","files_changed","notes","summary","tokens_estimate","is_archived","created_at"],quests:["title","description","priority","status","tags","created_at","completed_at"],ground_truths:["category","key","value","rationale","source","is_current","confidence","last_verified_at","created_at","ttl_days"],memory_artifacts:["kind","problem","constraints","validated_fix","why_it_worked","outcome","tags","confidence","last_validated_at","created_at"],decision_edges:["from_kind","from_id","to_kind","to_id","relation","rationale","confidence","created_at","invalidated_at"]},l={session:{table:"sessions",ts:"created_at"},quest:{table:"quests",ts:"created_at"},truth:{table:"ground_truths",ts:"updated_at"},artifact:{table:"memory_artifacts",ts:"last_accessed_at"},edge:{table:"decision_edges",ts:"created_at"}};class h{db;constructor(t){this.db=t}share(t,r){const e=l[t];return!e||this.isPrivateGroveRow(e.table,r)?!1:this.db.prepare(`UPDATE ${e.table} SET is_shared = 1 WHERE id = ?`).run(r).changes>0}safeRemoteColumns(t,r){if(!new Set(Object.values(l).map(n=>n.table)).has(t))return[];let s;try{const n=this.db.prepare(`PRAGMA table_info(${t})`).all();s=new Set(n.map(a=>a.name))}catch{return[]}return(f[t]??[]).filter(n=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(n)&&s.has(n)&&n in r)}isPrivateGroveRow(t,r){const e=this.groveOf(t,r);return!e||e.policy==null?!1:e.policy==="private"}groveOf(t,r){try{return this.db.prepare(`SELECT t.project_id AS project_id, (SELECT sync_policy FROM projects WHERE id = t.project_id) AS policy
2
+ FROM ${t} t WHERE t.id = ?`).get(r)}catch{return}}shareOutcome(t,r){const e=l[t];if(!e)return{ok:!1,reason:"not_found"};const s=this.groveOf(e.table,r);return s&&s.policy==="private"?{ok:!1,reason:"private_grove",projectId:s.project_id}:this.share(t,r)?{ok:!0}:{ok:!1,reason:"not_found"}}projectsHasSyncPolicy(){try{return this.db.prepare("PRAGMA table_info(projects)").all().some(t=>t.name==="sync_policy")}catch{return!1}}unshare(t,r){const e=l[t];return e?this.db.prepare(`UPDATE ${e.table} SET is_shared = 0 WHERE id = ?`).run(r).changes>0:!1}collectForPush(t,r=500){const e=t??"1970-01-01",s=[],c=this.projectsHasSyncPolicy()?"AND (project_id IS NULL OR project_id IN (SELECT id FROM projects WHERE sync_policy = 'team'))":"";for(const[n,a]of Object.entries(l)){if(s.length>=r)break;const d=n,o=this.db.prepare(`SELECT * FROM ${a.table}
3
3
  WHERE is_shared = 1 ${c} AND ${a.ts} > ?
4
4
  ORDER BY ${a.ts} ASC
5
- LIMIT ?`).all(e,Math.max(1,s-r.length));for(const i of o)r.push({kind:l,id:i.id,project_id:i.project_id??null,payload:i,updated_at:i[a.ts]||new Date().toISOString()})}return r}applyRemote(t,s){const e=d[t.kind];if(!e)return{kind:"skipped"};const r=this.db.prepare(`SELECT ${e.ts} as ts FROM ${e.table} WHERE id = ?`).get(t.id);if(!r){const o=this.safeRemoteColumns(e.table,t.payload);if(o.length===0)return{kind:"skipped"};if(t.project_id==null)return{kind:"skipped"};const i=["id","project_id",...o],p=i.map(()=>"?").join(","),u=[t.id,t.project_id,...o.map(_=>t.payload[_])];try{return this.db.prepare(`INSERT INTO ${e.table} (${i.join(",")}) VALUES (${p})`).run(...u),{kind:"inserted"}}catch{return{kind:"skipped"}}}if(r.ts>t.updated_at){const i=this.db.prepare(`
5
+ LIMIT ?`).all(e,Math.max(1,r-s.length));for(const i of o)s.push({kind:d,id:i.id,project_id:i.project_id??null,payload:i,updated_at:i[a.ts]||new Date().toISOString()})}return s}applyRemote(t,r){const e=l[t.kind];if(!e)return{kind:"skipped"};const s=this.db.prepare(`SELECT ${e.ts} as ts FROM ${e.table} WHERE id = ?`).get(t.id);if(!s){const o=this.safeRemoteColumns(e.table,t.payload);if(o.length===0)return{kind:"skipped"};if(t.project_id==null)return{kind:"skipped"};const i=["id","project_id",...o],p=i.map(()=>"?").join(","),u=[t.id,t.project_id,...o.map(_=>t.payload[_])];try{return this.db.prepare(`INSERT INTO ${e.table} (${i.join(",")}) VALUES (${p})`).run(...u),{kind:"inserted"}}catch{return{kind:"skipped"}}}if(s.ts>t.updated_at){const i=this.db.prepare(`
6
6
  INSERT INTO sync_conflicts
7
7
  (local_kind, local_id, remote_payload, remote_origin)
8
8
  VALUES (?, ?, ?, ?)
9
- `).run(t.kind,t.id,JSON.stringify(t.payload),s).lastInsertRowid;if(t.project_id!=null)try{this.db.prepare(`
9
+ `).run(t.kind,t.id,JSON.stringify(t.payload),r).lastInsertRowid;if(t.project_id!=null)try{this.db.prepare(`
10
10
  INSERT INTO quests (project_id, title, description, priority, status, tags)
11
11
  VALUES (?, ?, ?, 'high', 'pending', 'sync-conflict')
12
- `).run(t.project_id,`[sync] Resolve conflict on ${t.kind} #${t.id}`,`A remote ${s} pushed a ${t.kind} that conflicts with a newer local edit. See sync_conflicts row #${i} for the remote payload. Resolve with wyrm_sync_resolve (kept_local | kept_remote | merged).`)}catch{}return{kind:"conflict",conflict_id:i}}const n=this.safeRemoteColumns(e.table,t.payload);if(n.length===0)return{kind:"skipped"};const a=n.map(o=>`${o} = ?`).join(", "),l=n.map(o=>t.payload[o]);try{return this.db.prepare(`UPDATE ${e.table} SET ${a} WHERE id = ?`).run(...l,t.id),{kind:"overwritten"}}catch{return{kind:"skipped"}}}recordPush(t,s,e,r){const c=new Date().toISOString();return this.db.prepare(`
12
+ `).run(t.project_id,`[sync] Resolve conflict on ${t.kind} #${t.id}`,`A remote ${r} pushed a ${t.kind} that conflicts with a newer local edit. See sync_conflicts row #${i} for the remote payload. Resolve with wyrm_sync_resolve (kept_local | kept_remote | merged).`)}catch{}return{kind:"conflict",conflict_id:i}}const n=this.safeRemoteColumns(e.table,t.payload);if(n.length===0)return{kind:"skipped"};const a=n.map(o=>`${o} = ?`).join(", "),d=n.map(o=>t.payload[o]);try{return this.db.prepare(`UPDATE ${e.table} SET ${a} WHERE id = ?`).run(...d,t.id),{kind:"overwritten"}}catch{return{kind:"skipped"}}}recordPush(t,r,e,s){const c=new Date().toISOString();return this.db.prepare(`
13
13
  INSERT INTO sync_log
14
14
  (direction, remote_origin, kind, count, since_cursor, new_cursor, duration_ms)
15
15
  VALUES ('push', ?, 'mixed', ?, ?, ?, ?)
16
- `).run(s,t.length,r??null,c,e),{pushed:t.length,conflicts:0,new_cursor:c,conflict_ids:[]}}applyPull(t,s,e,r){const c={};let n=0;for(const l of t){const o=this.applyRemote(l,s);(o.kind==="inserted"||o.kind==="overwritten")&&(n++,c[l.kind]=(c[l.kind]??0)+1)}const a=new Date().toISOString();return this.db.prepare(`
16
+ `).run(r,t.length,s??null,c,e),{pushed:t.length,conflicts:0,new_cursor:c,conflict_ids:[]}}applyPull(t,r,e,s){const c={};let n=0;for(const d of t){const o=this.applyRemote(d,r);(o.kind==="inserted"||o.kind==="overwritten")&&(n++,c[d.kind]=(c[d.kind]??0)+1)}const a=new Date().toISOString();return this.db.prepare(`
17
17
  INSERT INTO sync_log
18
18
  (direction, remote_origin, kind, count, since_cursor, new_cursor, duration_ms)
19
19
  VALUES ('pull', ?, 'mixed', ?, ?, ?, ?)
20
- `).run(s,n,r??null,a,e),{pulled:n,new_cursor:a,by_kind:c}}latestCursor(t,s){return this.db.prepare(`
20
+ `).run(r,n,s??null,a,e),{pulled:n,new_cursor:a,by_kind:c}}latestCursor(t,r){return this.db.prepare(`
21
21
  SELECT new_cursor FROM sync_log
22
22
  WHERE direction = ? AND remote_origin = ?
23
23
  ORDER BY id DESC LIMIT 1
24
- `).get(t,s)?.new_cursor??null}unresolvedConflicts(t=50){return this.db.prepare(`
24
+ `).get(t,r)?.new_cursor??null}unresolvedConflicts(t=50){return this.db.prepare(`
25
25
  SELECT id, local_kind, local_id, remote_origin, detected_at, quest_id
26
26
  FROM sync_conflicts
27
27
  WHERE resolved_at IS NULL
28
28
  ORDER BY detected_at DESC LIMIT ?
29
- `).all(t)}resolveConflict(t,s,e){const r=this.db.prepare("SELECT * FROM sync_conflicts WHERE id = ? AND resolved_at IS NULL").get(t);if(!r)return!1;if(s==="kept_remote"||s==="merged"){const c=d[r.local_kind];if(c){const n=s==="merged"&&e?e:JSON.parse(r.remote_payload),a=Object.keys(n).filter(i=>i!=="id"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)),l=a.map(i=>`${i} = ?`).join(", "),o=a.map(i=>n[i]);try{this.db.prepare(`UPDATE ${c.table} SET ${l} WHERE id = ?`).run(...o,r.local_id)}catch{}}}return this.db.prepare(`
29
+ `).all(t)}resolveConflict(t,r,e){const s=this.db.prepare("SELECT * FROM sync_conflicts WHERE id = ? AND resolved_at IS NULL").get(t);if(!s)return!1;if(r==="kept_remote"||r==="merged"){const c=l[s.local_kind];if(c){const n=r==="merged"&&e?e:JSON.parse(s.remote_payload),a=Object.keys(n).filter(i=>i!=="id"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(i)),d=a.map(i=>`${i} = ?`).join(", "),o=a.map(i=>n[i]);try{this.db.prepare(`UPDATE ${c.table} SET ${d} WHERE id = ?`).run(...o,s.local_id)}catch{}}}return this.db.prepare(`
30
30
  UPDATE sync_conflicts
31
31
  SET resolved_at = datetime('now'), resolution = ?
32
32
  WHERE id = ?
33
- `).run(s,t),!0}}export{h as Federation};
33
+ `).run(r,t),!0}}export{h as Federation};
@@ -0,0 +1 @@
1
+ import{unknownKeysError as f}from"../validate.js";import{registryToolDefs as w}from"./registry.js";import{shimToolDefs as y}from"./shims.js";const b=["actor","run_id"],_={wyrm_quest_complete:{quest_id:"spelling of questId; wyrm_quest publishes quest_id",id:"spelling of questId; a rendered quest:N ref binds here too"},wyrm_quest_claim:{questId:"spelling of quest_id; wyrm_quest_complete publishes questId",id:"spelling of quest_id; a rendered quest:N ref binds here too"},wyrm_quest_release:{questId:"spelling of quest_id; wyrm_quest_complete publishes questId",id:"spelling of quest_id; a rendered quest:N ref binds here too"},wyrm_all_quests:{limit:"result cap; published on wyrm_quest for action=list, read the same when called by this name"},wyrm_goal_complete:{goal_id:"spelling of id; wyrm_goal_iterations publishes goal_id"},wyrm_goal_pause:{goal_id:"spelling of id; wyrm_goal_iterations publishes goal_id"},wyrm_goal_resume:{goal_id:"spelling of id; wyrm_goal_iterations publishes goal_id"},wyrm_goal_abandon:{goal_id:"spelling of id; wyrm_goal_iterations publishes goal_id"},wyrm_goal_iterations:{id:"spelling of goal_id; wyrm_goal publishes id"},wyrm_remember:{validated_fix:"spelling of validatedFix, the column and outputSchema name",why_it_worked:"spelling of whyItWorked, the column and outputSchema name"},wyrm_capture:{validated_fix:"spelling of validatedFix, read by the guard that sends a direct-capture payload to mode=direct"},wyrm_failure_record:{files:"source files the failure is about, anchored for the staleness check; undeclared on the lean default surface"}};let u=null;function c(e){return u??=new Map([...w(),...y()].map(t=>[t.name,Object.keys(t.inputSchema.properties??{})])),u.get(e)}const m=new Set;function S(e,t,o){const r=c(e);if(r===void 0)return;const p=o===e?[]:c(o)??[],s=[...new Set([...r,...p])],l=[...Object.keys(_[e]??{}),...o===e?[]:Object.keys(_[o]??{})],h=new Set([...s,...l,...b]),i=Object.keys(t).filter(g=>!h.has(g));if(i.length===0)return;const n=f(i,[...s,...l],s),a=process.env.WYRM_ALLOW_UNKNOWN_ARGS;if(a!=="1"&&a!=="true")throw n;const d=`${e}\0${i.join("\0")}`;m.has(d)||(m.add(d),console.error(`[wyrm] ${e}: ${n.message}. Passed through because WYRM_ALLOW_UNKNOWN_ARGS=1 (the tool ignores keys it does not read).`))}export{_ as ARG_ALIASES,b as UNIVERSAL_ARG_NAMES,c as publishedArgNames,S as rejectUnknownArgs};
@@ -1,78 +1,78 @@
1
- import{join as z}from"path";import{createHash as K}from"crypto";import{TOOL_ANNOTATIONS as D}from"../tool-annotations.js";import{renderResult as E,withGlyph as T,renderErrorResponse as R,validationErrorBody as A}from"../render.js";import{ValidationError as Z,asEnum as ee,asTags as J}from"../validate.js";import{daemonOr as M}from"../daemon-writer.js";import{classifyCapture as te}from"../capture.js";import{recordWrite as C}from"../receipts.js";import{extractCandidates as Y,candidateToArtifact as Q,escapeLikePattern as W}from"../auto-capture.js";import{parseTrace as re,segmentsToText as ie}from"../trace-harvest.js";import{getActor as se,runWithActor as oe}from"./boundary.js";import{harvestProjects as ne}from"../harvest.js";import{readFileSync as X,readdirSync as ae,statSync as F,lstatSync as de}from"fs";import{join as N}from"path";import{homedir as G}from"os";import{resolveUserPath as U,userPathRoots as H,SecurityError as V}from"../security.js";import{autoEnrollProject as ce}from"../project-resolve.js";import{readSpecDir as pe,specTaskSignature as le}from"../spec-kit.js";function B($,w){return($?.needs_review??w)===1}const Ee=[{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:w,raw:I,memory:b,truths:m,cache:_})=>{const{content:o,project_id:f,projectPath:n,mode:d}=$,h=J("tags",$.tags);if(typeof o!="string"||!o.trim()){const p=$;return p.problem||p.validated_fix||p.validatedFix||p.kind?R(A("wyrm_capture","mode","you passed pattern/lesson fields (kind/problem/validated_fix) \u2014 set mode:'direct' to store them as a distilled artifact.")):R(A("wyrm_capture","content","content is required for auto capture (or use mode:'direct' with problem + validated_fix)."))}let k=te(o);d&&d!=="auto"&&(k={type:d,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[d]??d,confidence:100,reasoning:`Mode override: ${d}`});const{type:a,subtype:i,confidence:c,reasoning:v}=k,e=w,t=f??(n?w.getProject(n)?.id??ce(e,n)?.id:void 0)??null;let s=0,x="",r=!1,l;if(a==="quest"){if(t===null)return R(A("wyrm_capture","projectPath","is required for quest capture"));s=(await M("quest_add",t,{title:o.slice(0,200),description:"",priority:"medium",tags:h?.join(",")},()=>w.addQuest(t,o.slice(0,200),"","medium",h?.join(",")))).id,x="quest",_.invalidate("wyrm_all_quests"),_.invalidate("wyrm_stats")}else if(a==="truth"){if(t===null)return R(A("wyrm_capture","projectPath","is required for truth capture"));if(c>=80){const p=i??"other",u=m.getCurrent(t).filter(g=>g.category===p);if(u.length>0){const g={kind:"pattern",problem:`Potential conflict with ${u.length} existing truth(s) in category "${p}"`,validatedFix:o,whyItWorked:"Pending review \u2014 possible supersession",tags:h??[],confidence:c/100,needsReview:1},S=await M("artifact_add",t,g,()=>b.add(t,g)),q=B(S,1),L=C(I(),{tool:"wyrm_capture",outcome:q?"queued":"stored",refTable:"mem",refId:S.id,reason:q?`conflict_check \u2014 possible supersession of ${u.length} truth(s); review to activate`:`conflict_check \u2014 possible supersession of ${u.length} truth(s); auto-approved, live in recall`,projectId:t});return E({status:q?"queued_for_review":"captured",reason:"conflict_check",artifact_id:S.id,conflicts_with:u.map(O=>({id:O.id,content:O.value.slice(0,80)})),receipt:L})}}if(d!=="truth"&&c<100){const p={kind:"pattern",problem:o,validatedFix:"",whyItWorked:"",tags:h??[],confidence:c/100,needsReview:1},P=await M("artifact_add",t,p,()=>b.add(t,p));s=P.id,x="mem",r=B(P,1)}else{const p={category:"decision",key:o.slice(0,60),value:o};s=(await M("truth_set",t,p,()=>m.set(t,p))).id,x="truth",_.invalidate("wyrm_truth_get"),_.invalidate("wyrm_context_build")}}else{if(t===null)return R(A("wyrm_capture","projectPath","is required for memory capture"));const p=c>=75,P={kind:i,problem:o,validatedFix:"",whyItWorked:"",tags:h??[],confidence:c/100,needsReview:p?0:1},u=await M("artifact_add",t,P,()=>b.add(t,P));if(s=u.id,x="mem",r=B(u,p?0:1),i==="heuristic"&&c>=75&&t!==null)try{const g=o.replace(/['"*]/g," ").trim().split(/\s+/).slice(0,5).join(" "),S=I().prepare(`
1
+ import{join as re}from"path";import{createHash as K}from"crypto";import{TOOL_ANNOTATIONS as D}from"../tool-annotations.js";import{renderResult as E,withGlyph as T,validationErrorResponse as R}from"../render.js";import{ValidationError as J,asEnum as ie,asTags as Y}from"../validate.js";import{daemonOr as O}from"../daemon-writer.js";import{classifyCapture as se}from"../capture.js";import{recordWrite as A}from"../receipts.js";import{extractCandidates as Q,candidateToArtifact as z,escapeLikePattern as W}from"../auto-capture.js";import{parseTrace as oe,segmentsToText as ne}from"../trace-harvest.js";import{getActor as ae,runWithActor as de}from"./boundary.js";import{harvestProjects as ce}from"../harvest.js";import{readFileSync as X,readdirSync as pe,statSync as F,lstatSync as ue}from"fs";import{join as N}from"path";import{homedir as G}from"os";import{resolveUserPath as U,userPathRoots as H,SecurityError as V}from"../security.js";import{autoEnrollProject as le}from"../project-resolve.js";import{readSpecDir as me,specTaskSignature as ye}from"../spec-kit.js";function B(m,y){return(m?.needs_review??y)===1}const Z=["auto","quest","truth","memory","classify","direct","extract","trace","session","artifacts","import","spec","checklist","feedback"],M=(m,y)=>y.map($=>`${m}:${$}`),fe=["auto","classify","quest","truth","memory"];function ee(m){return new Set(m.toLowerCase().split(/[^a-z0-9]+/).filter(y=>y.length>2))}function he(m,y,$){if(m.value.trim()===$.trim())return!1;if(m.key.trim().toLowerCase()===y.trim().toLowerCase())return!0;const _=ee(m.value),u=ee($);if(_.size===0||u.size===0)return!1;let f=0;for(const n of _)u.has(n)&&f++;return f/(_.size+u.size-f)>=.6}const De=[{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, feedback (artifactId + success: mark what you recalled as useful, or not). 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"},tags:{type:"array",items:{type:"string"}},mode:{type:"string",enum:[...Z],description:"quest|truth|memory force the type"},source:{type:"string",enum:["git","pr","rules"]},projectPath:{type:"string"},kind:{type:"string",enum:["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]},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","skipped"]},mode:{type:"string"},refs:{type:"array",items:{type:"string"}},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","mode","refs"]},annotations:D.wyrm_capture,aliases:[],handler:async(m,{store:y,raw:$,memory:_,truths:u,cache:f})=>{const{content:n,project_id:h,projectPath:d,mode:a}=m,g=Y("tags",m.tags);if(a!==void 0&&!fe.includes(a))throw new J("mode",`must be one of: ${Z.join(", ")}`);if(typeof n!="string"||!n.trim()){const c=m;return c.problem||c.validated_fix||c.validatedFix||c.kind?R("wyrm_capture","mode","you passed pattern/lesson fields (kind/problem/validated_fix); set mode:'direct' to store them as a distilled artifact."):R("wyrm_capture","content","content is required for auto capture (or use mode:'direct' with problem + validated_fix).")}let w=se(n);a&&a!=="auto"&&a!=="classify"&&(w={type:a,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[a]??a,confidence:100,reasoning:`Mode override: ${a}`});const{type:b,subtype:s,confidence:o,reasoning:v}=w,i=y,t=h??(d?y.getProject(d)?.id??le(i,d)?.id:void 0)??null;let r=0,x="",I=!1,e;if(b==="quest"){if(t===null)return R("wyrm_capture","projectPath","is required for quest capture");r=(await O("quest_add",t,{title:n.slice(0,200),description:"",priority:"medium",tags:g?.join(",")},()=>y.addQuest(t,n.slice(0,200),"","medium",g?.join(",")))).id,x="quest",f.invalidate("wyrm_all_quests"),f.invalidate("wyrm_stats")}else if(b==="truth"){if(t===null)return R("wyrm_capture","projectPath","is required for truth capture");if(a!=="truth"&&o>=80){const c=s??"other",q=u.getCurrent(t).filter(l=>l.category===c&&he(l,n.slice(0,60),n));if(q.length>0){const l={kind:"pattern",problem:`Potential conflict with ${q.length} existing truth(s) in category "${c}" (same key or near-identical statement)`,validatedFix:n,whyItWorked:"Pending review \u2014 possible supersession",tags:g??[],confidence:o/100,needsReview:1},j=await O("artifact_add",t,l,()=>_.add(t,l)),S=B(j,1),L=A($(),{tool:"wyrm_capture",outcome:S?"queued":"stored",refTable:"mem",refId:j.id,reason:S?`conflict_check \u2014 possible supersession of ${q.length} truth(s); review to activate`:`conflict_check \u2014 possible supersession of ${q.length} truth(s); auto-approved, live in recall`,projectId:t});return E({status:S?"queued_for_review":"captured",mode:a??"auto",refs:M("mem",[j.id]),reason:"conflict_check",artifact_id:j.id,conflicts_with:q.map(C=>({id:C.id,content:C.value.slice(0,80)})),receipt:L})}}if(a!=="truth"&&o<100){const c={kind:"pattern",problem:n,validatedFix:"",whyItWorked:"",tags:g??[],confidence:o/100,needsReview:1},P=await O("artifact_add",t,c,()=>_.add(t,c));r=P.id,x="mem",I=B(P,1)}else{const c={category:"decision",key:n.slice(0,60),value:n};r=(await O("truth_set",t,c,()=>u.set(t,c))).id,x="truth",f.invalidate("wyrm_truth_get"),f.invalidate("wyrm_context_build")}}else{if(t===null)return R("wyrm_capture","projectPath","is required for memory capture");const c=o>=75,P={kind:s,problem:n,validatedFix:"",whyItWorked:"",tags:g??[],confidence:o/100,needsReview:c?0:1},q=await O("artifact_add",t,P,()=>_.add(t,P));if(r=q.id,x="mem",I=B(q,c?0:1),s==="heuristic"&&o>=75&&t!==null)try{const l=n.replace(/['"*]/g," ").trim().split(/\s+/).slice(0,5).join(" "),j=$().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(g,t);S.length>0&&(l=S.map(q=>({id:q.id,content:q.problem.slice(0,80)})))}catch{}}const y=C(I(),{tool:"wyrm_capture",outcome:r?"queued":"stored",refTable:x,refId:s,reason:r?`needs_review (confidence ${c}%) \u2014 review to activate`:void 0,projectId:t??void 0}),j={status:"captured",type:a,subtype:i,confidence:c,reasoning:v,id:s,ref:`${x}:${s}`,needs_review:r,receipt:y,...l&&l.length>0?{advisory_conflicts:l}:{}};return E(j,(p,P)=>{let u=`Captured as ${p.type}: ${p.subtype}
7
- Confidence: ${p.confidence}% | ${p.reasoning}
8
- ID: ${p.ref}`;p.needs_review&&(u+=`
9
- `+T(P.warn,"Stored for review -- run `wyrm_review` to activate"));const g=p.advisory_conflicts;return g&&g.length>0&&(u+=`
10
-
11
- `+T(P.warn,`Advisory: ${g.length} similar heuristic(s) found:`)+`
12
- `+g.map(S=>` ${P.bullet} [${S.id}] ${S.content}`).join(`
13
- `)),u})}},{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:w,memory:I,raw:b})=>{const{projectPath:m,kind:_,problem:o,constraints:f,outcome:n,confidence:d,sourceSessionId:h}=$,k=J("tags",$.tags),a=$,i=a.validatedFix??a.validated_fix,c=a.whyItWorked??a.why_it_worked,v=ee("kind",_,["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]);if(v===void 0)throw new Z("kind","is required");const e=w.getProject(m);if(!e)return R(A("wyrm_remember","projectPath","project not found"));const t={kind:v,problem:o,constraints:f,validatedFix:i,whyItWorked:c,outcome:n,tags:k,confidence:d,sourceSessionId:h},s=await M("artifact_add",e.id,t,()=>I.add(e.id,t)),x=C(b(),{tool:"wyrm_remember",outcome:s.needs_review===1?"queued":"stored",refTable:"mem",refId:s.id,reason:s.needs_review===1?"needs_review \u2014 hidden until approved":void 0,source:s.created_by,projectId:e.id}),r={id:s.id,kind:s.kind,problem:s.problem,validated_fix:s.validated_fix??null,why_it_worked:s.why_it_worked??null,confidence:s.confidence,tags:s.tags??null,receipt:x};return E(r,(l,y)=>{let j=T(y.brand,"**Memory Stored**")+`
14
-
15
- `;return j+=`${y.bullet} **Kind:** ${l.kind}
16
- `,j+=`${y.bullet} **ID:** ${l.id}
17
- `,j+=`${y.bullet} **Problem:** ${l.problem}
18
- `,l.validated_fix&&(j+=`${y.bullet} **Solution:** ${l.validated_fix}
19
- `),l.why_it_worked&&(j+=`${y.bullet} **Why it worked:** ${l.why_it_worked}
20
- `),j+=`${y.bullet} **Confidence:** ${(l.confidence*100).toFixed(0)}%
21
- `,l.tags&&(j+=`${y.bullet} **Tags:** ${l.tags}
22
- `),j+="\n_Use `wyrm_recall` to retrieve similar memories, or `wyrm_context_build` to assemble a task brief._",j})}},{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:w,raw:I,memory:b,cache:m})=>{const{projectPath:_,text:o,model:f}=$,n=w.getProject(_);if(!n)return R(A("wyrm_auto_capture","projectPath","project not found"));if(!o||o.trim().length<20)return R(A("wyrm_auto_capture","text","must be at least 20 characters"));const{candidates:d,method:h,model:k}=await Y(o,{model:f}),a=I();let i=0,c=0;for(const e of d){const t=Q(e),s=t.tags[t.tags.length-1];if(a.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(n.id,"%"+W(s)+"%")){c++,C(a,{tool:"wyrm_auto_capture",outcome:"dropped",reason:"dedup \u2014 already captured",source:"auto-extract",projectId:n.id});continue}const x=b.add(n.id,{kind:t.kind,problem:t.problem,tags:t.tags,confidence:t.confidence,needsReview:1,createdBy:"auto-extract"});C(a,{tool:"wyrm_auto_capture",outcome:"queued",refTable:"mem",refId:x.id,reason:"needs_review \u2014 auto-extracted; review to activate",source:"auto-extract",projectId:n.id}),i++}i>0&&m.invalidate();const v={method:h,model:k??null,added:i,skipped:c,receipt:{outcome:i>0?"queued":"dropped",reason:`${i} queued for review, ${c} dropped as duplicates`},candidates:d.slice(0,8).map(e=>({kind:e.kind,text:e.text.slice(0,80)}))};return E(v,(e,t)=>{const s=e.candidates.map(x=>` ${t.bullet} [${x.kind}] ${x.text}`).join(`
23
- `);return T(t.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:D.wyrm_capture_trace,aliases:[],handler:async($,{store:w,raw:I,memory:b,cache:m})=>{const{projectPath:_,trace:o,path:f,format:n,run_id:d,model:h}=$,k=w.getProject(_);if(!k)return R(A("wyrm_capture_trace","projectPath","project not found"));const a=se(),i=typeof d=="string"&&d.trim()?d.trim().slice(0,64):a.run_id;let c="",v="inline";if(typeof o=="string"&&o.trim())c=o,v="inline";else if(typeof f=="string"&&f.trim()){let u;try{u=U(f,H([N(G(),".dragon","traces")]),"wyrm_capture_trace.path")}catch(g){if(g instanceof V)return R(A("wyrm_capture_trace","path",g.message));throw g}try{if(F(u).isDirectory()){const S=H([N(G(),".dragon","traces")]),q=ae(u).map(L=>N(u,L)).filter(L=>{try{return de(L).isFile()?(U(L,S,"wyrm_capture_trace.path"),!0):!1}catch{return!1}}).sort((L,O)=>F(O).mtimeMs-F(L).mtimeMs);if(q.length===0)return R(A("wyrm_capture_trace","path","no trace files in directory"));c=X(q[0],"utf-8"),v=q[0]}else c=X(u,"utf-8"),v=u}catch(g){return R(A("wyrm_capture_trace","path",`could not read trace path: ${g.message}`))}}else return R(A("wyrm_capture_trace","trace","provide inline trace or path to trace file"));const{segments:e,format:t}=re(c,n??"auto"),s=ie(e);if(s.trim().length<20){const u={method:"deterministic",model:null,format:t,source:v,run_id:i,segments:e.length,added:0,skipped:0,candidates:[]};return E(u,(g,S)=>T(S.brand,`Trace harvest (${g.format}) -- no durable content extracted from ${g.segments} segment(s).`))}const{candidates:x,method:r,model:l}=await Y(s,{model:h}),y=I();let j=0,p=0;for(const u of x){const g=Q(u),S=g.tags[g.tags.length-1];if(y.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(k.id,"%"+W(S)+"%")){p++;continue}const q=i?[...g.tags,"trace",`run:${i}`]:[...g.tags,"trace"];oe({agent_id:a.agent_id,run_id:i,source:i?"param":a.source},()=>b.add(k.id,{kind:g.kind,problem:g.problem,tags:q,confidence:g.confidence,needsReview:1,createdBy:"trace-harvest"})),j++}j>0&&m.invalidate();const P={method:r,model:l??null,format:t,source:v,run_id:i,segments:e.length,added:j,skipped:p,candidates:x.slice(0,8).map(u=>({kind:u.kind,text:u.text.slice(0,80)}))};return E(P,(u,g)=>{const S=u.candidates.map(q=>` ${g.bullet} [${q.kind}] ${q.text}`).join(`
27
- `);return T(g.brand,`Trace harvest (${u.format}, ${u.method}${u.model?` - ${u.model}`:""}) -- ${u.segments} segment(s) -> ${u.added} candidate(s) to review queue, ${u.skipped} already present${u.run_id?` [run:${u.run_id}]`:""}.`)+(S?`
6
+ `).all(l,t);j.length>0&&(e=j.map(S=>({id:S.id,content:S.problem.slice(0,80)})))}catch{}}const k=A($(),{tool:"wyrm_capture",outcome:I?"queued":"stored",refTable:x,refId:r,reason:I?`needs_review (confidence ${o}%) \u2014 review to activate`:void 0,projectId:t??void 0}),p={status:"captured",mode:a==="classify"||a===void 0?"auto":a,refs:[`${x}:${r}`],type:b,subtype:s,confidence:o,reasoning:v,id:r,ref:`${x}:${r}`,needs_review:I,receipt:k,...e&&e.length>0?{advisory_conflicts:e}:{}};return E(p,(c,P)=>{let q=`Captured as ${c.type}: ${c.subtype}
7
+ Confidence: ${c.confidence}% | ${c.reasoning}
8
+ ID: ${c.ref}`;c.needs_review&&(q+=`
9
+ `+T(P.warn,"Stored for review -- run `wyrm_review` to activate"));const l=c.advisory_conflicts;return l&&l.length>0&&(q+=`
10
+
11
+ `+T(P.warn,`Advisory: ${l.length} similar heuristic(s) found:`)+`
12
+ `+l.map(j=>` ${P.bullet} [${j.id}] ${j.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:D.wyrm_remember,aliases:[],handler:async(m,{store:y,memory:$,raw:_})=>{const{projectPath:u,kind:f,problem:n,constraints:h,outcome:d,confidence:a,sourceSessionId:g}=m,w=Y("tags",m.tags),b=m,s=b.validatedFix??b.validated_fix,o=b.whyItWorked??b.why_it_worked,v=ie("kind",f,["reasoning_trace","lesson","pattern","anti_pattern","heuristic"]);if(v===void 0)throw new J("kind","is required");const i=y.getProject(u);if(!i)return R("wyrm_remember","projectPath","project not found");const t={kind:v,problem:n,constraints:h,validatedFix:s,whyItWorked:o,outcome:d,tags:w,confidence:a,sourceSessionId:g},r=await O("artifact_add",i.id,t,()=>$.add(i.id,t)),x=A(_(),{tool:"wyrm_remember",outcome:r.needs_review===1?"queued":"stored",refTable:"mem",refId:r.id,reason:r.needs_review===1?"needs_review \u2014 hidden until approved":void 0,source:r.created_by,projectId:i.id}),I={status:r.needs_review===1?"queued_for_review":"captured",mode:"direct",refs:M("mem",[r.id]),id:r.id,kind:r.kind,problem:r.problem,validated_fix:r.validated_fix??null,why_it_worked:r.why_it_worked??null,confidence:r.confidence,tags:r.tags??null,receipt:x};return E(I,(e,k)=>{let p=T(k.brand,"**Memory Stored**")+`
14
+
15
+ `;return p+=`${k.bullet} **Kind:** ${e.kind}
16
+ `,p+=`${k.bullet} **ID:** ${e.id}
17
+ `,p+=`${k.bullet} **Problem:** ${e.problem}
18
+ `,e.validated_fix&&(p+=`${k.bullet} **Solution:** ${e.validated_fix}
19
+ `),e.why_it_worked&&(p+=`${k.bullet} **Why it worked:** ${e.why_it_worked}
20
+ `),p+=`${k.bullet} **Confidence:** ${(e.confidence*100).toFixed(0)}%
21
+ `,e.tags&&(p+=`${k.bullet} **Tags:** ${e.tags}
22
+ `),p+="\n_Use `wyrm_recall` to retrieve similar memories, or `wyrm_context_build` to assemble a task brief._",p})}},{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(m,{store:y,raw:$,memory:_,cache:u})=>{const{projectPath:f,text:n,model:h}=m,d=y.getProject(f);if(!d)return R("wyrm_auto_capture","projectPath","project not found");if(!n||n.trim().length<20)return R("wyrm_auto_capture","text","must be at least 20 characters");const{candidates:a,method:g,model:w}=await Q(n,{model:h}),b=$();let s=0,o=0;const v=[];for(const t of a){const r=z(t),x=r.tags[r.tags.length-1];if(b.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(d.id,"%"+W(x)+"%")){o++,A(b,{tool:"wyrm_auto_capture",outcome:"dropped",reason:"dedup \u2014 already captured",source:"auto-extract",projectId:d.id});continue}const I=_.add(d.id,{kind:r.kind,problem:r.problem,tags:r.tags,confidence:r.confidence,needsReview:1,createdBy:"auto-extract"});v.push(I.id),A(b,{tool:"wyrm_auto_capture",outcome:"queued",refTable:"mem",refId:I.id,reason:"needs_review \u2014 auto-extracted; review to activate",source:"auto-extract",projectId:d.id}),s++}s>0&&u.invalidate();const i={method:g,model:w??null,added:s,skipped:o,status:s>0?"queued_for_review":"skipped",mode:"extract",refs:M("mem",v),receipt:{outcome:s>0?"queued":"dropped",reason:`${s} queued for review, ${o} dropped as duplicates`},candidates:a.slice(0,8).map(t=>({kind:t.kind,text:t.text.slice(0,80)}))};return E(i,(t,r)=>{const x=t.candidates.map(I=>` ${r.bullet} [${I.kind}] ${I.text}`).join(`
23
+ `);return T(r.brand,`Auto-capture (${t.method}${t.model?` - ${t.model}`:""}) -- ${t.added} candidate(s) -> review queue, ${t.skipped} already present.`)+`
24
+ ${x}
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(m,{store:y,raw:$,memory:_,cache:u})=>{const{projectPath:f,trace:n,path:h,format:d,run_id:a,model:g}=m,w=y.getProject(f);if(!w)return R("wyrm_capture_trace","projectPath","project not found");const b=ae(),s=typeof a=="string"&&a.trim()?a.trim().slice(0,64):b.run_id;let o="",v="inline";if(typeof n=="string"&&n.trim())o=n,v="inline";else if(typeof h=="string"&&h.trim()){let l;try{l=U(h,H([N(G(),".dragon","traces")]),"wyrm_capture_trace.path")}catch(j){if(j instanceof V)return R("wyrm_capture_trace","path",j.message);throw j}try{if(F(l).isDirectory()){const S=H([N(G(),".dragon","traces")]),L=pe(l).map(C=>N(l,C)).filter(C=>{try{return ue(C).isFile()?(U(C,S,"wyrm_capture_trace.path"),!0):!1}catch{return!1}}).sort((C,te)=>F(te).mtimeMs-F(C).mtimeMs);if(L.length===0)return R("wyrm_capture_trace","path","no trace files in directory");o=X(L[0],"utf-8"),v=L[0]}else o=X(l,"utf-8"),v=l}catch(j){return R("wyrm_capture_trace","path",`could not read trace path: ${j.message}`)}}else return R("wyrm_capture_trace","trace","provide inline trace or path to trace file");const{segments:i,format:t}=oe(o,d??"auto"),r=ne(i);if(r.trim().length<20){const l={method:"deterministic",model:null,format:t,source:v,run_id:s,segments:i.length,added:0,skipped:0,status:"skipped",mode:"trace",refs:[],candidates:[]};return E(l,(j,S)=>T(S.brand,`Trace harvest (${j.format}) -- no durable content extracted from ${j.segments} segment(s).`))}const{candidates:x,method:I,model:e}=await Q(r,{model:g}),k=$();let p=0,c=0;const P=[];for(const l of x){const j=z(l),S=j.tags[j.tags.length-1];if(k.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(w.id,"%"+W(S)+"%")){c++;continue}const L=s?[...j.tags,"trace",`run:${s}`]:[...j.tags,"trace"],C=de({agent_id:b.agent_id,run_id:s,source:s?"param":b.source},()=>_.add(w.id,{kind:j.kind,problem:j.problem,tags:L,confidence:j.confidence,needsReview:1,createdBy:"trace-harvest"}));P.push(C.id),p++}p>0&&u.invalidate();const q={method:I,model:e??null,format:t,source:v,run_id:s,segments:i.length,added:p,skipped:c,status:p>0?"queued_for_review":"skipped",mode:"trace",refs:M("mem",P),candidates:x.slice(0,8).map(l=>({kind:l.kind,text:l.text.slice(0,80)}))};return E(q,(l,j)=>{const S=l.candidates.map(L=>` ${j.bullet} [${L.kind}] ${L.text}`).join(`
27
+ `);return T(j.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}]`:""}.`)+(S?`
28
28
  ${S}`:"")+`
29
29
 
30
- Approve/reject with wyrm_review.`})}},{name:"wyrm_distill",description:"Distill a work session into candidate memory artifacts for review. Parses the session's objectives, decisions, and outcomes into structured artifacts (lessons, patterns, anti-patterns) and queues them for approval via wyrm_review. Use at session end to extract institutional knowledge.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root path"},sessionId:{type:"string",description:"Session ID to distill"},candidates:{type:"array",description:"Pre-parsed candidate artifacts to store for review",items:{type:"object",properties:{kind:{type:"string",enum:["lesson","pattern","anti_pattern","heuristic","reasoning_trace"]},title:{type:"string"},content:{type:"string"},tags:{type:"array",items:{type:"string"}},confidence:{type:"number"}},required:["kind","title","content"]}}},required:["projectPath","candidates"]},outputSchema:{type:"object",properties:{count:{type:"integer"},artifacts:{type:"array",items:{type:"object",properties:{id:{type:"integer"},kind:{type:"string"},title:{type:"string"}},required:["id","kind","title"]}}},required:["count","artifacts"]},annotations:D.wyrm_distill,aliases:[],handler:($,{store:w,memory:I})=>{const{projectPath:b,candidates:m}=$,_=w.getProject(b);if(!_)return{content:[{type:"text",text:`Project not found: ${b}`}],isError:!0};if(!m||m.length===0)return{content:[{type:"text",text:`**Distill**
30
+ Approve/reject with wyrm_review.`})}},{name:"wyrm_distill",description:"Distill a work session into candidate memory artifacts for review. Parses the session's objectives, decisions, and outcomes into structured artifacts (lessons, patterns, anti-patterns) and queues them for approval via wyrm_review. Use at session end to extract institutional knowledge.",inputSchema:{type:"object",properties:{projectPath:{type:"string",description:"Project root path"},sessionId:{type:"string",description:"Session ID to distill"},candidates:{type:"array",description:"Pre-parsed candidate artifacts to store for review",items:{type:"object",properties:{kind:{type:"string",enum:["lesson","pattern","anti_pattern","heuristic","reasoning_trace"]},title:{type:"string"},content:{type:"string"},tags:{type:"array",items:{type:"string"}},confidence:{type:"number"}},required:["kind","title","content"]}}},required:["projectPath","candidates"]},outputSchema:{type:"object",properties:{count:{type:"integer"},artifacts:{type:"array",items:{type:"object",properties:{id:{type:"integer"},kind:{type:"string"},title:{type:"string"}},required:["id","kind","title"]}}},required:["count","artifacts"]},annotations:D.wyrm_distill,aliases:[],handler:(m,{store:y,memory:$})=>{const{projectPath:_,candidates:u}=m,f=y.getProject(_);if(!f)return{content:[{type:"text",text:`Project not found: ${_}`}],isError:!0};if(!u||u.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 o=[];for(const n of m){const d=I.add(_.id,{kind:n.kind,problem:n.title,validatedFix:n.content,tags:n.tags??[],confidence:n.confidence??.7,needsReview:1});o.push({id:d.id,kind:n.kind,title:n.title})}const f={count:o.length,artifacts:o};return E(f,(n,d)=>{let h=T(d.brand,`**Distillation Complete** -- ${n.count} artifact${n.count!==1?"s":""} queued for review`)+`
32
+ No candidates provided. Provide an array of candidate artifacts to distill.`}],isError:!0};const n=[];for(const d of u){const a=$.add(f.id,{kind:d.kind,problem:d.title,validatedFix:d.content,tags:d.tags??[],confidence:d.confidence??.7,needsReview:1});n.push({id:a.id,kind:d.kind,title:d.title})}const h={status:"queued_for_review",mode:"session",refs:M("mem",n.map(d=>d.id)),count:n.length,artifacts:n};return E(h,(d,a)=>{let g=T(a.brand,`**Distillation Complete** -- ${d.count} artifact${d.count!==1?"s":""} queued for review`)+`
33
33
 
34
- `;return h+=n.artifacts.map(k=>`${d.bullet} [#${k.id}] **${k.kind}**: ${k.title}`).join(`
35
- `),h+="\n\nUse `wyrm_review` with each ID to approve or reject.",h})}},{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:w,raw:I,memory:b,symbols:m,cache:_})=>{const{projectPath:o,dryRun:f,gitLimit:n,includeCode:d}=$,h=I(),k={existsBySig:(r,l)=>!!h.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(r,"%"+W(l)+"%"),addCandidate:(r,l)=>{const y=b.add(r,{kind:l.kind,problem:l.text,tags:[...l.tags,l.sig],confidence:l.confidence,needsReview:1,createdBy:"harvest"});C(h,{tool:"wyrm_harvest",outcome:"queued",refTable:"mem",refId:y.id,reason:"needs_review \u2014 harvested; review to activate",source:"harvest",projectId:r})},onSkip:r=>{C(h,{tool:"wyrm_harvest",outcome:"dropped",reason:"dedup \u2014 signature already harvested",source:"harvest",projectId:r})}};let a;if(o){const r=w.getProject(o);if(!r)return{content:[{type:"text",text:"Project not found"}],isError:!0};a=[{id:r.id,name:r.name,path:r.path}]}else a=w.getAllProjects(500).map(r=>({id:r.id,name:r.name,path:r.path}));const{reports:i,totalAdded:c,totalSkipped:v}=ne(k,a,{dryRun:f,gitLimit:n,includeCode:d});!f&&c>0&&_.invalidate();let e=null;if(d&&!f){let r=0,l=0,y=0;for(const j of a)try{const p=m.indexProject(j.id,j.path);r+=p.files,l+=p.symbols,y++}catch{}e={symbols:l,projects:y,files:r}}const t=i.filter(r=>r.added>0).sort((r,l)=>l.added-r.added).slice(0,15).map(r=>({project:r.project,added:r.added,skipped:r.skipped})),s=i.flatMap(r=>r.sample??[]).slice(0,6),x={dry_run:!!f,projects_scanned:a.length,added:c,skipped:v,top:t,sample:s,code_symbols:e};return E(x,(r,l)=>{const y=r.code_symbols?`
36
- Indexed ${r.code_symbols.symbols} code symbols across ${r.code_symbols.projects} project(s) (${r.code_symbols.files} files) -> searchable via wyrm_symbol_search.`:"",j=r.top.map(P=>` +${String(P.added).padStart(3)} (skip ${P.skipped}) ${P.project}`).join(`
37
- `),p=r.sample.map(P=>` ${l.bullet} ${P}`).join(`
38
- `);return T(l.brand,`Harvest ${r.dry_run?"(dry run) ":""}-- ${r.added} candidate(s) -> review queue across ${r.projects_scanned} project(s); ${r.skipped} already present.`)+`${y}
39
- ${j}`+(p?`
34
+ `;return g+=d.artifacts.map(w=>`${a.bullet} [#${w.id}] **${w.kind}**: ${w.title}`).join(`
35
+ `),g+="\n\nUse `wyrm_review` with each ID to approve or reject.",g})}},{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:(m,{store:y,raw:$,memory:_,symbols:u,cache:f})=>{const{projectPath:n,dryRun:h,gitLimit:d,includeCode:a}=m,g=$(),w=[],b={existsBySig:(e,k)=>!!g.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(e,"%"+W(k)+"%"),addCandidate:(e,k)=>{const p=_.add(e,{kind:k.kind,problem:k.text,tags:[...k.tags,k.sig],confidence:k.confidence,needsReview:1,createdBy:"harvest"});w.push(p.id),A(g,{tool:"wyrm_harvest",outcome:"queued",refTable:"mem",refId:p.id,reason:"needs_review \u2014 harvested; review to activate",source:"harvest",projectId:e})},onSkip:e=>{A(g,{tool:"wyrm_harvest",outcome:"dropped",reason:"dedup \u2014 signature already harvested",source:"harvest",projectId:e})}};let s;if(n){const e=y.getProject(n);if(!e)return{content:[{type:"text",text:"Project not found"}],isError:!0};s=[{id:e.id,name:e.name,path:e.path}]}else s=y.getAllProjects(500).map(e=>({id:e.id,name:e.name,path:e.path}));const{reports:o,totalAdded:v,totalSkipped:i}=ce(b,s,{dryRun:h,gitLimit:d,includeCode:a});!h&&v>0&&f.invalidate();let t=null;if(a&&!h){let e=0,k=0,p=0;for(const c of s)try{const P=u.indexProject(c.id,c.path);e+=P.files,k+=P.symbols,p++}catch{}t={symbols:k,projects:p,files:e}}const r=o.filter(e=>e.added>0).sort((e,k)=>k.added-e.added).slice(0,15).map(e=>({project:e.project,added:e.added,skipped:e.skipped})),x=o.flatMap(e=>e.sample??[]).slice(0,6),I={status:!h&&v>0?"queued_for_review":"skipped",mode:"artifacts",refs:M("mem",w),dry_run:!!h,projects_scanned:s.length,added:v,skipped:i,top:r,sample:x,code_symbols:t};return E(I,(e,k)=>{const p=e.code_symbols?`
36
+ Indexed ${e.code_symbols.symbols} code symbols across ${e.code_symbols.projects} project(s) (${e.code_symbols.files} files).`:"",c=e.top.map(q=>` +${String(q.added).padStart(3)} (skip ${q.skipped}) ${q.project}`).join(`
37
+ `),P=e.sample.map(q=>` ${k.bullet} ${q}`).join(`
38
+ `);return T(k.brand,`Harvest ${e.dry_run?"(dry run) ":""}-- ${e.added} candidate(s) -> review queue across ${e.projects_scanned} project(s); ${e.skipped} already present.`)+`${p}
39
+ ${c}`+(P?`
40
40
 
41
41
  Sample:
42
- ${p}`:"")+`
42
+ ${P}`:"")+`
43
43
 
44
- Approve/reject with wyrm_review.`})}},{name:"wyrm_import_git",description:"Import a list of commits into the Wyrm memory review queue. Useful for onboarding a project's history or capturing recent work.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},commits:{type:"array",description:"Array of commit objects",items:{type:"object",properties:{message:{type:"string"},diff_summary:{type:"string"},author:{type:"string"},date:{type:"string"}},required:["message"]}},auto_approve:{type:"boolean",description:"Skip review queue and activate immediately (default: false)"}},required:["project_id","commits"]},outputSchema:{type:"object",properties:{captured:{type:"integer"},skipped:{type:"integer"},auto_approved:{type:"boolean"}},required:["captured","skipped","auto_approved"]},annotations:D.wyrm_import_git,aliases:[],handler:($,{store:w,memory:I,raw:b})=>{const{project_id:m,commits:_,auto_approve:o}=$;if(!w.getProjectById(m))return{content:[{type:"text",text:`Project ID ${m} not found.`}],isError:!0};let n=0,d=0;const h=b();for(const a of _){const i=a.message??"";if(/^Merge /i.test(i)){d++;continue}if(/^(chore|bump|release|version)/i.test(i)){d++;continue}const c="gi:"+K("sha1").update(`${i}
45
- ${a.diff_summary??""}`).digest("hex").slice(0,16);if(h.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(m,"%"+W(c)+"%")){d++,C(h,{tool:"wyrm_import_git",outcome:"dropped",reason:"dedup \u2014 this commit was already imported (gi: signature match)",source:"import:git",projectId:m});continue}let v="pattern";/^fix(\(.+\))?:/i.test(i)?v="lesson":/^feat(\(.+\))?:/i.test(i)?v="pattern":/^refactor(\(.+\))?:/i.test(i)&&(v="heuristic");const e=i.split(":")[0]??"commit",t=I.add(m,{kind:v,problem:i,validatedFix:a.diff_summary??"",whyItWorked:`Committed by ${a.author??"unknown"} on ${a.date??"unknown"}`,tags:["git","commit",e.toLowerCase(),c],confidence:.6,needsReview:o?0:1});C(h,{tool:"wyrm_import_git",outcome:o?"stored":"queued",refTable:"mem",refId:t.id,reason:o?void 0:"needs_review \u2014 imported; review to activate",source:"import:git",projectId:m}),n++}return E({captured:n,skipped:d,auto_approved:!!o},(a,i)=>T(i.brand,"**Git Import Complete**")+`
44
+ Approve/reject with wyrm_review.`})}},{name:"wyrm_import_git",description:"Import a list of commits into the Wyrm memory review queue. Useful for onboarding a project's history or capturing recent work.",inputSchema:{type:"object",properties:{project_id:{type:"number",description:"Project ID"},commits:{type:"array",description:"Array of commit objects",items:{type:"object",properties:{message:{type:"string"},diff_summary:{type:"string"},author:{type:"string"},date:{type:"string"}},required:["message"]}},auto_approve:{type:"boolean",description:"Skip review queue and activate immediately (default: false)"}},required:["project_id","commits"]},outputSchema:{type:"object",properties:{captured:{type:"integer"},skipped:{type:"integer"},auto_approved:{type:"boolean"}},required:["captured","skipped","auto_approved"]},annotations:D.wyrm_import_git,aliases:[],handler:(m,{store:y,memory:$,raw:_})=>{const{project_id:u,commits:f,auto_approve:n}=m;if(!y.getProjectById(u))return{content:[{type:"text",text:`Project ID ${u} not found.`}],isError:!0};let d=0,a=0;const g=[],w=_();for(const s of f){const o=s.message??"";if(/^Merge /i.test(o)){a++;continue}if(/^(chore|bump|release|version)/i.test(o)){a++;continue}const v="gi:"+K("sha1").update(`${o}
45
+ ${s.diff_summary??""}`).digest("hex").slice(0,16);if(w.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(u,"%"+W(v)+"%")){a++,A(w,{tool:"wyrm_import_git",outcome:"dropped",reason:"dedup \u2014 this commit was already imported (gi: signature match)",source:"import:git",projectId:u});continue}let i="pattern";/^fix(\(.+\))?:/i.test(o)?i="lesson":/^feat(\(.+\))?:/i.test(o)?i="pattern":/^refactor(\(.+\))?:/i.test(o)&&(i="heuristic");const t=o.split(":")[0]??"commit",r=$.add(u,{kind:i,problem:o,validatedFix:s.diff_summary??"",whyItWorked:`Committed by ${s.author??"unknown"} on ${s.date??"unknown"}`,tags:["git","commit",t.toLowerCase(),v],confidence:.6,needsReview:n?0:1});g.push(r.id),A(w,{tool:"wyrm_import_git",outcome:n?"stored":"queued",refTable:"mem",refId:r.id,reason:n?void 0:"needs_review \u2014 imported; review to activate",source:"import:git",projectId:u}),d++}const b={status:d===0?"skipped":n?"captured":"queued_for_review",mode:"import",refs:M("mem",g),captured:d,skipped:a,auto_approved:!!n};return E(b,(s,o)=>T(o.brand,"**Git Import Complete**")+`
46
46
 
47
- ${i.bullet} **Captured:** ${a.captured}
48
- ${i.bullet} **Skipped:** ${a.skipped} (merges/chores)
49
- ${i.bullet} **Review needed:** ${a.auto_approved?"No (auto-approved)":`Yes -- run \`wyrm_review\` to activate ${a.captured} artifact${a.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:w,memory:I,raw:b})=>{const{project_id:m,title:_,body:o,review_comments:f,auto_approve:n}=$;if(!w.getProjectById(m))return{content:[{type:"text",text:`Project ID ${m} not found.`}],isError:!0};let h=0,k=0;const a=n?0:1,i=b(),c=(e,t,s)=>{const x="pr:"+K("sha1").update(t).digest("hex").slice(0,16);if(i.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(m,"%"+W(x)+"%")){k++,C(i,{tool:"wyrm_import_pr",outcome:"dropped",reason:"dedup \u2014 already imported (pr: signature)",source:"import:pr",projectId:m});return}const r=I.add(m,{kind:e,problem:t,validatedFix:"",whyItWorked:"",tags:[...s,x],confidence:.65,needsReview:a,createdBy:"import:pr"});C(i,{tool:"wyrm_import_pr",outcome:n?"stored":"queued",refTable:"mem",refId:r.id,reason:n?void 0:"needs_review \u2014 imported; review to activate",source:"import:pr",projectId:m}),h++};c("pattern",`${_}
47
+ ${o.bullet} **Captured:** ${s.captured}
48
+ ${o.bullet} **Skipped:** ${s.skipped} (merges/chores)
49
+ ${o.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:D.wyrm_import_pr,aliases:[],handler:(m,{store:y,memory:$,raw:_})=>{const{project_id:u,title:f,body:n,review_comments:h,auto_approve:d}=m;if(!y.getProjectById(u))return{content:[{type:"text",text:`Project ID ${u} not found.`}],isError:!0};let g=0,w=0;const b=[],s=d?0:1,o=_(),v=(t,r,x)=>{const I="pr:"+K("sha1").update(r).digest("hex").slice(0,16);if(o.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(u,"%"+W(I)+"%")){w++,A(o,{tool:"wyrm_import_pr",outcome:"dropped",reason:"dedup \u2014 already imported (pr: signature)",source:"import:pr",projectId:u});return}const e=$.add(u,{kind:t,problem:r,validatedFix:"",whyItWorked:"",tags:[...x,I],confidence:.65,needsReview:s,createdBy:"import:pr"});b.push(e.id),A(o,{tool:"wyrm_import_pr",outcome:d?"stored":"queued",refTable:"mem",refId:e.id,reason:d?void 0:"needs_review \u2014 imported; review to activate",source:"import:pr",projectId:u}),g++};v("pattern",`${f}
50
50
 
51
- ${o}`,["git","pr"]);for(const e of f??[])/\b(should|must|always|never|prefer|avoid|use|don't)\b/i.test(e)&&c("heuristic",e,["git","pr","review"]);return E({created:h,skipped:k,auto_approved:!!n},(e,t)=>T(t.brand,"**PR Import Complete**")+`
51
+ ${n}`,["git","pr"]);for(const t of h??[])/\b(should|must|always|never|prefer|avoid|use|don't)\b/i.test(t)&&v("heuristic",t,["git","pr","review"]);const i={status:g===0?"skipped":d?"captured":"queued_for_review",mode:"import",refs:M("mem",b),created:g,skipped:w,auto_approved:!!d};return E(i,(t,r)=>T(r.brand,"**PR Import Complete**")+`
52
52
 
53
- ${t.bullet} **Artifacts created:** ${e.created}
54
- ${t.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:w,memory:I,truths:b,raw:m})=>{const{project_id:_,content:o,format:f,source_file:n}=$;if(!w.getProjectById(_))return{content:[{type:"text",text:`Project ID ${_} not found.`}],isError:!0};const h=f??"plain",k=n??"rules",a=["imported",h,k],i=o.split(/\n(?=#)/),c=o.split(/\n\n+/),v=(i.length>=c.length?i:c).map(y=>y.trim()).filter(y=>y.length>=15);let e=0,t=0,s=0;const{isConfigShapedTruth:x}=await import("../metabolize.js"),r=m();for(const y of v){const j=y.slice(0,50).replace(/\n/g," ");if(/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(y)&&!x(j,y)){const p=b.set(_,{category:"constraint",key:j,value:y,source:k});C(r,{tool:"wyrm_import_rules",outcome:"stored",refTable:"truth",refId:p.id,source:"import:rules",projectId:_}),e++}else{const p=I.add(_,{kind:"heuristic",problem:y,validatedFix:"",whyItWorked:"",tags:a,confidence:.7,needsReview:1,createdBy:"import:rules"});x(j,y)&&s++,C(r,{tool:"wyrm_import_rules",outcome:"queued",refTable:"mem",refId:p.id,reason:x(j,y)?"truth-shape lint \u2014 config shape routed to review":"needs_review \u2014 imported; review to activate",source:"import:rules",projectId:_}),t++}}return E({format:h,source:k,truths_created:e,artifacts_created:t,linted:s},(y,j)=>T(j.brand,`**Rules Import Complete** (${y.format})`)+`
53
+ ${r.bullet} **Artifacts created:** ${t.created}
54
+ ${r.bullet} **Review needed:** ${t.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(m,{store:y,memory:$,truths:_,raw:u})=>{const{project_id:f,content:n,format:h,source_file:d}=m;if(!y.getProjectById(f))return{content:[{type:"text",text:`Project ID ${f} not found.`}],isError:!0};const g=h??"plain",w=d??"rules",b=["imported",g,w],s=n.split(/\n(?=#)/),o=n.split(/\n\n+/),v=(s.length>=o.length?s:o).map(p=>p.trim()).filter(p=>p.length>=15);let i=0,t=0,r=0;const x=[],{isConfigShapedTruth:I}=await import("../metabolize.js"),e=u();for(const p of v){const c=p.slice(0,50).replace(/\n/g," ");if(/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(p)&&!I(c,p)){const P=_.set(f,{category:"constraint",key:c,value:p,source:w});A(e,{tool:"wyrm_import_rules",outcome:"stored",refTable:"truth",refId:P.id,source:"import:rules",projectId:f}),x.push(`truth:${P.id}`),i++}else{const P=$.add(f,{kind:"heuristic",problem:p,validatedFix:"",whyItWorked:"",tags:b,confidence:.7,needsReview:1,createdBy:"import:rules"});x.push(`mem:${P.id}`),I(c,p)&&r++,A(e,{tool:"wyrm_import_rules",outcome:"queued",refTable:"mem",refId:P.id,reason:I(c,p)?"truth-shape lint \u2014 config shape routed to review":"needs_review \u2014 imported; review to activate",source:"import:rules",projectId:f}),t++}}const k={status:t>0?"queued_for_review":i>0?"captured":"skipped",mode:"import",refs:x,format:g,source:w,truths_created:i,artifacts_created:t,linted:r};return E(k,(p,c)=>T(c.brand,`**Rules Import Complete** (${p.format})`)+`
55
55
 
56
- ${j.bullet} **Ground truths created:** ${y.truths_created} (active immediately)
57
- ${j.bullet} **Memory artifacts created:** ${y.artifacts_created} (pending review)
58
- ${j.bullet} **Source:** ${y.source}
56
+ ${c.bullet} **Ground truths created:** ${p.truths_created} (active immediately)
57
+ ${c.bullet} **Memory artifacts created:** ${p.artifacts_created} (pending review)
58
+ ${c.bullet} **Source:** ${p.source}
59
59
 
60
- Run \`wyrm_review\` to approve the memory artifacts.`)}},{name:"wyrm_spec_register",description:"Make spec-kit Wyrm-native. Reads a spec directory (spec.md title/summary + tasks.md task list) and creates one Wyrm quest per task, linked to a project, with a stored spec\u2192project link. Idempotent \u2014 re-running updates the same quests (deduped by a per-spec-task signature) instead of duplicating.",inputSchema:{type:"object",properties:{specDir:{type:"string",description:"Absolute path to the spec directory (e.g. '.../dragon-platform/specs/001-ghostmesh')"},projectPath:{type:"string",description:"Path of the Wyrm project to attach the spec + quests to (must already be registered)"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Priority for the generated quests (default 'medium')"}},required:["specDir","projectPath"]},outputSchema:{type:"object",properties:{spec_dir:{type:"string"},title:{type:["string","null"]},project:{type:"string"},tasks_parsed:{type:"integer"},quests_created:{type:"integer"},quests_updated:{type:"integer"},quest_ids:{type:"array",items:{type:"integer"}}},required:["spec_dir","title","project","tasks_parsed","quests_created","quests_updated","quest_ids"]},annotations:D.wyrm_spec_register,aliases:[],handler:($,{store:w,indexing:I})=>{const{specDir:b,projectPath:m,priority:_}=$,o=["specDir","projectPath"].filter(e=>{const t=$[e];return!t&&t!==0&&t!==!1});if(o.length>0)return{content:[{type:"text",text:`Missing required arguments: ${o.join(", ")}`}],isError:!0};const f=w.getProject(m);if(!f)return{content:[{type:"text",text:`**Spec Register**: Project not found at "${m}". Register it first (wyrm_scan_projects / wyrm_session_start).`}],isError:!0};let n;try{const e=typeof f.path=="string"&&f.path?[f.path]:[];n=U(b,H(e),"wyrm_spec_register.specDir")}catch(e){if(e instanceof V)return R(A("wyrm_spec_register","specDir",e.message));throw e}const d=pe(n);if(d.tasks.length===0){const e={spec_dir:b,title:d.title??null,project:f.name,tasks_parsed:0,quests_created:0,quests_updated:0,quest_ids:[]};return E(e,(t,s)=>T(s.brand,`**Spec Register**: No tasks found in ${z(t.spec_dir,"tasks.md")}. Nothing to create.`))}const h=_||"medium";let k=0,a=0;const i=[];for(const e of d.tasks){const t=le(b,e.id),s=`${e.id}: ${e.title}`,x=t,r=w.findQuestBySpecSignature(f.id,t);if(r)w.updateQuestFields(r.id,{title:s,tags:x}),i.push(r.id),a++;else{const l=w.addQuest(f.id,s,`spec-kit task from ${b}`,h,x);I()?.enqueue("quest",l.id,f.id),i.push(l.id),k++}}const c=w.upsertSpec(f.id,b,d.title,d.summary,d.tasks.length),v={spec_dir:c.spec_dir,title:c.title??null,project:f.name,tasks_parsed:d.tasks.length,quests_created:k,quests_updated:a,quest_ids:i};return E(v,(e,t)=>{let s=T(t.brand,"**Spec Registered**")+`
60
+ Run \`wyrm_review\` to approve the memory artifacts.`)}},{name:"wyrm_spec_register",description:"Make spec-kit Wyrm-native. Reads a spec directory (spec.md title/summary + tasks.md task list) and creates one Wyrm quest per task, linked to a project, with a stored spec\u2192project link. Idempotent \u2014 re-running updates the same quests (deduped by a per-spec-task signature) instead of duplicating.",inputSchema:{type:"object",properties:{specDir:{type:"string",description:"Absolute path to the spec directory (e.g. '.../dragon-platform/specs/001-ghostmesh')"},projectPath:{type:"string",description:"Path of the Wyrm project to attach the spec + quests to (must already be registered)"},priority:{type:"string",enum:["critical","high","medium","low"],description:"Priority for the generated quests (default 'medium')"}},required:["specDir","projectPath"]},outputSchema:{type:"object",properties:{spec_dir:{type:"string"},title:{type:["string","null"]},project:{type:"string"},tasks_parsed:{type:"integer"},quests_created:{type:"integer"},quests_updated:{type:"integer"},quest_ids:{type:"array",items:{type:"integer"}}},required:["spec_dir","title","project","tasks_parsed","quests_created","quests_updated","quest_ids"]},annotations:D.wyrm_spec_register,aliases:[],handler:(m,{store:y,indexing:$})=>{const{specDir:_,projectPath:u,priority:f}=m,n=["specDir","projectPath"].filter(i=>{const t=m[i];return!t&&t!==0&&t!==!1});if(n.length>0)return{content:[{type:"text",text:`Missing required arguments: ${n.join(", ")}`}],isError:!0};const h=y.getProject(u);if(!h)return{content:[{type:"text",text:`**Spec Register**: Project not found at "${u}". Register it first (wyrm_project action=scan, or wyrm_session action=start).`}],isError:!0};let d;try{const i=typeof h.path=="string"&&h.path?[h.path]:[];d=U(_,H(i),"wyrm_spec_register.specDir")}catch(i){if(i instanceof V)return R("wyrm_spec_register","specDir",i.message);throw i}const a=me(d);if(a.tasks.length===0){const i={status:"skipped",mode:"spec",refs:[],spec_dir:_,title:a.title??null,project:h.name,tasks_parsed:0,quests_created:0,quests_updated:0,quest_ids:[]};return E(i,(t,r)=>T(r.brand,`**Spec Register**: No tasks found in ${re(t.spec_dir,"tasks.md")}. Nothing to create.`))}const g=f||"medium";let w=0,b=0;const s=[];for(const i of a.tasks){const t=ye(_,i.id),r=`${i.id}: ${i.title}`,x=t,I=y.findQuestBySpecSignature(h.id,t);if(I)y.updateQuestFields(I.id,{title:r,tags:x}),s.push(I.id),b++;else{const e=y.addQuest(h.id,r,`spec-kit task from ${_}`,g,x);$()?.enqueue("quest",e.id,h.id),s.push(e.id),w++}}const o=y.upsertSpec(h.id,_,a.title,a.summary,a.tasks.length),v={status:"captured",mode:"spec",refs:M("quest",s),spec_dir:o.spec_dir,title:o.title??null,project:h.name,tasks_parsed:a.tasks.length,quests_created:w,quests_updated:b,quest_ids:s};return E(v,(i,t)=>{let r=T(t.brand,"**Spec Registered**")+`
61
61
 
62
- `;return s+=`Spec: ${e.title||"(untitled)"}
63
- `,c.summary&&(s+=`Summary: ${c.summary}
64
- `),s+=`Dir: ${e.spec_dir}
65
- `,s+=`Project: ${e.project}
66
- `,s+=`Tasks parsed: ${e.tasks_parsed}
67
- `,s+=`Quests created: ${e.quests_created} - updated: ${e.quests_updated}
68
- `,s+=`
62
+ `;return r+=`Spec: ${i.title||"(untitled)"}
63
+ `,o.summary&&(r+=`Summary: ${o.summary}
64
+ `),r+=`Dir: ${i.spec_dir}
65
+ `,r+=`Project: ${i.project}
66
+ `,r+=`Tasks parsed: ${i.tasks_parsed}
67
+ `,r+=`Quests created: ${i.quests_created} - updated: ${i.quests_updated}
68
+ `,r+=`
69
69
  \`\`\`json
70
- ${JSON.stringify({spec:e.spec_dir,title:e.title,project:e.project,tasksParsed:e.tasks_parsed,questsCreated:e.quests_created,questsUpdated:e.quests_updated,questIds:e.quest_ids},null,2)}
71
- \`\`\``,s})}},{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:w,scaffolds:I,cache:b})=>{const{projectPath:m,problemType:_,description:o,whenToUse:f,steps:n,verificationSteps:d,doNotApplyIf:h,tags:k}=$,a=m?w.getProject(m)?.id??void 0:void 0,i=I.save({projectId:a,problemType:_,description:o,whenToUse:f,steps:n,verificationSteps:d??void 0,doNotApplyIf:h?[h]:void 0,tags:k??[]});b.invalidate("wyrm_scaffold_get"),b.invalidate("wyrm_context_build");const c={id:i.id,problem_type:_,description:o,steps:n.length};return E(c,(v,e)=>T(e.brand,"**Reasoning Scaffold Saved**")+`
70
+ ${JSON.stringify({spec:i.spec_dir,title:i.title,project:i.project,tasksParsed:i.tasks_parsed,questsCreated:i.quests_created,questsUpdated:i.quests_updated,questIds:i.quest_ids},null,2)}
71
+ \`\`\``,r})}},{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:(m,{store:y,scaffolds:$,cache:_})=>{const{projectPath:u,problemType:f,description:n,whenToUse:h,steps:d,verificationSteps:a,doNotApplyIf:g,tags:w}=m,b=u?y.getProject(u)?.id??void 0:void 0,s=$.save({projectId:b,problemType:f,description:n,whenToUse:h,steps:d,verificationSteps:a??void 0,doNotApplyIf:g?[g]:void 0,tags:w??[]});_.invalidate("wyrm_scaffold_get"),_.invalidate("wyrm_context_build");const o={status:"captured",mode:"checklist",refs:M("scaffold",[s.id]),id:s.id,problem_type:f,description:n,steps:d.length};return E(o,(v,i)=>T(i.brand,"**Reasoning Scaffold Saved**")+`
72
72
 
73
- ${e.bullet} **Problem Type:** ${v.problem_type}
74
- ${e.bullet} **Description:** ${v.description}
75
- ${e.bullet} **Steps:** ${v.steps} checklist items
76
- ${e.bullet} **ID:** ${v.id}
73
+ ${i.bullet} **Problem Type:** ${v.problem_type}
74
+ ${i.bullet} **Description:** ${v.description}
75
+ ${i.bullet} **Steps:** ${v.steps} checklist items
76
+ ${i.bullet} **ID:** ${v.id}
77
77
 
78
- This scaffold will be surfaced by \`wyrm_context_build\` when tasks match "${v.problem_type}".`)}}];export{Ee as captureToolSpecs};
78
+ This scaffold will be surfaced by \`wyrm_context_build\` when tasks match "${v.problem_type}".`)}}];export{De as captureToolSpecs,he as truthMayConflict};
@@ -1,9 +1,9 @@
1
- import{TOOL_ANNOTATIONS as u}from"../tool-annotations.js";import{staleFoundationWarning as y}from"../causality.js";import{refreshThread as h}from"../thread-assemble.js";const b=[{name:"wyrm_decided_because",description:"Use to link a choice or decision to the assumption or evidence it was based on - records a causal edge (truth/quest/artifact/session) so stale foundations invalidate downstream.",inputSchema:{type:"object",properties:{projectPath:{type:"string"},from_kind:{type:"string",enum:["truth","artifact","quest","session","data"]},from_id:{type:"number"},to_kind:{type:"string",enum:["truth","artifact","quest","session","data"]},to_id:{type:"number"},relation:{type:"string",enum:["because_of","supersedes","refutes","verifies"],description:"Default because_of"},rationale:{type:"string",description:"Why"},confidence:{type:"number",description:"0-1, default 1.0"}},required:["projectPath","from_kind","from_id","to_kind","to_id"]},annotations:u.wyrm_decided_because,aliases:[],handler:async(a,d)=>{const{causality:r,db:o}=d,{projectPath:i,from_kind:e,from_id:s,to_kind:t,to_id:c,relation:n,rationale:m,confidence:f}=a,p=o.getProject(i);if(!p)return{content:[{type:"text",text:"Project not found"}],isError:!0};const l=r.link({project_id:p.id,from_kind:e,from_id:s,to_kind:t,to_id:c,relation:n,rationale:m,confidence:f});return h(o.getDatabase(),p.id),{content:[{type:"text",text:`\u{F115D} Edge #${l.id} \u2014 ${e}#${s} ${l.relation} ${t}#${c}`}]}}},{name:"wyrm_decision_downstream",description:"List all decisions that depend on the given source. Use before invalidating a truth to see the blast radius.",inputSchema:{type:"object",properties:{kind:{type:"string",enum:["truth","artifact","quest","session","data"]},id:{type:"number"}},required:["kind","id"]},annotations:u.wyrm_decision_downstream,aliases:[],handler:async(a,d)=>{const{causality:r}=d,{kind:o,id:i}=a,e=r.downstreamOf(o,i);if(e.length===0)return{content:[{type:"text",text:`\u{F115D} No active dependents on ${o}#${i}.`}]};const s=e.map(t=>`\u2022 ${t.from_kind}#${t.from_id} (${t.relation}, conf ${t.confidence})${t.rationale?` \u2014 ${t.rationale}`:""}`).join(`
2
- `);return{content:[{type:"text",text:`\u{F115D} ${e.length} dependent(s):
3
- ${s}`}]}}},{name:"wyrm_decision_upstream",description:"List all sources a decision was based on (incoming edges). Walks the 'why did we choose this?' chain.",inputSchema:{type:"object",properties:{kind:{type:"string",enum:["truth","artifact","quest","session","data"]},id:{type:"number"}},required:["kind","id"]},annotations:u.wyrm_decision_upstream,aliases:[],handler:async(a,d)=>{const{causality:r}=d,{kind:o,id:i}=a,e=r.upstreamOf(o,i),s=y(r.staleFoundations(o,i)),t=s?`${s}
1
+ import{TOOL_ANNOTATIONS as u}from"../tool-annotations.js";import{staleFoundationWarning as k}from"../causality.js";import{refreshThread as b}from"../thread-assemble.js";import{ValidationError as w,asEnum as p,asNumber as x,asString as v,requireInt as _}from"../validate.js";import{requireProjectFromArg as j}from"./project-arg.js";const y=["truth","artifact","quest","session","data"],q=["because_of","supersedes","refutes","verifies"];function h(r,s){if(s===void 0)throw new w(r,"is required");return s}const P=[{name:"wyrm_decided_because",description:"Use to link a choice or decision to the assumption or evidence it was based on - records a causal edge (truth/quest/artifact/session) so stale foundations invalidate downstream.",inputSchema:{type:"object",properties:{projectPath:{type:"string"},from_kind:{type:"string",enum:["truth","artifact","quest","session","data"]},from_id:{type:"number"},to_kind:{type:"string",enum:["truth","artifact","quest","session","data"]},to_id:{type:"number"},relation:{type:"string",enum:["because_of","supersedes","refutes","verifies"],description:"Default because_of"},rationale:{type:"string",description:"Why"},confidence:{type:"number",description:"0-1, default 1.0"}},required:["projectPath","from_kind","from_id","to_kind","to_id"]},annotations:u.wyrm_decided_because,aliases:[],handler:async(r,s)=>{const{causality:d,db:o}=s,t=r,n=h("from_kind",p("from_kind",t.from_kind,y)),a=_("from_id",t.from_id,{min:1}),e=h("to_kind",p("to_kind",t.to_kind,y)),c=_("to_id",t.to_id,{min:1}),i=p("relation",t.relation,q),$=v("rationale",t.rationale),g=x("confidence",t.confidence,{min:0,max:1}),m=j(o,o.getDatabase(),t.projectPath);if(!m)return{content:[{type:"text",text:`Project not found: ${String(t.projectPath)}`}],isError:!0};const{edge:f,created:l}=d.linkOnce({project_id:m.id,from_kind:n,from_id:a,to_kind:e,to_id:c,relation:i,rationale:$,confidence:g});return l&&b(o.getDatabase(),m.id),{content:[{type:"text",text:`\u{F115D} Edge #${f.id} \u2014 ${n}#${a} ${f.relation} ${e}#${c}${l?"":" (already recorded)"}`}]}}},{name:"wyrm_decision_downstream",description:"List all decisions that depend on the given source. Use before invalidating a truth to see the blast radius.",inputSchema:{type:"object",properties:{kind:{type:"string",enum:["truth","artifact","quest","session","data"]},id:{type:"number"}},required:["kind","id"]},annotations:u.wyrm_decision_downstream,aliases:[],handler:async(r,s)=>{const{causality:d}=s,{kind:o,id:t}=r,n=d.downstreamOf(o,t);if(n.length===0)return{content:[{type:"text",text:`\u{F115D} No active dependents on ${o}#${t}.`}]};const a=n.map(e=>`\u2022 ${e.from_kind}#${e.from_id} (${e.relation}, conf ${e.confidence})${e.rationale?` \u2014 ${e.rationale}`:""}`).join(`
2
+ `);return{content:[{type:"text",text:`\u{F115D} ${n.length} dependent(s):
3
+ ${a}`}]}}},{name:"wyrm_decision_upstream",description:"List all sources a decision was based on (incoming edges). Walks the 'why did we choose this?' chain.",inputSchema:{type:"object",properties:{kind:{type:"string",enum:["truth","artifact","quest","session","data"]},id:{type:"number"}},required:["kind","id"]},annotations:u.wyrm_decision_upstream,aliases:[],handler:async(r,s)=>{const{causality:d}=s,{kind:o,id:t}=r,n=d.upstreamOf(o,t),a=k(d.staleFoundations(o,t)),e=a?`${a}
4
4
 
5
- `:"";if(e.length===0)return{content:[{type:"text",text:`${t}\u{F115D} No recorded basis for ${o}#${i}.`}]};const c=e.map(n=>`\u2022 ${n.to_kind}#${n.to_id} (${n.relation}, conf ${n.confidence})${n.rationale?` \u2014 ${n.rationale}`:""}`).join(`
6
- `);return{content:[{type:"text",text:`${t}\u{F115D} ${e.length} basis edge(s):
7
- ${c}`}]}}},{name:"wyrm_decision_invalidate",description:"Cascade-invalidate all decisions downstream of a source (recursive). Use when a foundational truth turns out to be wrong. Returns the set of affected (kind, id) pairs.",inputSchema:{type:"object",properties:{kind:{type:"string",enum:["truth","artifact","quest","session","data"]},id:{type:"number"},reason:{type:"string",description:"Why the source was invalidated"}},required:["kind","id"]},annotations:u.wyrm_decision_invalidate,aliases:[],handler:async(a,d)=>{const{causality:r}=d,o=a||{},{kind:i,id:e,reason:s}=a,t=r.invalidateDownstream(i,e,s);if(t.invalidated===0)return{content:[{type:"text",text:`\u{F115D} No dependents to invalidate from ${i}#${e}.`}]};const c=t.affected.map(n=>`\u2022 ${n.kind}#${n.id} (edge #${n.edge_id})`).join(`
8
- `);return{content:[{type:"text",text:`\u{F115D} Invalidated ${t.invalidated} downstream decision(s):
9
- ${c}`}]}}}];export{b as causalityToolSpecs};
5
+ `:"";if(n.length===0)return{content:[{type:"text",text:`${e}\u{F115D} No recorded basis for ${o}#${t}.`}]};const c=n.map(i=>`\u2022 ${i.to_kind}#${i.to_id} (${i.relation}, conf ${i.confidence})${i.rationale?` \u2014 ${i.rationale}`:""}`).join(`
6
+ `);return{content:[{type:"text",text:`${e}\u{F115D} ${n.length} basis edge(s):
7
+ ${c}`}]}}},{name:"wyrm_decision_invalidate",description:"Cascade-invalidate all decisions downstream of a source (recursive). Use when a foundational truth turns out to be wrong. Returns the set of affected (kind, id) pairs.",inputSchema:{type:"object",properties:{kind:{type:"string",enum:["truth","artifact","quest","session","data"]},id:{type:"number"},reason:{type:"string",description:"Why the source was invalidated"}},required:["kind","id"]},annotations:u.wyrm_decision_invalidate,aliases:[],handler:async(r,s)=>{const{causality:d}=s,o=r||{},{kind:t,id:n,reason:a}=r,e=d.invalidateDownstream(t,n,a);if(e.invalidated===0)return{content:[{type:"text",text:`\u{F115D} No dependents to invalidate from ${t}#${n}.`}]};const c=e.affected.map(i=>`\u2022 ${i.kind}#${i.id} (edge #${i.edge_id})`).join(`
8
+ `);return{content:[{type:"text",text:`\u{F115D} Invalidated ${e.invalidated} downstream decision(s):
9
+ ${c}`}]}}}];export{P as causalityToolSpecs};