wyrm-mcp 8.7.4 → 8.7.6
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/autoconfig.js +1 -1
- package/dist/index.js +2 -2
- package/dist/maintenance.js +2 -2
- package/dist/migrations.js +25 -17
- package/dist/served-records.js +5 -0
- package/dist/session-seen.js +3 -3
- package/dist/tool-manifest-v2.json +1 -1
- package/dist/tool-manifest.json +1 -1
- package/dist/wyrm-manifest.json +1 -1
- package/package.json +3 -2
- package/scripts/hooks/wyrm-citation-audit.mjs +120 -0
package/dist/autoconfig.js
CHANGED
|
@@ -4,7 +4,7 @@ import{existsSync as d,readFileSync as p,writeFileSync as l,mkdirSync as P,copyF
|
|
|
4
4
|
`)[0];break}}}catch{}}function ee(e,t){switch(t.configFormat){case"vscode":return e.mcp?.servers?.wyrm!==void 0;case"mcp-json":return e[t.mcpKey]?.wyrm!==void 0;case"zed":return e[t.mcpKey]?.wyrm!==void 0;default:return!1}}function T(){try{const n=v("which",["wyrm-mcp"],{encoding:"utf-8",timeout:5e3});if(n.stdout?.trim())return n.stdout.trim()}catch{}try{const s=v("npm",["root","-g"],{encoding:"utf-8",timeout:5e3}).stdout?.trim();if(s){const r=c(s,"wyrm-mcp","dist","index.js");if(d(r))return r}}catch{}const e=V(__dirname,"index.js");if(d(e))return e;const t=c(m(),".wyrm","node_modules","wyrm-mcp","dist","index.js");if(d(t))return t;const o=[c(m(),"Git Projects","Wyrm","packages","mcp-server","dist","index.js"),c(m(),"projects","Wyrm","packages","mcp-server","dist","index.js"),c(m(),"dev","Wyrm","packages","mcp-server","dist","index.js")];for(const n of o)if(d(n))return n;return"wyrm-mcp"}function D(){return c(m(),".wyrm","wyrm.db")}function ye(e="mcp-json",t){const o=t?.serverPath??T(),n=t?.dbPath??D(),s=o==="wyrm-mcp",r={command:s?"npx":"node",args:s?["wyrm-mcp"]:[o],env:{WYRM_DB_PATH:n}};switch(e){case"stdio":return r;case"vscode":return{mcp:{servers:{wyrm:r}}};default:return{mcpServers:{wyrm:r}}}}function te(e,t){const o=t.serverPath,n=o==="wyrm-mcp",s=o.endsWith(".js");switch(e.configFormat){case"vscode":return{command:n?"npx":"node",args:n?["wyrm-mcp"]:[o],env:{WYRM_DB_PATH:t.dbPath}};case"mcp-json":return{command:n?"npx":"node",args:n?["wyrm-mcp"]:[o],env:{WYRM_DB_PATH:t.dbPath}};case"zed":return{command:n?"npx":"node",args:n?["wyrm-mcp"]:[o],env:{WYRM_DB_PATH:t.dbPath}};default:return{}}}function U(e,t){if(!e.detected)return{client:e,action:"skipped",message:`${e.name} not detected`};try{const o=w(e.configPath);d(o)||P(o,{recursive:!0});let n={},s=!1;if(d(e.configPath))try{const a=p(e.configPath,"utf-8");n=$(a),s=!0}catch{n={}}let r;if(s){r=`${e.configPath}.wyrm-backup`,l(r,p(e.configPath),{mode:384});try{j(r,384)}catch{}}const i=te(e,t);switch(e.configFormat){case"vscode":{n.mcp||(n.mcp={});const a=n.mcp;a.servers||(a.servers={});const f=a.servers;f.wyrm=i;break}case"mcp-json":{n[e.mcpKey]||(n[e.mcpKey]={});const a=n[e.mcpKey];a.wyrm=i;break}case"zed":{n[e.mcpKey]||(n[e.mcpKey]={});const a=n[e.mcpKey];a.wyrm=i;break}}l(e.configPath,JSON.stringify(n,null,2)+`
|
|
5
5
|
`,"utf-8");const u=e.configured?"updated":"configured";return e.configured=!0,{client:e,action:u,message:`${e.name} ${u==="configured"?"configured":"updated"} successfully`,backup:r}}catch(o){return{client:e,action:"failed",message:`Failed to configure ${e.name}: ${o}`}}}function we(e,t){try{if(!d(e.configPath))return{client:e,action:"skipped",message:"No config file"};const o=p(e.configPath,"utf-8");let n;try{n=$(o)}catch{return{client:e,action:"failed",message:"Config file is not valid JSON; refusing to touch it"}}const r=(e.configFormat==="vscode"?n.mcp?.servers:n[e.mcpKey])?.wyrm;if(!r)return{client:e,action:"skipped",message:"Wyrm not configured in this client"};const i=`${e.configPath}.wyrm-backup`;l(i,o,{encoding:"utf-8",mode:384});try{j(i,384)}catch{}return r.env={...r.env,...t},l(e.configPath,JSON.stringify(n,null,2)+`
|
|
6
6
|
`,"utf-8"),{client:e,action:"updated",message:`env: ${Object.keys(t).join(", ")}`,backup:i}}catch(o){return{client:e,action:"failed",message:String(o)}}}function oe(e){if(!e.detected||!e.configured)return{client:e,action:"skipped",message:`${e.name} not configured`};try{if(!d(e.configPath))return{client:e,action:"skipped",message:`${e.name} config not found`};const t=p(e.configPath,"utf-8"),o=$(t),n=`${e.configPath}.wyrm-backup`;l(n,t,{mode:384});try{j(n,384)}catch{}switch(e.configFormat){case"vscode":{const r=o.mcp?.servers;r&&delete r.wyrm;break}case"mcp-json":case"zed":{const s=o[e.mcpKey];s&&delete s.wyrm;break}}return l(e.configPath,JSON.stringify(o,null,2)+`
|
|
7
|
-
`,"utf-8"),e.configured=!1,{client:e,action:"configured",message:`Removed Wyrm from ${e.name}`,backup:n}}catch(t){return{client:e,action:"failed",message:`Failed to remove from ${e.name}: ${t}`}}}function A(){return{id:"claude-code-hooks",name:"Claude Code (auto-memory)",icon:"\u{1FA9D}",configPath:c(m(),".claude","settings.json"),configFormat:"mcp-json",mcpKey:"",detected:!0,configured:!1}}const R=[{script:"wyrm-session-capture.mjs",events:["SessionEnd","PreCompact"]},{script:"wyrm-session-rehydrate.mjs",events:["SessionStart"]},{script:"wyrm-session-prune.mjs",events:["SessionEnd"]},{script:"wyrm-tool-call-trace.mjs",events:["PostToolUse"]},{script:"wyrm-run-auto.mjs",events:["SessionStart",{event:"PreToolUse",matcher:"Task"},"SessionEnd"]}];function ne(){const e=c(m(),".claude");if(!d(e))return null;const t=A();try{const o=c(e,"hooks");d(o)||P(o,{recursive:!0});const n=w(N(import.meta.url)),s=c(n,"..","scripts","hooks"),r=t.configPath;let i={};if(d(r))try{i=JSON.parse(p(r,"utf-8"))}catch{i={}}const u=i.hooks??{};let a=!1;const f=[];for(const h of R){const g=c(s,h.script);if(!d(g)){f.push(h.script);continue}const W=c(o,h.script);q(g,W);try{j(W,493)}catch{}const O=`node ${W}`;for(const k of h.events){const x=typeof k=="string"?k:k.event,M=typeof k=="string"?void 0:k.matcher,E=Array.isArray(u[x])?u[x]:[];if(!E.some(S=>Array.isArray(S.hooks)&&S.hooks.some(Y=>Y.command===O))){const S=M?{matcher:M,hooks:[{type:"command",command:O,timeout:30}]}:{hooks:[{type:"command",command:O,timeout:30}]};E.push(S),a=!0}u[x]=E}}i.hooks=u,l(r,JSON.stringify(i,null,2)+`
|
|
7
|
+
`,"utf-8"),e.configured=!1,{client:e,action:"configured",message:`Removed Wyrm from ${e.name}`,backup:n}}catch(t){return{client:e,action:"failed",message:`Failed to remove from ${e.name}: ${t}`}}}function A(){return{id:"claude-code-hooks",name:"Claude Code (auto-memory)",icon:"\u{1FA9D}",configPath:c(m(),".claude","settings.json"),configFormat:"mcp-json",mcpKey:"",detected:!0,configured:!1}}const R=[{script:"wyrm-session-capture.mjs",events:["SessionEnd","PreCompact"]},{script:"wyrm-session-rehydrate.mjs",events:["SessionStart"]},{script:"wyrm-session-prune.mjs",events:["SessionEnd"]},{script:"wyrm-tool-call-trace.mjs",events:["PostToolUse"]},{script:"wyrm-run-auto.mjs",events:["SessionStart",{event:"PreToolUse",matcher:"Task"},"SessionEnd"]},{script:"wyrm-citation-audit.mjs",events:["Stop"]}];function ne(){const e=c(m(),".claude");if(!d(e))return null;const t=A();try{const o=c(e,"hooks");d(o)||P(o,{recursive:!0});const n=w(N(import.meta.url)),s=c(n,"..","scripts","hooks"),r=t.configPath;let i={};if(d(r))try{i=JSON.parse(p(r,"utf-8"))}catch{i={}}const u=i.hooks??{};let a=!1;const f=[];for(const h of R){const g=c(s,h.script);if(!d(g)){f.push(h.script);continue}const W=c(o,h.script);q(g,W);try{j(W,493)}catch{}const O=`node ${W}`;for(const k of h.events){const x=typeof k=="string"?k:k.event,M=typeof k=="string"?void 0:k.matcher,E=Array.isArray(u[x])?u[x]:[];if(!E.some(S=>Array.isArray(S.hooks)&&S.hooks.some(Y=>Y.command===O))){const S=M?{matcher:M,hooks:[{type:"command",command:O,timeout:30}]}:{hooks:[{type:"command",command:O,timeout:30}]};E.push(S),a=!0}u[x]=E}}i.hooks=u,l(r,JSON.stringify(i,null,2)+`
|
|
8
8
|
`,"utf-8"),t.configured=!0;const y=f.length?` (missing from package: ${f.join(", ")})`:"";return{client:t,action:a?"configured":"skipped",message:(a?"auto-memory hooks installed":"already installed")+y}}catch(o){return{client:t,action:"failed",message:o instanceof Error?o.message:String(o)}}}function ve(){const e=c(m(),".claude");if(!d(e))return null;const t=A();try{const o=w(N(import.meta.url)),n=`node ${c(o,"wyrm-statusline.js")}`,s=t.configPath;let r={};if(d(s))try{r=JSON.parse(p(s,"utf-8"))}catch{r={}}const i=r.statusLine;if(i?.command&&!/wyrm-statusline/.test(i.command))return{client:t,action:"skipped",message:`a non-Wyrm statusLine is already set (${i.command}); not overwriting`};const u=i?.command===n;return r.statusLine={type:"command",command:n,padding:0},l(s,JSON.stringify(r,null,2)+`
|
|
9
9
|
`,"utf-8"),{client:t,action:u?"skipped":"configured",message:u?"buddy statusline already installed":"Wyrm buddy statusline installed \u2014 persistent in the Claude Code TUI"}}catch(o){return{client:t,action:"failed",message:o instanceof Error?o.message:String(o)}}}function ke(){const e=c(m(),".claude","settings.json");if(!d(e))return null;const t=A();try{const o=JSON.parse(p(e,"utf-8")),n=o.statusLine;return n?.command&&/wyrm-statusline/.test(n.command)?(delete o.statusLine,l(e,JSON.stringify(o,null,2)+`
|
|
10
10
|
`,"utf-8"),{client:t,action:"configured",message:"Wyrm statusline removed"}):{client:t,action:"skipped",message:"no Wyrm statusline set"}}catch(o){return{client:t,action:"failed",message:o instanceof Error?o.message:String(o)}}}function re(){const e=c(m(),".claude","settings.json");if(!d(e))return null;const t=A();try{const o=JSON.parse(p(e,"utf-8")),n=c(m(),".claude","hooks"),s=new Set(R.map(u=>`node ${c(n,u.script)}`)),r=new Set(R.flatMap(u=>u.events.map(a=>typeof a=="string"?a:a.event))),i=o.hooks;if(i){for(const u of r)Array.isArray(i[u])&&(i[u]=i[u].map(a=>({...a,hooks:Array.isArray(a.hooks)?a.hooks.filter(f=>!s.has(f.command??"")):a.hooks})).filter(a=>!Array.isArray(a.hooks)||a.hooks.length>0),i[u].length===0&&delete i[u]);Object.keys(i).length===0&&delete o.hooks}return l(e,JSON.stringify(o,null,2)+`
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Server as
|
|
3
|
-
`).map(E=>E.trim()).filter(Boolean).join(" ").slice(0,500));const S=m[1].match(/category:\s*([^\n]+)/);S&&(u=S[1].trim())}r.registerSkill(i.name,a,i.path,u,"Ghost Protocol",void 0,"bundled"),_++}catch{}_>0&&console.error(`Wyrm: Registered ${_} bundled skill(s) on first start.`);try{
|
|
2
|
+
import{Server as fe}from"@modelcontextprotocol/sdk/server/index.js";import{StdioServerTransport as de}from"@modelcontextprotocol/sdk/server/stdio.js";import{CallToolRequestSchema as ge,GetPromptRequestSchema as he,ListPromptsRequestSchema as we,ListResourcesRequestSchema as Se,ListResourceTemplatesRequestSchema as Re,ListToolsRequestSchema as ve,ReadResourceRequestSchema as ke}from"@modelcontextprotocol/sdk/types.js";import{WyrmDB as be,resolveDbPath as Ee}from"./database.js";import{ValidationError as U}from"./validate.js";import{validationErrorResponse as q,cacheKeyFor as De}from"./render.js";import{handlerRegistry as h,registryToolDefs as Ce,applyDeclaredOutputSchemas as Te,buildStableToolList as Oe}from"./handlers/registry.js";import{resolveActorEnvelope as V,runWithActor as J,getActor as xe,runWithReadCacheKey as Me}from"./handlers/boundary.js";import{resolveAliasCall as We}from"./handlers/aliases.js";import{resolveShimCall as Pe,shimToolDefs as Ae}from"./handlers/shims.js";import{getPromptResult as Ie,wyrmPromptList as Ne}from"./handlers/prompts.js";import{listWyrmResources as Le,listWyrmResourceTemplates as Ye,readWyrmResource as je,ResourceNotFoundError as Fe}from"./handlers/resources.js";import{TaskStore as Be,resolveTaskGate as Ke,runLongOp as Ge}from"./tasks.js";import{registerTaskHandlers as He,finalizeEarly as Ue,unwrapOutcome as qe,applyAdminGate as Ve}from"./tasks-dispatch.js";import{ReplicationManager as Je}from"./replication-daemon.js";import{WYRM_SERVER_INSTRUCTIONS as $e}from"./priority-embed.js";import{WyrmSync as ze}from"./sync.js";import{cache as w,estimateTokens as W}from"./performance.js";import{readFileSync as $,unlinkSync as Qe,existsSync as z}from"fs";import{join as Xe}from"path";import{initializeOrchestrator as Ze}from"./auto-orchestrator.js";import{getCrypto as et,initializeCrypto as tt}from"./crypto.js";import{initVectorSearch as rt}from"./vector-init.js";import{KnowledgeGraph as ot}from"./knowledge-graph.js";import{MemoryArtifacts as st}from"./memory-artifacts.js";import{GroundTruths as nt,ReasoningScaffolds as at}from"./intelligence.js";import{classifyCapture as $o}from"./capture.js";import{initializeLicense as it,getLicenseInfo as ct}from"./license.js";import{refreshRevocations as Q}from"./revocations.js";import{refreshLicenseIfNeeded as X}from"./license-refresh.js";import{activationSatisfied as mt,activationGateResult as lt}from"./activation.js";import{WyrmAnalytics as pt}from"./analytics.js";import{WyrmCloudBackup as _t}from"./cloud-backup.js";import{CloudSyncManager as ut}from"./cloud-sync.js";import{FailurePatterns as yt}from"./failure-patterns.js";import{AgentPresence as ft}from"./presence.js";import{Causality as dt}from"./causality.js";import{wireTruthAutoCascade as gt}from"./truth-cascade.js";import{SymbolGraph as ht}from"./symbols.js";import{HourLedger as wt}from"./hours.js";import{ToolAnalytics as St}from"./tool-analytics.js";import{Rehydration as Rt}from"./rehydration.js";import{AuditLog as vt,loadAuditSignerFromEnv as kt}from"./audit.js";import{retryableWriteCause as bt,busyErrorResponse as Et}from"./sqlite-busy.js";import{SubAgent as Dt}from"./sub-agent.js";import{Federation as Ct}from"./federation.js";import{Goals as Tt}from"./goals.js";import{OutboundMcpClient as Ot}from"./mcp-client.js";import{AgentLoop as xt}from"./agent-loop.js";import{makeInternalDispatch as Mt}from"./internal-dispatch.js";import{createUsageTracker as Wt}from"./usage-tracker.js";import{AgentDaemon as Pt}from"./agent-daemon.js";import{emitStartupVersionBanner as At}from"./version-check.js";import{resolveProfile as It,filterByProfile as Nt}from"./tool-profiles.js";import{annotateTools as Lt,elideDefaultAnnotations as Yt}from"./tool-annotations.js";import{applyDeprecationNotices as jt,noteDeprecatedToolInvocation as Ft,isHardCliExile as Bt,cliExileRedirectResponse as Kt}from"./deprecations.js";import{goldenCapture as f}from"./golden.js";import{makeEstimator as Gt}from"./token-budget.js";import{makeRunBudgetedContextBuild as Ht}from"./context-build-budgeted.js";import{assembleThread as Ut}from"./thread-assemble.js";import{getThread as qt}from"./thread-store.js";import{renderThreadForContext as Z}from"./handlers/thread.js";import{makeRunCompanionBuddy as Vt}from"./buddy-runner.js";import{loadWeightsFromEnv as Jt}from"./context-ranking.js";import{SessionSeen as $t}from"./session-seen.js";import{recordServed as zt}from"./served-records.js";import{DesignSystem as Qt}from"./design.js";import{fileURLToPath as Xt}from"url";import{dirname as Zt,join as ee}from"path";import{readFileSync as er,existsSync as tr}from"fs";const rr=137;let P=null;function or(){return P||(P=new Qt(r.getDatabase())),P}const sr=Gt(),nr=Jt();let A=null;function te(){return A||(A=new $t(r.getDatabase())),A}const C=(()=>{try{const e=Zt(Xt(import.meta.url));for(const t of[ee(e,"..","package.json"),ee(e,"..","..","package.json")])if(tr(t)){const s=JSON.parse(er(t,"utf-8")).version;if(typeof s=="string")return s}}catch{}return"unknown"})(),r=new be(Ee()),ar=new ze(r),re=new ot(r.getDatabase()),R=new st(r.getDatabase()),v=new nt(r.getDatabase()),I=new at(r.getDatabase()),N=new yt(r.getDatabase()),L=new ft(r.getDatabase()),Y=new dt(r.getDatabase());gt(v,Y);const j=new ht(r.getDatabase()),ir=new wt(r.getDatabase()),k=new St(r.getDatabase()),cr=Ht({groundTruths:v,scaffoldLib:I,memory:R,toolAnalytics:k,sessionSeen:te,tokenEstimator:sr,rankWeights:nr,threadText:e=>{try{return Z(Ut(r.getDatabase(),e))}catch{try{const t=qt(r.getDatabase(),e);return t?Z(t):""}catch{return""}}}}),oe=new Rt(r.getDatabase()),mr=new vt(r.getDatabase(),kt()),lr=new Dt(r.getDatabase()),se=new Ct(r.getDatabase()),ne=new Tt(r.getDatabase()),ae={projects:r,goals:ne,getActor:xe,store:r,raw:()=>r.getDatabase(),memory:R,truths:v,scaffolds:I,failures:N,presence:L,rehydration:oe,graph:re,symbols:j,vectors:()=>T,indexing:()=>K,cache:w,decrypt:e=>B.maybeDecrypt(e),clientSupportsResources:()=>{const e=c.getClientCapabilities()?.experimental;return!!e&&"resources"in e}},F=new Ot(r.getDatabase()),pr=Vt({db:r,mcpClient:F,version:C}),_r=new Pt(r.getDatabase()),ur=Mt({db:r,failures:N,symbols:j,rehydration:oe,causality:Y,presence:L,federation:se,memory:R,groundTruths:v}),yr=new xt(r.getDatabase(),F,ur);if(process.env.WYRM_ENCRYPTION_KEY)try{tt(process.env.WYRM_ENCRYPTION_KEY)}catch(e){console.error("Wyrm: Failed to initialize encryption:",e)}const B=et();let T=null,K=null;{const e=rt(r,R,B);T=e.vectorStore,K=e.indexingPipeline}const fr=Ze({autoOrchestrateEnabled:!0,minConfidenceThreshold:65,maxParallelAgents:6,defaultHaikuBoosting:!0,trackMetrics:!0});it();const O=ct();O.tier!=="free"&&console.error(`Wyrm: Licensed \u2014 ${O.tier} tier (expires: ${O.expiresAt||"never"})`);const dr=!!O.key&&!/^(0|false|no|off)$/i.test(process.env.WYRM_LICENSE_REFRESH??"");dr&&(Promise.all([Q(),X()]).catch(()=>{}),setInterval(()=>{Promise.all([Q(),X()]).catch(()=>{})},1440*60*1e3).unref?.());try{const e=process.env.HOME||process.env.USERPROFILE||"",t=Xe(e,".wyrm","bundled-skills.json");if(e&&z(t)){const s=JSON.parse($(t,"utf-8"));let _=0;for(const i of s.skills)try{if(!z(i.path))continue;const m=$(i.path,"utf-8").match(/^---\s*\n([\s\S]*?)\n---/);let a=i.name,u;if(m){const g=m[1].match(/description:\s*\|?\s*\n([\s\S]*?)(?:\nname:|\nmetadata:|\ncategory:|\ntype:|$)/);g&&(a=g[1].split(`
|
|
3
|
+
`).map(E=>E.trim()).filter(Boolean).join(" ").slice(0,500));const S=m[1].match(/category:\s*([^\n]+)/);S&&(u=S[1].trim())}r.registerSkill(i.name,a,i.path,u,"Ghost Protocol",void 0,"bundled"),_++}catch{}_>0&&console.error(`Wyrm: Registered ${_} bundled skill(s) on first start.`);try{Qe(t)}catch{}}}catch{}const G=new pt(r.getDatabase()),ie=new _t;process.env.WYRM_R2_ENDPOINT&&process.env.WYRM_R2_ACCESS_KEY&&process.env.WYRM_R2_SECRET_KEY&&ie.configure({endpoint:process.env.WYRM_R2_ENDPOINT,bucket:process.env.WYRM_R2_BUCKET||"wyrm-backups",accessKeyId:process.env.WYRM_R2_ACCESS_KEY,secretAccessKey:process.env.WYRM_R2_SECRET_KEY},process.env.WYRM_ENCRYPTION_KEY);import{fileURLToPath as gr}from"url";import{dirname as hr,join as ce}from"path";const wr=gr(import.meta.url),me=hr(wr),Sr=new ut(ce(me,"cloud-sync-entrypoint.js")),Rr=new Je(ce(me,"replication-daemon-entrypoint.js")),{trackUsage:d,getUsageStats:vr,usageLog:kr}=Wt(G),br=new Map;function Er(e,t=!1){return{content:[{type:"text",text:e}]}}const Dr=new Set(["wyrm_list_projects","wyrm_project_context","wyrm_global_context","wyrm_all_quests","wyrm_data_query","wyrm_data_categories","wyrm_search","wyrm_stats","wyrm_skill_list","wyrm_skill_get","wyrm_skill_search","wyrm_skill_stats","wyrm_orchestration_config","wyrm_orchestration_stats","wyrm_license","wyrm_analytics_dashboard","wyrm_cost_report","wyrm_entity_search","wyrm_entity_graph","wyrm_entity_path","wyrm_truth_get","wyrm_scaffold_get","wyrm_session_prime"]);function Cr(e,t){return!(!Dr.has(e)||e==="wyrm_session_prime"&&(t?.run_id===void 0||t?.run_id===null))}const le=new Set(["wyrm_session_start","wyrm_session_update","wyrm_quest_add","wyrm_quest_complete","wyrm_data_insert","wyrm_data_batch_insert","wyrm_set_global","wyrm_scan_projects","wyrm_sync","wyrm_maintenance","wyrm_vector_setup","wyrm_reindex","wyrm_skill_register","wyrm_skill_delete","wyrm_skill_activate","wyrm_skill_deactivate","wyrm_spec_register","wyrm_activate","wyrm_cloud_backup","wyrm_cloud_sync","wyrm_encrypt_setup","wyrm_entity_add","wyrm_entity_link","wyrm_entity_merge","wyrm_remember","wyrm_recall","wyrm_feedback","wyrm_truth_set","wyrm_scaffold_save","wyrm_distill","wyrm_review","wyrm_capture","wyrm_import_git","wyrm_import_pr","wyrm_import_rules","wyrm_inject_prompt","wyrm_prune","wyrm_sync_export","wyrm_sync_import"]),b=new Be,c=new fe({name:"wyrm",version:C},{capabilities:{tools:{},prompts:{},resources:{},tasks:{list:{},cancel:{},requests:{tools:{call:{}}}}},instructions:$e}),pe={...ae,db:r,sync:ar,graph:re,memory:R,groundTruths:v,scaffoldLib:I,failures:N,presence:L,causality:Y,symbols:j,hours:ir,toolAnalytics:k,auditLog:mr,subAgent:lr,federation:se,goals:ne,mcpClient:F,agentDaemon:_r,agentLoop:yr,analytics:G,cloudBackup:ie,cloudSyncManager:Sr,replicationManager:Rr,orchestrator:fr,server:c,wyrmCrypto:B,get vectorStore(){return T},get indexingPipeline(){return K},setVectorStore:e=>{T=e},WYRM_PACKAGE_VERSION:C,WYRM_TOOL_COUNT:rr,WRITE_TOOLS:le,usageLog:kr,responseFingerprints:br,designSystem:or,sessionSeen:te,cachedResponse:Er,getUsageStats:vr,runCompanionBuddy:pr,runBudgetedContextBuild:cr};c.setRequestHandler(ve,async()=>{const e=[...Ce(),...Ae()],t=It();return{tools:Oe(Te(jt(Yt(Lt(Nt(e,t))))))}}),c.setRequestHandler(we,async()=>({prompts:[...Ne()]})),c.setRequestHandler(he,async e=>{const t=e.params.arguments??{},s=V({args:t,meta:e.params._meta,clientName:c.getClientVersion()?.name});return J(s,()=>Ie(e.params.name,t,ae))}),c.setRequestHandler(Se,async()=>({resources:Le()})),c.setRequestHandler(Re,async()=>({resourceTemplates:Ye()})),c.setRequestHandler(ke,async e=>{const t=e.params.uri;try{const s=je(t,pe),{nextCursor:_,...i}=s;return _?{contents:[i],_meta:{"wyrm/nextCursor":_}}:{contents:[i]}}catch(s){throw s instanceof Fe?new Error(s.message):s}}),He(c,b),c.setRequestHandler(ge,async e=>{const{name:t,arguments:s}=e.params;if(!mt())return lt();const _=V({args:s??{},meta:e.params._meta,clientName:c.getClientVersion()?.name});Ft(t);const i=performance.now(),x=JSON.stringify(s||{}),m=W(x);let a,u,g=null;try{const o=We(t,s??{});o.via?.kind==="cli-exile"&&(g=o.via),{tool:a,args:u}=Pe(o.tool,o.args)}catch(o){if(o instanceof U){const n=Math.round(performance.now()-i);d({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()});const l=q(t,o.field,o.message);return f({tool:t,args:s,meta:e.params._meta,response:l,outcome:"validation_error",ms:n,dispatch:"switch"}),l}throw o}if(g&&Bt(g.name)){const o=Math.round(performance.now()-i);d({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:o,timestamp:new Date().toISOString()});const n=Kt(g.name);return f({tool:t,args:s,meta:e.params._meta,response:n,outcome:"soft_error",ms:o,dispatch:"switch"}),n}const S=Ke(c.getClientCapabilities()?.tasks,e.params),E=Ve(b,S,a,o=>{const n=Math.round(performance.now()-i);d({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()}),f({tool:t,args:s,meta:e.params._meta,response:o,outcome:"soft_error",ms:n,dispatch:h.has(a)?"registry":"switch"})});if(E!==null)return E;const _e=a===t?x:JSON.stringify(u),M=Cr(a,u??{})?De(a,_e):null;if(M){const o=w.get(M);if(o){const n=Math.round(performance.now()-i),l=W(JSON.stringify(o));d({tool:t,tokens_in:m,tokens_out:l,cached:!0,ms:n,timestamp:new Date().toISOString()});const p={...o};return f({tool:t,args:s,meta:e.params._meta,response:p,cached:!0,ms:n,dispatch:h.has(a)?"registry":"switch"}),Ue(b,S,a,p)}}if(le.has(a)){const o=u?.projectPath;o&&w.invalidate(o),w.invalidate("wyrm_list_projects"),w.invalidate("wyrm_global_context"),w.invalidate("wyrm_all_quests"),w.invalidate("wyrm_stats")}let D;const ue=u||{};try{const o=await J(_,async()=>{const H=h.get(a);return H?await Ge(a,S,b,()=>Me(M,()=>H(ue,pe))):{kind:"inline",result:{content:[{type:"text",text:`Unknown tool: ${a}`}],isError:!0}}}),{wireValue:n,payload:l}=qe(b,o);D=l;const p=Math.round(performance.now()-i),y=JSON.stringify(D),ye=W(y);return zt(r.getDatabase(),y),d({tool:t,tokens_in:m,tokens_out:ye,cached:!1,ms:p,timestamp:new Date().toISOString()}),k.log({tool_name:t,args:s,success:!D?.isError,latency_ms:p}),f({tool:t,args:s,meta:e.params._meta,response:D,ms:p,dispatch:h.has(a)?"registry":"switch"}),n}catch(o){const n=Math.round(performance.now()-i);if(o instanceof U){d({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()});const y=q(t,o.field,o.message);return f({tool:t,args:s,meta:e.params._meta,response:y,outcome:"validation_error",ms:n,dispatch:h.has(a)?"registry":"switch"}),y}const l=bt(o);if(l!==null){d({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()}),k.log({tool_name:t,args:s,success:!1,error_message:`WYRM_BUSY[${l}]: ${String(o).slice(0,400)}`,latency_ms:n});const y=Et(t,l);return f({tool:t,args:s,meta:e.params._meta,response:y,outcome:"error",ms:n,dispatch:h.has(a)?"registry":"switch"}),y}d({tool:t,tokens_in:m,tokens_out:0,cached:!1,ms:n,timestamp:new Date().toISOString()}),k.log({tool_name:t,args:s,success:!1,error_message:String(o).slice(0,500),latency_ms:n});const p={content:[{type:"text",text:`Error: ${o}`}],isError:!0};return f({tool:t,args:s,meta:e.params._meta,response:p,outcome:"error",ms:n,dispatch:h.has(a)?"registry":"switch"}),p}}),process.on("uncaughtException",e=>{try{console.error("Wyrm[uncaughtException]:",e instanceof Error?e.stack:e)}catch{}}),process.on("unhandledRejection",e=>{try{console.error("Wyrm[unhandledRejection]:",e instanceof Error?e.stack:e)}catch{}});async function Tr(){const e=new de;await c.connect(e),At(r.getDatabase(),C).catch(()=>{});const t=()=>{try{G.shutdown()}catch{}process.exit(0)};process.on("SIGINT",t),process.on("SIGTERM",t)}Tr().catch(console.error);export{$o as classifyCapture};
|
package/dist/maintenance.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{pruneWriteLedger as _}from"./receipts.js";import{metabolizeEnabled as E,metabolizeDefaultEnabled as
|
|
1
|
+
import{pruneWriteLedger as _}from"./receipts.js";import{metabolizeEnabled as E,metabolizeDefaultEnabled as h,runMetabolize as f}from"./metabolize.js";import{ServedRecords as l}from"./served-records.js";function y(c,o={}){const{db:n,sessionSeen:d,failures:a,presence:u}=c,{vacuum:p,archiveDays:i}=o,t=[];if(i){const e=n.getAllProjects(1e3);let r=0;for(const s of e)r+=n.archiveOldSessions(s.id,i);t.push(`Archived ${r} old sessions`)}p&&(n.vacuum(),t.push("Vacuumed database"));try{const e=parseInt(process.env.WYRM_SEEN_TTL_DAYS??"7",10),r=d.prune(Number.isFinite(e)&&e>0?e:7);r>0&&t.push(`Pruned ${r} session_seen_artifacts rows older than ${e}d`)}catch{}try{const e=parseInt(process.env.WYRM_SEEN_TTL_DAYS??"7",10),r=Number.isFinite(e)&&e>0?e:7,s=new l(n.getDatabase()).prune(r);s>0&&t.push(`Pruned ${s} served_records rows older than ${r}d`)}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),r=parseInt(process.env.WYRM_EVENT_MAX_PER_PROJECT??"5000",10),{deleted:s}=n.pruneEvents({olderThanDays:Number.isFinite(e)?e:90,maxPerProject:Number.isFinite(r)?r:5e3});s>0&&t.push(`Pruned ${s} Live Memory events (retention)`)}catch{}try{if(h()){const e=f(n.getDatabase(),{near:E()});e.exactMerged+e.nearCandidatesQueued+e.decayed>0&&t.push(`Metabolize: ${e.exactMerged} exact dupes superseded, ${e.nearCandidatesQueued} near-dup candidates queued, ${e.decayed} stale auto-captures decayed`)}}catch{}try{const e=_(n.getDatabase());e>0&&t.push(`Pruned ${e} write_ledger receipts (retention)`)}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),r=Number.isFinite(e)&&e>0?e:90,s=a.pruneBlocks(r);s>0&&t.push(`Pruned ${s} failure_blocks rows older than ${r}d (retention)`)}catch{}try{const e=u.reap();(e.presence>0||e.claims>0)&&t.push(`Reaped ${e.presence} stale presence row(s) and ${e.claims} expired quest claim(s)`)}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),r=Number.isFinite(e)&&e>0?e:90,s=n.getDatabase().prepare("DELETE FROM run_briefs WHERE created_at < datetime('now', ?)").run(`-${r} days`).changes;s>0&&t.push(`Pruned ${s} run_briefs rows older than ${r}d (retention)`)}catch{}try{const e=parseInt(process.env.WYRM_RUN_BRIEFS_MAX??"512",10),r=Number.isFinite(e)&&e>0?e:512,s=n.getDatabase().prepare(`
|
|
2
2
|
DELETE FROM run_briefs WHERE rowid IN (
|
|
3
3
|
SELECT rowid FROM run_briefs ORDER BY created_at DESC, rowid DESC LIMIT -1 OFFSET ?
|
|
4
|
-
)`).run(r).changes;
|
|
4
|
+
)`).run(r).changes;s>0&&t.push(`Pruned ${s} run_briefs rows over the ${r}-row cap (WYRM_RUN_BRIEFS_MAX)`)}catch{}try{const e=parseInt(process.env.WYRM_RUN_INACTIVE_HOURS??"24",10),r=a.sweepRunQuarantine({runInactiveHours:Number.isFinite(e)&&e>0?e:24});(r.promoted>0||r.expired>0||r.runs_abandoned>0)&&t.push(`Run-quarantine sweep: promoted ${r.promoted} failure(s), expired ${r.expired} abandoned-run failure(s), TTL-abandoned ${r.runs_abandoned} stalled run(s)`),r.degraded&&t.push(`Run-quarantine sweep: ${r.degraded}`)}catch{}return n.checkpoint(),t.push("Checkpointed WAL"),{lines:t,dbSize:n.getStats().dbSize}}export{y as runMaintenance};
|
package/dist/migrations.js
CHANGED
|
@@ -210,7 +210,7 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
|
|
|
210
210
|
timestamp TEXT DEFAULT (datetime('now'))
|
|
211
211
|
);
|
|
212
212
|
CREATE INDEX IF NOT EXISTS idx_usage_timestamp ON usage_events(timestamp);
|
|
213
|
-
`)}},{version:3,description:"Add visibility and created_by columns for future multi-user support",up:e=>{const s=["sessions","quests","context","data_lake"];for(const t of s){const
|
|
213
|
+
`)}},{version:3,description:"Add visibility and created_by columns for future multi-user support",up:e=>{const s=["sessions","quests","context","data_lake"];for(const t of s){const E=e.prepare(`PRAGMA table_info(${t})`).all().map(T=>T.name);E.includes("visibility")||e.exec(`ALTER TABLE ${t} ADD COLUMN visibility TEXT DEFAULT 'private'`),E.includes("created_by")||e.exec(`ALTER TABLE ${t} ADD COLUMN created_by TEXT DEFAULT 'local'`)}}},{version:4,description:"Knowledge graph \u2014 entities, aliases, relationships with FTS5",up:e=>{e.exec(`
|
|
214
214
|
-- Entities: named things that can be linked together
|
|
215
215
|
CREATE TABLE IF NOT EXISTS entities (
|
|
216
216
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
@@ -844,7 +844,7 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
|
|
|
844
844
|
ON token_savings_log(session_id, timestamp DESC);
|
|
845
845
|
CREATE INDEX IF NOT EXISTS idx_savings_category
|
|
846
846
|
ON token_savings_log(category, timestamp DESC);
|
|
847
|
-
`);const s=["ground_truths","memory_artifacts","quests","decision_edges","design_references","design_tokens"];for(const t of s)try{if(e.prepare(`PRAGMA table_info(${t})`).all().some(
|
|
847
|
+
`);const s=["ground_truths","memory_artifacts","quests","decision_edges","design_references","design_tokens"];for(const t of s)try{if(e.prepare(`PRAGMA table_info(${t})`).all().some(E=>E.name==="cross_project_visibility"))continue;e.exec(`
|
|
848
848
|
ALTER TABLE ${t} ADD COLUMN cross_project_visibility TEXT NOT NULL DEFAULT 'within'
|
|
849
849
|
CHECK (cross_project_visibility IN ('within', 'org', 'public'));
|
|
850
850
|
`)}catch{}}},{version:15,description:"Live Memory v6.4 \u2014 append-only events log + wyrm_meta (device identity)",up:e=>{e.exec(`
|
|
@@ -908,7 +908,7 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
|
|
|
908
908
|
`)}},{version:17,description:'Backfill cross_project_visibility on decision_edges (migration 14 named a non-existent "decisions" table)',up:e=>{try{e.prepare("PRAGMA table_info(decision_edges)").all().some(t=>t.name==="cross_project_visibility")||e.exec(`
|
|
909
909
|
ALTER TABLE decision_edges ADD COLUMN cross_project_visibility TEXT NOT NULL DEFAULT 'within'
|
|
910
910
|
CHECK (cross_project_visibility IN ('within', 'org', 'public'));
|
|
911
|
-
`)}catch{}}},{version:18,description:"GOD-SKILL SPEC v2 \u2014 skill tier/governs/composes + spec-kit registry (specs table)",up:e=>{const s=e.prepare("PRAGMA table_info(skills)").all(),t=
|
|
911
|
+
`)}catch{}}},{version:18,description:"GOD-SKILL SPEC v2 \u2014 skill tier/governs/composes + spec-kit registry (specs table)",up:e=>{const s=e.prepare("PRAGMA table_info(skills)").all(),t=i=>s.some(E=>E.name===i);t("tier")||e.exec(`
|
|
912
912
|
ALTER TABLE skills ADD COLUMN tier TEXT NOT NULL DEFAULT 'atomic'
|
|
913
913
|
CHECK (tier IN ('atomic', 'mega', 'god'));
|
|
914
914
|
`),t("governs")||e.exec("ALTER TABLE skills ADD COLUMN governs TEXT NOT NULL DEFAULT '[]';"),t("composes")||e.exec("ALTER TABLE skills ADD COLUMN composes TEXT NOT NULL DEFAULT '[]';"),e.exec("CREATE INDEX IF NOT EXISTS idx_skills_tier ON skills(tier);"),e.exec(`
|
|
@@ -929,8 +929,8 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
|
|
|
929
929
|
`)}},{version:19,description:"Grove sync policy: projects.sync_policy gate (private by default) for cloud + federation isolation",up:e=>{e.prepare("PRAGMA table_info(projects)").all().some(a=>a.name==="sync_policy")||e.exec(`
|
|
930
930
|
ALTER TABLE projects ADD COLUMN sync_policy TEXT NOT NULL DEFAULT 'private'
|
|
931
931
|
CHECK (sync_policy IN ('private', 'cloud', 'team'));
|
|
932
|
-
`);const t=(a,o)=>{try{return e.prepare(`PRAGMA table_info(${a})`).all().some(r=>r.name===o)}catch{return!1}},
|
|
933
|
-
WHERE cross_project_visibility IN ('org', 'public') AND project_id IS NOT NULL`))
|
|
932
|
+
`);const t=(a,o)=>{try{return e.prepare(`PRAGMA table_info(${a})`).all().some(r=>r.name===o)}catch{return!1}},i=a=>{try{return e.prepare(a).all().map(o=>o.pid)}catch{return[]}},E=new Set;for(const a of["ground_truths","memory_artifacts","quests","design_tokens","design_references"])if(!(!t(a,"cross_project_visibility")||!t(a,"project_id")))for(const o of i(`SELECT DISTINCT project_id AS pid FROM ${a}
|
|
933
|
+
WHERE cross_project_visibility IN ('org', 'public') AND project_id IS NOT NULL`))E.add(o);const T=e.prepare("UPDATE projects SET sync_policy = 'cloud' WHERE id = ? AND sync_policy = 'private'");for(const a of E)T.run(a)}},{version:20,description:"v7 F2 (T008) \u2014 run-native provenance: runs + run_agents tables, agent_id/run_id attribution on 9 tables, failure_patterns.quarantine_scope",up:e=>{e.exec(`
|
|
934
934
|
CREATE TABLE IF NOT EXISTS runs (
|
|
935
935
|
run_id TEXT PRIMARY KEY,
|
|
936
936
|
parent_run_id TEXT,
|
|
@@ -955,7 +955,7 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
|
|
|
955
955
|
FOREIGN KEY (run_id) REFERENCES runs(run_id) ON DELETE CASCADE
|
|
956
956
|
);
|
|
957
957
|
CREATE INDEX IF NOT EXISTS idx_run_agents_agent ON run_agents(agent_id);
|
|
958
|
-
`);const s=(E
|
|
958
|
+
`);const s=(i,E)=>{try{return e.prepare(`PRAGMA table_info(${i})`).all().some(T=>T.name===E)}catch{return!1}},t=["memory_artifacts","failure_patterns","decision_edges","ground_truths","quests","sessions","quest_claims","events","audit_log"];for(const i of t)s(i,"agent_id")||e.exec(`ALTER TABLE ${i} ADD COLUMN agent_id TEXT;`),s(i,"run_id")||e.exec(`ALTER TABLE ${i} ADD COLUMN run_id TEXT;`);e.exec(`
|
|
959
959
|
CREATE INDEX IF NOT EXISTS idx_failure_run ON failure_patterns(run_id) WHERE run_id IS NOT NULL;
|
|
960
960
|
CREATE INDEX IF NOT EXISTS idx_events_run ON events(run_id) WHERE run_id IS NOT NULL;
|
|
961
961
|
CREATE INDEX IF NOT EXISTS idx_artifacts_run ON memory_artifacts(run_id) WHERE run_id IS NOT NULL;
|
|
@@ -990,10 +990,10 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
|
|
|
990
990
|
created_at TEXT DEFAULT (datetime('now')),
|
|
991
991
|
PRIMARY KEY (run_id, role)
|
|
992
992
|
);
|
|
993
|
-
`)}},{version:24,description:"v7 F3 (T029) \u2014 claims/presence hardening: role on quest_claims, run_id/role on agent_presence, run-scoped partial indexes",up:e=>{const s=(t,
|
|
993
|
+
`)}},{version:24,description:"v7 F3 (T029) \u2014 claims/presence hardening: role on quest_claims, run_id/role on agent_presence, run-scoped partial indexes",up:e=>{const s=(t,i)=>{try{return e.prepare(`PRAGMA table_info(${t})`).all().some(E=>E.name===i)}catch{return!1}};s("quest_claims","role")||e.exec("ALTER TABLE quest_claims ADD COLUMN role TEXT;"),s("agent_presence","run_id")||e.exec("ALTER TABLE agent_presence ADD COLUMN run_id TEXT;"),s("agent_presence","role")||e.exec("ALTER TABLE agent_presence ADD COLUMN role TEXT;"),e.exec(`
|
|
994
994
|
CREATE INDEX IF NOT EXISTS idx_quest_claims_run ON quest_claims(run_id) WHERE run_id IS NOT NULL;
|
|
995
995
|
CREATE INDEX IF NOT EXISTS idx_presence_run ON agent_presence(run_id) WHERE run_id IS NOT NULL;
|
|
996
|
-
`)}},{version:25,description:"Skills portability \u2014 store SKILL.md content (+ sha/ts) in the registry and make skills cloud-sync-eligible behind the per-row visibility gate",up:e=>{const s=(t,
|
|
996
|
+
`)}},{version:25,description:"Skills portability \u2014 store SKILL.md content (+ sha/ts) in the registry and make skills cloud-sync-eligible behind the per-row visibility gate",up:e=>{const s=(t,i)=>{try{return e.prepare(`PRAGMA table_info(${t})`).all().some(E=>E.name===i)}catch{return!1}};s("skills","content")||e.exec("ALTER TABLE skills ADD COLUMN content TEXT;"),s("skills","content_sha256")||e.exec("ALTER TABLE skills ADD COLUMN content_sha256 TEXT;"),s("skills","content_updated_at")||e.exec("ALTER TABLE skills ADD COLUMN content_updated_at TEXT;"),s("skills","cross_project_visibility")||e.exec("ALTER TABLE skills ADD COLUMN cross_project_visibility TEXT NOT NULL DEFAULT 'within';"),s("skills","is_shared")||e.exec("ALTER TABLE skills ADD COLUMN is_shared INTEGER NOT NULL DEFAULT 0;"),e.exec("CREATE INDEX IF NOT EXISTS idx_skills_visibility ON skills(cross_project_visibility) WHERE cross_project_visibility != 'within';")}},{version:26,description:"Reverse-bridge rejection tombstones \u2014 remember a once-rejected outside-prose sig so the next sweep never re-queues content the operator already deleted",up:e=>{e.exec(`
|
|
997
997
|
CREATE TABLE IF NOT EXISTS reverse_bridge_tombstones (
|
|
998
998
|
project_id INTEGER NOT NULL,
|
|
999
999
|
sig TEXT NOT NULL,
|
|
@@ -1130,20 +1130,20 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
|
|
|
1130
1130
|
UNIQUE(kind, row_id)
|
|
1131
1131
|
);
|
|
1132
1132
|
CREATE INDEX IF NOT EXISTS idx_sync_tombstones_pending ON sync_tombstones(pushed_at_ms);
|
|
1133
|
-
`);const s=[["ground_truths","truth"],["memory_artifacts","memory_artifact"],["quests","quest"],["design_tokens","design_token"],["design_references","design_reference"],["skills","skill"]];for(const[t,
|
|
1133
|
+
`);const s=[["ground_truths","truth"],["memory_artifacts","memory_artifact"],["quests","quest"],["design_tokens","design_token"],["design_references","design_reference"],["skills","skill"]];for(const[t,i]of s)e.exec(`
|
|
1134
1134
|
CREATE TRIGGER IF NOT EXISTS trg_tombstone_${t} AFTER DELETE ON ${t}
|
|
1135
1135
|
BEGIN
|
|
1136
1136
|
INSERT OR IGNORE INTO sync_tombstones (kind, row_id, deleted_at_ms)
|
|
1137
|
-
VALUES ('${
|
|
1137
|
+
VALUES ('${i}', CAST(OLD.id AS TEXT), CAST(strftime('%s','now') AS INTEGER) * 1000);
|
|
1138
1138
|
END;
|
|
1139
|
-
`)}},{version:35,description:"Grove-gate the tombstone triggers (quest #113): a tombstone must record ONLY when the deleted row would have SYNCED, matching the upsert gate exactly (cross_project_visibility IN org/public AND grove sync_policy IN cloud/team). Migration 34 recorded a tombstone for EVERY delete, so a PRIVATE grove's (or unshared skill's) deletion leaked content-free deletion metadata to the cloud as noise. Recreates all 6 triggers gated.",up:e=>{const s=[["ground_truths","truth"],["memory_artifacts","memory_artifact"],["quests","quest"],["design_tokens","design_token"],["design_references","design_reference"],["skills","skill"]];for(const[t,
|
|
1139
|
+
`)}},{version:35,description:"Grove-gate the tombstone triggers (quest #113): a tombstone must record ONLY when the deleted row would have SYNCED, matching the upsert gate exactly (cross_project_visibility IN org/public AND grove sync_policy IN cloud/team). Migration 34 recorded a tombstone for EVERY delete, so a PRIVATE grove's (or unshared skill's) deletion leaked content-free deletion metadata to the cloud as noise. Recreates all 6 triggers gated.",up:e=>{const s=[["ground_truths","truth"],["memory_artifacts","memory_artifact"],["quests","quest"],["design_tokens","design_token"],["design_references","design_reference"],["skills","skill"]];for(const[t,i]of s){e.exec(`DROP TRIGGER IF EXISTS trg_tombstone_${t};`);const E=t==="skills"?"OLD.cross_project_visibility IN ('org','public')":"OLD.cross_project_visibility IN ('org','public') AND (OLD.project_id IS NULL OR (SELECT sync_policy FROM projects WHERE id = OLD.project_id) IN ('cloud','team'))";e.exec(`
|
|
1140
1140
|
CREATE TRIGGER trg_tombstone_${t} AFTER DELETE ON ${t}
|
|
1141
|
-
WHEN ${
|
|
1141
|
+
WHEN ${E}
|
|
1142
1142
|
BEGIN
|
|
1143
1143
|
INSERT OR IGNORE INTO sync_tombstones (kind, row_id, deleted_at_ms)
|
|
1144
|
-
VALUES ('${
|
|
1144
|
+
VALUES ('${i}', CAST(OLD.id AS TEXT), CAST(strftime('%s','now') AS INTEGER) * 1000);
|
|
1145
1145
|
END;
|
|
1146
|
-
`)}}},{version:36,description:`Add updated_at to quests + design_references so cloud sync can watermark-filter them. Root cause of "sync never settles" (2026-07-17): collectChangedRows skips its incremental time filter for any synced table WITHOUT an updated_at column, so it re-collected ALL org/public quests (101) + design_references every sync, stamping each with Date.now() and re-pushing forever (~1s/row server-side). The 4 other synced tables already have updated_at. This migration adds the column + backfills from the row's real last-change time (normalized via datetime() to the clean "YYYY-MM-DD HH:MM:SS" format strftime expects). No triggers: both tables are external-content FTS5, where a self-UPDATE inside a trigger corrupts the FTS index when an indexed column changes ("database disk image is malformed"). updated_at is stamped in app code on every insert/update instead (database.ts addQuest/updateQuest/dynamic-update, design.ts) \u2014 the same convention the other synced tables use.`,up:e=>{const s=(t,
|
|
1146
|
+
`)}}},{version:36,description:`Add updated_at to quests + design_references so cloud sync can watermark-filter them. Root cause of "sync never settles" (2026-07-17): collectChangedRows skips its incremental time filter for any synced table WITHOUT an updated_at column, so it re-collected ALL org/public quests (101) + design_references every sync, stamping each with Date.now() and re-pushing forever (~1s/row server-side). The 4 other synced tables already have updated_at. This migration adds the column + backfills from the row's real last-change time (normalized via datetime() to the clean "YYYY-MM-DD HH:MM:SS" format strftime expects). No triggers: both tables are external-content FTS5, where a self-UPDATE inside a trigger corrupts the FTS index when an indexed column changes ("database disk image is malformed"). updated_at is stamped in app code on every insert/update instead (database.ts addQuest/updateQuest/dynamic-update, design.ts) \u2014 the same convention the other synced tables use.`,up:e=>{const s=(t,i)=>e.prepare(`PRAGMA table_info(${t})`).all().some(E=>E.name===i);s("quests","updated_at")||(e.exec("ALTER TABLE quests ADD COLUMN updated_at TEXT"),e.exec("UPDATE quests SET updated_at = datetime(COALESCE(completed_at, created_at, 'now'))")),s("design_references","updated_at")||(e.exec("ALTER TABLE design_references ADD COLUMN updated_at TEXT"),e.exec("UPDATE design_references SET updated_at = datetime('now')"))}},{version:37,description:"Add metrics_snapshots \u2014 the longitudinal flight recorder for Wyrm effectiveness + quality over time. wyrm doctor / stats / benches all measure a MOMENT; nothing timestamped a trend, so a slow degradation (recall drifting as the corpus outgrows the index, vectors quietly off for days, a crucible-caught defect class recurring) was invisible until someone re-ran a tool by hand. One row per (kind, capture): kind=health (corpus/coverage/queue/failures/doctor checks), kind=effectiveness (recall hit-rate, failure-block rate, rehydrate non-empty rate, token savings), kind=retrieval (recall@k from the eval bench). metrics_json keeps the schema flexible so new metrics need no migration. Written nightly (health+effectiveness) + on-demand/per-release (retrieval); read by `wyrm metrics trend`.",up:e=>{e.exec(`
|
|
1147
1147
|
CREATE TABLE IF NOT EXISTS metrics_snapshots (
|
|
1148
1148
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1149
1149
|
captured_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
@@ -1164,10 +1164,10 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
|
|
|
1164
1164
|
source_refs TEXT DEFAULT '{}',
|
|
1165
1165
|
updated_at INTEGER NOT NULL DEFAULT 0
|
|
1166
1166
|
);
|
|
1167
|
-
`)}},{version:39,description:"Firewall target normalization (quest #1033) \u2014 add canonical_target + command_head to failure_patterns so the guard can catch flag-reordered / =-form command repeats (Tier A hard block) and warn on added-flag variants (Tier B advisory). Backfills existing command rows via canonicalizeCommand/commandHead; indexes both keys for range-scan lookups.",up:e=>{const s=e.prepare("PRAGMA table_info(failure_patterns)").all().map(
|
|
1167
|
+
`)}},{version:39,description:"Firewall target normalization (quest #1033) \u2014 add canonical_target + command_head to failure_patterns so the guard can catch flag-reordered / =-form command repeats (Tier A hard block) and warn on added-flag variants (Tier B advisory). Backfills existing command rows via canonicalizeCommand/commandHead; indexes both keys for range-scan lookups.",up:e=>{const s=e.prepare("PRAGMA table_info(failure_patterns)").all().map(E=>E.name);s.includes("canonical_target")||e.exec("ALTER TABLE failure_patterns ADD COLUMN canonical_target TEXT;"),s.includes("command_head")||e.exec("ALTER TABLE failure_patterns ADD COLUMN command_head TEXT;"),e.exec(`
|
|
1168
1168
|
CREATE INDEX IF NOT EXISTS idx_failure_canonical ON failure_patterns(canonical_target);
|
|
1169
1169
|
CREATE INDEX IF NOT EXISTS idx_failure_cmdhead ON failure_patterns(command_head);
|
|
1170
|
-
`);const t=e.prepare("SELECT id, target FROM failure_patterns WHERE scope = 'command'").all(),
|
|
1170
|
+
`);const t=e.prepare("SELECT id, target FROM failure_patterns WHERE scope = 'command'").all(),i=e.prepare("UPDATE failure_patterns SET canonical_target = ?, command_head = ? WHERE id = ?");for(const E of t)i.run(n(E.target)||null,d(E.target)||null,E.id)}},{version:40,description:"Negotiated Recall NR-1 (specs/negotiated-recall) \u2014 recall_policy: one row per run_id holding the session's recall consent state. mode=full is today's behavior (no filtering); mode=clean mutes the MUTE set (memory_artifacts kind IN (pattern, heuristic) OR outcome=positive) while the firewall (anti_pattern/negative/failure_patterns) and ground_truths stay unaffected by construction, never by an exclusion list; mode=custom governs by muted_ids/challenged_truth_ids alone. muted_ids/challenged_truth_ids are JSON arrays applied in every mode. Table only \u2014 no enforcement here (that lands in NR-3 at the MemoryArtifacts chokepoint); a DB with zero recall_policy rows recalls identically to pre-NR-1.",up:e=>{e.exec(`
|
|
1171
1171
|
CREATE TABLE IF NOT EXISTS recall_policy (
|
|
1172
1172
|
run_id TEXT PRIMARY KEY,
|
|
1173
1173
|
mode TEXT NOT NULL DEFAULT 'full'
|
|
@@ -1177,10 +1177,18 @@ import{canonicalizeCommand as n,commandHead as d}from"./failure-patterns.js";con
|
|
|
1177
1177
|
created_at INTEGER NOT NULL,
|
|
1178
1178
|
updated_at INTEGER NOT NULL
|
|
1179
1179
|
);
|
|
1180
|
+
`)}},{version:41,description:"Grounding enforcement \u2014 served_records: the per-connection ledger of which artifacts Wyrm actually handed to a client, so a citation naming a record that was never served can be identified as a fabrication rather than trusted. Keyed by session_key (an opaque per-server-process id), NOT run_id: WYRM_RUN_ID is not present in the MCP server environment, so run_id resolves null at dispatch and every session would collapse into one bucket. Keyed separately from session_seen_artifacts, whose session_id is a caller-supplied integer used for context_build elision and is pruned on its own TTL.",up:e=>{e.exec(`
|
|
1181
|
+
CREATE TABLE IF NOT EXISTS served_records (
|
|
1182
|
+
session_key TEXT NOT NULL,
|
|
1183
|
+
artifact_id INTEGER NOT NULL,
|
|
1184
|
+
artifact_kind TEXT NOT NULL,
|
|
1185
|
+
served_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
1186
|
+
PRIMARY KEY (session_key, artifact_id, artifact_kind)
|
|
1187
|
+
);
|
|
1180
1188
|
`)}}];function l(e){e.exec(`
|
|
1181
1189
|
CREATE TABLE IF NOT EXISTS schema_versions (
|
|
1182
1190
|
version INTEGER PRIMARY KEY,
|
|
1183
1191
|
description TEXT NOT NULL,
|
|
1184
1192
|
applied_at TEXT DEFAULT (datetime('now'))
|
|
1185
1193
|
);
|
|
1186
|
-
`);const s=e.prepare("SELECT COALESCE(MAX(version), 0) as v FROM schema_versions").get().v,t=N.filter(T=>T.version>s).slice().sort((T,a)=>T.version-a.version);if(t.length===0)return[];const
|
|
1194
|
+
`);const s=e.prepare("SELECT COALESCE(MAX(version), 0) as v FROM schema_versions").get().v,t=N.filter(T=>T.version>s).slice().sort((T,a)=>T.version-a.version);if(t.length===0)return[];const i=[],E=e.prepare("INSERT INTO schema_versions (version, description) VALUES (?, ?)");for(const T of t)e.transaction(()=>{T.up(e),E.run(T.version,T.description)})(),i.push(T);return i}function _(e){try{return e.prepare("SELECT COALESCE(MAX(version), 0) as v FROM schema_versions").get().v}catch{return 0}}export{_ as getSchemaVersion,N as migrations,l as runMigrations};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import{randomUUID as f}from"node:crypto";const m=process.env.WYRM_SESSION_KEY??f(),_=[{re:/\b(mem|memory)[ \t]*[:#][ \t]*(\d{1,7})\b/gi,kind:"mem"},{re:/\btruth[ \t]*[:#][ \t]*(\d{1,7})\b/gi,kind:"truth"},{re:/\bquest[ \t]*[:#][ \t]*(\d{1,7})\b/gi,kind:"quest"},{re:/\bfailure[ \t]*[:#][ \t]*(\d{1,7})\b/gi,kind:"failure"}],E=/\(ID:[ \t]*(\d{1,7})\)/gi;function h(i){const t=new Map;if(!i)return[];for(const{re:r,kind:e}of _)if(e)for(const s of i.matchAll(r)){const d=s[2]??s[1],n=Number(d);Number.isFinite(n)&&n>0&&t.set(`${e}:${n}`,{id:n,kind:e})}for(const r of i.matchAll(E)){const e=Number(r[1]);if(!(!Number.isFinite(e)||e<=0))for(const s of["mem","truth","quest","failure"])t.set(`${s}:${e}`,{id:e,kind:s})}return[...t.values()]}let a=null;function l(i,t){try{a||(a=new k(i)),a.recordFromText(m,t)}catch{}}class k{db;constructor(t){this.db=t}record(t,r){if(!r.length)return;const e=this.db.prepare(`
|
|
2
|
+
INSERT INTO served_records (session_key, artifact_id, artifact_kind)
|
|
3
|
+
VALUES (?, ?, ?)
|
|
4
|
+
ON CONFLICT(session_key, artifact_id, artifact_kind) DO NOTHING
|
|
5
|
+
`);this.db.transaction(d=>{for(const n of d)e.run(t,n.id,n.kind)})(r)}recordFromText(t,r){const e=h(r);return this.record(t,e),e.length}attest(t,r){const e=this.db.prepare("SELECT artifact_id, artifact_kind FROM served_records WHERE session_key = ?").all(t),s=new Set(e.map(o=>`${o.artifact_kind}:${o.artifact_id}`)),d=[],n=[],u=new Set;for(const o of r){const c=`${o.kind}:${o.id}`;u.has(c)||(u.add(c),(s.has(c)?d:n).push({id:o.id,kind:o.kind}))}return{served:d,unserved:n,ok:n.length===0}}countFor(t){return this.db.prepare("SELECT COUNT(*) AS n FROM served_records WHERE session_key = ?").get(t).n}prune(t=7){return this.db.prepare("DELETE FROM served_records WHERE served_at < datetime('now', ? || ' days')").run(`-${t}`).changes??0}}export{m as SESSION_KEY,k as ServedRecords,h as extractRefs,l as recordServed};
|
package/dist/session-seen.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
class
|
|
1
|
+
class f{db;constructor(e){this.db=e}mark(e,i,s,a){this.db.prepare(`
|
|
2
2
|
INSERT INTO session_seen_artifacts (session_id, artifact_id, artifact_kind, render_mode)
|
|
3
3
|
VALUES (?, ?, ?, ?)
|
|
4
4
|
ON CONFLICT(session_id, artifact_id, artifact_kind)
|
|
5
5
|
DO UPDATE SET shown_at = datetime('now'), render_mode = excluded.render_mode
|
|
6
|
-
`).run(e,
|
|
6
|
+
`).run(e,i,s,a)}markBulk(e,i){const s=this.db.prepare(`
|
|
7
7
|
INSERT INTO session_seen_artifacts (session_id, artifact_id, artifact_kind, render_mode)
|
|
8
8
|
VALUES (?, ?, ?, ?)
|
|
9
9
|
ON CONFLICT(session_id, artifact_id, artifact_kind)
|
|
10
10
|
DO UPDATE SET shown_at = datetime('now'), render_mode = excluded.render_mode
|
|
11
|
-
`);this.db.transaction(
|
|
11
|
+
`);this.db.transaction(r=>{for(const n of r)s.run(e,n.id,n.kind,n.mode)})(i)}getSeen(e){const i=this.db.prepare("SELECT artifact_id, artifact_kind FROM session_seen_artifacts WHERE session_id = ? AND render_mode = 'inline'").all(e);return new Set(i.map(s=>`${s.artifact_kind}:${s.artifact_id}`))}attest(e,i){const s=this.db.prepare("SELECT artifact_id, artifact_kind FROM session_seen_artifacts WHERE session_id = ?").all(e),a=new Set(s.map(t=>`${t.artifact_kind}:${t.artifact_id}`)),r=[],n=[],d=new Set;for(const t of i){const o=`${t.kind}:${t.id}`;d.has(o)||(d.add(o),(a.has(o)?r:n).push({id:t.id,kind:t.kind}))}const c=s.filter(t=>!d.has(`${t.artifact_kind}:${t.artifact_id}`)).map(t=>({id:t.artifact_id,kind:t.artifact_kind}));return{served:r,unserved:n,unseen:c,ok:n.length===0}}prune(e=7){return this.db.prepare("DELETE FROM session_seen_artifacts WHERE shown_at < datetime('now', ? || ' days')").run(`-${e}`).changes??0}count(){return this.db.prepare("SELECT COUNT(*) as n FROM session_seen_artifacts").get().n}}export{f as SessionSeen};
|
package/dist/tool-manifest.json
CHANGED
package/dist/wyrm-manifest.json
CHANGED
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wyrm-mcp",
|
|
3
|
-
"version": "8.7.
|
|
3
|
+
"version": "8.7.6",
|
|
4
4
|
"mcpName": "lk.ghosts/wyrm",
|
|
5
|
-
"description": "Local-first persistent memory for AI agents over MCP. Ground truths, negative learning (recorded failures block repeats), decision causality, hybrid recall, negotiated recall (clean-mode injection you steer), live memory streams, run-attributed fleet memory
|
|
5
|
+
"description": "Local-first persistent memory for AI agents over MCP. Ground truths, negative learning (recorded failures block repeats), decision causality, hybrid recall, negotiated recall (clean-mode injection you steer), live memory streams, run-attributed fleet memory \u2014 a structured SQLite memory on your machine, no cloud or LLM required. Claude / Copilot / Cursor / Windsurf / Codex.",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "dist/index.js",
|
|
8
8
|
"bin": {
|
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
"scripts/hooks/wyrm-session-prune.mjs",
|
|
30
30
|
"scripts/hooks/wyrm-tool-call-trace.mjs",
|
|
31
31
|
"scripts/hooks/wyrm-run-auto.mjs",
|
|
32
|
+
"scripts/hooks/wyrm-citation-audit.mjs",
|
|
32
33
|
"README.md",
|
|
33
34
|
"BENCHMARKS.md",
|
|
34
35
|
"COMPARISON.md",
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Wyrm citation audit (Stop hook) — enforcement for the grounding rules.
|
|
4
|
+
*
|
|
5
|
+
* 8.7.4 ships server instructions telling the model to cite the record id for
|
|
6
|
+
* anything it claims from memory and never to assert what it did not retrieve.
|
|
7
|
+
* Those are directives, and a directive is not a guarantee. This makes it a
|
|
8
|
+
* check.
|
|
9
|
+
*
|
|
10
|
+
* The transcript is the ledger. Everything Wyrm actually put in front of this
|
|
11
|
+
* session is in it: tool results, the SessionStart recall brief, injected
|
|
12
|
+
* prompt context. So a citation naming a record that never appeared in any of
|
|
13
|
+
* them was not retrieved — it was produced. That is decidable by set
|
|
14
|
+
* membership, with no model and no second opinion.
|
|
15
|
+
*
|
|
16
|
+
* Advisory by design: it reports, it does not block. A false accusation that
|
|
17
|
+
* silently eats a turn would be worse than the problem it polices.
|
|
18
|
+
*
|
|
19
|
+
* Claude Code passes a JSON payload on stdin including `transcript_path`.
|
|
20
|
+
*/
|
|
21
|
+
import { readFileSync } from 'node:fs';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Canonical citation form the grounding rules mandate: `mem:5508`, `truth:921`.
|
|
25
|
+
*
|
|
26
|
+
* Horizontal whitespace only. `\s*` would span a newline and read prose like
|
|
27
|
+
* "...without being a JS failure:\n\n1. Phone with Data Saver" as `failure:1`,
|
|
28
|
+
* which is how the first version produced its only false positive across 25
|
|
29
|
+
* real transcripts. A citation never straddles a line break.
|
|
30
|
+
*/
|
|
31
|
+
const CITE = /\b(mem|memory|truth|quest|failure)[ \t]*[:#][ \t]*(\d{1,7})\b/gi;
|
|
32
|
+
|
|
33
|
+
/** Normalize the aliases Wyrm renders (`mem:` and `memory #` are one kind). */
|
|
34
|
+
function norm(kind) {
|
|
35
|
+
const k = kind.toLowerCase();
|
|
36
|
+
return k === 'memory' ? 'mem' : k;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function idsIn(text) {
|
|
40
|
+
const out = new Set();
|
|
41
|
+
if (!text) return out;
|
|
42
|
+
for (const m of String(text).matchAll(CITE)) out.add(`${norm(m[1])}:${m[2]}`);
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let payload = {};
|
|
47
|
+
try { payload = JSON.parse(readFileSync(0, 'utf8') || '{}'); } catch { /* no/invalid stdin */ }
|
|
48
|
+
if (!payload || typeof payload !== 'object') payload = {};
|
|
49
|
+
|
|
50
|
+
const tpath = payload.transcript_path;
|
|
51
|
+
if (!tpath) process.exit(0);
|
|
52
|
+
|
|
53
|
+
let lines;
|
|
54
|
+
try { lines = readFileSync(tpath, 'utf8').split('\n'); } catch { process.exit(0); }
|
|
55
|
+
|
|
56
|
+
const served = new Set(); // every id Wyrm put in front of this session
|
|
57
|
+
const cited = new Set(); // every id the FINAL assistant turn asserted
|
|
58
|
+
let lastAssistantText = [];
|
|
59
|
+
|
|
60
|
+
for (const line of lines) {
|
|
61
|
+
if (!line.trim()) continue;
|
|
62
|
+
let o;
|
|
63
|
+
try { o = JSON.parse(line); } catch { continue; }
|
|
64
|
+
const type = o.type;
|
|
65
|
+
|
|
66
|
+
// Anything that is not the model's own prose is a hand-off TO the model:
|
|
67
|
+
// tool results, the SessionStart brief, injected context, attachments.
|
|
68
|
+
if (type === 'user' || type === 'system' || type === 'attachment') {
|
|
69
|
+
const content = o?.message?.content ?? o?.content ?? o?.text ?? '';
|
|
70
|
+
if (typeof content === 'string') {
|
|
71
|
+
for (const id of idsIn(content)) served.add(id);
|
|
72
|
+
} else if (Array.isArray(content)) {
|
|
73
|
+
for (const c of content) {
|
|
74
|
+
if (!c || typeof c !== 'object') continue;
|
|
75
|
+
const t = typeof c.content === 'string'
|
|
76
|
+
? c.content
|
|
77
|
+
: Array.isArray(c.content)
|
|
78
|
+
? c.content.map((x) => (typeof x === 'string' ? x : x?.text ?? '')).join('\n')
|
|
79
|
+
: (c.text ?? '');
|
|
80
|
+
for (const id of idsIn(t)) served.add(id);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (type === 'assistant') {
|
|
87
|
+
const blocks = o?.message?.content;
|
|
88
|
+
if (!Array.isArray(blocks)) continue;
|
|
89
|
+
// A new assistant turn replaces the previous candidate: we audit the
|
|
90
|
+
// response the user actually ends up reading, not the whole conversation.
|
|
91
|
+
const texts = blocks.filter((c) => c?.type === 'text').map((c) => c.text ?? '');
|
|
92
|
+
if (texts.length) lastAssistantText = texts;
|
|
93
|
+
// A tool_use is the model asking, not asserting — its arguments echo ids
|
|
94
|
+
// it is looking up and must not count as a claim.
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
for (const t of lastAssistantText) for (const id of idsIn(t)) cited.add(id);
|
|
99
|
+
|
|
100
|
+
const fabricated = [...cited].filter((id) => !served.has(id));
|
|
101
|
+
|
|
102
|
+
if (fabricated.length === 0) process.exit(0);
|
|
103
|
+
|
|
104
|
+
// Surface it. Exit 0 with context so the finding reaches the transcript
|
|
105
|
+
// without killing the turn.
|
|
106
|
+
const detail = fabricated.sort().join(', ');
|
|
107
|
+
console.log(JSON.stringify({
|
|
108
|
+
hookSpecificOutput: {
|
|
109
|
+
hookEventName: 'Stop',
|
|
110
|
+
additionalContext:
|
|
111
|
+
`<wyrm-citation-audit>\n` +
|
|
112
|
+
`UNGROUNDED CITATION(S): ${detail}\n` +
|
|
113
|
+
`These record ids appear in the reply but were never returned by a Wyrm tool, ` +
|
|
114
|
+
`the SessionStart brief, or injected context in this session. ` +
|
|
115
|
+
`Per the grounding rules: cite only what was actually retrieved. ` +
|
|
116
|
+
`Retrieve them and correct the claim, or drop the citation.\n` +
|
|
117
|
+
`</wyrm-citation-audit>`,
|
|
118
|
+
},
|
|
119
|
+
}));
|
|
120
|
+
process.exit(0);
|