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,4 +1,4 @@
1
- import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";const r=[{version:1,description:"Baseline schema \u2014 projects, sessions, quests, context, data_lake, skills, FTS5",up:e=>{e.exec(`
1
+ import{canonicalizeCommand as u,commandHead as A}from"./failure-patterns.js";import{recordGovernanceEvent as O}from"./governance.js";const I=[{version:1,description:"Baseline schema: projects, sessions, quests, context, data_lake, skills, FTS5",up:e=>{e.exec(`
2
2
  -- Core tables
3
3
  CREATE TABLE IF NOT EXISTS projects (
4
4
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -210,7 +210,7 @@ import{canonicalizeCommand as d,commandHead as N}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 i=e.prepare(`PRAGMA table_info(${t})`).all().map(T=>T.name);i.includes("visibility")||e.exec(`ALTER TABLE ${t} ADD COLUMN visibility TEXT DEFAULT 'private'`),i.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(`
213
+ `)}},{version:3,description:"Add visibility and created_by columns for future multi-user support",up:e=>{const t=["sessions","quests","context","data_lake"];for(const s of t){const i=e.prepare(`PRAGMA table_info(${s})`).all().map(o=>o.name);i.includes("visibility")||e.exec(`ALTER TABLE ${s} ADD COLUMN visibility TEXT DEFAULT 'private'`),i.includes("created_by")||e.exec(`ALTER TABLE ${s} ADD COLUMN created_by TEXT DEFAULT 'local'`)}}},{version:4,description:"Knowledge graph: 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,
@@ -285,7 +285,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
285
285
  INSERT INTO entities_fts(rowid, name, type, metadata)
286
286
  VALUES (new.id, new.name, new.type, new.metadata);
287
287
  END;
288
- `)}},{version:5,description:"Memory artifacts \u2014 distilled knowledge for intelligence amplification",up:e=>{e.exec(`
288
+ `)}},{version:5,description:"Memory artifacts: distilled knowledge for intelligence amplification",up:e=>{e.exec(`
289
289
  -- Memory artifacts: distilled problem-solution records, lessons, patterns, anti-patterns.
290
290
  -- Used by wyrm_context_build to assemble task-specific memory briefs for AI models.
291
291
  CREATE TABLE IF NOT EXISTS memory_artifacts (
@@ -340,7 +340,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
340
340
  INSERT INTO memory_artifacts_fts(rowid, problem, constraints, validated_fix, why_it_worked, tags)
341
341
  VALUES (new.id, new.problem, new.constraints, new.validated_fix, new.why_it_worked, new.tags);
342
342
  END;
343
- `)}},{version:6,description:"Intelligence amplification \u2014 ground truths, reasoning scaffolds, distillation review queue",up:e=>{e.exec(`
343
+ `)}},{version:6,description:"Intelligence amplification: ground truths, reasoning scaffolds, distillation review queue",up:e=>{e.exec(`
344
344
  -- Ground truths: authoritative, versioned project facts.
345
345
  -- Use is_current=1 for the live value. Superseded rows kept for history.
346
346
  CREATE TABLE IF NOT EXISTS ground_truths (
@@ -410,12 +410,12 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
410
410
  -- needs_review=1 means it was auto-created by wyrm_distill and awaits approval
411
411
  ALTER TABLE memory_artifacts ADD COLUMN needs_review INTEGER DEFAULT 0;
412
412
  CREATE INDEX IF NOT EXISTS idx_artifacts_review ON memory_artifacts(project_id, needs_review);
413
- `)}},{version:7,description:"Ground truth TTL \u2014 temporal decay support for staleness detection",up:e=>{e.exec(`
413
+ `)}},{version:7,description:"Ground truth TTL: temporal decay support for staleness detection",up:e=>{e.exec(`
414
414
  ALTER TABLE ground_truths ADD COLUMN ttl_days INTEGER CHECK(ttl_days IS NULL OR ttl_days > 0);
415
- `)}},{version:8,description:"Memory artifact decay \u2014 access tracking for auto-prune",up:e=>{e.exec(`
415
+ `)}},{version:8,description:"Memory artifact decay: access tracking for auto-prune",up:e=>{e.exec(`
416
416
  ALTER TABLE memory_artifacts ADD COLUMN last_accessed_at TEXT DEFAULT (datetime('now'));
417
417
  ALTER TABLE memory_artifacts ADD COLUMN access_count INTEGER NOT NULL DEFAULT 0;
418
- `)}},{version:9,description:"v3.9.0 \u2014 failure patterns, agent presence, causality, symbol index, tool analytics",up:e=>{e.exec(`
418
+ `)}},{version:9,description:"v3.9.0: failure patterns, agent presence, causality, symbol index, tool analytics",up:e=>{e.exec(`
419
419
  -- ============================================================
420
420
  -- Tier 1.1: Counter-pattern detection
421
421
  -- Records edits/commands that failed so the predictive push can
@@ -562,7 +562,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
562
562
  CREATE INDEX IF NOT EXISTS idx_toolcall_name ON tool_call_log(tool_name, called_at DESC);
563
563
  CREATE INDEX IF NOT EXISTS idx_toolcall_project ON tool_call_log(project_id, called_at DESC);
564
564
  CREATE INDEX IF NOT EXISTS idx_toolcall_success ON tool_call_log(success, called_at DESC);
565
- `)}},{version:10,description:"v4.0.0 \u2014 federated sync, hash-chained audit, sub-agent embedding (wyrm_ask), session-rehydration helpers",up:e=>{e.exec(`
565
+ `)}},{version:10,description:"v4.0.0: federated sync, hash-chained audit, sub-agent embedding (wyrm_ask), session-rehydration helpers",up:e=>{e.exec(`
566
566
  -- ============================================================
567
567
  -- Tier 2.8: Federated team Wyrm \u2014 selective sharing
568
568
  -- A single "is_shared" flag on the major user-facing tables.
@@ -659,7 +659,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
659
659
  );
660
660
  CREATE INDEX IF NOT EXISTS idx_llm_project ON llm_query_log(project_id, asked_at DESC);
661
661
  CREATE INDEX IF NOT EXISTS idx_llm_model ON llm_query_log(model, asked_at DESC);
662
- `)}},{version:11,description:"v5.0.0 \u2014 goals, agent loop, outbound MCP clients, action log",up:e=>{e.exec(`
662
+ `)}},{version:11,description:"v5.0.0: goals, agent loop, outbound MCP clients, action log",up:e=>{e.exec(`
663
663
  -- ============================================================
664
664
  -- v5.0.0: Goals \u2014 persistent objectives Wyrm pursues
665
665
  -- ============================================================
@@ -770,7 +770,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
770
770
  ON session_seen_artifacts(session_id, shown_at DESC);
771
771
  CREATE INDEX IF NOT EXISTS idx_session_seen_prune
772
772
  ON session_seen_artifacts(shown_at);
773
- `)}},{version:13,description:"design_tokens + design_references \u2014 creative workflow tables (5.9.0)",up:e=>{e.exec(`
773
+ `)}},{version:13,description:"design_tokens + design_references: creative workflow tables (5.9.0)",up:e=>{e.exec(`
774
774
  CREATE TABLE IF NOT EXISTS design_tokens (
775
775
  id INTEGER PRIMARY KEY AUTOINCREMENT,
776
776
  project_id INTEGER NOT NULL,
@@ -821,7 +821,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
821
821
  INSERT INTO design_references_fts(rowid, title, notes, tags)
822
822
  VALUES (new.id, new.title, new.notes, new.tags);
823
823
  END;
824
- `)}},{version:14,description:"token_savings_log + cross_project_visibility \u2014 Wyrm 6.0 substrate (spec 018)",up:e=>{e.exec(`
824
+ `)}},{version:14,description:"token_savings_log + cross_project_visibility: Wyrm 6.0 substrate (spec 018)",up:e=>{e.exec(`
825
825
  -- Token-savings telemetry: every Wyrm tool that has a counterfactual
826
826
  -- logs an estimate so the statusline and digest can show real ROI.
827
827
  CREATE TABLE IF NOT EXISTS token_savings_log (
@@ -844,10 +844,10 @@ import{canonicalizeCommand as d,commandHead as N}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(i=>i.name==="cross_project_visibility"))continue;e.exec(`
848
- ALTER TABLE ${t} ADD COLUMN cross_project_visibility TEXT NOT NULL DEFAULT 'within'
847
+ `);const t=["ground_truths","memory_artifacts","quests","decision_edges","design_references","design_tokens"];for(const s of t)try{if(e.prepare(`PRAGMA table_info(${s})`).all().some(i=>i.name==="cross_project_visibility"))continue;e.exec(`
848
+ ALTER TABLE ${s} ADD COLUMN cross_project_visibility TEXT NOT NULL DEFAULT 'within'
849
849
  CHECK (cross_project_visibility IN ('within', 'org', 'public'));
850
- `)}catch{}}},{version:15,description:"Live Memory v6.4 \u2014 append-only events log + wyrm_meta (device identity)",up:e=>{e.exec(`
850
+ `)}catch{}}},{version:15,description:"Live Memory v6.4: append-only events log + wyrm_meta (device identity)",up:e=>{e.exec(`
851
851
  -- Node-local KV (stable device id for cross-device event identity, etc.)
852
852
  CREATE TABLE IF NOT EXISTS wyrm_meta (
853
853
  key TEXT PRIMARY KEY,
@@ -905,13 +905,13 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
905
905
  tokenize='porter unicode61'
906
906
  );
907
907
  INSERT INTO skills_fts(skills_fts) VALUES('rebuild');
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(`
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(s=>s.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=E=>s.some(i=>i.name===E);t("tier")||e.exec(`
911
+ `)}catch{}}},{version:18,description:"GOD-SKILL SPEC v2: skill tier/governs/composes + spec-kit registry (specs table)",up:e=>{const t=e.prepare("PRAGMA table_info(skills)").all(),s=E=>t.some(i=>i.name===E);s("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
- `),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(`
914
+ `),s("governs")||e.exec("ALTER TABLE skills ADD COLUMN governs TEXT NOT NULL DEFAULT '[]';"),s("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(`
915
915
  CREATE TABLE IF NOT EXISTS specs (
916
916
  id INTEGER PRIMARY KEY AUTOINCREMENT,
917
917
  project_id INTEGER NOT NULL,
@@ -929,8 +929,8 @@ import{canonicalizeCommand as d,commandHead as N}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(n=>n.name===o)}catch{return!1}},E=a=>{try{return e.prepare(a).all().map(o=>o.pid)}catch{return[]}},i=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 E(`SELECT DISTINCT project_id AS pid FROM ${a}
933
- WHERE cross_project_visibility IN ('org', 'public') AND project_id IS NOT NULL`))i.add(o);const T=e.prepare("UPDATE projects SET sync_policy = 'cloud' WHERE id = ? AND sync_policy = 'private'");for(const a of i)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(`
932
+ `);const s=(a,r)=>{try{return e.prepare(`PRAGMA table_info(${a})`).all().some(c=>c.name===r)}catch{return!1}},E=a=>{try{return e.prepare(a).all().map(r=>r.pid)}catch{return[]}},i=new Set;for(const a of["ground_truths","memory_artifacts","quests","design_tokens","design_references"])if(!(!s(a,"cross_project_visibility")||!s(a,"project_id")))for(const r of E(`SELECT DISTINCT project_id AS pid FROM ${a}
933
+ WHERE cross_project_visibility IN ('org', 'public') AND project_id IS NOT NULL`))i.add(r);const o=e.prepare("UPDATE projects SET sync_policy = 'cloud' WHERE id = ? AND sync_policy = 'private'");for(const a of i)o.run(a)}},{version:20,description:"v7 F2 (T008), 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,14 +955,14 @@ import{canonicalizeCommand as d,commandHead as N}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,i)=>{try{return e.prepare(`PRAGMA table_info(${E})`).all().some(T=>T.name===i)}catch{return!1}},t=["memory_artifacts","failure_patterns","decision_edges","ground_truths","quests","sessions","quest_claims","events","audit_log"];for(const E of t)s(E,"agent_id")||e.exec(`ALTER TABLE ${E} ADD COLUMN agent_id TEXT;`),s(E,"run_id")||e.exec(`ALTER TABLE ${E} ADD COLUMN run_id TEXT;`);e.exec(`
958
+ `);const t=(E,i)=>{try{return e.prepare(`PRAGMA table_info(${E})`).all().some(o=>o.name===i)}catch{return!1}},s=["memory_artifacts","failure_patterns","decision_edges","ground_truths","quests","sessions","quest_claims","events","audit_log"];for(const E of s)t(E,"agent_id")||e.exec(`ALTER TABLE ${E} ADD COLUMN agent_id TEXT;`),t(E,"run_id")||e.exec(`ALTER TABLE ${E} 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;
962
- `),s("failure_patterns","quarantine_scope")||(e.exec(`
962
+ `),t("failure_patterns","quarantine_scope")||(e.exec(`
963
963
  ALTER TABLE failure_patterns ADD COLUMN quarantine_scope TEXT NOT NULL DEFAULT 'project'
964
964
  CHECK (quarantine_scope IN ('run', 'project', 'global'));
965
- `),e.exec("UPDATE failure_patterns SET quarantine_scope = 'global' WHERE project_id IS NULL;")),e.exec("CREATE INDEX IF NOT EXISTS idx_failure_quarantine ON failure_patterns(quarantine_scope, resolved);")}},{version:21,description:"v7 F2 (T015) \u2014 failure_confirmations: distinct-agent confirmation ledger behind run-quarantine auto-promotion",up:e=>{e.exec(`
965
+ `),e.exec("UPDATE failure_patterns SET quarantine_scope = 'global' WHERE project_id IS NULL;")),e.exec("CREATE INDEX IF NOT EXISTS idx_failure_quarantine ON failure_patterns(quarantine_scope, resolved);")}},{version:21,description:"v7 F2 (T015), failure_confirmations: distinct-agent confirmation ledger behind run-quarantine auto-promotion",up:e=>{e.exec(`
966
966
  CREATE TABLE IF NOT EXISTS failure_confirmations (
967
967
  failure_id INTEGER NOT NULL,
968
968
  agent_id TEXT NOT NULL,
@@ -971,7 +971,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
971
971
  PRIMARY KEY (failure_id, agent_id),
972
972
  FOREIGN KEY (failure_id) REFERENCES failure_patterns(id) ON DELETE CASCADE
973
973
  );
974
- `)}},{version:22,description:"v7 F2 (T017) \u2014 failure_blocks: prevented-repeat ledger behind wyrm_stats view=failures",up:e=>{e.exec(`
974
+ `)}},{version:22,description:"v7 F2 (T017), failure_blocks: prevented-repeat ledger behind wyrm_stats view=failures",up:e=>{e.exec(`
975
975
  CREATE TABLE IF NOT EXISTS failure_blocks (
976
976
  id INTEGER PRIMARY KEY AUTOINCREMENT,
977
977
  failure_id INTEGER NOT NULL,
@@ -981,7 +981,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
981
981
  blocked_at TEXT DEFAULT (datetime('now')),
982
982
  FOREIGN KEY (failure_id) REFERENCES failure_patterns(id) ON DELETE CASCADE
983
983
  );
984
- `),e.exec("CREATE INDEX IF NOT EXISTS idx_failure_blocks_run ON failure_blocks(run_id) WHERE run_id IS NOT NULL;"),e.exec("CREATE INDEX IF NOT EXISTS idx_failure_blocks_failure ON failure_blocks(failure_id);")}},{version:23,description:"v7 F3 (T028) \u2014 run_briefs: byte-stable fleet session_prime brief cache, one row per (run_id, role)",up:e=>{e.exec(`
984
+ `),e.exec("CREATE INDEX IF NOT EXISTS idx_failure_blocks_run ON failure_blocks(run_id) WHERE run_id IS NOT NULL;"),e.exec("CREATE INDEX IF NOT EXISTS idx_failure_blocks_failure ON failure_blocks(failure_id);")}},{version:23,description:"v7 F3 (T028), run_briefs: byte-stable fleet session_prime brief cache, one row per (run_id, role)",up:e=>{e.exec(`
985
985
  CREATE TABLE IF NOT EXISTS run_briefs (
986
986
  run_id TEXT NOT NULL,
987
987
  role TEXT NOT NULL DEFAULT '',
@@ -990,17 +990,17 @@ import{canonicalizeCommand as d,commandHead as N}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,E)=>{try{return e.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===E)}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(`
993
+ `)}},{version:24,description:"v7 F3 (T029), claims/presence hardening: role on quest_claims, run_id/role on agent_presence, run-scoped partial indexes",up:e=>{const t=(s,E)=>{try{return e.prepare(`PRAGMA table_info(${s})`).all().some(i=>i.name===E)}catch{return!1}};t("quest_claims","role")||e.exec("ALTER TABLE quest_claims ADD COLUMN role TEXT;"),t("agent_presence","run_id")||e.exec("ALTER TABLE agent_presence ADD COLUMN run_id TEXT;"),t("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,E)=>{try{return e.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===E)}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(`
996
+ `)}},{version:25,description:"Skills portability: store SKILL.md content (+ sha/ts) in the registry and make skills cloud-sync-eligible behind the per-row visibility gate",up:e=>{const t=(s,E)=>{try{return e.prepare(`PRAGMA table_info(${s})`).all().some(i=>i.name===E)}catch{return!1}};t("skills","content")||e.exec("ALTER TABLE skills ADD COLUMN content TEXT;"),t("skills","content_sha256")||e.exec("ALTER TABLE skills ADD COLUMN content_sha256 TEXT;"),t("skills","content_updated_at")||e.exec("ALTER TABLE skills ADD COLUMN content_updated_at TEXT;"),t("skills","cross_project_visibility")||e.exec("ALTER TABLE skills ADD COLUMN cross_project_visibility TEXT NOT NULL DEFAULT 'within';"),t("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: 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,
1000
1000
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
1001
1001
  PRIMARY KEY (project_id, sig)
1002
1002
  );
1003
- `)}},{version:27,description:'Continuity Layer \u2014 the rolling per-project living thread ("where we left off / what we were talking and thinking about"), captured continuously and restored on every new session, for any agent/system that primes Wyrm',up:e=>{e.exec(`
1003
+ `)}},{version:27,description:'Continuity Layer: the rolling per-project living thread ("where we left off / what we were talking and thinking about"), captured continuously and restored on every new session, for any agent/system that primes Wyrm',up:e=>{e.exec(`
1004
1004
  CREATE TABLE IF NOT EXISTS project_continuity (
1005
1005
  project_id INTEGER PRIMARY KEY,
1006
1006
  thread TEXT NOT NULL DEFAULT '',
@@ -1009,7 +1009,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
1009
1009
  turn_count INTEGER NOT NULL DEFAULT 0,
1010
1010
  FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
1011
1011
  );
1012
- `)}},{version:28,description:"Routing memory \u2014 record which model/tool succeeded (or failed) per task_type so the dragon-cli multi-model router can do negative learning over past routing outcomes",up:e=>{e.exec(`
1012
+ `)}},{version:28,description:"Routing memory: record which model/tool succeeded (or failed) per task_type so the dragon-cli multi-model router can do negative learning over past routing outcomes",up:e=>{e.exec(`
1013
1013
  CREATE TABLE IF NOT EXISTS routing_memory (
1014
1014
  id INTEGER PRIMARY KEY AUTOINCREMENT,
1015
1015
  project_id INTEGER NOT NULL DEFAULT -1,
@@ -1024,7 +1024,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
1024
1024
  ON routing_memory(project_id, task_type, ts DESC);
1025
1025
  CREATE INDEX IF NOT EXISTS idx_routing_memory_task
1026
1026
  ON routing_memory(task_type, ts DESC);
1027
- `)}},{version:29,description:"Failure Firewall v2 \u2014 content tier: a normalized signature of the CODE that broke, so the opt-in PreToolUse guard can block an edit that re-introduces a recorded failure pattern (not just an identical target path)",up:e=>{e.prepare("PRAGMA table_info(failure_patterns)").all().some(t=>t.name==="content_sig")||e.exec("ALTER TABLE failure_patterns ADD COLUMN content_sig TEXT;")}},{version:30,description:"Failure Firewall staleness oracle \u2014 failure_anchors: the source files a failure was recorded against (project-relative path + normalized-content sha + stat fast-path fields), so the firewall can tell a still-true block from one whose source has since changed and downgrade it to advisory",up:e=>{e.exec(`
1027
+ `)}},{version:29,description:"Failure Firewall v2, content tier: a normalized signature of the CODE that broke, so the opt-in PreToolUse guard can block an edit that re-introduces a recorded failure pattern (not just an identical target path)",up:e=>{e.prepare("PRAGMA table_info(failure_patterns)").all().some(s=>s.name==="content_sig")||e.exec("ALTER TABLE failure_patterns ADD COLUMN content_sig TEXT;")}},{version:30,description:"Failure Firewall staleness oracle, failure_anchors: the source files a failure was recorded against (project-relative path + normalized-content sha + stat fast-path fields), so the firewall can tell a still-true block from one whose source has since changed and downgrade it to advisory",up:e=>{e.exec(`
1028
1028
  CREATE TABLE IF NOT EXISTS failure_anchors (
1029
1029
  id INTEGER PRIMARY KEY AUTOINCREMENT,
1030
1030
  failure_id INTEGER NOT NULL REFERENCES failure_patterns(id) ON DELETE CASCADE,
@@ -1036,7 +1036,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
1036
1036
  );
1037
1037
  CREATE UNIQUE INDEX IF NOT EXISTS ux_failure_anchors_failure_rel
1038
1038
  ON failure_anchors(failure_id, rel_path);
1039
- `)}},{version:31,description:"FABLE skill tier \u2014 widen skills.tier to (atomic, mega, god, fable): model-vintage master-craft skills authored by Fable-class models during real builds, every law validated by shipping the artifact in the authoring session (fable-skill-spec)",up:e=>{const s=e.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'skills'").get();!s?.sql||s.sql.includes("'fable'")||e.exec(`
1039
+ `)}},{version:31,description:"FABLE skill tier. Widen skills.tier to (atomic, mega, god, fable): model-vintage master-craft skills authored by Fable-class models during real builds, every law validated by shipping the artifact in the authoring session (fable-skill-spec)",up:e=>{const t=e.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'skills'").get();!t?.sql||t.sql.includes("'fable'")||e.exec(`
1040
1040
  CREATE TABLE skills_v31 (
1041
1041
  id INTEGER PRIMARY KEY AUTOINCREMENT,
1042
1042
  name TEXT UNIQUE NOT NULL,
@@ -1098,7 +1098,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
1098
1098
  INSERT INTO skills_fts(rowid, name, description, tags) VALUES (new.id, new.name, new.description, new.tags);
1099
1099
  END;
1100
1100
  INSERT INTO skills_fts(skills_fts) VALUES('rebuild');
1101
- `)}},{version:32,description:'v8 F1 \u2014 write_ledger: the receipt spine (v8-A1). Every memory write records what happened (stored/queued/merged/aliased/dropped + why) so `wyrm digest --writes` can answer "what did Wyrm learn today, and what did it refuse?" offline. Local-only (never replicated), pruned by maintenance.',up:e=>{e.exec(`
1101
+ `)}},{version:32,description:'v8 F1, write_ledger: the receipt spine (v8-A1). Every memory write records what happened (stored/queued/merged/aliased/dropped + why) so `wyrm digest --writes` can answer "what did Wyrm learn today, and what did it refuse?" offline. Local-only (never replicated), pruned by maintenance.',up:e=>{e.exec(`
1102
1102
  CREATE TABLE IF NOT EXISTS write_ledger (
1103
1103
  id INTEGER PRIMARY KEY AUTOINCREMENT,
1104
1104
  ts TEXT DEFAULT (datetime('now')),
@@ -1113,14 +1113,14 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
1113
1113
  );
1114
1114
  CREATE INDEX IF NOT EXISTS idx_write_ledger_ts ON write_ledger(ts);
1115
1115
  CREATE INDEX IF NOT EXISTS idx_write_ledger_tool ON write_ledger(tool, ts);
1116
- `)}},{version:33,description:"v8 F5 \u2014 source_trust provenance lane on memory artifacts (v8-A5): operator > agent > imported > untrusted. Conservative backfill: bridge:* (the operator's own daily record) \u2192 operator; import:*/imported_from tags \u2192 imported; everything else stays agent. Unknown NEVER backfills to operator.",up:e=>{e.prepare("PRAGMA table_info(memory_artifacts)").all().some(t=>t.name==="source_trust")||e.exec(`
1116
+ `)}},{version:33,description:"v8 F5, source_trust provenance lane on memory artifacts (v8-A5): operator > agent > imported > untrusted. Conservative backfill: bridge:* (the operator's own daily record) \u2192 operator; import:*/imported_from tags \u2192 imported; everything else stays agent. Unknown NEVER backfills to operator.",up:e=>{e.prepare("PRAGMA table_info(memory_artifacts)").all().some(s=>s.name==="source_trust")||e.exec(`
1117
1117
  ALTER TABLE memory_artifacts ADD COLUMN source_trust TEXT NOT NULL DEFAULT 'agent'
1118
1118
  CHECK (source_trust IN ('operator', 'agent', 'imported', 'untrusted'));
1119
1119
  `),e.exec(`
1120
1120
  UPDATE memory_artifacts SET source_trust = 'operator' WHERE created_by LIKE 'bridge:%';
1121
1121
  UPDATE memory_artifacts SET source_trust = 'imported'
1122
1122
  WHERE created_by LIKE 'import:%' OR tags LIKE '%imported_from:%';
1123
- `)}},{version:34,description:"Sovereign-sync GA correctness: AFTER DELETE triggers on the 6 synced tables auto-record sync_tombstones, so a row deleted on one device propagates as a tombstone and does NOT resurrect from another device on the next pull. Exhaustive by construction \u2014 no delete callsite can bypass a trigger (recordTombstone had zero callers, the GA blocker found 2026-07-17).",up:e=>{e.exec(`
1123
+ `)}},{version:34,description:"Sovereign-sync GA correctness: AFTER DELETE triggers on the 6 synced tables auto-record sync_tombstones, so a row deleted on one device propagates as a tombstone and does NOT resurrect from another device on the next pull. Exhaustive by construction: no delete callsite can bypass a trigger (recordTombstone had zero callers, the GA blocker found 2026-07-17).",up:e=>{e.exec(`
1124
1124
  CREATE TABLE IF NOT EXISTS sync_tombstones (
1125
1125
  id INTEGER PRIMARY KEY AUTOINCREMENT,
1126
1126
  kind TEXT NOT NULL,
@@ -1130,20 +1130,20 @@ import{canonicalizeCommand as d,commandHead as N}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,E]of s)e.exec(`
1134
- CREATE TRIGGER IF NOT EXISTS trg_tombstone_${t} AFTER DELETE ON ${t}
1133
+ `);const t=[["ground_truths","truth"],["memory_artifacts","memory_artifact"],["quests","quest"],["design_tokens","design_token"],["design_references","design_reference"],["skills","skill"]];for(const[s,E]of t)e.exec(`
1134
+ CREATE TRIGGER IF NOT EXISTS trg_tombstone_${s} AFTER DELETE ON ${s}
1135
1135
  BEGIN
1136
1136
  INSERT OR IGNORE INTO sync_tombstones (kind, row_id, deleted_at_ms)
1137
1137
  VALUES ('${E}', 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,E]of s){e.exec(`DROP TRIGGER IF EXISTS trg_tombstone_${t};`);const i=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
- CREATE TRIGGER trg_tombstone_${t} AFTER DELETE ON ${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 t=[["ground_truths","truth"],["memory_artifacts","memory_artifact"],["quests","quest"],["design_tokens","design_token"],["design_references","design_reference"],["skills","skill"]];for(const[s,E]of t){e.exec(`DROP TRIGGER IF EXISTS trg_tombstone_${s};`);const i=s==="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
+ CREATE TRIGGER trg_tombstone_${s} AFTER DELETE ON ${s}
1141
1141
  WHEN ${i}
1142
1142
  BEGIN
1143
1143
  INSERT OR IGNORE INTO sync_tombstones (kind, row_id, deleted_at_ms)
1144
1144
  VALUES ('${E}', 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,E)=>e.prepare(`PRAGMA table_info(${t})`).all().some(i=>i.name===E);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(`
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), the same convention the other synced tables use.`,up:e=>{const t=(s,E)=>e.prepare(`PRAGMA table_info(${s})`).all().some(i=>i.name===E);t("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'))")),t("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: 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')),
@@ -1151,7 +1151,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
1151
1151
  kind TEXT NOT NULL CHECK (kind IN ('health', 'effectiveness', 'retrieval')),
1152
1152
  metrics_json TEXT NOT NULL
1153
1153
  );
1154
- `),e.exec("CREATE INDEX IF NOT EXISTS idx_metrics_kind_time ON metrics_snapshots(kind, captured_at DESC);")}},{version:38,description:`Add threads \u2014 the per-project Working-Thread Layer. One row per project holding the live state of "what we're doing right now": objective, in-progress note, recent decisions, open loops, next step, entities in play, and source refs back to the rows that grounded each field. Foundational table only (Task 1 of the feature) \u2014 reads/writes land in later tasks.`,up:e=>{e.exec(`
1154
+ `),e.exec("CREATE INDEX IF NOT EXISTS idx_metrics_kind_time ON metrics_snapshots(kind, captured_at DESC);")}},{version:38,description:`Add threads: the per-project Working-Thread Layer. One row per project holding the live state of "what we're doing right now": objective, in-progress note, recent decisions, open loops, next step, entities in play, and source refs back to the rows that grounded each field. Foundational table only (Task 1 of the feature); reads/writes land in later tasks.`,up:e=>{e.exec(`
1155
1155
  CREATE TABLE IF NOT EXISTS threads (
1156
1156
  id INTEGER PRIMARY KEY,
1157
1157
  project_id INTEGER NOT NULL UNIQUE,
@@ -1164,10 +1164,10 @@ import{canonicalizeCommand as d,commandHead as N}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(i=>i.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(`
1167
+ `)}},{version:39,description:"Firewall target normalization (quest #1033): 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 t=e.prepare("PRAGMA table_info(failure_patterns)").all().map(i=>i.name);t.includes("canonical_target")||e.exec("ALTER TABLE failure_patterns ADD COLUMN canonical_target TEXT;"),t.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(),E=e.prepare("UPDATE failure_patterns SET canonical_target = ?, command_head = ? WHERE id = ?");for(const i of t)E.run(d(i.target)||null,N(i.target)||null,i.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(`
1170
+ `);const s=e.prepare("SELECT id, target FROM failure_patterns WHERE scope = 'command'").all(),E=e.prepare("UPDATE failure_patterns SET canonical_target = ?, command_head = ? WHERE id = ?");for(const i of s)E.run(u(i.target)||null,A(i.target)||null,i.id)}},{version:40,description:"Negotiated Recall NR-1 (specs/negotiated-recall), 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; 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,7 +1177,7 @@ import{canonicalizeCommand as d,commandHead as N}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(`
1180
+ `)}},{version:41,description:"Grounding enforcement, 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
1181
  CREATE TABLE IF NOT EXISTS served_records (
1182
1182
  session_key TEXT NOT NULL,
1183
1183
  artifact_id INTEGER NOT NULL,
@@ -1185,7 +1185,7 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
1185
1185
  served_at TEXT NOT NULL DEFAULT (datetime('now')),
1186
1186
  PRIMARY KEY (session_key, artifact_id, artifact_kind)
1187
1187
  );
1188
- `)}},{version:42,description:"Token firewall phase 1 \u2014 read_memos: one row per file read in full (path, sha256, a landmark map, counters), so the wyrm-memo PreToolUse hook can recognise a repeat whole-file read of an unchanged file and count or hand back the map instead. Raw file text is never stored.",up:e=>{e.exec(`
1188
+ `)}},{version:42,description:"Token firewall phase 1, read_memos: one row per file read in full (path, sha256, a landmark map, counters), so the wyrm-memo PreToolUse hook can recognise a repeat whole-file read of an unchanged file and count or hand back the map instead. Raw file text is never stored.",up:e=>{e.exec(`
1189
1189
  CREATE TABLE IF NOT EXISTS read_memos (
1190
1190
  path TEXT PRIMARY KEY,
1191
1191
  sha256 TEXT NOT NULL,
@@ -1202,10 +1202,201 @@ import{canonicalizeCommand as d,commandHead as N}from"./failure-patterns.js";con
1202
1202
  tokens_avoided INTEGER NOT NULL DEFAULT 0
1203
1203
  );
1204
1204
  CREATE INDEX IF NOT EXISTS idx_read_memos_last_seen ON read_memos(last_seen);
1205
- `)}}];function l(e){const s=r.reduce((E,i)=>Math.max(E,i.version),0);let t=0;try{t=e.prepare("SELECT COALESCE(MAX(version), 0) AS v FROM schema_versions").get().v}catch{}return{store:t,binary:s,storeIsNewer:t>s}}function _(e){e.exec(`
1205
+ `)}},{version:43,description:"Erasure record, erasure_log: one row per erasure or retention preview (mode, reason, data_lake category, the predicate as a shape, per-table counts, when, and the agent/run that ran it). Erased content, including the matched text of a subject request, is never stored.",up:e=>{e.exec(`
1206
+ CREATE TABLE IF NOT EXISTS erasure_log (
1207
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1208
+ erased_at TEXT NOT NULL DEFAULT (datetime('now')),
1209
+ mode TEXT NOT NULL CHECK (mode IN ('erase', 'preview')),
1210
+ reason TEXT NOT NULL,
1211
+ category TEXT,
1212
+ predicate_json TEXT NOT NULL DEFAULT '{}',
1213
+ counts_json TEXT NOT NULL DEFAULT '{}',
1214
+ total INTEGER NOT NULL DEFAULT 0,
1215
+ actor TEXT,
1216
+ agent_id TEXT,
1217
+ run_id TEXT
1218
+ );
1219
+ CREATE INDEX IF NOT EXISTS idx_erasure_log_at ON erasure_log(erased_at);
1220
+ `)}},{version:44,description:"Knowledge that never goes stale (quest #1152). failure_patterns.downgraded_at: set when an unresolved pattern with no hits for WYRM_FAILURE_QUIET_DAYS (default 60) is downgraded from block to warn, cleared when it re-occurs; failure_pattern_history: one row per downgrade/re-arm, so a pattern never changes enforcement without a record; served_counts: per-record count of connections a record was served to (from served_records), stored for usefulness analysis only and never read by ranking. Backfills served_counts from served_records. Truth TTL defaults and the parked quest status need no schema: quests.status carries no CHECK, so existing parked rows are already valid.",up:e=>{const t=e.prepare("PRAGMA table_info(failure_patterns)").all();t.length>0&&!t.some(E=>E.name==="downgraded_at")&&e.exec("ALTER TABLE failure_patterns ADD COLUMN downgraded_at TEXT"),e.exec(`
1221
+ CREATE TABLE IF NOT EXISTS failure_pattern_history (
1222
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1223
+ failure_id INTEGER NOT NULL,
1224
+ event TEXT NOT NULL CHECK (event IN ('downgraded', 'rearmed')),
1225
+ detail TEXT,
1226
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
1227
+ );
1228
+ CREATE INDEX IF NOT EXISTS idx_failure_history_failure ON failure_pattern_history(failure_id, created_at);
1229
+
1230
+ CREATE TABLE IF NOT EXISTS served_counts (
1231
+ artifact_kind TEXT NOT NULL,
1232
+ artifact_id INTEGER NOT NULL,
1233
+ served_sessions INTEGER NOT NULL DEFAULT 0,
1234
+ first_served_at TEXT NOT NULL DEFAULT (datetime('now')),
1235
+ last_served_at TEXT NOT NULL DEFAULT (datetime('now')),
1236
+ PRIMARY KEY (artifact_kind, artifact_id)
1237
+ );
1238
+ `),e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'served_records'").get()&&e.exec(`
1239
+ INSERT OR IGNORE INTO served_counts (artifact_kind, artifact_id, served_sessions, first_served_at, last_served_at)
1240
+ SELECT artifact_kind, artifact_id, COUNT(DISTINCT session_key), MIN(served_at), MAX(served_at)
1241
+ FROM served_records
1242
+ GROUP BY artifact_kind, artifact_id
1243
+ `)}},{version:45,description:"Index health (quest #1153): vectors becomes a migrated table (the same DDL vectors.ts created lazily) with a (model, content_type, project_id) index, so a scoped vector search is filtered in SQL. Quest vectors that reindex stored under content_type context are relabelled quest wherever no quest row already holds that (id, model). Triggers purge a row's vectors when a memory is deleted or superseded, or a quest, session or data point is deleted.",up:e=>{e.exec(`
1244
+ CREATE TABLE IF NOT EXISTS vectors (
1245
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1246
+ project_id INTEGER,
1247
+ content_type TEXT NOT NULL,
1248
+ content_id INTEGER NOT NULL,
1249
+ content_hash TEXT NOT NULL,
1250
+ embedding BLOB NOT NULL,
1251
+ model TEXT NOT NULL,
1252
+ dimensions INTEGER NOT NULL,
1253
+ created_at TEXT DEFAULT (datetime('now')),
1254
+ UNIQUE(content_type, content_id, model)
1255
+ );
1256
+ CREATE INDEX IF NOT EXISTS idx_vectors_project ON vectors(project_id);
1257
+ CREATE INDEX IF NOT EXISTS idx_vectors_content ON vectors(content_type, content_id);
1258
+ CREATE INDEX IF NOT EXISTS idx_vectors_hash ON vectors(content_hash);
1259
+ CREATE INDEX IF NOT EXISTS idx_vectors_model_type_project ON vectors(model, content_type, project_id);
1260
+ `),e.exec(`
1261
+ UPDATE OR IGNORE vectors SET content_type = 'quest'
1262
+ WHERE content_type = 'context' AND content_id IN (SELECT id FROM quests);
1263
+ `),e.exec(`
1264
+ CREATE TRIGGER IF NOT EXISTS vectors_purge_artifact_delete AFTER DELETE ON memory_artifacts BEGIN
1265
+ DELETE FROM vectors WHERE content_type = 'artifact' AND content_id = OLD.id;
1266
+ END;
1267
+ CREATE TRIGGER IF NOT EXISTS vectors_purge_artifact_supersede AFTER UPDATE OF supersedes_id ON memory_artifacts
1268
+ WHEN NEW.supersedes_id IS NOT NULL BEGIN
1269
+ DELETE FROM vectors WHERE content_type = 'artifact' AND content_id = NEW.id;
1270
+ END;
1271
+ CREATE TRIGGER IF NOT EXISTS vectors_purge_quest_delete AFTER DELETE ON quests BEGIN
1272
+ DELETE FROM vectors WHERE content_type IN ('quest', 'context') AND content_id = OLD.id;
1273
+ END;
1274
+ CREATE TRIGGER IF NOT EXISTS vectors_purge_session_delete AFTER DELETE ON sessions BEGIN
1275
+ DELETE FROM vectors WHERE content_type = 'session' AND content_id = OLD.id;
1276
+ END;
1277
+ CREATE TRIGGER IF NOT EXISTS vectors_purge_note_delete AFTER DELETE ON data_lake BEGIN
1278
+ DELETE FROM vectors WHERE content_type = 'note' AND content_id = OLD.id;
1279
+ END;
1280
+ `)}},{version:46,description:"Fleet integrity (quest #1154): events gain origin_epoch in the dedup key (table rebuilt, cursor sequence preserved) and an (origin_device, origin_seq) index for the persisted counter; sync_cursors holds replication cursors inside the store; sync_conflicts records which side won and where the conflict came from; demoting a synced row to within, or a grove to private, writes a retraction tombstone, and promoting it back clears one.",up:e=>{const t=e.prepare("PRAGMA table_info(events)").all();if(t.length>0&&!t.some(T=>T.name==="origin_epoch")){const T={cursor:"cursor INTEGER PRIMARY KEY AUTOINCREMENT",origin_device:"origin_device TEXT NOT NULL",origin_seq:"origin_seq INTEGER NOT NULL",cloud_cursor:"cloud_cursor INTEGER",project_id:"project_id TEXT NOT NULL",kind:"kind TEXT NOT NULL",ref_table:"ref_table TEXT",ref_id:"ref_id TEXT",actor:"actor TEXT",is_shared:"is_shared INTEGER NOT NULL DEFAULT 0",payload_json:"payload_json TEXT",created_at:"created_at INTEGER NOT NULL",agent_id:"agent_id TEXT",run_id:"run_id TEXT"},d=/^[A-Za-z_][A-Za-z0-9_]*$/,_=t.filter(n=>d.test(n.name)),N=_.map(n=>T[n.name]??`${n.name} ${d.test(n.type)?n.type:""}${n.dflt_value!=null?` DEFAULT ${n.dflt_value}`:""}`);N.push("origin_epoch INTEGER NOT NULL DEFAULT 0","UNIQUE(origin_device, origin_epoch, origin_seq)");const L=_.map(n=>n.name).join(", "),l=e.prepare("SELECT seq FROM sqlite_sequence WHERE name = 'events'").get()?.seq??0,R=e.prepare("SELECT sql FROM sqlite_master WHERE tbl_name = 'events' AND type IN ('index', 'trigger') AND sql IS NOT NULL").all();e.exec(`CREATE TABLE events_v46 (${N.join(", ")})`),e.exec(`INSERT INTO events_v46 (${L}) SELECT ${L} FROM events`),e.exec("DROP TABLE events"),e.exec("ALTER TABLE events_v46 RENAME TO events"),e.prepare("UPDATE sqlite_sequence SET seq = MAX(seq, ?) WHERE name = 'events'").run(l).changes===0&&l>0&&e.prepare("INSERT INTO sqlite_sequence (name, seq) VALUES ('events', ?)").run(l);for(const{sql:n}of R)e.exec(n)}e.exec(`
1281
+ CREATE INDEX IF NOT EXISTS idx_events_project_cursor ON events(project_id, cursor);
1282
+ CREATE INDEX IF NOT EXISTS idx_events_kind ON events(kind, created_at);
1283
+ CREATE INDEX IF NOT EXISTS idx_events_origin_seq ON events(origin_device, origin_seq);
1284
+ `),e.exec(`
1285
+ INSERT OR IGNORE INTO wyrm_meta (key, value)
1286
+ SELECT 'event_seq:' || origin_device, CAST(MAX(origin_seq) AS TEXT) FROM events
1287
+ WHERE origin_device = (SELECT value FROM wyrm_meta WHERE key = 'device_id')
1288
+ GROUP BY origin_device;
1289
+ `),e.exec(`
1290
+ CREATE TABLE IF NOT EXISTS sync_cursors (
1291
+ name TEXT PRIMARY KEY, -- 'cloud' (sovereign sync), 'bridge' (connector push)
1292
+ value_json TEXT NOT NULL,
1293
+ device_epoch INTEGER NOT NULL DEFAULT 0, -- epoch the cursor was written under
1294
+ imported_from TEXT, -- legacy file path, when imported
1295
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
1296
+ );
1297
+ `);const s=new Set(e.prepare("PRAGMA table_info(sync_conflicts)").all().map(T=>T.name));s.has("source")||e.exec("ALTER TABLE sync_conflicts ADD COLUMN source TEXT"),s.has("winner")||e.exec("ALTER TABLE sync_conflicts ADD COLUMN winner TEXT"),s.has("local_payload")||e.exec("ALTER TABLE sync_conflicts ADD COLUMN local_payload TEXT");const E=[["ground_truths","truth"],["memory_artifacts","memory_artifact"],["quests","quest"],["design_tokens","design_token"],["design_references","design_reference"],["skills","skill"]],i="CAST(strftime('%s','now') AS INTEGER) * 1000";for(const[T,d]of E){if(!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(T))continue;const N=T==="skills"?"":"AND (OLD.project_id IS NULL OR (SELECT sync_policy FROM projects WHERE id = OLD.project_id) IN ('cloud','team'))";e.exec(`
1298
+ CREATE TRIGGER IF NOT EXISTS trg_retract_demote_${T} AFTER UPDATE OF cross_project_visibility ON ${T}
1299
+ WHEN OLD.cross_project_visibility IN ('org','public') AND NEW.cross_project_visibility NOT IN ('org','public') ${N}
1300
+ BEGIN
1301
+ INSERT INTO sync_tombstones (kind, row_id, deleted_at_ms) VALUES ('${d}', CAST(OLD.id AS TEXT), ${i})
1302
+ ON CONFLICT(kind, row_id) DO UPDATE SET deleted_at_ms = excluded.deleted_at_ms, pushed_at_ms = NULL;
1303
+ END;
1304
+ CREATE TRIGGER IF NOT EXISTS trg_retract_promote_${T} AFTER UPDATE OF cross_project_visibility ON ${T}
1305
+ WHEN NEW.cross_project_visibility IN ('org','public') AND OLD.cross_project_visibility NOT IN ('org','public')
1306
+ BEGIN
1307
+ DELETE FROM sync_tombstones WHERE kind = '${d}' AND row_id = CAST(NEW.id AS TEXT);
1308
+ END;
1309
+ `)}const o=E.filter(([T])=>T!=="skills"&&e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(T)),a=o.map(([T,d])=>`
1310
+ INSERT INTO sync_tombstones (kind, row_id, deleted_at_ms)
1311
+ SELECT '${d}', CAST(id AS TEXT), ${i} FROM ${T}
1312
+ WHERE project_id = NEW.id AND cross_project_visibility IN ('org','public')
1313
+ ON CONFLICT(kind, row_id) DO UPDATE SET deleted_at_ms = excluded.deleted_at_ms, pushed_at_ms = NULL;`).join(""),r=o.map(([T,d])=>`
1314
+ DELETE FROM sync_tombstones WHERE kind = '${d}' AND row_id IN (SELECT CAST(id AS TEXT) FROM ${T} WHERE project_id = NEW.id);`).join("");e.prepare("PRAGMA table_info(projects)").all().some(T=>T.name==="sync_policy")&&o.length>0&&e.exec(`
1315
+ CREATE TRIGGER IF NOT EXISTS trg_retract_grove_private AFTER UPDATE OF sync_policy ON projects
1316
+ WHEN OLD.sync_policy IN ('cloud','team') AND NEW.sync_policy NOT IN ('cloud','team')
1317
+ BEGIN${a}
1318
+ END;
1319
+ CREATE TRIGGER IF NOT EXISTS trg_retract_grove_shared AFTER UPDATE OF sync_policy ON projects
1320
+ WHEN NEW.sync_policy IN ('cloud','team') AND OLD.sync_policy NOT IN ('cloud','team')
1321
+ BEGIN${r}
1322
+ END;
1323
+ `)}},{version:47,description:"Index health follow-up (quest #1153): indexing_queue becomes a migrated table (the DDL indexer.ts created lazily). When the text a vector was embedded from changes (a memory's problem or validated_fix, a quest's title or description, a session's objectives, completed, notes or summary, a data point's category, key or value), triggers delete that row's vectors under every model and requeue the row, so no vector outlives its text and the replacement is embedded under the active model. An update that leaves those columns unchanged fires nothing.",up:e=>{e.exec(`
1324
+ CREATE TABLE IF NOT EXISTS indexing_queue (
1325
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1326
+ content_type TEXT NOT NULL,
1327
+ content_id INTEGER NOT NULL,
1328
+ project_id INTEGER NOT NULL,
1329
+ status TEXT NOT NULL DEFAULT 'pending',
1330
+ retry_count INTEGER NOT NULL DEFAULT 0,
1331
+ error_message TEXT,
1332
+ created_at TEXT DEFAULT (datetime('now')),
1333
+ processed_at TEXT,
1334
+ UNIQUE(content_type, content_id)
1335
+ );
1336
+ CREATE INDEX IF NOT EXISTS idx_iq_status ON indexing_queue(status);
1337
+ CREATE INDEX IF NOT EXISTS idx_iq_content ON indexing_queue(content_type, content_id);
1338
+ `),e.exec(`
1339
+ CREATE TRIGGER IF NOT EXISTS vectors_restale_artifact AFTER UPDATE OF problem, validated_fix ON memory_artifacts
1340
+ WHEN OLD.problem IS NOT NEW.problem OR OLD.validated_fix IS NOT NEW.validated_fix BEGIN
1341
+ DELETE FROM vectors WHERE content_type = 'artifact' AND content_id = NEW.id;
1342
+ INSERT INTO indexing_queue (content_type, content_id, project_id, status, retry_count)
1343
+ SELECT 'artifact', NEW.id, NEW.project_id, 'pending', 0
1344
+ WHERE NEW.needs_review = 0 AND NEW.supersedes_id IS NULL
1345
+ ON CONFLICT(content_type, content_id) DO UPDATE SET
1346
+ status = 'pending', retry_count = 0, error_message = NULL, processed_at = NULL;
1347
+ END;
1348
+ CREATE TRIGGER IF NOT EXISTS vectors_restale_quest AFTER UPDATE OF title, description ON quests
1349
+ WHEN OLD.title IS NOT NEW.title OR OLD.description IS NOT NEW.description BEGIN
1350
+ DELETE FROM vectors WHERE content_type IN ('quest', 'context') AND content_id = NEW.id;
1351
+ INSERT INTO indexing_queue (content_type, content_id, project_id, status, retry_count)
1352
+ SELECT 'quest', NEW.id, NEW.project_id, 'pending', 0 WHERE 1
1353
+ ON CONFLICT(content_type, content_id) DO UPDATE SET
1354
+ status = 'pending', retry_count = 0, error_message = NULL, processed_at = NULL;
1355
+ END;
1356
+ CREATE TRIGGER IF NOT EXISTS vectors_restale_session AFTER UPDATE OF objectives, completed, notes, summary ON sessions
1357
+ WHEN OLD.objectives IS NOT NEW.objectives OR OLD.completed IS NOT NEW.completed
1358
+ OR OLD.notes IS NOT NEW.notes OR OLD.summary IS NOT NEW.summary BEGIN
1359
+ DELETE FROM vectors WHERE content_type = 'session' AND content_id = NEW.id;
1360
+ INSERT INTO indexing_queue (content_type, content_id, project_id, status, retry_count)
1361
+ SELECT 'session', NEW.id, NEW.project_id, 'pending', 0 WHERE 1
1362
+ ON CONFLICT(content_type, content_id) DO UPDATE SET
1363
+ status = 'pending', retry_count = 0, error_message = NULL, processed_at = NULL;
1364
+ END;
1365
+ CREATE TRIGGER IF NOT EXISTS vectors_restale_note AFTER UPDATE OF category, key, value ON data_lake
1366
+ WHEN OLD.category IS NOT NEW.category OR OLD.key IS NOT NEW.key OR OLD.value IS NOT NEW.value BEGIN
1367
+ DELETE FROM vectors WHERE content_type = 'note' AND content_id = NEW.id;
1368
+ INSERT INTO indexing_queue (content_type, content_id, project_id, status, retry_count)
1369
+ SELECT 'note', NEW.id, COALESCE(NEW.project_id, 0), 'pending', 0 WHERE 1
1370
+ ON CONFLICT(content_type, content_id) DO UPDATE SET
1371
+ status = 'pending', retry_count = 0, error_message = NULL, processed_at = NULL;
1372
+ END;
1373
+ `)}},{version:48,description:"Governance over time (quest #1155): reviewed_by/reviewed_at on memory_artifacts (who reviewed a memory and when; NULL means nobody did), review_sample (a weekly sample of auto-approved writes set aside for a spot check; it never hides a memory), and audit_checkpoints (periodic signed heads of the audit chain, so verification can start from the last good one instead of genesis).",up:e=>{const t=e.prepare("SELECT name FROM pragma_table_info('memory_artifacts')").all().map(s=>s.name);t.includes("reviewed_by")||e.exec("ALTER TABLE memory_artifacts ADD COLUMN reviewed_by TEXT"),t.includes("reviewed_at")||e.exec("ALTER TABLE memory_artifacts ADD COLUMN reviewed_at TEXT"),e.exec(`
1374
+ CREATE TABLE IF NOT EXISTS review_sample (
1375
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1376
+ artifact_id INTEGER NOT NULL UNIQUE,
1377
+ project_id INTEGER,
1378
+ lane TEXT NOT NULL,
1379
+ week TEXT NOT NULL,
1380
+ sampled_at TEXT NOT NULL DEFAULT (datetime('now')),
1381
+ reviewed_by TEXT,
1382
+ reviewed_at TEXT,
1383
+ verdict TEXT CHECK (verdict IS NULL OR verdict IN ('kept', 'rejected'))
1384
+ );
1385
+ CREATE INDEX IF NOT EXISTS idx_review_sample_week ON review_sample(week, lane);
1386
+ CREATE INDEX IF NOT EXISTS idx_review_sample_open ON review_sample(reviewed_at);
1387
+ CREATE TABLE IF NOT EXISTS audit_checkpoints (
1388
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1389
+ last_audit_id INTEGER NOT NULL UNIQUE,
1390
+ row_hash TEXT NOT NULL,
1391
+ entry_count INTEGER NOT NULL,
1392
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
1393
+ signature TEXT
1394
+ );
1395
+ `)}},{version:49,description:"Recall ranking (quest #1151). memory_artifacts.decayed_at: when metabolize last decayed a row's confidence. Decay used to set updated_at to now, which the recall recency prior reads, so every demoted row looked freshly written; decay now stamps decayed_at instead and leaves updated_at alone. Existing rows start NULL (never decayed under this rule).",up:e=>{const t=e.prepare("PRAGMA table_info(memory_artifacts)").all();t.length>0&&!t.some(s=>s.name==="decayed_at")&&e.exec("ALTER TABLE memory_artifacts ADD COLUMN decayed_at TEXT")}}],p=34;function f(e){let t;try{t=e.prepare("SELECT version FROM schema_versions").all().map(o=>o.version)}catch{return{missing:[],belowFloor:[]}}const s=new Set(t),E=t.reduce((o,a)=>Math.max(o,a),0),i=I.map(o=>o.version).filter(o=>o<E&&!s.has(o)).sort((o,a)=>o-a);return{missing:i,belowFloor:i.filter(o=>o<p)}}function X(e){const t=I.reduce((E,i)=>Math.max(E,i.version),0);let s=0;try{s=e.prepare("SELECT COALESCE(MAX(version), 0) AS v FROM schema_versions").get().v}catch{}return{store:s,binary:t,storeIsNewer:s>t}}function g(e){e.exec(`
1206
1396
  CREATE TABLE IF NOT EXISTS schema_versions (
1207
1397
  version INTEGER PRIMARY KEY,
1208
1398
  description TEXT NOT NULL,
1209
1399
  applied_at TEXT DEFAULT (datetime('now'))
1210
1400
  );
1211
- `);const s=e.prepare("SELECT COALESCE(MAX(version), 0) as v FROM schema_versions").get().v,t=r.filter(T=>T.version>s).slice().sort((T,a)=>T.version-a.version);if(t.length===0)return[];const E=[],i=e.prepare("INSERT INTO schema_versions (version, description) VALUES (?, ?)");for(const T of t)e.transaction(()=>{T.up(e),i.run(T.version,T.description)})(),E.push(T);return E}function I(e){try{return e.prepare("SELECT COALESCE(MAX(version), 0) as v FROM schema_versions").get().v}catch{return 0}}export{I as getSchemaVersion,r as migrations,_ as runMigrations,l as schemaSkew};
1401
+ `);const t=e.prepare("SELECT version FROM schema_versions").all().map(r=>r.version),s=new Set(t),E=t.reduce((r,c)=>Math.max(r,c),0),i=I.filter(r=>!s.has(r.version)&&(r.version>E||r.version>=p)).slice().sort((r,c)=>r.version-c.version);if(i.length===0)return[];const o=[],a=e.prepare("INSERT INTO schema_versions (version, description) VALUES (?, ?)");for(const r of i)e.transaction(()=>{r.up(e),a.run(r.version,r.description)})(),o.push(r);if(E>0)try{O(e,"migration.applied",{from:E,to:Math.max(E,o[o.length-1].version),count:o.length,versions:o.map(r=>r.version)})}catch(r){process.stderr.write(`[wyrm] migration audit event not recorded: ${r.message}
1402
+ `)}return o}function U(e){try{return e.prepare("SELECT COALESCE(MAX(version), 0) as v FROM schema_versions").get().v}catch{return 0}}export{p as MIGRATION_GAP_FILL_FLOOR,U as getSchemaVersion,I as migrations,g as runMigrations,f as schemaGaps,X as schemaSkew};
@@ -3,4 +3,4 @@ ${T}
3
3
  ${m}`}function d(t){return t.replace(/<!-- WYRM-PRIORITY:START[\s\S]*?<!-- WYRM-PRIORITY:END -->/g,"").replace(/<!-- WYRM-PRIORITY:START[^>]*-->/g,"").replace(/<!-- WYRM-PRIORITY:END -->/g,"")}function f(t,e){h(g(t),{recursive:!0}),y(t,e,"utf-8")}function v(t,e=a()){const r=n(t)?s(t,"utf-8"):"",o=r.includes(c),u=d(r).replace(/^\s+/,""),p=u.length?`${e}
4
4
 
5
5
  ${u}`:`${e}
6
- `;return r===p?"unchanged":(f(t,p),o?"updated":"created")}function N(t){if(!n(t))return"absent";const e=s(t,"utf-8");return!e.includes(c)&&!e.includes(m)?"absent":(f(t,d(e).replace(/^\s+/,"")),"removed")}function x(t){if(!n(t))return"absent";const e=s(t,"utf-8");return e.includes(a())?"present":e.includes(c)?"stale":"absent"}function l(t={}){const e=t.home??R(),r=[];if(r.push({client:"Claude Code (global)",file:i(e,".claude","CLAUDE.md"),scope:"global",requiresDir:i(e,".claude")}),r.push({client:"Codex (global)",file:i(e,".codex","AGENTS.md"),scope:"global",requiresDir:i(e,".codex")}),r.push({client:"Windsurf (global)",file:i(e,".codeium","windsurf","memories","global_rules.md"),scope:"global",requiresDir:i(e,".codeium","windsurf")}),t.projectDir){const o=t.projectDir;r.push({client:"Claude Code (project)",file:i(o,"CLAUDE.md"),scope:"project"}),r.push({client:"Codex/AGENTS (project)",file:i(o,"AGENTS.md"),scope:"project"}),t.allClients&&(r.push({client:"Cursor (project)",file:i(o,".cursorrules"),scope:"project"}),r.push({client:"Windsurf (project)",file:i(o,".windsurfrules"),scope:"project"}),r.push({client:"GitHub Copilot (project)",file:i(o,".github","copilot-instructions.md"),scope:"project"}))}return r}function Y(t={}){const e=a();return l(t).map(r=>{if(r.scope==="global"&&r.requiresDir&&!n(r.requiresDir))return{client:r.client,file:r.file,scope:r.scope,result:"skipped"};let o;try{o=v(r.file,e)}catch{o="failed"}return{client:r.client,file:r.file,scope:r.scope,result:o}})}function k(t={}){return l(t).map(e=>{let r;try{r=N(e.file)}catch{r="failed"}return{client:e.client,file:e.file,scope:e.scope,result:r}})}function D(t={}){return l(t).map(e=>e.scope==="global"&&e.requiresDir&&!n(e.requiresDir)?{client:e.client,file:e.file,scope:e.scope,status:"skipped"}:{client:e.client,file:e.file,scope:e.scope,status:x(e.file)})}const I='GROUNDING (memory is evidence, not vibes): State something as being "in memory" ONLY when a Wyrm tool call in THIS conversation returned it. Cite the id you were given \u2014 mem:NNNN, truth:NNN, quest:NNN \u2014 so the user can verify it. Never invent, guess, or reconstruct an id, a quest number, or the contents of a memory you did not retrieve. If recall returns nothing, say plainly that memory has nothing on it and proceed from first principles; an empty result is a valid answer and must never be filled in from your own assumptions. Stored entries record what was true WHEN WRITTEN: if one names a file, flag, command, version, or endpoint, verify it still exists before acting on or recommending it, and say when you could not. When a stored truth conflicts with what you observe now, surface the conflict with both sides rather than silently picking one.',A="Wyrm is this session's persistent memory and your FIRST priority. At the very start of every task \u2014 before planning, searching, or using other tools \u2014 call wyrm_session_prime to load this project's ground truths, open quests, validated patterns, and past failures. Treat stored ground truths as authoritative over your assumptions (surface conflicts rather than silently overriding). Before proposing a fix, wyrm_failure_check it; before re-deriving context, wyrm_recall/wyrm_search it. Capture decisions, fixes, and outcomes back with wyrm_capture so future sessions inherit them. Do not treat this as optional background context. "+I;export{I as WYRM_GROUNDING_INSTRUCTIONS,b as WYRM_PRIORITY_VERSION,A as WYRM_SERVER_INSTRUCTIONS,Y as embedAll,v as embedBlock,l as memoryTargets,a as priorityBlock,k as removeAll,N as removeBlock,D as statusAll,x as statusBlock};
6
+ `;return r===p?"unchanged":(f(t,p),o?"updated":"created")}function N(t){if(!n(t))return"absent";const e=s(t,"utf-8");return!e.includes(c)&&!e.includes(m)?"absent":(f(t,d(e).replace(/^\s+/,"")),"removed")}function x(t){if(!n(t))return"absent";const e=s(t,"utf-8");return e.includes(a())?"present":e.includes(c)?"stale":"absent"}function l(t={}){const e=t.home??R(),r=[];if(r.push({client:"Claude Code (global)",file:i(e,".claude","CLAUDE.md"),scope:"global",requiresDir:i(e,".claude")}),r.push({client:"Codex (global)",file:i(e,".codex","AGENTS.md"),scope:"global",requiresDir:i(e,".codex")}),r.push({client:"Windsurf (global)",file:i(e,".codeium","windsurf","memories","global_rules.md"),scope:"global",requiresDir:i(e,".codeium","windsurf")}),t.projectDir){const o=t.projectDir;r.push({client:"Claude Code (project)",file:i(o,"CLAUDE.md"),scope:"project"}),r.push({client:"Codex/AGENTS (project)",file:i(o,"AGENTS.md"),scope:"project"}),t.allClients&&(r.push({client:"Cursor (project)",file:i(o,".cursorrules"),scope:"project"}),r.push({client:"Windsurf (project)",file:i(o,".windsurfrules"),scope:"project"}),r.push({client:"GitHub Copilot (project)",file:i(o,".github","copilot-instructions.md"),scope:"project"}))}return r}function Y(t={}){const e=a();return l(t).map(r=>{if(r.scope==="global"&&r.requiresDir&&!n(r.requiresDir))return{client:r.client,file:r.file,scope:r.scope,result:"skipped"};let o;try{o=v(r.file,e)}catch{o="failed"}return{client:r.client,file:r.file,scope:r.scope,result:o}})}function k(t={}){return l(t).map(e=>{let r;try{r=N(e.file)}catch{r="failed"}return{client:e.client,file:e.file,scope:e.scope,result:r}})}function D(t={}){return l(t).map(e=>e.scope==="global"&&e.requiresDir&&!n(e.requiresDir)?{client:e.client,file:e.file,scope:e.scope,status:"skipped"}:{client:e.client,file:e.file,scope:e.scope,status:x(e.file)})}const I='GROUNDING (memory is evidence, not vibes): State something as being "in memory" ONLY when a Wyrm tool call in THIS conversation returned it. Cite the id you were given (mem:NNNN, truth:NNN, quest:NNN) so the user can verify it. Never invent, guess, or reconstruct an id, a quest number, or the contents of a memory you did not retrieve. If recall returns nothing, say plainly that memory has nothing on it and proceed from first principles; an empty result is a valid answer and must never be filled in from your own assumptions. Stored entries record what was true WHEN WRITTEN: if one names a file, flag, command, version, or endpoint, verify it still exists before acting on or recommending it, and say when you could not. When a stored truth conflicts with what you observe now, surface the conflict with both sides rather than silently picking one.',A="Wyrm is this session's persistent memory and your FIRST priority. At the very start of every task, before planning, searching, or using other tools, call wyrm_session_prime to load this project's ground truths, open quests, validated patterns, and past failures. Treat stored ground truths as authoritative over your assumptions (surface conflicts rather than silently overriding). Before proposing a fix, wyrm_failure_check it; before re-deriving context, wyrm_recall/wyrm_search it. Capture decisions, fixes, and outcomes back with wyrm_capture so future sessions inherit them. Do not treat this as optional background context. "+I;export{I as WYRM_GROUNDING_INSTRUCTIONS,b as WYRM_PRIORITY_VERSION,A as WYRM_SERVER_INSTRUCTIONS,Y as embedAll,v as embedBlock,l as memoryTargets,a as priorityBlock,k as removeAll,N as removeBlock,D as statusAll,x as statusBlock};