wyrm-mcp 7.3.1 → 7.3.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 (194) hide show
  1. package/BENCHMARKS.md +54 -1
  2. package/COMPARISON.md +117 -0
  3. package/README.md +14 -15
  4. package/dist/activation.js +59 -1
  5. package/dist/agent-daemon.js +281 -4
  6. package/dist/agent-loop.js +332 -7
  7. package/dist/analytics.js +236 -13
  8. package/dist/attribution.js +49 -1
  9. package/dist/audit.js +457 -2
  10. package/dist/auto-capture.js +138 -3
  11. package/dist/auto-orchestrator.js +325 -1
  12. package/dist/autoconfig.d.ts +50 -0
  13. package/dist/autoconfig.d.ts.map +1 -1
  14. package/dist/autoconfig.js +1115 -39
  15. package/dist/autoconfig.js.map +1 -1
  16. package/dist/buddy-runner.js +109 -1
  17. package/dist/buddy.js +564 -14
  18. package/dist/build-flags.js +15 -1
  19. package/dist/capabilities.js +183 -3
  20. package/dist/capture.js +56 -1
  21. package/dist/causality.js +148 -8
  22. package/dist/cli.js +281 -20
  23. package/dist/cloud/cli.js +541 -5
  24. package/dist/cloud/client.js +221 -1
  25. package/dist/cloud/crypto.js +85 -1
  26. package/dist/cloud/machine-id.js +113 -2
  27. package/dist/cloud/recovery.js +60 -1
  28. package/dist/cloud/sync-engine.js +543 -7
  29. package/dist/cloud-backup.js +579 -5
  30. package/dist/cloud-profile.js +138 -1
  31. package/dist/cloud-sync-entrypoint.js +47 -1
  32. package/dist/cloud-sync.js +309 -2
  33. package/dist/connectors/bridge-source.d.ts +46 -0
  34. package/dist/connectors/bridge-source.d.ts.map +1 -0
  35. package/dist/connectors/bridge-source.js +77 -0
  36. package/dist/connectors/bridge-source.js.map +1 -0
  37. package/dist/connectors/index.d.ts +24 -0
  38. package/dist/connectors/index.d.ts.map +1 -0
  39. package/dist/connectors/index.js +69 -0
  40. package/dist/connectors/index.js.map +1 -0
  41. package/dist/connectors/ingest.d.ts +16 -0
  42. package/dist/connectors/ingest.d.ts.map +1 -0
  43. package/dist/connectors/ingest.js +116 -0
  44. package/dist/connectors/ingest.js.map +1 -0
  45. package/dist/connectors/types.d.ts +99 -0
  46. package/dist/connectors/types.d.ts.map +1 -0
  47. package/dist/connectors/types.js +17 -0
  48. package/dist/connectors/types.js.map +1 -0
  49. package/dist/constellation.js +168 -12
  50. package/dist/content-signature.js +45 -1
  51. package/dist/context-build-budgeted.js +144 -4
  52. package/dist/context-ranking.js +69 -1
  53. package/dist/crypto.js +179 -1
  54. package/dist/daemon-write-endpoint.js +290 -1
  55. package/dist/daemon-writer.js +406 -2
  56. package/dist/database.js +1278 -53
  57. package/dist/deprecations.js +162 -2
  58. package/dist/design.js +141 -13
  59. package/dist/event-replication.js +112 -1
  60. package/dist/events-sse.js +43 -7
  61. package/dist/events.js +238 -6
  62. package/dist/failure-patterns.d.ts +107 -0
  63. package/dist/failure-patterns.d.ts.map +1 -1
  64. package/dist/failure-patterns.js +924 -43
  65. package/dist/failure-patterns.js.map +1 -1
  66. package/dist/federation.js +236 -12
  67. package/dist/goals.js +101 -13
  68. package/dist/golden.js +355 -3
  69. package/dist/handlers/agent.js +165 -4
  70. package/dist/handlers/alias-adapters.js +129 -1
  71. package/dist/handlers/aliases.js +171 -1
  72. package/dist/handlers/audit.js +87 -1
  73. package/dist/handlers/boundary.js +221 -1
  74. package/dist/handlers/capture.js +1114 -73
  75. package/dist/handlers/causality.js +119 -9
  76. package/dist/handlers/cloud.js +382 -85
  77. package/dist/handlers/companion.js +459 -28
  78. package/dist/handlers/datalake.js +187 -7
  79. package/dist/handlers/dispatch-context.js +22 -0
  80. package/dist/handlers/entity.js +256 -25
  81. package/dist/handlers/events.js +335 -16
  82. package/dist/handlers/failure.d.ts.map +1 -1
  83. package/dist/handlers/failure.js +408 -13
  84. package/dist/handlers/failure.js.map +1 -1
  85. package/dist/handlers/goals.js +296 -4
  86. package/dist/handlers/intelligence.js +681 -126
  87. package/dist/handlers/invoicing.js +70 -1
  88. package/dist/handlers/mcpclient.js +137 -6
  89. package/dist/handlers/orchestration.js +125 -40
  90. package/dist/handlers/output-schemas.js +24 -1
  91. package/dist/handlers/presence.js +99 -3
  92. package/dist/handlers/project.js +182 -28
  93. package/dist/handlers/prompts.js +157 -6
  94. package/dist/handlers/quest.js +224 -4
  95. package/dist/handlers/recall.js +237 -13
  96. package/dist/handlers/registry.js +167 -1
  97. package/dist/handlers/resources.js +288 -1
  98. package/dist/handlers/review.js +74 -11
  99. package/dist/handlers/run.js +498 -16
  100. package/dist/handlers/search.js +338 -15
  101. package/dist/handlers/session.js +643 -31
  102. package/dist/handlers/share.js +184 -8
  103. package/dist/handlers/shims.js +464 -1
  104. package/dist/handlers/skill.js +449 -67
  105. package/dist/handlers/survivors.js +120 -1
  106. package/dist/handlers/symbols.js +109 -8
  107. package/dist/handlers/syncops.js +302 -4
  108. package/dist/handlers/types.js +27 -1
  109. package/dist/harvest.js +191 -5
  110. package/dist/hours.js +156 -7
  111. package/dist/http-auth.js +321 -3
  112. package/dist/http-fast.js +1302 -22
  113. package/dist/icons.js +47 -1
  114. package/dist/importers.js +268 -1
  115. package/dist/index.d.ts.map +1 -1
  116. package/dist/index.js +840 -2
  117. package/dist/index.js.map +1 -1
  118. package/dist/indexer.js +145 -4
  119. package/dist/intelligence.js +261 -31
  120. package/dist/internal-dispatch.js +212 -3
  121. package/dist/keyset.js +110 -1
  122. package/dist/knowledge-graph.js +176 -12
  123. package/dist/license.js +441 -2
  124. package/dist/logger.js +199 -2
  125. package/dist/maintenance.js +148 -2
  126. package/dist/mcp-client.js +262 -6
  127. package/dist/memory-artifacts.js +596 -32
  128. package/dist/migrate-prompt.js +124 -2
  129. package/dist/migrations.d.ts.map +1 -1
  130. package/dist/migrations.js +799 -42
  131. package/dist/migrations.js.map +1 -1
  132. package/dist/performance.js +228 -1
  133. package/dist/presence.js +140 -11
  134. package/dist/priority-embed.js +164 -5
  135. package/dist/providers/embedding-provider.js +196 -1
  136. package/dist/readonly-gate.js +29 -1
  137. package/dist/receipt.js +43 -1
  138. package/dist/rehydration.js +157 -9
  139. package/dist/reindex.js +88 -1
  140. package/dist/render-target.js +544 -21
  141. package/dist/render.js +280 -4
  142. package/dist/repl-guard.js +173 -1
  143. package/dist/replication-daemon-entrypoint.js +31 -1
  144. package/dist/replication-daemon.js +262 -2
  145. package/dist/rerank.js +142 -1
  146. package/dist/resilience.js +591 -1
  147. package/dist/reverse-bridge.js +360 -5
  148. package/dist/security.js +244 -1
  149. package/dist/session-seen.js +51 -3
  150. package/dist/setup.js +260 -1
  151. package/dist/skill-author.js +168 -5
  152. package/dist/spec-kit.js +191 -1
  153. package/dist/sqlite-busy.js +154 -1
  154. package/dist/statusline.js +315 -11
  155. package/dist/sub-agent.js +262 -13
  156. package/dist/summarizer.js +139 -13
  157. package/dist/symbols.js +283 -7
  158. package/dist/sync.js +359 -5
  159. package/dist/tasks-dispatch.js +84 -1
  160. package/dist/tasks.js +282 -1
  161. package/dist/token-budget.js +143 -1
  162. package/dist/tool-analytics.js +129 -7
  163. package/dist/tool-annotations.js +365 -1
  164. package/dist/tool-manifest-v2.json +1 -1
  165. package/dist/tool-manifest.json +1 -1
  166. package/dist/tool-profiles.js +75 -1
  167. package/dist/trace-harvest.js +244 -6
  168. package/dist/types.js +30 -1
  169. package/dist/ui-dashboard.js +50 -41
  170. package/dist/ulid.js +81 -1
  171. package/dist/usage-tracker.d.ts +55 -0
  172. package/dist/usage-tracker.d.ts.map +1 -0
  173. package/dist/usage-tracker.js +66 -0
  174. package/dist/usage-tracker.js.map +1 -0
  175. package/dist/validate.js +129 -1
  176. package/dist/vault.js +534 -1
  177. package/dist/vector-init.d.ts +28 -0
  178. package/dist/vector-init.d.ts.map +1 -0
  179. package/dist/vector-init.js +67 -0
  180. package/dist/vector-init.js.map +1 -0
  181. package/dist/vectors.js +184 -3
  182. package/dist/version-check.js +136 -4
  183. package/dist/visibility.js +155 -19
  184. package/dist/wyrm-cli.js +2845 -101
  185. package/dist/wyrm-cli.js.map +1 -1
  186. package/dist/wyrm-guard.d.ts.map +1 -1
  187. package/dist/wyrm-guard.js +475 -14
  188. package/dist/wyrm-guard.js.map +1 -1
  189. package/dist/wyrm-loop.js +150 -3
  190. package/dist/wyrm-manifest.json +1 -1
  191. package/dist/wyrm-statusline-daemon.js +11 -1
  192. package/dist/wyrm-statusline.js +56 -4
  193. package/dist/wyrm-ui.js +77 -9
  194. package/package.json +2 -1
package/BENCHMARKS.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  Wyrm competes on an axis the cloud memory layers can't stand on: **the number is produced with zero cloud calls and zero generative-LLM calls, and anyone can reproduce it offline.** mem0 / Zep / Supermemory headline end-to-end QA accuracy that depends on an LLM extracting and answering; the number below is the **retrieval floor underneath that** — *did the memory actually return a ground-truth supporting turn?* — measured deterministically.
4
4
 
5
+ > **Comparing to mem0 / Zep / others?** See **[COMPARISON.md](./COMPARISON.md)** — a cited, honest side-by-side that keeps retrieval-recall and QA-answer-accuracy in *separate* columns (they measure different things, and every competitor number is vendor-self-reported).
6
+
5
7
  ## Metric
6
8
 
7
9
  Real **LoCoMo** (*Evaluating Very Long-Term Conversational Memory*, snap-research/locomo — 10 multi-session conversations, 1,986 QA). Every dialogue turn is ingested tagged with its `dia_id`; for each question that ships ground-truth `evidence` turns, Wyrm recalls over the question and we score whether a supporting `dia_id` comes back in the top-_k_.
@@ -50,8 +52,59 @@ node bench/locomo-hybrid.mjs bench/data/locomo10.json --k 10
50
52
 
51
53
  The committed `bench/longmemeval-fixture.json` ships a small self-contained corpus so `node bench/longmemeval.mjs` runs with **no download at all** — that fixture's no-LLM floor is the CI gate that keeps these numbers from regressing.
52
54
 
55
+ ## Beyond the retrieval floor — two more benchmarks
56
+
57
+ Retrieval recall is the floor. Two more, all reproducible, all local (added 2026-06-27).
58
+
59
+ ### Negative learning — the firewall benchmark (the race we own)
60
+
61
+ No public memory benchmark measures this. `bench/negative-learning.mjs` asks: when an agent is about to **repeat** a recorded mistake, does `wyrm_failure_check` block it — and stay silent on novel actions? Deterministic, no LLM, no cloud.
62
+
63
+ | probe | result |
64
+ |---|---|
65
+ | same action re-attempted (the guard's real input) | **recall 100%** (16/16) |
66
+ | novel actions | **precision 100%** · specificity 100% (0 false blocks of 16) |
67
+ | reworded restatement | recall 12.5% — conjunctive-AND FTS is precision-first *by design* |
68
+ | `checkVerdict` latency | p50 ~0.1 ms |
69
+
70
+ Wyrm blocks literal repeats deterministically with zero false alarms. The reworded tier is intentionally conservative; a stopword filter on the fuzzy probe (so incidental filler words can't break the conjunctive-AND) recovered the filler-broken matches — **6.3% → 12.5% with precision held at 100%** (`tests/firewall-recall.test.ts` guards it). Going higher needs OR/threshold matching that would trade away that precision, so the firewall stays precision-first. Run: `node bench/negative-learning.mjs`.
71
+
72
+ ### Embedding-model sweep
73
+
74
+ The hybrid number uses local `nomic-embed-text`. Swapping the embedder (same harness, `--model`):
75
+
76
+ | embedder | hybrid r@5 | hybrid r@10 | MRR | multi-hop r@5 | note |
77
+ |---|:--:|:--:|:--:|:--:|---|
78
+ | `nomic-embed-text` (default, 274 MB) | 60.3% | 72.2% | .447 | 49.3% | the shipped default |
79
+ | `mxbai-embed-large` (669 MB) | **61.1%** | **72.9%** | **.453** | **55.3%** | small net lift + notable multi-hop gain; 2.4× size |
80
+ | `bge-m3` | — | — | — | — | errored under Ollama (NaN embeddings) — not benchmarkable here |
81
+
82
+ `mxbai-embed-large` is a viable switchable upgrade (`--model mxbai-embed-large`), especially for multi-hop; nomic stays the lightweight default.
83
+
84
+ ### Cross-encoder reranker (opt-in) — measured: the biggest top-rank lift here
85
+
86
+ `WYRM_RERANK_MODEL` engages `src/rerank.ts` (bge-reranker-v2-m3 over a local llama.cpp `/v1/rerank` endpoint) as a final, opt-in leg of `recallHybrid`. Measured on real LoCoMo (`bench/locomo-rerank.mjs`, 755 evidence QA / 4 convs, Q8_0, every query reranked — 0 fallbacks):
87
+
88
+ | metric | hybrid (fused) | **+ reranker** | Δ |
89
+ |---|:--:|:--:|:--:|
90
+ | recall@1 | 33.2% | **52.6%** | **+19.4** |
91
+ | recall@5 | 61.1% | **73.0%** | **+11.9** |
92
+ | recall@10 | 73.2% | **76.6%** | +3.4 |
93
+ | MRR@10 | .453 | **.613** | **+.16** |
94
+
95
+ It lifts the **weak categories** most (recall@5): multi-hop **51.4 → 67.6**, open-domain **30.0 → 43.3**, single-hop 59.8 → 74.9, temporal 76.9 → 86.2. A cross-encoder's strength is precision at the *top* — hence the large recall@1 / MRR gains.
96
+
97
+ **The tradeoff (why it's OFF by default):** a forward pass per candidate is slow — ~3.6 s/query on CPU at cand=15 (far faster on GPU). It's a quality lever for high-value retrieval, not the hot path; the deterministic hybrid stays the default. Setup + repro:
98
+
99
+ ```sh
100
+ # 1. a llama.cpp server with reranking, serving bge-reranker-v2-m3 on :8088
101
+ llama-server -m bge-reranker-v2-m3-Q8_0.gguf --reranking --pooling rank --port 8088
102
+ # 2. the lift bench (local Ollama for embeddings, llama.cpp for the reranker)
103
+ WYRM_RERANK_MODEL=bge-reranker-v2-m3 node bench/locomo-rerank.mjs bench/data/locomo10.json --convs 4
104
+ ```
105
+
53
106
  ## Why this framing, honestly
54
107
 
55
- - This is **retrieval recall, not QA accuracy.** We do not claim to beat Supermemory's 81.6% LongMemEval *answer* score — that's a different, LLM-in-the-loop metric on a different task. We claim the **strongest deterministic, zero-cloud retrieval floor**, which is the thing those products don't publish because their pipelines can't run without a cloud LLM.
108
+ - This is **retrieval recall, not QA accuracy.** We do not claim to beat the cloud memory layers' end-to-end *answer*-accuracy scores — that's a different, LLM-in-the-loop metric on a different task (see `COMPARISON.md`; note every competitor figure is vendor-self-reported, and circulating "81.6% LongMemEval"-type numbers could not be tied to a verifiable primary source). We claim the **strongest deterministic, zero-cloud retrieval floor**, which is the thing those products don't publish because their pipelines can't run without a cloud LLM.
56
109
  - The floor is **honest about its weak spots** — multi-hop and open-domain are where pure lexical retrieval struggles; the per-category table shows it rather than hiding behind an average.
57
110
  - Every number here is **offline and reproducible.** No leaderboard submission, no private eval harness — the dataset is public and the harness is in this repo.
package/COMPARISON.md ADDED
@@ -0,0 +1,117 @@
1
+ # Wyrm vs. the field — an honest comparison
2
+
3
+ > Companion to [`BENCHMARKS.md`](./BENCHMARKS.md). Last verified **2026-06-27** via a
4
+ > multi-source, adversarially-verified literature pass against primary sources.
5
+ > Every competitor number here is **vendor-self-reported** and cited to its paper/repo.
6
+
7
+ ## The one rule this document refuses to break
8
+
9
+ There are **two different evaluation axes**, and they are routinely (and incorrectly)
10
+ mixed in marketing tables:
11
+
12
+ | Axis | Question it answers | Who reports it |
13
+ |---|---|---|
14
+ | **Retrieval recall@k** | "When the question is asked, did the memory layer *surface the ground-truth supporting evidence*?" | **Wyrm** |
15
+ | **QA answer accuracy** | "Did a *separate LLM judge* rate the *generated answer* correct vs a golden answer?" | mem0, Zep, and effectively every other system below |
16
+
17
+ These are **not comparable numbers.** A retrieval recall@k of 72.2 is *not* better or
18
+ worse than a QA-accuracy of 66.9 — they measure different things. This document keeps
19
+ them in **separate tables** on purpose. Anyone placing "Wyrm 72.2" next to "Mem0 66.9"
20
+ in one ranked column is making a category error.
21
+
22
+ (Note the naming trap: Zep's headline benchmark is literally called *Deep Memory
23
+ **Retrieval*** (DMR), but its score is final-answer correctness judged by an LLM — **not**
24
+ recall@k.)
25
+
26
+ ## What *is* apples-to-apples: architecture
27
+
28
+ This table compares facts that mean the same thing for every system.
29
+
30
+ | System | Open source | Runs fully local / no cloud | LLM at **write** (ingest) | LLM at **answer** | Headline metric |
31
+ |---|---|---|---|---|---|
32
+ | **Wyrm** | AGPL-3.0 (dual-licensed) | ✅ yes | ❌ **none** (deterministic FTS/vector) | ❌ **none** (retrieval only) | retrieval recall@k |
33
+ | Mem0 | Apache-2.0 (+ managed cloud) | self-host possible | ✅ required (LLM extraction + ADD/UPDATE/DELETE/NOOP) | ✅ required | QA accuracy (LLM-judge "J") |
34
+ | Zep / Graphiti | Graphiti Apache-2.0 (Zep cloud) | self-host possible | ✅ required (LLM graph construction) | ✅ required | QA accuracy (LLM-judge) |
35
+ | SuperMemory · cognee · SuperLocalMemory | varies | varies | varies | varies | *no citable LoCoMo/LongMemEval number found* (see below) |
36
+
37
+ **The defensible differentiator:** Wyrm reaches competitive *retrieval* with **zero cloud
38
+ and zero LLM calls at both read and write.** mem0 and Zep each require an LLM at ingest
39
+ *and* at answer time. (Plus Wyrm's structural differentiators: negative learning /
40
+ failure memory, decision causality, MCP-native, deterministic — none of which these
41
+ benchmarks measure.)
42
+
43
+ ## The published numbers (separated by axis — do **not** cross-rank)
44
+
45
+ ### Wyrm — retrieval recall@k, real LoCoMo, local + zero-LLM
46
+
47
+ Reproduces the figures in [`BENCHMARKS.md`](./BENCHMARKS.md) (snap-research/LoCoMo, 10
48
+ convs / 1,982 evidence-bearing QA, k=10; re-run 2026-06-27, HEAD).
49
+
50
+ | Tier | recall@1 | recall@5 | recall@10 | MRR | LLM? | Cloud? |
51
+ |---|---|---|---|---|---|---|
52
+ | FTS floor (deterministic, offline) | 29.5 | 52.4 | 59.9 | .393 | none | none |
53
+ | + vectors (nomic-embed-text, local) | 28.8 | 58.7 | 69.5 | .413 | none* | none |
54
+ | hybrid (FTS ⊕ vector, RRF cand25) | 32.8 | 60.3 | 72.2 | .447 | none* | none |
55
+ | production (convex fusion, cand50 α0.7) | 32.1 | 61.6 | 72.5 | .446 | none* | none |
56
+
57
+ \* the embedding model is a local Ollama call, not a generative LLM; the FTS floor needs
58
+ no model at all and is the CI-gated, fully-deterministic number.
59
+
60
+ ### Competitors — QA answer accuracy (LLM-judge), vendor-self-reported
61
+
62
+ | System | Benchmark | Metric | Score | Source |
63
+ |---|---|---|---|---|
64
+ | Mem0 (paper) | LoCoMo | LLM-judge "J" | **66.88%** (mem0-graph 68.44%) | arXiv 2504.19413 |
65
+ | ↳ same table, comparators | LoCoMo | LLM-judge "J" | Full-Context 72.90 · Zep 65.99† · LangMem 58.10 · OpenAI-memory 52.90 | arXiv 2504.19413 |
66
+ | Mem0 (managed Platform v3 — *different config from the paper*) | LoCoMo | answer acc. | 92.5% (Top-200) / 91.8% (Top-50) | github: mem0ai/memory-benchmarks |
67
+ | Mem0 (managed Platform v3) | LongMemEval | answer acc. | 94.4% (Top-200) / 94.8% (Top-50) | github: mem0ai/memory-benchmarks |
68
+ | Zep (paper) | LongMemEval | answer acc. (GPT-4o judge) | 71.2% (gpt-4o) / 63.8% (gpt-4o-mini) vs baseline 60.2 / 55.4 | arXiv 2501.13956 |
69
+ | Zep (paper) | DMR | answer acc. | 94.8% (gpt-4-turbo) / 98.2% (gpt-4o-mini) vs MemGPT 93.4% | arXiv 2501.13956 |
70
+
71
+ ## Footnotes that matter (read before quoting any number)
72
+
73
+ - **† The "Zep LoCoMo 65.99%" figure is not Zep's.** Zep's own paper reports **no LoCoMo
74
+ numbers at all** — only DMR and LongMemEval. The 65.99% comes from *Mem0's* table
75
+ (Mem0 scoring Zep). A separate third-party correction (getzep/zep-papers issue #5)
76
+ recalculated a circulating "Zep 84% LoCoMo" claim down to ~58.44% once the otherwise-
77
+ excluded adversarial category is included.
78
+ - **Mem0's paper (~67%) and Mem0's repo (~92%) disagree** because they measure different
79
+ systems/configs (the ECAI paper's OSS pipeline vs. the managed Platform v3). Both are
80
+ answer-accuracy, both vendor-self-reported.
81
+ - **Everything in the competitor table is vendor-self-reported** — the paper authors carry
82
+ `@mem0.ai` / `@getzep.com` affiliations and the benchmark repos are the vendors' own.
83
+ No independent third-party reproduction was found.
84
+ - **LoCoMo is a weak benchmark.** The QA-eval set is only **10 conversations**; the
85
+ **adversarial category is excluded** because ground-truth answers are unavailable; and
86
+ the dialogues are **synthetically LLM-generated** with documented gold-answer quality
87
+ flaws. Treat all LoCoMo numbers — ours included — with that caution.
88
+ - **Zep itself calls its DMR gains "marginal"** over both MemGPT and a full-context
89
+ baseline (94.8 vs 94.4), and notes DMR's 60-message conversations fit in a modern
90
+ context window, making DMR a weak test of memory.
91
+
92
+ ## What we looked for and did **not** find
93
+
94
+ No citable, primary-source LoCoMo or LongMemEval number survived verification for
95
+ **SuperMemory**, **cognee**, **Letta/MemGPT** (it appears only as a *baseline* inside
96
+ Zep's DMR table at 93.4%), or **SuperLocalMemory**. Figures circulating for these (e.g.
97
+ a "SuperMemory 81.6% LongMemEval" or "SuperLocalMemory 74.8% LoCoMo") could not be tied
98
+ to a verifiable primary source and are deliberately omitted rather than repeated.
99
+
100
+ ## The honest takeaway
101
+
102
+ - You **cannot** say "Wyrm beats mem0/Zep" — they report a different metric on a
103
+ partly-different benchmark, with an LLM in the loop that Wyrm doesn't use.
104
+ - What is **true and rare**: Wyrm delivers competitive *retrieval* (recall@10 72.2 on
105
+ real LoCoMo) **with no cloud and no LLM at read or write**, where mem0 and Zep both
106
+ require an LLM at ingest and answer time. That — plus negative learning, decision
107
+ causality, and MCP-native local-first operation — is the moat. Not a bigger number.
108
+
109
+ ## Sources
110
+
111
+ - Mem0 — "Mem0: Building Production-Ready AI Agents with Scalable Long-Term Memory",
112
+ arXiv:2504.19413 (ECAI 2025). Benchmark repo: github.com/mem0ai/memory-benchmarks.
113
+ - Zep — "Zep: A Temporal Knowledge Graph Architecture for Agent Memory",
114
+ arXiv:2501.13956 (Jan 2025). Blog: blog.getzep.com.
115
+ - LoCoMo — snap-research/locomo (the dataset Wyrm's retrieval numbers are measured on).
116
+ - Wyrm retrieval numbers + methodology — [`BENCHMARKS.md`](./BENCHMARKS.md); reproduce with
117
+ `node bench/locomo-real.mjs` (FTS floor) and `node bench/locomo-hybrid.mjs` (hybrid).
package/README.md CHANGED
@@ -3,14 +3,14 @@
3
3
  > Persistent memory is table stakes. The real problem is what agents *do* with it — Wyrm blocks the repeat, keeps decisions true, and learns as a fleet. Memory is the substrate; the judgment is the moat.
4
4
 
5
5
  [![npm version](https://img.shields.io/npm/v/wyrm-mcp?color=00B89F&label=npm)](https://www.npmjs.com/package/wyrm-mcp)
6
- [![License: AGPL-3.0](https://img.shields.io/badge/License-AGPL--3.0-00B89F.svg)](LICENSE)
6
+ [![License: Proprietary](https://img.shields.io/badge/License-Proprietary-b91c1c.svg)](LICENSE)
7
7
  [![Tests](https://img.shields.io/badge/tests-1820%20passing-00B89F)](https://github.com/Ghosts-Protocol-Pvt-Ltd/Wyrm)
8
8
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.9-3178C6?logo=typescript&logoColor=white)](https://www.typescriptlang.org/)
9
9
  [![MCP](https://img.shields.io/badge/MCP-compatible-00B89F)](https://modelcontextprotocol.io)
10
10
 
11
11
  **[wyrm.ghosts.lk](https://wyrm.ghosts.lk)**  ·  **[npm](https://www.npmjs.com/package/wyrm-mcp)**  ·  **[GitHub](https://github.com/Ghosts-Protocol-Pvt-Ltd/Wyrm)**  ·  **[Ghost Protocol](https://ghosts.lk)**  ·  `npm i -g wyrm-mcp`
12
12
 
13
- Local-first persistent memory for AI agents over MCP — by [Ghost Protocol](https://ghosts.lk). Runs fully offline on your machine: no cloud, no account, no LLM required. The managed cloud tier lives at **[wyrm.ghosts.lk](https://wyrm.ghosts.lk)**.
13
+ Local-first persistent memory for AI agents over MCP — by [Ghost Protocol](https://ghosts.lk). Runs fully offline on your machine: no cloud, no LLM required. The official build activates with a one-time free `wyrm login`; your memory stays local either way. The managed cloud tier lives at **[wyrm.ghosts.lk](https://wyrm.ghosts.lk)**.
14
14
 
15
15
  ---
16
16
 
@@ -24,7 +24,12 @@ Wyrm is not "AI memory." It's the **substrate** that turns one-shot AI conversat
24
24
  4. **↯ Federation.** Wyrm calls other MCP servers (GitHub, Slack, Linear, …) as tools. Buddy Protocol v1.0 lets Wyrm talk to other AI memory tools. Composes your whole stack into one mind.
25
25
  5. **✺ Creative substrate.** First-class design tokens (colour / type / spacing / motion / shadow / radius / breakpoint) and a tagged design-reference clipper — Wyrm is not just for code.
26
26
 
27
- **Reproducible numbers.** On real LoCoMo (1,982 evidence QA, verified on 7.3.0), Wyrm's deterministic **zero-LLM, zero-cloud** retrieval floor is recall@5 **52.4%** / recall@10 **59.9%**, lifting to **60.3% / 72.2%** with local Ollama vectors — every number offline and reproducible from this repo. → **[BENCHMARKS.md](BENCHMARKS.md)**
27
+ **Reproducible numbers with receipts.** Every figure below is offline and reproducible from this repo → **[BENCHMARKS.md](BENCHMARKS.md)**:
28
+
29
+ - **Retrieval** — real LoCoMo (1,982 evidence QA): the deterministic **zero-LLM, zero-cloud** floor is recall@5 **52.4%** / recall@10 **59.9%**, lifting to **60.3% / 72.2%** with local Ollama vectors.
30
+ - **Negative learning** — the benchmark no recall-only memory runs: the firewall blocks a repeated mistake at **100% recall · 100% precision** (0 false blocks on novel actions), deterministic, p50 ~0.1 ms.
31
+ - **Reranker (opt-in)** — a local cross-encoder lifts recall@1 **33% → 53%** (+19 pts) and MRR **.45 → .61**.
32
+ - **Honest vs the field** → **[COMPARISON.md](COMPARISON.md)**: Wyrm reports *retrieval recall@k*; mem0 / Zep report *LLM-judged QA-accuracy* — different axes, never conflated, every competitor figure cited + vendor-self-reported.
28
33
 
29
34
  ```
30
35
  You: "What did we decide about the auth architecture last week?"
@@ -258,7 +263,7 @@ Once connected, your AI has access to all Wyrm tools. Try:
258
263
 
259
264
  ## MCP Tools Reference
260
265
 
261
- Wyrm exposes 38 tools via the Model Context Protocol:
266
+ Wyrm exposes a frozen 32-verb typed surface (137 tools callable) via the Model Context Protocol:
262
267
 
263
268
  ### Projects
264
269
 
@@ -480,15 +485,9 @@ Wyrm/
480
485
 
481
486
  ## Contributing
482
487
 
483
- Contributions are welcome! Here's how:
484
-
485
- 1. **Fork** the repository
486
- 2. **Create** a feature branch (`git checkout -b feat/amazing-feature`)
487
- 3. **Commit** your changes (`git commit -m 'feat: add amazing feature'`)
488
- 4. **Push** to the branch (`git push origin feat/amazing-feature`)
489
- 5. **Open** a Pull Request
488
+ Wyrm is a **proprietary repository** — free to use, but not open to external contributions. We do **not** accept forks or external pull requests.
490
489
 
491
- Please ensure tests pass (`npm test`) and the project builds (`npm run build`) before submitting.
490
+ Issues and bug reports are welcome: please open an issue or email ryan@ghosts.lk.
492
491
 
493
492
  ---
494
493
 
@@ -499,7 +498,7 @@ Please ensure tests pass (`npm test`) and the project builds (`npm run build`) b
499
498
  - **Optional encryption** — AES-256-GCM for sensitive context data.
500
499
  - **Audited** — Security audits documented in [SECURITY_AUDIT.md](SECURITY_AUDIT.md) and [SECURITY_AUDIT_V2.md](SECURITY_AUDIT_V2.md).
501
500
 
502
- Found a vulnerability? Please open an issue or email security@ghosts.lk.
501
+ Found a vulnerability? Please open an issue or email ryan@ghosts.lk.
503
502
 
504
503
  ---
505
504
 
@@ -508,9 +507,9 @@ Found a vulnerability? Please open an issue or email security@ghosts.lk.
508
507
  **Open standard + protected implementation:**
509
508
 
510
509
  - **The Wyrm Memory Protocol** ([`PROTOCOL.md`](../../PROTOCOL.md)) is an **open spec, freely implementable** by anyone (CC-BY-4.0) — build a WMP-compatible memory without touching Wyrm's code.
511
- - **This implementation** (`wyrm-mcp`) is **[AGPL-3.0-or-later](LICENSE)** — Copyright © 2024-2026 [Ghost Protocol (Pvt) Ltd](https://ghosts.lk).
510
+ - **This implementation** (`wyrm-mcp`) is **[Proprietary Freeware](LICENSE)** — free to use, all rights reserved. Copyright © 2024-2026 [Ghost Protocol (Pvt) Ltd](https://ghosts.lk).
512
511
 
513
- For a **commercial license** (embedding Wyrm in a closed product, or running it as a managed service without AGPL's source-sharing obligations), contact [ghosts.lk@proton.me](mailto:ghosts.lk@proton.me).
512
+ For a **commercial license** (embedding Wyrm in a closed product, or running it as a managed service), contact [ryan@ghosts.lk](mailto:ryan@ghosts.lk).
514
513
 
515
514
  ---
516
515
 
@@ -1 +1,59 @@
1
- import{getLicenseInfo as r,selfTestVerifier as n}from"./license.js";import{OFFICIAL_BUILD as e}from"./build-flags.js";const i=e||/^(1|true|yes|on)$/i.test(process.env.WYRM_REQUIRE_ACTIVATION??""),t=e?!n().ok:!1;if(t)try{console.error("Wyrm: integrity self-test FAILED \u2014 license verifier tampered; activation gate locked.")}catch{}function s(){return t?!1:!i||r().valid}function c(){return{content:[{type:"text",text:"\u{1F512} Wyrm requires a free account on this build.\n\nRun `wyrm login` in your terminal to sign in and activate (free). Your memory stays local \u2014 login just ties usage to an account so it can be managed.\n\nAlready logged in? Your activation may have expired \u2014 run `wyrm login` again to refresh."}],isError:!0}}export{i as REQUIRE_ACTIVATION,c as activationGateResult,s as activationSatisfied};
1
+ /**
2
+ * Activation gate for account-required builds.
3
+ *
4
+ * OFF by default in source — the test suite and local dev builds are unaffected.
5
+ * The OFFICIAL distribution bakes `WYRM_REQUIRE_ACTIVATION=1`, so the free tier
6
+ * needs a (free) account: `wyrm login` fetches a short-lived, account-bound signed
7
+ * license that's validated locally by license.ts. A suspended account can't
8
+ * refresh, so access lapses at expiry. Memory is local either way — login only
9
+ * ties usage to a revocable identity. (Wyrm is proprietary; see LICENSE.)
10
+ *
11
+ * @copyright 2026 Ghost Protocol (Pvt) Ltd.
12
+ * @license Proprietary — (c) 2026 Ghost Protocol (Pvt) Ltd. All rights reserved. See LICENSE.
13
+ */
14
+ import { getLicenseInfo, selfTestVerifier } from './license.js';
15
+ import { OFFICIAL_BUILD } from './build-flags.js';
16
+ /**
17
+ * Whether the account-required gate is enabled on this build. ON when this is the
18
+ * official published artifact (OFFICIAL_BUILD baked true at release), OR when the
19
+ * operator opts in via WYRM_REQUIRE_ACTIVATION. OFF in source + tests.
20
+ */
21
+ export const REQUIRE_ACTIVATION = OFFICIAL_BUILD || /^(1|true|yes|on)$/i.test(process.env.WYRM_REQUIRE_ACTIVATION ?? '');
22
+ /**
23
+ * Tamper-evidence: on the official build, verify at load that the license verifier
24
+ * still rejects a forged signature. If it doesn't, someone stubbed the verifier to
25
+ * bypass the gate — so we keep the gate CLOSED regardless of what getLicenseInfo()
26
+ * now claims. A determined forker can remove this too (patching the closed, minified dist) — a
27
+ * deterrent, not a guarantee.
28
+ */
29
+ const TAMPERED = OFFICIAL_BUILD ? !selfTestVerifier().ok : false;
30
+ if (TAMPERED) {
31
+ try {
32
+ console.error('Wyrm: integrity self-test FAILED — license verifier tampered; activation gate locked.');
33
+ }
34
+ catch { /* noop */ }
35
+ }
36
+ /**
37
+ * True when tool execution is permitted. Always true unless the build requires
38
+ * activation AND no valid (free or paid) account-bound license is loaded.
39
+ * Re-checked live so a mid-session `wyrm login` takes effect without a restart.
40
+ */
41
+ export function activationSatisfied() {
42
+ if (TAMPERED)
43
+ return false; // verifier subverted → never satisfy the gate
44
+ return !REQUIRE_ACTIVATION || getLicenseInfo().valid;
45
+ }
46
+ /** The MCP error result returned for any tool call while activation is unmet. */
47
+ export function activationGateResult() {
48
+ return {
49
+ content: [{
50
+ type: 'text',
51
+ text: '🔒 Wyrm requires a free account on this build.\n\n'
52
+ + 'Run `wyrm login` in your terminal to sign in and activate (free). '
53
+ + 'Your memory stays local — login just ties usage to an account so it can be managed.\n\n'
54
+ + 'Already logged in? Your activation may have expired — run `wyrm login` again to refresh.',
55
+ }],
56
+ isError: true,
57
+ };
58
+ }
59
+ //# sourceMappingURL=activation.js.map
@@ -1,6 +1,283 @@
1
- import{spawn as E}from"child_process";import{existsSync as l,readFileSync as g,writeFileSync as I,statSync as w,openSync as M,closeSync as h,renameSync as v,unlinkSync as f,mkdirSync as O}from"fs";import{homedir as R}from"os";import{join as d,dirname as S,resolve as k}from"path";import{fileURLToPath as b}from"url";const m=d(R(),".wyrm"),i=d(m,"wyrm-loop.pid"),u=d(m,"wyrm-loop.log"),_=d(m,"wyrm-loop.log.1"),D=1e6;function T(){l(m)||O(m,{recursive:!0})}function C(){try{l(u)&&w(u).size>D&&(l(_)&&f(_),v(u,_))}catch{}}function L(){try{const p=g(i,"utf-8").trim(),t=parseInt(p,10);return Number.isFinite(t)&&t>0?t:null}catch{return null}}function y(p){try{return process.kill(p,0),!0}catch{return!1}}function F(){try{const t=b(import.meta.url),r=[k(S(t),"wyrm-loop.js"),k(S(t),"..","dist","wyrm-loop.js")];for(const n of r)if(l(n))return n}catch{}const p=(process.env.PATH??"").split(":");for(const t of p){const r=d(t,"wyrm-loop");if(l(r))return r}return null}class A{db;constructor(t){this.db=t}status(){const t=L(),r=t!=null&&y(t);let n,a;try{if(l(i)){const s=w(i);n=s.mtime.toISOString(),a=Math.round((Date.now()-s.mtime.getTime())/1e3)}}catch{}let e;try{const s=this.db.prepare(`
1
+ /**
2
+ * Agent daemon process manager.
3
+ *
4
+ * Lets an AI client (Claude / Codex / Cursor / etc.) bootstrap, monitor,
5
+ * and tear down the `wyrm-loop` autonomous scheduler without the
6
+ * operator running shell commands. The MCP server can spawn the daemon
7
+ * as a detached background process, write a PID + log file under
8
+ * `~/.wyrm/`, and check liveness on demand.
9
+ *
10
+ * Files (all under `~/.wyrm/`):
11
+ * wyrm-loop.pid PID of the running daemon (single-line)
12
+ * wyrm-loop.log Stdout/stderr of the daemon (rotated at 1MB)
13
+ *
14
+ * Single-instance guarantee — if a PID file exists and the process is
15
+ * alive, `start()` refuses (no fork-bomb). `restart()` is provided as
16
+ * an explicit operation.
17
+ *
18
+ * @copyright 2026 Ghost Protocol (Pvt) Ltd.
19
+ * @license Proprietary — (c) 2026 Ghost Protocol (Pvt) Ltd. All rights reserved. See LICENSE.
20
+ */
21
+ import { spawn } from 'child_process';
22
+ import { existsSync, readFileSync, writeFileSync, statSync, openSync, closeSync, renameSync, unlinkSync, mkdirSync } from 'fs';
23
+ import { homedir } from 'os';
24
+ import { join, dirname, resolve } from 'path';
25
+ import { fileURLToPath } from 'url';
26
+ const WYRM_DIR = join(homedir(), '.wyrm');
27
+ const PID_FILE = join(WYRM_DIR, 'wyrm-loop.pid');
28
+ const LOG_FILE = join(WYRM_DIR, 'wyrm-loop.log');
29
+ const LOG_FILE_OLD = join(WYRM_DIR, 'wyrm-loop.log.1');
30
+ const MAX_LOG_BYTES = 1_000_000;
31
+ function ensureWyrmDir() {
32
+ if (!existsSync(WYRM_DIR))
33
+ mkdirSync(WYRM_DIR, { recursive: true });
34
+ }
35
+ function rotateLogIfLarge() {
36
+ try {
37
+ if (existsSync(LOG_FILE) && statSync(LOG_FILE).size > MAX_LOG_BYTES) {
38
+ if (existsSync(LOG_FILE_OLD))
39
+ unlinkSync(LOG_FILE_OLD);
40
+ renameSync(LOG_FILE, LOG_FILE_OLD);
41
+ }
42
+ }
43
+ catch { /* best-effort */ }
44
+ }
45
+ function readPid() {
46
+ try {
47
+ const raw = readFileSync(PID_FILE, 'utf-8').trim();
48
+ const pid = parseInt(raw, 10);
49
+ return Number.isFinite(pid) && pid > 0 ? pid : null;
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ function isProcessAlive(pid) {
56
+ try {
57
+ // signal 0 doesn't kill; just checks existence + permission
58
+ process.kill(pid, 0);
59
+ return true;
60
+ }
61
+ catch {
62
+ return false;
63
+ }
64
+ }
65
+ /** Find the bundled `wyrm-loop` script path. Resolves relative to this
66
+ * module so it works whether installed via npm, run from source, or
67
+ * invoked from a global symlink. */
68
+ function locateLoopBinary() {
69
+ // 1. import.meta.url → packages/mcp-server/dist/agent-daemon.js
70
+ try {
71
+ const here = fileURLToPath(import.meta.url);
72
+ const candidates = [
73
+ // installed alongside (dist/wyrm-loop.js)
74
+ resolve(dirname(here), 'wyrm-loop.js'),
75
+ // source layout
76
+ resolve(dirname(here), '..', 'dist', 'wyrm-loop.js'),
77
+ ];
78
+ for (const p of candidates) {
79
+ if (existsSync(p))
80
+ return p;
81
+ }
82
+ }
83
+ catch { /* fall through */ }
84
+ // 2. Look in PATH for the `wyrm-loop` binary (set up by `npm install -g`)
85
+ const pathDirs = (process.env.PATH ?? '').split(':');
86
+ for (const dir of pathDirs) {
87
+ const cand = join(dir, 'wyrm-loop');
88
+ if (existsSync(cand))
89
+ return cand;
90
+ }
91
+ return null;
92
+ }
93
+ export class AgentDaemon {
94
+ db;
95
+ constructor(db) {
96
+ this.db = db;
97
+ }
98
+ /** Current daemon status. Always safe to call. */
99
+ status() {
100
+ const pid = readPid();
101
+ const running = pid != null && isProcessAlive(pid);
102
+ let started_at;
103
+ let uptime_seconds;
104
+ try {
105
+ if (existsSync(PID_FILE)) {
106
+ const st = statSync(PID_FILE);
107
+ started_at = st.mtime.toISOString();
108
+ uptime_seconds = Math.round((Date.now() - st.mtime.getTime()) / 1000);
109
+ }
110
+ }
111
+ catch { /* best-effort */ }
112
+ // Read latest agent_actions row for "last action" summary
113
+ let last_action;
114
+ try {
115
+ const row = this.db.prepare(`
2
116
  SELECT actor, goal_id, action_kind, summary, result_status, ran_at
3
117
  FROM agent_actions ORDER BY id DESC LIMIT 1
4
- `).get();s&&(e={ran_at:s.ran_at,actor:s.actor,goal_id:s.goal_id,summary:`${s.action_kind}: ${s.summary}`.slice(0,200),result_status:s.result_status})}catch{}let o=0,c=0;try{o=this.db.prepare("SELECT COUNT(*) as c FROM goals WHERE status = 'active'").get().c,c=this.db.prepare("SELECT COALESCE(SUM(iterations_count), 0) as c FROM goals").get().c}catch{}return{running:r,pid:r?t:null,pid_file:i,log_file:u,started_at:r?n:void 0,uptime_seconds:r?a:void 0,last_action:e,active_goals:o,total_iterations:c}}start(t={}){T(),C();const r=this.status();if(r.running)return{ok:!0,pid:r.pid??void 0,status:r};if(l(i))try{f(i)}catch{}const n=F();if(!n)return{ok:!1,error:"Could not locate wyrm-loop binary. Run `npm install -g wyrm-mcp` or `npm run build` in packages/mcp-server."};const a=["--interval",String(t.interval_seconds??600)];t.max_steps&&a.push("--max-steps",String(t.max_steps)),t.project_path&&a.push("--project",t.project_path),t.verbose&&a.push("--verbose");let e;try{e=M(u,"a")}catch(c){return{ok:!1,error:`Could not open log file ${u}: ${c.message}`}}let o;try{o=E("node",[n,...a],{detached:!0,stdio:["ignore",e,e],env:{...process.env,WYRM_LOOP_LOG:t.verbose?"1":"0"}})}catch(c){return{ok:!1,error:`spawn failed: ${c.message}`}}if(!o.pid){try{h(e)}catch{}return{ok:!1,error:"spawn returned no PID"}}try{I(i,String(o.pid),"utf-8")}catch(c){try{process.kill(o.pid,"SIGTERM")}catch{}try{h(e)}catch{}return{ok:!1,error:`Could not write PID file: ${c.message}`}}try{h(e)}catch{}return o.unref(),{ok:!0,pid:o.pid,status:this.status()}}async stop(t={}){const r=L();if(r==null)return{ok:!0,was_running:!1};if(!y(r)){try{f(i)}catch{}return{ok:!0,was_running:!1,pid:r}}try{process.kill(r,"SIGTERM")}catch(e){return{ok:!1,was_running:!0,pid:r,error:`SIGTERM failed: ${e.message}`}}const n=Math.max(100,Math.min(t.grace_ms??3e3,3e4)),a=Date.now();for(;Date.now()-a<n&&y(r);)await new Promise(e=>{setTimeout(e,100)});if(y(r))try{process.kill(r,"SIGKILL")}catch{}try{f(i)}catch{}return{ok:!0,was_running:!0,pid:r}}async restart(t={}){return await this.stop({grace_ms:3e3}),this.start(t)}recentLog(t=40){try{return l(u)?g(u,"utf-8").split(`
5
- `).slice(-Math.max(1,Math.min(t,1e3))).join(`
6
- `):"(log file does not exist)"}catch(r){return`(could not read log: ${r.message})`}}}export{A as AgentDaemon};
118
+ `).get();
119
+ if (row)
120
+ last_action = {
121
+ ran_at: row.ran_at, actor: row.actor, goal_id: row.goal_id,
122
+ summary: `${row.action_kind}: ${row.summary}`.slice(0, 200),
123
+ result_status: row.result_status,
124
+ };
125
+ }
126
+ catch { /* table may not exist on pre-v5 DBs */ }
127
+ let active_goals = 0;
128
+ let total_iterations = 0;
129
+ try {
130
+ active_goals = this.db.prepare(`SELECT COUNT(*) as c FROM goals WHERE status = 'active'`).get().c;
131
+ total_iterations = this.db.prepare(`SELECT COALESCE(SUM(iterations_count), 0) as c FROM goals`).get().c;
132
+ }
133
+ catch { /* pre-v5 DB */ }
134
+ return {
135
+ running,
136
+ pid: running ? pid : null,
137
+ pid_file: PID_FILE,
138
+ log_file: LOG_FILE,
139
+ started_at: running ? started_at : undefined,
140
+ uptime_seconds: running ? uptime_seconds : undefined,
141
+ last_action,
142
+ active_goals,
143
+ total_iterations,
144
+ };
145
+ }
146
+ /** Start the daemon. No-op if already running. */
147
+ start(opts = {}) {
148
+ ensureWyrmDir();
149
+ rotateLogIfLarge();
150
+ const cur = this.status();
151
+ if (cur.running) {
152
+ return { ok: true, pid: cur.pid ?? undefined, status: cur };
153
+ }
154
+ // Clear stale PID file from a crashed prior run
155
+ if (existsSync(PID_FILE)) {
156
+ try {
157
+ unlinkSync(PID_FILE);
158
+ }
159
+ catch { /* ignore */ }
160
+ }
161
+ const binary = locateLoopBinary();
162
+ if (!binary) {
163
+ return { ok: false, error: 'Could not locate wyrm-loop binary. Run `npm install -g wyrm-mcp` or `npm run build` in packages/mcp-server.' };
164
+ }
165
+ const args = ['--interval', String(opts.interval_seconds ?? 600)];
166
+ if (opts.max_steps)
167
+ args.push('--max-steps', String(opts.max_steps));
168
+ if (opts.project_path)
169
+ args.push('--project', opts.project_path);
170
+ if (opts.verbose)
171
+ args.push('--verbose');
172
+ // Open the log file once, share fd with the child
173
+ let logFd;
174
+ try {
175
+ logFd = openSync(LOG_FILE, 'a');
176
+ }
177
+ catch (err) {
178
+ return { ok: false, error: `Could not open log file ${LOG_FILE}: ${err.message}` };
179
+ }
180
+ let child;
181
+ try {
182
+ child = spawn('node', [binary, ...args], {
183
+ detached: true,
184
+ stdio: ['ignore', logFd, logFd],
185
+ env: { ...process.env, WYRM_LOOP_LOG: opts.verbose ? '1' : '0' },
186
+ });
187
+ }
188
+ catch (err) {
189
+ return { ok: false, error: `spawn failed: ${err.message}` };
190
+ }
191
+ if (!child.pid) {
192
+ try {
193
+ closeSync(logFd);
194
+ }
195
+ catch { /* ignore */ }
196
+ return { ok: false, error: 'spawn returned no PID' };
197
+ }
198
+ try {
199
+ writeFileSync(PID_FILE, String(child.pid), 'utf-8');
200
+ }
201
+ catch (err) {
202
+ // Process is up but we can't track it — kill to keep state consistent
203
+ try {
204
+ process.kill(child.pid, 'SIGTERM');
205
+ }
206
+ catch { /* ignore */ }
207
+ try {
208
+ closeSync(logFd);
209
+ }
210
+ catch { /* ignore */ }
211
+ return { ok: false, error: `Could not write PID file: ${err.message}` };
212
+ }
213
+ // Close the parent's copy of the log fd — the child inherits its own
214
+ // dup via stdio. Without this, every successful spawn leaks one fd in
215
+ // the parent (the MCP server).
216
+ try {
217
+ closeSync(logFd);
218
+ }
219
+ catch { /* ignore */ }
220
+ // unref so this process doesn't wait on the child
221
+ child.unref();
222
+ // Brief settle delay so status() reflects the new state
223
+ return { ok: true, pid: child.pid, status: this.status() };
224
+ }
225
+ /** Stop the daemon. Sends SIGTERM, then SIGKILL after a grace period. */
226
+ async stop(opts = {}) {
227
+ const pid = readPid();
228
+ if (pid == null) {
229
+ return { ok: true, was_running: false };
230
+ }
231
+ if (!isProcessAlive(pid)) {
232
+ // Stale PID file
233
+ try {
234
+ unlinkSync(PID_FILE);
235
+ }
236
+ catch { /* ignore */ }
237
+ return { ok: true, was_running: false, pid };
238
+ }
239
+ try {
240
+ process.kill(pid, 'SIGTERM');
241
+ }
242
+ catch (err) {
243
+ return { ok: false, was_running: true, pid, error: `SIGTERM failed: ${err.message}` };
244
+ }
245
+ const grace = Math.max(100, Math.min(opts.grace_ms ?? 3000, 30_000));
246
+ const start = Date.now();
247
+ while (Date.now() - start < grace) {
248
+ if (!isProcessAlive(pid))
249
+ break;
250
+ await new Promise(r => { setTimeout(r, 100); });
251
+ }
252
+ if (isProcessAlive(pid)) {
253
+ try {
254
+ process.kill(pid, 'SIGKILL');
255
+ }
256
+ catch { /* may already be dead */ }
257
+ }
258
+ try {
259
+ unlinkSync(PID_FILE);
260
+ }
261
+ catch { /* ignore */ }
262
+ return { ok: true, was_running: true, pid };
263
+ }
264
+ /** Stop + Start in sequence. */
265
+ async restart(opts = {}) {
266
+ await this.stop({ grace_ms: 3000 });
267
+ return this.start(opts);
268
+ }
269
+ /** Read the last N lines of the daemon log. */
270
+ recentLog(lines = 40) {
271
+ try {
272
+ if (!existsSync(LOG_FILE))
273
+ return '(log file does not exist)';
274
+ const raw = readFileSync(LOG_FILE, 'utf-8');
275
+ const all = raw.split('\n');
276
+ return all.slice(-Math.max(1, Math.min(lines, 1000))).join('\n');
277
+ }
278
+ catch (err) {
279
+ return `(could not read log: ${err.message})`;
280
+ }
281
+ }
282
+ }
283
+ //# sourceMappingURL=agent-daemon.js.map