wyrm-mcp 9.5.1 → 9.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cloud/cli.js +3 -3
- package/dist/cloud/sync-engine.js +13 -13
- package/dist/maintenance.js +2 -2
- package/dist/metabolize.js +26 -9
- package/dist/self-maintenance.js +4 -4
- package/dist/tool-manifest-v2.json +1 -1
- package/dist/tool-manifest.json +1 -1
- package/dist/wyrm-manifest.json +1 -1
- package/package.json +1 -1
package/dist/cloud/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{randomBytes as R}from"node:crypto";import{writeFileSync as W}from"node:fs";import{homedir as M,hostname as F}from"node:os";import{resolve as j,dirname as B,join as U}from"node:path";import{fileURLToPath as G}from"node:url";import{createInterface as H}from"node:readline";import{CloudClient as g,CloudError as f,DEFAULT_BASE as v,SESSION_FILE as $,loadSession as y,saveSession as C,clearSession as
|
|
1
|
+
import{randomBytes as R}from"node:crypto";import{writeFileSync as W}from"node:fs";import{homedir as M,hostname as F}from"node:os";import{resolve as j,dirname as B,join as U}from"node:path";import{fileURLToPath as G}from"node:url";import{createInterface as H}from"node:readline";import{CloudClient as g,CloudError as f,DEFAULT_BASE as v,SESSION_FILE as $,loadSession as y,saveSession as C,clearSession as k}from"./client.js";import{getMasterKey as Y,keyExists as _,keyFilePath as m,decrypt as J}from"./crypto.js";import{computeMachineFp as I,classifySession as q,cloudMachineId as K}from"./machine-id.js";import{runSync as z,CopiedSessionError as V,pendingPush as X,peekCursor as Q,parseSince as Z}from"./sync-engine.js";import{SyncLockedError as ee,EX_TEMPFAIL as oe}from"./sync-lock.js";import{WyrmDB as se,resolveDbPath as ne}from"../database.js";import{redactCredentials as te}from"../security.js";import{SovereignSyncManager as re,restartIntervalMinutes as ce}from"./sync-daemon.js";import{initializeLicense as le,hasFeature as ie,getTier as ae}from"../license.js";function S(){le(),ie("cloud_backup")||(console.error("\u{F115D} Wyrm Cloud sync requires a Pro license or higher."),console.error(` Current tier: ${ae()}`),console.error(" Get Pro: write to support@ghosts.lk"),console.error(" Details: 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 b(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":"never"}async function Be(e){const t=e[0],n=e.slice(1);try{switch(t){case void 0:case"help":case"--help":case"-h":return de();case"login":return await ue(n);case"logout":return await ge();case"status":return await me(n);case"doctor":return pe();case"devices":return await fe(n);case"sync":return await $e(n);case"daemon":return await _e(n);case"export":return await Se(n);case"delete":return await be(n);case"recovery":return await xe(n);default:console.error(`Unknown subcommand: wyrm cloud ${t}`),console.error("Try `wyrm cloud help`"),process.exit(1)}}catch(o){if(o instanceof ee&&(console.error(o.message),process.exit(oe)),o instanceof V&&process.exit(1),o instanceof f)o.status===401?console.error("\u2718 Not authenticated. Run `wyrm cloud login`."):o.status===403?console.error(`\u2718 Forbidden: ${o.message}`):o.status===0?(console.error(`\u2718 ${o.message}`),console.error(" Check your internet connection. If wyrm.ghosts.lk is unreachable, see status at https://www.cloudflarestatus.com")):o.status===501?console.error(`\u2718 Service not configured: ${o.message}`):console.error(`\u2718 ${o.message} (HTTP ${o.status})`);else if(o instanceof Error){const r=o.message;r.includes("Not logged in")?console.error("\u2718 Not logged in. Run `wyrm cloud login`."):r.includes("Wyrm Cloud key")?console.error(`\u2718 Encryption-key error: ${r}`):console.error(`\u2718 ${r}`)}else console.error("\u2718 Unexpected error:",o);process.exit(1)}}function de(){console.log(`\u{F115D} wyrm cloud: sync your Wyrm memory across devices
|
|
2
2
|
|
|
3
3
|
USAGE:
|
|
4
4
|
wyrm cloud <subcommand> [args]
|
|
@@ -50,6 +50,6 @@ CONSTITUTION:
|
|
|
50
50
|
|
|
51
51
|
DOMAIN:
|
|
52
52
|
https://wyrm.ghosts.lk
|
|
53
|
-
`)}async function ue(e){const t=y();if(t)try{await new g(t.base,t.session).me(),console.error("Already logged in. Run `wyrm cloud logout` first to switch accounts."),process.exit(1)}catch(i){i instanceof f&&i.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."),
|
|
53
|
+
`)}async function ue(e){const t=y();if(t)try{await new g(t.base,t.session).me(),console.error("Already logged in. Run `wyrm cloud logout` first to switch accounts."),process.exit(1)}catch(i){i instanceof f&&i.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 g(v),o=R(32).toString("hex");let r;try{r=await n.cliInit(o)}catch(i){console.error(`\u2718 Could not start login: ${i instanceof Error?i.message:i}`),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(` ${r.browser_url}`),console.log(""),console.log(" 2. Type this code when prompted:"),console.log(` ${r.code}`),console.log(""),console.log(" 3. Sign in with Google or GitHub."),console.log(""),console.log(` Waiting (expires in ${Math.round(r.expires_in_sec/60)} min)\u2026`);const c=Date.now()+r.expires_in_sec*1e3;let l,a;for(;Date.now()<c;){await new Promise(i=>{setTimeout(i,3e3)});try{const i=await n.cliPoll(o);if(i.ready&&i.session){l=i.session,a=i.account_id;break}}catch(i){console.error(`
|
|
54
54
|
\u2718 Login failed: ${i instanceof Error?i.message:i}`),process.exit(1)}}(!l||!a)&&(console.error("\n\u2718 Login timed out. Run `wyrm cloud login` again."),process.exit(1)),C({base:v,session:l,account_id:a,created_at:Date.now()});const d=new g(v,l);let u="";try{u=(await d.me()).account.email}catch{}const h=`${F()} (${process.platform})`;let p;try{p=(await d.registerDevice(h,void 0,K())).device.id;const w=y();w&&C({...w,email:u,device_id:p,device_name:h,machine_fp:I()})}catch(i){console.error(`
|
|
55
|
-
\u26A0 Logged in but could not register device: ${i instanceof Error?i.message:i}`),console.error(" Re-run `wyrm cloud login` to retry.");return}console.log(""),console.log(`\u2713 Signed in as ${u}`),console.log(`\u2713 Device registered: ${h}`),console.log(`\u2713 Session saved to ${$}`);const L=!k();if(Y(),L?(console.log(`\u2713 Encryption key generated at ${m()} (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; 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 ${m()}`),p)try{const i=await d.syncStatus();if(i.deltas>0){const E=(await d.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 ${m()} cannot decrypt`),console.log(` the ${i.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: a connected pipe that carries nothing."),console.log(""),console.log(" Fix: adopt the account key on this device by running"),console.log(" wyrm cloud recovery restore (needs the account's 24-word phrase)"),console.log(` Heads-up: restore OVERWRITES ${m()}. 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 ge(){const e=y();if(!e){console.log("Not logged in.");return}try{await new g(e.base,e.session).logout(),console.log("\u2713 Session revoked server-side.")}catch(t){console.error(`\u26A0 Could not revoke server-side: ${t instanceof Error?t.message:t}`),console.error(" Local session cleared anyway.")}_(),console.log(`\u2713 Local session removed (${$}).`),console.log(" Note: ~/.wyrm/cloud.key kept. Delete manually if you want a clean slate.")}function D(e){const t=new se(ne());try{const n=X(t,{all:e}),o=Q(t.getDatabase());for(const r of n.errors)console.error(`\u26A0 pending count: ${r}`);return{...n,last_push_at:o.last_push_at,last_push_attempt_at:o.last_push_attempt_at,last_pull_at:o.last_pull_at}}finally{try{t.close()}catch{}}}const N="Session expired or invalid. Run `wyrm cloud login` again.";function O(e){const t=e?.message,n=typeof t=="string"?t:String(e),o=M();return te(o&&o!=="/"?n.split(o).join("~"):n)}async function me(e){const t=e.includes("--json"),n=e.includes("--all"),o=y();if(!o){if(t){console.log(JSON.stringify({logged_in:!1})),process.exitCode=1;return}console.log("Not logged in. Run `wyrm cloud login`.");return}if(t)return ye(o,n);let r;try{const c=D(n);r=`${c.rows} row(s), ${c.tombstones} tombstone(s) not yet pushed`}catch(c){r=`unknown (${O(c)})`}const s=new g(o.base,o.session);try{const c=await s.me(),l=await s.syncStatus();console.log(""),console.log(`\u{F115D} Wyrm Cloud: ${c.account.email}`),console.log(""),console.log(` Tier: ${l.tier}`),console.log(` Storage: ${b(l.storage.used_bytes)} / ${b(l.storage.limit_bytes)} (${l.storage.percent}%)`),console.log(` Deltas: ${l.deltas}`),console.log(` Devices: ${l.devices}`),console.log(` Pending: ${r}`),console.log(` Providers:${c.identities.map(a=>" "+a.provider).join(",")}`),console.log(""),console.log(` This machine: ${o.device_name??"(not registered)"}`),console.log(` Device ID: ${o.device_id?o.device_id.slice(0,8)+"\u2026":"(none)"}`),console.log(` Session age: ${Math.round((Date.now()-o.created_at)/(1440*60*1e3))} day(s)`),P(o),console.log(""),k()?l.deltas>0&&(console.log(` Key: ${m()} (0600)`),console.log(` \u26A0 Back this file up. Losing it = losing access to your ${l.deltas} deltas.`),console.log("")):(console.log(" \u26A0 ENCRYPTION KEY MISSING"),console.log(` Expected at: ${m()}`),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(c){throw c instanceof f&&c.status===401&&(console.error(N),process.exit(1)),c}}async function ye(e,t){const n=e.device_id?e.device_id.slice(0,8):null;let o;try{o=D(t)}catch(s){console.log(JSON.stringify({logged_in:!0,device:n,error:`store: ${O(s)}`})),process.exitCode=2;return}let r;try{const s=await new g(e.base,e.session).syncStatus();r={ok:!0,tier:s.tier,deltas:s.deltas,devices:s.devices}}catch(s){r={ok:!1,error:s instanceof f&&s.status===401?N:s instanceof Error?s.message:String(s)}}console.log(JSON.stringify({logged_in:!0,device:n,push:{mark_ms:o.mark_ms,mark_iso:o.mark_ms>0?new Date(o.mark_ms).toISOString():null,last_push_at:o.last_push_at,last_push_attempt_at:o.last_push_attempt_at,pending_rows:o.rows,pending_tombstones:o.tombstones,mode:t?"all":"default"},pull:{last_pull_at:o.last_pull_at},remote:r}))}function P(e){const t=q(e.machine_fp);t.state==="match"?console.log(" Identity: \u2713 machine fingerprint matches (not a copied session)"):t.state==="adopt"?console.log(" Identity: no fingerprint yet (pre-7.0.3 session; adopted on next sync)"):(console.log(" Identity: \u26A0 FINGERPRINT MISMATCH: this session looks COPIED"),console.log(` stored ${t.stored.slice(0,12)}\u2026 vs this machine ${t.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 pe(){const e=y();if(console.log(""),console.log("\u{F115D} Wyrm Cloud: 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; 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, pre-7.0.3 session)"}`),console.log(` This box fp: ${I().slice(0,12)}\u2026`),P(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 fe(e){const t=e[0],n=g.fromSession();if(t==="revoke"){const l=e[1];l||(console.error("Usage: wyrm cloud devices revoke <device-id>"),process.exit(1));const a=await he(n,l);await n.revokeDevice(a),console.log(`\u2713 Device ${a.slice(0,8)}\u2026 revoked.`);return}const o=e.includes("--full"),{devices:r}=await n.listDevices(),c=y()?.device_id;console.log(""),console.log(`\u{F115D} Devices (${r.length})`),console.log("");for(const l of r){const a=l.id===c?"\u2605":" ",d=l.revoked?"(revoked)":"",u=o?l.id:`${l.id.slice(0,8)}\u2026`;console.log(` ${a} ${u} ${l.name.padEnd(30)} last_seen=${x(l.last_seen_at)} ${d}`)}console.log(""),console.log(" \u2605 = this machine"),console.log(" Revoke: wyrm cloud devices revoke <device-id> (an id prefix as shown above is fine)"),o||console.log(" Full ids: wyrm cloud devices --full"),console.log("")}async function he(e,t){const n=t.replace(/[….]+$/,"").trim().toLowerCase(),{devices:o}=await e.listDevices(),r=o.find(c=>c.id.toLowerCase()===n);if(r)return r.id;const s=o.filter(c=>c.id.toLowerCase().startsWith(n));if(s.length===1)return s[0].id;s.length===0&&(console.error(`\u2718 No device matches "${t}". List them with: wyrm cloud devices`),process.exit(1)),console.error(`\u2718 "${t}" is ambiguous; it matches ${s.length} devices:`);for(const c of s)console.error(` ${c.id} ${c.name}`);console.error(" Re-run with more characters, or the full id."),process.exit(1)}const we=new Set(["--dry-run","--all","--force","--since"]);function ve(e){for(let t=0;t<e.length;t++){const n=e[t];if(n==="--since"){t++;continue}if(!(n.startsWith("--since=")||we.has(n)))return n}}async function $e(e){const t=ve(e);if(t!==void 0){console.error(`\u2718 Unknown flag for \`wyrm cloud sync\`: ${t}`),console.error(" It takes --dry-run, --all, --force and --since <when>. See `wyrm cloud help`."),process.exitCode=1;return}let n;const o=e.findIndex(d=>d==="--since"||d.startsWith("--since="));if(o>=0){const d=e[o];try{n=Z(d==="--since"?e[o+1]??"":d.slice(8))}catch(u){console.error(`\u2718 ${u instanceof Error?u.message:u}`),process.exitCode=1;return}}const r=e.includes("--dry-run"),s=e.includes("--all"),c=e.includes("--force");S(),k()||(console.error("\u26A0 Encryption key not found at",m()),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. Press Ctrl+C to abort."),await new Promise(d=>{setTimeout(d,5e3)}));const a=await z({dryRun:r,all:s,force:c,sinceMs:n,onStart:()=>{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("")),n!==void 0&&console.log(` --since ${new Date(n).toISOString()}: rows changed at or after it are collected, below the push mark too.`)}});if(console.log(""),console.log(a.errors.length>0?"\u{F115D} Sync finished with errors":"\u{F115D} Sync complete"),console.log(""),console.log(` Pushed: ${a.pushed} row(s)${r?" (dry run)":""}`),console.log(` Pulled: ${a.pulled} row(s)`),console.log(` Deleted: ${a.deleted_local} row(s) (peer tombstones)`),a.quarantined&&a.quarantined>0&&console.log(` Quarantined: ${a.quarantined} undecryptable delta(s) set aside (see errors)`),a.errors.length>0){console.log(""),console.log(" Errors:");for(const d of a.errors)console.log(` - ${d}`);process.exitCode=1}console.log("")}function _e(){const e=U(B(G(import.meta.url)),"sync-daemon-entrypoint.js");return new re(e)}async function ke(e){S();const t=e[0]??"status",n=e.find(s=>s.startsWith("--interval="));let o;if(n){const s=Number(n.split("=")[1]);(!Number.isFinite(s)||s<=0)&&(console.error("\u2716 --interval= expects a positive number of minutes, got "+JSON.stringify(n)),process.exit(1)),o=s}const r=_e();switch(t){case"start":{y()||(console.error("\u2718 Not logged in. Run `wyrm cloud login` first."),process.exit(1));const s=r.start({interval_minutes:o});s.ok||(console.error(`\u{F115D} sovereign-sync daemon: ${s.reason??"failed to start"}${s.pid?` (pid ${s.pid})`:""}`),process.exit(s.pid?0:1)),console.log(`\u{F115D} \u2713 sovereign-sync daemon started (pid ${s.pid}). Logs: ~/.wyrm/wyrm-sovereign-sync.log`);return}case"stop":{const s=r.stop();console.log(s.ok?"\u{F115D} \u2713 sovereign-sync daemon stopped":`\u{F115D} sovereign-sync daemon: ${s.reason??"failed to stop"}`);return}case"restart":{const s=ce(o,r.status().state?.interval_ms);r.stop(),await new Promise(l=>{setTimeout(l,500)});const c=r.start({interval_minutes:s});console.log(c.ok?`\u{F115D} \u2713 sovereign-sync daemon restarted (pid ${c.pid}, every ${s} min)`:`\u{F115D} restart failed: ${c.reason??"unknown"}`);return}case"status":{const s=r.status();console.log("\u{F115D} Sovereign-sync daemon"),console.log(` Running: ${s.running?`\u2713 yes (pid ${s.pid})`:"\u2717 no"}`),s.state?.interval_ms&&console.log(` Interval: every ${s.state.interval_ms/6e4} min`),s.state?.started_ts&&console.log(` Started: ${x(s.state.started_ts)}`),s.state?.last_tick_ts&&(console.log(` Last tick: ${x(s.state.last_tick_ts)} (exit ${s.state.last_tick_exit??"n/a"})`),s.state.last_tick_summary&&console.log(` Last result: ${s.state.last_tick_summary}`));return}default:console.error(`Unknown daemon action: ${t}. Use: start, stop, restart, status`),process.exit(1)}}async function Se(e){S();const t=g.fromSession(),n=e.find(c=>!c.startsWith("-")),o=j(n??`wyrm-cloud-export-${new Date().toISOString().slice(0,10)}.json`);console.log(" Fetching account export\u2026");const r=await t.accountExport(),s=JSON.stringify(r,null,2);W(o,s,{mode:384}),console.log(""),console.log(`\u2713 Exported to ${o}`),console.log(""),console.log(` Account: ${r.account.email} (${r.account.id.slice(0,8)}\u2026)`),console.log(` Devices: ${r.devices.length}`),console.log(` Identities: ${r.identities.length}`),console.log(` Orgs: ${r.orgs.length}`),console.log(` Deltas: ${r.deltas.length}`),console.log(` Size: ${b(s.length)}`),console.log(""),console.log(" Deltas are still AES-256-GCM ciphertext. To decrypt them you"),console.log(` need the key at ${m()}. Back that up alongside this file.`),console.log("")}async function be(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=y();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 A(' Type "DELETE my account" to confirm: ')).trim()!=="DELETE my account"&&(console.error("\u2718 Confirmation phrase did not match. Aborting."),process.exit(1)),await new g(n.base,n.session).accountDelete(),_(),console.log(""),console.log("\u2713 Account deleted on server."),console.log(`\u2713 Local session removed (${$}).`),console.log(` Kept: ${m()} (in case you need to decrypt an old export).`),console.log("")}function A(e){return new Promise(t=>{const n=H({input:process.stdin,output:process.stdout});n.question(e,o=>{n.close(),t(o)})})}async function xe(e){const t=e[0];if(t==="show"){const{keyToMnemonic:n}=await import("./recovery.js"),r=n().split(" ");console.log(""),console.log("\u{1F511} Wyrm Cloud recovery phrase (BIP39, 24 words)"),console.log("");for(let s=0;s<4;s++){const c=r.slice(s*6,s*6+6).map((l,a)=>`${String(s*6+a+1).padStart(2)}. ${l.padEnd(10)}`).join(" ");console.log(` ${c}`)}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(t==="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 o=await A(" > "),{mnemonicToKey:r}=await import("./recovery.js"),{path:s,overwrote:c}=r(o,{overwrite:n});console.log(""),console.log(`\u2713 Master key restored to ${s} (0600)`),c&&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};
|
|
55
|
+
\u26A0 Logged in but could not register device: ${i instanceof Error?i.message:i}`),console.error(" Re-run `wyrm cloud login` to retry.");return}console.log(""),console.log(`\u2713 Signed in as ${u}`),console.log(`\u2713 Device registered: ${h}`),console.log(`\u2713 Session saved to ${$}`);const L=!_();if(Y(),L?(console.log(`\u2713 Encryption key generated at ${m()} (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; 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 ${m()}`),p)try{const i=await d.syncStatus();if(i.deltas>0){const E=(await d.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 ${m()} cannot decrypt`),console.log(` the ${i.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: a connected pipe that carries nothing."),console.log(""),console.log(" Fix: adopt the account key on this device by running"),console.log(" wyrm cloud recovery restore (needs the account's 24-word phrase)"),console.log(` Heads-up: restore OVERWRITES ${m()}. 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 ge(){const e=y();if(!e){console.log("Not logged in.");return}try{await new g(e.base,e.session).logout(),console.log("\u2713 Session revoked server-side.")}catch(t){console.error(`\u26A0 Could not revoke server-side: ${t instanceof Error?t.message:t}`),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.")}function D(e){const t=new se(ne());try{const n=X(t,{all:e}),o=Q(t.getDatabase());for(const r of n.errors)console.error(`\u26A0 pending count: ${r}`);return{...n,last_push_at:o.last_push_at,last_push_attempt_at:o.last_push_attempt_at,last_pull_at:o.last_pull_at}}finally{try{t.close()}catch{}}}const N="Session expired or invalid. Run `wyrm cloud login` again.";function O(e){const t=e?.message,n=typeof t=="string"?t:String(e),o=M();return te(o&&o!=="/"?n.split(o).join("~"):n)}async function me(e){const t=e.includes("--json"),n=e.includes("--all"),o=y();if(!o){if(t){console.log(JSON.stringify({logged_in:!1})),process.exitCode=1;return}console.log("Not logged in. Run `wyrm cloud login`.");return}if(t)return ye(o,n);let r;try{const c=D(n);r=c.refused?`none: sync is refused for this store. ${c.refused}`:`${c.rows} row(s), ${c.tombstones} tombstone(s) not yet pushed`}catch(c){r=`unknown (${O(c)})`}const s=new g(o.base,o.session);try{const c=await s.me(),l=await s.syncStatus();console.log(""),console.log(`\u{F115D} Wyrm Cloud: ${c.account.email}`),console.log(""),console.log(` Tier: ${l.tier}`),console.log(` Storage: ${b(l.storage.used_bytes)} / ${b(l.storage.limit_bytes)} (${l.storage.percent}%)`),console.log(` Deltas: ${l.deltas}`),console.log(` Devices: ${l.devices}`),console.log(` Pending: ${r}`),console.log(` Providers:${c.identities.map(a=>" "+a.provider).join(",")}`),console.log(""),console.log(` This machine: ${o.device_name??"(not registered)"}`),console.log(` Device ID: ${o.device_id?o.device_id.slice(0,8)+"\u2026":"(none)"}`),console.log(` Session age: ${Math.round((Date.now()-o.created_at)/(1440*60*1e3))} day(s)`),P(o),console.log(""),_()?l.deltas>0&&(console.log(` Key: ${m()} (0600)`),console.log(` \u26A0 Back this file up. Losing it = losing access to your ${l.deltas} deltas.`),console.log("")):(console.log(" \u26A0 ENCRYPTION KEY MISSING"),console.log(` Expected at: ${m()}`),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(c){throw c instanceof f&&c.status===401&&(console.error(N),process.exit(1)),c}}async function ye(e,t){const n=e.device_id?e.device_id.slice(0,8):null;let o;try{o=D(t)}catch(s){console.log(JSON.stringify({logged_in:!0,device:n,error:`store: ${O(s)}`})),process.exitCode=2;return}let r;try{const s=await new g(e.base,e.session).syncStatus();r={ok:!0,tier:s.tier,deltas:s.deltas,devices:s.devices}}catch(s){r={ok:!1,error:s instanceof f&&s.status===401?N:s instanceof Error?s.message:String(s)}}console.log(JSON.stringify({logged_in:!0,device:n,push:{mark_ms:o.mark_ms,mark_iso:o.mark_ms>0?new Date(o.mark_ms).toISOString():null,last_push_at:o.last_push_at,last_push_attempt_at:o.last_push_attempt_at,pending_rows:o.rows,pending_tombstones:o.tombstones,...o.refused?{refused:o.refused}:{},mode:t?"all":"default"},pull:{last_pull_at:o.last_pull_at},remote:r}))}function P(e){const t=q(e.machine_fp);t.state==="match"?console.log(" Identity: \u2713 machine fingerprint matches (not a copied session)"):t.state==="adopt"?console.log(" Identity: no fingerprint yet (pre-7.0.3 session; adopted on next sync)"):(console.log(" Identity: \u26A0 FINGERPRINT MISMATCH: this session looks COPIED"),console.log(` stored ${t.stored.slice(0,12)}\u2026 vs this machine ${t.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 pe(){const e=y();if(console.log(""),console.log("\u{F115D} Wyrm Cloud: 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; 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, pre-7.0.3 session)"}`),console.log(` This box fp: ${I().slice(0,12)}\u2026`),P(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 fe(e){const t=e[0],n=g.fromSession();if(t==="revoke"){const l=e[1];l||(console.error("Usage: wyrm cloud devices revoke <device-id>"),process.exit(1));const a=await he(n,l);await n.revokeDevice(a),console.log(`\u2713 Device ${a.slice(0,8)}\u2026 revoked.`);return}const o=e.includes("--full"),{devices:r}=await n.listDevices(),c=y()?.device_id;console.log(""),console.log(`\u{F115D} Devices (${r.length})`),console.log("");for(const l of r){const a=l.id===c?"\u2605":" ",d=l.revoked?"(revoked)":"",u=o?l.id:`${l.id.slice(0,8)}\u2026`;console.log(` ${a} ${u} ${l.name.padEnd(30)} last_seen=${x(l.last_seen_at)} ${d}`)}console.log(""),console.log(" \u2605 = this machine"),console.log(" Revoke: wyrm cloud devices revoke <device-id> (an id prefix as shown above is fine)"),o||console.log(" Full ids: wyrm cloud devices --full"),console.log("")}async function he(e,t){const n=t.replace(/[….]+$/,"").trim().toLowerCase(),{devices:o}=await e.listDevices(),r=o.find(c=>c.id.toLowerCase()===n);if(r)return r.id;const s=o.filter(c=>c.id.toLowerCase().startsWith(n));if(s.length===1)return s[0].id;s.length===0&&(console.error(`\u2718 No device matches "${t}". List them with: wyrm cloud devices`),process.exit(1)),console.error(`\u2718 "${t}" is ambiguous; it matches ${s.length} devices:`);for(const c of s)console.error(` ${c.id} ${c.name}`);console.error(" Re-run with more characters, or the full id."),process.exit(1)}const we=new Set(["--dry-run","--all","--force","--since"]);function ve(e){for(let t=0;t<e.length;t++){const n=e[t];if(n==="--since"){t++;continue}if(!(n.startsWith("--since=")||we.has(n)))return n}}async function $e(e){const t=ve(e);if(t!==void 0){console.error(`\u2718 Unknown flag for \`wyrm cloud sync\`: ${t}`),console.error(" It takes --dry-run, --all, --force and --since <when>. See `wyrm cloud help`."),process.exitCode=1;return}let n;const o=e.findIndex(d=>d==="--since"||d.startsWith("--since="));if(o>=0){const d=e[o];try{n=Z(d==="--since"?e[o+1]??"":d.slice(8))}catch(u){console.error(`\u2718 ${u instanceof Error?u.message:u}`),process.exitCode=1;return}}const r=e.includes("--dry-run"),s=e.includes("--all"),c=e.includes("--force");S(),_()||(console.error("\u26A0 Encryption key not found at",m()),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. Press Ctrl+C to abort."),await new Promise(d=>{setTimeout(d,5e3)}));const a=await z({dryRun:r,all:s,force:c,sinceMs:n,onStart:()=>{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("")),n!==void 0&&console.log(` --since ${new Date(n).toISOString()}: rows changed at or after it are collected, below the push mark too.`)}});if(console.log(""),console.log(a.errors.length>0?"\u{F115D} Sync finished with errors":"\u{F115D} Sync complete"),console.log(""),console.log(` Pushed: ${a.pushed} row(s)${r?" (dry run)":""}`),console.log(` Pulled: ${a.pulled} row(s)`),console.log(` Deleted: ${a.deleted_local} row(s) (peer tombstones)`),a.quarantined&&a.quarantined>0&&console.log(` Quarantined: ${a.quarantined} undecryptable delta(s) set aside (see errors)`),a.skipped_tables&&a.skipped_tables.length>0&&console.log(` Skipped tables this Wyrm does not know: ${a.skipped_tables.join(", ")} (not sent; a newer Wyrm syncs them)`),a.errors.length>0){console.log(""),console.log(" Errors:");for(const d of a.errors)console.log(` - ${d}`);process.exitCode=1}console.log("")}function ke(){const e=U(B(G(import.meta.url)),"sync-daemon-entrypoint.js");return new re(e)}async function _e(e){S();const t=e[0]??"status",n=e.find(s=>s.startsWith("--interval="));let o;if(n){const s=Number(n.split("=")[1]);(!Number.isFinite(s)||s<=0)&&(console.error("\u2716 --interval= expects a positive number of minutes, got "+JSON.stringify(n)),process.exit(1)),o=s}const r=ke();switch(t){case"start":{y()||(console.error("\u2718 Not logged in. Run `wyrm cloud login` first."),process.exit(1));const s=r.start({interval_minutes:o});s.ok||(console.error(`\u{F115D} sovereign-sync daemon: ${s.reason??"failed to start"}${s.pid?` (pid ${s.pid})`:""}`),process.exit(s.pid?0:1)),console.log(`\u{F115D} \u2713 sovereign-sync daemon started (pid ${s.pid}). Logs: ~/.wyrm/wyrm-sovereign-sync.log`);return}case"stop":{const s=r.stop();console.log(s.ok?"\u{F115D} \u2713 sovereign-sync daemon stopped":`\u{F115D} sovereign-sync daemon: ${s.reason??"failed to stop"}`);return}case"restart":{const s=ce(o,r.status().state?.interval_ms);r.stop(),await new Promise(l=>{setTimeout(l,500)});const c=r.start({interval_minutes:s});console.log(c.ok?`\u{F115D} \u2713 sovereign-sync daemon restarted (pid ${c.pid}, every ${s} min)`:`\u{F115D} restart failed: ${c.reason??"unknown"}`);return}case"status":{const s=r.status();console.log("\u{F115D} Sovereign-sync daemon"),console.log(` Running: ${s.running?`\u2713 yes (pid ${s.pid})`:"\u2717 no"}`),s.state?.interval_ms&&console.log(` Interval: every ${s.state.interval_ms/6e4} min`),s.state?.started_ts&&console.log(` Started: ${x(s.state.started_ts)}`),s.state?.last_tick_ts&&(console.log(` Last tick: ${x(s.state.last_tick_ts)} (exit ${s.state.last_tick_exit??"n/a"})`),s.state.last_tick_summary&&console.log(` Last result: ${s.state.last_tick_summary}`));return}default:console.error(`Unknown daemon action: ${t}. Use: start, stop, restart, status`),process.exit(1)}}async function Se(e){S();const t=g.fromSession(),n=e.find(c=>!c.startsWith("-")),o=j(n??`wyrm-cloud-export-${new Date().toISOString().slice(0,10)}.json`);console.log(" Fetching account export\u2026");const r=await t.accountExport(),s=JSON.stringify(r,null,2);W(o,s,{mode:384}),console.log(""),console.log(`\u2713 Exported to ${o}`),console.log(""),console.log(` Account: ${r.account.email} (${r.account.id.slice(0,8)}\u2026)`),console.log(` Devices: ${r.devices.length}`),console.log(` Identities: ${r.identities.length}`),console.log(` Orgs: ${r.orgs.length}`),console.log(` Deltas: ${r.deltas.length}`),console.log(` Size: ${b(s.length)}`),console.log(""),console.log(" Deltas are still AES-256-GCM ciphertext. To decrypt them you"),console.log(` need the key at ${m()}. Back that up alongside this file.`),console.log("")}async function be(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=y();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 A(' Type "DELETE my account" to confirm: ')).trim()!=="DELETE my account"&&(console.error("\u2718 Confirmation phrase did not match. Aborting."),process.exit(1)),await new g(n.base,n.session).accountDelete(),k(),console.log(""),console.log("\u2713 Account deleted on server."),console.log(`\u2713 Local session removed (${$}).`),console.log(` Kept: ${m()} (in case you need to decrypt an old export).`),console.log("")}function A(e){return new Promise(t=>{const n=H({input:process.stdin,output:process.stdout});n.question(e,o=>{n.close(),t(o)})})}async function xe(e){const t=e[0];if(t==="show"){const{keyToMnemonic:n}=await import("./recovery.js"),r=n().split(" ");console.log(""),console.log("\u{1F511} Wyrm Cloud recovery phrase (BIP39, 24 words)"),console.log("");for(let s=0;s<4;s++){const c=r.slice(s*6,s*6+6).map((l,a)=>`${String(s*6+a+1).padStart(2)}. ${l.padEnd(10)}`).join(" ");console.log(` ${c}`)}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(t==="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 o=await A(" > "),{mnemonicToKey:r}=await import("./recovery.js"),{path:s,overwrote:c}=r(o,{overwrite:n});console.log(""),console.log(`\u2713 Master key restored to ${s} (0600)`),c&&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,5 +1,5 @@
|
|
|
1
|
-
import{readFileSync as
|
|
2
|
-
WHERE type='table' AND name NOT LIKE 'sqlite_%'`).all();for(const
|
|
1
|
+
import{readFileSync as oe,writeFileSync as ae,existsSync as ie}from"node:fs";import{join as ce}from"node:path";import{createHash as W}from"node:crypto";import{WyrmDB as le,resolveDbPath as ue}from"../database.js";import{getLineage as de,getCursor as A,setCursor as pe,importCursorFile as _e,bumpDeviceEpoch as fe,mirrorStamp as H}from"../lineage.js";import{CloudClient as he,CloudError as me,loadSession as ye,saveSession as ge,resolveCloudDir as Ee}from"./client.js";import{encrypt as we,decrypt as be}from"./crypto.js";import{classifySession as Se,computeMachineFp as Ne}from"./machine-id.js";import{redactInboundRow as C}from"../inbound-redact.js";import{acquireSyncLock as Te}from"./sync-lock.js";import{schemaSkew as q}from"../migrations.js";function M(){return ce(Ee(),"cloud-cursor.json")}const V=2;function ke(e,t,r,s){const o=e?{...e}:{kind:t.kind,row_id:t.row_id,attempts:0,quarantined:!1,last_error:r,first_ms:s,last_ms:s};o.attempts+=1,o.last_error=r,o.last_ms=s;const n=o.attempts>=V,c=n&&!o.quarantined;return n&&(o.quarantined=!0),{entry:o,action:n?"skip":"retry",newlyQuarantined:c}}const O=[{kind:"truth",table:"ground_truths",hasVisibility:!0},{kind:"memory_artifact",table:"memory_artifacts",hasVisibility:!0},{kind:"quest",table:"quests",hasVisibility:!0},{kind:"design_token",table:"design_tokens",hasVisibility:!0},{kind:"design_reference",table:"design_references",hasVisibility:!0},{kind:"skill",table:"skills",hasVisibility:!0}],Ie=new Set(["sessions","agent_actions","agent_presence","session_seen_artifacts","tool_call_log","llm_query_log","external_call_log","token_savings_log","cost_tracking","usage_events","audit_log","indexing_queue","vectors","symbol_index","update_check","sync_conflicts","sync_log","sync_tombstones","wyrm_cloud_sync_state","cloud_push_ledger","mcp_client_configs","watch_dirs","global_context","schema_versions","failure_patterns","data_lake","projects"]),Oe=new Set(["context","entities","entity_aliases","relationships","reasoning_scaffolds","decision_edges","goals","goal_iterations","specs","failure_blocks","routing_memory","failure_anchors","write_ledger","metrics_snapshots","threads","erasure_log","failure_pattern_history","review_sample","audit_checkpoints"]);class Y extends Error{constructor(t,r){super(`This store was upgraded by a newer Wyrm (schema v${t}; this Wyrm knows up to v${r}), so it was not synced: update Wyrm before syncing. Nothing was sent. Run \`wyrm update\`, then sync again.`),this.name="NewerStoreSyncError"}}function G(e){const t=q(e);if(t.storeIsNewer)throw new Y(t.store,t.binary)}const Re=/_fts(_config|_data|_docsize|_idx)?$/;function Le(e){return B(e).tables}function B(e){const t=e.getDatabase(),r=[...O],s=[],o=new Set(O.map(n=>n.table));try{const n=t.prepare(`SELECT name FROM sqlite_master
|
|
2
|
+
WHERE type='table' AND name NOT LIKE 'sqlite_%'`).all();for(const c of n){const a=c.name;if(o.has(a)||Ie.has(a)||Re.test(a)||!N.test(a))continue;const i=t.prepare(`PRAGMA table_info(${a})`).all();if(!i.some(p=>p.name==="id"))continue;if(!Oe.has(a)){s.push(a);continue}const l=i.some(p=>p.name==="cross_project_visibility");r.push({kind:a,table:a,hasVisibility:l})}}catch{}return{tables:r,skipped:s.sort()}}function ht(e){return e}function X(e,t){if(!N.test(t))return new Set;try{const s=e.getDatabase().prepare(`PRAGMA table_info(${t})`).all();return new Set(s.filter(o=>N.test(o.name)).map(o=>o.name))}catch{return new Set}}const N=/^[a-z_][a-z0-9_]*$/i;function J(){const e=M();if(!ie(e))return null;try{const t=JSON.parse(oe(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function $e(e){const t={pull_cursor:0,last_push_updated_ms:0,last_push_at:0,last_push_attempt_at:0,last_pull_at:0},r=de(e),s=J();let o=A(e,"cloud");if(!o){if(_e(e,"cloud",M()),o=A(e,"cloud"),!o){if(!s)return t;const{store:c,...a}=s;return{...t,...a}}return{...t,...o.value}}const n=s?.store;return s&&n&&n.device_id===r.deviceId&&n.epoch===r.epoch&&n.fingerprint===H(e).fingerprint&&Number(s.last_pull_at??0)>Number(o.value.last_pull_at??0)&&fe(e,"cloud-cursor.json is ahead of the database (restored in place)"),{...t,...o.value}}function K(e){let t;try{t=A(e,"cloud")?.value}catch{}if(!t){const s=J();if(s){const{store:o,...n}=s;t=n}}const r=s=>Number.isFinite(Number(s))?Number(s):0;return{last_push_updated_ms:r(t?.last_push_updated_ms),last_push_at:r(t?.last_push_at),last_push_attempt_at:r(t?.last_push_attempt_at??t?.last_push_at),last_pull_at:r(t?.last_pull_at)}}function De(e,t){try{pe(e,"cloud",t)}catch{}ae(M(),JSON.stringify({...t,store:H(e)},null,2),{mode:384})}function Q(e){e.getDatabase().exec(`
|
|
3
3
|
CREATE TABLE IF NOT EXISTS sync_tombstones (
|
|
4
4
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
5
5
|
kind TEXT NOT NULL,
|
|
@@ -10,7 +10,7 @@ import{readFileSync as te,writeFileSync as ne,existsSync as se}from"node:fs";imp
|
|
|
10
10
|
);
|
|
11
11
|
CREATE INDEX IF NOT EXISTS idx_sync_tombstones_pending
|
|
12
12
|
ON sync_tombstones(pushed_at_ms);
|
|
13
|
-
`)}function
|
|
13
|
+
`)}function Ae(e){e.exec(`
|
|
14
14
|
CREATE TABLE IF NOT EXISTS cloud_push_ledger (
|
|
15
15
|
kind TEXT NOT NULL,
|
|
16
16
|
row_id TEXT NOT NULL,
|
|
@@ -18,17 +18,17 @@ import{readFileSync as te,writeFileSync as ne,existsSync as se}from"node:fs";imp
|
|
|
18
18
|
pushed_at INTEGER NOT NULL,
|
|
19
19
|
PRIMARY KEY (kind, row_id)
|
|
20
20
|
);
|
|
21
|
-
`)}function
|
|
22
|
-
ON CONFLICT(kind, row_id) DO UPDATE SET hash = excluded.hash, pushed_at = excluded.pushed_at`);for(const
|
|
23
|
-
WHERE kind = ? AND row_id NOT IN (SELECT CAST(id AS TEXT) FROM ${r})`).all(t)}catch(
|
|
24
|
-
VALUES (?, ?, ?)`).run(t,String(r),Date.now())}class
|
|
25
|
-
`)),console.error(" Proceeding anyway (--force / WYRM_ALLOW_COPIED_SESSION=1); fingerprint updated."),console.error(""),t(
|
|
26
|
-
`)),new
|
|
27
|
-
FROM ${
|
|
21
|
+
`)}function Ce(e){const t=Object.fromEntries(Object.keys(e).sort().map(r=>[r,e[r]]));return W("sha256").update(JSON.stringify(t)).digest("hex")}function Me(e,t){let r;try{r=e.prepare("SELECT row_id, hash FROM cloud_push_ledger WHERE kind = ?").all(t)}catch(s){if(/no such table/i.test(s instanceof Error?s.message:String(s)))return new Map;throw s}return new Map(r.map(s=>[s.row_id,s.hash]))}function ve(e,t,r,s){e.transaction(()=>{Ae(e);const o=e.prepare("DELETE FROM cloud_push_ledger WHERE kind = ? AND row_id = ?");for(const c of r)o.run(c.kind,c.row_id);const n=e.prepare(`INSERT INTO cloud_push_ledger (kind, row_id, hash, pushed_at) VALUES (?, ?, ?, ?)
|
|
22
|
+
ON CONFLICT(kind, row_id) DO UPDATE SET hash = excluded.hash, pushed_at = excluded.pushed_at`);for(const c of t)n.run(c.kind,c.row_id,c.hash,s)})()}function Ue(e,t,r){try{return e.prepare(`SELECT kind, row_id FROM cloud_push_ledger
|
|
23
|
+
WHERE kind = ? AND row_id NOT IN (SELECT CAST(id AS TEXT) FROM ${r})`).all(t)}catch(s){if(/no such table: cloud_push_ledger/i.test(s instanceof Error?s.message:String(s)))return[];throw s}}function z(e,t,r,s){const o=t.flatMap(n=>n.hash===null?[]:[{kind:n.kind,row_id:n.row_id,hash:n.hash}]);if(!(o.length===0&&r.length===0))try{ve(e.getDatabase(),o,r,Date.now())}catch(n){const c=o.length>0?`; ${o.length} row(s) go out again with the next sync`:"";s.push(`push ledger not written: ${v(n)}${c}`)}}function mt(e,t,r){if(typeof t!="string"||t.length===0||t.length>64)return;Q(e),e.getDatabase().prepare(`INSERT OR IGNORE INTO sync_tombstones (kind, row_id, deleted_at_ms)
|
|
24
|
+
VALUES (?, ?, ?)`).run(t,String(r),Date.now())}class xe extends Error{constructor(t){super(t),this.name="CopiedSessionError"}}function je(e){return!!e||process.env.WYRM_ALLOW_COPIED_SESSION==="1"}function Fe(e,t,r){const s=Se(e.machine_fp);if(s.state==="match")return;if(s.state==="adopt"){t(Ne());return}const o=["","\u26A0 WYRM CLOUD: this session looks COPIED from another machine.","",` Stored machine fingerprint: ${s.stored.slice(0,12)}\u2026`,` This machine's fingerprint: ${s.current.slice(0,12)}\u2026`,""," Both machines now share ONE device_id. The cloud pull query skips a"," device's own deltas, so each machine filters the OTHER's changes out:"," push works but pull silently returns 0 rows (peer memory looks MISSING).",""," FIX: give this machine its own identity (keep your encryption key):"," rm ~/.wyrm/cloud.json ~/.wyrm/cloud-cursor.json # NOT cloud.key"," wyrm cloud login",""," If this is a legitimate change (e.g. you renamed this host), re-run with:"," wyrm cloud sync --force (or set WYRM_ALLOW_COPIED_SESSION=1)",""];if(je(r)){console.error(o.join(`
|
|
25
|
+
`)),console.error(" Proceeding anyway (--force / WYRM_ALLOW_COPIED_SESSION=1); fingerprint updated."),console.error(""),t(s.current);return}throw console.error(o.join(`
|
|
26
|
+
`)),new xe("Cloud session looks copied from another machine (device_id collision). Re-login or pass --force.")}async function yt(e={}){if(e.sinceMs!==void 0&&!(Number.isFinite(e.sinceMs)&&e.sinceMs>=0))throw new Error($);const t=ye();if(!t||!t.device_id)throw new Error("Not logged in or device not registered. Run `wyrm cloud login`.");Fe(t,n=>{ge({...t,machine_fp:n})},e.force);const r=new he(t.base,t.session),s=ue(),o=Te(s);try{const n=new le(s);try{return G(n.getDatabase()),e.onStart?.(),await Pe(n,r,t.device_id,e)}finally{try{n.close()}catch{}}}finally{o()}}async function Pe(e,t,r,s){G(e.getDatabase()),Q(e);const o=e.getDatabase(),n=$e(o),c=Number(n.last_push_at)||Number(n.last_pull_at)||0,a={pushed:0,pulled:0,deleted_local:0,errors:[],quarantined:0,conflicts:0},i=s.all?B(e):{tables:O,skipped:[]},l=i.tables;i.skipped.length>0&&(a.skipped_tables=i.skipped);const p=Date.now(),E=n.last_push_updated_ms,S=[],m=Z(e,l,qe(E,s.sinceMs),!!s.all,a.errors,{useLedger:s.sinceMs===void 0,stale:S});if(m.length>0&&!s.dryRun){const y=await Ke(t,r,m,{prevMark:E,selectedAtMs:p},a.errors);a.pushed+=y.pushed,n.last_push_updated_ms=y.mark,n.last_push_attempt_at=Date.now(),y.stopped||(n.last_push_at=n.last_push_attempt_at),Ze(e,y.tombstoneIds),z(e,y.ledger,S,a.errors)}else a.pushed=m.length,s.dryRun||(n.last_push_at=n.last_push_attempt_at=Date.now(),z(e,[],S,a.errors));if(!s.dryRun){let y=n.pull_cursor,h=0;e:for(;h<50;){let f;try{f=await t.syncPull(r,y,100)}catch(d){a.errors.push(`pull failed: ${d instanceof Error?d.message:d}`);break}if(f.deltas.length===0)break;for(const d of f.deltas)try{const u=be(d.payload_b64);if(d.kind==="tombstone"){const{kind:_,row_id:w}=JSON.parse(u);nt(e,l,_,w)&&a.deleted_local++}else{const _=JSON.parse(u);et(e,l,d.kind,d.row_id,_,{remoteOrigin:`cloud:${d.device_id??"unknown"}`,lastSyncMs:c}).conflictId!==void 0&&(a.conflicts=(a.conflicts??0)+1),a.pulled++}}catch(u){const _=u instanceof Error?u.message:String(u),w=n.quarantine??={},{entry:b,action:T,newlyQuarantined:j}=ke(w[d.id],d,_,Date.now());if(w[d.id]=b,T==="skip"){j&&(a.quarantined=(a.quarantined??0)+1),a.errors.push(`quarantined ${d.kind}:${d.row_id} after ${b.attempts} attempts (${_})`);continue}a.errors.push(`apply ${d.kind}:${d.row_id}: ${_} (attempt ${b.attempts}/${V}, will retry)`);break e}if(y=f.next_cursor,!f.has_more)break;h++}n.pull_cursor=y,n.last_pull_at=Date.now()}return De(o,n),a}const $="--since must be an ISO date or epoch milliseconds",We=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})?)?$/i,He=1e12;function gt(e){const t=typeof e=="string"?e.trim():"";if(/^\d+$/.test(t)){const s=Number(t);if(!Number.isSafeInteger(s))throw new Error($);if(s<He)throw new Error(`${$} (epoch milliseconds, not seconds; or use YYYY-MM-DD): a number below 1000000000000 is before 2001-09-09`);return s}const r=We.exec(t);if(r){const[,s,o,n,c="00",a="00",i="00",l,p]=r,E=new Date(Date.UTC(Number(s),Number(o)-1,Number(n))),m=E.getUTCFullYear()===Number(s)&&E.getUTCMonth()===Number(o)-1&&E.getUTCDate()===Number(n)?Date.parse(`${s}-${o}-${n}T${c}:${a}:${i}${l?`.${l}`:""}${p?p.toUpperCase():"Z"}`):NaN;if(Number.isFinite(m)&&m>=0)return m}throw new Error($)}function qe(e,t){return t===void 0?e:Math.min(e,Math.max(0,t-1))}function Et(e,t={}){const r=e.getDatabase(),s=K(r).last_push_updated_ms,o=q(r);if(o.storeIsNewer)return{rows:0,tombstones:0,mark_ms:s,errors:[],refused:new Y(o.store,o.binary).message};const n=t.all?Le(e):O,c=[];return{rows:Z(e,n,s,!!t.all,c).filter(i=>i.tombstoneId===null).length,tombstones:Ve(r),mark_ms:s,errors:c}}function Ve(e){try{return e.prepare("SELECT COUNT(*) AS n FROM sync_tombstones WHERE pushed_at_ms IS NULL").get().n}catch{return 0}}function wt(e,t){const r=e.getDatabase(),s=K(r).last_push_updated_ms;if(s<=0)return null;let o=0,n=1/0;for(const a of O){if(!a.hasVisibility||!I(e,a.table,"project_id")||!I(e,a.table,"updated_at"))continue;const i=r.prepare(`SELECT COUNT(*) AS n, MIN(CAST(strftime('%s', updated_at) AS INTEGER)) AS earliest
|
|
27
|
+
FROM ${a.table}
|
|
28
28
|
WHERE project_id = ? AND cross_project_visibility IN ('org', 'public')
|
|
29
|
-
AND updated_at IS NOT NULL AND strftime('%s', updated_at) * 1000 <= ?`).get(t,
|
|
29
|
+
AND updated_at IS NOT NULL AND strftime('%s', updated_at) * 1000 <= ?`).get(t,s);o+=i.n,i.earliest!==null&&i.earliest<n&&(n=i.earliest)}if(o===0||n===1/0)return null;const c=n*1e3;return{rows:o,earliest_ms:c,mark_ms:s,since:new Date(c).toISOString().slice(0,10)}}function Z(e,t,r,s,o,n={}){const c=Qe(e,t,r,s,o,n),a=ze(e);return[...c.map(i=>{const l=i.updated_at??Date.now();return{kind:i.kind,row_id:String(i.row_id),visibility:i.visibility,body:i.row,updated_at:l,stamp:i.stamped?l:null,tombstoneId:null,hash:i.hash}}),...a.map(i=>({kind:"tombstone",row_id:`${i.kind}:${i.row_id}`,visibility:"org",body:{kind:i.kind,row_id:i.row_id,deleted_at_ms:i.deleted_at_ms},updated_at:i.deleted_at_ms,stamp:null,tombstoneId:i.id,hash:null}))]}function Ye(e,t){let r=e,s=0;for(;s<t.length&&t[s].ok;s++)for(const n of t[s].stamps)n>r&&(r=n);let o=1/0;for(;s<t.length;s++)for(const n of t[s].stamps)n<o&&(o=n);return o===1/0?r:Math.min(r,Math.floor(o/1e3)*1e3-1)}const ee=25,Ge=new Set([400,409,413,422]),Be=new Set(["storage_cap_exceeded","invalid_device_id","bad_request","no_deltas"]);function te(e){if(!(e instanceof me)||!Ge.has(e.status))return null;const t=e.body;return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Xe(e){const t=te(e);return t!==null&&!Be.has(String(t.error))}function Je(e){return te(e)?.index===0}const v=e=>{const t=e?.message;return typeof t=="string"?t:String(e)};async function Ke(e,t,r,s,o){const n=[];for(let h=0;h<r.length;h+=ee)n.push(r.slice(h,h+ee));const c=h=>h.flatMap(f=>f.stamp===null?[]:[f.stamp]),a=[],i=[],l=[];let p=0;const E=async(h,f)=>{const d=await e.syncPush(t,f);if(p+=d.accepted,d.rejected>0){const u=[...new Set((d.rejected_details??[]).map(_=>_.reason))].join(", ");return`the server did not store ${d.rejected} of ${f.length} delta(s)${u?` (${u})`:""}`}for(const u of h)u.tombstoneId!==null&&i.push(u.tombstoneId),u.hash!==null&&l.push(u);return null},S=async(h,f)=>{for(let d=0;d<h.length;d++)try{const u=await E([h[d]],[f[d]]);if(u!==null)return u}catch(u){if(!Je(u))return v(u);o.push(`push refused (HTTP ${u.status}) on ${h[d].kind}:${h[d].row_id}`)}return null};let m=null;for(let h=0;h<n.length&&m===null;h++){const f=n[h],d=f.map(_=>({kind:_.kind,row_id:_.row_id,visibility:_.visibility,payload_b64:we(JSON.stringify(_.body)),updated_at:_.updated_at}));let u;try{u=await E(f,d)}catch(_){u=Xe(_)?await S(f,d):v(_)}if(u===null){a.push({ok:!0,stamps:c(f)});continue}for(const _ of n.slice(h))a.push({ok:!1,stamps:c(_)});m={chunk:h+1,why:u}}const y=Math.min(Ye(s.prevMark,a),Math.floor(s.selectedAtMs/1e3)*1e3-1);if(m!==null){const h=new Set(i),f=new Set(l),d=r.filter(u=>u.tombstoneId!==null?!h.has(u.tombstoneId):u.hash!==null?!f.has(u):u.stamp===null||u.stamp>y).length;o.push(`push stopped at chunk ${m.chunk} of ${n.length}: ${m.why}; ${d} row(s) left for the next sync`)}return{pushed:p,mark:y,tombstoneIds:i,ledger:l,stopped:m!==null}}function U(e){if(typeof e!="string"||e.length===0)return 0;const t=e.includes("T")?e:e.replace(" ","T")+"Z",r=Date.parse(t);return Number.isFinite(r)?r:0}function I(e,t,r){try{return e.getDatabase().prepare(`PRAGMA table_info(${t})`).all().some(n=>n.name===r)}catch{return!1}}function Qe(e,t,r,s,o,n={}){const c=[],a=e.getDatabase(),i=I(e,"projects","sync_policy");for(const l of t)if(N.test(l.table)&&!(!s&&!l.hasVisibility))try{const p=I(e,l.table,"updated_at"),E=l.hasVisibility?"WHERE cross_project_visibility IN ('org', 'public')":"WHERE 1=1",S=i&&I(e,l.table,"project_id")?"AND (project_id IS NULL OR project_id IN (SELECT id FROM projects WHERE sync_policy IN ('cloud', 'team')))":"",m=p?"AND (? = 0 OR updated_at IS NULL OR strftime('%s', updated_at) * 1000 > ?)":"",y=p?"ORDER BY (updated_at IS NULL) ASC, updated_at ASC":"",h=`SELECT * FROM ${l.table} ${E} ${S} ${m} ${y}`,f=a.prepare(h),d=p?f.all(r,r):f.all(),u=p||n.useLedger===!1?null:Me(a,l.kind);!p&&n.stale&&n.stale.push(...Ue(a,l.kind,l.table));for(const _ of d){const w=p?null:Ce(_);if(u!==null&&u.get(String(_.id??"?"))===w)continue;const b=U(_.updated_at);if(r>0&&b>0&&b<=r)continue;const T=l.hasVisibility?String(_.cross_project_visibility??"within"):"org";c.push({kind:l.kind,row_id:_.id??"?",visibility:T,row:_,updated_at:b||Date.now(),stamped:b>0,hash:w})}}catch(p){const E=p instanceof Error?p.message:String(p);if(/no such table/i.test(E))continue;o.push(`collect ${l.table}: ${E}`)}return c.sort((l,p)=>(l.updated_at??0)-(p.updated_at??0)),c}function ze(e){const t=e.getDatabase();try{return t.prepare(`SELECT id, kind, row_id, deleted_at_ms
|
|
30
30
|
FROM sync_tombstones
|
|
31
31
|
WHERE pushed_at_ms IS NULL
|
|
32
32
|
ORDER BY id ASC
|
|
33
|
-
LIMIT 500`).all()}catch{return[]}}function
|
|
34
|
-
VALUES (?, ?, ?, ?, 'cloud', ?, ?)`).run(r,l,c,
|
|
33
|
+
LIMIT 500`).all()}catch{return[]}}function Ze(e,t){if(t.length===0)return;const r=e.getDatabase(),s=Date.now(),o=r.prepare("UPDATE sync_tombstones SET pushed_at_ms = ? WHERE id = ?"),n=r.transaction(c=>{for(const a of c)o.run(s,a)});try{n(t)}catch{}}const se=new Set(["updated_at","last_accessed_at","access_count","reuse_count","reuse_success_count","reuse_failure_count","usage_count","last_used","last_validated_at","last_verified_at"]),R=e=>e==null?null:String(e);function ne(e,t){const r=t.filter(s=>!se.has(s)).sort().map(s=>[s,R(e[s])]);return W("sha256").update(JSON.stringify(r)).digest("hex")}function x(e,t,r,s,o,n,c,a){const i=Number(s);if(Number.isSafeInteger(i))try{const l=JSON.stringify(C(t,o)),p=e.prepare("SELECT id FROM sync_conflicts WHERE resolved_at IS NULL AND source = 'cloud' AND local_kind = ? AND local_id = ? AND remote_payload = ?").get(r,i,l);return p?p.id:Number(e.prepare(`INSERT INTO sync_conflicts (local_kind, local_id, remote_payload, remote_origin, source, winner, local_payload)
|
|
34
|
+
VALUES (?, ?, ?, ?, 'cloud', ?, ?)`).run(r,i,l,a,c,JSON.stringify(C(t,n))).lastInsertRowid)}catch{return}}function et(e,t,r,s,o,n={remoteOrigin:"cloud",lastSyncMs:0}){const c=t.find(g=>g.kind===r);if(!c)return{action:"skipped"};if(!N.test(c.table))throw new Error(`apply ${r}: refusing unsafe table name ${c.table}`);const a=C(c.table,o),i=X(e,c.table);if(i.size===0)throw new Error(`apply ${r}: ${c.table} has no readable schema`);const l=Object.keys(a).filter(g=>i.has(g)&&N.test(g));if(l.length===0)throw new Error(`apply ${r}: no columns from peer payload matched local schema`);const p=e.getDatabase(),E=l.map(()=>"?").join(","),S=l.join(","),m=l.map(g=>a[g]),y=l.filter(g=>g!=="id"),h=y.map(g=>`${g} = ?`).join(", "),f=a.id,d=(g,L)=>{try{return g==="insert"?p.prepare(`INSERT INTO ${c.table} (${S}) VALUES (${E})`).run(...m):y.length>0&&p.prepare(`UPDATE ${c.table} SET ${h} WHERE id = ?`).run(...y.map(k=>a[k]),f),{action:L}}catch(k){const D=tt(k)?st(p,c.table,i,a):void 0;if(!D)throw new Error(`apply ${r} failed: ${k instanceof Error?k.message:k}`);return{action:"kept_local",conflictId:x(p,c.table,r,D.id,a,D,"local",n.remoteOrigin)}}},u=!i.has("id")||f===void 0||f===null?void 0:p.prepare(`SELECT * FROM ${c.table} WHERE id = ?`).get(f);if(!u)return d("insert","inserted");if(!l.some(g=>!se.has(g)&&R(u[g])!==R(a[g])))return{action:"identical"};if(re(p,c.table,i,a).some(g=>g.some(L=>R(u[L])!==R(a[L]))))return{action:"kept_local",conflictId:x(p,c.table,r,u.id,a,u,"local",n.remoteOrigin)};const _=i.has("updated_at")?U(u.updated_at):0,w=i.has("updated_at")?U(a.updated_at):0;if(_===0||w===0)return d("update","updated");const b=_===w,T=b?ne(a,l)>ne(u,l):w>_,F=b||!T||n.lastSyncMs>0&&_>n.lastSyncMs?x(p,c.table,r,f,a,u,T?"remote":"local",n.remoteOrigin):void 0;if(!T)return{action:"kept_local",conflictId:F};const P=d("update","updated");return P.action==="kept_local"?P:{action:"updated",conflictId:F}}const tt=e=>e?.code==="SQLITE_CONSTRAINT_UNIQUE"||/UNIQUE constraint failed/i.test(e instanceof Error?e.message:String(e));function re(e,t,r,s){const o=[];if(!N.test(t))return o;const n=e.prepare(`PRAGMA index_list(${t})`).all();for(const c of n){if(!c.unique||c.origin==="pk"||c.partial||!N.test(c.name))continue;const a=e.prepare(`PRAGMA index_info(${c.name})`).all().map(i=>i.name);a.length===0||a.some(i=>!i||!N.test(i)||!r.has(i)||!(i in s))||o.push(a)}return o}function st(e,t,r,s){for(const o of re(e,t,r,s)){const n=o.map(a=>`${a} IS ?`).join(" AND "),c=e.prepare(`SELECT * FROM ${t} WHERE ${n}`).get(...o.map(a=>s[a]));if(c)return c}}function nt(e,t,r,s){const o=t.find(i=>i.kind===r);if(!o||!N.test(o.table))return!1;const n=e.getDatabase(),c=X(e,o.table);if(c.has("cross_project_visibility")){const i=c.has("project_id")?n.prepare(`SELECT cross_project_visibility AS vis, project_id FROM ${o.table} WHERE id = ?`).get(s):n.prepare(`SELECT cross_project_visibility AS vis FROM ${o.table} WHERE id = ?`).get(s);if(!i||i.vis!=="org"&&i.vis!=="public")return!1;if(i.project_id!=null&&I(e,"projects","sync_policy")){const l=n.prepare("SELECT sync_policy AS p FROM projects WHERE id = ?").get(i.project_id);if(l?.p&&l.p!=="cloud"&&l.p!=="team")return!1}}return n.prepare(`DELETE FROM ${o.table} WHERE id = ?`).run(s).changes>0}export{xe as CopiedSessionError,O as DEFAULT_TABLES,Y as NewerStoreSyncError,V as QUARANTINE_AFTER,$ as SINCE_USAGE,et as applyRow,Qe as collectChangedRows,B as discoverSyncTables,Le as discoverTables,Ae as ensurePushLedgerTable,wt as groveBelowMark,Fe as guardCopiedSession,gt as parseSince,K as peekCursor,Et as pendingPush,ke as quarantineDecision,mt as recordTombstone,yt as runSync,Ye as safePushMark,Z as selectPushItems};
|
package/dist/maintenance.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{pruneWriteLedger as m}from"./receipts.js";import{metabolizeEnabled as f,metabolizeDefaultEnabled as _,runMetabolize as
|
|
1
|
+
import{pruneWriteLedger as m}from"./receipts.js";import{metabolizeEnabled as f,metabolizeDefaultEnabled as _,repairWrongMerges as y,runMetabolize as b}from"./metabolize.js";import{ServedRecords as R}from"./served-records.js";import{ReadMemos as g}from"./read-memo.js";import{ToolAnalytics as $}from"./tool-analytics.js";import{WyrmAnalytics as E}from"./analytics.js";import{failureQuietDays as D}from"./failure-patterns.js";import{enforceIngestRetention as v,retentionLine as M}from"./retention.js";import{compactGraph as w,formatBytes as N,pruneEndedRuns as T,pruneReferenceModel as c,pruneStuckQueue as A,pruneVectors as I,runRetainDays as S}from"./index-health.js";import{liveServerModels as Y}from"./live-embedding-state.js";function V(u,a={}){const{db:n,sessionSeen:p,failures:o,presence:l}=u,{vacuum:h,archiveDays:i}=a,t=[];if(i){const e=n.getAllProjects(1e3);let r=0;for(const s of e)r+=n.archiveOldSessions(s.id,i);t.push(`Archived ${r} old sessions`)}h&&(n.vacuum(),t.push("Vacuumed database"));try{const e=parseInt(process.env.WYRM_SEEN_TTL_DAYS??"7",10),r=p.prune(Number.isFinite(e)&&e>0?e:7);r>0&&t.push(`Pruned ${r} session_seen_artifacts rows older than ${e}d`)}catch{}try{const e=parseInt(process.env.WYRM_SEEN_TTL_DAYS??"7",10),r=Number.isFinite(e)&&e>0?e:7,s=new R(n.getDatabase()).prune(r);s>0&&t.push(`Pruned ${s} served_records rows older than ${r}d`)}catch{}try{const e=parseInt(process.env.WYRM_MEMO_TTL_DAYS??"7",10),r=Number.isFinite(e)&&e>0?e:7,s=new g(n.getDatabase()).prune(r);s>0&&t.push(`Pruned ${s} read_memos rows older than ${r}d`)}catch{}try{const e=parseInt(process.env.WYRM_TOOL_LOG_RETAIN_DAYS??"90",10),r=Number.isFinite(e)&&e>0?e:90,s=new $(n.getDatabase()).prune(r);s>0&&t.push(`Pruned ${s} tool_call_log rows older than ${r}d`)}catch{}try{const e=parseInt(process.env.WYRM_USAGE_RETAIN_DAYS??"90",10),r=Number.isFinite(e)&&e>0?e:90,s=new E(n.getDatabase());try{const{deleted:d}=s.cleanup(r);d>0&&t.push(`Rolled up and pruned ${d} usage_events rows older than ${r}d`)}finally{s.shutdown()}}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),r=parseInt(process.env.WYRM_EVENT_MAX_PER_PROJECT??"5000",10),{deleted:s}=n.pruneEvents({olderThanDays:Number.isFinite(e)?e:90,maxPerProject:Number.isFinite(r)?r:5e3});s>0&&t.push(`Pruned ${s} Live Memory events (retention)`)}catch{}try{const e=M(v(n,{days:a.ingestRetainDays,actor:"maintenance"}));e&&t.push(e)}catch{}try{const e=y(n.getDatabase());e.restored.length>0&&t.push(`Metabolize repair: restored ${e.restored.length} memories an exact merge before 9.5.2 had retired behind a same-text copy of another lane, kind, project, constraints, outcome or sharing`)}catch{}try{if(_()){const e=b(n.getDatabase(),{near:f()});e.exactMerged+e.nearCandidatesQueued+e.decayed>0&&t.push(`Metabolize: ${e.exactMerged} exact dupes superseded, ${e.nearCandidatesQueued} near-dup candidates queued, ${e.decayed} stale auto-captures decayed`)}}catch{}try{const e=m(n.getDatabase());e>0&&t.push(`Pruned ${e} write_ledger receipts (retention)`)}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),r=Number.isFinite(e)&&e>0?e:90,s=o.pruneBlocks(r);s>0&&t.push(`Pruned ${s} failure_blocks rows older than ${r}d (retention)`)}catch{}try{const e=l.reap();(e.presence>0||e.claims>0)&&t.push(`Reaped ${e.presence} stale presence row(s) and ${e.claims} expired quest claim(s)`)}catch{}try{const e=parseInt(process.env.WYRM_EVENT_RETAIN_DAYS??"90",10),r=Number.isFinite(e)&&e>0?e:90,s=n.getDatabase().prepare("DELETE FROM run_briefs WHERE created_at < datetime('now', ?)").run(`-${r} days`).changes;s>0&&t.push(`Pruned ${s} run_briefs rows older than ${r}d (retention)`)}catch{}try{const e=parseInt(process.env.WYRM_RUN_BRIEFS_MAX??"512",10),r=Number.isFinite(e)&&e>0?e:512,s=n.getDatabase().prepare(`
|
|
2
2
|
DELETE FROM run_briefs WHERE rowid IN (
|
|
3
3
|
SELECT rowid FROM run_briefs ORDER BY created_at DESC, rowid DESC LIMIT -1 OFFSET ?
|
|
4
|
-
)`).run(r).changes;
|
|
4
|
+
)`).run(r).changes;s>0&&t.push(`Pruned ${s} run_briefs rows over the ${r}-row cap (WYRM_RUN_BRIEFS_MAX)`)}catch{}try{const e=parseInt(process.env.WYRM_RUN_INACTIVE_HOURS??"24",10),r=o.sweepRunQuarantine({runInactiveHours:Number.isFinite(e)&&e>0?e:24});(r.promoted>0||r.expired>0||r.runs_abandoned>0)&&t.push(`Run-quarantine sweep: promoted ${r.promoted} failure(s), expired ${r.expired} abandoned-run failure(s), TTL-abandoned ${r.runs_abandoned} stalled run(s)`),r.degraded&&t.push(`Run-quarantine sweep: ${r.degraded}`)}catch{}try{const e=D();if(e>0){const r=o.sweepQuiet(e);r.downgraded>0&&t.push(`Quiet-period sweep: ${r.downgraded} unresolved failure(s) with no hits for ${e}d downgraded from block to warn (history recorded; recording one again re-arms it)`)}}catch{}try{const e=n.getDatabase(),r=I(e,{activeModel:c(e,a.activeModel),protectedModels:Y(e)});r.deleted+r.relabelled>0&&t.push(`Vector hygiene: removed ${r.orphans} orphan, ${r.superseded} superseded and ${r.oldModel} old-model vector(s); ${r.mislabelled} mislabelled (${r.relabelled} relabelled); ${N(r.bytes)} freed`)}catch{}try{const e=n.getDatabase(),r=A(e,{activeModel:c(e,a.activeModel)});r.cleared>0&&t.push(`Indexing queue: cleared ${r.cleared} stuck row(s) (${r.gone} gone, ${r.notNeeded} no longer eligible, ${r.embedded} already embedded); ${r.remaining} still waiting for a vector`)}catch{}try{const e=a.runRetainDays??S();if(e>0){const r=T(n.getDatabase(),{olderThanDays:e});r.runs>0&&t.push(`Pruned ${r.runs} ended run(s) and ${r.runAgents} run_agents row(s) older than ${e}d (WYRM_RUN_RETAIN_DAYS)`)}}catch{}try{if(a.compactGraph??process.env.WYRM_GRAPH_COMPACT==="1"){const e=w(n.getDatabase());e.relationships+e.entities>0&&t.push(`Graph compaction: removed ${e.relationships} unsupported relationship(s) and ${e.entities} entit${e.entities===1?"y":"ies"} no live memory mentions`)}}catch{}return n.checkpoint(),t.push("Checkpointed WAL"),{lines:t,dbSize:n.getStats().dbSize}}export{V as runMaintenance};
|
package/dist/metabolize.js
CHANGED
|
@@ -1,22 +1,39 @@
|
|
|
1
|
-
import{createHash as
|
|
2
|
-
SELECT id, project_id, kind, problem, validated_fix,
|
|
1
|
+
import{createHash as j}from"crypto";import{recordWrite as y}from"./receipts.js";import{writerEnvelope as L}from"./handlers/boundary.js";import{redactedPrefix as g}from"./security.js";import{recordGovernanceEvent as I}from"./governance.js";const A=e=>j("sha1").update(e).digest("hex");function E(e,t){return t!=null?e.prepare(`
|
|
2
|
+
SELECT id, project_id, kind, problem, validated_fix, constraints, outcome, source_trust,
|
|
3
|
+
is_shared, cross_project_visibility, confidence, reuse_count,
|
|
3
4
|
created_by, created_at, updated_at, last_accessed_at
|
|
4
5
|
FROM memory_artifacts
|
|
5
6
|
WHERE needs_review = 0 AND supersedes_id IS NULL AND project_id = ?
|
|
6
7
|
ORDER BY id
|
|
7
|
-
`).all(
|
|
8
|
-
SELECT id, project_id, kind, problem, validated_fix,
|
|
8
|
+
`).all(t):e.prepare(`
|
|
9
|
+
SELECT id, project_id, kind, problem, validated_fix, constraints, outcome, source_trust,
|
|
10
|
+
is_shared, cross_project_visibility, confidence, reuse_count,
|
|
9
11
|
created_by, created_at, updated_at, last_accessed_at
|
|
10
12
|
FROM memory_artifacts
|
|
11
13
|
WHERE needs_review = 0 AND supersedes_id IS NULL
|
|
12
14
|
ORDER BY id
|
|
13
|
-
`).all()}
|
|
14
|
-
`+(
|
|
15
|
+
`).all()}const N=e=>A(e.problem+`
|
|
16
|
+
`+(e.validated_fix??""));function h(e){return[["project",e.project_id],["kind",e.kind],["lane",e.source_trust??"agent"],["constraints",e.constraints??""],["outcome",e.outcome??""],["is_shared",e.is_shared??0],["cross_project_visibility",e.cross_project_visibility??"within"],["text",N(e)]]}function O(e){return JSON.stringify(h(e).map(([,t])=>t))}function T(e,t={}){const i=E(e,t.projectId),o=new Map;for(const c of i){const _=O(c),n=o.get(_);n?n.push(c):o.set(_,[c])}let r=0,s=0;const a=e.prepare("UPDATE memory_artifacts SET supersedes_id = ?, updated_at = datetime('now') WHERE id = ?");for(const c of o.values()){if(c.length<2)continue;s++;const _=c[0];for(const n of c.slice(1))t.dryRun||(a.run(_.id,n.id),y(e,{tool:"wyrm_metabolize",outcome:"merged",refTable:"mem",refId:n.id,reason:`exact duplicate of mem:${_.id} , superseded (not deleted; sync-safe)`,source:"metabolize",projectId:n.project_id})),r++}return{merged:r,groups:s}}const R="metabolize_lane_repair_952",z=["project_id","kind","source_trust","constraints","outcome","is_shared","cross_project_visibility","problem","validated_fix"],f=250,D=`
|
|
17
|
+
SELECT r.id, r.project_id, r.kind, r.source_trust, r.constraints, r.outcome, r.is_shared,
|
|
18
|
+
r.cross_project_visibility, r.problem, r.validated_fix,
|
|
19
|
+
s.id AS s_id, s.project_id AS s_project_id, s.kind AS s_kind, s.source_trust AS s_source_trust,
|
|
20
|
+
s.constraints AS s_constraints, s.outcome AS s_outcome, s.is_shared AS s_is_shared,
|
|
21
|
+
s.cross_project_visibility AS s_cross_project_visibility, s.problem AS s_problem, s.validated_fix AS s_validated_fix
|
|
22
|
+
FROM memory_artifacts r JOIN memory_artifacts s ON s.id = r.supersedes_id
|
|
23
|
+
WHERE r.supersedes_id IS NOT NULL
|
|
24
|
+
ORDER BY r.id`,M=`
|
|
25
|
+
SELECT r.id, r.project_id, r.kind, r.source_trust, r.constraints, r.outcome, r.is_shared,
|
|
26
|
+
r.cross_project_visibility, r.problem, r.validated_fix,
|
|
27
|
+
s.id AS s_id, s.project_id AS s_project_id, s.kind AS s_kind, s.source_trust AS s_source_trust,
|
|
28
|
+
s.constraints AS s_constraints, s.outcome AS s_outcome, s.is_shared AS s_is_shared,
|
|
29
|
+
s.cross_project_visibility AS s_cross_project_visibility, s.problem AS s_problem, s.validated_fix AS s_validated_fix
|
|
30
|
+
FROM memory_artifacts r JOIN memory_artifacts s ON s.id = r.supersedes_id
|
|
31
|
+
WHERE r.id = ? AND r.supersedes_id = ?`;function b(e){const t=Object.fromEntries(z.map(s=>[s,e[`s_${s}`]])),i=h(e),o=h(t),r=i.filter(([,s],a)=>s!==o[a][1]).map(([s])=>s);return r.includes("text")||r.length===0?null:r}function v(e){const t=e.prepare(D).all(),i=[];for(const o of t){const r=b(o);r&&i.push({id:o.id,was_superseded_by:o.s_id,differs:r})}return i}function x(e,t){return e.transaction(()=>{const i=e.prepare(M),o=e.prepare("UPDATE memory_artifacts SET supersedes_id = NULL, updated_at = datetime('now') WHERE id = ? AND supersedes_id = ?"),r=[];for(const s of t){const a=i.get(s.id,s.was_superseded_by),c=a?b(a):null;!a||!c||(o.run(s.id,s.was_superseded_by),y(e,{tool:"wyrm_metabolize",outcome:"stored",refTable:"mem",refId:s.id,reason:`restored: an exact merge before 9.5.2 had retired it behind mem:${s.was_superseded_by}, which has the same text but differs in ${c.join(", ")}`,source:"metabolize-repair",projectId:a.project_id}),r.push({...s,differs:c}))}return r.length>0&&I(e,"metabolize.repair",{restored:r.length,artifact_ids:r.map(s=>s.id),superseded_by:r.map(s=>s.was_superseded_by)},{system:"metabolize-repair"}),r}).immediate()}function w(e,t){e.prepare("SELECT 1 FROM wyrm_meta WHERE key = ?").get(R)||e.transaction(()=>{e.prepare("INSERT OR IGNORE INTO wyrm_meta (key, value) VALUES (?, ?)").run(R,JSON.stringify({at:new Date().toISOString(),restored:t.map(i=>i.id)}))}).immediate()}function K(e,t={}){const i=v(e);if(t.dryRun)return{restored:i};const o=[];for(let r=0;r<i.length;r+=f)o.push(...x(e,i.slice(r,r+f)));return w(e,o),{restored:o}}function q(e){return new Promise(t=>{const i=[];let o;try{o=v(e())}catch{t({restored:i});return}let r=0;const s=()=>{try{const a=e();if(r<o.length&&(i.push(...x(a,o.slice(r,r+f))),r+=f,r<o.length)){setImmediate(s);return}w(a,i)}catch{}t({restored:i})};s()})}const $=new Set(["the","a","an","and","or","to","of","in","on","for","with","is","was","are","this","that","it","as","at","by"]);function k(e,t=3){const i=e.toLowerCase().split(/[^a-z0-9]+/).filter(r=>r.length>1&&!$.has(r)),o=new Set;for(let r=0;r+t<=i.length;r++)o.add(i.slice(r,r+t).join(" "));return o}function C(e,t){if(e.size===0||t.size===0)return 0;let i=0;const[o,r]=e.size<=t.size?[e,t]:[t,e];for(const s of o)r.has(s)&&i++;return i/(e.size+t.size-i)}function W(e,t={}){const i=t.threshold??.82,o=t.maxPairs??20,s=E(e,t.projectId).map(n=>({r:n,s:k(`${n.problem} ${n.validated_fix??""}`.slice(0,1500))})).filter(n=>n.s.size>=8);let a=0,c=0;const _=e.prepare("SELECT 1 FROM memory_artifacts WHERE tags LIKE ? ESCAPE '\\' LIMIT 1");for(let n=0;n<s.length&&a<o;n++)for(let p=n+1;p<s.length&&a<o;p++){if(s[n].r.project_id!==s[p].r.project_id)continue;c++;const m=C(s[n].s,s[p].s);if(m<i)continue;const d=s[n].r,u=s[p].r,S="nd:"+A(`${Math.min(d.id,u.id)}:${Math.max(d.id,u.id)}`).slice(0,16);if(!_.get("%"+S.replace(/[%_\\]/g,l=>"\\"+l)+"%")){if(!t.dryRun){const l=L("metabolize");e.prepare(`
|
|
15
32
|
INSERT INTO memory_artifacts (project_id, kind, problem, validated_fix, confidence, needs_review, tags, created_by, agent_id, run_id)
|
|
16
33
|
VALUES (?, 'pattern', ?, ?, ?, 1, ?, 'metabolize', ?, ?)
|
|
17
|
-
`).run(
|
|
34
|
+
`).run(d.project_id,`MERGE CANDIDATE (similarity ${(m*100).toFixed(0)}%): mem:${d.id} and mem:${u.id} look like the same memory. Approve to keep both; to merge, supersede one via review.`,`mem:${d.id}: ${g(d.problem,160)}
|
|
18
35
|
---
|
|
19
|
-
mem:${
|
|
36
|
+
mem:${u.id}: ${g(u.problem,160)}`,m,`metabolize,near-dup,${S}`,l.agent_id,l.run_id),y(e,{tool:"wyrm_metabolize",outcome:"queued",reason:`near-duplicate candidate mem:${d.id} ~ mem:${u.id} (${(m*100).toFixed(0)}%); review to merge`,source:"metabolize",projectId:d.project_id})}a++}}return{queued:a,comparedPairs:c}}function P(e,t={}){const i=t.olderThanDays??60,o=t.factor??.9,r=t.floor??.3,s=e.prepare(`
|
|
20
37
|
SELECT id FROM memory_artifacts
|
|
21
38
|
WHERE needs_review = 0 AND supersedes_id IS NULL
|
|
22
39
|
AND reuse_count = 0
|
|
@@ -25,4 +42,4 @@ mem:${l.id}: ${y(l.problem,160)}`,f,`metabolize,near-dup,${E}`,p.agent_id,p.run_
|
|
|
25
42
|
AND (decayed_at IS NULL OR decayed_at < datetime('now', ?))
|
|
26
43
|
AND source_trust <> 'operator'
|
|
27
44
|
AND (problem LIKE '[auto:%' OR created_by LIKE 'bridge:%' OR created_by = 'auto-extract')
|
|
28
|
-
`).all(
|
|
45
|
+
`).all(r,`-${i} days`,`-${i} days`);if(!t.dryRun&&s.length>0){const a=e.prepare("UPDATE memory_artifacts SET confidence = MAX(?, confidence * ?), decayed_at = datetime('now') WHERE id = ?");for(const{id:c}of s)a.run(r,o,c)}return{decayed:s.length}}function J(e,t={}){const i=E(e,t.projectId).length,o=T(e,t),r=t.near===!1?{queued:0}:W(e,t),s=P(e,t);return{scanned:i,exactMerged:o.merged,nearCandidatesQueued:r.queued,decayed:s.decayed,dryRun:!!t.dryRun}}function G(e=process.env){const t=(e.WYRM_METABOLIZE??"").toLowerCase();return t==="1"||t==="true"||t==="yes"}function Q(e=process.env){const t=(e.WYRM_METABOLIZE??"").toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"&&t!=="off"}function V(e,t){const i=t.trim();if(/^[a-z][a-z0-9_.-]*\s*=\s*(true|false|\d+(\.\d+)?|"[^"]{0,40}"|'[^']{0,40}'|[a-z0-9_.-]{1,40})$/i.test(i))return!0;const o=e.trim().toLowerCase();return!!(i.toLowerCase().startsWith(o)&&/=\s*\S+$/.test(i)&&i.length<80&&!/[.!?]\s/.test(i))}export{R as LANE_REPAIR_KEY,f as REPAIR_BATCH,P as decayStaleAutoCaptures,V as isConfigShapedTruth,C as jaccard,T as mergeExactDuplicates,Q as metabolizeDefaultEnabled,G as metabolizeEnabled,v as planWrongMerges,W as queueNearDuplicates,K as repairWrongMerges,q as repairWrongMergesInSteps,J as runMetabolize,k as shingles};
|
package/dist/self-maintenance.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{SessionSeen as _}from"./session-seen.js";import{FailurePatterns as y}from"./failure-patterns.js";import{AgentPresence as
|
|
1
|
+
import{SessionSeen as _}from"./session-seen.js";import{FailurePatterns as y}from"./failure-patterns.js";import{AgentPresence as M}from"./presence.js";import{runMaintenance as A}from"./maintenance.js";import{repairWrongMergesInSteps as h}from"./metabolize.js";import{maybeBackfill as S,runRetainDays as T}from"./index-health.js";import{maybeScheduledBackup as R}from"./backup.js";const E="last_maintenance_at",g=24;function D(r){const e=Number(r.WYRM_MAINTENANCE_INTERVAL_HOURS);return Number.isFinite(e)&&e>0?e:g}function I(r,e,s){const t=new Date(e).toISOString(),a=new Date(e-s*36e5).toISOString();return r.prepare(`
|
|
2
2
|
INSERT INTO wyrm_meta (key, value) VALUES (?, ?)
|
|
3
3
|
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
|
4
4
|
WHERE wyrm_meta.value < ?
|
|
5
|
-
`).run(
|
|
5
|
+
`).run(E,t,a).changes===1}function L(r){try{return r.prepare("SELECT value FROM wyrm_meta WHERE key = ?").get(E)?.value??null}catch{return null}}function C(r,e=process.env,s=Date.now(),t={}){try{if((e.WYRM_AUTO_MAINTENANCE??"1")==="0")return{outcome:"disabled",lines:[]};const a=r.getDatabase();if(!I(a,s,D(e)))return{outcome:"not-due",lines:[]};try{const n=A({db:r,sessionSeen:new _(a),failures:new y(a),presence:new M(a)},{activeModel:t.activeModel??null,compactGraph:e.WYRM_GRAPH_COMPACT==="1",runRetainDays:T(e)});return e.WYRM_MAINTENANCE_DEBUG==="1"&&process.stderr.write(`wyrm: automatic maintenance ran, ${n.lines.length} step(s)
|
|
6
6
|
`),{outcome:"ran",lines:n.lines}}catch(n){if(e.WYRM_MAINTENANCE_DEBUG==="1"){const i=n instanceof Error?n.message:String(n);process.stderr.write(`wyrm: automatic maintenance failed (retries next interval): ${i.slice(0,200)}
|
|
7
|
-
`)}return{outcome:"failed",lines:[]}}}catch{return{outcome:"failed",lines:[]}}}const
|
|
7
|
+
`)}return{outcome:"failed",lines:[]}}}catch{return{outcome:"failed",lines:[]}}}const d=new Set;async function k(r,e=process.env,s=new Date){try{const t=await R({dbPath:r.getDatabasePath(),env:e,now:s,keyring:!1});return t.action==="skipped"&&t.reason&&!d.has(t.reason)&&(d.add(t.reason),process.stderr.write(`wyrm: daily snapshot skipped: ${t.reason}
|
|
8
8
|
`)),e.WYRM_MAINTENANCE_DEBUG==="1"&&t.created&&process.stderr.write(`wyrm: daily snapshot ${t.created.file}${t.pruned.length?`, rotated out ${t.pruned.map(a=>a.file).join(", ")}`:""}
|
|
9
9
|
`),t}catch(t){return e.WYRM_MAINTENANCE_DEBUG==="1"&&process.stderr.write(`wyrm: daily snapshot failed (retries next interval): ${(t instanceof Error?t.message:String(t)).slice(0,200)}
|
|
10
|
-
`),null}}const
|
|
10
|
+
`),null}}const b=36e5;function P(r,e=process.env,s={}){const t=typeof r=="function"?r:()=>r;if(setImmediate(()=>{h(()=>t().getDatabase())}),(e.WYRM_AUTO_MAINTENANCE??"1")==="0")return null;const a=s.now??Date.now;let n=!1;const i=()=>{if(n)return;n=!0;let o=null,m=!1,c=null;try{c=t(),o=s.vectors?.()??null,m=C(c,e,a(),{activeModel:o?o.getProvider().model:null}).outcome==="ran"}catch{}if(!m||!c){n=!1;return}const f=c,w=async()=>{if(!o)return;let p;try{p=f.getDatabase()}catch{return}await S(p,o,e).catch(()=>null)};k(f,e,new Date(a())).then(w).catch(()=>null).finally(()=>{n=!1})};setImmediate(i);const l=Number(e.WYRM_MAINTENANCE_CHECK_MS),N=s.checkEveryMs??(Number.isFinite(l)&&l>=10?l:b),u=setInterval(i,N);return u.unref(),u}export{E as LAST_MAINTENANCE_KEY,I as claimMaintenanceSlot,L as lastMaintenanceAt,C as maybeRunMaintenance,P as scheduleMaintenanceSweep,k as snapshotAfterSweep};
|
package/dist/tool-manifest.json
CHANGED
package/dist/wyrm-manifest.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "wyrm-mcp",
|
|
3
|
-
"version": "9.5.
|
|
3
|
+
"version": "9.5.2",
|
|
4
4
|
"mcpName": "lk.ghosts/wyrm",
|
|
5
5
|
"description": "The intelligence layer for AI agents over MCP: local-first persistent memory with ground truths, a failure firewall that blocks repeated mistakes (negative learning), and hybrid recall, stored in SQLite on your machine. No cloud or LLM required. Proprietary license.",
|
|
6
6
|
"type": "module",
|