wyrm-mcp 9.4.2 → 9.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cloud/cli.js CHANGED
@@ -1,4 +1,4 @@
1
- import{randomBytes as L}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 d,CloudError as h,DEFAULT_BASE as v,SESSION_FILE as $,loadSession as g,saveSession as C,clearSession as _}from"./client.js";import{getMasterKey as J,keyExists as k,keyFilePath as u,decrypt as Y}from"./crypto.js";import{computeMachineFp as D,classifySession as q,cloudMachineId as K}from"./machine-id.js";import{runSync as z,CopiedSessionError as V,pendingPush as Q,peekCursor as X,parseSince as Z}from"./sync-engine.js";import{WyrmDB as ee,resolveDbPath as oe}from"../database.js";import{redactCredentials as se}from"../security.js";import{SovereignSyncManager as te,restartIntervalMinutes as ne}from"./sync-daemon.js";import{initializeLicense as re,hasFeature as ce,getTier as le}from"../license.js";function S(){re(),ce("cloud_backup")||(console.error("\u{F115D} Wyrm Cloud sync requires a Pro license or higher."),console.error(` Current tier: ${le()}`),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 Le(e){const n=e[0],t=e.slice(1);try{switch(n){case void 0:case"help":case"--help":case"-h":return ie();case"login":return await ae(t);case"logout":return await de();case"status":return await ue(t);case"doctor":return me();case"devices":return await ye(t);case"sync":return await he(t);case"daemon":return await we(t);case"export":return await ve(t);case"delete":return await $e(t);case"recovery":return await _e(t);default:console.error(`Unknown subcommand: wyrm cloud ${n}`),console.error("Try `wyrm cloud help`"),process.exit(1)}}catch(o){if(o instanceof V&&process.exit(1),o instanceof h)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 ie(){console.log(`\u{F115D} wyrm cloud: sync your Wyrm memory across devices
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 _}from"./client.js";import{getMasterKey as Y,keyExists as k,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 ke(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]
@@ -18,11 +18,16 @@ SUBCOMMANDS:
18
18
  Push local cross-project rows + pull peer deltas.
19
19
  --all syncs every semantic table (ignores
20
20
  visibility opt-in). Skips telemetry / FTS / logs.
21
+ A row of a table with no updated_at goes out only
22
+ when its content changed since the cloud stored it.
23
+ One sync runs per store at a time; another started
24
+ meanwhile is skipped and exits 75.
21
25
  --force proceeds past a copied-session warning
22
26
  (or set WYRM_ALLOW_COPIED_SESSION=1).
23
27
  --since re-pushes rows changed at or after <when>
24
28
  (2026-10-01 as a UTC day, an ISO datetime, or epoch
25
- milliseconds), even below the push mark. Try it with
29
+ milliseconds), even below the push mark, and every
30
+ row of the tables with no updated_at. Try it with
26
31
  --dry-run first.
27
32
  daemon <start|stop|restart|status> [--interval=<min>]
28
33
  Hands-off sovereign sync: run 'sync' every interval
@@ -45,6 +50,6 @@ CONSTITUTION:
45
50
 
46
51
  DOMAIN:
47
52
  https://wyrm.ghosts.lk
48
- `)}async function ae(e){const n=g();if(n)try{await new d(n.base,n.session).me(),console.error("Already logged in. Run `wyrm cloud logout` first to switch accounts."),process.exit(1)}catch(i){i instanceof h&&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."),_()}const t=new d(v),o=L(32).toString("hex");let r;try{r=await t.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 t.cliPoll(o);if(i.ready&&i.session){l=i.session,a=i.account_id;break}}catch(i){console.error(`
49
- \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 m=new d(v,l);let y="";try{y=(await m.me()).account.email}catch{}const f=`${F()} (${process.platform})`;let p;try{p=(await m.registerDevice(f,void 0,K())).device.id;const w=g();w&&C({...w,email:y,device_id:p,device_name:f,machine_fp:D()})}catch(i){console.error(`
50
- \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 ${y}`),console.log(`\u2713 Device registered: ${f}`),console.log(`\u2713 Session saved to ${$}`);const A=!k();if(J(),A?(console.log(`\u2713 Encryption key generated at ${u()} (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 ${u()}`),p)try{const i=await m.syncStatus();if(i.deltas>0){const E=(await m.syncPull(p,0,1)).deltas[0];if(E){let T=!0;try{Y(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 ${u()} 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 ${u()}. 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 de(){const e=g();if(!e){console.log("Not logged in.");return}try{await new d(e.base,e.session).logout(),console.log("\u2713 Session revoked server-side.")}catch(n){console.error(`\u26A0 Could not revoke server-side: ${n instanceof Error?n.message:n}`),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 I(e){const n=new ee(oe());try{const t=Q(n,{all:e}),o=X(n.getDatabase());for(const r of t.errors)console.error(`\u26A0 pending count: ${r}`);return{...t,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{n.close()}catch{}}}const N="Session expired or invalid. Run `wyrm cloud login` again.";function O(e){const n=e?.message,t=typeof n=="string"?n:String(e),o=M();return se(o&&o!=="/"?t.split(o).join("~"):t)}async function ue(e){const n=e.includes("--json"),t=e.includes("--all"),o=g();if(!o){if(n){console.log(JSON.stringify({logged_in:!1})),process.exitCode=1;return}console.log("Not logged in. Run `wyrm cloud login`.");return}if(n)return ge(o,t);let r;try{const c=I(t);r=`${c.rows} row(s), ${c.tombstones} tombstone(s) not yet pushed`}catch(c){r=`unknown (${O(c)})`}const s=new d(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: ${u()} (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: ${u()}`),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 h&&c.status===401&&(console.error(N),process.exit(1)),c}}async function ge(e,n){const t=e.device_id?e.device_id.slice(0,8):null;let o;try{o=I(n)}catch(s){console.log(JSON.stringify({logged_in:!0,device:t,error:`store: ${O(s)}`})),process.exitCode=2;return}let r;try{const s=await new d(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 h&&s.status===401?N:s instanceof Error?s.message:String(s)}}console.log(JSON.stringify({logged_in:!0,device:t,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:n?"all":"default"},pull:{last_pull_at:o.last_pull_at},remote:r}))}function P(e){const n=q(e.machine_fp);n.state==="match"?console.log(" Identity: \u2713 machine fingerprint matches (not a copied session)"):n.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 ${n.stored.slice(0,12)}\u2026 vs this machine ${n.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 me(){const e=g();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: ${D().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 ye(e){const n=e[0],t=d.fromSession();if(n==="revoke"){const l=e[1];l||(console.error("Usage: wyrm cloud devices revoke <device-id>"),process.exit(1));const a=await pe(t,l);await t.revokeDevice(a),console.log(`\u2713 Device ${a.slice(0,8)}\u2026 revoked.`);return}const o=e.includes("--full"),{devices:r}=await t.listDevices(),c=g()?.device_id;console.log(""),console.log(`\u{F115D} Devices (${r.length})`),console.log("");for(const l of r){const a=l.id===c?"\u2605":" ",m=l.revoked?"(revoked)":"",y=o?l.id:`${l.id.slice(0,8)}\u2026`;console.log(` ${a} ${y} ${l.name.padEnd(30)} last_seen=${x(l.last_seen_at)} ${m}`)}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 pe(e,n){const t=n.replace(/[….]+$/,"").trim().toLowerCase(),{devices:o}=await e.listDevices(),r=o.find(c=>c.id.toLowerCase()===t);if(r)return r.id;const s=o.filter(c=>c.id.toLowerCase().startsWith(t));if(s.length===1)return s[0].id;s.length===0&&(console.error(`\u2718 No device matches "${n}". List them with: wyrm cloud devices`),process.exit(1)),console.error(`\u2718 "${n}" 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)}async function he(e){let n;const t=e.findIndex(l=>l==="--since"||l.startsWith("--since="));if(t>=0){const l=e[t];try{n=Z(l==="--since"?e[t+1]??"":l.slice(8))}catch(a){console.error(`\u2718 ${a instanceof Error?a.message:a}`),process.exitCode=1;return}}S();const o=e.includes("--dry-run"),r=e.includes("--all"),s=e.includes("--force");k()||(console.error("\u26A0 Encryption key not found at",u()),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(l=>{setTimeout(l,5e3)})),r&&(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.`);const c=await z({dryRun:o,all:r,force:s,sinceMs:n});if(console.log(""),console.log(c.errors.length>0?"\u{F115D} Sync finished with errors":"\u{F115D} Sync complete"),console.log(""),console.log(` Pushed: ${c.pushed} row(s)${o?" (dry run)":""}`),console.log(` Pulled: ${c.pulled} row(s)`),console.log(` Deleted: ${c.deleted_local} row(s) (peer tombstones)`),c.quarantined&&c.quarantined>0&&console.log(` Quarantined: ${c.quarantined} undecryptable delta(s) set aside (see errors)`),c.errors.length>0){console.log(""),console.log(" Errors:");for(const l of c.errors)console.log(` - ${l}`);process.exitCode=1}console.log("")}function fe(){const e=U(B(G(import.meta.url)),"sync-daemon-entrypoint.js");return new te(e)}async function we(e){S();const n=e[0]??"status",t=e.find(s=>s.startsWith("--interval="));let o;if(t){const s=Number(t.split("=")[1]);(!Number.isFinite(s)||s<=0)&&(console.error("\u2716 --interval= expects a positive number of minutes, got "+JSON.stringify(t)),process.exit(1)),o=s}const r=fe();switch(n){case"start":{g()||(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=ne(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: ${n}. Use: start, stop, restart, status`),process.exit(1)}}async function ve(e){S();const n=d.fromSession(),t=e.find(c=>!c.startsWith("-")),o=j(t??`wyrm-cloud-export-${new Date().toISOString().slice(0,10)}.json`);console.log(" Fetching account export\u2026");const r=await n.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 ${u()}. Back that up alongside this file.`),console.log("")}async function $e(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 t=g();t||(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: ${t.email??t.account_id}`),console.log(` Server: ${t.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 R(' Type "DELETE my account" to confirm: ')).trim()!=="DELETE my account"&&(console.error("\u2718 Confirmation phrase did not match. Aborting."),process.exit(1)),await new d(t.base,t.session).accountDelete(),_(),console.log(""),console.log("\u2713 Account deleted on server."),console.log(`\u2713 Local session removed (${$}).`),console.log(` Kept: ${u()} (in case you need to decrypt an old export).`),console.log("")}function R(e){return new Promise(n=>{const t=H({input:process.stdin,output:process.stdout});t.question(e,o=>{t.close(),n(o)})})}async function _e(e){const n=e[0];if(n==="show"){const{keyToMnemonic:t}=await import("./recovery.js"),r=t().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(n==="restore"){const t=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 R(" > "),{mnemonicToKey:r}=await import("./recovery.js"),{path:s,overwrote:c}=r(o,{overwrite:t});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{Le as cmdCloud};
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."),_()}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
+ \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};
@@ -1,5 +1,5 @@
1
- import{readFileSync as Z,writeFileSync as tt,existsSync as et}from"node:fs";import{join as nt}from"node:path";import{createHash as st}from"node:crypto";import{WyrmDB as rt,resolveDbPath as ot}from"../database.js";import{getLineage as at,getCursor as C,setCursor as it,importCursorFile as ct,bumpDeviceEpoch as lt,mirrorStamp as F}from"../lineage.js";import{CloudClient as ut,CloudError as dt,loadSession as pt,saveSession as _t,resolveCloudDir as ft}from"./client.js";import{encrypt as mt,decrypt as ht}from"./crypto.js";import{classifySession as yt,computeMachineFp as Et}from"./machine-id.js";import{redactInboundRow as L}from"../inbound-redact.js";function M(){return nt(ft(),"cloud-cursor.json")}const P=2;function bt(t,e,r,n){const a=t?{...t}:{kind:e.kind,row_id:e.row_id,attempts:0,quarantined:!1,last_error:r,first_ms:n,last_ms:n};a.attempts+=1,a.last_error=r,a.last_ms=n;const s=a.attempts>=P,c=s&&!a.quarantined;return s&&(a.quarantined=!0),{entry:a,action:s?"skip":"retry",newlyQuarantined:c}}const I=[{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}],gt=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","mcp_client_configs","watch_dirs","global_context","schema_versions","failure_patterns","data_lake","projects"]),St=/_fts(_config|_data|_docsize|_idx)?$/;function W(t){const e=t.getDatabase(),r=[...I],n=new Set(I.map(a=>a.table));try{const a=e.prepare(`SELECT name FROM sqlite_master
2
- WHERE type='table' AND name NOT LIKE 'sqlite_%'`).all();for(const s of a){const c=s.name;if(n.has(c)||gt.has(c)||St.test(c)||!S.test(c))continue;const o=e.prepare(`PRAGMA table_info(${c})`).all();if(!o.some(l=>l.name==="id"))continue;const i=o.some(l=>l.name==="cross_project_visibility");r.push({kind:c,table:c,hasVisibility:i})}}catch{}return r}function ee(t){return t}function H(t,e){if(!S.test(e))return new Set;try{const n=t.getDatabase().prepare(`PRAGMA table_info(${e})`).all();return new Set(n.filter(a=>S.test(a.name)).map(a=>a.name))}catch{return new Set}}const S=/^[a-z_][a-z0-9_]*$/i;function q(){const t=M();if(!et(t))return null;try{const e=JSON.parse(Z(t,"utf-8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function wt(t){const e={pull_cursor:0,last_push_updated_ms:0,last_push_at:0,last_push_attempt_at:0,last_pull_at:0},r=at(t),n=q();let a=C(t,"cloud");if(!a){if(ct(t,"cloud",M()),a=C(t,"cloud"),!a){if(!n)return e;const{store:c,...o}=n;return{...e,...o}}return{...e,...a.value}}const s=n?.store;return n&&s&&s.device_id===r.deviceId&&s.epoch===r.epoch&&s.fingerprint===F(t).fingerprint&&Number(n.last_pull_at??0)>Number(a.value.last_pull_at??0)&&lt(t,"cloud-cursor.json is ahead of the database (restored in place)"),{...e,...a.value}}function V(t){let e;try{e=C(t,"cloud")?.value}catch{}if(!e){const n=q();if(n){const{store:a,...s}=n;e=s}}const r=n=>Number.isFinite(Number(n))?Number(n):0;return{last_push_updated_ms:r(e?.last_push_updated_ms),last_push_at:r(e?.last_push_at),last_push_attempt_at:r(e?.last_push_attempt_at??e?.last_push_at),last_pull_at:r(e?.last_pull_at)}}function Nt(t,e){try{it(t,"cloud",e)}catch{}tt(M(),JSON.stringify({...e,store:F(t)},null,2),{mode:384})}function Y(t){t.getDatabase().exec(`
1
+ import{readFileSync as te,writeFileSync as ne,existsSync as se}from"node:fs";import{join as re}from"node:path";import{createHash as P}from"node:crypto";import{WyrmDB as oe,resolveDbPath as ae}from"../database.js";import{getLineage as ie,getCursor as A,setCursor as le,importCursorFile as ce,bumpDeviceEpoch as ue,mirrorStamp as W}from"../lineage.js";import{CloudClient as de,CloudError as pe,loadSession as _e,saveSession as fe,resolveCloudDir as he}from"./client.js";import{encrypt as me,decrypt as ye}from"./crypto.js";import{classifySession as ge,computeMachineFp as Ee}from"./machine-id.js";import{redactInboundRow as C}from"../inbound-redact.js";import{acquireSyncLock as be}from"./sync-lock.js";function M(){return re(he(),"cloud-cursor.json")}const H=2;function Se(e,t,r,n){const o=e?{...e}:{kind:t.kind,row_id:t.row_id,attempts:0,quarantined:!1,last_error:r,first_ms:n,last_ms:n};o.attempts+=1,o.last_error=r,o.last_ms=n;const s=o.attempts>=H,a=s&&!o.quarantined;return s&&(o.quarantined=!0),{entry:o,action:s?"skip":"retry",newlyQuarantined:a}}const k=[{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}],we=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"]),Ne=/_fts(_config|_data|_docsize|_idx)?$/;function q(e){const t=e.getDatabase(),r=[...k],n=new Set(k.map(o=>o.table));try{const o=t.prepare(`SELECT name FROM sqlite_master
2
+ WHERE type='table' AND name NOT LIKE 'sqlite_%'`).all();for(const s of o){const a=s.name;if(n.has(a)||we.has(a)||Ne.test(a)||!w.test(a))continue;const i=t.prepare(`PRAGMA table_info(${a})`).all();if(!i.some(c=>c.name==="id"))continue;const l=i.some(c=>c.name==="cross_project_visibility");r.push({kind:a,table:a,hasVisibility:l})}}catch{}return r}function ct(e){return e}function V(e,t){if(!w.test(t))return new Set;try{const n=e.getDatabase().prepare(`PRAGMA table_info(${t})`).all();return new Set(n.filter(o=>w.test(o.name)).map(o=>o.name))}catch{return new Set}}const w=/^[a-z_][a-z0-9_]*$/i;function Y(){const e=M();if(!se(e))return null;try{const t=JSON.parse(te(e,"utf-8"));return t&&typeof t=="object"&&!Array.isArray(t)?t:null}catch{return null}}function Te(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=ie(e),n=Y();let o=A(e,"cloud");if(!o){if(ce(e,"cloud",M()),o=A(e,"cloud"),!o){if(!n)return t;const{store:a,...i}=n;return{...t,...i}}return{...t,...o.value}}const s=n?.store;return n&&s&&s.device_id===r.deviceId&&s.epoch===r.epoch&&s.fingerprint===W(e).fingerprint&&Number(n.last_pull_at??0)>Number(o.value.last_pull_at??0)&&ue(e,"cloud-cursor.json is ahead of the database (restored in place)"),{...t,...o.value}}function G(e){let t;try{t=A(e,"cloud")?.value}catch{}if(!t){const n=Y();if(n){const{store:o,...s}=n;t=s}}const r=n=>Number.isFinite(Number(n))?Number(n):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 Ie(e,t){try{le(e,"cloud",t)}catch{}ne(M(),JSON.stringify({...t,store:W(e)},null,2),{mode:384})}function B(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,15 +10,25 @@ import{readFileSync as Z,writeFileSync as tt,existsSync as et}from"node:fs";impo
10
10
  );
11
11
  CREATE INDEX IF NOT EXISTS idx_sync_tombstones_pending
12
12
  ON sync_tombstones(pushed_at_ms);
13
- `)}function ne(t,e,r){if(typeof e!="string"||e.length===0||e.length>64)return;Y(t),t.getDatabase().prepare(`INSERT OR IGNORE INTO sync_tombstones (kind, row_id, deleted_at_ms)
14
- VALUES (?, ?, ?)`).run(e,String(r),Date.now())}class Tt extends Error{constructor(e){super(e),this.name="CopiedSessionError"}}function It(t){return!!t||process.env.WYRM_ALLOW_COPIED_SESSION==="1"}function Ot(t,e,r){const n=yt(t.machine_fp);if(n.state==="match")return;if(n.state==="adopt"){e(Et());return}const a=["","\u26A0 WYRM CLOUD: this session looks COPIED from another machine.","",` Stored machine fingerprint: ${n.stored.slice(0,12)}\u2026`,` This machine's fingerprint: ${n.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(It(r)){console.error(a.join(`
15
- `)),console.error(" Proceeding anyway (--force / WYRM_ALLOW_COPIED_SESSION=1); fingerprint updated."),console.error(""),e(n.current);return}throw console.error(a.join(`
16
- `)),new Tt("Cloud session looks copied from another machine (device_id collision). Re-login or pass --force.")}async function se(t={}){if(t.sinceMs!==void 0&&!(Number.isFinite(t.sinceMs)&&t.sinceMs>=0))throw new Error($);const e=pt();if(!e||!e.device_id)throw new Error("Not logged in or device not registered. Run `wyrm cloud login`.");Ot(e,a=>{_t({...e,machine_fp:a})},t.force);const r=new ut(e.base,e.session),n=new rt(ot());try{return await kt(n,r,e.device_id,t)}finally{try{n.close()}catch{}}}async function kt(t,e,r,n){Y(t);const a=t.getDatabase(),s=wt(a),c=Number(s.last_push_at)||Number(s.last_pull_at)||0,o={pushed:0,pulled:0,deleted_local:0,errors:[],quarantined:0,conflicts:0},i=n.all?W(t):I,l=Date.now(),m=s.last_push_updated_ms,E=G(t,i,Dt(m,n.sinceMs),!!n.all,o.errors);if(E.length>0&&!n.dryRun){const h=await Ut(e,r,E,{prevMark:m,selectedAtMs:l},o.errors);o.pushed+=h.pushed,s.last_push_updated_ms=h.mark,s.last_push_attempt_at=Date.now(),h.stopped||(s.last_push_at=s.last_push_attempt_at),Pt(t,h.tombstoneIds)}else o.pushed=E.length,n.dryRun||(s.last_push_at=s.last_push_attempt_at=Date.now());if(!n.dryRun){let h=s.pull_cursor,b=0;t:for(;b<50;){let _;try{_=await e.syncPull(r,h,100)}catch(u){o.errors.push(`pull failed: ${u instanceof Error?u.message:u}`);break}if(_.deltas.length===0)break;for(const u of _.deltas)try{const d=ht(u.payload_b64);if(u.kind==="tombstone"){const{kind:p,row_id:f}=JSON.parse(d);Vt(t,i,p,f)&&o.deleted_local++}else{const p=JSON.parse(d);Wt(t,i,u.kind,u.row_id,p,{remoteOrigin:`cloud:${u.device_id??"unknown"}`,lastSyncMs:c}).conflictId!==void 0&&(o.conflicts=(o.conflicts??0)+1),o.pulled++}}catch(d){const p=d instanceof Error?d.message:String(d),f=s.quarantine??={},{entry:g,action:T,newlyQuarantined:k}=bt(f[u.id],u,p,Date.now());if(f[u.id]=g,T==="skip"){k&&(o.quarantined=(o.quarantined??0)+1),o.errors.push(`quarantined ${u.kind}:${u.row_id} after ${g.attempts} attempts (${p})`);continue}o.errors.push(`apply ${u.kind}:${u.row_id}: ${p} (attempt ${g.attempts}/${P}, will retry)`);break t}if(h=_.next_cursor,!_.has_more)break;b++}s.pull_cursor=h,s.last_pull_at=Date.now()}return Nt(a,s),o}const $="--since must be an ISO date or epoch milliseconds",Rt=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})?)?$/i,$t=1e12;function re(t){const e=typeof t=="string"?t.trim():"";if(/^\d+$/.test(e)){const n=Number(e);if(!Number.isSafeInteger(n))throw new Error($);if(n<$t)throw new Error(`${$} (epoch milliseconds, not seconds; or use YYYY-MM-DD): a number below 1000000000000 is before 2001-09-09`);return n}const r=Rt.exec(e);if(r){const[,n,a,s,c="00",o="00",i="00",l,m]=r,E=new Date(Date.UTC(Number(n),Number(a)-1,Number(s))),b=E.getUTCFullYear()===Number(n)&&E.getUTCMonth()===Number(a)-1&&E.getUTCDate()===Number(s)?Date.parse(`${n}-${a}-${s}T${c}:${o}:${i}${l?`.${l}`:""}${m?m.toUpperCase():"Z"}`):NaN;if(Number.isFinite(b)&&b>=0)return b}throw new Error($)}function Dt(t,e){return e===void 0?t:Math.min(t,Math.max(0,e-1))}function oe(t,e={}){const r=t.getDatabase(),n=V(r).last_push_updated_ms,a=e.all?W(t):I,s=[];return{rows:G(t,a,n,!!e.all,s).filter(o=>o.tombstoneId===null).length,tombstones:At(r),mark_ms:n,errors:s}}function At(t){try{return t.prepare("SELECT COUNT(*) AS n FROM sync_tombstones WHERE pushed_at_ms IS NULL").get().n}catch{return 0}}function ae(t,e){const r=t.getDatabase(),n=V(r).last_push_updated_ms;if(n<=0)return null;let a=0,s=1/0;for(const o of I){if(!o.hasVisibility||!N(t,o.table,"project_id")||!N(t,o.table,"updated_at"))continue;const i=r.prepare(`SELECT COUNT(*) AS n, MIN(CAST(strftime('%s', updated_at) AS INTEGER)) AS earliest
17
- FROM ${o.table}
13
+ `)}function Oe(e){e.exec(`
14
+ CREATE TABLE IF NOT EXISTS cloud_push_ledger (
15
+ kind TEXT NOT NULL,
16
+ row_id TEXT NOT NULL,
17
+ hash TEXT NOT NULL,
18
+ pushed_at INTEGER NOT NULL,
19
+ PRIMARY KEY (kind, row_id)
20
+ );
21
+ `)}function ke(e){const t=Object.fromEntries(Object.keys(e).sort().map(r=>[r,e[r]]));return P("sha256").update(JSON.stringify(t)).digest("hex")}function Re(e,t){let r;try{r=e.prepare("SELECT row_id, hash FROM cloud_push_ledger WHERE kind = ?").all(t)}catch(n){if(/no such table/i.test(n instanceof Error?n.message:String(n)))return new Map;throw n}return new Map(r.map(n=>[n.row_id,n.hash]))}function Le(e,t,r,n){e.transaction(()=>{Oe(e);const o=e.prepare("DELETE FROM cloud_push_ledger WHERE kind = ? AND row_id = ?");for(const a of r)o.run(a.kind,a.row_id);const s=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 a of t)s.run(a.kind,a.row_id,a.hash,n)})()}function $e(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(n){if(/no such table: cloud_push_ledger/i.test(n instanceof Error?n.message:String(n)))return[];throw n}}function X(e,t,r,n){const o=t.flatMap(s=>s.hash===null?[]:[{kind:s.kind,row_id:s.row_id,hash:s.hash}]);if(!(o.length===0&&r.length===0))try{Le(e.getDatabase(),o,r,Date.now())}catch(s){const a=o.length>0?`; ${o.length} row(s) go out again with the next sync`:"";n.push(`push ledger not written: ${v(s)}${a}`)}}function ut(e,t,r){if(typeof t!="string"||t.length===0||t.length>64)return;B(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 De extends Error{constructor(t){super(t),this.name="CopiedSessionError"}}function Ae(e){return!!e||process.env.WYRM_ALLOW_COPIED_SESSION==="1"}function Ce(e,t,r){const n=ge(e.machine_fp);if(n.state==="match")return;if(n.state==="adopt"){t(Ee());return}const o=["","\u26A0 WYRM CLOUD: this session looks COPIED from another machine.","",` Stored machine fingerprint: ${n.stored.slice(0,12)}\u2026`,` This machine's fingerprint: ${n.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(Ae(r)){console.error(o.join(`
25
+ `)),console.error(" Proceeding anyway (--force / WYRM_ALLOW_COPIED_SESSION=1); fingerprint updated."),console.error(""),t(n.current);return}throw console.error(o.join(`
26
+ `)),new De("Cloud session looks copied from another machine (device_id collision). Re-login or pass --force.")}async function dt(e={}){if(e.sinceMs!==void 0&&!(Number.isFinite(e.sinceMs)&&e.sinceMs>=0))throw new Error($);const t=_e();if(!t||!t.device_id)throw new Error("Not logged in or device not registered. Run `wyrm cloud login`.");Ce(t,s=>{fe({...t,machine_fp:s})},e.force);const r=new de(t.base,t.session),n=ae(),o=be(n);try{e.onStart?.();const s=new oe(n);try{return await Me(s,r,t.device_id,e)}finally{try{s.close()}catch{}}}finally{o()}}async function Me(e,t,r,n){B(e);const o=e.getDatabase(),s=Te(o),a=Number(s.last_push_at)||Number(s.last_pull_at)||0,i={pushed:0,pulled:0,deleted_local:0,errors:[],quarantined:0,conflicts:0},l=n.all?q(e):k,c=Date.now(),p=s.last_push_updated_ms,g=[],b=J(e,l,je(p,n.sinceMs),!!n.all,i.errors,{useLedger:n.sinceMs===void 0,stale:g});if(b.length>0&&!n.dryRun){const m=await Ve(t,r,b,{prevMark:p,selectedAtMs:c},i.errors);i.pushed+=m.pushed,s.last_push_updated_ms=m.mark,s.last_push_attempt_at=Date.now(),m.stopped||(s.last_push_at=s.last_push_attempt_at),Be(e,m.tombstoneIds),X(e,m.ledger,g,i.errors)}else i.pushed=b.length,n.dryRun||(s.last_push_at=s.last_push_attempt_at=Date.now(),X(e,[],g,i.errors));if(!n.dryRun){let m=s.pull_cursor,E=0;e:for(;E<50;){let _;try{_=await t.syncPull(r,m,100)}catch(d){i.errors.push(`pull failed: ${d instanceof Error?d.message:d}`);break}if(_.deltas.length===0)break;for(const d of _.deltas)try{const h=ye(d.payload_b64);if(d.kind==="tombstone"){const{kind:u,row_id:f}=JSON.parse(h);Ke(e,l,u,f)&&i.deleted_local++}else{const u=JSON.parse(h);Xe(e,l,d.kind,d.row_id,u,{remoteOrigin:`cloud:${d.device_id??"unknown"}`,lastSyncMs:a}).conflictId!==void 0&&(i.conflicts=(i.conflicts??0)+1),i.pulled++}}catch(h){const u=h instanceof Error?h.message:String(h),f=s.quarantine??={},{entry:S,action:N,newlyQuarantined:T}=Se(f[d.id],d,u,Date.now());if(f[d.id]=S,N==="skip"){T&&(i.quarantined=(i.quarantined??0)+1),i.errors.push(`quarantined ${d.kind}:${d.row_id} after ${S.attempts} attempts (${u})`);continue}i.errors.push(`apply ${d.kind}:${d.row_id}: ${u} (attempt ${S.attempts}/${H}, will retry)`);break e}if(m=_.next_cursor,!_.has_more)break;E++}s.pull_cursor=m,s.last_pull_at=Date.now()}return Ie(o,s),i}const $="--since must be an ISO date or epoch milliseconds",ve=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})?)?$/i,Ue=1e12;function pt(e){const t=typeof e=="string"?e.trim():"";if(/^\d+$/.test(t)){const n=Number(t);if(!Number.isSafeInteger(n))throw new Error($);if(n<Ue)throw new Error(`${$} (epoch milliseconds, not seconds; or use YYYY-MM-DD): a number below 1000000000000 is before 2001-09-09`);return n}const r=ve.exec(t);if(r){const[,n,o,s,a="00",i="00",l="00",c,p]=r,g=new Date(Date.UTC(Number(n),Number(o)-1,Number(s))),m=g.getUTCFullYear()===Number(n)&&g.getUTCMonth()===Number(o)-1&&g.getUTCDate()===Number(s)?Date.parse(`${n}-${o}-${s}T${a}:${i}:${l}${c?`.${c}`:""}${p?p.toUpperCase():"Z"}`):NaN;if(Number.isFinite(m)&&m>=0)return m}throw new Error($)}function je(e,t){return t===void 0?e:Math.min(e,Math.max(0,t-1))}function _t(e,t={}){const r=e.getDatabase(),n=G(r).last_push_updated_ms,o=t.all?q(e):k,s=[];return{rows:J(e,o,n,!!t.all,s).filter(i=>i.tombstoneId===null).length,tombstones:xe(r),mark_ms:n,errors:s}}function xe(e){try{return e.prepare("SELECT COUNT(*) AS n FROM sync_tombstones WHERE pushed_at_ms IS NULL").get().n}catch{return 0}}function ft(e,t){const r=e.getDatabase(),n=G(r).last_push_updated_ms;if(n<=0)return null;let o=0,s=1/0;for(const i of k){if(!i.hasVisibility||!O(e,i.table,"project_id")||!O(e,i.table,"updated_at"))continue;const l=r.prepare(`SELECT COUNT(*) AS n, MIN(CAST(strftime('%s', updated_at) AS INTEGER)) AS earliest
27
+ FROM ${i.table}
18
28
  WHERE project_id = ? AND cross_project_visibility IN ('org', 'public')
19
- AND updated_at IS NOT NULL AND strftime('%s', updated_at) * 1000 <= ?`).get(e,n);a+=i.n,i.earliest!==null&&i.earliest<s&&(s=i.earliest)}if(a===0||s===1/0)return null;const c=s*1e3;return{rows:a,earliest_ms:c,mark_ms:n,since:new Date(c).toISOString().slice(0,10)}}function G(t,e,r,n,a){const s=xt(t,e,r,n,a),c=Ft(t);return[...s.map(o=>{const i=o.updated_at??Date.now();return{kind:o.kind,row_id:String(o.row_id),visibility:o.visibility,body:o.row,updated_at:i,stamp:o.stamped?i:null,tombstoneId:null}}),...c.map(o=>({kind:"tombstone",row_id:`${o.kind}:${o.row_id}`,visibility:"org",body:{kind:o.kind,row_id:o.row_id,deleted_at_ms:o.deleted_at_ms},updated_at:o.deleted_at_ms,stamp:null,tombstoneId:o.id}))]}function Ct(t,e){let r=t,n=0;for(;n<e.length&&e[n].ok;n++)for(const s of e[n].stamps)s>r&&(r=s);let a=1/0;for(;n<e.length;n++)for(const s of e[n].stamps)s<a&&(a=s);return a===1/0?r:Math.min(r,Math.floor(a/1e3)*1e3-1)}const B=25,Lt=new Set([400,409,413,422]),Mt=new Set(["storage_cap_exceeded","invalid_device_id","bad_request","no_deltas"]);function J(t){if(!(t instanceof dt)||!Lt.has(t.status))return null;const e=t.body;return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:{}}function vt(t){const e=J(t);return e!==null&&!Mt.has(String(e.error))}function jt(t){return J(t)?.index===0}const Q=t=>t instanceof Error?t.message:String(t);async function Ut(t,e,r,n,a){const s=[];for(let _=0;_<r.length;_+=B)s.push(r.slice(_,_+B));const c=_=>_.flatMap(u=>u.stamp===null?[]:[u.stamp]),o=[],i=[];let l=0;const m=async(_,u)=>{const d=await t.syncPush(e,u);if(l+=d.accepted,d.rejected>0){const p=[...new Set((d.rejected_details??[]).map(f=>f.reason))].join(", ");return`the server did not store ${d.rejected} of ${u.length} delta(s)${p?` (${p})`:""}`}for(const p of _)p.tombstoneId!==null&&i.push(p.tombstoneId);return null},E=async(_,u)=>{for(let d=0;d<_.length;d++)try{const p=await m([_[d]],[u[d]]);if(p!==null)return p}catch(p){if(!jt(p))return Q(p);a.push(`push refused (HTTP ${p.status}) on ${_[d].kind}:${_[d].row_id}`)}return null};let h=null;for(let _=0;_<s.length&&h===null;_++){const u=s[_],d=u.map(f=>({kind:f.kind,row_id:f.row_id,visibility:f.visibility,payload_b64:mt(JSON.stringify(f.body)),updated_at:f.updated_at}));let p;try{p=await m(u,d)}catch(f){p=vt(f)?await E(u,d):Q(f)}if(p===null){o.push({ok:!0,stamps:c(u)});continue}for(const f of s.slice(_))o.push({ok:!1,stamps:c(f)});h={chunk:_+1,why:p}}const b=Math.min(Ct(n.prevMark,o),Math.floor(n.selectedAtMs/1e3)*1e3-1);if(h!==null){const _=new Set(i),u=r.filter(d=>d.tombstoneId!==null?!_.has(d.tombstoneId):d.stamp===null||d.stamp>b).length;a.push(`push stopped at chunk ${h.chunk} of ${s.length}: ${h.why}; ${u} row(s) left for the next sync`)}return{pushed:l,mark:b,tombstoneIds:i,stopped:h!==null}}function v(t){if(typeof t!="string"||t.length===0)return 0;const e=t.includes("T")?t:t.replace(" ","T")+"Z",r=Date.parse(e);return Number.isFinite(r)?r:0}function N(t,e,r){try{return t.getDatabase().prepare(`PRAGMA table_info(${e})`).all().some(s=>s.name===r)}catch{return!1}}function xt(t,e,r,n,a){const s=[],c=t.getDatabase(),o=N(t,"projects","sync_policy");for(const i of e)if(S.test(i.table)&&!(!n&&!i.hasVisibility))try{const l=N(t,i.table,"updated_at"),m=i.hasVisibility?"WHERE cross_project_visibility IN ('org', 'public')":"WHERE 1=1",E=o&&N(t,i.table,"project_id")?"AND (project_id IS NULL OR project_id IN (SELECT id FROM projects WHERE sync_policy IN ('cloud', 'team')))":"",h=l?"AND (? = 0 OR updated_at IS NULL OR strftime('%s', updated_at) * 1000 > ?)":"",b=l?"ORDER BY (updated_at IS NULL) ASC, updated_at ASC":"",_=`SELECT * FROM ${i.table} ${m} ${E} ${h} ${b}`,u=c.prepare(_),d=l?u.all(r,r):u.all();for(const p of d){const f=v(p.updated_at);if(r>0&&f>0&&f<=r)continue;const g=i.hasVisibility?String(p.cross_project_visibility??"within"):"org";s.push({kind:i.kind,row_id:p.id??"?",visibility:g,row:p,updated_at:f||Date.now(),stamped:f>0})}}catch(l){const m=l instanceof Error?l.message:String(l);if(/no such table/i.test(m))continue;a.push(`collect ${i.table}: ${m}`)}return s.sort((i,l)=>(i.updated_at??0)-(l.updated_at??0)),s}function Ft(t){const e=t.getDatabase();try{return e.prepare(`SELECT id, kind, row_id, deleted_at_ms
29
+ AND updated_at IS NOT NULL AND strftime('%s', updated_at) * 1000 <= ?`).get(t,n);o+=l.n,l.earliest!==null&&l.earliest<s&&(s=l.earliest)}if(o===0||s===1/0)return null;const a=s*1e3;return{rows:o,earliest_ms:a,mark_ms:n,since:new Date(a).toISOString().slice(0,10)}}function J(e,t,r,n,o,s={}){const a=Ye(e,t,r,n,o,s),i=Ge(e);return[...a.map(l=>{const c=l.updated_at??Date.now();return{kind:l.kind,row_id:String(l.row_id),visibility:l.visibility,body:l.row,updated_at:c,stamp:l.stamped?c:null,tombstoneId:null,hash:l.hash}}),...i.map(l=>({kind:"tombstone",row_id:`${l.kind}:${l.row_id}`,visibility:"org",body:{kind:l.kind,row_id:l.row_id,deleted_at_ms:l.deleted_at_ms},updated_at:l.deleted_at_ms,stamp:null,tombstoneId:l.id,hash:null}))]}function Fe(e,t){let r=e,n=0;for(;n<t.length&&t[n].ok;n++)for(const s of t[n].stamps)s>r&&(r=s);let o=1/0;for(;n<t.length;n++)for(const s of t[n].stamps)s<o&&(o=s);return o===1/0?r:Math.min(r,Math.floor(o/1e3)*1e3-1)}const Q=25,Pe=new Set([400,409,413,422]),We=new Set(["storage_cap_exceeded","invalid_device_id","bad_request","no_deltas"]);function K(e){if(!(e instanceof pe)||!Pe.has(e.status))return null;const t=e.body;return t!==null&&typeof t=="object"&&!Array.isArray(t)?t:{}}function He(e){const t=K(e);return t!==null&&!We.has(String(t.error))}function qe(e){return K(e)?.index===0}const v=e=>{const t=e?.message;return typeof t=="string"?t:String(e)};async function Ve(e,t,r,n,o){const s=[];for(let _=0;_<r.length;_+=Q)s.push(r.slice(_,_+Q));const a=_=>_.flatMap(d=>d.stamp===null?[]:[d.stamp]),i=[],l=[],c=[];let p=0;const g=async(_,d)=>{const h=await e.syncPush(t,d);if(p+=h.accepted,h.rejected>0){const u=[...new Set((h.rejected_details??[]).map(f=>f.reason))].join(", ");return`the server did not store ${h.rejected} of ${d.length} delta(s)${u?` (${u})`:""}`}for(const u of _)u.tombstoneId!==null&&l.push(u.tombstoneId),u.hash!==null&&c.push(u);return null},b=async(_,d)=>{for(let h=0;h<_.length;h++)try{const u=await g([_[h]],[d[h]]);if(u!==null)return u}catch(u){if(!qe(u))return v(u);o.push(`push refused (HTTP ${u.status}) on ${_[h].kind}:${_[h].row_id}`)}return null};let m=null;for(let _=0;_<s.length&&m===null;_++){const d=s[_],h=d.map(f=>({kind:f.kind,row_id:f.row_id,visibility:f.visibility,payload_b64:me(JSON.stringify(f.body)),updated_at:f.updated_at}));let u;try{u=await g(d,h)}catch(f){u=He(f)?await b(d,h):v(f)}if(u===null){i.push({ok:!0,stamps:a(d)});continue}for(const f of s.slice(_))i.push({ok:!1,stamps:a(f)});m={chunk:_+1,why:u}}const E=Math.min(Fe(n.prevMark,i),Math.floor(n.selectedAtMs/1e3)*1e3-1);if(m!==null){const _=new Set(l),d=new Set(c),h=r.filter(u=>u.tombstoneId!==null?!_.has(u.tombstoneId):u.hash!==null?!d.has(u):u.stamp===null||u.stamp>E).length;o.push(`push stopped at chunk ${m.chunk} of ${s.length}: ${m.why}; ${h} row(s) left for the next sync`)}return{pushed:p,mark:E,tombstoneIds:l,ledger:c,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 O(e,t,r){try{return e.getDatabase().prepare(`PRAGMA table_info(${t})`).all().some(s=>s.name===r)}catch{return!1}}function Ye(e,t,r,n,o,s={}){const a=[],i=e.getDatabase(),l=O(e,"projects","sync_policy");for(const c of t)if(w.test(c.table)&&!(!n&&!c.hasVisibility))try{const p=O(e,c.table,"updated_at"),g=c.hasVisibility?"WHERE cross_project_visibility IN ('org', 'public')":"WHERE 1=1",b=l&&O(e,c.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 > ?)":"",E=p?"ORDER BY (updated_at IS NULL) ASC, updated_at ASC":"",_=`SELECT * FROM ${c.table} ${g} ${b} ${m} ${E}`,d=i.prepare(_),h=p?d.all(r,r):d.all(),u=p||s.useLedger===!1?null:Re(i,c.kind);!p&&s.stale&&s.stale.push(...$e(i,c.kind,c.table));for(const f of h){const S=p?null:ke(f);if(u!==null&&u.get(String(f.id??"?"))===S)continue;const N=U(f.updated_at);if(r>0&&N>0&&N<=r)continue;const T=c.hasVisibility?String(f.cross_project_visibility??"within"):"org";a.push({kind:c.kind,row_id:f.id??"?",visibility:T,row:f,updated_at:N||Date.now(),stamped:N>0,hash:S})}}catch(p){const g=p instanceof Error?p.message:String(p);if(/no such table/i.test(g))continue;o.push(`collect ${c.table}: ${g}`)}return a.sort((c,p)=>(c.updated_at??0)-(p.updated_at??0)),a}function Ge(e){const t=e.getDatabase();try{return t.prepare(`SELECT id, kind, row_id, deleted_at_ms
20
30
  FROM sync_tombstones
21
31
  WHERE pushed_at_ms IS NULL
22
32
  ORDER BY id ASC
23
- LIMIT 500`).all()}catch{return[]}}function Pt(t,e){if(e.length===0)return;const r=t.getDatabase(),n=Date.now(),a=r.prepare("UPDATE sync_tombstones SET pushed_at_ms = ? WHERE id = ?"),s=r.transaction(c=>{for(const o of c)a.run(n,o)});try{s(e)}catch{}}const K=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"]),O=t=>t==null?null:String(t);function X(t,e){const r=e.filter(n=>!K.has(n)).sort().map(n=>[n,O(t[n])]);return st("sha256").update(JSON.stringify(r)).digest("hex")}function j(t,e,r,n,a,s,c,o){const i=Number(n);if(Number.isSafeInteger(i))try{const l=JSON.stringify(L(e,a)),m=t.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 m?m.id:Number(t.prepare(`INSERT INTO sync_conflicts (local_kind, local_id, remote_payload, remote_origin, source, winner, local_payload)
24
- VALUES (?, ?, ?, ?, 'cloud', ?, ?)`).run(r,i,l,o,c,JSON.stringify(L(e,s))).lastInsertRowid)}catch{return}}function Wt(t,e,r,n,a,s={remoteOrigin:"cloud",lastSyncMs:0}){const c=e.find(y=>y.kind===r);if(!c)return{action:"skipped"};if(!S.test(c.table))throw new Error(`apply ${r}: refusing unsafe table name ${c.table}`);const o=L(c.table,a),i=H(t,c.table);if(i.size===0)throw new Error(`apply ${r}: ${c.table} has no readable schema`);const l=Object.keys(o).filter(y=>i.has(y)&&S.test(y));if(l.length===0)throw new Error(`apply ${r}: no columns from peer payload matched local schema`);const m=t.getDatabase(),E=l.map(()=>"?").join(","),h=l.join(","),b=l.map(y=>o[y]),_=l.filter(y=>y!=="id"),u=_.map(y=>`${y} = ?`).join(", "),d=o.id,p=(y,R)=>{try{return y==="insert"?m.prepare(`INSERT INTO ${c.table} (${h}) VALUES (${E})`).run(...b):_.length>0&&m.prepare(`UPDATE ${c.table} SET ${u} WHERE id = ?`).run(..._.map(w=>o[w]),d),{action:R}}catch(w){const A=Ht(w)?qt(m,c.table,i,o):void 0;if(!A)throw new Error(`apply ${r} failed: ${w instanceof Error?w.message:w}`);return{action:"kept_local",conflictId:j(m,c.table,r,A.id,o,A,"local",s.remoteOrigin)}}},f=!i.has("id")||d===void 0||d===null?void 0:m.prepare(`SELECT * FROM ${c.table} WHERE id = ?`).get(d);if(!f)return p("insert","inserted");if(!l.some(y=>!K.has(y)&&O(f[y])!==O(o[y])))return{action:"identical"};if(z(m,c.table,i,o).some(y=>y.some(R=>O(f[R])!==O(o[R]))))return{action:"kept_local",conflictId:j(m,c.table,r,f.id,o,f,"local",s.remoteOrigin)};const g=i.has("updated_at")?v(f.updated_at):0,T=i.has("updated_at")?v(o.updated_at):0;if(g===0||T===0)return p("update","updated");const k=g===T,D=k?X(o,l)>X(f,l):T>g,U=k||!D||s.lastSyncMs>0&&g>s.lastSyncMs?j(m,c.table,r,d,o,f,D?"remote":"local",s.remoteOrigin):void 0;if(!D)return{action:"kept_local",conflictId:U};const x=p("update","updated");return x.action==="kept_local"?x:{action:"updated",conflictId:U}}const Ht=t=>t?.code==="SQLITE_CONSTRAINT_UNIQUE"||/UNIQUE constraint failed/i.test(t instanceof Error?t.message:String(t));function z(t,e,r,n){const a=[];if(!S.test(e))return a;const s=t.prepare(`PRAGMA index_list(${e})`).all();for(const c of s){if(!c.unique||c.origin==="pk"||c.partial||!S.test(c.name))continue;const o=t.prepare(`PRAGMA index_info(${c.name})`).all().map(i=>i.name);o.length===0||o.some(i=>!i||!S.test(i)||!r.has(i)||!(i in n))||a.push(o)}return a}function qt(t,e,r,n){for(const a of z(t,e,r,n)){const s=a.map(o=>`${o} IS ?`).join(" AND "),c=t.prepare(`SELECT * FROM ${e} WHERE ${s}`).get(...a.map(o=>n[o]));if(c)return c}}function Vt(t,e,r,n){const a=e.find(i=>i.kind===r);if(!a||!S.test(a.table))return!1;const s=t.getDatabase(),c=H(t,a.table);if(c.has("cross_project_visibility")){const i=c.has("project_id")?s.prepare(`SELECT cross_project_visibility AS vis, project_id FROM ${a.table} WHERE id = ?`).get(n):s.prepare(`SELECT cross_project_visibility AS vis FROM ${a.table} WHERE id = ?`).get(n);if(!i||i.vis!=="org"&&i.vis!=="public")return!1;if(i.project_id!=null&&N(t,"projects","sync_policy")){const l=s.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 s.prepare(`DELETE FROM ${a.table} WHERE id = ?`).run(n).changes>0}export{Tt as CopiedSessionError,I as DEFAULT_TABLES,P as QUARANTINE_AFTER,$ as SINCE_USAGE,Wt as applyRow,xt as collectChangedRows,W as discoverTables,ae as groveBelowMark,Ot as guardCopiedSession,re as parseSince,V as peekCursor,oe as pendingPush,bt as quarantineDecision,ne as recordTombstone,se as runSync,Ct as safePushMark,G as selectPushItems};
33
+ LIMIT 500`).all()}catch{return[]}}function Be(e,t){if(t.length===0)return;const r=e.getDatabase(),n=Date.now(),o=r.prepare("UPDATE sync_tombstones SET pushed_at_ms = ? WHERE id = ?"),s=r.transaction(a=>{for(const i of a)o.run(n,i)});try{s(t)}catch{}}const z=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 Z(e,t){const r=t.filter(n=>!z.has(n)).sort().map(n=>[n,R(e[n])]);return P("sha256").update(JSON.stringify(r)).digest("hex")}function j(e,t,r,n,o,s,a,i){const l=Number(n);if(Number.isSafeInteger(l))try{const c=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,l,c);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,l,c,i,a,JSON.stringify(C(t,s))).lastInsertRowid)}catch{return}}function Xe(e,t,r,n,o,s={remoteOrigin:"cloud",lastSyncMs:0}){const a=t.find(y=>y.kind===r);if(!a)return{action:"skipped"};if(!w.test(a.table))throw new Error(`apply ${r}: refusing unsafe table name ${a.table}`);const i=C(a.table,o),l=V(e,a.table);if(l.size===0)throw new Error(`apply ${r}: ${a.table} has no readable schema`);const c=Object.keys(i).filter(y=>l.has(y)&&w.test(y));if(c.length===0)throw new Error(`apply ${r}: no columns from peer payload matched local schema`);const p=e.getDatabase(),g=c.map(()=>"?").join(","),b=c.join(","),m=c.map(y=>i[y]),E=c.filter(y=>y!=="id"),_=E.map(y=>`${y} = ?`).join(", "),d=i.id,h=(y,L)=>{try{return y==="insert"?p.prepare(`INSERT INTO ${a.table} (${b}) VALUES (${g})`).run(...m):E.length>0&&p.prepare(`UPDATE ${a.table} SET ${_} WHERE id = ?`).run(...E.map(I=>i[I]),d),{action:L}}catch(I){const D=Je(I)?Qe(p,a.table,l,i):void 0;if(!D)throw new Error(`apply ${r} failed: ${I instanceof Error?I.message:I}`);return{action:"kept_local",conflictId:j(p,a.table,r,D.id,i,D,"local",s.remoteOrigin)}}},u=!l.has("id")||d===void 0||d===null?void 0:p.prepare(`SELECT * FROM ${a.table} WHERE id = ?`).get(d);if(!u)return h("insert","inserted");if(!c.some(y=>!z.has(y)&&R(u[y])!==R(i[y])))return{action:"identical"};if(ee(p,a.table,l,i).some(y=>y.some(L=>R(u[L])!==R(i[L]))))return{action:"kept_local",conflictId:j(p,a.table,r,u.id,i,u,"local",s.remoteOrigin)};const f=l.has("updated_at")?U(u.updated_at):0,S=l.has("updated_at")?U(i.updated_at):0;if(f===0||S===0)return h("update","updated");const N=f===S,T=N?Z(i,c)>Z(u,c):S>f,x=N||!T||s.lastSyncMs>0&&f>s.lastSyncMs?j(p,a.table,r,d,i,u,T?"remote":"local",s.remoteOrigin):void 0;if(!T)return{action:"kept_local",conflictId:x};const F=h("update","updated");return F.action==="kept_local"?F:{action:"updated",conflictId:x}}const Je=e=>e?.code==="SQLITE_CONSTRAINT_UNIQUE"||/UNIQUE constraint failed/i.test(e instanceof Error?e.message:String(e));function ee(e,t,r,n){const o=[];if(!w.test(t))return o;const s=e.prepare(`PRAGMA index_list(${t})`).all();for(const a of s){if(!a.unique||a.origin==="pk"||a.partial||!w.test(a.name))continue;const i=e.prepare(`PRAGMA index_info(${a.name})`).all().map(l=>l.name);i.length===0||i.some(l=>!l||!w.test(l)||!r.has(l)||!(l in n))||o.push(i)}return o}function Qe(e,t,r,n){for(const o of ee(e,t,r,n)){const s=o.map(i=>`${i} IS ?`).join(" AND "),a=e.prepare(`SELECT * FROM ${t} WHERE ${s}`).get(...o.map(i=>n[i]));if(a)return a}}function Ke(e,t,r,n){const o=t.find(l=>l.kind===r);if(!o||!w.test(o.table))return!1;const s=e.getDatabase(),a=V(e,o.table);if(a.has("cross_project_visibility")){const l=a.has("project_id")?s.prepare(`SELECT cross_project_visibility AS vis, project_id FROM ${o.table} WHERE id = ?`).get(n):s.prepare(`SELECT cross_project_visibility AS vis FROM ${o.table} WHERE id = ?`).get(n);if(!l||l.vis!=="org"&&l.vis!=="public")return!1;if(l.project_id!=null&&O(e,"projects","sync_policy")){const c=s.prepare("SELECT sync_policy AS p FROM projects WHERE id = ?").get(l.project_id);if(c?.p&&c.p!=="cloud"&&c.p!=="team")return!1}}return s.prepare(`DELETE FROM ${o.table} WHERE id = ?`).run(n).changes>0}export{De as CopiedSessionError,k as DEFAULT_TABLES,H as QUARANTINE_AFTER,$ as SINCE_USAGE,Xe as applyRow,Ye as collectChangedRows,q as discoverTables,Oe as ensurePushLedgerTable,ft as groveBelowMark,Ce as guardCopiedSession,pt as parseSince,G as peekCursor,_t as pendingPush,Se as quarantineDecision,ut as recordTombstone,dt as runSync,Fe as safePushMark,J as selectPushItems};
@@ -0,0 +1,3 @@
1
+ import{linkSync as _,readFileSync as l,statSync as w,unlinkSync as s,writeFileSync as d}from"node:fs";import{basename as b,dirname as k,join as N}from"node:path";import{randomBytes as O}from"node:crypto";const D=75;class f extends Error{pid;since;constructor(n,r){const e=Number.isFinite(r)&&r>0?new Date(r).toISOString():"an unknown time";super(`another cloud sync is running (pid ${n}, since ${e}); skipped`),this.name="SyncLockedError",this.pid=n,this.since=r}}function $(t){return N(k(t),`${b(t).replace(/\.(?:db|sqlite3?)$/i,"")}.cloud-sync.lock`)}function m(t){try{const n=l(`/proc/${t}/stat`,"utf8"),r=n.slice(n.lastIndexOf(")")+2).split(" ")[19],e=l("/proc/sys/kernel/random/boot_id","utf8").trim();return r&&/^\d+$/.test(r)&&e?{start:r,boot:e}:null}catch{return null}}function p(t){let n;try{n=l(t,"utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}try{const r=JSON.parse(n),e=Number(r.pid),i=typeof r.proc_start=="string"&&typeof r.boot_id=="string"?{start:r.proc_start,boot:r.boot_id}:null;return{text:n,pid:Number.isSafeInteger(e)&&e>0?e:0,since:Number(r.started_at)||0,identity:i}}catch{return{text:n,pid:0,since:0,identity:null}}}function x(t){if(t<=0)return!1;try{return process.kill(t,0),!0}catch(n){return n.code==="EPERM"}}function S(t){if(!x(t.pid))return!1;if(t.identity===null)return!0;const n=m(t.pid);return n===null?!0:n.start===t.identity.start&&n.boot===t.identity.boot}const T=new Set(["EPERM","ENOTSUP","EOPNOTSUPP","ENOSYS"]);function A(t,n,r){try{_(n,t)}catch(e){const i=e.code??"";if(!T.has(i))throw e;d(t,r,{flag:"wx",mode:384})}}const I=3e4,P=2e3;function L(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function h(t,n,r){try{return A(t,n,r),!0}catch(e){if(e.code==="EEXIST")return!1;throw e}}function g(t){try{return d(t,`${process.pid}
2
+ `,{flag:"wx",mode:384}),!0}catch(n){if(n.code!=="EEXIST")throw n}try{const n=w(t);Date.now()-n.mtimeMs>I&&w(t).ino===n.ino&&s(t)}catch{}return!1}function F(t,n=Date.now()){const r=$(t),e=`${r}.takeover`,i=m(process.pid),c=`${JSON.stringify({pid:process.pid,started_at:n,...i?{proc_start:i.start,boot_id:i.boot}:{}})}
3
+ `,a=`${r}.${process.pid}.${O(6).toString("hex")}.tmp`,y=performance.now()+P;d(a,c,{mode:384});try{let o=null;for(;performance.now()<y;){if(h(r,a,c))return()=>E(r,c);if(o=p(r),o!==null){if(S(o))throw new f(o.pid,o.since);for(;!g(e);){if(performance.now()>=y)throw new f(o.pid,o.since);L(10)}try{const u=p(r);if(u!==null){if(S(u))throw new f(u.pid,u.since);s(r)}if(h(r,a,c))return()=>E(r,c)}finally{try{s(e)}catch{}}}}throw o=p(r),new f(o?.pid??0,o?.since??0)}finally{try{s(a)}catch{}}}function E(t,n){try{l(t,"utf8")===n&&s(t)}catch{}}export{D as EX_TEMPFAIL,f as SyncLockedError,F as acquireSyncLock,$ as syncLockPath};
@@ -1 +1 @@
1
- import{redactCredentials as i,redactCredentialTokens as _,redactJsonText as l}from"./security.js";function g(e,t){return e==="json"?l(t):e==="label"?_(t):i(t)}const p={agent_actions:{summary:"text"},agent_presence:{current_file:"text",current_symbol:"text",metadata:"json",agent_kind:"text",role:"text"},context:{value:"text"},data_lake:{value:"text",metadata:"json",category:"text",key:"text"},decision_edges:{rationale:"text"},design_references:{location:"text",title:"text",notes:"text",tags:"text"},design_tokens:{value:"text",notes:"text"},entities:{name:"text",metadata:"text",type:"label"},entity_aliases:{alias:"text"},events:{payload_json:"json",actor:"text",ref_table:"text"},external_call_log:{args_summary:"text",error_message:"text",server_name:"text",tool_name:"text"},failure_patterns:{target:"text",description:"text",why_failed:"text",resolution_note:"text",content_sig:"text"},global_context:{value:"text"},goal_iterations:{observe_summary:"text",orient_summary:"text",decided_action:"text",action_result:"text",notes:"text"},goals:{title:"text",description:"text",success_criteria:"text",last_outcome:"text",deadline:"text"},ground_truths:{category:"text",key:"text",value:"text",rationale:"text",source:"text"},indexing_queue:{error_message:"text"},llm_query_log:{query:"text",context_summary:"text",response:"text",error_message:"text"},memory_artifacts:{problem:"text",constraints:"text",validated_fix:"text",why_it_worked:"text",tags:"text"},project_continuity:{thread:"text"},projects:{repo:"text",last_commit:"text"},quest_claims:{role:"text"},quests:{title:"text",description:"text",tags:"text"},read_memos:{distilled:"text"},reasoning_scaffolds:{problem_type:"text",description:"text",when_to_use:"text",tags:"text",steps:"json",verification_steps:"json",do_not_apply_if:"json"},relationships:{metadata:"text",relationship_type:"text",source_memory:"text"},run_agents:{role:"text"},run_briefs:{body_json:"json"},sessions:{objectives:"text",completed:"text",issues:"text",commits:"text",files_changed:"text",notes:"text",summary:"text"},skills:{category:"text",description:"text",tags:"text",content:"text",author:"text",version:"text",governs:"json",composes:"json"},specs:{title:"text",summary:"text"},sync_conflicts:{remote_payload:"json",local_payload:"json",remote_origin:"text"},sync_log:{remote_origin:"text"},threads:{objective:"text",in_progress:"text",next_step:"text",last_decisions:"json",open_loops:"json",in_play:"json"},tool_call_log:{args_summary:"text",error_message:"text"},usage_events:{error_message:"text"},write_ledger:{reason:"text",source:"text"}},x={cross_project_visibility:"an enum: within, org or public",visibility:"an enum",created_by:"the writer label (local, auto-extract, an agent id)"},o="hash-chained: rewriting a stored row breaks verification",s="hash-chained: redacted at write, before the hash (audit.ts log), and never rewritten after, as rewriting a stored row breaks verification",n="a launch config read back to spawn the server; a token there is stored as given by design (wyrm vault exec keeps it out)",r="derived from target; the back-fill recomputes them from the redacted target the way the record path does",a="derived from source files, rebuilt by the indexer",y={"agent_actions.actor":"an actor label","agent_actions.action_kind":"an enum","agent_actions.result_status":"an enum","agent_presence.last_heartbeat":"a timestamp","audit_checkpoints.row_hash":"a hash of the audit chain","audit_checkpoints.signature":"the chain's signature","audit_log.event_kind":s,"audit_log.actor":s,"audit_log.payload_json":s,"audit_log.prev_hash":o,"audit_log.row_hash":o,"audit_log.signature":s,"context.key":"natural key (project_id, key)","decision_edges.from_kind":"an enum","decision_edges.to_kind":"an enum","decision_edges.relation":"an enum","design_references.kind":"an enum","design_tokens.category":"natural key (project_id, category, key)","design_tokens.key":"natural key (project_id, category, key)","design_tokens.source":"an origin label (user, derived, imported, observed)","erasure_log.mode":"an enum","erasure_log.reason":"a reason tag","erasure_log.category":"a category label","erasure_log.predicate_json":"a predicate over ids and keys","erasure_log.counts_json":"counts","erasure_log.actor":"an actor label","events.origin_device":"a device id, part of the natural key (origin_device, origin_seq)","events.kind":"an event kind","failure_anchors.rel_path":"a path a failure is anchored to","failure_anchors.sha":"a file hash","failure_pattern_history.event":"an enum","failure_pattern_history.detail":"the firewall's own sentence about its row","failure_patterns.signature":r,"failure_patterns.canonical_target":r,"failure_patterns.command_head":r,"failure_patterns.scope":"an enum","failure_patterns.severity":"an enum","failure_patterns.quarantine_scope":"an enum","failure_patterns.first_seen":"a timestamp","failure_patterns.last_seen":"a timestamp","global_context.key":"a setting name, the natural key","goal_iterations.outcome":"an enum","goal_iterations.model":"a model id","goals.status":"an enum","goals.priority":"an enum","indexing_queue.content_type":"an enum","indexing_queue.status":"an enum","llm_query_log.model":"a model id","mcp_client_configs.server_name":"a server name, the natural key","mcp_client_configs.command":n,"mcp_client_configs.args":n,"mcp_client_configs.env":n,"memory_artifacts.kind":"an enum","memory_artifacts.outcome":"an enum","memory_artifacts.source_trust":"an enum (the trust lane)","memory_artifacts.reviewed_by":"a reviewer id","metrics_snapshots.wyrm_version":"a version","metrics_snapshots.kind":"an enum","metrics_snapshots.metrics_json":"counters","project_continuity.updated_by":"the writer label","projects.name":"natural key (name)","projects.path":"natural key (path)","projects.stack":"a stack label Wyrm detects","projects.branch":"a git branch name","projects.sync_policy":"an enum","quests.priority":"an enum","quests.status":"an enum","read_memos.path":"a file path","read_memos.sha256":"a file hash","read_memos.tool":"a tool name","read_memos.first_seen":"a timestamp","read_memos.last_seen":"a timestamp","recall_policy.mode":"an enum","recall_policy.muted_ids":"memory ids","recall_policy.challenged_truth_ids":"truth ids","relationships.extraction_method":"an enum","reverse_bridge_tombstones.sig":"a signature","review_sample.lane":"an enum","review_sample.week":"a week label","review_sample.verdict":"an enum","review_sample.reviewed_by":"a reviewer id","routing_memory.task_type":"a task-type label","routing_memory.tool_names":"tool names","routing_memory.ts":"a timestamp","run_briefs.role":"a role label","runs.orchestrator":"an orchestrator label","runs.status":"an enum","served_counts.artifact_kind":"an enum","served_records.session_key":"an opaque per-process id","served_records.artifact_kind":"an enum","session_seen_artifacts.artifact_kind":"an enum","session_seen_artifacts.render_mode":"an enum","sessions.date":"a date","skills.name":"natural key (name)","skills.skill_path":"a path","skills.tier":"an enum","skills.last_used":"a timestamp","skills.content_sha256":"a hash of the stored body","specs.spec_dir":"natural key (project_id, spec_dir)","symbol_index.file_path":a,"symbol_index.symbol":a,"symbol_index.kind":a,"symbol_index.language":a,"symbol_index.signature":a,"sync_conflicts.local_kind":"a sync kind","sync_conflicts.resolution":"an enum","sync_conflicts.source":"an enum (cloud or federation)","sync_conflicts.winner":"an enum","sync_cursors.name":"a cursor name","sync_cursors.value_json":"Wyrm's own watermark","sync_cursors.imported_from":"the legacy cursor file path","sync_log.direction":"an enum","sync_log.kind":"a sync kind","sync_log.since_cursor":"a cursor","sync_log.new_cursor":"a cursor","sync_tombstones.kind":"a sync kind","threads.source_refs":"references to the rows the thread was built from","token_savings_log.tool_name":"a tool name","token_savings_log.category":"a category label","token_savings_log.confidence":"an enum","token_savings_log.timestamp":"a timestamp","tool_call_log.tool_name":"a tool name","usage_events.tool_name":"a tool name","usage_events.timestamp":"a timestamp","watch_dirs.path":"a directory path","watch_dirs.last_scan":"a timestamp","write_ledger.ts":"a timestamp","write_ledger.tool":"a tool name","write_ledger.outcome":"an enum","write_ledger.ref_table":"a table name","wyrm_meta.key":"a meta key","wyrm_meta.value":"Wyrm's own watermark or setting"},c={vectors:"embeddings; the rows built from text that changed are dropped and rebuilt",sqlite_sequence:"SQLite's AUTOINCREMENT counters",schema_versions:"the migration ledger Wyrm writes"},m=/^\s*CREATE\s+VIRTUAL\s+TABLE\b/i,d=/_(?:data|idx|content|docsize|config)$/;function h(e,t){return Object.prototype.hasOwnProperty.call(c,e)?!0:t===null?!1:m.test(t)?!0:d.test(e)&&t.trimStart().startsWith(`CREATE TABLE '${e}'(`)}const f=["design_tokens.key","global_context.key","skills.name","run_briefs.role","events.ref_id"],k=["agent_id","run_id","parent_run_id"];function b(e){return/^(?:id|.+_id|.+_at|.+_ms)$/.test(e)}export{p as FREE_TEXT_COLUMNS,f as GUARDED_KEY_COLUMNS,y as HELD_COLUMNS,x as HELD_IN_EVERY_TABLE,k as IDENTITY_COLUMN_NAMES,c as SKIPPED_TABLES,b as isHeldByName,h as isSkippedTable,g as redactForShape};
1
+ import{redactCredentials as i,redactCredentialTokens as _,redactJsonText as l}from"./security.js";function g(e,t){return e==="json"?l(t):e==="label"?_(t):i(t)}const p={agent_actions:{summary:"text"},agent_presence:{current_file:"text",current_symbol:"text",metadata:"json",agent_kind:"text",role:"text"},context:{value:"text"},data_lake:{value:"text",metadata:"json",category:"text",key:"text"},decision_edges:{rationale:"text"},design_references:{location:"text",title:"text",notes:"text",tags:"text"},design_tokens:{value:"text",notes:"text"},entities:{name:"text",metadata:"text",type:"label"},entity_aliases:{alias:"text"},events:{payload_json:"json",actor:"text",ref_table:"text"},external_call_log:{args_summary:"text",error_message:"text",server_name:"text",tool_name:"text"},failure_patterns:{target:"text",description:"text",why_failed:"text",resolution_note:"text",content_sig:"text"},global_context:{value:"text"},goal_iterations:{observe_summary:"text",orient_summary:"text",decided_action:"text",action_result:"text",notes:"text"},goals:{title:"text",description:"text",success_criteria:"text",last_outcome:"text",deadline:"text"},ground_truths:{category:"text",key:"text",value:"text",rationale:"text",source:"text"},indexing_queue:{error_message:"text"},llm_query_log:{query:"text",context_summary:"text",response:"text",error_message:"text"},memory_artifacts:{problem:"text",constraints:"text",validated_fix:"text",why_it_worked:"text",tags:"text"},project_continuity:{thread:"text"},projects:{repo:"text",last_commit:"text"},quest_claims:{role:"text"},quests:{title:"text",description:"text",tags:"text"},read_memos:{distilled:"text"},reasoning_scaffolds:{problem_type:"text",description:"text",when_to_use:"text",tags:"text",steps:"json",verification_steps:"json",do_not_apply_if:"json"},relationships:{metadata:"text",relationship_type:"text",source_memory:"text"},run_agents:{role:"text"},run_briefs:{body_json:"json"},sessions:{objectives:"text",completed:"text",issues:"text",commits:"text",files_changed:"text",notes:"text",summary:"text"},skills:{category:"text",description:"text",tags:"text",content:"text",author:"text",version:"text",governs:"json",composes:"json"},specs:{title:"text",summary:"text"},sync_conflicts:{remote_payload:"json",local_payload:"json",remote_origin:"text"},sync_log:{remote_origin:"text"},threads:{objective:"text",in_progress:"text",next_step:"text",last_decisions:"json",open_loops:"json",in_play:"json"},tool_call_log:{args_summary:"text",error_message:"text"},usage_events:{error_message:"text"},write_ledger:{reason:"text",source:"text"}},y={cross_project_visibility:"an enum: within, org or public",visibility:"an enum",created_by:"the writer label (local, auto-extract, an agent id)"},o="hash-chained: rewriting a stored row breaks verification",s="hash-chained: redacted at write, before the hash (audit.ts log), and never rewritten after, as rewriting a stored row breaks verification",n="a launch config read back to spawn the server; a token there is stored as given by design (wyrm vault exec keeps it out)",r="derived from target; the back-fill recomputes them from the redacted target the way the record path does",a="derived from source files, rebuilt by the indexer",x={"agent_actions.actor":"an actor label","agent_actions.action_kind":"an enum","agent_actions.result_status":"an enum","agent_presence.last_heartbeat":"a timestamp","audit_checkpoints.row_hash":"a hash of the audit chain","audit_checkpoints.signature":"the chain's signature","audit_log.event_kind":s,"audit_log.actor":s,"audit_log.payload_json":s,"audit_log.prev_hash":o,"audit_log.row_hash":o,"audit_log.signature":s,"cloud_push_ledger.kind":"a sync kind","cloud_push_ledger.hash":"a content hash of a row as the cloud last stored it","context.key":"natural key (project_id, key)","decision_edges.from_kind":"an enum","decision_edges.to_kind":"an enum","decision_edges.relation":"an enum","design_references.kind":"an enum","design_tokens.category":"natural key (project_id, category, key)","design_tokens.key":"natural key (project_id, category, key)","design_tokens.source":"an origin label (user, derived, imported, observed)","erasure_log.mode":"an enum","erasure_log.reason":"a reason tag","erasure_log.category":"a category label","erasure_log.predicate_json":"a predicate over ids and keys","erasure_log.counts_json":"counts","erasure_log.actor":"an actor label","events.origin_device":"a device id, part of the natural key (origin_device, origin_seq)","events.kind":"an event kind","failure_anchors.rel_path":"a path a failure is anchored to","failure_anchors.sha":"a file hash","failure_pattern_history.event":"an enum","failure_pattern_history.detail":"the firewall's own sentence about its row","failure_patterns.signature":r,"failure_patterns.canonical_target":r,"failure_patterns.command_head":r,"failure_patterns.scope":"an enum","failure_patterns.severity":"an enum","failure_patterns.quarantine_scope":"an enum","failure_patterns.first_seen":"a timestamp","failure_patterns.last_seen":"a timestamp","global_context.key":"a setting name, the natural key","goal_iterations.outcome":"an enum","goal_iterations.model":"a model id","goals.status":"an enum","goals.priority":"an enum","indexing_queue.content_type":"an enum","indexing_queue.status":"an enum","llm_query_log.model":"a model id","mcp_client_configs.server_name":"a server name, the natural key","mcp_client_configs.command":n,"mcp_client_configs.args":n,"mcp_client_configs.env":n,"memory_artifacts.kind":"an enum","memory_artifacts.outcome":"an enum","memory_artifacts.source_trust":"an enum (the trust lane)","memory_artifacts.reviewed_by":"a reviewer id","metrics_snapshots.wyrm_version":"a version","metrics_snapshots.kind":"an enum","metrics_snapshots.metrics_json":"counters","project_continuity.updated_by":"the writer label","projects.name":"natural key (name)","projects.path":"natural key (path)","projects.stack":"a stack label Wyrm detects","projects.branch":"a git branch name","projects.sync_policy":"an enum","quests.priority":"an enum","quests.status":"an enum","read_memos.path":"a file path","read_memos.sha256":"a file hash","read_memos.tool":"a tool name","read_memos.first_seen":"a timestamp","read_memos.last_seen":"a timestamp","recall_policy.mode":"an enum","recall_policy.muted_ids":"memory ids","recall_policy.challenged_truth_ids":"truth ids","relationships.extraction_method":"an enum","reverse_bridge_tombstones.sig":"a signature","review_sample.lane":"an enum","review_sample.week":"a week label","review_sample.verdict":"an enum","review_sample.reviewed_by":"a reviewer id","routing_memory.task_type":"a task-type label","routing_memory.tool_names":"tool names","routing_memory.ts":"a timestamp","run_briefs.role":"a role label","runs.orchestrator":"an orchestrator label","runs.status":"an enum","served_counts.artifact_kind":"an enum","served_records.session_key":"an opaque per-process id","served_records.artifact_kind":"an enum","session_seen_artifacts.artifact_kind":"an enum","session_seen_artifacts.render_mode":"an enum","sessions.date":"a date","skills.name":"natural key (name)","skills.skill_path":"a path","skills.tier":"an enum","skills.last_used":"a timestamp","skills.content_sha256":"a hash of the stored body","specs.spec_dir":"natural key (project_id, spec_dir)","symbol_index.file_path":a,"symbol_index.symbol":a,"symbol_index.kind":a,"symbol_index.language":a,"symbol_index.signature":a,"sync_conflicts.local_kind":"a sync kind","sync_conflicts.resolution":"an enum","sync_conflicts.source":"an enum (cloud or federation)","sync_conflicts.winner":"an enum","sync_cursors.name":"a cursor name","sync_cursors.value_json":"Wyrm's own watermark","sync_cursors.imported_from":"the legacy cursor file path","sync_log.direction":"an enum","sync_log.kind":"a sync kind","sync_log.since_cursor":"a cursor","sync_log.new_cursor":"a cursor","sync_tombstones.kind":"a sync kind","threads.source_refs":"references to the rows the thread was built from","token_savings_log.tool_name":"a tool name","token_savings_log.category":"a category label","token_savings_log.confidence":"an enum","token_savings_log.timestamp":"a timestamp","tool_call_log.tool_name":"a tool name","usage_events.tool_name":"a tool name","usage_events.timestamp":"a timestamp","watch_dirs.path":"a directory path","watch_dirs.last_scan":"a timestamp","write_ledger.ts":"a timestamp","write_ledger.tool":"a tool name","write_ledger.outcome":"an enum","write_ledger.ref_table":"a table name","wyrm_meta.key":"a meta key","wyrm_meta.value":"Wyrm's own watermark or setting"},c={vectors:"embeddings; the rows built from text that changed are dropped and rebuilt",sqlite_sequence:"SQLite's AUTOINCREMENT counters",schema_versions:"the migration ledger Wyrm writes"},m=/^\s*CREATE\s+VIRTUAL\s+TABLE\b/i,d=/_(?:data|idx|content|docsize|config)$/;function h(e,t){return Object.prototype.hasOwnProperty.call(c,e)?!0:t===null?!1:m.test(t)?!0:d.test(e)&&t.trimStart().startsWith(`CREATE TABLE '${e}'(`)}const f=["design_tokens.key","global_context.key","skills.name","run_briefs.role","events.ref_id"],k=["agent_id","run_id","parent_run_id"];function b(e){return/^(?:id|.+_id|.+_at|.+_ms)$/.test(e)}export{p as FREE_TEXT_COLUMNS,f as GUARDED_KEY_COLUMNS,x as HELD_COLUMNS,y as HELD_IN_EVERY_TABLE,k as IDENTITY_COLUMN_NAMES,c as SKIPPED_TABLES,b as isHeldByName,h as isSkippedTable,g as redactForShape};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contract": "wyrm-cloud-memory-v2",
3
- "version": "9.4.2",
3
+ "version": "9.4.3",
4
4
  "derivedFrom": "standard tier MINUS device-local/egress/subprocess (src/cloud-profile.ts)",
5
5
  "count": 20,
6
6
  "tools": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contract": "wyrm-cloud-memory-v1",
3
- "version": "9.4.2",
3
+ "version": "9.4.3",
4
4
  "tools": [
5
5
  {
6
6
  "name": "wyrm_recall",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contract": "wyrm-cloud-memory-v1",
3
- "version": "9.4.2",
3
+ "version": "9.4.3",
4
4
  "generatedBy": "scripts/gen-tool-manifest.mjs (from the dist/ registry modules — never hand-edited)",
5
5
  "tiers": {
6
6
  "core": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wyrm-mcp",
3
- "version": "9.4.2",
3
+ "version": "9.4.3",
4
4
  "mcpName": "lk.ghosts/wyrm",
5
5
  "description": "Local-first persistent memory for AI agents over MCP. 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",