wyrm-mcp 9.2.2 → 9.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/dist/activation.js +1 -1
  2. package/dist/agent-loop.js +2 -2
  3. package/dist/audit.js +2 -2
  4. package/dist/autoconfig.js +6 -6
  5. package/dist/backup-cli.js +6 -0
  6. package/dist/backup.js +1 -0
  7. package/dist/bridge.js +1 -1
  8. package/dist/buddy-runner.js +1 -1
  9. package/dist/buddy.js +4 -4
  10. package/dist/capabilities.js +1 -1
  11. package/dist/causality.js +3 -3
  12. package/dist/cloud/cli.js +3 -3
  13. package/dist/cloud/sync-daemon-entrypoint.js +1 -1
  14. package/dist/cloud/sync-engine.js +8 -7
  15. package/dist/cloud-backup.js +4 -4
  16. package/dist/cloud-sync-entrypoint.js +1 -1
  17. package/dist/cloud-sync.js +1 -1
  18. package/dist/connectors/ingest.js +2 -2
  19. package/dist/constellation.js +1 -1
  20. package/dist/context-build-budgeted.js +4 -4
  21. package/dist/context-ranking.js +1 -1
  22. package/dist/daemon-writer.js +1 -1
  23. package/dist/database.js +41 -23
  24. package/dist/design.js +1 -1
  25. package/dist/erasure-cli.js +3 -0
  26. package/dist/erasure-log.js +8 -0
  27. package/dist/erasure.js +1 -0
  28. package/dist/event-replication.js +1 -1
  29. package/dist/events.js +11 -11
  30. package/dist/failure-patterns.js +67 -44
  31. package/dist/federation.js +11 -10
  32. package/dist/governance.js +1 -0
  33. package/dist/handlers/agent.js +4 -4
  34. package/dist/handlers/alias-adapters.js +1 -1
  35. package/dist/handlers/audit.js +1 -1
  36. package/dist/handlers/boundary.js +1 -1
  37. package/dist/handlers/capture.js +54 -52
  38. package/dist/handlers/causality.js +2 -2
  39. package/dist/handlers/cloud.js +9 -9
  40. package/dist/handlers/companion.js +4 -4
  41. package/dist/handlers/entity.js +6 -6
  42. package/dist/handlers/events.js +4 -4
  43. package/dist/handlers/failure.js +15 -12
  44. package/dist/handlers/goals.js +2 -2
  45. package/dist/handlers/intelligence.js +81 -74
  46. package/dist/handlers/mcpclient.js +3 -3
  47. package/dist/handlers/presence.js +1 -1
  48. package/dist/handlers/prompts.js +2 -2
  49. package/dist/handlers/quest.js +11 -4
  50. package/dist/handlers/recall.js +10 -10
  51. package/dist/handlers/resources.js +1 -1
  52. package/dist/handlers/review.js +3 -3
  53. package/dist/handlers/run.js +3 -3
  54. package/dist/handlers/search.js +1 -1
  55. package/dist/handlers/session.js +27 -25
  56. package/dist/handlers/share.js +3 -3
  57. package/dist/handlers/skill.js +2 -2
  58. package/dist/handlers/symbols.js +5 -5
  59. package/dist/handlers/syncops.js +2 -2
  60. package/dist/harvest.js +5 -5
  61. package/dist/hours.js +1 -1
  62. package/dist/http-auth.js +2 -2
  63. package/dist/http-fast.js +17 -17
  64. package/dist/http-projects.js +4 -0
  65. package/dist/http-rate-limit.js +1 -0
  66. package/dist/index-health.js +52 -0
  67. package/dist/index.js +2 -2
  68. package/dist/indexer.js +4 -4
  69. package/dist/intelligence.js +36 -29
  70. package/dist/lane-provenance.js +39 -0
  71. package/dist/license.js +1 -1
  72. package/dist/lineage.js +15 -0
  73. package/dist/live-embedding-state.js +2 -2
  74. package/dist/maintenance.js +2 -2
  75. package/dist/mcp-integrity.js +2 -2
  76. package/dist/memory-artifacts.js +39 -37
  77. package/dist/metabolize.js +9 -7
  78. package/dist/metrics.js +1 -1
  79. package/dist/migrate-prompt.js +1 -1
  80. package/dist/migrations.js +236 -45
  81. package/dist/priority-embed.js +1 -1
  82. package/dist/providers/embedding-provider.js +1 -1
  83. package/dist/readonly-gate.js +1 -1
  84. package/dist/redact-backfill.js +1 -0
  85. package/dist/rehydration.js +30 -20
  86. package/dist/reindex.js +1 -1
  87. package/dist/render-target.js +6 -6
  88. package/dist/repl-guard.js +1 -1
  89. package/dist/replication-daemon-entrypoint.js +1 -1
  90. package/dist/replication-daemon.js +1 -1
  91. package/dist/retention.js +1 -0
  92. package/dist/reverse-bridge.js +6 -6
  93. package/dist/review-sample.js +31 -0
  94. package/dist/security.js +1 -1
  95. package/dist/self-maintenance.js +4 -4
  96. package/dist/served-records.js +8 -2
  97. package/dist/setup-wizard.js +1 -1
  98. package/dist/setup.js +1 -1
  99. package/dist/skill-author.js +2 -2
  100. package/dist/store-open.js +1 -0
  101. package/dist/store-readonly.js +1 -0
  102. package/dist/sub-agent.js +2 -2
  103. package/dist/tool-manifest-v2.json +1 -1
  104. package/dist/tool-manifest.json +1 -1
  105. package/dist/truth-freshness.js +8 -0
  106. package/dist/ui-dashboard.js +4 -4
  107. package/dist/vault.js +1 -1
  108. package/dist/vector-init.js +1 -1
  109. package/dist/vectors.js +4 -3
  110. package/dist/visibility.js +12 -12
  111. package/dist/write-guard.js +1 -0
  112. package/dist/wyrm-cli.js +108 -92
  113. package/dist/wyrm-guard.js +13 -12
  114. package/dist/wyrm-loop.js +3 -3
  115. package/dist/wyrm-manifest.json +1 -1
  116. package/dist/wyrm-memo.js +5 -5
  117. package/package.json +1 -1
  118. package/scripts/hooks/wyrm-session-capture.mjs +3 -0
@@ -1,53 +1,60 @@
1
- import{redactCredentials as p}from"./security.js";import{emitEvent as h}from"./events.js";import{getActor as g}from"./handlers/boundary.js";const R=1200;function A(d){if(!d.ttl_days||!d.last_verified_at)return null;const t=new Date(d.last_verified_at).getTime(),e=(Date.now()-t)/(1e3*60*60*24);return Math.min(1,e/d.ttl_days)}const S=["is_shared","cross_project_visibility"];function y(d){const t=d,e={};for(const r of S)r in t&&t[r]!=null&&(e[r]=t[r]);return e}class L{db;cascadeHook;lastCascade=null;constructor(t){this.db=t}attachCascade(t){this.cascadeHook=t}set(t,e){const r=this.db.transaction(()=>{const i=this.db.prepare(`
1
+ import{redactCredentials as p}from"./security.js";import{emitEvent as y}from"./events.js";import{getActor as N}from"./handlers/boundary.js";import{defaultTtlDays as O,explicitRefs as D}from"./truth-freshness.js";import{recordGovernanceEvent as g}from"./governance.js";const T=1200;function U(a){if(!a.ttl_days||!a.last_verified_at)return null;const e=new Date(a.last_verified_at).getTime(),t=(Date.now()-e)/(1e3*60*60*24);return Math.min(1,t/a.ttl_days)}function m(a,e){return!(p(e.value.trim())!==a.value||e.rationale!==void 0&&e.rationale!==null&&p(e.rationale.trim())!==(a.rationale??"")||e.source!==void 0&&e.source!==null&&e.source.trim()!==(a.source??"")||e.confidence!==void 0&&e.confidence!==a.confidence||e.ttl_days!==void 0&&e.ttl_days!==a.ttl_days)}function A(a,e,t,r){const i=e==="truth"?a.prepare("SELECT 1 FROM ground_truths WHERE id = ? AND project_id = ?"):e==="artifact"?a.prepare("SELECT 1 FROM memory_artifacts WHERE id = ? AND project_id = ?"):a.prepare("SELECT 1 FROM quests WHERE id = ? AND project_id = ?");try{return!!i.get(t,r)}catch{return!1}}function S(a,e,t,r,i,c,d,s){try{if(a.prepare(`
2
+ SELECT 1 FROM decision_edges
3
+ WHERE project_id = ? AND from_kind = 'truth' AND from_id = ? AND to_kind = ? AND to_id = ?
4
+ AND relation = ? AND invalidated_at IS NULL
5
+ `).get(e,t,r,i,c))return null;const o=a.prepare(`
6
+ INSERT INTO decision_edges (project_id, from_kind, from_id, to_kind, to_id, relation, rationale, agent_id, run_id)
7
+ VALUES (?, 'truth', ?, ?, ?, ?, ?, ?, ?)
8
+ `).run(e,t,r,i,c,d,s.agent_id,s.run_id);return Number(o.lastInsertRowid)}catch{return null}}const C=["is_shared","cross_project_visibility"];function b(a){const e=a,t={};for(const r of C)r in e&&e[r]!=null&&(t[r]=e[r]);return t}class ${db;cascadeHook;lastCascade=null;lastWrite=null;constructor(e){this.db=e}attachCascade(e){this.cascadeHook=e}set(e,t){const r=this.db.transaction(()=>{const n=this.db.prepare(`
2
9
  SELECT * FROM ground_truths
3
10
  WHERE project_id = ? AND category = ? AND key = ? AND is_current = 1
4
11
  ORDER BY id DESC LIMIT 1
5
- `).get(t,e.category,e.key);i&&this.db.prepare("UPDATE ground_truths SET is_current = 0, updated_at = datetime('now') WHERE id = ?").run(i.id);const n=g(),a=[t,e.category,e.key.trim(),p(e.value.trim()),e.rationale?p(e.rationale.trim()):null,e.source?.trim()??null,e.confidence??1,i?.id??null,e.ttl_days??null,n.agent_id,n.run_id],o=i?y(i):{},l="is_shared"in o&&"cross_project_visibility"in o?this.db.prepare(`
12
+ `).get(e,t.category,t.key.trim());if(n&&m(n,t)){this.db.prepare("UPDATE ground_truths SET last_verified_at = datetime('now'), updated_at = datetime('now') WHERE id = ?").run(n.id);const u=this.db.prepare("SELECT * FROM ground_truths WHERE id = ?").get(n.id);return g(this.db,"truth.verify",{truth_id:n.id,category:t.category},{projectId:e}),{fresh:u,superseded:null,verified:!0,edges:[]}}n&&this.db.prepare("UPDATE ground_truths SET is_current = 0, updated_at = datetime('now') WHERE id = ?").run(n.id);const o=N(),l=[e,t.category,t.key.trim(),p(t.value.trim()),t.rationale?p(t.rationale.trim()):null,t.source?.trim()??null,t.confidence??1,n?.id??null,t.ttl_days??n?.ttl_days??O(t.category,t.key),o.agent_id,o.run_id],h=n?b(n):{},E="is_shared"in h&&"cross_project_visibility"in h?this.db.prepare(`
6
13
  INSERT INTO ground_truths (project_id, category, key, value, rationale, source, confidence, supersedes_id, ttl_days, agent_id, run_id, is_shared, cross_project_visibility)
7
14
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
8
- `).run(...a,o.is_shared,o.cross_project_visibility):this.db.prepare(`
15
+ `).run(...l,h.is_shared,h.cross_project_visibility):this.db.prepare(`
9
16
  INSERT INTO ground_truths (project_id, category, key, value, rationale, source, confidence, supersedes_id, ttl_days, agent_id, run_id)
10
17
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
11
- `).run(...a);return{fresh:this.db.prepare("SELECT * FROM ground_truths WHERE id = ?").get(l.lastInsertRowid),superseded:i??null}}),{fresh:s,superseded:c}=r();if(h(this.db,{projectId:t,kind:"truth",refTable:"ground_truths",refId:s.id,isShared:!!s.is_shared}),this.lastCascade=null,c&&this.cascadeHook&&c.value!==s.value&&!/^(1|true|yes|on)$/i.test(process.env.WYRM_NO_AUTO_CASCADE??""))try{this.lastCascade=this.cascadeHook(c,s)}catch{}return s}getCurrent(t,e){return e?this.db.prepare(`
18
+ `).run(...l),f=this.db.prepare("SELECT * FROM ground_truths WHERE id = ?").get(E.lastInsertRowid),_=[];if(n){const u=S(this.db,e,f.id,"truth",n.id,"supersedes",`truth ${t.category}.${t.key.trim()} superseded`,o);u!==null&&_.push(u)}for(const u of D(t.source)){if(u.kind==="truth"&&u.id===f.id||!A(this.db,u.kind,u.id,e))continue;const R=S(this.db,e,f.id,u.kind,u.id,"because_of","explicit source reference",o);R!==null&&_.push(R)}return g(this.db,n?"truth.supersede":"truth.set",{truth_id:f.id,supersedes_id:n?.id??null,category:t.category,edges:_.length},{projectId:e}),{fresh:f,superseded:n??null,verified:!1,edges:_}}),{fresh:i,superseded:c,verified:d,edges:s}=r();this.lastWrite=d?"verified":"stored",y(this.db,{projectId:e,kind:"truth",refTable:"ground_truths",refId:i.id,isShared:!!i.is_shared});for(const n of s)y(this.db,{projectId:e,kind:"decision",refTable:"decision_edges",refId:n});if(this.lastCascade=null,c&&this.cascadeHook&&c.value!==i.value&&!/^(1|true|yes|on)$/i.test(process.env.WYRM_NO_AUTO_CASCADE??""))try{this.lastCascade=this.cascadeHook(c,i)}catch{}return i}getCurrent(e,t){return t?this.db.prepare(`
12
19
  SELECT * FROM ground_truths
13
20
  WHERE project_id = ? AND category = ? AND is_current = 1
14
21
  ORDER BY category, key
15
- `).all(t,e):this.db.prepare(`
22
+ `).all(e,t):this.db.prepare(`
16
23
  SELECT * FROM ground_truths
17
24
  WHERE project_id = ? AND is_current = 1
18
25
  ORDER BY category, key
19
- `).all(t)}getHistory(t,e,r){return this.db.prepare(`
26
+ `).all(e)}getHistory(e,t,r){return this.db.prepare(`
20
27
  SELECT * FROM ground_truths
21
28
  WHERE project_id = ? AND category = ? AND key = ?
22
29
  ORDER BY id DESC
23
- `).all(t,e,r)}revoke(t,e,r){return this.db.prepare(`
24
- UPDATE ground_truths SET is_current = 0, updated_at = datetime('now')
25
- WHERE project_id = ? AND category = ? AND key = ? AND is_current = 1
26
- `).run(t,e,r).changes>0}formatForContext(t,e=R){const r=this.getCurrent(t);if(r.length===0)return"";const s={tech_stack:"\u{1F6E0}\uFE0F Tech Stack",architecture:"\u{1F3D7}\uFE0F Architecture",constraint:"\u{1F6A7} Constraints",decision:"\u{1F4CB} Decisions",contact:"\u{1F464} Contacts",other:"\u{1F4CC} Other Facts"},c=new Map;for(const o of r){const l=c.get(o.category)??[];l.push(o),c.set(o.category,l)}let i=`### \u{1F4DA} Project Ground Truths _(treat as authoritative \u2014 do not infer or contradict)_
27
- `,n=i.length;for(const[o,l]of c){const _=`**${s[o]??o}:**
28
- `;if(n+_.length>e)break;i+=_,n+=_.length;for(const u of l){const f=`- **${u.key}:** ${u.value}${u.rationale?` _(${u.rationale})_`:""}
29
- `;if(n+f.length>e)break;i+=f,n+=f.length}}const a=n>=e?`
30
- _(truncated \u2014 use wyrm_truth_get for full list)_
31
- `:"";return i+a}getStats(t){const e=this.db.prepare("SELECT COUNT(*) as n FROM ground_truths WHERE project_id = ? AND is_current = 1").get(t).n,r=this.db.prepare("SELECT COUNT(*) as n FROM ground_truths WHERE project_id = ? AND is_current = 0").get(t).n,s=this.db.prepare(`
30
+ `).all(e,t,r)}revoke(e,t,r){return this.db.transaction(()=>{const i=this.db.prepare(`
31
+ UPDATE ground_truths SET is_current = 0, updated_at = datetime('now')
32
+ WHERE project_id = ? AND category = ? AND key = ? AND is_current = 1
33
+ `).run(e,t,r);return i.changes>0&&g(this.db,"truth.revoke",{category:t,count:i.changes},{projectId:e}),i.changes>0})()}formatForContext(e,t=T){const r=this.getCurrent(e);if(r.length===0)return"";const i={tech_stack:"\u{1F6E0}\uFE0F Tech Stack",architecture:"\u{1F3D7}\uFE0F Architecture",constraint:"\u{1F6A7} Constraints",decision:"\u{1F4CB} Decisions",contact:"\u{1F464} Contacts",other:"\u{1F4CC} Other Facts"},c=new Map;for(const o of r){const l=c.get(o.category)??[];l.push(o),c.set(o.category,l)}let d=`### \u{1F4DA} Project Ground Truths _(treat as authoritative; do not infer or contradict)_
34
+ `,s=d.length;for(const[o,l]of c){const E=`**${i[o]??o}:**
35
+ `;if(s+E.length>t)break;d+=E,s+=E.length;for(const f of l){const _=`- **${f.key}:** ${f.value}${f.rationale?` _(${f.rationale})_`:""}
36
+ `;if(s+_.length>t)break;d+=_,s+=_.length}}const n=s>=t?`
37
+ _(truncated; use wyrm_truth_get for full list)_
38
+ `:"";return d+n}getStats(e){const t=this.db.prepare("SELECT COUNT(*) as n FROM ground_truths WHERE project_id = ? AND is_current = 1").get(e).n,r=this.db.prepare("SELECT COUNT(*) as n FROM ground_truths WHERE project_id = ? AND is_current = 0").get(e).n,i=this.db.prepare(`
32
39
  SELECT category, COUNT(*) as cnt FROM ground_truths
33
40
  WHERE project_id = ? AND is_current = 1 GROUP BY category
34
- `).all(t),c={};for(const i of s)c[i.category]=i.cnt;return{current:e,superseded:r,byCategory:c}}}const N=.3,O=1500;class b{db;constructor(t){this.db=t}save(t){const e=this.db.prepare(`
41
+ `).all(e),c={};for(const d of i)c[d.category]=d.cnt;return{current:t,superseded:r,byCategory:c}}}const L=.3,v=1500;class w{db;constructor(e){this.db=e}save(e){const t=this.db.prepare(`
35
42
  INSERT INTO reasoning_scaffolds
36
43
  (project_id, problem_type, description, when_to_use, steps, verification_steps, do_not_apply_if, tags)
37
44
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
38
- `).run(t.projectId??null,t.problemType.trim(),t.description?.trim()??null,t.whenToUse?.trim()??null,JSON.stringify(t.steps),t.verificationSteps?JSON.stringify(t.verificationSteps):null,t.doNotApplyIf?JSON.stringify(t.doNotApplyIf):null,t.tags?.join(",")??null);return this.get(e.lastInsertRowid)}get(t){return this.db.prepare("SELECT * FROM reasoning_scaffolds WHERE id = ?").get(t)??null}findBest(t,e,r=N){const s=t.replace(/['"*]/g," ").trim();if(!s)return null;const c=e?"AND (s.project_id = ? OR s.project_id IS NULL)":"AND s.project_id IS NULL",i=[s];e&&i.push(e),i.push(10);let n=[];try{n=this.db.prepare(`
45
+ `).run(e.projectId??null,e.problemType.trim(),e.description?.trim()??null,e.whenToUse?.trim()??null,JSON.stringify(e.steps),e.verificationSteps?JSON.stringify(e.verificationSteps):null,e.doNotApplyIf?JSON.stringify(e.doNotApplyIf):null,e.tags?.join(",")??null);return this.get(t.lastInsertRowid)}get(e){return this.db.prepare("SELECT * FROM reasoning_scaffolds WHERE id = ?").get(e)??null}findBest(e,t,r=L){const i=e.replace(/['"*]/g," ").trim();if(!i)return null;const c=t?"AND (s.project_id = ? OR s.project_id IS NULL)":"AND s.project_id IS NULL",d=[i];t&&d.push(t),d.push(10);let s=[];try{s=this.db.prepare(`
39
46
  SELECT s.* FROM reasoning_scaffolds s
40
47
  JOIN scaffolds_fts fts ON s.id = fts.rowid
41
48
  WHERE fts MATCH ?
42
49
  ${c}
43
50
  ORDER BY rank, s.confidence DESC
44
51
  LIMIT ?
45
- `).all(...i)}catch{n=this.fallbackSearch(t,e,5)}if(n.length===0)return null;const a=n[0],l=(n.length>1?.7:1)*a.confidence;return l<r?null:{scaffold:a,matchScore:l}}fallbackSearch(t,e,r=5){const s=t.toLowerCase().split(/\s+/).filter(o=>o.length>3);if(!s.length)return[];const c=s.slice(0,3).map(()=>"LOWER(problem_type) LIKE ? OR LOWER(tags) LIKE ?").join(" OR "),i=s.slice(0,3).flatMap(o=>[`%${o}%`,`%${o}%`]),n=e?"AND (project_id = ? OR project_id IS NULL)":"AND project_id IS NULL",a=[...i];return e&&a.push(e),a.push(r),this.db.prepare(`
52
+ `).all(...d)}catch{s=this.fallbackSearch(e,t,5)}if(s.length===0)return null;const n=s[0],l=(s.length>1?.7:1)*n.confidence;return l<r?null:{scaffold:n,matchScore:l}}fallbackSearch(e,t,r=5){const i=e.toLowerCase().split(/\s+/).filter(o=>o.length>3);if(!i.length)return[];const c=i.slice(0,3).map(()=>"LOWER(problem_type) LIKE ? OR LOWER(tags) LIKE ?").join(" OR "),d=i.slice(0,3).flatMap(o=>[`%${o}%`,`%${o}%`]),s=t?"AND (project_id = ? OR project_id IS NULL)":"AND project_id IS NULL",n=[...d];return t&&n.push(t),n.push(r),this.db.prepare(`
46
53
  SELECT * FROM reasoning_scaffolds
47
- WHERE (${c}) ${n}
54
+ WHERE (${c}) ${s}
48
55
  ORDER BY confidence DESC
49
56
  LIMIT ?
50
- `).all(...a)}recordOutcome(t,e){const r=e?"success_count":"usage_count";this.db.prepare(`
57
+ `).all(...n)}recordOutcome(e,t){const r=t?"success_count":"usage_count";this.db.prepare(`
51
58
  UPDATE reasoning_scaffolds SET
52
59
  usage_count = usage_count + 1,
53
60
  ${r} = ${r} + 1,
@@ -57,17 +64,17 @@ _(truncated \u2014 use wyrm_truth_get for full list)_
57
64
  END,
58
65
  updated_at = datetime('now')
59
66
  WHERE id = ?
60
- `).run(e?1:0,t)}list(t,e=20){const r=t?"WHERE project_id = ? OR project_id IS NULL":"WHERE project_id IS NULL",s=[];return t&&s.push(t),s.push(e),this.db.prepare(`
67
+ `).run(t?1:0,e)}list(e,t=20){const r=e?"WHERE project_id = ? OR project_id IS NULL":"WHERE project_id IS NULL",i=[];return e&&i.push(e),i.push(t),this.db.prepare(`
61
68
  SELECT * FROM reasoning_scaffolds ${r}
62
69
  ORDER BY confidence DESC, usage_count DESC
63
70
  LIMIT ?
64
- `).all(...s)}delete(t){return this.db.prepare("DELETE FROM reasoning_scaffolds WHERE id = ?").run(t).changes>0}formatForContext(t,e=O){const r=t.scaffold,s=JSON.parse(r.steps||"[]"),c=r.verification_steps?JSON.parse(r.verification_steps):[],i=r.do_not_apply_if?JSON.parse(r.do_not_apply_if):[];let n=`### \u{1F9ED} Reasoning Scaffold: "${r.problem_type}" _(confidence: ${(t.matchScore*100).toFixed(0)}%)_
65
- `;r.when_to_use&&(n+=`**When to use:** ${r.when_to_use}
66
- `),i.length&&(n+=`**Do NOT apply if:** ${i.join(" \xB7 ")}
67
- `),n+=`
71
+ `).all(...i)}delete(e){return this.db.prepare("DELETE FROM reasoning_scaffolds WHERE id = ?").run(e).changes>0}formatForContext(e,t=v){const r=e.scaffold,i=JSON.parse(r.steps||"[]"),c=r.verification_steps?JSON.parse(r.verification_steps):[],d=r.do_not_apply_if?JSON.parse(r.do_not_apply_if):[];let s=`### \u{1F9ED} Reasoning Scaffold: "${r.problem_type}" _(confidence: ${(e.matchScore*100).toFixed(0)}%)_
72
+ `;r.when_to_use&&(s+=`**When to use:** ${r.when_to_use}
73
+ `),d.length&&(s+=`**Do NOT apply if:** ${d.join(" \xB7 ")}
74
+ `),s+=`
68
75
  **Execution steps:**
69
- `;for(let a=0;a<s.length;a++){const o=`${a+1}. ${s[a]}
70
- `;if(n.length+o.length>e)break;n+=o}if(c.length&&n.length+100<e){n+=`
76
+ `;for(let n=0;n<i.length;n++){const o=`${n+1}. ${i[n]}
77
+ `;if(s.length+o.length>t)break;s+=o}if(c.length&&s.length+100<t){s+=`
71
78
  **Before finishing, verify:**
72
- `;for(const a of c){const o=`- [ ] ${a}
73
- `;if(n.length+o.length>e)break;n+=o}}return n}}export{L as GroundTruths,b as ReasoningScaffolds,A as computeStaleness};
79
+ `;for(const n of c){const o=`- [ ] ${n}
80
+ `;if(s.length+o.length>t)break;s+=o}}return s}}export{$ as GroundTruths,w as ReasoningScaffolds,U as computeStaleness};
@@ -0,0 +1,39 @@
1
+ import{recordGovernanceEvent as c}from"./governance.js";const i=["harvest","trace-harvest","auto-extract","reverse-bridge"],u=["connector:","hook:","ingest:"],d=/^\[auto:(precompact|sessionend|sessionstart)/i;function R(r,s,o){const t=r??"";if(i.includes(t))return t;for(const e of u)if(t.startsWith(e))return e.slice(0,-1);return(s??"").split(",").some(e=>e.startsWith("lake:"))?"lake-tagged":d.test((o??"").trimStart())?"hook-digest":null}const E=`
2
+ SELECT CASE
3
+ WHEN created_by IN ('harvest', 'trace-harvest', 'auto-extract', 'reverse-bridge') THEN created_by
4
+ WHEN substr(created_by, 1, 10) = 'connector:' THEN 'connector'
5
+ WHEN substr(created_by, 1, 5) = 'hook:' THEN 'hook'
6
+ WHEN substr(created_by, 1, 7) = 'ingest:' THEN 'ingest'
7
+ WHEN instr(',' || COALESCE(tags, '') || ',', ',lake:') > 0 THEN 'lake-tagged'
8
+ WHEN problem LIKE '[auto:precompact%' OR problem LIKE '[auto:sessionend%' OR problem LIKE '[auto:sessionstart%' THEN 'hook-digest'
9
+ END AS writer,
10
+ COUNT(*) AS rows,
11
+ COALESCE(SUM(needs_review), 0) AS queued
12
+ FROM memory_artifacts
13
+ WHERE source_trust = 'agent' AND (? IS NULL OR project_id = ?)
14
+ GROUP BY writer
15
+ HAVING writer IS NOT NULL
16
+ ORDER BY rows DESC, writer ASC
17
+ `,p=`
18
+ UPDATE memory_artifacts SET source_trust = 'imported'
19
+ WHERE source_trust = 'agent' AND (? IS NULL OR project_id = ?)
20
+ AND (created_by IN ('harvest', 'trace-harvest', 'auto-extract', 'reverse-bridge')
21
+ OR substr(created_by, 1, 10) = 'connector:'
22
+ OR substr(created_by, 1, 5) = 'hook:'
23
+ OR substr(created_by, 1, 7) = 'ingest:'
24
+ OR instr(',' || COALESCE(tags, '') || ',', ',lake:') > 0
25
+ OR problem LIKE '[auto:precompact%' OR problem LIKE '[auto:sessionend%' OR problem LIKE '[auto:sessionstart%')
26
+ `,_=`
27
+ SELECT id FROM memory_artifacts
28
+ WHERE needs_review = 1
29
+ AND (source_trust IN ('operator', 'agent')
30
+ OR (source_trust = 'imported'
31
+ AND substr(COALESCE(created_by, ''), 1, 7) <> 'import:'
32
+ AND instr(COALESCE(tags, ''), 'imported_from:') = 0
33
+ AND (created_by IN ('harvest', 'trace-harvest', 'auto-extract', 'reverse-bridge')
34
+ OR substr(created_by, 1, 10) = 'connector:'
35
+ OR substr(created_by, 1, 5) = 'hook:'
36
+ OR substr(created_by, 1, 7) = 'ingest:'
37
+ OR instr(',' || COALESCE(tags, '') || ',', ',lake:') > 0
38
+ OR problem LIKE '[auto:precompact%' OR problem LIKE '[auto:sessionend%' OR problem LIKE '[auto:sessionstart%')))
39
+ `;function m(r,s){const o=r.transaction(()=>{const e=r.prepare(_).all().map(n=>n.id),a=r.prepare("UPDATE memory_artifacts SET needs_review = 0, reviewed_by = ?, reviewed_at = datetime('now') WHERE id = ? AND needs_review = 1");for(const n of e)a.run(s,n);return e.length>0&&c(r,"review.approve",{bulk:!0,count:e.length,artifact_ids:e},{actor:s}),e})(),t=r.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE needs_review = 1").get().n;return{approvedIds:o,refused:t}}function b(r,s={}){const o=s.projectId??null,t=r.prepare(E).all(o,o);return{total:t.reduce((e,a)=>e+a.rows,0),queued:t.reduce((e,a)=>e+a.queued,0),byWriter:t,applied:!1}}function O(r,s={}){const o=s.projectId??null;return r.transaction(()=>{const t=b(r,{projectId:o});if(t.total===0)return t;r.prepare(p).run(o,o);const e={};for(const a of t.byWriter)e[a.writer]=a.rows;return c(r,"lanes.reclassify",{from:"agent",to:"imported",moved:t.total,queued:t.queued,by_writer:e},{projectId:o}),{...t,applied:!0}})()}export{i as THIRD_PARTY_WRITERS,u as THIRD_PARTY_WRITER_PREFIXES,O as applyLaneReclassification,m as bulkApproveQueued,b as planLaneReclassification,R as thirdPartyProvenance};
package/dist/license.js CHANGED
@@ -1,3 +1,3 @@
1
1
  import{createPrivateKey as L,createPublicKey as T,sign as I,verify as A,generateKeyPairSync as K,randomBytes as h}from"crypto";import{readFileSync as b,writeFileSync as F,mkdirSync as B,existsSync as m,chmodSync as R}from"fs";import{homedir as N}from"os";import{join as _}from"path";import{OFFICIAL_BUILD as v}from"./build-flags.js";import{loadRevocations as D,isKeyRevoked as S}from"./revocations.js";const g="ABCDEFGHJKMNPQRSTUVWXYZ234567890",M="WRM",P=4,C=4,l=_(N(),".wyrm"),c=_(l,"license.json"),n={free:["local_storage","all_tools","fts_search","unlimited_projects"],pro:["cloud_backup","encryption","analytics","priority_support"],team:["shared_memory","workspaces","admin_dashboard","slack_integration"],enterprise:["unlimited_seats","sso_saml","custom_sla","on_premise"]},p=["free","pro","team","enterprise"],Y={free:1,pro:1,team:25,enterprise:-1},O=`-----BEGIN PUBLIC KEY-----
2
2
  MCowBQYDK2VwAyEA5WkbNjI9tclD+Mps13IzEXH5FhCBnblwy4+bjYJHpOk=
3
- -----END PUBLIC KEY-----`;let s=null,o="free",a=new Set(n.free);function j(e){const r=p.indexOf(e),i=[];for(let t=0;t<=r;t++)i.push(...n[p[t]]);return[...new Set(i)]}function w(e){return[e.key,e.product,e.tier,e.issued_to,e.issued_at,e.expires_at??"perpetual",String(e.max_devices),e.features.sort().join(","),e.hardware_id??""].join("|")}function U(e){const r=h(e);let i="";for(let t=0;t<e;t++)i+=g[r[t]%g.length];return i}function ie(){const{publicKey:e,privateKey:r}=K("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKey:e,privateKey:r}}function V(){const e=[];for(let r=0;r<P;r++)e.push(U(C));return`${M}-${e.join("-")}`}function ne(e,r,i={}){const t=j(r);if(i.extraFeatures)for(const u of i.extraFeatures)t.includes(u)||t.push(u);return{key:V(),product:"wyrm",tier:r,issued_to:e,issued_at:new Date().toISOString(),expires_at:i.expiresAt??null,max_devices:i.maxDevices??Y[r],features:t,hardware_id:i.hardwareId}}function se(e,r){const i=w(e),t=L(r),u=I(null,Buffer.from(i,"utf-8"),t);return{license:e,signature:u.toString("base64")}}function f(e,r){const i={valid:!1,tier:"free",features:[...n.free],expiresAt:null};try{const{license:t,signature:u}=e;if(t.product!=="wyrm")return{...i,error:"Invalid product identifier"};if(!p.includes(t.tier))return{...i,error:`Unknown tier: ${t.tier}`};const E=w(t),k=r??O;let x;try{x=T(k)}catch{return{...i,error:"Invalid public key"}}if(!A(null,Buffer.from(E,"utf-8"),x,Buffer.from(u,"base64")))return{...i,error:"Invalid signature \u2014 license may be tampered"};if(t.expires_at!==null){const y=new Date(t.expires_at);if(isNaN(y.getTime()))return{...i,error:"Malformed expiry date"};if(y.getTime()<Date.now())return{valid:!1,tier:t.tier,features:[...n.free],expiresAt:t.expires_at,error:`License expired on ${t.expires_at}`}}return S(t.key)?{valid:!1,tier:t.tier,features:[...n.free],expiresAt:t.expires_at,error:"License revoked"}:{valid:!0,tier:t.tier,features:[...t.features],expiresAt:t.expires_at}}catch(t){const u=t instanceof Error?t.message:String(t);return{...i,error:`Verification failed: ${u}`}}}function H(){try{const e={license:{key:"WRM-KAT0-KAT0-KAT0-KAT0",product:"wyrm",tier:"enterprise",issued_to:"integrity@selftest",issued_at:"2026-01-01T00:00:00.000Z",expires_at:null,max_devices:-1,features:[...n.enterprise]},signature:Buffer.from("integrity-self-test-not-a-valid-signature").toString("base64")};return f(e).valid?{ok:!1,reason:"verifier_accepts_forged_signature"}:{ok:!0}}catch{return{ok:!0}}}let d=null;function J(){return d===null&&(d=v?!H().ok:!1),d}function oe(e){if(J()&&!n.free.includes(e))return!1;if(s){const{license:r}=s;(r.expires_at!==null&&new Date(r.expires_at).getTime()<Date.now()||S(r.key))&&(o="free",a=new Set(n.free))}return a.has(e)}function ae(){return o}function ue(){if(!s)return{tier:"free",features:[...n.free],expiresAt:null,valid:!1,issuedTo:null,key:null};const e=f(s);return{tier:e.tier,features:e.features,expiresAt:e.expiresAt,valid:e.valid,issuedTo:s.license.issued_to,key:s.license.key,error:e.error}}function W(){try{if(!m(c))return null;const e=b(c,"utf-8"),r=JSON.parse(e);return!r.license||!r.signature||!r.license.key||!r.license.tier?null:r}catch{return null}}function G(e){m(l)||B(l,{recursive:!0});const r=JSON.stringify(e,null,2);F(c,r,{encoding:"utf-8",mode:384}),R(c,384)}function fe(e){let r;try{r=JSON.parse(e)}catch{return{valid:!1,tier:"free",features:[...n.free],expiresAt:null,error:"Invalid license format \u2014 expected JSON"}}if(!r.license||!r.signature)return{valid:!1,tier:"free",features:[...n.free],expiresAt:null,error:"Malformed license \u2014 missing license data or signature"};const i=f(r);return i.valid&&(G(r),s=r,o=i.tier,a=new Set(i.features)),i}function $(e){return e==="License revoked"||/^License expired on /.test(e??"")}function X(e,r){if(!e)return s=null,o="free",a=new Set(n.free),{valid:!1,tier:"free",features:[...n.free],expiresAt:null};const i=f(e,r);return i.valid?(s=e,o=i.tier,a=new Set(i.features)):$(i.error)?(s=e,o="free",a=new Set(n.free)):(s=null,o="free",a=new Set(n.free)),i}function ce(){D(),X(W())}function le(){if(!s)return o="free",a=new Set(n.free),{valid:!1,tier:"free",features:[...n.free],expiresAt:null};const e=f(s);return e.valid?(o=e.tier,a=new Set(e.features)):(o="free",a=new Set(n.free)),e}function pe(){s=null,o="free",a=new Set(n.free)}function de(e){v||(s=e,o=e.license.tier,a=new Set(e.license.features))}export{Y as TIER_DEVICE_LIMITS,n as TIER_FEATURES,O as WYRM_PUBLIC_KEY,de as __setLicenseForTesting,fe as activateLicense,X as applyLoadedLicense,ne as createLicense,ie as generateKeyPair,V as generateLicenseKey,ue as getLicenseInfo,ae as getTier,oe as hasFeature,ce as initializeLicense,W as loadLicense,le as reconcileLicenseState,pe as resetLicense,j as resolveFeaturesForTier,G as saveLicense,H as selfTestVerifier,se as signLicense,f as verifyLicense};
3
+ -----END PUBLIC KEY-----`;let s=null,o="free",a=new Set(n.free);function j(e){const r=p.indexOf(e),i=[];for(let t=0;t<=r;t++)i.push(...n[p[t]]);return[...new Set(i)]}function w(e){return[e.key,e.product,e.tier,e.issued_to,e.issued_at,e.expires_at??"perpetual",String(e.max_devices),e.features.sort().join(","),e.hardware_id??""].join("|")}function U(e){const r=h(e);let i="";for(let t=0;t<e;t++)i+=g[r[t]%g.length];return i}function ie(){const{publicKey:e,privateKey:r}=K("ed25519",{publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{publicKey:e,privateKey:r}}function V(){const e=[];for(let r=0;r<P;r++)e.push(U(C));return`${M}-${e.join("-")}`}function ne(e,r,i={}){const t=j(r);if(i.extraFeatures)for(const u of i.extraFeatures)t.includes(u)||t.push(u);return{key:V(),product:"wyrm",tier:r,issued_to:e,issued_at:new Date().toISOString(),expires_at:i.expiresAt??null,max_devices:i.maxDevices??Y[r],features:t,hardware_id:i.hardwareId}}function se(e,r){const i=w(e),t=L(r),u=I(null,Buffer.from(i,"utf-8"),t);return{license:e,signature:u.toString("base64")}}function f(e,r){const i={valid:!1,tier:"free",features:[...n.free],expiresAt:null};try{const{license:t,signature:u}=e;if(t.product!=="wyrm")return{...i,error:"Invalid product identifier"};if(!p.includes(t.tier))return{...i,error:`Unknown tier: ${t.tier}`};const E=w(t),k=r??O;let x;try{x=T(k)}catch{return{...i,error:"Invalid public key"}}if(!A(null,Buffer.from(E,"utf-8"),x,Buffer.from(u,"base64")))return{...i,error:"Invalid signature: license may be tampered"};if(t.expires_at!==null){const y=new Date(t.expires_at);if(isNaN(y.getTime()))return{...i,error:"Malformed expiry date"};if(y.getTime()<Date.now())return{valid:!1,tier:t.tier,features:[...n.free],expiresAt:t.expires_at,error:`License expired on ${t.expires_at}`}}return S(t.key)?{valid:!1,tier:t.tier,features:[...n.free],expiresAt:t.expires_at,error:"License revoked"}:{valid:!0,tier:t.tier,features:[...t.features],expiresAt:t.expires_at}}catch(t){const u=t instanceof Error?t.message:String(t);return{...i,error:`Verification failed: ${u}`}}}function H(){try{const e={license:{key:"WRM-KAT0-KAT0-KAT0-KAT0",product:"wyrm",tier:"enterprise",issued_to:"integrity@selftest",issued_at:"2026-01-01T00:00:00.000Z",expires_at:null,max_devices:-1,features:[...n.enterprise]},signature:Buffer.from("integrity-self-test-not-a-valid-signature").toString("base64")};return f(e).valid?{ok:!1,reason:"verifier_accepts_forged_signature"}:{ok:!0}}catch{return{ok:!0}}}let d=null;function J(){return d===null&&(d=v?!H().ok:!1),d}function oe(e){if(J()&&!n.free.includes(e))return!1;if(s){const{license:r}=s;(r.expires_at!==null&&new Date(r.expires_at).getTime()<Date.now()||S(r.key))&&(o="free",a=new Set(n.free))}return a.has(e)}function ae(){return o}function ue(){if(!s)return{tier:"free",features:[...n.free],expiresAt:null,valid:!1,issuedTo:null,key:null};const e=f(s);return{tier:e.tier,features:e.features,expiresAt:e.expiresAt,valid:e.valid,issuedTo:s.license.issued_to,key:s.license.key,error:e.error}}function W(){try{if(!m(c))return null;const e=b(c,"utf-8"),r=JSON.parse(e);return!r.license||!r.signature||!r.license.key||!r.license.tier?null:r}catch{return null}}function G(e){m(l)||B(l,{recursive:!0});const r=JSON.stringify(e,null,2);F(c,r,{encoding:"utf-8",mode:384}),R(c,384)}function fe(e){let r;try{r=JSON.parse(e)}catch{return{valid:!1,tier:"free",features:[...n.free],expiresAt:null,error:"Invalid license format: expected JSON"}}if(!r.license||!r.signature)return{valid:!1,tier:"free",features:[...n.free],expiresAt:null,error:"Malformed license: missing license data or signature"};const i=f(r);return i.valid&&(G(r),s=r,o=i.tier,a=new Set(i.features)),i}function $(e){return e==="License revoked"||/^License expired on /.test(e??"")}function X(e,r){if(!e)return s=null,o="free",a=new Set(n.free),{valid:!1,tier:"free",features:[...n.free],expiresAt:null};const i=f(e,r);return i.valid?(s=e,o=i.tier,a=new Set(i.features)):$(i.error)?(s=e,o="free",a=new Set(n.free)):(s=null,o="free",a=new Set(n.free)),i}function ce(){D(),X(W())}function le(){if(!s)return o="free",a=new Set(n.free),{valid:!1,tier:"free",features:[...n.free],expiresAt:null};const e=f(s);return e.valid?(o=e.tier,a=new Set(e.features)):(o="free",a=new Set(n.free)),e}function pe(){s=null,o="free",a=new Set(n.free)}function de(e){v||(s=e,o=e.license.tier,a=new Set(e.license.features))}export{Y as TIER_DEVICE_LIMITS,n as TIER_FEATURES,O as WYRM_PUBLIC_KEY,de as __setLicenseForTesting,fe as activateLicense,X as applyLoadedLicense,ne as createLicense,ie as generateKeyPair,V as generateLicenseKey,ue as getLicenseInfo,ae as getTier,oe as hasFeature,ce as initializeLicense,W as loadLicense,le as reconcileLicenseState,pe as resetLicense,j as resolveFeaturesForTier,G as saveLicense,H as selfTestVerifier,se as signLicense,f as verifyLicense};
@@ -0,0 +1,15 @@
1
+ import{createHash as I,randomUUID as T}from"node:crypto";import{hostname as S}from"node:os";import{existsSync as x,readFileSync as v,realpathSync as C}from"node:fs";import{dirname as A,join as L}from"node:path";import{logger as h}from"./logger.js";const l="device_id",g="device_epoch",s="store_fingerprint",O="device_epoch_reason",y="device_epoch_at",N="bridge_reconcile_pending",w=1e9,D={cloud:"cloud-cursor.json",bridge:"bridge-cursor.json"},p=e=>`event_seq:${e}`;function o(e,r){return e.prepare("SELECT value FROM wyrm_meta WHERE key = ?").get(r)?.value}function i(e,r,t){e.prepare(`INSERT INTO wyrm_meta (key, value) VALUES (?, ?)
2
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(r,t)}const R=new WeakMap,_=new WeakSet;function E(e){const r=R.get(e);if(r)return r;let t=o(e,l);if(!t){const n=`${S().slice(0,24)}-${T().slice(0,8)}`;e.prepare("INSERT OR IGNORE INTO wyrm_meta (key, value) VALUES (?, ?)").run(l,n),t=o(e,l)||n}return R.set(e,t),t}function u(e){const r=Number(o(e,g)??"0");return Number.isSafeInteger(r)&&r>=0?r:0}function F(){const e=process.env.WYRM_LINEAGE_HOST_ID;if(e&&e.trim())return`override:${e.trim()}`;for(const r of["/etc/machine-id","/var/lib/dbus/machine-id"])try{const t=v(r,"utf8").trim();if(t)return`machine:${t}`}catch{}return`host:${S()}`}function m(e){const r=e.name;if(!r||r===":memory:"||e.memory)return null;let t=r;try{t=C(r)}catch{}return I("sha256").update(`${F()}
3
+ ${t}`).digest("hex").slice(0,32)}function k(e,r){const t=E(e);let n=0;return e.transaction(()=>{n=u(e)+1,i(e,g,String(n)),i(e,O,r.slice(0,200)),i(e,y,new Date().toISOString()),i(e,N,"1");const a=m(e);a&&i(e,s,a);const c=Number(o(e,p(t))??"0"),d=Number.isSafeInteger(c)?c:0;i(e,p(t),String(d+w))})(),h.warn("lineage: device epoch bumped",{db:e.name,epoch:n,reason:r}),n}function H(e){if(!_.has(e)){_.add(e);try{E(e);const r=m(e);if(r){const t=o(e,s);t?t!==r&&e.prepare("UPDATE wyrm_meta SET value = ? WHERE key = ? AND value = ?").run(r,s,t).changes===1&&k(e,"store fingerprint changed (the database was copied, moved or restored)"):e.prepare("INSERT OR IGNORE INTO wyrm_meta (key, value) VALUES (?, ?)").run(s,r),j(e,A(e.name))}}catch(r){_.delete(e),h.warn("lineage: check skipped",{db:e.name,err:r instanceof Error?r.message:String(r)})}}}function U(e){return H(e),{deviceId:E(e),epoch:u(e)}}function $(e,r){const t=p(r);e.prepare("INSERT OR IGNORE INTO wyrm_meta (key, value) VALUES (?, '0')").run(t);const n=e.prepare(`
4
+ UPDATE wyrm_meta
5
+ SET value = CAST(MAX(CAST(value AS INTEGER),
6
+ (SELECT COALESCE(MAX(origin_seq), 0) FROM events WHERE origin_device = ?)) + 1 AS TEXT)
7
+ WHERE key = ?
8
+ RETURNING value
9
+ `).get(r,t);return Number(n.value)}function f(e){return!!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sync_cursors'").get()}function K(e,r){if(!f(e))return null;const t=e.prepare("SELECT value_json, device_epoch, imported_from, updated_at FROM sync_cursors WHERE name = ?").get(r);if(!t)return null;try{return{value:JSON.parse(t.value_json),epoch:t.device_epoch,importedFrom:t.imported_from,updatedAt:t.updated_at}}catch{return null}}function q(e,r,t){e.prepare(`
10
+ INSERT INTO sync_cursors (name, value_json, device_epoch, updated_at) VALUES (?, ?, ?, datetime('now'))
11
+ ON CONFLICT(name) DO UPDATE SET value_json = excluded.value_json, device_epoch = excluded.device_epoch, updated_at = excluded.updated_at
12
+ `).run(r,JSON.stringify(t),u(e))}function M(e,r,t){if(!f(e))return"no-table";if(e.prepare("SELECT 1 FROM sync_cursors WHERE name = ?").get(r))return"present";if(!x(t))return"absent";let n;try{n=JSON.parse(v(t,"utf8"))}catch{return"unreadable"}if(!n||typeof n!="object"||Array.isArray(n))return"unreadable";const{store:a,...c}=n;return e.prepare(`
13
+ INSERT OR IGNORE INTO sync_cursors (name, value_json, device_epoch, imported_from, updated_at)
14
+ VALUES (?, ?, ?, ?, datetime('now'))
15
+ `).run(r,JSON.stringify(c),u(e),t).changes>0?"imported":"present"}function j(e,r){const t={};for(const[n,a]of Object.entries(D))try{t[n]=M(e,n,L(r,a))}catch{t[n]="unreadable"}return t}function J(e){return{device_id:E(e),epoch:u(e),fingerprint:m(e)}}function X(e){const r=U(e),t=m(e),n=o(e,s)??null,a=f(e)?e.prepare("SELECT name, device_epoch, imported_from, updated_at FROM sync_cursors ORDER BY name").all().map(c=>({name:c.name,epoch:c.device_epoch,importedFrom:c.imported_from,updatedAt:c.updated_at})):[];return{...r,fingerprint:t,fingerprintMatches:t&&n?t===n:null,epochReason:o(e,O)??null,epochAt:o(e,y)??null,reconcilePending:o(e,N)==="1",nextSeq:Number(o(e,p(r.deviceId))??"0")+1,cursors:a}}export{g as DEVICE_EPOCH_KEY,l as DEVICE_ID_KEY,y as EPOCH_AT_KEY,O as EPOCH_REASON_KEY,w as EPOCH_SEQ_GAP,D as LEGACY_CURSOR_FILES,N as RECONCILE_PENDING_KEY,s as STORE_FINGERPRINT_KEY,k as bumpDeviceEpoch,H as ensureLineage,K as getCursor,u as getDeviceEpoch,E as getDeviceId,U as getLineage,M as importCursorFile,j as importLegacyCursorFiles,X as lineageStatus,J as mirrorStamp,$ as nextOriginSeq,q as setCursor,m as storeFingerprint};
@@ -1,2 +1,2 @@
1
- import{resolveEmbeddingState as f}from"./providers/embedding-provider.js";const u="embedding_servers",m=720*60*60*1e3;function d(r){if(!Number.isInteger(r)||r<=0)return!1;try{return process.kill(r,0),!0}catch(n){return n.code==="EPERM"}}function l(r){try{const n=r.prepare("SELECT value FROM wyrm_meta WHERE key = ?").get(u);if(!n)return{};const e=JSON.parse(n.value);return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return{}}}function p(r,n){const e=Date.parse(r.at);return Number.isFinite(e)&&n-e<=m&&n-e>=-6e4}function w(r,n,e={}){try{const i=e.now??Date.now(),o=e.pid??process.pid,t=l(r);for(const[c,s]of Object.entries(t))(Number(c)===o||!s||!d(s.pid)||!p(s,i))&&delete t[c];t[String(o)]={...n,pid:o,cwd:e.cwd??process.cwd(),at:new Date(i).toISOString()},r.prepare(`INSERT INTO wyrm_meta (key, value) VALUES (?, ?)
2
- ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(u,JSON.stringify(t))}catch{}}function E(r,n,e=Date.now()){const i=Object.values(l(r)).filter(t=>t&&typeof t.pid=="number"&&d(t.pid)&&p(t,e));if(!i.length)return null;const o=t=>(t||"").replace(/\/+$/,"");if(n){const t=o(n),c=i.filter(s=>{const a=o(s.cwd);return a!==""&&(t===a||t.startsWith(a+"/"))}).sort((s,a)=>o(a.cwd).length-o(s.cwd).length||a.at.localeCompare(s.at));if(c.length)return c[0]}return i.sort((t,c)=>c.at.localeCompare(t.at))[0]}function g(r,n){if(r){const e=E(r,n);if(e){const{pid:i,cwd:o,at:t,...c}=e;return{...c,source:"server",pid:i,cwd:o}}}return{...f(),source:"env"}}export{u as LIVE_EMBEDDING_KEY,g as effectiveEmbeddingState,E as liveEmbeddingState,d as pidAlive,w as recordServerEmbeddingState};
1
+ import{resolveEmbeddingState as p}from"./providers/embedding-provider.js";const l="embedding_servers",m=720*60*60*1e3;function u(t){if(!Number.isInteger(t)||t<=0)return!1;try{return process.kill(t,0),!0}catch(r){return r.code==="EPERM"}}function d(t){try{const r=t.prepare("SELECT value FROM wyrm_meta WHERE key = ?").get(l);if(!r)return{};const e=JSON.parse(r.value);return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return{}}}function f(t,r){const e=Date.parse(t.at);return Number.isFinite(e)&&r-e<=m&&r-e>=-6e4}function w(t,r,e={}){try{const i=e.now??Date.now(),o=e.pid??process.pid,n=d(t);for(const[c,s]of Object.entries(n))(Number(c)===o||!s||!u(s.pid)||!f(s,i))&&delete n[c];n[String(o)]={...r,pid:o,cwd:e.cwd??process.cwd(),at:new Date(i).toISOString()},t.prepare(`INSERT INTO wyrm_meta (key, value) VALUES (?, ?)
2
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`).run(l,JSON.stringify(n))}catch{}}function S(t){const r=new Set;for(const e of Object.values(d(t)))e&&typeof e.pid=="number"&&typeof e.model=="string"&&e.model&&e.resolved!=="none"&&u(e.pid)&&r.add(e.model);return[...r]}function v(t,r,e=Date.now()){const i=Object.values(d(t)).filter(n=>n&&typeof n.pid=="number"&&u(n.pid)&&f(n,e));if(!i.length)return null;const o=n=>(n||"").replace(/\/+$/,"");if(r){const n=o(r),c=i.filter(s=>{const a=o(s.cwd);return a!==""&&(n===a||n.startsWith(a+"/"))}).sort((s,a)=>o(a.cwd).length-o(s.cwd).length||a.at.localeCompare(s.at));if(c.length)return c[0]}return i.sort((n,c)=>c.at.localeCompare(n.at))[0]}function g(t,r){if(t){const e=v(t,r);if(e){const{pid:i,cwd:o,at:n,...c}=e;return{...c,source:"server",pid:i,cwd:o}}}return{...p(),source:"env"}}export{l as LIVE_EMBEDDING_KEY,g as effectiveEmbeddingState,v as liveEmbeddingState,S as liveServerModels,u as pidAlive,w as recordServerEmbeddingState};
@@ -1,4 +1,4 @@
1
- import{pruneWriteLedger as l}from"./receipts.js";import{metabolizeEnabled as h,metabolizeDefaultEnabled as f,runMetabolize as m}from"./metabolize.js";import{ServedRecords as E}from"./served-records.js";import{ReadMemos as b}from"./read-memo.js";import{ToolAnalytics as R}from"./tool-analytics.js";import{WyrmAnalytics as y}from"./analytics.js";function w(i,d={}){const{db:n,sessionSeen:u,failures:a,presence:p}=i,{vacuum:_,archiveDays:o}=d,t=[];if(o){const e=n.getAllProjects(1e3);let s=0;for(const r of e)s+=n.archiveOldSessions(r.id,o);t.push(`Archived ${s} old sessions`)}_&&(n.vacuum(),t.push("Vacuumed database"));try{const e=parseInt(process.env.WYRM_SEEN_TTL_DAYS??"7",10),s=u.prune(Number.isFinite(e)&&e>0?e:7);s>0&&t.push(`Pruned ${s} session_seen_artifacts rows older than ${e}d`)}catch{}try{const e=parseInt(process.env.WYRM_SEEN_TTL_DAYS??"7",10),s=Number.isFinite(e)&&e>0?e:7,r=new E(n.getDatabase()).prune(s);r>0&&t.push(`Pruned ${r} served_records rows older than ${s}d`)}catch{}try{const e=parseInt(process.env.WYRM_MEMO_TTL_DAYS??"7",10),s=Number.isFinite(e)&&e>0?e:7,r=new b(n.getDatabase()).prune(s);r>0&&t.push(`Pruned ${r} read_memos rows older than ${s}d`)}catch{}try{const e=parseInt(process.env.WYRM_TOOL_LOG_RETAIN_DAYS??"90",10),s=Number.isFinite(e)&&e>0?e:90,r=new R(n.getDatabase()).prune(s);r>0&&t.push(`Pruned ${r} tool_call_log rows older than ${s}d`)}catch{}try{const e=parseInt(process.env.WYRM_USAGE_RETAIN_DAYS??"90",10),s=Number.isFinite(e)&&e>0?e:90,r=new y(n.getDatabase());try{const{deleted:c}=r.cleanup(s);c>0&&t.push(`Rolled up and pruned ${c} usage_events rows older than ${s}d`)}finally{r.shutdown()}}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),s=parseInt(process.env.WYRM_EVENT_MAX_PER_PROJECT??"5000",10),{deleted:r}=n.pruneEvents({olderThanDays:Number.isFinite(e)?e:90,maxPerProject:Number.isFinite(s)?s:5e3});r>0&&t.push(`Pruned ${r} Live Memory events (retention)`)}catch{}try{if(f()){const e=m(n.getDatabase(),{near:h()});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=l(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),s=Number.isFinite(e)&&e>0?e:90,r=a.pruneBlocks(s);r>0&&t.push(`Pruned ${r} failure_blocks rows older than ${s}d (retention)`)}catch{}try{const e=p.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),s=Number.isFinite(e)&&e>0?e:90,r=n.getDatabase().prepare("DELETE FROM run_briefs WHERE created_at < datetime('now', ?)").run(`-${s} days`).changes;r>0&&t.push(`Pruned ${r} run_briefs rows older than ${s}d (retention)`)}catch{}try{const e=parseInt(process.env.WYRM_RUN_BRIEFS_MAX??"512",10),s=Number.isFinite(e)&&e>0?e:512,r=n.getDatabase().prepare(`
1
+ import{pruneWriteLedger as m}from"./receipts.js";import{metabolizeEnabled as f,metabolizeDefaultEnabled as _,runMetabolize as y}from"./metabolize.js";import{ServedRecords as b}from"./served-records.js";import{ReadMemos as R}from"./read-memo.js";import{ToolAnalytics as $}from"./tool-analytics.js";import{WyrmAnalytics as E}from"./analytics.js";import{failureQuietDays as D}from"./failure-patterns.js";import{enforceIngestRetention as g,retentionLine as v}from"./retention.js";import{compactGraph as M,formatBytes as w,pruneEndedRuns as N,pruneReferenceModel as c,pruneStuckQueue as T,pruneVectors as A,runRetainDays as I}from"./index-health.js";import{liveServerModels as S}from"./live-embedding-state.js";function B(u,a={}){const{db:n,sessionSeen:p,failures:o,presence:l}=u,{vacuum:h,archiveDays:i}=a,s=[];if(i){const e=n.getAllProjects(1e3);let r=0;for(const t of e)r+=n.archiveOldSessions(t.id,i);s.push(`Archived ${r} old sessions`)}h&&(n.vacuum(),s.push("Vacuumed database"));try{const e=parseInt(process.env.WYRM_SEEN_TTL_DAYS??"7",10),r=p.prune(Number.isFinite(e)&&e>0?e:7);r>0&&s.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,t=new b(n.getDatabase()).prune(r);t>0&&s.push(`Pruned ${t} served_records rows older than ${r}d`)}catch{}try{const e=parseInt(process.env.WYRM_MEMO_TTL_DAYS??"7",10),r=Number.isFinite(e)&&e>0?e:7,t=new R(n.getDatabase()).prune(r);t>0&&s.push(`Pruned ${t} read_memos rows older than ${r}d`)}catch{}try{const e=parseInt(process.env.WYRM_TOOL_LOG_RETAIN_DAYS??"90",10),r=Number.isFinite(e)&&e>0?e:90,t=new $(n.getDatabase()).prune(r);t>0&&s.push(`Pruned ${t} tool_call_log rows older than ${r}d`)}catch{}try{const e=parseInt(process.env.WYRM_USAGE_RETAIN_DAYS??"90",10),r=Number.isFinite(e)&&e>0?e:90,t=new E(n.getDatabase());try{const{deleted:d}=t.cleanup(r);d>0&&s.push(`Rolled up and pruned ${d} usage_events rows older than ${r}d`)}finally{t.shutdown()}}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:t}=n.pruneEvents({olderThanDays:Number.isFinite(e)?e:90,maxPerProject:Number.isFinite(r)?r:5e3});t>0&&s.push(`Pruned ${t} Live Memory events (retention)`)}catch{}try{const e=v(g(n,{days:a.ingestRetainDays,actor:"maintenance"}));e&&s.push(e)}catch{}try{if(_()){const e=y(n.getDatabase(),{near:f()});e.exactMerged+e.nearCandidatesQueued+e.decayed>0&&s.push(`Metabolize: ${e.exactMerged} exact dupes superseded, ${e.nearCandidatesQueued} near-dup candidates queued, ${e.decayed} stale auto-captures decayed`)}}catch{}try{const e=m(n.getDatabase());e>0&&s.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,t=o.pruneBlocks(r);t>0&&s.push(`Pruned ${t} failure_blocks rows older than ${r}d (retention)`)}catch{}try{const e=l.reap();(e.presence>0||e.claims>0)&&s.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,t=n.getDatabase().prepare("DELETE FROM run_briefs WHERE created_at < datetime('now', ?)").run(`-${r} days`).changes;t>0&&s.push(`Pruned ${t} 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,t=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(s).changes;r>0&&t.push(`Pruned ${r} run_briefs rows over the ${s}-row cap (WYRM_RUN_BRIEFS_MAX)`)}catch{}try{const e=parseInt(process.env.WYRM_RUN_INACTIVE_HOURS??"24",10),s=a.sweepRunQuarantine({runInactiveHours:Number.isFinite(e)&&e>0?e:24});(s.promoted>0||s.expired>0||s.runs_abandoned>0)&&t.push(`Run-quarantine sweep: promoted ${s.promoted} failure(s), expired ${s.expired} abandoned-run failure(s), TTL-abandoned ${s.runs_abandoned} stalled run(s)`),s.degraded&&t.push(`Run-quarantine sweep: ${s.degraded}`)}catch{}return n.checkpoint(),t.push("Checkpointed WAL"),{lines:t,dbSize:n.getStats().dbSize}}export{w as runMaintenance};
4
+ )`).run(r).changes;t>0&&s.push(`Pruned ${t} 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=o.sweepRunQuarantine({runInactiveHours:Number.isFinite(e)&&e>0?e:24});(r.promoted>0||r.expired>0||r.runs_abandoned>0)&&s.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&&s.push(`Run-quarantine sweep: ${r.degraded}`)}catch{}try{const e=D();if(e>0){const r=o.sweepQuiet(e);r.downgraded>0&&s.push(`Quiet-period sweep: ${r.downgraded} unresolved failure(s) with no hits for ${e}d downgraded from block to warn (history recorded; recording one again re-arms it)`)}}catch{}try{const e=n.getDatabase(),r=A(e,{activeModel:c(e,a.activeModel),protectedModels:S(e)});r.deleted+r.relabelled>0&&s.push(`Vector hygiene: removed ${r.orphans} orphan, ${r.superseded} superseded and ${r.oldModel} old-model vector(s); ${r.mislabelled} mislabelled (${r.relabelled} relabelled); ${w(r.bytes)} freed`)}catch{}try{const e=n.getDatabase(),r=T(e,{activeModel:c(e,a.activeModel)});r.cleared>0&&s.push(`Indexing queue: cleared ${r.cleared} stuck row(s) (${r.gone} gone, ${r.notNeeded} no longer eligible, ${r.embedded} already embedded); ${r.remaining} still waiting for a vector`)}catch{}try{const e=a.runRetainDays??I();if(e>0){const r=N(n.getDatabase(),{olderThanDays:e});r.runs>0&&s.push(`Pruned ${r.runs} ended run(s) and ${r.runAgents} run_agents row(s) older than ${e}d (WYRM_RUN_RETAIN_DAYS)`)}}catch{}try{if(a.compactGraph??process.env.WYRM_GRAPH_COMPACT==="1"){const e=M(n.getDatabase());e.relationships+e.entities>0&&s.push(`Graph compaction: removed ${e.relationships} unsupported relationship(s) and ${e.entities} entit${e.entities===1?"y":"ies"} no live memory mentions`)}}catch{}return n.checkpoint(),s.push("Checkpointed WAL"),{lines:s,dbSize:n.getStats().dbSize}}export{B as runMaintenance};
@@ -1,2 +1,2 @@
1
- import*as n from"crypto";import*as r from"fs";import*as i from"path";import*as m from"os";class d{keyPath;pinsPath;key=null;warnedUnpinned=new Set;constructor(e=i.join(m.homedir(),".wyrm")){this.keyPath=i.join(e,"mcp-integrity.key"),this.pinsPath=i.join(e,"mcp-integrity.json")}loadKey(){if(this.key)return this.key;try{this.key=r.readFileSync(this.keyPath)}catch{r.mkdirSync(i.dirname(this.keyPath),{recursive:!0}),this.key=n.randomBytes(32),r.writeFileSync(this.keyPath,this.key,{mode:384})}return this.key}readPins(){try{return JSON.parse(r.readFileSync(this.pinsPath,"utf-8"))}catch{return{}}}writePins(e){r.mkdirSync(i.dirname(this.pinsPath),{recursive:!0}),r.writeFileSync(this.pinsPath,JSON.stringify(e,null,2),{mode:384})}mac(e){const t=JSON.stringify([e.server_name,e.command,e.args??null,e.env??null]);return n.createHmac("sha256",this.loadKey()).update(t).digest("hex")}pin(e){const t=this.readPins();t[e.server_name]=this.mac(e),this.writePins(t)}unpin(e){const t=this.readPins();e in t&&(delete t[e],this.writePins(t))}verify(e){const s=this.readPins()[e.server_name];if(s===void 0){this.warnedUnpinned.has(e.server_name)||(this.warnedUnpinned.add(e.server_name),process.stderr.write(`wyrm: MCP server "${e.server_name}" predates integrity pinning \u2014 pinning its current config now (trust-on-first-use)
2
- `)),this.pin(e);return}const h=this.mac(e);if(!n.timingSafeEqual(Buffer.from(s,"hex"),Buffer.from(h,"hex"))){const a=new Error(`MCP server "${e.server_name}" config does not match its integrity pin \u2014 its command/args/env changed outside wyrm_mcp_register. Refusing to spawn. If this change is intentional, re-register the server with wyrm_mcp_register to re-pin it.`);throw a.code="WYRM_MCP_INTEGRITY",a}}}export{d as McpIntegrity};
1
+ import*as n from"crypto";import*as r from"fs";import*as i from"path";import*as m from"os";class d{keyPath;pinsPath;key=null;warnedUnpinned=new Set;constructor(e=i.join(m.homedir(),".wyrm")){this.keyPath=i.join(e,"mcp-integrity.key"),this.pinsPath=i.join(e,"mcp-integrity.json")}loadKey(){if(this.key)return this.key;try{this.key=r.readFileSync(this.keyPath)}catch{r.mkdirSync(i.dirname(this.keyPath),{recursive:!0}),this.key=n.randomBytes(32),r.writeFileSync(this.keyPath,this.key,{mode:384})}return this.key}readPins(){try{return JSON.parse(r.readFileSync(this.pinsPath,"utf-8"))}catch{return{}}}writePins(e){r.mkdirSync(i.dirname(this.pinsPath),{recursive:!0}),r.writeFileSync(this.pinsPath,JSON.stringify(e,null,2),{mode:384})}mac(e){const t=JSON.stringify([e.server_name,e.command,e.args??null,e.env??null]);return n.createHmac("sha256",this.loadKey()).update(t).digest("hex")}pin(e){const t=this.readPins();t[e.server_name]=this.mac(e),this.writePins(t)}unpin(e){const t=this.readPins();e in t&&(delete t[e],this.writePins(t))}verify(e){const s=this.readPins()[e.server_name];if(s===void 0){this.warnedUnpinned.has(e.server_name)||(this.warnedUnpinned.add(e.server_name),process.stderr.write(`wyrm: MCP server "${e.server_name}" predates integrity pinning; pinning its current config now (trust-on-first-use)
2
+ `)),this.pin(e);return}const h=this.mac(e);if(!n.timingSafeEqual(Buffer.from(s,"hex"),Buffer.from(h,"hex"))){const a=new Error(`MCP server "${e.server_name}" config does not match its integrity pin: its command/args/env changed outside wyrm_mcp_register. Refusing to spawn. If this change is intentional, re-register the server with wyrm_mcp_register to re-pin it.`);throw a.code="WYRM_MCP_INTEGRITY",a}}}export{d as McpIntegrity};
@@ -1,10 +1,12 @@
1
- import{emitEvent as G}from"./events.js";import{sanitizeFtsQuery as z,buildFtsMatchQuery as X,redactCredentials as H}from"./security.js";import{getActor as ue}from"./handlers/boundary.js";import{buildPage as me,DEFAULT_PAGE_SIZE as he}from"./keyset.js";import{rerankConfigured as _e,rerankCandidates as pe}from"./rerank.js";import{autoSummaryPenalty as J,recallRecencyWeight as Q,recallRecencyHalfLifeDays as Z,recencyMultiplier as q,extractTemporalWindow as ee,recallTemporalWeight as te,temporalMultiplier as ne,recallUsefulnessWeight as ie,usefulnessMultiplier as re,looksInjectionShaped as Ee,trustMarker as ge}from"./context-ranking.js";import{queryGraphContext as Se,graphMultiplier as Re,recallGraphWeight as ye}from"./graph-recall.js";import{populateEntities as se}from"./entity-populate.js";import{resolvePolicy as Y,mutePredicateSql as ae,truthIsChallenged as we,classifyArtifact as Ae}from"./recall-policy.js";const ce=40,ve=10,Ne=.3,oe="auto_approve",K=new WeakMap;function Ce(M){if(/^(1|true|yes|on)$/i.test(process.env.WYRM_AUTO_APPROVE??""))return!0;const n=K.get(M),e=Date.now();if(n&&e-n.at<5e3)return n.on;let t=!1;try{t=M.prepare("SELECT value FROM wyrm_meta WHERE key = ?").get(oe)?.value==="1"}catch{t=!1}return K.set(M,{at:e,on:t}),t}function We(M,n){M.prepare("INSERT INTO wyrm_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(oe,n?"1":"0"),K.delete(M)}function Fe(M,n){try{return(n==null?M.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE needs_review = 1").get():M.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE needs_review = 1 AND project_id = ?").get(n))?.n??0}catch{return 0}}class $e{db;vectorStore;setVectorStore(n){this.vectorStore=n}getVectorStore(){return this.vectorStore}pendingIndex=new Set;async flushIndexing(){for(;this.pendingIndex.size>0;)await Promise.allSettled([...this.pendingIndex])}constructor(n){this.db=n}indexArtifact(n){if(!this.vectorStore)return;const e=`${n.problem}${n.validated_fix?" "+n.validated_fix:""}`.slice(0,2e3),t=this.vectorStore.addVector(e,"artifact",n.id,n.project_id).catch(()=>{});this.pendingIndex.add(t),t.finally(()=>{this.pendingIndex.delete(t)})}add(n,e){if(typeof e.problem!="string"||!e.problem.trim())throw new Error("memory.add: 'problem' is required (a non-empty string).");const t=e.tags?.length?e.tags.join(","):null,i=ue(),c=e.createdBy??"local",r=e.sourceTrust??(c.startsWith("bridge:")?"operator":c.startsWith("import:")||(t??"").includes("imported_from:")?"imported":"agent");let s=e.needsReview??0,a=null;if(s===0&&r==="agent"&&i.agent_id&&(process.env.WYRM_PROBATION??"")==="1"){const S=Number(process.env.WYRM_PROBATION_HOURS),N=Number.isFinite(S)&&S>=1?S:24,d=this.db.prepare("SELECT MIN(created_at) AS f FROM memory_artifacts WHERE agent_id = ?").get(i.agent_id),m=d.f?new Date(d.f.replace(" ","T")+"Z").getTime():NaN;(!Number.isFinite(m)||Date.now()-m<N*36e5)&&(s=1,a="probation")}const p=r==="operator"||r==="agent";r==="untrusted"&&(s=1),s===1&&p&&Ce(this.db)&&(s=0,a=null);const f=a?t?`${t},${a}`:a:t,A=H(e.problem),_=e.constraints?H(e.constraints):null,o=e.validatedFix?H(e.validatedFix):null,g=e.whyItWorked?H(e.whyItWorked):null,v=this.db.prepare(`
1
+ import{emitEvent as ne}from"./events.js";import{sanitizeFtsQuery as re,buildFtsMatchQuery as ie,redactCredentials as P}from"./security.js";import{getActor as Se}from"./handlers/boundary.js";import{buildPage as Re,DEFAULT_PAGE_SIZE as ye}from"./keyset.js";import{rerankConfigured as Ae,rerankCandidates as Ce}from"./rerank.js";import{autoSummaryPenalty as U,recallRecencyWeight as se,recallRecencyHalfLifeDays as ae,recencyMultiplier as ce,extractTemporalWindow as oe,recallTemporalWeight as de,temporalMultiplier as le,recallUsefulnessWeight as ue,usefulnessMultiplier as fe,recallConfidenceWeight as G,confidenceMultiplier as z,looksInjectionShaped as Ne,trustMarker as be}from"./context-ranking.js";import{queryGraphContext as De,graphMultiplier as ke,recallGraphWeight as Me}from"./graph-recall.js";import{populateEntities as me}from"./entity-populate.js";import{artifactVectorText as Te}from"./index-health.js";import{resolvePolicy as X,mutePredicateSql as he,truthIsChallenged as Le,classifyArtifact as Ie}from"./recall-policy.js";import{recordGovernanceEvent as J,governanceActor as _e}from"./governance.js";import{thirdPartyProvenance as Oe}from"./lane-provenance.js";import{sampleAutoApprovedWrite as We,markSampleRejected as xe}from"./review-sample.js";const pe=40;function Q(v){return`${v.source_trust??""}
2
+ ${v.problem.trim()}
3
+ ${(v.validated_fix??"").trim()}`}function Ee(v){const t=new Set;return v.filter(e=>{const n=Q(e.artifact);return t.has(n)?!1:(t.add(n),!0)})}const Fe=10,$e=.3,Z="auto_approve",q=new WeakMap;function ge(v){if(/^(1|true|yes|on)$/i.test(process.env.WYRM_AUTO_APPROVE??""))return!0;const t=q.get(v),e=Date.now();if(t&&e-t.at<5e3)return t.on;let n=!1;try{n=v.prepare("SELECT value FROM wyrm_meta WHERE key = ?").get(Z)?.value==="1"}catch{n=!1}return q.set(v,{at:e,on:n}),n}function Ze(v,t){v.transaction(()=>{const e=v.prepare("SELECT value FROM wyrm_meta WHERE key = ?").get(Z)?.value==="1";v.prepare("INSERT INTO wyrm_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(Z,t?"1":"0"),J(v,"auto_approve.set",{on:t,previous:e})})(),q.delete(v)}function qe(v,t){try{return(t==null?v.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE needs_review = 1").get():v.prepare("SELECT COUNT(*) AS n FROM memory_artifacts WHERE needs_review = 1 AND project_id = ?").get(t))?.n??0}catch{return 0}}class et{db;vectorStore;setVectorStore(t){this.vectorStore=t}getVectorStore(){return this.vectorStore}pendingIndex=new Set;async flushIndexing(){for(;this.pendingIndex.size>0;)await Promise.allSettled([...this.pendingIndex])}constructor(t){this.db=t}indexArtifact(t){if(!this.vectorStore)return;const e=Te(t),n=this.vectorStore.addVector(e,"artifact",t.id,t.project_id).catch(()=>{});this.pendingIndex.add(n),n.finally(()=>{this.pendingIndex.delete(n)})}add(t,e){if(typeof e.problem!="string"||!e.problem.trim())throw new Error("memory.add: 'problem' is required (a non-empty string).");const n=e.tags?.length?e.tags.join(","):null,r=Se(),i=e.createdBy??"local",s=i.startsWith("import:")||(n??"").includes("imported_from:"),c=i.startsWith("bridge:")||s?null:Oe(i,n,e.problem),o=e.sourceTrust??(i.startsWith("bridge:")?"operator":s||c?"imported":"agent"),h=!e.sourceTrust&&c!==null;let l=e.needsReview??0,g=null;if(l===0&&(o==="agent"||h)&&r.agent_id&&r.source!=="writer"&&(process.env.WYRM_PROBATION??"")==="1"){const A=Number(process.env.WYRM_PROBATION_HOURS),k=Number.isFinite(A)&&A>=1?A:24,C=this.db.prepare("SELECT MIN(created_at) AS f FROM memory_artifacts WHERE agent_id = ?").get(r.agent_id),I=C.f?new Date(C.f.replace(" ","T")+"Z").getTime():NaN;(!Number.isFinite(I)||Date.now()-I<k*36e5)&&(l=1,g="probation")}const N=o==="operator"||o==="agent"||h;o==="untrusted"&&(l=1);let a=!1;l===1&&N&&ge(this.db)&&(l=0,g=null,a=!0);const w=g?n?`${n},${g}`:g:n,y=P(e.problem),b=e.constraints?P(e.constraints):null,R=e.validatedFix?P(e.validatedFix):null,D=e.whyItWorked?P(e.whyItWorked):null,u=this.db.prepare(`
2
4
  INSERT INTO memory_artifacts
3
5
  (project_id, kind, problem, constraints, validated_fix, why_it_worked,
4
6
  outcome, source_session_id, tags, confidence, needs_review, created_by, agent_id, run_id, source_trust)
5
7
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
6
- `).run(n,e.kind,A.trim(),_?.trim()??null,o?.trim()??null,g?.trim()??null,e.outcome??"neutral",e.sourceSessionId??null,f,e.confidence??1,s,c,i.agent_id,i.run_id,r),h=this.get(v.lastInsertRowid);if(!s){G(this.db,{projectId:n,kind:"capture",refTable:"memory_artifacts",refId:h.id,isShared:!!h.is_shared}),this.indexArtifact(h);try{const S=`${h.problem}${h.validated_fix?`
7
- `+h.validated_fix:""}`;se(this.db,n,S,`mem:${h.id}`)}catch{}}return h}get(n){return this.db.prepare("SELECT * FROM memory_artifacts WHERE id = ?").get(n)??null}update(n,e){return this.db.prepare(`
8
+ `).run(t,e.kind,y.trim(),b?.trim()??null,R?.trim()??null,D?.trim()??null,e.outcome??"neutral",e.sourceSessionId??null,w,e.confidence??1,l,i,r.agent_id,r.run_id,o),f=this.get(u.lastInsertRowid);if(!l){ne(this.db,{projectId:t,kind:"capture",refTable:"memory_artifacts",refId:f.id,isShared:!!f.is_shared}),this.indexArtifact(f);try{const A=`${f.problem}${f.validated_fix?`
9
+ `+f.validated_fix:""}`;me(this.db,t,A,`mem:${f.id}`)}catch{}(a||o==="imported"&&ge(this.db))&&We(this.db,f)}return f}get(t){return this.db.prepare("SELECT * FROM memory_artifacts WHERE id = ?").get(t)??null}update(t,e){return this.db.prepare(`
8
10
  UPDATE memory_artifacts SET
9
11
  confidence = COALESCE(?, confidence),
10
12
  validated_fix = COALESCE(?, validated_fix),
@@ -13,85 +15,85 @@ import{emitEvent as G}from"./events.js";import{sanitizeFtsQuery as z,buildFtsMat
13
15
  needs_review = COALESCE(?, needs_review),
14
16
  updated_at = datetime('now')
15
17
  WHERE id = ?
16
- `).run(e.confidence??null,e.validated_fix!=null?H(e.validated_fix):null,e.why_it_worked!=null?H(e.why_it_worked):null,e.last_validated_at??null,e.needs_review??null,n),this.get(n)}approve(n){const e=this.get(n);if(!e)return null;if(e.needs_review===0)return e;this.db.prepare("UPDATE memory_artifacts SET needs_review = 0, updated_at = datetime('now') WHERE id = ?").run(n);const t=this.get(n);G(this.db,{projectId:t.project_id,kind:"capture",refTable:"memory_artifacts",refId:t.id,isShared:!!t.is_shared}),this.indexArtifact(t);try{const i=`${t.problem}${t.validated_fix?`
17
- `+t.validated_fix:""}`;se(this.db,t.project_id,i,`mem:${t.id}`)}catch{}return t}markSuperseded(n,e){this.db.prepare("UPDATE memory_artifacts SET supersedes_id = ?, updated_at = datetime('now') WHERE id = ?").run(e,n)}recordFeedback(n,e){const t=e?"reuse_success_count":"reuse_failure_count";this.db.prepare(`
18
+ `).run(e.confidence??null,e.validated_fix!=null?P(e.validated_fix):null,e.why_it_worked!=null?P(e.why_it_worked):null,e.last_validated_at??null,e.needs_review??null,t),this.get(t)}approve(t,e={}){const n=this.get(t);if(!n)return null;if(n.needs_review===0)return n;const r=e.reviewer??_e();this.db.transaction(()=>{this.db.prepare("UPDATE memory_artifacts SET needs_review = 0, reviewed_by = ?, reviewed_at = datetime('now'), updated_at = datetime('now') WHERE id = ?").run(r,t),J(this.db,"review.approve",{artifact_id:t,lane:n.source_trust,kind:n.kind},{projectId:n.project_id,actor:r})})();const i=this.get(t);ne(this.db,{projectId:i.project_id,kind:"capture",refTable:"memory_artifacts",refId:i.id,isShared:!!i.is_shared}),this.indexArtifact(i);try{const s=`${i.problem}${i.validated_fix?`
19
+ `+i.validated_fix:""}`;me(this.db,i.project_id,s,`mem:${i.id}`)}catch{}return i}reject(t,e={}){const n=this.get(t);if(!n)return null;const r=e.reviewer??_e();return this.db.transaction(()=>{this.db.prepare("DELETE FROM memory_artifacts WHERE id = ?").run(t),xe(this.db,t,r),J(this.db,"review.reject",{artifact_id:t,lane:n.source_trust,kind:n.kind,queued:n.needs_review===1},{projectId:n.project_id,actor:r})})(),n}markSuperseded(t,e){this.db.prepare("UPDATE memory_artifacts SET supersedes_id = ?, updated_at = datetime('now') WHERE id = ?").run(e,t)}recordFeedback(t,e){const n=e?"reuse_success_count":"reuse_failure_count";this.db.prepare(`
18
20
  UPDATE memory_artifacts SET
19
21
  reuse_count = reuse_count + 1,
20
- ${t} = ${t} + 1,
22
+ ${n} = ${n} + 1,
21
23
  confidence = CASE
22
24
  WHEN ? THEN MIN(1.0, confidence + 0.05)
23
25
  ELSE MAX(0.0, confidence - 0.1)
24
26
  END,
25
27
  updated_at = datetime('now')
26
28
  WHERE id = ?
27
- `).run(e?1:0,n)}recall(n,e,t={}){const i=t.limit??10,c=t.minConfidence??0,r=Y(this.db,t.runId??null),s=ae(r),a=this.searchByFts(n,e,ce,t.kind,c,s),p=this.searchByTags(n,e,ce,t.kind,c,s),f=new Set,A=[];a.forEach((o,g)=>{f.add(o.id),A.push({artifact:o,inFts:!0,inTag:!1,ftsRank:g})});for(const o of p)if(!f.has(o.id))f.add(o.id),A.push({artifact:o,inFts:!1,inTag:!0});else{const g=A.find(v=>v.artifact.id===o.id);g&&(g.inTag=!0)}return A.filter(({artifact:o})=>o.confidence>=c).map(({artifact:o,inFts:g,inTag:v,ftsRank:h})=>{let S;if(g){const m=1-(h??0)/(a.length+1);S=(v?.7:.55)+.45*m}else S=.4;S*=o.confidence,o.outcome==="positive"&&(S*=1.1);const N=(Date.now()-new Date(o.last_validated_at).getTime())/(1e3*60*60*24),d=Math.max(.5,1-N/180);return S*=d,{artifact:o,relevance_score:Math.min(1,S),match_type:g&&v?"both":g?"fts":"tag"}}).sort((o,g)=>g.relevance_score-o.relevance_score).slice(0,i)}async recallHybrid(n,e,t={}){const i=t.limit??10,c=t.minConfidence??0,r=Y(this.db,t.runId??null),s=ae(r),a=t.rerank===!0&&_e(),p=Math.min(Math.max(i*2,20),50),f=a?p:i;if(!this.vectorStore)return this.recall(n,e,t);const A=Math.max(50,f*5),_=Date.now(),o=this.searchByFts(n,e,A,t.kind,c,s),g=Date.now()-_,v=Date.now();let h=[];try{h=(await this.vectorStore.search(e,A,n,["artifact"])).map(w=>({id:w.content_id,s:w.similarity}))}catch{}const S=Date.now()-v;if(h.length===0)return this.recall(n,e,t);const N=Date.now(),d=60,m=Number(process.env.WYRM_RERANK_ALPHA),k=Number.isFinite(m)?Math.max(0,Math.min(1,m)):.7,C=new Map;if(process.env.WYRM_RERANK_FUSION==="rrf")o.forEach((u,w)=>C.set(u.id,(C.get(u.id)??0)+1/(d+w+1))),h.forEach((u,w)=>C.set(u.id,(C.get(u.id)??0)+1/(d+w+1)));else{const u=o.length+1;o.forEach((x,fe)=>C.set(x.id,(C.get(x.id)??0)+(1-k)*(1-fe/u)));const w=h.map(x=>x.s),R=Math.min(...w),U=Math.max(...w),F=U-R;h.forEach(x=>C.set(x.id,(C.get(x.id)??0)+k*(F>1e-9?(x.s-R)/F:1)))}const D=new Set(o.map(u=>u.id)),I=new Set(h.map(u=>u.id)),T=new Map(o.map(u=>[u.id,u])),$=[...C.entries()].sort((u,w)=>w[1]-u[1]),l=Q(),E=Z(),y=te(),L=y>0?ee(e):null,O=ie(),b=ye(),P=b>0?Se(this.db,n,e):null,j=new Date,de=Math.min($.length,Math.max(f*4,50)),B=[];for(const[u,w]of $.slice(0,de)){const R=T.get(u)??this.get(u)??void 0;if(!R||R.confidence<c||R.needs_review===1||R.supersedes_id!=null||t.kind&&R.kind!==t.kind||r.mode==="clean"&&Ae(R)==="prescription"||r.mutedIds.includes(R.id))continue;const U=R.updated_at??R.created_at;let F=w*q(U,l,E,j);L&&(F*=ne(R.created_at,L,y,j)),F*=re(R.reuse_count,R.reuse_success_count,O),P&&(F*=Re(`${R.problem} ${R.validated_fix??""}`,P,b)),B.push({id:u,s:F,art:R})}B.sort((u,w)=>w.s-u.s);const le=B[0]?.s??1,W=[];for(const{id:u,s:w,art:R}of B){if(W.length>=f)break;const U=D.has(u)&&I.has(u)?"hybrid":I.has(u)?"vector":"fts";W.push({artifact:R,relevance_score:Math.min(1,w/le),match_type:U})}const V=Date.now()-N;if(a&&W.length>0){const u=Date.now(),w=await this.rerankResults(e,W);return t.onStats?.({ftsMs:g,vectorMs:S,fusionMs:V,rerankMs:Date.now()-u,candidates:W.length}),w.slice(0,i)}return t.onStats?.({ftsMs:g,vectorMs:S,fusionMs:V,candidates:W.length}),W}async rerankResults(n,e){const t=e.map(a=>({id:a.artifact.id,text:`${a.artifact.problem}${a.artifact.validated_fix?" "+a.artifact.validated_fix:""}`.slice(0,2e3)})),i=await pe(n,t);if(!i)return e;const c=new Map(e.map(a=>[a.artifact.id,a])),r=[],s=i.length;return i.forEach((a,p)=>{const f=c.get(a.id);f&&r.push({...f,relevance_score:s>0?(s-p)/s:f.relevance_score})}),r}async recallHybridGlobal(n,e={}){const t=e.limit??10,i=e.minConfidence??0,c=Math.max(50,t*5),r=this.searchByFtsGlobal(n,c,e.kind,i),s=()=>r.slice(0,t).map((l,E)=>({artifact:l,relevance_score:1-E/(r.length+1),match_type:"fts"}));if(!this.vectorStore)return s();let a=[];try{a=(await this.vectorStore.search(n,c,void 0,["artifact"])).map(E=>({id:E.content_id,s:E.similarity}))}catch{}if(a.length===0)return s();const p=60,f=Number(process.env.WYRM_RERANK_ALPHA),A=Number.isFinite(f)?Math.max(0,Math.min(1,f)):.7,_=new Map;if(process.env.WYRM_RERANK_FUSION==="rrf")r.forEach((l,E)=>_.set(l.id,(_.get(l.id)??0)+1/(p+E+1))),a.forEach((l,E)=>_.set(l.id,(_.get(l.id)??0)+1/(p+E+1)));else{const l=r.length+1;r.forEach((b,P)=>_.set(b.id,(_.get(b.id)??0)+(1-A)*(1-P/l)));const E=a.map(b=>b.s),y=Math.min(...E),L=Math.max(...E),O=L-y;a.forEach(b=>_.set(b.id,(_.get(b.id)??0)+A*(O>1e-9?(b.s-y)/O:1)))}const o=new Set(r.map(l=>l.id)),g=new Set(a.map(l=>l.id)),v=new Map(r.map(l=>[l.id,l])),h=[..._.entries()].sort((l,E)=>E[1]-l[1]),S=Q(),N=Z(),d=te(),m=d>0?ee(n):null,k=ie(),C=new Date,D=Math.min(h.length,Math.max(t*4,50)),I=[];for(const[l,E]of h.slice(0,D)){const y=v.get(l)??this.get(l)??void 0;if(!y||y.confidence<i||y.needs_review===1||y.supersedes_id!=null||e.kind&&y.kind!==e.kind)continue;const L=y.updated_at??y.created_at;let O=E*q(L,S,N,C);m&&(O*=ne(y.created_at,m,d,C)),O*=re(y.reuse_count,y.reuse_success_count,k),I.push({id:l,s:O,art:y})}I.sort((l,E)=>E.s-l.s);const T=I[0]?.s??1,$=[];for(const{id:l,s:E,art:y}of I){if($.length>=t)break;const L=o.has(l)&&g.has(l)?"hybrid":g.has(l)?"vector":"fts";$.push({artifact:y,relevance_score:Math.min(1,E/T),match_type:L})}return $}searchByFtsGlobal(n,e,t,i=0){if(!this.db)return[];let c="";try{const a=z(n);c=a?X(a):""}catch{return[]}if(!c)return[];const r=t?"AND a.kind = ?":"",s=[c,i];t&&s.push(t),s.push(e);try{return this.db.prepare(`
29
+ `).run(e?1:0,t)}recall(t,e,n={}){const r=n.limit??10,i=n.minConfidence??0,s=X(this.db,n.runId??null),c=he(s),o=this.searchByFts(t,e,pe,n.kind,i,c),h=this.searchByTags(t,e,pe,n.kind,i,c),l=new Set,g=[];o.forEach((a,w)=>{l.add(a.id),g.push({artifact:a,inFts:!0,inTag:!1,ftsRank:w})});for(const a of h)if(!l.has(a.id))l.add(a.id),g.push({artifact:a,inFts:!1,inTag:!0});else{const w=g.find(y=>y.artifact.id===a.id);w&&(w.inTag=!0)}const N=g.filter(({artifact:a})=>a.confidence>=i).map(({artifact:a,inFts:w,inTag:y,ftsRank:b})=>{let R;if(w){const f=1-(b??0)/(o.length+1);R=(y?.7:.55)+.45*f}else R=.4;R*=a.confidence,a.outcome==="positive"&&(R*=1.1);const D=(Date.now()-new Date(a.last_validated_at).getTime())/(1e3*60*60*24),u=Math.max(.5,1-D/180);return R*=u,R*=1-U(a.problem),{artifact:a,relevance_score:Math.min(1,R),match_type:w&&y?"both":w?"fts":"tag"}});return Ee(N.sort((a,w)=>w.relevance_score-a.relevance_score)).slice(0,r)}async recallHybrid(t,e,n={}){const r=n.limit??10,i=n.minConfidence??0,s=X(this.db,n.runId??null),c=he(s),o=n.rerank===!0&&Ae(),h=Math.min(Math.max(r*2,20),50),l=o?h:r;if(!this.vectorStore)return this.recall(t,e,n);const g=Math.max(50,l*5),N=Date.now(),a=this.searchByFts(t,e,g,n.kind,i,c),w=Date.now()-N,y=Date.now();let b=[];try{b=(await this.vectorStore.search(e,g,t,["artifact"])).map(S=>({id:S.content_id,s:S.similarity}))}catch{}const R=Date.now()-y;if(b.length===0)return this.recall(t,e,n);const D=Date.now(),u=60,f=Number(process.env.WYRM_RERANK_ALPHA),A=Number.isFinite(f)?Math.max(0,Math.min(1,f)):.7,k=new Map;if(process.env.WYRM_RERANK_FUSION==="rrf")a.forEach((m,S)=>k.set(m.id,(k.get(m.id)??0)+1/(u+S+1))),b.forEach((m,S)=>k.set(m.id,(k.get(m.id)??0)+1/(u+S+1)));else{const m=a.length+1;a.forEach((x,we)=>k.set(x.id,(k.get(x.id)??0)+(1-A)*(1-we/m)));const S=b.map(x=>x.s),p=Math.min(...S),H=Math.max(...S),L=H-p;b.forEach(x=>k.set(x.id,(k.get(x.id)??0)+A*(L>1e-9?(x.s-p)/L:1)))}const C=new Set(a.map(m=>m.id)),I=new Set(b.map(m=>m.id)),O=new Map(a.map(m=>[m.id,m])),F=[...k.entries()].sort((m,S)=>S[1]-m[1]),Y=se(),B=ae(),j=de(),d=j>0?oe(e):null,_=ue(),E=G(),W=Me(),M=W>0?De(this.db,t,e):null,T=new Date,V=Math.min(F.length,Math.max(l*4,50)),K=[];for(const[m,S]of F.slice(0,V)){const p=O.get(m)??this.get(m)??void 0;if(!p||p.confidence<i||p.needs_review===1||p.supersedes_id!=null||n.kind&&p.kind!==n.kind||s.mode==="clean"&&Ie(p)==="prescription"||s.mutedIds.includes(p.id))continue;const H=p.updated_at??p.created_at;let L=S*ce(H,Y,B,T);d&&(L*=le(p.created_at,d,j,T)),L*=fe(p.reuse_count,p.reuse_success_count,_),M&&(L*=ke(`${p.problem} ${p.validated_fix??""}`,M,W)),L*=1-U(p.problem),L*=z(p.confidence,E),K.push({id:m,s:L,art:p})}K.sort((m,S)=>S.s-m.s);const ve=K[0]?.s??1,$=[],ee=new Set;for(const{id:m,s:S,art:p}of K){if($.length>=l)break;const H=Q(p);if(ee.has(H))continue;ee.add(H);const L=C.has(m)&&I.has(m)?"hybrid":I.has(m)?"vector":"fts";$.push({artifact:p,relevance_score:Math.min(1,S/ve),match_type:L})}const te=Date.now()-D;if(o&&$.length>0){const m=Date.now(),S=await this.rerankResults(e,$);return n.onStats?.({ftsMs:w,vectorMs:R,fusionMs:te,rerankMs:Date.now()-m,candidates:$.length}),S.slice(0,r)}return n.onStats?.({ftsMs:w,vectorMs:R,fusionMs:te,candidates:$.length}),$}async rerankResults(t,e){const n=e.map(o=>({id:o.artifact.id,text:`${o.artifact.problem}${o.artifact.validated_fix?" "+o.artifact.validated_fix:""}`.slice(0,2e3)})),r=await Ce(t,n);if(!r)return e;const i=new Map(e.map(o=>[o.artifact.id,o])),s=[],c=r.length;return r.forEach((o,h)=>{const l=i.get(o.id);l&&s.push({...l,relevance_score:c>0?(c-h)/c:l.relevance_score})}),s}async recallHybridGlobal(t,e={}){const n=e.limit??10,r=e.minConfidence??0,i=Math.max(50,n*5),s=this.searchByFtsGlobal(t,i,e.kind,r),c=G(),o=()=>Ee(s.map((d,_)=>({artifact:d,relevance_score:(1-_/(s.length+1))*(1-U(d.problem))*z(d.confidence,c),match_type:"fts"})).sort((d,_)=>_.relevance_score-d.relevance_score)).slice(0,n);if(!this.vectorStore)return o();let h=[];try{h=(await this.vectorStore.search(t,i,void 0,["artifact"])).map(_=>({id:_.content_id,s:_.similarity}))}catch{}if(h.length===0)return o();const l=60,g=Number(process.env.WYRM_RERANK_ALPHA),N=Number.isFinite(g)?Math.max(0,Math.min(1,g)):.7,a=new Map;if(process.env.WYRM_RERANK_FUSION==="rrf")s.forEach((d,_)=>a.set(d.id,(a.get(d.id)??0)+1/(l+_+1))),h.forEach((d,_)=>a.set(d.id,(a.get(d.id)??0)+1/(l+_+1)));else{const d=s.length+1;s.forEach((T,V)=>a.set(T.id,(a.get(T.id)??0)+(1-N)*(1-V/d)));const _=h.map(T=>T.s),E=Math.min(..._),W=Math.max(..._),M=W-E;h.forEach(T=>a.set(T.id,(a.get(T.id)??0)+N*(M>1e-9?(T.s-E)/M:1)))}const w=new Set(s.map(d=>d.id)),y=new Set(h.map(d=>d.id)),b=new Map(s.map(d=>[d.id,d])),R=[...a.entries()].sort((d,_)=>_[1]-d[1]),D=se(),u=ae(),f=de(),A=f>0?oe(t):null,k=ue(),C=G(),I=new Date,O=Math.min(R.length,Math.max(n*4,50)),F=[];for(const[d,_]of R.slice(0,O)){const E=b.get(d)??this.get(d)??void 0;if(!E||E.confidence<r||E.needs_review===1||E.supersedes_id!=null||e.kind&&E.kind!==e.kind)continue;const W=E.updated_at??E.created_at;let M=_*ce(W,D,u,I);A&&(M*=le(E.created_at,A,f,I)),M*=fe(E.reuse_count,E.reuse_success_count,k),M*=1-U(E.problem),M*=z(E.confidence,C),F.push({id:d,s:M,art:E})}F.sort((d,_)=>_.s-d.s);const Y=F[0]?.s??1,B=[],j=new Set;for(const{id:d,s:_,art:E}of F){if(B.length>=n)break;const W=Q(E);if(j.has(W))continue;j.add(W);const M=w.has(d)&&y.has(d)?"hybrid":y.has(d)?"vector":"fts";B.push({artifact:E,relevance_score:Math.min(1,_/Y),match_type:M})}return B}searchByFtsGlobal(t,e,n,r=0){if(!this.db)return[];let i="";try{const o=re(t);i=o?ie(o):""}catch{return[]}if(!i)return[];const s=n?"AND a.kind = ?":"",c=[i,r];n&&c.push(n),c.push(e);try{return this.db.prepare(`
28
30
  SELECT a.* FROM memory_artifacts a
29
31
  JOIN memory_artifacts_fts ON a.id = memory_artifacts_fts.rowid
30
32
  WHERE memory_artifacts_fts MATCH ?
31
33
  AND a.confidence >= ?
32
34
  AND a.supersedes_id IS NULL
33
35
  AND a.needs_review = 0
34
- ${r}
36
+ ${s}
35
37
  ORDER BY rank, a.confidence DESC
36
38
  LIMIT ?
37
- `).all(...s)}catch{return[]}}searchByFts(n,e,t,i,c=0,r="1=1"){let s="";try{const f=z(e);s=f?X(f):""}catch{return this.listRecent(n,t,i,r)}if(!s)return this.listRecent(n,t,i,r);const a=i?"AND a.kind = ?":"",p=[s,n,c];i&&p.push(i),p.push(t);try{return this.db.prepare(`
38
- SELECT a.* FROM memory_artifacts a
39
- JOIN memory_artifacts_fts ON a.id = memory_artifacts_fts.rowid
39
+ `).all(...c)}catch{return[]}}searchByFts(t,e,n,r,i=0,s="1=1"){let c="";try{const l=re(e);c=l?ie(l):""}catch{return this.listRecent(t,n,r,s)}if(!c)return this.listRecent(t,n,r,s);const o=r?"AND a.kind = ?":"",h=[c,t,i];r&&h.push(r),h.push(n);try{return this.db.prepare(`
40
+ SELECT a.* FROM memory_artifacts_fts
41
+ CROSS JOIN memory_artifacts a ON a.id = memory_artifacts_fts.rowid
40
42
  WHERE memory_artifacts_fts MATCH ?
41
43
  AND a.project_id = ?
42
44
  AND a.confidence >= ?
43
45
  AND a.supersedes_id IS NULL
44
46
  AND a.needs_review = 0
45
- AND (${r})
46
- ${a}
47
- ORDER BY rank, a.confidence DESC
47
+ AND (${s})
48
+ ${o}
49
+ ORDER BY rank, a.confidence DESC, a.id
48
50
  LIMIT ?
49
- `).all(...p)}catch{return this.listRecent(n,t,i,r)}}searchByTags(n,e,t,i,c=0,r="1=1"){const s=e.toLowerCase().split(/\s+/).filter(o=>o.length>2);if(!s.length)return[];const a=o=>o.replace(/[%_\\]/g,"\\$&"),p=s.map(()=>"LOWER(tags) LIKE ? ESCAPE '\\'").join(" OR "),f=s.map(o=>`%${a(o)}%`),A=i?"AND kind = ?":"",_=[n,c,...f];return i&&_.push(i),_.push(t),this.db.prepare(`
51
+ `).all(...h)}catch{return this.listRecent(t,n,r,s)}}searchByTags(t,e,n,r,i=0,s="1=1"){const c=e.toLowerCase().split(/\s+/).filter(a=>a.length>2);if(!c.length)return[];const o=a=>a.replace(/[%_\\]/g,"\\$&"),h=c.map(()=>"LOWER(tags) LIKE ? ESCAPE '\\'").join(" OR "),l=c.map(a=>`%${o(a)}%`),g=r?"AND kind = ?":"",N=[t,i,...l];return r&&N.push(r),N.push(n),this.db.prepare(`
50
52
  SELECT * FROM memory_artifacts
51
53
  WHERE project_id = ? AND confidence >= ? AND supersedes_id IS NULL
52
54
  AND needs_review = 0
53
- AND (${p})
54
- AND (${r})
55
- ${A}
55
+ AND (${h})
56
+ AND (${s})
57
+ ${g}
56
58
  ORDER BY confidence DESC, reuse_success_count DESC
57
59
  LIMIT ?
58
- `).all(..._)}listRecent(n,e=20,t,i="1=1"){const c=t?"AND kind = ?":"",r=[n];return t&&r.push(t),r.push(e),this.db.prepare(`
60
+ `).all(...N)}listRecent(t,e=20,n,r="1=1"){const i=n?"AND kind = ?":"",s=[t];return n&&s.push(n),s.push(e),this.db.prepare(`
59
61
  SELECT * FROM memory_artifacts
60
62
  WHERE project_id = ? AND supersedes_id IS NULL AND needs_review = 0
61
- AND (${i})
62
- ${c}
63
+ AND (${r})
64
+ ${i}
63
65
  ORDER BY confidence DESC, created_at DESC
64
66
  LIMIT ?
65
- `).all(...r)}buildContextBrief(n,e,t={}){const i=t.kinds??["pattern","heuristic","reasoning_trace","lesson","anti_pattern"],c=t.maxItems??ve,r=t.minConfidence??Ne,s=t.runId??null,a=this.recall(n,e,{limit:c*2,minConfidence:r,runId:s});a.sort((d,m)=>(J(d.artifact.problem)>0?1:0)-(J(m.artifact.problem)>0?1:0));const p=[],A=a.filter(d=>{const m=d.artifact.source_trust;return m==="untrusted"||m==="imported"&&Ee(`${d.artifact.problem} ${d.artifact.validated_fix??""}`)?(p.push(d.artifact.id),!1):!0}).filter(d=>i.includes(d.artifact.kind)).slice(0,c),_=new Map;for(const d of A){const m=_.get(d.artifact.kind)??[];m.push(d),_.set(d.artifact.kind,m)}const o={pattern:"\u2705 Proven Patterns",heuristic:"\u{1F4A1} Heuristics",reasoning_trace:"\u{1F9E0} Past Reasoning",lesson:"\u{1F4DA} Lessons Learned",anti_pattern:"\u26A0\uFE0F Anti-Patterns to Avoid"},g=["pattern","heuristic","reasoning_trace","lesson","anti_pattern"],v=[],h=[];let S=0;for(const d of g){if(!i.includes(d))continue;const m=_.get(d)??[];if(!m.length)continue;const k=[];for(const C of m){if(S>=c)break;const D=C.artifact;let T=`${ge(D.source_trust)}**Problem:** ${D.problem}`;D.constraints&&(T+=`
66
- _Constraints:_ ${D.constraints}`),D.validated_fix&&(T+=`
67
- _Solution:_ ${D.validated_fix}`),D.why_it_worked&&(T+=`
68
- _Why it worked:_ ${D.why_it_worked}`),D.outcome==="negative"&&(T+=`
69
- _Note: This approach failed \u2014 avoid it_`),k.push(T),h.push(D.id),S++}k.length&&v.push({heading:o[d],items:k,source:d})}let N="";if(v.length>0){N+=`---
67
+ `).all(...s)}buildContextBrief(t,e,n={}){const r=n.kinds??["pattern","heuristic","reasoning_trace","lesson","anti_pattern"],i=n.maxItems??Fe,s=n.minConfidence??$e,c=n.runId??null,o=this.recall(t,e,{limit:i*2,minConfidence:s,runId:c});o.sort((u,f)=>(U(u.artifact.problem)>0?1:0)-(U(f.artifact.problem)>0?1:0));const h=[],g=o.filter(u=>{const f=u.artifact.source_trust;return f==="untrusted"||f==="imported"&&Ne(`${u.artifact.problem} ${u.artifact.validated_fix??""}`)?(h.push(u.artifact.id),!1):!0}).filter(u=>r.includes(u.artifact.kind)).slice(0,i),N=new Map;for(const u of g){const f=N.get(u.artifact.kind)??[];f.push(u),N.set(u.artifact.kind,f)}const a={pattern:"\u2705 Proven Patterns",heuristic:"\u{1F4A1} Heuristics",reasoning_trace:"\u{1F9E0} Past Reasoning",lesson:"\u{1F4DA} Lessons Learned",anti_pattern:"\u26A0\uFE0F Anti-Patterns to Avoid"},w=["pattern","heuristic","reasoning_trace","lesson","anti_pattern"],y=[],b=[];let R=0;for(const u of w){if(!r.includes(u))continue;const f=N.get(u)??[];if(!f.length)continue;const A=[];for(const k of f){if(R>=i)break;const C=k.artifact;let O=`${be(C.source_trust)}**Problem:** ${C.problem}`;C.constraints&&(O+=`
68
+ _Constraints:_ ${C.constraints}`),C.validated_fix&&(O+=`
69
+ _Solution:_ ${C.validated_fix}`),C.why_it_worked&&(O+=`
70
+ _Why it worked:_ ${C.why_it_worked}`),C.outcome==="negative"&&(O+=`
71
+ _Note: This approach failed; avoid it_`),A.push(O),b.push(C.id),R++}A.length&&y.push({heading:a[u],items:A,source:u})}let D="";if(y.length>0){D+=`---
70
72
  ## \u{F115D} Memory Brief
71
73
  _Relevant past knowledge from Wyrm:_
72
74
 
73
- `;for(const d of v){N+=`### ${d.heading}
74
- `;for(const m of d.items)N+=`- ${m}
75
- `;N+=`
76
- `}N+=`---
77
- `}if(t.groundTruths){const d=Y(this.db,s),m=t.groundTruths.filter(k=>!we(d,k.id));return{sections:v,text:N,sourceIds:h,groundTruths:m}}return{sections:v,text:N,sourceIds:h}}getStats(n){const e=this.db.prepare("SELECT COUNT(*) as n FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NULL").get(n).n,t=this.db.prepare("SELECT COUNT(*) as n FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NOT NULL").get(n).n,i=this.db.prepare("SELECT AVG(confidence) as v FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NULL").get(n).v??0,c=this.db.prepare("SELECT kind, COUNT(*) as cnt FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NULL GROUP BY kind").all(n),r={};for(const s of c)r[s.kind]=s.cnt;return{total:e,byKind:r,avgConfidence:Math.round(i*100)/100,supersededCount:t}}listAll(n,e={}){const t=e.kind?"AND kind = ?":"",i=e.includeSuperseded?"":"AND supersedes_id IS NULL",c=[n];return e.kind&&c.push(e.kind),c.push(e.limit??50),this.db.prepare(`
75
+ `;for(const u of y){D+=`### ${u.heading}
76
+ `;for(const f of u.items)D+=`- ${f}
77
+ `;D+=`
78
+ `}D+=`---
79
+ `}if(n.groundTruths){const u=X(this.db,c),f=n.groundTruths.filter(A=>!Le(u,A.id));return{sections:y,text:D,sourceIds:b,groundTruths:f}}return{sections:y,text:D,sourceIds:b}}getStats(t){const e=this.db.prepare("SELECT COUNT(*) as n FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NULL").get(t).n,n=this.db.prepare("SELECT COUNT(*) as n FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NOT NULL").get(t).n,r=this.db.prepare("SELECT AVG(confidence) as v FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NULL").get(t).v??0,i=this.db.prepare("SELECT kind, COUNT(*) as cnt FROM memory_artifacts WHERE project_id = ? AND supersedes_id IS NULL GROUP BY kind").all(t),s={};for(const c of i)s[c.kind]=c.cnt;return{total:e,byKind:s,avgConfidence:Math.round(r*100)/100,supersededCount:n}}listAll(t,e={}){const n=e.kind?"AND kind = ?":"",r=e.includeSuperseded?"":"AND supersedes_id IS NULL",i=[t];return e.kind&&i.push(e.kind),i.push(e.limit??50),this.db.prepare(`
78
80
  SELECT * FROM memory_artifacts
79
- WHERE project_id = ? ${t} ${i}
81
+ WHERE project_id = ? ${n} ${r}
80
82
  ORDER BY confidence DESC, created_at DESC
81
83
  LIMIT ?
82
- `).all(...c)}listPage(n,e={pageSize:he}){const t=e.kind?"AND kind = ?":"",i=e.includeSuperseded?"":"AND supersedes_id IS NULL",c="AND needs_review = 0",r=[n];e.kind&&r.push(e.kind);let s="";if(e.after){const f=Number(e.after.sortKey);Number.isFinite(f)&&(s="AND (confidence < ? OR (confidence = ? AND id < ?))",r.push(f,f,e.after.id))}const a=e.pageSize+1;r.push(a);const p=this.db.prepare(`
84
+ `).all(...i)}listPage(t,e={pageSize:ye}){const n=e.kind?"AND kind = ?":"",r=e.includeSuperseded?"":"AND supersedes_id IS NULL",i="AND needs_review = 0",s=[t];e.kind&&s.push(e.kind);let c="";if(e.after){const l=Number(e.after.sortKey);Number.isFinite(l)&&(c="AND (confidence < ? OR (confidence = ? AND id < ?))",s.push(l,l,e.after.id))}const o=e.pageSize+1;s.push(o);const h=this.db.prepare(`
83
85
  SELECT * FROM memory_artifacts
84
- WHERE project_id = ? ${t} ${i} ${c} ${s}
86
+ WHERE project_id = ? ${n} ${r} ${i} ${c}
85
87
  ORDER BY confidence DESC, id DESC
86
88
  LIMIT ?
87
- `).all(...r);return me(p,e.pageSize,f=>({sortKey:String(f.confidence),id:f.id}))}pruneStale(n={}){const e=n.minConfidence??.3,t=n.olderThanDays??90,i=n.dryRun??!0,c=n.projectId!=null,r=[e,`-${t} days`];c&&r.push(n.projectId);const s=this.db.prepare(`
89
+ `).all(...s);return Re(h,e.pageSize,l=>({sortKey:String(l.confidence),id:l.id}))}pruneStale(t={}){const e=t.minConfidence??.3,n=t.olderThanDays??90,r=t.dryRun??!0,i=t.projectId!=null,s=[e,`-${n} days`];i&&s.push(t.projectId);const c=this.db.prepare(`
88
90
  SELECT id, kind, problem, confidence, last_accessed_at
89
91
  FROM memory_artifacts
90
92
  WHERE confidence < ?
91
93
  AND (last_accessed_at IS NULL OR last_accessed_at < datetime('now', ?))
92
94
  AND needs_review = 0
93
95
  AND supersedes_id IS NULL
94
- ${c?"AND project_id = ?":""}
96
+ ${i?"AND project_id = ?":""}
95
97
  ORDER BY confidence ASC
96
98
  LIMIT 500
97
- `).all(...r);return i||s.length===0?{candidates:s,deleted:0,dryRun:i}:{candidates:s,deleted:this.deleteArtifacts(s.map(a=>a.id)),dryRun:i}}deleteArtifacts(n){if(n.length===0)return 0;const e=n.map(()=>"?").join(",");return this.db.prepare(`DELETE FROM memory_artifacts WHERE id IN (${e}) AND needs_review = 0`).run(...n).changes}}export{$e as MemoryArtifacts,Ce as isAutoApproveOn,Fe as queuedForReview,We as setAutoApprove};
99
+ `).all(...s);return r||c.length===0?{candidates:c,deleted:0,dryRun:r}:{candidates:c,deleted:this.deleteArtifacts(c.map(o=>o.id)),dryRun:r}}deleteArtifacts(t){if(t.length===0)return 0;const e=t.map(()=>"?").join(",");return this.db.prepare(`DELETE FROM memory_artifacts WHERE id IN (${e}) AND needs_review = 0`).run(...t).changes}}export{et as MemoryArtifacts,ge as isAutoApproveOn,qe as queuedForReview,Ze as setAutoApprove};