wyrm-mcp 8.2.0 → 8.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/wyrm-cli.js CHANGED
@@ -1,87 +1,88 @@
1
1
  #!/usr/bin/env node
2
- import{join as q,dirname as ne}from"path";import{homedir as Pe}from"os";import{existsSync as H,readFileSync as B,readdirSync as Ie}from"fs";import{fileURLToPath as re}from"url";import{spawnSync as z}from"child_process";import{createInterface as Q}from"readline";import{WyrmDB as Ne}from"./database.js";import{MemoryArtifacts as G}from"./memory-artifacts.js";import{GroundTruths as pe}from"./intelligence.js";import{Causality as ue}from"./causality.js";import{wireTruthAutoCascade as me}from"./truth-cascade.js";import{Rehydration as Me}from"./rehydration.js";import{makeRenderDeps as fe,buildRenderPlan as ie,renderToDisk as Oe,renderForClient as ge,detectClients as Ae,ALL_RENDER_CLIENTS as ce,ALL_CLIENT_MARKERS as Le}from"./render-target.js";import{classifyCapture as We}from"./capture.js";import{importFrom as Ue,IMPORT_SOURCES as ye}from"./importers.js";import{c as p,colors as N,formatTable as P,printSection as S,printSuccess as b,printError as f,icons as Y}from"./cli.js";import{loadConnectorConfigs as he,upsertConnectorConfig as qe,runConnector as Ye,runAllConnectors as Fe}from"./connectors/index.js";import{readActor as He}from"./attribution.js";function M(){try{const l=ne(re(import.meta.url));return JSON.parse(B(q(l,"..","package.json"),"utf-8"))}catch{return{}}}function D(l,a){const e=typeof l=="string"?parseInt(l,10):NaN;return Number.isFinite(e)?e:a}function Z(l,a){const e=typeof l=="string"?parseFloat(l):NaN;return Number.isFinite(e)?e:a}function Be(){return process.env.WYRM_DB_PATH??q(Pe(),".wyrm","wyrm.db")}function C(){return new Ne(Be())}function _(l){const a=[],e={};let i=0;for(;i<l.length;){const s=l[i];if(s.startsWith("--")){const t=s.slice(2),r=l[i+1];r&&!r.startsWith("--")?(e[t]=r,i+=2):(e[t]=!0,i++)}else a.push(s),i++}return{positional:a,flags:e}}function x(l,a){return a?l.getDatabase().prepare("SELECT * FROM projects WHERE LOWER(name) LIKE LOWER(?) LIMIT 1").get(`%${a}%`)??null:null}async function Ve(l){const{positional:a,flags:e}=_(l),i=a[0];i||(f("Usage: wyrm search <query> [--project <name>] [--type all|memories|truths|quests|data]"),process.exit(1));const s=C(),t=s.getDatabase(),r=e.type??"all",o=e.project,d=(o?x(s,o):null)?.id;S(`Search: "${i}"`);const c=[];if(r==="all"||r==="memories")try{const m=d?`AND m.project_id = ${d}`:"",g=t.prepare(`
2
+ import{join as F,dirname as re,resolve as Ie,basename as Pe}from"path";import{homedir as Ne}from"os";import{existsSync as q,readFileSync as V,readdirSync as Me}from"fs";import{fileURLToPath as ne}from"url";import{spawnSync as z}from"child_process";import{createInterface as Q}from"readline";import{WyrmDB as Oe}from"./database.js";import{MemoryArtifacts as G}from"./memory-artifacts.js";import{GroundTruths as pe}from"./intelligence.js";import{Causality as ue}from"./causality.js";import{wireTruthAutoCascade as me}from"./truth-cascade.js";import{Rehydration as Ae}from"./rehydration.js";import{makeRenderDeps as fe,buildRenderPlan as ie,renderToDisk as Le,renderForClient as ge,detectClients as We,ALL_RENDER_CLIENTS as ae,ALL_CLIENT_MARKERS as Ue}from"./render-target.js";import{classifyCapture as Fe}from"./capture.js";import{importFrom as qe,IMPORT_SOURCES as ye}from"./importers.js";import{c as d,colors as N,formatTable as D,printSection as k,printSuccess as b,printError as m,icons as Y}from"./cli.js";import{loadConnectorConfigs as he,upsertConnectorConfig as Ye,runConnector as He,runAllConnectors as Ve}from"./connectors/index.js";import{readActor as Be}from"./attribution.js";function M(){try{const l=re(ne(import.meta.url));return JSON.parse(V(F(l,"..","package.json"),"utf-8"))}catch{return{}}}function I(l,c){const t=typeof l=="string"?parseInt(l,10):NaN;return Number.isFinite(t)?t:c}function X(l,c){const t=typeof l=="string"?parseFloat(l):NaN;return Number.isFinite(t)?t:c}function Ke(){return process.env.WYRM_DB_PATH??F(Ne(),".wyrm","wyrm.db")}function j(){return new Oe(Ke())}function C(l){const c=[],t={};let i=0;for(;i<l.length;){const r=l[i];if(r.startsWith("--")){const e=r.slice(2),s=l[i+1];s&&!s.startsWith("--")?(t[e]=s,i+=2):(t[e]=!0,i++)}else c.push(r),i++}return{positional:c,flags:t}}function x(l,c){return c?l.getDatabase().prepare("SELECT * FROM projects WHERE LOWER(name) LIKE LOWER(?) LIMIT 1").get(`%${c}%`)??null:null}async function Ge(l){const{positional:c,flags:t}=C(l),i=c[0];i||(m("Usage: wyrm search <query> [--project <name>] [--type all|memories|truths|quests|data]"),process.exit(1));const r=j(),e=r.getDatabase(),s=t.type??"all",o=t.project,p=(o?x(r,o):null)?.id;k(`Search: "${i}"`);const a=[];if(s==="all"||s==="memories")try{const u=p?`AND m.project_id = ${p}`:"",g=e.prepare(`
3
3
  SELECT m.id, m.kind, m.problem, m.project_id FROM memory_artifacts m
4
4
  JOIN memory_artifacts_fts fts ON m.id = fts.rowid
5
- WHERE memory_artifacts_fts MATCH ? ${m}
5
+ WHERE memory_artifacts_fts MATCH ? ${u}
6
6
  LIMIT 20
7
- `).all(i);for(const u of g)c.push([`mem:${u.id}`,"memory",u.kind,u.problem.slice(0,80)])}catch{}if(r==="all"||r==="sessions")try{const m=d?`AND s.project_id = ${d}`:"",g=t.prepare(`
7
+ `).all(i);for(const f of g)a.push([`mem:${f.id}`,"memory",f.kind,f.problem.slice(0,80)])}catch{}if(s==="all"||s==="sessions")try{const u=p?`AND s.project_id = ${p}`:"",g=e.prepare(`
8
8
  SELECT s.id, s.objectives, s.project_id FROM sessions s
9
9
  JOIN sessions_fts fts ON s.id = fts.rowid
10
- WHERE sessions_fts MATCH ? ${m}
10
+ WHERE sessions_fts MATCH ? ${u}
11
11
  LIMIT 10
12
- `).all(i);for(const u of g)c.push([`session:${u.id}`,"session","",u.objectives.slice(0,80)])}catch{}if(r==="all"||r==="quests")try{const m=d?`AND q.project_id = ${d}`:"",g=t.prepare(`
12
+ `).all(i);for(const f of g)a.push([`session:${f.id}`,"session","",f.objectives.slice(0,80)])}catch{}if(s==="all"||s==="quests")try{const u=p?`AND q.project_id = ${p}`:"",g=e.prepare(`
13
13
  SELECT q.id, q.title, q.priority, q.project_id FROM quests q
14
14
  JOIN quests_fts fts ON q.id = fts.rowid
15
- WHERE quests_fts MATCH ? ${m}
15
+ WHERE quests_fts MATCH ? ${u}
16
16
  LIMIT 10
17
- `).all(i);for(const u of g)c.push([`quest:${u.id}`,"quest",u.priority,u.title.slice(0,80)])}catch{}if(r==="all"||r==="data")try{const m=d?`AND d.project_id = ${d}`:"",g=t.prepare(`
17
+ `).all(i);for(const f of g)a.push([`quest:${f.id}`,"quest",f.priority,f.title.slice(0,80)])}catch{}if(s==="all"||s==="data")try{const u=p?`AND d.project_id = ${p}`:"",g=e.prepare(`
18
18
  SELECT d.id, d.category, d.key, d.value FROM data_lake d
19
19
  JOIN data_lake_fts fts ON d.id = fts.rowid
20
- WHERE data_lake_fts MATCH ? ${m}
20
+ WHERE data_lake_fts MATCH ? ${u}
21
21
  LIMIT 10
22
- `).all(i);for(const u of g)c.push([`data:${u.id}`,"data",u.category,u.value.slice(0,80)])}catch{}if(s.close(),c.length===0){console.log(p.dim(` No results found for "${i}"`));return}console.log(P(["ID","Type","Subtype","Preview"],c)),console.log(p.dim(`
23
- ${c.length} result${c.length!==1?"s":""}`))}async function Ke(l){const{flags:a}=_(l),e=a.type??"all",i=D(a.limit,20),s=a.project,t=C(),r=t.getDatabase(),n=(s?x(t,s):null)?.id,d=n?`WHERE project_id = ${n}`:"",c=n?`AND project_id = ${n}`:"";if(S("Wyrm Memory"),e==="all"||e==="memories"){S("Memories");const m=r.prepare(`
22
+ `).all(i);for(const f of g)a.push([`data:${f.id}`,"data",f.category,f.value.slice(0,80)])}catch{}if(r.close(),a.length===0){console.log(d.dim(` No results found for "${i}"`));return}console.log(D(["ID","Type","Subtype","Preview"],a)),console.log(d.dim(`
23
+ ${a.length} result${a.length!==1?"s":""}`))}async function Je(l){const{flags:c}=C(l),t=c.type??"all",i=I(c.limit,20),r=c.project,e=j(),s=e.getDatabase(),n=(r?x(e,r):null)?.id,p=n?`WHERE project_id = ${n}`:"",a=n?`AND project_id = ${n}`:"";if(k("Wyrm Memory"),t==="all"||t==="memories"){k("Memories");const u=s.prepare(`
24
24
  SELECT id, kind, confidence, problem, tags FROM memory_artifacts
25
- ${d}
25
+ ${p}
26
26
  ORDER BY created_at DESC LIMIT ?
27
- `).all(i);if(m.length>0){const g=m.map(u=>[`mem:${u.id}`,u.kind,`${Math.round(u.confidence*100)}%`,u.problem.slice(0,60),u.tags?.slice(0,30)??""]);console.log(P(["ID","Kind","Conf","Preview","Tags"],g))}else console.log(p.dim(" No memories yet."))}if(e==="all"||e==="truths"){S("Ground Truths");const m=r.prepare(`
27
+ `).all(i);if(u.length>0){const g=u.map(f=>[`mem:${f.id}`,f.kind,`${Math.round(f.confidence*100)}%`,f.problem.slice(0,60),f.tags?.slice(0,30)??""]);console.log(D(["ID","Kind","Conf","Preview","Tags"],g))}else console.log(d.dim(" No memories yet."))}if(t==="all"||t==="truths"){k("Ground Truths");const u=s.prepare(`
28
28
  SELECT id, category, key, value FROM ground_truths
29
- WHERE is_current = 1 ${c}
29
+ WHERE is_current = 1 ${a}
30
30
  ORDER BY created_at DESC LIMIT ?
31
- `).all(i);if(m.length>0){const g=m.map(u=>[`truth:${u.id}`,u.category,u.key.slice(0,30),u.value.slice(0,60)]);console.log(P(["ID","Category","Key","Value"],g))}else console.log(p.dim(" No ground truths yet."))}if(e==="all"||e==="quests"){S("Quests");const m=r.prepare(`
31
+ `).all(i);if(u.length>0){const g=u.map(f=>[`truth:${f.id}`,f.category,f.key.slice(0,30),f.value.slice(0,60)]);console.log(D(["ID","Category","Key","Value"],g))}else console.log(d.dim(" No ground truths yet."))}if(t==="all"||t==="quests"){k("Quests");const u=s.prepare(`
32
32
  SELECT id, priority, title, status FROM quests
33
- ${d}
33
+ ${p}
34
34
  ORDER BY created_at DESC LIMIT ?
35
- `).all(i);if(m.length>0){const g=m.map(u=>[`quest:${u.id}`,u.priority,u.title.slice(0,60),u.status]);console.log(P(["ID","Priority","Title","Status"],g))}else console.log(p.dim(" No quests yet."))}t.close()}async function Ge(l){const{positional:a}=_(l),e=a[0];e||(f("Usage: wyrm show <typed-id> (e.g. mem:41, quest:12, truth:7, data:5, session:3)"),process.exit(1));const[i,s]=e.split(":"),t=parseInt(s??"",10);(!i||isNaN(t))&&(f(`Invalid typed ID: ${e}. Format: type:number (e.g. mem:41)`),process.exit(1));const r=C(),o=r.getDatabase();switch(S(`${e}`),i){case"mem":{const n=o.prepare("SELECT * FROM memory_artifacts WHERE id = ?").get(t);if(!n){f(`Memory artifact ${t} not found`);break}console.log(p.bold("Kind: ")+n.kind),console.log(p.bold("Confidence:")+` ${Math.round(n.confidence*100)}%`),console.log(p.bold("Problem: ")+`
36
- `+n.problem),n.validated_fix&&console.log(p.bold("Solution: ")+`
37
- `+n.validated_fix),n.why_it_worked&&console.log(p.bold("Why: ")+`
38
- `+n.why_it_worked),n.tags&&console.log(p.bold("Tags: ")+n.tags),console.log(p.bold("Created: ")+n.created_at);break}case"quest":{const n=o.prepare("SELECT * FROM quests WHERE id = ?").get(t);if(!n){f(`Quest ${t} not found`);break}console.log(p.bold("Title: ")+n.title),console.log(p.bold("Priority: ")+n.priority),console.log(p.bold("Status: ")+n.status),n.description&&console.log(p.bold("Desc: ")+`
39
- `+n.description),n.tags&&console.log(p.bold("Tags: ")+n.tags),console.log(p.bold("Created: ")+n.created_at);break}case"truth":{const n=o.prepare("SELECT * FROM ground_truths WHERE id = ?").get(t);if(!n){f(`Ground truth ${t} not found`);break}console.log(p.bold("Category: ")+n.category),console.log(p.bold("Key: ")+n.key),console.log(p.bold("Value: ")+`
40
- `+n.value),n.rationale&&console.log(p.bold("Rationale:")+`
41
- `+n.rationale),console.log(p.bold("Active: ")+(n.is_current?"Yes":"No (superseded)")),console.log(p.bold("Created: ")+n.created_at);break}case"data":{const n=o.prepare("SELECT * FROM data_lake WHERE id = ?").get(t);if(!n){f(`Data point ${t} not found`);break}console.log(p.bold("Category: ")+n.category),console.log(p.bold("Key: ")+n.key),console.log(p.bold("Value: ")+`
42
- `+String(n.value).slice(0,500)),console.log(p.bold("Created: ")+n.created_at);break}case"session":{const n=o.prepare("SELECT * FROM sessions WHERE id = ?").get(t);if(!n){f(`Session ${t} not found`);break}console.log(p.bold("Date: ")+n.date),console.log(p.bold("Objectives: ")+`
43
- `+n.objectives),n.completed&&console.log(p.bold("Completed: ")+`
44
- `+n.completed),n.notes&&console.log(p.bold("Notes: ")+`
45
- `+n.notes);break}default:f(`Unknown type prefix: ${i}. Use mem|quest|truth|data|session`)}r.close()}async function Je(l){const{positional:a,flags:e}=_(l),i=a[0];i||(f('Usage: wyrm capture "<content>" [--project <name>] [--mode auto|quest|truth|memory]'),process.exit(1));const s=e.project,t=e.mode,r=C(),o=r.getDatabase();let n=null;if(s){const k=x(r,s);k||(f(`Project not found: ${s}`),r.close(),process.exit(1)),n=k.id}let d=We(i);t&&t!=="auto"&&(d={type:t,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[t]??t,confidence:100,reasoning:`Mode override: ${t}`});const{type:c,subtype:m,confidence:g,reasoning:u}=d;(c==="quest"||c==="truth"||c==="memory")&&n===null&&(f('A --project is required to capture. Use: wyrm capture "<text>" --project <name>'),r.close(),process.exit(1));let h=0,y="",w=!1;const v=new G(o),R=new pe(o);if(me(R,new ue(o)),c==="quest")h=r.addQuest(n,i.slice(0,200),"","medium").id,y="quest";else if(c==="truth")t!=="truth"&&g<100?(h=v.add(n,{kind:"pattern",problem:i,confidence:g/100,needsReview:1}).id,y="mem",w=!0):(h=R.set(n,{category:"decision",key:i.slice(0,60),value:i}).id,y="truth");else{const k=g>=75;h=v.add(n,{kind:m,problem:i,confidence:g/100,needsReview:k?0:1}).id,y="mem",k||(w=!0)}const{recordWrite:j}=await import("./receipts.js"),E=j(o,{tool:"wyrm_capture",outcome:w?"queued":"stored",refTable:y,refId:h,reason:w?`needs_review (confidence ${g}%) \u2014 review to activate`:void 0,source:"cli",projectId:n??void 0});r.close(),b(`Captured as ${c}: ${m}`),console.log(`${p.dim("Confidence:")} ${g}% | ${p.dim(u)}`),console.log(`${p.dim("ID:")} ${y}:${h}`),w&&console.log(`${Y.warning} Stored for review \u2014 run ${p.cyan("wyrm review")} to activate`),console.log(`receipt: ${E.outcome} ${E.ref??""}${E.reason?` \u2014 ${E.reason}`:""}`)}async function ze(l){const{flags:a}=_(l);if(a.writes!==!0){f("Usage: wyrm digest --writes [--since <days>] [--json]"),process.exitCode=1;return}const e=Number(a.since)>=1?Number(a.since):1,{buildWriteDigest:i}=await import("./receipts.js"),s=C();try{const t=i(s.getDatabase(),e);if(a.json===!0){process.stdout.write(JSON.stringify(t)+`
46
- `);return}if(S(`Write digest \u2014 last ${t.since}`),console.log(`${p.bold("Total writes:")} ${t.total} ${p.bold("Outcomes:")} ${Object.entries(t.byOutcome).map(([r,o])=>`${r} ${o}`).join(" \xB7 ")||"none"}`),console.log(`${p.bold("Review queue:")} ${t.reviewQueueDepth} awaiting review${t.reviewQueueDepth>0?p.dim(" (invisible to recall until approved)"):""}`),t.byTool.length>0&&console.log(P(["Tool","Outcome","N"],t.byTool.map(r=>[r.tool,r.outcome,String(r.n)]))),t.reasons.length>0){console.log(p.bold("Non-stored reasons:"));for(const r of t.reasons)console.log(` ${r.outcome} \xD7${r.n} \u2014 ${r.reason.slice(0,110)}`)}t.bySource.length>0&&console.log(p.bold("By source: ")+t.bySource.map(r=>`${r.source} ${r.n}`).join(" \xB7 "))}finally{s.close()}}async function Qe(l){const{flags:a}=_(l),e=D(a.session,0),i=a.path,s=a.project,t=D(a["max-chars"],6e3),r=a.quiet===!0,o=console.log;console.log=()=>{};const n=C();try{const d=new Me(n.getDatabase());let c=e;if(c<=0){let u=i?n.getProject(i):void 0;if(!u&&s&&(u=x(n,s)??void 0),u||(u=n.getProject(process.cwd())),!u){r||process.stderr.write(`wyrm rehydrate: no Wyrm project for this directory, nothing to restore.
47
- `);return}const h=n.getRecentSessions(u.id,1);if(h.length===0){r||process.stderr.write(`wyrm rehydrate: project "${u.name}" has no prior sessions yet.
48
- `);return}c=h[0].id}const m=d.rehydrate(c);if(!m){r||process.stderr.write(`wyrm rehydrate: session ${c} not found.
49
- `);return}let g=m.briefing_markdown;t>0&&g.length>t&&(g=g.slice(0,t)+`
50
-
51
- _... brief truncated at ${t} chars, run \`wyrm show session:${m.session_id}\` for the full record._`),process.stdout.write(g+`
52
- `)}finally{n.close(),console.log=o}}async function Ze(l){const{flags:a}=_(l),{runMetabolize:e}=await import("./metabolize.js"),i=C(),s=console.log;try{let t;if(typeof a.project=="string"){const o=x(i,a.project);if(!o){f(`Project not found: ${a.project}`),process.exitCode=1;return}t=o.id}const r=e(i.getDatabase(),{projectId:t,dryRun:a["dry-run"]===!0,near:a["no-near"]===!0?!1:void 0});console.log(`metabolize${r.dryRun?" (dry-run)":""} \u2014 scanned ${r.scanned} \xB7 exact-merged ${r.exactMerged} (superseded, not deleted) \xB7 near-dup candidates queued ${r.nearCandidatesQueued} \xB7 decayed ${r.decayed}`)}finally{i.close(),console.log=s}}async function Xe(l){const{positional:a,flags:e}=_(l),i=a[0]??"stats",{backfillEntities:s}=await import("./entity-populate.js"),t=C(),r=console.log;try{const o=t.getDatabase();let n;if(typeof e.project=="string"){const d=x(t,e.project);if(!d){f(`Project not found: ${e.project}`),process.exitCode=1;return}n=d.id}if(i==="stats"){const d=c=>{if(n!=null){const g=c==="entities"?"SELECT COUNT(*) AS n FROM entities WHERE project_id = ?":"SELECT COUNT(*) AS n FROM relationships WHERE project_id = ?";return o.prepare(g).get(n).n}const m=c==="entities"?"SELECT COUNT(*) AS n FROM entities":"SELECT COUNT(*) AS n FROM relationships";return o.prepare(m).get().n};console.log(`entities: ${d("entities")} \xB7 relationships: ${d("relationships")}${n!=null?` (project ${n})`:" (all projects)"}`);return}if(i==="backfill"){const d=n!=null?[{id:n}]:o.prepare("SELECT id FROM projects").all();let c=0,m=0,g=0;for(const u of d){const h=s(o,u.id,{limit:D(e.limit,5e3)});c+=h.created,m+=h.linked,g+=h.artifactsScanned}console.log(`entities backfill \u2014 scanned ${g} artifact(s) across ${d.length} project(s): +${c} entities, +${m} co-occurrence edges`);return}f("Usage: wyrm entities <backfill|stats> [--project <name>] [--limit N]"),process.exitCode=1}finally{t.close(),console.log=r}}async function et(l){const{positional:a,flags:e}=_(l),i=a[0],s=await import("./bridge.js");if(i==="init"){const{existsSync:t,writeFileSync:r}=await import("node:fs"),o=s.configPath();if(t(o)&&e.force!==!0){f(`${o} already exists (use --force to overwrite).`),process.exitCode=1;return}const n=(await import("node:os")).homedir(),d={sources:[{type:"remember",name:"remember",dir:`${n}/.remember`,projectPath:n,windowDays:7}]};r(o,JSON.stringify(d,null,2)),b(`Wrote ${o} (1 source: remember). Add render/reverse sources per project as needed.`);return}if(i==="status"){const t=s.loadConfig();if(!t){f(`No bridge config at ${s.configPath()} \u2014 run \`wyrm bridge init\`.`),process.exitCode=1;return}const r=s.loadState();S("Bridge sources");for(const o of t.sources){const n=Object.keys(r).filter(c=>c.startsWith(o.name+":")),d=n.reduce((c,m)=>c+r[m].length,0);console.log(` ${o.name} [${o.type}] \u2192 ${"projectPath"in o?o.projectPath:""}${o.type==="remember"?` (${n.length} files tracked, ${d} sections bridged)`:""}`)}return}if(i==="run"){const t=s.loadConfig();if(!t){f(`No bridge config at ${s.configPath()} \u2014 run \`wyrm bridge init\`.`),process.exitCode=1;return}const r=C(),o=console.log;try{const n={wyrm_version:M().version??"unknown",compiled_at:new Date().toISOString()},d=await s.runBridge(r.getDatabase(),t,n,{only:typeof e.source=="string"?e.source:void 0,dryRun:e["dry-run"]===!0});for(const c of d)console.log(`bridge:${c.source} [${c.type}]${e["dry-run"]===!0?" (dry-run)":""} \u2014 stored ${c.stored} \xB7 queued ${c.queued} \xB7 dropped ${c.dropped} \xB7 rendered ${c.rendered}${c.note?` \xB7 ${c.note}`:""}`);if(e.watch===!0){const c=Number(e.interval)>=2?Number(e.interval):15;console.log(`bridge watch \u2014 re-rendering on write events (poll ${c}s, Ctrl-C to stop)`),await s.watchBridge(r.getDatabase(),t,()=>({wyrm_version:M().version??"unknown",compiled_at:new Date().toISOString()}),{intervalSec:c,onCycle:m=>{for(const g of m)console.log(`bridge:${g.source} re-rendered (${g.rendered} file(s), ${g.queued} edit(s) harvested)`)}})}return}finally{r.close(),console.log=o}}f("Usage: wyrm bridge <init|status|run> [--source <name>] [--dry-run] [--force]"),process.exitCode=1}async function tt(l){const{positional:a,flags:e}=_(l);if(a[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 s=c=>typeof e[c]=="string"?e[c]:void 0,t=s("path"),r=s("project"),o=s("run")?.slice(0,64),n=console.log;console.log=()=>{};const d=C();try{let c=t?d.getProject(t):void 0;if(!c&&r&&(c=x(d,r)??void 0),c||(c=d.getProject(process.cwd())),!c){process.stderr.write(`wyrm session log: no Wyrm project for this directory, nothing recorded.
53
- `);return}const m={};for(const h of["objectives","completed","issues","commits","notes"]){const y=s(h);y&&(m[h]=y.slice(0,8e3))}const g=d.getDatabase();let u;o&&(u=g.prepare("SELECT id FROM sessions WHERE project_id = ? AND run_id = ? ORDER BY id DESC LIMIT 1").get(c.id,o)?.id),u?d.updateSession(u,m):(u=d.createSession(c.id,m).id,o&&g.prepare("UPDATE sessions SET run_id = ? WHERE id = ?").run(o,u)),process.stdout.write(`session:${u}
54
- `)}finally{d.close(),console.log=n}}async function ot(l){const{positional:a,flags:e}=_(l),i=a[0],s=d=>typeof e[d]=="string"?e[d]:void 0,{AgentPresence:t,processStartTime:r,presenceLiveness:o}=await import("./presence.js"),n=C();try{const d=new t(n.getDatabase());if(i==="announce"){const c=s("agent");if(!c){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 m=s("path");let g=m?n.getProject(m):void 0;!g&&s("project")&&(g=x(n,s("project"))??void 0);const u=e["auto-pid"]===!0?process.ppid:Number(s("pid")),h={};let y="";if(Number.isInteger(u)&&u>0){const R=r(u);R?(h.pid=u,h.pid_start=R,y=` \xB7 pid ${u} (start ${R})`):y=` \xB7 pid ${u} unreadable \u2014 TTL fallback`}const w=Number(s("ttl")),v=d.announce({agent_id:c,agent_kind:s("kind")??"cli",project_id:g?.id??null,current_quest_id:s("quest")?Number(s("quest")):null,ttl_seconds:Number.isFinite(w)&&w>0?w:h.pid?86400:300,metadata:Object.keys(h).length?h:void 0,role:s("role")??null});process.stdout.write(`presence:${v.id} ${c}${y}
55
- `);return}if(i==="list"||i==="ls"||i===void 0){const c=n.getDatabase().prepare("SELECT * FROM agent_presence ORDER BY last_heartbeat DESC").all();if(c.length===0){process.stdout.write(`No agents on the board.
56
- `);return}const m={"alive-pid":"ALIVE (pid)","dead-pid":"DEAD (pid gone)","alive-ttl":"alive (ttl)",stale:"stale"};for(const g of c){const u=o(g);process.stdout.write(`${g.agent_id} [${g.agent_kind}] ${m[u]} hb ${g.last_heartbeat}${g.role?` role ${g.role}`:""}${g.current_quest_id?` quest #${g.current_quest_id}`:""}
57
- `)}return}if(i==="release"){const c=s("agent");if(!c){f("Usage: wyrm presence release --agent <id>"),process.exitCode=1;return}const m=d.release(c);process.stdout.write(m?`released ${c}
58
- `:`no presence row for ${c}
59
- `);return}f("Usage: wyrm presence <announce|list|release> [options]"),process.exitCode=1}finally{n.close()}}async function st(l){const{flags:a}=_(l),e=a.path,i=a.project,s=a.out,t=a.brief===!0,r=a.force===!0,o=a.quiet===!0,n=(typeof a.client=="string"?a.client:"").split(",").map(u=>u.trim().toLowerCase()).filter(Boolean);let d=n.filter(u=>ce.includes(u));const c=n.filter(u=>!ce.includes(u));c.length>0&&(f(`Unknown --client value(s): ${c.join(", ")} (valid: ${ce.join("|")})`),process.exit(1));const m=console.log;t&&(console.log=()=>{});const g=C();try{let u=e?g.getProject(e):void 0;!u&&i&&(u=x(g,i)??void 0),u||(u=g.getProject(process.cwd())),u||(console.log=m,f("wyrm render: no Wyrm project for this directory (use --path or --project)."),process.exit(1));const h=fe(g.getDatabase()),y={wyrm_version:M().version??"unknown",compiled_at:new Date().toISOString()};if(t){const j=ie(h,u,y);console.log=m,process.stdout.write(j.sessionBrief+`
60
- `);return}const w=s??u.path;d.length===0&&n.length===0&&(d=Ae(Le.filter(j=>H(q(w,j)))));{const j=await import("./reverse-bridge.js"),E=ie(h,u,y),k={"MEMORY.md":E.memoryMd};for(const L of d){const W=ge(L,E.model,y);k[W.relPath]=W.block}try{const L=j.makeBridgeDeps(g.getDatabase()),W=await j.sweepProject(L,{id:u.id,path:u.path},k,{rootDir:w});W.added>0&&!o&&console.log(` ${Y.warning} harvested ${W.added} human edit(s) \u2192 review queue before overwrite`)}catch{}}const{plan:v,writes:R}=Oe(h,u,y,{rootDir:w,clients:d,force:r});if(!o){b(`Rendered ${u.name} memory (${v.model.truths.length} truths, ${v.model.failures.length} failures, ${v.model.quests.length} quests, ${v.model.artifacts.length} patterns) to ${w}`);for(const j of R){const E=j.action==="created"?Y.success:j.action==="updated"?Y.info:Y.warning;console.log(` ${E} ${j.action.padEnd(7)} ${j.path}${j.reason?` (${j.reason})`:""}`)}}}finally{g.close(),console.log=m}}async function nt(l){const{flags:a}=_(l),e=a.path,i=a.project,s=a.root,t=a["dry-run"]===!0||a.dry===!0,r=(typeof a.client=="string"?a.client:"").split(",").map(m=>m.trim().toLowerCase()).filter(Boolean),o=["claude","cursor","copilot","agents"],n=r.filter(m=>o.includes(m)),d=await import("./reverse-bridge.js"),c=C();try{let m=e?c.getProject(e):void 0;if(!m&&i&&(m=x(c,i)??void 0),m||(m=c.getProject(process.cwd())),!m){f("wyrm reverse-bridge: no Wyrm project for this directory (use --path or --project)."),process.exitCode=1;return}const g=fe(c.getDatabase()),u={wyrm_version:M().version??"unknown",compiled_at:new Date().toISOString()},h=ie(g,m,u),y={"MEMORY.md":h.memoryMd};for(const R of n){const j=ge(R,h.model,u);y[j.relPath]=j.block}const w=d.makeBridgeDeps(c.getDatabase()),v=await d.sweepProject(w,{id:m.id,path:m.path},y,{dryRun:t,rootDir:s});S(`Reverse bridge ${t?"(dry run) ":""}\u2014 ${v.added} candidate(s) queued, ${v.skipped} already present (${v.filesWithEdits}/${v.filesScanned} file(s) with edits)`);for(const R of v.sample)console.log(` ${Y.bullet} ${R}`);!t&&v.added>0&&b("Review with: wyrm review")}finally{c.close()}}async function rt(l){const a=_(l);if(typeof a.flags.from=="string"){await it(a);return}const{positional:e,flags:i}=_(l.slice(1)),s=l[0],t=i.project;if(s==="git"){const r=D(i.last,20),o=C(),n=o.getDatabase();let d=null;if(t){const y=x(o,t);y||(f(`Project not found: ${t}`),o.close(),process.exit(1)),d=y.id}else{const y=n.prepare("SELECT p.* FROM projects p JOIN sessions s ON s.project_id = p.id ORDER BY s.created_at DESC LIMIT 1").get();y&&(d=y.id)}d||(f("No project found. Use --project <name>"),o.close(),process.exit(1));const c=z("git",["log","--pretty=format:%H%x1f%s%x1f%an%x1f%ai",`-${r}`],{cwd:process.cwd(),encoding:"utf-8",timeout:1e4,shell:!1});(c.error||c.status!==0)&&(f("git log failed. Make sure you are in a git repository."),o.close(),process.exit(1));const m=c.stdout.split(`
61
- `).filter(y=>y.trim()),g=new G(n);let u=0,h=0;for(const y of m){const[,w,v,R]=y.split(""),j=w??"";if(/^Merge /i.test(j)||/^(chore|bump|release|version)/i.test(j)){h++;continue}let E="pattern";/^fix(\(.+\))?:/i.test(j)?E="lesson":/^refactor(\(.+\))?:/i.test(j)&&(E="heuristic");const k=j.split(":")[0]??"commit";g.add(d,{kind:E,problem:j,whyItWorked:`Committed by ${v??"unknown"} on ${R??"unknown"}`,tags:["git","commit",k.toLowerCase()],confidence:.6,needsReview:1}),u++}o.close(),b(`Imported ${u} commits (${h} skipped). Run ${p.cyan("wyrm review")} to activate.`)}else if(s==="rules"){const r=e[0],o=i.format??"plain";r||(f("Usage: wyrm import rules <path> [--project <name>] [--format cursorrules|copilot|plain]"),process.exit(1)),H(r)||(f(`File not found: ${r}`),process.exit(1));const n=B(r,"utf-8"),d=C(),c=d.getDatabase();let m=null;if(t){const k=x(d,t);k||(f(`Project not found: ${t}`),d.close(),process.exit(1)),m=k.id}else{const k=c.prepare("SELECT p.* FROM projects p JOIN sessions s ON s.project_id = p.id ORDER BY s.created_at DESC LIMIT 1").get();k&&(m=k.id)}m||(f("No project found. Use --project <name>"),d.close(),process.exit(1));const g=r.split("/").pop()??"rules",u=["imported",o,g],h=n.split(/\n(?=#)/),y=n.split(/\n\n+/),w=(h.length>=y.length?h:y).map(k=>k.trim()).filter(k=>k.length>=15),v=new G(c),R=new pe(c);me(R,new ue(c));let j=0,E=0;for(const k of w)/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(k)?(R.set(m,{category:"constraint",key:k.slice(0,50).replace(/\n/g," "),value:k,source:g}),j++):(v.add(m,{kind:"heuristic",problem:k,tags:u,confidence:.7,needsReview:1}),E++);d.close(),b(`Imported ${j} ground truths + ${E} 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 ${ye.join("|")} <file.json> [--project <name>]`),process.exit(1)}async function it(l){const a=l.flags.from,e=l.positional[0],i=l.flags.project,s=`Usage: wyrm import --from ${ye.join("|")} <file.json> [--project <name>]`;e||(f(s),process.exit(1)),H(e)||(f(`File not found: ${e}`),process.exit(1));let t;try{t=JSON.parse(B(e,"utf-8"))}catch(n){f(`Could not parse JSON from ${e}: ${n.message}`),process.exit(1)}let r;try{r=Ue(a,t)}catch(n){f(n.message),process.exit(1)}const o=C();try{let n=i?x(o,i):null;if(n||(n=o.getProject(process.cwd())??null),!n){f(i?`Project not found: ${i}`:"wyrm import: no Wyrm project for this directory (pass --project <name>)."),process.exitCode=1;return}if(r.length===0){f(`No importable memories found in ${e} for source "${a}".`);return}const d=o.getDatabase(),c=new G(d);try{const{createVectorStore:g}=await import("./vectors.js"),u=process.env.WYRM_VECTOR_PROVIDER??"auto";c.setVectorStore(g({provider:u},d))}catch{}let m=0;for(const g of r)c.add(n.id,{kind:"lesson",problem:g.text,tags:g.tags,constraints:g.metadata?JSON.stringify(g.metadata):void 0,whyItWorked:`Imported from ${g.source}`,outcome:"neutral",confidence:.6,needsReview:1}),m++;b(`Imported ${m} ${m===1?"memory":"memories"} from ${a} into ${p.cyan(n.name)} review queue. Run ${p.cyan("wyrm review")} to vet (tagged ${p.dim(`imported_from:${r[0]?.source??a}`)}).`)}finally{o.close()}}async function ct(l){const{flags:a}=_(l),e=a.project,i=C(),s=i.getDatabase();if(S("Wyrm Statistics"),e){const t=x(i,e);t||(f(`Project not found: ${e}`),i.close(),process.exit(1));const r=i.getProjectStats(t.id),o=[["Sessions",String(r.sessions)],["Quests (pending)",String(r.quests.pending)],["Quests (completed)",String(r.quests.completed)],["Data Points",String(r.dataPoints)]];console.log(P(["Metric","Value"],o))}else{const t=i.getStats(),r=[["Projects",String(t.projects)],["Sessions",String(t.sessions)],["Quests",String(t.quests)],["Data Points",String(t.dataPoints)],["DB Size",t.dbSize]],o=s.prepare("SELECT COUNT(*) as n FROM memory_artifacts").get().n,n=s.prepare("SELECT COUNT(*) as n FROM ground_truths WHERE is_current = 1").get().n;r.push(["Memories",String(o)],["Ground Truths",String(n)]),console.log(P(["Metric","Value"],r))}i.close()}async function at(l){const{flags:a}=_(l),e=a.project,i=C(),s=i.getDatabase();let t=null;if(e){const c=x(i,e);c||(f(`Project not found: ${e}`),i.close(),process.exit(1)),t=c.id}const r=t?`AND project_id = ${t}`:"",o=s.prepare(`
35
+ `).all(i);if(u.length>0){const g=u.map(f=>[`quest:${f.id}`,f.priority,f.title.slice(0,60),f.status]);console.log(D(["ID","Priority","Title","Status"],g))}else console.log(d.dim(" No quests yet."))}e.close()}async function ze(l){const{positional:c}=C(l),t=c[0];t||(m("Usage: wyrm show <typed-id> (e.g. mem:41, quest:12, truth:7, data:5, session:3)"),process.exit(1));const[i,r]=t.split(":"),e=parseInt(r??"",10);(!i||isNaN(e))&&(m(`Invalid typed ID: ${t}. Format: type:number (e.g. mem:41)`),process.exit(1));const s=j(),o=s.getDatabase();switch(k(`${t}`),i){case"mem":{const n=o.prepare("SELECT * FROM memory_artifacts WHERE id = ?").get(e);if(!n){m(`Memory artifact ${e} not found`);break}console.log(d.bold("Kind: ")+n.kind),console.log(d.bold("Confidence:")+` ${Math.round(n.confidence*100)}%`),console.log(d.bold("Problem: ")+`
36
+ `+n.problem),n.validated_fix&&console.log(d.bold("Solution: ")+`
37
+ `+n.validated_fix),n.why_it_worked&&console.log(d.bold("Why: ")+`
38
+ `+n.why_it_worked),n.tags&&console.log(d.bold("Tags: ")+n.tags),console.log(d.bold("Created: ")+n.created_at);break}case"quest":{const n=o.prepare("SELECT * FROM quests WHERE id = ?").get(e);if(!n){m(`Quest ${e} not found`);break}console.log(d.bold("Title: ")+n.title),console.log(d.bold("Priority: ")+n.priority),console.log(d.bold("Status: ")+n.status),n.description&&console.log(d.bold("Desc: ")+`
39
+ `+n.description),n.tags&&console.log(d.bold("Tags: ")+n.tags),console.log(d.bold("Created: ")+n.created_at);break}case"truth":{const n=o.prepare("SELECT * FROM ground_truths WHERE id = ?").get(e);if(!n){m(`Ground truth ${e} not found`);break}console.log(d.bold("Category: ")+n.category),console.log(d.bold("Key: ")+n.key),console.log(d.bold("Value: ")+`
40
+ `+n.value),n.rationale&&console.log(d.bold("Rationale:")+`
41
+ `+n.rationale),console.log(d.bold("Active: ")+(n.is_current?"Yes":"No (superseded)")),console.log(d.bold("Created: ")+n.created_at);break}case"data":{const n=o.prepare("SELECT * FROM data_lake WHERE id = ?").get(e);if(!n){m(`Data point ${e} not found`);break}console.log(d.bold("Category: ")+n.category),console.log(d.bold("Key: ")+n.key),console.log(d.bold("Value: ")+`
42
+ `+String(n.value).slice(0,500)),console.log(d.bold("Created: ")+n.created_at);break}case"session":{const n=o.prepare("SELECT * FROM sessions WHERE id = ?").get(e);if(!n){m(`Session ${e} not found`);break}console.log(d.bold("Date: ")+n.date),console.log(d.bold("Objectives: ")+`
43
+ `+n.objectives),n.completed&&console.log(d.bold("Completed: ")+`
44
+ `+n.completed),n.notes&&console.log(d.bold("Notes: ")+`
45
+ `+n.notes);break}default:m(`Unknown type prefix: ${i}. Use mem|quest|truth|data|session`)}s.close()}async function Qe(l){const{positional:c,flags:t}=C(l),i=c[0];i||(m('Usage: wyrm capture "<content>" [--project <name>] [--mode auto|quest|truth|memory]'),process.exit(1));const r=t.project,e=t.mode,s=j(),o=s.getDatabase();let n=null;if(r){const S=x(s,r);S||(m(`Project not found: ${r}`),s.close(),process.exit(1)),n=S.id}let p=Fe(i);e&&e!=="auto"&&(p={type:e,subtype:{quest:"quest",truth:"decision",memory:"pattern"}[e]??e,confidence:100,reasoning:`Mode override: ${e}`});const{type:a,subtype:u,confidence:g,reasoning:f}=p;(a==="quest"||a==="truth"||a==="memory")&&n===null&&(m('A --project is required to capture. Use: wyrm capture "<text>" --project <name>'),s.close(),process.exit(1));let y=0,h="",w=!1;const $=new G(o),E=new pe(o);if(me(E,new ue(o)),a==="quest")y=s.addQuest(n,i.slice(0,200),"","medium").id,h="quest";else if(a==="truth")e!=="truth"&&g<100?(y=$.add(n,{kind:"pattern",problem:i,confidence:g/100,needsReview:1}).id,h="mem",w=!0):(y=E.set(n,{category:"decision",key:i.slice(0,60),value:i}).id,h="truth");else{const S=g>=75;y=$.add(n,{kind:u,problem:i,confidence:g/100,needsReview:S?0:1}).id,h="mem",S||(w=!0)}const{recordWrite:_}=await import("./receipts.js"),R=_(o,{tool:"wyrm_capture",outcome:w?"queued":"stored",refTable:h,refId:y,reason:w?`needs_review (confidence ${g}%) \u2014 review to activate`:void 0,source:"cli",projectId:n??void 0});s.close(),b(`Captured as ${a}: ${u}`),console.log(`${d.dim("Confidence:")} ${g}% | ${d.dim(f)}`),console.log(`${d.dim("ID:")} ${h}:${y}`),w&&console.log(`${Y.warning} Stored for review \u2014 run ${d.cyan("wyrm review")} to activate`),console.log(`receipt: ${R.outcome} ${R.ref??""}${R.reason?` \u2014 ${R.reason}`:""}`)}async function Xe(l){const{flags:c}=C(l);if(c.writes!==!0){m("Usage: wyrm digest --writes [--since <days>] [--json]"),process.exitCode=1;return}const t=Number(c.since)>=1?Number(c.since):1,{buildWriteDigest:i}=await import("./receipts.js"),r=j();try{const e=i(r.getDatabase(),t);if(c.json===!0){process.stdout.write(JSON.stringify(e)+`
46
+ `);return}if(k(`Write digest \u2014 last ${e.since}`),console.log(`${d.bold("Total writes:")} ${e.total} ${d.bold("Outcomes:")} ${Object.entries(e.byOutcome).map(([s,o])=>`${s} ${o}`).join(" \xB7 ")||"none"}`),console.log(`${d.bold("Review queue:")} ${e.reviewQueueDepth} awaiting review${e.reviewQueueDepth>0?d.dim(" (invisible to recall until approved)"):""}`),e.byTool.length>0&&console.log(D(["Tool","Outcome","N"],e.byTool.map(s=>[s.tool,s.outcome,String(s.n)]))),e.reasons.length>0){console.log(d.bold("Non-stored reasons:"));for(const s of e.reasons)console.log(` ${s.outcome} \xD7${s.n} \u2014 ${s.reason.slice(0,110)}`)}e.bySource.length>0&&console.log(d.bold("By source: ")+e.bySource.map(s=>`${s.source} ${s.n}`).join(" \xB7 "))}finally{r.close()}}async function Ze(l){const{flags:c}=C(l),t=I(c.session,0),i=c.path,r=c.project,e=I(c["max-chars"],6e3),s=c.quiet===!0,o=console.log;console.log=()=>{};const n=j();try{const p=new Ae(n.getDatabase());let a=t;if(a<=0){let f=i?n.getProject(i):void 0;if(!f&&r&&(f=x(n,r)??void 0),f||(f=n.getProject(process.cwd())),!f){s||process.stderr.write(`wyrm rehydrate: no Wyrm project for this directory, nothing to restore.
47
+ `);return}const y=n.getRecentSessions(f.id,1);if(y.length===0){s||process.stderr.write(`wyrm rehydrate: project "${f.name}" has no prior sessions yet.
48
+ `);return}a=y[0].id}const u=p.rehydrate(a);if(!u){s||process.stderr.write(`wyrm rehydrate: session ${a} not found.
49
+ `);return}let g=u.briefing_markdown;e>0&&g.length>e&&(g=g.slice(0,e)+`
50
+
51
+ _... brief truncated at ${e} chars, run \`wyrm show session:${u.session_id}\` for the full record._`),process.stdout.write(g+`
52
+ `)}finally{n.close(),console.log=o}}async function et(l){const{flags:c}=C(l),{runMetabolize:t}=await import("./metabolize.js"),i=j(),r=console.log;try{let e;if(typeof c.project=="string"){const o=x(i,c.project);if(!o){m(`Project not found: ${c.project}`),process.exitCode=1;return}e=o.id}const s=t(i.getDatabase(),{projectId:e,dryRun:c["dry-run"]===!0,near:c["no-near"]===!0?!1:void 0});console.log(`metabolize${s.dryRun?" (dry-run)":""} \u2014 scanned ${s.scanned} \xB7 exact-merged ${s.exactMerged} (superseded, not deleted) \xB7 near-dup candidates queued ${s.nearCandidatesQueued} \xB7 decayed ${s.decayed}`)}finally{i.close(),console.log=r}}async function tt(l){const{positional:c,flags:t}=C(l),i=c[0]??"stats",{backfillEntities:r}=await import("./entity-populate.js"),e=j(),s=console.log;try{const o=e.getDatabase();let n;if(typeof t.project=="string"){const p=x(e,t.project);if(!p){m(`Project not found: ${t.project}`),process.exitCode=1;return}n=p.id}if(i==="stats"){const p=a=>{if(n!=null){const g=a==="entities"?"SELECT COUNT(*) AS n FROM entities WHERE project_id = ?":"SELECT COUNT(*) AS n FROM relationships WHERE project_id = ?";return o.prepare(g).get(n).n}const u=a==="entities"?"SELECT COUNT(*) AS n FROM entities":"SELECT COUNT(*) AS n FROM relationships";return o.prepare(u).get().n};console.log(`entities: ${p("entities")} \xB7 relationships: ${p("relationships")}${n!=null?` (project ${n})`:" (all projects)"}`);return}if(i==="backfill"){const p=n!=null?[{id:n}]:o.prepare("SELECT id FROM projects").all();let a=0,u=0,g=0;for(const f of p){const y=r(o,f.id,{limit:I(t.limit,5e3)});a+=y.created,u+=y.linked,g+=y.artifactsScanned}console.log(`entities backfill \u2014 scanned ${g} artifact(s) across ${p.length} project(s): +${a} entities, +${u} co-occurrence edges`);return}m("Usage: wyrm entities <backfill|stats> [--project <name>] [--limit N]"),process.exitCode=1}finally{e.close(),console.log=s}}async function ot(l){const{positional:c,flags:t}=C(l),i=c[0],r=await import("./bridge.js");if(i==="init"){const{existsSync:e,writeFileSync:s}=await import("node:fs"),o=r.configPath();if(e(o)&&t.force!==!0){m(`${o} already exists (use --force to overwrite).`),process.exitCode=1;return}const n=(await import("node:os")).homedir(),p={sources:[{type:"remember",name:"remember",dir:`${n}/.remember`,projectPath:n,windowDays:7}]};s(o,JSON.stringify(p,null,2)),b(`Wrote ${o} (1 source: remember). Add render/reverse sources per project as needed.`);return}if(i==="status"){const e=r.loadConfig();if(!e){m(`No bridge config at ${r.configPath()} \u2014 run \`wyrm bridge init\`.`),process.exitCode=1;return}const s=r.loadState();k("Bridge sources");for(const o of e.sources){const n=Object.keys(s).filter(a=>a.startsWith(o.name+":")),p=n.reduce((a,u)=>a+s[u].length,0);console.log(` ${o.name} [${o.type}] \u2192 ${"projectPath"in o?o.projectPath:""}${o.type==="remember"?` (${n.length} files tracked, ${p} sections bridged)`:""}`)}return}if(i==="run"){const e=r.loadConfig();if(!e){m(`No bridge config at ${r.configPath()} \u2014 run \`wyrm bridge init\`.`),process.exitCode=1;return}const s=j(),o=console.log;try{const n={wyrm_version:M().version??"unknown",compiled_at:new Date().toISOString()},p=await r.runBridge(s.getDatabase(),e,n,{only:typeof t.source=="string"?t.source:void 0,dryRun:t["dry-run"]===!0});for(const a of p)console.log(`bridge:${a.source} [${a.type}]${t["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(t.watch===!0){const a=Number(t.interval)>=2?Number(t.interval):15;console.log(`bridge watch \u2014 re-rendering on write events (poll ${a}s, Ctrl-C to stop)`),await r.watchBridge(s.getDatabase(),e,()=>({wyrm_version:M().version??"unknown",compiled_at:new Date().toISOString()}),{intervalSec:a,onCycle:u=>{for(const g of u)console.log(`bridge:${g.source} re-rendered (${g.rendered} file(s), ${g.queued} edit(s) harvested)`)}})}return}finally{s.close(),console.log=o}}m("Usage: wyrm bridge <init|status|run> [--source <name>] [--dry-run] [--force]"),process.exitCode=1}async function st(l){const{positional:c,flags:t}=C(l);if(c[0]!=="log"){m("Usage: wyrm session log [--path <dir>] [--run <id>] [--objectives <t>] [--completed <t>] [--issues <t>] [--commits <t>] [--notes <t>]"),process.exitCode=1;return}const r=a=>typeof t[a]=="string"?t[a]:void 0,e=r("path"),s=r("project"),o=r("run")?.slice(0,64),n=console.log;console.log=()=>{};const p=j();try{let a=e?p.getProject(e):void 0;if(!a&&s&&(a=x(p,s)??void 0),a||(a=p.getProject(process.cwd())),!a){process.stderr.write(`wyrm session log: no Wyrm project for this directory, nothing recorded.
53
+ `);return}const u={};for(const y of["objectives","completed","issues","commits","notes"]){const h=r(y);h&&(u[y]=h.slice(0,8e3))}const g=p.getDatabase();let f;o&&(f=g.prepare("SELECT id FROM sessions WHERE project_id = ? AND run_id = ? ORDER BY id DESC LIMIT 1").get(a.id,o)?.id),f?p.updateSession(f,u):(f=p.createSession(a.id,u).id,o&&g.prepare("UPDATE sessions SET run_id = ? WHERE id = ?").run(o,f)),process.stdout.write(`session:${f}
54
+ `)}finally{p.close(),console.log=n}}async function rt(l){const{positional:c,flags:t}=C(l),i=c[0],r=p=>typeof t[p]=="string"?t[p]:void 0,{AgentPresence:e,processStartTime:s,presenceLiveness:o}=await import("./presence.js"),n=j();try{const p=new e(n.getDatabase());if(i==="announce"){const a=r("agent");if(!a){m("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 u=r("path");let g=u?n.getProject(u):void 0;!g&&r("project")&&(g=x(n,r("project"))??void 0);const f=t["auto-pid"]===!0?process.ppid:Number(r("pid")),y={};let h="";if(Number.isInteger(f)&&f>0){const E=s(f);E?(y.pid=f,y.pid_start=E,h=` \xB7 pid ${f} (start ${E})`):h=` \xB7 pid ${f} unreadable \u2014 TTL fallback`}const w=Number(r("ttl")),$=p.announce({agent_id:a,agent_kind:r("kind")??"cli",project_id:g?.id??null,current_quest_id:r("quest")?Number(r("quest")):null,ttl_seconds:Number.isFinite(w)&&w>0?w:y.pid?86400:300,metadata:Object.keys(y).length?y:void 0,role:r("role")??null});process.stdout.write(`presence:${$.id} ${a}${h}
55
+ `);return}if(i==="list"||i==="ls"||i===void 0){const a=n.getDatabase().prepare("SELECT * FROM agent_presence ORDER BY last_heartbeat DESC").all();if(a.length===0){process.stdout.write(`No agents on the board.
56
+ `);return}const u={"alive-pid":"ALIVE (pid)","dead-pid":"DEAD (pid gone)","alive-ttl":"alive (ttl)",stale:"stale"};for(const g of a){const f=o(g);process.stdout.write(`${g.agent_id} [${g.agent_kind}] ${u[f]} hb ${g.last_heartbeat}${g.role?` role ${g.role}`:""}${g.current_quest_id?` quest #${g.current_quest_id}`:""}
57
+ `)}return}if(i==="release"){const a=r("agent");if(!a){m("Usage: wyrm presence release --agent <id>"),process.exitCode=1;return}const u=p.release(a);process.stdout.write(u?`released ${a}
58
+ `:`no presence row for ${a}
59
+ `);return}m("Usage: wyrm presence <announce|list|release> [options]"),process.exitCode=1}finally{n.close()}}async function nt(l){const{flags:c}=C(l),t=c.path,i=c.project,r=c.out,e=c.brief===!0,s=c.force===!0,o=c.quiet===!0,n=(typeof c.client=="string"?c.client:"").split(",").map(f=>f.trim().toLowerCase()).filter(Boolean);let p=n.filter(f=>ae.includes(f));const a=n.filter(f=>!ae.includes(f));a.length>0&&(m(`Unknown --client value(s): ${a.join(", ")} (valid: ${ae.join("|")})`),process.exit(1));const u=console.log;e&&(console.log=()=>{});const g=j();try{let f=t?g.getProject(t):void 0;!f&&i&&(f=x(g,i)??void 0),f||(f=g.getProject(process.cwd())),f||(console.log=u,m("wyrm render: no Wyrm project for this directory (use --path or --project)."),process.exit(1));const y=fe(g.getDatabase()),h={wyrm_version:M().version??"unknown",compiled_at:new Date().toISOString()};if(e){const _=ie(y,f,h);console.log=u,process.stdout.write(_.sessionBrief+`
60
+ `);return}const w=r??f.path;p.length===0&&n.length===0&&(p=We(Ue.filter(_=>q(F(w,_)))));{const _=await import("./reverse-bridge.js"),R=ie(y,f,h),S={"MEMORY.md":R.memoryMd};for(const L of p){const W=ge(L,R.model,h);S[W.relPath]=W.block}try{const L=_.makeBridgeDeps(g.getDatabase()),W=await _.sweepProject(L,{id:f.id,path:f.path},S,{rootDir:w});W.added>0&&!o&&console.log(` ${Y.warning} harvested ${W.added} human edit(s) \u2192 review queue before overwrite`)}catch{}}const{plan:$,writes:E}=Le(y,f,h,{rootDir:w,clients:p,force:s});if(!o){b(`Rendered ${f.name} memory (${$.model.truths.length} truths, ${$.model.failures.length} failures, ${$.model.quests.length} quests, ${$.model.artifacts.length} patterns) to ${w}`);for(const _ of E){const R=_.action==="created"?Y.success:_.action==="updated"?Y.info:Y.warning;console.log(` ${R} ${_.action.padEnd(7)} ${_.path}${_.reason?` (${_.reason})`:""}`)}}}finally{g.close(),console.log=u}}async function it(l){const{flags:c}=C(l),t=c.path,i=c.project,r=c.root,e=c["dry-run"]===!0||c.dry===!0,s=(typeof c.client=="string"?c.client:"").split(",").map(u=>u.trim().toLowerCase()).filter(Boolean),o=["claude","cursor","copilot","agents"],n=s.filter(u=>o.includes(u)),p=await import("./reverse-bridge.js"),a=j();try{let u=t?a.getProject(t):void 0;if(!u&&i&&(u=x(a,i)??void 0),u||(u=a.getProject(process.cwd())),!u){m("wyrm reverse-bridge: no Wyrm project for this directory (use --path or --project)."),process.exitCode=1;return}const g=fe(a.getDatabase()),f={wyrm_version:M().version??"unknown",compiled_at:new Date().toISOString()},y=ie(g,u,f),h={"MEMORY.md":y.memoryMd};for(const E of n){const _=ge(E,y.model,f);h[_.relPath]=_.block}const w=p.makeBridgeDeps(a.getDatabase()),$=await p.sweepProject(w,{id:u.id,path:u.path},h,{dryRun:e,rootDir:r});k(`Reverse bridge ${e?"(dry run) ":""}\u2014 ${$.added} candidate(s) queued, ${$.skipped} already present (${$.filesWithEdits}/${$.filesScanned} file(s) with edits)`);for(const E of $.sample)console.log(` ${Y.bullet} ${E}`);!e&&$.added>0&&b("Review with: wyrm review")}finally{a.close()}}async function at(l){const c=C(l);if(typeof c.flags.from=="string"){await ct(c);return}const{positional:t,flags:i}=C(l.slice(1)),r=l[0],e=i.project;if(r==="git"){const s=I(i.last,20),o=j(),n=o.getDatabase();let p=null;if(e){const h=x(o,e);h||(m(`Project not found: ${e}`),o.close(),process.exit(1)),p=h.id}else{const h=n.prepare("SELECT p.* FROM projects p JOIN sessions s ON s.project_id = p.id ORDER BY s.created_at DESC LIMIT 1").get();h&&(p=h.id)}p||(m("No project found. Use --project <name>"),o.close(),process.exit(1));const a=z("git",["log","--pretty=format:%H%x1f%s%x1f%an%x1f%ai",`-${s}`],{cwd:process.cwd(),encoding:"utf-8",timeout:1e4,shell:!1});(a.error||a.status!==0)&&(m("git log failed. Make sure you are in a git repository."),o.close(),process.exit(1));const u=a.stdout.split(`
61
+ `).filter(h=>h.trim()),g=new G(n);let f=0,y=0;for(const h of u){const[,w,$,E]=h.split(""),_=w??"";if(/^Merge /i.test(_)||/^(chore|bump|release|version)/i.test(_)){y++;continue}let R="pattern";/^fix(\(.+\))?:/i.test(_)?R="lesson":/^refactor(\(.+\))?:/i.test(_)&&(R="heuristic");const S=_.split(":")[0]??"commit";g.add(p,{kind:R,problem:_,whyItWorked:`Committed by ${$??"unknown"} on ${E??"unknown"}`,tags:["git","commit",S.toLowerCase()],confidence:.6,needsReview:1}),f++}o.close(),b(`Imported ${f} commits (${y} skipped). Run ${d.cyan("wyrm review")} to activate.`)}else if(r==="rules"){const s=t[0],o=i.format??"plain";s||(m("Usage: wyrm import rules <path> [--project <name>] [--format cursorrules|copilot|plain]"),process.exit(1)),q(s)||(m(`File not found: ${s}`),process.exit(1));const n=V(s,"utf-8"),p=j(),a=p.getDatabase();let u=null;if(e){const S=x(p,e);S||(m(`Project not found: ${e}`),p.close(),process.exit(1)),u=S.id}else{const S=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();S&&(u=S.id)}u||(m("No project found. Use --project <name>"),p.close(),process.exit(1));const g=s.split("/").pop()??"rules",f=["imported",o,g],y=n.split(/\n(?=#)/),h=n.split(/\n\n+/),w=(y.length>=h.length?y:h).map(S=>S.trim()).filter(S=>S.length>=15),$=new G(a),E=new pe(a);me(E,new ue(a));let _=0,R=0;for(const S of w)/\b(always|never|must|use|don't|avoid|prefer)\b/i.test(S)?(E.set(u,{category:"constraint",key:S.slice(0,50).replace(/\n/g," "),value:S,source:g}),_++):($.add(u,{kind:"heuristic",problem:S,tags:f,confidence:.7,needsReview:1}),R++);p.close(),b(`Imported ${_} ground truths + ${R} artifacts (pending review).`)}else m("Usage: wyrm import git [--project <name>] [--last N]"),m(" wyrm import rules <path> [--project <name>] [--format cursorrules|copilot|plain]"),m(` wyrm import --from ${ye.join("|")} <file.json> [--project <name>]`),process.exit(1)}async function ct(l){const c=l.flags.from,t=l.positional[0],i=l.flags.project,r=`Usage: wyrm import --from ${ye.join("|")} <file.json> [--project <name>]`;t||(m(r),process.exit(1)),q(t)||(m(`File not found: ${t}`),process.exit(1));let e;try{e=JSON.parse(V(t,"utf-8"))}catch(n){m(`Could not parse JSON from ${t}: ${n.message}`),process.exit(1)}let s;try{s=qe(c,e)}catch(n){m(n.message),process.exit(1)}const o=j();try{let n=i?x(o,i):null;if(n||(n=o.getProject(process.cwd())??null),!n){m(i?`Project not found: ${i}`:"wyrm import: no Wyrm project for this directory (pass --project <name>)."),process.exitCode=1;return}if(s.length===0){m(`No importable memories found in ${t} for source "${c}".`);return}const p=o.getDatabase(),a=new G(p);try{const{createVectorStore:g}=await import("./vectors.js"),f=process.env.WYRM_VECTOR_PROVIDER??"auto";a.setVectorStore(g({provider:f},p))}catch{}let u=0;for(const g of s)a.add(n.id,{kind:"lesson",problem:g.text,tags:g.tags,constraints:g.metadata?JSON.stringify(g.metadata):void 0,whyItWorked:`Imported from ${g.source}`,outcome:"neutral",confidence:.6,needsReview:1}),u++;b(`Imported ${u} ${u===1?"memory":"memories"} from ${c} into ${d.cyan(n.name)} review queue. Run ${d.cyan("wyrm review")} to vet (tagged ${d.dim(`imported_from:${s[0]?.source??c}`)}).`)}finally{o.close()}}async function lt(l){const{flags:c}=C(l),t=c.project,i=j(),r=i.getDatabase();if(k("Wyrm Statistics"),t){const e=x(i,t);e||(m(`Project not found: ${t}`),i.close(),process.exit(1));const s=i.getProjectStats(e.id),o=[["Sessions",String(s.sessions)],["Quests (pending)",String(s.quests.pending)],["Quests (completed)",String(s.quests.completed)],["Data Points",String(s.dataPoints)]];console.log(D(["Metric","Value"],o))}else{const e=i.getStats(),s=[["Projects",String(e.projects)],["Sessions",String(e.sessions)],["Quests",String(e.quests)],["Data Points",String(e.dataPoints)],["DB Size",e.dbSize]],o=r.prepare("SELECT COUNT(*) as n FROM memory_artifacts").get().n,n=r.prepare("SELECT COUNT(*) as n FROM ground_truths WHERE is_current = 1").get().n;s.push(["Memories",String(o)],["Ground Truths",String(n)]),console.log(D(["Metric","Value"],s))}i.close()}async function dt(l){const{flags:c}=C(l),t=c.project,i=j(),r=i.getDatabase();let e=null;if(t){const a=x(i,t);a||(m(`Project not found: ${t}`),i.close(),process.exit(1)),e=a.id}const s=e?`AND project_id = ${e}`:"",o=r.prepare(`
62
62
  SELECT id, kind, problem FROM memory_artifacts
63
- WHERE needs_review = 1 ${r}
63
+ WHERE needs_review = 1 ${s}
64
64
  ORDER BY created_at ASC
65
- `).all();if(o.length===0){console.log(p.dim(` No artifacts pending review${e?` for ${e}`:""}.`)),i.close();return}S(`Review Queue (${o.length} items)`);const n=Q({input:process.stdin,output:process.stdout}),d=c=>new Promise(m=>{n.question(c,m)});for(const c of o){console.log(`
66
- ${p.bold(`[${c.kind}] #${c.id}`)}`),console.log(p.dim("\u2500".repeat(60))),console.log(c.problem.slice(0,300)),console.log(p.dim("\u2500".repeat(60)));const g=(await d(`${p.cyan("[a]")}pprove / ${p.red("[r]")}eject / ${p.yellow("[s]")}kip? `)).trim().toLowerCase();g==="a"?(s.prepare("UPDATE memory_artifacts SET needs_review = 0, updated_at = datetime('now') WHERE id = ?").run(c.id),b(`Approved #${c.id}`)):g==="r"?(s.prepare("DELETE FROM memory_artifacts WHERE id = ?").run(c.id),console.log(`${Y.cross} Rejected #${c.id}`)):console.log(p.dim(` Skipped #${c.id}`))}n.close(),i.close(),console.log(`
67
- Review complete.`)}async function lt(l){const{positional:a,flags:e}=_(l),i=a[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:s,pbkdf2Sync:t,createCipheriv:r,createDecipheriv:o}=await import("crypto"),{readFileSync:n,writeFileSync:d,copyFileSync:c,unlinkSync:m,existsSync:g,chmodSync:u}=await import("fs"),{homedir:h}=await import("os"),{join:y}=await import("path"),w=(await import("better-sqlite3")).default;let v=process.env.WYRM_SYNC_PASSPHRASE??"";if(!v){const T=Q({input:process.stdin,output:process.stdout});v=await new Promise(I=>{process.stdout.write("Passphrase: "),process.stdin.isTTY&&process.stdin.setRawMode?.(!0),T.question("",U=>{process.stdin.isTTY&&process.stdin.setRawMode?.(!1),console.log(""),T.close(),I(U)})})}v||(f("Passphrase is required. Set WYRM_SYNC_PASSPHRASE or enter interactively."),process.exit(1));const R=y(h(),".wyrm"),j=C();if(i==="export"){const T=e.out;T||(f("--out <path> is required"),process.exit(1));const I=y(R,"wyrm_cli_export_temp.db");try{const U=j.getDatabase();g(I)&&m(I),U.prepare("VACUUM INTO ?").run(I);const K=n(I),F=s(32),J=s(16),Re=t(v,F,6e5,32,"sha256"),se=r("aes-256-gcm",Re,J),Ee=Buffer.concat([se.update(K),se.final()]),xe=se.getAuthTag(),Te=Buffer.from("WYRM"),le=Buffer.alloc(1);le.writeUInt8(1,0);const de=Buffer.concat([Te,le,F,J,xe,Ee]);d(T,de);try{u(T,384)}catch{}try{m(I)}catch{}const De=(de.length/(1024*1024)).toFixed(2);b(`Exported to ${T} (${De} MB)`)}catch(U){try{g(I)&&m(I)}catch{}f(`Export failed: ${U}`)}j.close();return}const E=e.from;E||(f("--from <path> is required"),process.exit(1));const k=n(E);k.subarray(0,4).toString("ascii")!=="WYRM"&&(f("Invalid Wyrm snapshot file."),process.exit(1));const L=k.readUInt8(4);L!==1&&(f(`Unsupported snapshot version: ${L}`),process.exit(1));const W=k.subarray(5,37),ve=k.subarray(37,53),ke=k.subarray(53,69),je=k.subarray(69),Se=t(v,W,6e5,32,"sha256"),X=o("aes-256-gcm",Se,ve);X.setAuthTag(ke);let ee;try{ee=Buffer.concat([X.update(je),X.final()])}catch{f("Decryption failed \u2014 wrong passphrase or corrupted file."),process.exit(1)}if(i==="preview"){const T=y(R,"wyrm_cli_preview_temp.db");g(T)&&m(T),d(T,ee);try{const I=new w(T,{readonly:!0}),U=["projects","sessions","ground_truths","memory_artifacts","quests"];S("Snapshot Preview");const K=[];for(const F of U)try{const J=I.prepare(`SELECT COUNT(*) as n FROM ${F}`).get();K.push([F,String(J.n)])}catch{K.push([F,"?"])}console.log(P(["Table","Count"],K)),I.close()}catch(I){f(`Preview failed: ${I}`)}try{g(T)&&m(T)}catch{}j.close();return}const V=j.getDatabasePath(),ae=Q({input:process.stdin,output:process.stdout}),Ce=await new Promise(T=>{ae.question("This will REPLACE your current database. Type CONFIRM to proceed: ",T)});if(ae.close(),Ce.trim()!=="CONFIRM"){console.log(p.dim("Aborted.")),j.close();return}const _e=new Date().toISOString().replace(/[:.]/g,"-"),te=`${V}.backup.${_e}`;c(V,te),b(`Backed up to ${te}`);const oe=y(R,"wyrm_cli_restore_temp.db");d(oe,ee),j.getDatabase().close(),c(oe,V);for(const T of["-wal","-shm"])try{g(V+T)&&m(V+T)}catch{}try{m(oe)}catch{}b(`Restored from ${E}. Backup at ${te}`)}async function dt(l){const{flags:a}=_(l),e=a.project,i=a.path,s=Z(a["min-confidence"],.3),t=D(a["older-than"],90),r=a["no-dry-run"]===!0,o=a.yes===!0,n=C(),d=n.getDatabase();let c=null;if(i||e){const y=i?n.getProject(i):x(n,e);y||(f(`Project not found: ${i??e}`),n.close(),process.exit(1)),c=y.id}const m=new G(d),{candidates:g}=m.pruneStale({projectId:c,minConfidence:s,olderThanDays:t,dryRun:!0});if(S(`Prune Candidates${r?" (LIVE DELETE)":" (dry-run)"}`),g.length===0){console.log(p.dim(" No artifacts match prune criteria.")),n.close();return}const u=g.map(y=>[String(y.id),y.kind,y.problem.slice(0,60),(y.confidence*100).toFixed(0)+"%",y.last_accessed_at??"never"]);if(console.log(P(["ID","Kind","Problem","Conf","Last Accessed"],u)),console.log(`
68
- Total: ${g.length} candidate(s)`),!r){console.log(p.dim(`
69
- This is a dry run. Use --no-dry-run to delete (confirm each ID).`)),n.close();return}if(!o){const y=Q({input:process.stdin,output:process.stdout}),w=await new Promise(v=>{y.question(`
70
- Delete these ${g.length} artifact(s)? Type CONFIRM to proceed: `,v)});if(y.close(),w.trim()!=="CONFIRM"){console.log(p.dim("Aborted.")),n.close();return}}const h=m.deleteArtifacts(g.map(y=>y.id));b(`Deleted ${h} artifact(s).`),n.close()}async function pt(l){const{positional:a,flags:e}=_(l),i=a[0]||"list",s=C();try{if(i==="list"||i==="ls"){const t=he(s);if(t.length===0){S("Connectors"),console.log(`${N.dim} none configured. Add one with: wyrm connector add --name <n> --url <bridge-url> --workspace <w>${N.reset}`);return}S("Connectors");const r=t.map(o=>[o.name,o.source,o.enabled?"on":"off",o.workspace,ht(o.baseUrl),o.allowlist.length?`${o.allowlist.length} chats`:"all"]);console.log(P(["Name","Source","Enabled","Workspace","Bridge","Allowlist"],r));return}if(i==="add"){const t=A(e.name),r=A(e.url),o=A(e.workspace);if(!t||!r||!o){f("usage: wyrm connector add --name <n> --url <bridge-url> --workspace <w> [--allowlist a,b] [--token T] [--disabled]"),process.exitCode=1;return}const n={name:t,source:"bridge",enabled:!e.disabled,baseUrl:r,workspace:o,allowlist:A(e.allowlist)?A(e.allowlist).split(",").map(d=>d.trim()).filter(Boolean):[],...A(e.token)?{authToken:A(e.token)}:{}};qe(s,n),b(`Connector "${t}" saved (source=bridge, workspace=${o}). Token, if any, stored without being printed.`),console.log(`${N.dim} Tip: prefer the env var WYRM_CONNECTOR_TOKEN_${t.toUpperCase().replace(/[^A-Z0-9]/g,"_")} over --token.${N.reset}`);return}if(i==="sync"){const t=a[1]||A(e.name);if(t){const o=he(s).find(d=>d.name===t);if(!o){f(`Connector not found: ${t}`),process.exitCode=1;return}const n=await Ye(s,o);b(`${n.source}: fetched ${n.fetched}, ingested ${n.ingested}, skipped ${n.skipped} -> ${n.workspace}`);return}const r=await Fe(s);if(r.length===0){console.log(`${N.dim} no enabled connectors.${N.reset}`);return}for(const o of r)"error"in o?f(`${o.name}: ${o.error}`):b(`${o.source}: fetched ${o.fetched}, ingested ${o.ingested}, skipped ${o.skipped} -> ${o.workspace}`);return}f(`Unknown connector subcommand: ${i} (use list | add | sync)`),process.exitCode=1}finally{s.close()}}function we(){return B(0,"utf-8").trim()}async function ut(){const{initializeLicense:l,getLicenseInfo:a,getTier:e}=await import("./license.js");l();const i=a();S("Wyrm License");const s=[["Tier",e()],["Status",i.valid?"valid":"free tier (no license key)"]];i.valid&&i.key&&(s.push(["Key",i.key]),s.push(["Issued to",i.issuedTo??"unknown"]),s.push(["Expires",i.expiresAt?new Date(i.expiresAt).toLocaleDateString():"never"])),s.push(["Features",i.features.join(", ")||"(free)"]),console.log(P(["Field","Value"],s)),i.valid||console.log(p.dim(`
71
- Activate with: wyrm login (free) \xB7 or: wyrm activate <license.json | key>`)),console.log(p.dim(`
72
- \xA9 2026 Ghost Protocol (Pvt) Ltd \xB7 Proprietary \xB7 https://wyrm.ghosts.lk`)),console.log(p.dim(" Licensed under the Wyrm Terms of Service. No open-source license is granted."))}async function mt(){const l=(process.env.WYRM_ACCOUNT_URL??"https://account.ghosts.lk").replace(/\/$/,""),a=(()=>{try{return M().version??"unknown"}catch{return"unknown"}})();let e;try{const c=await fetch(`${l}/api/v1/cli/auth/start`,{method:"POST",headers:{"x-wyrm-version":a}});if(!c.ok)throw new Error(`HTTP ${c.status}`);e=await c.json()}catch(c){f(`Couldn't reach ${l} (${c instanceof Error?c.message:"network error"}).`),process.exitCode=1;return}const i=e.verification_uri_complete||e.verification_uri||`${l}/cli`;console.log(`
73
- ${p.cyan("Sign in to activate Wyrm (free):")}`),console.log(` 1. Open ${p.cyan(i)}`),console.log(` 2. Approve the code ${p.cyan(e.user_code)}`),console.log(p.dim(`
74
- Waiting for approval\u2026 (Ctrl-C to cancel)`));const s=(e.interval??3)*1e3,t=Date.now()+(e.expires_in??600)*1e3;let r="";for(;Date.now()<t;){await new Promise(c=>{setTimeout(c,s)});try{const m=await(await fetch(`${l}/api/v1/cli/auth/poll`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:e.device_code})})).json();if(m.status==="approved"&&m.token){r=m.token;break}if(m.status==="denied"||m.error==="expired"){f("Login was denied or the code expired. Run `wyrm login` again."),process.exitCode=1;return}}catch{}}if(!r){f("Login timed out. Run `wyrm login` again."),process.exitCode=1;return}let o;try{const c=await fetch(`${l}/api/v1/license/free`,{method:"POST",headers:{authorization:`Bearer ${r}`,"x-wyrm-version":a}});if(!c.ok){const m=await c.json().catch(()=>({}));f(`Activation failed (${c.status}): ${m.hint||m.error||"unknown error"}`),process.exitCode=1;return}o=JSON.stringify(await c.json())}catch(c){f(`Activation request failed (${c instanceof Error?c.message:"network error"}).`),process.exitCode=1;return}const{activateLicense:n}=await import("./license.js"),d=n(o);d.valid?(b(`Signed in & activated \u2014 ${d.tier} tier (expires ${d.expiresAt??"never"}).`),console.log(p.dim(" Restart the Wyrm MCP server / daemon to apply."))):(f(`Activation failed: ${d.error??"unknown error"}`),process.exitCode=1)}async function ft(l){const{positional:a}=_(l),e=a[0];let i;e&&H(e)?i=B(e,"utf-8"):e?i=e:process.stdin.isTTY?(f("Usage: wyrm activate <license.json path | license JSON> (or pipe the JSON on stdin)"),process.exit(1)):i=we();const{activateLicense:s}=await import("./license.js");try{const t=s(i);t.valid?(b(`License activated \u2014 ${t.tier} tier (${t.features.join(", ")})`),console.log(p.dim(" Restart Wyrm (MCP server / daemon) to apply all features."))):(f(`License activation failed: ${t.error??"unknown error"}`),process.exitCode=1)}catch{f("Invalid license format. Please verify your license key."),process.exitCode=1}}async function gt(l){const{flags:a}=_(l),{runMaintenance:e}=await import("./maintenance.js"),{FailurePatterns:i}=await import("./failure-patterns.js"),{SessionSeen:s}=await import("./session-seen.js"),{AgentPresence:t}=await import("./presence.js"),r=C();try{const o=r.getDatabase(),n=D(a["archive-days"],0),d=e({db:r,sessionSeen:new s(o),failures:new i(o),presence:new t(o)},{vacuum:a.vacuum===!0,archiveDays:n>0?n:void 0});S("Maintenance complete");for(const c of d.lines)console.log(` - ${c}`);console.log(p.dim(`
75
- Database size: ${d.dbSize}`))}finally{r.close()}}async function yt(l){const{positional:a,flags:e}=_(l),i=a[0]??"status",{createVectorStore:s}=await import("./vectors.js"),r={provider:e.provider??process.env.WYRM_VECTOR_PROVIDER??"auto",model:e.model,apiKey:e["api-key"]??process.env.OPENAI_API_KEY,ollamaUrl:e["ollama-url"]};if(i==="setup"){const{createProvider:n}=await import("./providers/embedding-provider.js"),d=n(r);if(!await d.isReady()&&r.provider!=="none"){f(`Provider not ready: ${d.name}. Check the configuration and try again.`),process.exitCode=1;return}b(`Vector provider verified: ${d.name} (model ${d.model}, ${d.dimensions}d)`),console.log(p.dim(" The MCP server reads WYRM_VECTOR_PROVIDER (and provider-specific env) at boot \u2014")),console.log(p.dim(` set WYRM_VECTOR_PROVIDER=${d.name==="none"?"none":r.provider} in the server env, then: wyrm index rebuild`));return}const o=C();try{const n=o.getDatabase(),d=s(r,n);if(i==="status"){const c=d.getStats();S("Vector index");const m=[["Provider",c.provider],["Model",c.model],["Vectors",String(c.total)],...Object.entries(c.byType).map(([g,u])=>[` ${g}`,String(u)])];console.log(P(["Field","Value"],m));return}if(i==="rebuild"){const{reindexProjects:c}=await import("./reindex.js"),m=e["dry-run"]===!0,g=e.project;let u;if(g){const w=o.getProject(g)??x(o,g);if(!w){f(`Project not found: ${g}`),process.exitCode=1;return}u=[w.id]}else u=o.getAllProjects(1e3).map(w=>w.id);const{indexed:h,skipped:y}=await c(n,d,u,{dryRun:m,onError:(w,v)=>f(`${w}: ${JSON.stringify(v)}`)});b(`Reindex ${m?"(dry run) ":""}\u2014 ${u.length} project(s), ${h} indexed, ${y} skipped`);return}f("Usage: wyrm index <setup|rebuild|status> [--provider auto|local|ollama|openai|none] [--model M] [--project P] [--dry-run]"),process.exitCode=1}finally{o.close()}}function A(l){return typeof l=="string"?l:""}function ht(l){try{return new URL(l).host}catch{return l}}async function wt(l){const{flags:a}=_(l),{getUpdateStatus:e}=await import("./version-check.js"),i=M().version??"0.0.0",s=C();let t;try{t=await e(s.getDatabase(),i,{force:a.force===!0||a.check===!0})}finally{s.close()}if(S("Wyrm update"),console.log(P(["Field","Value"],[["Current",t.current],["Latest",t.latest??"unknown (offline?)"],["Update available",t.updateAvailable?"yes":"no"],["Checked",`${t.checkedAt} (${t.source})`]])),a.check===!0)return;if(!t.updateAvailable&&a.force!==!0){console.log(p.dim(`
76
- Already up to date. (Use --force to reinstall anyway.)`));return}console.log(p.dim(`
65
+ `).all();if(o.length===0){console.log(d.dim(` No artifacts pending review${t?` for ${t}`:""}.`)),i.close();return}k(`Review Queue (${o.length} items)`);const n=Q({input:process.stdin,output:process.stdout}),p=a=>new Promise(u=>{n.question(a,u)});for(const a of o){console.log(`
66
+ ${d.bold(`[${a.kind}] #${a.id}`)}`),console.log(d.dim("\u2500".repeat(60))),console.log(a.problem.slice(0,300)),console.log(d.dim("\u2500".repeat(60)));const g=(await p(`${d.cyan("[a]")}pprove / ${d.red("[r]")}eject / ${d.yellow("[s]")}kip? `)).trim().toLowerCase();g==="a"?(r.prepare("UPDATE memory_artifacts SET needs_review = 0, updated_at = datetime('now') WHERE id = ?").run(a.id),b(`Approved #${a.id}`)):g==="r"?(r.prepare("DELETE FROM memory_artifacts WHERE id = ?").run(a.id),console.log(`${Y.cross} Rejected #${a.id}`)):console.log(d.dim(` Skipped #${a.id}`))}n.close(),i.close(),console.log(`
67
+ Review complete.`)}async function pt(l){const{positional:c,flags:t}=C(l),i=c[0];(!i||!["export","import","preview"].includes(i))&&(m("Usage: wyrm sync export --out <path> | wyrm sync import --from <path> | wyrm sync preview --from <path>"),process.exit(1));const{randomBytes:r,pbkdf2Sync:e,createCipheriv:s,createDecipheriv:o}=await import("crypto"),{readFileSync:n,writeFileSync:p,copyFileSync:a,unlinkSync:u,existsSync:g,chmodSync:f}=await import("fs"),{homedir:y}=await import("os"),{join:h}=await import("path"),w=(await import("better-sqlite3")).default;let $=process.env.WYRM_SYNC_PASSPHRASE??"";if(!$){const T=Q({input:process.stdin,output:process.stdout});$=await new Promise(P=>{process.stdout.write("Passphrase: "),process.stdin.isTTY&&process.stdin.setRawMode?.(!0),T.question("",U=>{process.stdin.isTTY&&process.stdin.setRawMode?.(!1),console.log(""),T.close(),P(U)})})}$||(m("Passphrase is required. Set WYRM_SYNC_PASSPHRASE or enter interactively."),process.exit(1));const E=h(y(),".wyrm"),_=j();if(i==="export"){const T=t.out;T||(m("--out <path> is required"),process.exit(1));const P=h(E,"wyrm_cli_export_temp.db");try{const U=_.getDatabase();g(P)&&u(P),U.prepare("VACUUM INTO ?").run(P);const K=n(P),H=r(32),J=r(16),Ee=e($,H,6e5,32,"sha256"),se=s("aes-256-gcm",Ee,J),Re=Buffer.concat([se.update(K),se.final()]),xe=se.getAuthTag(),Te=Buffer.from("WYRM"),le=Buffer.alloc(1);le.writeUInt8(1,0);const de=Buffer.concat([Te,le,H,J,xe,Re]);p(T,de);try{f(T,384)}catch{}try{u(P)}catch{}const De=(de.length/(1024*1024)).toFixed(2);b(`Exported to ${T} (${De} MB)`)}catch(U){try{g(P)&&u(P)}catch{}m(`Export failed: ${U}`)}_.close();return}const R=t.from;R||(m("--from <path> is required"),process.exit(1));const S=n(R);S.subarray(0,4).toString("ascii")!=="WYRM"&&(m("Invalid Wyrm snapshot file."),process.exit(1));const L=S.readUInt8(4);L!==1&&(m(`Unsupported snapshot version: ${L}`),process.exit(1));const W=S.subarray(5,37),ve=S.subarray(37,53),ke=S.subarray(53,69),Se=S.subarray(69),_e=e($,W,6e5,32,"sha256"),Z=o("aes-256-gcm",_e,ve);Z.setAuthTag(ke);let ee;try{ee=Buffer.concat([Z.update(Se),Z.final()])}catch{m("Decryption failed \u2014 wrong passphrase or corrupted file."),process.exit(1)}if(i==="preview"){const T=h(E,"wyrm_cli_preview_temp.db");g(T)&&u(T),p(T,ee);try{const P=new w(T,{readonly:!0}),U=["projects","sessions","ground_truths","memory_artifacts","quests"];k("Snapshot Preview");const K=[];for(const H of U)try{const J=P.prepare(`SELECT COUNT(*) as n FROM ${H}`).get();K.push([H,String(J.n)])}catch{K.push([H,"?"])}console.log(D(["Table","Count"],K)),P.close()}catch(P){m(`Preview failed: ${P}`)}try{g(T)&&u(T)}catch{}_.close();return}const B=_.getDatabasePath(),ce=Q({input:process.stdin,output:process.stdout}),je=await new Promise(T=>{ce.question("This will REPLACE your current database. Type CONFIRM to proceed: ",T)});if(ce.close(),je.trim()!=="CONFIRM"){console.log(d.dim("Aborted.")),_.close();return}const Ce=new Date().toISOString().replace(/[:.]/g,"-"),te=`${B}.backup.${Ce}`;a(B,te),b(`Backed up to ${te}`);const oe=h(E,"wyrm_cli_restore_temp.db");p(oe,ee),_.getDatabase().close(),a(oe,B);for(const T of["-wal","-shm"])try{g(B+T)&&u(B+T)}catch{}try{u(oe)}catch{}b(`Restored from ${R}. Backup at ${te}`)}async function ut(l){const{flags:c}=C(l),t=c.project,i=c.path,r=X(c["min-confidence"],.3),e=I(c["older-than"],90),s=c["no-dry-run"]===!0,o=c.yes===!0,n=j(),p=n.getDatabase();let a=null;if(i||t){const h=i?n.getProject(i):x(n,t);h||(m(`Project not found: ${i??t}`),n.close(),process.exit(1)),a=h.id}const u=new G(p),{candidates:g}=u.pruneStale({projectId:a,minConfidence:r,olderThanDays:e,dryRun:!0});if(k(`Prune Candidates${s?" (LIVE DELETE)":" (dry-run)"}`),g.length===0){console.log(d.dim(" No artifacts match prune criteria.")),n.close();return}const f=g.map(h=>[String(h.id),h.kind,h.problem.slice(0,60),(h.confidence*100).toFixed(0)+"%",h.last_accessed_at??"never"]);if(console.log(D(["ID","Kind","Problem","Conf","Last Accessed"],f)),console.log(`
68
+ Total: ${g.length} candidate(s)`),!s){console.log(d.dim(`
69
+ This is a dry run. Use --no-dry-run to delete (confirm each ID).`)),n.close();return}if(!o){const h=Q({input:process.stdin,output:process.stdout}),w=await new Promise($=>{h.question(`
70
+ Delete these ${g.length} artifact(s)? Type CONFIRM to proceed: `,$)});if(h.close(),w.trim()!=="CONFIRM"){console.log(d.dim("Aborted.")),n.close();return}}const y=u.deleteArtifacts(g.map(h=>h.id));b(`Deleted ${y} artifact(s).`),n.close()}async function mt(l){const{positional:c,flags:t}=C(l),i=c[0]||"list",r=j();try{if(i==="list"||i==="ls"){const e=he(r);if(e.length===0){k("Connectors"),console.log(`${N.dim} none configured. Add one with: wyrm connector add --name <n> --url <bridge-url> --workspace <w>${N.reset}`);return}k("Connectors");const s=e.map(o=>[o.name,o.source,o.enabled?"on":"off",o.workspace,kt(o.baseUrl),o.allowlist.length?`${o.allowlist.length} chats`:"all"]);console.log(D(["Name","Source","Enabled","Workspace","Bridge","Allowlist"],s));return}if(i==="add"){const e=A(t.name),s=A(t.url),o=A(t.workspace);if(!e||!s||!o){m("usage: wyrm connector add --name <n> --url <bridge-url> --workspace <w> [--allowlist a,b] [--token T] [--disabled]"),process.exitCode=1;return}const n={name:e,source:"bridge",enabled:!t.disabled,baseUrl:s,workspace:o,allowlist:A(t.allowlist)?A(t.allowlist).split(",").map(p=>p.trim()).filter(Boolean):[],...A(t.token)?{authToken:A(t.token)}:{}};Ye(r,n),b(`Connector "${e}" saved (source=bridge, workspace=${o}). Token, if any, stored without being printed.`),console.log(`${N.dim} Tip: prefer the env var WYRM_CONNECTOR_TOKEN_${e.toUpperCase().replace(/[^A-Z0-9]/g,"_")} over --token.${N.reset}`);return}if(i==="sync"){const e=c[1]||A(t.name);if(e){const o=he(r).find(p=>p.name===e);if(!o){m(`Connector not found: ${e}`),process.exitCode=1;return}const n=await He(r,o);b(`${n.source}: fetched ${n.fetched}, ingested ${n.ingested}, skipped ${n.skipped} -> ${n.workspace}`);return}const s=await Ve(r);if(s.length===0){console.log(`${N.dim} no enabled connectors.${N.reset}`);return}for(const o of s)"error"in o?m(`${o.name}: ${o.error}`):b(`${o.source}: fetched ${o.fetched}, ingested ${o.ingested}, skipped ${o.skipped} -> ${o.workspace}`);return}m(`Unknown connector subcommand: ${i} (use list | add | sync)`),process.exitCode=1}finally{r.close()}}function we(){return V(0,"utf-8").trim()}async function ft(){const{initializeLicense:l,getLicenseInfo:c,getTier:t}=await import("./license.js");l();const i=c();k("Wyrm License");const r=[["Tier",t()],["Status",i.valid?"valid":"free tier (no license key)"]];i.valid&&i.key&&(r.push(["Key",i.key]),r.push(["Issued to",i.issuedTo??"unknown"]),r.push(["Expires",i.expiresAt?new Date(i.expiresAt).toLocaleDateString():"never"])),r.push(["Features",i.features.join(", ")||"(free)"]),console.log(D(["Field","Value"],r)),i.valid||console.log(d.dim(`
71
+ Activate with: wyrm login (free) \xB7 or: wyrm activate <license.json | key>`)),console.log(d.dim(`
72
+ \xA9 2026 Ghost Protocol (Pvt) Ltd \xB7 Proprietary \xB7 https://wyrm.ghosts.lk`)),console.log(d.dim(" Licensed under the Wyrm Terms of Service. No open-source license is granted."))}async function gt(){const l=(process.env.WYRM_ACCOUNT_URL??"https://account.ghosts.lk").replace(/\/$/,""),c=(()=>{try{return M().version??"unknown"}catch{return"unknown"}})();let t;try{const a=await fetch(`${l}/api/v1/cli/auth/start`,{method:"POST",headers:{"x-wyrm-version":c}});if(!a.ok)throw new Error(`HTTP ${a.status}`);t=await a.json()}catch(a){m(`Couldn't reach ${l} (${a instanceof Error?a.message:"network error"}).`),process.exitCode=1;return}const i=t.verification_uri_complete||t.verification_uri||`${l}/cli`;console.log(`
73
+ ${d.cyan("Sign in to activate Wyrm (free):")}`),console.log(` 1. Open ${d.cyan(i)}`),console.log(` 2. Approve the code ${d.cyan(t.user_code)}`),console.log(d.dim(`
74
+ Waiting for approval\u2026 (Ctrl-C to cancel)`));const r=(t.interval??3)*1e3,e=Date.now()+(t.expires_in??600)*1e3;let s="";for(;Date.now()<e;){await new Promise(a=>{setTimeout(a,r)});try{const u=await(await fetch(`${l}/api/v1/cli/auth/poll`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_code:t.device_code})})).json();if(u.status==="approved"&&u.token){s=u.token;break}if(u.status==="denied"||u.error==="expired"){m("Login was denied or the code expired. Run `wyrm login` again."),process.exitCode=1;return}}catch{}}if(!s){m("Login timed out. Run `wyrm login` again."),process.exitCode=1;return}let o;try{const a=await fetch(`${l}/api/v1/license/free`,{method:"POST",headers:{authorization:`Bearer ${s}`,"x-wyrm-version":c}});if(!a.ok){const u=await a.json().catch(()=>({}));m(`Activation failed (${a.status}): ${u.hint||u.error||"unknown error"}`),process.exitCode=1;return}o=JSON.stringify(await a.json())}catch(a){m(`Activation request failed (${a instanceof Error?a.message:"network error"}).`),process.exitCode=1;return}const{activateLicense:n}=await import("./license.js"),p=n(o);p.valid?(b(`Signed in & activated \u2014 ${p.tier} tier (expires ${p.expiresAt??"never"}).`),console.log(d.dim(" Restart the Wyrm MCP server / daemon to apply."))):(m(`Activation failed: ${p.error??"unknown error"}`),process.exitCode=1)}async function yt(l){const{positional:c}=C(l),t=c[0];let i;t&&q(t)?i=V(t,"utf-8"):t?i=t:process.stdin.isTTY?(m("Usage: wyrm activate <license.json path | license JSON> (or pipe the JSON on stdin)"),process.exit(1)):i=we();const{activateLicense:r}=await import("./license.js");try{const e=r(i);e.valid?(b(`License activated \u2014 ${e.tier} tier (${e.features.join(", ")})`),console.log(d.dim(" Restart Wyrm (MCP server / daemon) to apply all features."))):(m(`License activation failed: ${e.error??"unknown error"}`),process.exitCode=1)}catch{m("Invalid license format. Please verify your license key."),process.exitCode=1}}async function ht(l){const{flags:c}=C(l),{runMaintenance:t}=await import("./maintenance.js"),{FailurePatterns:i}=await import("./failure-patterns.js"),{SessionSeen:r}=await import("./session-seen.js"),{AgentPresence:e}=await import("./presence.js"),s=j();try{const o=s.getDatabase(),n=I(c["archive-days"],0),p=t({db:s,sessionSeen:new r(o),failures:new i(o),presence:new e(o)},{vacuum:c.vacuum===!0,archiveDays:n>0?n:void 0});k("Maintenance complete");for(const a of p.lines)console.log(` - ${a}`);console.log(d.dim(`
75
+ Database size: ${p.dbSize}`))}finally{s.close()}}async function wt(l){const{resolveEmbeddingState:c}=await import("./providers/embedding-provider.js"),t=j();let i=0;const r=(s,o)=>{console.log(` ${d.green("\u2714")} ${s} \u2014 ${d.dim(o)}`)},e=(s,o,n)=>{i++,console.log(` ${d.red("\u2716")} ${s} \u2014 ${o}`),console.log(` ${d.yellow("fix:")} ${n}`)};try{const s=t.getDatabase();k("wyrm doctor");const o=c();o.reason===""&&o.resolved!=="local"?r("Embedding provider",`${o.resolved} (${o.model})${o.egressHost?` \xB7 egress: ${o.egressHost}`:" \xB7 local"}`):o.resolved==="local"?e("Embedding provider","local-hash (hash-384) is NOT semantic \u2014 test-only vectors",o.fix||"use NVIDIA NIM: set WYRM_VECTOR_PROVIDER=nim + NVIDIA_API_KEY"):o.reason==="ollama_deprecated"?e("Embedding provider","ollama (deprecated \u2014 leaves in the next major)",o.fix):e("Embedding provider",`none (${o.reason})`,o.fix);const n=s.prepare("SELECT COUNT(*) AS n FROM memory_artifacts").get().n;let p=0;try{p=s.prepare("SELECT COUNT(*) AS n FROM vectors").get().n}catch{}o.resolved==="none"||o.resolved==="local"?e("Vector index",`${p} vector(s) / ${n} memories \u2014 recall is FTS5 keyword-only (~59.9% vs 72.2% hybrid recall@10)`,o.fix||"enable a provider, then: wyrm index rebuild"):p===0&&n>0?e("Vector index",`provider '${o.resolved}' is configured but 0 of ${n} memories are indexed`,"wyrm index rebuild"):r("Vector index",`${p} vector(s) over ${n} memories`);try{const g=s.prepare("SELECT COUNT(*) AS n FROM memory_artifacts_fts").get().n;g===n?r("FTS index",`${g}/${n} rows in sync`):e("FTS index",`${g} FTS rows vs ${n} 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 a=s.prepare("SELECT COUNT(*) AS n FROM failure_patterns WHERE resolved = 0").get().n;r("Failure firewall",`${a} unresolved pattern(s) \xB7 matching = exact signature + FTS5 fuzzy (no vector tier in this build)`);const u=s.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE needs_review = 1").get().n;u>0?e("Review queue",`${u} memor${u===1?"y":"ies"} invisible to recall until approved`,"wyrm review"):r("Review queue","empty");try{const g=s.prepare("SELECT MAX(version) AS v FROM schema_versions").get().v;r("Schema",`migration v${g??0}`)}catch{e("Schema","schema_versions unreadable","wyrm maintenance")}console.log(""),i===0?b("All checks passed \u2014 nothing is silently off."):(m(`${i} check(s) DEGRADED \u2014 the fixes above are exact.`),process.exitCode=1)}finally{t.close()}}async function bt(l){const{positional:c,flags:t}=C(l),i=c[0]??"list",r=j();try{const e=r.getDatabase();if(i==="list"){const s=e.prepare("SELECT id, scope, target, occurrences, last_seen FROM failure_patterns WHERE resolved = 0 ORDER BY last_seen DESC LIMIT 25").all();if(k("Unresolved failures"),!s.length){console.log(d.dim(" none \u2014 the firewall has nothing active."));return}console.log(D(["ID","Scope","Target","Seen","Last seen"],s.map(o=>[String(o.id),o.scope,o.target.slice(0,48),String(o.occurrences),o.last_seen]))),console.log(d.dim(`
76
+ resolve one: wyrm failure resolve <id>`));return}if(i==="resolve"){const s=Number(c[1]);if(!Number.isInteger(s)||s<=0){m('Usage: wyrm failure resolve <id> [--note "root cause fixed by ..."]'),process.exitCode=1;return}const o=t.note??"";(e.prepare("UPDATE failure_patterns SET resolved = 1, resolution_note = ?, last_seen = datetime('now') WHERE id = ? AND resolved = 0").run(o||"resolved via wyrm failure resolve",s).changes??0)>0?b(`Failure #${s} resolved \u2014 it will no longer flag.`):(m(`No unresolved failure #${s}.`),process.exitCode=1);return}m("Usage: wyrm failure <list|resolve <id> [--note N]>"),process.exitCode=1}finally{r.close()}}async function $t(l){const{positional:c,flags:t}=C(l),i=c[0]??"list",r=j();try{if(i==="add"){const e=c[1]??process.cwd(),s=Ie(e);if(!q(s)){m(`Path does not exist: ${s}`),process.exitCode=1;return}const o=t.name??Pe(s),n=r.registerProject(o,s);b(`Project #${n.id} '${n.name}' registered at ${n.path}`);return}if(i==="list"){const e=r.getAllProjects(50);k("Projects"),console.log(D(["ID","Name","Path"],e.map(s=>[String(s.id),s.name,s.path])));return}m("Usage: wyrm project <add [path] [--name N] | list>"),process.exitCode=1}finally{r.close()}}async function vt(l){const{positional:c,flags:t}=C(l),i="Usage: wyrm index <setup|rebuild|status> [--provider auto|local|nim|openai|none] [--model M] [--project P] [--dry-run]";if(t.help===!0){console.log(i);return}const r=c[0]??"status",{createVectorStore:e}=await import("./vectors.js"),o={provider:t.provider??process.env.WYRM_VECTOR_PROVIDER??"auto",model:t.model,apiKey:t["api-key"]??process.env.OPENAI_API_KEY,ollamaUrl:t["ollama-url"]};if(r==="setup"){const{createProvider:p}=await import("./providers/embedding-provider.js"),a=p(o);if(!await a.isReady()&&o.provider!=="none"){m(`Provider not ready: ${a.name}. Check the configuration and try again.`),process.exitCode=1;return}b(`Vector provider verified: ${a.name} (model ${a.model}, ${a.dimensions}d)`),console.log(d.dim(" The MCP server reads WYRM_VECTOR_PROVIDER (and provider-specific env) at boot \u2014")),console.log(d.dim(` set WYRM_VECTOR_PROVIDER=${a.name==="none"?"none":o.provider} in the server env, then: wyrm index rebuild`));return}const n=j();try{const p=n.getDatabase(),a=e(o,p);if(r==="status"){const u=a.getStats();k("Vector index");const g=[["Provider",u.provider],["Model",u.model],["Vectors",String(u.total)],...Object.entries(u.byType).map(([f,y])=>[` ${f}`,String(y)])];console.log(D(["Field","Value"],g));return}if(r==="rebuild"){const{reindexProjects:u}=await import("./reindex.js"),g=t["dry-run"]===!0,f=t.project;let y;if(f){const $=n.getProject(f)??x(n,f);if(!$){m(`Project not found: ${f}`),process.exitCode=1;return}y=[$.id]}else y=n.getAllProjects(1e3).map($=>$.id);const{indexed:h,skipped:w}=await u(p,a,y,{dryRun:g,onError:($,E)=>m(`${$}: ${JSON.stringify(E)}`)});b(`Reindex ${g?"(dry run) ":""}\u2014 ${y.length} project(s), ${h} indexed, ${w} skipped`);return}m(i),process.exitCode=1}finally{n.close()}}function A(l){return typeof l=="string"?l:""}function kt(l){try{return new URL(l).host}catch{return l}}async function St(l){const{flags:c}=C(l),{getUpdateStatus:t}=await import("./version-check.js"),i=M().version??"0.0.0",r=j();let e;try{e=await t(r.getDatabase(),i,{force:c.force===!0||c.check===!0})}finally{r.close()}if(k("Wyrm update"),console.log(D(["Field","Value"],[["Current",e.current],["Latest",e.latest??"unknown (offline?)"],["Update available",e.updateAvailable?"yes":"no"],["Checked",`${e.checkedAt} (${e.source})`]])),c.check===!0)return;if(!e.updateAvailable&&c.force!==!0){console.log(d.dim(`
77
+ Already up to date. (Use --force to reinstall anyway.)`));return}console.log(d.dim(`
77
78
  Running: npm install -g wyrm-mcp@latest
78
- `));const r=z("npm",["install","-g","wyrm-mcp@latest"],{stdio:"inherit",shell:!1});r.status===0?b("Updated. Restart your MCP clients to pick up the new binary."):(f(`npm install exited with ${r.status??"unknown"}`),process.exitCode=r.status??1)}async function bt(l){const{positional:a,flags:e}=_(l),i=a[0],s=e.project??process.cwd();if(i==="inject"){const{injectSystemPrompt:t}=await import("./autoconfig.js"),r=typeof e.clients=="string"?e.clients.split(",").map(n=>n.trim()).filter(Boolean):[],o=t(s,r);S("System prompt injection");for(const n of o.injected)console.log(` + ${n}`);for(const n of o.skipped)console.log(p.dim(` o skipped (unknown client): ${n}`));for(const n of o.errors)f(n);o.injected.length>0&&b("AI clients in this project will now call wyrm_session_prime at conversation start."),o.errors.length>0&&(process.exitCode=1);return}if(i==="migrate"){const{migrateProject:t,renderMigrationReport:r}=await import("./migrate-prompt.js"),{WYRM_INJECT_BLOCK:o}=await import("./autoconfig.js"),n=e.apply===!0,d=t({projectPath:s,newBlock:o,apply:n});console.log(r(d,n));return}f("Usage: wyrm prompt inject [--project <path>] [--clients copilot,cursor] | wyrm prompt migrate [--project <path>] [--apply]"),process.exitCode=1}async function $t(l){const{positional:a,flags:e}=_(l);(a[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 s=e.from,t=e.to;(!s||!t)&&(f("--from and --to are required (YYYY-MM-DD)"),process.exit(1));const{HourLedger:r}=await import("./hours.js"),o=C();try{const n=e.project,d=n?x(o,n):null;if(n&&!d){f(`Project not found: ${n}`),process.exitCode=1;return}const c=new r(o.getDatabase()).report({range_start:s,range_end:t,project_id:d?.id,default_session_hours:Z(e["session-hours"],1)});if(e.json===!0){console.log(JSON.stringify(c,null,2));return}if(S(`Hours ${c.range.start} \u2192 ${c.range.end}`),c.by_project.length===0){console.log(p.dim(" No sessions in range."));return}console.log(P(["Project","Sessions","Hours"],c.by_project.map(m=>[m.project_name,String(m.session_count),m.hours.toFixed(2)]))),console.log(`
79
- Total: ${c.total_hours.toFixed(2)}h across ${c.entries.length} session(s)`+(c.estimated_sessions>0?p.dim(` (${c.estimated_sessions} estimated)`):""))}finally{o.close()}}async function vt(l){const{positional:a,flags:e}=_(l),i=a[0]??"generate",s=e.client,t=Z(e.rate,NaN),r=e.from,o=e.to;(i!=="generate"||!s||!Number.isFinite(t)||!r||!o)&&(f('Usage: wyrm invoice generate --client <name> --rate <usd/hour> --from YYYY-MM-DD --to YYYY-MM-DD [--project <name>] [--number INV-X] [--currency USD] [--notes "\u2026"] [--out <path>]'),process.exit(1));const{HourLedger:n}=await import("./hours.js"),d=C();try{const c=e.project,m=c?x(d,c):null;if(c&&!m){f(`Project not found: ${c}`),process.exitCode=1;return}const g=new n(d.getDatabase()).invoice({client_name:s,hourly_rate_usd:t,range_start:r,range_end:o,project_id:m?.id,invoice_number:e.number,currency:e.currency,notes:e.notes,business_name:e["business-name"],business_address:e["business-address"],business_contact:e["business-contact"],client_address:e["client-address"],default_session_hours:Z(e["session-hours"],1)}),u=e.out;if(u){const{writeFileSync:h}=await import("node:fs");h(u,g+`
80
- `,"utf-8"),b(`Invoice written to ${u}`)}else process.stdout.write(g+`
81
- `)}finally{d.close()}}async function kt(l){const{positional:a,flags:e}=_(l),i=a[0]??"status",{AgentDaemon:s}=await import("./agent-daemon.js"),t=C();try{const r=new s(t.getDatabase());switch(i){case"init":case"start":{const o=Math.max(10,Math.min(D(e.interval,600),86400)),n=r.start({interval_seconds:o,max_steps:e["max-steps"]!==void 0&&D(e["max-steps"],0)||void 0,project_path:e.project,verbose:e.verbose===!0});if(!n.ok){f(`Agent init failed: ${n.error}`),process.exitCode=1;return}const d=n.status;b(`Agent ${d.pid!=null&&d.pid!==n.pid?"already running":"started"} \u2014 pid ${d.pid}`),console.log(` Interval: ${o}s \xB7 Active goals: ${d.active_goals} \xB7 Total iterations: ${d.total_iterations}`),console.log(p.dim(` Log: ${d.log_file}`));return}case"status":{const o=r.status();S("Wyrm agent"),console.log(o.running?` RUNNING \u2014 pid ${o.pid}${o.started_at?` (since ${o.started_at})`:""}`:" NOT RUNNING. Start it with: wyrm agent init"),console.log(` Active goals: ${o.active_goals} \xB7 Total iterations: ${o.total_iterations}`),o.last_action&&console.log(` Last action (${o.last_action.ran_at}): ${o.last_action.summary} [${o.last_action.result_status??"?"}]`),e.log===!0&&(console.log(`
82
- === Recent log ===`),console.log(r.recentLog(40)));return}case"stop":{const o=await r.stop({grace_ms:e.grace!==void 0?D(e.grace,3e3):void 0});if(!o.ok){f(`Stop failed: ${o.error}`),process.exitCode=1;return}b(o.was_running?`Agent stopped (was pid ${o.pid}). Goals remain in DB \u2014 wyrm agent init resumes.`:"Agent was not running. (No-op.)");return}case"restart":{const o=await r.restart({interval_seconds:e.interval!==void 0?D(e.interval,600):void 0,max_steps:e["max-steps"]!==void 0&&D(e["max-steps"],0)||void 0,project_path:e.project,verbose:e.verbose===!0});if(!o.ok){f(`Restart failed: ${o.error}`),process.exitCode=1;return}b(`Agent restarted \u2014 pid ${o.status.pid}. Active goals: ${o.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{t.close()}}async function jt(l){if(l.includes("--encrypt")){const{initializeLicense:i,hasFeature:s}=await import("./license.js");if(i(),!s("encryption")){f("Encryption setup requires a Pro license or higher. See: wyrm license"),process.exitCode=1;return}const{getCrypto:t,initializeCrypto:r}=await import("./crypto.js"),o=l.includes("--enable"),n=l.includes("--test");if(o){const c=process.env.WYRM_ENCRYPTION_KEY??(process.stdin.isTTY?"":we());if(!c||c.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}r(c),b("Encryption enabled (AES-256-GCM, key derived via PBKDF2). Store your password safely \u2014 it cannot be recovered.");return}const d=t();if(n){if(!d.isEnabled()){f("Encryption not enabled. Run: wyrm setup --encrypt --enable"),process.exitCode=1;return}const c="Wyrm encryption test "+Date.now();d.decrypt(d.encrypt(c))===c?b("Encryption test PASSED (encrypt \u2192 decrypt roundtrip)."):(f("Encryption test FAILED."),process.exitCode=1);return}S("Encryption status"),console.log(` Enabled: ${d.isEnabled()?"yes \u2014 new data is encrypted at rest":"no"}`),console.log(" Algorithm: AES-256-GCM"),d.isEnabled()||console.log(p.dim(" Enable with: wyrm setup --encrypt --enable (password via WYRM_ENCRYPTION_KEY or stdin)"));return}const a=ne(re(import.meta.url)),e=z(process.execPath,[q(a,"setup.js"),...l],{stdio:"inherit",shell:!1});process.exitCode=e.status??0}async function St(l){const a="https://github.com/Ghosts-Protocol-Pvt-Ltd/wyrm-mcp",i=`- wyrm-mcp: ${M().version??"unknown"}
79
+ `));const s=z("npm",["install","-g","wyrm-mcp@latest"],{stdio:"inherit",shell:!1});s.status===0?b("Updated. Restart your MCP clients to pick up the new binary."):(m(`npm install exited with ${s.status??"unknown"}`),process.exitCode=s.status??1)}async function _t(l){const{positional:c,flags:t}=C(l),i=c[0],r=t.project??process.cwd();if(i==="inject"){const{injectSystemPrompt:e}=await import("./autoconfig.js"),s=typeof t.clients=="string"?t.clients.split(",").map(n=>n.trim()).filter(Boolean):[],o=e(r,s);k("System prompt injection");for(const n of o.injected)console.log(` + ${n}`);for(const n of o.skipped)console.log(d.dim(` o skipped (unknown client): ${n}`));for(const n of o.errors)m(n);o.injected.length>0&&b("AI clients in this project will now call wyrm_session_prime at conversation start."),o.errors.length>0&&(process.exitCode=1);return}if(i==="migrate"){const{migrateProject:e,renderMigrationReport:s}=await import("./migrate-prompt.js"),{WYRM_INJECT_BLOCK:o}=await import("./autoconfig.js"),n=t.apply===!0,p=e({projectPath:r,newBlock:o,apply:n});console.log(s(p,n));return}m("Usage: wyrm prompt inject [--project <path>] [--clients copilot,cursor] | wyrm prompt migrate [--project <path>] [--apply]"),process.exitCode=1}async function jt(l){const{positional:c,flags:t}=C(l);(c[0]??"report")!=="report"&&(m("Usage: wyrm hours report --from YYYY-MM-DD --to YYYY-MM-DD [--project <name>] [--session-hours H] [--json]"),process.exit(1));const r=t.from,e=t.to;(!r||!e)&&(m("--from and --to are required (YYYY-MM-DD)"),process.exit(1));const{HourLedger:s}=await import("./hours.js"),o=j();try{const n=t.project,p=n?x(o,n):null;if(n&&!p){m(`Project not found: ${n}`),process.exitCode=1;return}const a=new s(o.getDatabase()).report({range_start:r,range_end:e,project_id:p?.id,default_session_hours:X(t["session-hours"],1)});if(t.json===!0){console.log(JSON.stringify(a,null,2));return}if(k(`Hours ${a.range.start} \u2192 ${a.range.end}`),a.by_project.length===0){console.log(d.dim(" No sessions in range."));return}console.log(D(["Project","Sessions","Hours"],a.by_project.map(u=>[u.project_name,String(u.session_count),u.hours.toFixed(2)]))),console.log(`
80
+ Total: ${a.total_hours.toFixed(2)}h across ${a.entries.length} session(s)`+(a.estimated_sessions>0?d.dim(` (${a.estimated_sessions} estimated)`):""))}finally{o.close()}}async function Ct(l){const{positional:c,flags:t}=C(l),i=c[0]??"generate",r=t.client,e=X(t.rate,NaN),s=t.from,o=t.to;(i!=="generate"||!r||!Number.isFinite(e)||!s||!o)&&(m('Usage: wyrm invoice generate --client <name> --rate <usd/hour> --from YYYY-MM-DD --to YYYY-MM-DD [--project <name>] [--number INV-X] [--currency USD] [--notes "\u2026"] [--out <path>]'),process.exit(1));const{HourLedger:n}=await import("./hours.js"),p=j();try{const a=t.project,u=a?x(p,a):null;if(a&&!u){m(`Project not found: ${a}`),process.exitCode=1;return}const g=new n(p.getDatabase()).invoice({client_name:r,hourly_rate_usd:e,range_start:s,range_end:o,project_id:u?.id,invoice_number:t.number,currency:t.currency,notes:t.notes,business_name:t["business-name"],business_address:t["business-address"],business_contact:t["business-contact"],client_address:t["client-address"],default_session_hours:X(t["session-hours"],1)}),f=t.out;if(f){const{writeFileSync:y}=await import("node:fs");y(f,g+`
81
+ `,"utf-8"),b(`Invoice written to ${f}`)}else process.stdout.write(g+`
82
+ `)}finally{p.close()}}async function Et(l){const{positional:c,flags:t}=C(l),i=c[0]??"status",{AgentDaemon:r}=await import("./agent-daemon.js"),e=j();try{const s=new r(e.getDatabase());switch(i){case"init":case"start":{const o=Math.max(10,Math.min(I(t.interval,600),86400)),n=s.start({interval_seconds:o,max_steps:t["max-steps"]!==void 0&&I(t["max-steps"],0)||void 0,project_path:t.project,verbose:t.verbose===!0});if(!n.ok){m(`Agent init failed: ${n.error}`),process.exitCode=1;return}const p=n.status;b(`Agent ${p.pid!=null&&p.pid!==n.pid?"already running":"started"} \u2014 pid ${p.pid}`),console.log(` Interval: ${o}s \xB7 Active goals: ${p.active_goals} \xB7 Total iterations: ${p.total_iterations}`),console.log(d.dim(` Log: ${p.log_file}`));return}case"status":{const o=s.status();k("Wyrm agent"),console.log(o.running?` RUNNING \u2014 pid ${o.pid}${o.started_at?` (since ${o.started_at})`:""}`:" NOT RUNNING. Start it with: wyrm agent init"),console.log(` Active goals: ${o.active_goals} \xB7 Total iterations: ${o.total_iterations}`),o.last_action&&console.log(` Last action (${o.last_action.ran_at}): ${o.last_action.summary} [${o.last_action.result_status??"?"}]`),t.log===!0&&(console.log(`
83
+ === Recent log ===`),console.log(s.recentLog(40)));return}case"stop":{const o=await s.stop({grace_ms:t.grace!==void 0?I(t.grace,3e3):void 0});if(!o.ok){m(`Stop failed: ${o.error}`),process.exitCode=1;return}b(o.was_running?`Agent stopped (was pid ${o.pid}). Goals remain in DB \u2014 wyrm agent init resumes.`:"Agent was not running. (No-op.)");return}case"restart":{const o=await s.restart({interval_seconds:t.interval!==void 0?I(t.interval,600):void 0,max_steps:t["max-steps"]!==void 0&&I(t["max-steps"],0)||void 0,project_path:t.project,verbose:t.verbose===!0});if(!o.ok){m(`Restart failed: ${o.error}`),process.exitCode=1;return}b(`Agent restarted \u2014 pid ${o.status.pid}. Active goals: ${o.status.active_goals}.`);return}default:m("Usage: wyrm agent <init|status|stop|restart> [--interval N] [--max-steps N] [--project <path>] [--verbose] [--log]"),process.exitCode=1}}finally{e.close()}}async function Rt(l){if(l.includes("--encrypt")){const{initializeLicense:i,hasFeature:r}=await import("./license.js");if(i(),!r("encryption")){m("Encryption setup requires a Pro license or higher. See: wyrm license"),process.exitCode=1;return}const{getCrypto:e,initializeCrypto:s}=await import("./crypto.js"),o=l.includes("--enable"),n=l.includes("--test");if(o){const a=process.env.WYRM_ENCRYPTION_KEY??(process.stdin.isTTY?"":we());if(!a||a.length<8){m('Password must be at least 8 characters. Set WYRM_ENCRYPTION_KEY or pipe it: printf %s "$PW" | wyrm setup --encrypt --enable'),process.exitCode=1;return}s(a),b("Encryption enabled (AES-256-GCM, key derived via PBKDF2). Store your password safely \u2014 it cannot be recovered.");return}const p=e();if(n){if(!p.isEnabled()){m("Encryption not enabled. Run: wyrm setup --encrypt --enable"),process.exitCode=1;return}const a="Wyrm encryption test "+Date.now();p.decrypt(p.encrypt(a))===a?b("Encryption test PASSED (encrypt \u2192 decrypt roundtrip)."):(m("Encryption test FAILED."),process.exitCode=1);return}k("Encryption status"),console.log(` Enabled: ${p.isEnabled()?"yes \u2014 new data is encrypted at rest":"no"}`),console.log(" Algorithm: AES-256-GCM"),p.isEnabled()||console.log(d.dim(" Enable with: wyrm setup --encrypt --enable (password via WYRM_ENCRYPTION_KEY or stdin)"));return}const c=re(ne(import.meta.url)),t=z(process.execPath,[F(c,"setup.js"),...l],{stdio:"inherit",shell:!1});process.exitCode=t.status??0}async function xt(l){const c="https://github.com/Ghosts-Protocol-Pvt-Ltd/wyrm-mcp",i=`- wyrm-mcp: ${M().version??"unknown"}
83
84
  - node: ${process.version}
84
- - platform: ${process.platform} ${process.arch}`,s=l.includes("--bug")?"bug":l.includes("--idea")||l.includes("--feature")?"idea":l.includes("--question")||l.includes("--ask")?"question":"feedback",t=l.filter(d=>!d.startsWith("--")).join(" ").trim(),r={bug:`**What happened**
85
+ - platform: ${process.platform} ${process.arch}`,r=l.includes("--bug")?"bug":l.includes("--idea")||l.includes("--feature")?"idea":l.includes("--question")||l.includes("--ask")?"question":"feedback",e=l.filter(p=>!p.startsWith("--")).join(" ").trim(),s={bug:`**What happened**
85
86
 
86
87
 
87
88
  **What you expected**
@@ -107,54 +108,57 @@ ${i}`,feedback:`**Your feedback** (what's working, what's rough)
107
108
 
108
109
 
109
110
  ---
110
- ${i}`},o={bug:"bug",idea:"enhancement",question:"question",feedback:"feedback"};let n;s==="question"?n=`${a}/discussions/new?category=q-a`+(t?`&title=${encodeURIComponent(t)}`:"")+`&body=${encodeURIComponent(r.question)}`:n=`${a}/issues/new?labels=${encodeURIComponent(o[s])}&title=${encodeURIComponent(`[${s}] ${t}`.trim())}&body=${encodeURIComponent(r[s])}`,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"),c=process.platform,m=c==="darwin"?d("open",[n],{stdio:"ignore",detached:!0}):c==="win32"?d("cmd",["/c","start","",n],{stdio:"ignore",detached:!0}):d("xdg-open",[n],{stdio:"ignore",detached:!0});m.on("error",()=>{}),m.unref()}catch{}}function be(){console.log(`
111
+ ${i}`},o={bug:"bug",idea:"enhancement",question:"question",feedback:"feedback"};let n;r==="question"?n=`${c}/discussions/new?category=q-a`+(e?`&title=${encodeURIComponent(e)}`:"")+`&body=${encodeURIComponent(s.question)}`:n=`${c}/issues/new?labels=${encodeURIComponent(o[r])}&title=${encodeURIComponent(`[${r}] ${e}`.trim())}&body=${encodeURIComponent(s[r])}`,console.log(""),console.log(" "+d.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(" "+d.cyan(n)),console.log(""),console.log(d.dim(" Prefer email? ryan@ghosts.lk \xB7 Bug: wyrm feedback --bug Idea: --idea Question: --question")),console.log("");try{const{spawn:p}=await import("child_process"),a=process.platform,u=a==="darwin"?p("open",[n],{stdio:"ignore",detached:!0}):a==="win32"?p("cmd",["/c","start","",n],{stdio:"ignore",detached:!0}):p("xdg-open",[n],{stdio:"ignore",detached:!0});u.on("error",()=>{}),u.unref()}catch{}}function be(){console.log(`
111
112
  ${N.brightMagenta}\u{F115D} Wyrm CLI v${M().version??"unknown"}${N.reset}
112
113
  ${N.dim}Persistent AI Memory System${N.reset}
113
114
 
114
- ${p.bold("Usage:")} wyrm <command> [options]
115
-
116
- ${p.bold("Commands:")}
117
- ${p.cyan("search")} <query> Search across memories, truths, quests, and data
118
- ${p.cyan("ls")} List stored items
119
- ${p.cyan("show")} <typed-id> Show full detail (mem:N, quest:N, truth:N, data:N, session:N)
120
- ${p.cyan("capture")} "<content>" Classify and capture a thought, task, or lesson
121
- ${p.cyan("rehydrate")} [--project <name>] Print the latest session's continuity brief (for SessionStart)
122
- ${p.cyan("session log")} [--run <id>] [--\u2026] Create/update this project's session record (rehydrate's write side)
123
- ${p.cyan("presence")} <announce|list|release> Agent presence board from the shell; --pid = process-identity liveness
124
- ${p.cyan("digest")} --writes [--since <days>] What Wyrm learned, queued, and refused \u2014 the offline write-receipt report
125
- ${p.cyan("bridge")} <init|status|run> The substrate flow: remember/render/reverse lanes from one receipted config
126
- ${p.cyan("metabolize")} [--dry-run] Memory metabolism: supersede exact dupes, queue near-dup candidates, decay stale auto-captures
127
- ${p.cyan("render")} [--client <list>] [--brief] Compile DB \u2192 MEMORY.md + topic files (zero-MCP-token memory)
128
- ${p.cyan("import git")} Import git log history to review queue
129
- ${p.cyan("import rules")} <path> Import .cursorrules / copilot-instructions file
130
- ${p.cyan("stats")} Show database statistics
131
- ${p.cyan("review")} Interactively review pending artifacts
132
- ${p.cyan("sync export")} --out <path> Export encrypted DB snapshot
133
- ${p.cyan("sync import")} --from <path> Restore from encrypted snapshot (backs up first)
134
- ${p.cyan("sync preview")} --from <path> Preview snapshot stats without restoring
135
- ${p.cyan("prune")} [--project <name>] Prune stale low-confidence artifacts (dry-run by default)
136
- ${p.cyan("cloud")} <login|sync|export|\u2026> Cloud backup & multi-device sync (Pro license)
137
- ${p.cyan("grove")} <status|policy> Per-project sync lanes (private|cloud|team) + leak audit
138
- ${p.cyan("run")} <start|join|end|status> Fleet-run lifecycle (records the migration-20 runs/run_agents tables)
139
- ${p.cyan("events")} [since|publish] [--project] Live-Memory event stream: read (since) or publish (was undocumented \u2014 tallow, 2026-07-14)
140
- ${p.cyan("skill")} <list|backfill-content|export|share> Discover bundled guides; store/sync SKILL.md content
141
- ${p.cyan("serve")} [--ui] Start the Wyrm HTTP server (optionally open the dashboard)
142
- ${p.cyan("setup")} [--check|--encrypt|\u2026] Auto-configure AI clients (wyrm-setup); --encrypt for at-rest crypto
143
- ${p.cyan("guard")} [--remove|--status] Failure-firewall PreToolUse hooks for Claude Code (wyrm-guard)
144
- ${p.cyan("intro")} What Wyrm is and how to use it
145
- ${p.cyan("license")} Show license status & features
146
- ${p.cyan("login")} Sign in (free account) and activate \u2014 required on official builds
147
- ${p.cyan("activate")} <key|path> Activate a license (JSON arg, file path, or stdin)
148
- ${p.cyan("maintenance")} [--vacuum] Archive/prune/sweep/checkpoint the database
149
- ${p.cyan("index")} <setup|rebuild|status> Vector search: verify provider, reindex, stats
150
- ${p.cyan("update")} [--check] Check for / install the latest wyrm-mcp
151
- ${p.cyan("prompt")} <inject|migrate> Inject/refresh the session-prime block in client files
152
- ${p.cyan("hours")} report --from --to Hours report derived from session history
153
- ${p.cyan("invoice")} generate --client \u2026 Markdown invoice from the hours ledger
154
- ${p.cyan("agent")} <init|status|stop|restart> Background agent daemon (goal loop)
155
- ${p.cyan("feedback")} [--bug|--idea|--question] Send feedback or report a bug (opens a prefilled GitHub report)
156
-
157
- ${p.bold("Options:")}
115
+ ${d.bold("Usage:")} wyrm <command> [options]
116
+
117
+ ${d.bold("Commands:")}
118
+ ${d.cyan("search")} <query> Search across memories, truths, quests, and data
119
+ ${d.cyan("ls")} List stored items
120
+ ${d.cyan("show")} <typed-id> Show full detail (mem:N, quest:N, truth:N, data:N, session:N)
121
+ ${d.cyan("capture")} "<content>" Classify and capture a thought, task, or lesson
122
+ ${d.cyan("rehydrate")} [--project <name>] Print the latest session's continuity brief (for SessionStart)
123
+ ${d.cyan("session log")} [--run <id>] [--\u2026] Create/update this project's session record (rehydrate's write side)
124
+ ${d.cyan("presence")} <announce|list|release> Agent presence board from the shell; --pid = process-identity liveness
125
+ ${d.cyan("digest")} --writes [--since <days>] What Wyrm learned, queued, and refused \u2014 the offline write-receipt report
126
+ ${d.cyan("bridge")} <init|status|run> The substrate flow: remember/render/reverse lanes from one receipted config
127
+ ${d.cyan("metabolize")} [--dry-run] Memory metabolism: supersede exact dupes, queue near-dup candidates, decay stale auto-captures
128
+ ${d.cyan("render")} [--client <list>] [--brief] Compile DB \u2192 MEMORY.md + topic files (zero-MCP-token memory)
129
+ ${d.cyan("import git")} Import git log history to review queue
130
+ ${d.cyan("import rules")} <path> Import .cursorrules / copilot-instructions file
131
+ ${d.cyan("stats")} Show database statistics
132
+ ${d.cyan("review")} Interactively review pending artifacts
133
+ ${d.cyan("sync export")} --out <path> Export encrypted DB snapshot
134
+ ${d.cyan("sync import")} --from <path> Restore from encrypted snapshot (backs up first)
135
+ ${d.cyan("sync preview")} --from <path> Preview snapshot stats without restoring
136
+ ${d.cyan("prune")} [--project <name>] Prune stale low-confidence artifacts (dry-run by default)
137
+ ${d.cyan("cloud")} <login|sync|export|\u2026> Cloud backup & multi-device sync (Pro license)
138
+ ${d.cyan("grove")} <status|policy> Per-project sync lanes (private|cloud|team) + leak audit
139
+ ${d.cyan("run")} <start|join|end|status> Fleet-run lifecycle (records the migration-20 runs/run_agents tables)
140
+ ${d.cyan("events")} [since|publish] [--project] Live-Memory event stream: read (since) or publish (was undocumented \u2014 tallow, 2026-07-14)
141
+ ${d.cyan("skill")} <list|backfill-content|export|share> Discover bundled guides; store/sync SKILL.md content
142
+ ${d.cyan("serve")} [--ui] Start the Wyrm HTTP server (optionally open the dashboard)
143
+ ${d.cyan("setup")} [--check|--encrypt|\u2026] Auto-configure AI clients (wyrm-setup); --encrypt for at-rest crypto
144
+ ${d.cyan("guard")} [--remove|--status] Failure-firewall PreToolUse hooks for Claude Code (wyrm-guard)
145
+ ${d.cyan("intro")} What Wyrm is and how to use it
146
+ ${d.cyan("license")} Show license status & features
147
+ ${d.cyan("login")} Sign in (free account) and activate \u2014 required on official builds
148
+ ${d.cyan("activate")} <key|path> Activate a license (JSON arg, file path, or stdin)
149
+ ${d.cyan("maintenance")} [--vacuum] Archive/prune/sweep/checkpoint the database
150
+ ${d.cyan("index")} <setup|rebuild|status> Vector search: verify provider, reindex, stats
151
+ ${d.cyan("doctor")} Health check that refuses to flatter \u2014 reports anything silently degraded
152
+ ${d.cyan("failure")} <list|resolve> Failure firewall: list unresolved patterns, resolve a fixed one
153
+ ${d.cyan("project")} <add|list> Register a project without needing a session start
154
+ ${d.cyan("update")} [--check] Check for / install the latest wyrm-mcp
155
+ ${d.cyan("prompt")} <inject|migrate> Inject/refresh the session-prime block in client files
156
+ ${d.cyan("hours")} report --from --to Hours report derived from session history
157
+ ${d.cyan("invoice")} generate --client \u2026 Markdown invoice from the hours ledger
158
+ ${d.cyan("agent")} <init|status|stop|restart> Background agent daemon (goal loop)
159
+ ${d.cyan("feedback")} [--bug|--idea|--question] Send feedback or report a bug (opens a prefilled GitHub report)
160
+
161
+ ${d.bold("Options:")}
158
162
  --project <name> Filter or associate with a specific project
159
163
  --type <type> Filter type (memories|truths|quests|data|all)
160
164
  --limit <N> Limit number of results (default: 20)
@@ -171,26 +175,26 @@ ${p.bold("Options:")}
171
175
  --help, -h Show this help
172
176
  --version, -v Print the installed version
173
177
 
174
- ${p.bold("Environment:")}
178
+ ${d.bold("Environment:")}
175
179
  WYRM_DB_PATH Override database path (default: ~/.wyrm/wyrm.db)
176
180
  WYRM_SYNC_PASSPHRASE Passphrase for encrypted sync (or prompted interactively)
177
181
 
178
- ${p.bold("Examples:")}
182
+ ${d.bold("Examples:")}
179
183
  wyrm search "authentication bug"
180
184
  wyrm ls --type memories --project MyApp
181
185
  wyrm capture "TODO: refactor the auth module" --project MyApp
182
186
  wyrm sync export --out ~/wyrm-backup.wyrm
183
187
  wyrm sync preview --from ~/wyrm-backup.wyrm
184
188
  wyrm prune --project MyApp --min-confidence 0.2 --older-than 30
185
- `)}const[,,O,...$]=process.argv;function $e(l){const a=l.ref_table?`${l.ref_table}${l.ref_id?"#"+l.ref_id:""}`:"",e=new Date(l.created_at).toLocaleTimeString();return`#${l.cursor} ${l.kind.padEnd(15)} ${a.padEnd(16)} ${He(l.actor)} ${e}`}async function Ct(l){const{positional:a,flags:e}=_(l),i=a[0]||"since",s=C();try{if(!s.liveMemoryEnabled()){f("Live Memory is disabled (set WYRM_LIVE_MEMORY=1)."),process.exitCode=1;return}const t=(typeof e.project=="string"?e.project:"")||process.cwd(),r=s.getProject(t)??s.getProjectByName(t);if(!r){f(`Project not found: ${t}`),process.exitCode=1;return}if(i==="publish"){const o=a[1]||(typeof e.kind=="string"?e.kind:"");if(!o){f("usage: wyrm events publish <kind> --project <p> [--actor A] [--ref-table T --ref-id ID]"),process.exitCode=1;return}s.publishEvent({projectId:r.id,kind:o,refTable:typeof e["ref-table"]=="string"?e["ref-table"]:void 0,refId:typeof e["ref-id"]=="string"?e["ref-id"]:void 0,actor:typeof e.actor=="string"?e.actor:void 0}),b(`Event published (${o}) to ${r.name}`);return}if(i==="since"){const o=D(e.cursor,0),n=D(e.limit,50),d=s.eventsSince(r.id,o,n);for(const c of d)console.log($e(c));S(`${d.length} event(s) for '${r.name}' since cursor ${o}`);return}f("usage: wyrm events <publish|since> ..."),process.exitCode=1}finally{s.close()}}async function _t(l){const{flags:a}=_(l),e=C();if(!e.liveMemoryEnabled()){f("Live Memory is disabled (set WYRM_LIVE_MEMORY=1)."),e.close(),process.exitCode=1;return}const i=(typeof a.project=="string"?a.project:"")||process.cwd(),s=e.getProject(i)??x(e,i);if(!s){f(`Project not found: ${i}`),e.close(),process.exitCode=1;return}const t=Math.max(250,D(a.interval,1e3));let r=D(a.since,e.subscribeEvents(s.id,1).cursor);S(`Watching '${s.name}' (cursor ${r}, every ${t}ms) \u2014 Ctrl-C to stop`);const o=()=>{try{for(const c of e.eventsSince(s.id,r,200))r=c.cursor,console.log($e(c))}catch{}};o();const n=setInterval(o,t),d=()=>{clearInterval(n);try{e.close()}catch{}process.exit(0)};process.on("SIGINT",d),process.on("SIGTERM",d)}async function Rt(l){const{flags:a}=_(l),{embedAll:e,removeAll:i,statusAll:s}=await import("./priority-embed.js"),t={projectDir:typeof a.project=="string"?a.project:void 0,allClients:a.all===!0},r=o=>console.log(` ${String(o.result??o.status).padEnd(9)} [${o.scope}] ${o.file}`);if(a.status){S("Wyrm priority embedding \u2014 status"),s(t).forEach(r);return}if(a.remove){S("Wyrm priority embedding \u2014 removed"),i(t).forEach(r);return}S("Wyrm is now FIRST-PRIORITY memory"),e(t).forEach(r);try{const{installClaudeCodeHooks:o,installClaudeStatusline:n}=await import("./autoconfig.js");o()?b("Proactive hooks installed (SessionStart rehydrate + capture + tool-trace)."):console.log(" (Claude Code not detected \u2014 skipped hook install.)");const c=n();c&&b(`Buddy statusline: ${c.message}`)}catch{}b("Wyrm will now be read first, primed proactively, and shown in the TUI at all times.")}async function Et(l){const{flags:a}=_(l),{harvestProjects:e}=await import("./harvest.js"),{MemoryArtifacts:i}=await import("./memory-artifacts.js"),{escapeLikePattern:s}=await import("./auto-capture.js"),t=C();try{const r=t.getDatabase(),o=new i(r),n={existsBySig:(w,v)=>!!r.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(w,"%"+s(v)+"%"),addCandidate:(w,v)=>o.add(w,{kind:v.kind,problem:v.text,tags:[...v.tags,v.sig],confidence:v.confidence,needsReview:1,createdBy:"harvest"})},d=typeof a.project=="string"?a.project:void 0;let c;if(d){const w=t.getProject(d)??t.getProjectByName(d);if(!w){f(`Project not found: ${d}`),process.exitCode=1;return}c=[{id:w.id,name:w.name,path:w.path}]}else c=t.getAllProjects(500).map(w=>({id:w.id,name:w.name,path:w.path}));const m=a["dry-run"]===!0||a.dry===!0,g=a.code===!0||a["include-code"]===!0,{reports:u,totalAdded:h,totalSkipped:y}=e(n,c,{dryRun:m,gitLimit:D(a.limit,30),includeCode:g});S(`Harvest ${m?"(dry run) ":""}\u2014 ${h} candidate(s), ${y} already present (${c.length} project(s))`);for(const w of u.filter(v=>v.added>0).sort((v,R)=>R.added-v.added).slice(0,25))console.log(` +${String(w.added).padStart(3)} (skip ${w.skipped}) ${w.project}`);if(g&&!m){const{SymbolGraph:w}=await import("./symbols.js"),v=new w(r);let R=0,j=0;for(const E of c)try{const k=v.indexProject(E.id,E.path);R+=k.symbols,j+=k.files}catch{}console.log(` \u{1F4D0} Indexed ${R} code symbols (${j} files) \u2192 searchable via 'wyrm search'`)}!m&&h>0&&b("Review with: wyrm review")}finally{t.close()}}async function xt(l){const a=await import("./vault.js"),[e,...i]=l;try{switch(e){case"set":{const s=i[0];if(!s){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 ${s}`),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}a.vaultSet(s,r),b(`Stored "${s}" (AES-256-GCM). Use it without exposing it: wyrm vault exec ${s} -- <command>`);break}case"get":{const s=i[0];if(!s){f("usage: wyrm vault get <name>"),process.exitCode=1;return}const t=a.vaultGet(s);if(t===void 0){f(`no secret named "${s}"`),process.exitCode=1;return}process.stdout.write(t);break}case"list":case"ls":{const s=a.vaultList();if(!s.length){console.log("(vault is empty)");break}S(`Vault \u2014 ${s.length} secret(s)`);for(const t of s)console.log(" \u2022 "+t);break}case"rm":case"remove":case"delete":{const s=i[0];if(!s){f("usage: wyrm vault rm <name>"),process.exitCode=1;return}b(a.vaultRemove(s)?`Removed "${s}"`:`(no secret named "${s}")`);break}case"exec":{const s=i[0],t=i.indexOf("--");if(!s||t===-1||t+1>=i.length){f("usage: wyrm vault exec <name> [--as ENVVAR] -- <command...>"),process.exitCode=1;return}const r=i.slice(1,t),o=r.indexOf("--as"),n=o>=0?r[o+1]:s.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),d=i.slice(t+1),c=a.vaultGet(s);if(c===void 0){f(`no secret named "${s}"`),process.exitCode=1;return}const m=z(d[0],d.slice(1),{stdio:"inherit",env:{...process.env,[n]:c}});process.exitCode=m.status??1;break}case"import-npm":{const s=await import("node:fs"),t=await import("node:os"),o=(await import("node:path")).join(t.homedir(),".npmrc");if(!s.existsSync(o)){f("~/.npmrc not found"),process.exitCode=1;return}const n=s.readFileSync(o,"utf8").match(/\/\/registry\.npmjs\.org\/:_authToken=(.+)/);if(!n){f("no npm authToken found in ~/.npmrc"),process.exitCode=1;return}a.vaultSet("npm-token",n[1].trim()),b('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 s=a.vaultPaths();if(s.secure)b(`Vault is already secure (backend: ${s.backend}, ${s.count} secret(s)).`);else{const t=s.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=a.vaultSecure({backend:t});b(`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 s=i.indexOf("--backend"),t=s>=0?i[s+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=!i.includes("--no-rotate"),o=a.vaultSecure({backend:t,rotate:r});b(`Vault secured: ${o.from} \u2192 ${o.to}${o.rotated?" (key rotated)":""}.`),console.log(` secrets re-encrypted: ${o.secrets}`),o.keyfileShredded&&console.log(" plaintext vault.key: shredded \u2714"),o.backup&&console.log(` ciphertext backup: ${o.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 s=a.vaultPaths();S("Vault"),console.log(` backend: ${s.backend}`),console.log(` secrets: ${s.count}`),console.log(` store: ${s.vault} (0600)`),console.log(` key: ${s.backend==="keyfile"?s.key+" (0600)":s.backend==="keychain"?"(OS keychain \u2014 no key on disk)":"(derived from WYRM_VAULT_PASSPHRASE \u2014 no key on disk)"}`),console.log(` secure: ${s.secure?"yes \u2014 key is not a plaintext file beside the ciphertext":"NO \u2014 key sits beside ciphertext"}`),s.secure||console.log(s.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(s){f(`vault: ${s.message}`),process.exitCode=1}}function Tt(){const l=ne(re(import.meta.url)),e=[q(l,"..","skills"),q(l,"..","..","skills")].find(s=>H(s));if(!e)return[];const i=[];for(const s of Ie(e,{withFileTypes:!0})){if(!s.isDirectory())continue;const t=q(e,s.name,"SKILL.md");if(!H(t))continue;let r=s.name,o="";try{const n=B(t,"utf8"),d=n.match(/^name:\s*(.+)$/m);if(d&&(r=d[1].trim()),/^description:\s*[|>]/m.test(n))o=((n.split(/^description:.*$/m)[1]??"").split(`
186
- `).find(g=>g.trim())??"").trim();else{const c=n.match(/^description:\s*(.+)$/m);c&&(o=c[1].trim())}}catch{}i.push({name:r,description:o})}return i.sort((s,t)=>s.name.localeCompare(t.name))}async function Dt(l){const a=l[0];if(!a||a==="help"||a==="--help"){console.log(`Usage:
189
+ `)}const[,,O,...v]=process.argv;function $e(l){const c=l.ref_table?`${l.ref_table}${l.ref_id?"#"+l.ref_id:""}`:"",t=new Date(l.created_at).toLocaleTimeString();return`#${l.cursor} ${l.kind.padEnd(15)} ${c.padEnd(16)} ${Be(l.actor)} ${t}`}async function Tt(l){const{positional:c,flags:t}=C(l),i=c[0]||"since",r=j();try{if(!r.liveMemoryEnabled()){m("Live Memory is disabled (set WYRM_LIVE_MEMORY=1)."),process.exitCode=1;return}const e=(typeof t.project=="string"?t.project:"")||process.cwd(),s=r.getProject(e)??r.getProjectByName(e);if(!s){m(`Project not found: ${e}`),process.exitCode=1;return}if(i==="publish"){const o=c[1]||(typeof t.kind=="string"?t.kind:"");if(!o){m("usage: wyrm events publish <kind> --project <p> [--actor A] [--ref-table T --ref-id ID]"),process.exitCode=1;return}r.publishEvent({projectId:s.id,kind:o,refTable:typeof t["ref-table"]=="string"?t["ref-table"]:void 0,refId:typeof t["ref-id"]=="string"?t["ref-id"]:void 0,actor:typeof t.actor=="string"?t.actor:void 0}),b(`Event published (${o}) to ${s.name}`);return}if(i==="since"){const o=I(t.cursor,0),n=I(t.limit,50),p=r.eventsSince(s.id,o,n);for(const a of p)console.log($e(a));k(`${p.length} event(s) for '${s.name}' since cursor ${o}`);return}m("usage: wyrm events <publish|since> ..."),process.exitCode=1}finally{r.close()}}async function Dt(l){const{flags:c}=C(l),t=j();if(!t.liveMemoryEnabled()){m("Live Memory is disabled (set WYRM_LIVE_MEMORY=1)."),t.close(),process.exitCode=1;return}const i=(typeof c.project=="string"?c.project:"")||process.cwd(),r=t.getProject(i)??x(t,i);if(!r){m(`Project not found: ${i}`),t.close(),process.exitCode=1;return}const e=Math.max(250,I(c.interval,1e3));let s=I(c.since,t.subscribeEvents(r.id,1).cursor);k(`Watching '${r.name}' (cursor ${s}, every ${e}ms) \u2014 Ctrl-C to stop`);const o=()=>{try{for(const a of t.eventsSince(r.id,s,200))s=a.cursor,console.log($e(a))}catch{}};o();const n=setInterval(o,e),p=()=>{clearInterval(n);try{t.close()}catch{}process.exit(0)};process.on("SIGINT",p),process.on("SIGTERM",p)}async function It(l){const{flags:c}=C(l),{embedAll:t,removeAll:i,statusAll:r}=await import("./priority-embed.js"),e={projectDir:typeof c.project=="string"?c.project:void 0,allClients:c.all===!0},s=o=>console.log(` ${String(o.result??o.status).padEnd(9)} [${o.scope}] ${o.file}`);if(c.status){k("Wyrm priority embedding \u2014 status"),r(e).forEach(s);return}if(c.remove){k("Wyrm priority embedding \u2014 removed"),i(e).forEach(s);return}k("Wyrm is now FIRST-PRIORITY memory"),t(e).forEach(s);try{const{installClaudeCodeHooks:o,installClaudeStatusline:n}=await import("./autoconfig.js");o()?b("Proactive hooks installed (SessionStart rehydrate + capture + tool-trace)."):console.log(" (Claude Code not detected \u2014 skipped hook install.)");const a=n();a&&b(`Buddy statusline: ${a.message}`)}catch{}b("Wyrm will now be read first, primed proactively, and shown in the TUI at all times.")}async function Pt(l){const{flags:c}=C(l),{harvestProjects:t}=await import("./harvest.js"),{MemoryArtifacts:i}=await import("./memory-artifacts.js"),{escapeLikePattern:r}=await import("./auto-capture.js"),e=j();try{const s=e.getDatabase(),o=new i(s),n={existsBySig:(w,$)=>!!s.prepare("SELECT 1 FROM memory_artifacts WHERE project_id = ? AND tags LIKE ? ESCAPE '\\' LIMIT 1").get(w,"%"+r($)+"%"),addCandidate:(w,$)=>o.add(w,{kind:$.kind,problem:$.text,tags:[...$.tags,$.sig],confidence:$.confidence,needsReview:1,createdBy:"harvest"})},p=typeof c.project=="string"?c.project:void 0;let a;if(p){const w=e.getProject(p)??e.getProjectByName(p);if(!w){m(`Project not found: ${p}`),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 u=c["dry-run"]===!0||c.dry===!0,g=c.code===!0||c["include-code"]===!0,{reports:f,totalAdded:y,totalSkipped:h}=t(n,a,{dryRun:u,gitLimit:I(c.limit,30),includeCode:g});k(`Harvest ${u?"(dry run) ":""}\u2014 ${y} candidate(s), ${h} already present (${a.length} project(s))`);for(const w of f.filter($=>$.added>0).sort(($,E)=>E.added-$.added).slice(0,25))console.log(` +${String(w.added).padStart(3)} (skip ${w.skipped}) ${w.project}`);if(g&&!u){const{SymbolGraph:w}=await import("./symbols.js"),$=new w(s);let E=0,_=0;for(const R of a)try{const S=$.indexProject(R.id,R.path);E+=S.symbols,_+=S.files}catch{}console.log(` \u{1F4D0} Indexed ${E} code symbols (${_} files) \u2192 searchable via 'wyrm search'`)}!u&&y>0&&b("Review with: wyrm review")}finally{e.close()}}async function Nt(l){const c=await import("./vault.js"),[t,...i]=l;try{switch(t){case"set":{const r=i[0];if(!r){m("usage: wyrm vault set <name> (the secret is read from STDIN, never argv)"),process.exitCode=1;return}if(process.stdin.isTTY){m(`pipe the secret in, e.g.: printf %s "$TOKEN" | wyrm vault set ${r}`),process.exitCode=1;return}const s=(await import("node:fs")).readFileSync(0,"utf8").replace(/\r?\n$/,"");if(!s){m("empty secret on stdin"),process.exitCode=1;return}c.vaultSet(r,s),b(`Stored "${r}" (AES-256-GCM). Use it without exposing it: wyrm vault exec ${r} -- <command>`);break}case"get":{const r=i[0];if(!r){m("usage: wyrm vault get <name>"),process.exitCode=1;return}const e=c.vaultGet(r);if(e===void 0){m(`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}k(`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){m("usage: wyrm vault rm <name>"),process.exitCode=1;return}b(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){m("usage: wyrm vault exec <name> [--as ENVVAR] -- <command...>"),process.exitCode=1;return}const s=i.slice(1,e),o=s.indexOf("--as"),n=o>=0?s[o+1]:r.toUpperCase().replace(/[^A-Z0-9]+/g,"_"),p=i.slice(e+1),a=c.vaultGet(r);if(a===void 0){m(`no secret named "${r}"`),process.exitCode=1;return}const u=z(p[0],p.slice(1),{stdio:"inherit",env:{...process.env,[n]:a}});process.exitCode=u.status??1;break}case"import-npm":{const r=await import("node:fs"),e=await import("node:os"),o=(await import("node:path")).join(e.homedir(),".npmrc");if(!r.existsSync(o)){m("~/.npmrc not found"),process.exitCode=1;return}const n=r.readFileSync(o,"utf8").match(/\/\/registry\.npmjs\.org\/:_authToken=(.+)/);if(!n){m("no npm authToken found in ~/.npmrc"),process.exitCode=1;return}c.vaultSet("npm-token",n[1].trim()),b('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)b(`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){m("No OS keychain on this host. Set WYRM_VAULT_PASSPHRASE, then re-run: wyrm vault setup"),process.exitCode=1;return}const s=c.vaultSecure({backend:e});b(`Vault secured: ${s.from} \u2192 ${s.to}${s.rotated?" (key rotated)":""}.`),s.keyfileShredded&&console.log(" plaintext vault.key: shredded \u2714"),s.backup&&console.log(` ciphertext backup: ${s.backup} (delete once confirmed)`)}k("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"){m("usage: wyrm vault secure [--backend keychain|passphrase] [--no-rotate]"),process.exitCode=1;return}if(e==="passphrase"&&!process.env.WYRM_VAULT_PASSPHRASE){m("set WYRM_VAULT_PASSPHRASE before: wyrm vault secure --backend passphrase"),process.exitCode=1;return}const s=!i.includes("--no-rotate"),o=c.vaultSecure({backend:e,rotate:s});b(`Vault secured: ${o.from} \u2192 ${o.to}${o.rotated?" (key rotated)":""}.`),console.log(` secrets re-encrypted: ${o.secrets}`),o.keyfileShredded&&console.log(" plaintext vault.key: shredded \u2714"),o.backup&&console.log(` ciphertext backup: ${o.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();k("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:m("usage: wyrm vault <setup|set|get|list|rm|exec|import-npm|secure|info>"),process.exitCode=1}}catch(r){m(`vault: ${r.message}`),process.exitCode=1}}function Mt(){const l=re(ne(import.meta.url)),t=[F(l,"..","skills"),F(l,"..","..","skills")].find(r=>q(r));if(!t)return[];const i=[];for(const r of Me(t,{withFileTypes:!0})){if(!r.isDirectory())continue;const e=F(t,r.name,"SKILL.md");if(!q(e))continue;let s=r.name,o="";try{const n=V(e,"utf8"),p=n.match(/^name:\s*(.+)$/m);if(p&&(s=p[1].trim()),/^description:\s*[|>]/m.test(n))o=((n.split(/^description:.*$/m)[1]??"").split(`
190
+ `).find(g=>g.trim())??"").trim();else{const a=n.match(/^description:\s*(.+)$/m);a&&(o=a[1].trim())}}catch{}i.push({name:s,description:o})}return i.sort((r,e)=>r.name.localeCompare(e.name))}async function Ot(l){const c=l[0];if(!c||c==="help"||c==="--help"){console.log(`Usage:
187
191
  wyrm skill list show the bundled guides + your registered skills
188
192
  wyrm skill backfill-content read every skill's SKILL.md into the registry (idempotent)
189
193
  wyrm skill export <targetDir> [--all] materialize SKILL.md files from stored content
190
- wyrm skill share <name|--all|--tier T> [--public|--private] [--include-inactive] set cloud-sync visibility (single or bulk)`);return}if(a==="list"||a==="ls"){const i=Tt();if(S("Bundled skill guides (shipped in the box)"),i.length===0)console.log(p.yellow(" none found next to this install"));else{for(const t of i)console.log(` ${p.cyan(t.name)}`),t.description&&console.log(` ${p.dim(t.description)}`);console.log(p.dim("\n Read one: open its SKILL.md, or `wyrm skill export <dir>` to materialize all."))}const s=C();try{const t=s.listSkills(!0);if(S(`Registered skills in your memory (${t.length})`),t.length===0)console.log(p.dim(" none yet \u2014 register with wyrm_skill_register or author with wyrm_skill_create"));else{for(const r of t.slice(0,40))console.log(` ${p.cyan(r.name)}${r.tier?p.dim(" ["+r.tier+"]"):""}`);t.length>40&&console.log(p.dim(` \u2026 and ${t.length-40} more`))}}finally{s.close()}return}const e=C();try{if(a==="backfill-content"||a==="backfill"){S("Backfill SKILL.md content into the registry");const i=e.backfillSkillContent();b(`${i.filled} filled . ${i.unchanged} unchanged . ${i.missing} missing-file (of ${i.total} registered)`),i.missing>0&&console.log(p.yellow(` ${i.missing} skill(s) had no readable SKILL.md \u2014 re-run after restoring their files.`));return}if(a==="export"){const i=l[1];i||(f("Usage: wyrm skill export <targetDir> [--all]"),e.close(),process.exit(1));const s=l.includes("--all");S(`Export skills \u2192 ${i}`);const t=e.exportSkillContent(i,{includeInactive:s});b(`${t.written} SKILL.md written . ${t.skipped_no_content} skipped (no stored content) (of ${t.total} ${s?"total":"active"})`),t.skipped_no_content>0&&console.log(p.yellow(" Run `wyrm skill backfill-content` on the source machine to populate content first.")),t.collisions>0&&console.log(p.yellow(` ${t.collisions} slug collision(s) disambiguated with a name-hash suffix (distinct skills, same slug) \u2014 no content lost.`));return}if(a==="share"){const i=l.includes("--private")?"within":l.includes("--public")?"public":"org",s=l.includes("--include-inactive"),t=l.indexOf("--tier"),r=t>=0?l[t+1]:void 0;if(t>=0&&(!r||r.startsWith("--"))&&(f("Usage: wyrm skill share --tier <god|mega|atomic> [--public|--private] [--include-inactive]"),e.close(),process.exit(1)),l.includes("--all")||!!r){const c=e.setAllSkillsVisibility(i,{tier:r,includeInactive:s}),m=r?`tier '${r}'`:s?"all skills":"all active skills";b(`${c} skill(s) (${m}) visibility \u2192 '${i}'.`),console.log(i==="within"?" These skills will NOT egress on cloud sync (private).":` ${c} skills are now cloud-sync-eligible (they leave on the next \`wyrm cloud sync\`).`);return}const n=l[1];n||(f("Usage: wyrm skill share <name|--all|--tier <tier>> [--public|--private] [--include-inactive]"),e.close(),process.exit(1)),e.setSkillVisibility(n,i)||(f(`Skill not found: ${n}`),e.close(),process.exit(1)),b(`Skill "${n}" 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: ${a}`),process.exit(1)}finally{e.close()}}async function Pt(l){const a=l[0]??"status",e=C(),i=e.getDatabase();if(i.prepare("PRAGMA table_info(projects)").all().some(t=>t.name==="sync_policy")||(f("Grove sync policy is not on this database yet (upgrade Wyrm so migrations apply)."),e.close(),process.exit(1)),a==="status"||a==="ls"||a==="list"){S("Grove sync policy + leak audit");const t=i.prepare("SELECT id, name, sync_policy FROM projects ORDER BY id").all(),r=["ground_truths","memory_artifacts","quests","design_tokens","design_references"],o=["ground_truths","memory_artifacts","quests","sessions","decision_edges"],n=(m,g,u)=>{let h=0;for(const y of m)try{h+=i.prepare(`SELECT COUNT(*) AS n FROM ${y} WHERE project_id = ? AND ${u}`).get(g).n}catch{}return h},d=[];let c=0;for(const m of t){const g=n(r,m.id,"cross_project_visibility IN ('org','public')"),u=n(o,m.id,"is_shared = 1"),h=m.sync_policy==="private"&&g+u>0;h&&c++;const y=h?p.red(`LEAK: ${g} promoted + ${u} shared in a PRIVATE grove`):`${g} promoted / ${u} shared`;d.push([String(m.id),m.name,m.sync_policy,y])}console.log(P(["#","Grove","sync_policy","rows eligible to leave"],d)),console.log(`
191
- private = never replicates . cloud = your own cloud backup . team = federates to a team Wyrm`),c>0&&console.log(p.red(`
192
- ! ${c} private grove(s) hold rows marked to leave. Re-private those rows or change the grove lane.`)),e.close();return}if(a==="policy"||a==="set"){const t=l[1],r=l[2];(!t||!["private","cloud","team"].includes(r))&&(f("Usage: wyrm grove policy <project|id> <private|cloud|team>"),e.close(),process.exit(1));let o=x(e,t);!o&&/^\d+$/.test(t)&&(o=i.prepare("SELECT id, name FROM projects WHERE id = ?").get(Number(t))),o||(f(`Grove not found: ${t}`),e.close(),process.exit(1)),i.prepare("UPDATE projects SET sync_policy = ? WHERE id = ?").run(r,o.id),b(`Grove "${o.name}" set to '${r}'.`),r!=="private"&&console.log(` Rows still only leave when also marked ${r==="team"?"is_shared (team)":"org/public (cloud)"}. The grove is the outer gate.`),e.close();return}f(`Unknown grove subcommand: ${a}`),console.log(`Usage:
194
+ wyrm skill share <name|--all|--tier T> [--public|--private] [--include-inactive] set cloud-sync visibility (single or bulk)`);return}if(c==="list"||c==="ls"){const i=Mt();if(k("Bundled skill guides (shipped in the box)"),i.length===0)console.log(d.yellow(" none found next to this install"));else{for(const e of i)console.log(` ${d.cyan(e.name)}`),e.description&&console.log(` ${d.dim(e.description)}`);console.log(d.dim("\n Read one: open its SKILL.md, or `wyrm skill export <dir>` to materialize all."))}const r=j();try{const e=r.listSkills(!0);if(k(`Registered skills in your memory (${e.length})`),e.length===0)console.log(d.dim(" none yet \u2014 register with wyrm_skill_register or author with wyrm_skill_create"));else{for(const s of e.slice(0,40))console.log(` ${d.cyan(s.name)}${s.tier?d.dim(" ["+s.tier+"]"):""}`);e.length>40&&console.log(d.dim(` \u2026 and ${e.length-40} more`))}}finally{r.close()}return}const t=j();try{if(c==="backfill-content"||c==="backfill"){k("Backfill SKILL.md content into the registry");const i=t.backfillSkillContent();b(`${i.filled} filled . ${i.unchanged} unchanged . ${i.missing} missing-file (of ${i.total} registered)`),i.missing>0&&console.log(d.yellow(` ${i.missing} skill(s) had no readable SKILL.md \u2014 re-run after restoring their files.`));return}if(c==="export"){const i=l[1];i||(m("Usage: wyrm skill export <targetDir> [--all]"),t.close(),process.exit(1));const r=l.includes("--all");k(`Export skills \u2192 ${i}`);const e=t.exportSkillContent(i,{includeInactive:r});b(`${e.written} SKILL.md written . ${e.skipped_no_content} skipped (no stored content) (of ${e.total} ${r?"total":"active"})`),e.skipped_no_content>0&&console.log(d.yellow(" Run `wyrm skill backfill-content` on the source machine to populate content first.")),e.collisions>0&&console.log(d.yellow(` ${e.collisions} slug collision(s) disambiguated with a name-hash suffix (distinct skills, same slug) \u2014 no content lost.`));return}if(c==="share"){const i=l.includes("--private")?"within":l.includes("--public")?"public":"org",r=l.includes("--include-inactive"),e=l.indexOf("--tier"),s=e>=0?l[e+1]:void 0;if(e>=0&&(!s||s.startsWith("--"))&&(m("Usage: wyrm skill share --tier <god|mega|atomic> [--public|--private] [--include-inactive]"),t.close(),process.exit(1)),l.includes("--all")||!!s){const a=t.setAllSkillsVisibility(i,{tier:s,includeInactive:r}),u=s?`tier '${s}'`:r?"all skills":"all active skills";b(`${a} skill(s) (${u}) 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 n=l[1];n||(m("Usage: wyrm skill share <name|--all|--tier <tier>> [--public|--private] [--include-inactive]"),t.close(),process.exit(1)),t.setSkillVisibility(n,i)||(m(`Skill not found: ${n}`),t.close(),process.exit(1)),b(`Skill "${n}" 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}m(`Unknown skill subcommand: ${c}`),process.exit(1)}finally{t.close()}}async function At(l){const c=l[0]??"status",t=j(),i=t.getDatabase();if(i.prepare("PRAGMA table_info(projects)").all().some(e=>e.name==="sync_policy")||(m("Grove sync policy is not on this database yet (upgrade Wyrm so migrations apply)."),t.close(),process.exit(1)),c==="status"||c==="ls"||c==="list"){k("Grove sync policy + leak audit");const e=i.prepare("SELECT id, name, sync_policy FROM projects ORDER BY id").all(),s=["ground_truths","memory_artifacts","quests","design_tokens","design_references"],o=["ground_truths","memory_artifacts","quests","sessions","decision_edges"],n=(u,g,f)=>{let y=0;for(const h of u)try{y+=i.prepare(`SELECT COUNT(*) AS n FROM ${h} WHERE project_id = ? AND ${f}`).get(g).n}catch{}return y},p=[];let a=0;for(const u of e){const g=n(s,u.id,"cross_project_visibility IN ('org','public')"),f=n(o,u.id,"is_shared = 1"),y=u.sync_policy==="private"&&g+f>0;y&&a++;const h=y?d.red(`LEAK: ${g} promoted + ${f} shared in a PRIVATE grove`):`${g} promoted / ${f} shared`;p.push([String(u.id),u.name,u.sync_policy,h])}console.log(D(["#","Grove","sync_policy","rows eligible to leave"],p)),console.log(`
195
+ private = never replicates . cloud = your own cloud backup . team = federates to a team Wyrm`),a>0&&console.log(d.red(`
196
+ ! ${a} private grove(s) hold rows marked to leave. Re-private those rows or change the grove lane.`)),t.close();return}if(c==="policy"||c==="set"){const e=l[1],s=l[2];(!e||!["private","cloud","team"].includes(s))&&(m("Usage: wyrm grove policy <project|id> <private|cloud|team>"),t.close(),process.exit(1));let o=x(t,e);!o&&/^\d+$/.test(e)&&(o=i.prepare("SELECT id, name FROM projects WHERE id = ?").get(Number(e))),o||(m(`Grove not found: ${e}`),t.close(),process.exit(1)),i.prepare("UPDATE projects SET sync_policy = ? WHERE id = ?").run(s,o.id),b(`Grove "${o.name}" set to '${s}'.`),s!=="private"&&console.log(` Rows still only leave when also marked ${s==="team"?"is_shared (team)":"org/public (cloud)"}. The grove is the outer gate.`),t.close();return}m(`Unknown grove subcommand: ${c}`),console.log(`Usage:
193
197
  wyrm grove status
194
- wyrm grove policy <project|id> <private|cloud|team>`),e.close(),process.exit(1)}async function It(l){const a=l[0],{flags:e}=_(l.slice(1)),{ulid:i}=await import("./ulid.js"),{createRun:s,setRunStatus:t,registerAgent:r,getRun:o,getAgents:n}=await import("./handlers/run.js"),{sanitizeActorId:d}=await import("./handlers/boundary.js"),c=u=>typeof u=="string"?d(u):null,m=C(),g=m.getDatabase();try{switch(a){case"start":{const u=(typeof e.orchestrator=="string"?e.orchestrator:"cli").slice(0,200),h=c(e.agent)??d(u)??"cli",y=c(e.parent);if(y&&!o(g,y)){f(`Parent run not found: ${y}`),process.exitCode=1;return}const w=i();s(g,w,y,u),r(g,w,h,"orchestrator"),process.stdout.write(w+`
195
- `),process.stderr.write(`Run ${w} started by ${u}.
196
- `);break}case"join":{const u=c(e.run),h=c(e.agent);if(!u||!h){f("Usage: wyrm run join --run <RUNID> --agent <ID> [--role <ROLE>]"),process.exitCode=1;return}if(!o(g,u)){f(`Run not found: ${u}`),process.exitCode=1;return}const y=typeof e.role=="string"?e.role.slice(0,200):null;r(g,u,h,y),b(`${h} joined run ${u}${y?` as ${y}`:""}.`);break}case"end":{const u=c(e.run);if(!u){f("Usage: wyrm run end --run <RUNID> [--status completed|failed|abandoned]"),process.exitCode=1;return}if(!o(g,u)){f(`Run not found: ${u}`),process.exitCode=1;return}const h=typeof e.status=="string"?e.status:"completed",w=["completed","failed","abandoned"].includes(h)?h:"completed";t(g,u,w),b(`Run ${u} ended (${w}).`);break}case"status":{const u=c(e.run);if(!u){f("Usage: wyrm run status --run <RUNID>"),process.exitCode=1;return}const h=o(g,u);if(!h){f(`Run not found: ${u}`),process.exitCode=1;return}const y=n(g,u);S(`Run ${h.run_id} [${h.status}]`),h.orchestrator&&console.log(p.bold("Orchestrator: ")+h.orchestrator),h.parent_run_id&&console.log(p.bold("Parent: ")+h.parent_run_id),console.log(p.bold("Created: ")+h.created_at),console.log(p.bold("Updated: ")+h.updated_at),y.length>0?console.log(P(["Agent","Role","Joined"],y.map(w=>[w.agent_id,w.role??"",w.joined_at]))):console.log(p.dim(" No agents registered."));break}default:f("Usage: wyrm run <start|join|end|status> [options]"),console.log(" wyrm run start [--orchestrator NAME] [--agent ID] [--parent RUNID]"),console.log(" wyrm run join --run RUNID --agent ID [--role ROLE]"),console.log(" wyrm run end --run RUNID [--status completed|failed|abandoned]"),console.log(" wyrm run status --run RUNID"),process.exitCode=1;return}}finally{m.close()}}if(O==="--version"||O==="-v"||O==="version"){const l=M();console.log(`${l.name??"wyrm-mcp"} v${l.version??"unknown"}`)}else!O||O==="--help"||O==="-h"||O==="help"?be():(async()=>{try{switch(O){case"search":await Ve($);break;case"ls":await Ke($);break;case"show":await Ge($);break;case"capture":await Je($);break;case"rehydrate":await Qe($);break;case"session":await tt($);break;case"presence":await ot($);break;case"digest":await ze($);break;case"bridge":await et($);break;case"metabolize":await Ze($);break;case"entities":await Xe($);break;case"render":await st($);break;case"reverse-bridge":await nt($);break;case"import":await rt($);break;case"stats":await ct($);break;case"review":await at($);break;case"sync":await lt($);break;case"cloud":{const{cmdCloud:l}=await import("./cloud/cli.js");await l($);break}case"grove":await Pt($);break;case"run":await It($);break;case"skill":await Dt($);break;case"prune":await dt($);break;case"license":await ut();break;case"login":await mt();break;case"activate":await ft($);break;case"maintenance":await gt($);break;case"index":await yt($);break;case"update":await wt($);break;case"prompt":await bt($);break;case"hours":await $t($);break;case"invoice":await vt($);break;case"agent":await kt($);break;case"feedback":await St($);break;case"setup":await jt($);break;case"intro":{const{renderIntro:l}=await import("./visibility.js");console.log(l(M().version??"unknown"));break}case"events":await Ct($);break;case"watch":await _t($);break;case"embed":await Rt($);break;case"harvest":await Et($);break;case"vault":await xt($);break;case"connector":case"connectors":await pt($);break;case"statusline":{const{installClaudeStatusline:l,removeClaudeStatusline:a}=await import("./autoconfig.js"),e=$.includes("--remove")?a():l();e?b(e.message):f("Claude Code not detected (~/.claude missing).");break}case"guard":{const{installWyrmGuardHooks:l,removeWyrmGuardHooks:a,wyrmGuardHookStatus:e}=await import("./autoconfig.js");if($.includes("--status")){const s=e();if(console.log(` settings: ${s.settingsPath}`),s.installed){b(`wyrm-guard hooks installed (${s.commands.length} entr${s.commands.length===1?"y":"ies"})`);for(const t of s.commands)console.log(p.dim(` ${t}`))}else console.log(p.yellow(" wyrm-guard hooks not installed \u2014 run: wyrm guard"));break}const i=$.includes("--remove")||$.includes("--uninstall")?a():l();i?i.action==="failed"?(f(i.message),process.exitCode=1):b(i.message):f("Claude Code not detected (~/.claude missing).");break}case"ui":case"dashboard":$.includes("--ui")||$.push("--ui");case"serve":{const l=$.includes("--ui");if(l){const{enableDevMode:s}=await import("./http-auth.js");s()}const{server:a}=await import("./http-fast.js"),e=parseInt(process.env.WYRM_PORT??process.env.PORT??"3333",10),i=process.env.WYRM_BIND_HOST||"127.0.0.1";a.listen(e,i,()=>{if(b(`Wyrm HTTP server running on ${i}:${e}`),process.env.WYRM_UI_READONLY==="1"&&console.log("\u{1F512} READ-ONLY mode: writes + off-box egress are blocked; safe to expose."),l){const s=`http://localhost:${e}/ui`;console.log(`\u{1F5A5}\uFE0F Dashboard: ${s}`),import("child_process").then(({spawn:t})=>{const r=process.platform;try{const o=r==="darwin"?t("open",[s],{stdio:"ignore",detached:!0}):r==="win32"?t("cmd",["/c","start","",s],{stdio:"ignore",detached:!0}):t("xdg-open",[s],{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}).catch(()=>{})}});break}default:f(`Unknown command: ${O}`),be(),process.exit(1)}}catch(l){f(String(l)),process.exit(1)}})();
198
+ wyrm grove policy <project|id> <private|cloud|team>`),t.close(),process.exit(1)}async function Lt(l){const c=l[0],{flags:t}=C(l.slice(1)),{ulid:i}=await import("./ulid.js"),{createRun:r,setRunStatus:e,registerAgent:s,getRun:o,getAgents:n}=await import("./handlers/run.js"),{sanitizeActorId:p}=await import("./handlers/boundary.js"),a=f=>typeof f=="string"?p(f):null,u=j(),g=u.getDatabase();try{switch(c){case"start":{const f=(typeof t.orchestrator=="string"?t.orchestrator:"cli").slice(0,200),y=a(t.agent)??p(f)??"cli",h=a(t.parent);if(h&&!o(g,h)){m(`Parent run not found: ${h}`),process.exitCode=1;return}const w=i();r(g,w,h,f),s(g,w,y,"orchestrator"),process.stdout.write(w+`
199
+ `),process.stderr.write(`Run ${w} started by ${f}.
200
+ `);break}case"join":{const f=a(t.run),y=a(t.agent);if(!f||!y){m("Usage: wyrm run join --run <RUNID> --agent <ID> [--role <ROLE>]"),process.exitCode=1;return}if(!o(g,f)){m(`Run not found: ${f}`),process.exitCode=1;return}const h=typeof t.role=="string"?t.role.slice(0,200):null;s(g,f,y,h),b(`${y} joined run ${f}${h?` as ${h}`:""}.`);break}case"end":{const f=a(t.run);if(!f){m("Usage: wyrm run end --run <RUNID> [--status completed|failed|abandoned]"),process.exitCode=1;return}if(!o(g,f)){m(`Run not found: ${f}`),process.exitCode=1;return}const y=typeof t.status=="string"?t.status:"completed",w=["completed","failed","abandoned"].includes(y)?y:"completed";e(g,f,w),b(`Run ${f} ended (${w}).`);break}case"status":{const f=a(t.run);if(!f){m("Usage: wyrm run status --run <RUNID>"),process.exitCode=1;return}const y=o(g,f);if(!y){m(`Run not found: ${f}`),process.exitCode=1;return}const h=n(g,f);k(`Run ${y.run_id} [${y.status}]`),y.orchestrator&&console.log(d.bold("Orchestrator: ")+y.orchestrator),y.parent_run_id&&console.log(d.bold("Parent: ")+y.parent_run_id),console.log(d.bold("Created: ")+y.created_at),console.log(d.bold("Updated: ")+y.updated_at),h.length>0?console.log(D(["Agent","Role","Joined"],h.map(w=>[w.agent_id,w.role??"",w.joined_at]))):console.log(d.dim(" No agents registered."));break}default:m("Usage: wyrm run <start|join|end|status> [options]"),console.log(" wyrm run start [--orchestrator NAME] [--agent ID] [--parent RUNID]"),console.log(" wyrm run join --run RUNID --agent ID [--role ROLE]"),console.log(" wyrm run end --run RUNID [--status completed|failed|abandoned]"),console.log(" wyrm run status --run RUNID"),process.exitCode=1;return}}finally{u.close()}}if(O==="--version"||O==="-v"||O==="version"){const l=M();console.log(`${l.name??"wyrm-mcp"} v${l.version??"unknown"}`)}else!O||O==="--help"||O==="-h"||O==="help"?be():(async()=>{try{switch(O){case"search":await Ge(v);break;case"ls":await Je(v);break;case"show":await ze(v);break;case"capture":await Qe(v);break;case"rehydrate":await Ze(v);break;case"session":await st(v);break;case"presence":await rt(v);break;case"digest":await Xe(v);break;case"bridge":await ot(v);break;case"metabolize":await et(v);break;case"entities":await tt(v);break;case"render":await nt(v);break;case"reverse-bridge":await it(v);break;case"import":await at(v);break;case"stats":await lt(v);break;case"review":await dt(v);break;case"sync":await pt(v);break;case"cloud":{const{cmdCloud:l}=await import("./cloud/cli.js");await l(v);break}case"grove":await At(v);break;case"run":await Lt(v);break;case"skill":await Ot(v);break;case"prune":await ut(v);break;case"license":await ft();break;case"login":await gt();break;case"activate":await yt(v);break;case"maintenance":await ht(v);break;case"doctor":await wt(v);break;case"failure":await bt(v);break;case"project":await $t(v);break;case"index":await vt(v);break;case"update":await St(v);break;case"prompt":await _t(v);break;case"hours":await jt(v);break;case"invoice":await Ct(v);break;case"agent":await Et(v);break;case"feedback":await xt(v);break;case"setup":await Rt(v);break;case"intro":{const{renderIntro:l}=await import("./visibility.js");console.log(l(M().version??"unknown"));break}case"events":await Tt(v);break;case"watch":await Dt(v);break;case"embed":await It(v);break;case"harvest":await Pt(v);break;case"vault":await Nt(v);break;case"connector":case"connectors":await mt(v);break;case"statusline":{const{installClaudeStatusline:l,removeClaudeStatusline:c}=await import("./autoconfig.js"),t=v.includes("--remove")?c():l();t?b(t.message):m("Claude Code not detected (~/.claude missing).");break}case"guard":{const{installWyrmGuardHooks:l,removeWyrmGuardHooks:c,wyrmGuardHookStatus:t}=await import("./autoconfig.js");if(v.includes("--status")){const r=t();if(console.log(` settings: ${r.settingsPath}`),r.installed){b(`wyrm-guard hooks installed (${r.commands.length} entr${r.commands.length===1?"y":"ies"})`);for(const e of r.commands)console.log(d.dim(` ${e}`))}else console.log(d.yellow(" wyrm-guard hooks not installed \u2014 run: wyrm guard"));break}const i=v.includes("--remove")||v.includes("--uninstall")?c():l();i?i.action==="failed"?(m(i.message),process.exitCode=1):b(i.message):m("Claude Code not detected (~/.claude missing).");break}case"ui":case"dashboard":v.includes("--ui")||v.push("--ui");case"serve":{const l=v.includes("--ui");if(l){const{enableDevMode:r}=await import("./http-auth.js");r()}const{server:c}=await import("./http-fast.js"),t=parseInt(process.env.WYRM_PORT??process.env.PORT??"3333",10),i=process.env.WYRM_BIND_HOST||"127.0.0.1";c.listen(t,i,()=>{if(b(`Wyrm HTTP server running on ${i}:${t}`),process.env.WYRM_UI_READONLY==="1"&&console.log("\u{1F512} READ-ONLY mode: writes + off-box egress are blocked; safe to expose."),l){const r=`http://localhost:${t}/ui`;console.log(`\u{1F5A5}\uFE0F Dashboard: ${r}`),import("child_process").then(({spawn:e})=>{const s=process.platform;try{const o=s==="darwin"?e("open",[r],{stdio:"ignore",detached:!0}):s==="win32"?e("cmd",["/c","start","",r],{stdio:"ignore",detached:!0}):e("xdg-open",[r],{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}).catch(()=>{})}});break}default:m(`Unknown command: ${O}`),be(),process.exit(1)}}catch(l){m(String(l)),process.exit(1)}})();