wyrm-mcp 9.2.0 → 9.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -0
- package/dist/auto-runs.js +1 -0
- package/dist/autoconfig.js +3 -3
- package/dist/capabilities.js +3 -3
- package/dist/causality.js +13 -8
- package/dist/cli.js +25 -22
- package/dist/cloud/cli.js +3 -3
- package/dist/cloud/sync-daemon-entrypoint.js +2 -2
- package/dist/cloud/sync-daemon.js +1 -1
- package/dist/color.js +1 -0
- package/dist/database.js +3 -3
- package/dist/deprecations.js +2 -2
- package/dist/events.js +6 -6
- package/dist/federation.js +10 -10
- package/dist/handlers/arg-keys.js +1 -0
- package/dist/handlers/capture.js +58 -58
- package/dist/handlers/causality.js +8 -8
- package/dist/handlers/cloud.js +85 -83
- package/dist/handlers/companion.js +10 -10
- package/dist/handlers/entity.js +1 -1
- package/dist/handlers/events.js +12 -12
- package/dist/handlers/failure.js +12 -12
- package/dist/handlers/goals.js +4 -4
- package/dist/handlers/intelligence.js +63 -63
- package/dist/handlers/mcpclient.js +1 -1
- package/dist/handlers/presence.js +3 -3
- package/dist/handlers/project-arg.js +1 -0
- package/dist/handlers/project.js +1 -1
- package/dist/handlers/quest.js +5 -3
- package/dist/handlers/recall.js +18 -18
- package/dist/handlers/registry.js +1 -1
- package/dist/handlers/resources.js +1 -1
- package/dist/handlers/review.js +3 -3
- package/dist/handlers/run.js +3 -3
- package/dist/handlers/search.js +3 -3
- package/dist/handlers/session.js +24 -24
- package/dist/handlers/share.js +5 -5
- package/dist/handlers/shims.js +1 -1
- package/dist/handlers/thread.js +2 -2
- package/dist/http-auth.js +1 -1
- package/dist/http-fast.js +15 -15
- package/dist/index.js +2 -2
- package/dist/logger.js +2 -2
- package/dist/receipt.js +1 -1
- package/dist/rehydration.js +24 -9
- package/dist/render.js +3 -3
- package/dist/setup.js +2 -3
- package/dist/sqlite-busy.js +1 -1
- package/dist/stale-servers.js +2 -0
- package/dist/stdio-lifecycle.js +1 -0
- package/dist/storage/index.js +3 -3
- package/dist/tool-manifest-v2.json +1 -1
- package/dist/tool-manifest.json +1 -1
- package/dist/ui-dashboard.js +9 -8
- package/dist/validate.js +1 -1
- package/dist/vault-exec.js +4 -0
- package/dist/vault.js +1 -1
- package/dist/wyrm-cli.js +105 -142
- package/dist/wyrm-manifest.json +3 -3
- package/dist/wyrm-ui.js +14 -7
- package/dist/wyrm.js +2 -0
- package/package.json +6 -4
- package/scripts/hooks/wyrm-citation-audit.mjs +155 -46
- package/scripts/hooks/wyrm-prompt-context.mjs +300 -0
- package/scripts/hooks/wyrm-run-auto.mjs +148 -37
- package/scripts/hooks/wyrm-session-rehydrate.mjs +142 -24
package/dist/wyrm-cli.js
CHANGED
|
@@ -1,94 +1,98 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{join as
|
|
2
|
+
import{join as U,dirname as re,resolve as ne,basename as Ge}from"path";import{homedir as ie}from"os";import{existsSync as q,readFileSync as J,readdirSync as Je,rmSync as ze}from"fs";import{fileURLToPath as ee}from"url";import{spawnSync as ue}from"child_process";import{createInterface as ae}from"readline";import{WyrmDB as Qe}from"./database.js";import{MemoryArtifacts as K,queuedForReview as ke}from"./memory-artifacts.js";import{GroundTruths as pe}from"./intelligence.js";import{Causality as _e}from"./causality.js";import{wireTruthAutoCascade as Ee}from"./truth-cascade.js";import{Rehydration as Xe}from"./rehydration.js";import{makeRenderDeps as Re,buildRenderPlan as me,renderToDisk as Ze,renderForClient as Se,detectClients as et,ALL_RENDER_CLIENTS as fe,ALL_CLIENT_MARKERS as tt}from"./render-target.js";import{classifyCapture as ot}from"./capture.js";import{importFrom as st,IMPORT_SOURCES as Ce}from"./importers.js";import{c as y,colors as V,formatTable as P,printSection as S,printSuccess as k,printError as f,printWarning as ge,icons as B,readSecret as rt,ReadSecretCanceled as nt,suggestClosest as je,npmGlobalPrefixFromPath as it,createDownloadProgress as at}from"./cli.js";import{setDefaultLogLevel as ct}from"./logger.js";import{autoEnrollProject as lt}from"./project-resolve.js";import{buildDeterminismReceipt as dt,attestation as ut}from"./receipt.js";import{loadConnectorConfigs as xe,upsertConnectorConfig as pt,runConnector as mt,runAllConnectors as ft}from"./connectors/index.js";import{readActor as gt}from"./attribution.js";import{captureHealth as yt,captureEffectiveness as ht,recordSnapshot as ye,getSnapshots as Te,trendFlags as wt}from"./metrics.js";function H(){try{const c=re(ee(import.meta.url));return JSON.parse(J(U(c,"..","package.json"),"utf-8"))}catch{return{}}}function A(c,l){const o=typeof c=="string"?parseInt(c,10):NaN;return Number.isFinite(o)?o:l}function te(c,l){const o=typeof c=="string"?parseFloat(c):NaN;return Number.isFinite(o)?o:l}function Ne(){return process.env.WYRM_DB_PATH??U(ie(),".wyrm","wyrm.db")}function C(){return new Qe(Ne())}function j(c){const l=[],o={};let i=0;for(;i<c.length;){const n=c[i];if(n.startsWith("--")){const s=n.slice(2),e=c[i+1];e&&!e.startsWith("--")?(o[s]=e,i+=2):(o[s]=!0,i++)}else l.push(n),i++}return{positional:l,flags:o}}function M(c,l){return l?c.getDatabase().prepare("SELECT * FROM projects WHERE LOWER(name) LIKE LOWER(?) LIMIT 1").get(`%${l}%`)??null:null}function Me(c,l){if(l.project===void 0)return;const o=D(l.project),i=o?M(c,o):null;return i||(f(o?`Project not found: ${o}`:"--project needs a project name"),console.error(y.dim(" list projects: wyrm project list")),process.exitCode=1,null)}const bt={search:["project","type"],recall:["project","type","set","mode","run","mute","challenge","propose","limit"],ls:["project","type","limit"],show:[],capture:["project","mode"],stats:["project"],review:["project","approve-all","auto"],digest:["writes","since","json"],forget:["match","dataset","older-than","yes"],prune:["project","path","min-confidence","older-than","no-dry-run","yes"]};function vt(c,l){const o=bt[c];if(o)for(const i of l){if(i==="--")break;if(!i.startsWith("--")||i.length===2)continue;const n=i.slice(2).split("=")[0];if(n==="help"||o.includes(n))continue;const[s]=je(n,o,1);process.stderr.write(`${B.warning} unknown flag --${n}${s?` (did you mean --${s}?)`:""}
|
|
3
|
+
`)}}async function De(c){const{positional:l,flags:o}=j(c),i=l[0];i||(f("Usage: wyrm search <query> [--project <name>] [--type all|memories|truths|quests|data]"),process.exit(1));const n=C();try{const s=n.getDatabase(),e=o.type??"all",t=Me(n,o);if(t===null)return;const r=t?.id;S(`Search: "${i}"`);const u=[];let a=null;if(e==="all"||e==="memories"){const{resolveEmbeddingState:m}=await import("./providers/embedding-provider.js"),h=m(),g=new K(s);if(h.resolved!=="none"){const{createVectorStore:v}=await import("./vectors.js"),R=process.env.WYRM_VECTOR_PROVIDER??"auto",E=v({provider:R},s);g.setVectorStore(E)}let w;const b={limit:20,onStats:v=>{w=v}},$=r!=null?await g.recallHybrid(r,i,b):await g.recallHybridGlobal(i,b);for(const v of $)u.push([`mem:${v.artifact.id}`,"memory",v.artifact.kind,v.artifact.problem.slice(0,80)]);if(h.resolved==="none")a="keyword-only (no vector provider; run: wyrm vectors download)";else{const v=w!==void 0||$.some(I=>I.match_type==="vector"||I.match_type==="hybrid"),R=g.getVectorStore(),E=typeof R?.getProvider=="function"?R.getProvider():void 0;let x=null;if(!v)if(!R||E?.name==="none")x=h.reason||"vector_store_unavailable";else{let I;try{I=R.indexCoverage()}catch{}if(I?.stale)x="stale_index";else{let W=-1;try{W=R.getStats().total}catch{}x=W===0?"empty_index":W<0?"index_state_unknown":"no_vector_hit"}}let T=null;if(v&&R)try{const I=s.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE needs_review = 0 AND supersedes_id IS NULL").get().n;T={indexed:R.indexCoverage().activeCount,eligible:I}}catch{}const N=dt({coverage:T,vectorsAvailable:v,rerankActive:!1,embedModel:v?E?.model??h.model:null,rerankModel:null,embedEgressHost:v?E?.remoteHost??null:null,rerankEgressHost:null,ftsOnlyReason:x});a=ut(N)}}if(e==="all"||e==="sessions")try{const m=r?`AND s.project_id = ${r}`:"",h=s.prepare(`
|
|
3
4
|
SELECT s.id, s.objectives, s.project_id FROM sessions s
|
|
4
5
|
JOIN sessions_fts fts ON s.id = fts.rowid
|
|
5
|
-
WHERE sessions_fts MATCH ? ${
|
|
6
|
+
WHERE sessions_fts MATCH ? ${m}
|
|
6
7
|
LIMIT 10
|
|
7
|
-
`).all(i);for(const
|
|
8
|
+
`).all(i);for(const g of h)u.push([`session:${g.id}`,"session","",g.objectives.slice(0,80)])}catch{}if(e==="all"||e==="quests")try{const m=r?`AND q.project_id = ${r}`:"",h=s.prepare(`
|
|
8
9
|
SELECT q.id, q.title, q.priority, q.project_id FROM quests q
|
|
9
10
|
JOIN quests_fts fts ON q.id = fts.rowid
|
|
10
|
-
WHERE quests_fts MATCH ? ${
|
|
11
|
+
WHERE quests_fts MATCH ? ${m}
|
|
11
12
|
LIMIT 10
|
|
12
|
-
`).all(i);for(const
|
|
13
|
+
`).all(i);for(const g of h)u.push([`quest:${g.id}`,"quest",g.priority,g.title.slice(0,80)])}catch{}if(e==="all"||e==="data")try{const m=r?`AND d.project_id = ${r}`:"",h=s.prepare(`
|
|
13
14
|
SELECT d.id, d.category, d.key, d.value FROM data_lake d
|
|
14
15
|
JOIN data_lake_fts fts ON d.id = fts.rowid
|
|
15
|
-
WHERE data_lake_fts MATCH ? ${
|
|
16
|
+
WHERE data_lake_fts MATCH ? ${m}
|
|
16
17
|
LIMIT 10
|
|
17
|
-
`).all(i);for(const
|
|
18
|
-
${
|
|
18
|
+
`).all(i);for(const g of h)u.push([`data:${g.id}`,"data",g.category,g.value.slice(0,80)])}catch{}const d=e==="all"||e==="memories"?ke(s,r??null):0,p=r!=null?" in this project":"";u.length===0?(console.log(y.dim(` No results found for "${i}"`)),d>0&&(a=`${d} memor${d===1?"y":"ies"}${p} ${d===1?"is":"are"} waiting in the review queue and invisible to recall \u2014 run \`wyrm review\` (or \`wyrm review --approve-all\`)`)):(console.log(P(["ID","Type","Subtype","Preview"],u)),console.log(y.dim(`
|
|
19
|
+
${u.length} result${u.length!==1?"s":""}`)),d>0&&console.log(y.dim(` ${d} memor${d===1?"y":"ies"}${p} await${d===1?"s":""} review and ${d===1?"is":"are"} not searched (wyrm review)`))),a&&console.log(y.dim(` ${a}`))}finally{n.close()}}async function $t(c){const{flags:l}=j(c),o=l.type??"all",i=A(l.limit,20),n=C(),s=n.getDatabase(),e=Me(n,l);if(e===null){n.close();return}const t=e?.id,r=t?`WHERE project_id = ${t}`:"",u=t?`AND project_id = ${t}`:"";if(S("Wyrm Memory"),o==="all"||o==="memories"){S("Memories");const a=s.prepare(`
|
|
19
20
|
SELECT id, kind, confidence, problem, tags FROM memory_artifacts
|
|
20
|
-
${
|
|
21
|
+
${r}
|
|
21
22
|
ORDER BY created_at DESC LIMIT ?
|
|
22
|
-
`).all(i);if(
|
|
23
|
+
`).all(i);if(a.length>0){const d=a.map(p=>[`mem:${p.id}`,p.kind,`${Math.round(p.confidence*100)}%`,p.problem.slice(0,60),p.tags?.slice(0,30)??""]);console.log(P(["ID","Kind","Conf","Preview","Tags"],d))}else console.log(y.dim(" No memories yet."))}if(o==="all"||o==="truths"){S("Ground Truths");const a=s.prepare(`
|
|
23
24
|
SELECT id, category, key, value FROM ground_truths
|
|
24
|
-
WHERE is_current = 1 ${
|
|
25
|
+
WHERE is_current = 1 ${u}
|
|
25
26
|
ORDER BY created_at DESC LIMIT ?
|
|
26
|
-
`).all(i);if(
|
|
27
|
+
`).all(i);if(a.length>0){const d=a.map(p=>[`truth:${p.id}`,p.category,p.key.slice(0,30),p.value.slice(0,60)]);console.log(P(["ID","Category","Key","Value"],d))}else console.log(y.dim(" No ground truths yet."))}if(o==="all"||o==="quests"){S("Quests");const a=s.prepare(`
|
|
27
28
|
SELECT id, priority, title, status FROM quests
|
|
28
|
-
${
|
|
29
|
+
${r}
|
|
29
30
|
ORDER BY created_at DESC LIMIT ?
|
|
30
|
-
`).all(i);if(
|
|
31
|
-
`+
|
|
32
|
-
`+
|
|
33
|
-
`+
|
|
34
|
-
`+
|
|
35
|
-
`+
|
|
36
|
-
`+
|
|
37
|
-
`+String(
|
|
38
|
-
`+
|
|
39
|
-
`+
|
|
40
|
-
`+
|
|
41
|
-
`);return}if(
|
|
42
|
-
`)},
|
|
43
|
-
`);return}const b=
|
|
44
|
-
`);return}
|
|
45
|
-
`);return}let
|
|
46
|
-
|
|
47
|
-
_... brief truncated at ${
|
|
48
|
-
`);return}process.stdout.write(
|
|
49
|
-
`)}finally{
|
|
50
|
-
`);return}const
|
|
51
|
-
`)}finally{
|
|
52
|
-
`);return}if(i==="list"||i==="ls"||i===void 0){const a=
|
|
53
|
-
`);return}const
|
|
54
|
-
`)}return}if(i==="release"){const a=
|
|
31
|
+
`).all(i);if(a.length>0){const d=a.map(p=>[`quest:${p.id}`,p.priority,p.title.slice(0,60),p.status]);console.log(P(["ID","Priority","Title","Status"],d))}else console.log(y.dim(" No quests yet."))}n.close()}async function kt(c){const{positional:l}=j(c),o=l[0];o||(f("Usage: wyrm show <typed-id> (e.g. mem:41, quest:12, truth:7, data:5, session:3)"),process.exit(1));const[i,n]=o.split(":"),s=parseInt(n??"",10);(!i||isNaN(s))&&(f(`Invalid typed ID: ${o}. Format: type:number (e.g. mem:41)`),process.exit(1));const e=C(),t=e.getDatabase();switch(S(`${o}`),i){case"mem":{const r=t.prepare("SELECT * FROM memory_artifacts WHERE id = ?").get(s);if(!r){f(`Memory artifact ${s} not found`),process.exitCode=1;break}console.log(y.bold("Kind: ")+r.kind),console.log(y.bold("Confidence:")+` ${Math.round(r.confidence*100)}%`),console.log(y.bold("Problem: ")+`
|
|
32
|
+
`+r.problem),r.validated_fix&&console.log(y.bold("Solution: ")+`
|
|
33
|
+
`+r.validated_fix),r.why_it_worked&&console.log(y.bold("Why: ")+`
|
|
34
|
+
`+r.why_it_worked),r.tags&&console.log(y.bold("Tags: ")+r.tags),console.log(y.bold("Created: ")+r.created_at);break}case"quest":{const r=t.prepare("SELECT * FROM quests WHERE id = ?").get(s);if(!r){f(`Quest ${s} not found`),process.exitCode=1;break}console.log(y.bold("Title: ")+r.title),console.log(y.bold("Priority: ")+r.priority),console.log(y.bold("Status: ")+r.status),r.description&&console.log(y.bold("Desc: ")+`
|
|
35
|
+
`+r.description),r.tags&&console.log(y.bold("Tags: ")+r.tags),console.log(y.bold("Created: ")+r.created_at);break}case"truth":{const r=t.prepare("SELECT * FROM ground_truths WHERE id = ?").get(s);if(!r){f(`Ground truth ${s} not found`),process.exitCode=1;break}console.log(y.bold("Category: ")+r.category),console.log(y.bold("Key: ")+r.key),console.log(y.bold("Value: ")+`
|
|
36
|
+
`+r.value),r.rationale&&console.log(y.bold("Rationale:")+`
|
|
37
|
+
`+r.rationale),console.log(y.bold("Active: ")+(r.is_current?"Yes":"No (superseded)")),console.log(y.bold("Created: ")+r.created_at);break}case"data":{const r=t.prepare("SELECT * FROM data_lake WHERE id = ?").get(s);if(!r){f(`Data point ${s} not found`),process.exitCode=1;break}console.log(y.bold("Category: ")+r.category),console.log(y.bold("Key: ")+r.key),console.log(y.bold("Value: ")+`
|
|
38
|
+
`+String(r.value).slice(0,500)),console.log(y.bold("Created: ")+r.created_at);break}case"session":{const r=t.prepare("SELECT * FROM sessions WHERE id = ?").get(s);if(!r){f(`Session ${s} not found`),process.exitCode=1;break}console.log(y.bold("Date: ")+r.date),console.log(y.bold("Objectives: ")+`
|
|
39
|
+
`+r.objectives),r.completed&&console.log(y.bold("Completed: ")+`
|
|
40
|
+
`+r.completed),r.notes&&console.log(y.bold("Notes: ")+`
|
|
41
|
+
`+r.notes);break}default:f(`Unknown type prefix: ${i}. Use mem|quest|truth|data|session`),process.exitCode=1}e.close()}async function _t(c){const{positional:l,flags:o}=j(c),i=l[0];i||(f('Usage: wyrm capture "<content>" [--project <name>] [--mode auto|quest|truth|memory]'),process.exit(1));const n=o.project,s=o.mode,e=C(),t=e.getDatabase();let r=null,u=null;if(n){const N=M(e,n);N||(f(`Project not found: ${n}`),console.error(y.dim(` create it: wyrm project add ${n} --path <dir>`)),e.close(),process.exit(1)),r=N.id}else{const N=()=>t.prepare("SELECT COUNT(*) AS n FROM projects").get().n,I=N(),W=e.getProject(process.cwd())??lt(e,process.cwd());W&&(r=W.id,N()>I&&(u=`enrolled ${W.name} (${W.path}) as a project on first capture`))}let a=ot(i);s&&s!=="auto"&&(a={type:s,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[s]??s,confidence:100,reasoning:`Mode override: ${s}`});const{type:d,subtype:p,confidence:m,reasoning:h}=a;(d==="quest"||d==="truth"||d==="memory")&&r===null&&(f("No project for this directory. Pass --project <name>, run this inside a git repository (it is enrolled automatically), or register one: wyrm project add <name> --path <dir>"),e.close(),process.exit(1));let g=0,w="",b=!1;const $=new K(t),v=new pe(t);if(Ee(v,new _e(t)),d==="quest")g=e.addQuest(r,i.slice(0,200),"","medium").id,w="quest";else if(d==="truth")if(s!=="truth"&&m<100){const N=$.add(r,{kind:"pattern",problem:i,confidence:m/100,needsReview:1});g=N.id,w="mem",b=N.needs_review===1}else g=v.set(r,{category:"decision",key:i.slice(0,60),value:i}).id,w="truth";else{const N=m>=75,I=$.add(r,{kind:p,problem:i,confidence:m/100,needsReview:N?0:1});g=I.id,w="mem",b=I.needs_review===1}const{recordWrite:R}=await import("./receipts.js"),E=R(t,{tool:"wyrm_capture",outcome:b?"queued":"stored",refTable:w,refId:g,reason:b?`needs_review (confidence ${m}%) \u2014 review to activate`:void 0,source:"cli",projectId:r??void 0});let x=null;if(w==="mem"){const{resolveEmbeddingState:N}=await import("./providers/embedding-provider.js");if(N().resolved!=="none")try{const{createVectorStore:W}=await import("./vectors.js"),F=process.env.WYRM_VECTOR_PROVIDER??"auto";x=await W({provider:F},t).addVector(i,"artifact",g,r)?"embedded for semantic recall":"not embedded yet (wyrm index rebuild will backfill)"}catch{x="not embedded yet (wyrm index rebuild will backfill)"}}e.close();const T=`${w}:${g}`;if(w==="mem"&&d==="truth"){const N=/^[aeiou]/i.test(p)?"an":"a";k(`Stored as memory ${T} (classified as ${N} ${p}, ${m}%; use --mode truth to store a ground truth)`)}else w==="mem"?k(`Stored as memory ${T} (${p}, ${m}%)`):w==="truth"?k(`Stored as ground truth ${T} (${p})`):k(`Stored as quest ${T}`);console.log(y.dim(` ${h}`)),u&&console.log(y.dim(` ${u}`)),b&&console.log(`${B.warning} Stored for review \u2014 run ${y.cyan("wyrm review")} to activate`),x&&console.log(y.dim(` ${x}`)),console.log(`receipt: ${E.outcome} ${E.ref??""}${E.reason?` \u2014 ${E.reason}`:""}`)}async function Et(c){const{positional:l,flags:o}=j(c);if(l.length>0){f("Usage: wyrm digest [--writes] [--since <days>] [--json]"),process.exitCode=1;return}const i=Number(o.since)>=1?Number(o.since):1,{buildWriteDigest:n}=await import("./receipts.js"),s=C();try{const e=n(s.getDatabase(),i);if(o.json===!0){process.stdout.write(JSON.stringify(e)+`
|
|
42
|
+
`);return}if(S(`Write digest \u2014 last ${e.since}`),console.log(`${y.bold("Total writes:")} ${e.total} ${y.bold("Outcomes:")} ${Object.entries(e.byOutcome).map(([t,r])=>`${t} ${r}`).join(" \xB7 ")||"none"}`),console.log(`${y.bold("Review queue:")} ${e.reviewQueueDepth} awaiting review${e.reviewQueueDepth>0?y.dim(" (invisible to recall until approved)"):""}`),e.byTool.length>0&&console.log(P(["Tool","Outcome","N"],e.byTool.map(t=>[t.tool,t.outcome,String(t.n)]))),e.reasons.length>0){console.log(y.bold("Non-stored reasons:"));for(const t of e.reasons)console.log(` ${t.outcome} \xD7${t.n} \u2014 ${t.reason.slice(0,110)}`)}e.bySource.length>0&&console.log(y.bold("By source: ")+e.bySource.map(t=>`${t.source} ${t.n}`).join(" \xB7 "))}finally{s.close()}}async function Rt(c){const{flags:l}=j(c),o=A(l.session,0),i=l.path,n=l.project,s=A(l["max-chars"],6e3),e=l.json===!0,t=e||l.quiet===!0,r=console.log;console.log=()=>{};const u=(p,m)=>{if(m==null)return 0;try{return p.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE project_id = ?").get(m).n}catch{return 0}},a=p=>{process.stdout.write(JSON.stringify({brief:"",attached:{quests:0,truths:0,artifacts:0,failures:0},memories:u(d.getDatabase(),p)})+`
|
|
43
|
+
`)},d=C();try{const p=new Xe(d.getDatabase());let m=o;if(m<=0){let w=i?d.getProject(i):void 0;if(!w&&n&&(w=M(d,n)??void 0),w||(w=d.getProject(process.cwd())),!w){if(e){a();return}t||process.stderr.write(`wyrm rehydrate: no Wyrm project for this directory, nothing to restore.
|
|
44
|
+
`);return}const b=p.latestSessionId(w.id);if(b===null){if(e){a(w.id);return}t||process.stderr.write(`wyrm rehydrate: project "${w.name}" has no prior sessions yet.
|
|
45
|
+
`);return}m=b}const h=p.rehydrate(m,{max_chars:s});if(!h){if(e){a();return}t||process.stderr.write(`wyrm rehydrate: session ${m} not found.
|
|
46
|
+
`);return}let g=h.briefing_markdown;if(s>0&&g.length>s&&(g=g.slice(0,s)+`
|
|
47
|
+
|
|
48
|
+
_... brief truncated at ${s} chars, run \`wyrm show session:${h.session_id}\` for the full record._`),e){const w=d.getDatabase().prepare("SELECT project_id FROM sessions WHERE id = ?").get(h.session_id),b=u(d.getDatabase(),w?.project_id);process.stdout.write(JSON.stringify({brief:g,attached:h.attached,memories:b})+`
|
|
49
|
+
`);return}process.stdout.write(g+`
|
|
50
|
+
`)}finally{d.close(),console.log=r}}async function St(c){const{flags:l}=j(c),o=typeof l.match=="string"?l.match:void 0,i=typeof l.dataset=="string"?l.dataset:void 0,n=l["older-than"]!==void 0?Number(l["older-than"]):void 0,s=l.yes===!0;if(!o&&!i&&n===void 0){f("wyrm forget needs a predicate \u2014 nothing is erased without one."),console.log(' by subject: wyrm forget --match "someone@example.com"'),console.log(" by source: wyrm forget --dataset ingested_transcripts (matches the `category` column)"),console.log(" by age: wyrm forget --older-than 365"),console.log(" add --yes to actually delete (dry run otherwise)."),process.exitCode=1;return}const e=C();try{const t=e.forgetData({match:o,dataset:i,olderThanDays:n,dryRun:!s});if(t.matched===0){if(console.log("Nothing matched in the ingested data lake, so nothing was erased."),console.log(" wyrm forget covers ingested third-party data only (connector transcripts and imports), not memories."),o){const{escapeLikePattern:r}=await import("./auto-capture.js"),u=`%${r(o)}%`;let a=0;try{a=e.getDatabase().prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE problem LIKE ? ESCAPE '\\' OR validated_fix LIKE ? ESCAPE '\\'").get(u,u).n}catch{}a>0&&console.log(` ${a} memor${a===1?"y contains":"ies contain"} "${o}".`)}console.log(" To remove a memory: reject it in wyrm review while it is queued, have an agent call wyrm_review with action reject and its id, or use wyrm prune for stale low-confidence ones.");return}S(s?"Erased":"Would erase (dry run)"),console.log(` ${t.matched} row(s) in the data lake`);for(const r of t.samples)console.log(` ${r.created_at.slice(0,10)} ${r.category} ${r.key.slice(0,60)}`);t.samples.length<t.matched&&console.log(` \u2026 and ${t.matched-t.samples.length} more`),s?(k(`Deleted ${t.deleted} row(s). Full-text index updated by trigger; freed pages are overwritten (secure_delete is on).`),console.log(" NOTE: snapshots under ~/.wyrm/backups still contain the old rows. Erase or rotate them separately.")):(console.log(""),console.log(" Dry run \u2014 nothing was deleted. Re-run with --yes to erase."))}finally{e.close()}}async function Ct(c){const{flags:l}=j(c),{runMetabolize:o}=await import("./metabolize.js"),i=C(),n=console.log;try{let s;if(typeof l.project=="string"){const t=M(i,l.project);if(!t){f(`Project not found: ${l.project}`),process.exitCode=1;return}s=t.id}const e=o(i.getDatabase(),{projectId:s,dryRun:l["dry-run"]===!0,near:l["no-near"]===!0?!1:void 0});console.log(`metabolize${e.dryRun?" (dry-run)":""} \u2014 scanned ${e.scanned} \xB7 exact-merged ${e.exactMerged} (superseded, not deleted) \xB7 near-dup candidates queued ${e.nearCandidatesQueued} \xB7 decayed ${e.decayed}`)}finally{i.close(),console.log=n}}async function jt(c){const{positional:l,flags:o}=j(c),i=l[0]??"stats",{backfillEntities:n}=await import("./entity-populate.js"),s=C(),e=console.log;try{const t=s.getDatabase();let r;if(typeof o.project=="string"){const u=M(s,o.project);if(!u){f(`Project not found: ${o.project}`),process.exitCode=1;return}r=u.id}if(i==="stats"){const u=a=>{if(r!=null){const p=a==="entities"?"SELECT COUNT(*) AS n FROM entities WHERE project_id = ?":"SELECT COUNT(*) AS n FROM relationships WHERE project_id = ?";return t.prepare(p).get(r).n}const d=a==="entities"?"SELECT COUNT(*) AS n FROM entities":"SELECT COUNT(*) AS n FROM relationships";return t.prepare(d).get().n};console.log(`entities: ${u("entities")} \xB7 relationships: ${u("relationships")}${r!=null?` (project ${r})`:" (all projects)"}`);return}if(i==="backfill"){const u=r!=null?[{id:r}]:t.prepare("SELECT id FROM projects").all();let a=0,d=0,p=0;for(const m of u){const h=n(t,m.id,{limit:A(o.limit,5e3)});a+=h.created,d+=h.linked,p+=h.artifactsScanned}console.log(`entities backfill \u2014 scanned ${p} artifact(s) across ${u.length} project(s): +${a} entities, +${d} co-occurrence edges`);return}f("Usage: wyrm entities <backfill|stats> [--project <name>] [--limit N]"),process.exitCode=1}finally{s.close(),console.log=e}}async function xt(c){const{positional:l,flags:o}=j(c),i=l[0],n=await import("./bridge.js");if(i==="init"){const{existsSync:s,writeFileSync:e}=await import("node:fs"),t=n.configPath();if(s(t)&&o.force!==!0){f(`${t} already exists (use --force to overwrite).`),process.exitCode=1;return}const r=(await import("node:os")).homedir(),u={sources:[{type:"remember",name:"remember",dir:`${r}/.remember`,projectPath:r,windowDays:7}]};e(t,JSON.stringify(u,null,2)),k(`Wrote ${t} (1 source: remember). Add render/reverse sources per project as needed.`);return}if(i==="status"){const s=n.loadConfig();if(!s){f(`No bridge config at ${n.configPath()} \u2014 run \`wyrm bridge init\`.`),process.exitCode=1;return}const e=n.loadState();S("Bridge sources");for(const t of s.sources){const r=Object.keys(e).filter(a=>a.startsWith(t.name+":")),u=r.reduce((a,d)=>a+e[d].length,0);console.log(` ${t.name} [${t.type}] \u2192 ${"projectPath"in t?t.projectPath:""}${t.type==="remember"?` (${r.length} files tracked, ${u} sections bridged)`:""}`)}return}if(i==="run"){const s=n.loadConfig();if(!s){f(`No bridge config at ${n.configPath()} \u2014 run \`wyrm bridge init\`.`),process.exitCode=1;return}const e=C(),t=console.log;try{const r={wyrm_version:H().version??"unknown",compiled_at:new Date().toISOString()},u=await n.runBridge(e.getDatabase(),s,r,{only:typeof o.source=="string"?o.source:void 0,dryRun:o["dry-run"]===!0});for(const a of u)console.log(`bridge:${a.source} [${a.type}]${o["dry-run"]===!0?" (dry-run)":""} \u2014 stored ${a.stored} \xB7 queued ${a.queued} \xB7 dropped ${a.dropped} \xB7 rendered ${a.rendered}${a.note?` \xB7 ${a.note}`:""}`);if(o.watch===!0){const a=Number(o.interval)>=2?Number(o.interval):15;console.log(`bridge watch \u2014 re-rendering on write events (poll ${a}s, Ctrl-C to stop)`),await n.watchBridge(e.getDatabase(),s,()=>({wyrm_version:H().version??"unknown",compiled_at:new Date().toISOString()}),{intervalSec:a,onCycle:d=>{for(const p of d)console.log(`bridge:${p.source} re-rendered (${p.rendered} file(s), ${p.queued} edit(s) harvested)`)}})}return}finally{e.close(),console.log=t}}f("Usage: wyrm bridge <init|status|run> [--source <name>] [--dry-run] [--force]"),process.exitCode=1}async function Tt(c){const{positional:l,flags:o}=j(c);if(l[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 n=a=>typeof o[a]=="string"?o[a]:void 0,s=n("path"),e=n("project"),t=n("run")?.slice(0,64),r=console.log;console.log=()=>{};const u=C();try{let a=s?u.getProject(s):void 0;if(!a&&e&&(a=M(u,e)??void 0),a||(a=u.getProject(process.cwd())),!a){process.stderr.write(`wyrm session log: no Wyrm project for this directory, nothing recorded.
|
|
51
|
+
`);return}const d={};for(const h of["objectives","completed","issues","commits","notes"]){const g=n(h);g&&(d[h]=g.slice(0,8e3))}const p=u.getDatabase();let m;t&&(m=p.prepare("SELECT id FROM sessions WHERE project_id = ? AND run_id = ? ORDER BY id DESC LIMIT 1").get(a.id,t)?.id),m?u.updateSession(m,d):(m=u.createSession(a.id,d).id,t&&p.prepare("UPDATE sessions SET run_id = ? WHERE id = ?").run(t,m)),process.stdout.write(`session:${m}
|
|
52
|
+
`)}finally{u.close(),console.log=r}}async function Nt(c){const{positional:l,flags:o}=j(c),i=l[0],n=u=>typeof o[u]=="string"?o[u]:void 0,{AgentPresence:s,processStartTime:e,presenceLiveness:t}=await import("./presence.js"),r=C();try{const u=new s(r.getDatabase());if(i==="announce"){const a=n("agent");if(!a){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 d=n("path");let p=d?r.getProject(d):void 0;if(!p&&n("project")&&(p=M(r,n("project"))??void 0),!p&&n("project")){f(`Project not found: ${n("project")}`),process.exitCode=1;return}const m=o["auto-pid"]===!0?process.ppid:Number(n("pid")),h={};let g="";if(Number.isInteger(m)&&m>0){const $=e(m);$?(h.pid=m,h.pid_start=$,g=` \xB7 pid ${m} (start ${$})`):g=` \xB7 pid ${m} unreadable \u2014 TTL fallback`}const w=Number(n("ttl")),b=u.announce({agent_id:a,agent_kind:n("kind")??"cli",project_id:p?.id??null,current_quest_id:n("quest")?Number(n("quest")):null,ttl_seconds:Number.isFinite(w)&&w>0?w:h.pid?86400:300,metadata:Object.keys(h).length?h:void 0,role:n("role")??null});process.stdout.write(`presence:${b.id} ${a}${g}
|
|
53
|
+
`);return}if(i==="list"||i==="ls"||i===void 0){const a=r.getDatabase().prepare("SELECT * FROM agent_presence ORDER BY last_heartbeat DESC").all();if(a.length===0){process.stdout.write(`No agents on the board.
|
|
54
|
+
`);return}const d={"alive-pid":"ALIVE (pid)","dead-pid":"DEAD (pid gone)","alive-ttl":"alive (ttl)",stale:"stale"};for(const p of a){const m=t(p);process.stdout.write(`${p.agent_id} [${p.agent_kind}] ${d[m]} hb ${p.last_heartbeat}${p.role?` role ${p.role}`:""}${p.current_quest_id?` quest #${p.current_quest_id}`:""}
|
|
55
|
+
`)}return}if(i==="release"){const a=n("agent");if(!a){f("Usage: wyrm presence release --agent <id>"),process.exitCode=1;return}const d=u.release(a);process.stdout.write(d?`released ${a}
|
|
55
56
|
`:`no presence row for ${a}
|
|
56
|
-
`);return}
|
|
57
|
-
`);return}const w=
|
|
58
|
-
`).filter(
|
|
59
|
-
WHERE
|
|
60
|
-
|
|
57
|
+
`);return}f("Usage: wyrm presence <announce|list|release> [options]"),process.exitCode=1}finally{r.close()}}async function Mt(c){const{flags:l}=j(c),o=l.path,i=l.project,n=l.out,s=l.brief===!0,e=l.force===!0,t=l.quiet===!0,r=(typeof l.client=="string"?l.client:"").split(",").map(m=>m.trim().toLowerCase()).filter(Boolean);let u=r.filter(m=>fe.includes(m));const a=r.filter(m=>!fe.includes(m));a.length>0&&(f(`Unknown --client value(s): ${a.join(", ")} (valid: ${fe.join("|")})`),process.exit(1));const d=console.log;s&&(console.log=()=>{});const p=C();try{let m=o?p.getProject(o):void 0;if(!m&&i&&(m=M(p,i)??void 0),!m&&i){console.log=d,f(`Project not found: ${i}`),process.exitCode=1;return}m||(m=p.getProject(process.cwd())),m||(console.log=d,f("wyrm render: no Wyrm project for this directory (use --path or --project)."),process.exit(1));const h=Re(p.getDatabase()),g={wyrm_version:H().version??"unknown",compiled_at:new Date().toISOString()};if(s){const v=me(h,m,g);console.log=d,process.stdout.write(v.sessionBrief+`
|
|
58
|
+
`);return}const w=n??m.path;u.length===0&&r.length===0&&(u=et(tt.filter(v=>q(U(w,v)))));{const v=await import("./reverse-bridge.js"),R=me(h,m,g),E={"MEMORY.md":R.memoryMd};for(const x of u){const T=Se(x,R.model,g);E[T.relPath]=T.block}try{const x=v.makeBridgeDeps(p.getDatabase()),T=await v.sweepProject(x,{id:m.id,path:m.path},E,{rootDir:w});T.added>0&&!t&&console.log(` ${B.warning} harvested ${T.added} human edit(s) \u2192 review queue before overwrite`)}catch{}}const{plan:b,writes:$}=Ze(h,m,g,{rootDir:w,clients:u,force:e});if(!t){k(`Rendered ${m.name} memory (${b.model.truths.length} truths, ${b.model.failures.length} failures, ${b.model.quests.length} quests, ${b.model.artifacts.length} patterns) to ${w}`);for(const v of $){const R=v.action==="created"?B.success:v.action==="updated"?B.info:B.warning;console.log(` ${R} ${v.action.padEnd(7)} ${v.path}${v.reason?` (${v.reason})`:""}`)}}}finally{p.close(),console.log=d}}async function Dt(c){const{flags:l}=j(c),o=l.path,i=l.project,n=l.root,s=l["dry-run"]===!0||l.dry===!0,e=(typeof l.client=="string"?l.client:"").split(",").map(d=>d.trim().toLowerCase()).filter(Boolean),t=["claude","cursor","copilot","agents"],r=e.filter(d=>t.includes(d)),u=await import("./reverse-bridge.js"),a=C();try{let d=o?a.getProject(o):void 0;if(!d&&i&&(d=M(a,i)??void 0),!d&&i){f(`Project not found: ${i}`),process.exitCode=1;return}if(d||(d=a.getProject(process.cwd())),!d){f("wyrm reverse-bridge: no Wyrm project for this directory (use --path or --project)."),process.exitCode=1;return}const p=Re(a.getDatabase()),m={wyrm_version:H().version??"unknown",compiled_at:new Date().toISOString()},h=me(p,d,m),g={"MEMORY.md":h.memoryMd};for(const $ of r){const v=Se($,h.model,m);g[v.relPath]=v.block}const w=u.makeBridgeDeps(a.getDatabase()),b=await u.sweepProject(w,{id:d.id,path:d.path},g,{dryRun:s,rootDir:n});S(`Reverse bridge ${s?"(dry run) ":""}\u2014 ${b.added} candidate(s) queued, ${b.skipped} already present (${b.filesWithEdits}/${b.filesScanned} file(s) with edits)`);for(const $ of b.sample)console.log(` ${B.bullet} ${$}`);!s&&b.added>0&&k("Review with: wyrm review")}finally{a.close()}}async function It(c){const l=j(c);if(typeof l.flags.from=="string"){await Ot(l);return}const{positional:o,flags:i}=j(c.slice(1)),n=c[0],s=i.project;if(n==="git"){const e=A(i.last,20),t=C(),r=t.getDatabase();let u=null;if(s){const g=M(t,s);g||(f(`Project not found: ${s}`),t.close(),process.exit(1)),u=g.id}else{const g=r.prepare("SELECT p.* FROM projects p JOIN sessions s ON s.project_id = p.id ORDER BY s.created_at DESC LIMIT 1").get();g&&(u=g.id)}u||(f("No project found. Use --project <name>"),t.close(),process.exit(1));const a=ue("git",["log","--pretty=format:%H%x1f%s%x1f%an%x1f%ai",`-${e}`],{cwd:process.cwd(),encoding:"utf-8",timeout:1e4,shell:!1});(a.error||a.status!==0)&&(f("git log failed. Make sure you are in a git repository."),t.close(),process.exit(1));const d=a.stdout.split(`
|
|
59
|
+
`).filter(g=>g.trim()),p=new K(r);let m=0,h=0;for(const g of d){const[,w,b,$]=g.split(""),v=w??"";if(/^Merge /i.test(v)||/^(chore|bump|release|version)/i.test(v)){h++;continue}let R="pattern";/^fix(\(.+\))?:/i.test(v)?R="lesson":/^refactor(\(.+\))?:/i.test(v)&&(R="heuristic");const E=v.split(":")[0]??"commit";p.add(u,{kind:R,problem:v,whyItWorked:`Committed by ${b??"unknown"} on ${$??"unknown"}`,tags:["git","commit",E.toLowerCase()],confidence:.6,needsReview:1}),m++}t.close(),k(`Imported ${m} commits (${h} skipped). Run ${y.cyan("wyrm review")} to activate.`)}else if(n==="rules"){const e=o[0],t=i.format??"plain";e||(f("Usage: wyrm import rules <path> [--project <name>] [--format cursorrules|copilot|plain]"),process.exit(1)),q(e)||(f(`File not found: ${e}`),process.exit(1));const r=J(e,"utf-8"),u=C(),a=u.getDatabase();let d=null;if(s){const E=M(u,s);E||(f(`Project not found: ${s}`),u.close(),process.exit(1)),d=E.id}else{const E=a.prepare("SELECT p.* FROM projects p JOIN sessions s ON s.project_id = p.id ORDER BY s.created_at DESC LIMIT 1").get();E&&(d=E.id)}d||(f("No project found. Use --project <name>"),u.close(),process.exit(1));const p=e.split("/").pop()??"rules",m=["imported",t,p],h=r.split(/\n(?=#)/),g=r.split(/\n\n+/),w=(h.length>=g.length?h:g).map(E=>E.trim()).filter(E=>E.length>=15),b=new K(a),$=new pe(a);Ee($,new _e(a));let v=0,R=0;for(const E of w)/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(E)?($.set(d,{category:"constraint",key:E.slice(0,50).replace(/\n/g," "),value:E,source:p}),v++):(b.add(d,{kind:"heuristic",problem:E,tags:m,confidence:.7,needsReview:1}),R++);u.close(),k(`Imported ${v} ground truths + ${R} 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 ${Ce.join("|")} <file.json> [--project <name>]`),process.exit(1)}async function Ot(c){const l=c.flags.from,o=c.positional[0],i=c.flags.project,n=`Usage: wyrm import --from ${Ce.join("|")} <file.json> [--project <name>]`;o||(f(n),process.exit(1)),q(o)||(f(`File not found: ${o}`),process.exit(1));let s;try{s=JSON.parse(J(o,"utf-8"))}catch(r){f(`Could not parse JSON from ${o}: ${r.message}`),process.exit(1)}let e;try{e=st(l,s)}catch(r){f(r.message),process.exit(1)}const t=C();try{let r=i?M(t,i):null;if(r||(r=t.getProject(process.cwd())??null),!r){f(i?`Project not found: ${i}`:"wyrm import: no Wyrm project for this directory (pass --project <name>)."),process.exitCode=1;return}if(e.length===0){f(`No importable memories found in ${o} for source "${l}".`);return}const u=t.getDatabase(),a=new K(u);try{const{createVectorStore:p}=await import("./vectors.js"),m=process.env.WYRM_VECTOR_PROVIDER??"auto";a.setVectorStore(p({provider:m},u))}catch{}let d=0;for(const p of e)a.add(r.id,{kind:"lesson",problem:p.text,tags:p.tags,constraints:p.metadata?JSON.stringify(p.metadata):void 0,whyItWorked:`Imported from ${p.source}`,outcome:"neutral",confidence:.6,needsReview:1}),d++;k(`Imported ${d} ${d===1?"memory":"memories"} from ${l} into ${y.cyan(r.name)} review queue. Run ${y.cyan("wyrm review")} to vet (tagged ${y.dim(`imported_from:${e[0]?.source??l}`)}).`)}finally{t.close()}}async function Pt(c){const{flags:l}=j(c),o=l.project,i=C(),n=i.getDatabase();if(S("Wyrm Statistics"),o){const s=M(i,o);s||(f(`Project not found: ${o}`),i.close(),process.exit(1));const e=i.getProjectStats(s.id),t=[["Sessions",String(e.sessions)],["Quests (pending)",String(e.quests.pending)],["Quests (completed)",String(e.quests.completed)],["Data Points",String(e.dataPoints)]];console.log(P(["Metric","Value"],t))}else{const s=i.getStats(),e=[["Projects",String(s.projects)],["Sessions",String(s.sessions)],["Quests",String(s.quests)],["Data Points",String(s.dataPoints)],["DB Size",s.dbSize]],t=n.prepare("SELECT COUNT(*) as n FROM memory_artifacts").get().n,r=n.prepare("SELECT COUNT(*) as n FROM ground_truths WHERE is_current = 1").get().n,u=n.prepare("SELECT COUNT(*) as n FROM memory_artifacts WHERE needs_review = 1").get().n;let a=0;try{a=n.prepare("SELECT COUNT(*) as n FROM failure_patterns WHERE resolved = 0").get().n}catch{}e.push(["Memories",String(t)],["Ground Truths",String(r)]),u>0&&e.push([" \u21B3 in review queue",`${u} (invisible to recall \u2014 wyrm review)`]),a>0&&e.push(["Unresolved failures",`${a} (the firewall is armed against these)`]),console.log(P(["Metric","Value"],e))}i.close()}async function At(c,l){if(l.length===0)return 0;const{effectiveEmbeddingState:o}=await import("./live-embedding-state.js"),i=o(c,process.cwd());if(i.resolved==="none"||!i.model)return 0;try{return c.prepare(`SELECT COUNT(*) AS n FROM json_each(?) j
|
|
60
|
+
WHERE NOT EXISTS (SELECT 1 FROM vectors v
|
|
61
|
+
WHERE v.content_type = 'artifact' AND v.content_id = j.value AND v.model = ?)`).get(JSON.stringify(l),i.model).n}catch{return l.length}}async function Lt(c){const{flags:l}=j(c),o=l.project,i=C(),n=i.getDatabase();if(l.auto!==void 0){const{isAutoApproveOn:d,setAutoApprove:p}=await import("./memory-artifacts.js"),m=l.auto===!0?"status":String(l.auto).toLowerCase();try{m==="on"||m==="1"?(p(n,!0),k("Auto-approve ON: new memories skip the review queue and are recall-visible immediately.")):m==="off"||m==="0"||m==="false"?(p(n,!1),k("Auto-approve OFF: risky writes queue for wyrm review again.")):m==="status"?console.log(` auto-approve: ${d(n)?"on":"off"}${process.env.WYRM_AUTO_APPROVE?" (WYRM_AUTO_APPROVE env)":""}`):(f("usage: wyrm review --auto on|off|status"),process.exitCode=1)}finally{i.close()}return}if(l["approve-all"]===!0){const d=n.transaction(()=>{const h=n.prepare("SELECT id FROM memory_artifacts WHERE needs_review = 1 AND source_trust IN ('operator', 'agent')").all().map(g=>g.id);return n.prepare(`UPDATE memory_artifacts SET needs_review = 0
|
|
62
|
+
WHERE needs_review = 1 AND source_trust IN ('operator', 'agent')`).run(),h})(),p=d.length,m=n.prepare(`SELECT COUNT(*) AS n FROM memory_artifacts
|
|
63
|
+
WHERE needs_review = 1 AND source_trust NOT IN ('operator', 'agent')`).get().n;if(k(`Approved ${p} queued memor${p===1?"y":"ies"} (now recall-visible).`),p>0){const h=await At(n,d);if(h>0){const g=h===p?p===1?"It is":"They are":`${h} of them ${h===1?"is":"are"}`;console.log(` ${g} keyword-searchable only (no vector under the active model). To embed for semantic recall: wyrm index rebuild`)}}m>0&&console.log(` ${m} left queued: imported/untrusted lanes need an explicit per-row review (wyrm review).`),i.close();return}let s=null;if(o){const d=M(i,o);d||(f(`Project not found: ${o}`),i.close(),process.exit(1)),s=d.id}const e=s?`AND project_id = ${s}`:"",t=n.prepare(`
|
|
61
64
|
SELECT id, kind, problem FROM memory_artifacts
|
|
62
|
-
WHERE needs_review = 1 ${
|
|
65
|
+
WHERE needs_review = 1 ${e}
|
|
63
66
|
ORDER BY created_at ASC
|
|
64
|
-
`).all();if(t.length===0){console.log(
|
|
65
|
-
${
|
|
66
|
-
Review complete.`)}async function
|
|
67
|
-
Total: ${
|
|
68
|
-
This is a dry run. Use --no-dry-run to delete (confirm each ID).`)),
|
|
69
|
-
Delete these ${
|
|
70
|
-
Activate with: wyrm login (free) \xB7 or: wyrm activate <license.json | key>`)),
|
|
71
|
-
License refreshed automatically.`)),!
|
|
72
|
-
This license has been revoked. Contact support if you believe this is a mistake.`)),console.log(
|
|
73
|
-
\xA9 2026 Ghost Protocol (Pvt) Ltd \xB7 Proprietary \xB7 https://wyrm.ghosts.lk`)),console.log(
|
|
74
|
-
${
|
|
75
|
-
Waiting for approval\u2026 (Ctrl-C to cancel)`));const
|
|
76
|
-
Database size: ${d.dbSize}`))}finally{o.close()}}async function Mt(m){const{positional:c,flags:s}=x(m),i=c[0]??"trend",r=U().version??null,e=C();try{const o=e.getDatabase();if(i==="snapshot"){const t=M(s.kind)||"all",n=[];if((t==="all"||t==="health")&&ge(o,"health",rt(o),r)!=null&&n.push("health"),(t==="all"||t==="effectiveness")&&ge(o,"effectiveness",nt(o),r)!=null&&n.push("effectiveness"),t==="retrieval"||s.full===!0){const d=await Ot();d&&ge(o,"retrieval",d,r)!=null?n.push("retrieval"):d||console.log(p.dim(" retrieval: bench unavailable (run from the repo with bench/ present) \u2014 skipped"))}n.length?k(`metrics snapshot recorded: ${n.join(", ")} @ ${r??"unknown"}`):g("metrics snapshot: nothing recorded");return}if(i==="trend"){const t=M(s.kind),n=Number(M(s.limit))||14,d=t?[t]:["health","effectiveness","retrieval"];let a=!1;for(const l of d){const u=Se(o,l,n);if(!u.length)continue;a=!0,R(`${l} \u2014 ${u.length} snapshot(s)`);const f=It[l],h=u.slice().reverse().map(y=>[y.captured_at.slice(0,16),y.wyrm_version??"-",...f.map(w=>Dt(y.metrics[w]))]);console.log(D(["when","ver",...f],h));for(const y of it(u,l))console.log(" "+p.yellow("!")+" "+y)}a||(console.log(p.dim(" No metrics yet. Record the first snapshot: wyrm metrics snapshot")),console.log(p.dim(" (health + effectiveness are cheap; add --full for retrieval recall@k.)")));return}if(i==="show"){const t=M(s.kind)||"health",n=Se(o,t,1);if(!n.length){console.log(p.dim(` No ${t} snapshot yet.`));return}R(`latest ${t} @ ${n[0].captured_at} (${n[0].wyrm_version??"-"})`),console.log(JSON.stringify(n[0].metrics,null,2));return}g("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 Dt(m){return m==null?"-":typeof m=="number"?Number.isInteger(m)?String(m):m.toFixed(3):String(m)}async function Ot(){try{const m=te(se(import.meta.url)),c=F(m,"..","bench"),s=F(c,"lib","retrieval-eval.mjs"),i=F(c,"eval-corpus.json");if(!q(s)||!q(i))return null;const r=process.env.WYRM_VECTOR_PROVIDER||"none";process.env.WYRM_LIVE_MEMORY="0";const{evaluate:e}=await import(s),{WyrmDB:o}=await import("./database.js"),{MemoryArtifacts:t}=await import("./memory-artifacts.js"),n=JSON.parse(K(i,"utf8")),d=`/tmp/wyrm-metrics-eval-${process.pid}.db`,a=new o(d);let l;try{l=e(n,a,t,{k:10})}finally{a.close();for(const f of["","-wal","-shm"])try{Fe(d+f,{force:!0})}catch{}}const u=l.quality.overall;return{mode:r==="none"?"fts-floor":r,k:10,recall_at_1:u.recall_at_1??null,recall_at_10:u.recall_at_k??null,mrr:u.mrr??null,queries:u.n??l.performance?.queries??null,p50_ms:l.performance?.p50_ms??null,p95_ms:l.performance?.p95_ms??null}}catch{return null}}async function At(m){const c=console.error;console.error=()=>{};const s=C();let i=0;const r=(o,t)=>{console.log(` ${p.green("\u2714")} ${o} \u2014 ${p.dim(t)}`)},e=(o,t,n)=>{i++,console.log(` ${p.red("\u2716")} ${o} \u2014 ${t}`),console.log(` ${p.yellow("fix:")} ${n}`)};try{const o=s.getDatabase();R("wyrm doctor");const{tierForResolution:t}=await import("./providers/embedding-provider.js"),{effectiveEmbeddingState:n}=await import("./live-embedding-state.js"),d=n(o,process.cwd()),a=t(d),l=d.source==="server"?` \xB7 via running server (pid ${d.pid}${process.cwd()===d.cwd||process.cwd().startsWith(d.cwd.replace(/\/+$/,"")+"/")?"":`, ${d.cwd}`})`:"";d.reason===""&&d.resolved!=="local"?r("Embedding provider",`${d.resolved} (${d.model}) \xB7 tier ${a.n}/3 (${a.label})${d.egressHost?` \xB7 egress: ${d.egressHost}`:" \xB7 local"}${l}`):d.resolved==="local"?e("Embedding provider",`local-hash (hash-384) is NOT semantic \u2014 test-only vectors \xB7 tier ${a.n}/3 (${a.label})${l}`,d.fix||"use NVIDIA NIM: set WYRM_VECTOR_PROVIDER=nim + NVIDIA_API_KEY"):d.reason==="ollama_deprecated"?e("Embedding provider",`ollama (deprecated \u2014 leaves in the next major) \xB7 tier ${a.n}/3 (${a.label})${l}`,d.fix):e("Embedding provider",`none (${d.reason}) \xB7 tier ${a.n}/3 (${a.label})${l}`,d.fix),a.n===2&&console.log(` ${p.dim("next: wyrm upgrade \u2192 max recall (hosted NIM)")}`);const u=o.prepare("SELECT COUNT(*) AS n FROM memory_artifacts").get().n;if(d.resolved==="none"||d.resolved==="local"){let y=0;try{y=o.prepare("SELECT COUNT(*) AS n FROM vectors").get().n}catch{}e("Vector index",`${y} vector(s) / ${u} memories \u2014 recall is FTS5 keyword-only (~59.9% vs 72.2% hybrid recall@10)`,d.fix||"enable a provider, then: wyrm index rebuild")}else{let y=0;try{y=o.prepare("SELECT COUNT(DISTINCT content_id) AS n FROM vectors WHERE content_type = 'artifact' AND model = ?").get(d.model).n}catch{}if(y===0&&u>0)e("Vector index",`provider '${d.resolved}' is configured but 0 of ${u} memories are indexed`,"wyrm index rebuild");else{const w=u>0?Math.round(y/u*100):100;let b;try{b=o.prepare("SELECT model, COUNT(DISTINCT content_id) AS n FROM vectors WHERE content_type = 'artifact' AND model <> ? GROUP BY model ORDER BY n DESC LIMIT 1").get(d.model)}catch{}b&&b.n>y?e("Vector index",`${y} of ${u} indexed under the ACTIVE model ${d.model} (${w}%), but ${b.n} are indexed under ${b.model} \u2014 the embedding provider changed and semantic recall cannot see those`,"restore the previous provider (check the MCP server env: WYRM_VECTOR_PROVIDER + its API key), or re-embed everything: wyrm index rebuild"):u>=50&&w<25?e("Vector index",`only ${y} of ${u} memories indexed under ${d.model} (${w}%) \u2014 most of the store is invisible to semantic recall`,"wyrm index rebuild"):r("Vector index",`${y} of ${u} memories indexed under ${d.model} (${w}%)`),w<100&&!b&&!(u>=50&&w<25)&&console.log(` ${p.dim("next: wyrm index rebuild backfills the rest")}`)}}if(d.resolved!=="none"&&d.resolved!=="local"){const{getMeta:y}=await import("./events.js"),{RETIRED_NIM_EMBED_MODELS:w}=await import("./providers/embedding-provider.js"),b=d.model?w[d.model]:void 0,$=y(o,"embed_last_ok_at"),v=y(o,"embed_last_error_at"),S=y(o,"embed_last_error"),_=L=>Date.parse(L.includes("T")?L:L.replace(" ","T")+"Z"),j=L=>Math.max(0,Math.round((Date.now()-_(L))/36e5));let T=null,A=0;try{T=o.prepare("SELECT MAX(created_at) AS t FROM vectors WHERE content_type = 'artifact' AND model = ?").get(d.model).t,T&&(A=o.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE needs_review = 0 AND created_at > ?").get(T).n)}catch{}const W=!!v&&(!$||_(v)>_($)),z=!!T&&A>0&&j(T)>24;if(b||W||z){const L=[];b&&L.push(`${d.model} was retired by NVIDIA on ${b} and can no longer embed`),z&&L.push(`${A} memories written since the newest ${d.model} vector (${j(T)}h ago): indexing has stopped`),W&&L.push(`last embed error ${j(v)}h ago: ${S??"unknown"}`);const Q=!!b||/\b410\b|end of life|no longer available/i.test(S??"");e("Embedding health",L.join("; "),Q?"upgrade Wyrm, or set WYRM_NIM_EMBED_MODEL to a supported model, then re-embed: wyrm index rebuild":"check the provider key, quota and the model named in the error, then: wyrm index rebuild")}else $&&r("Embedding health",`last successful embed ${j($)}h ago`)}try{const y=o.prepare("SELECT COUNT(*) AS n FROM memory_artifacts_fts").get().n;y===u?r("FTS index",`${y}/${u} rows in sync`):e("FTS index",`${y} FTS rows vs ${u} 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 f=o.prepare("SELECT COUNT(*) AS n FROM failure_patterns WHERE resolved = 0").get().n;r("Failure firewall",`${f} unresolved pattern(s) \xB7 matching = exact signature + FTS5 fuzzy (no vector tier in this build)`);const h=o.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=o.prepare("SELECT MAX(version) AS v FROM schema_versions").get().v,{schemaSkew:w}=await import("./migrations.js"),b=w(o);b.storeIsNewer?e("Schema",`store is at migration v${b.store}, but this Wyrm only knows up to v${b.binary}: an older binary is writing to a newer store`,"upgrade Wyrm on this machine: wyrm update"):r("Schema",`migration v${y??0}`)}catch{e("Schema","schema_versions unreadable","wyrm maintenance")}try{const{lastMaintenanceAt:y}=await import("./self-maintenance.js"),w=y(o);if((process.env.WYRM_AUTO_MAINTENANCE??"1")==="0")e("Store upkeep","automatic maintenance is disabled (WYRM_AUTO_MAINTENANCE=0) \u2014 pruning and metabolize never run","unset WYRM_AUTO_MAINTENANCE, or schedule `wyrm maintenance` yourself");else if(!w)r("Store upkeep","automatic \u2014 first sweep runs on the next MCP server start");else{const $=(Date.now()-Date.parse(w))/36e5;$>72?e("Store upkeep",`last sweep ${Math.floor($/24)}d ago \u2014 the store is not being pruned`,"wyrm maintenance"):r("Store upkeep",`last sweep ${$<1?"under an hour":`${Math.floor($)}h`} ago (automatic, daily)`)}}catch{}try{const{wyrmMemoHookStatus:y}=await import("./autoconfig.js"),w=y(),b=(process.env.WYRM_MEMO_MODE??"observe").toLowerCase();if(!w.installed)r("Token firewall","not installed (optional) \u2014 `wyrm memo` records what you re-read in full");else{const $=o.prepare("SELECT COUNT(*) AS memos, COALESCE(SUM(hits),0) AS hits, COALESCE(SUM(tokens_avoided),0) AS tok FROM read_memos").get(),v=`${$.memos} memo(s), ${$.hits} repeat read(s), ~${$.tok} tokens`;b==="observe"&&$.hits>0?r("Token firewall",`${v} \u2014 observe mode, nothing withheld yet. Set WYRM_MEMO_MODE=warn to hand the map back instead`):r("Token firewall",`${b} mode \xB7 ${v}`)}}catch{}console.log(""),i===0?k("All checks passed \u2014 nothing is silently off."):(g(`${i} check(s) DEGRADED \u2014 the fixes above are exact.`),process.exitCode=1)}finally{s.close(),console.error=c}}const Pt=new Set(["nomic-embed-text","nomic-embed-text-v1.5-int8","nvidia/nemotron-3-embed-1b","nvidia/llama-nemotron-embed-vl-1b-v2","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 Lt(m){const{tierForResolution:c}=await import("./providers/embedding-provider.js"),{detectClients:s,loadWyrmMeta:i}=await import("./autoconfig.js"),r=l=>l.split(ue()).join("~"),e=l=>l&&(Pt.has(l)?l:"custom"),o=U(),{effectiveEmbeddingState:t}=await import("./live-embedding-state.js"),n=console.error;console.error=()=>{};const d=C(),a=["## Wyrm Report",""];try{const l=d.getDatabase(),u=t(l,process.cwd()),f=c(u),h=v=>{try{return l.prepare(v).get().n}catch{return 0}};a.push(`version: ${o.version??"unknown"}`),a.push(`search tier: ${f.n}/3 (${f.label}) \xB7 provider: ${u.resolved}${u.model?` (${e(u.model)})`:""}${u.reason?` \xB7 reason: ${u.reason}`:""}${u.source==="server"?" \xB7 via running server":""}`),a.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();a.push(`last session: ${y?.date??"none yet"}`);const w=s().filter(v=>v.configured).map(v=>v.id);a.push(`clients: ${w.length?w.join(", "):"none configured"}`);const b=F(ue(),".claude","hooks","wyrm-session-capture.mjs");a.push(`hooks: ${q(b)?"installed (Claude Code)":"not installed (model-driven capture on non-Claude-Code clients)"}`);const $=i();a.push(`setup: ${$?`clients ${$.configuredClients.join(", ")} (last setup ${$.lastSetup})`:"no setup metadata"}`),a.push(`db: ${r(Ce())}`)}finally{d.close(),console.error=n}console.log("```"),console.log(a.join(`
|
|
77
|
-
`)),console.log("```")}async function
|
|
78
|
-
resolve one: wyrm failure resolve <id>`));return}if(i==="resolve"){const
|
|
79
|
-
${
|
|
80
|
-
${
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
Running:
|
|
85
|
-
`));const
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
67
|
+
`).all();if(t.length===0){console.log(y.dim(` No artifacts pending review${o?` for ${o}`:""}.`)),i.close();return}S(`Review Queue (${t.length} items)`);const r=ae({input:process.stdin,output:process.stdout}),u=d=>new Promise(p=>{r.question(d,p)}),a=new K(n);try{const{createVectorStore:d}=await import("./vectors.js"),p=process.env.WYRM_VECTOR_PROVIDER??"auto";p!=="none"&&a.setVectorStore(d({provider:p},n))}catch{}for(const d of t){console.log(`
|
|
68
|
+
${y.bold(`[${d.kind}] #${d.id}`)}`),console.log(y.dim("\u2500".repeat(60))),console.log(d.problem.slice(0,300)),console.log(y.dim("\u2500".repeat(60)));const m=(await u(`${y.cyan("[a]")}pprove / ${y.red("[r]")}eject / ${y.yellow("[s]")}kip? `)).trim().toLowerCase();m==="a"?(a.approve(d.id),k(`Approved #${d.id}`)):m==="r"?(n.prepare("DELETE FROM memory_artifacts WHERE id = ?").run(d.id),console.log(`${B.cross} Rejected #${d.id}`)):console.log(y.dim(` Skipped #${d.id}`))}await a.flushIndexing(),r.close(),i.close(),console.log(`
|
|
69
|
+
Review complete.`)}async function Wt(c){const{positional:l,flags:o}=j(c),i=l[0];(!i||!["export","import","preview"].includes(i))&&(f("Usage: wyrm sync export --out <path> | wyrm sync import --from <path> | wyrm sync preview --from <path>"),process.exit(1));const{randomBytes:n,pbkdf2Sync:s,createCipheriv:e,createDecipheriv:t}=await import("crypto"),{readFileSync:r,writeFileSync:u,copyFileSync:a,unlinkSync:d,existsSync:p,chmodSync:m}=await import("fs"),{homedir:h}=await import("os"),{join:g}=await import("path"),w=(await import("better-sqlite3")).default;let b=process.env.WYRM_SYNC_PASSPHRASE??"";if(!b){const O=ae({input:process.stdin,output:process.stdout});b=await new Promise(Y=>{process.stdout.write("Passphrase: "),process.stdin.isTTY&&process.stdin.setRawMode?.(!0),O.question("",G=>{process.stdin.isTTY&&process.stdin.setRawMode?.(!1),console.log(""),O.close(),Y(G)})})}b||(f("Passphrase is required. Set WYRM_SYNC_PASSPHRASE or enter interactively."),process.exit(1));const $=g(h(),".wyrm"),v=C();if(i==="export"){const O=o.out;O||(f("--out <path> is required"),process.exit(1));const Y=g($,"wyrm_cli_export_temp.db");try{const G=v.getDatabase();p(Y)&&d(Y),G.prepare("VACUUM INTO ?").run(Y);const Z=r(Y),Q=n(32),se=n(16),qe=s(b,Q,6e5,32,"sha256"),de=e("aes-256-gcm",qe,se),He=Buffer.concat([de.update(Z),de.final()]),Ve=de.getAuthTag(),Be=Buffer.from("WYRM"),ve=Buffer.alloc(1);ve.writeUInt8(1,0);const $e=Buffer.concat([Be,ve,Q,se,Ve,He]);u(O,$e);try{m(O,384)}catch{}try{d(Y)}catch{}const Ke=($e.length/(1024*1024)).toFixed(2);k(`Exported to ${O} (${Ke} MB)`)}catch(G){try{p(Y)&&d(Y)}catch{}f(`Export failed: ${G}`)}v.close();return}const R=o.from;R||(f("--from <path> is required"),process.exit(1));const E=r(R);E.subarray(0,4).toString("ascii")!=="WYRM"&&(f("Invalid Wyrm snapshot file."),process.exit(1));const x=E.readUInt8(4);x!==1&&(f(`Unsupported snapshot version: ${x}`),process.exit(1));const T=E.subarray(5,37),N=E.subarray(37,53),I=E.subarray(53,69),W=E.subarray(69),F=s(b,T,6e5,32,"sha256"),z=t("aes-256-gcm",F,N);z.setAuthTag(I);let oe;try{oe=Buffer.concat([z.update(W),z.final()])}catch{f("Decryption failed \u2014 wrong passphrase or corrupted file."),process.exit(1)}if(i==="preview"){const O=g($,"wyrm_cli_preview_temp.db");p(O)&&d(O),u(O,oe);try{const Y=new w(O,{readonly:!0}),G=["projects","sessions","ground_truths","memory_artifacts","quests"];S("Snapshot Preview");const Z=[];for(const Q of G)try{const se=Y.prepare(`SELECT COUNT(*) as n FROM ${Q}`).get();Z.push([Q,String(se.n)])}catch{Z.push([Q,"?"])}console.log(P(["Table","Count"],Z)),Y.close()}catch(Y){f(`Preview failed: ${Y}`)}try{p(O)&&d(O)}catch{}v.close();return}const X=v.getDatabasePath(),be=ae({input:process.stdin,output:process.stdout}),Fe=await new Promise(O=>{be.question("This will REPLACE your current database. Type CONFIRM to proceed: ",O)});if(be.close(),Fe.trim()!=="CONFIRM"){console.log(y.dim("Aborted.")),v.close();return}const Ye=new Date().toISOString().replace(/[:.]/g,"-"),ce=`${X}.backup.${Ye}`;a(X,ce),k(`Backed up to ${ce}`);const le=g($,"wyrm_cli_restore_temp.db");u(le,oe),v.getDatabase().close(),a(le,X);for(const O of["-wal","-shm"])try{p(X+O)&&d(X+O)}catch{}try{d(le)}catch{}k(`Restored from ${R}. Backup at ${ce}`)}async function Ut(c){const{flags:l}=j(c),o=l.project,i=l.path,n=te(l["min-confidence"],.3),s=A(l["older-than"],90),e=l["no-dry-run"]===!0,t=l.yes===!0,r=C(),u=r.getDatabase();let a=null;if(i||o){const g=i?r.getProject(i):M(r,o);g||(f(`Project not found: ${i??o}`),r.close(),process.exit(1)),a=g.id}const d=new K(u),{candidates:p}=d.pruneStale({projectId:a,minConfidence:n,olderThanDays:s,dryRun:!0});if(S(`Prune Candidates${e?" (LIVE DELETE)":" (dry-run)"}`),p.length===0){console.log(y.dim(" No artifacts match prune criteria.")),r.close();return}const m=p.map(g=>[String(g.id),g.kind,g.problem.slice(0,60),(g.confidence*100).toFixed(0)+"%",g.last_accessed_at??"never"]);if(console.log(P(["ID","Kind","Problem","Conf","Last Accessed"],m)),console.log(`
|
|
70
|
+
Total: ${p.length} candidate(s)`),!e){console.log(y.dim(`
|
|
71
|
+
This is a dry run. Use --no-dry-run to delete (confirm each ID).`)),r.close();return}if(!t){const g=ae({input:process.stdin,output:process.stdout}),w=await new Promise(b=>{g.question(`
|
|
72
|
+
Delete these ${p.length} artifact(s)? Type CONFIRM to proceed: `,b)});if(g.close(),w.trim()!=="CONFIRM"){console.log(y.dim("Aborted.")),r.close();return}}const h=d.deleteArtifacts(p.map(g=>g.id));k(`Deleted ${h} artifact(s).`),r.close()}async function Ft(c){const{positional:l,flags:o}=j(c),i=l[0]||"list",n=C();try{if(i==="list"||i==="ls"){const s=xe(n);if(s.length===0){S("Connectors"),console.log(`${V.dim} none configured. Add one with: wyrm connector add --name <n> --url <bridge-url> --workspace <w>${V.reset}`);return}S("Connectors");const e=s.map(t=>[t.name,t.source,t.enabled?"on":"off",t.workspace,no(t.baseUrl),t.allowlist.length?`${t.allowlist.length} chats`:"all"]);console.log(P(["Name","Source","Enabled","Workspace","Bridge","Allowlist"],e));return}if(i==="add"){const s=D(o.name),e=D(o.url),t=D(o.workspace);if(!s||!e||!t){f("usage: wyrm connector add --name <n> --url <bridge-url> --workspace <w> [--allowlist a,b] [--token T] [--disabled]"),process.exitCode=1;return}const r={name:s,source:"bridge",enabled:!o.disabled,baseUrl:e,workspace:t,allowlist:D(o.allowlist)?D(o.allowlist).split(",").map(u=>u.trim()).filter(Boolean):[],...D(o.token)?{authToken:D(o.token)}:{}};pt(n,r),k(`Connector "${s}" saved (source=bridge, workspace=${t}). Token, if any, stored without being printed.`),console.log(`${V.dim} Tip: prefer the env var WYRM_CONNECTOR_TOKEN_${s.toUpperCase().replace(/[^A-Z0-9]/g,"_")} over --token.${V.reset}`);return}if(i==="sync"){const s=l[1]||D(o.name);if(s){const t=xe(n).find(u=>u.name===s);if(!t){f(`Connector not found: ${s}`),process.exitCode=1;return}const r=await mt(n,t);k(`${r.source}: fetched ${r.fetched}, ingested ${r.ingested}, skipped ${r.skipped} -> ${r.workspace}`);return}const e=await ft(n);if(e.length===0){console.log(`${V.dim} no enabled connectors.${V.reset}`);return}for(const t of e)"error"in t?f(`${t.name}: ${t.error}`):k(`${t.source}: fetched ${t.fetched}, ingested ${t.ingested}, skipped ${t.skipped} -> ${t.workspace}`);return}f(`Unknown connector subcommand: ${i} (use list | add | sync)`),process.exitCode=1}finally{n.close()}}function Ie(){return J(0,"utf-8").trim()}async function Yt(){const{initializeLicense:c,getLicenseInfo:l,getTier:o}=await import("./license.js");c();const{refreshRevocations:i}=await import("./revocations.js"),{refreshLicenseIfNeeded:n}=await import("./license-refresh.js");await i();const s=await n(),e=l();S("Wyrm License");const t=e.valid?"valid":e.error==="License revoked"?"REVOKED (running as free tier)":e.error&&/expired/i.test(e.error)?"EXPIRED (running as free tier)":e.key?`invalid (${e.error??"unknown reason"}) \u2014 running as free tier`:"free tier (no license key)",r=[["Tier",o()],["Status",t]];e.key&&(r.push(["Key",e.key]),r.push(["Issued to",e.issuedTo??"unknown"]),r.push(["Expires",e.expiresAt?new Date(e.expiresAt).toLocaleDateString():"never"])),r.push(["Features",e.features.join(", ")||"(free)"]),console.log(P(["Field","Value"],r)),!e.valid&&!e.key&&console.log(y.dim(`
|
|
73
|
+
Activate with: wyrm login (free) \xB7 or: wyrm activate <license.json | key>`)),s==="refreshed"&&console.log(y.dim(`
|
|
74
|
+
License refreshed automatically.`)),!e.valid&&e.error==="License revoked"&&console.log(y.dim(`
|
|
75
|
+
This license has been revoked. Contact support if you believe this is a mistake.`)),console.log(y.dim(`
|
|
76
|
+
\xA9 2026 Ghost Protocol (Pvt) Ltd \xB7 Proprietary \xB7 https://wyrm.ghosts.lk`)),console.log(y.dim(" Licensed under the Wyrm Terms of Service. No open-source license is granted."))}async function qt(){const c=(process.env.WYRM_ACCOUNT_URL??"https://account.ghosts.lk").replace(/\/$/,""),l=(()=>{try{return H().version??"unknown"}catch{return"unknown"}})();let o;try{const d=await fetch(`${c}/api/v1/cli/auth/start`,{method:"POST",headers:{"x-wyrm-version":l}});if(!d.ok)throw new Error(`HTTP ${d.status}`);o=await d.json()}catch(d){f(`Couldn't reach ${c} (${d instanceof Error?d.message:"network error"}).`),process.exitCode=1;return}const i=o.verification_uri_complete||o.verification_uri||`${c}/cli`;console.log(`
|
|
77
|
+
${y.cyan("Sign in to activate Wyrm (free):")}`),console.log(` 1. Open ${y.cyan(i)}`),console.log(` 2. Approve the code ${y.cyan(o.user_code)}`),console.log(y.dim(`
|
|
78
|
+
Waiting for approval\u2026 (Ctrl-C to cancel)`));const n=(o.interval??3)*1e3,s=Date.now()+(o.expires_in??600)*1e3;let e="";for(;Date.now()<s;){await new Promise(d=>{setTimeout(d,n)});try{const p=await(await fetch(`${c}/api/v1/cli/auth/poll`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:o.device_code})})).json();if(p.status==="approved"&&p.token){e=p.token;break}if(p.status==="denied"||p.error==="expired"){f("Login was denied or the code expired. Run `wyrm login` again."),process.exitCode=1;return}}catch{}}if(!e){f("Login timed out. Run `wyrm login` again."),process.exitCode=1;return}let t;try{const d=await fetch(`${c}/api/v1/license/free`,{method:"POST",headers:{authorization:`Bearer ${e}`,"x-wyrm-version":l}});if(!d.ok){const p=await d.json().catch(()=>({}));f(`Activation failed (${d.status}): ${p.hint||p.error||"unknown error"}`),process.exitCode=1;return}t=JSON.stringify(await d.json())}catch(d){f(`Activation request failed (${d instanceof Error?d.message:"network error"}).`),process.exitCode=1;return}const{saveAccountToken:r}=await import("./license-refresh.js");r(e);const{activateLicense:u}=await import("./license.js"),a=u(t);if(a.valid){k(`Signed in & activated \u2014 ${a.tier} tier (expires ${a.expiresAt??"never"}).`),console.log(y.dim(" Restart the Wyrm MCP server / daemon to apply."));const{refreshRevocations:d}=await import("./revocations.js");await d()}else f(`Activation failed: ${a.error??"unknown error"}`),process.exitCode=1}async function Ht(c){const{positional:l}=j(c),o=l[0];let i;o&&q(o)?i=J(o,"utf-8"):o?i=o:process.stdin.isTTY?(f("Usage: wyrm activate <license.json path | license JSON> (or pipe the JSON on stdin)"),process.exit(1)):i=Ie();const{activateLicense:n}=await import("./license.js");try{const s=n(i);s.valid?(k(`License activated \u2014 ${s.tier} tier (${s.features.join(", ")})`),console.log(y.dim(" Restart Wyrm (MCP server / daemon) to apply all features."))):(f(`License activation failed: ${s.error??"unknown error"}`),process.exitCode=1)}catch{f("Invalid license format. Please verify your license key."),process.exitCode=1}}async function Vt(c){const{flags:l}=j(c),{runMaintenance:o}=await import("./maintenance.js"),{FailurePatterns:i}=await import("./failure-patterns.js"),{SessionSeen:n}=await import("./session-seen.js"),{AgentPresence:s}=await import("./presence.js"),e=C();try{const t=e.getDatabase(),r=A(l["archive-days"],0),u=o({db:e,sessionSeen:new n(t),failures:new i(t),presence:new s(t)},{vacuum:l.vacuum===!0,archiveDays:r>0?r:void 0});try{const{LAST_MAINTENANCE_KEY:a}=await import("./self-maintenance.js");t.prepare("INSERT INTO wyrm_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(a,new Date().toISOString())}catch{}S("Maintenance complete");for(const a of u.lines)console.log(` - ${a}`);console.log(y.dim(`
|
|
79
|
+
Database size: ${u.dbSize}`))}finally{e.close()}}async function Bt(c){const{positional:l,flags:o}=j(c),i=l[0]??"trend",n=H().version??null,s=C();try{const e=s.getDatabase();if(i==="snapshot"){const t=D(o.kind)||"all",r=[];if((t==="all"||t==="health")&&ye(e,"health",yt(e),n)!=null&&r.push("health"),(t==="all"||t==="effectiveness")&&ye(e,"effectiveness",ht(e),n)!=null&&r.push("effectiveness"),t==="retrieval"||o.full===!0){const u=await Jt();u&&ye(e,"retrieval",u,n)!=null?r.push("retrieval"):u||console.log(y.dim(" retrieval: bench unavailable (run from the repo with bench/ present) \u2014 skipped"))}r.length?k(`metrics snapshot recorded: ${r.join(", ")} @ ${n??"unknown"}`):f("metrics snapshot: nothing recorded");return}if(i==="trend"){const t=D(o.kind),r=Number(D(o.limit))||14,u=t?[t]:["health","effectiveness","retrieval"];let a=!1;for(const d of u){const p=Te(e,d,r);if(!p.length)continue;a=!0,S(`${d} \u2014 ${p.length} snapshot(s)`);const m=Kt[d],h=p.slice().reverse().map(g=>[g.captured_at.slice(0,16),g.wyrm_version??"-",...m.map(w=>Gt(g.metrics[w]))]);console.log(P(["when","ver",...m],h));for(const g of wt(p,d))console.log(" "+y.yellow("!")+" "+g)}a||(console.log(y.dim(" No metrics yet. Record the first snapshot: wyrm metrics snapshot")),console.log(y.dim(" (health + effectiveness are cheap; add --full for retrieval recall@k.)")));return}if(i==="show"){const t=D(o.kind)||"health",r=Te(e,t,1);if(!r.length){console.log(y.dim(` No ${t} snapshot yet.`));return}S(`latest ${t} @ ${r[0].captured_at} (${r[0].wyrm_version??"-"})`),console.log(JSON.stringify(r[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{s.close()}}const Kt={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 Gt(c){return c==null?"-":typeof c=="number"?Number.isInteger(c)?String(c):c.toFixed(3):String(c)}async function Jt(){try{const c=re(ee(import.meta.url)),l=U(c,"..","bench"),o=U(l,"lib","retrieval-eval.mjs"),i=U(l,"eval-corpus.json");if(!q(o)||!q(i))return null;const n=process.env.WYRM_VECTOR_PROVIDER||"none";process.env.WYRM_LIVE_MEMORY="0";const{evaluate:s}=await import(o),{WyrmDB:e}=await import("./database.js"),{MemoryArtifacts:t}=await import("./memory-artifacts.js"),r=JSON.parse(J(i,"utf8")),u=`/tmp/wyrm-metrics-eval-${process.pid}.db`,a=new e(u);let d;try{d=s(r,a,t,{k:10})}finally{a.close();for(const m of["","-wal","-shm"])try{ze(u+m,{force:!0})}catch{}}const p=d.quality.overall;return{mode:n==="none"?"fts-floor":n,k:10,recall_at_1:p.recall_at_1??null,recall_at_10:p.recall_at_k??null,mrr:p.mrr??null,queries:p.n??d.performance?.queries??null,p50_ms:d.performance?.p50_ms??null,p95_ms:d.performance?.p95_ms??null}}catch{return null}}async function zt(c){const l=console.error;console.error=()=>{};const o=C();let i=0;const n=(e,t)=>{console.log(` ${y.green("\u2714")} ${e} \u2014 ${y.dim(t)}`)},s=(e,t,r)=>{i++,console.log(` ${y.red("\u2716")} ${e} \u2014 ${t}`),console.log(` ${y.yellow("fix:")} ${r}`)};try{const e=o.getDatabase();S("wyrm doctor");const{tierForResolution:t}=await import("./providers/embedding-provider.js"),{effectiveEmbeddingState:r}=await import("./live-embedding-state.js"),u=r(e,process.cwd()),a=t(u),d=u.source==="server"?` \xB7 via running server (pid ${u.pid}${process.cwd()===u.cwd||process.cwd().startsWith(u.cwd.replace(/\/+$/,"")+"/")?"":`, ${u.cwd}`})`:"";u.reason===""&&u.resolved!=="local"?n("Embedding provider",`${u.resolved} (${u.model}) \xB7 tier ${a.n}/3 (${a.label})${u.egressHost?` \xB7 egress: ${u.egressHost}`:" \xB7 local"}${d}`):u.resolved==="local"?s("Embedding provider",`local-hash (hash-384) is NOT semantic \u2014 test-only vectors \xB7 tier ${a.n}/3 (${a.label})${d}`,u.fix||"use NVIDIA NIM: set WYRM_VECTOR_PROVIDER=nim + NVIDIA_API_KEY"):u.reason==="ollama_deprecated"?s("Embedding provider",`ollama (deprecated \u2014 leaves in the next major) \xB7 tier ${a.n}/3 (${a.label})${d}`,u.fix):s("Embedding provider",`none (${u.reason}) \xB7 tier ${a.n}/3 (${a.label})${d}`,u.fix),a.n===2&&console.log(` ${y.dim("next: wyrm upgrade \u2192 max recall (hosted NIM)")}`);const p=e.prepare("SELECT COUNT(*) AS n FROM memory_artifacts").get().n;if(u.resolved==="none"||u.resolved==="local"){let g=0;try{g=e.prepare("SELECT COUNT(*) AS n FROM vectors").get().n}catch{}s("Vector index",`${g} vector(s) / ${p} memories \u2014 recall is FTS5 keyword-only (~59.9% vs 72.2% hybrid recall@10)`,u.fix||"enable a provider, then: wyrm index rebuild")}else{let g=0;try{g=e.prepare("SELECT COUNT(DISTINCT content_id) AS n FROM vectors WHERE content_type = 'artifact' AND model = ?").get(u.model).n}catch{}if(g===0&&p>0)s("Vector index",`provider '${u.resolved}' is configured but 0 of ${p} memories are indexed`,"wyrm index rebuild");else{const w=p>0?Math.round(g/p*100):100;let b;try{b=e.prepare("SELECT model, COUNT(DISTINCT content_id) AS n FROM vectors WHERE content_type = 'artifact' AND model <> ? GROUP BY model ORDER BY n DESC LIMIT 1").get(u.model)}catch{}b&&b.n>g?s("Vector index",`${g} of ${p} indexed under the ACTIVE model ${u.model} (${w}%), but ${b.n} are indexed under ${b.model} \u2014 the embedding provider changed and semantic recall cannot see those`,"restore the previous provider (check the MCP server env: WYRM_VECTOR_PROVIDER + its API key), or re-embed everything: wyrm index rebuild"):p>=50&&w<25?s("Vector index",`only ${g} of ${p} memories indexed under ${u.model} (${w}%) \u2014 most of the store is invisible to semantic recall`,"wyrm index rebuild"):n("Vector index",`${g} of ${p} memories indexed under ${u.model} (${w}%)`),w<100&&!b&&!(p>=50&&w<25)&&console.log(` ${y.dim("next: wyrm index rebuild backfills the rest")}`)}}if(u.resolved!=="none"&&u.resolved!=="local"){const{getMeta:g}=await import("./events.js"),{RETIRED_NIM_EMBED_MODELS:w}=await import("./providers/embedding-provider.js"),b=u.model?w[u.model]:void 0,$=g(e,"embed_last_ok_at"),v=g(e,"embed_last_error_at"),R=g(e,"embed_last_error"),E=F=>Date.parse(F.includes("T")?F:F.replace(" ","T")+"Z"),x=F=>Math.max(0,Math.round((Date.now()-E(F))/36e5));let T=null,N=0;try{T=e.prepare("SELECT MAX(created_at) AS t FROM vectors WHERE content_type = 'artifact' AND model = ?").get(u.model).t,T&&(N=e.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE needs_review = 0 AND created_at > ?").get(T).n)}catch{}const I=!!v&&(!$||E(v)>E($)),W=!!T&&N>0&&x(T)>24;if(b||I||W){const F=[];b&&F.push(`${u.model} was retired by NVIDIA on ${b} and can no longer embed`),W&&F.push(`${N} memories written since the newest ${u.model} vector (${x(T)}h ago): indexing has stopped`),I&&F.push(`last embed error ${x(v)}h ago: ${R??"unknown"}`);const z=!!b||/\b410\b|end of life|no longer available/i.test(R??"");s("Embedding health",F.join("; "),z?"upgrade Wyrm, or set WYRM_NIM_EMBED_MODEL to a supported model, then re-embed: wyrm index rebuild":"check the provider key, quota and the model named in the error, then: wyrm index rebuild")}else $&&n("Embedding health",`last successful embed ${x($)}h ago`)}try{const g=e.prepare("SELECT COUNT(*) AS n FROM memory_artifacts_fts").get().n;g===p?n("FTS index",`${g}/${p} rows in sync`):s("FTS index",`${g} FTS rows vs ${p} memories \u2014 keyword recall is missing rows`,"INSERT INTO memory_artifacts_fts(memory_artifacts_fts) VALUES('rebuild') via wyrm maintenance")}catch{s("FTS index","memory_artifacts_fts unreadable","wyrm maintenance")}const m=e.prepare("SELECT COUNT(*) AS n FROM failure_patterns WHERE resolved = 0").get().n;n("Failure firewall",`${m} unresolved pattern(s) \xB7 matching = exact signature + FTS5 fuzzy (no vector tier in this build)`);const h=e.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE needs_review = 1").get().n;h>0?s("Review queue",`${h} memor${h===1?"y":"ies"} invisible to recall until approved`,"wyrm review"):n("Review queue","empty");try{const g=e.prepare("SELECT MAX(version) AS v FROM schema_versions").get().v,{schemaSkew:w}=await import("./migrations.js"),b=w(e);b.storeIsNewer?s("Schema",`store is at migration v${b.store}, but this Wyrm only knows up to v${b.binary}: an older binary is writing to a newer store`,"upgrade Wyrm on this machine: wyrm update"):n("Schema",`migration v${g??0}`)}catch{s("Schema","schema_versions unreadable","wyrm maintenance")}try{const{lastMaintenanceAt:g}=await import("./self-maintenance.js"),w=g(e);if((process.env.WYRM_AUTO_MAINTENANCE??"1")==="0")s("Store upkeep","automatic maintenance is disabled (WYRM_AUTO_MAINTENANCE=0) \u2014 pruning and metabolize never run","unset WYRM_AUTO_MAINTENANCE, or schedule `wyrm maintenance` yourself");else if(!w)n("Store upkeep","automatic \u2014 first sweep runs on the next MCP server start");else{const $=(Date.now()-Date.parse(w))/36e5;$>72?s("Store upkeep",`last sweep ${Math.floor($/24)}d ago \u2014 the store is not being pruned`,"wyrm maintenance"):n("Store upkeep",`last sweep ${$<1?"under an hour":`${Math.floor($)}h`} ago (automatic, daily)`)}}catch{}try{const{wyrmMemoHookStatus:g}=await import("./autoconfig.js"),w=g(),b=(process.env.WYRM_MEMO_MODE??"observe").toLowerCase();if(!w.installed)n("Token firewall","not installed (optional) \u2014 `wyrm memo` records what you re-read in full");else{const $=e.prepare("SELECT COUNT(*) AS memos, COALESCE(SUM(hits),0) AS hits, COALESCE(SUM(tokens_avoided),0) AS tok FROM read_memos").get(),v=`${$.memos} memo(s), ${$.hits} repeat read(s), ~${$.tok} tokens`;b==="observe"&&$.hits>0?n("Token firewall",`${v} \u2014 observe mode, nothing withheld yet. Set WYRM_MEMO_MODE=warn to hand the map back instead`):n("Token firewall",`${b} mode \xB7 ${v}`)}}catch{}if(q(U(ie(),".claude"))){const{wyrmGuardHookStatus:g}=await import("./autoconfig.js"),w=g();w.installed?n("Firewall hooks",`wyrm-guard PreToolUse hooks installed in ${w.settingsPath}`):s("Firewall hooks",`no wyrm-guard hooks in ${w.settingsPath}, so recorded failures are not checked before Claude Code runs a tool`,"wyrm guard")}try{const{liveServers:g,serversPredatingInstall:w,packageInstalledAtMs:b}=await import("./stale-servers.js"),$=b(),v=g(e);if($!==null&&v.length>0){const R=H().version??"current",E=w(v,$);E.length>0?s("Running servers",`${E.length} of ${v.length} live wyrm-mcp server(s) predate the installed ${R} and still run the old code (pid ${E.map(x=>x.pid).join(", ")})`,"restart those sessions; their MCP clients start a server on the installed build"):n("Running servers",`${v.length} live, all started on the installed ${R}`)}}catch{}console.log(""),i===0?k("All checks passed \u2014 nothing is silently off."):(console.log(`${B.error} ${y.error(`${i} check(s) DEGRADED \u2014 the fixes above are exact.`)}`),process.exitCode=1)}finally{o.close(),console.error=l}}const Qt=new Set(["nomic-embed-text","nomic-embed-text-v1.5-int8","nvidia/nemotron-3-embed-1b","nvidia/llama-nemotron-embed-vl-1b-v2","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 Xt(c){const{tierForResolution:l}=await import("./providers/embedding-provider.js"),{detectClients:o,loadWyrmMeta:i}=await import("./autoconfig.js"),n=d=>d.split(ie()).join("~"),s=d=>d&&(Qt.has(d)?d:"custom"),e=H(),{effectiveEmbeddingState:t}=await import("./live-embedding-state.js"),r=console.error;console.error=()=>{};const u=C(),a=["## Wyrm Report",""];try{const d=u.getDatabase(),p=t(d,process.cwd()),m=l(p),h=v=>{try{return d.prepare(v).get().n}catch{return 0}};a.push(`version: ${e.version??"unknown"}`),a.push(`search tier: ${m.n}/3 (${m.label}) \xB7 provider: ${p.resolved}${p.model?` (${s(p.model)})`:""}${p.reason?` \xB7 reason: ${p.reason}`:""}${p.source==="server"?" \xB7 via running server":""}`),a.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 g=d.prepare("SELECT date FROM sessions ORDER BY id DESC LIMIT 1").get();a.push(`last session: ${g?.date??"none yet"}`);const w=o().filter(v=>v.configured).map(v=>v.id);a.push(`clients: ${w.length?w.join(", "):"none configured"}`);const b=U(ie(),".claude","hooks","wyrm-session-capture.mjs");a.push(`hooks: ${q(b)?"installed (Claude Code)":"not installed (model-driven capture on non-Claude-Code clients)"}`);const $=i();a.push(`setup: ${$?`clients ${$.configuredClients.join(", ")} (last setup ${$.lastSetup})`:"no setup metadata"}`),a.push(`db: ${n(Ne())}`)}finally{u.close(),console.error=r}console.log("```"),console.log(a.join(`
|
|
80
|
+
`)),console.log("```")}async function Zt(c){const{positional:l,flags:o}=j(c),i=l[0]??"list",n=C();try{const s=n.getDatabase();if(i==="list"){const e=s.prepare("SELECT id, scope, target, occurrences, last_seen FROM failure_patterns WHERE resolved = 0 ORDER BY last_seen DESC LIMIT 25").all();if(S("Unresolved failures"),!e.length){console.log(y.dim(" none \u2014 the firewall has nothing active."));return}console.log(P(["ID","Scope","Target","Seen","Last seen"],e.map(t=>[String(t.id),t.scope,t.target.slice(0,48),String(t.occurrences),t.last_seen]))),console.log(y.dim(`
|
|
81
|
+
resolve one: wyrm failure resolve <id>`));return}if(i==="resolve"){const e=Number(l[1]);if(!Number.isInteger(e)||e<=0){f('Usage: wyrm failure resolve <id> [--note "root cause fixed by ..."]'),process.exitCode=1;return}const t=D(o.note);(s.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",e).changes??0)>0?k(`Failure #${e} resolved \u2014 it will no longer flag.`):(f(`No unresolved failure #${e}.`),process.exitCode=1);return}f("Usage: wyrm failure <list|resolve <id> [--note N]>"),process.exitCode=1}finally{n.close()}}function Oe(c,l){const o=[],i=`--${l}`;for(let n=0;n<c.length;n++)if(c[n]===i&&n+1<c.length)for(const s of c[n+1].split(",")){const e=s.trim();if(e==="")continue;const t=Number(e);if(!Number.isInteger(t))throw new Error(`${i} must be a comma-separated list of integers (got "${e}")`);o.push(t)}return o}async function eo(c,l){const{positional:o}=j(c),i="Usage: wyrm recall --propose <query> [--project <name>] [--run <id>] [--limit N]",n=typeof l.propose=="string"?l.propose:o[0];if(!n){f(i),process.exitCode=1;return}const s=D(l.limit);let e;if(s&&(e=Number(s),!Number.isInteger(e)||e<1)){f(`--limit must be a positive integer (got "${s}")`),process.exitCode=1;return}const{buildRecallProposal:t}=await import("./handlers/recall.js"),{FailurePatterns:r}=await import("./failure-patterns.js"),{sanitizeActorId:u}=await import("./handlers/boundary.js"),a=C();try{const d=D(l.project),p=d?M(a,d):null;if(d&&!p){f(`Project not found: ${d}`),process.exitCode=1;return}const m=D(l.run),h=u(m||process.env.WYRM_RUN_ID),g=a.getDatabase(),w=new K(g),b=new pe(g),$=new r(g),v=await t({store:a,raw:()=>g,memory:w,truths:b,failures:$},{query:n,projectId:p?.id??null,runId:h,limit:e});S(`Recall proposal -- "${n}"`);const R=(E,x)=>{if(console.log(y.bold(`
|
|
82
|
+
${E} (${x.length})`)),x.length===0){console.log(y.dim(" (none)"));return}for(const T of x)console.log(` #${T.id} [${T.kind}/${T.outcome}] ${T.summary}`),console.log(y.dim(` conf ${(T.confidence*100).toFixed(0)}% | ${T.age_days}d old${T.project?` | ${T.project}`:""}`))};if(R("Prescriptions (muted by clean mode)",v.prescriptions),R("Firewall (never muted)",v.firewall),R("Ground truths",v.truths),v.prescriptions.length===0&&v.firewall.length===0&&v.truths.length===0){const E=ke(g,p?.id??null);E>0&&(console.log(y.warning(`
|
|
83
|
+
${E} stored ${E===1?"memory is":"memories are"} held for review and excluded from recall.`)),console.log(y.dim(` Run \`wyrm review\` to approve ${E===1?"it":"them"}, or \`wyrm review --auto on\` to stop queueing.`)))}console.log(y.dim("\n Review-only -- use `wyrm recall --set` to mute/veto specific ids."))}finally{a.close()}}async function to(c){const{positional:l,flags:o}=j(c);if(o.propose!==void 0)return eo(c,o);if(!o.set&&l.length>0)return De(c);const i="Usage: wyrm recall <query> [--project <name>] | 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(!o.set){f(i),process.exitCode=1;return}const{sanitizeActorId:n}=await import("./handlers/boundary.js"),{upsertRecallPolicy:s}=await import("./handlers/recall.js"),{RECALL_POLICY_MODES:e}=await import("./recall-policy.js"),t=D(o.run),r=n(t||process.env.WYRM_RUN_ID);if(!r){f("No run id: pass --run <id>, or export WYRM_RUN_ID (see `wyrm run start`)."),process.exitCode=1;return}let u;if(o.mode!==void 0){const m=D(o.mode);if(!e.includes(m)){f(`--mode must be one of: ${e.join(", ")} (got "${m}")`),process.exitCode=1;return}u=m}let a,d;try{a=Oe(c,"mute"),d=Oe(c,"challenge")}catch(m){f(m instanceof Error?m.message:String(m)),process.exitCode=1;return}const p=C();try{const m=s(p.getDatabase(),{runId:r,mode:u,muteIds:a.length?a:void 0,challengeTruthIds:d.length?d:void 0});k(`Recall policy for run ${r}: mode=${m.mode}`),console.log(y.dim(` Muted ids: ${m.mutedIds.length?m.mutedIds.join(", "):"(none)"}`)),console.log(y.dim(` Challenged truth ids: ${m.challengedTruthIds.length?m.challengedTruthIds.join(", "):"(none)"}`))}finally{p.close()}}async function oo(c){const{positional:l,flags:o}=j(c),i=l[0]??"list",n=C();try{if(i==="add"){const s=l[1],e=D(o.path);let t,r;if(e?(t=ne(e),r=s):s&&q(ne(s))?(t=ne(s),r=void 0):(t=ne(process.cwd()),r=s),!q(t)){f(`Path does not exist: ${t}`),process.exitCode=1;return}const u=D(o.name)||r||Ge(t),a=n.registerProject(u,t);k(`Project #${a.id} '${a.name}' registered at ${a.path}`);return}if(i==="list"){const s=n.getAllProjects(50);S("Projects"),console.log(P(["ID","Name","Path"],s.map(e=>[String(e.id),e.name,e.path])));return}f("Usage: wyrm project <add <name> [--path <dir>] | list>"),process.exitCode=1}finally{n.close()}}async function so(c){const{positional:l,flags:o}=j(c),i="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(i);return}const n=l[0]??"status",{createVectorStore:s}=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(n==="setup"){const{createProvider:u}=await import("./providers/embedding-provider.js"),a=u(t);if(!await a.isReady()&&t.provider!=="none"){f(`Provider not ready: ${a.name}. Check the configuration and try again.`),process.exitCode=1;return}k(`Vector provider verified: ${a.name} (model ${a.model}, ${a.dimensions}d)`),console.log(y.dim(" The MCP server reads WYRM_VECTOR_PROVIDER (and provider-specific env) at boot \u2014")),console.log(y.dim(` set WYRM_VECTOR_PROVIDER=${a.name==="none"?"none":t.provider} in the server env, then: wyrm index rebuild`));return}const r=C();try{const u=r.getDatabase(),a=s(t,u);if(n==="status"){const d=a.getStats();S("Vector index");const p=[["Provider",d.provider],["Model",d.model],["Vectors",String(d.total)],...Object.entries(d.byType).map(([m,h])=>[` ${m}`,String(h)])];console.log(P(["Field","Value"],p));return}if(n==="rebuild"){const{reindexProjects:d}=await import("./reindex.js"),p=o["dry-run"]===!0,m=o.project;let h;if(m){const $=r.getProject(m)??M(r,m);if(!$){f(`Project not found: ${m}`),process.exitCode=1;return}h=[$.id]}else h=r.getAllProjects(1e3).map($=>$.id);const{indexed:g,skipped:w}=await d(u,a,h,{dryRun:p,onError:($,v)=>f(`${$}: ${JSON.stringify(v)}`)}),b=`Reindex ${p?"(dry run) ":""}\u2014 ${h.length} project(s), ${g} indexed, ${w} skipped`;if(g===0&&w>0){const{resolveEmbeddingState:$}=await import("./providers/embedding-provider.js"),v=$(t.provider);ge(`${b}: ${v.reason||"embedding unavailable"}. fix: ${v.fix||"wyrm vectors download"}`)}else k(b);return}f(i),process.exitCode=1}finally{r.close()}}async function ro(c){const{positional:l,flags:o}=j(c);if(o.help===!0||typeof o.help=="string"){console.log("Usage: wyrm vectors <download|status> [--force]");return}const i=l[0]??"status",{bundledModelPresent:n,downloadBundledModel:s,BUNDLED_MODEL_DIR:e,BUNDLED_MODEL_SIZE_LABEL:t}=await import("./providers/bundled-model.js"),{resolveEmbeddingState:r,tierForResolution:u}=await import("./providers/embedding-provider.js");if(i==="status"){const m=console.error;console.error=()=>{};try{const{effectiveEmbeddingState:h}=await import("./live-embedding-state.js");let g=null,w=null;try{w=C(),g=w.getDatabase()}catch{g=null}const b=h(g,process.cwd());try{w?.close()}catch{}const $=u(b);S("wyrm vectors"),console.log(` provider: ${b.resolved}${b.model?` (${b.model})`:""}${b.source==="server"?` \xB7 via running server (pid ${b.pid})`:""}`),console.log(` tier: ${$.n}/3 (${$.label})`),console.log(` bundled model: ${n()?`present at ${e()}`:"not downloaded (run: wyrm vectors download)"}`)}finally{console.error=m}return}if(i!=="download"){f("Usage: wyrm vectors <download|status> [--force]"),process.exitCode=1;return}if(n()&&o.force!==!0){k("Bundled model already present.");return}S("Downloading bundled embedding model");const a=at(process.stdout),d=await s({onProgress:a.onProgress});if(a.finish(),!d.ok){f(`Download failed: ${d.error}`),console.log(" Recall stays keyword-only until this succeeds. Retry: wyrm vectors download"),process.exitCode=1;return}k(`Model ready (${t}). Vector recall is on.`);const{runBundledBackfill:p}=await import("./reindex.js");await p()}function D(c){return typeof c=="string"?c:""}function no(c){try{return new URL(c).host}catch{return c}}async function io(c){if(!process.stdin.isTTY){f("wyrm upgrade is interactive; run it in a terminal."),process.exitCode=1;return}const{tierForResolution:l}=await import("./providers/embedding-provider.js"),{effectiveEmbeddingState:o}=await import("./live-embedding-state.js");let i=null,n=null;try{n=C(),i=n.getDatabase()}catch{i=null}const s=o(i,process.cwd());try{n?.close()}catch{}const e=l(s);if(S("wyrm upgrade"),console.log(` Current: tier ${e.n}/3 (${e.label})${s.model?` \xB7 ${s.model}`:""}${s.source==="server"?` \xB7 via running server (pid ${s.pid})`:""}`),e.n===3){k("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(`
|
|
84
|
+
1. Get a free API key: ${y.cyan("https://build.nvidia.com")} (Get API Key on any embedding model page)`);let t;try{t=(await rt(" 2. Paste your key (nvapi-...): ")).trim()}catch(d){if(d instanceof nt){console.log(""),process.exitCode=130;return}throw d}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:r}=await import("./providers/embedding-provider.js");try{if(!(await new r(t).embed("wyrm connectivity probe")).length)throw new Error("empty embedding");console.log(y.green("ok"))}catch(d){console.log(y.red("failed")),f(`Key validation failed: ${d}. Nothing written.`),process.exitCode=1;return}const a=(await import("node:readline/promises")).createInterface({input:process.stdin,output:process.stdout});try{const{detectClients:d,applyWyrmEnvToClient:p}=await import("./autoconfig.js"),m=d().filter(b=>b.configured);if(!m.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 g=0;for(const b of m){let $=!1;try{const R=(await import("node:fs")).readFileSync(b.configPath,"utf-8");$=/WYRM_VECTOR_PROVIDER/.test(R)}catch{}if($&&(await a.question(` ${b.name} already sets a provider. Overwrite with NIM? [y/N] `)).trim().toLowerCase()!=="y"){console.log(` ${y.dim("skipped")}`);continue}const v=p(b,h);v.action==="updated"&&g++,console.log(` ${v.action==="updated"?y.green("\u2714"):y.dim("\u25CB")} ${b.name}: ${v.message}`)}if(g===0&&(ge("No client config was changed (all skipped or failed). The NIM tier is NOT active yet."),console.log(y.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 a.question(" Reindex existing memories on the NIM tier now? [Y/n] ")).trim().toLowerCase()!=="n"){const b=C();try{const $=b.getDatabase(),{createVectorStore:v}=await import("./vectors.js"),{reindexProjects:R}=await import("./reindex.js"),E=v({provider:"nim",apiKey:t},$),x=b.getAllProjects(1e3).map(I=>I.id),{indexed:T,skipped:N}=await R($,E,x,{dryRun:!1});k(`Reindexed on NIM: ${T} indexed, ${N} skipped.`)}finally{b.close()}}else console.log(` ${y.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")}`);g>0?k(`Upgrade complete (${g} client${g===1?"":"s"} updated). Restart your AI clients to pick up the new env.`):process.exitCode=1}finally{a.close()}}async function ao(c){const{flags:l}=j(c),{getUpdateStatus:o}=await import("./version-check.js"),i=H().version??"0.0.0",n=C();let s;try{s=await o(n.getDatabase(),i,{force:l.force===!0||l.check===!0})}finally{n.close()}S("Wyrm update");const e=s.latest?s.lookupFailed?`${s.latest} (last known \u2014 registry unreachable now)`:s.latest:s.lookupFailed?"unknown \u2014 npm registry unreachable":"unknown (version check disabled)";if(console.log(P(["Field","Value"],[["Current",s.current],["Latest",e],["Update available",s.updateAvailable?"yes":s.lookupFailed&&!s.latest?"unknown":"no"],["Checked",`${s.checkedAt} (${s.source})`]])),s.lookupFailed&&!s.updateAvailable&&l.force!==!0){f('Could not reach the npm registry, so whether an update exists is UNKNOWN (not "up to date").'),console.log(y.dim(" Retry when online: wyrm update \xB7 or install directly: npm install -g wyrm-mcp@latest")),process.exitCode=2;return}if(l.check===!0)return;if(!s.updateAvailable&&l.force!==!0){console.log(y.dim(`
|
|
85
|
+
Already up to date. (Use --force to reinstall anyway.)`));return}const{realpathSync:t,accessSync:r,constants:u}=await import("node:fs");let a=ee(import.meta.url);try{a=t(a)}catch{}const d=it(a);if(!d){f(`This wyrm is not running from a global npm install (${a}), so wyrm update will not replace it.`),console.log(y.dim(" Update it the way it was installed: in a checkout, git pull then npm run build.")),process.exitCode=1;return}const p=["install","-g","--prefix",d,"wyrm-mcp@latest","--allow-scripts=wyrm-mcp,better-sqlite3"],m=$=>/^[\w@%+=:,./-]+$/.test($)?$:`'${$.replace(/'/g,"'\\''")}'`,h=`npm ${p.map(m).join(" ")}`,w=(process.platform==="win32"?[U(d,"node_modules")]:[U(d,"lib","node_modules"),U(d,"bin")]).filter($=>q($)).filter($=>{try{return r($,u.W_OK),!1}catch{return!0}});if(w.length>0){f(`${w.join(" and ")} ${w.length===1?"is":"are"} not writable by this user, so npm cannot update the install there.`),console.log(` Run the update with the rights that installed it:
|
|
86
|
+
${h}`),process.exitCode=1;return}console.log(y.dim(`
|
|
87
|
+
Running: ${h}
|
|
88
|
+
`));const b=ue("npm",p,{stdio:"inherit",shell:!1});b.status===0?k("Updated. Restart your MCP clients to pick up the new binary."):(f(`npm install exited with ${b.status??(b.error?b.error.message:"unknown")}`),console.log(` The exact command was:
|
|
89
|
+
${h}`),process.exitCode=b.status??1)}async function co(c){const{positional:l,flags:o}=j(c),i=l[0],n=o.project??process.cwd();if(i==="inject"){const{injectSystemPrompt:s}=await import("./autoconfig.js"),e=typeof o.clients=="string"?o.clients.split(",").map(r=>r.trim()).filter(Boolean):[],t=s(n,e);S("System prompt injection");for(const r of t.injected)console.log(` + ${r}`);for(const r of t.skipped)console.log(y.dim(` o skipped (unknown client): ${r}`));for(const r of t.errors)f(r);t.injected.length>0&&k("AI clients in this project will now call wyrm_session_prime at conversation start."),t.errors.length>0&&(process.exitCode=1);return}if(i==="migrate"){const{migrateProject:s,renderMigrationReport:e}=await import("./migrate-prompt.js"),{WYRM_INJECT_BLOCK:t}=await import("./autoconfig.js"),r=o.apply===!0,u=s({projectPath:n,newBlock:t,apply:r});console.log(e(u,r));return}f("Usage: wyrm prompt inject [--project <path>] [--clients copilot,cursor] | wyrm prompt migrate [--project <path>] [--apply]"),process.exitCode=1}async function lo(c){const{positional:l,flags:o}=j(c);(l[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 n=o.from,s=o.to;(!n||!s)&&(f("--from and --to are required (YYYY-MM-DD)"),process.exit(1));const{HourLedger:e}=await import("./hours.js"),t=C();try{const r=o.project,u=r?M(t,r):null;if(r&&!u){f(`Project not found: ${r}`),process.exitCode=1;return}const a=new e(t.getDatabase()).report({range_start:n,range_end:s,project_id:u?.id,default_session_hours:te(o["session-hours"],1)});if(o.json===!0){console.log(JSON.stringify(a,null,2));return}if(S(`Hours ${a.range.start} \u2192 ${a.range.end}`),a.by_project.length===0){console.log(y.dim(" No sessions in range."));return}console.log(P(["Project","Sessions","Hours"],a.by_project.map(d=>[d.project_name,String(d.session_count),d.hours.toFixed(2)]))),console.log(`
|
|
90
|
+
Total: ${a.total_hours.toFixed(2)}h across ${a.entries.length} session(s)`+(a.estimated_sessions>0?y.dim(` (${a.estimated_sessions} estimated)`):""))}finally{t.close()}}async function uo(c){const{positional:l,flags:o}=j(c),i=l[0]??"generate",n=o.client,s=te(o.rate,NaN),e=o.from,t=o.to;(i!=="generate"||!n||!Number.isFinite(s)||!e||!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:r}=await import("./hours.js"),u=C();try{const a=o.project,d=a?M(u,a):null;if(a&&!d){f(`Project not found: ${a}`),process.exitCode=1;return}const p=new r(u.getDatabase()).invoice({client_name:n,hourly_rate_usd:s,range_start:e,range_end:t,project_id:d?.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:te(o["session-hours"],1)}),m=o.out;if(m){const{writeFileSync:h}=await import("node:fs");h(m,p+`
|
|
91
|
+
`,"utf-8"),k(`Invoice written to ${m}`)}else process.stdout.write(p+`
|
|
92
|
+
`)}finally{u.close()}}async function po(c){const{positional:l,flags:o}=j(c),i=l[0]??"status",{AgentDaemon:n}=await import("./agent-daemon.js"),s=C();try{const e=new n(s.getDatabase());switch(i){case"init":case"start":{const t=Math.max(10,Math.min(A(o.interval,600),86400)),r=e.start({interval_seconds:t,max_steps:o["max-steps"]!==void 0&&A(o["max-steps"],0)||void 0,project_path:o.project,verbose:o.verbose===!0});if(!r.ok){f(`Agent init failed: ${r.error}`),process.exitCode=1;return}const u=r.status;k(`Agent ${u.pid!=null&&u.pid!==r.pid?"already running":"started"} \u2014 pid ${u.pid}`),console.log(` Interval: ${t}s \xB7 Active goals: ${u.active_goals} \xB7 Total iterations: ${u.total_iterations}`),console.log(y.dim(` Log: ${u.log_file}`));return}case"status":{const t=e.status();S("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(`
|
|
93
|
+
=== Recent log ===`),console.log(e.recentLog(40)));return}case"stop":{const t=await e.stop({grace_ms:o.grace!==void 0?A(o.grace,3e3):void 0});if(!t.ok){f(`Stop failed: ${t.error}`),process.exitCode=1;return}k(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 e.restart({interval_seconds:o.interval!==void 0?A(o.interval,600):void 0,max_steps:o["max-steps"]!==void 0&&A(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}k(`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{s.close()}}async function mo(c){if(c.includes("--encrypt")){const{initializeLicense:i,hasFeature:n}=await import("./license.js");if(i(),!n("encryption")){f("Encryption setup requires a Pro license or higher. See: wyrm license"),process.exitCode=1;return}const{getCrypto:s,initializeCrypto:e}=await import("./crypto.js"),t=c.includes("--enable"),r=c.includes("--test");if(t){const a=process.env.WYRM_ENCRYPTION_KEY??(process.stdin.isTTY?"":Ie());if(!a||a.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}e(a),k("Encryption enabled (AES-256-GCM, key derived via PBKDF2). Store your password safely \u2014 it cannot be recovered.");return}const u=s();if(r){if(!u.isEnabled()){f("Encryption not enabled. Run: wyrm setup --encrypt --enable"),process.exitCode=1;return}const a="Wyrm encryption test "+Date.now();u.decrypt(u.encrypt(a))===a?k("Encryption test PASSED (encrypt \u2192 decrypt roundtrip)."):(f("Encryption test FAILED."),process.exitCode=1);return}S("Encryption status"),console.log(` Enabled: ${u.isEnabled()?"yes \u2014 new data is encrypted at rest":"no"}`),console.log(" Algorithm: AES-256-GCM"),u.isEnabled()||console.log(y.dim(" Enable with: wyrm setup --encrypt --enable (password via WYRM_ENCRYPTION_KEY or stdin)"));return}const l=re(ee(import.meta.url)),o=ue(process.execPath,[U(l,"setup.js"),...c],{stdio:"inherit",shell:!1});process.exitCode=o.status??0}async function fo(c){const l="https://github.com/Ghosts-Protocol-Pvt-Ltd/wyrm-mcp",i=`- wyrm-mcp: ${H().version??"unknown"}
|
|
90
94
|
- node: ${process.version}
|
|
91
|
-
- platform: ${process.platform} ${process.arch}`,
|
|
95
|
+
- platform: ${process.platform} ${process.arch}`,n=c.includes("--bug")?"bug":c.includes("--idea")||c.includes("--feature")?"idea":c.includes("--question")||c.includes("--ask")?"question":"feedback",s=c.filter(u=>!u.startsWith("--")).join(" ").trim(),e={bug:`**What happened**
|
|
92
96
|
|
|
93
97
|
|
|
94
98
|
**What you expected**
|
|
@@ -114,66 +118,19 @@ ${i}`,feedback:`**Your feedback** (what's working, what's rough)
|
|
|
114
118
|
|
|
115
119
|
|
|
116
120
|
---
|
|
117
|
-
${i}`},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(o.question)}`:n=`${c}/issues/new?labels=${encodeURIComponent(t[r])}&title=${encodeURIComponent(`[${r}] ${e}`.trim())}&body=${encodeURIComponent(o[r])}`,console.log(""),console.log(" "+p.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(" "+p.cyan(n)),console.log(""),console.log(p.dim(" Prefer email? ryan@ghosts.lk \xB7 Bug: wyrm feedback --bug Idea: --idea Question: --question")),console.log("");try{const{spawn:d}=await import("child_process"),a=process.platform,l=a==="darwin"?d("open",[n],{stdio:"ignore",detached:!0}):a==="win32"?d("cmd",["/c","start","",n],{stdio:"ignore",detached:!0}):d("xdg-open",[n],{stdio:"ignore",detached:!0});l.on("error",()=>{}),l.unref()}catch{}}function Te(){console.log(`
|
|
118
|
-
${
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
${
|
|
122
|
-
|
|
123
|
-
${
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
${p.cyan("presence")} <announce|list|release> Agent presence board from the shell; --pid = process-identity liveness
|
|
131
|
-
${p.cyan("digest")} --writes [--since <days>] What Wyrm learned, queued, and refused \u2014 the offline write-receipt report
|
|
132
|
-
${p.cyan("bridge")} <init|status|run> The substrate flow: remember/render/reverse lanes from one receipted config
|
|
133
|
-
${p.cyan("forget")} --match|--dataset|--older-than Erase ingested third-party data (dry run unless --yes)
|
|
134
|
-
${p.cyan("metabolize")} [--dry-run] Memory metabolism: supersede exact dupes, queue near-dup candidates, decay stale auto-captures
|
|
135
|
-
${p.cyan("render")} [--client <list>] [--brief] Compile DB \u2192 MEMORY.md + topic files (zero-MCP-token memory)
|
|
136
|
-
${p.cyan("import git")} Import git log history to review queue
|
|
137
|
-
${p.cyan("import rules")} <path> Import .cursorrules / copilot-instructions file
|
|
138
|
-
${p.cyan("stats")} Show database statistics
|
|
139
|
-
${p.cyan("review")} [--approve-all] [--auto on|off] Activate queued memories (they are invisible to recall until you do)
|
|
140
|
-
${p.cyan("sync export")} --out <path> Export encrypted DB snapshot
|
|
141
|
-
${p.cyan("sync import")} --from <path> Restore from encrypted snapshot (backs up first)
|
|
142
|
-
${p.cyan("sync preview")} --from <path> Preview snapshot stats without restoring
|
|
143
|
-
${p.cyan("prune")} [--project <name>] Prune stale low-confidence artifacts (dry-run by default)
|
|
144
|
-
${p.cyan("cloud")} <login|sync|export|\u2026> Cloud backup & multi-device sync (Pro license)
|
|
145
|
-
${p.cyan("grove")} <status|policy> Per-project sync lanes (private|cloud|team) + leak audit
|
|
146
|
-
${p.cyan("visibility")} <kind>:<id> <level> Promote/demote a truth|mem|quest: cross-project search + cloud egress (within|org|public)
|
|
147
|
-
${p.cyan("run")} <start|join|end|status> Fleet-run lifecycle (records the migration-20 runs/run_agents tables)
|
|
148
|
-
${p.cyan("events")} [since|publish] [--project] Live-Memory event stream: read (since) or publish (was undocumented \u2014 tallow, 2026-07-14)
|
|
149
|
-
${p.cyan("skill")} <list|backfill-content|export|share> Discover bundled guides; store/sync SKILL.md content
|
|
150
|
-
${p.cyan("serve")} [--ui] Start the Wyrm HTTP server (optionally open the dashboard)
|
|
151
|
-
${p.cyan("setup")} [--check|--encrypt|\u2026] Auto-configure AI clients (wyrm-setup); --encrypt for at-rest crypto
|
|
152
|
-
${p.cyan("guard")} [--remove|--status] Failure-firewall PreToolUse hooks for Claude Code (wyrm-guard)
|
|
153
|
-
${p.cyan("memo")} [--remove|--status|--report] Token firewall: read-memo hooks for Claude Code (wyrm-memo), observe by default
|
|
154
|
-
${p.cyan("intro")} What Wyrm is and how to use it
|
|
155
|
-
${p.cyan("license")} Show license status & features
|
|
156
|
-
${p.cyan("login")} Sign in (free account) and activate \u2014 required on official builds
|
|
157
|
-
${p.cyan("activate")} <key|path> Activate a license (JSON arg, file path, or stdin)
|
|
158
|
-
${p.cyan("maintenance")} [--vacuum] Archive/prune/sweep/checkpoint the database
|
|
159
|
-
${p.cyan("index")} <setup|rebuild|status> Vector search: verify provider, reindex, stats
|
|
160
|
-
${p.cyan("vectors")} <download|status> Bundled local embedding model (default vector tier)
|
|
161
|
-
${p.cyan("doctor")} Health check that refuses to flatter \u2014 reports anything silently degraded
|
|
162
|
-
${p.cyan("report")} Shareable redacted diagnostic for support
|
|
163
|
-
${p.cyan("metrics")} <snapshot|trend|show> Effectiveness + quality OVER TIME \u2014 the flight recorder (trend flags drift)
|
|
164
|
-
${p.cyan("failure")} <list|resolve> Failure firewall: list unresolved patterns, resolve a fixed one
|
|
165
|
-
${p.cyan("recall")} --set [--mode M] [--run <id>] Negotiate a run's recall policy: mute/veto ids merge, --mode replaces
|
|
166
|
-
${p.cyan("recall")} --propose <query> Review buckets (prescriptions/firewall/truths) BEFORE negotiating --set
|
|
167
|
-
${p.cyan("project")} <add|list> Register a project without needing a session start
|
|
168
|
-
${p.cyan("update")} [--check] Check for / install the latest wyrm-mcp
|
|
169
|
-
${p.cyan("upgrade")} Guided upgrade to the max-recall tier (hosted NIM)
|
|
170
|
-
${p.cyan("prompt")} <inject|migrate> Inject/refresh the session-prime block in client files
|
|
171
|
-
${p.cyan("hours")} report --from --to Hours report derived from session history
|
|
172
|
-
${p.cyan("invoice")} generate --client \u2026 Markdown invoice from the hours ledger
|
|
173
|
-
${p.cyan("agent")} <init|status|stop|restart> Background agent daemon (goal loop)
|
|
174
|
-
${p.cyan("feedback")} [--bug|--idea|--question] Send feedback or report a bug (opens a prefilled GitHub report)
|
|
175
|
-
|
|
176
|
-
${p.bold("Options:")}
|
|
121
|
+
${i}`},t={bug:"bug",idea:"enhancement",question:"question",feedback:"feedback"};let r;n==="question"?r=`${l}/discussions/new?category=q-a`+(s?`&title=${encodeURIComponent(s)}`:"")+`&body=${encodeURIComponent(e.question)}`:r=`${l}/issues/new?labels=${encodeURIComponent(t[n])}&title=${encodeURIComponent(`[${n}] ${s}`.trim())}&body=${encodeURIComponent(e[n])}`,console.log(""),console.log(" "+y.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(" "+y.cyan(r)),console.log(""),console.log(y.dim(" Prefer email? ryan@ghosts.lk \xB7 Bug: wyrm feedback --bug Idea: --idea Question: --question")),console.log("");try{const{spawn:u}=await import("child_process"),a=process.platform,d=a==="darwin"?u("open",[r],{stdio:"ignore",detached:!0}):a==="win32"?u("cmd",["/c","start","",r],{stdio:"ignore",detached:!0}):u("xdg-open",[r],{stdio:"ignore",detached:!0});d.on("error",()=>{}),d.unref()}catch{}}const he=[{cmd:"search",name:"search",args:"<query>",desc:"Search across memories, truths, quests, and data"},{cmd:"recall",name:"recall",args:"<query>",desc:"The same retrieval as search (the recall step of the everyday loop)"},{cmd:"ls",name:"ls",args:"",desc:"List stored items"},{cmd:"show",name:"show",args:"<typed-id>",desc:"Show full detail (mem:N, quest:N, truth:N, data:N, session:N)"},{cmd:"capture",name:"capture",args:'"<content>"',desc:"Classify and capture a thought, task, or lesson (enrols a git repo on first use)"},{cmd:"rehydrate",name:"rehydrate",args:"[--project <name>]",desc:"Print the latest session's continuity brief (for SessionStart)"},{cmd:"session",name:"session log",args:"[--run <id>] [--\u2026]",desc:"Create/update this project's session record (rehydrate's write side)"},{cmd:"presence",name:"presence",args:"<announce|list|release>",desc:"Agent presence board from the shell; --pid = process-identity liveness"},{cmd:"digest",name:"digest",args:"[--writes] [--since <days>]",desc:"What Wyrm learned, queued, and refused: the offline write-receipt report"},{cmd:"bridge",name:"bridge",args:"<init|status|run>",desc:"The substrate flow: remember/render/reverse lanes from one receipted config"},{cmd:"forget",name:"forget",args:"--match|--dataset|--older-than",desc:"Erase ingested third-party data (dry run unless --yes)"},{cmd:"metabolize",name:"metabolize",args:"[--dry-run]",desc:"Memory metabolism: supersede exact dupes, queue near-dup candidates, decay stale auto-captures"},{cmd:"entities",name:"entities",args:"<backfill|stats>",desc:"Populate the knowledge graph from project memory, or count it"},{cmd:"render",name:"render",args:"[--client <list>] [--brief]",desc:"Compile DB \u2192 MEMORY.md + topic files (zero-MCP-token memory)"},{cmd:"reverse-bridge",name:"reverse-bridge",args:"[--path <dir>] [--dry-run]",desc:"Queue edits made to rendered memory files for review"},{cmd:"import",name:"import git",args:"",desc:"Import git log history to review queue"},{cmd:"import",name:"import rules",args:"<path>",desc:"Import .cursorrules / copilot-instructions file"},{cmd:"import",name:"import --from",args:"<source> <file.json>",desc:"Migrate a mem0, zep, supermemory or letta export into the review queue"},{cmd:"harvest",name:"harvest",args:"[--project <p>] [--dry-run]",desc:"Queue memory candidates found in project docs and git history"},{cmd:"stats",name:"stats",args:"",desc:"Show database statistics"},{cmd:"review",name:"review",args:"[--approve-all] [--auto on|off]",desc:"Activate queued memories (they are invisible to recall until you do)"},{cmd:"sync",name:"sync export",args:"--out <path>",desc:"Export encrypted DB snapshot"},{cmd:"sync",name:"sync import",args:"--from <path>",desc:"Restore from encrypted snapshot (backs up first)"},{cmd:"sync",name:"sync preview",args:"--from <path>",desc:"Preview snapshot stats without restoring"},{cmd:"prune",name:"prune",args:"[--project <name>]",desc:"Prune stale low-confidence artifacts (dry-run by default)"},{cmd:"cloud",name:"cloud",args:"<login|sync|export|\u2026>",desc:"Cloud backup & multi-device sync (Pro license)"},{cmd:"grove",name:"grove",args:"<status|policy>",desc:"Per-project sync lanes (private|cloud|team) + leak audit"},{cmd:"visibility",name:"visibility",args:"<kind>:<id> <level>",desc:"Promote/demote a truth|mem|quest: cross-project search + cloud egress (within|org|public)"},{cmd:"run",name:"run",args:"<start|join|end|status|prune>",desc:"Fleet-run lifecycle: start a run, join agents to it, end it, inspect it"},{cmd:"events",name:"events",args:"[since|publish] [--project]",desc:"Live-Memory event stream: read (since) or publish"},{cmd:"watch",name:"watch",args:"[--project <p>] [--interval <ms>]",desc:"Tail a project's Live-Memory event stream"},{cmd:"skill",name:"skill",args:"<list|backfill-content|export|share>",desc:"Discover bundled guides; store/sync SKILL.md content"},{cmd:"serve",name:"serve",args:"[--ui] [--port <n>]",desc:"Start the Wyrm HTTP server and print the dashboard URL (--ui also opens it)"},{cmd:"ui",name:"ui",args:"",desc:"Start the HTTP server and open the dashboard (alias: dashboard)"},{cmd:"setup",name:"setup",args:"[--check|--encrypt|\u2026]",desc:"Auto-configure AI clients (wyrm-setup); --encrypt for at-rest crypto"},{cmd:"guard",name:"guard",args:"[--remove|--status]",desc:"Failure-firewall PreToolUse hooks for Claude Code (wyrm-guard)"},{cmd:"memo",name:"memo",args:"[--remove|--status|--report]",desc:"Token firewall: read-memo hooks for Claude Code (wyrm-memo), observe by default"},{cmd:"statusline",name:"statusline",args:"[--remove]",desc:"Install or remove the Wyrm statusline in Claude Code"},{cmd:"embed",name:"embed",args:"[--remove|--status] [--all]",desc:"Make Wyrm first-priority memory in client instruction files, plus hooks"},{cmd:"vault",name:"vault",args:"<set|get|list|rm|exec|\u2026>",desc:"Local encrypted secret store; exec hands a secret to a command as an env var"},{cmd:"connector",name:"connector",args:"<list|add|sync>",desc:"Pull an external message source (a bridge) into the data lake"},{cmd:"intro",name:"intro",args:"",desc:"What Wyrm is and how to use it"},{cmd:"license",name:"license",args:"",desc:"Show license status & features"},{cmd:"login",name:"login",args:"",desc:"Sign in (free account) and activate; required on official builds"},{cmd:"activate",name:"activate",args:"<key|path>",desc:"Activate a license (JSON arg, file path, or stdin)"},{cmd:"maintenance",name:"maintenance",args:"[--vacuum]",desc:"Archive/prune/sweep/checkpoint the database"},{cmd:"index",name:"index",args:"<setup|rebuild|status>",desc:"Vector search: verify provider, reindex, stats"},{cmd:"vectors",name:"vectors",args:"<download|status>",desc:"Bundled local embedding model (default vector tier)"},{cmd:"doctor",name:"doctor",args:"",desc:"Health check that refuses to flatter: reports anything silently degraded"},{cmd:"report",name:"report",args:"",desc:"Shareable redacted diagnostic for support"},{cmd:"metrics",name:"metrics",args:"<snapshot|trend|show>",desc:"Effectiveness + quality over time, the flight recorder (trend flags drift)"},{cmd:"failure",name:"failure",args:"<list|resolve>",desc:"Failure firewall: list unresolved patterns, resolve a fixed one"},{cmd:"recall",name:"recall --set",args:"[--mode M] [--run <id>]",desc:"Negotiate a run's recall policy: mute/veto ids merge, --mode replaces"},{cmd:"recall",name:"recall --propose",args:"<query>",desc:"Review buckets (prescriptions/firewall/truths) BEFORE negotiating --set"},{cmd:"project",name:"project",args:"<add|list>",desc:"Register a project without needing a session start"},{cmd:"update",name:"update",args:"[--check]",desc:"Check for / install the latest wyrm-mcp into the install that is running"},{cmd:"upgrade",name:"upgrade",args:"",desc:"Guided upgrade to the max-recall tier (hosted NIM)"},{cmd:"prompt",name:"prompt",args:"<inject|migrate>",desc:"Inject/refresh the session-prime block in client files"},{cmd:"hours",name:"hours",args:"report --from --to",desc:"Hours report derived from session history"},{cmd:"invoice",name:"invoice",args:"generate --client \u2026",desc:"Markdown invoice from the hours ledger"},{cmd:"agent",name:"agent",args:"<init|status|stop|restart>",desc:"Background agent daemon (goal loop)"},{cmd:"feedback",name:"feedback",args:"[--bug|--idea|--question]",desc:"Send feedback or report a bug (opens a prefilled GitHub report)"}],Pe={dashboard:"ui",connectors:"connector"},we=new Set([...he.map(c=>c.cmd),...Object.keys(Pe),"version","help"]),go={search:["--project <name> scope to one project (a name that matches none is an error)","--type <t> all|memories|sessions|quests|data"],recall:["--project <name> scope a query to one project","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]"],ls:["--type <t> memories|truths|quests|all","--limit <N> default 20","--project <name>"],capture:["--project <name> default: the project for this directory (a git repo is enrolled on first use)","--mode <m> auto|quest|truth|memory"],review:["--approve-all approve every queued operator or agent memory","--auto on|off|status let new writes skip the queue; a bare --auto shows the status","--project <name> review one project"],digest:["--since <days> default 1","--json one JSON line"],forget:["--match <text> rows whose content contains the text","--dataset <category> rows from one ingest source","--older-than <days>","--yes erase (dry run otherwise)","Covers the ingested data lake only, not memories."],prune:["--project <name> | --path <dir>","--min-confidence <0-1> default 0.3","--older-than <days> default 90","--no-dry-run [--yes] delete (asks you to type CONFIRM unless --yes)"],session:["log [--path <dir>] [--run <id>] [--objectives <t>] [--completed <t>] [--issues <t>] [--commits <t>] [--notes <t>]"],presence:["announce --agent <id> [--kind <kind>] [--project <name>|--path <dir>] [--quest <n>] [--pid <n>|--auto-pid] [--ttl <sec>] [--role <r>]","list","release --agent <id>"],events:["since [--project <p>] [--cursor N] [--limit N]","publish <kind> --project <p> [--actor A] [--ref-table T --ref-id ID]"],run:["start [--orchestrator NAME] [--agent ID] [--parent RUNID]","join --run RUNID --agent ID [--role ROLE]","end --run RUNID [--status completed|failed|abandoned]","status --run RUNID","prune [--older-than <days>] [--dry-run]"," tidy the Claude Code hook's session map (~/.wyrm/auto-runs.json): drop mappings whose run has ended"," or that have been idle past <days> (default 7); --dry-run lists them and changes nothing"],grove:["status","policy <project|id> <private|cloud|team>"],vault:["set <name> read the secret from stdin, never argv (alias: put)","get <name> | list | rm <name> | info","exec <name> [--as ENV_VAR] -- <command...>","setup | secure [--backend keychain|passphrase] [--no-rotate] | import-npm","WYRM_VAULT_WAIT_SECONDS how long a non-interactive call waits for a locked keyring (default 90, 0 = no wait)"],connector:["list","add --name <n> --url <bridge-url> --workspace <w> [--allowlist a,b] [--token T] [--disabled]","sync [<name>]"],serve:["--port <n> port (else WYRM_PORT, alias WYRM_HTTP_PORT; default 3333)","--ui enable localhost dashboard access and open the browser"],ui:["--port <n> port (else WYRM_PORT, alias WYRM_HTTP_PORT; default 3333)"],update:["--check report only","--force reinstall even when up to date","Installs into the npm prefix this wyrm runs from (npm install -g --prefix <prefix>)."],agent:["init [--interval N] [--max-steps N] [--project <path>] [--verbose]","status [--log]","stop [--grace <ms>]","restart"],hours:["report --from YYYY-MM-DD --to YYYY-MM-DD [--project <name>] [--session-hours H] [--json]"],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>]']};function yo(c){const l=c.args?`${c.name} ${c.args}`:c.name,o=" ".repeat(Math.max(2,36-l.length));return` ${y.cyan(c.name)}${c.args?` ${c.args}`:""}${o}${c.desc}`}function Ae(c){const l=Pe[c]??c,o=he.filter(n=>n.cmd===l);console.log(y.bold("Usage:"));for(const n of o)console.log(` wyrm ${n.name}${n.args?` ${n.args}`:""}`),console.log(` ${y.dim(n.desc)}`);const i=go[l];if(i&&i.length>0){console.log(`
|
|
122
|
+
${y.bold("Details:")}`);for(const n of i)console.log(` ${n}`)}console.log(y.dim(`
|
|
123
|
+
Global options and every command: wyrm --help`))}const ho=new Set(["index","vectors","setup"]);function wo(c,l){if(!we.has(c)||ho.has(c)||c==="help"||c==="version")return!1;const o=l.indexOf("--"),i=o===-1?l:l.slice(0,o);return i.includes("--help")||i.includes("-h")}function bo(){console.log(`
|
|
124
|
+
${V.brightMagenta}\u{F115D} Wyrm CLI v${H().version??"unknown"}${V.reset}
|
|
125
|
+
${V.dim}Persistent AI Memory System${V.reset}
|
|
126
|
+
|
|
127
|
+
${y.bold("Usage:")} wyrm <command> [options] ${y.dim("wyrm <command> --help shows one command")}
|
|
128
|
+
|
|
129
|
+
${y.bold("Commands:")}
|
|
130
|
+
${he.map(yo).join(`
|
|
131
|
+
`)}
|
|
132
|
+
|
|
133
|
+
${y.bold("Options:")}
|
|
177
134
|
--project <name> Filter or associate with a specific project
|
|
178
135
|
--type <type> Filter type (memories|truths|quests|data|all)
|
|
179
136
|
--limit <N> Limit number of results (default: 20)
|
|
@@ -188,29 +145,35 @@ ${p.bold("Options:")}
|
|
|
188
145
|
--session <id> Rehydrate a specific session instead of the latest
|
|
189
146
|
--max-chars <N> Cap the rehydrate brief length (default: 6000)
|
|
190
147
|
--json Rehydrate: print {brief, attached} as one JSON line (implies --quiet)
|
|
191
|
-
--help, -h Show this help
|
|
148
|
+
--help, -h Show this help (after a command: that command's usage)
|
|
192
149
|
--version, -v Print the installed version
|
|
193
150
|
|
|
194
|
-
${
|
|
151
|
+
${y.bold("Environment:")}
|
|
195
152
|
WYRM_DB_PATH Override database path (default: ~/.wyrm/wyrm.db)
|
|
196
153
|
WYRM_SYNC_PASSPHRASE Passphrase for encrypted sync (or prompted interactively)
|
|
154
|
+
WYRM_LOG_LEVEL debug|info|warn|error (the CLI defaults to warn)
|
|
155
|
+
WYRM_LOG_DIR Directory for wyrm.log (default: ~/.wyrm/logs)
|
|
156
|
+
WYRM_PORT HTTP port for serve and ui (default: 3333; WYRM_HTTP_PORT is an alias)
|
|
157
|
+
WYRM_VAULT_WAIT_SECONDS Non-interactive wait for a locked keyring (default: 90; 0 disables)
|
|
158
|
+
NO_COLOR, FORCE_COLOR Turn colour off or on (default: on only when output is a terminal)
|
|
197
159
|
|
|
198
|
-
${
|
|
160
|
+
${y.bold("Examples:")}
|
|
199
161
|
wyrm search "authentication bug"
|
|
162
|
+
wyrm recall "why did we pick SQLite" --project MyApp
|
|
200
163
|
wyrm ls --type memories --project MyApp
|
|
201
164
|
wyrm capture "TODO: refactor the auth module" --project MyApp
|
|
202
165
|
wyrm sync export --out ~/wyrm-backup.wyrm
|
|
203
166
|
wyrm sync preview --from ~/wyrm-backup.wyrm
|
|
204
167
|
wyrm prune --project MyApp --min-confidence 0.2 --older-than 30
|
|
205
|
-
`)}const[,,V,...E]=process.argv;process.env.WYRM_LOG_LEVEL||(process.env.WYRM_LOG_LEVEL="warn");function Ne(m){const c=m.ref_table?`${m.ref_table}${m.ref_id?"#"+m.ref_id:""}`:"",s=new Date(m.created_at).toLocaleTimeString();return`#${m.cursor} ${m.kind.padEnd(15)} ${c.padEnd(16)} ${st(m.actor)} ${s}`}async function eo(m){const{positional:c,flags:s}=x(m),i=c[0]||"since",r=C();try{if(!r.liveMemoryEnabled()){g("Live Memory is disabled (set WYRM_LIVE_MEMORY=1)."),process.exitCode=1;return}const e=(typeof s.project=="string"?s.project:"")||process.cwd(),o=r.getProject(e)??r.getProjectByName(e);if(!o){g(`Project not found: ${e}`),process.exitCode=1;return}if(i==="publish"){const t=c[1]||(typeof s.kind=="string"?s.kind:"");if(!t){g("usage: wyrm events publish <kind> --project <p> [--actor A] [--ref-table T --ref-id ID]"),process.exitCode=1;return}r.publishEvent({projectId:o.id,kind:t,refTable:typeof s["ref-table"]=="string"?s["ref-table"]:void 0,refId:typeof s["ref-id"]=="string"?s["ref-id"]:void 0,actor:typeof s.actor=="string"?s.actor:void 0}),k(`Event published (${t}) to ${o.name}`);return}if(i==="since"){const t=O(s.cursor,0),n=O(s.limit,50),d=r.eventsSince(o.id,t,n);for(const a of d)console.log(Ne(a));R(`${d.length} event(s) for '${o.name}' since cursor ${t}`);return}g("usage: wyrm events <publish|since> ..."),process.exitCode=1}finally{r.close()}}async function to(m){const{flags:c}=x(m),s=C();if(!s.liveMemoryEnabled()){g("Live Memory is disabled (set WYRM_LIVE_MEMORY=1)."),s.close(),process.exitCode=1;return}const i=(typeof c.project=="string"?c.project:"")||process.cwd(),r=s.getProject(i)??N(s,i);if(!r){g(`Project not found: ${i}`),s.close(),process.exitCode=1;return}const e=Math.max(250,O(c.interval,1e3));let o=O(c.since,s.subscribeEvents(r.id,1).cursor);R(`Watching '${r.name}' (cursor ${o}, every ${e}ms) \u2014 Ctrl-C to stop`);const t=()=>{try{for(const a of s.eventsSince(r.id,o,200))o=a.cursor,console.log(Ne(a))}catch{}};t();const n=setInterval(t,e),d=()=>{clearInterval(n);try{s.close()}catch{}process.exit(0)};process.on("SIGINT",d),process.on("SIGTERM",d)}async function oo(m){const{flags:c}=x(m),{embedAll:s,removeAll:i,statusAll:r}=await import("./priority-embed.js"),e={projectDir:typeof c.project=="string"?c.project:void 0,allClients:c.all===!0},o=t=>console.log(` ${String(t.result??t.status).padEnd(9)} [${t.scope}] ${t.file}`);if(c.status){R("Wyrm priority embedding \u2014 status"),r(e).forEach(o);return}if(c.remove){R("Wyrm priority embedding \u2014 removed"),i(e).forEach(o);return}R("Wyrm is now FIRST-PRIORITY memory"),s(e).forEach(o);try{const{installClaudeCodeHooks:t,installClaudeStatusline:n}=await import("./autoconfig.js");t()?k("Proactive hooks installed (SessionStart rehydrate + capture + tool-trace)."):console.log(" (Claude Code not detected \u2014 skipped hook install.)");const a=n();a&&k(`Buddy statusline: ${a.message}`)}catch{}k("Wyrm will now be read first, primed proactively, and shown in the TUI at all times.")}async function so(m){const{flags:c}=x(m),{harvestProjects:s}=await import("./harvest.js"),{MemoryArtifacts:i}=await import("./memory-artifacts.js"),{escapeLikePattern:r}=await import("./auto-capture.js"),e=C();try{const o=e.getDatabase(),t=new i(o),n={existsBySig:(w,b)=>!!o.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(w,"%"+r(b)+"%"),addCandidate:(w,b)=>t.add(w,{kind:b.kind,problem:b.text,tags:[...b.tags,b.sig],confidence:b.confidence,needsReview:1,createdBy:"harvest"})},d=typeof c.project=="string"?c.project:void 0;let a;if(d){const w=e.getProject(d)??e.getProjectByName(d);if(!w){g(`Project not found: ${d}`),process.exitCode=1;return}a=[{id:w.id,name:w.name,path:w.path}]}else a=e.getAllProjects(500).map(w=>({id:w.id,name:w.name,path:w.path}));const l=c["dry-run"]===!0||c.dry===!0,u=c.code===!0||c["include-code"]===!0,{reports:f,totalAdded:h,totalSkipped:y}=s(n,a,{dryRun:l,gitLimit:O(c.limit,30),includeCode:u});R(`Harvest ${l?"(dry run) ":""}\u2014 ${h} candidate(s), ${y} already present (${a.length} project(s))`);for(const w of f.filter(b=>b.added>0).sort((b,$)=>$.added-b.added).slice(0,25))console.log(` +${String(w.added).padStart(3)} (skip ${w.skipped}) ${w.project}`);if(u&&!l){const{SymbolGraph:w}=await import("./symbols.js"),b=new w(o);let $=0,v=0;for(const S of a)try{const _=b.indexProject(S.id,S.path);$+=_.symbols,v+=_.files}catch{}console.log(` \u{1F4D0} Indexed ${$} code symbols (${v} files) \u2192 searchable via 'wyrm search'`)}!l&&h>0&&k("Review with: wyrm review")}finally{e.close()}}async function ro(m){const c=await import("./vault.js"),[s,...i]=m;try{switch(s){case"set":{const r=i[0];if(!r){g("usage: wyrm vault set <name> (the secret is read from STDIN, never argv)"),process.exitCode=1;return}if(process.stdin.isTTY){g(`pipe the secret in, e.g.: printf %s "$TOKEN" | wyrm vault set ${r}`),process.exitCode=1;return}const o=(await import("node:fs")).readFileSync(0,"utf8").replace(/\r?\n$/,"");if(!o){g("empty secret on stdin"),process.exitCode=1;return}c.vaultSet(r,o),k(`Stored "${r}" (AES-256-GCM). Use it without exposing it: wyrm vault exec ${r} -- <command>`);break}case"get":{const r=i[0];if(!r){g("usage: wyrm vault get <name>"),process.exitCode=1;return}const e=c.vaultGet(r);if(e===void 0){g(`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}R(`Vault \u2014 ${r.length} secret(s)`);for(const e of r)console.log(" \u2022 "+e);break}case"rm":case"remove":case"delete":{const r=i[0];if(!r){g("usage: wyrm vault rm <name>"),process.exitCode=1;return}k(c.vaultRemove(r)?`Removed "${r}"`:`(no secret named "${r}")`);break}case"exec":{const r=i[0],e=i.indexOf("--");if(!r||e===-1||e+1>=i.length){g("usage: wyrm vault exec <name> [--as ENVVAR] -- <command...>"),process.exitCode=1;return}const o=i.slice(1,e),t=o.indexOf("--as"),n=t>=0?o[t+1]:r.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),d=i.slice(e+1),a=c.vaultGet(r);if(a===void 0){g(`no secret named "${r}"`),process.exitCode=1;return}const l=re(d[0],d.slice(1),{stdio:"inherit",env:{...process.env,[n]:a}});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)){g("~/.npmrc not found"),process.exitCode=1;return}const n=r.readFileSync(t,"utf8").match(/\/\/registry\.npmjs\.org\/:_authToken=(.+)/);if(!n){g("no npm authToken found in ~/.npmrc"),process.exitCode=1;return}c.vaultSet("npm-token",n[1].trim()),k('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)k(`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){g("No OS keychain on this host. Set WYRM_VAULT_PASSPHRASE, then re-run: wyrm vault setup"),process.exitCode=1;return}const o=c.vaultSecure({backend:e});k(`Vault secured: ${o.from} \u2192 ${o.to}${o.rotated?" (key rotated)":""}.`),o.keyfileShredded&&console.log(" plaintext vault.key: shredded \u2714"),o.backup&&console.log(` ciphertext backup: ${o.backup} (delete once confirmed)`)}R("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=i.indexOf("--backend"),e=r>=0?i[r+1]:"keychain";if(e!=="keychain"&&e!=="passphrase"){g("usage: wyrm vault secure [--backend keychain|passphrase] [--no-rotate]"),process.exitCode=1;return}if(e==="passphrase"&&!process.env.WYRM_VAULT_PASSPHRASE){g("set WYRM_VAULT_PASSPHRASE before: wyrm vault secure --backend passphrase"),process.exitCode=1;return}const o=!i.includes("--no-rotate"),t=c.vaultSecure({backend:e,rotate:o});k(`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();R("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:g("usage: wyrm vault <setup|set|get|list|rm|exec|import-npm|secure|info>"),process.exitCode=1}}catch(r){g(`vault: ${r.message}`),process.exitCode=1}}function no(){const m=te(se(import.meta.url)),s=[F(m,"..","skills"),F(m,"..","..","skills")].find(r=>q(r));if(!s)return[];const i=[];for(const r of Ue(s,{withFileTypes:!0})){if(!r.isDirectory())continue;const e=F(s,r.name,"SKILL.md");if(!q(e))continue;let o=r.name,t="";try{const n=K(e,"utf8"),d=n.match(/^name:\s*(.+)$/m);if(d&&(o=d[1].trim()),/^description:\s*[|>]/m.test(n))t=((n.split(/^description:.*$/m)[1]??"").split(`
|
|
206
|
-
`).find(
|
|
168
|
+
`)}const[,,L,..._]=process.argv;ct("warn");function Le(c){const l=c.ref_table?`${c.ref_table}${c.ref_id?"#"+c.ref_id:""}`:"",o=new Date(c.created_at).toLocaleTimeString();return`#${c.cursor} ${c.kind.padEnd(15)} ${l.padEnd(16)} ${gt(c.actor)} ${o}`}async function vo(c){const{positional:l,flags:o}=j(c),i=l[0]||"since",n=C();try{if(!n.liveMemoryEnabled()){f("Live Memory is disabled (set WYRM_LIVE_MEMORY=1)."),process.exitCode=1;return}const s=(typeof o.project=="string"?o.project:"")||process.cwd(),e=n.getProject(s)??n.getProjectByName(s);if(!e){f(`Project not found: ${s}`),process.exitCode=1;return}if(i==="publish"){const t=l[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:e.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}),k(`Event published (${t}) to ${e.name}`);return}if(i==="since"){const t=A(o.cursor,0),r=A(o.limit,50),u=n.eventsSince(e.id,t,r);for(const a of u)console.log(Le(a));S(`${u.length} event(s) for '${e.name}' since cursor ${t}`);return}f("usage: wyrm events <publish|since> ..."),process.exitCode=1}finally{n.close()}}async function $o(c){const{flags:l}=j(c),o=C();if(!o.liveMemoryEnabled()){f("Live Memory is disabled (set WYRM_LIVE_MEMORY=1)."),o.close(),process.exitCode=1;return}const i=(typeof l.project=="string"?l.project:"")||process.cwd(),n=o.getProject(i)??M(o,i);if(!n){f(`Project not found: ${i}`),o.close(),process.exitCode=1;return}const s=Math.max(250,A(l.interval,1e3));let e=A(l.since,o.subscribeEvents(n.id,1).cursor);S(`Watching '${n.name}' (cursor ${e}, every ${s}ms) \u2014 Ctrl-C to stop`);const t=()=>{try{for(const a of o.eventsSince(n.id,e,200))e=a.cursor,console.log(Le(a))}catch{}};t();const r=setInterval(t,s),u=()=>{clearInterval(r);try{o.close()}catch{}process.exit(0)};process.on("SIGINT",u),process.on("SIGTERM",u)}async function ko(c){const{flags:l}=j(c),{embedAll:o,removeAll:i,statusAll:n}=await import("./priority-embed.js"),s={projectDir:typeof l.project=="string"?l.project:void 0,allClients:l.all===!0},e=t=>console.log(` ${String(t.result??t.status).padEnd(9)} [${t.scope}] ${t.file}`);if(l.status){S("Wyrm priority embedding \u2014 status"),n(s).forEach(e);return}if(l.remove){S("Wyrm priority embedding \u2014 removed"),i(s).forEach(e);return}S("Wyrm is now FIRST-PRIORITY memory"),o(s).forEach(e);try{const{installClaudeCodeHooks:t,installClaudeStatusline:r}=await import("./autoconfig.js");t()?k("Proactive hooks installed (SessionStart rehydrate + capture + tool-trace)."):console.log(" (Claude Code not detected \u2014 skipped hook install.)");const a=r();a&&k(`Buddy statusline: ${a.message}`)}catch{}k("Wyrm will now be read first, primed proactively, and shown in the TUI at all times.")}async function _o(c){const{flags:l}=j(c),{harvestProjects:o}=await import("./harvest.js"),{MemoryArtifacts:i}=await import("./memory-artifacts.js"),{escapeLikePattern:n}=await import("./auto-capture.js"),s=C();try{const e=s.getDatabase(),t=new i(e),r={existsBySig:(w,b)=>!!e.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(w,"%"+n(b)+"%"),addCandidate:(w,b)=>t.add(w,{kind:b.kind,problem:b.text,tags:[...b.tags,b.sig],confidence:b.confidence,needsReview:1,createdBy:"harvest"})},u=typeof l.project=="string"?l.project:void 0;let a;if(u){const w=s.getProject(u)??s.getProjectByName(u);if(!w){f(`Project not found: ${u}`),process.exitCode=1;return}a=[{id:w.id,name:w.name,path:w.path}]}else a=s.getAllProjects(500).map(w=>({id:w.id,name:w.name,path:w.path}));const d=l["dry-run"]===!0||l.dry===!0,p=l.code===!0||l["include-code"]===!0,{reports:m,totalAdded:h,totalSkipped:g}=o(r,a,{dryRun:d,gitLimit:A(l.limit,30),includeCode:p});S(`Harvest ${d?"(dry run) ":""}\u2014 ${h} candidate(s), ${g} already present (${a.length} project(s))`);for(const w of m.filter(b=>b.added>0).sort((b,$)=>$.added-b.added).slice(0,25))console.log(` +${String(w.added).padStart(3)} (skip ${w.skipped}) ${w.project}`);if(p&&!d){const{SymbolGraph:w}=await import("./symbols.js"),b=new w(e);let $=0,v=0;for(const R of a)try{const E=b.indexProject(R.id,R.path);$+=E.symbols,v+=E.files}catch{}console.log(` \u{1F4D0} Indexed ${$} code symbols (${v} files) \u2192 searchable via 'wyrm search'`)}!d&&h>0&&k("Review with: wyrm review")}finally{s.close()}}function We(c){c?c.action==="failed"?(f(c.message),process.exitCode=1):c.action==="skipped"&&!c.client.configured?ge(c.message):k(c.message):f("Claude Code not detected (~/.claude missing).")}async function Eo(c){const l=await import("./vault.js"),{withKeyringWait:o,vaultExec:i}=await import("./vault-exec.js"),[n,...s]=c;try{switch(n){case"set":case"put":{const e=s[0];if(!e){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 ${e}`),process.exitCode=1;return}const r=(await import("node:fs")).readFileSync(0,"utf8").replace(/\r?\n$/,"");if(!r){f("empty secret on stdin"),process.exitCode=1;return}await o(()=>l.vaultSet(e,r)),k(`Stored "${e}" (AES-256-GCM). Use it without exposing it: wyrm vault exec ${e} -- <command>`);break}case"get":{const e=s[0];if(!e){f("usage: wyrm vault get <name>"),process.exitCode=1;return}const t=await o(()=>l.vaultGet(e));if(t===void 0){f(`no secret named "${e}"`),process.exitCode=1;return}process.stdout.write(t);break}case"list":case"ls":{const e=await o(()=>l.vaultList());if(!e.length){console.log("(vault is empty)");break}S(`Vault \u2014 ${e.length} secret(s)`);for(const t of e)console.log(" \u2022 "+t);break}case"rm":case"remove":case"delete":{const e=s[0];if(!e){f("usage: wyrm vault rm <name>"),process.exitCode=1;return}const t=await o(()=>l.vaultRemove(e));k(t?`Removed "${e}"`:`(no secret named "${e}")`);break}case"exec":{await i(s);break}case"import-npm":{const e=await import("node:fs"),t=await import("node:os"),u=(await import("node:path")).join(t.homedir(),".npmrc");if(!e.existsSync(u)){f("~/.npmrc not found"),process.exitCode=1;return}const a=e.readFileSync(u,"utf8").match(/\/\/registry\.npmjs\.org\/:_authToken=(.+)/);if(!a){f("no npm authToken found in ~/.npmrc"),process.exitCode=1;return}l.vaultSet("npm-token",a[1].trim()),k('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 e=l.vaultPaths();if(e.secure)k(`Vault is already secure (backend: ${e.backend}, ${e.count} secret(s)).`);else{const t=e.keychainAvailable?"keychain":"passphrase";if(t==="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 r=l.vaultSecure({backend:t});k(`Vault secured: ${r.from} \u2192 ${r.to}${r.rotated?" (key rotated)":""}.`),r.keyfileShredded&&console.log(" plaintext vault.key: shredded \u2714"),r.backup&&console.log(` ciphertext backup: ${r.backup} (delete once confirmed)`)}S("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 e=s.indexOf("--backend"),t=e>=0?s[e+1]:"keychain";if(t!=="keychain"&&t!=="passphrase"){f("usage: wyrm vault secure [--backend keychain|passphrase] [--no-rotate]"),process.exitCode=1;return}if(t==="passphrase"&&!process.env.WYRM_VAULT_PASSPHRASE){f("set WYRM_VAULT_PASSPHRASE before: wyrm vault secure --backend passphrase"),process.exitCode=1;return}const r=!s.includes("--no-rotate"),u=l.vaultSecure({backend:t,rotate:r});k(`Vault secured: ${u.from} \u2192 ${u.to}${u.rotated?" (key rotated)":""}.`),console.log(` secrets re-encrypted: ${u.secrets}`),u.keyfileShredded&&console.log(" plaintext vault.key: shredded \u2714"),u.backup&&console.log(` ciphertext backup: ${u.backup} (delete once you've confirmed)`),console.log(t==="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 e=l.vaultPaths();S("Vault"),console.log(` backend: ${e.backend}`),console.log(` secrets: ${e.count}`),console.log(` store: ${e.vault} (0600)`),console.log(` key: ${e.backend==="keyfile"?e.key+" (0600)":e.backend==="keychain"?"(OS keychain \u2014 no key on disk)":"(derived from WYRM_VAULT_PASSPHRASE \u2014 no key on disk)"}`),console.log(` secure: ${e.secure?"yes \u2014 key is not a plaintext file beside the ciphertext":"NO \u2014 key sits beside ciphertext"}`),e.secure||console.log(e.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(e){f(`vault: ${e.message}`),process.exitCode=1}}function Ro(){const c=re(ee(import.meta.url)),o=[U(c,"..","skills"),U(c,"..","..","skills")].find(n=>q(n));if(!o)return[];const i=[];for(const n of Je(o,{withFileTypes:!0})){if(!n.isDirectory())continue;const s=U(o,n.name,"SKILL.md");if(!q(s))continue;let e=n.name,t="";try{const r=J(s,"utf8"),u=r.match(/^name:\s*(.+)$/m);if(u&&(e=u[1].trim()),/^description:\s*[|>]/m.test(r))t=((r.split(/^description:.*$/m)[1]??"").split(`
|
|
169
|
+
`).find(p=>p.trim())??"").trim();else{const a=r.match(/^description:\s*(.+)$/m);a&&(t=a[1].trim())}}catch{}i.push({name:e,description:t})}return i.sort((n,s)=>n.name.localeCompare(s.name))}async function Ue(c){const l=c[0];if(!l||l==="help"||l==="--help"){console.log(`Usage:
|
|
207
170
|
wyrm skill list show the bundled guides + your registered skills
|
|
208
171
|
wyrm skill backfill-content read every skill's SKILL.md into the registry (idempotent)
|
|
209
172
|
wyrm skill export <targetDir> [--all] materialize SKILL.md files from stored content
|
|
210
|
-
wyrm skill share <name|--all|--tier T> [--public|--private] [--include-inactive] set cloud-sync visibility (single or bulk)`);return}if(
|
|
211
|
-
private = never replicates . cloud = your own cloud backup . team = federates to a team Wyrm`),a>0&&console.log(
|
|
212
|
-
! ${a} private grove(s) hold rows marked to leave. Re-private those rows or change the grove lane.`)),
|
|
173
|
+
wyrm skill share <name|--all|--tier T> [--public|--private] [--include-inactive] set cloud-sync visibility (single or bulk)`);return}if(l==="list"||l==="ls"){const i=Ro();if(S("Bundled skill guides (shipped in the box)"),i.length===0)console.log(y.yellow(" none found next to this install"));else{for(const s of i)console.log(` ${y.cyan(s.name)}`),s.description&&console.log(` ${y.dim(s.description)}`);console.log(y.dim("\n Read one: open its SKILL.md, or `wyrm skill export <dir>` to materialize all."))}const n=C();try{const s=n.listSkills(!0);if(S(`Registered skills in your memory (${s.length})`),s.length===0)console.log(y.dim(" none yet \u2014 register with wyrm_skill_register or author with wyrm_skill_create"));else{for(const e of s.slice(0,40))console.log(` ${y.cyan(e.name)}${e.tier?y.dim(" ["+e.tier+"]"):""}`);s.length>40&&console.log(y.dim(` \u2026 and ${s.length-40} more`))}}finally{n.close()}return}const o=C();try{if(l==="backfill-content"||l==="backfill"){S("Backfill SKILL.md content into the registry");const i=o.backfillSkillContent();k(`${i.filled} filled . ${i.unchanged} unchanged . ${i.missing} missing-file (of ${i.total} registered)`),i.missing>0&&console.log(y.yellow(` ${i.missing} skill(s) had no readable SKILL.md \u2014 re-run after restoring their files.`));return}if(l==="export"){const i=c[1];i||(f("Usage: wyrm skill export <targetDir> [--all]"),o.close(),process.exit(1));const n=c.includes("--all");S(`Export skills \u2192 ${i}`);const s=o.exportSkillContent(i,{includeInactive:n});k(`${s.written} SKILL.md written . ${s.skipped_no_content} skipped (no stored content) (of ${s.total} ${n?"total":"active"})`),s.skipped_no_content>0&&console.log(y.yellow(" Run `wyrm skill backfill-content` on the source machine to populate content first.")),s.collisions>0&&console.log(y.yellow(` ${s.collisions} slug collision(s) disambiguated with a name-hash suffix (distinct skills, same slug) \u2014 no content lost.`));return}if(l==="share"){const i=c.includes("--private")?"within":c.includes("--public")?"public":"org",n=c.includes("--include-inactive"),s=c.indexOf("--tier"),e=s>=0?c[s+1]:void 0;if(s>=0&&(!e||e.startsWith("--"))&&(f("Usage: wyrm skill share --tier <god|mega|atomic> [--public|--private] [--include-inactive]"),o.close(),process.exit(1)),c.includes("--all")||!!e){const a=o.setAllSkillsVisibility(i,{tier:e,includeInactive:n}),d=e?`tier '${e}'`:n?"all skills":"all active skills";k(`${a} skill(s) (${d}) visibility \u2192 '${i}'.`),console.log(i==="within"?" These skills will NOT egress on cloud sync (private).":` ${a} skills are now cloud-sync-eligible (they leave on the next \`wyrm cloud sync\`).`);return}const r=c[1];r||(f("Usage: wyrm skill share <name|--all|--tier <tier>> [--public|--private] [--include-inactive]"),o.close(),process.exit(1)),o.setSkillVisibility(r,i)||(f(`Skill not found: ${r}`),o.close(),process.exit(1)),k(`Skill "${r}" visibility \u2192 '${i}'.`),console.log(i==="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: ${l}`),process.exit(1)}finally{o.close()}}async function So(c){const l="Usage: wyrm visibility <truth|mem|quest>:<id> <within|org|public> (or: wyrm visibility <kind> <id> <level>)",o=/^([a-z]+):(\d+)$/i.exec(c[0]??""),[i,n,s]=o?[o[1],o[2],c[1]]:[c[0],c[1],c[2]],t=i?{truth:"truth",mem:"memory",memory:"memory",artifact:"memory",quest:"quest"}[i.toLowerCase()]:void 0,r=n&&/^\d+$/.test(n)?Number(n):NaN;if(!t||!Number.isInteger(r)||r<1||!s||!["within","org","public"].includes(s)){f(l),process.exitCode=1;return}const u=s,a=`${t==="memory"?"mem":t}:${r}`,d=C();try{const p=d.setRowVisibility(t,r,u),m=p.projectName?`grove "${p.projectName}", policy ${p.syncPolicy??"unset"}`:"no project";if(p.outcome==="not_found"){f(`${a} not found.`),process.exitCode=1;return}if(p.outcome==="refused_private_grove"){f(`Refused: ${a} belongs to a private grove (${m}). A private grove never replicates, and a promoted row inside one is what \`wyrm grove status\` reports as a leak.`),console.log(y.dim(` To publish it, change the grove's lane first: wyrm grove policy ${p.projectId} cloud`)),process.exitCode=1;return}if(p.outcome==="unchanged")k(`${a} is already '${u}' (${m}). Nothing changed.`);else{const{recordWrite:h}=await import("./receipts.js");h(d.getDatabase(),{tool:"wyrm visibility",outcome:"stored",refTable:t==="memory"?"mem":t,refId:r,reason:`cross_project_visibility ${p.previous} -> ${u} (operator, CLI)`,projectId:p.projectId??void 0}),k(`${a} visibility ${p.previous} -> '${u}' (${m}).`)}u==="within"?(console.log(" Hidden from other projects' constellation search, and no longer eligible to leave this machine."),p.previous&&p.previous!=="within"&&console.log(y.yellow(" This stops FUTURE sync only. A copy that already synced to the cloud is not recalled."))):p.egressEligible?console.log(" Surfaces in other projects' constellation search, and is now cloud-sync-eligible (it leaves on the next `wyrm cloud sync`)."):console.log(" Surfaces in other projects' constellation search. Not cloud-sync-eligible under its grove's policy.")}finally{d.close()}}async function Co(c){const l=c[0]??"status",o=C(),i=o.getDatabase();if(i.prepare("PRAGMA table_info(projects)").all().some(s=>s.name==="sync_policy")||(f("Grove sync policy is not on this database yet (upgrade Wyrm so migrations apply)."),o.close(),process.exit(1)),l==="status"||l==="ls"||l==="list"){S("Grove sync policy + leak audit");const s=i.prepare("SELECT id, name, sync_policy FROM projects ORDER BY id").all(),e=["ground_truths","memory_artifacts","quests","design_tokens","design_references"],t=["ground_truths","memory_artifacts","quests","sessions","decision_edges"],r=(d,p,m)=>{let h=0;for(const g of d)try{h+=i.prepare(`SELECT COUNT(*) AS n FROM ${g} WHERE project_id = ? AND ${m}`).get(p).n}catch{}return h},u=[];let a=0;for(const d of s){const p=r(e,d.id,"cross_project_visibility IN ('org','public')"),m=r(t,d.id,"is_shared = 1"),h=d.sync_policy==="private"&&p+m>0;h&&a++;const g=h?y.red(`LEAK: ${p} promoted + ${m} shared in a PRIVATE grove`):`${p} promoted / ${m} shared`;u.push([String(d.id),d.name,d.sync_policy,g])}console.log(P(["#","Grove","sync_policy","rows eligible to leave"],u)),console.log(`
|
|
174
|
+
private = never replicates . cloud = your own cloud backup . team = federates to a team Wyrm`),a>0&&console.log(y.red(`
|
|
175
|
+
! ${a} private grove(s) hold rows marked to leave. Re-private those rows or change the grove lane.`)),o.close();return}if(l==="policy"||l==="set"){const s=c[1],e=c[2];(!s||!["private","cloud","team"].includes(e))&&(f("Usage: wyrm grove policy <project|id> <private|cloud|team>"),o.close(),process.exit(1));let t=M(o,s);!t&&/^\d+$/.test(s)&&(t=i.prepare("SELECT id, name FROM projects WHERE id = ?").get(Number(s))),t||(f(`Grove not found: ${s}`),o.close(),process.exit(1)),i.prepare("UPDATE projects SET sync_policy = ? WHERE id = ?").run(e,t.id),k(`Grove "${t.name}" set to '${e}'.`),e!=="private"&&console.log(` Rows still only leave when also marked ${e==="team"?"is_shared (team)":"org/public (cloud)"}. The grove is the outer gate.`),o.close();return}f(`Unknown grove subcommand: ${l}`),console.log(`Usage:
|
|
213
176
|
wyrm grove status
|
|
214
|
-
wyrm grove policy <project|id> <private|cloud|team>`),
|
|
215
|
-
`),process.stderr.write(`Run ${w} started by ${
|
|
216
|
-
`);break}case"join":{const
|
|
177
|
+
wyrm grove policy <project|id> <private|cloud|team>`),o.close(),process.exit(1)}async function jo(c){const l=c[0],{flags:o}=j(c.slice(1)),{ulid:i}=await import("./ulid.js"),{createRun:n,setRunStatus:s,registerAgent:e,getRun:t,getAgents:r}=await import("./handlers/run.js"),{sanitizeActorId:u}=await import("./handlers/boundary.js"),a=m=>typeof m=="string"?u(m):null,d=C(),p=d.getDatabase();try{switch(l){case"start":{const m=(typeof o.orchestrator=="string"?o.orchestrator:"cli").slice(0,200),h=a(o.agent)??u(m)??"cli",g=a(o.parent);if(g&&!t(p,g)){f(`Parent run not found: ${g}`),process.exitCode=1;return}const w=i();n(p,w,g,m),e(p,w,h,"orchestrator"),process.stdout.write(w+`
|
|
178
|
+
`),process.stderr.write(`Run ${w} started by ${m}.
|
|
179
|
+
`);break}case"join":{const m=a(o.run),h=a(o.agent);if(!m||!h){f("Usage: wyrm run join --run <RUNID> --agent <ID> [--role <ROLE>]"),process.exitCode=1;return}if(!t(p,m)){f(`Run not found: ${m}`),process.exitCode=1;return}const g=typeof o.role=="string"?o.role.slice(0,200):null;e(p,m,h,g),k(`${h} joined run ${m}${g?` as ${g}`:""}.`);break}case"end":{const m=a(o.run);if(!m){f("Usage: wyrm run end --run <RUNID> [--status completed|failed|abandoned]"),process.exitCode=1;return}if(!t(p,m)){f(`Run not found: ${m}`),process.exitCode=1;return}const h=typeof o.status=="string"?o.status:"completed",w=["completed","failed","abandoned"].includes(h)?h:"completed";s(p,m,w),k(`Run ${m} ended (${w}).`);break}case"status":{const m=a(o.run);if(!m){f("Usage: wyrm run status --run <RUNID>"),process.exitCode=1;return}const h=t(p,m);if(!h){f(`Run not found: ${m}`),process.exitCode=1;return}const g=r(p,m);S(`Run ${h.run_id} [${h.status}]`),h.orchestrator&&console.log(y.bold("Orchestrator: ")+h.orchestrator),h.parent_run_id&&console.log(y.bold("Parent: ")+h.parent_run_id),console.log(y.bold("Created: ")+h.created_at),console.log(y.bold("Updated: ")+h.updated_at),g.length>0?console.log(P(["Agent","Role","Joined"],g.map(w=>[w.agent_id,w.role??"",w.joined_at]))):console.log(y.dim(" No agents registered."));break}case"prune":{const{autoRunsPath:m,pruneAutoRunsFile:h,AUTO_RUNS_MAX_AGE_DAYS:g}=await import("./auto-runs.js"),w=te(o["older-than"],g);if(w<0){f("--older-than takes a number of days, 0 or more"),process.exitCode=1;return}const b=o["dry-run"]===!0,$=m(),v=x=>t(p,x)?.status,R=h($,{now:Date.now(),maxAgeMs:w*864e5,dryRun:b,runStatus:v});if(R.outcome==="missing"){console.log(`No run map at ${$}; nothing to prune.`);break}if(R.outcome==="corrupt"){f(`${$} is not valid JSON; left as it is.`),process.exitCode=1;return}if(R.outcome==="locked"){f(`${$} is being written by another process (${$}.lock); try again.`),process.exitCode=1;return}k(`${b?"Would remove":"Removed"} ${R.removed.length} of ${R.total} mapping(s) in ${$}; ${R.total-R.removed.length} kept.`);for(const x of R.removed)console.log(` ${x.reason.padEnd(8)} ${x.session}${x.runId?` ${x.runId}`:""}`);const E=R.removed.filter(x=>x.runId&&v(x.runId)==="running").length;E>0&&console.log(y.dim(` ${E} of them ${E===1?"points at a run":"point at runs"} still marked running; close one with: wyrm run end --run RUNID --status abandoned`));break}default:f("Usage: wyrm run <start|join|end|status|prune> [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"),console.log(" wyrm run prune [--older-than DAYS] [--dry-run]"),process.exitCode=1;return}}finally{d.close()}}if(L==="--version"||L==="-v"||L==="version"){const c=H();console.log(`${c.name??"wyrm-mcp"} v${c.version??"unknown"}`)}else L==="help"&&_[0]&&we.has(_[0])?Ae(_[0]):!L||L==="--help"||L==="-h"||L==="help"?bo():wo(L,_)?L==="cloud"?import("./cloud/cli.js").then(({cmdCloud:c})=>c(["help"])):L==="skill"?Ue(["help"]):Ae(L):(vt(L,_),(async()=>{try{switch(L){case"search":await De(_);break;case"ls":await $t(_);break;case"show":await kt(_);break;case"capture":await _t(_);break;case"rehydrate":await Rt(_);break;case"session":await Tt(_);break;case"presence":await Nt(_);break;case"digest":await Et(_);break;case"bridge":await xt(_);break;case"metabolize":await Ct(_);break;case"forget":await St(_);break;case"entities":await jt(_);break;case"render":await Mt(_);break;case"reverse-bridge":await Dt(_);break;case"import":await It(_);break;case"stats":await Pt(_);break;case"review":await Lt(_);break;case"sync":await Wt(_);break;case"cloud":{const{cmdCloud:c}=await import("./cloud/cli.js");await c(_);break}case"grove":await Co(_);break;case"visibility":await So(_);break;case"run":await jo(_);break;case"skill":await Ue(_);break;case"prune":await Ut(_);break;case"license":await Yt();break;case"login":await qt();break;case"activate":await Ht(_);break;case"maintenance":await Vt(_);break;case"doctor":await zt(_);break;case"report":await Xt(_);break;case"metrics":await Bt(_);break;case"failure":await Zt(_);break;case"recall":await to(_);break;case"project":await oo(_);break;case"index":await so(_);break;case"vectors":await ro(_);break;case"update":await ao(_);break;case"upgrade":await io(_);break;case"prompt":await co(_);break;case"hours":await lo(_);break;case"invoice":await uo(_);break;case"agent":await po(_);break;case"feedback":await fo(_);break;case"setup":await mo(_);break;case"intro":{const{renderIntro:c}=await import("./visibility.js");console.log(c(H().version??"unknown"));break}case"events":await vo(_);break;case"watch":await $o(_);break;case"embed":await ko(_);break;case"harvest":await _o(_);break;case"vault":await Eo(_);break;case"connector":case"connectors":await Ft(_);break;case"statusline":{const{installClaudeStatusline:c,removeClaudeStatusline:l}=await import("./autoconfig.js"),o=_.includes("--remove")?l():c();o?k(o.message):f("Claude Code not detected (~/.claude missing).");break}case"guard":{const{installWyrmGuardHooks:c,removeWyrmGuardHooks:l,wyrmGuardHookStatus:o}=await import("./autoconfig.js");if(_.includes("--status")){const n=o();if(console.log(` settings: ${n.settingsPath}`),n.installed){k(`wyrm-guard hooks installed (${n.commands.length} entr${n.commands.length===1?"y":"ies"})`);for(const s of n.commands)console.log(y.dim(` ${s}`))}else console.log(y.yellow(" wyrm-guard hooks not installed \u2014 run: wyrm guard"));break}const i=_.includes("--remove")||_.includes("--uninstall")?l():c();We(i);break}case"memo":{const{installWyrmMemoHooks:c,removeWyrmMemoHooks:l,wyrmMemoHookStatus:o,getDefaultDbPath:i}=await import("./autoconfig.js");if(_.includes("--status")){const s=o();if(console.log(` settings: ${s.settingsPath}`),s.installed){k(`wyrm-memo hooks installed (${s.commands.length} entr${s.commands.length===1?"y":"ies"})`);for(const e of s.commands)console.log(y.dim(` ${e}`))}else console.log(y.yellow(" wyrm-memo hooks not installed \u2014 run: wyrm memo"));console.log(y.dim(` mode: ${(process.env.WYRM_MEMO_MODE??"observe").toLowerCase()} (WYRM_MEMO_MODE=off|observe|warn)`));break}if(_.includes("--report")){const{openDatabase:s}=await import("./storage/index.js"),{ReadMemos:e}=await import("./read-memo.js"),t=process.env.WYRM_DB_PATH??i(),r=s(t,{readonly:!0,fileMustExist:!0});try{const u=new e(r).summary(),a=r.prepare("SELECT path, hits, tokens_avoided, seen_count, last_seen FROM read_memos ORDER BY hits DESC, last_seen DESC LIMIT 10").all();k(`token firewall: ${u.memos} memo(s), ${u.hits} repeat read(s) seen, ~${u.tokensAvoided} tokens at stake`),console.log(y.dim(` mode: ${(process.env.WYRM_MEMO_MODE??"observe").toLowerCase()} \u2014 in observe mode nothing was withheld; the number is what warn mode would offer back`));for(const d of a)console.log(y.dim(` ${d.hits}x ~${d.tokens_avoided} tok seen ${d.seen_count}x ${d.last_seen} ${d.path}`))}finally{r.close()}break}const n=_.includes("--remove")||_.includes("--uninstall")?l():c();We(n);break}case"ui":case"dashboard":_.includes("--ui")||_.push("--ui");case"serve":{const c=_.includes("--ui");if(c){const{enableDevMode:t}=await import("./http-auth.js");t()}const{server:l,primeLicenseRevocations:o}=await import("./http-fast.js");o();const i=_.indexOf("--port"),n=i>=0?_[i+1]:void 0,s=parseInt(n||process.env.WYRM_PORT||process.env.WYRM_HTTP_PORT||"3333",10)||3333,e=process.env.WYRM_BIND_HOST||"127.0.0.1";l.listen(s,e,()=>{k(`Wyrm HTTP server running on ${e}:${s}`),process.env.WYRM_UI_READONLY==="1"&&console.log("\u{1F512} READ-ONLY mode: writes + off-box egress are blocked; safe to expose.");const t=`http://localhost:${s}/ui`;c||console.log(`Dashboard: ${t}`),c&&(console.log(`\u{1F5A5}\uFE0F Dashboard: ${t}`),import("child_process").then(({spawn:r})=>{const u=process.platform;try{const a=u==="darwin"?r("open",[t],{stdio:"ignore",detached:!0}):u==="win32"?r("cmd",["/c","start","",t],{stdio:"ignore",detached:!0}):r("xdg-open",[t],{stdio:"ignore",detached:!0});a.on("error",()=>{}),a.unref()}catch{}}).catch(()=>{}))});break}default:{const c=je(L,[...we]);f(`Unknown command: ${L}.${c.length?` Did you mean: ${c.join(", ")}?`:""}`),console.error(`Run ${y.cyan("wyrm --help")} for the list of commands.`),process.exitCode=1}}}catch(c){f(String(c)),process.exit(1)}})());
|