wyrm-mcp 9.1.2 → 9.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/BENCHMARKS.md +8 -4
- package/README.md +11 -1
- package/dist/autoconfig.js +3 -3
- package/dist/causality.js +13 -8
- package/dist/cli.js +25 -22
- package/dist/cloud/cli.js +3 -3
- package/dist/cloud/sync-daemon-entrypoint.js +2 -2
- package/dist/cloud/sync-daemon.js +1 -1
- package/dist/database.js +30 -27
- package/dist/events.js +6 -6
- package/dist/federation.js +10 -10
- package/dist/handlers/capture.js +60 -60
- package/dist/handlers/causality.js +8 -8
- package/dist/handlers/companion.js +7 -7
- package/dist/handlers/entity.js +1 -1
- package/dist/handlers/events.js +12 -12
- package/dist/handlers/failure.js +12 -12
- package/dist/handlers/goals.js +4 -4
- package/dist/handlers/intelligence.js +66 -66
- package/dist/handlers/mcpclient.js +1 -1
- package/dist/handlers/presence.js +3 -3
- package/dist/handlers/project-arg.js +1 -0
- package/dist/handlers/project.js +1 -1
- package/dist/handlers/quest.js +5 -3
- package/dist/handlers/recall.js +18 -18
- package/dist/handlers/registry.js +1 -1
- package/dist/handlers/review.js +3 -3
- package/dist/handlers/search.js +3 -3
- package/dist/handlers/session.js +24 -24
- package/dist/handlers/share.js +5 -5
- package/dist/handlers/shims.js +1 -1
- package/dist/handlers/thread.js +2 -2
- package/dist/http-auth.js +1 -1
- package/dist/http-fast.js +15 -15
- package/dist/index.js +2 -2
- package/dist/intelligence.js +25 -22
- package/dist/logger.js +2 -2
- package/dist/maintenance.js +2 -2
- package/dist/memory-artifacts.js +27 -26
- package/dist/migrations.js +5 -5
- package/dist/providers/embedding-provider.js +1 -1
- package/dist/receipt.js +1 -1
- package/dist/rehydration.js +24 -9
- package/dist/render.js +3 -3
- package/dist/rerank.js +1 -1
- package/dist/security.js +1 -1
- package/dist/setup.js +2 -3
- package/dist/stale-servers.js +2 -0
- package/dist/stdio-lifecycle.js +1 -0
- package/dist/tool-analytics.js +4 -4
- package/dist/tool-manifest-v2.json +1 -1
- package/dist/tool-manifest.json +1 -1
- package/dist/ui-dashboard.js +9 -8
- package/dist/validate.js +1 -1
- package/dist/vault.js +1 -1
- package/dist/vectors.js +3 -3
- package/dist/wyrm-cli.js +107 -142
- package/dist/wyrm-manifest.json +1 -1
- package/dist/wyrm-ui.js +14 -7
- package/package.json +5 -3
- package/scripts/hooks/wyrm-citation-audit.mjs +155 -46
- package/scripts/hooks/wyrm-prompt-context.mjs +300 -0
- package/scripts/hooks/wyrm-run-auto.mjs +29 -5
- package/scripts/hooks/wyrm-session-rehydrate.mjs +142 -24
- package/skills/wyrm-nvidia-nim/SKILL.md +26 -17
package/BENCHMARKS.md
CHANGED
|
@@ -61,16 +61,20 @@ Retrieval recall is the floor. Two more, all reproducible, all local (added 2026
|
|
|
61
61
|
|
|
62
62
|
### Negative learning — the firewall benchmark (the race we own)
|
|
63
63
|
|
|
64
|
-
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
|
|
64
|
+
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. Measured on wyrm-mcp 9.1.2, 2026-09-12 (`bench/firewall-receipt.json`):
|
|
65
65
|
|
|
66
66
|
| probe | result |
|
|
67
67
|
|---|---|
|
|
68
68
|
| same action re-attempted (the guard's real input) | **recall 100%** (16/16) |
|
|
69
|
+
| reworded restatement | **recall 100%** (16/16) |
|
|
69
70
|
| novel actions | **precision 100%** · specificity 100% (0 false blocks of 16) |
|
|
70
|
-
|
|
|
71
|
-
|
|
|
71
|
+
| confidence separation | 0.86 |
|
|
72
|
+
| staleness oracle | passes |
|
|
73
|
+
| `checkVerdict` latency | p50 2.7 ms · p95 6.1 ms |
|
|
72
74
|
|
|
73
|
-
|
|
75
|
+
The reworded tier used to sit at 12.5% (8.5.3), because the fuzzy probe was a conjunctive-AND FTS kept precision-first by design. Target normalization (canonical command matching, flag order and `=` form folded, positionals kept in order) closed that gap without giving up a single false block. Run: `node bench/negative-learning.mjs`.
|
|
76
|
+
|
|
77
|
+
The end-to-end version of the same question, a blind agent working real tickets with and without the firewall in front of its actions, is the agent A/B: repeated-failure rate 38.9% (14/36) without the firewall to 8.3% (3/36) with it, 11 blocks, relative reduction 78.6% (bootstrap 95% CI 45.5% to 100%, n=36 per arm, 3 repetitions). Method, per-scenario table and the stated limits: `docs/firewall-receipt.md`.
|
|
74
78
|
|
|
75
79
|
### Embedding-model sweep
|
|
76
80
|
|
package/README.md
CHANGED
|
@@ -35,6 +35,8 @@ npm install -g wyrm-mcp # install
|
|
|
35
35
|
wyrm-setup # wire it into your AI clients, then restart them
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
+
> **If `npm install -g` fails with EACCES**, npm's global prefix is a directory you cannot write (often `/usr`). Install under a prefix you own instead, and put its `bin` on your PATH: `npm install -g --prefix ~/.npm-global wyrm-mcp`, then `export PATH="$HOME/.npm-global/bin:$PATH"`. `wyrm update` later updates that same install.
|
|
39
|
+
|
|
38
40
|
> **On npm v12+**, npm denies dependency install scripts by default, which skips `better-sqlite3`'s native build — the install *succeeds* but `wyrm` then fails with *"Could not locate the bindings file"*. Install with the build allow-listed instead: `npm install -g wyrm-mcp --allow-scripts=wyrm-mcp,better-sqlite3` (`wyrm update` already does this for you). See [TROUBLESHOOTING.md](https://github.com/Ghosts-Protocol-Pvt-Ltd/wyrm-mcp/blob/HEAD/TROUBLESHOOTING.md).
|
|
39
41
|
|
|
40
42
|
Then, from inside your client, ask it to call `wyrm_capabilities` to confirm the connection. The everyday loop is four steps the agent runs on its own once the habit sets in:
|
|
@@ -50,6 +52,14 @@ capture → store durable facts, lessons, and tasks as you go
|
|
|
50
52
|
|
|
51
53
|
Every number Wyrm publishes comes from a benchmark committed to the source, reproducible on your own data. The negative-learning firewall and the recall lift are the two that matter most, and both are covered below.
|
|
52
54
|
|
|
55
|
+
### The Firewall Receipt
|
|
56
|
+
|
|
57
|
+
The receipt is the measured proof of one claim: when a failure is on record, the firewall blocks the repeat, stays silent on novel actions, and drops the block once the anchored source drifts, deterministically and with no model in the loop. On wyrm-mcp 9.1.2, measured 2026-09-12, the deterministic bench scores recall 100% (32/32) on same-action and reworded repeats with precision 100% (0 false blocks of 16), and in the blind agent A/B the repeated-failure rate falls from 38.9% (14/36) to 8.3% (3/36), a 78.6% relative reduction with a bootstrap 95% CI of 45.5% to 100% (n=36 per arm). The method, the per-scenario table and the two limits the numbers carry are in [docs/firewall-receipt.md](docs/firewall-receipt.md); the deterministic receipt is regenerated on every push in CI as the artifact `firewall-receipt-node22.x` ([workflow](https://github.com/Ghosts-Protocol-Pvt-Ltd/wyrm-mcp/actions/workflows/ci.yml)).
|
|
58
|
+
|
|
59
|
+
The failure firewall in twenty seconds: a failure is on record, the agent proposes the same deploy, and the PreToolUse hook refuses it with the recorded reason before the command runs. A variant with an added flag gets an advisory, not a block, which is the honest edge of the deterministic match. Every line in the clip is real hook output.
|
|
60
|
+
|
|
61
|
+

|
|
62
|
+
|
|
53
63
|
## Why Wyrm
|
|
54
64
|
|
|
55
65
|
### It remembers what failed, not just what worked
|
|
@@ -78,7 +88,7 @@ Every artifact is tagged with where it came from: you, an agent, an import, or a
|
|
|
78
88
|
|
|
79
89
|
## NVIDIA NIM retrieval (optional)
|
|
80
90
|
|
|
81
|
-
Local vectors are on by default. NIM is the further step up, for embeddings and reranking, when accuracy is worth a hosted call. On
|
|
91
|
+
Local vectors are on by default. NIM is the further step up, for embeddings and reranking, when accuracy is worth a hosted call. On the LoCoMo retrieval benchmark committed in the repo (2 conversations, k=10, measured September 2026), the default NIM embedding model `nvidia/nemotron-3-embed-1b` reached recall@1 39.9% and recall@10 76.7%; adding the NIM reranker (`nvidia/llama-nemotron-rerank-vl-1b-v2`) raised recall@1 to 55.5% across the same 301 questions, at about one extra second per query. Figures published here earlier were measured on models NVIDIA retired on 25 August 2026, and have been withdrawn. It is an explicit opt-in, off by default, and the egress is disclosed on every call.
|
|
82
92
|
|
|
83
93
|
The guided path is `wyrm upgrade`: a free API key, masked key entry, a live call to validate the key before anything is written, and an optional one-time reindex of existing memories on the new tier. To configure it by hand instead:
|
|
84
94
|
|
package/dist/autoconfig.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{existsSync as f,readFileSync as y,writeFileSync as p,mkdirSync as P,copyFileSync as X,chmodSync as C}from"fs";import{homedir as h,platform as b}from"os";import{join as a,dirname as v,resolve as ee}from"path";import{fileURLToPath as _}from"url";import{spawnSync as w}from"child_process";function te(){const e=h(),t=b(),o=t==="darwin"?a(e,"Library","Application Support","Code","User"):t==="win32"?a(e,"AppData","Roaming","Code","User"):a(e,".config","Code","User"),n=t==="darwin"?a(e,"Library","Application Support","Code - Insiders","User"):t==="win32"?a(e,"AppData","Roaming","Code - Insiders","User"):a(e,".config","Code - Insiders","User"),s=t==="darwin"?a(e,"Library","Application Support","Claude"):t==="win32"?a(e,"AppData","Roaming","Claude"):a(e,".config","claude"),r=t==="darwin"?a(e,".cursor"):t==="win32"?a(e,".cursor"):a(e,".cursor"),i=t==="darwin"?a(e,".codeium","windsurf"):t==="win32"?a(e,".codeium","windsurf"):a(e,".codeium","windsurf"),c=t==="darwin"?a(e,".config","zed"):t==="win32"?a(e,"AppData","Roaming","Zed"):a(e,".config","zed"),u=a(e,".continue");return[{id:"vscode-copilot",name:"VS Code (Copilot)",icon:"\u{1F4BB}",configPath:a(o,"settings.json"),configFormat:"vscode",mcpKey:"mcp.servers",detected:!1,configured:!1},{id:"vscode-insiders",name:"VS Code Insiders",icon:"\u{1F7E2}",configPath:a(n,"settings.json"),configFormat:"vscode",mcpKey:"mcp.servers",detected:!1,configured:!1},{id:"claude-desktop",name:"Claude Desktop",icon:"\u{1F916}",configPath:a(s,"claude_desktop_config.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"claude-code",name:"Claude Code",icon:"\u2733\uFE0F",configPath:a(e,".claude.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"cursor",name:"Cursor",icon:"\u{1F4D0}",configPath:a(r,"mcp.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"windsurf",name:"Windsurf",icon:"\u{1F3C4}",configPath:a(i,"mcp_config.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"zed",name:"Zed",icon:"\u26A1",configPath:a(c,"settings.json"),configFormat:"zed",mcpKey:"context_servers",detected:!1,configured:!1},{id:"continue",name:"Continue",icon:"\u{1F504}",configPath:a(u,"config.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1}]}function oe(e){try{const t=b()==="win32"?"where":"which",o=w(t,[e],{encoding:"utf-8",timeout:5e3});return o.status===0&&!!o.stdout&&o.stdout.trim().length>0}catch{return!1}}function A(){const e=te();for(const t of e){if(t.id==="claude-code")t.detected=f(t.configPath)||oe("claude");else{const o=v(t.configPath);t.detected=f(o)}if(t.detected&&f(t.configPath))try{const o=y(t.configPath,"utf-8"),n=$(o);t.configured=re(n,t)}catch{t.configured=!1}t.detected&&(t.version=ne(t))}return e}function ne(e){try{switch(e.id){case"vscode-copilot":case"vscode-insiders":{const t=e.id==="vscode-insiders"?"code-insiders":"code",o=w(t,["--version"],{encoding:"utf-8",timeout:5e3});if(o.stdout)return o.stdout.split(`
|
|
1
|
+
import{existsSync as f,readFileSync as y,writeFileSync as p,mkdirSync as P,copyFileSync as X,chmodSync as C}from"fs";import{homedir as h,platform as b}from"os";import{join as a,dirname as v,resolve as ee}from"path";import{fileURLToPath as _}from"url";import{spawnSync as w}from"child_process";function te(){const e=h(),t=b(),o=t==="darwin"?a(e,"Library","Application Support","Code","User"):t==="win32"?a(e,"AppData","Roaming","Code","User"):a(e,".config","Code","User"),n=t==="darwin"?a(e,"Library","Application Support","Code - Insiders","User"):t==="win32"?a(e,"AppData","Roaming","Code - Insiders","User"):a(e,".config","Code - Insiders","User"),s=t==="darwin"?a(e,"Library","Application Support","Claude"):t==="win32"?a(e,"AppData","Roaming","Claude"):a(e,".config","claude"),r=t==="darwin"?a(e,".cursor"):t==="win32"?a(e,".cursor"):a(e,".cursor"),i=t==="darwin"?a(e,".codeium","windsurf"):t==="win32"?a(e,".codeium","windsurf"):a(e,".codeium","windsurf"),c=t==="darwin"?a(e,".config","zed"):t==="win32"?a(e,"AppData","Roaming","Zed"):a(e,".config","zed"),u=a(e,".continue");return[{id:"vscode-copilot",name:"VS Code (Copilot)",icon:"\u{1F4BB}",configPath:a(o,"settings.json"),configFormat:"vscode",mcpKey:"mcp.servers",detected:!1,configured:!1},{id:"vscode-insiders",name:"VS Code Insiders",icon:"\u{1F7E2}",configPath:a(n,"settings.json"),configFormat:"vscode",mcpKey:"mcp.servers",detected:!1,configured:!1},{id:"claude-desktop",name:"Claude Desktop",icon:"\u{1F916}",configPath:a(s,"claude_desktop_config.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"claude-code",name:"Claude Code",icon:"\u2733\uFE0F",configPath:a(e,".claude.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"cursor",name:"Cursor",icon:"\u{1F4D0}",configPath:a(r,"mcp.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"windsurf",name:"Windsurf",icon:"\u{1F3C4}",configPath:a(i,"mcp_config.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1},{id:"zed",name:"Zed",icon:"\u26A1",configPath:a(c,"settings.json"),configFormat:"zed",mcpKey:"context_servers",detected:!1,configured:!1},{id:"continue",name:"Continue",icon:"\u{1F504}",configPath:a(u,"config.json"),configFormat:"mcp-json",mcpKey:"mcpServers",detected:!1,configured:!1}]}function oe(e){try{const t=b()==="win32"?"where":"which",o=w(t,[e],{encoding:"utf-8",timeout:5e3});return o.status===0&&!!o.stdout&&o.stdout.trim().length>0}catch{return!1}}function A(){const e=te();for(const t of e){if(t.id==="claude-code")t.detected=f(a(v(t.configPath),".claude"))||oe("claude");else{const o=v(t.configPath);t.detected=f(o)}if(t.detected&&f(t.configPath))try{const o=y(t.configPath,"utf-8"),n=$(o);t.configured=re(n,t)}catch{t.configured=!1}t.detected&&(t.version=ne(t))}return e}function ne(e){try{switch(e.id){case"vscode-copilot":case"vscode-insiders":{const t=e.id==="vscode-insiders"?"code-insiders":"code",o=w(t,["--version"],{encoding:"utf-8",timeout:5e3});if(o.stdout)return o.stdout.split(`
|
|
2
2
|
`)[0];break}case"cursor":{const t=w("cursor",["--version"],{encoding:"utf-8",timeout:5e3});if(t.stdout)return t.stdout.split(`
|
|
3
3
|
`)[0];break}case"claude-code":{const t=w("claude",["--version"],{encoding:"utf-8",timeout:5e3});if(t.stdout)return t.stdout.trim().split(`
|
|
4
4
|
`)[0];break}}}catch{}}function re(e,t){switch(t.configFormat){case"vscode":return e.mcp?.servers?.wyrm!==void 0;case"mcp-json":return e[t.mcpKey]?.wyrm!==void 0;case"zed":return e[t.mcpKey]?.wyrm!==void 0;default:return!1}}function M(){try{const n=w("which",["wyrm-mcp"],{encoding:"utf-8",timeout:5e3});if(n.stdout?.trim())return n.stdout.trim()}catch{}try{const s=w("npm",["root","-g"],{encoding:"utf-8",timeout:5e3}).stdout?.trim();if(s){const r=a(s,"wyrm-mcp","dist","index.js");if(f(r))return r}}catch{}const e=ee(__dirname,"index.js");if(f(e))return e;const t=a(h(),".wyrm","node_modules","wyrm-mcp","dist","index.js");if(f(t))return t;const o=[a(h(),"Git Projects","Wyrm","packages","mcp-server","dist","index.js"),a(h(),"projects","Wyrm","packages","mcp-server","dist","index.js"),a(h(),"dev","Wyrm","packages","mcp-server","dist","index.js")];for(const n of o)if(f(n))return n;return"wyrm-mcp"}function D(){return a(h(),".wyrm","wyrm.db")}function je(e="mcp-json",t){const o=t?.serverPath??M(),n=t?.dbPath??D(),s=o==="wyrm-mcp",r={command:s?"npx":"node",args:s?["wyrm-mcp"]:[o],env:{WYRM_DB_PATH:n}};switch(e){case"stdio":return r;case"vscode":return{mcp:{servers:{wyrm:r}}};default:return{mcpServers:{wyrm:r}}}}function se(e,t){const o=t.serverPath,n=o==="wyrm-mcp",s=o.endsWith(".js");switch(e.configFormat){case"vscode":return{command:n?"npx":"node",args:n?["wyrm-mcp"]:[o],env:{WYRM_DB_PATH:t.dbPath}};case"mcp-json":return{command:n?"npx":"node",args:n?["wyrm-mcp"]:[o],env:{WYRM_DB_PATH:t.dbPath}};case"zed":return{command:n?"npx":"node",args:n?["wyrm-mcp"]:[o],env:{WYRM_DB_PATH:t.dbPath}};default:return{}}}function ie(e,t){if(!e||typeof e!="object"||Array.isArray(e))return{entry:t,preservedLauncher:!1};const o=e,n=o.env&&typeof o.env=="object"&&!Array.isArray(o.env)?o.env:{},s=t.env&&typeof t.env=="object"&&!Array.isArray(t.env)?t.env:{};if(o.command===t.command&&JSON.stringify(o.args??null)===JSON.stringify(t.args??null))return{entry:{...t,env:{...s,...n}},preservedLauncher:!1};const i={...n};for(const[c,u]of Object.entries(s))c in i||(i[c]=u);return{entry:{...o,env:i},preservedLauncher:!0}}function H(e,t){if(!e.detected)return{client:e,action:"skipped",message:`${e.name} not detected`};try{const o=v(e.configPath);f(o)||P(o,{recursive:!0});let n={},s=!1;if(f(e.configPath))try{const d=y(e.configPath,"utf-8");n=$(d),s=!0}catch{n={}}let r;if(s){r=`${e.configPath}.wyrm-backup`,p(r,y(e.configPath),{mode:384});try{C(r,384)}catch{}}const i=se(e,t);let c=!1;const u=(d,l)=>{const g=ie(d.wyrm,l);return d.wyrm=g.entry,g.preservedLauncher};switch(e.configFormat){case"vscode":{n.mcp||(n.mcp={});const d=n.mcp;d.servers||(d.servers={});const l=d.servers;c=u(l,i)||c;break}case"mcp-json":{n[e.mcpKey]||(n[e.mcpKey]={});const d=n[e.mcpKey];c=u(d,i)||c;break}case"zed":{n[e.mcpKey]||(n[e.mcpKey]={});const d=n[e.mcpKey];c=u(d,i)||c;break}}p(e.configPath,JSON.stringify(n,null,2)+`
|
|
5
5
|
`,"utf-8");const m=e.configured?"updated":"configured";return e.configured=!0,{client:e,action:m,message:`${e.name} ${m==="configured"?"configured":"updated"} successfully`+(c?" (kept your custom launch command; only missing env was added)":""),backup:r}}catch(o){return{client:e,action:"failed",message:`Failed to configure ${e.name}: ${o}`}}}function Ce(e,t){try{if(!f(e.configPath))return{client:e,action:"skipped",message:"No config file"};const o=y(e.configPath,"utf-8");let n;try{n=$(o)}catch{return{client:e,action:"failed",message:"Config file is not valid JSON; refusing to touch it"}}const r=(e.configFormat==="vscode"?n.mcp?.servers:n[e.mcpKey])?.wyrm;if(!r)return{client:e,action:"skipped",message:"Wyrm not configured in this client"};const i=`${e.configPath}.wyrm-backup`;p(i,o,{encoding:"utf-8",mode:384});try{C(i,384)}catch{}return r.env={...r.env,...t},p(e.configPath,JSON.stringify(n,null,2)+`
|
|
6
6
|
`,"utf-8"),{client:e,action:"updated",message:`env: ${Object.keys(t).join(", ")}`,backup:i}}catch(o){return{client:e,action:"failed",message:String(o)}}}function ce(e){if(!e.detected||!e.configured)return{client:e,action:"skipped",message:`${e.name} not configured`};try{if(!f(e.configPath))return{client:e,action:"skipped",message:`${e.name} config not found`};const t=y(e.configPath,"utf-8"),o=$(t),n=`${e.configPath}.wyrm-backup`;p(n,t,{mode:384});try{C(n,384)}catch{}switch(e.configFormat){case"vscode":{const r=o.mcp?.servers;r&&delete r.wyrm;break}case"mcp-json":case"zed":{const s=o[e.mcpKey];s&&delete s.wyrm;break}}return p(e.configPath,JSON.stringify(o,null,2)+`
|
|
7
|
-
`,"utf-8"),e.configured=!1,{client:e,action:"configured",message:`Removed Wyrm from ${e.name}`,backup:n}}catch(t){return{client:e,action:"failed",message:`Failed to remove from ${e.name}: ${t}`}}}function O(){return{id:"claude-code-hooks",name:"Claude Code (auto-memory)",icon:"\u{1FA9D}",configPath:a(h(),".claude","settings.json"),configFormat:"mcp-json",mcpKey:"",detected:!0,configured:!1}}const J=[{script:"wyrm-session-capture.mjs",events:["SessionEnd","PreCompact"]},{script:"wyrm-session-rehydrate.mjs",events:["SessionStart"]},{script:"wyrm-session-prune.mjs",events:["SessionEnd"]},{script:"wyrm-tool-call-trace.mjs",events:["PostToolUse"]},{script:"wyrm-run-auto.mjs",events:["SessionStart",{event:"PreToolUse",matcher:"Task"},"SessionEnd"]},{script:"wyrm-citation-audit.mjs",events:["Stop"]}];function ae(){const e=a(h(),".claude");if(!f(e))return null;const t=O();try{const o=a(e,"hooks");f(o)||P(o,{recursive:!0});const n=v(_(import.meta.url)),s=a(n,"..","scripts","hooks"),r=t.configPath;let i={};if(f(r))try{i=JSON.parse(y(r,"utf-8"))}catch{i={}}const c=i.hooks??{};let u=!1;const m=[];for(const l of J){const g=a(s,l.script);if(!f(g)){m.push(l.script);continue}const N=a(o,l.script);X(g,N);try{C(N,493)}catch{}const T=`node ${N}`;for(const S of l.events){const W=typeof S=="string"?S:S.event,B=typeof S=="string"?void 0:S.matcher,x=Array.isArray(c[W])?c[W]:[];if(!x.some(j=>Array.isArray(j.hooks)&&j.hooks.some(Z=>Z.command===T))){const j=B?{matcher:B,hooks:[{type:"command",command:T,timeout:30}]}:{hooks:[{type:"command",command:T,timeout:30}]};x.push(j),u=!0}c[W]=x}}i.hooks=c,p(r,JSON.stringify(i,null,2)+`
|
|
7
|
+
`,"utf-8"),e.configured=!1,{client:e,action:"configured",message:`Removed Wyrm from ${e.name}`,backup:n}}catch(t){return{client:e,action:"failed",message:`Failed to remove from ${e.name}: ${t}`}}}function O(){return{id:"claude-code-hooks",name:"Claude Code (auto-memory)",icon:"\u{1FA9D}",configPath:a(h(),".claude","settings.json"),configFormat:"mcp-json",mcpKey:"",detected:!0,configured:!1}}const J=[{script:"wyrm-session-capture.mjs",events:["SessionEnd","PreCompact"]},{script:"wyrm-session-rehydrate.mjs",events:["SessionStart"]},{script:"wyrm-session-prune.mjs",events:["SessionEnd"]},{script:"wyrm-tool-call-trace.mjs",events:["PostToolUse"]},{script:"wyrm-run-auto.mjs",events:["SessionStart",{event:"PreToolUse",matcher:"Task"},"SessionEnd"]},{script:"wyrm-citation-audit.mjs",events:["Stop"]},{script:"wyrm-prompt-context.mjs",events:["UserPromptSubmit"]}];function ae(){const e=a(h(),".claude");if(!f(e))return null;const t=O();try{const o=a(e,"hooks");f(o)||P(o,{recursive:!0});const n=v(_(import.meta.url)),s=a(n,"..","scripts","hooks"),r=t.configPath;let i={};if(f(r))try{i=JSON.parse(y(r,"utf-8"))}catch{i={}}const c=i.hooks??{};let u=!1;const m=[];for(const l of J){const g=a(s,l.script);if(!f(g)){m.push(l.script);continue}const N=a(o,l.script);X(g,N);try{C(N,493)}catch{}const T=`node ${N}`;for(const S of l.events){const W=typeof S=="string"?S:S.event,B=typeof S=="string"?void 0:S.matcher,x=Array.isArray(c[W])?c[W]:[];if(!x.some(j=>Array.isArray(j.hooks)&&j.hooks.some(Z=>Z.command===T))){const j=B?{matcher:B,hooks:[{type:"command",command:T,timeout:30}]}:{hooks:[{type:"command",command:T,timeout:30}]};x.push(j),u=!0}c[W]=x}}i.hooks=c,p(r,JSON.stringify(i,null,2)+`
|
|
8
8
|
`,"utf-8"),t.configured=!0;const d=m.length?` (missing from package: ${m.join(", ")})`:"";return{client:t,action:u?"configured":"skipped",message:(u?"auto-memory hooks installed":"already installed")+d}}catch(o){return{client:t,action:"failed",message:o instanceof Error?o.message:String(o)}}}function _e(){const e=a(h(),".claude");if(!f(e))return null;const t=O();try{const o=v(_(import.meta.url)),n=`node ${a(o,"wyrm-statusline.js")}`,s=t.configPath;let r={};if(f(s))try{r=JSON.parse(y(s,"utf-8"))}catch{r={}}const i=r.statusLine;if(i?.command&&!/wyrm-statusline/.test(i.command))return{client:t,action:"skipped",message:`a non-Wyrm statusLine is already set (${i.command}); not overwriting`};const c=i?.command===n;return r.statusLine={type:"command",command:n,padding:0},p(s,JSON.stringify(r,null,2)+`
|
|
9
9
|
`,"utf-8"),{client:t,action:c?"skipped":"configured",message:c?"buddy statusline already installed":"Wyrm buddy statusline installed \u2014 persistent in the Claude Code TUI"}}catch(o){return{client:t,action:"failed",message:o instanceof Error?o.message:String(o)}}}function Oe(){const e=a(h(),".claude","settings.json");if(!f(e))return null;const t=O();try{const o=JSON.parse(y(e,"utf-8")),n=o.statusLine;return n?.command&&/wyrm-statusline/.test(n.command)?(delete o.statusLine,p(e,JSON.stringify(o,null,2)+`
|
|
10
10
|
`,"utf-8"),{client:t,action:"configured",message:"Wyrm statusline removed"}):{client:t,action:"skipped",message:"no Wyrm statusline set"}}catch(o){return{client:t,action:"failed",message:o instanceof Error?o.message:String(o)}}}function ue(){const e=a(h(),".claude","settings.json");if(!f(e))return null;const t=O();try{const o=JSON.parse(y(e,"utf-8")),n=a(h(),".claude","hooks"),s=new Set(J.map(c=>`node ${a(n,c.script)}`)),r=new Set(J.flatMap(c=>c.events.map(u=>typeof u=="string"?u:u.event))),i=o.hooks;if(i){for(const c of r)Array.isArray(i[c])&&(i[c]=i[c].map(u=>({...u,hooks:Array.isArray(u.hooks)?u.hooks.filter(m=>!s.has(m.command??"")):u.hooks})).filter(u=>!Array.isArray(u.hooks)||u.hooks.length>0),i[c].length===0&&delete i[c]);Object.keys(i).length===0&&delete o.hooks}return p(e,JSON.stringify(o,null,2)+`
|
|
@@ -14,7 +14,7 @@ import{existsSync as f,readFileSync as y,writeFileSync as p,mkdirSync as P,copyF
|
|
|
14
14
|
`,"utf-8"),{client:o,action:"configured",message:"failure-firewall hooks removed"}):{client:o,action:"skipped",message:"no wyrm-guard hooks installed"}}catch(n){return{client:o,action:"failed",message:n instanceof Error?n.message:String(n)}}}function Ee(e={}){const t=k(e),o=[];try{const s=JSON.parse(y(t,"utf-8")).hooks??{};for(const r of Object.values(s))if(Array.isArray(r))for(const i of r)for(const c of i?.hooks??[]){const u=c?.command;u&&I.test(u)&&o.push(u)}}catch{}return{settingsPath:t,installed:o.length>0,commands:o}}const L=/wyrm-memo/,pe=[{event:"PreToolUse",matcher:"Read"},{event:"PreToolUse",matcher:"Bash"},{event:"PostToolUse",matcher:"Read"},{event:"PostToolUse",matcher:"Bash"}];function Y(e){return{id:"claude-code-memo",name:"Claude Code (token firewall)",icon:"",configPath:e,configFormat:"mcp-json",mcpKey:"",detected:!0,configured:!1}}function he(){const e=v(_(import.meta.url)),t=a(e,"wyrm-memo.js");if(f(t))return`node ${E(t)}`;try{const o=b()==="win32"?"where":"which",s=w(o,["wyrm-memo"],{encoding:"utf-8",timeout:5e3}).stdout?.trim().split(`
|
|
15
15
|
`)[0]?.trim();if(s)return E(s)}catch{}return null}function ge(e={}){const t=k(e),o=!!(e.settingsPath??process.env.CLAUDE_SETTINGS),n=Y(t);if(!o&&!f(a(h(),".claude")))return{client:n,action:"skipped",message:"token firewall: ~/.claude not found on this machine (needs the Claude Code CLI). Not armed. Install Claude Code then re-run `wyrm memo`"};try{const s=e.memoCommand??he();if(!s)return{client:n,action:"skipped",message:"wyrm-memo bin not found (npm i -g wyrm-mcp, or build dist/). Token-firewall hooks not installed"};P(v(t),{recursive:!0});let r={};if(f(t))try{const d=JSON.parse(y(t,"utf-8"));if(typeof d!="object"||d===null||Array.isArray(d))throw new Error("not an object");r=d}catch{return{client:n,action:"failed",message:`${t} is not valid JSON \u2014 refusing to overwrite it (fix or remove the file, then re-run)`}}const i=r.hooks;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))return{client:n,action:"failed",message:`${t} "hooks" has an unexpected shape (not a plain object) \u2014 refusing to modify`};for(const d of["PreToolUse","PostToolUse"]){const l=i?.[d];if(l!==void 0&&!Array.isArray(l))return{client:n,action:"failed",message:`${t} hooks.${d} has an unexpected shape (not an array) \u2014 refusing to modify`}}const c=JSON.stringify(r);U(r,L);const u=r.hooks??{};for(const{event:d,matcher:l}of pe){const g=Array.isArray(u[d])?u[d]:[];g.push({matcher:l,hooks:[{type:"command",command:s,timeout:G}]}),u[d]=g}r.hooks=u;const m=JSON.stringify(r)!==c;return m&&p(t,JSON.stringify(r,null,2)+`
|
|
16
16
|
`,"utf-8"),n.configured=!0,{client:n,action:m?"configured":"skipped",message:m?"token-firewall hooks installed (PreToolUse + PostToolUse: Read, Bash). Mode: observe (set WYRM_MEMO_MODE=warn to hand maps back)":"token-firewall hooks already installed"}}catch(s){return{client:n,action:"failed",message:s instanceof Error?s.message:String(s)}}}function $e(e={}){const t=k(e);if(!f(t))return null;const o=Y(t);try{let n;try{const r=JSON.parse(y(t,"utf-8"));if(typeof r!="object"||r===null||Array.isArray(r))throw new Error("not an object");n=r}catch{return{client:o,action:"failed",message:`${t} is not valid JSON \u2014 not touching it`}}return U(n,L)?(p(t,JSON.stringify(n,null,2)+`
|
|
17
|
-
`,"utf-8"),{client:o,action:"configured",message:"token-firewall hooks removed"}):{client:o,action:"skipped",message:"no wyrm-memo hooks installed"}}catch(n){return{client:o,action:"failed",message:n instanceof Error?n.message:String(n)}}}function Ne(e={}){const t=k(e),o=[];try{const s=JSON.parse(y(t,"utf-8")).hooks??{};for(const r of Object.values(s))if(Array.isArray(r))for(const i of r)for(const c of i?.hooks??[]){const u=c?.command;u&&L.test(u)&&o.push(u)}}catch{}return{settingsPath:t,installed:o.length>0,commands:o}}function ye(e){const t={serverPath:e?.serverPath||M(),dbPath:e?.dbPath||D(),httpPort:e?.httpPort},o=a(h(),".wyrm");f(o)||P(o,{recursive:!0})
|
|
17
|
+
`,"utf-8"),{client:o,action:"configured",message:"token-firewall hooks removed"}):{client:o,action:"skipped",message:"no wyrm-memo hooks installed"}}catch(n){return{client:o,action:"failed",message:n instanceof Error?n.message:String(n)}}}function Ne(e={}){const t=k(e),o=[];try{const s=JSON.parse(y(t,"utf-8")).hooks??{};for(const r of Object.values(s))if(Array.isArray(r))for(const i of r)for(const c of i?.hooks??[]){const u=c?.command;u&&L.test(u)&&o.push(u)}}catch{}return{settingsPath:t,installed:o.length>0,commands:o}}function ye(e){const t={serverPath:e?.serverPath||M(),dbPath:e?.dbPath||D(),httpPort:e?.httpPort},o=a(h(),".wyrm");f(o)||P(o,{recursive:!0});const n=A(),s=[];for(const u of n)s.push(H(u,t));q(t);const r=ae();r&&s.push(r);const i=me();i&&s.push(i);const c=ge();return c&&s.push(c),s}function Te(){const e=A(),t=[];for(const s of e)t.push(ce(s));const o=ue();o&&t.push(o);const n=le();return n&&t.push(n),t}function ve(e,t){const o={serverPath:t?.serverPath||M(),dbPath:t?.dbPath||D(),httpPort:t?.httpPort},n=A(),s=[];for(const r of n)e.includes(r.id)&&s.push(H(r,o));return q(o),s}function q(e){const t=a(h(),".wyrm","wyrm-config.json"),o=A().filter(s=>s.configured).map(s=>s.id),n={version:"3.0.0",serverPath:e.serverPath,dbPath:e.dbPath,httpPort:e.httpPort,configuredClients:o,lastSetup:new Date().toISOString(),autoUpdate:!0};p(t,JSON.stringify(n,null,2)+`
|
|
18
18
|
`,"utf-8")}function V(){const e=a(h(),".wyrm","wyrm-config.json");if(!f(e))return null;try{return JSON.parse(y(e,"utf-8"))}catch{return null}}function We(){const e=V();return e?ve(e.configuredClients,{serverPath:e.serverPath,dbPath:e.dbPath,httpPort:e.httpPort}):ye()}const Q="<!-- wyrm:start -->",K="<!-- wyrm:end -->",F=`${Q}
|
|
19
19
|
## Wyrm Memory + Agent (auto-managed \u2014 do not edit this section)
|
|
20
20
|
|
package/dist/causality.js
CHANGED
|
@@ -1,29 +1,34 @@
|
|
|
1
|
-
import{emitEvent as f}from"./events.js";import{getActor as E}from"./handlers/boundary.js";function g(c){if(c.length===0)return"";const e=c.map(
|
|
1
|
+
import{emitEvent as f}from"./events.js";import{getActor as E}from"./handlers/boundary.js";function g(c){if(c.length===0)return"";const e=c.map(t=>`${t.to_kind} #${t.to_id} (${t.reason})`).join(", "),i=c.length===1;return`[STALE FOUNDATION] this decision rests on ${i?"a foundation that has":`${c.length} foundations that have`} since been ${i?c[0].reason:"invalidated"} -- ${e}. Re-evaluate before relying on it (wyrm_decision_invalidate to cascade, or re-decide).`}class k{db;constructor(e){this.db=e}link(e){return this.linkOnce(e).edge}linkOnce(e){const i=e.relation??"because_of",t=this.db.prepare(`
|
|
2
|
+
SELECT * FROM decision_edges
|
|
3
|
+
WHERE project_id = ? AND from_kind = ? AND from_id = ? AND to_kind = ? AND to_id = ?
|
|
4
|
+
AND relation = ? AND invalidated_at IS NULL
|
|
5
|
+
ORDER BY id LIMIT 1
|
|
6
|
+
`).get(e.project_id,e.from_kind,e.from_id,e.to_kind,e.to_id,i);return t?{edge:t,created:!1}:{edge:this.insertEdge(e),created:!0}}insertEdge(e){const i=E(),t=this.db.prepare(`
|
|
2
7
|
INSERT INTO decision_edges
|
|
3
8
|
(project_id, from_kind, from_id, to_kind, to_id, relation, rationale, confidence, agent_id, run_id)
|
|
4
9
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5
|
-
`).run(e.project_id,e.from_kind,e.from_id,e.to_kind,e.to_id,e.relation??"because_of",e.rationale??null,e.confidence??1,
|
|
10
|
+
`).run(e.project_id,e.from_kind,e.from_id,e.to_kind,e.to_id,e.relation??"because_of",e.rationale??null,e.confidence??1,i.agent_id,i.run_id),o=this.get(t.lastInsertRowid);return f(this.db,{projectId:e.project_id,kind:"decision",refTable:"decision_edges",refId:o.id,isShared:!!o.is_shared}),o}get(e){return this.db.prepare("SELECT * FROM decision_edges WHERE id = ?").get(e)??null}downstreamOf(e,i){return this.db.prepare(`
|
|
6
11
|
SELECT * FROM decision_edges
|
|
7
12
|
WHERE to_kind = ? AND to_id = ? AND invalidated_at IS NULL
|
|
8
13
|
ORDER BY created_at DESC
|
|
9
|
-
`).all(e,
|
|
14
|
+
`).all(e,i)}upstreamOf(e,i){return this.db.prepare(`
|
|
10
15
|
SELECT * FROM decision_edges
|
|
11
16
|
WHERE from_kind = ? AND from_id = ? AND invalidated_at IS NULL
|
|
12
17
|
ORDER BY created_at DESC
|
|
13
|
-
`).all(e,
|
|
18
|
+
`).all(e,i)}staleFoundations(e,i){const t=this.db.prepare(`
|
|
14
19
|
SELECT to_kind, to_id FROM decision_edges
|
|
15
20
|
WHERE from_kind = ? AND from_id = ? AND relation = 'because_of' AND invalidated_at IS NULL
|
|
16
|
-
`).all(e,
|
|
21
|
+
`).all(e,i),o=this.db.prepare("SELECT is_current FROM ground_truths WHERE id = ?"),s=this.db.prepare(`
|
|
17
22
|
SELECT 1 FROM decision_edges
|
|
18
23
|
WHERE to_kind = ? AND to_id = ? AND relation = 'refutes' AND invalidated_at IS NULL LIMIT 1
|
|
19
|
-
`),
|
|
24
|
+
`),d=[];for(const r of t){let n=null;if(r.to_kind==="truth"){const a=o.get(r.to_id);a&&a.is_current===0&&(n="superseded")}!n&&s.get(r.to_kind,r.to_id)&&(n="refuted"),n&&d.push({to_kind:r.to_kind,to_id:r.to_id,reason:n})}return d}invalidateDownstream(e,i,t){const o=[],s=new Set,d=[{kind:e,id:i}],r=this.db.prepare(`
|
|
20
25
|
UPDATE decision_edges
|
|
21
26
|
SET invalidated_at = datetime('now'),
|
|
22
27
|
rationale = COALESCE(?, rationale)
|
|
23
28
|
WHERE id = ?
|
|
24
|
-
`);for(;
|
|
29
|
+
`);for(;d.length>0;){const n=d.shift(),a=`${n.kind}:${n.id}`;if(s.has(a))continue;s.add(a);const l=this.downstreamOf(n.kind,n.id);for(const _ of l)r.run(t??null,_.id),o.push({kind:_.from_kind,id:_.from_id,edge_id:_.id,rationale:_.rationale}),d.push({kind:_.from_kind,id:_.from_id})}return{invalidated:o.length,affected:o}}pathTo(e,i,t=6){const o=new Set,s=[{node:e,path:[]}];for(;s.length>0;){const{node:d,path:r}=s.pop(),n=`${d.kind}:${d.id}`;if(!(o.has(n)||r.length>t)){if(o.add(n),d.kind===i.kind&&d.id===i.id)return r;for(const a of this.upstreamOf(d.kind,d.id))s.push({node:{kind:a.to_kind,id:a.to_id},path:[...r,a]})}}return[]}invalidatedInProject(e,i=50){return this.db.prepare(`
|
|
25
30
|
SELECT * FROM decision_edges
|
|
26
31
|
WHERE project_id = ? AND invalidated_at IS NOT NULL
|
|
27
32
|
ORDER BY invalidated_at DESC
|
|
28
33
|
LIMIT ?
|
|
29
|
-
`).all(e,
|
|
34
|
+
`).all(e,i)}}export{k as Causality,g as staleFoundationWarning};
|
package/dist/cli.js
CHANGED
|
@@ -1,22 +1,25 @@
|
|
|
1
|
-
import{readFileSync as
|
|
2
|
-
${
|
|
3
|
-
${
|
|
4
|
-
${
|
|
5
|
-
${
|
|
6
|
-
${
|
|
7
|
-
${
|
|
8
|
-
${
|
|
9
|
-
${
|
|
10
|
-
`}function
|
|
11
|
-
`),d+=(
|
|
12
|
-
`,
|
|
13
|
-
`);for(const
|
|
14
|
-
`;return
|
|
15
|
-
`),
|
|
16
|
-
`;
|
|
17
|
-
`,
|
|
18
|
-
`;for(const
|
|
19
|
-
`;return
|
|
20
|
-
${
|
|
21
|
-
`),
|
|
22
|
-
`),
|
|
1
|
+
import{readFileSync as g}from"fs";import{dirname as x,join as b}from"path";import{fileURLToPath as w}from"url";function f(){try{const t=x(w(import.meta.url));return JSON.parse(g(b(t,"..","package.json"),"utf-8")).version??"dev"}catch{return"dev"}}function M(t,n){const o=t.FORCE_COLOR;return o!==void 0?!(o==="0"||o.toLowerCase()==="false"):t.NO_COLOR!==void 0&&t.NO_COLOR!==""?!1:n===!0}const y=M(process.env,process.stdout.isTTY),C=t=>y?t:"",R={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",italic:"\x1B[3m",underline:"\x1B[4m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m"},e=Object.fromEntries(Object.entries(R).map(([t,n])=>[t,C(n)])),$={bold:t=>`${e.bold}${t}${e.reset}`,dim:t=>`${e.dim}${t}${e.reset}`,red:t=>`${e.red}${t}${e.reset}`,green:t=>`${e.green}${t}${e.reset}`,yellow:t=>`${e.yellow}${t}${e.reset}`,blue:t=>`${e.blue}${t}${e.reset}`,magenta:t=>`${e.magenta}${t}${e.reset}`,cyan:t=>`${e.cyan}${t}${e.reset}`,primary:t=>`${e.brightMagenta}${t}${e.reset}`,success:t=>`${e.brightGreen}${t}${e.reset}`,warning:t=>`${e.brightYellow}${t}${e.reset}`,error:t=>`${e.brightRed}${t}${e.reset}`},p={dragon:"\u{F115D}",fire:"\u{1F525}",scroll:"\u{1F4DC}",sword:"\u2694\uFE0F",shield:"\u{1F6E1}\uFE0F",treasure:"\u{1F48E}",quest:"\u{1F3AF}",check:"\u2713",cross:"\u2717",arrow:"\u2192",bullet:"\u2022",star:"\u2605",warning:"\u26A0\uFE0F",error:"\u274C",success:"\u2705",info:"\u2139\uFE0F",clock:"\u{1F550}",folder:"\u{1F4C1}",file:"\u{1F4C4}",lock:"\u{1F512}",unlock:"\u{1F513}",sync:"\u{1F504}",search:"\u{1F50D}",sparkle:"\u2728"},v={critical:"\u{1F534}",high:"\u{1F7E0}",medium:"\u{1F7E1}",low:"\u{1F7E2}"};function P(){return`
|
|
2
|
+
${e.brightMagenta}\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557${e.reset}
|
|
3
|
+
${e.brightMagenta}\u2588\u2588\u2551 \u2588\u2588\u2551\u255A\u2588\u2588\u2557 \u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551${e.reset}
|
|
4
|
+
${e.brightMagenta}\u2588\u2588\u2551 \u2588\u2557 \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551${e.reset}
|
|
5
|
+
${e.brightMagenta}\u2588\u2588\u2551\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u255A\u2588\u2588\u2554\u255D \u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551${e.reset}
|
|
6
|
+
${e.brightMagenta}\u255A\u2588\u2588\u2588\u2554\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551${e.reset}
|
|
7
|
+
${e.brightMagenta} \u255A\u2550\u2550\u255D\u255A\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D${e.reset}
|
|
8
|
+
${e.dim} Persistent AI Memory System v${f()}${e.reset}
|
|
9
|
+
${e.dim} ghosts.lk${e.reset}
|
|
10
|
+
`}function E(){return`${e.brightMagenta}\u{F115D} Wyrm v${f()}${e.reset}`}class N{frames=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"];current=0;interval=null;text;constructor(n="Loading..."){this.text=n}start(){this.interval=setInterval(()=>{process.stdout.write(`\r${e.cyan}${this.frames[this.current]}${e.reset} ${this.text}`),this.current=(this.current+1)%this.frames.length},80)}update(n){this.text=n}succeed(n){this.stop(),console.log(`\r${$.success("\u2713")} ${n||this.text}`)}fail(n){this.stop(),console.log(`\r${$.error("\u2717")} ${n||this.text}`)}warn(n){this.stop(),console.log(`\r${$.warning("!")} ${n||this.text}`)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null,process.stdout.write("\r\x1B[K"))}}class _{total;current=0;width;label;constructor(n,o="Progress",r=30){this.total=n,this.width=r,this.label=o}update(n,o){this.current=n,o&&(this.label=o),this.render()}increment(n){this.update(this.current+1,n)}render(){const n=Math.min(100,Math.floor(this.current/this.total*100)),o=Math.floor(this.current/this.total*this.width),r=this.width-o,s=`${e.brightMagenta}${"\u2588".repeat(o)}${e.dim}${"\u2591".repeat(r)}${e.reset}`,i=`${n}%`.padStart(4);process.stdout.write(`\r${this.label} ${s} ${i} (${this.current}/${this.total})`)}complete(){this.update(this.total),console.log()}}function I(t,n,o={}){const{padding:r=2,border:s=!0}=o,i=t.map((c,l)=>{const m=Math.max(...n.map(u=>(u[l]||"").length));return Math.max(c.length,m)}),a=(c,l)=>c.padEnd(l),h=i.map(c=>"\u2500".repeat(c+r)).join(s?"\u253C":" ");let d="";s&&(d+=`${e.dim}\u250C${i.map(c=>"\u2500".repeat(c+r)).join("\u252C")}\u2510${e.reset}
|
|
11
|
+
`),d+=(s?`${e.dim}\u2502${e.reset}`:"")+t.map((c,l)=>` ${$.bold(a(c,i[l]))} `).join(s?`${e.dim}\u2502${e.reset}`:"")+(s?`${e.dim}\u2502${e.reset}`:"")+`
|
|
12
|
+
`,s&&(d+=`${e.dim}\u251C${h}\u2524${e.reset}
|
|
13
|
+
`);for(const c of n)d+=(s?`${e.dim}\u2502${e.reset}`:"")+c.map((l,m)=>` ${a(l||"",i[m])} `).join(s?`${e.dim}\u2502${e.reset}`:"")+(s?`${e.dim}\u2502${e.reset}`:"")+`
|
|
14
|
+
`;return s&&(d+=`${e.dim}\u2514${i.map(c=>"\u2500".repeat(c+r)).join("\u2534")}\u2518${e.reset}`),d}function T(t,n,o=50){const r=n.split(`
|
|
15
|
+
`),s=Math.max(t.length,...r.map(a=>a.length),o);let i=`${e.dim}\u256D${"\u2500".repeat(s+2)}\u256E${e.reset}
|
|
16
|
+
`;i+=`${e.dim}\u2502${e.reset} ${$.bold(t.padEnd(s))} ${e.dim}\u2502${e.reset}
|
|
17
|
+
`,i+=`${e.dim}\u251C${"\u2500".repeat(s+2)}\u2524${e.reset}
|
|
18
|
+
`;for(const a of r)i+=`${e.dim}\u2502${e.reset} ${a.padEnd(s)} ${e.dim}\u2502${e.reset}
|
|
19
|
+
`;return i+=`${e.dim}\u2570${"\u2500".repeat(s+2)}\u256F${e.reset}`,i}function S(t){if(t===0)return"0 B";const n=1024,o=["B","KB","MB","GB","TB"],r=Math.floor(Math.log(t)/Math.log(n));return`${(t/Math.pow(n,r)).toFixed(2)} ${o[r]}`}function A(t){return t<1e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:t<36e5?`${Math.floor(t/6e4)}m ${Math.floor(t%6e4/1e3)}s`:`${Math.floor(t/36e5)}h ${Math.floor(t%36e5/6e4)}m`}function G(t){console.log(`
|
|
20
|
+
${$.bold($.primary(`\u25B6 ${t}`))}`),console.log(`${e.dim}${"\u2500".repeat(t.length+4)}${e.reset}`)}function Y(t){console.log(`${p.success} ${$.success(t)}`)}function D(t){console.error(`${p.error} ${$.error(t)}`)}function F(t){console.log(`${p.warning} ${$.warning(t)}`)}function W(t){console.log(`${p.info} ${t}`)}function O(t,n){const o=Array.from({length:t.length+1},(r,s)=>[s,...Array(n.length).fill(0)]);for(let r=1;r<=n.length;r++)o[0][r]=r;for(let r=1;r<=t.length;r++)for(let s=1;s<=n.length;s++){const i=t[r-1]===n[s-1]?0:1;o[r][s]=Math.min(o[r-1][s]+1,o[r][s-1]+1,o[r-1][s-1]+i),r>1&&s>1&&t[r-1]===n[s-2]&&t[r-2]===n[s-1]&&(o[r][s]=Math.min(o[r][s],o[r-2][s-2]+1))}return o[t.length][n.length]}function K(t,n,o=3){const r=t.toLowerCase(),s=r.length<=4?1:2;return[...new Set(n)].map(i=>({cand:i,dist:O(r,i.toLowerCase())})).filter(({cand:i,dist:a})=>a<=s||r.length>=3&&i.toLowerCase().startsWith(r)).sort((i,a)=>i.dist-a.dist||i.cand.localeCompare(a.cand)).slice(0,o).map(({cand:i})=>i)}function U(t,n=process.platform){const o=n==="win32"?/^(.*?)[\\/]node_modules[\\/]wyrm-mcp[\\/]/i.exec(t):/^(.*)\/lib\/node_modules\/wyrm-mcp\//.exec(t);return!o||!o[1]||/[\\/](_npx|node_modules)([\\/]|$)/.test(o[1])?null:o[1]}function q(t){if(t.isTTY){let r=-1;return{onProgress:(s,i,a)=>{const h=Math.floor(i/a*100);h!==r&&(r=h,t.write(`\r ${s}: ${h}% `))},finish:()=>{t.write(`
|
|
21
|
+
`)}}}const n=new Set,o=new Set;return{onProgress:(r,s,i)=>{n.has(r)||(n.add(r),t.write(` ${r}: downloading (${S(i)})
|
|
22
|
+
`)),s>=i&&!o.has(r)&&(o.add(r),t.write(` ${r}: done
|
|
23
|
+
`))},finish:()=>{}}}class B extends Error{constructor(){super("readSecret canceled"),this.name="ReadSecretCanceled"}}async function J(t,n={}){const o=n.input??process.stdin,r=n.output??process.stdout,s=typeof o.setRawMode=="function";r.write(t),s&&o.setRawMode(!0),o.resume();let i="";return new Promise((a,h)=>{const d=m=>{for(const u of m){if(u===13||u===10){l(),r.write(`
|
|
24
|
+
`),a(i);return}if(u===3){l(),h(new B);return}if(u===4){l(),r.write(`
|
|
25
|
+
`),a(i);return}if(u===127||u===8){i.length>0&&(i=i.slice(0,-1),r.write("\b \b"));continue}i+=String.fromCharCode(u),r.write("*")}},c=()=>{l(),a(i)};function l(){s&&o.setRawMode(!1),o.pause(),o.removeListener("data",d),o.removeListener("end",c)}o.on("data",d),o.on("end",c)})}export{P as BANNER,E as MINI_BANNER,_ as ProgressBar,B as ReadSecretCanceled,N as Spinner,$ as c,e as colors,q as createDownloadProgress,O as editDistance,T as formatBox,S as formatBytes,A as formatDuration,I as formatTable,p as icons,U as npmGlobalPrefixFromPath,D as printError,W as printInfo,G as printSection,Y as printSuccess,F as printWarning,v as priorityIcons,J as readSecret,M as shouldUseColor,K as suggestClosest};
|
package/dist/cloud/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{randomBytes as A}from"node:crypto";import{writeFileSync as L}from"node:fs";import{hostname as O}from"node:os";import{resolve as P,dirname as W,join as M}from"node:path";import{fileURLToPath as F}from"node:url";import{createInterface as B}from"node:readline";import{CloudClient as u,CloudError as w,DEFAULT_BASE as v,SESSION_FILE as $,loadSession as g,saveSession as C,clearSession as k}from"./client.js";import{getMasterKey as U,keyExists as b,keyFilePath as d,decrypt as j}from"./crypto.js";import{computeMachineFp as D,classifySession as G}from"./machine-id.js";import{runSync as H,CopiedSessionError as Y}from"./sync-engine.js";import{SovereignSyncManager as q,restartIntervalMinutes as K}from"./sync-daemon.js";import{initializeLicense as J,hasFeature as z,getTier as V}from"../license.js";function S(){J(),z("cloud_backup")||(console.error("\u{F115D} Wyrm Cloud sync requires a Pro license or higher."),console.error(` Current tier: ${V()}`),console.error(" Upgrade: https://ghosts.lk/wyrm"),console.error(" Already paid? Activate your license (wyrm_license tool, or place"),console.error(" the signed JSON at ~/.wyrm/license.json) and retry."),process.exit(1))}function _(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MiB`:`${(e/(1024*1024*1024)).toFixed(2)} GiB`}function x(e){return e?new Date(e).toISOString().replace("T"," ").slice(0,16)+" UTC":"\u2014"}async function be(e){const r=e[0],
|
|
1
|
+
import{randomBytes as A}from"node:crypto";import{writeFileSync as L}from"node:fs";import{hostname as O}from"node:os";import{resolve as P,dirname as W,join as M}from"node:path";import{fileURLToPath as F}from"node:url";import{createInterface as B}from"node:readline";import{CloudClient as u,CloudError as w,DEFAULT_BASE as v,SESSION_FILE as $,loadSession as g,saveSession as C,clearSession as k}from"./client.js";import{getMasterKey as U,keyExists as b,keyFilePath as d,decrypt as j}from"./crypto.js";import{computeMachineFp as D,classifySession as G}from"./machine-id.js";import{runSync as H,CopiedSessionError as Y}from"./sync-engine.js";import{SovereignSyncManager as q,restartIntervalMinutes as K}from"./sync-daemon.js";import{initializeLicense as J,hasFeature as z,getTier as V}from"../license.js";function S(){J(),z("cloud_backup")||(console.error("\u{F115D} Wyrm Cloud sync requires a Pro license or higher."),console.error(` Current tier: ${V()}`),console.error(" Upgrade: https://ghosts.lk/wyrm"),console.error(" Already paid? Activate your license (wyrm_license tool, or place"),console.error(" the signed JSON at ~/.wyrm/license.json) and retry."),process.exit(1))}function _(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KiB`:e<1024*1024*1024?`${(e/(1024*1024)).toFixed(1)} MiB`:`${(e/(1024*1024*1024)).toFixed(2)} GiB`}function x(e){return e?new Date(e).toISOString().replace("T"," ").slice(0,16)+" UTC":"\u2014"}async function be(e){const r=e[0],n=e.slice(1);try{switch(r){case void 0:case"help":case"--help":case"-h":return Q();case"login":return await X(n);case"logout":return await Z();case"status":return await ee();case"doctor":return oe();case"devices":return await se(n);case"sync":return await te(n);case"daemon":return await ce(n);case"export":return await le(n);case"delete":return await ie(n);case"recovery":return await ae(n);default:console.error(`Unknown subcommand: wyrm cloud ${r}`),console.error("Try `wyrm cloud help`"),process.exit(1)}}catch(t){if(t instanceof Y&&process.exit(1),t instanceof w)t.status===401?console.error("\u2718 Not authenticated. Run `wyrm cloud login`."):t.status===403?console.error(`\u2718 Forbidden: ${t.message}`):t.status===0?(console.error(`\u2718 ${t.message}`),console.error(" Check your internet connection. If wyrm.ghosts.lk is unreachable, see status at https://www.cloudflarestatus.com")):t.status===501?console.error(`\u2718 Service not configured: ${t.message}`):console.error(`\u2718 ${t.message} (HTTP ${t.status})`);else if(t instanceof Error){const s=t.message;s.includes("Not logged in")?console.error("\u2718 Not logged in. Run `wyrm cloud login`."):s.includes("Wyrm Cloud key")?console.error(`\u2718 Encryption-key error: ${s}`):console.error(`\u2718 ${s}`)}else console.error("\u2718 Unexpected error:",t);process.exit(1)}}function Q(){console.log(`\u{F115D} wyrm cloud \u2014 sync your Wyrm memory across devices
|
|
2
2
|
|
|
3
3
|
USAGE:
|
|
4
4
|
wyrm cloud <subcommand> [args]
|
|
@@ -37,6 +37,6 @@ CONSTITUTION:
|
|
|
37
37
|
|
|
38
38
|
DOMAIN:
|
|
39
39
|
https://wyrm.ghosts.lk
|
|
40
|
-
`)}async function X(e){const r=g();if(r)try{await new u(r.base,r.session).me(),console.error("Already logged in. Run `wyrm cloud logout` first to switch accounts."),process.exit(1)}catch(c){c instanceof w&&c.status===401||(console.error("Already logged in. Run `wyrm cloud logout` first to switch accounts."),process.exit(1)),console.log("Previous session expired; starting a fresh login."),k()}const
|
|
40
|
+
`)}async function X(e){const r=g();if(r)try{await new u(r.base,r.session).me(),console.error("Already logged in. Run `wyrm cloud logout` first to switch accounts."),process.exit(1)}catch(c){c instanceof w&&c.status===401||(console.error("Already logged in. Run `wyrm cloud logout` first to switch accounts."),process.exit(1)),console.log("Previous session expired; starting a fresh login."),k()}const n=new u(v),t=A(32).toString("hex");let s;try{s=await n.cliInit(t)}catch(c){console.error(`\u2718 Could not start login: ${c instanceof Error?c.message:c}`),process.exit(1)}console.log(""),console.log("\u{F115D} Sign in to Wyrm Cloud"),console.log(""),console.log(" 1. Open this URL on any device:"),console.log(` ${s.browser_url}`),console.log(""),console.log(" 2. Type this code when prompted:"),console.log(` ${s.code}`),console.log(""),console.log(" 3. Sign in with Google or GitHub."),console.log(""),console.log(` Waiting (expires in ${Math.round(s.expires_in_sec/60)} min)\u2026`);const l=Date.now()+s.expires_in_sec*1e3;let i,a;for(;Date.now()<l;){await new Promise(c=>{setTimeout(c,3e3)});try{const c=await n.cliPoll(t);if(c.ready&&c.session){i=c.session,a=c.account_id;break}}catch(c){console.error(`
|
|
41
41
|
\u2718 Login failed: ${c instanceof Error?c.message:c}`),process.exit(1)}}(!i||!a)&&(console.error("\n\u2718 Login timed out. Run `wyrm cloud login` again."),process.exit(1)),C({base:v,session:i,account_id:a,created_at:Date.now()});const y=new u(v,i);let m="";try{m=(await y.me()).account.email}catch{}const f=`${O()} (${process.platform})`;let p;try{p=(await y.registerDevice(f)).device.id;const h=g();h&&C({...h,email:m,device_id:p,device_name:f,machine_fp:D()})}catch(c){console.error(`
|
|
42
|
-
\u26A0 Logged in but could not register device: ${c instanceof Error?c.message:c}`),console.error(" Re-run `wyrm cloud login` to retry.");return}console.log(""),console.log(`\u2713 Signed in as ${m}`),console.log(`\u2713 Device registered: ${f}`),console.log(`\u2713 Session saved to ${$}`);const R=!b();if(U(),R?(console.log(`\u2713 Encryption key generated at ${d()} (0600)`),console.log(""),console.log(" \u26A0 Back up the key file. Losing it means losing access to your synced data."),console.log(" The Wyrm Cloud server CANNOT recover it \u2014 that's the operator-owns-data"),console.log(" guarantee. Run `wyrm cloud recovery show` now to get a 24-word phrase,"),console.log(" or copy the key file to a password manager / encrypted backup.")):console.log(`\u2713 Encryption key reused from ${d()}`),p)try{const c=await y.syncStatus();if(c.deltas>0){const E=(await y.syncPull(p,0,1)).deltas[0];if(E){let T=!0;try{j(E.payload_b64)}catch{T=!1}T||(console.log(""),console.log(" \u26A0 THIS DEVICE CANNOT READ THE ACCOUNT'S DATA YET"),console.log(` Login succeeded, but the key at ${d()} cannot decrypt`),console.log(` the ${c.deltas} delta(s) already on this account. They were encrypted`),console.log(" with a different master key (e.g. this is an org account whose other"),console.log(" devices hold the shared key). Until the keys match, sync will move"),console.log(" 0 rows in BOTH directions \u2014 a connected pipe that carries nothing."),console.log(""),console.log(" Fix: adopt the account key on this device \u2014"),console.log(" wyrm cloud recovery restore (needs the account's 24-word phrase)"),console.log(` Heads-up: restore OVERWRITES ${d()}. If this device also has`),console.log(" its OWN separate cloud data, back that key up first, or run the org"),console.log(" sync under a separate WYRM home so both keys coexist."))}}}catch{}console.log(""),console.log("Next: `wyrm cloud sync` to push your memory.")}async function Z(){const e=g();if(!e){console.log("Not logged in.");return}try{await new u(e.base,e.session).logout(),console.log("\u2713 Session revoked server-side.")}catch(r){console.error(`\u26A0 Could not revoke server-side: ${r instanceof Error?r.message:r}`),console.error(" Local session cleared anyway.")}k(),console.log(`\u2713 Local session removed (${$}).`),console.log(" Note: ~/.wyrm/cloud.key kept. Delete manually if you want a clean slate.")}async function ee(){const e=g();if(!e){console.log("Not logged in. Run `wyrm cloud login`.");return}const r=new u(e.base,e.session);try{const s=await r.me(),n=await r.syncStatus();console.log(""),console.log(`\u{F115D} Wyrm Cloud \u2014 ${s.account.email}`),console.log(""),console.log(` Tier: ${n.tier}`),console.log(` Storage: ${_(n.storage.used_bytes)} / ${_(n.storage.limit_bytes)} (${n.storage.percent}%)`),console.log(` Deltas: ${n.deltas}`),console.log(` Devices: ${n.devices}`),console.log(` Providers:${s.identities.map(t=>" "+t.provider).join(",")}`),console.log(""),console.log(` This machine: ${e.device_name??"(not registered)"}`),console.log(` Device ID: ${e.device_id?e.device_id.slice(0,8)+"\u2026":"(none)"}`),console.log(` Session age: ${Math.round((Date.now()-e.created_at)/(1440*60*1e3))} day(s)`),I(e),console.log(""),b()?n.deltas>0&&(console.log(` Key: ${d()} (0600)`),console.log(` \u26A0 Back this file up. Losing it = losing access to your ${n.deltas} deltas.`),console.log("")):(console.log(" \u26A0 ENCRYPTION KEY MISSING"),console.log(` Expected at: ${d()}`),console.log(" Without this file, deltas already pushed cannot be decrypted."),console.log(" If you have a backup, restore it before running sync."),console.log(""))}catch(s){throw s instanceof w&&s.status===401&&(console.error("Session expired or invalid. Run `wyrm cloud login` again."),process.exit(1)),s}}function I(e){const r=G(e.machine_fp);r.state==="match"?console.log(" Identity: \u2713 machine fingerprint matches (not a copied session)"):r.state==="adopt"?console.log(" Identity: \u2014 no fingerprint yet (pre-7.0.3 session; adopted on next sync)"):(console.log(" Identity: \u26A0 FINGERPRINT MISMATCH \u2014 this session looks COPIED"),console.log(` stored ${r.stored.slice(0,12)}\u2026 vs this machine ${r.current.slice(0,12)}\u2026`),console.log(" device_id collision \u2192 cross-device pull returns 0 silently."),console.log(" Fix: rm ~/.wyrm/cloud.json ~/.wyrm/cloud-cursor.json (KEEP cloud.key),"),console.log(" then `wyrm cloud login`. (Or `wyrm cloud sync --force` if intended.)"))}function oe(){const e=g();if(console.log(""),console.log("\u{F115D} Wyrm Cloud \u2014 device identity doctor"),console.log(""),!e){console.log(" Not logged in. Run `wyrm cloud login`."),console.log("");return}console.log(` Account: ${e.email??e.account_id.slice(0,8)+"\u2026"}`),console.log(` Device ID: ${e.device_id?e.device_id.slice(0,8)+"\u2026":"(none \u2014 re-run `wyrm cloud login`)"}`),console.log(` Server: ${e.base}`),console.log(` Stored fp: ${e.machine_fp?e.machine_fp.slice(0,12)+"\u2026":"(none \u2014 pre-7.0.3 session)"}`),console.log(` This box fp: ${D().slice(0,12)}\u2026`),I(e),console.log(""),console.log(" Only ~/.wyrm/cloud.key is meant to be shared across your machines."),console.log(" cloud.json + cloud-cursor.json + machine-id are per-device."),console.log("")}async function se(e){const r=e[0],s=u.fromSession();if(r==="revoke"){const i=e[1];i||(console.error("Usage: wyrm cloud devices revoke <device-id>"),process.exit(1));const a=await ne(s,i);await s.revokeDevice(a),console.log(`\u2713 Device ${a.slice(0,8)}\u2026 revoked.`);return}const n=e.includes("--full"),{devices:t}=await s.listDevices(),l=g()?.device_id;console.log(""),console.log(`\u{F115D} Devices (${t.length})`),console.log("");for(const i of t){const a=i.id===l?"\u2605":" ",y=i.revoked?"(revoked)":"",m=n?i.id:`${i.id.slice(0,8)}\u2026`;console.log(` ${a} ${m} ${i.name.padEnd(30)} last_seen=${x(i.last_seen_at)} ${y}`)}console.log(""),console.log(" \u2605 = this machine"),console.log(" Revoke: wyrm cloud devices revoke <device-id> (an id prefix as shown above is fine)"),n||console.log(" Full ids: wyrm cloud devices --full"),console.log("")}async function ne(e,r){const s=r.replace(/[….]+$/,"").trim().toLowerCase(),{devices:n}=await e.listDevices(),t=n.find(l=>l.id.toLowerCase()===s);if(t)return t.id;const o=n.filter(l=>l.id.toLowerCase().startsWith(s));if(o.length===1)return o[0].id;o.length===0&&(console.error(`\u2718 No device matches "${r}". List them with: wyrm cloud devices`),process.exit(1)),console.error(`\u2718 "${r}" is ambiguous \u2014 it matches ${o.length} devices:`);for(const l of o)console.error(` ${l.id} ${l.name}`);console.error(" Re-run with more characters, or the full id."),process.exit(1)}async function te(e){S();const r=e.includes("--dry-run"),s=e.includes("--all"),n=e.includes("--force");b()||(console.error("\u26A0 Encryption key not found at",d()),console.error(" A new key will be generated, but it will NOT decrypt deltas"),console.error(" pushed by other devices using a different key. If you have a backup,"),console.error(" restore it to ~/.wyrm/cloud.key (0600) before running sync."),console.error(" Continuing in 5 seconds \u2014 press Ctrl+C to abort."),await new Promise(o=>{setTimeout(o,5e3)})),s&&(console.log("\u{1F310} --all mode: syncing every semantic table (ignoring visibility flags)."),console.log(" Skipped: per-device logs, FTS shadows, sync internals."),console.log(""));const t=await H({dryRun:r,all:s,force:n});if(console.log(""),console.log("\u{F115D} Sync complete"),console.log(""),console.log(` Pushed: ${t.pushed} row(s)${r?" (dry run)":""}`),console.log(` Pulled: ${t.pulled} row(s)`),console.log(` Deleted: ${t.deleted_local} row(s) (peer tombstones)`),t.quarantined&&t.quarantined>0&&console.log(` Quarantined: ${t.quarantined} undecryptable delta(s) set aside (see errors)`),t.errors.length>0){console.log(""),console.log(" Errors:");for(const o of t.errors)console.log(` - ${o}`)}console.log("")}function re(){const e=M(W(F(import.meta.url)),"sync-daemon-entrypoint.js");return new q(e)}async function ce(e){S();const r=e[0]??"status",s=e.find(o=>o.startsWith("--interval="));let n;if(s){const o=Number(s.split("=")[1]);(!Number.isFinite(o)||o<=0)&&(console.error("\u2716 --interval= expects a positive number of minutes, got "+JSON.stringify(s)),process.exit(1)),n=o}const t=re();switch(r){case"start":{g()||(console.error("\u2718 Not logged in. Run `wyrm cloud login` first."),process.exit(1));const o=t.start({interval_minutes:n});o.ok||(console.error(`\u{F115D} sovereign-sync daemon: ${o.reason??"failed to start"}${o.pid?` (pid ${o.pid})`:""}`),process.exit(o.pid?0:1)),console.log(`\u{F115D} \u2713 sovereign-sync daemon started (pid ${o.pid}). Logs: ~/.wyrm/wyrm-sovereign-sync.log`);return}case"stop":{const o=t.stop();console.log(o.ok?"\u{F115D} \u2713 sovereign-sync daemon stopped":`\u{F115D} sovereign-sync daemon: ${o.reason??"failed to stop"}`);return}case"restart":{const o=K(n,t.status().state?.interval_ms);t.stop(),await new Promise(i=>{setTimeout(i,500)});const l=t.start({interval_minutes:o});console.log(l.ok?`\u{F115D} \u2713 sovereign-sync daemon restarted (pid ${l.pid}, every ${o} min)`:`\u{F115D} restart failed: ${l.reason??"unknown"}`);return}case"status":{const o=t.status();console.log("\u{F115D} Sovereign-sync daemon"),console.log(` Running: ${o.running?`\u2713 yes (pid ${o.pid})`:"\u2717 no"}`),o.state?.interval_ms&&console.log(` Interval: every ${o.state.interval_ms/6e4} min`),o.state?.started_ts&&console.log(` Started: ${x(o.state.started_ts)}`),o.state?.last_tick_ts&&(console.log(` Last tick: ${x(o.state.last_tick_ts)} (exit ${o.state.last_tick_exit??"\u2014"})`),o.state.last_tick_summary&&console.log(` Last result: ${o.state.last_tick_summary}`));return}default:console.error(`Unknown daemon action: ${r}. Use: start, stop, restart, status`),process.exit(1)}}async function le(e){S();const r=u.fromSession(),s=e.find(l=>!l.startsWith("-")),n=P(s??`wyrm-cloud-export-${new Date().toISOString().slice(0,10)}.json`);console.log(" Fetching account export\u2026");const t=await r.accountExport(),o=JSON.stringify(t,null,2);L(n,o,{mode:384}),console.log(""),console.log(`\u2713 Exported to ${n}`),console.log(""),console.log(` Account: ${t.account.email} (${t.account.id.slice(0,8)}\u2026)`),console.log(` Devices: ${t.devices.length}`),console.log(` Identities: ${t.identities.length}`),console.log(` Orgs: ${t.orgs.length}`),console.log(` Deltas: ${t.deltas.length}`),console.log(` Size: ${_(o.length)}`),console.log(""),console.log(" Deltas are still AES-256-GCM ciphertext. To decrypt them you"),console.log(` need the key at ${d()}. Back that up alongside this file.`),console.log("")}async function ie(e){e.includes("--confirm")||(console.error("\u2718 This permanently deletes your Wyrm Cloud account."),console.error(" Re-run with --confirm to proceed:"),console.error(" wyrm cloud delete --confirm"),process.exit(1));const s=g();s||(console.error("\u2718 Not logged in. Nothing to delete."),process.exit(1)),console.log(""),console.log("\u26A0 You are about to PERMANENTLY DELETE your Wyrm Cloud account."),console.log(""),console.log(` Account: ${s.email??s.account_id}`),console.log(` Server: ${s.base}`),console.log(""),console.log(" This wipes all encrypted blobs, devices, identities, and org"),console.log(" memberships you own. The local ~/.wyrm/cloud.key is kept so"),console.log(" any backups remain decryptable. This action CANNOT be undone."),console.log(""),(await N(' Type "DELETE my account" to confirm: ')).trim()!=="DELETE my account"&&(console.error("\u2718 Confirmation phrase did not match. Aborting."),process.exit(1)),await new u(s.base,s.session).accountDelete(),k(),console.log(""),console.log("\u2713 Account deleted on server."),console.log(`\u2713 Local session removed (${$}).`),console.log(` Kept: ${d()} (in case you need to decrypt an old export).`),console.log("")}function N(e){return new Promise(r=>{const s=B({input:process.stdin,output:process.stdout});s.question(e,n=>{s.close(),r(n)})})}async function ae(e){const r=e[0];if(r==="show"){const{keyToMnemonic:s}=await import("./recovery.js"),t=s().split(" ");console.log(""),console.log("\u{1F511} Wyrm Cloud recovery phrase (BIP39, 24 words)"),console.log("");for(let o=0;o<4;o++){const l=t.slice(o*6,o*6+6).map((i,a)=>`${String(o*6+a+1).padStart(2)}. ${i.padEnd(10)}`).join(" ");console.log(` ${l}`)}console.log(""),console.log(" Write these down on PAPER and keep them somewhere safe."),console.log(" Anyone with this phrase can decrypt your synced Wyrm memory."),console.log(" Wyrm Cloud has NO COPY of this. Lose it = lose your data."),console.log("");return}if(r==="restore"){const s=e.includes("--overwrite");console.log(""),console.log("\u{1F511} Restore master key from BIP39 recovery phrase"),console.log(""),console.log(" Enter your 24 words separated by spaces (case-insensitive)."),console.log(" Press Enter when done."),console.log("");const n=await N(" > "),{mnemonicToKey:t}=await import("./recovery.js"),{path:o,overwrote:l}=t(n,{overwrite:s});console.log(""),console.log(`\u2713 Master key restored to ${o} (0600)`),l&&console.log(" Replaced existing key (you passed --overwrite)."),console.log(" Run `wyrm cloud sync` to pull deltas with the restored key."),console.log("");return}console.error("Usage:"),console.error(" wyrm cloud recovery show"),console.error(" wyrm cloud recovery restore [--overwrite]"),process.exit(1)}export{be as cmdCloud};
|
|
42
|
+
\u26A0 Logged in but could not register device: ${c instanceof Error?c.message:c}`),console.error(" Re-run `wyrm cloud login` to retry.");return}console.log(""),console.log(`\u2713 Signed in as ${m}`),console.log(`\u2713 Device registered: ${f}`),console.log(`\u2713 Session saved to ${$}`);const R=!b();if(U(),R?(console.log(`\u2713 Encryption key generated at ${d()} (0600)`),console.log(""),console.log(" \u26A0 Back up the key file. Losing it means losing access to your synced data."),console.log(" The Wyrm Cloud server CANNOT recover it \u2014 that's the operator-owns-data"),console.log(" guarantee. Run `wyrm cloud recovery show` now to get a 24-word phrase,"),console.log(" or copy the key file to a password manager / encrypted backup.")):console.log(`\u2713 Encryption key reused from ${d()}`),p)try{const c=await y.syncStatus();if(c.deltas>0){const E=(await y.syncPull(p,0,1)).deltas[0];if(E){let T=!0;try{j(E.payload_b64)}catch{T=!1}T||(console.log(""),console.log(" \u26A0 THIS DEVICE CANNOT READ THE ACCOUNT'S DATA YET"),console.log(` Login succeeded, but the key at ${d()} cannot decrypt`),console.log(` the ${c.deltas} delta(s) already on this account. They were encrypted`),console.log(" with a different master key (e.g. this is an org account whose other"),console.log(" devices hold the shared key). Until the keys match, sync will move"),console.log(" 0 rows in BOTH directions \u2014 a connected pipe that carries nothing."),console.log(""),console.log(" Fix: adopt the account key on this device \u2014"),console.log(" wyrm cloud recovery restore (needs the account's 24-word phrase)"),console.log(` Heads-up: restore OVERWRITES ${d()}. If this device also has`),console.log(" its OWN separate cloud data, back that key up first, or run the org"),console.log(" sync under a separate WYRM home so both keys coexist."))}}}catch{}console.log(""),console.log("Next: `wyrm cloud sync` to push your memory.")}async function Z(){const e=g();if(!e){console.log("Not logged in.");return}try{await new u(e.base,e.session).logout(),console.log("\u2713 Session revoked server-side.")}catch(r){console.error(`\u26A0 Could not revoke server-side: ${r instanceof Error?r.message:r}`),console.error(" Local session cleared anyway.")}k(),console.log(`\u2713 Local session removed (${$}).`),console.log(" Note: ~/.wyrm/cloud.key kept. Delete manually if you want a clean slate.")}async function ee(){const e=g();if(!e){console.log("Not logged in. Run `wyrm cloud login`.");return}const r=new u(e.base,e.session);try{const n=await r.me(),t=await r.syncStatus();console.log(""),console.log(`\u{F115D} Wyrm Cloud \u2014 ${n.account.email}`),console.log(""),console.log(` Tier: ${t.tier}`),console.log(` Storage: ${_(t.storage.used_bytes)} / ${_(t.storage.limit_bytes)} (${t.storage.percent}%)`),console.log(` Deltas: ${t.deltas}`),console.log(` Devices: ${t.devices}`),console.log(` Providers:${n.identities.map(s=>" "+s.provider).join(",")}`),console.log(""),console.log(` This machine: ${e.device_name??"(not registered)"}`),console.log(` Device ID: ${e.device_id?e.device_id.slice(0,8)+"\u2026":"(none)"}`),console.log(` Session age: ${Math.round((Date.now()-e.created_at)/(1440*60*1e3))} day(s)`),I(e),console.log(""),b()?t.deltas>0&&(console.log(` Key: ${d()} (0600)`),console.log(` \u26A0 Back this file up. Losing it = losing access to your ${t.deltas} deltas.`),console.log("")):(console.log(" \u26A0 ENCRYPTION KEY MISSING"),console.log(` Expected at: ${d()}`),console.log(" Without this file, deltas already pushed cannot be decrypted."),console.log(" If you have a backup, restore it before running sync."),console.log(""))}catch(n){throw n instanceof w&&n.status===401&&(console.error("Session expired or invalid. Run `wyrm cloud login` again."),process.exit(1)),n}}function I(e){const r=G(e.machine_fp);r.state==="match"?console.log(" Identity: \u2713 machine fingerprint matches (not a copied session)"):r.state==="adopt"?console.log(" Identity: \u2014 no fingerprint yet (pre-7.0.3 session; adopted on next sync)"):(console.log(" Identity: \u26A0 FINGERPRINT MISMATCH \u2014 this session looks COPIED"),console.log(` stored ${r.stored.slice(0,12)}\u2026 vs this machine ${r.current.slice(0,12)}\u2026`),console.log(" device_id collision \u2192 cross-device pull returns 0 silently."),console.log(" Fix: rm ~/.wyrm/cloud.json ~/.wyrm/cloud-cursor.json (KEEP cloud.key),"),console.log(" then `wyrm cloud login`. (Or `wyrm cloud sync --force` if intended.)"))}function oe(){const e=g();if(console.log(""),console.log("\u{F115D} Wyrm Cloud \u2014 device identity doctor"),console.log(""),!e){console.log(" Not logged in. Run `wyrm cloud login`."),console.log("");return}console.log(` Account: ${e.email??e.account_id.slice(0,8)+"\u2026"}`),console.log(` Device ID: ${e.device_id?e.device_id.slice(0,8)+"\u2026":"(none \u2014 re-run `wyrm cloud login`)"}`),console.log(` Server: ${e.base}`),console.log(` Stored fp: ${e.machine_fp?e.machine_fp.slice(0,12)+"\u2026":"(none \u2014 pre-7.0.3 session)"}`),console.log(` This box fp: ${D().slice(0,12)}\u2026`),I(e),console.log(""),console.log(" Only ~/.wyrm/cloud.key is meant to be shared across your machines."),console.log(" cloud.json + cloud-cursor.json + machine-id are per-device."),console.log("")}async function se(e){const r=e[0],n=u.fromSession();if(r==="revoke"){const i=e[1];i||(console.error("Usage: wyrm cloud devices revoke <device-id>"),process.exit(1));const a=await ne(n,i);await n.revokeDevice(a),console.log(`\u2713 Device ${a.slice(0,8)}\u2026 revoked.`);return}const t=e.includes("--full"),{devices:s}=await n.listDevices(),l=g()?.device_id;console.log(""),console.log(`\u{F115D} Devices (${s.length})`),console.log("");for(const i of s){const a=i.id===l?"\u2605":" ",y=i.revoked?"(revoked)":"",m=t?i.id:`${i.id.slice(0,8)}\u2026`;console.log(` ${a} ${m} ${i.name.padEnd(30)} last_seen=${x(i.last_seen_at)} ${y}`)}console.log(""),console.log(" \u2605 = this machine"),console.log(" Revoke: wyrm cloud devices revoke <device-id> (an id prefix as shown above is fine)"),t||console.log(" Full ids: wyrm cloud devices --full"),console.log("")}async function ne(e,r){const n=r.replace(/[….]+$/,"").trim().toLowerCase(),{devices:t}=await e.listDevices(),s=t.find(l=>l.id.toLowerCase()===n);if(s)return s.id;const o=t.filter(l=>l.id.toLowerCase().startsWith(n));if(o.length===1)return o[0].id;o.length===0&&(console.error(`\u2718 No device matches "${r}". List them with: wyrm cloud devices`),process.exit(1)),console.error(`\u2718 "${r}" is ambiguous \u2014 it matches ${o.length} devices:`);for(const l of o)console.error(` ${l.id} ${l.name}`);console.error(" Re-run with more characters, or the full id."),process.exit(1)}async function te(e){S();const r=e.includes("--dry-run"),n=e.includes("--all"),t=e.includes("--force");b()||(console.error("\u26A0 Encryption key not found at",d()),console.error(" A new key will be generated, but it will NOT decrypt deltas"),console.error(" pushed by other devices using a different key. If you have a backup,"),console.error(" restore it to ~/.wyrm/cloud.key (0600) before running sync."),console.error(" Continuing in 5 seconds \u2014 press Ctrl+C to abort."),await new Promise(o=>{setTimeout(o,5e3)})),n&&(console.log("\u{1F310} --all mode: syncing every semantic table (ignoring visibility flags)."),console.log(" Skipped: per-device logs, FTS shadows, sync internals."),console.log(""));const s=await H({dryRun:r,all:n,force:t});if(console.log(""),console.log(s.errors.length>0?"\u{F115D} Sync finished with errors":"\u{F115D} Sync complete"),console.log(""),console.log(` Pushed: ${s.pushed} row(s)${r?" (dry run)":""}`),console.log(` Pulled: ${s.pulled} row(s)`),console.log(` Deleted: ${s.deleted_local} row(s) (peer tombstones)`),s.quarantined&&s.quarantined>0&&console.log(` Quarantined: ${s.quarantined} undecryptable delta(s) set aside (see errors)`),s.errors.length>0){console.log(""),console.log(" Errors:");for(const o of s.errors)console.log(` - ${o}`);process.exitCode=1}console.log("")}function re(){const e=M(W(F(import.meta.url)),"sync-daemon-entrypoint.js");return new q(e)}async function ce(e){S();const r=e[0]??"status",n=e.find(o=>o.startsWith("--interval="));let t;if(n){const o=Number(n.split("=")[1]);(!Number.isFinite(o)||o<=0)&&(console.error("\u2716 --interval= expects a positive number of minutes, got "+JSON.stringify(n)),process.exit(1)),t=o}const s=re();switch(r){case"start":{g()||(console.error("\u2718 Not logged in. Run `wyrm cloud login` first."),process.exit(1));const o=s.start({interval_minutes:t});o.ok||(console.error(`\u{F115D} sovereign-sync daemon: ${o.reason??"failed to start"}${o.pid?` (pid ${o.pid})`:""}`),process.exit(o.pid?0:1)),console.log(`\u{F115D} \u2713 sovereign-sync daemon started (pid ${o.pid}). Logs: ~/.wyrm/wyrm-sovereign-sync.log`);return}case"stop":{const o=s.stop();console.log(o.ok?"\u{F115D} \u2713 sovereign-sync daemon stopped":`\u{F115D} sovereign-sync daemon: ${o.reason??"failed to stop"}`);return}case"restart":{const o=K(t,s.status().state?.interval_ms);s.stop(),await new Promise(i=>{setTimeout(i,500)});const l=s.start({interval_minutes:o});console.log(l.ok?`\u{F115D} \u2713 sovereign-sync daemon restarted (pid ${l.pid}, every ${o} min)`:`\u{F115D} restart failed: ${l.reason??"unknown"}`);return}case"status":{const o=s.status();console.log("\u{F115D} Sovereign-sync daemon"),console.log(` Running: ${o.running?`\u2713 yes (pid ${o.pid})`:"\u2717 no"}`),o.state?.interval_ms&&console.log(` Interval: every ${o.state.interval_ms/6e4} min`),o.state?.started_ts&&console.log(` Started: ${x(o.state.started_ts)}`),o.state?.last_tick_ts&&(console.log(` Last tick: ${x(o.state.last_tick_ts)} (exit ${o.state.last_tick_exit??"\u2014"})`),o.state.last_tick_summary&&console.log(` Last result: ${o.state.last_tick_summary}`));return}default:console.error(`Unknown daemon action: ${r}. Use: start, stop, restart, status`),process.exit(1)}}async function le(e){S();const r=u.fromSession(),n=e.find(l=>!l.startsWith("-")),t=P(n??`wyrm-cloud-export-${new Date().toISOString().slice(0,10)}.json`);console.log(" Fetching account export\u2026");const s=await r.accountExport(),o=JSON.stringify(s,null,2);L(t,o,{mode:384}),console.log(""),console.log(`\u2713 Exported to ${t}`),console.log(""),console.log(` Account: ${s.account.email} (${s.account.id.slice(0,8)}\u2026)`),console.log(` Devices: ${s.devices.length}`),console.log(` Identities: ${s.identities.length}`),console.log(` Orgs: ${s.orgs.length}`),console.log(` Deltas: ${s.deltas.length}`),console.log(` Size: ${_(o.length)}`),console.log(""),console.log(" Deltas are still AES-256-GCM ciphertext. To decrypt them you"),console.log(` need the key at ${d()}. Back that up alongside this file.`),console.log("")}async function ie(e){e.includes("--confirm")||(console.error("\u2718 This permanently deletes your Wyrm Cloud account."),console.error(" Re-run with --confirm to proceed:"),console.error(" wyrm cloud delete --confirm"),process.exit(1));const n=g();n||(console.error("\u2718 Not logged in. Nothing to delete."),process.exit(1)),console.log(""),console.log("\u26A0 You are about to PERMANENTLY DELETE your Wyrm Cloud account."),console.log(""),console.log(` Account: ${n.email??n.account_id}`),console.log(` Server: ${n.base}`),console.log(""),console.log(" This wipes all encrypted blobs, devices, identities, and org"),console.log(" memberships you own. The local ~/.wyrm/cloud.key is kept so"),console.log(" any backups remain decryptable. This action CANNOT be undone."),console.log(""),(await N(' Type "DELETE my account" to confirm: ')).trim()!=="DELETE my account"&&(console.error("\u2718 Confirmation phrase did not match. Aborting."),process.exit(1)),await new u(n.base,n.session).accountDelete(),k(),console.log(""),console.log("\u2713 Account deleted on server."),console.log(`\u2713 Local session removed (${$}).`),console.log(` Kept: ${d()} (in case you need to decrypt an old export).`),console.log("")}function N(e){return new Promise(r=>{const n=B({input:process.stdin,output:process.stdout});n.question(e,t=>{n.close(),r(t)})})}async function ae(e){const r=e[0];if(r==="show"){const{keyToMnemonic:n}=await import("./recovery.js"),s=n().split(" ");console.log(""),console.log("\u{1F511} Wyrm Cloud recovery phrase (BIP39, 24 words)"),console.log("");for(let o=0;o<4;o++){const l=s.slice(o*6,o*6+6).map((i,a)=>`${String(o*6+a+1).padStart(2)}. ${i.padEnd(10)}`).join(" ");console.log(` ${l}`)}console.log(""),console.log(" Write these down on PAPER and keep them somewhere safe."),console.log(" Anyone with this phrase can decrypt your synced Wyrm memory."),console.log(" Wyrm Cloud has NO COPY of this. Lose it = lose your data."),console.log("");return}if(r==="restore"){const n=e.includes("--overwrite");console.log(""),console.log("\u{1F511} Restore master key from BIP39 recovery phrase"),console.log(""),console.log(" Enter your 24 words separated by spaces (case-insensitive)."),console.log(" Press Enter when done."),console.log("");const t=await N(" > "),{mnemonicToKey:s}=await import("./recovery.js"),{path:o,overwrote:l}=s(t,{overwrite:n});console.log(""),console.log(`\u2713 Master key restored to ${o} (0600)`),l&&console.log(" Replaced existing key (you passed --overwrite)."),console.log(" Run `wyrm cloud sync` to pull deltas with the restored key."),console.log("");return}console.error("Usage:"),console.error(" wyrm cloud recovery show"),console.error(" wyrm cloud recovery restore [--overwrite]"),process.exit(1)}export{be as cmdCloud};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{spawn as a}from"child_process";import{fileURLToPath as l}from"url";import{dirname as m,join as p}from"path";import{loadSession as d}from"./client.js";import{writeSovereignState as n,DEFAULT_SOVEREIGN_INTERVAL_MS as g}from"./sync-daemon.js";const
|
|
2
|
-
`)}function c(){return new Promise(e=>{const s=a(process.execPath,[
|
|
1
|
+
import{spawn as a}from"child_process";import{fileURLToPath as l}from"url";import{dirname as m,join as p}from"path";import{loadSession as d}from"./client.js";import{writeSovereignState as n,DEFAULT_SOVEREIGN_INTERVAL_MS as _,SOVEREIGN_PID_FILE as g,releasePidFileOnExit as u}from"./sync-daemon.js";const v=p(m(l(import.meta.url)),"..","wyrm-cli.js");function i(e){process.stdout.write(`[${new Date().toISOString()}] ${e}
|
|
2
|
+
`)}function c(){return new Promise(e=>{const s=a(process.execPath,[v,"cloud","sync"],{stdio:["ignore","pipe","pipe"],env:{...process.env}});let o="";s.stdout.on("data",t=>{o+=t.toString()}),s.stderr.on("data",t=>{o+=t.toString()}),s.on("close",t=>{const r=o.replace(/\s+/g," ").trim().slice(0,300);i(`tick exit=${t}: ${r}`),n({last_tick_ts:Date.now(),last_tick_exit:t,last_tick_summary:r}),e()}),s.on("error",t=>{i(`tick spawn error: ${t.message}`),n({last_tick_ts:Date.now(),last_tick_exit:null,last_tick_summary:`spawn error: ${t.message}`}),e()})})}async function I(){u(g);let e;const s=r=>{e&&clearInterval(e),i(`${r} \u2014 exiting`),process.exit(0)};process.on("SIGTERM",()=>s("SIGTERM")),process.on("SIGINT",()=>s("SIGINT"));const o=Number(process.argv[2])||_,t=d();(!t||!t.device_id)&&(console.error("[sovereign-sync] device not logged in (run `wyrm cloud login`) \u2014 refusing to start"),process.exit(2)),i(`sovereign-sync started \xB7 interval=${o}ms \xB7 device=${t.device_id.slice(0,8)}\u2026`),await c(),e=setInterval(()=>{c()},o)}I().catch(e=>{console.error("[sovereign-sync] fatal:",e),process.exit(1)});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{spawn as g}from"child_process";import{existsSync as
|
|
1
|
+
import{spawn as g}from"child_process";import{existsSync as d,readFileSync as o,writeFileSync as y,mkdirSync as v,openSync as S,closeSync as m,unlinkSync as f,statSync as P,renameSync as I}from"fs";import{homedir as k}from"os";import{basename as x,join as c}from"path";const i=c(k(),".wyrm"),a=c(i,"wyrm-sovereign-sync.pid"),n=c(i,"wyrm-sovereign-sync.log"),u=c(i,"wyrm-sovereign-sync.state"),L=1e6,A=0,h=600*1e3,V=a;function E(t){try{const e=Number(o(t,"utf8").trim());return Number.isInteger(e)&&e>0?e:void 0}catch{return}}function F(t,e){try{process.kill(t,A)}catch{return!1}let r;try{r=o(`/proc/${t}/cmdline`,"utf8")}catch{return!0}return r.includes(e)}function N(t,e){if(E(t)!==e)return!1;try{return f(t),!0}catch{return!1}}function J(t,e=process.pid){process.on("exit",()=>{N(t,e)})}class B{daemonEntrypoint;constructor(e){this.daemonEntrypoint=e,_()}start(e={}){if(this.isAlive())return{ok:!1,pid:this.readPid(),reason:"already running"};this.cleanPid(),R();const r=(e.interval_minutes??h/6e4)*6e4,l=S(n,"a"),p=S(n,"a"),s=g(process.execPath,[this.daemonEntrypoint,String(r)],{detached:!0,stdio:["ignore",l,p],env:{...process.env}});return s.unref(),m(l),m(p),typeof s.pid!="number"?{ok:!1,reason:"spawn returned no pid"}:(y(a,String(s.pid)),O({started_ts:Date.now(),interval_ms:r}),{ok:!0,pid:s.pid})}stop(){if(!this.isAlive())return this.cleanPid(),{ok:!1,reason:"not running"};const e=this.readPid();if(!e)return{ok:!1,reason:"pid file unreadable"};try{return process.kill(e,"SIGTERM"),{ok:!0}}catch(r){return{ok:!1,reason:r?.message??String(r)}}}status(){const e=this.isAlive();return e||this.cleanPid(),{running:e,pid:e?this.readPid():void 0,state:d(u)?w():void 0}}isAlive(){const e=this.readPid();return e!==void 0&&F(e,x(this.daemonEntrypoint))}readPid(){return E(a)}cleanPid(){try{f(a)}catch{}}}function M(t,e){return t&&t>0?t:e&&e>0?e/6e4:h/6e4}function O(t){_();let e={};try{e=JSON.parse(o(u,"utf8"))}catch{}y(u,JSON.stringify({...e,...t},null,2))}function _(){d(i)||v(i,{recursive:!0})}function w(){try{return JSON.parse(o(u,"utf8"))}catch{return}}function R(){if(d(n))try{if(P(n).size>L){const t=`${n}.1`;try{f(t)}catch{}I(n,t)}}catch{}}export{h as DEFAULT_SOVEREIGN_INTERVAL_MS,V as SOVEREIGN_PID_FILE,B as SovereignSyncManager,F as daemonProcessAlive,E as readPidFile,N as releasePidFile,J as releasePidFileOnExit,M as restartIntervalMinutes,O as writeSovereignState};
|