wyrm-mcp 8.7.0 → 8.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/memory-artifacts.js +18 -18
- package/dist/tool-manifest-v2.json +1 -1
- package/dist/tool-manifest.json +1 -1
- package/dist/wyrm-cli.js +54 -54
- package/dist/wyrm-manifest.json +1 -1
- package/package.json +1 -1
package/dist/memory-artifacts.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{emitEvent as
|
|
1
|
+
import{emitEvent as de}from"./events.js";import{sanitizeFtsQuery as j,buildFtsMatchQuery as G}from"./security.js";import{getActor as le}from"./handlers/boundary.js";import{buildPage as fe,DEFAULT_PAGE_SIZE as ue}from"./keyset.js";import{rerankConfigured as me,rerankCandidates as he}from"./rerank.js";import{autoSummaryPenalty as z,recallRecencyWeight as X,recallRecencyHalfLifeDays as J,recencyMultiplier as Q,extractTemporalWindow as Z,recallTemporalWeight as q,temporalMultiplier as ee,recallUsefulnessWeight as te,usefulnessMultiplier as ne,looksInjectionShaped as _e,trustMarker as pe}from"./context-ranking.js";import{queryGraphContext as Ee,graphMultiplier as ge,recallGraphWeight as Se}from"./graph-recall.js";import{populateEntities as Re}from"./entity-populate.js";import{resolvePolicy as B,mutePredicateSql as se,truthIsChallenged as Ae,classifyArtifact as Ne}from"./recall-policy.js";const ie=40,ye=10,we=.3,re="auto_approve",Y=new WeakMap;function Ce(W){if(/^(1|true|yes|on)$/i.test(process.env.WYRM_AUTO_APPROVE??""))return!0;const t=Y.get(W),e=Date.now();if(t&&e-t.at<5e3)return t.on;let n=!1;try{n=W.prepare("SELECT value FROM wyrm_meta WHERE key = ?").get(re)?.value==="1"}catch{n=!1}return Y.set(W,{at:e,on:n}),n}function We(W,t){W.prepare("INSERT INTO wyrm_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(re,t?"1":"0"),Y.delete(W)}class $e{db;vectorStore;setVectorStore(t){this.vectorStore=t}getVectorStore(){return this.vectorStore}constructor(t){this.db=t}indexArtifact(t){if(!this.vectorStore)return;const e=`${t.problem}${t.validated_fix?" "+t.validated_fix:""}`.slice(0,2e3);this.vectorStore.addVector(e,"artifact",t.id,t.project_id).catch(()=>{})}add(t,e){if(typeof e.problem!="string"||!e.problem.trim())throw new Error("memory.add: 'problem' is required (a non-empty string).");const n=e.tags?.length?e.tags.join(","):null,s=le(),c=e.createdBy??"local",i=e.sourceTrust??(c.startsWith("bridge:")?"operator":c.startsWith("import:")||(n??"").includes("imported_from:")?"imported":"agent");let r=e.needsReview??0,a=null;if(r===0&&i==="agent"&&s.agent_id&&(process.env.WYRM_PROBATION??"")==="1"){const m=Number(process.env.WYRM_PROBATION_HOURS),o=Number.isFinite(m)&&m>=1?m:24,E=this.db.prepare("SELECT MIN(created_at) AS f FROM memory_artifacts WHERE agent_id = ?").get(s.agent_id),N=E.f?new Date(E.f.replace(" ","T")+"Z").getTime():NaN;(!Number.isFinite(N)||Date.now()-N<o*36e5)&&(r=1,a="probation")}r===1&&Ce(this.db)&&(r=0,a=null);const p=a?n?`${n},${a}`:a:n,f=this.db.prepare(`
|
|
2
2
|
INSERT INTO memory_artifacts
|
|
3
3
|
(project_id, kind, problem, constraints, validated_fix, why_it_worked,
|
|
4
4
|
outcome, source_session_id, tags, confidence, needs_review, created_by, agent_id, run_id, source_trust)
|
|
5
5
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
6
|
-
`).run(t,e.kind,e.problem.trim(),e.constraints?.trim()??null,e.validatedFix?.trim()??null,e.whyItWorked?.trim()??null,e.outcome??"neutral",e.sourceSessionId??null,p,e.confidence??1,r,c,s.agent_id,s.run_id,i),h=this.get(f.lastInsertRowid);if(!r){
|
|
7
|
-
`+h.validated_fix:""}`;
|
|
6
|
+
`).run(t,e.kind,e.problem.trim(),e.constraints?.trim()??null,e.validatedFix?.trim()??null,e.whyItWorked?.trim()??null,e.outcome??"neutral",e.sourceSessionId??null,p,e.confidence??1,r,c,s.agent_id,s.run_id,i),h=this.get(f.lastInsertRowid);if(!r){de(this.db,{projectId:t,kind:"capture",refTable:"memory_artifacts",refId:h.id,isShared:!!h.is_shared}),this.indexArtifact(h);try{const m=`${h.problem}${h.validated_fix?`
|
|
7
|
+
`+h.validated_fix:""}`;Re(this.db,t,m,`mem:${h.id}`)}catch{}}return h}get(t){return this.db.prepare("SELECT * FROM memory_artifacts WHERE id = ?").get(t)??null}update(t,e){return this.db.prepare(`
|
|
8
8
|
UPDATE memory_artifacts SET
|
|
9
9
|
confidence = COALESCE(?, confidence),
|
|
10
10
|
validated_fix = COALESCE(?, validated_fix),
|
|
@@ -23,7 +23,7 @@ import{emitEvent as ae}from"./events.js";import{sanitizeFtsQuery as Y,buildFtsMa
|
|
|
23
23
|
END,
|
|
24
24
|
updated_at = datetime('now')
|
|
25
25
|
WHERE id = ?
|
|
26
|
-
`).run(e?1:0,t)}recall(t,e,n={}){const s=n.limit??10,c=n.minConfidence??0,i=B(this.db,n.runId??null),r=
|
|
26
|
+
`).run(e?1:0,t)}recall(t,e,n={}){const s=n.limit??10,c=n.minConfidence??0,i=B(this.db,n.runId??null),r=se(i),a=this.searchByFts(t,e,ie,n.kind,c,r),p=this.searchByTags(t,e,ie,n.kind,c,r),f=new Set,h=[];a.forEach((o,E)=>{f.add(o.id),h.push({artifact:o,inFts:!0,inTag:!1,ftsRank:E})});for(const o of p)if(!f.has(o.id))f.add(o.id),h.push({artifact:o,inFts:!1,inTag:!0});else{const E=h.find(N=>N.artifact.id===o.id);E&&(E.inTag=!0)}return h.filter(({artifact:o})=>o.confidence>=c).map(({artifact:o,inFts:E,inTag:N,ftsRank:y})=>{let w;if(E){const _=1-(y??0)/(a.length+1);w=(N?.7:.55)+.45*_}else w=.4;w*=o.confidence,o.outcome==="positive"&&(w*=1.1);const D=(Date.now()-new Date(o.last_validated_at).getTime())/(1e3*60*60*24),d=Math.max(.5,1-D/180);return w*=d,{artifact:o,relevance_score:Math.min(1,w),match_type:E&&N?"both":E?"fts":"tag"}}).sort((o,E)=>E.relevance_score-o.relevance_score).slice(0,s)}async recallHybrid(t,e,n={}){const s=n.limit??10,c=n.minConfidence??0,i=B(this.db,n.runId??null),r=se(i),a=n.rerank===!0&&me(),p=Math.min(Math.max(s*2,20),50),f=a?p:s;if(!this.vectorStore)return this.recall(t,e,n);const h=Math.max(50,f*5),m=Date.now(),o=this.searchByFts(t,e,h,n.kind,c,r),E=Date.now()-m,N=Date.now();let y=[];try{y=(await this.vectorStore.search(e,h,t,["artifact"])).map(A=>({id:A.content_id,s:A.similarity}))}catch{}const w=Date.now()-N;if(y.length===0)return this.recall(t,e,n);const D=Date.now(),d=60,_=Number(process.env.WYRM_RERANK_ALPHA),b=Number.isFinite(_)?Math.max(0,Math.min(1,_)):.7,C=new Map;if(process.env.WYRM_RERANK_FUSION==="rrf")o.forEach((u,A)=>C.set(u.id,(C.get(u.id)??0)+1/(d+A+1))),y.forEach((u,A)=>C.set(u.id,(C.get(u.id)??0)+1/(d+A+1)));else{const u=o.length+1;o.forEach((O,oe)=>C.set(O.id,(C.get(O.id)??0)+(1-b)*(1-oe/u)));const A=y.map(O=>O.s),S=Math.min(...A),H=Math.max(...A),F=H-S;y.forEach(O=>C.set(O.id,(C.get(O.id)??0)+b*(F>1e-9?(O.s-S)/F:1)))}const v=new Set(o.map(u=>u.id)),L=new Set(y.map(u=>u.id)),k=new Map(o.map(u=>[u.id,u])),x=[...C.entries()].sort((u,A)=>A[1]-u[1]),l=X(),g=J(),R=q(),T=R>0?Z(e):null,I=te(),M=Se(),U=M>0?Ee(this.db,t,e):null,K=new Date,ae=Math.min(x.length,Math.max(f*4,50)),P=[];for(const[u,A]of x.slice(0,ae)){const S=k.get(u)??this.get(u)??void 0;if(!S||S.confidence<c||S.needs_review===1||S.supersedes_id!=null||n.kind&&S.kind!==n.kind||i.mode==="clean"&&Ne(S)==="prescription"||i.mutedIds.includes(S.id))continue;const H=S.updated_at??S.created_at;let F=A*Q(H,l,g,K);T&&(F*=ee(S.created_at,T,R,K)),F*=ne(S.reuse_count,S.reuse_success_count,I),U&&(F*=ge(`${S.problem} ${S.validated_fix??""}`,U,M)),P.push({id:u,s:F,art:S})}P.sort((u,A)=>A.s-u.s);const ce=P[0]?.s??1,$=[];for(const{id:u,s:A,art:S}of P){if($.length>=f)break;const H=v.has(u)&&L.has(u)?"hybrid":L.has(u)?"vector":"fts";$.push({artifact:S,relevance_score:Math.min(1,A/ce),match_type:H})}const V=Date.now()-D;if(a&&$.length>0){const u=Date.now(),A=await this.rerankResults(e,$);return n.onStats?.({ftsMs:E,vectorMs:w,fusionMs:V,rerankMs:Date.now()-u,candidates:$.length}),A.slice(0,s)}return n.onStats?.({ftsMs:E,vectorMs:w,fusionMs:V,candidates:$.length}),$}async rerankResults(t,e){const n=e.map(a=>({id:a.artifact.id,text:`${a.artifact.problem}${a.artifact.validated_fix?" "+a.artifact.validated_fix:""}`.slice(0,2e3)})),s=await he(t,n);if(!s)return e;const c=new Map(e.map(a=>[a.artifact.id,a])),i=[],r=s.length;return s.forEach((a,p)=>{const f=c.get(a.id);f&&i.push({...f,relevance_score:r>0?(r-p)/r:f.relevance_score})}),i}async recallHybridGlobal(t,e={}){const n=e.limit??10,s=e.minConfidence??0,c=Math.max(50,n*5),i=this.searchByFtsGlobal(t,c,e.kind,s),r=()=>i.slice(0,n).map((l,g)=>({artifact:l,relevance_score:1-g/(i.length+1),match_type:"fts"}));if(!this.vectorStore)return r();let a=[];try{a=(await this.vectorStore.search(t,c,void 0,["artifact"])).map(g=>({id:g.content_id,s:g.similarity}))}catch{}if(a.length===0)return r();const p=60,f=Number(process.env.WYRM_RERANK_ALPHA),h=Number.isFinite(f)?Math.max(0,Math.min(1,f)):.7,m=new Map;if(process.env.WYRM_RERANK_FUSION==="rrf")i.forEach((l,g)=>m.set(l.id,(m.get(l.id)??0)+1/(p+g+1))),a.forEach((l,g)=>m.set(l.id,(m.get(l.id)??0)+1/(p+g+1)));else{const l=i.length+1;i.forEach((M,U)=>m.set(M.id,(m.get(M.id)??0)+(1-h)*(1-U/l)));const g=a.map(M=>M.s),R=Math.min(...g),T=Math.max(...g),I=T-R;a.forEach(M=>m.set(M.id,(m.get(M.id)??0)+h*(I>1e-9?(M.s-R)/I:1)))}const o=new Set(i.map(l=>l.id)),E=new Set(a.map(l=>l.id)),N=new Map(i.map(l=>[l.id,l])),y=[...m.entries()].sort((l,g)=>g[1]-l[1]),w=X(),D=J(),d=q(),_=d>0?Z(t):null,b=te(),C=new Date,v=Math.min(y.length,Math.max(n*4,50)),L=[];for(const[l,g]of y.slice(0,v)){const R=N.get(l)??this.get(l)??void 0;if(!R||R.confidence<s||R.needs_review===1||R.supersedes_id!=null||e.kind&&R.kind!==e.kind)continue;const T=R.updated_at??R.created_at;let I=g*Q(T,w,D,C);_&&(I*=ee(R.created_at,_,d,C)),I*=ne(R.reuse_count,R.reuse_success_count,b),L.push({id:l,s:I,art:R})}L.sort((l,g)=>g.s-l.s);const k=L[0]?.s??1,x=[];for(const{id:l,s:g,art:R}of L){if(x.length>=n)break;const T=o.has(l)&&E.has(l)?"hybrid":E.has(l)?"vector":"fts";x.push({artifact:R,relevance_score:Math.min(1,g/k),match_type:T})}return x}searchByFtsGlobal(t,e,n,s=0){if(!this.db)return[];let c="";try{const a=j(t);c=a?G(a):""}catch{return[]}if(!c)return[];const i=n?"AND a.kind = ?":"",r=[c,s];n&&r.push(n),r.push(e);try{return this.db.prepare(`
|
|
27
27
|
SELECT a.* FROM memory_artifacts a
|
|
28
28
|
JOIN memory_artifacts_fts ON a.id = memory_artifacts_fts.rowid
|
|
29
29
|
WHERE memory_artifacts_fts MATCH ?
|
|
@@ -33,7 +33,7 @@ import{emitEvent as ae}from"./events.js";import{sanitizeFtsQuery as Y,buildFtsMa
|
|
|
33
33
|
${i}
|
|
34
34
|
ORDER BY rank, a.confidence DESC
|
|
35
35
|
LIMIT ?
|
|
36
|
-
`).all(...r)}catch{return[]}}searchByFts(t,e,n,s,c=0,i="1=1"){let r="";try{const f=
|
|
36
|
+
`).all(...r)}catch{return[]}}searchByFts(t,e,n,s,c=0,i="1=1"){let r="";try{const f=j(e);r=f?G(f):""}catch{return this.listRecent(t,n,s,i)}if(!r)return this.listRecent(t,n,s,i);const a=s?"AND a.kind = ?":"",p=[r,t,c];s&&p.push(s),p.push(n);try{return this.db.prepare(`
|
|
37
37
|
SELECT a.* FROM memory_artifacts a
|
|
38
38
|
JOIN memory_artifacts_fts ON a.id = memory_artifacts_fts.rowid
|
|
39
39
|
WHERE memory_artifacts_fts MATCH ?
|
|
@@ -61,29 +61,29 @@ import{emitEvent as ae}from"./events.js";import{sanitizeFtsQuery as Y,buildFtsMa
|
|
|
61
61
|
${c}
|
|
62
62
|
ORDER BY confidence DESC, created_at DESC
|
|
63
63
|
LIMIT ?
|
|
64
|
-
`).all(...i)}buildContextBrief(t,e,n={}){const s=n.kinds??["pattern","heuristic","reasoning_trace","lesson","anti_pattern"],c=n.maxItems??
|
|
65
|
-
_Constraints:_ ${
|
|
66
|
-
_Solution:_ ${
|
|
67
|
-
_Why it worked:_ ${
|
|
68
|
-
_Note: This approach failed \u2014 avoid it_`),
|
|
64
|
+
`).all(...i)}buildContextBrief(t,e,n={}){const s=n.kinds??["pattern","heuristic","reasoning_trace","lesson","anti_pattern"],c=n.maxItems??ye,i=n.minConfidence??we,r=n.runId??null,a=this.recall(t,e,{limit:c*2,minConfidence:i,runId:r});a.sort((d,_)=>(z(d.artifact.problem)>0?1:0)-(z(_.artifact.problem)>0?1:0));const p=[],h=a.filter(d=>{const _=d.artifact.source_trust;return _==="untrusted"||_==="imported"&&_e(`${d.artifact.problem} ${d.artifact.validated_fix??""}`)?(p.push(d.artifact.id),!1):!0}).filter(d=>s.includes(d.artifact.kind)).slice(0,c),m=new Map;for(const d of h){const _=m.get(d.artifact.kind)??[];_.push(d),m.set(d.artifact.kind,_)}const o={pattern:"\u2705 Proven Patterns",heuristic:"\u{1F4A1} Heuristics",reasoning_trace:"\u{1F9E0} Past Reasoning",lesson:"\u{1F4DA} Lessons Learned",anti_pattern:"\u26A0\uFE0F Anti-Patterns to Avoid"},E=["pattern","heuristic","reasoning_trace","lesson","anti_pattern"],N=[],y=[];let w=0;for(const d of E){if(!s.includes(d))continue;const _=m.get(d)??[];if(!_.length)continue;const b=[];for(const C of _){if(w>=c)break;const v=C.artifact;let k=`${pe(v.source_trust)}**Problem:** ${v.problem}`;v.constraints&&(k+=`
|
|
65
|
+
_Constraints:_ ${v.constraints}`),v.validated_fix&&(k+=`
|
|
66
|
+
_Solution:_ ${v.validated_fix}`),v.why_it_worked&&(k+=`
|
|
67
|
+
_Why it worked:_ ${v.why_it_worked}`),v.outcome==="negative"&&(k+=`
|
|
68
|
+
_Note: This approach failed \u2014 avoid it_`),b.push(k),y.push(v.id),w++}b.length&&N.push({heading:o[d],items:b,source:d})}let D="";if(N.length>0){D+=`---
|
|
69
69
|
## \u{F115D} Memory Brief
|
|
70
70
|
_Relevant past knowledge from Wyrm:_
|
|
71
71
|
|
|
72
|
-
`;for(const d of
|
|
73
|
-
`;for(const _ of d.items)
|
|
74
|
-
`;
|
|
75
|
-
`}
|
|
76
|
-
`}if(n.groundTruths){const d=B(this.db,r),_=n.groundTruths.filter(
|
|
72
|
+
`;for(const d of N){D+=`### ${d.heading}
|
|
73
|
+
`;for(const _ of d.items)D+=`- ${_}
|
|
74
|
+
`;D+=`
|
|
75
|
+
`}D+=`---
|
|
76
|
+
`}if(n.groundTruths){const d=B(this.db,r),_=n.groundTruths.filter(b=>!Ae(d,b.id));return{sections:N,text:D,sourceIds:y,groundTruths:_}}return{sections:N,text:D,sourceIds:y}}getStats(t){const e=this.db.prepare("SELECT COUNT(*) as n FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NULL").get(t).n,n=this.db.prepare("SELECT COUNT(*) as n FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NOT NULL").get(t).n,s=this.db.prepare("SELECT AVG(confidence) as v FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NULL").get(t).v??0,c=this.db.prepare("SELECT kind, COUNT(*) as cnt FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NULL GROUP BY kind").all(t),i={};for(const r of c)i[r.kind]=r.cnt;return{total:e,byKind:i,avgConfidence:Math.round(s*100)/100,supersededCount:n}}listAll(t,e={}){const n=e.kind?"AND kind = ?":"",s=e.includeSuperseded?"":"AND supersedes_id IS NULL",c=[t];return e.kind&&c.push(e.kind),c.push(e.limit??50),this.db.prepare(`
|
|
77
77
|
SELECT * FROM memory_artifacts
|
|
78
78
|
WHERE project_id = ? ${n} ${s}
|
|
79
79
|
ORDER BY confidence DESC, created_at DESC
|
|
80
80
|
LIMIT ?
|
|
81
|
-
`).all(...c)}listPage(t,e={pageSize:
|
|
81
|
+
`).all(...c)}listPage(t,e={pageSize:ue}){const n=e.kind?"AND kind = ?":"",s=e.includeSuperseded?"":"AND supersedes_id IS NULL",c="AND needs_review = 0",i=[t];e.kind&&i.push(e.kind);let r="";if(e.after){const f=Number(e.after.sortKey);Number.isFinite(f)&&(r="AND (confidence < ? OR (confidence = ? AND id < ?))",i.push(f,f,e.after.id))}const a=e.pageSize+1;i.push(a);const p=this.db.prepare(`
|
|
82
82
|
SELECT * FROM memory_artifacts
|
|
83
83
|
WHERE project_id = ? ${n} ${s} ${c} ${r}
|
|
84
84
|
ORDER BY confidence DESC, id DESC
|
|
85
85
|
LIMIT ?
|
|
86
|
-
`).all(...i);return
|
|
86
|
+
`).all(...i);return fe(p,e.pageSize,f=>({sortKey:String(f.confidence),id:f.id}))}pruneStale(t={}){const e=t.minConfidence??.3,n=t.olderThanDays??90,s=t.dryRun??!0,c=t.projectId!=null,i=[e,`-${n} days`];c&&i.push(t.projectId);const r=this.db.prepare(`
|
|
87
87
|
SELECT id, kind, problem, confidence, last_accessed_at
|
|
88
88
|
FROM memory_artifacts
|
|
89
89
|
WHERE confidence < ?
|
|
@@ -93,4 +93,4 @@ _Relevant past knowledge from Wyrm:_
|
|
|
93
93
|
${c?"AND project_id = ?":""}
|
|
94
94
|
ORDER BY confidence ASC
|
|
95
95
|
LIMIT 500
|
|
96
|
-
`).all(...i);return s||r.length===0?{candidates:r,deleted:0,dryRun:s}:{candidates:r,deleted:this.deleteArtifacts(r.map(a=>a.id)),dryRun:s}}deleteArtifacts(t){if(t.length===0)return 0;const e=t.map(()=>"?").join(",");return this.db.prepare(`DELETE FROM memory_artifacts WHERE id IN (${e}) AND needs_review = 0`).run(...t).changes}}export{
|
|
96
|
+
`).all(...i);return s||r.length===0?{candidates:r,deleted:0,dryRun:s}:{candidates:r,deleted:this.deleteArtifacts(r.map(a=>a.id)),dryRun:s}}deleteArtifacts(t){if(t.length===0)return 0;const e=t.map(()=>"?").join(",");return this.db.prepare(`DELETE FROM memory_artifacts WHERE id IN (${e}) AND needs_review = 0`).run(...t).changes}}export{$e as MemoryArtifacts,Ce as isAutoApproveOn,We as setAutoApprove};
|
package/dist/tool-manifest.json
CHANGED
package/dist/wyrm-cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{join as W,dirname as X,resolve as Z,basename as We}from"path";import{homedir as le}from"os";import{existsSync as U,readFileSync as H,readdirSync as Ue,rmSync as Fe}from"fs";import{fileURLToPath as ee}from"url";import{spawnSync as te}from"child_process";import{createInterface as oe}from"readline";import{WyrmDB as qe}from"./database.js";import{MemoryArtifacts as B}from"./memory-artifacts.js";import{GroundTruths as de}from"./intelligence.js";import{Causality as be}from"./causality.js";import{wireTruthAutoCascade as
|
|
2
|
+
import{join as W,dirname as X,resolve as Z,basename as We}from"path";import{homedir as le}from"os";import{existsSync as U,readFileSync as H,readdirSync as Ue,rmSync as Fe}from"fs";import{fileURLToPath as ee}from"url";import{spawnSync as te}from"child_process";import{createInterface as oe}from"readline";import{WyrmDB as qe}from"./database.js";import{MemoryArtifacts as B}from"./memory-artifacts.js";import{GroundTruths as de}from"./intelligence.js";import{Causality as be}from"./causality.js";import{wireTruthAutoCascade as ve}from"./truth-cascade.js";import{Rehydration as Ye}from"./rehydration.js";import{makeRenderDeps as $e,buildRenderPlan as ue,renderToDisk as Ve,renderForClient as ke,detectClients as He,ALL_RENDER_CLIENTS as pe,ALL_CLIENT_MARKERS as Be}from"./render-target.js";import{classifyCapture as Ke}from"./capture.js";import{importFrom as Ge,IMPORT_SOURCES as _e}from"./importers.js";import{c as u,colors as F,formatTable as P,printSection as E,printSuccess as $,printError as f,printWarning as Ee,icons as K,readSecret as Je,ReadSecretCanceled as ze}from"./cli.js";import{buildDeterminismReceipt as Qe,attestation as Xe}from"./receipt.js";import{loadConnectorConfigs as Se,upsertConnectorConfig as Ze,runConnector as et,runAllConnectors as tt}from"./connectors/index.js";import{readActor as ot}from"./attribution.js";import{captureHealth as st,captureEffectiveness as rt,recordSnapshot as me,getSnapshots as Re,trendFlags as nt}from"./metrics.js";function A(){try{const d=X(ee(import.meta.url));return JSON.parse(H(W(d,"..","package.json"),"utf-8"))}catch{return{}}}function M(d,c){const o=typeof d=="string"?parseInt(d,10):NaN;return Number.isFinite(o)?o:c}function se(d,c){const o=typeof d=="string"?parseFloat(d):NaN;return Number.isFinite(o)?o:c}function Ce(){return process.env.WYRM_DB_PATH??W(le(),".wyrm","wyrm.db")}function R(){return new qe(Ce())}function j(d){const c=[],o={};let a=0;for(;a<d.length;){const r=d[a];if(r.startsWith("--")){const e=r.slice(2),s=d[a+1];s&&!s.startsWith("--")?(o[e]=s,a+=2):(o[e]=!0,a++)}else c.push(r),a++}return{positional:c,flags:o}}function I(d,c){return c?d.getDatabase().prepare("SELECT * FROM projects WHERE LOWER(name) LIKE LOWER(?) LIMIT 1").get(`%${c}%`)??null:null}async function it(d){const{positional:c,flags:o}=j(d),a=c[0];a||(f("Usage: wyrm search <query> [--project <name>] [--type all|memories|truths|quests|data]"),process.exit(1));const r=console.error;console.error=()=>{};const e=R();try{const s=e.getDatabase(),t=o.type??"all",n=o.project,i=(n?I(e,n):null)?.id;E(`Search: "${a}"`);const l=[];let m=null;if(t==="all"||t==="memories"){const{resolveEmbeddingState:g}=await import("./providers/embedding-provider.js"),h=g(),y=new B(s);if(h.resolved!=="none"){const{createVectorStore:b}=await import("./vectors.js"),C=process.env.WYRM_VECTOR_PROVIDER??"auto",S=b({provider:C},s);y.setVectorStore(S)}let w;const v={limit:20,onStats:b=>{w=b}},k=i!=null?await y.recallHybrid(i,a,v):await y.recallHybridGlobal(a,v);for(const b of k)l.push([`mem:${b.artifact.id}`,"memory",b.artifact.kind,b.artifact.problem.slice(0,80)]);if(h.resolved==="none")m="keyword-only (no vector provider; run: wyrm vectors download)";else{const b=w!==void 0||k.some(L=>L.match_type==="vector"||L.match_type==="hybrid"),C=y.getVectorStore(),S=typeof C?.getProvider=="function"?C.getProvider():void 0;let x=null;if(!b)if(!C||S?.name==="none")x=h.reason||"vector_store_unavailable";else{let L;try{L=C.indexCoverage()}catch{}if(L?.stale)x="stale_index";else{let Y=-1;try{Y=C.getStats().total}catch{}x=Y===0?"empty_index":"embed_error"}}const T=Qe({vectorsAvailable:b,rerankActive:!1,embedModel:b?S?.model??h.model:null,rerankModel:null,embedEgressHost:b?S?.remoteHost??null:null,rerankEgressHost:null,ftsOnlyReason:x});m=Xe(T)}}if(t==="all"||t==="sessions")try{const g=i?`AND s.project_id = ${i}`:"",h=s.prepare(`
|
|
3
3
|
SELECT s.id, s.objectives, s.project_id FROM sessions s
|
|
4
4
|
JOIN sessions_fts fts ON s.id = fts.rowid
|
|
5
5
|
WHERE sessions_fts MATCH ? ${g}
|
|
@@ -14,78 +14,78 @@ import{join as W,dirname as X,resolve as Z,basename as We}from"path";import{home
|
|
|
14
14
|
JOIN data_lake_fts fts ON d.id = fts.rowid
|
|
15
15
|
WHERE data_lake_fts MATCH ? ${g}
|
|
16
16
|
LIMIT 10
|
|
17
|
-
`).all(a);for(const y of h)l.push([`data:${y.id}`,"data",y.category,y.value.slice(0,80)])}catch{}l.length===0?console.log(u.dim(` No results found for "${a}"`)):(console.log(
|
|
18
|
-
${l.length} result${l.length!==1?"s":""}`))),m&&console.log(u.dim(` ${m}`))}finally{e.close(),console.error=
|
|
17
|
+
`).all(a);for(const y of h)l.push([`data:${y.id}`,"data",y.category,y.value.slice(0,80)])}catch{}l.length===0?console.log(u.dim(` No results found for "${a}"`)):(console.log(P(["ID","Type","Subtype","Preview"],l)),console.log(u.dim(`
|
|
18
|
+
${l.length} result${l.length!==1?"s":""}`))),m&&console.log(u.dim(` ${m}`))}finally{e.close(),console.error=r}}async function at(d){const{flags:c}=j(d),o=c.type??"all",a=M(c.limit,20),r=c.project,e=R(),s=e.getDatabase(),n=(r?I(e,r):null)?.id,p=n?`WHERE project_id = ${n}`:"",i=n?`AND project_id = ${n}`:"";if(E("Wyrm Memory"),o==="all"||o==="memories"){E("Memories");const l=s.prepare(`
|
|
19
19
|
SELECT id, kind, confidence, problem, tags FROM memory_artifacts
|
|
20
20
|
${p}
|
|
21
21
|
ORDER BY created_at DESC LIMIT ?
|
|
22
|
-
`).all(a);if(l.length>0){const m=l.map(g=>[`mem:${g.id}`,g.kind,`${Math.round(g.confidence*100)}%`,g.problem.slice(0,60),g.tags?.slice(0,30)??""]);console.log(
|
|
22
|
+
`).all(a);if(l.length>0){const m=l.map(g=>[`mem:${g.id}`,g.kind,`${Math.round(g.confidence*100)}%`,g.problem.slice(0,60),g.tags?.slice(0,30)??""]);console.log(P(["ID","Kind","Conf","Preview","Tags"],m))}else console.log(u.dim(" No memories yet."))}if(o==="all"||o==="truths"){E("Ground Truths");const l=s.prepare(`
|
|
23
23
|
SELECT id, category, key, value FROM ground_truths
|
|
24
24
|
WHERE is_current = 1 ${i}
|
|
25
25
|
ORDER BY created_at DESC LIMIT ?
|
|
26
|
-
`).all(a);if(l.length>0){const m=l.map(g=>[`truth:${g.id}`,g.category,g.key.slice(0,30),g.value.slice(0,60)]);console.log(
|
|
26
|
+
`).all(a);if(l.length>0){const m=l.map(g=>[`truth:${g.id}`,g.category,g.key.slice(0,30),g.value.slice(0,60)]);console.log(P(["ID","Category","Key","Value"],m))}else console.log(u.dim(" No ground truths yet."))}if(o==="all"||o==="quests"){E("Quests");const l=s.prepare(`
|
|
27
27
|
SELECT id, priority, title, status FROM quests
|
|
28
28
|
${p}
|
|
29
29
|
ORDER BY created_at DESC LIMIT ?
|
|
30
|
-
`).all(a);if(l.length>0){const m=l.map(g=>[`quest:${g.id}`,g.priority,g.title.slice(0,60),g.status]);console.log(
|
|
31
|
-
`+
|
|
32
|
-
`+
|
|
33
|
-
`+
|
|
34
|
-
`+
|
|
35
|
-
`+
|
|
36
|
-
`+
|
|
37
|
-
`+String(
|
|
38
|
-
`+
|
|
39
|
-
`+
|
|
40
|
-
`+
|
|
41
|
-
`);return}if(E(`Write digest \u2014 last ${e.since}`),console.log(`${u.bold("Total writes:")} ${e.total} ${u.bold("Outcomes:")} ${Object.entries(e.byOutcome).map(([s,t])=>`${s} ${t}`).join(" \xB7 ")||"none"}`),console.log(`${u.bold("Review queue:")} ${e.reviewQueueDepth} awaiting review${e.reviewQueueDepth>0?u.dim(" (invisible to recall until approved)"):""}`),e.byTool.length>0&&console.log(
|
|
42
|
-
`)},l=R();try{const m=new Ye(l.getDatabase());let g=o;if(g<=0){let w=a?l.getProject(a):void 0;if(!w&&
|
|
43
|
-
`);return}const
|
|
44
|
-
`);return}g
|
|
30
|
+
`).all(a);if(l.length>0){const m=l.map(g=>[`quest:${g.id}`,g.priority,g.title.slice(0,60),g.status]);console.log(P(["ID","Priority","Title","Status"],m))}else console.log(u.dim(" No quests yet."))}e.close()}async function ct(d){const{positional:c}=j(d),o=c[0];o||(f("Usage: wyrm show <typed-id> (e.g. mem:41, quest:12, truth:7, data:5, session:3)"),process.exit(1));const[a,r]=o.split(":"),e=parseInt(r??"",10);(!a||isNaN(e))&&(f(`Invalid typed ID: ${o}. Format: type:number (e.g. mem:41)`),process.exit(1));const s=R(),t=s.getDatabase();switch(E(`${o}`),a){case"mem":{const n=t.prepare("SELECT * FROM memory_artifacts WHERE id = ?").get(e);if(!n){f(`Memory artifact ${e} not found`);break}console.log(u.bold("Kind: ")+n.kind),console.log(u.bold("Confidence:")+` ${Math.round(n.confidence*100)}%`),console.log(u.bold("Problem: ")+`
|
|
31
|
+
`+n.problem),n.validated_fix&&console.log(u.bold("Solution: ")+`
|
|
32
|
+
`+n.validated_fix),n.why_it_worked&&console.log(u.bold("Why: ")+`
|
|
33
|
+
`+n.why_it_worked),n.tags&&console.log(u.bold("Tags: ")+n.tags),console.log(u.bold("Created: ")+n.created_at);break}case"quest":{const n=t.prepare("SELECT * FROM quests WHERE id = ?").get(e);if(!n){f(`Quest ${e} not found`);break}console.log(u.bold("Title: ")+n.title),console.log(u.bold("Priority: ")+n.priority),console.log(u.bold("Status: ")+n.status),n.description&&console.log(u.bold("Desc: ")+`
|
|
34
|
+
`+n.description),n.tags&&console.log(u.bold("Tags: ")+n.tags),console.log(u.bold("Created: ")+n.created_at);break}case"truth":{const n=t.prepare("SELECT * FROM ground_truths WHERE id = ?").get(e);if(!n){f(`Ground truth ${e} not found`);break}console.log(u.bold("Category: ")+n.category),console.log(u.bold("Key: ")+n.key),console.log(u.bold("Value: ")+`
|
|
35
|
+
`+n.value),n.rationale&&console.log(u.bold("Rationale:")+`
|
|
36
|
+
`+n.rationale),console.log(u.bold("Active: ")+(n.is_current?"Yes":"No (superseded)")),console.log(u.bold("Created: ")+n.created_at);break}case"data":{const n=t.prepare("SELECT * FROM data_lake WHERE id = ?").get(e);if(!n){f(`Data point ${e} not found`);break}console.log(u.bold("Category: ")+n.category),console.log(u.bold("Key: ")+n.key),console.log(u.bold("Value: ")+`
|
|
37
|
+
`+String(n.value).slice(0,500)),console.log(u.bold("Created: ")+n.created_at);break}case"session":{const n=t.prepare("SELECT * FROM sessions WHERE id = ?").get(e);if(!n){f(`Session ${e} not found`);break}console.log(u.bold("Date: ")+n.date),console.log(u.bold("Objectives: ")+`
|
|
38
|
+
`+n.objectives),n.completed&&console.log(u.bold("Completed: ")+`
|
|
39
|
+
`+n.completed),n.notes&&console.log(u.bold("Notes: ")+`
|
|
40
|
+
`+n.notes);break}default:f(`Unknown type prefix: ${a}. Use mem|quest|truth|data|session`)}s.close()}async function lt(d){const{positional:c,flags:o}=j(d),a=c[0];a||(f('Usage: wyrm capture "<content>" [--project <name>] [--mode auto|quest|truth|memory]'),process.exit(1));const r=o.project,e=o.mode,s=R(),t=s.getDatabase();let n=null;if(r){const x=I(s,r);x||(f(`Project not found: ${r}`),console.log(u.dim(` create it: wyrm project add ${r} --path <dir>`)),s.close(),process.exit(1)),n=x.id}let p=Ke(a);e&&e!=="auto"&&(p={type:e,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[e]??e,confidence:100,reasoning:`Mode override: ${e}`});const{type:i,subtype:l,confidence:m,reasoning:g}=p;(i==="quest"||i==="truth"||i==="memory")&&n===null&&(f('A --project is required to capture. Use: wyrm capture "<text>" --project <name>'),s.close(),process.exit(1));let h=0,y="",w=!1;const v=new B(t),k=new de(t);if(ve(k,new be(t)),i==="quest")h=s.addQuest(n,a.slice(0,200),"","medium").id,y="quest";else if(i==="truth")e!=="truth"&&m<100?(h=v.add(n,{kind:"pattern",problem:a,confidence:m/100,needsReview:1}).id,y="mem",w=!0):(h=k.set(n,{category:"decision",key:a.slice(0,60),value:a}).id,y="truth");else{const x=m>=75;h=v.add(n,{kind:l,problem:a,confidence:m/100,needsReview:x?0:1}).id,y="mem",x||(w=!0)}const{recordWrite:b}=await import("./receipts.js"),C=b(t,{tool:"wyrm_capture",outcome:w?"queued":"stored",refTable:y,refId:h,reason:w?`needs_review (confidence ${m}%) \u2014 review to activate`:void 0,source:"cli",projectId:n??void 0});let S=null;if(y==="mem"){const{resolveEmbeddingState:x}=await import("./providers/embedding-provider.js");if(x().resolved!=="none")try{const{createVectorStore:L}=await import("./vectors.js"),Y=process.env.WYRM_VECTOR_PROVIDER??"auto";S=await L({provider:Y},t).addVector(a,"artifact",h,n)?"embedded for semantic recall":"not embedded yet (wyrm index rebuild will backfill)"}catch{S="not embedded yet (wyrm index rebuild will backfill)"}}s.close(),$(`Captured as ${i}: ${l}`),console.log(`${u.dim("Confidence:")} ${m}% | ${u.dim(g)}`),console.log(`${u.dim("ID:")} ${y}:${h}`),w&&console.log(`${K.warning} Stored for review \u2014 run ${u.cyan("wyrm review")} to activate`),S&&console.log(u.dim(` ${S}`)),console.log(`receipt: ${C.outcome} ${C.ref??""}${C.reason?` \u2014 ${C.reason}`:""}`)}async function dt(d){const{flags:c}=j(d);if(c.writes!==!0){f("Usage: wyrm digest --writes [--since <days>] [--json]"),process.exitCode=1;return}const o=Number(c.since)>=1?Number(c.since):1,{buildWriteDigest:a}=await import("./receipts.js"),r=R();try{const e=a(r.getDatabase(),o);if(c.json===!0){process.stdout.write(JSON.stringify(e)+`
|
|
41
|
+
`);return}if(E(`Write digest \u2014 last ${e.since}`),console.log(`${u.bold("Total writes:")} ${e.total} ${u.bold("Outcomes:")} ${Object.entries(e.byOutcome).map(([s,t])=>`${s} ${t}`).join(" \xB7 ")||"none"}`),console.log(`${u.bold("Review queue:")} ${e.reviewQueueDepth} awaiting review${e.reviewQueueDepth>0?u.dim(" (invisible to recall until approved)"):""}`),e.byTool.length>0&&console.log(P(["Tool","Outcome","N"],e.byTool.map(s=>[s.tool,s.outcome,String(s.n)]))),e.reasons.length>0){console.log(u.bold("Non-stored reasons:"));for(const s of e.reasons)console.log(` ${s.outcome} \xD7${s.n} \u2014 ${s.reason.slice(0,110)}`)}e.bySource.length>0&&console.log(u.bold("By source: ")+e.bySource.map(s=>`${s.source} ${s.n}`).join(" \xB7 "))}finally{r.close()}}async function ut(d){const{flags:c}=j(d),o=M(c.session,0),a=c.path,r=c.project,e=M(c["max-chars"],6e3),s=c.json===!0,t=s||c.quiet===!0,n=console.log;console.log=()=>{};const p=(m,g)=>{if(g==null)return 0;try{return m.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE project_id = ?").get(g).n}catch{return 0}},i=m=>{process.stdout.write(JSON.stringify({brief:"",attached:{quests:0,truths:0,artifacts:0,failures:0},memories:p(l.getDatabase(),m)})+`
|
|
42
|
+
`)},l=R();try{const m=new Ye(l.getDatabase());let g=o;if(g<=0){let w=a?l.getProject(a):void 0;if(!w&&r&&(w=I(l,r)??void 0),w||(w=l.getProject(process.cwd())),!w){if(s){i();return}t||process.stderr.write(`wyrm rehydrate: no Wyrm project for this directory, nothing to restore.
|
|
43
|
+
`);return}const v=l.getRecentSessions(w.id,1);if(v.length===0){if(s){i(w.id);return}t||process.stderr.write(`wyrm rehydrate: project "${w.name}" has no prior sessions yet.
|
|
44
|
+
`);return}g=v[0].id}const h=m.rehydrate(g);if(!h){if(s){i();return}t||process.stderr.write(`wyrm rehydrate: session ${g} not found.
|
|
45
45
|
`);return}let y=h.briefing_markdown;if(e>0&&y.length>e&&(y=y.slice(0,e)+`
|
|
46
46
|
|
|
47
|
-
_... brief truncated at ${e} chars, run \`wyrm show session:${h.session_id}\` for the full record._`),s){const w=l.getDatabase().prepare("SELECT project_id FROM sessions WHERE id = ?").get(h.session_id)
|
|
47
|
+
_... brief truncated at ${e} chars, run \`wyrm show session:${h.session_id}\` for the full record._`),s){const w=l.getDatabase().prepare("SELECT project_id FROM sessions WHERE id = ?").get(h.session_id),v=p(l.getDatabase(),w?.project_id);process.stdout.write(JSON.stringify({brief:y,attached:h.attached,memories:v})+`
|
|
48
48
|
`);return}process.stdout.write(y+`
|
|
49
|
-
`)}finally{l.close(),console.log=
|
|
50
|
-
`);return}const l={};for(const h of["objectives","completed","issues","commits","notes"]){const y=
|
|
51
|
-
`)}finally{p.close(),console.log=
|
|
52
|
-
`);return}if(a==="list"||a==="ls"||a===void 0){const i=
|
|
49
|
+
`)}finally{l.close(),console.log=n}}async function pt(d){const{flags:c}=j(d),{runMetabolize:o}=await import("./metabolize.js"),a=R(),r=console.log;try{let e;if(typeof c.project=="string"){const t=I(a,c.project);if(!t){f(`Project not found: ${c.project}`),process.exitCode=1;return}e=t.id}const s=o(a.getDatabase(),{projectId:e,dryRun:c["dry-run"]===!0,near:c["no-near"]===!0?!1:void 0});console.log(`metabolize${s.dryRun?" (dry-run)":""} \u2014 scanned ${s.scanned} \xB7 exact-merged ${s.exactMerged} (superseded, not deleted) \xB7 near-dup candidates queued ${s.nearCandidatesQueued} \xB7 decayed ${s.decayed}`)}finally{a.close(),console.log=r}}async function mt(d){const{positional:c,flags:o}=j(d),a=c[0]??"stats",{backfillEntities:r}=await import("./entity-populate.js"),e=R(),s=console.log;try{const t=e.getDatabase();let n;if(typeof o.project=="string"){const p=I(e,o.project);if(!p){f(`Project not found: ${o.project}`),process.exitCode=1;return}n=p.id}if(a==="stats"){const p=i=>{if(n!=null){const m=i==="entities"?"SELECT COUNT(*) AS n FROM entities WHERE project_id = ?":"SELECT COUNT(*) AS n FROM relationships WHERE project_id = ?";return t.prepare(m).get(n).n}const l=i==="entities"?"SELECT COUNT(*) AS n FROM entities":"SELECT COUNT(*) AS n FROM relationships";return t.prepare(l).get().n};console.log(`entities: ${p("entities")} \xB7 relationships: ${p("relationships")}${n!=null?` (project ${n})`:" (all projects)"}`);return}if(a==="backfill"){const p=n!=null?[{id:n}]:t.prepare("SELECT id FROM projects").all();let i=0,l=0,m=0;for(const g of p){const h=r(t,g.id,{limit:M(o.limit,5e3)});i+=h.created,l+=h.linked,m+=h.artifactsScanned}console.log(`entities backfill \u2014 scanned ${m} artifact(s) across ${p.length} project(s): +${i} entities, +${l} co-occurrence edges`);return}f("Usage: wyrm entities <backfill|stats> [--project <name>] [--limit N]"),process.exitCode=1}finally{e.close(),console.log=s}}async function ft(d){const{positional:c,flags:o}=j(d),a=c[0],r=await import("./bridge.js");if(a==="init"){const{existsSync:e,writeFileSync:s}=await import("node:fs"),t=r.configPath();if(e(t)&&o.force!==!0){f(`${t} already exists (use --force to overwrite).`),process.exitCode=1;return}const n=(await import("node:os")).homedir(),p={sources:[{type:"remember",name:"remember",dir:`${n}/.remember`,projectPath:n,windowDays:7}]};s(t,JSON.stringify(p,null,2)),$(`Wrote ${t} (1 source: remember). Add render/reverse sources per project as needed.`);return}if(a==="status"){const e=r.loadConfig();if(!e){f(`No bridge config at ${r.configPath()} \u2014 run \`wyrm bridge init\`.`),process.exitCode=1;return}const s=r.loadState();E("Bridge sources");for(const t of e.sources){const n=Object.keys(s).filter(i=>i.startsWith(t.name+":")),p=n.reduce((i,l)=>i+s[l].length,0);console.log(` ${t.name} [${t.type}] \u2192 ${"projectPath"in t?t.projectPath:""}${t.type==="remember"?` (${n.length} files tracked, ${p} sections bridged)`:""}`)}return}if(a==="run"){const e=r.loadConfig();if(!e){f(`No bridge config at ${r.configPath()} \u2014 run \`wyrm bridge init\`.`),process.exitCode=1;return}const s=R(),t=console.log;try{const n={wyrm_version:A().version??"unknown",compiled_at:new Date().toISOString()},p=await r.runBridge(s.getDatabase(),e,n,{only:typeof o.source=="string"?o.source:void 0,dryRun:o["dry-run"]===!0});for(const i of p)console.log(`bridge:${i.source} [${i.type}]${o["dry-run"]===!0?" (dry-run)":""} \u2014 stored ${i.stored} \xB7 queued ${i.queued} \xB7 dropped ${i.dropped} \xB7 rendered ${i.rendered}${i.note?` \xB7 ${i.note}`:""}`);if(o.watch===!0){const i=Number(o.interval)>=2?Number(o.interval):15;console.log(`bridge watch \u2014 re-rendering on write events (poll ${i}s, Ctrl-C to stop)`),await r.watchBridge(s.getDatabase(),e,()=>({wyrm_version:A().version??"unknown",compiled_at:new Date().toISOString()}),{intervalSec:i,onCycle:l=>{for(const m of l)console.log(`bridge:${m.source} re-rendered (${m.rendered} file(s), ${m.queued} edit(s) harvested)`)}})}return}finally{s.close(),console.log=t}}f("Usage: wyrm bridge <init|status|run> [--source <name>] [--dry-run] [--force]"),process.exitCode=1}async function gt(d){const{positional:c,flags:o}=j(d);if(c[0]!=="log"){f("Usage: wyrm session log [--path <dir>] [--run <id>] [--objectives <t>] [--completed <t>] [--issues <t>] [--commits <t>] [--notes <t>]"),process.exitCode=1;return}const r=i=>typeof o[i]=="string"?o[i]:void 0,e=r("path"),s=r("project"),t=r("run")?.slice(0,64),n=console.log;console.log=()=>{};const p=R();try{let i=e?p.getProject(e):void 0;if(!i&&s&&(i=I(p,s)??void 0),i||(i=p.getProject(process.cwd())),!i){process.stderr.write(`wyrm session log: no Wyrm project for this directory, nothing recorded.
|
|
50
|
+
`);return}const l={};for(const h of["objectives","completed","issues","commits","notes"]){const y=r(h);y&&(l[h]=y.slice(0,8e3))}const m=p.getDatabase();let g;t&&(g=m.prepare("SELECT id FROM sessions WHERE project_id = ? AND run_id = ? ORDER BY id DESC LIMIT 1").get(i.id,t)?.id),g?p.updateSession(g,l):(g=p.createSession(i.id,l).id,t&&m.prepare("UPDATE sessions SET run_id = ? WHERE id = ?").run(t,g)),process.stdout.write(`session:${g}
|
|
51
|
+
`)}finally{p.close(),console.log=n}}async function yt(d){const{positional:c,flags:o}=j(d),a=c[0],r=p=>typeof o[p]=="string"?o[p]:void 0,{AgentPresence:e,processStartTime:s,presenceLiveness:t}=await import("./presence.js"),n=R();try{const p=new e(n.getDatabase());if(a==="announce"){const i=r("agent");if(!i){f("Usage: wyrm presence announce --agent <id> [--kind <kind>] [--project <name>|--path <dir>] [--quest <n>] [--pid <n>|--auto-pid] [--ttl <sec>] [--role <r>]"),process.exitCode=1;return}const l=r("path");let m=l?n.getProject(l):void 0;!m&&r("project")&&(m=I(n,r("project"))??void 0);const g=o["auto-pid"]===!0?process.ppid:Number(r("pid")),h={};let y="";if(Number.isInteger(g)&&g>0){const k=s(g);k?(h.pid=g,h.pid_start=k,y=` \xB7 pid ${g} (start ${k})`):y=` \xB7 pid ${g} unreadable \u2014 TTL fallback`}const w=Number(r("ttl")),v=p.announce({agent_id:i,agent_kind:r("kind")??"cli",project_id:m?.id??null,current_quest_id:r("quest")?Number(r("quest")):null,ttl_seconds:Number.isFinite(w)&&w>0?w:h.pid?86400:300,metadata:Object.keys(h).length?h:void 0,role:r("role")??null});process.stdout.write(`presence:${v.id} ${i}${y}
|
|
52
|
+
`);return}if(a==="list"||a==="ls"||a===void 0){const i=n.getDatabase().prepare("SELECT * FROM agent_presence ORDER BY last_heartbeat DESC").all();if(i.length===0){process.stdout.write(`No agents on the board.
|
|
53
53
|
`);return}const l={"alive-pid":"ALIVE (pid)","dead-pid":"DEAD (pid gone)","alive-ttl":"alive (ttl)",stale:"stale"};for(const m of i){const g=t(m);process.stdout.write(`${m.agent_id} [${m.agent_kind}] ${l[g]} hb ${m.last_heartbeat}${m.role?` role ${m.role}`:""}${m.current_quest_id?` quest #${m.current_quest_id}`:""}
|
|
54
|
-
`)}return}if(a==="release"){const i=
|
|
54
|
+
`)}return}if(a==="release"){const i=r("agent");if(!i){f("Usage: wyrm presence release --agent <id>"),process.exitCode=1;return}const l=p.release(i);process.stdout.write(l?`released ${i}
|
|
55
55
|
`:`no presence row for ${i}
|
|
56
|
-
`);return}f("Usage: wyrm presence <announce|list|release> [options]"),process.exitCode=1}finally{
|
|
57
|
-
`);return}const w=
|
|
58
|
-
`).filter(y=>y.trim()),m=new B(
|
|
56
|
+
`);return}f("Usage: wyrm presence <announce|list|release> [options]"),process.exitCode=1}finally{n.close()}}async function ht(d){const{flags:c}=j(d),o=c.path,a=c.project,r=c.out,e=c.brief===!0,s=c.force===!0,t=c.quiet===!0,n=(typeof c.client=="string"?c.client:"").split(",").map(g=>g.trim().toLowerCase()).filter(Boolean);let p=n.filter(g=>pe.includes(g));const i=n.filter(g=>!pe.includes(g));i.length>0&&(f(`Unknown --client value(s): ${i.join(", ")} (valid: ${pe.join("|")})`),process.exit(1));const l=console.log;e&&(console.log=()=>{});const m=R();try{let g=o?m.getProject(o):void 0;!g&&a&&(g=I(m,a)??void 0),g||(g=m.getProject(process.cwd())),g||(console.log=l,f("wyrm render: no Wyrm project for this directory (use --path or --project)."),process.exit(1));const h=$e(m.getDatabase()),y={wyrm_version:A().version??"unknown",compiled_at:new Date().toISOString()};if(e){const b=ue(h,g,y);console.log=l,process.stdout.write(b.sessionBrief+`
|
|
57
|
+
`);return}const w=r??g.path;p.length===0&&n.length===0&&(p=He(Be.filter(b=>U(W(w,b)))));{const b=await import("./reverse-bridge.js"),C=ue(h,g,y),S={"MEMORY.md":C.memoryMd};for(const x of p){const T=ke(x,C.model,y);S[T.relPath]=T.block}try{const x=b.makeBridgeDeps(m.getDatabase()),T=await b.sweepProject(x,{id:g.id,path:g.path},S,{rootDir:w});T.added>0&&!t&&console.log(` ${K.warning} harvested ${T.added} human edit(s) \u2192 review queue before overwrite`)}catch{}}const{plan:v,writes:k}=Ve(h,g,y,{rootDir:w,clients:p,force:s});if(!t){$(`Rendered ${g.name} memory (${v.model.truths.length} truths, ${v.model.failures.length} failures, ${v.model.quests.length} quests, ${v.model.artifacts.length} patterns) to ${w}`);for(const b of k){const C=b.action==="created"?K.success:b.action==="updated"?K.info:K.warning;console.log(` ${C} ${b.action.padEnd(7)} ${b.path}${b.reason?` (${b.reason})`:""}`)}}}finally{m.close(),console.log=l}}async function wt(d){const{flags:c}=j(d),o=c.path,a=c.project,r=c.root,e=c["dry-run"]===!0||c.dry===!0,s=(typeof c.client=="string"?c.client:"").split(",").map(l=>l.trim().toLowerCase()).filter(Boolean),t=["claude","cursor","copilot","agents"],n=s.filter(l=>t.includes(l)),p=await import("./reverse-bridge.js"),i=R();try{let l=o?i.getProject(o):void 0;if(!l&&a&&(l=I(i,a)??void 0),l||(l=i.getProject(process.cwd())),!l){f("wyrm reverse-bridge: no Wyrm project for this directory (use --path or --project)."),process.exitCode=1;return}const m=$e(i.getDatabase()),g={wyrm_version:A().version??"unknown",compiled_at:new Date().toISOString()},h=ue(m,l,g),y={"MEMORY.md":h.memoryMd};for(const k of n){const b=ke(k,h.model,g);y[b.relPath]=b.block}const w=p.makeBridgeDeps(i.getDatabase()),v=await p.sweepProject(w,{id:l.id,path:l.path},y,{dryRun:e,rootDir:r});E(`Reverse bridge ${e?"(dry run) ":""}\u2014 ${v.added} candidate(s) queued, ${v.skipped} already present (${v.filesWithEdits}/${v.filesScanned} file(s) with edits)`);for(const k of v.sample)console.log(` ${K.bullet} ${k}`);!e&&v.added>0&&$("Review with: wyrm review")}finally{i.close()}}async function bt(d){const c=j(d);if(typeof c.flags.from=="string"){await vt(c);return}const{positional:o,flags:a}=j(d.slice(1)),r=d[0],e=a.project;if(r==="git"){const s=M(a.last,20),t=R(),n=t.getDatabase();let p=null;if(e){const y=I(t,e);y||(f(`Project not found: ${e}`),t.close(),process.exit(1)),p=y.id}else{const y=n.prepare("SELECT p.* FROM projects p JOIN sessions s ON s.project_id = p.id ORDER BY s.created_at DESC LIMIT 1").get();y&&(p=y.id)}p||(f("No project found. Use --project <name>"),t.close(),process.exit(1));const i=te("git",["log","--pretty=format:%H%x1f%s%x1f%an%x1f%ai",`-${s}`],{cwd:process.cwd(),encoding:"utf-8",timeout:1e4,shell:!1});(i.error||i.status!==0)&&(f("git log failed. Make sure you are in a git repository."),t.close(),process.exit(1));const l=i.stdout.split(`
|
|
58
|
+
`).filter(y=>y.trim()),m=new B(n);let g=0,h=0;for(const y of l){const[,w,v,k]=y.split(""),b=w??"";if(/^Merge /i.test(b)||/^(chore|bump|release|version)/i.test(b)){h++;continue}let C="pattern";/^fix(\(.+\))?:/i.test(b)?C="lesson":/^refactor(\(.+\))?:/i.test(b)&&(C="heuristic");const S=b.split(":")[0]??"commit";m.add(p,{kind:C,problem:b,whyItWorked:`Committed by ${v??"unknown"} on ${k??"unknown"}`,tags:["git","commit",S.toLowerCase()],confidence:.6,needsReview:1}),g++}t.close(),$(`Imported ${g} commits (${h} skipped). Run ${u.cyan("wyrm review")} to activate.`)}else if(r==="rules"){const s=o[0],t=a.format??"plain";s||(f("Usage: wyrm import rules <path> [--project <name>] [--format cursorrules|copilot|plain]"),process.exit(1)),U(s)||(f(`File not found: ${s}`),process.exit(1));const n=H(s,"utf-8"),p=R(),i=p.getDatabase();let l=null;if(e){const S=I(p,e);S||(f(`Project not found: ${e}`),p.close(),process.exit(1)),l=S.id}else{const S=i.prepare("SELECT p.* FROM projects p JOIN sessions s ON s.project_id = p.id ORDER BY s.created_at DESC LIMIT 1").get();S&&(l=S.id)}l||(f("No project found. Use --project <name>"),p.close(),process.exit(1));const m=s.split("/").pop()??"rules",g=["imported",t,m],h=n.split(/\n(?=#)/),y=n.split(/\n\n+/),w=(h.length>=y.length?h:y).map(S=>S.trim()).filter(S=>S.length>=15),v=new B(i),k=new de(i);ve(k,new be(i));let b=0,C=0;for(const S of w)/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(S)?(k.set(l,{category:"constraint",key:S.slice(0,50).replace(/\n/g," "),value:S,source:m}),b++):(v.add(l,{kind:"heuristic",problem:S,tags:g,confidence:.7,needsReview:1}),C++);p.close(),$(`Imported ${b} ground truths + ${C} artifacts (pending review).`)}else f("Usage: wyrm import git [--project <name>] [--last N]"),f(" wyrm import rules <path> [--project <name>] [--format cursorrules|copilot|plain]"),f(` wyrm import --from ${_e.join("|")} <file.json> [--project <name>]`),process.exit(1)}async function vt(d){const c=d.flags.from,o=d.positional[0],a=d.flags.project,r=`Usage: wyrm import --from ${_e.join("|")} <file.json> [--project <name>]`;o||(f(r),process.exit(1)),U(o)||(f(`File not found: ${o}`),process.exit(1));let e;try{e=JSON.parse(H(o,"utf-8"))}catch(n){f(`Could not parse JSON from ${o}: ${n.message}`),process.exit(1)}let s;try{s=Ge(c,e)}catch(n){f(n.message),process.exit(1)}const t=R();try{let n=a?I(t,a):null;if(n||(n=t.getProject(process.cwd())??null),!n){f(a?`Project not found: ${a}`:"wyrm import: no Wyrm project for this directory (pass --project <name>)."),process.exitCode=1;return}if(s.length===0){f(`No importable memories found in ${o} for source "${c}".`);return}const p=t.getDatabase(),i=new B(p);try{const{createVectorStore:m}=await import("./vectors.js"),g=process.env.WYRM_VECTOR_PROVIDER??"auto";i.setVectorStore(m({provider:g},p))}catch{}let l=0;for(const m of s)i.add(n.id,{kind:"lesson",problem:m.text,tags:m.tags,constraints:m.metadata?JSON.stringify(m.metadata):void 0,whyItWorked:`Imported from ${m.source}`,outcome:"neutral",confidence:.6,needsReview:1}),l++;$(`Imported ${l} ${l===1?"memory":"memories"} from ${c} into ${u.cyan(n.name)} review queue. Run ${u.cyan("wyrm review")} to vet (tagged ${u.dim(`imported_from:${s[0]?.source??c}`)}).`)}finally{t.close()}}async function $t(d){const{flags:c}=j(d),o=c.project,a=R(),r=a.getDatabase();if(E("Wyrm Statistics"),o){const e=I(a,o);e||(f(`Project not found: ${o}`),a.close(),process.exit(1));const s=a.getProjectStats(e.id),t=[["Sessions",String(s.sessions)],["Quests (pending)",String(s.quests.pending)],["Quests (completed)",String(s.quests.completed)],["Data Points",String(s.dataPoints)]];console.log(P(["Metric","Value"],t))}else{const e=a.getStats(),s=[["Projects",String(e.projects)],["Sessions",String(e.sessions)],["Quests",String(e.quests)],["Data Points",String(e.dataPoints)],["DB Size",e.dbSize]],t=r.prepare("SELECT COUNT(*) as n FROM memory_artifacts").get().n,n=r.prepare("SELECT COUNT(*) as n FROM ground_truths WHERE is_current = 1").get().n;s.push(["Memories",String(t)],["Ground Truths",String(n)]),console.log(P(["Metric","Value"],s))}a.close()}async function kt(d){const{flags:c}=j(d),o=c.project,a=R(),r=a.getDatabase();if(c.auto!==void 0){const{isAutoApproveOn:i,setAutoApprove:l}=await import("./memory-artifacts.js"),m=String(c.auto).toLowerCase();try{m==="on"||m==="1"||m==="true"?(l(r,!0),$("Auto-approve ON: new memories skip the review queue and are recall-visible immediately.")):m==="off"||m==="0"||m==="false"?(l(r,!1),$("Auto-approve OFF: risky writes queue for wyrm review again.")):m==="status"||m==="true"?console.log(` auto-approve: ${i(r)?"on":"off"}${process.env.WYRM_AUTO_APPROVE?" (WYRM_AUTO_APPROVE env)":""}`):(f("usage: wyrm review --auto on|off|status"),process.exitCode=1)}finally{a.close()}return}if(c["approve-all"]===!0){const i=r.prepare("UPDATE memory_artifacts SET needs_review = 0 WHERE needs_review = 1").run().changes;$(`Approved ${i} queued memor${i===1?"y":"ies"} (now recall-visible).`),a.close();return}let e=null;if(o){const i=I(a,o);i||(f(`Project not found: ${o}`),a.close(),process.exit(1)),e=i.id}const s=e?`AND project_id = ${e}`:"",t=r.prepare(`
|
|
59
59
|
SELECT id, kind, problem FROM memory_artifacts
|
|
60
60
|
WHERE needs_review = 1 ${s}
|
|
61
61
|
ORDER BY created_at ASC
|
|
62
|
-
`).all();if(t.length===0){console.log(u.dim(` No artifacts pending review${o?` for ${o}`:""}.`)),a.close();return}E(`Review Queue (${t.length} items)`);const
|
|
63
|
-
${u.bold(`[${i.kind}] #${i.id}`)}`),console.log(u.dim("\u2500".repeat(60))),console.log(i.problem.slice(0,300)),console.log(u.dim("\u2500".repeat(60)));const m=(await p(`${u.cyan("[a]")}pprove / ${u.red("[r]")}eject / ${u.yellow("[s]")}kip? `)).trim().toLowerCase();m==="a"?(
|
|
64
|
-
Review complete.`)}async function _t(d){const{positional:c,flags:o}=j(d),a=c[0];(!a||!["export","import","preview"].includes(a))&&(f("Usage: wyrm sync export --out <path> | wyrm sync import --from <path> | wyrm sync preview --from <path>"),process.exit(1));const{randomBytes:
|
|
62
|
+
`).all();if(t.length===0){console.log(u.dim(` No artifacts pending review${o?` for ${o}`:""}.`)),a.close();return}E(`Review Queue (${t.length} items)`);const n=oe({input:process.stdin,output:process.stdout}),p=i=>new Promise(l=>{n.question(i,l)});for(const i of t){console.log(`
|
|
63
|
+
${u.bold(`[${i.kind}] #${i.id}`)}`),console.log(u.dim("\u2500".repeat(60))),console.log(i.problem.slice(0,300)),console.log(u.dim("\u2500".repeat(60)));const m=(await p(`${u.cyan("[a]")}pprove / ${u.red("[r]")}eject / ${u.yellow("[s]")}kip? `)).trim().toLowerCase();m==="a"?(r.prepare("UPDATE memory_artifacts SET needs_review = 0, updated_at = datetime('now') WHERE id = ?").run(i.id),$(`Approved #${i.id}`)):m==="r"?(r.prepare("DELETE FROM memory_artifacts WHERE id = ?").run(i.id),console.log(`${K.cross} Rejected #${i.id}`)):console.log(u.dim(` Skipped #${i.id}`))}n.close(),a.close(),console.log(`
|
|
64
|
+
Review complete.`)}async function _t(d){const{positional:c,flags:o}=j(d),a=c[0];(!a||!["export","import","preview"].includes(a))&&(f("Usage: wyrm sync export --out <path> | wyrm sync import --from <path> | wyrm sync preview --from <path>"),process.exit(1));const{randomBytes:r,pbkdf2Sync:e,createCipheriv:s,createDecipheriv:t}=await import("crypto"),{readFileSync:n,writeFileSync:p,copyFileSync:i,unlinkSync:l,existsSync:m,chmodSync:g}=await import("fs"),{homedir:h}=await import("os"),{join:y}=await import("path"),w=(await import("better-sqlite3")).default;let v=process.env.WYRM_SYNC_PASSPHRASE??"";if(!v){const D=oe({input:process.stdin,output:process.stdout});v=await new Promise(O=>{process.stdout.write("Passphrase: "),process.stdin.isTTY&&process.stdin.setRawMode?.(!0),D.question("",V=>{process.stdin.isTTY&&process.stdin.setRawMode?.(!1),console.log(""),D.close(),O(V)})})}v||(f("Passphrase is required. Set WYRM_SYNC_PASSPHRASE or enter interactively."),process.exit(1));const k=y(h(),".wyrm"),b=R();if(a==="export"){const D=o.out;D||(f("--out <path> is required"),process.exit(1));const O=y(k,"wyrm_cli_export_temp.db");try{const V=b.getDatabase();m(O)&&l(O),V.prepare("VACUUM INTO ?").run(O);const z=n(O),G=r(32),Q=r(16),Pe=e(v,G,6e5,32,"sha256"),ce=s("aes-256-gcm",Pe,Q),Me=Buffer.concat([ce.update(z),ce.final()]),Oe=ce.getAuthTag(),Ae=Buffer.from("WYRM"),he=Buffer.alloc(1);he.writeUInt8(1,0);const we=Buffer.concat([Ae,he,G,Q,Oe,Me]);p(D,we);try{g(D,384)}catch{}try{l(O)}catch{}const Le=(we.length/(1024*1024)).toFixed(2);$(`Exported to ${D} (${Le} MB)`)}catch(V){try{m(O)&&l(O)}catch{}f(`Export failed: ${V}`)}b.close();return}const C=o.from;C||(f("--from <path> is required"),process.exit(1));const S=n(C);S.subarray(0,4).toString("ascii")!=="WYRM"&&(f("Invalid Wyrm snapshot file."),process.exit(1));const x=S.readUInt8(4);x!==1&&(f(`Unsupported snapshot version: ${x}`),process.exit(1));const T=S.subarray(5,37),L=S.subarray(37,53),Y=S.subarray(53,69),fe=S.subarray(69),ge=e(v,T,6e5,32,"sha256"),re=t("aes-256-gcm",ge,L);re.setAuthTag(Y);let ne;try{ne=Buffer.concat([re.update(fe),re.final()])}catch{f("Decryption failed \u2014 wrong passphrase or corrupted file."),process.exit(1)}if(a==="preview"){const D=y(k,"wyrm_cli_preview_temp.db");m(D)&&l(D),p(D,ne);try{const O=new w(D,{readonly:!0}),V=["projects","sessions","ground_truths","memory_artifacts","quests"];E("Snapshot Preview");const z=[];for(const G of V)try{const Q=O.prepare(`SELECT COUNT(*) as n FROM ${G}`).get();z.push([G,String(Q.n)])}catch{z.push([G,"?"])}console.log(P(["Table","Count"],z)),O.close()}catch(O){f(`Preview failed: ${O}`)}try{m(D)&&l(D)}catch{}b.close();return}const J=b.getDatabasePath(),ye=oe({input:process.stdin,output:process.stdout}),Ne=await new Promise(D=>{ye.question("This will REPLACE your current database. Type CONFIRM to proceed: ",D)});if(ye.close(),Ne.trim()!=="CONFIRM"){console.log(u.dim("Aborted.")),b.close();return}const De=new Date().toISOString().replace(/[:.]/g,"-"),ie=`${J}.backup.${De}`;i(J,ie),$(`Backed up to ${ie}`);const ae=y(k,"wyrm_cli_restore_temp.db");p(ae,ne),b.getDatabase().close(),i(ae,J);for(const D of["-wal","-shm"])try{m(J+D)&&l(J+D)}catch{}try{l(ae)}catch{}$(`Restored from ${C}. Backup at ${ie}`)}async function Et(d){const{flags:c}=j(d),o=c.project,a=c.path,r=se(c["min-confidence"],.3),e=M(c["older-than"],90),s=c["no-dry-run"]===!0,t=c.yes===!0,n=R(),p=n.getDatabase();let i=null;if(a||o){const y=a?n.getProject(a):I(n,o);y||(f(`Project not found: ${a??o}`),n.close(),process.exit(1)),i=y.id}const l=new B(p),{candidates:m}=l.pruneStale({projectId:i,minConfidence:r,olderThanDays:e,dryRun:!0});if(E(`Prune Candidates${s?" (LIVE DELETE)":" (dry-run)"}`),m.length===0){console.log(u.dim(" No artifacts match prune criteria.")),n.close();return}const g=m.map(y=>[String(y.id),y.kind,y.problem.slice(0,60),(y.confidence*100).toFixed(0)+"%",y.last_accessed_at??"never"]);if(console.log(P(["ID","Kind","Problem","Conf","Last Accessed"],g)),console.log(`
|
|
65
65
|
Total: ${m.length} candidate(s)`),!s){console.log(u.dim(`
|
|
66
|
-
This is a dry run. Use --no-dry-run to delete (confirm each ID).`)),
|
|
67
|
-
Delete these ${m.length} artifact(s)? Type CONFIRM to proceed:
|
|
66
|
+
This is a dry run. Use --no-dry-run to delete (confirm each ID).`)),n.close();return}if(!t){const y=oe({input:process.stdin,output:process.stdout}),w=await new Promise(v=>{y.question(`
|
|
67
|
+
Delete these ${m.length} artifact(s)? Type CONFIRM to proceed: `,v)});if(y.close(),w.trim()!=="CONFIRM"){console.log(u.dim("Aborted.")),n.close();return}}const h=l.deleteArtifacts(m.map(y=>y.id));$(`Deleted ${h} artifact(s).`),n.close()}async function St(d){const{positional:c,flags:o}=j(d),a=c[0]||"list",r=R();try{if(a==="list"||a==="ls"){const e=Se(r);if(e.length===0){E("Connectors"),console.log(`${F.dim} none configured. Add one with: wyrm connector add --name <n> --url <bridge-url> --workspace <w>${F.reset}`);return}E("Connectors");const s=e.map(t=>[t.name,t.source,t.enabled?"on":"off",t.workspace,Yt(t.baseUrl),t.allowlist.length?`${t.allowlist.length} chats`:"all"]);console.log(P(["Name","Source","Enabled","Workspace","Bridge","Allowlist"],s));return}if(a==="add"){const e=N(o.name),s=N(o.url),t=N(o.workspace);if(!e||!s||!t){f("usage: wyrm connector add --name <n> --url <bridge-url> --workspace <w> [--allowlist a,b] [--token T] [--disabled]"),process.exitCode=1;return}const n={name:e,source:"bridge",enabled:!o.disabled,baseUrl:s,workspace:t,allowlist:N(o.allowlist)?N(o.allowlist).split(",").map(p=>p.trim()).filter(Boolean):[],...N(o.token)?{authToken:N(o.token)}:{}};Ze(r,n),$(`Connector "${e}" saved (source=bridge, workspace=${t}). Token, if any, stored without being printed.`),console.log(`${F.dim} Tip: prefer the env var WYRM_CONNECTOR_TOKEN_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")} over --token.${F.reset}`);return}if(a==="sync"){const e=c[1]||N(o.name);if(e){const t=Se(r).find(p=>p.name===e);if(!t){f(`Connector not found: ${e}`),process.exitCode=1;return}const n=await et(r,t);$(`${n.source}: fetched ${n.fetched}, ingested ${n.ingested}, skipped ${n.skipped} -> ${n.workspace}`);return}const s=await tt(r);if(s.length===0){console.log(`${F.dim} no enabled connectors.${F.reset}`);return}for(const t of s)"error"in t?f(`${t.name}: ${t.error}`):$(`${t.source}: fetched ${t.fetched}, ingested ${t.ingested}, skipped ${t.skipped} -> ${t.workspace}`);return}f(`Unknown connector subcommand: ${a} (use list | add | sync)`),process.exitCode=1}finally{r.close()}}function je(){return H(0,"utf-8").trim()}async function Rt(){const{initializeLicense:d,getLicenseInfo:c,getTier:o}=await import("./license.js");d();const{refreshRevocations:a}=await import("./revocations.js"),{refreshLicenseIfNeeded:r}=await import("./license-refresh.js");await a();const e=await r(),s=c();E("Wyrm License");const t=s.valid?"valid":s.error==="License revoked"?"REVOKED (running as free tier)":s.error&&/expired/i.test(s.error)?"EXPIRED (running as free tier)":s.key?`invalid (${s.error??"unknown reason"}) \u2014 running as free tier`:"free tier (no license key)",n=[["Tier",o()],["Status",t]];s.key&&(n.push(["Key",s.key]),n.push(["Issued to",s.issuedTo??"unknown"]),n.push(["Expires",s.expiresAt?new Date(s.expiresAt).toLocaleDateString():"never"])),n.push(["Features",s.features.join(", ")||"(free)"]),console.log(P(["Field","Value"],n)),!s.valid&&!s.key&&console.log(u.dim(`
|
|
68
68
|
Activate with: wyrm login (free) \xB7 or: wyrm activate <license.json | key>`)),e==="refreshed"&&console.log(u.dim(`
|
|
69
69
|
License refreshed automatically.`)),!s.valid&&s.error==="License revoked"&&console.log(u.dim(`
|
|
70
70
|
This license has been revoked. Contact support if you believe this is a mistake.`)),console.log(u.dim(`
|
|
71
71
|
\xA9 2026 Ghost Protocol (Pvt) Ltd \xB7 Proprietary \xB7 https://wyrm.ghosts.lk`)),console.log(u.dim(" Licensed under the Wyrm Terms of Service. No open-source license is granted."))}async function Ct(){const d=(process.env.WYRM_ACCOUNT_URL??"https://account.ghosts.lk").replace(/\/$/,""),c=(()=>{try{return A().version??"unknown"}catch{return"unknown"}})();let o;try{const l=await fetch(`${d}/api/v1/cli/auth/start`,{method:"POST",headers:{"x-wyrm-version":c}});if(!l.ok)throw new Error(`HTTP ${l.status}`);o=await l.json()}catch(l){f(`Couldn't reach ${d} (${l instanceof Error?l.message:"network error"}).`),process.exitCode=1;return}const a=o.verification_uri_complete||o.verification_uri||`${d}/cli`;console.log(`
|
|
72
72
|
${u.cyan("Sign in to activate Wyrm (free):")}`),console.log(` 1. Open ${u.cyan(a)}`),console.log(` 2. Approve the code ${u.cyan(o.user_code)}`),console.log(u.dim(`
|
|
73
|
-
Waiting for approval\u2026 (Ctrl-C to cancel)`));const
|
|
74
|
-
Database size: ${p.dbSize}`))}finally{s.close()}}async function
|
|
75
|
-
`)),console.log("```")}async function At(d){const{positional:c,flags:o}=j(d),a=c[0]??"list",
|
|
76
|
-
resolve one: wyrm failure resolve <id>`));return}if(a==="resolve"){const s=Number(c[1]);if(!Number.isInteger(s)||s<=0){f('Usage: wyrm failure resolve <id> [--note "root cause fixed by ..."]'),process.exitCode=1;return}const t=N(o.note);(e.prepare("UPDATE failure_patterns SET resolved = 1, resolution_note = ?, last_seen = datetime('now') WHERE id = ? AND resolved = 0").run(t||"resolved via wyrm failure resolve",s).changes??0)>0
|
|
77
|
-
${S} (${x.length})`)),x.length===0){console.log(u.dim(" (none)"));return}for(const
|
|
78
|
-
`),!g.ok){f(`Download failed: ${g.error}`),console.log(" Recall stays keyword-only until this succeeds. Retry: wyrm vectors download"),process.exitCode=1;return}
|
|
79
|
-
1. Get a free API key: ${u.cyan("https://build.nvidia.com")} (Get API Key on any embedding model page)`);let t;try{t=(await Je(" 2. Paste your key (nvapi-...): ")).trim()}catch(l){if(l instanceof ze){console.log(""),process.exitCode=130;return}throw l}if(!t.startsWith("nvapi-")){f("That does not look like a NIM key (expected nvapi- prefix). Nothing written."),process.exitCode=1;return}process.stdout.write(" 3. Validating with a live embed call... ");const{NimProvider:
|
|
73
|
+
Waiting for approval\u2026 (Ctrl-C to cancel)`));const r=(o.interval??3)*1e3,e=Date.now()+(o.expires_in??600)*1e3;let s="";for(;Date.now()<e;){await new Promise(l=>{setTimeout(l,r)});try{const m=await(await fetch(`${d}/api/v1/cli/auth/poll`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:o.device_code})})).json();if(m.status==="approved"&&m.token){s=m.token;break}if(m.status==="denied"||m.error==="expired"){f("Login was denied or the code expired. Run `wyrm login` again."),process.exitCode=1;return}}catch{}}if(!s){f("Login timed out. Run `wyrm login` again."),process.exitCode=1;return}let t;try{const l=await fetch(`${d}/api/v1/license/free`,{method:"POST",headers:{authorization:`Bearer ${s}`,"x-wyrm-version":c}});if(!l.ok){const m=await l.json().catch(()=>({}));f(`Activation failed (${l.status}): ${m.hint||m.error||"unknown error"}`),process.exitCode=1;return}t=JSON.stringify(await l.json())}catch(l){f(`Activation request failed (${l instanceof Error?l.message:"network error"}).`),process.exitCode=1;return}const{saveAccountToken:n}=await import("./license-refresh.js");n(s);const{activateLicense:p}=await import("./license.js"),i=p(t);if(i.valid){$(`Signed in & activated \u2014 ${i.tier} tier (expires ${i.expiresAt??"never"}).`),console.log(u.dim(" Restart the Wyrm MCP server / daemon to apply."));const{refreshRevocations:l}=await import("./revocations.js");await l()}else f(`Activation failed: ${i.error??"unknown error"}`),process.exitCode=1}async function jt(d){const{positional:c}=j(d),o=c[0];let a;o&&U(o)?a=H(o,"utf-8"):o?a=o:process.stdin.isTTY?(f("Usage: wyrm activate <license.json path | license JSON> (or pipe the JSON on stdin)"),process.exit(1)):a=je();const{activateLicense:r}=await import("./license.js");try{const e=r(a);e.valid?($(`License activated \u2014 ${e.tier} tier (${e.features.join(", ")})`),console.log(u.dim(" Restart Wyrm (MCP server / daemon) to apply all features."))):(f(`License activation failed: ${e.error??"unknown error"}`),process.exitCode=1)}catch{f("Invalid license format. Please verify your license key."),process.exitCode=1}}async function xt(d){const{flags:c}=j(d),{runMaintenance:o}=await import("./maintenance.js"),{FailurePatterns:a}=await import("./failure-patterns.js"),{SessionSeen:r}=await import("./session-seen.js"),{AgentPresence:e}=await import("./presence.js"),s=R();try{const t=s.getDatabase(),n=M(c["archive-days"],0),p=o({db:s,sessionSeen:new r(t),failures:new a(t),presence:new e(t)},{vacuum:c.vacuum===!0,archiveDays:n>0?n:void 0});E("Maintenance complete");for(const i of p.lines)console.log(` - ${i}`);console.log(u.dim(`
|
|
74
|
+
Database size: ${p.dbSize}`))}finally{s.close()}}async function Tt(d){const{positional:c,flags:o}=j(d),a=c[0]??"trend",r=A().version??null,e=R();try{const s=e.getDatabase();if(a==="snapshot"){const t=N(o.kind)||"all",n=[];if((t==="all"||t==="health")&&me(s,"health",st(s),r)!=null&&n.push("health"),(t==="all"||t==="effectiveness")&&me(s,"effectiveness",rt(s),r)!=null&&n.push("effectiveness"),t==="retrieval"||o.full===!0){const p=await Dt();p&&me(s,"retrieval",p,r)!=null?n.push("retrieval"):p||console.log(u.dim(" retrieval: bench unavailable (run from the repo with bench/ present) \u2014 skipped"))}n.length?$(`metrics snapshot recorded: ${n.join(", ")} @ ${r??"unknown"}`):f("metrics snapshot: nothing recorded");return}if(a==="trend"){const t=N(o.kind),n=Number(N(o.limit))||14,p=t?[t]:["health","effectiveness","retrieval"];let i=!1;for(const l of p){const m=Re(s,l,n);if(!m.length)continue;i=!0,E(`${l} \u2014 ${m.length} snapshot(s)`);const g=It[l],h=m.slice().reverse().map(y=>[y.captured_at.slice(0,16),y.wyrm_version??"-",...g.map(w=>Nt(y.metrics[w]))]);console.log(P(["when","ver",...g],h));for(const y of nt(m,l))console.log(" "+u.yellow("!")+" "+y)}i||(console.log(u.dim(" No metrics yet. Record the first snapshot: wyrm metrics snapshot")),console.log(u.dim(" (health + effectiveness are cheap; add --full for retrieval recall@k.)")));return}if(a==="show"){const t=N(o.kind)||"health",n=Re(s,t,1);if(!n.length){console.log(u.dim(` No ${t} snapshot yet.`));return}E(`latest ${t} @ ${n[0].captured_at} (${n[0].wyrm_version??"-"})`),console.log(JSON.stringify(n[0].metrics,null,2));return}f("Usage: wyrm metrics <snapshot [--kind all|health|effectiveness|retrieval] [--full] | trend [--kind K] [--limit N] | show [--kind K]>"),process.exitCode=1}finally{e.close()}}const It={health:["memories","vectors","vector_coverage_pct","review_queue","unresolved_failures","provider"],effectiveness:["failure_blocks","rehydrate_calls","recall_calls","tokens_saved_total"],retrieval:["recall_at_1","recall_at_10","mrr","mode","queries"]};function Nt(d){return d==null?"-":typeof d=="number"?Number.isInteger(d)?String(d):d.toFixed(3):String(d)}async function Dt(){try{const d=X(ee(import.meta.url)),c=W(d,"..","bench"),o=W(c,"lib","retrieval-eval.mjs"),a=W(c,"eval-corpus.json");if(!U(o)||!U(a))return null;const r=process.env.WYRM_VECTOR_PROVIDER||"none";process.env.WYRM_LIVE_MEMORY="0";const{evaluate:e}=await import(o),{WyrmDB:s}=await import("./database.js"),{MemoryArtifacts:t}=await import("./memory-artifacts.js"),n=JSON.parse(H(a,"utf8")),p=`/tmp/wyrm-metrics-eval-${process.pid}.db`,i=new s(p);let l;try{l=e(n,i,t,{k:10})}finally{i.close();for(const g of["","-wal","-shm"])try{Fe(p+g,{force:!0})}catch{}}const m=l.quality.overall;return{mode:r==="none"?"fts-floor":r,k:10,recall_at_1:m.recall_at_1??null,recall_at_10:m.recall_at_k??null,mrr:m.mrr??null,queries:m.n??l.performance?.queries??null,p50_ms:l.performance?.p50_ms??null,p95_ms:l.performance?.p95_ms??null}}catch{return null}}async function Pt(d){const c=console.error;console.error=()=>{};const o=R();let a=0;const r=(s,t)=>{console.log(` ${u.green("\u2714")} ${s} \u2014 ${u.dim(t)}`)},e=(s,t,n)=>{a++,console.log(` ${u.red("\u2716")} ${s} \u2014 ${t}`),console.log(` ${u.yellow("fix:")} ${n}`)};try{const s=o.getDatabase();E("wyrm doctor");const{tierForResolution:t}=await import("./providers/embedding-provider.js"),{effectiveEmbeddingState:n}=await import("./live-embedding-state.js"),p=n(s,process.cwd()),i=t(p),l=p.source==="server"?` \xB7 via running server (pid ${p.pid}${process.cwd()===p.cwd||process.cwd().startsWith(p.cwd.replace(/\/+$/,"")+"/")?"":`, ${p.cwd}`})`:"";p.reason===""&&p.resolved!=="local"?r("Embedding provider",`${p.resolved} (${p.model}) \xB7 tier ${i.n}/3 (${i.label})${p.egressHost?` \xB7 egress: ${p.egressHost}`:" \xB7 local"}${l}`):p.resolved==="local"?e("Embedding provider",`local-hash (hash-384) is NOT semantic \u2014 test-only vectors \xB7 tier ${i.n}/3 (${i.label})${l}`,p.fix||"use NVIDIA NIM: set WYRM_VECTOR_PROVIDER=nim + NVIDIA_API_KEY"):p.reason==="ollama_deprecated"?e("Embedding provider",`ollama (deprecated \u2014 leaves in the next major) \xB7 tier ${i.n}/3 (${i.label})${l}`,p.fix):e("Embedding provider",`none (${p.reason}) \xB7 tier ${i.n}/3 (${i.label})${l}`,p.fix),i.n===2&&console.log(` ${u.dim("next: wyrm upgrade \u2192 max recall (hosted NIM)")}`);const m=s.prepare("SELECT COUNT(*) AS n FROM memory_artifacts").get().n;if(p.resolved==="none"||p.resolved==="local"){let y=0;try{y=s.prepare("SELECT COUNT(*) AS n FROM vectors").get().n}catch{}e("Vector index",`${y} vector(s) / ${m} memories \u2014 recall is FTS5 keyword-only (~59.9% vs 72.2% hybrid recall@10)`,p.fix||"enable a provider, then: wyrm index rebuild")}else{let y=0;try{y=s.prepare("SELECT COUNT(DISTINCT content_id) AS n FROM vectors WHERE content_type = 'artifact' AND model = ?").get(p.model).n}catch{}if(y===0&&m>0)e("Vector index",`provider '${p.resolved}' is configured but 0 of ${m} memories are indexed`,"wyrm index rebuild");else{const w=m>0?Math.round(y/m*100):100;r("Vector index",`${y} of ${m} memories indexed under ${p.model} (${w}%)`),w<100&&console.log(` ${u.dim("next: wyrm index rebuild backfills the rest")}`)}}try{const y=s.prepare("SELECT COUNT(*) AS n FROM memory_artifacts_fts").get().n;y===m?r("FTS index",`${y}/${m} rows in sync`):e("FTS index",`${y} FTS rows vs ${m} memories \u2014 keyword recall is missing rows`,"INSERT INTO memory_artifacts_fts(memory_artifacts_fts) VALUES('rebuild') via wyrm maintenance")}catch{e("FTS index","memory_artifacts_fts unreadable","wyrm maintenance")}const g=s.prepare("SELECT COUNT(*) AS n FROM failure_patterns WHERE resolved = 0").get().n;r("Failure firewall",`${g} unresolved pattern(s) \xB7 matching = exact signature + FTS5 fuzzy (no vector tier in this build)`);const h=s.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE needs_review = 1").get().n;h>0?e("Review queue",`${h} memor${h===1?"y":"ies"} invisible to recall until approved`,"wyrm review"):r("Review queue","empty");try{const y=s.prepare("SELECT MAX(version) AS v FROM schema_versions").get().v;r("Schema",`migration v${y??0}`)}catch{e("Schema","schema_versions unreadable","wyrm maintenance")}console.log(""),a===0?$("All checks passed \u2014 nothing is silently off."):(f(`${a} check(s) DEGRADED \u2014 the fixes above are exact.`),process.exitCode=1)}finally{o.close(),console.error=c}}const Mt=new Set(["nomic-embed-text","nomic-embed-text-v1.5-int8","nvidia/llama-nemotron-embed-1b-v2","nvidia/llama-3.2-nv-embedqa-1b-v2","nvidia/nv-embedqa-e5-v5","nvidia/nv-embedqa-mistral-7b-v2","nvidia/nv-embed-v1","text-embedding-3-small","text-embedding-3-large","hash-384","none"]);async function Ot(d){const{tierForResolution:c}=await import("./providers/embedding-provider.js"),{detectClients:o,loadWyrmMeta:a}=await import("./autoconfig.js"),r=l=>l.split(le()).join("~"),e=l=>l&&(Mt.has(l)?l:"custom"),s=A(),{effectiveEmbeddingState:t}=await import("./live-embedding-state.js"),n=console.error;console.error=()=>{};const p=R(),i=["## Wyrm Report",""];try{const l=p.getDatabase(),m=t(l,process.cwd()),g=c(m),h=b=>{try{return l.prepare(b).get().n}catch{return 0}};i.push(`version: ${s.version??"unknown"}`),i.push(`search tier: ${g.n}/3 (${g.label}) \xB7 provider: ${m.resolved}${m.model?` (${e(m.model)})`:""}${m.reason?` \xB7 reason: ${m.reason}`:""}${m.source==="server"?" \xB7 via running server":""}`),i.push(`corpus: ${h("SELECT COUNT(*) AS n FROM memory_artifacts")} memories \xB7 ${h("SELECT COUNT(*) AS n FROM vectors")} vectors \xB7 ${h("SELECT COUNT(*) AS n FROM ground_truths WHERE is_current = 1")} truths \xB7 ${h("SELECT COUNT(*) AS n FROM failure_patterns WHERE resolved = 0")} armed failures`);const y=l.prepare("SELECT date FROM sessions ORDER BY id DESC LIMIT 1").get();i.push(`last session: ${y?.date??"none yet"}`);const w=o().filter(b=>b.configured).map(b=>b.id);i.push(`clients: ${w.length?w.join(", "):"none configured"}`);const v=W(le(),".claude","hooks","wyrm-session-capture.mjs");i.push(`hooks: ${U(v)?"installed (Claude Code)":"not installed (model-driven capture on non-Claude-Code clients)"}`);const k=a();i.push(`setup: ${k?`clients ${k.configuredClients.join(", ")} (last setup ${k.lastSetup})`:"no setup metadata"}`),i.push(`db: ${r(Ce())}`)}finally{p.close(),console.error=n}console.log("```"),console.log(i.join(`
|
|
75
|
+
`)),console.log("```")}async function At(d){const{positional:c,flags:o}=j(d),a=c[0]??"list",r=R();try{const e=r.getDatabase();if(a==="list"){const s=e.prepare("SELECT id, scope, target, occurrences, last_seen FROM failure_patterns WHERE resolved = 0 ORDER BY last_seen DESC LIMIT 25").all();if(E("Unresolved failures"),!s.length){console.log(u.dim(" none \u2014 the firewall has nothing active."));return}console.log(P(["ID","Scope","Target","Seen","Last seen"],s.map(t=>[String(t.id),t.scope,t.target.slice(0,48),String(t.occurrences),t.last_seen]))),console.log(u.dim(`
|
|
76
|
+
resolve one: wyrm failure resolve <id>`));return}if(a==="resolve"){const s=Number(c[1]);if(!Number.isInteger(s)||s<=0){f('Usage: wyrm failure resolve <id> [--note "root cause fixed by ..."]'),process.exitCode=1;return}const t=N(o.note);(e.prepare("UPDATE failure_patterns SET resolved = 1, resolution_note = ?, last_seen = datetime('now') WHERE id = ? AND resolved = 0").run(t||"resolved via wyrm failure resolve",s).changes??0)>0?$(`Failure #${s} resolved \u2014 it will no longer flag.`):(f(`No unresolved failure #${s}.`),process.exitCode=1);return}f("Usage: wyrm failure <list|resolve <id> [--note N]>"),process.exitCode=1}finally{r.close()}}function xe(d,c){const o=[],a=`--${c}`;for(let r=0;r<d.length;r++)if(d[r]===a&&r+1<d.length)for(const e of d[r+1].split(",")){const s=e.trim();if(s==="")continue;const t=Number(s);if(!Number.isInteger(t))throw new Error(`${a} must be a comma-separated list of integers (got "${s}")`);o.push(t)}return o}async function Lt(d,c){const{positional:o}=j(d),a="Usage: wyrm recall --propose <query> [--project <name>] [--run <id>] [--limit N]",r=typeof c.propose=="string"?c.propose:o[0];if(!r){f(a),process.exitCode=1;return}const e=N(c.limit);let s;if(e&&(s=Number(e),!Number.isInteger(s)||s<1)){f(`--limit must be a positive integer (got "${e}")`),process.exitCode=1;return}const{buildRecallProposal:t}=await import("./handlers/recall.js"),{FailurePatterns:n}=await import("./failure-patterns.js"),{sanitizeActorId:p}=await import("./handlers/boundary.js"),i=R();try{const l=N(c.project),m=l?I(i,l):null;if(l&&!m){f(`Project not found: ${l}`),process.exitCode=1;return}const g=N(c.run),h=p(g||process.env.WYRM_RUN_ID),y=i.getDatabase(),w=new B(y),v=new de(y),k=new n(y),b=await t({store:i,raw:()=>y,memory:w,truths:v,failures:k},{query:r,projectId:m?.id??null,runId:h,limit:s});E(`Recall proposal -- "${r}"`);const C=(S,x)=>{if(console.log(u.bold(`
|
|
77
|
+
${S} (${x.length})`)),x.length===0){console.log(u.dim(" (none)"));return}for(const T of x)console.log(` #${T.id} [${T.kind}/${T.outcome}] ${T.summary}`),console.log(u.dim(` conf ${(T.confidence*100).toFixed(0)}% | ${T.age_days}d old${T.project?` | ${T.project}`:""}`))};C("Prescriptions (muted by clean mode)",b.prescriptions),C("Firewall (never muted)",b.firewall),C("Ground truths",b.truths),console.log(u.dim("\n Review-only -- use `wyrm recall --set` to mute/veto specific ids."))}finally{i.close()}}async function Wt(d){const{flags:c}=j(d);if(c.propose!==void 0)return Lt(d,c);const o="Usage: wyrm recall --set [--mode full|clean|custom] [--run <id>] [--mute <id>[,<id>...]] [--challenge <id>[,<id>...]] | wyrm recall --propose <query> [--project <name>] [--run <id>] [--limit N]";if(!c.set){f(o),process.exitCode=1;return}const{sanitizeActorId:a}=await import("./handlers/boundary.js"),{upsertRecallPolicy:r}=await import("./handlers/recall.js"),{RECALL_POLICY_MODES:e}=await import("./recall-policy.js"),s=N(c.run),t=a(s||process.env.WYRM_RUN_ID);if(!t){f("No run id: pass --run <id>, or export WYRM_RUN_ID (see `wyrm run start`)."),process.exitCode=1;return}let n;if(c.mode!==void 0){const m=N(c.mode);if(!e.includes(m)){f(`--mode must be one of: ${e.join(", ")} (got "${m}")`),process.exitCode=1;return}n=m}let p,i;try{p=xe(d,"mute"),i=xe(d,"challenge")}catch(m){f(m instanceof Error?m.message:String(m)),process.exitCode=1;return}const l=R();try{const m=r(l.getDatabase(),{runId:t,mode:n,muteIds:p.length?p:void 0,challengeTruthIds:i.length?i:void 0});$(`Recall policy for run ${t}: mode=${m.mode}`),console.log(u.dim(` Muted ids: ${m.mutedIds.length?m.mutedIds.join(", "):"(none)"}`)),console.log(u.dim(` Challenged truth ids: ${m.challengedTruthIds.length?m.challengedTruthIds.join(", "):"(none)"}`))}finally{l.close()}}async function Ut(d){const{positional:c,flags:o}=j(d),a=c[0]??"list",r=R();try{if(a==="add"){const e=c[1],s=N(o.path);let t,n;if(s?(t=Z(s),n=e):e&&U(Z(e))?(t=Z(e),n=void 0):(t=Z(process.cwd()),n=e),!U(t)){f(`Path does not exist: ${t}`),process.exitCode=1;return}const p=N(o.name)||n||We(t),i=r.registerProject(p,t);$(`Project #${i.id} '${i.name}' registered at ${i.path}`);return}if(a==="list"){const e=r.getAllProjects(50);E("Projects"),console.log(P(["ID","Name","Path"],e.map(s=>[String(s.id),s.name,s.path])));return}f("Usage: wyrm project <add <name> [--path <dir>] | list>"),process.exitCode=1}finally{r.close()}}async function Ft(d){const{positional:c,flags:o}=j(d),a="Usage: wyrm index <setup|rebuild|status> [--provider auto|local|bundled|nim|openai|none] [--model M] [--project P] [--dry-run]";if(o.help===!0||typeof o.help=="string"){console.log(a);return}const r=c[0]??"status",{createVectorStore:e}=await import("./vectors.js"),t={provider:o.provider??process.env.WYRM_VECTOR_PROVIDER??"auto",model:o.model,apiKey:o["api-key"]??process.env.OPENAI_API_KEY,ollamaUrl:o["ollama-url"]};if(r==="setup"){const{createProvider:p}=await import("./providers/embedding-provider.js"),i=p(t);if(!await i.isReady()&&t.provider!=="none"){f(`Provider not ready: ${i.name}. Check the configuration and try again.`),process.exitCode=1;return}$(`Vector provider verified: ${i.name} (model ${i.model}, ${i.dimensions}d)`),console.log(u.dim(" The MCP server reads WYRM_VECTOR_PROVIDER (and provider-specific env) at boot \u2014")),console.log(u.dim(` set WYRM_VECTOR_PROVIDER=${i.name==="none"?"none":t.provider} in the server env, then: wyrm index rebuild`));return}const n=R();try{const p=n.getDatabase(),i=e(t,p);if(r==="status"){const l=i.getStats();E("Vector index");const m=[["Provider",l.provider],["Model",l.model],["Vectors",String(l.total)],...Object.entries(l.byType).map(([g,h])=>[` ${g}`,String(h)])];console.log(P(["Field","Value"],m));return}if(r==="rebuild"){const{reindexProjects:l}=await import("./reindex.js"),m=o["dry-run"]===!0,g=o.project;let h;if(g){const k=n.getProject(g)??I(n,g);if(!k){f(`Project not found: ${g}`),process.exitCode=1;return}h=[k.id]}else h=n.getAllProjects(1e3).map(k=>k.id);const{indexed:y,skipped:w}=await l(p,i,h,{dryRun:m,onError:(k,b)=>f(`${k}: ${JSON.stringify(b)}`)}),v=`Reindex ${m?"(dry run) ":""}\u2014 ${h.length} project(s), ${y} indexed, ${w} skipped`;if(y===0&&w>0){const{resolveEmbeddingState:k}=await import("./providers/embedding-provider.js"),b=k(t.provider);Ee(`${v}: ${b.reason||"embedding unavailable"}. fix: ${b.fix||"wyrm vectors download"}`)}else $(v);return}f(a),process.exitCode=1}finally{n.close()}}async function qt(d){const{positional:c,flags:o}=j(d);if(o.help===!0||typeof o.help=="string"){console.log("Usage: wyrm vectors <download|status> [--force]");return}const a=c[0]??"status",{bundledModelPresent:r,downloadBundledModel:e,BUNDLED_MODEL_DIR:s,MANIFEST:t,BUNDLED_MODEL_SIZE_LABEL:n}=await import("./providers/bundled-model.js"),{resolveEmbeddingState:p,tierForResolution:i}=await import("./providers/embedding-provider.js");if(a==="status"){const y=console.error;console.error=()=>{};try{const{effectiveEmbeddingState:w}=await import("./live-embedding-state.js");let v=null,k=null;try{k=R(),v=k.getDatabase()}catch{v=null}const b=w(v,process.cwd());try{k?.close()}catch{}const C=i(b);E("wyrm vectors"),console.log(` provider: ${b.resolved}${b.model?` (${b.model})`:""}${b.source==="server"?` \xB7 via running server (pid ${b.pid})`:""}`),console.log(` tier: ${C.n}/3 (${C.label})`),console.log(` bundled model: ${r()?`present at ${s()}`:"not downloaded (run: wyrm vectors download)"}`)}finally{console.error=y}return}if(a!=="download"){f("Usage: wyrm vectors <download|status> [--force]"),process.exitCode=1;return}if(r()&&o.force!==!0){$("Bundled model already present.");return}E("Downloading bundled embedding model");const l=t.reduce((y,w)=>y+w.size,0);let m=-1;const g=await e({onProgress:(y,w,v)=>{const k=Math.floor(w/v*100);k!==m&&(m=k,process.stdout.write(`\r ${y}: ${k}% `))}});if(process.stdout.write(`
|
|
78
|
+
`),!g.ok){f(`Download failed: ${g.error}`),console.log(" Recall stays keyword-only until this succeeds. Retry: wyrm vectors download"),process.exitCode=1;return}$(`Model ready (${n}). Vector recall is on.`);const{runBundledBackfill:h}=await import("./reindex.js");await h()}function N(d){return typeof d=="string"?d:""}function Yt(d){try{return new URL(d).host}catch{return d}}async function Vt(d){if(!process.stdin.isTTY){f("wyrm upgrade is interactive; run it in a terminal."),process.exitCode=1;return}const{tierForResolution:c}=await import("./providers/embedding-provider.js"),{effectiveEmbeddingState:o}=await import("./live-embedding-state.js");let a=null,r=null;try{r=R(),a=r.getDatabase()}catch{a=null}const e=o(a,process.cwd());try{r?.close()}catch{}const s=c(e);if(E("wyrm upgrade"),console.log(` Current: tier ${s.n}/3 (${s.label})${e.model?` \xB7 ${e.model}`:""}${e.source==="server"?` \xB7 via running server (pid ${e.pid})`:""}`),s.n===3){$("Already on the max-recall tier.");return}console.log(" Next: tier 3/3 (max recall), hosted NVIDIA NIM embeddings (2048d)."),console.log(" Published local hybrid row: 60.3/72.2 recall@5/@10; NIM lifts retrieval further (see BENCHMARKS.md)."),console.log(`
|
|
79
|
+
1. Get a free API key: ${u.cyan("https://build.nvidia.com")} (Get API Key on any embedding model page)`);let t;try{t=(await Je(" 2. Paste your key (nvapi-...): ")).trim()}catch(l){if(l instanceof ze){console.log(""),process.exitCode=130;return}throw l}if(!t.startsWith("nvapi-")){f("That does not look like a NIM key (expected nvapi- prefix). Nothing written."),process.exitCode=1;return}process.stdout.write(" 3. Validating with a live embed call... ");const{NimProvider:n}=await import("./providers/embedding-provider.js");try{if(!(await new n(t).embed("wyrm connectivity probe")).length)throw new Error("empty embedding");console.log(u.green("ok"))}catch(l){console.log(u.red("failed")),f(`Key validation failed: ${l}. Nothing written.`),process.exitCode=1;return}const i=(await import("node:readline/promises")).createInterface({input:process.stdin,output:process.stdout});try{const{detectClients:l,applyWyrmEnvToClient:m}=await import("./autoconfig.js"),g=l().filter(v=>v.configured);if(!g.length){f("No configured clients found. Run wyrm-setup first."),process.exitCode=1;return}const h={WYRM_VECTOR_PROVIDER:"nim",WYRM_NIM_API_KEY:t};let y=0;for(const v of g){let k=!1;try{const C=(await import("node:fs")).readFileSync(v.configPath,"utf-8");k=/WYRM_VECTOR_PROVIDER/.test(C)}catch{}if(k&&(await i.question(` ${v.name} already sets a provider. Overwrite with NIM? [y/N] `)).trim().toLowerCase()!=="y"){console.log(` ${u.dim("skipped")}`);continue}const b=m(v,h);b.action==="updated"&&y++,console.log(` ${b.action==="updated"?u.green("\u2714"):u.dim("\u25CB")} ${v.name}: ${b.message}`)}if(y===0&&(Ee("No client config was changed (all skipped or failed). The NIM tier is NOT active yet."),console.log(u.dim(" Re-run and answer y to overwrite, or set WYRM_VECTOR_PROVIDER=nim + WYRM_NIM_API_KEY in your client env by hand."))),(await i.question(" Reindex existing memories on the NIM tier now? [Y/n] ")).trim().toLowerCase()!=="n"){const v=R();try{const k=v.getDatabase(),{createVectorStore:b}=await import("./vectors.js"),{reindexProjects:C}=await import("./reindex.js"),S=b({provider:"nim",apiKey:t},k),x=v.getAllProjects(1e3).map(Y=>Y.id),{indexed:T,skipped:L}=await C(k,S,x,{dryRun:!1});$(`Reindexed on NIM: ${T} indexed, ${L} skipped.`)}finally{v.close()}}else console.log(` ${u.dim("Skipped. New memories embed on NIM from now on; EXISTING memories stay findable by keyword and on their previous vector tier, but not with NIM-quality recall until you run: wyrm index rebuild")}`);y>0?$(`Upgrade complete (${y} client${y===1?"":"s"} updated). Restart your AI clients to pick up the new env.`):process.exitCode=1}finally{i.close()}}async function Ht(d){const{flags:c}=j(d),{getUpdateStatus:o}=await import("./version-check.js"),a=A().version??"0.0.0",r=R();let e;try{e=await o(r.getDatabase(),a,{force:c.force===!0||c.check===!0})}finally{r.close()}E("Wyrm update");const s=e.latest?e.lookupFailed?`${e.latest} (last known \u2014 registry unreachable now)`:e.latest:e.lookupFailed?"unknown \u2014 npm registry unreachable":"unknown (version check disabled)";if(console.log(P(["Field","Value"],[["Current",e.current],["Latest",s],["Update available",e.updateAvailable?"yes":e.lookupFailed&&!e.latest?"unknown":"no"],["Checked",`${e.checkedAt} (${e.source})`]])),e.lookupFailed&&!e.updateAvailable&&c.force!==!0){f('Could not reach the npm registry, so whether an update exists is UNKNOWN (not "up to date").'),console.log(u.dim(" Retry when online: wyrm update \xB7 or install directly: npm install -g wyrm-mcp@latest")),process.exitCode=2;return}if(c.check===!0)return;if(!e.updateAvailable&&c.force!==!0){console.log(u.dim(`
|
|
80
80
|
Already up to date. (Use --force to reinstall anyway.)`));return}console.log(u.dim(`
|
|
81
81
|
Running: npm install -g wyrm-mcp@latest --allow-scripts=wyrm-mcp,better-sqlite3
|
|
82
|
-
`));const t=te("npm",["install","-g","wyrm-mcp@latest","--allow-scripts=wyrm-mcp,better-sqlite3"],{stdio:"inherit",shell:!1});t.status===0
|
|
83
|
-
Total: ${i.total_hours.toFixed(2)}h across ${i.entries.length} session(s)`+(i.estimated_sessions>0?u.dim(` (${i.estimated_sessions} estimated)`):""))}finally{t.close()}}async function Gt(d){const{positional:c,flags:o}=j(d),a=c[0]??"generate",
|
|
84
|
-
`,"utf-8")
|
|
85
|
-
`)}finally{p.close()}}async function Jt(d){const{positional:c,flags:o}=j(d),a=c[0]??"status",{AgentDaemon:
|
|
86
|
-
=== Recent log ===`),console.log(s.recentLog(40)));return}case"stop":{const t=await s.stop({grace_ms:o.grace!==void 0?
|
|
82
|
+
`));const t=te("npm",["install","-g","wyrm-mcp@latest","--allow-scripts=wyrm-mcp,better-sqlite3"],{stdio:"inherit",shell:!1});t.status===0?$("Updated. Restart your MCP clients to pick up the new binary."):(f(`npm install exited with ${t.status??"unknown"}`),process.exitCode=t.status??1)}async function Bt(d){const{positional:c,flags:o}=j(d),a=c[0],r=o.project??process.cwd();if(a==="inject"){const{injectSystemPrompt:e}=await import("./autoconfig.js"),s=typeof o.clients=="string"?o.clients.split(",").map(n=>n.trim()).filter(Boolean):[],t=e(r,s);E("System prompt injection");for(const n of t.injected)console.log(` + ${n}`);for(const n of t.skipped)console.log(u.dim(` o skipped (unknown client): ${n}`));for(const n of t.errors)f(n);t.injected.length>0&&$("AI clients in this project will now call wyrm_session_prime at conversation start."),t.errors.length>0&&(process.exitCode=1);return}if(a==="migrate"){const{migrateProject:e,renderMigrationReport:s}=await import("./migrate-prompt.js"),{WYRM_INJECT_BLOCK:t}=await import("./autoconfig.js"),n=o.apply===!0,p=e({projectPath:r,newBlock:t,apply:n});console.log(s(p,n));return}f("Usage: wyrm prompt inject [--project <path>] [--clients copilot,cursor] | wyrm prompt migrate [--project <path>] [--apply]"),process.exitCode=1}async function Kt(d){const{positional:c,flags:o}=j(d);(c[0]??"report")!=="report"&&(f("Usage: wyrm hours report --from YYYY-MM-DD --to YYYY-MM-DD [--project <name>] [--session-hours H] [--json]"),process.exit(1));const r=o.from,e=o.to;(!r||!e)&&(f("--from and --to are required (YYYY-MM-DD)"),process.exit(1));const{HourLedger:s}=await import("./hours.js"),t=R();try{const n=o.project,p=n?I(t,n):null;if(n&&!p){f(`Project not found: ${n}`),process.exitCode=1;return}const i=new s(t.getDatabase()).report({range_start:r,range_end:e,project_id:p?.id,default_session_hours:se(o["session-hours"],1)});if(o.json===!0){console.log(JSON.stringify(i,null,2));return}if(E(`Hours ${i.range.start} \u2192 ${i.range.end}`),i.by_project.length===0){console.log(u.dim(" No sessions in range."));return}console.log(P(["Project","Sessions","Hours"],i.by_project.map(l=>[l.project_name,String(l.session_count),l.hours.toFixed(2)]))),console.log(`
|
|
83
|
+
Total: ${i.total_hours.toFixed(2)}h across ${i.entries.length} session(s)`+(i.estimated_sessions>0?u.dim(` (${i.estimated_sessions} estimated)`):""))}finally{t.close()}}async function Gt(d){const{positional:c,flags:o}=j(d),a=c[0]??"generate",r=o.client,e=se(o.rate,NaN),s=o.from,t=o.to;(a!=="generate"||!r||!Number.isFinite(e)||!s||!t)&&(f('Usage: wyrm invoice generate --client <name> --rate <usd/hour> --from YYYY-MM-DD --to YYYY-MM-DD [--project <name>] [--number INV-X] [--currency USD] [--notes "\u2026"] [--out <path>]'),process.exit(1));const{HourLedger:n}=await import("./hours.js"),p=R();try{const i=o.project,l=i?I(p,i):null;if(i&&!l){f(`Project not found: ${i}`),process.exitCode=1;return}const m=new n(p.getDatabase()).invoice({client_name:r,hourly_rate_usd:e,range_start:s,range_end:t,project_id:l?.id,invoice_number:o.number,currency:o.currency,notes:o.notes,business_name:o["business-name"],business_address:o["business-address"],business_contact:o["business-contact"],client_address:o["client-address"],default_session_hours:se(o["session-hours"],1)}),g=o.out;if(g){const{writeFileSync:h}=await import("node:fs");h(g,m+`
|
|
84
|
+
`,"utf-8"),$(`Invoice written to ${g}`)}else process.stdout.write(m+`
|
|
85
|
+
`)}finally{p.close()}}async function Jt(d){const{positional:c,flags:o}=j(d),a=c[0]??"status",{AgentDaemon:r}=await import("./agent-daemon.js"),e=R();try{const s=new r(e.getDatabase());switch(a){case"init":case"start":{const t=Math.max(10,Math.min(M(o.interval,600),86400)),n=s.start({interval_seconds:t,max_steps:o["max-steps"]!==void 0&&M(o["max-steps"],0)||void 0,project_path:o.project,verbose:o.verbose===!0});if(!n.ok){f(`Agent init failed: ${n.error}`),process.exitCode=1;return}const p=n.status;$(`Agent ${p.pid!=null&&p.pid!==n.pid?"already running":"started"} \u2014 pid ${p.pid}`),console.log(` Interval: ${t}s \xB7 Active goals: ${p.active_goals} \xB7 Total iterations: ${p.total_iterations}`),console.log(u.dim(` Log: ${p.log_file}`));return}case"status":{const t=s.status();E("Wyrm agent"),console.log(t.running?` RUNNING \u2014 pid ${t.pid}${t.started_at?` (since ${t.started_at})`:""}`:" NOT RUNNING. Start it with: wyrm agent init"),console.log(` Active goals: ${t.active_goals} \xB7 Total iterations: ${t.total_iterations}`),t.last_action&&console.log(` Last action (${t.last_action.ran_at}): ${t.last_action.summary} [${t.last_action.result_status??"?"}]`),o.log===!0&&(console.log(`
|
|
86
|
+
=== Recent log ===`),console.log(s.recentLog(40)));return}case"stop":{const t=await s.stop({grace_ms:o.grace!==void 0?M(o.grace,3e3):void 0});if(!t.ok){f(`Stop failed: ${t.error}`),process.exitCode=1;return}$(t.was_running?`Agent stopped (was pid ${t.pid}). Goals remain in DB \u2014 wyrm agent init resumes.`:"Agent was not running. (No-op.)");return}case"restart":{const t=await s.restart({interval_seconds:o.interval!==void 0?M(o.interval,600):void 0,max_steps:o["max-steps"]!==void 0&&M(o["max-steps"],0)||void 0,project_path:o.project,verbose:o.verbose===!0});if(!t.ok){f(`Restart failed: ${t.error}`),process.exitCode=1;return}$(`Agent restarted \u2014 pid ${t.status.pid}. Active goals: ${t.status.active_goals}.`);return}default:f("Usage: wyrm agent <init|status|stop|restart> [--interval N] [--max-steps N] [--project <path>] [--verbose] [--log]"),process.exitCode=1}}finally{e.close()}}async function zt(d){if(d.includes("--encrypt")){const{initializeLicense:a,hasFeature:r}=await import("./license.js");if(a(),!r("encryption")){f("Encryption setup requires a Pro license or higher. See: wyrm license"),process.exitCode=1;return}const{getCrypto:e,initializeCrypto:s}=await import("./crypto.js"),t=d.includes("--enable"),n=d.includes("--test");if(t){const i=process.env.WYRM_ENCRYPTION_KEY??(process.stdin.isTTY?"":je());if(!i||i.length<8){f('Password must be at least 8 characters. Set WYRM_ENCRYPTION_KEY or pipe it: printf %s "$PW" | wyrm setup --encrypt --enable'),process.exitCode=1;return}s(i),$("Encryption enabled (AES-256-GCM, key derived via PBKDF2). Store your password safely \u2014 it cannot be recovered.");return}const p=e();if(n){if(!p.isEnabled()){f("Encryption not enabled. Run: wyrm setup --encrypt --enable"),process.exitCode=1;return}const i="Wyrm encryption test "+Date.now();p.decrypt(p.encrypt(i))===i?$("Encryption test PASSED (encrypt \u2192 decrypt roundtrip)."):(f("Encryption test FAILED."),process.exitCode=1);return}E("Encryption status"),console.log(` Enabled: ${p.isEnabled()?"yes \u2014 new data is encrypted at rest":"no"}`),console.log(" Algorithm: AES-256-GCM"),p.isEnabled()||console.log(u.dim(" Enable with: wyrm setup --encrypt --enable (password via WYRM_ENCRYPTION_KEY or stdin)"));return}const c=X(ee(import.meta.url)),o=te(process.execPath,[W(c,"setup.js"),...d],{stdio:"inherit",shell:!1});process.exitCode=o.status??0}async function Qt(d){const c="https://github.com/Ghosts-Protocol-Pvt-Ltd/wyrm-mcp",a=`- wyrm-mcp: ${A().version??"unknown"}
|
|
87
87
|
- node: ${process.version}
|
|
88
|
-
- platform: ${process.platform} ${process.arch}`,
|
|
88
|
+
- platform: ${process.platform} ${process.arch}`,r=d.includes("--bug")?"bug":d.includes("--idea")||d.includes("--feature")?"idea":d.includes("--question")||d.includes("--ask")?"question":"feedback",e=d.filter(p=>!p.startsWith("--")).join(" ").trim(),s={bug:`**What happened**
|
|
89
89
|
|
|
90
90
|
|
|
91
91
|
**What you expected**
|
|
@@ -111,7 +111,7 @@ ${a}`,feedback:`**Your feedback** (what's working, what's rough)
|
|
|
111
111
|
|
|
112
112
|
|
|
113
113
|
---
|
|
114
|
-
${a}`},t={bug:"bug",idea:"enhancement",question:"question",feedback:"feedback"};let r
|
|
114
|
+
${a}`},t={bug:"bug",idea:"enhancement",question:"question",feedback:"feedback"};let n;r==="question"?n=`${c}/discussions/new?category=q-a`+(e?`&title=${encodeURIComponent(e)}`:"")+`&body=${encodeURIComponent(s.question)}`:n=`${c}/issues/new?labels=${encodeURIComponent(t[r])}&title=${encodeURIComponent(`[${r}] ${e}`.trim())}&body=${encodeURIComponent(s[r])}`,console.log(""),console.log(" "+u.bold("Thanks for helping make Wyrm better.")),console.log(" Opening a prefilled report in your browser. If it does not open, use this link:"),console.log(""),console.log(" "+u.cyan(n)),console.log(""),console.log(u.dim(" Prefer email? ryan@ghosts.lk \xB7 Bug: wyrm feedback --bug Idea: --idea Question: --question")),console.log("");try{const{spawn:p}=await import("child_process"),i=process.platform,l=i==="darwin"?p("open",[n],{stdio:"ignore",detached:!0}):i==="win32"?p("cmd",["/c","start","",n],{stdio:"ignore",detached:!0}):p("xdg-open",[n],{stdio:"ignore",detached:!0});l.on("error",()=>{}),l.unref()}catch{}}function Te(){console.log(`
|
|
115
115
|
${F.brightMagenta}\u{F115D} Wyrm CLI v${A().version??"unknown"}${F.reset}
|
|
116
116
|
${F.dim}Persistent AI Memory System${F.reset}
|
|
117
117
|
|
|
@@ -196,15 +196,15 @@ ${u.bold("Examples:")}
|
|
|
196
196
|
wyrm sync export --out ~/wyrm-backup.wyrm
|
|
197
197
|
wyrm sync preview --from ~/wyrm-backup.wyrm
|
|
198
198
|
wyrm prune --project MyApp --min-confidence 0.2 --older-than 30
|
|
199
|
-
`)}const[,,q,..._]=process.argv;process.env.WYRM_LOG_LEVEL||(process.env.WYRM_LOG_LEVEL="warn");function Te(d){const c=d.ref_table?`${d.ref_table}${d.ref_id?"#"+d.ref_id:""}`:"",o=new Date(d.created_at).toLocaleTimeString();return`#${d.cursor} ${d.kind.padEnd(15)} ${c.padEnd(16)} ${ot(d.actor)} ${o}`}async function Xt(d){const{positional:c,flags:o}=j(d),a=c[0]||"since",n=R();try{if(!n.liveMemoryEnabled()){f("Live Memory is disabled (set WYRM_LIVE_MEMORY=1)."),process.exitCode=1;return}const e=(typeof o.project=="string"?o.project:"")||process.cwd(),s=n.getProject(e)??n.getProjectByName(e);if(!s){f(`Project not found: ${e}`),process.exitCode=1;return}if(a==="publish"){const t=c[1]||(typeof o.kind=="string"?o.kind:"");if(!t){f("usage: wyrm events publish <kind> --project <p> [--actor A] [--ref-table T --ref-id ID]"),process.exitCode=1;return}n.publishEvent({projectId:s.id,kind:t,refTable:typeof o["ref-table"]=="string"?o["ref-table"]:void 0,refId:typeof o["ref-id"]=="string"?o["ref-id"]:void 0,actor:typeof o.actor=="string"?o.actor:void 0}),v(`Event published (${t}) to ${s.name}`);return}if(a==="since"){const t=P(o.cursor,0),r=P(o.limit,50),p=n.eventsSince(s.id,t,r);for(const i of p)console.log(Te(i));E(`${p.length} event(s) for '${s.name}' since cursor ${t}`);return}f("usage: wyrm events <publish|since> ..."),process.exitCode=1}finally{n.close()}}async function Zt(d){const{flags:c}=j(d),o=R();if(!o.liveMemoryEnabled()){f("Live Memory is disabled (set WYRM_LIVE_MEMORY=1)."),o.close(),process.exitCode=1;return}const a=(typeof c.project=="string"?c.project:"")||process.cwd(),n=o.getProject(a)??T(o,a);if(!n){f(`Project not found: ${a}`),o.close(),process.exitCode=1;return}const e=Math.max(250,P(c.interval,1e3));let s=P(c.since,o.subscribeEvents(n.id,1).cursor);E(`Watching '${n.name}' (cursor ${s}, every ${e}ms) \u2014 Ctrl-C to stop`);const t=()=>{try{for(const i of o.eventsSince(n.id,s,200))s=i.cursor,console.log(Te(i))}catch{}};t();const r=setInterval(t,e),p=()=>{clearInterval(r);try{o.close()}catch{}process.exit(0)};process.on("SIGINT",p),process.on("SIGTERM",p)}async function eo(d){const{flags:c}=j(d),{embedAll:o,removeAll:a,statusAll:n}=await import("./priority-embed.js"),e={projectDir:typeof c.project=="string"?c.project:void 0,allClients:c.all===!0},s=t=>console.log(` ${String(t.result??t.status).padEnd(9)} [${t.scope}] ${t.file}`);if(c.status){E("Wyrm priority embedding \u2014 status"),n(e).forEach(s);return}if(c.remove){E("Wyrm priority embedding \u2014 removed"),a(e).forEach(s);return}E("Wyrm is now FIRST-PRIORITY memory"),o(e).forEach(s);try{const{installClaudeCodeHooks:t,installClaudeStatusline:r}=await import("./autoconfig.js");t()?v("Proactive hooks installed (SessionStart rehydrate + capture + tool-trace)."):console.log(" (Claude Code not detected \u2014 skipped hook install.)");const i=r();i&&v(`Buddy statusline: ${i.message}`)}catch{}v("Wyrm will now be read first, primed proactively, and shown in the TUI at all times.")}async function to(d){const{flags:c}=j(d),{harvestProjects:o}=await import("./harvest.js"),{MemoryArtifacts:a}=await import("./memory-artifacts.js"),{escapeLikePattern:n}=await import("./auto-capture.js"),e=R();try{const s=e.getDatabase(),t=new a(s),r={existsBySig:(w,$)=>!!s.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(w,"%"+n($)+"%"),addCandidate:(w,$)=>t.add(w,{kind:$.kind,problem:$.text,tags:[...$.tags,$.sig],confidence:$.confidence,needsReview:1,createdBy:"harvest"})},p=typeof c.project=="string"?c.project:void 0;let i;if(p){const w=e.getProject(p)??e.getProjectByName(p);if(!w){f(`Project not found: ${p}`),process.exitCode=1;return}i=[{id:w.id,name:w.name,path:w.path}]}else i=e.getAllProjects(500).map(w=>({id:w.id,name:w.name,path:w.path}));const l=c["dry-run"]===!0||c.dry===!0,m=c.code===!0||c["include-code"]===!0,{reports:g,totalAdded:h,totalSkipped:y}=o(r,i,{dryRun:l,gitLimit:P(c.limit,30),includeCode:m});E(`Harvest ${l?"(dry run) ":""}\u2014 ${h} candidate(s), ${y} already present (${i.length} project(s))`);for(const w of g.filter($=>$.added>0).sort(($,k)=>k.added-$.added).slice(0,25))console.log(` +${String(w.added).padStart(3)} (skip ${w.skipped}) ${w.project}`);if(m&&!l){const{SymbolGraph:w}=await import("./symbols.js"),$=new w(s);let k=0,b=0;for(const C of i)try{const S=$.indexProject(C.id,C.path);k+=S.symbols,b+=S.files}catch{}console.log(` \u{1F4D0} Indexed ${k} code symbols (${b} files) \u2192 searchable via 'wyrm search'`)}!l&&h>0&&v("Review with: wyrm review")}finally{e.close()}}async function oo(d){const c=await import("./vault.js"),[o,...a]=d;try{switch(o){case"set":{const n=a[0];if(!n){f("usage: wyrm vault set <name> (the secret is read from STDIN, never argv)"),process.exitCode=1;return}if(process.stdin.isTTY){f(`pipe the secret in, e.g.: printf %s "$TOKEN" | wyrm vault set ${n}`),process.exitCode=1;return}const s=(await import("node:fs")).readFileSync(0,"utf8").replace(/\r?\n$/,"");if(!s){f("empty secret on stdin"),process.exitCode=1;return}c.vaultSet(n,s),v(`Stored "${n}" (AES-256-GCM). Use it without exposing it: wyrm vault exec ${n} -- <command>`);break}case"get":{const n=a[0];if(!n){f("usage: wyrm vault get <name>"),process.exitCode=1;return}const e=c.vaultGet(n);if(e===void 0){f(`no secret named "${n}"`),process.exitCode=1;return}process.stdout.write(e);break}case"list":case"ls":{const n=c.vaultList();if(!n.length){console.log("(vault is empty)");break}E(`Vault \u2014 ${n.length} secret(s)`);for(const e of n)console.log(" \u2022 "+e);break}case"rm":case"remove":case"delete":{const n=a[0];if(!n){f("usage: wyrm vault rm <name>"),process.exitCode=1;return}v(c.vaultRemove(n)?`Removed "${n}"`:`(no secret named "${n}")`);break}case"exec":{const n=a[0],e=a.indexOf("--");if(!n||e===-1||e+1>=a.length){f("usage: wyrm vault exec <name> [--as ENVVAR] -- <command...>"),process.exitCode=1;return}const s=a.slice(1,e),t=s.indexOf("--as"),r=t>=0?s[t+1]:n.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),p=a.slice(e+1),i=c.vaultGet(n);if(i===void 0){f(`no secret named "${n}"`),process.exitCode=1;return}const l=te(p[0],p.slice(1),{stdio:"inherit",env:{...process.env,[r]:i}});process.exitCode=l.status??1;break}case"import-npm":{const n=await import("node:fs"),e=await import("node:os"),t=(await import("node:path")).join(e.homedir(),".npmrc");if(!n.existsSync(t)){f("~/.npmrc not found"),process.exitCode=1;return}const r=n.readFileSync(t,"utf8").match(/\/\/registry\.npmjs\.org\/:_authToken=(.+)/);if(!r){f("no npm authToken found in ~/.npmrc"),process.exitCode=1;return}c.vaultSet("npm-token",r[1].trim()),v('Imported npm token \u2192 vault as "npm-token". You can now scrub the plaintext from ~/.npmrc and use: wyrm vault exec npm-token --as NODE_AUTH_TOKEN -- npm publish');break}case"setup":{const n=c.vaultPaths();if(n.secure)v(`Vault is already secure (backend: ${n.backend}, ${n.count} secret(s)).`);else{const e=n.keychainAvailable?"keychain":"passphrase";if(e==="passphrase"&&!process.env.WYRM_VAULT_PASSPHRASE){f("No OS keychain on this host. Set WYRM_VAULT_PASSPHRASE, then re-run: wyrm vault setup"),process.exitCode=1;return}const s=c.vaultSecure({backend:e});v(`Vault secured: ${s.from} \u2192 ${s.to}${s.rotated?" (key rotated)":""}.`),s.keyfileShredded&&console.log(" plaintext vault.key: shredded \u2714"),s.backup&&console.log(` ciphertext backup: ${s.backup} (delete once confirmed)`)}E("Store & use credentials safely"),console.log(' store: printf %s "$TOKEN" | wyrm vault set <name> # reads STDIN \u2014 never argv/shell history'),console.log(" use: wyrm vault exec <name> --as ENV_VAR -- <cmd> # injected as env var, never printed"),console.log(" list: wyrm vault list inspect: wyrm vault info");break}case"secure":{const n=a.indexOf("--backend"),e=n>=0?a[n+1]:"keychain";if(e!=="keychain"&&e!=="passphrase"){f("usage: wyrm vault secure [--backend keychain|passphrase] [--no-rotate]"),process.exitCode=1;return}if(e==="passphrase"&&!process.env.WYRM_VAULT_PASSPHRASE){f("set WYRM_VAULT_PASSPHRASE before: wyrm vault secure --backend passphrase"),process.exitCode=1;return}const s=!a.includes("--no-rotate"),t=c.vaultSecure({backend:e,rotate:s});v(`Vault secured: ${t.from} \u2192 ${t.to}${t.rotated?" (key rotated)":""}.`),console.log(` secrets re-encrypted: ${t.secrets}`),t.keyfileShredded&&console.log(" plaintext vault.key: shredded \u2714"),t.backup&&console.log(` ciphertext backup: ${t.backup} (delete once you've confirmed)`),console.log(e==="keychain"?" master key now lives in the OS keychain \u2014 not on disk.":" master key now derived from WYRM_VAULT_PASSPHRASE \u2014 keep that set for future use.");break}case"info":{const n=c.vaultPaths();E("Vault"),console.log(` backend: ${n.backend}`),console.log(` secrets: ${n.count}`),console.log(` store: ${n.vault} (0600)`),console.log(` key: ${n.backend==="keyfile"?n.key+" (0600)":n.backend==="keychain"?"(OS keychain \u2014 no key on disk)":"(derived from WYRM_VAULT_PASSPHRASE \u2014 no key on disk)"}`),console.log(` secure: ${n.secure?"yes \u2014 key is not a plaintext file beside the ciphertext":"NO \u2014 key sits beside ciphertext"}`),n.secure||console.log(n.keychainAvailable?" \u26A0 run `wyrm vault secure` to move the key into the OS keychain.":" \u26A0 no OS keychain found \u2014 set WYRM_VAULT_PASSPHRASE and run `wyrm vault secure --backend passphrase`.");break}default:f("usage: wyrm vault <setup|set|get|list|rm|exec|import-npm|secure|info>"),process.exitCode=1}}catch(n){f(`vault: ${n.message}`),process.exitCode=1}}function so(){const d=X(ee(import.meta.url)),o=[W(d,"..","skills"),W(d,"..","..","skills")].find(n=>U(n));if(!o)return[];const a=[];for(const n of Ue(o,{withFileTypes:!0})){if(!n.isDirectory())continue;const e=W(o,n.name,"SKILL.md");if(!U(e))continue;let s=n.name,t="";try{const r=H(e,"utf8"),p=r.match(/^name:\s*(.+)$/m);if(p&&(s=p[1].trim()),/^description:\s*[|>]/m.test(r))t=((r.split(/^description:.*$/m)[1]??"").split(`
|
|
200
|
-
`).find(m=>m.trim())??"").trim();else{const i=
|
|
199
|
+
`)}const[,,q,..._]=process.argv;process.env.WYRM_LOG_LEVEL||(process.env.WYRM_LOG_LEVEL="warn");function Ie(d){const c=d.ref_table?`${d.ref_table}${d.ref_id?"#"+d.ref_id:""}`:"",o=new Date(d.created_at).toLocaleTimeString();return`#${d.cursor} ${d.kind.padEnd(15)} ${c.padEnd(16)} ${ot(d.actor)} ${o}`}async function Xt(d){const{positional:c,flags:o}=j(d),a=c[0]||"since",r=R();try{if(!r.liveMemoryEnabled()){f("Live Memory is disabled (set WYRM_LIVE_MEMORY=1)."),process.exitCode=1;return}const e=(typeof o.project=="string"?o.project:"")||process.cwd(),s=r.getProject(e)??r.getProjectByName(e);if(!s){f(`Project not found: ${e}`),process.exitCode=1;return}if(a==="publish"){const t=c[1]||(typeof o.kind=="string"?o.kind:"");if(!t){f("usage: wyrm events publish <kind> --project <p> [--actor A] [--ref-table T --ref-id ID]"),process.exitCode=1;return}r.publishEvent({projectId:s.id,kind:t,refTable:typeof o["ref-table"]=="string"?o["ref-table"]:void 0,refId:typeof o["ref-id"]=="string"?o["ref-id"]:void 0,actor:typeof o.actor=="string"?o.actor:void 0}),$(`Event published (${t}) to ${s.name}`);return}if(a==="since"){const t=M(o.cursor,0),n=M(o.limit,50),p=r.eventsSince(s.id,t,n);for(const i of p)console.log(Ie(i));E(`${p.length} event(s) for '${s.name}' since cursor ${t}`);return}f("usage: wyrm events <publish|since> ..."),process.exitCode=1}finally{r.close()}}async function Zt(d){const{flags:c}=j(d),o=R();if(!o.liveMemoryEnabled()){f("Live Memory is disabled (set WYRM_LIVE_MEMORY=1)."),o.close(),process.exitCode=1;return}const a=(typeof c.project=="string"?c.project:"")||process.cwd(),r=o.getProject(a)??I(o,a);if(!r){f(`Project not found: ${a}`),o.close(),process.exitCode=1;return}const e=Math.max(250,M(c.interval,1e3));let s=M(c.since,o.subscribeEvents(r.id,1).cursor);E(`Watching '${r.name}' (cursor ${s}, every ${e}ms) \u2014 Ctrl-C to stop`);const t=()=>{try{for(const i of o.eventsSince(r.id,s,200))s=i.cursor,console.log(Ie(i))}catch{}};t();const n=setInterval(t,e),p=()=>{clearInterval(n);try{o.close()}catch{}process.exit(0)};process.on("SIGINT",p),process.on("SIGTERM",p)}async function eo(d){const{flags:c}=j(d),{embedAll:o,removeAll:a,statusAll:r}=await import("./priority-embed.js"),e={projectDir:typeof c.project=="string"?c.project:void 0,allClients:c.all===!0},s=t=>console.log(` ${String(t.result??t.status).padEnd(9)} [${t.scope}] ${t.file}`);if(c.status){E("Wyrm priority embedding \u2014 status"),r(e).forEach(s);return}if(c.remove){E("Wyrm priority embedding \u2014 removed"),a(e).forEach(s);return}E("Wyrm is now FIRST-PRIORITY memory"),o(e).forEach(s);try{const{installClaudeCodeHooks:t,installClaudeStatusline:n}=await import("./autoconfig.js");t()?$("Proactive hooks installed (SessionStart rehydrate + capture + tool-trace)."):console.log(" (Claude Code not detected \u2014 skipped hook install.)");const i=n();i&&$(`Buddy statusline: ${i.message}`)}catch{}$("Wyrm will now be read first, primed proactively, and shown in the TUI at all times.")}async function to(d){const{flags:c}=j(d),{harvestProjects:o}=await import("./harvest.js"),{MemoryArtifacts:a}=await import("./memory-artifacts.js"),{escapeLikePattern:r}=await import("./auto-capture.js"),e=R();try{const s=e.getDatabase(),t=new a(s),n={existsBySig:(w,v)=>!!s.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(w,"%"+r(v)+"%"),addCandidate:(w,v)=>t.add(w,{kind:v.kind,problem:v.text,tags:[...v.tags,v.sig],confidence:v.confidence,needsReview:1,createdBy:"harvest"})},p=typeof c.project=="string"?c.project:void 0;let i;if(p){const w=e.getProject(p)??e.getProjectByName(p);if(!w){f(`Project not found: ${p}`),process.exitCode=1;return}i=[{id:w.id,name:w.name,path:w.path}]}else i=e.getAllProjects(500).map(w=>({id:w.id,name:w.name,path:w.path}));const l=c["dry-run"]===!0||c.dry===!0,m=c.code===!0||c["include-code"]===!0,{reports:g,totalAdded:h,totalSkipped:y}=o(n,i,{dryRun:l,gitLimit:M(c.limit,30),includeCode:m});E(`Harvest ${l?"(dry run) ":""}\u2014 ${h} candidate(s), ${y} already present (${i.length} project(s))`);for(const w of g.filter(v=>v.added>0).sort((v,k)=>k.added-v.added).slice(0,25))console.log(` +${String(w.added).padStart(3)} (skip ${w.skipped}) ${w.project}`);if(m&&!l){const{SymbolGraph:w}=await import("./symbols.js"),v=new w(s);let k=0,b=0;for(const C of i)try{const S=v.indexProject(C.id,C.path);k+=S.symbols,b+=S.files}catch{}console.log(` \u{1F4D0} Indexed ${k} code symbols (${b} files) \u2192 searchable via 'wyrm search'`)}!l&&h>0&&$("Review with: wyrm review")}finally{e.close()}}async function oo(d){const c=await import("./vault.js"),[o,...a]=d;try{switch(o){case"set":{const r=a[0];if(!r){f("usage: wyrm vault set <name> (the secret is read from STDIN, never argv)"),process.exitCode=1;return}if(process.stdin.isTTY){f(`pipe the secret in, e.g.: printf %s "$TOKEN" | wyrm vault set ${r}`),process.exitCode=1;return}const s=(await import("node:fs")).readFileSync(0,"utf8").replace(/\r?\n$/,"");if(!s){f("empty secret on stdin"),process.exitCode=1;return}c.vaultSet(r,s),$(`Stored "${r}" (AES-256-GCM). Use it without exposing it: wyrm vault exec ${r} -- <command>`);break}case"get":{const r=a[0];if(!r){f("usage: wyrm vault get <name>"),process.exitCode=1;return}const e=c.vaultGet(r);if(e===void 0){f(`no secret named "${r}"`),process.exitCode=1;return}process.stdout.write(e);break}case"list":case"ls":{const r=c.vaultList();if(!r.length){console.log("(vault is empty)");break}E(`Vault \u2014 ${r.length} secret(s)`);for(const e of r)console.log(" \u2022 "+e);break}case"rm":case"remove":case"delete":{const r=a[0];if(!r){f("usage: wyrm vault rm <name>"),process.exitCode=1;return}$(c.vaultRemove(r)?`Removed "${r}"`:`(no secret named "${r}")`);break}case"exec":{const r=a[0],e=a.indexOf("--");if(!r||e===-1||e+1>=a.length){f("usage: wyrm vault exec <name> [--as ENVVAR] -- <command...>"),process.exitCode=1;return}const s=a.slice(1,e),t=s.indexOf("--as"),n=t>=0?s[t+1]:r.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),p=a.slice(e+1),i=c.vaultGet(r);if(i===void 0){f(`no secret named "${r}"`),process.exitCode=1;return}const l=te(p[0],p.slice(1),{stdio:"inherit",env:{...process.env,[n]:i}});process.exitCode=l.status??1;break}case"import-npm":{const r=await import("node:fs"),e=await import("node:os"),t=(await import("node:path")).join(e.homedir(),".npmrc");if(!r.existsSync(t)){f("~/.npmrc not found"),process.exitCode=1;return}const n=r.readFileSync(t,"utf8").match(/\/\/registry\.npmjs\.org\/:_authToken=(.+)/);if(!n){f("no npm authToken found in ~/.npmrc"),process.exitCode=1;return}c.vaultSet("npm-token",n[1].trim()),$('Imported npm token \u2192 vault as "npm-token". You can now scrub the plaintext from ~/.npmrc and use: wyrm vault exec npm-token --as NODE_AUTH_TOKEN -- npm publish');break}case"setup":{const r=c.vaultPaths();if(r.secure)$(`Vault is already secure (backend: ${r.backend}, ${r.count} secret(s)).`);else{const e=r.keychainAvailable?"keychain":"passphrase";if(e==="passphrase"&&!process.env.WYRM_VAULT_PASSPHRASE){f("No OS keychain on this host. Set WYRM_VAULT_PASSPHRASE, then re-run: wyrm vault setup"),process.exitCode=1;return}const s=c.vaultSecure({backend:e});$(`Vault secured: ${s.from} \u2192 ${s.to}${s.rotated?" (key rotated)":""}.`),s.keyfileShredded&&console.log(" plaintext vault.key: shredded \u2714"),s.backup&&console.log(` ciphertext backup: ${s.backup} (delete once confirmed)`)}E("Store & use credentials safely"),console.log(' store: printf %s "$TOKEN" | wyrm vault set <name> # reads STDIN \u2014 never argv/shell history'),console.log(" use: wyrm vault exec <name> --as ENV_VAR -- <cmd> # injected as env var, never printed"),console.log(" list: wyrm vault list inspect: wyrm vault info");break}case"secure":{const r=a.indexOf("--backend"),e=r>=0?a[r+1]:"keychain";if(e!=="keychain"&&e!=="passphrase"){f("usage: wyrm vault secure [--backend keychain|passphrase] [--no-rotate]"),process.exitCode=1;return}if(e==="passphrase"&&!process.env.WYRM_VAULT_PASSPHRASE){f("set WYRM_VAULT_PASSPHRASE before: wyrm vault secure --backend passphrase"),process.exitCode=1;return}const s=!a.includes("--no-rotate"),t=c.vaultSecure({backend:e,rotate:s});$(`Vault secured: ${t.from} \u2192 ${t.to}${t.rotated?" (key rotated)":""}.`),console.log(` secrets re-encrypted: ${t.secrets}`),t.keyfileShredded&&console.log(" plaintext vault.key: shredded \u2714"),t.backup&&console.log(` ciphertext backup: ${t.backup} (delete once you've confirmed)`),console.log(e==="keychain"?" master key now lives in the OS keychain \u2014 not on disk.":" master key now derived from WYRM_VAULT_PASSPHRASE \u2014 keep that set for future use.");break}case"info":{const r=c.vaultPaths();E("Vault"),console.log(` backend: ${r.backend}`),console.log(` secrets: ${r.count}`),console.log(` store: ${r.vault} (0600)`),console.log(` key: ${r.backend==="keyfile"?r.key+" (0600)":r.backend==="keychain"?"(OS keychain \u2014 no key on disk)":"(derived from WYRM_VAULT_PASSPHRASE \u2014 no key on disk)"}`),console.log(` secure: ${r.secure?"yes \u2014 key is not a plaintext file beside the ciphertext":"NO \u2014 key sits beside ciphertext"}`),r.secure||console.log(r.keychainAvailable?" \u26A0 run `wyrm vault secure` to move the key into the OS keychain.":" \u26A0 no OS keychain found \u2014 set WYRM_VAULT_PASSPHRASE and run `wyrm vault secure --backend passphrase`.");break}default:f("usage: wyrm vault <setup|set|get|list|rm|exec|import-npm|secure|info>"),process.exitCode=1}}catch(r){f(`vault: ${r.message}`),process.exitCode=1}}function so(){const d=X(ee(import.meta.url)),o=[W(d,"..","skills"),W(d,"..","..","skills")].find(r=>U(r));if(!o)return[];const a=[];for(const r of Ue(o,{withFileTypes:!0})){if(!r.isDirectory())continue;const e=W(o,r.name,"SKILL.md");if(!U(e))continue;let s=r.name,t="";try{const n=H(e,"utf8"),p=n.match(/^name:\s*(.+)$/m);if(p&&(s=p[1].trim()),/^description:\s*[|>]/m.test(n))t=((n.split(/^description:.*$/m)[1]??"").split(`
|
|
200
|
+
`).find(m=>m.trim())??"").trim();else{const i=n.match(/^description:\s*(.+)$/m);i&&(t=i[1].trim())}}catch{}a.push({name:s,description:t})}return a.sort((r,e)=>r.name.localeCompare(e.name))}async function ro(d){const c=d[0];if(!c||c==="help"||c==="--help"){console.log(`Usage:
|
|
201
201
|
wyrm skill list show the bundled guides + your registered skills
|
|
202
202
|
wyrm skill backfill-content read every skill's SKILL.md into the registry (idempotent)
|
|
203
203
|
wyrm skill export <targetDir> [--all] materialize SKILL.md files from stored content
|
|
204
|
-
wyrm skill share <name|--all|--tier T> [--public|--private] [--include-inactive] set cloud-sync visibility (single or bulk)`);return}if(c==="list"||c==="ls"){const a=so();if(E("Bundled skill guides (shipped in the box)"),a.length===0)console.log(u.yellow(" none found next to this install"));else{for(const e of a)console.log(` ${u.cyan(e.name)}`),e.description&&console.log(` ${u.dim(e.description)}`);console.log(u.dim("\n Read one: open its SKILL.md, or `wyrm skill export <dir>` to materialize all."))}const
|
|
204
|
+
wyrm skill share <name|--all|--tier T> [--public|--private] [--include-inactive] set cloud-sync visibility (single or bulk)`);return}if(c==="list"||c==="ls"){const a=so();if(E("Bundled skill guides (shipped in the box)"),a.length===0)console.log(u.yellow(" none found next to this install"));else{for(const e of a)console.log(` ${u.cyan(e.name)}`),e.description&&console.log(` ${u.dim(e.description)}`);console.log(u.dim("\n Read one: open its SKILL.md, or `wyrm skill export <dir>` to materialize all."))}const r=R();try{const e=r.listSkills(!0);if(E(`Registered skills in your memory (${e.length})`),e.length===0)console.log(u.dim(" none yet \u2014 register with wyrm_skill_register or author with wyrm_skill_create"));else{for(const s of e.slice(0,40))console.log(` ${u.cyan(s.name)}${s.tier?u.dim(" ["+s.tier+"]"):""}`);e.length>40&&console.log(u.dim(` \u2026 and ${e.length-40} more`))}}finally{r.close()}return}const o=R();try{if(c==="backfill-content"||c==="backfill"){E("Backfill SKILL.md content into the registry");const a=o.backfillSkillContent();$(`${a.filled} filled . ${a.unchanged} unchanged . ${a.missing} missing-file (of ${a.total} registered)`),a.missing>0&&console.log(u.yellow(` ${a.missing} skill(s) had no readable SKILL.md \u2014 re-run after restoring their files.`));return}if(c==="export"){const a=d[1];a||(f("Usage: wyrm skill export <targetDir> [--all]"),o.close(),process.exit(1));const r=d.includes("--all");E(`Export skills \u2192 ${a}`);const e=o.exportSkillContent(a,{includeInactive:r});$(`${e.written} SKILL.md written . ${e.skipped_no_content} skipped (no stored content) (of ${e.total} ${r?"total":"active"})`),e.skipped_no_content>0&&console.log(u.yellow(" Run `wyrm skill backfill-content` on the source machine to populate content first.")),e.collisions>0&&console.log(u.yellow(` ${e.collisions} slug collision(s) disambiguated with a name-hash suffix (distinct skills, same slug) \u2014 no content lost.`));return}if(c==="share"){const a=d.includes("--private")?"within":d.includes("--public")?"public":"org",r=d.includes("--include-inactive"),e=d.indexOf("--tier"),s=e>=0?d[e+1]:void 0;if(e>=0&&(!s||s.startsWith("--"))&&(f("Usage: wyrm skill share --tier <god|mega|atomic> [--public|--private] [--include-inactive]"),o.close(),process.exit(1)),d.includes("--all")||!!s){const i=o.setAllSkillsVisibility(a,{tier:s,includeInactive:r}),l=s?`tier '${s}'`:r?"all skills":"all active skills";$(`${i} skill(s) (${l}) visibility \u2192 '${a}'.`),console.log(a==="within"?" These skills will NOT egress on cloud sync (private).":` ${i} skills are now cloud-sync-eligible (they leave on the next \`wyrm cloud sync\`).`);return}const n=d[1];n||(f("Usage: wyrm skill share <name|--all|--tier <tier>> [--public|--private] [--include-inactive]"),o.close(),process.exit(1)),o.setSkillVisibility(n,a)||(f(`Skill not found: ${n}`),o.close(),process.exit(1)),$(`Skill "${n}" visibility \u2192 '${a}'.`),console.log(a==="within"?" This skill will NOT egress on cloud sync (private).":" This skill is now cloud-sync-eligible (it leaves on the next `wyrm cloud sync`).");return}f(`Unknown skill subcommand: ${c}`),process.exit(1)}finally{o.close()}}async function no(d){const c=d[0]??"status",o=R(),a=o.getDatabase();if(a.prepare("PRAGMA table_info(projects)").all().some(e=>e.name==="sync_policy")||(f("Grove sync policy is not on this database yet (upgrade Wyrm so migrations apply)."),o.close(),process.exit(1)),c==="status"||c==="ls"||c==="list"){E("Grove sync policy + leak audit");const e=a.prepare("SELECT id, name, sync_policy FROM projects ORDER BY id").all(),s=["ground_truths","memory_artifacts","quests","design_tokens","design_references"],t=["ground_truths","memory_artifacts","quests","sessions","decision_edges"],n=(l,m,g)=>{let h=0;for(const y of l)try{h+=a.prepare(`SELECT COUNT(*) AS n FROM ${y} WHERE project_id = ? AND ${g}`).get(m).n}catch{}return h},p=[];let i=0;for(const l of e){const m=n(s,l.id,"cross_project_visibility IN ('org','public')"),g=n(t,l.id,"is_shared = 1"),h=l.sync_policy==="private"&&m+g>0;h&&i++;const y=h?u.red(`LEAK: ${m} promoted + ${g} shared in a PRIVATE grove`):`${m} promoted / ${g} shared`;p.push([String(l.id),l.name,l.sync_policy,y])}console.log(P(["#","Grove","sync_policy","rows eligible to leave"],p)),console.log(`
|
|
205
205
|
private = never replicates . cloud = your own cloud backup . team = federates to a team Wyrm`),i>0&&console.log(u.red(`
|
|
206
|
-
! ${i} private grove(s) hold rows marked to leave. Re-private those rows or change the grove lane.`)),o.close();return}if(c==="policy"||c==="set"){const e=d[1],s=d[2];(!e||!["private","cloud","team"].includes(s))&&(f("Usage: wyrm grove policy <project|id> <private|cloud|team>"),o.close(),process.exit(1));let t=
|
|
206
|
+
! ${i} private grove(s) hold rows marked to leave. Re-private those rows or change the grove lane.`)),o.close();return}if(c==="policy"||c==="set"){const e=d[1],s=d[2];(!e||!["private","cloud","team"].includes(s))&&(f("Usage: wyrm grove policy <project|id> <private|cloud|team>"),o.close(),process.exit(1));let t=I(o,e);!t&&/^\d+$/.test(e)&&(t=a.prepare("SELECT id, name FROM projects WHERE id = ?").get(Number(e))),t||(f(`Grove not found: ${e}`),o.close(),process.exit(1)),a.prepare("UPDATE projects SET sync_policy = ? WHERE id = ?").run(s,t.id),$(`Grove "${t.name}" set to '${s}'.`),s!=="private"&&console.log(` Rows still only leave when also marked ${s==="team"?"is_shared (team)":"org/public (cloud)"}. The grove is the outer gate.`),o.close();return}f(`Unknown grove subcommand: ${c}`),console.log(`Usage:
|
|
207
207
|
wyrm grove status
|
|
208
|
-
wyrm grove policy <project|id> <private|cloud|team>`),o.close(),process.exit(1)}async function io(d){const c=d[0],{flags:o}=j(d.slice(1)),{ulid:a}=await import("./ulid.js"),{createRun:
|
|
208
|
+
wyrm grove policy <project|id> <private|cloud|team>`),o.close(),process.exit(1)}async function io(d){const c=d[0],{flags:o}=j(d.slice(1)),{ulid:a}=await import("./ulid.js"),{createRun:r,setRunStatus:e,registerAgent:s,getRun:t,getAgents:n}=await import("./handlers/run.js"),{sanitizeActorId:p}=await import("./handlers/boundary.js"),i=g=>typeof g=="string"?p(g):null,l=R(),m=l.getDatabase();try{switch(c){case"start":{const g=(typeof o.orchestrator=="string"?o.orchestrator:"cli").slice(0,200),h=i(o.agent)??p(g)??"cli",y=i(o.parent);if(y&&!t(m,y)){f(`Parent run not found: ${y}`),process.exitCode=1;return}const w=a();r(m,w,y,g),s(m,w,h,"orchestrator"),process.stdout.write(w+`
|
|
209
209
|
`),process.stderr.write(`Run ${w} started by ${g}.
|
|
210
|
-
`);break}case"join":{const g=i(o.run),h=i(o.agent);if(!g||!h){f("Usage: wyrm run join --run <RUNID> --agent <ID> [--role <ROLE>]"),process.exitCode=1;return}if(!t(m,g)){f(`Run not found: ${g}`),process.exitCode=1;return}const y=typeof o.role=="string"?o.role.slice(0,200):null;s(m,g,h,y)
|
|
210
|
+
`);break}case"join":{const g=i(o.run),h=i(o.agent);if(!g||!h){f("Usage: wyrm run join --run <RUNID> --agent <ID> [--role <ROLE>]"),process.exitCode=1;return}if(!t(m,g)){f(`Run not found: ${g}`),process.exitCode=1;return}const y=typeof o.role=="string"?o.role.slice(0,200):null;s(m,g,h,y),$(`${h} joined run ${g}${y?` as ${y}`:""}.`);break}case"end":{const g=i(o.run);if(!g){f("Usage: wyrm run end --run <RUNID> [--status completed|failed|abandoned]"),process.exitCode=1;return}if(!t(m,g)){f(`Run not found: ${g}`),process.exitCode=1;return}const h=typeof o.status=="string"?o.status:"completed",w=["completed","failed","abandoned"].includes(h)?h:"completed";e(m,g,w),$(`Run ${g} ended (${w}).`);break}case"status":{const g=i(o.run);if(!g){f("Usage: wyrm run status --run <RUNID>"),process.exitCode=1;return}const h=t(m,g);if(!h){f(`Run not found: ${g}`),process.exitCode=1;return}const y=n(m,g);E(`Run ${h.run_id} [${h.status}]`),h.orchestrator&&console.log(u.bold("Orchestrator: ")+h.orchestrator),h.parent_run_id&&console.log(u.bold("Parent: ")+h.parent_run_id),console.log(u.bold("Created: ")+h.created_at),console.log(u.bold("Updated: ")+h.updated_at),y.length>0?console.log(P(["Agent","Role","Joined"],y.map(w=>[w.agent_id,w.role??"",w.joined_at]))):console.log(u.dim(" No agents registered."));break}default:f("Usage: wyrm run <start|join|end|status> [options]"),console.log(" wyrm run start [--orchestrator NAME] [--agent ID] [--parent RUNID]"),console.log(" wyrm run join --run RUNID --agent ID [--role ROLE]"),console.log(" wyrm run end --run RUNID [--status completed|failed|abandoned]"),console.log(" wyrm run status --run RUNID"),process.exitCode=1;return}}finally{l.close()}}if(q==="--version"||q==="-v"||q==="version"){const d=A();console.log(`${d.name??"wyrm-mcp"} v${d.version??"unknown"}`)}else!q||q==="--help"||q==="-h"||q==="help"?Te():(async()=>{try{switch(q){case"search":await it(_);break;case"ls":await at(_);break;case"show":await ct(_);break;case"capture":await lt(_);break;case"rehydrate":await ut(_);break;case"session":await gt(_);break;case"presence":await yt(_);break;case"digest":await dt(_);break;case"bridge":await ft(_);break;case"metabolize":await pt(_);break;case"entities":await mt(_);break;case"render":await ht(_);break;case"reverse-bridge":await wt(_);break;case"import":await bt(_);break;case"stats":await $t(_);break;case"review":await kt(_);break;case"sync":await _t(_);break;case"cloud":{const{cmdCloud:d}=await import("./cloud/cli.js");await d(_);break}case"grove":await no(_);break;case"run":await io(_);break;case"skill":await ro(_);break;case"prune":await Et(_);break;case"license":await Rt();break;case"login":await Ct();break;case"activate":await jt(_);break;case"maintenance":await xt(_);break;case"doctor":await Pt(_);break;case"report":await Ot(_);break;case"metrics":await Tt(_);break;case"failure":await At(_);break;case"recall":await Wt(_);break;case"project":await Ut(_);break;case"index":await Ft(_);break;case"vectors":await qt(_);break;case"update":await Ht(_);break;case"upgrade":await Vt(_);break;case"prompt":await Bt(_);break;case"hours":await Kt(_);break;case"invoice":await Gt(_);break;case"agent":await Jt(_);break;case"feedback":await Qt(_);break;case"setup":await zt(_);break;case"intro":{const{renderIntro:d}=await import("./visibility.js");console.log(d(A().version??"unknown"));break}case"events":await Xt(_);break;case"watch":await Zt(_);break;case"embed":await eo(_);break;case"harvest":await to(_);break;case"vault":await oo(_);break;case"connector":case"connectors":await St(_);break;case"statusline":{const{installClaudeStatusline:d,removeClaudeStatusline:c}=await import("./autoconfig.js"),o=_.includes("--remove")?c():d();o?$(o.message):f("Claude Code not detected (~/.claude missing).");break}case"guard":{const{installWyrmGuardHooks:d,removeWyrmGuardHooks:c,wyrmGuardHookStatus:o}=await import("./autoconfig.js");if(_.includes("--status")){const r=o();if(console.log(` settings: ${r.settingsPath}`),r.installed){$(`wyrm-guard hooks installed (${r.commands.length} entr${r.commands.length===1?"y":"ies"})`);for(const e of r.commands)console.log(u.dim(` ${e}`))}else console.log(u.yellow(" wyrm-guard hooks not installed \u2014 run: wyrm guard"));break}const a=_.includes("--remove")||_.includes("--uninstall")?c():d();a?a.action==="failed"?(f(a.message),process.exitCode=1):$(a.message):f("Claude Code not detected (~/.claude missing).");break}case"ui":case"dashboard":_.includes("--ui")||_.push("--ui");case"serve":{const d=_.includes("--ui");if(d){const{enableDevMode:e}=await import("./http-auth.js");e()}const{server:c,primeLicenseRevocations:o}=await import("./http-fast.js");o();const a=parseInt(process.env.WYRM_PORT??process.env.PORT??"3333",10),r=process.env.WYRM_BIND_HOST||"127.0.0.1";c.listen(a,r,()=>{if($(`Wyrm HTTP server running on ${r}:${a}`),process.env.WYRM_UI_READONLY==="1"&&console.log("\u{1F512} READ-ONLY mode: writes + off-box egress are blocked; safe to expose."),d){const e=`http://localhost:${a}/ui`;console.log(`\u{1F5A5}\uFE0F Dashboard: ${e}`),import("child_process").then(({spawn:s})=>{const t=process.platform;try{const n=t==="darwin"?s("open",[e],{stdio:"ignore",detached:!0}):t==="win32"?s("cmd",["/c","start","",e],{stdio:"ignore",detached:!0}):s("xdg-open",[e],{stdio:"ignore",detached:!0});n.on("error",()=>{}),n.unref()}catch{}}).catch(()=>{})}});break}default:f(`Unknown command: ${q}`),Te(),process.exit(1)}}catch(d){f(String(d)),process.exit(1)}})();
|
package/dist/wyrm-manifest.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wyrm-mcp",
|
|
3
|
-
"version": "8.7.
|
|
3
|
+
"version": "8.7.1",
|
|
4
4
|
"mcpName": "lk.ghosts/wyrm",
|
|
5
5
|
"description": "Local-first persistent memory for AI agents over MCP. Ground truths, negative learning (recorded failures block repeats), decision causality, hybrid recall, negotiated recall (clean-mode injection you steer), live memory streams, run-attributed fleet memory — a structured SQLite memory on your machine, no cloud or LLM required. Claude / Copilot / Cursor / Windsurf / Codex.",
|
|
6
6
|
"type": "module",
|