@codemem/core 0.20.0-alpha.3 → 0.20.0-alpha.4

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/index.js CHANGED
@@ -1401,18 +1401,18 @@ var L = class {
1401
1401
  });
1402
1402
  }
1403
1403
  }, R = /* @__PURE__ */ de({
1404
- actors: () => un,
1404
+ actors: () => dn,
1405
1405
  artifacts: () => $t,
1406
1406
  memoryItems: () => B,
1407
1407
  opencodeSessions: () => tn,
1408
1408
  rawEventFlushBatches: () => nn,
1409
1409
  rawEventIngestSamples: () => ln,
1410
- rawEventIngestStats: () => q,
1410
+ rawEventIngestStats: () => un,
1411
1411
  rawEventSessions: () => H,
1412
1412
  rawEvents: () => V,
1413
1413
  replicationCursors: () => U,
1414
1414
  replicationOps: () => on,
1415
- schema: () => dn,
1415
+ schema: () => fn,
1416
1416
  sessionSummaries: () => an,
1417
1417
  sessions: () => z,
1418
1418
  syncAttempts: () => K,
@@ -1634,7 +1634,7 @@ var L = class {
1634
1634
  skipped_invalid: N("skipped_invalid").notNull().default(0),
1635
1635
  skipped_duplicate: N("skipped_duplicate").notNull().default(0),
1636
1636
  skipped_conflict: N("skipped_conflict").notNull().default(0)
1637
- }), q = P("raw_event_ingest_stats", {
1637
+ }), un = P("raw_event_ingest_stats", {
1638
1638
  id: N("id").primaryKey(),
1639
1639
  inserted_events: N("inserted_events").notNull().default(0),
1640
1640
  skipped_events: N("skipped_events").notNull().default(0),
@@ -1642,7 +1642,7 @@ var L = class {
1642
1642
  skipped_duplicate: N("skipped_duplicate").notNull().default(0),
1643
1643
  skipped_conflict: N("skipped_conflict").notNull().default(0),
1644
1644
  updated_at: F("updated_at").notNull()
1645
- }), un = P("actors", {
1645
+ }), dn = P("actors", {
1646
1646
  actor_id: F("actor_id").primaryKey(),
1647
1647
  display_name: F("display_name").notNull(),
1648
1648
  is_local: N("is_local").notNull().default(0),
@@ -1653,7 +1653,7 @@ var L = class {
1653
1653
  }, (e) => ({
1654
1654
  isLocalIdx: M("idx_actors_is_local").on(e.is_local),
1655
1655
  statusIdx: M("idx_actors_status").on(e.status)
1656
- })), dn = {
1656
+ })), fn = {
1657
1657
  sessions: z,
1658
1658
  artifacts: $t,
1659
1659
  memoryItems: B,
@@ -1672,12 +1672,12 @@ var L = class {
1672
1672
  syncAttempts: K,
1673
1673
  syncDaemonState: cn,
1674
1674
  rawEventIngestSamples: ln,
1675
- rawEventIngestStats: q,
1676
- actors: un
1675
+ rawEventIngestStats: un,
1676
+ actors: dn
1677
1677
  };
1678
1678
  //#endregion
1679
1679
  //#region src/observer-config.ts
1680
- function fn(e) {
1680
+ function pn(e) {
1681
1681
  let t = [], n = !1, r = !1;
1682
1682
  for (let i = 0; i < e.length; i++) {
1683
1683
  let a = e.charAt(i);
@@ -1718,7 +1718,7 @@ function fn(e) {
1718
1718
  }
1719
1719
  return t.join("");
1720
1720
  }
1721
- function pn(e) {
1721
+ function mn(e) {
1722
1722
  let t = [], n = !1, r = !1;
1723
1723
  for (let i = 0; i < e.length; i++) {
1724
1724
  let a = e.charAt(i);
@@ -1743,7 +1743,7 @@ function pn(e) {
1743
1743
  }
1744
1744
  return t.join("");
1745
1745
  }
1746
- function mn() {
1746
+ function hn() {
1747
1747
  let e = w(v(), ".config", "opencode"), t = [w(e, "opencode.json"), w(e, "opencode.jsonc")].find((e) => l(e));
1748
1748
  if (!t) return {};
1749
1749
  let n;
@@ -1756,16 +1756,16 @@ function mn() {
1756
1756
  return JSON.parse(n);
1757
1757
  } catch {}
1758
1758
  try {
1759
- let e = pn(fn(n));
1759
+ let e = mn(pn(n));
1760
1760
  return JSON.parse(e);
1761
1761
  } catch {
1762
1762
  return {};
1763
1763
  }
1764
1764
  }
1765
- function hn(e) {
1765
+ function gn(e) {
1766
1766
  return e.startsWith("~/") ? w(v(), e.slice(2)) : e;
1767
1767
  }
1768
- var gn = {
1768
+ var _n = {
1769
1769
  actor_id: "CODEMEM_ACTOR_ID",
1770
1770
  actor_display_name: "CODEMEM_ACTOR_DISPLAY_NAME",
1771
1771
  claude_command: "CODEMEM_CLAUDE_COMMAND",
@@ -1793,14 +1793,14 @@ var gn = {
1793
1793
  sync_coordinator_presence_ttl_s: "CODEMEM_SYNC_COORDINATOR_PRESENCE_TTL_S",
1794
1794
  raw_events_sweeper_interval_s: "CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_S"
1795
1795
  };
1796
- function _n() {
1796
+ function vn() {
1797
1797
  let e = process.env.CODEMEM_CONFIG?.trim();
1798
- if (e) return hn(e);
1798
+ if (e) return gn(e);
1799
1799
  let t = w(v(), ".config", "codemem");
1800
1800
  return [w(t, "config.json"), w(t, "config.jsonc")].find((e) => l(e)) ?? w(t, "config.json");
1801
1801
  }
1802
- function vn() {
1803
- let e = _n();
1802
+ function yn() {
1803
+ let e = vn();
1804
1804
  if (!l(e)) return {};
1805
1805
  let t;
1806
1806
  try {
@@ -1814,54 +1814,54 @@ function vn() {
1814
1814
  return typeof e == "object" && e && !Array.isArray(e) ? e : {};
1815
1815
  } catch {}
1816
1816
  try {
1817
- let e = pn(fn(t)), n = JSON.parse(e);
1817
+ let e = mn(pn(t)), n = JSON.parse(e);
1818
1818
  return typeof n == "object" && n && !Array.isArray(n) ? n : {};
1819
1819
  } catch {
1820
1820
  return {};
1821
1821
  }
1822
1822
  }
1823
- function yn(e, t) {
1824
- let n = t ? hn(t) : _n();
1823
+ function bn(e, t) {
1824
+ let n = t ? gn(t) : vn();
1825
1825
  return d(S(n), { recursive: !0 }), g(n, `${JSON.stringify(e, null, 2)}\n`, "utf8"), n;
1826
1826
  }
1827
- function bn() {
1827
+ function xn() {
1828
1828
  let e = {};
1829
- for (let [t, n] of Object.entries(gn)) {
1829
+ for (let [t, n] of Object.entries(_n)) {
1830
1830
  let r = process.env[n];
1831
1831
  r != null && r !== "" && (e[t] = n);
1832
1832
  }
1833
1833
  return e;
1834
1834
  }
1835
- function xn(e) {
1835
+ function Sn(e) {
1836
1836
  return typeof e == "object" && e && !Array.isArray(e) ? e : null;
1837
1837
  }
1838
- function Sn(e) {
1839
- let t = xn(mn().provider);
1840
- return t ? xn(t[e]) ?? {} : {};
1838
+ function Cn(e) {
1839
+ let t = Sn(hn().provider);
1840
+ return t ? Sn(t[e]) ?? {} : {};
1841
1841
  }
1842
- function Cn() {
1843
- let e = xn(mn().provider);
1842
+ function wn() {
1843
+ let e = Sn(hn().provider);
1844
1844
  return e ? new Set(Object.keys(e)) : /* @__PURE__ */ new Set();
1845
1845
  }
1846
- function wn(e, t) {
1846
+ function Tn(e, t) {
1847
1847
  if (!e || !e.includes("/")) return null;
1848
1848
  let n = e.split("/")[0] ?? "";
1849
1849
  return n && t.has(n) ? n : null;
1850
1850
  }
1851
- function Tn(e) {
1852
- return Dn(En(e));
1853
- }
1854
1851
  function En(e) {
1852
+ return On(Dn(e));
1853
+ }
1854
+ function Dn(e) {
1855
1855
  return e.replace(/\$\{([^}]+)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (e, t, n) => {
1856
1856
  let r = t ?? n;
1857
1857
  return process.env[r] ?? e;
1858
1858
  });
1859
1859
  }
1860
- function Dn(e) {
1860
+ function On(e) {
1861
1861
  return e.includes("{file:") ? e.replace(/\{file:([^}]+)\}/g, (e, t) => {
1862
1862
  let n = t.trim();
1863
1863
  if (!n) return e;
1864
- let r = En(n).replace(/^~/, v());
1864
+ let r = Dn(n).replace(/^~/, v());
1865
1865
  try {
1866
1866
  return f(r, "utf-8").trim();
1867
1867
  } catch {
@@ -1869,23 +1869,23 @@ function Dn(e) {
1869
1869
  }
1870
1870
  }) : e;
1871
1871
  }
1872
- function On(e) {
1873
- return xn(e.options) ?? {};
1874
- }
1875
1872
  function kn(e) {
1876
- let t = On(e), n = t.baseURL || t.baseUrl || t.base_url || e.base_url;
1877
- return typeof n == "string" && n ? n : null;
1873
+ return Sn(e.options) ?? {};
1878
1874
  }
1879
1875
  function An(e) {
1880
- let t = xn(On(e).headers);
1876
+ let t = kn(e), n = t.baseURL || t.baseUrl || t.base_url || e.base_url;
1877
+ return typeof n == "string" && n ? n : null;
1878
+ }
1879
+ function jn(e) {
1880
+ let t = Sn(kn(e).headers);
1881
1881
  if (!t) return {};
1882
1882
  let n = {};
1883
- for (let [e, r] of Object.entries(t)) typeof e != "string" || typeof r != "string" || (n[e] = Tn(r));
1883
+ for (let [e, r] of Object.entries(t)) typeof e != "string" || typeof r != "string" || (n[e] = En(r));
1884
1884
  return n;
1885
1885
  }
1886
- function jn(e) {
1887
- let t = On(e), n = t.apiKey || e.apiKey;
1888
- if (typeof n == "string" && n) return Tn(n);
1886
+ function Mn(e) {
1887
+ let t = kn(e), n = t.apiKey || e.apiKey;
1888
+ if (typeof n == "string" && n) return En(n);
1889
1889
  let r = t.apiKeyEnv ?? t.api_key_env;
1890
1890
  if (typeof r == "string" && r) {
1891
1891
  let e = process.env[r];
@@ -1893,22 +1893,22 @@ function jn(e) {
1893
1893
  }
1894
1894
  return null;
1895
1895
  }
1896
- function Mn(e) {
1897
- let t = Sn(e), n = On(t), r = n.defaultModel ?? n.default_model ?? t.defaultModel ?? t.default_model;
1896
+ function Nn(e) {
1897
+ let t = Cn(e), n = kn(t), r = n.defaultModel ?? n.default_model ?? t.defaultModel ?? t.default_model;
1898
1898
  if (typeof r == "string" && r) return r.startsWith(`${e}/`) ? r : `${e}/${r}`;
1899
- let i = xn(t.models);
1899
+ let i = Sn(t.models);
1900
1900
  if (i) {
1901
1901
  let t = Object.keys(i)[0];
1902
1902
  if (typeof t == "string" && t) return `${e}/${t}`;
1903
1903
  }
1904
1904
  return null;
1905
1905
  }
1906
- function Nn(e, t) {
1907
- let n = Sn(e), r = kn(n), i = An(n), a = t;
1908
- a ||= Mn(e) ?? "";
1909
- let o = `${e}/`, s = a.startsWith(o) ? a.slice(o.length) : a, c = xn(n.models), l = s;
1906
+ function Pn(e, t) {
1907
+ let n = Cn(e), r = An(n), i = jn(n), a = t;
1908
+ a ||= Nn(e) ?? "";
1909
+ let o = `${e}/`, s = a.startsWith(o) ? a.slice(o.length) : a, c = Sn(n.models), l = s;
1910
1910
  if (c) {
1911
- let e = xn(c[s]);
1911
+ let e = Sn(c[s]);
1912
1912
  e && typeof e.id == "string" && (l = e.id);
1913
1913
  }
1914
1914
  return (typeof l != "string" || !l) && (l = null), [
@@ -1919,23 +1919,23 @@ function Nn(e, t) {
1919
1919
  }
1920
1920
  //#endregion
1921
1921
  //#region src/db.ts
1922
- var Pn = 6, Fn = 6, In = [
1922
+ var Fn = 6, In = 6, Ln = [
1923
1923
  "memory_items",
1924
1924
  "sessions",
1925
1925
  "artifacts",
1926
1926
  "raw_events",
1927
1927
  "raw_event_sessions",
1928
1928
  "usage_events"
1929
- ], Ln = ".codemem-ts-accessed", Rn = w(v(), ".codemem", "mem.sqlite");
1930
- function zn(e) {
1931
- if (e) return hn(e);
1929
+ ], Rn = ".codemem-ts-accessed", zn = w(v(), ".codemem", "mem.sqlite");
1930
+ function Bn(e) {
1931
+ if (e) return gn(e);
1932
1932
  let t = process.env.CODEMEM_DB;
1933
- return t ? hn(t) : Rn;
1933
+ return t ? gn(t) : zn;
1934
1934
  }
1935
- var Bn = [w(v(), ".codemem.sqlite"), w(v(), ".opencode-mem.sqlite")], Vn = ["-wal", "-shm"];
1936
- function Hn(e, t) {
1935
+ var Vn = [w(v(), ".codemem.sqlite"), w(v(), ".opencode-mem.sqlite")], Hn = ["-wal", "-shm"];
1936
+ function Un(e, t) {
1937
1937
  d(S(t), { recursive: !0 });
1938
- let n = [[e, t], ...Vn.map((n) => [e + n, t + n])];
1938
+ let n = [[e, t], ...Hn.map((n) => [e + n, t + n])];
1939
1939
  for (let [e, t] of n) if (l(e)) try {
1940
1940
  p(e, t);
1941
1941
  } catch {
@@ -1950,34 +1950,34 @@ function Hn(e, t) {
1950
1950
  }
1951
1951
  }
1952
1952
  }
1953
- function Un(e) {
1954
- if (e === Rn && !l(e)) {
1955
- for (let t of Bn) if (l(t)) {
1956
- Hn(t, e);
1953
+ function Wn(e) {
1954
+ if (e === zn && !l(e)) {
1955
+ for (let t of Vn) if (l(t)) {
1956
+ Un(t, e);
1957
1957
  return;
1958
1958
  }
1959
1959
  }
1960
1960
  }
1961
- function Wn(e = Rn) {
1962
- Un(e), d(S(e), { recursive: !0 });
1961
+ function Gn(e = zn) {
1962
+ Wn(e), d(S(e), { recursive: !0 });
1963
1963
  let t = new ee(e);
1964
1964
  t.pragma("foreign_keys = ON"), t.pragma("busy_timeout = 5000");
1965
1965
  let n = t.pragma("journal_mode = WAL", { simple: !0 });
1966
1966
  return n.toLowerCase() !== "wal" && console.warn(`Failed to enable WAL mode (got ${n}). Concurrent access may not work correctly.`), t.pragma("synchronous = NORMAL"), t;
1967
1967
  }
1968
- function Gn(e) {
1969
- if (!Kn() && (le.load(e), !e.prepare("SELECT vec_version() AS v").get()?.v)) throw Error("sqlite-vec loaded but version check failed");
1968
+ function Kn(e) {
1969
+ if (!qn() && (le.load(e), !e.prepare("SELECT vec_version() AS v").get()?.v)) throw Error("sqlite-vec loaded but version check failed");
1970
1970
  }
1971
- function Kn() {
1971
+ function qn() {
1972
1972
  let e = process.env.CODEMEM_EMBEDDING_DISABLED?.toLowerCase();
1973
1973
  return e === "1" || e === "true" || e === "yes";
1974
1974
  }
1975
- function qn(e) {
1975
+ function Jn(e) {
1976
1976
  let t = e.pragma("user_version", { simple: !0 });
1977
1977
  return typeof t == "number" ? t : 0;
1978
1978
  }
1979
- function Jn(e) {
1980
- let t = w(S(e), Ln);
1979
+ function Yn(e) {
1980
+ let t = w(S(e), Rn);
1981
1981
  if (l(t)) return;
1982
1982
  let n = e;
1983
1983
  if (!l(e)) {
@@ -1997,19 +1997,19 @@ function Jn(e) {
1997
1997
  d(S(t), { recursive: !0 }), g(t, (/* @__PURE__ */ new Date()).toISOString(), "utf-8");
1998
1998
  } catch {}
1999
1999
  }
2000
- function Yn(e) {
2001
- let t = qn(e);
2000
+ function Xn(e) {
2001
+ let t = Jn(e);
2002
2002
  if (t === 0) throw Error("Database schema is not initialized. Run the Python runtime to initialize: uv run codemem stats");
2003
2003
  if (t < 6) throw Error(`Database schema version ${t} is older than minimum compatible (6). Run the Python runtime to complete migrations: uv run codemem stats`);
2004
2004
  t > 6 && console.warn(`Database schema version ${t} is newer than this TS runtime (6). Running in compatibility mode — additive schema changes are tolerated.`);
2005
- let n = In.filter((t) => !Xn(e, t));
2005
+ let n = Ln.filter((t) => !Zn(e, t));
2006
2006
  if (n.length > 0) throw Error(`Required tables missing: ${n.join(", ")}. The database may be corrupt or from an incompatible version.`);
2007
- if (!Xn(e, "memory_fts")) throw Error("FTS5 index (memory_fts) is missing. Run the Python runtime to rebuild: uv run codemem stats");
2007
+ if (!Zn(e, "memory_fts")) throw Error("FTS5 index (memory_fts) is missing. Run the Python runtime to rebuild: uv run codemem stats");
2008
2008
  }
2009
- function Xn(e, t) {
2009
+ function Zn(e, t) {
2010
2010
  return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t) !== void 0;
2011
2011
  }
2012
- function J(e) {
2012
+ function q(e) {
2013
2013
  if (!e) return {};
2014
2014
  try {
2015
2015
  let t = JSON.parse(e);
@@ -2018,41 +2018,47 @@ function J(e) {
2018
2018
  return console.warn(`[codemem] fromJson: invalid JSON (${e.slice(0, 80)}...)`), {};
2019
2019
  }
2020
2020
  }
2021
- function Y(e) {
2021
+ function Qn(e) {
2022
+ if (!e) return {};
2023
+ let t = JSON.parse(e);
2024
+ if (typeof t != "object" || !t || Array.isArray(t)) throw Error(`fromJsonStrict: expected object, got ${Array.isArray(t) ? "array" : typeof t}`);
2025
+ return t;
2026
+ }
2027
+ function J(e) {
2022
2028
  return e == null ? "{}" : JSON.stringify(e);
2023
2029
  }
2024
- function X(e) {
2030
+ function Y(e) {
2025
2031
  return e == null || typeof e == "object" && !Array.isArray(e) && Object.keys(e).length === 0 ? null : JSON.stringify(e);
2026
2032
  }
2027
2033
  //#endregion
2028
2034
  //#region src/sync-identity.ts
2029
- var Zn = w(v(), ".config", "codemem", "keys"), Qn = "device.key", $n = "device.key.pub", er = "codemem-sync";
2030
- function tr(t) {
2035
+ var $n = w(v(), ".config", "codemem", "keys"), er = "device.key", tr = "device.key.pub", nr = "codemem-sync";
2036
+ function rr(t) {
2031
2037
  return e("sha256").update(t, "utf-8").digest("hex");
2032
2038
  }
2033
- function nr() {
2039
+ function ir() {
2034
2040
  return process.env.CODEMEM_SYNC_KEY_STORE?.toLowerCase() === "keychain" ? "keychain" : "file";
2035
2041
  }
2036
- function rr(e) {
2042
+ function ar(e) {
2037
2043
  try {
2038
2044
  return ce("which", [e], { stdio: "pipe" }), !0;
2039
2045
  } catch {
2040
2046
  return !1;
2041
2047
  }
2042
2048
  }
2043
- function ir() {
2044
- process.platform === "darwin" && nr() === "keychain" && process.env.CODEMEM_SYNC_KEYCHAIN_WARN !== "0" && console.warn("[codemem] keychain storage on macOS uses the `security` CLI and may expose the key in process arguments.");
2049
+ function or() {
2050
+ process.platform === "darwin" && ir() === "keychain" && process.env.CODEMEM_SYNC_KEYCHAIN_WARN !== "0" && console.warn("[codemem] keychain storage on macOS uses the `security` CLI and may expose the key in process arguments.");
2045
2051
  }
2046
- function ar(e, t) {
2052
+ function sr(e, t) {
2047
2053
  if (process.platform === "linux") {
2048
- if (!rr("secret-tool")) return !1;
2054
+ if (!ar("secret-tool")) return !1;
2049
2055
  try {
2050
2056
  return ce("secret-tool", [
2051
2057
  "store",
2052
2058
  "--label",
2053
2059
  "codemem sync key",
2054
2060
  "service",
2055
- er,
2061
+ nr,
2056
2062
  "account",
2057
2063
  t
2058
2064
  ], {
@@ -2068,14 +2074,14 @@ function ar(e, t) {
2068
2074
  }
2069
2075
  }
2070
2076
  if (process.platform === "darwin") {
2071
- if (!rr("security")) return !1;
2077
+ if (!ar("security")) return !1;
2072
2078
  try {
2073
2079
  return ce("security", [
2074
2080
  "add-generic-password",
2075
2081
  "-a",
2076
2082
  t,
2077
2083
  "-s",
2078
- er,
2084
+ nr,
2079
2085
  "-w",
2080
2086
  e.toString("utf-8"),
2081
2087
  "-U"
@@ -2090,14 +2096,14 @@ function ar(e, t) {
2090
2096
  }
2091
2097
  return !1;
2092
2098
  }
2093
- function or(e) {
2099
+ function cr(e) {
2094
2100
  if (process.platform === "linux") {
2095
- if (!rr("secret-tool")) return null;
2101
+ if (!ar("secret-tool")) return null;
2096
2102
  try {
2097
2103
  let t = ce("secret-tool", [
2098
2104
  "lookup",
2099
2105
  "service",
2100
- er,
2106
+ nr,
2101
2107
  "account",
2102
2108
  e
2103
2109
  ], { stdio: [
@@ -2111,14 +2117,14 @@ function or(e) {
2111
2117
  }
2112
2118
  }
2113
2119
  if (process.platform === "darwin") {
2114
- if (!rr("security")) return null;
2120
+ if (!ar("security")) return null;
2115
2121
  try {
2116
2122
  let t = ce("security", [
2117
2123
  "find-generic-password",
2118
2124
  "-a",
2119
2125
  e,
2120
2126
  "-s",
2121
- er,
2127
+ nr,
2122
2128
  "-w"
2123
2129
  ], { stdio: [
2124
2130
  "pipe",
@@ -2132,51 +2138,51 @@ function or(e) {
2132
2138
  }
2133
2139
  return null;
2134
2140
  }
2135
- function sr(e) {
2136
- let t = e ?? Zn;
2137
- return [w(t, Qn), w(t, $n)];
2141
+ function lr(e) {
2142
+ let t = e ?? $n;
2143
+ return [w(t, er), w(t, tr)];
2138
2144
  }
2139
- function cr(e) {
2140
- let [, t] = sr(e);
2145
+ function ur(e) {
2146
+ let [, t] = lr(e);
2141
2147
  return l(t) && f(t, "utf-8").trim() || null;
2142
2148
  }
2143
- function lr(e, t) {
2144
- if (nr() === "keychain") {
2145
- let e = ur(t);
2149
+ function dr(e, t) {
2150
+ if (ir() === "keychain") {
2151
+ let e = fr(t);
2146
2152
  if (e) {
2147
- let t = or(e);
2153
+ let t = cr(e);
2148
2154
  if (t) return t;
2149
2155
  }
2150
2156
  }
2151
- let [n] = sr(e);
2157
+ let [n] = lr(e);
2152
2158
  return l(n) ? f(n) : null;
2153
2159
  }
2154
- function ur(e) {
2155
- let t = zn(e);
2160
+ function fr(e) {
2161
+ let t = Bn(e);
2156
2162
  if (!l(t)) return null;
2157
- let n = Wn(t);
2163
+ let n = Gn(t);
2158
2164
  try {
2159
2165
  return j(n, { schema: R }).select({ device_id: G.device_id }).from(G).limit(1).get()?.device_id ?? null;
2160
2166
  } finally {
2161
2167
  n.close();
2162
2168
  }
2163
2169
  }
2164
- function dr(e) {
2170
+ function pr(e) {
2165
2171
  let t = e.trim();
2166
2172
  return t.startsWith("ssh-ed25519 ") || t.startsWith("ssh-rsa ") || t.startsWith("ecdsa-");
2167
2173
  }
2168
- function fr(e, t) {
2174
+ function mr(e, t) {
2169
2175
  l(e) && p(e, e.replace(/([^/]+)$/, `$1.invalid-${t}`));
2170
2176
  }
2171
- function pr(e, t) {
2177
+ function hr(e, t) {
2172
2178
  if (d(S(e), { recursive: !0 }), l(e) && l(t)) return;
2173
2179
  if (l(e) && !l(t)) {
2174
2180
  try {
2175
- let r = mr(n(hr(e)).export({
2181
+ let r = gr(n(_r(e)).export({
2176
2182
  type: "spki",
2177
2183
  format: "der"
2178
2184
  }));
2179
- if (r && dr(r)) {
2185
+ if (r && pr(r)) {
2180
2186
  g(t, `${r}\n`, { mode: 420 });
2181
2187
  return;
2182
2188
  }
@@ -2188,19 +2194,19 @@ function pr(e, t) {
2188
2194
  type: "pkcs8",
2189
2195
  format: "pem"
2190
2196
  }), { mode: 384 });
2191
- let o = mr(i.export({
2197
+ let o = gr(i.export({
2192
2198
  type: "spki",
2193
2199
  format: "der"
2194
2200
  }));
2195
2201
  if (!o) throw Error("failed to convert public key to SSH format");
2196
2202
  g(t, `${o}\n`, { mode: 420 });
2197
2203
  }
2198
- function mr(e) {
2204
+ function gr(e) {
2199
2205
  if (e.length < 32) return null;
2200
2206
  let t = e.subarray(e.length - 32), n = Buffer.from("ssh-ed25519"), r = Buffer.alloc(4 + n.length + 4 + t.length), i = 0;
2201
2207
  return r.writeUInt32BE(n.length, i), i += 4, n.copy(r, i), i += n.length, r.writeUInt32BE(t.length, i), i += 4, t.copy(r, i), `ssh-ed25519 ${r.toString("base64")}`;
2202
2208
  }
2203
- function hr(e) {
2209
+ function _r(e) {
2204
2210
  let n = f(e);
2205
2211
  try {
2206
2212
  return t(n);
@@ -2212,43 +2218,43 @@ function hr(e) {
2212
2218
  });
2213
2219
  }
2214
2220
  }
2215
- function gr(e, t) {
2221
+ function vr(e, t) {
2216
2222
  if (!l(e) || !l(t)) return !1;
2217
2223
  let r = f(t, "utf-8").trim();
2218
- if (!r || !dr(r)) return !1;
2224
+ if (!r || !pr(r)) return !1;
2219
2225
  try {
2220
- let i = mr(n(hr(e)).export({
2226
+ let i = gr(n(_r(e)).export({
2221
2227
  type: "spki",
2222
2228
  format: "der"
2223
2229
  }));
2224
- return !i || !dr(i) ? !1 : (i !== r && g(t, `${i}\n`, "utf-8"), !0);
2230
+ return !i || !pr(i) ? !1 : (i !== r && g(t, `${i}\n`, "utf-8"), !0);
2225
2231
  } catch {
2226
2232
  return !1;
2227
2233
  }
2228
2234
  }
2229
- function _r(e, t) {
2230
- let [n, r] = sr(t?.keysDir ?? Zn);
2231
- ir();
2235
+ function yr(e, t) {
2236
+ let [n, r] = lr(t?.keysDir ?? $n);
2237
+ or();
2232
2238
  let i = j(e, { schema: R }), o = i.select({
2233
2239
  device_id: G.device_id,
2234
2240
  public_key: G.public_key,
2235
2241
  fingerprint: G.fingerprint
2236
2242
  }).from(G).limit(1).get(), s = o?.device_id ?? "", c = o?.public_key ?? "", u = o?.fingerprint ?? "", d = l(n) && l(r);
2237
- if (d && !gr(n, r)) {
2243
+ if (d && !vr(n, r)) {
2238
2244
  let e = (/* @__PURE__ */ new Date()).toISOString().replace(/[-:T.Z]/g, "").slice(0, 20);
2239
- fr(n, e), fr(r, e), d = !1;
2245
+ mr(n, e), mr(r, e), d = !1;
2240
2246
  }
2241
- d || pr(n, r);
2247
+ d || hr(n, r);
2242
2248
  let p = f(r, "utf-8").trim();
2243
2249
  if (!p) throw Error("public key missing");
2244
- let m = tr(p), h = (/* @__PURE__ */ new Date()).toISOString();
2250
+ let m = rr(p), h = (/* @__PURE__ */ new Date()).toISOString();
2245
2251
  if (s) {
2246
2252
  if ((c !== p || u !== m) && i.update(G).set({
2247
2253
  public_key: p,
2248
2254
  fingerprint: m
2249
- }).where(O(G.device_id, s)).run(), nr() === "keychain") {
2250
- let e = l(n) ? f(n) : or(s);
2251
- e && ar(e, s);
2255
+ }).where(O(G.device_id, s)).run(), ir() === "keychain") {
2256
+ let e = l(n) ? f(n) : cr(s);
2257
+ e && sr(e, s);
2252
2258
  }
2253
2259
  return [s, m];
2254
2260
  }
@@ -2258,16 +2264,16 @@ function _r(e, t) {
2258
2264
  public_key: p,
2259
2265
  fingerprint: m,
2260
2266
  created_at: h
2261
- }).run(), nr() === "keychain") {
2267
+ }).run(), ir() === "keychain") {
2262
2268
  let e = l(n) ? f(n) : null;
2263
- e && ar(e, g);
2269
+ e && sr(e, g);
2264
2270
  }
2265
2271
  return [g, m];
2266
2272
  }
2267
2273
  //#endregion
2268
2274
  //#region src/sync-auth.ts
2269
- var vr = "v2", yr = 300;
2270
- function br(t, n, r, i, a) {
2275
+ var br = "v2", xr = 300;
2276
+ function Sr(t, n, r, i, a) {
2271
2277
  let o = e("sha256").update(a).digest("hex"), s = [
2272
2278
  t.toUpperCase(),
2273
2279
  n,
@@ -2277,10 +2283,10 @@ function br(t, n, r, i, a) {
2277
2283
  ].join("\n");
2278
2284
  return Buffer.from(s, "utf-8");
2279
2285
  }
2280
- function xr(e) {
2286
+ function Cr(e) {
2281
2287
  let n = e.timestamp ?? String(Math.floor(Date.now() / 1e3)), r = e.nonce ?? i(16).toString("hex"), a = new URL(e.url), s = a.pathname || "/";
2282
2288
  a.search && (s = `${s}${a.search}`);
2283
- let c = br(e.method, s, n, r, e.bodyBytes), l = lr(e.keysDir);
2289
+ let c = Sr(e.method, s, n, r, e.bodyBytes), l = dr(e.keysDir);
2284
2290
  if (!l) throw Error("private key missing");
2285
2291
  let u;
2286
2292
  try {
@@ -2299,7 +2305,7 @@ function xr(e) {
2299
2305
  "X-Opencode-Signature": `v2:${d}`
2300
2306
  };
2301
2307
  }
2302
- function Sr(e) {
2308
+ function wr(e) {
2303
2309
  let t = e.timeWindowS ?? 300;
2304
2310
  if (!/^\d+$/.test(e.timestamp)) return !1;
2305
2311
  let n = Number.parseInt(e.timestamp, 10);
@@ -2318,14 +2324,14 @@ function Sr(e) {
2318
2324
  } catch {
2319
2325
  return !1;
2320
2326
  }
2321
- let u = br(e.method, e.pathWithQuery, e.timestamp, e.nonce, e.bodyBytes);
2327
+ let u = Sr(e.method, e.pathWithQuery, e.timestamp, e.nonce, e.bodyBytes);
2322
2328
  try {
2323
- return s(null, u, Cr(e.publicKey), l);
2329
+ return s(null, u, Tr(e.publicKey), l);
2324
2330
  } catch {
2325
2331
  return !1;
2326
2332
  }
2327
2333
  }
2328
- function Cr(e) {
2334
+ function Tr(e) {
2329
2335
  let t = e.trim().split(/\s+/);
2330
2336
  if (t.length < 2 || t[0] !== "ssh-ed25519") throw Error("not an ssh-ed25519 key");
2331
2337
  let r = Buffer.from(t[1], "base64");
@@ -2343,10 +2349,10 @@ function Cr(e) {
2343
2349
  type: "spki"
2344
2350
  });
2345
2351
  }
2346
- function wr(e) {
2352
+ function Er(e) {
2347
2353
  return {
2348
2354
  "X-Opencode-Device": e.deviceId,
2349
- ...xr({
2355
+ ...Cr({
2350
2356
  method: e.method,
2351
2357
  url: e.url,
2352
2358
  bodyBytes: e.bodyBytes,
@@ -2356,7 +2362,7 @@ function wr(e) {
2356
2362
  })
2357
2363
  };
2358
2364
  }
2359
- function Tr(e, t, n, r) {
2365
+ function Dr(e, t, n, r) {
2360
2366
  let i = j(e, { schema: R });
2361
2367
  try {
2362
2368
  return i.insert(sn).values({
@@ -2369,17 +2375,17 @@ function Tr(e, t, n, r) {
2369
2375
  throw e;
2370
2376
  }
2371
2377
  }
2372
- function Er(e, t) {
2378
+ function Or(e, t) {
2373
2379
  j(e, { schema: R }).delete(sn).where(re(sn.created_at, t)).run();
2374
2380
  }
2375
2381
  //#endregion
2376
2382
  //#region src/coordinator-api.ts
2377
- var Dr = 64 * 1024, Or = "X-Codemem-Coordinator-Admin";
2378
- function kr() {
2383
+ var kr = 64 * 1024, Ar = "X-Codemem-Coordinator-Admin";
2384
+ function jr() {
2379
2385
  return (process.env.CODEMEM_SYNC_COORDINATOR_ADMIN_SECRET ?? "").trim() || null;
2380
2386
  }
2381
- function Ar(e) {
2382
- let t = kr();
2387
+ function Mr(e) {
2388
+ let t = jr();
2383
2389
  if (!t) return {
2384
2390
  ok: !1,
2385
2391
  error: "admin_not_configured"
@@ -2396,21 +2402,21 @@ function Ar(e) {
2396
2402
  error: "missing_admin_header"
2397
2403
  };
2398
2404
  }
2399
- function jr(e) {
2405
+ function Nr(e) {
2400
2406
  let t = new URL(e);
2401
2407
  return t.search ? `${t.pathname}${t.search}` : t.pathname;
2402
2408
  }
2403
- function Mr(e, t, n, r) {
2409
+ function Pr(e, t, n, r) {
2404
2410
  try {
2405
2411
  return e.db.prepare("INSERT INTO request_nonces(device_id, nonce, created_at) VALUES (?, ?, ?)").run(t, n, r), !0;
2406
2412
  } catch {
2407
2413
  return !1;
2408
2414
  }
2409
2415
  }
2410
- function Nr(e, t) {
2416
+ function Fr(e, t) {
2411
2417
  e.db.prepare("DELETE FROM request_nonces WHERE created_at < ?").run(t);
2412
2418
  }
2413
- function Pr(e, t) {
2419
+ function Ir(e, t) {
2414
2420
  let { deviceId: n, signature: r, timestamp: i, nonce: a } = t;
2415
2421
  if (!n || !r || !i || !a) return {
2416
2422
  ok: !1,
@@ -2425,9 +2431,9 @@ function Pr(e, t) {
2425
2431
  };
2426
2432
  let s;
2427
2433
  try {
2428
- s = Sr({
2434
+ s = wr({
2429
2435
  method: t.method,
2430
- pathWithQuery: jr(t.url),
2436
+ pathWithQuery: Nr(t.url),
2431
2437
  bodyBytes: t.body,
2432
2438
  timestamp: i,
2433
2439
  nonce: a,
@@ -2442,7 +2448,7 @@ function Pr(e, t) {
2442
2448
  enrollment: null
2443
2449
  };
2444
2450
  }
2445
- return s ? Mr(e, n, a, (/* @__PURE__ */ new Date()).toISOString()) ? (Nr(e, (/* @__PURE__ */ new Date(Date.now() - 300 * 2 * 1e3)).toISOString()), {
2451
+ return s ? Pr(e, n, a, (/* @__PURE__ */ new Date()).toISOString()) ? (Fr(e, (/* @__PURE__ */ new Date(Date.now() - 300 * 2 * 1e3)).toISOString()), {
2446
2452
  ok: !0,
2447
2453
  error: "ok",
2448
2454
  enrollment: o
@@ -2456,11 +2462,11 @@ function Pr(e, t) {
2456
2462
  enrollment: null
2457
2463
  };
2458
2464
  }
2459
- function Fr(e) {
2465
+ function Lr(e) {
2460
2466
  let t = e?.dbPath, n = new Bt();
2461
2467
  return n.post("/v1/presence", async (e) => {
2462
2468
  let n = Buffer.from(await e.req.arrayBuffer());
2463
- if (n.length > Dr) return e.json({ error: "body_too_large" }, 413);
2469
+ if (n.length > kr) return e.json({ error: "body_too_large" }, 413);
2464
2470
  let r;
2465
2471
  try {
2466
2472
  if (r = JSON.parse(n.toString("utf-8")), typeof r != "object" || !r || Array.isArray(r)) return e.json({ error: "invalid_json" }, 400);
@@ -2471,7 +2477,7 @@ function Fr(e) {
2471
2477
  if (!i) return e.json({ error: "group_id_required" }, 400);
2472
2478
  let a = new L(t);
2473
2479
  try {
2474
- let t = Pr(a, {
2480
+ let t = Ir(a, {
2475
2481
  method: e.req.method,
2476
2482
  url: e.req.url,
2477
2483
  groupId: i,
@@ -2510,7 +2516,7 @@ function Fr(e) {
2510
2516
  if (!n) return e.json({ error: "group_id_required" }, 400);
2511
2517
  let r = new L(t);
2512
2518
  try {
2513
- let t = Pr(r, {
2519
+ let t = Ir(r, {
2514
2520
  method: e.req.method,
2515
2521
  url: e.req.url,
2516
2522
  groupId: n,
@@ -2527,10 +2533,10 @@ function Fr(e) {
2527
2533
  r.close();
2528
2534
  }
2529
2535
  }), n.post("/v1/admin/devices", async (e) => {
2530
- let n = Ar(e.req.header(Or));
2536
+ let n = Mr(e.req.header(Ar));
2531
2537
  if (!n.ok) return e.json({ error: n.error }, 401);
2532
2538
  let r = Buffer.from(await e.req.arrayBuffer());
2533
- if (r.length > Dr) return e.json({ error: "body_too_large" }, 413);
2539
+ if (r.length > kr) return e.json({ error: "body_too_large" }, 413);
2534
2540
  let i;
2535
2541
  try {
2536
2542
  if (i = JSON.parse(r.toString("utf-8")), typeof i != "object" || !i || Array.isArray(i)) return e.json({ error: "invalid_json" }, 400);
@@ -2552,7 +2558,7 @@ function Fr(e) {
2552
2558
  }
2553
2559
  return e.json({ ok: !0 });
2554
2560
  }), n.get("/v1/admin/devices", (e) => {
2555
- let n = Ar(e.req.header(Or));
2561
+ let n = Mr(e.req.header(Ar));
2556
2562
  if (!n.ok) return e.json({ error: n.error }, 401);
2557
2563
  let r = (e.req.query("group_id") ?? "").trim();
2558
2564
  if (!r) return e.json({ error: "group_id_required" }, 400);
@@ -2567,10 +2573,10 @@ function Fr(e) {
2567
2573
  a.close();
2568
2574
  }
2569
2575
  }), n.post("/v1/admin/devices/rename", async (e) => {
2570
- let n = Ar(e.req.header(Or));
2576
+ let n = Mr(e.req.header(Ar));
2571
2577
  if (!n.ok) return e.json({ error: n.error }, 401);
2572
2578
  let r = Buffer.from(await e.req.arrayBuffer());
2573
- if (r.length > Dr) return e.json({ error: "body_too_large" }, 413);
2579
+ if (r.length > kr) return e.json({ error: "body_too_large" }, 413);
2574
2580
  let i;
2575
2581
  try {
2576
2582
  if (i = JSON.parse(r.toString("utf-8")), typeof i != "object" || !i || Array.isArray(i)) return e.json({ error: "invalid_json" }, 400);
@@ -2587,10 +2593,10 @@ function Fr(e) {
2587
2593
  c.close();
2588
2594
  }
2589
2595
  }), n.post("/v1/admin/devices/disable", async (e) => {
2590
- let n = Ar(e.req.header(Or));
2596
+ let n = Mr(e.req.header(Ar));
2591
2597
  if (!n.ok) return e.json({ error: n.error }, 401);
2592
2598
  let r = Buffer.from(await e.req.arrayBuffer());
2593
- if (r.length > Dr) return e.json({ error: "body_too_large" }, 413);
2599
+ if (r.length > kr) return e.json({ error: "body_too_large" }, 413);
2594
2600
  let i;
2595
2601
  try {
2596
2602
  if (i = JSON.parse(r.toString("utf-8")), typeof i != "object" || !i || Array.isArray(i)) return e.json({ error: "invalid_json" }, 400);
@@ -2606,10 +2612,10 @@ function Fr(e) {
2606
2612
  s.close();
2607
2613
  }
2608
2614
  }), n.post("/v1/admin/devices/remove", async (e) => {
2609
- let n = Ar(e.req.header(Or));
2615
+ let n = Mr(e.req.header(Ar));
2610
2616
  if (!n.ok) return e.json({ error: n.error }, 401);
2611
2617
  let r = Buffer.from(await e.req.arrayBuffer());
2612
- if (r.length > Dr) return e.json({ error: "body_too_large" }, 413);
2618
+ if (r.length > kr) return e.json({ error: "body_too_large" }, 413);
2613
2619
  let i;
2614
2620
  try {
2615
2621
  if (i = JSON.parse(r.toString("utf-8")), typeof i != "object" || !i || Array.isArray(i)) return e.json({ error: "invalid_json" }, 400);
@@ -2625,10 +2631,10 @@ function Fr(e) {
2625
2631
  s.close();
2626
2632
  }
2627
2633
  }), n.post("/v1/admin/invites", async (e) => {
2628
- let n = Ar(e.req.header(Or));
2634
+ let n = Mr(e.req.header(Ar));
2629
2635
  if (!n.ok) return e.json({ error: n.error }, 401);
2630
2636
  let r = Buffer.from(await e.req.arrayBuffer());
2631
- if (r.length > Dr) return e.json({ error: "body_too_large" }, 413);
2637
+ if (r.length > kr) return e.json({ error: "body_too_large" }, 413);
2632
2638
  let i;
2633
2639
  try {
2634
2640
  if (i = JSON.parse(r.toString("utf-8")), typeof i != "object" || !i || Array.isArray(i)) return e.json({ error: "invalid_json" }, 400);
@@ -2666,7 +2672,7 @@ function Fr(e) {
2666
2672
  l.close();
2667
2673
  }
2668
2674
  }), n.get("/v1/admin/invites", (e) => {
2669
- let n = Ar(e.req.header(Or));
2675
+ let n = Mr(e.req.header(Ar));
2670
2676
  if (!n.ok) return e.json({ error: n.error }, 401);
2671
2677
  let r = (e.req.query("group_id") ?? "").trim();
2672
2678
  if (!r) return e.json({ error: "group_id_required" }, 400);
@@ -2677,8 +2683,8 @@ function Fr(e) {
2677
2683
  } finally {
2678
2684
  i.close();
2679
2685
  }
2680
- }), n.post("/v1/admin/join-requests/approve", async (e) => Ir(e, !0, t)), n.post("/v1/admin/join-requests/deny", async (e) => Ir(e, !1, t)), n.get("/v1/admin/join-requests", (e) => {
2681
- let n = Ar(e.req.header(Or));
2686
+ }), n.post("/v1/admin/join-requests/approve", async (e) => Rr(e, !0, t)), n.post("/v1/admin/join-requests/deny", async (e) => Rr(e, !1, t)), n.get("/v1/admin/join-requests", (e) => {
2687
+ let n = Mr(e.req.header(Ar));
2682
2688
  if (!n.ok) return e.json({ error: n.error }, 401);
2683
2689
  let r = (e.req.query("group_id") ?? "").trim();
2684
2690
  if (!r) return e.json({ error: "group_id_required" }, 400);
@@ -2690,7 +2696,7 @@ function Fr(e) {
2690
2696
  }
2691
2697
  }), n.post("/v1/join", async (e) => {
2692
2698
  let n = Buffer.from(await e.req.arrayBuffer());
2693
- if (n.length > Dr) return e.json({ error: "body_too_large" }, 413);
2699
+ if (n.length > kr) return e.json({ error: "body_too_large" }, 413);
2694
2700
  let r;
2695
2701
  try {
2696
2702
  if (r = JSON.parse(n.toString("utf-8")), typeof r != "object" || !r || Array.isArray(r)) return e.json({ error: "invalid_json" }, 400);
@@ -2748,11 +2754,11 @@ function Fr(e) {
2748
2754
  }
2749
2755
  }), n;
2750
2756
  }
2751
- async function Ir(e, t, n) {
2752
- let r = Ar(e.req.header(Or));
2757
+ async function Rr(e, t, n) {
2758
+ let r = Mr(e.req.header(Ar));
2753
2759
  if (!r.ok) return e.json({ error: r.error }, 401);
2754
2760
  let i = Buffer.from(await e.req.arrayBuffer());
2755
- if (i.length > Dr) return e.json({ error: "body_too_large" }, 413);
2761
+ if (i.length > kr) return e.json({ error: "body_too_large" }, 413);
2756
2762
  let a;
2757
2763
  try {
2758
2764
  if (a = JSON.parse(i.toString("utf-8")), typeof a != "object" || !a || Array.isArray(a)) return e.json({ error: "invalid_json" }, 400);
@@ -2781,10 +2787,10 @@ async function Ir(e, t, n) {
2781
2787
  }
2782
2788
  //#endregion
2783
2789
  //#region src/embeddings.ts
2784
- function Lr(t) {
2790
+ function zr(t) {
2785
2791
  return e("sha256").update(t, "utf-8").digest("hex");
2786
2792
  }
2787
- function Rr(e, t = 1200) {
2793
+ function Br(e, t = 1200) {
2788
2794
  let n = e.trim();
2789
2795
  if (!n) return [];
2790
2796
  if (n.length <= t) return [n];
@@ -2815,26 +2821,26 @@ function Rr(e, t = 1200) {
2815
2821
  }
2816
2822
  return a.length > 0 && i.push(a.join("\n\n")), i;
2817
2823
  }
2818
- var zr;
2819
- function Br() {
2820
- zr = void 0;
2824
+ var Vr;
2825
+ function Hr() {
2826
+ Vr = void 0;
2821
2827
  }
2822
- async function Vr() {
2823
- if (zr !== void 0) return zr;
2824
- if (Kn()) return zr = null, null;
2828
+ async function Ur() {
2829
+ if (Vr !== void 0) return Vr;
2830
+ if (qn()) return Vr = null, null;
2825
2831
  let e = process.env.CODEMEM_EMBEDDING_MODEL || "BAAI/bge-small-en-v1.5";
2826
2832
  try {
2827
- zr = await Ur(e);
2833
+ Vr = await Gr(e);
2828
2834
  } catch {
2829
- zr = null;
2835
+ Vr = null;
2830
2836
  }
2831
- return zr;
2837
+ return Vr;
2832
2838
  }
2833
- async function Hr(e) {
2834
- let t = await Vr();
2839
+ async function Wr(e) {
2840
+ let t = await Ur();
2835
2841
  return t ? t.embed(e) : [];
2836
2842
  }
2837
- async function Ur(e) {
2843
+ async function Gr(e) {
2838
2844
  let { pipeline: t } = await import("@xenova/transformers"), n = await t("feature-extraction", e, { quantized: !0 });
2839
2845
  return {
2840
2846
  model: e,
@@ -2855,26 +2861,26 @@ async function Ur(e) {
2855
2861
  }
2856
2862
  };
2857
2863
  }
2858
- function Wr(e) {
2864
+ function Kr(e) {
2859
2865
  let t = Buffer.alloc(e.length * 4);
2860
2866
  for (let n = 0; n < e.length; n++) t.writeFloatLE(e[n] ?? 0, n * 4);
2861
2867
  return t;
2862
2868
  }
2863
2869
  //#endregion
2864
2870
  //#region src/project.ts
2865
- function Gr(e) {
2871
+ function qr(e) {
2866
2872
  let t = e.replaceAll("\\", "/").replace(/\/+$/, "");
2867
2873
  if (!t) return "";
2868
2874
  let n = t.split("/");
2869
2875
  return n[n.length - 1] ?? "";
2870
2876
  }
2871
- function Kr(e, t) {
2877
+ function Jr(e, t) {
2872
2878
  let n = t.trim();
2873
2879
  if (!n) return {
2874
2880
  clause: "",
2875
2881
  params: []
2876
2882
  };
2877
- let r = /[\\/]/.test(n) ? Gr(n) : n;
2883
+ let r = /[\\/]/.test(n) ? qr(n) : n;
2878
2884
  return r ? {
2879
2885
  clause: `(${e} = ? OR ${e} LIKE ? OR ${e} LIKE ?)`,
2880
2886
  params: [
@@ -2887,18 +2893,18 @@ function Kr(e, t) {
2887
2893
  params: []
2888
2894
  };
2889
2895
  }
2890
- function qr(e) {
2891
- return Kr("sessions.project", e);
2896
+ function Yr(e) {
2897
+ return Jr("sessions.project", e);
2892
2898
  }
2893
- function Jr(e, t) {
2899
+ function Xr(e, t) {
2894
2900
  if (!e) return !0;
2895
2901
  if (!t) return !1;
2896
2902
  let n = e.trim().replaceAll("\\", "/");
2897
2903
  if (!n) return !0;
2898
- let r = n.includes("/") ? Gr(n) : n, i = t.replaceAll("\\", "/");
2904
+ let r = n.includes("/") ? qr(n) : n, i = t.replaceAll("\\", "/");
2899
2905
  return i === r || i.endsWith(`/${r}`);
2900
2906
  }
2901
- function Yr(e) {
2907
+ function Zr(e) {
2902
2908
  let t = T(e);
2903
2909
  for (;;) {
2904
2910
  let e = T(t, ".git");
@@ -2918,12 +2924,12 @@ function Yr(e) {
2918
2924
  t = n;
2919
2925
  }
2920
2926
  }
2921
- function Xr(e, t) {
2922
- return t == null ? x(Yr(e) || T(e)) : t.trim() || null;
2927
+ function Qr(e, t) {
2928
+ return t == null ? x(Zr(e) || T(e)) : t.trim() || null;
2923
2929
  }
2924
2930
  //#endregion
2925
2931
  //#region src/export-import.ts
2926
- var Zr = [
2932
+ var $r = [
2927
2933
  "request",
2928
2934
  "investigated",
2929
2935
  "learned",
@@ -2937,26 +2943,26 @@ var Zr = [
2937
2943
  "discovery_tokens",
2938
2944
  "discovery_source"
2939
2945
  ];
2940
- function Qr() {
2946
+ function ei() {
2941
2947
  return (/* @__PURE__ */ new Date()).toISOString();
2942
2948
  }
2943
- function $r() {
2949
+ function ti() {
2944
2950
  return Date.now();
2945
2951
  }
2946
- function ei(e) {
2952
+ function ni(e) {
2947
2953
  if (typeof e != "string" || e.trim().length === 0) return null;
2948
2954
  try {
2949
2955
  return JSON.parse(e);
2950
2956
  } catch {
2951
- return J(e);
2957
+ return q(e);
2952
2958
  }
2953
2959
  }
2954
- function ti(e, t) {
2960
+ function ri(e, t) {
2955
2961
  let n = { ...e };
2956
- for (let r of t) n[r] = ei(e[r]);
2962
+ for (let r of t) n[r] = ni(e[r]);
2957
2963
  return n;
2958
2964
  }
2959
- function ni(e) {
2965
+ function ii(e) {
2960
2966
  if (e == null) return null;
2961
2967
  if (typeof e == "string") try {
2962
2968
  let t = JSON.parse(e);
@@ -2966,7 +2972,7 @@ function ni(e) {
2966
2972
  }
2967
2973
  return typeof e == "object" && !Array.isArray(e) ? { ...e } : null;
2968
2974
  }
2969
- function ri(e, t, n, r) {
2975
+ function ai(e, t, n, r) {
2970
2976
  let i = [
2971
2977
  e,
2972
2978
  t,
@@ -2974,18 +2980,18 @@ function ri(e, t, n, r) {
2974
2980
  ];
2975
2981
  return r?.project && i.push(r.project), r?.createdAt && i.push(r.createdAt), r?.sourceDb && i.push(r.sourceDb), i.join("|");
2976
2982
  }
2977
- function ii(e, t) {
2978
- let n = ni(t);
2983
+ function oi(e, t) {
2984
+ let n = ii(t);
2979
2985
  if (!n) return e;
2980
2986
  let r = { ...e };
2981
- for (let e of Zr) {
2987
+ for (let e of $r) {
2982
2988
  if (!(e in n)) continue;
2983
2989
  let t = r[e], i = !(e in r);
2984
2990
  i ||= e === "discovery_tokens" || e === "prompt_number" ? t == null : typeof t == "string" ? t.trim().length === 0 : Array.isArray(t) ? t.length === 0 : t == null, i && (r[e] = n[e]);
2985
2991
  }
2986
2992
  return r.import_metadata = t, r;
2987
2993
  }
2988
- function ai(e) {
2994
+ function si(e) {
2989
2995
  if (typeof e != "string") return null;
2990
2996
  let t = e.trim();
2991
2997
  if (!t) return null;
@@ -2995,44 +3001,44 @@ function ai(e) {
2995
3001
  }
2996
3002
  return t;
2997
3003
  }
2998
- function oi(e) {
2999
- return e.allProjects ? null : Xr(e.cwd ?? process.cwd(), e.project ?? null);
3004
+ function ci(e) {
3005
+ return e.allProjects ? null : Qr(e.cwd ?? process.cwd(), e.project ?? null);
3000
3006
  }
3001
- function si(e, t, n) {
3007
+ function li(e, t, n) {
3002
3008
  let r = "SELECT * FROM sessions", i = [], a = [];
3003
3009
  if (t) {
3004
- let e = Kr("project", t);
3010
+ let e = Jr("project", t);
3005
3011
  e.clause && (a.push(e.clause), i.push(...e.params));
3006
3012
  }
3007
- return n && (a.push("started_at >= ?"), i.push(n)), a.length > 0 && (r += ` WHERE ${a.join(" AND ")}`), r += " ORDER BY started_at ASC", e.prepare(r).all(...i).map((e) => ti(e, ["metadata_json"]));
3013
+ return n && (a.push("started_at >= ?"), i.push(n)), a.length > 0 && (r += ` WHERE ${a.join(" AND ")}`), r += " ORDER BY started_at ASC", e.prepare(r).all(...i).map((e) => ri(e, ["metadata_json"]));
3008
3014
  }
3009
- function ci(e, t, n, r, i = "") {
3015
+ function ui(e, t, n, r, i = "") {
3010
3016
  if (n.length === 0) return [];
3011
3017
  let a = `SELECT * FROM ${t} WHERE session_id IN (${n.map(() => "?").join(",")})${i} ORDER BY ${r}`;
3012
3018
  return e.prepare(a).all(...n);
3013
3019
  }
3014
- function li(e = {}) {
3015
- let t = Wn(zn(e.dbPath));
3020
+ function di(e = {}) {
3021
+ let t = Gn(Bn(e.dbPath));
3016
3022
  try {
3017
- Yn(t);
3018
- let n = oi(e), r = {};
3023
+ Xn(t);
3024
+ let n = ci(e), r = {};
3019
3025
  n && (r.project = n), e.since && (r.since = e.since);
3020
- let i = si(t, n, e.since ?? null), a = i.map((e) => Number(e.id)).filter(Number.isFinite), o = ci(t, "memory_items", a, "created_at ASC", e.includeInactive ? "" : " AND active = 1").map((e) => ti(e, [
3026
+ let i = li(t, n, e.since ?? null), a = i.map((e) => Number(e.id)).filter(Number.isFinite), o = ui(t, "memory_items", a, "created_at ASC", e.includeInactive ? "" : " AND active = 1").map((e) => ri(e, [
3021
3027
  "metadata_json",
3022
3028
  "facts",
3023
3029
  "concepts",
3024
3030
  "files_read",
3025
3031
  "files_modified"
3026
- ])), s = ci(t, "session_summaries", a, "created_at_epoch ASC").map((e) => ti(e, [
3032
+ ])), s = ui(t, "session_summaries", a, "created_at_epoch ASC").map((e) => ri(e, [
3027
3033
  "metadata_json",
3028
3034
  "files_read",
3029
3035
  "files_edited"
3030
- ])), c = ci(t, "user_prompts", a, "created_at_epoch ASC").map((e) => ti(e, ["metadata_json"])), l = /* @__PURE__ */ new Map();
3036
+ ])), c = ui(t, "user_prompts", a, "created_at_epoch ASC").map((e) => ri(e, ["metadata_json"])), l = /* @__PURE__ */ new Map();
3031
3037
  for (let e of c) typeof e.id == "number" && typeof e.import_key == "string" && l.set(e.id, e.import_key);
3032
3038
  for (let e of o) typeof e.user_prompt_id == "number" && (e.user_prompt_import_key = l.get(e.user_prompt_id) ?? null);
3033
3039
  return {
3034
3040
  version: "1.0",
3035
- exported_at: Qr(),
3041
+ exported_at: ei(),
3036
3042
  export_metadata: {
3037
3043
  tool_version: "codemem",
3038
3044
  projects: [...new Set(i.map((e) => String(e.project ?? "")).filter(Boolean))],
@@ -3050,51 +3056,51 @@ function li(e = {}) {
3050
3056
  t.close();
3051
3057
  }
3052
3058
  }
3053
- function ui(e) {
3054
- let t = f(e === "-" ? 0 : hn(e), "utf8"), n = JSON.parse(t);
3059
+ function fi(e) {
3060
+ let t = f(e === "-" ? 0 : gn(e), "utf8"), n = JSON.parse(t);
3055
3061
  if (typeof n != "object" || !n || Array.isArray(n)) throw Error("Import payload must be a JSON object");
3056
3062
  let r = n;
3057
3063
  if (r.version !== "1.0") throw Error(`Unsupported export version: ${String(n.version ?? "unknown")}`);
3058
3064
  return r;
3059
3065
  }
3060
- function di(e, t, n) {
3066
+ function pi(e, t, n) {
3061
3067
  return e.prepare(`SELECT id FROM ${t} WHERE import_key = ? LIMIT 1`).get(n)?.id ?? null;
3062
3068
  }
3063
- function fi() {
3069
+ function mi() {
3064
3070
  return process.env.USER?.trim() || process.env.USERNAME?.trim() || "import";
3065
3071
  }
3066
- function pi(e, t) {
3072
+ function hi(e, t) {
3067
3073
  let n = e.insert(z).values({
3068
- started_at: typeof t.started_at == "string" ? t.started_at : Qr(),
3074
+ started_at: typeof t.started_at == "string" ? t.started_at : ei(),
3069
3075
  ended_at: typeof t.ended_at == "string" ? t.ended_at : null,
3070
3076
  cwd: String(t.cwd ?? process.cwd()),
3071
3077
  project: t.project == null ? null : String(t.project),
3072
3078
  git_remote: t.git_remote == null ? null : String(t.git_remote),
3073
3079
  git_branch: t.git_branch == null ? null : String(t.git_branch),
3074
- user: String(t.user ?? fi()),
3080
+ user: String(t.user ?? mi()),
3075
3081
  tool_version: String(t.tool_version ?? "import"),
3076
- metadata_json: Y(t.metadata_json ?? null),
3082
+ metadata_json: J(t.metadata_json ?? null),
3077
3083
  import_key: String(t.import_key)
3078
3084
  }).returning({ id: z.id }).all()[0]?.id;
3079
3085
  if (n == null) throw Error("session insert returned no id");
3080
3086
  return n;
3081
3087
  }
3082
- function mi(e, t) {
3088
+ function gi(e, t) {
3083
3089
  let n = e.insert(rn).values({
3084
3090
  session_id: Number(t.session_id),
3085
3091
  project: t.project == null ? null : String(t.project),
3086
3092
  prompt_text: String(t.prompt_text ?? ""),
3087
3093
  prompt_number: t.prompt_number == null ? null : Number(t.prompt_number),
3088
- created_at: typeof t.created_at == "string" ? t.created_at : Qr(),
3089
- created_at_epoch: typeof t.created_at_epoch == "number" ? t.created_at_epoch : $r(),
3090
- metadata_json: Y(t.metadata_json ?? null),
3094
+ created_at: typeof t.created_at == "string" ? t.created_at : ei(),
3095
+ created_at_epoch: typeof t.created_at_epoch == "number" ? t.created_at_epoch : ti(),
3096
+ metadata_json: J(t.metadata_json ?? null),
3091
3097
  import_key: String(t.import_key)
3092
3098
  }).returning({ id: rn.id }).all()[0]?.id;
3093
3099
  if (n == null) throw Error("prompt insert returned no id");
3094
3100
  return n;
3095
3101
  }
3096
- function hi(e, t) {
3097
- let n = Qr(), r = e.insert(B).values({
3102
+ function _i(e, t) {
3103
+ let n = ei(), r = e.insert(B).values({
3098
3104
  session_id: Number(t.session_id),
3099
3105
  kind: String(t.kind ?? "observation"),
3100
3106
  title: String(t.title ?? "Untitled"),
@@ -3105,7 +3111,7 @@ function hi(e, t) {
3105
3111
  active: 1,
3106
3112
  created_at: typeof t.created_at == "string" ? t.created_at : n,
3107
3113
  updated_at: typeof t.updated_at == "string" ? t.updated_at : n,
3108
- metadata_json: Y(t.metadata_json ?? null),
3114
+ metadata_json: J(t.metadata_json ?? null),
3109
3115
  actor_id: t.actor_id == null ? null : String(t.actor_id),
3110
3116
  actor_display_name: t.actor_display_name == null ? null : String(t.actor_display_name),
3111
3117
  visibility: t.visibility == null ? null : String(t.visibility),
@@ -3114,11 +3120,11 @@ function hi(e, t) {
3114
3120
  origin_device_id: t.origin_device_id == null ? null : String(t.origin_device_id),
3115
3121
  origin_source: t.origin_source == null ? null : String(t.origin_source),
3116
3122
  trust_state: t.trust_state == null ? null : String(t.trust_state),
3117
- facts: X(t.facts),
3123
+ facts: Y(t.facts),
3118
3124
  narrative: t.narrative == null ? null : String(t.narrative),
3119
- concepts: X(t.concepts),
3120
- files_read: X(t.files_read),
3121
- files_modified: X(t.files_modified),
3125
+ concepts: Y(t.concepts),
3126
+ files_read: Y(t.files_read),
3127
+ files_modified: Y(t.files_modified),
3122
3128
  user_prompt_id: t.user_prompt_id == null ? null : Number(t.user_prompt_id),
3123
3129
  prompt_number: t.prompt_number == null ? null : Number(t.prompt_number),
3124
3130
  deleted_at: null,
@@ -3128,7 +3134,7 @@ function hi(e, t) {
3128
3134
  if (r == null) throw Error("memory insert returned no id");
3129
3135
  return r;
3130
3136
  }
3131
- function gi(e, t) {
3137
+ function vi(e, t) {
3132
3138
  let n = e.insert(an).values({
3133
3139
  session_id: Number(t.session_id),
3134
3140
  project: t.project == null ? null : String(t.project),
@@ -3138,18 +3144,18 @@ function gi(e, t) {
3138
3144
  completed: String(t.completed ?? ""),
3139
3145
  next_steps: String(t.next_steps ?? ""),
3140
3146
  notes: String(t.notes ?? ""),
3141
- files_read: X(t.files_read),
3142
- files_edited: X(t.files_edited),
3147
+ files_read: Y(t.files_read),
3148
+ files_edited: Y(t.files_edited),
3143
3149
  prompt_number: t.prompt_number == null ? null : Number(t.prompt_number),
3144
- created_at: typeof t.created_at == "string" ? t.created_at : Qr(),
3145
- created_at_epoch: typeof t.created_at_epoch == "number" ? t.created_at_epoch : $r(),
3146
- metadata_json: Y(t.metadata_json ?? null),
3150
+ created_at: typeof t.created_at == "string" ? t.created_at : ei(),
3151
+ created_at_epoch: typeof t.created_at_epoch == "number" ? t.created_at_epoch : ti(),
3152
+ metadata_json: J(t.metadata_json ?? null),
3147
3153
  import_key: String(t.import_key)
3148
3154
  }).returning({ id: an.id }).all()[0]?.id;
3149
3155
  if (n == null) throw Error("summary insert returned no id");
3150
3156
  return n;
3151
3157
  }
3152
- function _i(e, t = {}) {
3158
+ function yi(e, t = {}) {
3153
3159
  let n = Array.isArray(e.sessions) ? e.sessions : [], r = Array.isArray(e.memory_items) ? e.memory_items : [], i = Array.isArray(e.session_summaries) ? e.session_summaries : [], a = Array.isArray(e.user_prompts) ? e.user_prompts : [];
3154
3160
  if (t.dryRun) return {
3155
3161
  sessions: n.length,
@@ -3158,17 +3164,17 @@ function _i(e, t = {}) {
3158
3164
  session_summaries: i.length,
3159
3165
  dryRun: !0
3160
3166
  };
3161
- let o = Wn(zn(t.dbPath));
3167
+ let o = Gn(Bn(t.dbPath));
3162
3168
  try {
3163
- Yn(o);
3169
+ Xn(o);
3164
3170
  let e = j(o, { schema: R });
3165
3171
  return o.transaction(() => {
3166
3172
  let s = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map(), l = /* @__PURE__ */ new Map(), u = 0, d = 0, f = 0, p = 0;
3167
3173
  for (let r of n) {
3168
- let n = Number(r.id), i = t.remapProject || ai(r.project), a = ri("export", "session", r.id, {
3174
+ let n = Number(r.id), i = t.remapProject || si(r.project), a = ai("export", "session", r.id, {
3169
3175
  project: i,
3170
3176
  createdAt: typeof r.started_at == "string" ? r.started_at : null
3171
- }), c = di(o, "sessions", a);
3177
+ }), c = pi(o, "sessions", a);
3172
3178
  if (c != null) {
3173
3179
  s.set(n, c);
3174
3180
  continue;
@@ -3180,7 +3186,7 @@ function _i(e, t = {}) {
3180
3186
  original_ended_at: r.ended_at ?? null,
3181
3187
  import_metadata: r.metadata_json ?? null,
3182
3188
  import_key: a
3183
- }, d = pi(e, {
3189
+ }, d = hi(e, {
3184
3190
  ...r,
3185
3191
  project: i,
3186
3192
  metadata_json: l,
@@ -3191,10 +3197,10 @@ function _i(e, t = {}) {
3191
3197
  for (let n of a) {
3192
3198
  let r = Number(n.session_id), i = s.get(r);
3193
3199
  if (i == null) continue;
3194
- let a = t.remapProject || ai(n.project), u = typeof n.import_key == "string" && n.import_key.trim() ? n.import_key.trim() : ri("export", "prompt", n.id, {
3200
+ let a = t.remapProject || si(n.project), u = typeof n.import_key == "string" && n.import_key.trim() ? n.import_key.trim() : ai("export", "prompt", n.id, {
3195
3201
  project: a,
3196
3202
  createdAt: typeof n.created_at == "string" ? n.created_at : null
3197
- }), f = di(o, "user_prompts", u);
3203
+ }), f = pi(o, "user_prompts", u);
3198
3204
  if (f != null) {
3199
3205
  typeof n.id == "number" && c.set(n.id, f), l.set(u, f);
3200
3206
  continue;
@@ -3205,7 +3211,7 @@ function _i(e, t = {}) {
3205
3211
  original_created_at: n.created_at ?? null,
3206
3212
  import_metadata: n.metadata_json ?? null,
3207
3213
  import_key: u
3208
- }, m = mi(e, {
3214
+ }, m = gi(e, {
3209
3215
  ...n,
3210
3216
  session_id: i,
3211
3217
  project: a,
@@ -3217,13 +3223,13 @@ function _i(e, t = {}) {
3217
3223
  for (let n of r) {
3218
3224
  let r = Number(n.session_id), i = s.get(r);
3219
3225
  if (i == null) continue;
3220
- let a = t.remapProject || ai(n.project), u = typeof n.import_key == "string" && n.import_key.trim() ? n.import_key.trim() : ri("export", "memory", n.id, {
3226
+ let a = t.remapProject || si(n.project), u = typeof n.import_key == "string" && n.import_key.trim() ? n.import_key.trim() : ai("export", "memory", n.id, {
3221
3227
  project: a,
3222
3228
  createdAt: typeof n.created_at == "string" ? n.created_at : null
3223
3229
  });
3224
- if (di(o, "memory_items", u) != null) continue;
3230
+ if (pi(o, "memory_items", u) != null) continue;
3225
3231
  let d = null;
3226
- typeof n.user_prompt_import_key == "string" && n.user_prompt_import_key.trim() ? d = l.get(n.user_prompt_import_key.trim()) ?? di(o, "user_prompts", n.user_prompt_import_key.trim()) : typeof n.user_prompt_id == "number" && (d = c.get(n.user_prompt_id) ?? null);
3232
+ typeof n.user_prompt_import_key == "string" && n.user_prompt_import_key.trim() ? d = l.get(n.user_prompt_import_key.trim()) ?? pi(o, "user_prompts", n.user_prompt_import_key.trim()) : typeof n.user_prompt_id == "number" && (d = c.get(n.user_prompt_id) ?? null);
3227
3233
  let p = {
3228
3234
  source: "export",
3229
3235
  original_memory_id: n.id ?? null,
@@ -3232,8 +3238,8 @@ function _i(e, t = {}) {
3232
3238
  import_key: u
3233
3239
  };
3234
3240
  typeof n.user_prompt_import_key == "string" && n.user_prompt_import_key.trim() && (p.user_prompt_import_key = n.user_prompt_import_key.trim());
3235
- let m = n.kind === "session_summary" ? ii(p, n.metadata_json ?? null) : p;
3236
- hi(e, {
3241
+ let m = n.kind === "session_summary" ? oi(p, n.metadata_json ?? null) : p;
3242
+ _i(e, {
3237
3243
  ...n,
3238
3244
  session_id: i,
3239
3245
  project: a,
@@ -3245,11 +3251,11 @@ function _i(e, t = {}) {
3245
3251
  for (let n of i) {
3246
3252
  let r = Number(n.session_id), i = s.get(r);
3247
3253
  if (i == null) continue;
3248
- let a = t.remapProject || ai(n.project), c = typeof n.import_key == "string" && n.import_key.trim() ? n.import_key.trim() : ri("export", "summary", n.id, {
3254
+ let a = t.remapProject || si(n.project), c = typeof n.import_key == "string" && n.import_key.trim() ? n.import_key.trim() : ai("export", "summary", n.id, {
3249
3255
  project: a,
3250
3256
  createdAt: typeof n.created_at == "string" ? n.created_at : null
3251
3257
  });
3252
- if (di(o, "session_summaries", c) != null) continue;
3258
+ if (pi(o, "session_summaries", c) != null) continue;
3253
3259
  let l = {
3254
3260
  source: "export",
3255
3261
  original_summary_id: n.id ?? null,
@@ -3257,7 +3263,7 @@ function _i(e, t = {}) {
3257
3263
  import_metadata: n.metadata_json ?? null,
3258
3264
  import_key: c
3259
3265
  };
3260
- gi(e, {
3266
+ vi(e, {
3261
3267
  ...n,
3262
3268
  session_id: i,
3263
3269
  project: a,
@@ -3279,7 +3285,7 @@ function _i(e, t = {}) {
3279
3285
  }
3280
3286
  //#endregion
3281
3287
  //#region src/filters.ts
3282
- function vi(e) {
3288
+ function bi(e) {
3283
3289
  if (e == null) return [];
3284
3290
  let t = Array.isArray(e) ? e : [e], n = /* @__PURE__ */ new Set(), r = [];
3285
3291
  for (let e of t) {
@@ -3288,16 +3294,16 @@ function vi(e) {
3288
3294
  }
3289
3295
  return r;
3290
3296
  }
3291
- function yi(e) {
3292
- return vi(e).map((e) => e.toLowerCase()).filter((e, t, n) => (e === "personal" || e === "shared") && n.indexOf(e) === t);
3297
+ function xi(e) {
3298
+ return bi(e).map((e) => e.toLowerCase()).filter((e, t, n) => (e === "personal" || e === "shared") && n.indexOf(e) === t);
3293
3299
  }
3294
- function bi(e) {
3295
- return vi(e).map((e) => e.toLowerCase()).filter((e, t, n) => (e === "private" || e === "shared") && n.indexOf(e) === t);
3300
+ function Si(e) {
3301
+ return bi(e).map((e) => e.toLowerCase()).filter((e, t, n) => (e === "private" || e === "shared") && n.indexOf(e) === t);
3296
3302
  }
3297
- function xi(e) {
3298
- return vi(e).map((e) => e.toLowerCase()).filter((e, t, n) => (e === "trusted" || e === "legacy_unknown" || e === "unreviewed") && n.indexOf(e) === t);
3303
+ function Ci(e) {
3304
+ return bi(e).map((e) => e.toLowerCase()).filter((e, t, n) => (e === "trusted" || e === "legacy_unknown" || e === "unreviewed") && n.indexOf(e) === t);
3299
3305
  }
3300
- function Si(e, t, n, r, i) {
3306
+ function wi(e, t, n, r, i) {
3301
3307
  if (r.length > 0) {
3302
3308
  let i = r.map(() => "?").join(", ");
3303
3309
  e.push(`${n} IN (${i})`), t.push(...r);
@@ -3307,10 +3313,10 @@ function Si(e, t, n, r, i) {
3307
3313
  e.push(`(${n} IS NULL OR ${n} NOT IN (${r}))`), t.push(...i);
3308
3314
  }
3309
3315
  }
3310
- function Ci(e) {
3311
- return wi(e);
3316
+ function Ti(e) {
3317
+ return Ei(e);
3312
3318
  }
3313
- function wi(e, t) {
3319
+ function Ei(e, t) {
3314
3320
  let n = {
3315
3321
  clauses: [],
3316
3322
  params: [],
@@ -3325,51 +3331,51 @@ function wi(e, t) {
3325
3331
  a === "mine" ? r.push(e) : r.push(`NOT ${e}`), i.push(t.actorId, t.deviceId);
3326
3332
  }
3327
3333
  if (e.project) {
3328
- let { clause: t, params: a } = qr(e.project);
3334
+ let { clause: t, params: a } = Yr(e.project);
3329
3335
  t && (r.push(t), i.push(...a), n.joinSessions = !0);
3330
3336
  }
3331
- return Si(r, i, "memory_items.visibility", bi(e.include_visibility ?? e.visibility), bi(e.exclude_visibility)), Si(r, i, "memory_items.workspace_id", vi(e.include_workspace_ids), vi(e.exclude_workspace_ids)), Si(r, i, "memory_items.workspace_kind", yi(e.include_workspace_kinds), yi(e.exclude_workspace_kinds)), Si(r, i, "memory_items.actor_id", vi(e.include_actor_ids), vi(e.exclude_actor_ids)), Si(r, i, "memory_items.trust_state", xi(e.include_trust_states), xi(e.exclude_trust_states)), n;
3337
+ return wi(r, i, "memory_items.visibility", Si(e.include_visibility ?? e.visibility), Si(e.exclude_visibility)), wi(r, i, "memory_items.workspace_id", bi(e.include_workspace_ids), bi(e.exclude_workspace_ids)), wi(r, i, "memory_items.workspace_kind", xi(e.include_workspace_kinds), xi(e.exclude_workspace_kinds)), wi(r, i, "memory_items.actor_id", bi(e.include_actor_ids), bi(e.exclude_actor_ids)), wi(r, i, "memory_items.trust_state", Ci(e.include_trust_states), Ci(e.exclude_trust_states)), n;
3332
3338
  }
3333
3339
  //#endregion
3334
3340
  //#region src/ingest-sanitize.ts
3335
- var Ti = /<private>.*?<\/private>/gis, Ei = /<private>/i, Di = /<\/private>/gi;
3336
- function Oi(e) {
3341
+ var Di = /<private>.*?<\/private>/gis, Oi = /<private>/i, ki = /<\/private>/gi;
3342
+ function Ai(e) {
3337
3343
  if (!e) return "";
3338
- let t = e.replace(Ti, ""), n = Ei.exec(t);
3339
- return n && (t = t.slice(0, n.index)), t = t.replace(Di, ""), t;
3344
+ let t = e.replace(Di, ""), n = Oi.exec(t);
3345
+ return n && (t = t.slice(0, n.index)), t = t.replace(ki, ""), t;
3340
3346
  }
3341
- var ki = /(?:^|_|-)(?:token|secret|password|passwd|api[_-]?key|authorization|private[_-]?key|cookie)(?:$|_|-)/i, Ai = "[REDACTED]";
3342
- function ji(e) {
3347
+ var ji = /(?:^|_|-)(?:token|secret|password|passwd|api[_-]?key|authorization|private[_-]?key|cookie)(?:$|_|-)/i, Mi = "[REDACTED]";
3348
+ function Ni(e) {
3343
3349
  let t = e.trim().toLowerCase();
3344
- return t ? ki.test(t) : !1;
3350
+ return t ? ji.test(t) : !1;
3345
3351
  }
3346
- function Mi(e) {
3347
- if (typeof e == "string") return Oi(e);
3348
- if (Array.isArray(e)) return e.map(Mi);
3352
+ function Pi(e) {
3353
+ if (typeof e == "string") return Ai(e);
3354
+ if (Array.isArray(e)) return e.map(Pi);
3349
3355
  if (typeof e == "object" && e) {
3350
3356
  let t = {};
3351
- for (let [n, r] of Object.entries(e)) ji(n) ? t[n] = Ai : t[n] = Mi(r);
3357
+ for (let [n, r] of Object.entries(e)) Ni(n) ? t[n] = Mi : t[n] = Pi(r);
3352
3358
  return t;
3353
3359
  }
3354
3360
  return e;
3355
3361
  }
3356
- function Ni(e, t) {
3362
+ function Fi(e, t) {
3357
3363
  return t <= 0 ? "" : e.length <= t ? e : `${e.slice(0, t)}... (truncated)`;
3358
3364
  }
3359
- function Pi(e, t) {
3365
+ function Ii(e, t) {
3360
3366
  if (e == null) return null;
3361
- if (typeof e == "string") return Ni(Oi(e), t);
3362
- let n = Mi(e);
3367
+ if (typeof e == "string") return Fi(Ai(e), t);
3368
+ let n = Pi(e);
3363
3369
  try {
3364
3370
  let e = JSON.stringify(n);
3365
- if (t > 0 && e.length > t) return Ni(e, t);
3371
+ if (t > 0 && e.length > t) return Fi(e, t);
3366
3372
  } catch {
3367
3373
  let e = String(n);
3368
- if (t > 0 && e.length > t) return Ni(e, t);
3374
+ if (t > 0 && e.length > t) return Fi(e, t);
3369
3375
  }
3370
3376
  return n;
3371
3377
  }
3372
- var Fi = new Set([
3378
+ var Li = new Set([
3373
3379
  "wrote file successfully.",
3374
3380
  "wrote file successfully",
3375
3381
  "file written successfully.",
@@ -3378,19 +3384,19 @@ var Fi = new Set([
3378
3384
  "<file>",
3379
3385
  "<image>"
3380
3386
  ]);
3381
- function Ii(e) {
3387
+ function Ri(e) {
3382
3388
  if (!e) return !0;
3383
3389
  let t = e.split("\n").map((e) => e.trim()).filter(Boolean);
3384
- return t.length === 0 ? !0 : t.every((e) => Fi.has(e.toLowerCase()));
3390
+ return t.length === 0 ? !0 : t.every((e) => Li.has(e.toLowerCase()));
3385
3391
  }
3386
- function Li(e, t, n) {
3392
+ function zi(e, t, n) {
3387
3393
  if (t == null) return null;
3388
- let r = Pi(t, n);
3389
- return Ii(String(r ?? "")) ? "" : r;
3394
+ let r = Ii(t, n);
3395
+ return Ri(String(r ?? "")) ? "" : r;
3390
3396
  }
3391
3397
  //#endregion
3392
3398
  //#region src/ingest-events.ts
3393
- var Ri = new Set([
3399
+ var Bi = new Set([
3394
3400
  "tui",
3395
3401
  "shell",
3396
3402
  "cmd",
@@ -3400,48 +3406,48 @@ var Ri = new Set([
3400
3406
  "todowrite",
3401
3407
  "askuserquestion"
3402
3408
  ]);
3403
- function zi(e) {
3409
+ function Vi(e) {
3404
3410
  return e.startsWith("codemem_memory_");
3405
3411
  }
3406
- function Bi(e) {
3412
+ function Hi(e) {
3407
3413
  let t = String(e.tool ?? e.type ?? "tool").toLowerCase();
3408
3414
  return t.includes(".") && (t = t.split(".").pop() ?? t), t.includes(":") && (t = t.split(":").pop() ?? t), t;
3409
3415
  }
3410
- function Vi(e, t = 80, n = 2e3) {
3416
+ function Ui(e, t = 80, n = 2e3) {
3411
3417
  if (!e) return "";
3412
3418
  let r = e.split("\n"), i = r;
3413
3419
  i.length > t && (i = [...i.slice(0, t), `... (+${r.length - t} more lines)`]);
3414
3420
  let a = i.join("\n");
3415
3421
  return n > 0 && a.length > n && (a = `${a.slice(0, n)}\n... (truncated)`), a;
3416
3422
  }
3417
- function Hi(e) {
3418
- return Vi(e, 120, 2400);
3423
+ function Wi(e) {
3424
+ return Ui(e, 120, 2400);
3419
3425
  }
3420
- function Ui(e, t, n = Ri) {
3426
+ function Gi(e, t, n = Bi) {
3421
3427
  if (e.type !== "tool.execute.after") return null;
3422
- let r = Bi(e);
3423
- if (zi(r) || n.has(r)) return null;
3424
- let i = e.args, a = typeof i == "object" && i && !Array.isArray(i) ? i : {}, o = Li(r, e.result, t);
3425
- r === "read" && typeof o == "string" && (o = Vi(o)), r === "bash" && typeof o == "string" && (o = Vi(o)), (r === "glob" || r === "grep") && typeof o == "string" && (o = Hi(o));
3426
- let s = Pi(e.error, t);
3428
+ let r = Hi(e);
3429
+ if (Vi(r) || n.has(r)) return null;
3430
+ let i = e.args, a = typeof i == "object" && i && !Array.isArray(i) ? i : {}, o = zi(r, e.result, t);
3431
+ r === "read" && typeof o == "string" && (o = Ui(o)), r === "bash" && typeof o == "string" && (o = Ui(o)), (r === "glob" || r === "grep") && typeof o == "string" && (o = Wi(o));
3432
+ let s = Ii(e.error, t);
3427
3433
  return {
3428
3434
  toolName: r,
3429
- toolInput: Pi(a, t),
3435
+ toolInput: Ii(a, t),
3430
3436
  toolOutput: o,
3431
3437
  toolError: s,
3432
3438
  timestamp: typeof e.timestamp == "string" ? e.timestamp : null,
3433
3439
  cwd: (typeof e.cwd == "string" ? e.cwd : null) ?? (typeof a.cwd == "string" ? a.cwd : null)
3434
3440
  };
3435
3441
  }
3436
- function Wi(e, t) {
3442
+ function Ki(e, t) {
3437
3443
  let n = [];
3438
3444
  for (let r of e) {
3439
- let e = Ui(r, t);
3445
+ let e = Gi(r, t);
3440
3446
  e && n.push(e);
3441
3447
  }
3442
3448
  return n;
3443
3449
  }
3444
- function Gi(e) {
3450
+ function qi(e) {
3445
3451
  let t = e._adapter;
3446
3452
  if (typeof t != "object" || !t || Array.isArray(t)) return null;
3447
3453
  let n = t;
@@ -3464,7 +3470,7 @@ function Gi(e) {
3464
3470
  }
3465
3471
  return n;
3466
3472
  }
3467
- function Ki(e, t) {
3473
+ function Ji(e, t) {
3468
3474
  let n = String(e.event_type ?? ""), r = e.payload;
3469
3475
  if (!r || typeof r != "object" || n !== "tool_result") return null;
3470
3476
  let i = r.tool_input;
@@ -3482,7 +3488,7 @@ function Ki(e, t) {
3482
3488
  cwd: t.cwd
3483
3489
  };
3484
3490
  }
3485
- function qi(e) {
3491
+ function Yi(e) {
3486
3492
  if (e.toolName === "bash" && e.toolInput != null && typeof e.toolInput == "object") {
3487
3493
  let t = e.toolInput, n = String(t.command ?? "").trim().toLowerCase();
3488
3494
  if ((n === "git status" || n === "git diff") && !e.toolError) return `bash:${n}`;
@@ -3495,26 +3501,26 @@ function qi(e) {
3495
3501
  }
3496
3502
  return e.toolError && t.push(String(e.toolError).slice(0, 200)), typeof e.toolOutput == "string" && e.toolOutput && t.push(e.toolOutput.slice(0, 200)), t.join("|");
3497
3503
  }
3498
- function Ji(e) {
3504
+ function Xi(e) {
3499
3505
  let t = 0;
3500
3506
  e.toolError && (t += 100);
3501
3507
  let n = (e.toolName || "").toLowerCase();
3502
3508
  return n === "edit" || n === "write" ? t += 50 : n === "bash" ? t += 30 : n === "read" ? t += 20 : t += 10, t;
3503
3509
  }
3504
- function Yi(e) {
3510
+ function Zi(e) {
3505
3511
  try {
3506
3512
  return JSON.stringify(e).length;
3507
3513
  } catch {
3508
3514
  return String(e).length;
3509
3515
  }
3510
3516
  }
3511
- function Xi(e, t, n) {
3517
+ function Qi(e, t, n) {
3512
3518
  if (!e.length || t <= 0 || n <= 0) return [];
3513
3519
  let r = /* @__PURE__ */ new Set(), i = [];
3514
3520
  for (let t = e.length - 1; t >= 0; t--) {
3515
3521
  let n = e[t];
3516
3522
  if (!n) continue;
3517
- let a = qi(n);
3523
+ let a = Yi(n);
3518
3524
  r.has(a) || (r.add(a), i.push(n));
3519
3525
  }
3520
3526
  i.reverse();
@@ -3525,31 +3531,31 @@ function Xi(e, t, n) {
3525
3531
  idx: t
3526
3532
  }));
3527
3533
  e.sort((e, t) => {
3528
- let n = Ji(t.event) - Ji(e.event);
3534
+ let n = Xi(t.event) - Xi(e.event);
3529
3535
  return n === 0 ? e.idx - t.idx : n;
3530
3536
  });
3531
3537
  let t = new Set(e.slice(0, n).map((e) => e.idx));
3532
3538
  a = a.filter((e, n) => t.has(n));
3533
3539
  }
3534
- if (a.reduce((e, t) => e + Yi(t), 0) <= t) return a;
3540
+ if (a.reduce((e, t) => e + Zi(t), 0) <= t) return a;
3535
3541
  let o = a.map((e, t) => ({
3536
3542
  event: e,
3537
3543
  idx: t
3538
3544
  }));
3539
3545
  o.sort((e, t) => {
3540
- let n = Ji(t.event) - Ji(e.event);
3546
+ let n = Xi(t.event) - Xi(e.event);
3541
3547
  return n === 0 ? e.idx - t.idx : n;
3542
3548
  });
3543
3549
  let s = [], c = 0;
3544
3550
  for (let e of o) {
3545
- let n = Yi(e.event);
3551
+ let n = Zi(e.event);
3546
3552
  if (!(c + n > t && s.length > 0) && (s.push(e), c += n, c >= t)) break;
3547
3553
  }
3548
3554
  return s.sort((e, t) => e.idx - t.idx), s.map((e) => e.event);
3549
3555
  }
3550
3556
  //#endregion
3551
3557
  //#region src/ingest-filters.ts
3552
- var Zi = [
3558
+ var $i = [
3553
3559
  /\bno\s+code\s+changes?\s+(?:were|was)\s+(?:recorded|made)\b/i,
3554
3560
  /\bno\s+code\s+was\s+modified\b/i,
3555
3561
  /\bno\s+new\s+(?:code|configuration|config|documentation)(?:\s+or\s+(?:code|configuration|config|documentation))?\s+(?:was|were)\s+(?:shipped|delivered)\b/i,
@@ -3564,18 +3570,18 @@ var Zi = [
3564
3570
  /\bwork\s+consisted\s+entirely\s+of\s+capturing\s+the\s+current\s+state\b/i,
3565
3571
  /\bprimary\s+user\s+request\s+details\s+were\s+absent\b/i
3566
3572
  ];
3567
- function Qi(e) {
3573
+ function ea(e) {
3568
3574
  let t = e.trim().replace(/^[\s\-\u2022\u2514\u203a>$]+/, "");
3569
3575
  return t = t.replace(/\s+/g, " ").trim(), t;
3570
3576
  }
3571
- function $i(e) {
3572
- let t = Qi(e);
3573
- return t ? Zi.some((e) => e.test(t)) : !0;
3577
+ function ta(e) {
3578
+ let t = ea(e);
3579
+ return t ? $i.some((e) => e.test(t)) : !0;
3574
3580
  }
3575
3581
  //#endregion
3576
3582
  //#region src/ingest-prompts.ts
3577
- var ea = "bugfix, feature, refactor, change, discovery, decision, exploration", ta = "You are a memory observer creating searchable records of development work FOR FUTURE SESSIONS. Record what was BUILT/FIXED/DEPLOYED/CONFIGURED/LEARNED, not what you (the observer) are doing. These memories help developers recall past work, decisions, learnings, and investigations.", na = "Focus on deliverables, capabilities, AND learnings:\n- What the system NOW DOES differently (new capabilities)\n- What shipped to users/production (features, fixes, configs, docs)\n- What was LEARNED through debugging, investigation, or testing\n- How systems work and why they behave the way they do\n- Changes in technical domains (auth, data, UI, infra, DevOps)\n\nUse outcome-focused verbs: implemented, fixed, deployed, configured, migrated, optimized, added, refactored, discovered, learned, debugged.\nOnly describe actions that are clearly supported by the observed context.\nNever invent file changes, API behavior, or code edits that are not explicitly present in the session evidence.", ra = "Skip routine operations WITHOUT learnings:\n- Empty status checks or listings (unless revealing important state)\n- Package installations with no errors or insights\n- Simple file reads with no discoveries\n- Repetitive operations already documented with no new findings\nIf nothing meaningful happened AND nothing was learned:\n- Output no <observation> blocks\n- Output <skip_summary reason=\"low-signal\"/> instead of a <summary> block.", ia = "Create narratives that tell the complete story:\n- Context: What was the problem or goal? What prompted this work?\n- Investigation: What was examined? What was discovered?\n- Learning: How does it work? Why does it exist? Any gotchas?\n- Implementation: What was changed? What does the code do now?\n- Impact: What's better? What does the system do differently?\n- Next steps: What remains? What should future sessions know?\n\nAim for ~120-400 words per significant work item.\nPrefer fewer, higher-signal observations over many small ones.\nInclude specific details when present: file paths, function names, configuration values.", aa = "Output only XML. Do not include commentary outside XML.\n\nALWAYS emit at least one <observation> block for any meaningful work. Observations are the PRIMARY output - they capture what was built, fixed, learned, or decided. Also emit a <summary> block to track session progress.\n\nPrefer fewer, more comprehensive observations over many small ones.", oa = `<observation>
3578
- <type>[ ${ea} ]</type>
3583
+ var na = "bugfix, feature, refactor, change, discovery, decision, exploration", ra = "You are a memory observer creating searchable records of development work FOR FUTURE SESSIONS. Record what was BUILT/FIXED/DEPLOYED/CONFIGURED/LEARNED, not what you (the observer) are doing. These memories help developers recall past work, decisions, learnings, and investigations.", ia = "Focus on deliverables, capabilities, AND learnings:\n- What the system NOW DOES differently (new capabilities)\n- What shipped to users/production (features, fixes, configs, docs)\n- What was LEARNED through debugging, investigation, or testing\n- How systems work and why they behave the way they do\n- Changes in technical domains (auth, data, UI, infra, DevOps)\n\nUse outcome-focused verbs: implemented, fixed, deployed, configured, migrated, optimized, added, refactored, discovered, learned, debugged.\nOnly describe actions that are clearly supported by the observed context.\nNever invent file changes, API behavior, or code edits that are not explicitly present in the session evidence.", aa = "Skip routine operations WITHOUT learnings:\n- Empty status checks or listings (unless revealing important state)\n- Package installations with no errors or insights\n- Simple file reads with no discoveries\n- Repetitive operations already documented with no new findings\nIf nothing meaningful happened AND nothing was learned:\n- Output no <observation> blocks\n- Output <skip_summary reason=\"low-signal\"/> instead of a <summary> block.", oa = "Create narratives that tell the complete story:\n- Context: What was the problem or goal? What prompted this work?\n- Investigation: What was examined? What was discovered?\n- Learning: How does it work? Why does it exist? Any gotchas?\n- Implementation: What was changed? What does the code do now?\n- Impact: What's better? What does the system do differently?\n- Next steps: What remains? What should future sessions know?\n\nAim for ~120-400 words per significant work item.\nPrefer fewer, higher-signal observations over many small ones.\nInclude specific details when present: file paths, function names, configuration values.", sa = "Output only XML. Do not include commentary outside XML.\n\nALWAYS emit at least one <observation> block for any meaningful work. Observations are the PRIMARY output - they capture what was built, fixed, learned, or decided. Also emit a <summary> block to track session progress.\n\nPrefer fewer, more comprehensive observations over many small ones.", ca = `<observation>
3584
+ <type>[ ${na} ]</type>
3579
3585
  <title>[Short outcome-focused title - what was achieved or learned]</title>
3580
3586
  <subtitle>[One sentence explanation of the outcome (max 24 words)]</subtitle>
3581
3587
  <facts>
@@ -3594,11 +3600,11 @@ var ea = "bugfix, feature, refactor, change, discovery, decision, exploration",
3594
3600
  <files_modified>
3595
3601
  <file>[full path from project root]</file>
3596
3602
  </files_modified>
3597
- </observation>`, sa = "<summary>\n <request>[What did the user request?]</request>\n <investigated>[What was explored or examined?]</investigated>\n <learned>[What was learned about how things work?]</learned>\n <completed>[What work was done? What shipped?]</completed>\n <next_steps>[What are the logical next steps?]</next_steps>\n <notes>[Additional context, insights, or warnings.]</notes>\n <files_read>\n <file>[path]</file>\n </files_read>\n <files_modified>\n <file>[path]</file>\n </files_modified>\n</summary>\n\nIf nothing meaningful happened, emit <skip_summary reason=\"low-signal\"/> and do not emit <summary>.\nOtherwise, write a summary that explains the current state of the PRIMARY work.\n\nOnly summarize what is evidenced in the session context. Do not infer or fabricate\nfile edits, behaviors, or outcomes that are not explicitly observed.\n\nKeep summaries concise (aim for ~150-450 words total across all fields).";
3598
- function Z(e) {
3603
+ </observation>`, la = "<summary>\n <request>[What did the user request?]</request>\n <investigated>[What was explored or examined?]</investigated>\n <learned>[What was learned about how things work?]</learned>\n <completed>[What work was done? What shipped?]</completed>\n <next_steps>[What are the logical next steps?]</next_steps>\n <notes>[Additional context, insights, or warnings.]</notes>\n <files_read>\n <file>[path]</file>\n </files_read>\n <files_modified>\n <file>[path]</file>\n </files_modified>\n</summary>\n\nIf nothing meaningful happened, emit <skip_summary reason=\"low-signal\"/> and do not emit <summary>.\nOtherwise, write a summary that explains the current state of the PRIMARY work.\n\nOnly summarize what is evidenced in the session context. Do not infer or fabricate\nfile edits, behaviors, or outcomes that are not explicitly observed.\n\nKeep summaries concise (aim for ~150-450 words total across all fields).";
3604
+ function X(e) {
3599
3605
  return e.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
3600
3606
  }
3601
- function ca(e) {
3607
+ function ua(e) {
3602
3608
  if (e == null) return "";
3603
3609
  if (typeof e == "string") return e;
3604
3610
  try {
@@ -3607,43 +3613,43 @@ function ca(e) {
3607
3613
  return String(e);
3608
3614
  }
3609
3615
  }
3610
- function la(e) {
3616
+ function da(e) {
3611
3617
  let t = ["<observed_from_primary_session>"];
3612
- t.push(` <what_happened>${Z(e.toolName)}</what_happened>`), e.timestamp && t.push(` <occurred_at>${Z(e.timestamp)}</occurred_at>`), e.cwd && t.push(` <working_directory>${Z(e.cwd)}</working_directory>`);
3613
- let n = Z(ca(e.toolInput)), r = Z(ca(e.toolOutput)), i = Z(ca(e.toolError));
3618
+ t.push(` <what_happened>${X(e.toolName)}</what_happened>`), e.timestamp && t.push(` <occurred_at>${X(e.timestamp)}</occurred_at>`), e.cwd && t.push(` <working_directory>${X(e.cwd)}</working_directory>`);
3619
+ let n = X(ua(e.toolInput)), r = X(ua(e.toolOutput)), i = X(ua(e.toolError));
3614
3620
  return n && t.push(` <parameters>${n}</parameters>`), r && t.push(` <outcome>${r}</outcome>`), i && t.push(` <error>${i}</error>`), t.push("</observed_from_primary_session>"), t.join("\n");
3615
3621
  }
3616
- function ua(e) {
3622
+ function fa(e) {
3617
3623
  let t = [
3618
- ta,
3619
- "",
3620
- na,
3621
- "",
3622
3624
  ra,
3623
3625
  "",
3624
3626
  ia,
3625
3627
  "",
3626
3628
  aa,
3627
3629
  "",
3630
+ oa,
3631
+ "",
3632
+ sa,
3633
+ "",
3628
3634
  "Observation XML schema:",
3629
- oa
3635
+ ca
3630
3636
  ];
3631
- e.includeSummary && t.push("", "Summary XML schema:", sa);
3637
+ e.includeSummary && t.push("", "Summary XML schema:", la);
3632
3638
  let n = t.join("\n\n").trim(), r = ["Observed session context:"];
3633
3639
  if (e.userPrompt) {
3634
3640
  let t = ["<observed_from_primary_session>"];
3635
- t.push(` <user_request>${Z(e.userPrompt)}</user_request>`), e.promptNumber != null && t.push(` <prompt_number>${e.promptNumber}</prompt_number>`), e.project && t.push(` <project>${Z(e.project)}</project>`), t.push("</observed_from_primary_session>"), r.push(t.join("\n"));
3641
+ t.push(` <user_request>${X(e.userPrompt)}</user_request>`), e.promptNumber != null && t.push(` <prompt_number>${e.promptNumber}</prompt_number>`), e.project && t.push(` <project>${X(e.project)}</project>`), t.push("</observed_from_primary_session>"), r.push(t.join("\n"));
3636
3642
  }
3637
- e.diffSummary && r.push(`<observed_from_primary_session>\n <diff_summary>${Z(e.diffSummary)}</diff_summary>\n</observed_from_primary_session>`), e.recentFiles && r.push(`<observed_from_primary_session>\n <recent_files>${Z(e.recentFiles)}</recent_files>\n</observed_from_primary_session>`);
3638
- for (let t of e.toolEvents) r.push(la(t));
3639
- return e.includeSummary && e.lastAssistantMessage && (r.push("Summary context:"), r.push(`<summary_context>\n <assistant_response>${Z(e.lastAssistantMessage)}</assistant_response>\n</summary_context>`)), {
3643
+ e.diffSummary && r.push(`<observed_from_primary_session>\n <diff_summary>${X(e.diffSummary)}</diff_summary>\n</observed_from_primary_session>`), e.recentFiles && r.push(`<observed_from_primary_session>\n <recent_files>${X(e.recentFiles)}</recent_files>\n</observed_from_primary_session>`);
3644
+ for (let t of e.toolEvents) r.push(da(t));
3645
+ return e.includeSummary && e.lastAssistantMessage && (r.push("Summary context:"), r.push(`<summary_context>\n <assistant_response>${X(e.lastAssistantMessage)}</assistant_response>\n</summary_context>`)), {
3640
3646
  system: n,
3641
3647
  user: r.join("\n\n").trim()
3642
3648
  };
3643
3649
  }
3644
3650
  //#endregion
3645
3651
  //#region src/ingest-transcript.ts
3646
- var da = new Set([
3652
+ var pa = new Set([
3647
3653
  "yes",
3648
3654
  "y",
3649
3655
  "ok",
@@ -3658,20 +3664,20 @@ var da = new Set([
3658
3664
  "go ahead",
3659
3665
  "proceed"
3660
3666
  ]);
3661
- function fa(e) {
3667
+ function ma(e) {
3662
3668
  if (!e) return "";
3663
3669
  let t = e.trim().replace(/^["']+|["']+$/g, "").trim();
3664
3670
  return t = t.replace(/\s+/g, " "), t.toLowerCase();
3665
3671
  }
3666
- function pa(e) {
3667
- let t = fa(e);
3668
- return t ? da.has(t) : !0;
3672
+ function ha(e) {
3673
+ let t = ma(e);
3674
+ return t ? pa.has(t) : !0;
3669
3675
  }
3670
- function ma(e) {
3676
+ function ga(e) {
3671
3677
  let t = e.split("\n").map((e) => e.trim()).filter(Boolean).join(" ");
3672
3678
  return t = t.replace(/^[#*\-\d.\s]+/, ""), (t.split(/(?<=[.!?])\s+/)[0] ?? t).trim();
3673
3679
  }
3674
- function ha(e) {
3680
+ function _a(e) {
3675
3681
  let t = [
3676
3682
  e.completed,
3677
3683
  e.learned,
@@ -3679,24 +3685,24 @@ function ha(e) {
3679
3685
  e.nextSteps,
3680
3686
  e.notes
3681
3687
  ];
3682
- for (let e of t) if (e) return ma(e);
3688
+ for (let e of t) if (e) return ga(e);
3683
3689
  return "";
3684
3690
  }
3685
- function ga(e) {
3691
+ function va(e) {
3686
3692
  let t = [];
3687
3693
  for (let n of e) {
3688
3694
  let e = n.type;
3689
3695
  if (e === "user_prompt") {
3690
- let e = Oi(String(n.prompt_text ?? "")).trim();
3696
+ let e = Ai(String(n.prompt_text ?? "")).trim();
3691
3697
  e && t.push(`User: ${e}`);
3692
3698
  } else if (e === "assistant_message") {
3693
- let e = Oi(String(n.assistant_text ?? "")).trim();
3699
+ let e = Ai(String(n.assistant_text ?? "")).trim();
3694
3700
  e && t.push(`Assistant: ${e}`);
3695
3701
  }
3696
3702
  }
3697
3703
  return t.join("\n\n");
3698
3704
  }
3699
- function _a(e) {
3705
+ function ya(e) {
3700
3706
  let t = [];
3701
3707
  for (let n of e) {
3702
3708
  if (n.type !== "assistant_message") continue;
@@ -3705,7 +3711,7 @@ function _a(e) {
3705
3711
  }
3706
3712
  return t;
3707
3713
  }
3708
- function va(e) {
3714
+ function ba(e) {
3709
3715
  let t = [];
3710
3716
  for (let n of e) {
3711
3717
  if (n.type !== "assistant_usage") continue;
@@ -3722,7 +3728,7 @@ function va(e) {
3722
3728
  }
3723
3729
  return t;
3724
3730
  }
3725
- function ya(e) {
3731
+ function xa(e) {
3726
3732
  let t = [];
3727
3733
  for (let n of e) {
3728
3734
  if (n.type !== "user_prompt") continue;
@@ -3735,7 +3741,7 @@ function ya(e) {
3735
3741
  }
3736
3742
  return t;
3737
3743
  }
3738
- function ba(e) {
3744
+ function Sa(e) {
3739
3745
  return e.map((e) => {
3740
3746
  let t = e._adapter;
3741
3747
  if (typeof t != "object" || !t || Array.isArray(t)) return e;
@@ -3766,15 +3772,15 @@ function ba(e) {
3766
3772
  }
3767
3773
  //#endregion
3768
3774
  //#region src/ingest-xml-parser.ts
3769
- var xa = /<observation[^>]*>.*?<\/observation>/gs, Sa = /<summary[^>]*>.*?<\/summary>/gs, Ca = /<skip_summary(?:\s+reason="(?<reason>[^"]+)")?\s*\/>/i, wa = /```(?:xml)?/gi;
3770
- function Ta(e) {
3771
- return e.replace(wa, "").trim();
3775
+ var Ca = /<observation[^>]*>.*?<\/observation>/gs, wa = /<summary[^>]*>.*?<\/summary>/gs, Ta = /<skip_summary(?:\s+reason="(?<reason>[^"]+)")?\s*\/>/i, Ea = /```(?:xml)?/gi;
3776
+ function Da(e) {
3777
+ return e.replace(Ea, "").trim();
3772
3778
  }
3773
- function Q(e, t) {
3779
+ function Z(e, t) {
3774
3780
  let n = RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`, "i").exec(e);
3775
3781
  return n?.[1] ? n[1].trim() : "";
3776
3782
  }
3777
- function Ea(e, t, n) {
3783
+ function Oa(e, t, n) {
3778
3784
  let r = RegExp(`<${t}[^>]*>([\\s\\S]*?)</${t}>`, "i").exec(e);
3779
3785
  if (!r?.[1]) return [];
3780
3786
  let i = RegExp(`<${n}[^>]*>([\\s\\S]*?)</${n}>`, "gi"), a = [];
@@ -3784,21 +3790,21 @@ function Ea(e, t, n) {
3784
3790
  }
3785
3791
  return a;
3786
3792
  }
3787
- function Da(e) {
3788
- let t = Q(e, "type"), n = Q(e, "title");
3793
+ function ka(e) {
3794
+ let t = Z(e, "type"), n = Z(e, "title");
3789
3795
  return !t && !n ? null : {
3790
3796
  kind: t,
3791
3797
  title: n,
3792
- narrative: Q(e, "narrative"),
3793
- subtitle: Q(e, "subtitle") || null,
3794
- facts: Ea(e, "facts", "fact"),
3795
- concepts: Ea(e, "concepts", "concept"),
3796
- filesRead: Ea(e, "files_read", "file"),
3797
- filesModified: Ea(e, "files_modified", "file")
3798
+ narrative: Z(e, "narrative"),
3799
+ subtitle: Z(e, "subtitle") || null,
3800
+ facts: Oa(e, "facts", "fact"),
3801
+ concepts: Oa(e, "concepts", "concept"),
3802
+ filesRead: Oa(e, "files_read", "file"),
3803
+ filesModified: Oa(e, "files_modified", "file")
3798
3804
  };
3799
3805
  }
3800
- function Oa(e) {
3801
- let t = Q(e, "request"), n = Q(e, "investigated"), r = Q(e, "learned"), i = Q(e, "completed"), a = Q(e, "next_steps"), o = Q(e, "notes");
3806
+ function Aa(e) {
3807
+ let t = Z(e, "request"), n = Z(e, "investigated"), r = Z(e, "learned"), i = Z(e, "completed"), a = Z(e, "next_steps"), o = Z(e, "notes");
3802
3808
  return !t && !n && !r && !i && !a && !o ? null : {
3803
3809
  request: t,
3804
3810
  investigated: n,
@@ -3806,31 +3812,31 @@ function Oa(e) {
3806
3812
  completed: i,
3807
3813
  nextSteps: a,
3808
3814
  notes: o,
3809
- filesRead: Ea(e, "files_read", "file"),
3810
- filesModified: Ea(e, "files_modified", "file")
3815
+ filesRead: Oa(e, "files_read", "file"),
3816
+ filesModified: Oa(e, "files_modified", "file")
3811
3817
  };
3812
3818
  }
3813
- function ka(e) {
3814
- let t = Ta(e), n = [], r = t.match(xa) ?? [];
3819
+ function ja(e) {
3820
+ let t = Da(e), n = [], r = t.match(Ca) ?? [];
3815
3821
  for (let e of r) {
3816
- let t = Da(e);
3822
+ let t = ka(e);
3817
3823
  t && n.push(t);
3818
3824
  }
3819
- let i = null, a = (t.match(Sa) ?? []).at(-1);
3820
- a && (i = Oa(a));
3821
- let o = Ca.exec(t)?.groups?.reason ?? null;
3825
+ let i = null, a = (t.match(wa) ?? []).at(-1);
3826
+ a && (i = Aa(a));
3827
+ let o = Ta.exec(t)?.groups?.reason ?? null;
3822
3828
  return {
3823
3829
  observations: n,
3824
3830
  summary: i,
3825
3831
  skipSummaryReason: o
3826
3832
  };
3827
3833
  }
3828
- function Aa(e) {
3834
+ function Ma(e) {
3829
3835
  return e.some((e) => e.title || e.narrative);
3830
3836
  }
3831
3837
  //#endregion
3832
3838
  //#region src/ingest-pipeline.ts
3833
- var ja = new Set([
3839
+ var Na = new Set([
3834
3840
  "bugfix",
3835
3841
  "feature",
3836
3842
  "refactor",
@@ -3839,17 +3845,17 @@ var ja = new Set([
3839
3845
  "decision",
3840
3846
  "exploration"
3841
3847
  ]);
3842
- function Ma(e, t) {
3848
+ function Pa(e, t) {
3843
3849
  if (!e) return "";
3844
3850
  let n = e.trim();
3845
3851
  if (!t) return n;
3846
3852
  let r = t.replace(/\/+$/, "");
3847
3853
  return n === r ? "." : n.startsWith(`${r}/`) ? n.slice(r.length + 1) : n;
3848
3854
  }
3849
- function Na(e, t) {
3850
- return e.map((e) => Ma(e, t)).filter(Boolean);
3855
+ function Fa(e, t) {
3856
+ return e.map((e) => Pa(e, t)).filter(Boolean);
3851
3857
  }
3852
- function Pa(e) {
3858
+ function Ia(e) {
3853
3859
  return [
3854
3860
  ["Request", e.request],
3855
3861
  ["Completed", e.completed],
@@ -3859,27 +3865,27 @@ function Pa(e) {
3859
3865
  ["Notes", e.notes]
3860
3866
  ].filter(([, e]) => e).map(([e, t]) => `## ${e}\n${t}`).join("\n\n");
3861
3867
  }
3862
- function Fa(e, t) {
3868
+ function La(e, t) {
3863
3869
  let n = [];
3864
3870
  for (let r of e) {
3865
- let e = Gi(r);
3871
+ let e = qi(r);
3866
3872
  if (e) {
3867
3873
  if (e.event_type === "tool_call") continue;
3868
- let i = Ki(e, r);
3874
+ let i = Ji(e, r);
3869
3875
  if (i) {
3870
- let e = Ui(i, t);
3876
+ let e = Gi(i, t);
3871
3877
  if (e) {
3872
3878
  n.push(e);
3873
3879
  continue;
3874
3880
  }
3875
3881
  }
3876
3882
  }
3877
- let i = Wi([r], t);
3883
+ let i = Ki([r], t);
3878
3884
  n.push(...i);
3879
3885
  }
3880
3886
  return n;
3881
3887
  }
3882
- async function Ia(e, t, n) {
3888
+ async function Ra(e, t, n) {
3883
3889
  let r = e.cwd ?? process.cwd(), i = e.events ?? [];
3884
3890
  if (!Array.isArray(i) || i.length === 0) return;
3885
3891
  let a = e.sessionContext ?? {}, o = n.storeSummary ?? !0, s = n.storeTyped ?? !0, c = n.maxChars ?? 12e3, l = n.observerMaxChars ?? 12e3, u = j(t.db, { schema: R }), d = (/* @__PURE__ */ new Date()).toISOString(), f = e.project ?? null, p = u.insert(z).values({
@@ -3888,7 +3894,7 @@ async function Ia(e, t, n) {
3888
3894
  project: f,
3889
3895
  user: process.env.USER ?? "unknown",
3890
3896
  tool_version: "plugin-ts",
3891
- metadata_json: Y({
3897
+ metadata_json: J({
3892
3898
  source: "plugin",
3893
3899
  event_count: i.length,
3894
3900
  started_at: e.startedAt,
@@ -3897,14 +3903,14 @@ async function Ia(e, t, n) {
3897
3903
  }).returning({ id: z.id }).all()[0]?.id;
3898
3904
  if (p == null) throw Error("session insert returned no id");
3899
3905
  try {
3900
- let e = ba(i), d = ya(e), m = d.length > 0 ? d[d.length - 1]?.promptNumber ?? d.length : null, h = Fa(i, c), g = Math.max(2e3, Math.min(8e3, l - 5e3));
3901
- h = Xi(h, g, 30);
3902
- let _ = _a(e), v = va(e), y = _.at(-1) ?? null, b = a.firstPrompt ?? (d.length > 0 ? d[d.length - 1]?.promptText : null) ?? null, x = h.length > 0 || !!b || o && !!y;
3903
- if (b && pa(b) && h.length === 0 && !y && (x = !1), !x) {
3904
- La(t, p, i.length, a);
3906
+ let e = Sa(i), d = xa(e), m = d.length > 0 ? d[d.length - 1]?.promptNumber ?? d.length : null, h = La(i, c), g = Math.max(2e3, Math.min(8e3, l - 5e3));
3907
+ h = Qi(h, g, 30);
3908
+ let _ = ya(e), v = ba(e), y = _.at(-1) ?? null, b = a.firstPrompt ?? (d.length > 0 ? d[d.length - 1]?.promptText : null) ?? null, x = h.length > 0 || !!b || o && !!y;
3909
+ if (b && ha(b) && h.length === 0 && !y && (x = !1), !x) {
3910
+ za(t, p, i.length, a);
3905
3911
  return;
3906
3912
  }
3907
- let S = ga(e), C = [];
3913
+ let S = va(e), C = [];
3908
3914
  if ((a.promptCount ?? 0) > 1 && C.push(`Session had ${a.promptCount} prompts`), (a.toolCount ?? 0) > 0 && C.push(`${a.toolCount} tool executions`), (a.durationMs ?? 0) > 0) {
3909
3915
  let e = (a.durationMs ?? 0) / 6e4;
3910
3916
  C.push(`~${e.toFixed(1)} minutes of work`);
@@ -3912,7 +3918,7 @@ async function Ia(e, t, n) {
3912
3918
  a.filesModified?.length && C.push(`Modified: ${a.filesModified.slice(0, 5).join(", ")}`), a.filesRead?.length && C.push(`Read: ${a.filesRead.slice(0, 5).join(", ")}`);
3913
3919
  let w = C.join("; "), T = b ?? "";
3914
3920
  w && (T = T ? `${T}\n\n[Session context: ${w}]` : `[Session context: ${w}]`);
3915
- let { system: ee, user: E } = ua({
3921
+ let { system: ee, user: E } = fa({
3916
3922
  project: f,
3917
3923
  userPrompt: T,
3918
3924
  promptNumber: m,
@@ -3925,15 +3931,15 @@ async function Ia(e, t, n) {
3925
3931
  if (!D.raw) {
3926
3932
  if (a?.flusher === "raw_events") throw Error("observer failed during raw-event flush");
3927
3933
  let e = n.observer.getStatus();
3928
- console.warn(`[codemem] Observer returned no output (provider=${D.provider}, model=${D.model}${e.lastError ? `, error=${e.lastError}` : ""}). No memories will be created for this session.`), La(t, p, i.length, a);
3934
+ console.warn(`[codemem] Observer returned no output (provider=${D.provider}, model=${D.model}${e.lastError ? `, error=${e.lastError}` : ""}). No memories will be created for this session.`), za(t, p, i.length, a);
3929
3935
  return;
3930
3936
  }
3931
- let O = D.raw, k = ka(O);
3937
+ let O = D.raw, k = ja(O);
3932
3938
  t.db.transaction(() => {
3933
- if (s && Aa(k.observations)) for (let e of k.observations) {
3939
+ if (s && Ma(k.observations)) for (let e of k.observations) {
3934
3940
  let n = e.kind.trim().toLowerCase();
3935
- if (!ja.has(n) || !e.title && !e.narrative || $i(e.title) || $i(e.narrative)) continue;
3936
- let i = Na(e.filesRead, r), a = Na(e.filesModified, r), o = [];
3941
+ if (!Na.has(n) || !e.title && !e.narrative || ta(e.title) || ta(e.narrative)) continue;
3942
+ let i = Fa(e.filesRead, r), a = Fa(e.filesModified, r), o = [];
3937
3943
  e.narrative && o.push(e.narrative), e.facts.length > 0 && o.push(e.facts.map((e) => `- ${e}`).join("\n"));
3938
3944
  let s = o.join("\n\n");
3939
3945
  t.remember(p, n, e.title || e.narrative, s, .5, void 0, {
@@ -3949,14 +3955,14 @@ async function Ia(e, t, n) {
3949
3955
  if (o && k.summary && !k.skipSummaryReason) {
3950
3956
  let e = k.summary;
3951
3957
  if (e.request || e.investigated || e.learned || e.completed || e.nextSteps || e.notes) {
3952
- e.filesRead = Na(e.filesRead, r), e.filesModified = Na(e.filesModified, r);
3958
+ e.filesRead = Fa(e.filesRead, r), e.filesModified = Fa(e.filesModified, r);
3953
3959
  let n = e.request;
3954
- if (pa(n)) {
3955
- let t = ha(e);
3960
+ if (ha(n)) {
3961
+ let t = _a(e);
3956
3962
  t && (n = t);
3957
3963
  }
3958
- let i = Pa(e);
3959
- i && !$i(ma(i)) && t.remember(p, "change", n || "Session summary", i, .3, void 0, {
3964
+ let i = Ia(e);
3965
+ i && !ta(ga(i)) && t.remember(p, "change", n || "Session summary", i, .3, void 0, {
3960
3966
  is_summary: !0,
3961
3967
  prompt_number: m,
3962
3968
  files_read: e.filesRead,
@@ -3972,7 +3978,7 @@ async function Ia(e, t, n) {
3972
3978
  tokens_read: O.length,
3973
3979
  tokens_written: S.length,
3974
3980
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
3975
- metadata_json: Y({
3981
+ metadata_json: J({
3976
3982
  project: f,
3977
3983
  observation_count: k.observations.length,
3978
3984
  has_summary: k.summary != null,
@@ -3981,15 +3987,15 @@ async function Ia(e, t, n) {
3981
3987
  session_usage_tokens: e
3982
3988
  })
3983
3989
  }).run();
3984
- })(), La(t, p, i.length, a);
3990
+ })(), za(t, p, i.length, a);
3985
3991
  } catch (e) {
3986
3992
  try {
3987
- La(t, p, i.length, a);
3993
+ za(t, p, i.length, a);
3988
3994
  } catch {}
3989
3995
  throw e;
3990
3996
  }
3991
3997
  }
3992
- function La(e, t, n, r) {
3998
+ function za(e, t, n, r) {
3993
3999
  e.endSession(t, {
3994
4000
  post: {},
3995
4001
  source: "plugin",
@@ -3997,11 +4003,11 @@ function La(e, t, n, r) {
3997
4003
  session_context: r
3998
4004
  });
3999
4005
  }
4000
- function Ra(e, t = 24) {
4006
+ function Ba(e, t = 24) {
4001
4007
  let n = j(e.db, { schema: R }), r = (/* @__PURE__ */ new Date(Date.now() - t * 36e5)).toISOString();
4002
4008
  return n.update(z).set({ ended_at: r }).where(E(ne(z.ended_at), re(z.started_at, r))).run().changes;
4003
4009
  }
4004
- async function za(e, t) {
4010
+ async function Va(e, t) {
4005
4011
  let n = [];
4006
4012
  for await (let e of process.stdin) n.push(String(e));
4007
4013
  let r = n.join("");
@@ -4012,30 +4018,30 @@ async function za(e, t) {
4012
4018
  } catch (e) {
4013
4019
  throw Error(`codemem: invalid payload: ${e}`);
4014
4020
  }
4015
- await Ia(i, e, { observer: t });
4021
+ await Ra(i, e, { observer: t });
4016
4022
  }
4017
4023
  //#endregion
4018
4024
  //#region src/integers.ts
4019
- var Ba = BigInt(2 ** 53 - 1), Va = BigInt(-(2 ** 53 - 1));
4020
- function Ha(e) {
4025
+ var Ha = BigInt(2 ** 53 - 1), Ua = BigInt(-(2 ** 53 - 1));
4026
+ function Wa(e) {
4021
4027
  if (e == null) return null;
4022
4028
  let t = e.trim();
4023
4029
  if (!/^[+-]?\d+$/.test(t)) return null;
4024
4030
  try {
4025
4031
  let e = BigInt(t);
4026
- return e < Va || e > Ba ? null : Number(e);
4032
+ return e < Ua || e > Ha ? null : Number(e);
4027
4033
  } catch {
4028
4034
  return null;
4029
4035
  }
4030
4036
  }
4031
- function Ua(e) {
4037
+ function Ga(e) {
4032
4038
  if (typeof e == "boolean") return null;
4033
4039
  if (typeof e == "number") return !Number.isInteger(e) || !Number.isSafeInteger(e) || e <= 0 ? null : e;
4034
4040
  if (typeof e == "string") {
4035
4041
  if (!/^\d+$/.test(e)) return null;
4036
4042
  try {
4037
4043
  let t = BigInt(e);
4038
- return t <= 0n || t > Ba ? null : Number(t);
4044
+ return t <= 0n || t > Ha ? null : Number(t);
4039
4045
  } catch {
4040
4046
  return null;
4041
4047
  }
@@ -4044,28 +4050,28 @@ function Ua(e) {
4044
4050
  }
4045
4051
  //#endregion
4046
4052
  //#region src/maintenance.ts
4047
- function Wa(e, t) {
4048
- let n = zn(e), r = Wn(n);
4053
+ function Ka(e, t) {
4054
+ let n = Bn(e), r = Gn(n);
4049
4055
  try {
4050
- return Yn(r), t(r, n);
4056
+ return Xn(r), t(r, n);
4051
4057
  } finally {
4052
4058
  r.close();
4053
4059
  }
4054
4060
  }
4055
- function Ga(e) {
4056
- return Wa(e, (e, t) => ({
4061
+ function qa(e) {
4062
+ return Ka(e, (e, t) => ({
4057
4063
  path: t,
4058
4064
  sizeBytes: m(t).size
4059
4065
  }));
4060
4066
  }
4061
- function Ka(e) {
4062
- return Wa(e, (e, t) => (e.exec("VACUUM"), {
4067
+ function Ja(e) {
4068
+ return Ka(e, (e, t) => (e.exec("VACUUM"), {
4063
4069
  path: t,
4064
4070
  sizeBytes: m(t).size
4065
4071
  }));
4066
4072
  }
4067
- function qa(e, t = 25) {
4068
- return Wa(e, (e) => {
4073
+ function Ya(e, t = 25) {
4074
+ return Ka(e, (e) => {
4069
4075
  let n = e.prepare("WITH max_events AS (\n SELECT source, stream_id, MAX(event_seq) AS max_seq\n FROM raw_events\n GROUP BY source, stream_id\n )\n SELECT s.source, s.stream_id, s.opencode_session_id, s.cwd, s.project,\n s.started_at, s.last_seen_ts_wall_ms,\n s.last_received_event_seq, s.last_flushed_event_seq, s.updated_at\n FROM raw_event_sessions s\n JOIN max_events e ON e.source = s.source AND e.stream_id = s.stream_id\n WHERE e.max_seq > s.last_flushed_event_seq\n ORDER BY s.updated_at DESC\n LIMIT ?").all(t).map((e) => {
4070
4076
  let t = String(e.stream_id ?? e.opencode_session_id ?? "");
4071
4077
  return {
@@ -4097,8 +4103,8 @@ function qa(e, t = 25) {
4097
4103
  };
4098
4104
  });
4099
4105
  }
4100
- function Ja(e, t) {
4101
- return Wa(e, (e) => {
4106
+ function Xa(e, t) {
4107
+ return Ka(e, (e) => {
4102
4108
  let n = t == null ? null : (/* @__PURE__ */ new Date(Date.now() - t * 3600 * 1e3)).toISOString(), r = `
4103
4109
  SELECT
4104
4110
  COALESCE(SUM(CASE WHEN status IN ('started', 'pending') THEN 1 ELSE 0 END), 0) AS started,
@@ -4151,40 +4157,40 @@ function Ja(e, t) {
4151
4157
  };
4152
4158
  });
4153
4159
  }
4154
- function Ya(e, t) {
4155
- let n = t?.minFlushSuccessRate ?? .95, r = t?.maxDroppedEventRate ?? .05, i = t?.minSessionBoundaryAccuracy ?? .9, a = Ja(e, t?.windowHours ?? 24), o = [];
4160
+ function Za(e, t) {
4161
+ let n = t?.minFlushSuccessRate ?? .95, r = t?.maxDroppedEventRate ?? .05, i = t?.minSessionBoundaryAccuracy ?? .9, a = Xa(e, t?.windowHours ?? 24), o = [];
4156
4162
  return a.rates.flush_success_rate < n && o.push(`flush_success_rate=${a.rates.flush_success_rate.toFixed(4)} < min ${n.toFixed(4)}`), a.rates.dropped_event_rate > r && o.push(`dropped_event_rate=${a.rates.dropped_event_rate.toFixed(4)} > max ${r.toFixed(4)}`), a.rates.session_boundary_accuracy < i && o.push(`session_boundary_accuracy=${a.rates.session_boundary_accuracy.toFixed(4)} < min ${i.toFixed(4)}`), {
4157
4163
  passed: o.length === 0,
4158
4164
  failures: o,
4159
4165
  metrics: a
4160
4166
  };
4161
4167
  }
4162
- function Xa(e, t = 25) {
4163
- return Wa(e, (e) => {
4168
+ function Qa(e, t = 25) {
4169
+ return Ka(e, (e) => {
4164
4170
  let n = (/* @__PURE__ */ new Date()).toISOString();
4165
4171
  return { retried: e.prepare("UPDATE raw_event_flush_batches\n SET status = 'pending',\n updated_at = ?,\n error_message = NULL,\n error_type = NULL,\n observer_provider = NULL,\n observer_model = NULL,\n observer_runtime = NULL\n WHERE id IN (\n SELECT id FROM raw_event_flush_batches\n WHERE status IN ('failed', 'error')\n ORDER BY updated_at ASC\n LIMIT ?\n )").run(n, t).changes };
4166
4172
  });
4167
4173
  }
4168
4174
  //#endregion
4169
4175
  //#region src/observer-auth.ts
4170
- var Za = "0.0.1", Qa = [/sk-[A-Za-z0-9]{10,}/g, /Bearer\s+[A-Za-z0-9._-]{10,}/g];
4171
- function $a(e, t = 400) {
4176
+ var $a = "0.0.1", eo = [/sk-[A-Za-z0-9]{10,}/g, /Bearer\s+[A-Za-z0-9._-]{10,}/g];
4177
+ function to(e, t = 400) {
4172
4178
  let n = e;
4173
- for (let e of Qa) n = n.replace(new RegExp(e.source, e.flags), "[redacted]");
4179
+ for (let e of eo) n = n.replace(new RegExp(e.source, e.flags), "[redacted]");
4174
4180
  return n.length > t ? `${n.slice(0, t)}…` : n;
4175
4181
  }
4176
- function eo() {
4182
+ function no() {
4177
4183
  return {
4178
4184
  token: null,
4179
4185
  authType: "none",
4180
4186
  source: "none"
4181
4187
  };
4182
4188
  }
4183
- function to() {
4189
+ function ro() {
4184
4190
  return w(v(), ".local", "share", "opencode", "auth.json");
4185
4191
  }
4186
- function no() {
4187
- let e = to();
4192
+ function io() {
4193
+ let e = ro();
4188
4194
  if (!l(e)) return {};
4189
4195
  try {
4190
4196
  let t = JSON.parse(f(e, "utf-8"));
@@ -4193,33 +4199,33 @@ function no() {
4193
4199
  return {};
4194
4200
  }
4195
4201
  }
4196
- function ro(e, t) {
4202
+ function ao(e, t) {
4197
4203
  return e && ["openai", "anthropic"].includes(e.toLowerCase()) ? e.toLowerCase() : t.toLowerCase().startsWith("claude") ? "anthropic" : "openai";
4198
4204
  }
4199
- function io(e, t) {
4205
+ function oo(e, t) {
4200
4206
  let n = e[t];
4201
4207
  return typeof n == "object" && n && !Array.isArray(n) ? n : null;
4202
4208
  }
4203
- function ao(e, t) {
4204
- let n = io(e, t);
4209
+ function so(e, t) {
4210
+ let n = oo(e, t);
4205
4211
  if (!n) return null;
4206
4212
  let r = n.access;
4207
4213
  return typeof r == "string" && r ? r : null;
4208
4214
  }
4209
- function oo(e, t) {
4210
- let n = io(e, t);
4215
+ function co(e, t) {
4216
+ let n = oo(e, t);
4211
4217
  if (!n) return null;
4212
4218
  let r = n.accountId;
4213
4219
  return typeof r == "string" && r ? r : null;
4214
4220
  }
4215
- function so(e, t) {
4216
- let n = io(e, t);
4221
+ function lo(e, t) {
4222
+ let n = oo(e, t);
4217
4223
  if (!n) return null;
4218
4224
  let r = n.expires;
4219
4225
  return typeof r == "number" ? r : null;
4220
4226
  }
4221
- function co(e, t) {
4222
- let n = process.env.CODEMEM_CODEX_ORIGINATOR ?? "opencode", r = process.env.CODEMEM_CODEX_USER_AGENT ?? `codemem/${Za} (${y()} ${b()}; ${_()})`, i = {
4227
+ function uo(e, t) {
4228
+ let n = process.env.CODEMEM_CODEX_ORIGINATOR ?? "opencode", r = process.env.CODEMEM_CODEX_USER_AGENT ?? `codemem/${$a} (${y()} ${b()}; ${_()})`, i = {
4223
4229
  authorization: `Bearer ${e}`,
4224
4230
  originator: n,
4225
4231
  "User-Agent": r,
@@ -4227,7 +4233,7 @@ function co(e, t) {
4227
4233
  };
4228
4234
  return t && (i["ChatGPT-Account-Id"] = t), i;
4229
4235
  }
4230
- function lo(e, t) {
4236
+ function fo(e, t) {
4231
4237
  let n = e[0];
4232
4238
  if (!n) return null;
4233
4239
  let r = Math.max(100, t);
@@ -4245,7 +4251,7 @@ function lo(e, t) {
4245
4251
  return null;
4246
4252
  }
4247
4253
  }
4248
- function uo(e) {
4254
+ function po(e) {
4249
4255
  if (!e) return null;
4250
4256
  let t = e.replace(/^~/, v());
4251
4257
  t = t.replace(/\$\{([^}]+)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (e, t, n) => {
@@ -4258,7 +4264,7 @@ function uo(e) {
4258
4264
  return null;
4259
4265
  }
4260
4266
  }
4261
- var fo = new Set([
4267
+ var mo = new Set([
4262
4268
  "",
4263
4269
  "auto",
4264
4270
  "env",
@@ -4266,47 +4272,47 @@ var fo = new Set([
4266
4272
  "command",
4267
4273
  "none"
4268
4274
  ]);
4269
- function po(e) {
4275
+ function ho(e) {
4270
4276
  let t = (e ?? "").trim().toLowerCase();
4271
- return fo.has(t) && t || "auto";
4277
+ return mo.has(t) && t || "auto";
4272
4278
  }
4273
- var mo = class {
4279
+ var go = class {
4274
4280
  source;
4275
4281
  filePath;
4276
4282
  command;
4277
4283
  timeoutMs;
4278
4284
  cacheTtlS;
4279
- cached = eo();
4285
+ cached = no();
4280
4286
  cachedAtMs = 0;
4281
4287
  constructor(e) {
4282
4288
  this.source = e?.source ?? "auto", this.filePath = e?.filePath ?? null, this.command = e?.command ?? [], this.timeoutMs = e?.timeoutMs ?? 1500, this.cacheTtlS = e?.cacheTtlS ?? 300;
4283
4289
  }
4284
4290
  resolve(e) {
4285
- let t = po(this.source), n = e?.explicitToken ?? null, r = e?.envTokens ?? [], i = e?.oauthToken ?? null, a = e?.forceRefresh ?? !1;
4286
- if (t === "none") return eo();
4291
+ let t = ho(this.source), n = e?.explicitToken ?? null, r = e?.envTokens ?? [], i = e?.oauthToken ?? null, a = e?.forceRefresh ?? !1;
4292
+ if (t === "none") return no();
4287
4293
  if (!a && (t === "command" || t === "file") && this.cacheTtlS > 0) {
4288
4294
  let e = performance.now() - this.cachedAtMs;
4289
4295
  if (this.cachedAtMs > 0 && e <= this.cacheTtlS * 1e3) return this.cached;
4290
4296
  }
4291
4297
  let o = null, s = "none";
4292
- t === "auto" ? (n && (o = n, s = "explicit"), o || (o = r.find((e) => !!e) ?? null, o && (s = "env")), !o && i && (o = i, s = "oauth")) : t === "env" && (o = r.find((e) => !!e) ?? null, o && (s = "env")), (t === "auto" || t === "file") && !o && (o = uo(this.filePath), o && (s = "file")), (t === "auto" || t === "command") && !o && (o = lo(this.command, this.timeoutMs), o && (s = "command"));
4298
+ t === "auto" ? (n && (o = n, s = "explicit"), o || (o = r.find((e) => !!e) ?? null, o && (s = "env")), !o && i && (o = i, s = "oauth")) : t === "env" && (o = r.find((e) => !!e) ?? null, o && (s = "env")), (t === "auto" || t === "file") && !o && (o = po(this.filePath), o && (s = "file")), (t === "auto" || t === "command") && !o && (o = fo(this.command, this.timeoutMs), o && (s = "command"));
4293
4299
  let c = o ? {
4294
4300
  token: o,
4295
4301
  authType: "bearer",
4296
4302
  source: s
4297
- } : eo(), l = t === "command" || t === "file";
4303
+ } : no(), l = t === "command" || t === "file";
4298
4304
  return l && c.token ? (this.cached = c, this.cachedAtMs = performance.now()) : l && this.invalidateCache(), c;
4299
4305
  }
4300
4306
  invalidateCache() {
4301
- this.cached = eo(), this.cachedAtMs = 0;
4307
+ this.cached = no(), this.cachedAtMs = 0;
4302
4308
  }
4303
- }, ho = /\$\{auth\.token\}/g, go = /\$\{auth\.type\}/g, _o = /\$\{auth\.source\}/g;
4304
- function vo(e, t) {
4309
+ }, _o = /\$\{auth\.token\}/g, vo = /\$\{auth\.type\}/g, yo = /\$\{auth\.source\}/g;
4310
+ function bo(e, t) {
4305
4311
  let n = t.token ?? "", r = {};
4306
4312
  for (let [i, a] of Object.entries(e)) {
4307
4313
  if (typeof i != "string" || typeof a != "string") continue;
4308
- let e = a.replace(ho, n);
4309
- if (e = e.replace(go, t.authType), e = e.replace(_o, t.source), a.includes("${auth.token}") && !n) continue;
4314
+ let e = a.replace(_o, n);
4315
+ if (e = e.replace(vo, t.authType), e = e.replace(yo, t.source), a.includes("${auth.token}") && !n) continue;
4310
4316
  let o = e.trim();
4311
4317
  o && (r[i] = o);
4312
4318
  }
@@ -4314,7 +4320,7 @@ function vo(e, t) {
4314
4320
  }
4315
4321
  //#endregion
4316
4322
  //#region src/observer-client.ts
4317
- var yo = "claude-sonnet-4-20250514", bo = "gpt-4.1-mini", xo = "https://api.anthropic.com/v1/messages", So = "2023-06-01", Co = "https://chatgpt.com/backend-api/codex/responses", wo = 6e4, To = {
4323
+ var xo = "claude-sonnet-4-20250514", So = "gpt-4.1-mini", Co = "https://api.anthropic.com/v1/messages", wo = "2023-06-01", To = "https://chatgpt.com/backend-api/codex/responses", Eo = 6e4, Do = {
4318
4324
  "claude-4.5-haiku": "claude-haiku-4-5",
4319
4325
  "claude-4.5-sonnet": "claude-sonnet-4-5",
4320
4326
  "claude-4.5-opus": "claude-opus-4-5",
@@ -4324,12 +4330,12 @@ var yo = "claude-sonnet-4-20250514", bo = "gpt-4.1-mini", xo = "https://api.anth
4324
4330
  "claude-4.0-sonnet": "claude-sonnet-4-0",
4325
4331
  "claude-4.0-opus": "claude-opus-4-0"
4326
4332
  };
4327
- function Eo(e, t) {
4333
+ function Oo(e, t) {
4328
4334
  if (e == null) return t;
4329
4335
  let n = typeof e == "string" ? Number.parseInt(e, 10) : Number(e);
4330
4336
  return Number.isFinite(n) ? n : t;
4331
4337
  }
4332
- function Do(e) {
4338
+ function ko(e) {
4333
4339
  if (e == null) return null;
4334
4340
  if (typeof e == "string") {
4335
4341
  let t = e.trim();
@@ -4343,7 +4349,7 @@ function Do(e) {
4343
4349
  }
4344
4350
  return typeof e == "object" && !Array.isArray(e) ? e : null;
4345
4351
  }
4346
- function Oo(e) {
4352
+ function Ao(e) {
4347
4353
  if (e == null) return null;
4348
4354
  if (Array.isArray(e)) return e.every((e) => typeof e == "string") ? e : null;
4349
4355
  if (typeof e == "string") {
@@ -4357,7 +4363,7 @@ function Oo(e) {
4357
4363
  }
4358
4364
  return null;
4359
4365
  }
4360
- function ko() {
4366
+ function jo() {
4361
4367
  let e = {
4362
4368
  observerProvider: null,
4363
4369
  observerModel: null,
@@ -4381,7 +4387,7 @@ function ko() {
4381
4387
  try {
4382
4388
  i = JSON.parse(e);
4383
4389
  } catch {
4384
- e = pn(fn(e)), i = JSON.parse(e);
4390
+ e = mn(pn(e)), i = JSON.parse(e);
4385
4391
  }
4386
4392
  (typeof i != "object" || !i || Array.isArray(i)) && (i = {});
4387
4393
  }
@@ -4389,41 +4395,41 @@ function ko() {
4389
4395
  i = {};
4390
4396
  }
4391
4397
  let a = { ...e };
4392
- typeof i.observer_provider == "string" && (a.observerProvider = i.observer_provider), typeof i.observer_model == "string" && (a.observerModel = i.observer_model), typeof i.observer_runtime == "string" && (a.observerRuntime = i.observer_runtime), typeof i.observer_api_key == "string" && (a.observerApiKey = i.observer_api_key), typeof i.observer_base_url == "string" && (a.observerBaseUrl = i.observer_base_url), a.observerMaxChars = Eo(i.observer_max_chars, a.observerMaxChars), a.observerMaxTokens = Eo(i.observer_max_tokens, a.observerMaxTokens), typeof i.observer_auth_source == "string" && (a.observerAuthSource = i.observer_auth_source), typeof i.observer_auth_file == "string" && (a.observerAuthFile = i.observer_auth_file), a.observerAuthTimeoutMs = Eo(i.observer_auth_timeout_ms, a.observerAuthTimeoutMs), a.observerAuthCacheTtlS = Eo(i.observer_auth_cache_ttl_s, a.observerAuthCacheTtlS);
4393
- let o = Do(i.observer_headers);
4398
+ typeof i.observer_provider == "string" && (a.observerProvider = i.observer_provider), typeof i.observer_model == "string" && (a.observerModel = i.observer_model), typeof i.observer_runtime == "string" && (a.observerRuntime = i.observer_runtime), typeof i.observer_api_key == "string" && (a.observerApiKey = i.observer_api_key), typeof i.observer_base_url == "string" && (a.observerBaseUrl = i.observer_base_url), a.observerMaxChars = Oo(i.observer_max_chars, a.observerMaxChars), a.observerMaxTokens = Oo(i.observer_max_tokens, a.observerMaxTokens), typeof i.observer_auth_source == "string" && (a.observerAuthSource = i.observer_auth_source), typeof i.observer_auth_file == "string" && (a.observerAuthFile = i.observer_auth_file), a.observerAuthTimeoutMs = Oo(i.observer_auth_timeout_ms, a.observerAuthTimeoutMs), a.observerAuthCacheTtlS = Oo(i.observer_auth_cache_ttl_s, a.observerAuthCacheTtlS);
4399
+ let o = ko(i.observer_headers);
4394
4400
  o && (a.observerHeaders = o);
4395
- let s = Oo(i.observer_auth_command);
4396
- s && (a.observerAuthCommand = s), a.observerProvider = process.env.CODEMEM_OBSERVER_PROVIDER ?? a.observerProvider, a.observerModel = process.env.CODEMEM_OBSERVER_MODEL ?? a.observerModel, a.observerRuntime = process.env.CODEMEM_OBSERVER_RUNTIME ?? a.observerRuntime, a.observerApiKey = process.env.CODEMEM_OBSERVER_API_KEY ?? a.observerApiKey, a.observerBaseUrl = process.env.CODEMEM_OBSERVER_BASE_URL ?? a.observerBaseUrl, a.observerAuthSource = process.env.CODEMEM_OBSERVER_AUTH_SOURCE ?? a.observerAuthSource, a.observerAuthFile = process.env.CODEMEM_OBSERVER_AUTH_FILE ?? a.observerAuthFile, a.observerMaxChars = Eo(process.env.CODEMEM_OBSERVER_MAX_CHARS, a.observerMaxChars), a.observerMaxTokens = Eo(process.env.CODEMEM_OBSERVER_MAX_TOKENS, a.observerMaxTokens), a.observerAuthTimeoutMs = Eo(process.env.CODEMEM_OBSERVER_AUTH_TIMEOUT_MS, a.observerAuthTimeoutMs), a.observerAuthCacheTtlS = Eo(process.env.CODEMEM_OBSERVER_AUTH_CACHE_TTL_S, a.observerAuthCacheTtlS);
4397
- let c = Do(process.env.CODEMEM_OBSERVER_HEADERS);
4401
+ let s = Ao(i.observer_auth_command);
4402
+ s && (a.observerAuthCommand = s), a.observerProvider = process.env.CODEMEM_OBSERVER_PROVIDER ?? a.observerProvider, a.observerModel = process.env.CODEMEM_OBSERVER_MODEL ?? a.observerModel, a.observerRuntime = process.env.CODEMEM_OBSERVER_RUNTIME ?? a.observerRuntime, a.observerApiKey = process.env.CODEMEM_OBSERVER_API_KEY ?? a.observerApiKey, a.observerBaseUrl = process.env.CODEMEM_OBSERVER_BASE_URL ?? a.observerBaseUrl, a.observerAuthSource = process.env.CODEMEM_OBSERVER_AUTH_SOURCE ?? a.observerAuthSource, a.observerAuthFile = process.env.CODEMEM_OBSERVER_AUTH_FILE ?? a.observerAuthFile, a.observerMaxChars = Oo(process.env.CODEMEM_OBSERVER_MAX_CHARS, a.observerMaxChars), a.observerMaxTokens = Oo(process.env.CODEMEM_OBSERVER_MAX_TOKENS, a.observerMaxTokens), a.observerAuthTimeoutMs = Oo(process.env.CODEMEM_OBSERVER_AUTH_TIMEOUT_MS, a.observerAuthTimeoutMs), a.observerAuthCacheTtlS = Oo(process.env.CODEMEM_OBSERVER_AUTH_CACHE_TTL_S, a.observerAuthCacheTtlS);
4403
+ let c = ko(process.env.CODEMEM_OBSERVER_HEADERS);
4398
4404
  c && (a.observerHeaders = c);
4399
- let u = Oo(process.env.CODEMEM_OBSERVER_AUTH_COMMAND);
4405
+ let u = Ao(process.env.CODEMEM_OBSERVER_AUTH_COMMAND);
4400
4406
  return u && (a.observerAuthCommand = u), a;
4401
4407
  }
4402
- var $ = class extends Error {
4408
+ var Q = class extends Error {
4403
4409
  constructor(e) {
4404
4410
  super(e), this.name = "ObserverAuthError";
4405
4411
  }
4406
4412
  };
4407
- function Ao(e) {
4413
+ function Mo(e) {
4408
4414
  return e === 401 || e === 403;
4409
4415
  }
4410
- function jo(e) {
4416
+ function No(e) {
4411
4417
  let t = e.trim();
4412
- return t && (To[t.toLowerCase()] ?? t);
4418
+ return t && (Do[t.toLowerCase()] ?? t);
4413
4419
  }
4414
- function Mo() {
4415
- return process.env.CODEMEM_ANTHROPIC_ENDPOINT ?? xo;
4420
+ function Po() {
4421
+ return process.env.CODEMEM_ANTHROPIC_ENDPOINT ?? Co;
4416
4422
  }
4417
- function No(e, t) {
4423
+ function Fo(e, t) {
4418
4424
  let n = {
4419
- "anthropic-version": So,
4425
+ "anthropic-version": wo,
4420
4426
  "content-type": "application/json"
4421
4427
  };
4422
4428
  return t ? (n.authorization = `Bearer ${e}`, n["anthropic-beta"] = "oauth-2025-04-20") : n["x-api-key"] = e, n;
4423
4429
  }
4424
- function Po(e, t, n, r) {
4430
+ function Io(e, t, n, r) {
4425
4431
  return {
4426
- model: jo(e),
4432
+ model: No(e),
4427
4433
  max_tokens: r,
4428
4434
  system: t,
4429
4435
  messages: [{
@@ -4432,23 +4438,27 @@ function Po(e, t, n, r) {
4432
4438
  }]
4433
4439
  };
4434
4440
  }
4435
- function Fo(e) {
4441
+ function Lo(e) {
4436
4442
  let t = e.content;
4437
- if (!Array.isArray(t)) return null;
4443
+ if (!Array.isArray(t)) return console.warn(`[codemem] Anthropic response has no content array (stop_reason=${e.stop_reason ?? "unknown"}, keys=${Object.keys(e).join(",")})`), null;
4438
4444
  let n = [];
4439
4445
  for (let e of t) if (typeof e == "object" && e && e.type === "text") {
4440
4446
  let t = e.text;
4441
4447
  typeof t == "string" && n.push(t);
4442
4448
  }
4449
+ if (n.length === 0 && t.length > 0) {
4450
+ let n = t.map((e) => typeof e == "object" && e ? e.type : typeof e).join(",");
4451
+ console.warn(`[codemem] Anthropic response has ${t.length} content block(s) but no text blocks (types=${n}, stop_reason=${e.stop_reason ?? "unknown"})`);
4452
+ }
4443
4453
  return n.length > 0 ? n.join("") : null;
4444
4454
  }
4445
- function Io(e) {
4455
+ function Ro(e) {
4446
4456
  return {
4447
4457
  authorization: `Bearer ${e}`,
4448
4458
  "content-type": "application/json"
4449
4459
  };
4450
4460
  }
4451
- function Lo(e, t, n, r) {
4461
+ function zo(e, t, n, r) {
4452
4462
  return {
4453
4463
  model: e,
4454
4464
  max_tokens: r,
@@ -4462,7 +4472,7 @@ function Lo(e, t, n, r) {
4462
4472
  }]
4463
4473
  };
4464
4474
  }
4465
- function Ro(e) {
4475
+ function Bo(e) {
4466
4476
  let t = e.choices;
4467
4477
  if (!Array.isArray(t) || t.length === 0) return null;
4468
4478
  let n = t[0];
@@ -4472,10 +4482,10 @@ function Ro(e) {
4472
4482
  let i = r.content;
4473
4483
  return typeof i == "string" ? i : null;
4474
4484
  }
4475
- function zo() {
4476
- return process.env.CODEMEM_CODEX_ENDPOINT ?? Co;
4485
+ function Vo() {
4486
+ return process.env.CODEMEM_CODEX_ENDPOINT ?? To;
4477
4487
  }
4478
- function Bo(e, t) {
4488
+ function Ho(e, t) {
4479
4489
  return {
4480
4490
  model: e,
4481
4491
  instructions: "You are a memory observer.",
@@ -4490,7 +4500,7 @@ function Bo(e, t) {
4490
4500
  stream: !0
4491
4501
  };
4492
4502
  }
4493
- function Vo(e, t) {
4503
+ function Uo(e, t) {
4494
4504
  let n = [];
4495
4505
  for (let r of e.split("\n")) {
4496
4506
  if (!r.startsWith("data:")) continue;
@@ -4502,14 +4512,14 @@ function Vo(e, t) {
4502
4512
  }
4503
4513
  return n.length > 0 ? n.join("").trim() : null;
4504
4514
  }
4505
- function Ho(e) {
4515
+ function Wo(e) {
4506
4516
  if (e.type === "response.output_text.delta") {
4507
4517
  let t = e.delta;
4508
4518
  return typeof t == "string" && t ? t : null;
4509
4519
  }
4510
4520
  return null;
4511
4521
  }
4512
- function Uo(e) {
4522
+ function Go(e) {
4513
4523
  if (e.type === "content_block_delta") {
4514
4524
  let t = e.delta;
4515
4525
  if (t && t.type === "text_delta") {
@@ -4519,10 +4529,10 @@ function Uo(e) {
4519
4529
  }
4520
4530
  return null;
4521
4531
  }
4522
- function Wo() {
4532
+ function Ko() {
4523
4533
  return Date.now();
4524
4534
  }
4525
- var Go = class {
4535
+ var qo = class {
4526
4536
  provider;
4527
4537
  model;
4528
4538
  runtime;
@@ -4539,18 +4549,18 @@ var Go = class {
4539
4549
  _lastErrorCode = null;
4540
4550
  _lastErrorMessage = null;
4541
4551
  constructor(e) {
4542
- let t = e ?? ko(), n = (t.observerProvider ?? "").toLowerCase(), r = (t.observerModel ?? "").trim(), i = Cn();
4552
+ let t = e ?? jo(), n = (t.observerProvider ?? "").toLowerCase(), r = (t.observerModel ?? "").trim(), i = wn();
4543
4553
  n && n !== "openai" && n !== "anthropic" && i.add(n);
4544
4554
  let a = n;
4545
4555
  if (!a) {
4546
- let e = wn(r, i);
4556
+ let e = Tn(r, i);
4547
4557
  e && (a = e);
4548
4558
  }
4549
- a ||= ro(null, r || bo), a !== "openai" && a !== "anthropic" && !i.has(a) && (a = "openai"), this.provider = a;
4559
+ a ||= ao(null, r || So), a !== "openai" && a !== "anthropic" && !i.has(a) && (a = "openai"), this.provider = a;
4550
4560
  let o = t.observerRuntime;
4551
- this.runtime = (typeof o == "string" && o.trim().toLowerCase(), "api_http"), r ? this.model = r : a === "anthropic" ? this.model = yo : a === "openai" ? this.model = bo : this.model = Mn(a) ?? "", this.maxChars = t.observerMaxChars, this.maxTokens = t.observerMaxTokens, this._observerHeaders = { ...t.observerHeaders }, this._apiKey = t.observerApiKey ?? null;
4561
+ this.runtime = (typeof o == "string" && o.trim().toLowerCase(), "api_http"), r ? this.model = r : a === "anthropic" ? this.model = xo : a === "openai" ? this.model = So : this.model = Nn(a) ?? "", this.maxChars = t.observerMaxChars, this.maxTokens = t.observerMaxTokens, this._observerHeaders = { ...t.observerHeaders }, this._apiKey = t.observerApiKey ?? null;
4552
4562
  let s = t.observerBaseUrl;
4553
- this._customBaseUrl = typeof s == "string" && s.trim() ? s.trim() : null, this.authAdapter = new mo({
4563
+ this._customBaseUrl = typeof s == "string" && s.trim() ? s.trim() : null, this.authAdapter = new go({
4554
4564
  source: t.observerAuthSource,
4555
4565
  filePath: t.observerAuthFile,
4556
4566
  command: t.observerAuthCommand,
@@ -4589,18 +4599,18 @@ var Go = class {
4589
4599
  let e = await this._callOnce(a, s);
4590
4600
  return e && this._clearLastError(), {
4591
4601
  raw: e,
4592
- parsed: e ? qo(e) : null,
4602
+ parsed: e ? Yo(e) : null,
4593
4603
  provider: this.provider,
4594
4604
  model: this.model
4595
4605
  };
4596
4606
  } catch (e) {
4597
- if (e instanceof $) {
4607
+ if (e instanceof Q) {
4598
4608
  if (this.refreshAuth(), !this.auth.token) throw e;
4599
4609
  try {
4600
4610
  let e = await this._callOnce(a, s);
4601
4611
  return e && this._clearLastError(), {
4602
4612
  raw: e,
4603
- parsed: e ? qo(e) : null,
4613
+ parsed: e ? Yo(e) : null,
4604
4614
  provider: this.provider,
4605
4615
  model: this.model
4606
4616
  };
@@ -4613,19 +4623,19 @@ var Go = class {
4613
4623
  }
4614
4624
  _initProvider(e) {
4615
4625
  this._codexAccess = null, this._codexAccountId = null, this._anthropicOAuthAccess = null;
4616
- let t = no(), n = null, r = null;
4626
+ let t = io(), n = null, r = null;
4617
4627
  if (this.provider === "openai" || this.provider === "anthropic") {
4618
- r = ro(this.provider, this.model), n = ao(t, r);
4619
- let e = so(t, r);
4620
- n && e != null && e <= Wo() && (n = null);
4628
+ r = ao(this.provider, this.model), n = so(t, r);
4629
+ let e = lo(t, r);
4630
+ n && e != null && e <= Ko() && (n = null);
4621
4631
  }
4622
4632
  if (this.provider !== "openai" && this.provider !== "anthropic") {
4623
- let t = Sn(this.provider), [n, r, i] = Nn(this.provider, this.model);
4633
+ let t = Cn(this.provider), [n, r, i] = Pn(this.provider, this.model);
4624
4634
  if (n && (this._customBaseUrl = n), r && (this.model = r), i && Object.keys(i).length > 0 && (this._observerHeaders = {
4625
4635
  ...this._observerHeaders,
4626
4636
  ...i
4627
4637
  }), !this._customBaseUrl) return;
4628
- let a = jn(t) || this._apiKey;
4638
+ let a = Mn(t) || this._apiKey;
4629
4639
  this.auth = this.authAdapter.resolve({
4630
4640
  explicitToken: a,
4631
4641
  envTokens: [process.env.CODEMEM_OBSERVER_API_KEY ?? ""],
@@ -4645,25 +4655,25 @@ var Go = class {
4645
4655
  ],
4646
4656
  oauthToken: n,
4647
4657
  forceRefresh: e
4648
- }), this.auth.source === "oauth" && n && (this._codexAccess = n, this._codexAccountId = oo(t, r ?? "openai")));
4658
+ }), this.auth.source === "oauth" && n && (this._codexAccess = n, this._codexAccountId = co(t, r ?? "openai")));
4649
4659
  }
4650
4660
  async _callOnce(e, t) {
4651
4661
  if (this._codexAccess) return this._callCodexConsumer(t);
4652
- if (this._anthropicOAuthAccess) return this._callAnthropicConsumer(t);
4662
+ if (this._anthropicOAuthAccess) return this._callAnthropicConsumer(e, t);
4653
4663
  if (!this.auth.token) {
4654
4664
  if (this._initProvider(!0), this._codexAccess) return this._callCodexConsumer(t);
4655
- if (this._anthropicOAuthAccess) return this._callAnthropicConsumer(t);
4656
- if (!this.auth.token) return this._setLastError(`${Ko(this.provider)} credentials are missing.`, "auth_missing"), null;
4665
+ if (this._anthropicOAuthAccess) return this._callAnthropicConsumer(e, t);
4666
+ if (!this.auth.token) return this._setLastError(`${Jo(this.provider)} credentials are missing.`, "auth_missing"), null;
4657
4667
  }
4658
4668
  return this.provider === "anthropic" ? this._callAnthropicDirect(e, t) : this._callOpenAIDirect(e, t);
4659
4669
  }
4660
4670
  async _callAnthropicDirect(e, t) {
4661
- let n = Mo(), r = {
4662
- ...No(this.auth.token ?? "", !1),
4663
- ...vo(this._observerHeaders, this.auth)
4664
- }, i = Po(this.model, e, t, this.maxTokens);
4671
+ let n = Po(), r = {
4672
+ ...Fo(this.auth.token ?? "", !1),
4673
+ ...bo(this._observerHeaders, this.auth)
4674
+ }, i = Io(this.model, e, t, this.maxTokens);
4665
4675
  return this._fetchJSON(n, r, i, {
4666
- parseResponse: Fo,
4676
+ parseResponse: Lo,
4667
4677
  providerLabel: "Anthropic"
4668
4678
  });
4669
4679
  }
@@ -4671,56 +4681,56 @@ var Go = class {
4671
4681
  let n;
4672
4682
  n = this._customBaseUrl ? `${this._customBaseUrl.replace(/\/+$/, "")}/chat/completions` : "https://api.openai.com/v1/chat/completions";
4673
4683
  let r = {
4674
- ...Io(this.auth.token ?? ""),
4675
- ...vo(this._observerHeaders, this.auth)
4676
- }, i = Lo(this.model, e, t, this.maxTokens);
4684
+ ...Ro(this.auth.token ?? ""),
4685
+ ...bo(this._observerHeaders, this.auth)
4686
+ }, i = zo(this.model, e, t, this.maxTokens);
4677
4687
  return this._fetchJSON(n, r, i, {
4678
- parseResponse: Ro,
4679
- providerLabel: Ko(this.provider)
4688
+ parseResponse: Bo,
4689
+ providerLabel: Jo(this.provider)
4680
4690
  });
4681
4691
  }
4682
4692
  async _callCodexConsumer(e) {
4683
4693
  if (!this._codexAccess) return null;
4684
- let t = co(this._codexAccess, this._codexAccountId);
4694
+ let t = uo(this._codexAccess, this._codexAccountId);
4685
4695
  if (Object.keys(this._observerHeaders).length > 0) {
4686
4696
  let e = {
4687
4697
  token: this._codexAccess,
4688
4698
  authType: "bearer",
4689
4699
  source: this.auth.source
4690
4700
  };
4691
- Object.assign(t, vo(this._observerHeaders, e));
4701
+ Object.assign(t, bo(this._observerHeaders, e));
4692
4702
  }
4693
4703
  t["content-type"] = "application/json";
4694
- let n = Bo(this.model, e), r = zo();
4695
- return this._fetchSSE(r, t, n, Ho, {
4704
+ let n = Ho(this.model, e), r = Vo();
4705
+ return this._fetchSSE(r, t, n, Wo, {
4696
4706
  providerLabel: "OpenAI",
4697
4707
  authErrorMessage: "OpenAI authentication failed. Refresh credentials and retry."
4698
4708
  });
4699
4709
  }
4700
- async _callAnthropicConsumer(e) {
4710
+ async _callAnthropicConsumer(e, t) {
4701
4711
  if (!this._anthropicOAuthAccess) return null;
4702
- let t = No(this._anthropicOAuthAccess, !0);
4712
+ let n = Fo(this._anthropicOAuthAccess, !0);
4703
4713
  if (Object.keys(this._observerHeaders).length > 0) {
4704
4714
  let e = {
4705
4715
  token: this._anthropicOAuthAccess,
4706
4716
  authType: "bearer",
4707
4717
  source: this.auth.source
4708
4718
  };
4709
- Object.assign(t, vo(this._observerHeaders, e));
4719
+ Object.assign(n, bo(this._observerHeaders, e));
4710
4720
  }
4711
- let n = Mo(), r = new URL(n);
4712
- r.searchParams.set("beta", "true");
4713
- let i = r.toString(), a = {
4714
- model: jo(this.model),
4721
+ let r = Po(), i = new URL(r);
4722
+ i.searchParams.set("beta", "true");
4723
+ let a = i.toString(), o = {
4724
+ model: No(this.model),
4715
4725
  max_tokens: this.maxTokens,
4716
4726
  stream: !0,
4717
4727
  messages: [{
4718
4728
  role: "user",
4719
- content: e
4729
+ content: t
4720
4730
  }],
4721
- system: "You are a memory observer."
4731
+ system: e
4722
4732
  };
4723
- return this._fetchSSE(i, t, a, Uo, {
4733
+ return this._fetchSSE(a, n, o, Go, {
4724
4734
  providerLabel: "Anthropic",
4725
4735
  authErrorMessage: "Anthropic authentication failed. Refresh credentials and retry."
4726
4736
  });
@@ -4731,16 +4741,16 @@ var Go = class {
4731
4741
  method: "POST",
4732
4742
  headers: t,
4733
4743
  body: JSON.stringify(n),
4734
- signal: AbortSignal.timeout(wo)
4744
+ signal: AbortSignal.timeout(Eo)
4735
4745
  });
4736
4746
  if (!i.ok) {
4737
4747
  let e = await i.text().catch(() => "");
4738
4748
  return this._handleHttpError(i.status, e, r.providerLabel), null;
4739
4749
  }
4740
- let a = await i.json();
4741
- return r.parseResponse(a);
4750
+ let a = await i.json(), o = r.parseResponse(a);
4751
+ return o === null && this._setLastError(`${r.providerLabel} returned 200 but response contained no extractable text.`, "empty_response"), o;
4742
4752
  } catch (e) {
4743
- if (e instanceof $) throw e;
4753
+ if (e instanceof Q) throw e;
4744
4754
  return this._setLastError(`${r.providerLabel} processing failed during observer inference.`, "observer_call_failed"), null;
4745
4755
  }
4746
4756
  }
@@ -4750,21 +4760,21 @@ var Go = class {
4750
4760
  method: "POST",
4751
4761
  headers: t,
4752
4762
  body: JSON.stringify(n),
4753
- signal: AbortSignal.timeout(wo)
4763
+ signal: AbortSignal.timeout(Eo)
4754
4764
  });
4755
4765
  if (!a.ok) {
4756
- if (await a.text().catch(() => ""), Ao(a.status)) throw this._setLastError(i.authErrorMessage, "auth_failed"), new $(`${i.providerLabel} auth error: ${a.status}`);
4766
+ if (await a.text().catch(() => ""), Mo(a.status)) throw this._setLastError(i.authErrorMessage, "auth_failed"), new Q(`${i.providerLabel} auth error: ${a.status}`);
4757
4767
  return this._setLastError(`${i.providerLabel} request failed during observer processing.`, "provider_request_failed"), null;
4758
4768
  }
4759
- return Vo(await a.text(), r);
4769
+ return Uo(await a.text(), r);
4760
4770
  } catch (e) {
4761
- if (e instanceof $) throw e;
4771
+ if (e instanceof Q) throw e;
4762
4772
  return this._setLastError(`${i.providerLabel} processing failed during observer inference.`, "observer_call_failed"), null;
4763
4773
  }
4764
4774
  }
4765
4775
  _handleHttpError(e, t, n) {
4766
- let r = $a(t);
4767
- if (Ao(e)) throw this._setLastError(`${n} authentication failed. Refresh credentials and retry.`, "auth_failed"), new $(`${n} auth error: ${e}: ${r}`);
4776
+ let r = to(t);
4777
+ if (Mo(e)) throw this._setLastError(`${n} authentication failed. Refresh credentials and retry.`, "auth_failed"), new Q(`${n} auth error: ${e}: ${r}`);
4768
4778
  if (e === 429) {
4769
4779
  this._setLastError(`${n} rate limited. Retry later.`, "rate_limited");
4770
4780
  return;
@@ -4789,10 +4799,10 @@ var Go = class {
4789
4799
  this._lastErrorCode = null, this._lastErrorMessage = null;
4790
4800
  }
4791
4801
  };
4792
- function Ko(e) {
4802
+ function Jo(e) {
4793
4803
  return e.charAt(0).toUpperCase() + e.slice(1);
4794
4804
  }
4795
- function qo(e) {
4805
+ function Yo(e) {
4796
4806
  try {
4797
4807
  let t = JSON.parse(e);
4798
4808
  return typeof t == "object" && t && !Array.isArray(t) ? t : null;
@@ -4802,10 +4812,10 @@ function qo(e) {
4802
4812
  }
4803
4813
  //#endregion
4804
4814
  //#region src/search.ts
4805
- function Jo(e) {
4815
+ function Xo(e) {
4806
4816
  return j(e, { schema: R });
4807
4817
  }
4808
- var Yo = {
4818
+ var Zo = {
4809
4819
  session_summary: .25,
4810
4820
  decision: .2,
4811
4821
  feature: .18,
@@ -4817,34 +4827,32 @@ var Yo = {
4817
4827
  observation: .1,
4818
4828
  exploration: .1,
4819
4829
  entities: .05
4820
- }, Xo = .45, Zo = .18, Qo = .12, $o = 3, es = 0, ts = 2, ns = [
4830
+ }, Qo = .45, $o = .18, es = .12, ts = 3, ns = 0, rs = 2, is = [
4821
4831
  /\bwhat did i\b/i,
4822
4832
  /\bmy notes\b/i,
4823
4833
  /\bmy last session\b/i,
4824
4834
  /\bmy machine\b/i
4825
- ], rs = new Set([
4835
+ ], as = new Set([
4826
4836
  "or",
4827
4837
  "and",
4828
4838
  "not",
4829
4839
  "near",
4830
4840
  "phrase"
4831
4841
  ]);
4832
- function is(e) {
4842
+ function os(e) {
4833
4843
  let t = e.match(/[A-Za-z0-9_]+/g);
4834
4844
  if (!t) return "";
4835
- let n = t.filter((e) => !rs.has(e.toLowerCase()));
4845
+ let n = t.filter((e) => !as.has(e.toLowerCase()));
4836
4846
  return n.length === 0 ? "" : n.length === 1 ? n[0] : n.join(" OR ");
4837
4847
  }
4838
- function as(e, t) {
4848
+ function ss(e, t) {
4839
4849
  let n = Date.parse(e);
4840
- if (Number.isNaN(n)) return 0;
4841
- let r = t ?? /* @__PURE__ */ new Date();
4842
- return 1 / (1 + Math.max(0, Math.floor((r.getTime() - n) / 864e5)) / 7);
4850
+ return Number.isNaN(n) ? 0 : 1 / (1 + Math.max(0, Math.floor(((t ?? /* @__PURE__ */ new Date()).getTime() - n) / 864e5)) / 7);
4843
4851
  }
4844
- function os(e) {
4845
- return e ? Yo[e.trim().toLowerCase()] ?? 0 : 0;
4852
+ function cs(e) {
4853
+ return e ? Zo[e.trim().toLowerCase()] ?? 0 : 0;
4846
4854
  }
4847
- function ss(e) {
4855
+ function ls(e) {
4848
4856
  if (!e || e.personal_first === void 0) return !0;
4849
4857
  let t = e.personal_first;
4850
4858
  if (typeof t == "string") {
@@ -4864,10 +4872,10 @@ function ss(e) {
4864
4872
  }
4865
4873
  return !!t;
4866
4874
  }
4867
- function cs(e) {
4875
+ function us(e) {
4868
4876
  return String(e?.trust_bias ?? "off").trim().toLowerCase() === "soft" ? "soft" : "off";
4869
4877
  }
4870
- function ls(e) {
4878
+ function ds(e) {
4871
4879
  if (!e || e.widen_shared_when_weak === void 0) return !1;
4872
4880
  let t = e.widen_shared_when_weak;
4873
4881
  if (typeof t == "string") {
@@ -4887,25 +4895,25 @@ function ls(e) {
4887
4895
  }
4888
4896
  return !!t;
4889
4897
  }
4890
- function us(e) {
4898
+ function fs(e) {
4891
4899
  let t = e?.widen_shared_min_personal_results;
4892
- return typeof t != "number" || !Number.isFinite(t) ? $o : Math.max(1, Math.trunc(t));
4900
+ return typeof t != "number" || !Number.isFinite(t) ? ts : Math.max(1, Math.trunc(t));
4893
4901
  }
4894
- function ds(e) {
4902
+ function ps(e) {
4895
4903
  let t = e?.widen_shared_min_personal_score;
4896
- return typeof t != "number" || !Number.isFinite(t) ? es : Math.max(0, t);
4904
+ return typeof t != "number" || !Number.isFinite(t) ? ns : Math.max(0, t);
4897
4905
  }
4898
- function fs(e) {
4899
- return ns.some((t) => t.test(e));
4906
+ function ms(e) {
4907
+ return is.some((t) => t.test(e));
4900
4908
  }
4901
- function ps(e) {
4909
+ function hs(e) {
4902
4910
  if (!e) return !1;
4903
4911
  let t = String(e.ownership_scope ?? "").trim().toLowerCase();
4904
4912
  if (t === "mine" || t === "theirs") return !0;
4905
- let n = bi(e.include_visibility ?? e.visibility), r = bi(e.exclude_visibility), i = vi(e.include_workspace_ids), a = vi(e.exclude_workspace_ids), o = yi(e.include_workspace_kinds), s = yi(e.exclude_workspace_kinds);
4913
+ let n = Si(e.include_visibility ?? e.visibility), r = Si(e.exclude_visibility), i = bi(e.include_workspace_ids), a = bi(e.exclude_workspace_ids), o = xi(e.include_workspace_kinds), s = xi(e.exclude_workspace_kinds);
4906
4914
  return n.length || i.length || o.length || r.includes("private") || r.includes("shared") || s.includes("shared") || s.includes("personal") ? !0 : a.some((e) => e.startsWith("personal:") || e.startsWith("shared:"));
4907
4915
  }
4908
- function ms(e) {
4916
+ function gs(e) {
4909
4917
  return {
4910
4918
  ...e ?? {},
4911
4919
  visibility: void 0,
@@ -4916,7 +4924,7 @@ function ms(e) {
4916
4924
  widen_shared_when_weak: !1
4917
4925
  };
4918
4926
  }
4919
- function hs(e) {
4927
+ function _s(e) {
4920
4928
  return e.map((e) => ({
4921
4929
  ...e,
4922
4930
  metadata: {
@@ -4925,36 +4933,36 @@ function hs(e) {
4925
4933
  }
4926
4934
  }));
4927
4935
  }
4928
- function gs(e, t, n) {
4929
- return ss(n) && e.memoryOwnedBySelf(t) ? Xo : 0;
4936
+ function vs(e, t, n) {
4937
+ return ls(n) && e.memoryOwnedBySelf(t) ? Qo : 0;
4930
4938
  }
4931
- function _s(e, t, n) {
4932
- if (cs(n) !== "soft" || e.memoryOwnedBySelf(t)) return 0;
4939
+ function ys(e, t, n) {
4940
+ if (us(n) !== "soft" || e.memoryOwnedBySelf(t)) return 0;
4933
4941
  let r = t.metadata ?? {}, i = String(r.visibility ?? "").trim().toLowerCase(), a = String(r.workspace_kind ?? "").trim().toLowerCase();
4934
4942
  if (i !== "shared" && a !== "shared") return 0;
4935
4943
  let o = String(r.trust_state ?? "trusted").trim().toLowerCase();
4936
- return o === "legacy_unknown" ? Zo : o === "unreviewed" ? Qo : 0;
4944
+ return o === "legacy_unknown" ? $o : o === "unreviewed" ? es : 0;
4937
4945
  }
4938
- function vs(e, t, n, r) {
4946
+ function bs(e, t, n, r) {
4939
4947
  let i = /* @__PURE__ */ new Date(), a = t.map((t) => ({
4940
4948
  item: t,
4941
- combinedScore: t.score * 1.5 + as(t.created_at, i) + os(t.kind) + gs(e, t, r) - _s(e, t, r)
4949
+ combinedScore: t.score * 1.5 + ss(t.created_at, i) + cs(t.kind) + vs(e, t, r) - ys(e, t, r)
4942
4950
  }));
4943
4951
  return a.sort((e, t) => t.combinedScore - e.combinedScore), a.slice(0, n).map((e) => e.item);
4944
4952
  }
4945
- function ys(e, t, n = 10, r) {
4946
- let i = bs(e, t, n, r);
4947
- if (!ls(r) || !t || fs(t) || ps(r)) return i;
4953
+ function xs(e, t, n = 10, r) {
4954
+ let i = Ss(e, t, n, r);
4955
+ if (!ds(r) || !t || ms(t) || hs(r)) return i;
4948
4956
  let a = i.filter((t) => e.memoryOwnedBySelf(t)), o = a[0]?.score ?? -Infinity;
4949
- if (a.length >= us(r) && o >= ds(r)) return i;
4950
- let s = hs(bs(e, t, ts, ms(r)).filter((t) => !e.memoryOwnedBySelf(t))), c = new Set(i.map((e) => e.id)), l = [...i], u = 0;
4951
- for (let e of s) if (!c.has(e.id) && (c.add(e.id), l.push(e), u += 1, u >= ts)) break;
4957
+ if (a.length >= fs(r) && o >= ps(r)) return i;
4958
+ let s = _s(Ss(e, t, rs, gs(r)).filter((t) => !e.memoryOwnedBySelf(t))), c = new Set(i.map((e) => e.id)), l = [...i], u = 0;
4959
+ for (let e of s) if (!c.has(e.id) && (c.add(e.id), l.push(e), u += 1, u >= rs)) break;
4952
4960
  return l;
4953
4961
  }
4954
- function bs(e, t, n = 10, r) {
4955
- let i = Math.max(1, Math.trunc(n)), a = is(t);
4962
+ function Ss(e, t, n = 10, r) {
4963
+ let i = Math.max(1, Math.trunc(n)), a = os(t);
4956
4964
  if (!a) return [];
4957
- let o = Math.min(Math.max(i * 4, i + 8), 200), s = [a], c = ["memory_items.active = 1", "memory_fts MATCH ?"], l = wi(r, {
4965
+ let o = Math.min(Math.max(i * 4, i + 8), 200), s = [a], c = ["memory_items.active = 1", "memory_fts MATCH ?"], l = Ei(r, {
4958
4966
  actorId: e.actorId,
4959
4967
  deviceId: e.deviceId
4960
4968
  });
@@ -4970,8 +4978,8 @@ function bs(e, t, n = 10, r) {
4970
4978
  ORDER BY (score * 1.5 + recency) DESC, memory_items.created_at DESC, memory_items.id DESC
4971
4979
  LIMIT ?
4972
4980
  `;
4973
- return s.push(o), vs(e, e.db.prepare(d).all(...s).map((e) => {
4974
- let t = { ...J(e.metadata_json) };
4981
+ return s.push(o), bs(e, e.db.prepare(d).all(...s).map((e) => {
4982
+ let t = { ...q(e.metadata_json) };
4975
4983
  for (let n of [
4976
4984
  "actor_id",
4977
4985
  "actor_display_name",
@@ -5004,7 +5012,7 @@ function bs(e, t, n = 10, r) {
5004
5012
  };
5005
5013
  }), i, r);
5006
5014
  }
5007
- function xs(e, t, n, r = 3, i = 3, a) {
5015
+ function Cs(e, t, n, r = 3, i = 3, a) {
5008
5016
  let o = null;
5009
5017
  if (n != null) {
5010
5018
  let t = e.get(n);
@@ -5015,7 +5023,7 @@ function xs(e, t, n, r = 3, i = 3, a) {
5015
5023
  });
5016
5024
  }
5017
5025
  if (o == null && t) {
5018
- let n = ys(e, t, 1, a ?? void 0);
5026
+ let n = xs(e, t, 1, a ?? void 0);
5019
5027
  if (n.length > 0) {
5020
5028
  let e = n[0];
5021
5029
  o = {
@@ -5025,12 +5033,12 @@ function xs(e, t, n, r = 3, i = 3, a) {
5025
5033
  };
5026
5034
  }
5027
5035
  }
5028
- return o == null ? [] : Ss(e, o, r, i, a);
5036
+ return o == null ? [] : ws(e, o, r, i, a);
5029
5037
  }
5030
- function Ss(e, t, n, r, i) {
5038
+ function ws(e, t, n, r, i) {
5031
5039
  let a = t.id, o = t.created_at, s = t.session_id;
5032
5040
  if (!a || !o) return [];
5033
- let c = wi(i, {
5041
+ let c = Ei(i, {
5034
5042
  actorId: e.actorId,
5035
5043
  deviceId: e.deviceId
5036
5044
  }), l = ["memory_items.active = 1", ...c.clauses], u = [...c.params];
@@ -5045,20 +5053,20 @@ function Ss(e, t, n, r, i) {
5045
5053
  ${f}
5046
5054
  WHERE ${d} AND memory_items.created_at > ?
5047
5055
  ORDER BY memory_items.created_at ASC
5048
- LIMIT ?`).all(...u, o, r), h = Jo(e.db).select().from(B).where(E(O(B.id, a), O(B.active, 1))).get(), g = [...p.reverse()];
5056
+ LIMIT ?`).all(...u, o, r), h = Xo(e.db).select().from(B).where(E(O(B.id, a), O(B.active, 1))).get(), g = [...p.reverse()];
5049
5057
  return h && g.push(h), g.push(...m), g.map((e) => {
5050
5058
  let { metadata_json: t, ...n } = e;
5051
5059
  return {
5052
5060
  ...n,
5053
- metadata_json: J(t),
5061
+ metadata_json: q(t),
5054
5062
  linked_prompt: null
5055
5063
  };
5056
5064
  });
5057
5065
  }
5058
- function Cs(e) {
5066
+ function Ts(e) {
5059
5067
  let t = /* @__PURE__ */ new Set(), n = [], r = [];
5060
5068
  for (let i of e) {
5061
- let e = Ua(i);
5069
+ let e = Ga(i);
5062
5070
  if (e == null) {
5063
5071
  r.push(String(i));
5064
5072
  continue;
@@ -5070,8 +5078,8 @@ function Cs(e) {
5070
5078
  invalid: r
5071
5079
  };
5072
5080
  }
5073
- function ws(e, t, n, r, i, a, o) {
5074
- let s = `${e.title} ${e.body_text} ${e.tags_text}`.toLowerCase(), c = r.filter((e) => s.includes(e)), l = t === "query" || t === "query+id_lookup" ? e.score : null, u = as(e.created_at, o), d = os(e.kind), f = null;
5081
+ function Es(e, t, n, r, i, a, o) {
5082
+ let s = `${e.title} ${e.body_text} ${e.tags_text}`.toLowerCase(), c = r.filter((e) => s.includes(e)), l = t === "query" || t === "query+id_lookup" ? e.score : null, u = ss(e.created_at, o), d = cs(e.kind), f = null;
5075
5083
  return l != null && (f = l * 1.5 + u + d), {
5076
5084
  id: e.id,
5077
5085
  kind: e.kind,
@@ -5094,21 +5102,21 @@ function ws(e, t, n, r, i, a, o) {
5094
5102
  },
5095
5103
  matches: {
5096
5104
  query_terms: c,
5097
- project_match: Jr(i, a)
5105
+ project_match: Xr(i, a)
5098
5106
  },
5099
5107
  pack_context: null
5100
5108
  };
5101
5109
  }
5102
- function Ts(e, t, n) {
5110
+ function Ds(e, t, n) {
5103
5111
  if (t.length === 0) return {
5104
5112
  items: [],
5105
5113
  missingNotFound: [],
5106
5114
  missingProjectMismatch: [],
5107
5115
  missingFilterMismatch: []
5108
5116
  };
5109
- let r = Jo(e.db).select().from(B).where(E(O(B.active, 1), te(B.id, t))).all(), i = new Set(r.map((e) => e.id)), a = t.map(() => "?").join(", "), o = r, s = new Set(i);
5117
+ let r = Xo(e.db).select().from(B).where(E(O(B.active, 1), te(B.id, t))).all(), i = new Set(r.map((e) => e.id)), a = t.map(() => "?").join(", "), o = r, s = new Set(i);
5110
5118
  if (n.project) {
5111
- let r = wi({ project: n.project }, {
5119
+ let r = Ei({ project: n.project }, {
5112
5120
  actorId: e.actorId,
5113
5121
  deviceId: e.deviceId
5114
5122
  });
@@ -5122,7 +5130,7 @@ function Ts(e, t, n) {
5122
5130
  AND ${r.clauses.join(" AND ")}`).all(...t, ...r.params), s = new Set(o.map((e) => e.id));
5123
5131
  }
5124
5132
  }
5125
- let c = wi(n, {
5133
+ let c = Ei(n, {
5126
5134
  actorId: e.actorId,
5127
5135
  deviceId: e.deviceId
5128
5136
  }), l = c.joinSessions ? "JOIN sessions ON sessions.id = memory_items.session_id" : "", u = e.db.prepare(`SELECT memory_items.*
@@ -5145,23 +5153,23 @@ function Ts(e, t, n) {
5145
5153
  tags_text: e.tags_text ?? "",
5146
5154
  score: 0,
5147
5155
  session_id: e.session_id,
5148
- metadata: J(e.metadata_json)
5156
+ metadata: q(e.metadata_json)
5149
5157
  })),
5150
5158
  missingNotFound: f,
5151
5159
  missingProjectMismatch: p,
5152
5160
  missingFilterMismatch: m
5153
5161
  };
5154
5162
  }
5155
- function Es(e, t) {
5163
+ function Os(e, t) {
5156
5164
  if (t.size === 0) return /* @__PURE__ */ new Map();
5157
- let n = [...t].sort((e, t) => e - t), r = Jo(e.db).select({
5165
+ let n = [...t].sort((e, t) => e - t), r = Xo(e.db).select({
5158
5166
  id: z.id,
5159
5167
  project: z.project
5160
5168
  }).from(z).where(te(z.id, n)).all();
5161
5169
  return new Map(r.map((e) => [e.id, e.project]));
5162
5170
  }
5163
- function Ds(e, t, n, r = 10, i) {
5164
- let a = (t ?? "").trim(), { ordered: o, invalid: s } = Cs(n ?? []), c = [];
5171
+ function ks(e, t, n, r = 10, i) {
5172
+ let a = (t ?? "").trim(), { ordered: o, invalid: s } = Ts(n ?? []), c = [];
5165
5173
  if (s.length > 0 && c.push({
5166
5174
  code: "INVALID_ARGUMENT",
5167
5175
  field: "ids",
@@ -5184,10 +5192,10 @@ function Ds(e, t, n, r = 10, i) {
5184
5192
  }
5185
5193
  };
5186
5194
  let l = [];
5187
- a && (l = ys(e, a, Math.max(1, Math.trunc(r)), i ?? void 0));
5195
+ a && (l = xs(e, a, Math.max(1, Math.trunc(r)), i ?? void 0));
5188
5196
  let u = /* @__PURE__ */ new Map();
5189
5197
  for (let e = 0; e < l.length; e++) u.set(l[e].id, e + 1);
5190
- let { items: d, missingNotFound: f, missingProjectMismatch: p, missingFilterMismatch: m } = Ts(e, o, i ?? {}), h = new Map(d.map((e) => [e.id, e])), g = new Set(o), _ = /* @__PURE__ */ new Set(), v = [];
5198
+ let { items: d, missingNotFound: f, missingProjectMismatch: p, missingFilterMismatch: m } = Ds(e, o, i ?? {}), h = new Map(d.map((e) => [e.id, e])), g = new Set(o), _ = /* @__PURE__ */ new Set(), v = [];
5191
5199
  for (let e of l) {
5192
5200
  _.add(e.id);
5193
5201
  let t = g.has(e.id) ? "query+id_lookup" : "query";
@@ -5206,7 +5214,7 @@ function Ds(e, t, n, r = 10, i) {
5206
5214
  rank: null
5207
5215
  }), _.add(e));
5208
5216
  }
5209
- let y = a ? (a.match(/[A-Za-z0-9_]+/g) ?? []).map((e) => e.toLowerCase()) : [], b = Es(e, new Set(v.map(({ item: e }) => e.session_id).filter((e) => e > 0))), x = /* @__PURE__ */ new Date(), S = v.map(({ item: e, source: t, rank: n }) => ws(e, t, n, y, i?.project ?? null, b.get(e.session_id) ?? null, x)), C = o.filter((e) => !_.has(e));
5217
+ let y = a ? (a.match(/[A-Za-z0-9_]+/g) ?? []).map((e) => e.toLowerCase()) : [], b = Os(e, new Set(v.map(({ item: e }) => e.session_id).filter((e) => e > 0))), x = /* @__PURE__ */ new Date(), S = v.map(({ item: e, source: t, rank: n }) => Es(e, t, n, y, i?.project ?? null, b.get(e.session_id) ?? null, x)), C = o.filter((e) => !_.has(e));
5210
5218
  return f.length > 0 && c.push({
5211
5219
  code: "NOT_FOUND",
5212
5220
  field: "ids",
@@ -5237,21 +5245,21 @@ function Ds(e, t, n, r = 10, i) {
5237
5245
  }
5238
5246
  //#endregion
5239
5247
  //#region src/vectors.ts
5240
- async function Os(e, t, n, r) {
5241
- let i = await Vr();
5248
+ async function As(e, t, n, r) {
5249
+ let i = await Ur();
5242
5250
  if (!i) return;
5243
- let a = Rr(`${n}\n${r}`.trim());
5251
+ let a = Br(`${n}\n${r}`.trim());
5244
5252
  if (a.length === 0) return;
5245
- let o = await Hr(a);
5253
+ let o = await Wr(a);
5246
5254
  if (o.length === 0) return;
5247
5255
  let s = i.model, c = e.prepare("INSERT INTO memory_vectors(embedding, memory_id, chunk_index, content_hash, model) VALUES (?, ?, ?, ?, ?)");
5248
5256
  for (let e = 0; e < a.length && e < o.length; e++) {
5249
5257
  let n = o[e];
5250
- !n || n.length === 0 || c.run(Wr(n), t, e, Lr(a[e]), s);
5258
+ !n || n.length === 0 || c.run(Kr(n), t, e, zr(a[e]), s);
5251
5259
  }
5252
5260
  }
5253
- async function ks(e, t = {}) {
5254
- let n = await Vr();
5261
+ async function js(e, t = {}) {
5262
+ let n = await Ur();
5255
5263
  if (!n) return {
5256
5264
  checked: 0,
5257
5265
  embedded: 0,
@@ -5260,7 +5268,7 @@ async function ks(e, t = {}) {
5260
5268
  };
5261
5269
  let { limit: r, since: i, project: a, activeOnly: o = !0, dryRun: s = !1, memoryIds: c } = t, l = [], u = [];
5262
5270
  if (o && u.push("memory_items.active = 1"), i && (u.push("memory_items.created_at >= ?"), l.push(i)), a) {
5263
- let e = qr(a);
5271
+ let e = Yr(a);
5264
5272
  e.clause && (u.push(e.clause), l.push(...e.params));
5265
5273
  }
5266
5274
  if (c && c.length > 0) {
@@ -5275,11 +5283,11 @@ async function ks(e, t = {}) {
5275
5283
  ORDER BY memory_items.created_at ASC ${p}`).all(...l), h = n.model, g = 0, _ = 0, v = 0, y = 0;
5276
5284
  for (let t of m) {
5277
5285
  g++;
5278
- let n = Rr(`${t.title ?? ""}\n${t.body_text ?? ""}`.trim());
5286
+ let n = Br(`${t.title ?? ""}\n${t.body_text ?? ""}`.trim());
5279
5287
  if (n.length === 0) continue;
5280
5288
  let r = e.prepare("SELECT content_hash FROM memory_vectors WHERE memory_id = ? AND model = ?").all(t.id, h), i = new Set(r.map((e) => e.content_hash).filter((e) => e != null)), a = [], o = [];
5281
5289
  for (let e of n) {
5282
- let t = Lr(e);
5290
+ let t = zr(e);
5283
5291
  if (i.has(t)) {
5284
5292
  y++;
5285
5293
  continue;
@@ -5287,7 +5295,7 @@ async function ks(e, t = {}) {
5287
5295
  a.push(e), o.push(t);
5288
5296
  }
5289
5297
  if (a.length === 0) continue;
5290
- let c = await Hr(a);
5298
+ let c = await Wr(a);
5291
5299
  if (c.length === 0) continue;
5292
5300
  if (_ += c.length, s) {
5293
5301
  v += c.length;
@@ -5296,7 +5304,7 @@ async function ks(e, t = {}) {
5296
5304
  let l = e.prepare("INSERT INTO memory_vectors(embedding, memory_id, chunk_index, content_hash, model) VALUES (?, ?, ?, ?, ?)");
5297
5305
  for (let e = 0; e < c.length; e++) {
5298
5306
  let n = c[e];
5299
- !n || n.length === 0 || (l.run(Wr(n), t.id, e, o[e], h), v++);
5307
+ !n || n.length === 0 || (l.run(Kr(n), t.id, e, o[e], h), v++);
5300
5308
  }
5301
5309
  }
5302
5310
  return {
@@ -5306,15 +5314,15 @@ async function ks(e, t = {}) {
5306
5314
  skipped: y
5307
5315
  };
5308
5316
  }
5309
- async function As(e, t, n = 10, r) {
5317
+ async function Ms(e, t, n = 10, r) {
5310
5318
  if (t.trim().length < 3) return [];
5311
- let i = await Hr([t]);
5319
+ let i = await Wr([t]);
5312
5320
  if (i.length === 0) return [];
5313
5321
  let a = i[0];
5314
5322
  if (!a) return [];
5315
- let o = [Wr(a), n], s = ["memory_items.active = 1"], c = !1;
5323
+ let o = [Kr(a), n], s = ["memory_items.active = 1"], c = !1;
5316
5324
  if (r?.project) {
5317
- let e = qr(r.project);
5325
+ let e = Yr(r.project);
5318
5326
  e.clause && (s.push(e.clause), o.push(...e.params), c = !0);
5319
5327
  }
5320
5328
  let l = s.join(" AND "), u = `
@@ -5344,7 +5352,7 @@ async function As(e, t, n = 10, r) {
5344
5352
  }
5345
5353
  //#endregion
5346
5354
  //#region src/pack.ts
5347
- var js = {
5355
+ var Ns = {
5348
5356
  decision: 0,
5349
5357
  feature: 1,
5350
5358
  bugfix: 2,
@@ -5354,10 +5362,10 @@ var js = {
5354
5362
  exploration: 6,
5355
5363
  note: 7
5356
5364
  };
5357
- function Ms(e) {
5365
+ function Ps(e) {
5358
5366
  return Math.ceil(e.length / 4);
5359
5367
  }
5360
- function Ns(e) {
5368
+ function Fs(e) {
5361
5369
  let t = [
5362
5370
  `[${e.id}]`,
5363
5371
  `(${e.kind})`,
@@ -5365,10 +5373,10 @@ function Ns(e) {
5365
5373
  ];
5366
5374
  return e.body_text && t.push("-", e.body_text), t.join(" ");
5367
5375
  }
5368
- function Ps(e, t) {
5369
- return t.length === 0 ? "" : [`## ${e}`, ...t.map(Ns)].join("\n");
5376
+ function Is(e, t) {
5377
+ return t.length === 0 ? "" : [`## ${e}`, ...t.map(Fs)].join("\n");
5370
5378
  }
5371
- function Fs(e, t) {
5379
+ function Ls(e, t) {
5372
5380
  let n = t?.duplicateIds.get(e.id), r = {
5373
5381
  id: e.id,
5374
5382
  kind: e.kind,
@@ -5380,18 +5388,18 @@ function Fs(e, t) {
5380
5388
  };
5381
5389
  return n && n.size > 0 && (r.support_count = 1 + n.size, r.duplicate_ids = [...n].sort((e, t) => e - t)), r;
5382
5390
  }
5383
- function Is(e) {
5391
+ function Rs(e) {
5384
5392
  return e.trim().toLowerCase().split(/\s+/).join(" ");
5385
5393
  }
5386
- function Ls(e) {
5394
+ function zs(e) {
5387
5395
  if (e.kind === "session_summary") return null;
5388
- let t = Is(e.title), n = Is(e.body_text);
5396
+ let t = Rs(e.title), n = Rs(e.body_text);
5389
5397
  return !t && !n ? null : `${e.kind.length}:${e.kind}|${t.length}:${t}|${n.length}:${n}`;
5390
5398
  }
5391
- function Rs(e, t) {
5399
+ function Bs(e, t) {
5392
5400
  let n = [];
5393
5401
  for (let r of e) {
5394
- let e = Ls(r);
5402
+ let e = zs(r);
5395
5403
  if (e === null) {
5396
5404
  n.push(r);
5397
5405
  continue;
@@ -5410,19 +5418,19 @@ function Rs(e, t) {
5410
5418
  }
5411
5419
  return n;
5412
5420
  }
5413
- function zs(e, t) {
5421
+ function Vs(e, t) {
5414
5422
  let n = new Set((t.toLowerCase().match(/[a-z0-9_]+/g) ?? []).filter(Boolean));
5415
5423
  return n.size === 0 ? e : [...e].sort((e, t) => {
5416
- let r = Bs(e.tags_text, n), i = Bs(t.tags_text, n);
5424
+ let r = Hs(e.tags_text, n), i = Hs(t.tags_text, n);
5417
5425
  return i === r ? (t.created_at ?? "").localeCompare(e.created_at ?? "") : i - r;
5418
5426
  });
5419
5427
  }
5420
- function Bs(e, t) {
5428
+ function Hs(e, t) {
5421
5429
  let n = new Set(e.split(/\s+/).filter(Boolean)), r = 0;
5422
5430
  for (let e of t) n.has(e) && r++;
5423
5431
  return r;
5424
5432
  }
5425
- function Vs(e, t, n) {
5433
+ function Us(e, t, n) {
5426
5434
  let r = /* @__PURE__ */ new Map();
5427
5435
  for (let t of e) {
5428
5436
  let e = r.get(t.id);
@@ -5440,10 +5448,10 @@ function Vs(e, t, n) {
5440
5448
  semanticCount: i
5441
5449
  };
5442
5450
  }
5443
- function Hs(e, t, n = 10, r = null, i, a) {
5444
- let o = Math.max(1, Math.trunc(n)), s = !1, c = 0, l = 0, u = ys(e, t, o, i), d;
5451
+ function Ws(e, t, n = 10, r = null, i, a) {
5452
+ let o = Math.max(1, Math.trunc(n)), s = !1, c = 0, l = 0, u = xs(e, t, o, i), d;
5445
5453
  if (a && a.length > 0) {
5446
- let e = Vs(u, a, o);
5454
+ let e = Us(u, a, o);
5447
5455
  d = e.merged, c = e.ftsCount, l = e.semanticCount;
5448
5456
  } else d = u, c = d.length;
5449
5457
  d.length === 0 && (s = !0, d = e.recent(o, i ?? null).map((e) => ({
@@ -5482,7 +5490,7 @@ function Hs(e, t, n = 10, r = null, i, a) {
5482
5490
  }];
5483
5491
  }
5484
5492
  }
5485
- let p = d.filter((e) => e.kind !== "session_summary").slice(0, 3), m = new Set(p.map((e) => e.id)), h = Object.keys(js), g = [...d].filter((e) => e.kind !== "session_summary" && !m.has(e.id)).sort((e, t) => (js[e.kind] ?? 99) - (js[t.kind] ?? 99));
5493
+ let p = d.filter((e) => e.kind !== "session_summary").slice(0, 3), m = new Set(p.map((e) => e.id)), h = Object.keys(Ns), g = [...d].filter((e) => e.kind !== "session_summary" && !m.has(e.id)).sort((e, t) => (Ns[e.kind] ?? 99) - (Ns[t.kind] ?? 99));
5486
5494
  g.length === 0 && (g = e.recentByKinds(h, Math.max(o * 3, 10), i ?? null).map((e) => ({
5487
5495
  id: e.id,
5488
5496
  kind: e.kind,
@@ -5495,44 +5503,44 @@ function Hs(e, t, n = 10, r = null, i, a) {
5495
5503
  score: 0,
5496
5504
  session_id: e.session_id,
5497
5505
  metadata: e.metadata_json
5498
- }))), g = zs(g, t);
5506
+ }))), g = Vs(g, t);
5499
5507
  let _ = {
5500
5508
  canonicalByKey: /* @__PURE__ */ new Map(),
5501
5509
  duplicateIds: /* @__PURE__ */ new Map()
5502
5510
  };
5503
- f = Rs(f, _), p = Rs(p, _), g = Rs(g, _);
5511
+ f = Bs(f, _), p = Bs(p, _), g = Bs(g, _);
5504
5512
  let v = f, y = p, b = g;
5505
5513
  if (r != null && r > 0) {
5506
5514
  let e = 0;
5507
5515
  v = [];
5508
5516
  for (let t of f) {
5509
- let n = Ms(Ns(t));
5517
+ let n = Ps(Fs(t));
5510
5518
  if (e + n > r) break;
5511
5519
  e += n, v.push(t);
5512
5520
  }
5513
5521
  y = [];
5514
5522
  for (let t of p) {
5515
- let n = Ms(Ns(t));
5523
+ let n = Ps(Fs(t));
5516
5524
  if (e + n > r) break;
5517
5525
  e += n, y.push(t);
5518
5526
  }
5519
5527
  b = [];
5520
5528
  for (let t of g) {
5521
- let n = Ms(Ns(t));
5529
+ let n = Ps(Fs(t));
5522
5530
  if (e + n > r) break;
5523
5531
  e += n, b.push(t);
5524
5532
  }
5525
5533
  }
5526
5534
  let x = [
5527
- Ps("Summary", v),
5528
- Ps("Timeline", y),
5529
- Ps("Observations", b)
5535
+ Is("Summary", v),
5536
+ Is("Timeline", y),
5537
+ Is("Observations", b)
5530
5538
  ].filter((e) => e.length > 0).join("\n\n"), S = /* @__PURE__ */ new Set(), C = [], w = [];
5531
5539
  for (let e of [
5532
5540
  ...v,
5533
5541
  ...y,
5534
5542
  ...b
5535
- ]) S.has(e.id) || (S.add(e.id), C.push(Fs(e, _)), w.push(e.id));
5543
+ ]) S.has(e.id) || (S.add(e.id), C.push(Ls(e, _)), w.push(e.id));
5536
5544
  return {
5537
5545
  context: t,
5538
5546
  items: C,
@@ -5540,7 +5548,7 @@ function Hs(e, t, n = 10, r = null, i, a) {
5540
5548
  pack_text: x,
5541
5549
  metrics: {
5542
5550
  total_items: C.length,
5543
- pack_tokens: Ms(x),
5551
+ pack_tokens: Ps(x),
5544
5552
  fallback_used: s,
5545
5553
  sources: {
5546
5554
  fts: c,
@@ -5550,10 +5558,10 @@ function Hs(e, t, n = 10, r = null, i, a) {
5550
5558
  }
5551
5559
  };
5552
5560
  }
5553
- async function Us(e, t, n = 10, r = null, i) {
5561
+ async function Gs(e, t, n = 10, r = null, i) {
5554
5562
  let a = [];
5555
5563
  try {
5556
- a = (await As(e.db, t, n, { project: i?.project })).map((e) => {
5564
+ a = (await Ms(e.db, t, n, { project: i?.project })).map((e) => {
5557
5565
  let t = {};
5558
5566
  if (e.metadata_json) try {
5559
5567
  let n = JSON.parse(e.metadata_json);
@@ -5574,24 +5582,24 @@ async function Us(e, t, n = 10, r = null, i) {
5574
5582
  };
5575
5583
  });
5576
5584
  } catch {}
5577
- return Hs(e, t, n, r, i, a);
5585
+ return Ws(e, t, n, r, i, a);
5578
5586
  }
5579
5587
  //#endregion
5580
5588
  //#region src/raw-event-flush.ts
5581
- var Ws = "raw_events_v1";
5582
- function Gs(e, t = 280) {
5589
+ var Ks = "raw_events_v1";
5590
+ function qs(e, t = 280) {
5583
5591
  let n = e.replace(/\s+/g, " ").trim();
5584
5592
  return n.length <= t ? n : `${n.slice(0, t - 3).trimEnd()}...`;
5585
5593
  }
5586
- function Ks(e) {
5594
+ function Js(e) {
5587
5595
  let t = (e ?? "").trim().toLowerCase();
5588
5596
  return t === "openai" ? "OpenAI" : t === "anthropic" ? "Anthropic" : t ? t.charAt(0).toUpperCase() + t.slice(1) : "Observer";
5589
5597
  }
5590
- function qs(e, t) {
5591
- let n = Ks(t), r = String(e.message ?? "").trim().toLowerCase();
5592
- return e instanceof $ ? `${n} authentication failed. Refresh credentials and retry.` : e.name === "TimeoutError" || r.includes("timeout") ? `${n} request timed out during raw-event processing.` : r === "observer failed during raw-event flush" ? `${n} returned no usable output for raw-event processing.` : /parse|xml|json/i.test(r) ? `${n} response could not be processed.` : `${n} processing failed during raw-event ingestion.`;
5598
+ function Ys(e, t) {
5599
+ let n = Js(t), r = String(e.message ?? "").trim().toLowerCase();
5600
+ return e instanceof Q ? `${n} authentication failed. Refresh credentials and retry.` : e.name === "TimeoutError" || r.includes("timeout") ? `${n} request timed out during raw-event processing.` : r === "observer failed during raw-event flush" ? `${n} returned no usable output for raw-event processing.` : /parse|xml|json/i.test(r) ? `${n} response could not be processed.` : `${n} processing failed during raw-event ingestion.`;
5593
5601
  }
5594
- function Js(e) {
5602
+ function Xs(e) {
5595
5603
  let t = 0, n = 0;
5596
5604
  for (let r of e) r.type === "user_prompt" && t++, r.type === "tool.execute.after" && n++;
5597
5605
  let r = [];
@@ -5636,7 +5644,7 @@ function Js(e) {
5636
5644
  filesRead: [...o].sort()
5637
5645
  };
5638
5646
  }
5639
- async function Ys(e, t, n) {
5647
+ async function Zs(e, t, n) {
5640
5648
  let { source: r = "opencode", cwd: i, project: a, startedAt: o } = n, { opencodeSessionId: s, maxEvents: c } = n;
5641
5649
  r = (r ?? "").trim().toLowerCase() || "opencode";
5642
5650
  let l = e.rawEventSessionMeta(s, r);
@@ -5666,7 +5674,7 @@ async function Ys(e, t, n) {
5666
5674
  flushed: 0,
5667
5675
  updatedState: 0
5668
5676
  };
5669
- let { batchId: h, status: g } = e.getOrCreateRawEventFlushBatch(s, r, p, m, Ws);
5677
+ let { batchId: h, status: g } = e.getOrCreateRawEventFlushBatch(s, r, p, m, Ks);
5670
5678
  if (g === "completed") return e.updateRawEventFlushState(s, m, r), {
5671
5679
  flushed: 0,
5672
5680
  updatedState: 1
@@ -5675,7 +5683,7 @@ async function Ys(e, t, n) {
5675
5683
  flushed: 0,
5676
5684
  updatedState: 0
5677
5685
  };
5678
- let _ = Js(d);
5686
+ let _ = Xs(d);
5679
5687
  _.opencodeSessionId = s, _.source = r, _.streamId = s, _.flusher = "raw_events", _.flushBatch = {
5680
5688
  batch_id: h,
5681
5689
  start_event_seq: p,
@@ -5689,12 +5697,12 @@ async function Ys(e, t, n) {
5689
5697
  sessionContext: _
5690
5698
  };
5691
5699
  try {
5692
- await Ia(v, e, t);
5700
+ await Ra(v, e, t);
5693
5701
  } catch (n) {
5694
- let r = n instanceof Error ? n : Error(String(n)), i = t.observer?.getStatus?.()?.provider, a = Gs(qs(r, i));
5702
+ let r = n instanceof Error ? n : Error(String(n)), i = t.observer?.getStatus?.()?.provider, a = qs(Ys(r, i));
5695
5703
  throw e.recordRawEventFlushBatchFailure(h, {
5696
5704
  message: a,
5697
- errorType: r instanceof $ ? "ObserverAuthError" : r.name,
5705
+ errorType: r instanceof Q ? "ObserverAuthError" : r.name,
5698
5706
  observerProvider: i ?? null,
5699
5707
  observerModel: t.observer?.getStatus?.()?.model ?? null,
5700
5708
  observerRuntime: null
@@ -5707,18 +5715,18 @@ async function Ys(e, t, n) {
5707
5715
  }
5708
5716
  //#endregion
5709
5717
  //#region src/raw-event-sweeper.ts
5710
- var Xs = 300;
5711
- function Zs(e, t) {
5718
+ var Qs = 60;
5719
+ function $s(e, t) {
5712
5720
  let n = process.env[e];
5713
5721
  if (n == null) return t;
5714
5722
  let r = Number.parseInt(n, 10);
5715
5723
  return Number.isFinite(r) ? r : t;
5716
5724
  }
5717
- function Qs(e) {
5725
+ function ec(e) {
5718
5726
  let t = (process.env[e] ?? "1").trim().toLowerCase();
5719
5727
  return t === "0" || t === "false" || t === "off";
5720
5728
  }
5721
- var $s = class {
5729
+ var tc = class {
5722
5730
  store;
5723
5731
  ingestOpts;
5724
5732
  active = !1;
@@ -5732,7 +5740,7 @@ var $s = class {
5732
5740
  this.store = e, this.ingestOpts = t;
5733
5741
  }
5734
5742
  enabled() {
5735
- return !Qs("CODEMEM_RAW_EVENTS_SWEEPER");
5743
+ return !ec("CODEMEM_RAW_EVENTS_SWEEPER");
5736
5744
  }
5737
5745
  intervalMs() {
5738
5746
  let e = process.env.CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_MS;
@@ -5740,29 +5748,29 @@ var $s = class {
5740
5748
  let t = Number.parseInt(e, 10);
5741
5749
  return Number.isFinite(t) ? Math.max(1e3, t) : 3e4;
5742
5750
  }
5743
- let t = vn().raw_events_sweeper_interval_s, n = typeof t == "number" ? t : typeof t == "string" ? Number.parseInt(t, 10) : NaN;
5751
+ let t = yn().raw_events_sweeper_interval_s, n = typeof t == "number" ? t : typeof t == "string" ? Number.parseInt(t, 10) : NaN;
5744
5752
  return Number.isFinite(n) && n > 0 ? Math.max(1e3, n * 1e3) : 3e4;
5745
5753
  }
5746
5754
  idleMs() {
5747
- return Zs("CODEMEM_RAW_EVENTS_SWEEPER_IDLE_MS", 12e4);
5755
+ return $s("CODEMEM_RAW_EVENTS_SWEEPER_IDLE_MS", 12e4);
5748
5756
  }
5749
5757
  limit() {
5750
- return Zs("CODEMEM_RAW_EVENTS_SWEEPER_LIMIT", 25);
5758
+ return $s("CODEMEM_RAW_EVENTS_SWEEPER_LIMIT", 25);
5751
5759
  }
5752
5760
  workerMaxEvents() {
5753
- let e = Zs("CODEMEM_RAW_EVENTS_WORKER_MAX_EVENTS", 250);
5761
+ let e = $s("CODEMEM_RAW_EVENTS_WORKER_MAX_EVENTS", 250);
5754
5762
  return e <= 0 ? null : e;
5755
5763
  }
5756
5764
  retentionMs() {
5757
- return Zs("CODEMEM_RAW_EVENTS_RETENTION_MS", 0);
5765
+ return $s("CODEMEM_RAW_EVENTS_RETENTION_MS", 0);
5758
5766
  }
5759
5767
  stuckBatchMs() {
5760
- return Zs("CODEMEM_RAW_EVENTS_STUCK_BATCH_MS", 3e5);
5768
+ return $s("CODEMEM_RAW_EVENTS_STUCK_BATCH_MS", 3e5);
5761
5769
  }
5762
5770
  handleAuthError(e) {
5763
- if (this.authBackoffUntil = Date.now() / 1e3 + Xs, !this.authErrorLogged) {
5771
+ if (this.authBackoffUntil = Date.now() / 1e3 + Qs, !this.authErrorLogged) {
5764
5772
  this.authErrorLogged = !0;
5765
- let t = `codemem: observer auth error — backing off for ${Xs}s. Refresh your provider credentials or update observer_provider in settings. (${e.message})`;
5773
+ let t = `codemem: observer auth error — backing off for ${Qs}s. Refresh your provider credentials or update observer_provider in settings. (${e.message})`;
5766
5774
  console.error(t);
5767
5775
  }
5768
5776
  }
@@ -5823,7 +5831,7 @@ var $s = class {
5823
5831
  for (let e of s) {
5824
5832
  let { source: t, streamId: n } = e;
5825
5833
  if (n) try {
5826
- await Ys(this.store, this.ingestOpts, {
5834
+ await Zs(this.store, this.ingestOpts, {
5827
5835
  opencodeSessionId: n,
5828
5836
  source: t,
5829
5837
  cwd: null,
@@ -5832,7 +5840,7 @@ var $s = class {
5832
5840
  maxEvents: i
5833
5841
  }), o.add(`${t}:${n}`);
5834
5842
  } catch (e) {
5835
- if (e instanceof $) {
5843
+ if (e instanceof Q) {
5836
5844
  this.handleAuthError(e);
5837
5845
  return;
5838
5846
  }
@@ -5843,7 +5851,7 @@ var $s = class {
5843
5851
  for (let e of c) {
5844
5852
  let { source: t, streamId: n } = e;
5845
5853
  if (n && !o.has(`${t}:${n}`)) try {
5846
- await Ys(this.store, this.ingestOpts, {
5854
+ await Zs(this.store, this.ingestOpts, {
5847
5855
  opencodeSessionId: n,
5848
5856
  source: t,
5849
5857
  cwd: null,
@@ -5852,7 +5860,7 @@ var $s = class {
5852
5860
  maxEvents: i
5853
5861
  });
5854
5862
  } catch (e) {
5855
- if (e instanceof $) {
5863
+ if (e instanceof Q) {
5856
5864
  this.handleAuthError(e);
5857
5865
  return;
5858
5866
  }
@@ -5863,7 +5871,7 @@ var $s = class {
5863
5871
  };
5864
5872
  //#endregion
5865
5873
  //#region src/sync-replication.ts
5866
- function ec(e, t) {
5874
+ function nc(e, t) {
5867
5875
  let n = new TextEncoder(), r = [], i = [], a = 9;
5868
5876
  for (let o of e) {
5869
5877
  let e = n.encode(JSON.stringify(o)).byteLength, s = i.length === 0 ? e : e + 1;
@@ -5875,14 +5883,14 @@ function ec(e, t) {
5875
5883
  }
5876
5884
  return i.length > 0 && r.push(i), r;
5877
5885
  }
5878
- function tc(e, t) {
5886
+ function rc(e, t) {
5879
5887
  let n = j(e, { schema: R }).select({
5880
5888
  last_applied_cursor: U.last_applied_cursor,
5881
5889
  last_acked_cursor: U.last_acked_cursor
5882
5890
  }).from(U).where(O(U.peer_device_id, t)).get();
5883
5891
  return n ? [n.last_applied_cursor, n.last_acked_cursor] : [null, null];
5884
5892
  }
5885
- function nc(e, t, n = {}) {
5893
+ function ic(e, t, n = {}) {
5886
5894
  let r = (/* @__PURE__ */ new Date()).toISOString(), i = n.lastApplied ?? null, a = n.lastAcked ?? null;
5887
5895
  j(e, { schema: R }).insert(U).values({
5888
5896
  peer_device_id: t,
@@ -5898,7 +5906,7 @@ function nc(e, t, n = {}) {
5898
5906
  }
5899
5907
  }).run();
5900
5908
  }
5901
- var rc = [
5909
+ var ac = [
5902
5910
  "op_id",
5903
5911
  "entity_type",
5904
5912
  "entity_id",
@@ -5909,28 +5917,28 @@ var rc = [
5909
5917
  "device_id",
5910
5918
  "created_at"
5911
5919
  ];
5912
- function ic(e) {
5920
+ function oc(e) {
5913
5921
  if (typeof e != "object" || !e) return [];
5914
5922
  let t = e.ops;
5915
5923
  return Array.isArray(t) ? t.filter((e) => {
5916
5924
  if (typeof e != "object" || !e) return !1;
5917
5925
  let t = e;
5918
- return rc.every((e) => t[e] !== void 0 && t[e] !== null);
5926
+ return ac.every((e) => t[e] !== void 0 && t[e] !== null);
5919
5927
  }) : [];
5920
5928
  }
5921
- function ac(e, t, n) {
5929
+ function sc(e, t, n) {
5922
5930
  return [
5923
5931
  e,
5924
5932
  t,
5925
5933
  n
5926
5934
  ];
5927
5935
  }
5928
- function oc(e, t) {
5936
+ function cc(e, t) {
5929
5937
  return e[0] === t[0] ? e[1] === t[1] ? e[2] > t[2] : e[1] > t[1] : e[0] > t[0];
5930
5938
  }
5931
- function sc(e, t) {
5932
- let n = j(e, { schema: R }), r = a(), i = (/* @__PURE__ */ new Date()).toISOString(), o = n.select().from(B).where(O(B.id, t.memoryId)).get(), s = Number(o?.rev ?? 0), c = o?.updated_at ?? i, l = o?.import_key ?? String(t.memoryId), u = J(o?.metadata_json).clock_device_id || t.deviceId, d;
5933
- if (t.payload) d = Y(t.payload);
5939
+ function lc(e, t) {
5940
+ let n = j(e, { schema: R }), r = a(), i = (/* @__PURE__ */ new Date()).toISOString(), o = n.select().from(B).where(O(B.id, t.memoryId)).get(), s = Number(o?.rev ?? 0), c = o?.updated_at ?? i, l = o?.import_key ?? String(t.memoryId), u = q(o?.metadata_json).clock_device_id || t.deviceId, d;
5941
+ if (t.payload) d = J(t.payload);
5934
5942
  else if (o && t.opType === "upsert") {
5935
5943
  let e = (e) => {
5936
5944
  if (typeof e != "string") return e ?? null;
@@ -5940,7 +5948,7 @@ function sc(e, t) {
5940
5948
  return e;
5941
5949
  }
5942
5950
  };
5943
- d = Y({
5951
+ d = J({
5944
5952
  session_id: o.session_id,
5945
5953
  kind: o.kind,
5946
5954
  title: o.title,
@@ -5983,17 +5991,17 @@ function sc(e, t) {
5983
5991
  created_at: i
5984
5992
  }).run(), r;
5985
5993
  }
5986
- function cc(e) {
5994
+ function uc(e) {
5987
5995
  let t = e.indexOf("|");
5988
5996
  return t < 0 ? null : [e.slice(0, t), e.slice(t + 1)];
5989
5997
  }
5990
- function lc(e, t) {
5998
+ function dc(e, t) {
5991
5999
  return `${e}|${t}`;
5992
6000
  }
5993
- function uc(e, t, n = 100, r) {
6001
+ function fc(e, t, n = 100, r) {
5994
6002
  let i = j(e, { schema: R }), a = on, o = [];
5995
6003
  if (t) {
5996
- let e = cc(t);
6004
+ let e = uc(t);
5997
6005
  if (e) {
5998
6006
  let [t, n] = e;
5999
6007
  o.push(ie(k(a.created_at, t), E(O(a.created_at, t), k(a.op_id, n))));
@@ -6014,11 +6022,11 @@ function uc(e, t, n = 100, r) {
6014
6022
  })), u = null;
6015
6023
  if (c.length > 0) {
6016
6024
  let e = c.at(-1);
6017
- e && (u = lc(e.created_at, e.op_id));
6025
+ e && (u = dc(e.created_at, e.op_id));
6018
6026
  }
6019
6027
  return [l, u];
6020
6028
  }
6021
- function dc(e, t, n) {
6029
+ function pc(e, t, n) {
6022
6030
  let r = j(e, { schema: R }), i = {
6023
6031
  applied: 0,
6024
6032
  skipped: 0,
@@ -6042,29 +6050,34 @@ function dc(e, t, n) {
6042
6050
  updated_at: B.updated_at,
6043
6051
  metadata_json: B.metadata_json
6044
6052
  }).from(B).where(O(B.import_key, t)).get(), a = (t) => {
6045
- if (!t) return {};
6046
- let n = J(t);
6047
- return typeof n != "object" || !n ? (i.errors.push(`op ${e.op_id}: payload_json is not a valid object`), {}) : n;
6053
+ if (!t) return null;
6054
+ try {
6055
+ return Qn(t);
6056
+ } catch (t) {
6057
+ return i.errors.push(`op ${e.op_id}: skipped — payload_json is not a valid object: ${t instanceof Error ? t.message : String(t)}`), null;
6058
+ }
6048
6059
  };
6049
6060
  if (n) {
6050
- let o = J(n.metadata_json).clock_device_id || "", s = ac(n.rev ?? 0, n.updated_at ?? "", o);
6051
- if (!oc(ac(e.clock_rev, e.clock_updated_at, e.clock_device_id), s)) {
6052
- i.conflicts++, fc(r, e);
6061
+ let o = q(n.metadata_json).clock_device_id ?? "", s = sc(n.rev ?? 0, n.updated_at ?? "", o);
6062
+ if (!cc(sc(e.clock_rev, e.clock_updated_at, e.clock_device_id), s)) {
6063
+ i.conflicts++, mc(r, e);
6053
6064
  continue;
6054
6065
  }
6055
- let c = a(e.payload_json), l = c.metadata_json ?? {}, u = typeof l == "object" && l ? l : {};
6066
+ let c = a(e.payload_json);
6067
+ if (!c) continue;
6068
+ let l = c.metadata_json ?? {}, u = typeof l == "object" && l ? l : {};
6056
6069
  u.clock_device_id = e.clock_device_id, r.update(B).set({
6057
- kind: A`COALESCE(${c.kind || null}, ${B.kind})`,
6058
- title: A`COALESCE(${c.title || null}, ${B.title})`,
6070
+ kind: A`COALESCE(${c.kind ?? null}, ${B.kind})`,
6071
+ title: A`COALESCE(${c.title ?? null}, ${B.title})`,
6059
6072
  subtitle: c.subtitle ?? null,
6060
- body_text: A`COALESCE(${c.body_text || null}, ${B.body_text})`,
6073
+ body_text: A`COALESCE(${c.body_text ?? null}, ${B.body_text})`,
6061
6074
  confidence: A`COALESCE(${c.confidence == null ? null : Number(c.confidence)}, ${B.confidence})`,
6062
6075
  tags_text: A`COALESCE(${c.tags_text ?? null}, ${B.tags_text})`,
6063
6076
  active: A`COALESCE(${c.active == null ? null : Number(c.active)}, ${B.active})`,
6064
6077
  updated_at: e.clock_updated_at,
6065
- metadata_json: Y(u),
6078
+ metadata_json: J(u),
6066
6079
  rev: e.clock_rev,
6067
- deleted_at: c.deleted_at || null,
6080
+ deleted_at: c.deleted_at ?? null,
6068
6081
  actor_id: A`COALESCE(${c.actor_id ?? null}, ${B.actor_id})`,
6069
6082
  actor_display_name: A`COALESCE(${c.actor_display_name ?? null}, ${B.actor_display_name})`,
6070
6083
  visibility: A`COALESCE(${c.visibility ?? null}, ${B.visibility})`,
@@ -6074,27 +6087,29 @@ function dc(e, t, n) {
6074
6087
  origin_source: A`COALESCE(${c.origin_source ?? null}, ${B.origin_source})`,
6075
6088
  trust_state: A`COALESCE(${c.trust_state ?? null}, ${B.trust_state})`,
6076
6089
  narrative: c.narrative ?? null,
6077
- facts: X(c.facts),
6078
- concepts: X(c.concepts),
6079
- files_read: X(c.files_read),
6080
- files_modified: X(c.files_modified)
6090
+ facts: Y(c.facts),
6091
+ concepts: Y(c.concepts),
6092
+ files_read: Y(c.files_read),
6093
+ files_modified: Y(c.files_modified)
6081
6094
  }).where(O(B.import_key, t)).run();
6082
6095
  } else {
6083
- let n = a(e.payload_json), i = pc(r, null, e.clock_updated_at), o = n.metadata_json ?? {}, s = typeof o == "object" && o ? o : {};
6096
+ let n = a(e.payload_json);
6097
+ if (!n) continue;
6098
+ let i = hc(r, null, e.clock_updated_at), o = n.metadata_json ?? {}, s = typeof o == "object" && o ? o : {};
6084
6099
  s.clock_device_id = e.clock_device_id, r.insert(B).values({
6085
6100
  session_id: i,
6086
- kind: n.kind || "discovery",
6087
- title: n.title || "",
6101
+ kind: n.kind ?? "discovery",
6102
+ title: n.title ?? "",
6088
6103
  subtitle: n.subtitle ?? null,
6089
- body_text: n.body_text || "",
6104
+ body_text: n.body_text ?? "",
6090
6105
  confidence: n.confidence == null ? .5 : Number(n.confidence),
6091
- tags_text: n.tags_text || "",
6106
+ tags_text: n.tags_text ?? "",
6092
6107
  active: n.active == null ? 1 : Number(n.active),
6093
- created_at: n.created_at || e.clock_updated_at,
6108
+ created_at: n.created_at ?? e.clock_updated_at,
6094
6109
  updated_at: e.clock_updated_at,
6095
- metadata_json: Y(s),
6110
+ metadata_json: J(s),
6096
6111
  import_key: t,
6097
- deleted_at: n.deleted_at || null,
6112
+ deleted_at: n.deleted_at ?? null,
6098
6113
  rev: e.clock_rev,
6099
6114
  actor_id: n.actor_id ?? null,
6100
6115
  actor_display_name: n.actor_display_name ?? null,
@@ -6105,10 +6120,10 @@ function dc(e, t, n) {
6105
6120
  origin_source: n.origin_source ?? null,
6106
6121
  trust_state: n.trust_state ?? null,
6107
6122
  narrative: n.narrative ?? null,
6108
- facts: X(n.facts),
6109
- concepts: X(n.concepts),
6110
- files_read: X(n.files_read),
6111
- files_modified: X(n.files_modified)
6123
+ facts: Y(n.facts),
6124
+ concepts: Y(n.concepts),
6125
+ files_read: Y(n.files_read),
6126
+ files_modified: Y(n.files_modified)
6112
6127
  }).run();
6113
6128
  }
6114
6129
  } else if (e.op_type === "delete") {
@@ -6119,9 +6134,9 @@ function dc(e, t, n) {
6119
6134
  metadata_json: B.metadata_json
6120
6135
  }).from(B).where(O(B.import_key, t)).limit(1).get();
6121
6136
  if (n) {
6122
- let t = J(n.metadata_json), a = ac(n.rev ?? 1, n.updated_at ?? "", String(t.clock_device_id ?? ""));
6123
- if (!oc(ac(e.clock_rev, e.clock_updated_at, e.clock_device_id), a)) {
6124
- i.conflicts++, fc(r, e);
6137
+ let t = q(n.metadata_json), a = sc(n.rev ?? 1, n.updated_at ?? "", String(t.clock_device_id ?? ""));
6138
+ if (!cc(sc(e.clock_rev, e.clock_updated_at, e.clock_device_id), a)) {
6139
+ i.conflicts++, mc(r, e);
6125
6140
  continue;
6126
6141
  }
6127
6142
  let o = (/* @__PURE__ */ new Date()).toISOString();
@@ -6133,16 +6148,16 @@ function dc(e, t, n) {
6133
6148
  }).where(O(B.id, n.id)).run();
6134
6149
  }
6135
6150
  } else {
6136
- i.skipped++, fc(r, e);
6151
+ i.skipped++, mc(r, e);
6137
6152
  continue;
6138
6153
  }
6139
- fc(r, e), i.applied++;
6154
+ mc(r, e), i.applied++;
6140
6155
  } catch (t) {
6141
6156
  i.errors.push(`op ${e.op_id}: ${t instanceof Error ? t.message : String(t)}`);
6142
6157
  }
6143
6158
  })(), i;
6144
6159
  }
6145
- function fc(e, t) {
6160
+ function mc(e, t) {
6146
6161
  e.insert(on).values({
6147
6162
  op_id: t.op_id,
6148
6163
  entity_type: t.entity_type,
@@ -6156,20 +6171,20 @@ function fc(e, t) {
6156
6171
  created_at: t.created_at
6157
6172
  }).onConflictDoNothing().run();
6158
6173
  }
6159
- function pc(e, t, n) {
6174
+ function hc(e, t, n) {
6160
6175
  if (t != null && e.select({ id: z.id }).from(z).where(O(z.id, t)).get()) return t;
6161
6176
  let r = n || (/* @__PURE__ */ new Date()).toISOString(), i = e.insert(z).values({
6162
6177
  started_at: r,
6163
6178
  user: "sync",
6164
6179
  tool_version: "sync_replication",
6165
- metadata_json: Y({ source: "sync" })
6180
+ metadata_json: J({ source: "sync" })
6166
6181
  }).returning({ id: z.id }).all()[0]?.id;
6167
6182
  if (i == null) throw Error("session insert returned no id");
6168
6183
  return i;
6169
6184
  }
6170
6185
  //#endregion
6171
6186
  //#region src/store.ts
6172
- var mc = new Set([
6187
+ var gc = new Set([
6173
6188
  "discovery",
6174
6189
  "change",
6175
6190
  "feature",
@@ -6178,27 +6193,27 @@ var mc = new Set([
6178
6193
  "decision",
6179
6194
  "exploration"
6180
6195
  ]);
6181
- function hc(e) {
6196
+ function _c(e) {
6182
6197
  let t = e.trim().toLowerCase();
6183
- if (!mc.has(t)) throw Error(`Invalid memory kind "${e}". Allowed: ${[...mc].join(", ")}`);
6198
+ if (!gc.has(t)) throw Error(`Invalid memory kind "${e}". Allowed: ${[...gc].join(", ")}`);
6184
6199
  return t;
6185
6200
  }
6186
- function gc() {
6201
+ function vc() {
6187
6202
  return (/* @__PURE__ */ new Date()).toISOString();
6188
6203
  }
6189
- function _c(e) {
6204
+ function $(e) {
6190
6205
  if (e == null || typeof e != "string") return null;
6191
6206
  let t = e.trim();
6192
6207
  return t.length > 0 ? t : null;
6193
6208
  }
6194
- function vc(e) {
6209
+ function yc(e) {
6195
6210
  let { metadata_json: t, ...n } = e;
6196
6211
  return {
6197
6212
  ...n,
6198
- metadata_json: J(t)
6213
+ metadata_json: q(t)
6199
6214
  };
6200
6215
  }
6201
- var yc = class {
6216
+ var bc = class {
6202
6217
  db;
6203
6218
  dbPath;
6204
6219
  deviceId;
@@ -6208,10 +6223,10 @@ var yc = class {
6208
6223
  get d() {
6209
6224
  return this._drizzle ||= j(this.db, { schema: R }), this._drizzle;
6210
6225
  }
6211
- constructor(e = Rn) {
6212
- this.dbPath = zn(e), Jn(this.dbPath), this.db = Wn(this.dbPath);
6226
+ constructor(e = zn) {
6227
+ this.dbPath = Bn(e), Yn(this.dbPath), this.db = Gn(this.dbPath);
6213
6228
  try {
6214
- Gn(this.db), Yn(this.db);
6229
+ Kn(this.db), Xn(this.db);
6215
6230
  } catch (e) {
6216
6231
  throw this.db.close(), e;
6217
6232
  }
@@ -6224,15 +6239,15 @@ var yc = class {
6224
6239
  } catch {}
6225
6240
  this.deviceId = e ?? "local";
6226
6241
  }
6227
- let n = vn();
6228
- this.actorId = (Object.hasOwn(process.env, "CODEMEM_ACTOR_ID") ? _c(process.env.CODEMEM_ACTOR_ID) : _c(n.actor_id) ?? null) || `local:${this.deviceId}`, this.actorDisplayName = (Object.hasOwn(process.env, "CODEMEM_ACTOR_DISPLAY_NAME") ? _c(process.env.CODEMEM_ACTOR_DISPLAY_NAME) : _c(n.actor_display_name) ?? null) || process.env.USER?.trim() || process.env.USERNAME?.trim() || this.actorId;
6242
+ let n = yn();
6243
+ this.actorId = (Object.hasOwn(process.env, "CODEMEM_ACTOR_ID") ? $(process.env.CODEMEM_ACTOR_ID) : $(n.actor_id) ?? null) || `local:${this.deviceId}`, this.actorDisplayName = (Object.hasOwn(process.env, "CODEMEM_ACTOR_DISPLAY_NAME") ? $(process.env.CODEMEM_ACTOR_DISPLAY_NAME) : $(n.actor_display_name) ?? null) || process.env.USER?.trim() || process.env.USERNAME?.trim() || this.actorId;
6229
6244
  }
6230
6245
  get(e) {
6231
6246
  let t = this.d.select().from(B).where(O(B.id, e)).get();
6232
- return t ? vc(t) : null;
6247
+ return t ? yc(t) : null;
6233
6248
  }
6234
6249
  startSession(e) {
6235
- let t = gc(), n = this.d.insert(z).values({
6250
+ let t = vc(), n = this.d.insert(z).values({
6236
6251
  started_at: t,
6237
6252
  cwd: e.cwd ?? process.cwd(),
6238
6253
  project: e.project ?? null,
@@ -6240,26 +6255,26 @@ var yc = class {
6240
6255
  git_branch: e.gitBranch ?? null,
6241
6256
  user: e.user ?? process.env.USER ?? "unknown",
6242
6257
  tool_version: e.toolVersion ?? "manual",
6243
- metadata_json: Y(e.metadata ?? {})
6258
+ metadata_json: J(e.metadata ?? {})
6244
6259
  }).returning({ id: z.id }).all()[0]?.id;
6245
6260
  if (n == null) throw Error("session insert returned no id");
6246
6261
  return n;
6247
6262
  }
6248
6263
  endSession(e, t) {
6249
- let n = gc();
6264
+ let n = vc();
6250
6265
  if (t) {
6251
6266
  let r = {
6252
- ...J(this.d.select({ metadata_json: z.metadata_json }).from(z).where(O(z.id, e)).get()?.metadata_json),
6267
+ ...q(this.d.select({ metadata_json: z.metadata_json }).from(z).where(O(z.id, e)).get()?.metadata_json),
6253
6268
  ...t
6254
6269
  };
6255
6270
  this.d.update(z).set({
6256
6271
  ended_at: n,
6257
- metadata_json: Y(r)
6272
+ metadata_json: J(r)
6258
6273
  }).where(O(z.id, e)).run();
6259
6274
  } else this.d.update(z).set({ ended_at: n }).where(O(z.id, e)).run();
6260
6275
  }
6261
6276
  remember(e, t, n, r, i = .5, o, s) {
6262
- let c = hc(t), l = gc(), u = o ? [...new Set(o)].sort().join(" ") : "", d = { ...s ?? {} };
6277
+ let c = _c(t), l = vc(), u = o ? [...new Set(o)].sort().join(" ") : "", d = { ...s ?? {} };
6263
6278
  d.clock_device_id ??= this.deviceId;
6264
6279
  let f = d.import_key || a();
6265
6280
  d.import_key = f;
@@ -6274,7 +6289,7 @@ var yc = class {
6274
6289
  active: 1,
6275
6290
  created_at: l,
6276
6291
  updated_at: l,
6277
- metadata_json: Y(d),
6292
+ metadata_json: J(d),
6278
6293
  actor_id: x.actor_id,
6279
6294
  actor_display_name: x.actor_display_name,
6280
6295
  visibility: x.visibility,
@@ -6284,10 +6299,10 @@ var yc = class {
6284
6299
  origin_source: x.origin_source,
6285
6300
  trust_state: x.trust_state,
6286
6301
  narrative: m,
6287
- facts: X(h),
6288
- concepts: X(g),
6289
- files_read: X(_),
6290
- files_modified: X(v),
6302
+ facts: Y(h),
6303
+ concepts: Y(g),
6304
+ files_read: Y(_),
6305
+ files_modified: Y(v),
6291
6306
  prompt_number: y,
6292
6307
  user_prompt_id: b,
6293
6308
  deleted_at: null,
@@ -6296,7 +6311,7 @@ var yc = class {
6296
6311
  }).returning({ id: B.id }).all()[0]?.id;
6297
6312
  if (S == null) throw Error("memory insert returned no id");
6298
6313
  try {
6299
- sc(this.db, {
6314
+ lc(this.db, {
6300
6315
  memoryId: S,
6301
6316
  opType: "upsert",
6302
6317
  deviceId: this.deviceId
@@ -6327,43 +6342,45 @@ var yc = class {
6327
6342
  }
6328
6343
  memoryOwnedBySelf(e) {
6329
6344
  let t = e, n = t.metadata ?? {};
6330
- return (_c(t.actor_id) ?? _c(n.actor_id)) === this.actorId || (_c(t.origin_device_id) ?? _c(n.origin_device_id)) === this.deviceId;
6345
+ return ($(t.actor_id) ?? $(n.actor_id)) === this.actorId || ($(t.origin_device_id) ?? $(n.origin_device_id)) === this.deviceId;
6331
6346
  }
6332
6347
  forget(e) {
6333
- let t = this.d.select({
6334
- rev: B.rev,
6335
- metadata_json: B.metadata_json
6336
- }).from(B).where(O(B.id, e)).get();
6337
- if (!t) return;
6338
- let n = J(t.metadata_json);
6339
- n.clock_device_id = this.deviceId;
6340
- let r = gc(), i = (t.rev ?? 0) + 1;
6341
- this.d.update(B).set({
6342
- active: 0,
6343
- deleted_at: r,
6344
- updated_at: r,
6345
- metadata_json: Y(n),
6346
- rev: i
6347
- }).where(O(B.id, e)).run();
6348
- try {
6349
- sc(this.db, {
6350
- memoryId: e,
6351
- opType: "delete",
6352
- deviceId: this.deviceId
6353
- });
6354
- } catch {}
6348
+ this.db.transaction(() => {
6349
+ let t = this.d.select({
6350
+ rev: B.rev,
6351
+ metadata_json: B.metadata_json
6352
+ }).from(B).where(O(B.id, e)).get();
6353
+ if (!t) return;
6354
+ let n = q(t.metadata_json);
6355
+ n.clock_device_id = this.deviceId;
6356
+ let r = vc(), i = (t.rev ?? 0) + 1;
6357
+ this.d.update(B).set({
6358
+ active: 0,
6359
+ deleted_at: r,
6360
+ updated_at: r,
6361
+ metadata_json: J(n),
6362
+ rev: i
6363
+ }).where(O(B.id, e)).run();
6364
+ try {
6365
+ lc(this.db, {
6366
+ memoryId: e,
6367
+ opType: "delete",
6368
+ deviceId: this.deviceId
6369
+ });
6370
+ } catch {}
6371
+ }).immediate();
6355
6372
  }
6356
6373
  recent(e = 10, t, n = 0) {
6357
- let r = ["memory_items.active = 1"], i = Ci(t), a = [...r, ...i.clauses].join(" AND "), o = i.joinSessions ? "memory_items JOIN sessions ON sessions.id = memory_items.session_id" : "memory_items";
6374
+ let r = ["memory_items.active = 1"], i = Ti(t), a = [...r, ...i.clauses].join(" AND "), o = i.joinSessions ? "memory_items JOIN sessions ON sessions.id = memory_items.session_id" : "memory_items";
6358
6375
  return this.db.prepare(`SELECT memory_items.* FROM ${o}
6359
6376
  WHERE ${a}
6360
6377
  ORDER BY created_at DESC
6361
- LIMIT ? OFFSET ?`).all(...i.params, e, Math.max(n, 0)).map((e) => vc(e));
6378
+ LIMIT ? OFFSET ?`).all(...i.params, e, Math.max(n, 0)).map((e) => yc(e));
6362
6379
  }
6363
6380
  recentByKinds(e, t = 10, n, r = 0) {
6364
6381
  let i = e.filter((e) => e.length > 0);
6365
6382
  if (i.length === 0) return [];
6366
- let a = ["memory_items.active = 1", `memory_items.kind IN (${i.map(() => "?").join(", ")})`], o = Ci(n), s = [...a, ...o.clauses].join(" AND "), c = o.joinSessions ? "memory_items JOIN sessions ON sessions.id = memory_items.session_id" : "memory_items", l = [
6383
+ let a = ["memory_items.active = 1", `memory_items.kind IN (${i.map(() => "?").join(", ")})`], o = Ti(n), s = [...a, ...o.clauses].join(" AND "), c = o.joinSessions ? "memory_items JOIN sessions ON sessions.id = memory_items.session_id" : "memory_items", l = [
6367
6384
  ...i,
6368
6385
  ...o.params,
6369
6386
  t,
@@ -6372,11 +6389,11 @@ var yc = class {
6372
6389
  return this.db.prepare(`SELECT memory_items.* FROM ${c}
6373
6390
  WHERE ${s}
6374
6391
  ORDER BY created_at DESC
6375
- LIMIT ? OFFSET ?`).all(...l).map((e) => vc(e));
6392
+ LIMIT ? OFFSET ?`).all(...l).map((e) => yc(e));
6376
6393
  }
6377
6394
  stats() {
6378
6395
  let e = (e) => this.d.select({ c: A`COUNT(*)` }).from(e).get()?.c ?? 0, t = e(B), n = this.d.select({ c: A`COUNT(*)` }).from(B).where(O(B.active, 1)).get()?.c ?? 0, r = e(z), i = e($t), a = e(V), o = 0;
6379
- Xn(this.db, "memory_vectors") && (o = this.db.prepare("SELECT COUNT(*) AS c FROM memory_vectors").get()?.c ?? 0);
6396
+ Zn(this.db, "memory_vectors") && (o = this.db.prepare("SELECT COUNT(*) AS c FROM memory_vectors").get()?.c ?? 0);
6380
6397
  let s = n > 0 ? Math.min(1, o / n) : 0, c = this.d.select({ c: A`COUNT(*)` }).from(B).where(E(O(B.active, 1), A`TRIM(tags_text) != ''`)).get()?.c ?? 0, l = n > 0 ? Math.min(1, c / n) : 0, u = 0;
6381
6398
  try {
6382
6399
  u = m(this.dbPath).size;
@@ -6427,45 +6444,47 @@ var yc = class {
6427
6444
  updateMemoryVisibility(e, t) {
6428
6445
  let n = t.trim();
6429
6446
  if (n !== "private" && n !== "shared") throw Error("visibility must be private or shared");
6430
- let r = this.d.select().from(B).where(E(O(B.id, e), O(B.active, 1))).get();
6431
- if (!r) throw Error("memory not found");
6432
- if (!this.memoryOwnedBySelf(r)) throw Error("memory not owned by this device");
6433
- let i = _c(r.actor_id) ?? this.actorId, a = n === "shared" ? "shared" : "personal", o = n === "shared" && r.workspace_id?.startsWith("shared:") ? r.workspace_id : a === "personal" ? `personal:${i}` : "shared:default", s = J(r.metadata_json);
6434
- s.visibility = n, s.workspace_kind = a, s.workspace_id = o, s.clock_device_id = this.deviceId;
6435
- let c = gc(), l = (r.rev ?? 0) + 1;
6436
- this.d.update(B).set({
6437
- visibility: n,
6438
- workspace_kind: a,
6439
- workspace_id: o,
6440
- updated_at: c,
6441
- metadata_json: Y(s),
6442
- rev: l
6443
- }).where(O(B.id, e)).run();
6444
- try {
6445
- sc(this.db, {
6446
- memoryId: e,
6447
- opType: "upsert",
6448
- deviceId: this.deviceId
6449
- });
6450
- } catch {}
6451
- let u = this.get(e);
6452
- if (!u) throw Error("memory not found after update");
6453
- return u;
6447
+ return this.db.transaction(() => {
6448
+ let t = this.d.select().from(B).where(E(O(B.id, e), O(B.active, 1))).get();
6449
+ if (!t) throw Error("memory not found");
6450
+ if (!this.memoryOwnedBySelf(t)) throw Error("memory not owned by this device");
6451
+ let r = $(t.actor_id) ?? this.actorId, i = n === "shared" ? "shared" : "personal", a = n === "shared" && t.workspace_id?.startsWith("shared:") ? t.workspace_id : i === "personal" ? `personal:${r}` : "shared:default", o = q(t.metadata_json);
6452
+ o.visibility = n, o.workspace_kind = i, o.workspace_id = a, o.clock_device_id = this.deviceId;
6453
+ let s = vc(), c = (t.rev ?? 0) + 1;
6454
+ this.d.update(B).set({
6455
+ visibility: n,
6456
+ workspace_kind: i,
6457
+ workspace_id: a,
6458
+ updated_at: s,
6459
+ metadata_json: J(o),
6460
+ rev: c
6461
+ }).where(O(B.id, e)).run();
6462
+ try {
6463
+ lc(this.db, {
6464
+ memoryId: e,
6465
+ opType: "upsert",
6466
+ deviceId: this.deviceId
6467
+ });
6468
+ } catch {}
6469
+ let l = this.get(e);
6470
+ if (!l) throw Error("memory not found after update");
6471
+ return l;
6472
+ }).immediate();
6454
6473
  }
6455
6474
  search(e, t = 10, n) {
6456
- return ys(this, e, t, n);
6475
+ return xs(this, e, t, n);
6457
6476
  }
6458
6477
  timeline(e, t, n = 3, r = 3, i) {
6459
- return xs(this, e, t, n, r, i);
6478
+ return Cs(this, e, t, n, r, i);
6460
6479
  }
6461
6480
  explain(e, t, n = 10, r) {
6462
- return Ds(this, e, t, n, r);
6481
+ return ks(this, e, t, n, r);
6463
6482
  }
6464
6483
  buildMemoryPack(e, t, n, r) {
6465
- return Hs(this, e, t, n ?? null, r);
6484
+ return Ws(this, e, t, n ?? null, r);
6466
6485
  }
6467
6486
  async buildMemoryPackAsync(e, t, n, r) {
6468
- return Us(this, e, t, n ?? null, r);
6487
+ return Gs(this, e, t, n ?? null, r);
6469
6488
  }
6470
6489
  normalizeStreamIdentity(e, t) {
6471
6490
  let n = e.trim().toLowerCase() || "opencode", r = t.trim();
@@ -6524,7 +6543,7 @@ var yc = class {
6524
6543
  WHERE source = ? AND stream_id = ? AND event_seq > ?
6525
6544
  ORDER BY event_seq ASC
6526
6545
  ${o}`).all(...s).map((e) => {
6527
- let t = J(e.payload_json);
6546
+ let t = q(e.payload_json);
6528
6547
  return t.type = t.type || e.event_type, t.timestamp_wall_ms = e.ts_wall_ms, t.timestamp_mono_ms = e.ts_mono_ms, t.event_seq = e.event_seq, t.event_id = e.event_id, t;
6529
6548
  });
6530
6549
  }
@@ -6586,14 +6605,14 @@ var yc = class {
6586
6605
  }).run();
6587
6606
  }
6588
6607
  updateRawEventIngestStats(e, t, n, r) {
6589
- let i = gc(), a = t + n + r;
6608
+ let i = vc(), a = t + n + r;
6590
6609
  this.d.insert(ln).values({
6591
6610
  created_at: i,
6592
6611
  inserted_events: e,
6593
6612
  skipped_invalid: t,
6594
6613
  skipped_duplicate: n,
6595
6614
  skipped_conflict: r
6596
- }).run(), this.d.insert(q).values({
6615
+ }).run(), this.d.insert(un).values({
6597
6616
  id: 1,
6598
6617
  inserted_events: e,
6599
6618
  skipped_events: a,
@@ -6602,13 +6621,13 @@ var yc = class {
6602
6621
  skipped_conflict: r,
6603
6622
  updated_at: i
6604
6623
  }).onConflictDoUpdate({
6605
- target: q.id,
6624
+ target: un.id,
6606
6625
  set: {
6607
- inserted_events: A`${q.inserted_events} + excluded.inserted_events`,
6608
- skipped_events: A`${q.skipped_events} + excluded.skipped_events`,
6609
- skipped_invalid: A`${q.skipped_invalid} + excluded.skipped_invalid`,
6610
- skipped_duplicate: A`${q.skipped_duplicate} + excluded.skipped_duplicate`,
6611
- skipped_conflict: A`${q.skipped_conflict} + excluded.skipped_conflict`,
6626
+ inserted_events: A`${un.inserted_events} + excluded.inserted_events`,
6627
+ skipped_events: A`${un.skipped_events} + excluded.skipped_events`,
6628
+ skipped_invalid: A`${un.skipped_invalid} + excluded.skipped_invalid`,
6629
+ skipped_duplicate: A`${un.skipped_duplicate} + excluded.skipped_duplicate`,
6630
+ skipped_conflict: A`${un.skipped_conflict} + excluded.skipped_conflict`,
6612
6631
  updated_at: A`excluded.updated_at`
6613
6632
  }
6614
6633
  }).run();
@@ -6619,7 +6638,7 @@ var yc = class {
6619
6638
  if (!e.eventType.trim()) throw Error("event_type is required");
6620
6639
  let [t, n] = this.normalizeStreamIdentity(e.source ?? "opencode", e.opencodeSessionId);
6621
6640
  return this.db.transaction(() => {
6622
- let r = gc();
6641
+ let r = vc();
6623
6642
  if (this.d.select({ one: A`1` }).from(V).where(E(O(V.source, t), O(V.stream_id, n), O(V.event_id, e.eventId))).get() != null) return this.updateRawEventIngestStats(0, 0, 1, 0), !1;
6624
6643
  this.d.select({ one: A`1` }).from(H).where(E(O(H.source, t), O(H.stream_id, n))).get() ?? this.d.insert(H).values({
6625
6644
  opencode_session_id: n,
@@ -6642,7 +6661,7 @@ var yc = class {
6642
6661
  event_type: e.eventType,
6643
6662
  ts_wall_ms: e.tsWallMs ?? null,
6644
6663
  ts_mono_ms: e.tsMonoMs ?? null,
6645
- payload_json: Y(e.payload),
6664
+ payload_json: J(e.payload),
6646
6665
  created_at: r
6647
6666
  }).run(), this.updateRawEventIngestStats(1, 0, 0, 0), !0;
6648
6667
  })();
@@ -6651,7 +6670,7 @@ var yc = class {
6651
6670
  if (!e.trim()) throw Error("opencode_session_id is required");
6652
6671
  let [n, r] = this.normalizeStreamIdentity("opencode", e);
6653
6672
  return this.db.transaction(() => {
6654
- let e = gc();
6673
+ let e = vc();
6655
6674
  this.d.select({ one: A`1` }).from(H).where(E(O(H.source, n), O(H.stream_id, r))).get() ?? this.d.insert(H).values({
6656
6675
  opencode_session_id: r,
6657
6676
  source: n,
@@ -6702,7 +6721,7 @@ var yc = class {
6702
6721
  for (let t = 0; t < u.length; t++) {
6703
6722
  let i = u[t];
6704
6723
  try {
6705
- m.run(n, r, r, i.eventId, f + t, i.eventType, i.tsWallMs ?? null, i.tsMonoMs ?? null, Y(i.payload), e), p++;
6724
+ m.run(n, r, r, i.eventId, f + t, i.eventType, i.tsWallMs ?? null, i.tsMonoMs ?? null, J(i.payload), e), p++;
6706
6725
  } catch (e) {
6707
6726
  if (e instanceof Error && e.message.includes("UNIQUE constraint")) o++;
6708
6727
  else throw e;
@@ -6715,7 +6734,7 @@ var yc = class {
6715
6734
  })();
6716
6735
  }
6717
6736
  updateRawEventSessionMeta(e) {
6718
- let [t, n] = this.normalizeStreamIdentity(e.source ?? "opencode", e.opencodeSessionId), r = gc(), i = H;
6737
+ let [t, n] = this.normalizeStreamIdentity(e.source ?? "opencode", e.opencodeSessionId), r = vc(), i = H;
6719
6738
  this.d.insert(i).values({
6720
6739
  opencode_session_id: n,
6721
6740
  source: t,
@@ -6779,7 +6798,7 @@ var yc = class {
6779
6798
  };
6780
6799
  //#endregion
6781
6800
  //#region src/address-utils.ts
6782
- function bc(e) {
6801
+ function xc(e) {
6783
6802
  let t = e.trim();
6784
6803
  if (!t) return "";
6785
6804
  let n = t.includes("://") ? t : `http://${t}`;
@@ -6790,7 +6809,7 @@ function bc(e) {
6790
6809
  return "";
6791
6810
  }
6792
6811
  }
6793
- function xc(e) {
6812
+ function Sc(e) {
6794
6813
  if (!e) return "";
6795
6814
  try {
6796
6815
  let t = new URL(e), n = t.hostname.toLowerCase();
@@ -6799,21 +6818,21 @@ function xc(e) {
6799
6818
  } catch {}
6800
6819
  return e;
6801
6820
  }
6802
- function Sc(e, t) {
6821
+ function Cc(e, t) {
6803
6822
  let n = [], r = /* @__PURE__ */ new Set();
6804
6823
  for (let i of [...e, ...t]) {
6805
- let e = bc(i), t = xc(e);
6824
+ let e = xc(i), t = Sc(e);
6806
6825
  !e || r.has(t) || (r.add(t), n.push(e));
6807
6826
  }
6808
6827
  return n;
6809
6828
  }
6810
6829
  //#endregion
6811
6830
  //#region src/sync-discovery.ts
6812
- var Cc = "_codemem._tcp.local.";
6813
- function wc(e) {
6814
- return e.mdns.length === 0 ? Sc(e.stored, []) : Sc(e.mdns, e.stored);
6831
+ var wc = "_codemem._tcp.local.";
6832
+ function Tc(e) {
6833
+ return e.mdns.length === 0 ? Cc(e.stored, []) : Cc(e.mdns, e.stored);
6815
6834
  }
6816
- function Tc(e, t) {
6835
+ function Ec(e, t) {
6817
6836
  let n = j(e, { schema: R }).select({ addresses_json: W.addresses_json }).from(W).where(O(W.peer_device_id, t)).get();
6818
6837
  if (!n?.addresses_json) return [];
6819
6838
  try {
@@ -6823,8 +6842,8 @@ function Tc(e, t) {
6823
6842
  return [];
6824
6843
  }
6825
6844
  }
6826
- function Ec(e, t, n, r) {
6827
- let i = Sc(Tc(e, t), n), a = (/* @__PURE__ */ new Date()).toISOString(), o = JSON.stringify(i);
6845
+ function Dc(e, t, n, r) {
6846
+ let i = Cc(Ec(e, t), n), a = (/* @__PURE__ */ new Date()).toISOString(), o = JSON.stringify(i);
6828
6847
  return j(e, { schema: R }).insert(W).values({
6829
6848
  peer_device_id: t,
6830
6849
  name: r?.name ?? null,
@@ -6844,7 +6863,7 @@ function Ec(e, t, n, r) {
6844
6863
  }
6845
6864
  }).run(), i;
6846
6865
  }
6847
- function Dc(e, t, n) {
6866
+ function Oc(e, t, n) {
6848
6867
  let r = j(e, { schema: R }), i = (/* @__PURE__ */ new Date()).toISOString();
6849
6868
  r.insert(K).values({
6850
6869
  peer_device_id: t,
@@ -6859,35 +6878,35 @@ function Dc(e, t, n) {
6859
6878
  last_error: null
6860
6879
  }).where(O(W.peer_device_id, t)).run() : r.update(W).set({ last_error: n.error ?? null }).where(O(W.peer_device_id, t)).run();
6861
6880
  }
6862
- function Oc(e, t, n) {
6863
- let r = Tc(e, t), i = bc(n ?? ""), a = r;
6864
- return i && (a = [i, ...r.filter((e) => bc(e) !== i)], j(e, { schema: R }).update(W).set({
6881
+ function kc(e, t, n) {
6882
+ let r = Ec(e, t), i = xc(n ?? ""), a = r;
6883
+ return i && (a = [i, ...r.filter((e) => xc(e) !== i)], j(e, { schema: R }).update(W).set({
6865
6884
  addresses_json: JSON.stringify(a),
6866
6885
  last_sync_at: (/* @__PURE__ */ new Date()).toISOString(),
6867
6886
  last_error: null
6868
6887
  }).where(O(W.peer_device_id, t)).run()), a;
6869
6888
  }
6870
- function kc(e, t, n) {
6889
+ function Ac(e, t, n) {
6871
6890
  let r = n.include === null ? null : JSON.stringify(n.include), i = n.exclude === null ? null : JSON.stringify(n.exclude);
6872
6891
  j(e, { schema: R }).update(W).set({
6873
6892
  projects_include_json: r,
6874
6893
  projects_exclude_json: i
6875
6894
  }).where(O(W.peer_device_id, t)).run();
6876
6895
  }
6877
- function Ac(e, t, n) {
6896
+ function jc(e, t, n) {
6878
6897
  j(e, { schema: R }).update(W).set({ claimed_local_actor: n ? 1 : 0 }).where(O(W.peer_device_id, t)).run();
6879
6898
  }
6880
- function jc() {
6899
+ function Mc() {
6881
6900
  let e = process.env.CODEMEM_SYNC_MDNS;
6882
6901
  return e ? e === "1" || e.toLowerCase() === "true" : !1;
6883
6902
  }
6884
- function Mc(e, t) {
6903
+ function Nc(e, t) {
6885
6904
  return { close() {} };
6886
6905
  }
6887
- function Nc() {
6906
+ function Pc() {
6888
6907
  return [];
6889
6908
  }
6890
- function Pc(e, t) {
6909
+ function Fc(e, t) {
6891
6910
  let n = [];
6892
6911
  for (let r of t) {
6893
6912
  let t = r.properties ?? {}, i = t.device_id ?? t.device_id;
@@ -6901,11 +6920,11 @@ function Pc(e, t) {
6901
6920
  }
6902
6921
  //#endregion
6903
6922
  //#region src/sync-http-client.ts
6904
- function Fc(e) {
6923
+ function Ic(e) {
6905
6924
  let t = e.trim().replace(/\/+$/, "");
6906
6925
  return t ? /^[a-z][a-z0-9+.-]*:\/\//i.test(t) ? t : `http://${t}` : "";
6907
6926
  }
6908
- async function Ic(e, t, n = {}) {
6927
+ async function Lc(e, t, n = {}) {
6909
6928
  let { headers: r, body: i, timeoutS: a = 3 } = n, { bodyBytes: o } = n;
6910
6929
  o == null && i != null && (o = new TextEncoder().encode(JSON.stringify(i)));
6911
6930
  let s = { Accept: "application/json" };
@@ -6928,19 +6947,19 @@ async function Ic(e, t, n = {}) {
6928
6947
  }
6929
6948
  //#endregion
6930
6949
  //#region src/sync-pass.ts
6931
- var Lc = 1048576, Rc = 200;
6932
- function zc(e, t) {
6950
+ var Rc = 1048576, zc = 200;
6951
+ function Bc(e, t) {
6933
6952
  return !t || !t.includes("|") ? !1 : e ? t > e : !0;
6934
6953
  }
6935
- function Bc(e) {
6954
+ function Vc(e) {
6936
6955
  if (!e) return null;
6937
6956
  let t = e.error, n = e.reason;
6938
6957
  return typeof t == "string" && typeof n == "string" ? `${t}:${n}` : typeof t == "string" ? t : null;
6939
6958
  }
6940
- function Vc(e) {
6959
+ function Hc(e) {
6941
6960
  return e.length === 0 ? null : `all addresses failed | ${e.map((e) => `${e.address}: ${e.error}`).join(" || ")}`;
6942
6961
  }
6943
- function Hc(e, t, n) {
6962
+ function Uc(e, t, n) {
6944
6963
  let r = j(e, { schema: R }), i = (/* @__PURE__ */ new Date()).toISOString();
6945
6964
  r.insert(K).values({
6946
6965
  peer_device_id: t,
@@ -6952,7 +6971,7 @@ function Hc(e, t, n) {
6952
6971
  error: n.error ?? null
6953
6972
  }).run();
6954
6973
  }
6955
- function Uc(e, t) {
6974
+ function Wc(e, t) {
6956
6975
  let n = j(e, { schema: R }), r = (/* @__PURE__ */ new Date()).toISOString();
6957
6976
  n.update(W).set({
6958
6977
  last_sync_at: r,
@@ -6960,7 +6979,7 @@ function Uc(e, t) {
6960
6979
  last_error: null
6961
6980
  }).where(O(W.peer_device_id, t)).run();
6962
6981
  }
6963
- function Wc(e, t, n) {
6982
+ function Gc(e, t, n) {
6964
6983
  if (t.length === 0) return {
6965
6984
  inserted: 0,
6966
6985
  skipped: 0
@@ -6985,7 +7004,7 @@ function Wc(e, t, n) {
6985
7004
  skipped: t.length - i
6986
7005
  };
6987
7006
  }
6988
- function Gc(e, t, n, r) {
7007
+ function Kc(e, t, n, r) {
6989
7008
  let i = j(e, { schema: R }), { replicationOps: a } = R, o;
6990
7009
  if (t) {
6991
7010
  let e = t.indexOf("|"), s = e >= 0 ? t.slice(0, e) : t, c = e >= 0 ? t.slice(e + 1) : "";
@@ -6997,11 +7016,11 @@ function Gc(e, t, n, r) {
6997
7016
  let c = `${s.created_at}|${s.op_id}`;
6998
7017
  return [o, c];
6999
7018
  }
7000
- var Kc = 8;
7001
- async function qc(e, t, n, r, i = 0) {
7019
+ var qc = 8;
7020
+ async function Jc(e, t, n, r, i = 0) {
7002
7021
  if (n.length === 0) return;
7003
- let a = { ops: n }, o = Buffer.from(JSON.stringify(a), "utf-8"), [s, c] = await Ic("POST", e, {
7004
- headers: wr({
7022
+ let a = { ops: n }, o = Buffer.from(JSON.stringify(a), "utf-8"), [s, c] = await Lc("POST", e, {
7023
+ headers: Er({
7005
7024
  deviceId: t,
7006
7025
  method: "POST",
7007
7026
  url: e,
@@ -7012,18 +7031,18 @@ async function qc(e, t, n, r, i = 0) {
7012
7031
  bodyBytes: o
7013
7032
  });
7014
7033
  if (s === 200 && c != null) return;
7015
- let l = Bc(c);
7016
- if (s === 413 && n.length > 1 && i < Kc && (l === "payload_too_large" || l === "too_many_ops")) {
7034
+ let l = Vc(c);
7035
+ if (s === 413 && n.length > 1 && i < qc && (l === "payload_too_large" || l === "too_many_ops")) {
7017
7036
  let a = Math.floor(n.length / 2);
7018
- await qc(e, t, n.slice(0, a), r, i + 1), await qc(e, t, n.slice(a), r, i + 1);
7037
+ await Jc(e, t, n.slice(0, a), r, i + 1), await Jc(e, t, n.slice(a), r, i + 1);
7019
7038
  return;
7020
7039
  }
7021
7040
  let u = l ? ` (${s}: ${l})` : ` (${s})`;
7022
7041
  throw Error(`peer ops push failed${u}`);
7023
7042
  }
7024
- function Jc(e) {}
7025
- async function Yc(e, t, n, r) {
7026
- let i = r?.limit ?? Rc, a = r?.keysDir, o = j(e, { schema: R }).select({ pinned_fingerprint: W.pinned_fingerprint }).from(W).where(O(W.peer_device_id, t)).get()?.pinned_fingerprint ?? "";
7043
+ function Yc(e) {}
7044
+ async function Xc(e, t, n, r) {
7045
+ let i = r?.limit ?? zc, a = r?.keysDir, o = j(e, { schema: R }).select({ pinned_fingerprint: W.pinned_fingerprint }).from(W).where(O(W.peer_device_id, t)).get()?.pinned_fingerprint ?? "";
7027
7046
  if (!o) return {
7028
7047
  ok: !1,
7029
7048
  error: "peer not pinned",
@@ -7031,12 +7050,12 @@ async function Yc(e, t, n, r) {
7031
7050
  opsOut: 0,
7032
7051
  addressErrors: []
7033
7052
  };
7034
- let [s, c] = tc(e, t), l;
7053
+ let [s, c] = rc(e, t), l;
7035
7054
  try {
7036
- [l] = _r(e, { keysDir: a });
7055
+ [l] = yr(e, { keysDir: a });
7037
7056
  } catch (n) {
7038
7057
  let r = `device identity unavailable: ${n instanceof Error ? n.message.trim() || n.constructor.name : "unknown"}`;
7039
- return Hc(e, t, {
7058
+ return Uc(e, t, {
7040
7059
  ok: !1,
7041
7060
  error: r
7042
7061
  }), {
@@ -7049,11 +7068,11 @@ async function Yc(e, t, n, r) {
7049
7068
  }
7050
7069
  let u = [], d = !1;
7051
7070
  for (let r of n) {
7052
- let n = Fc(r);
7071
+ let n = Ic(r);
7053
7072
  if (n) {
7054
7073
  d = !0;
7055
7074
  try {
7056
- let r = `${n}/v1/status`, [u, d] = await Ic("GET", r, { headers: wr({
7075
+ let r = `${n}/v1/status`, [u, d] = await Lc("GET", r, { headers: Er({
7057
7076
  deviceId: l,
7058
7077
  method: "GET",
7059
7078
  url: r,
@@ -7061,14 +7080,14 @@ async function Yc(e, t, n, r) {
7061
7080
  keysDir: a
7062
7081
  }) });
7063
7082
  if (u !== 200 || !d) {
7064
- let e = Bc(d), t = e ? ` (${u}: ${e})` : ` (${u})`;
7083
+ let e = Vc(d), t = e ? ` (${u}: ${e})` : ` (${u})`;
7065
7084
  throw Error(`peer status failed${t}`);
7066
7085
  }
7067
7086
  if (d.fingerprint !== o) throw Error("peer fingerprint mismatch");
7068
7087
  let f = `${n}/v1/ops?${new URLSearchParams({
7069
7088
  since: s ?? "",
7070
7089
  limit: String(i)
7071
- }).toString()}`, [p, m] = await Ic("GET", f, { headers: wr({
7090
+ }).toString()}`, [p, m] = await Lc("GET", f, { headers: Er({
7072
7091
  deviceId: l,
7073
7092
  method: "GET",
7074
7093
  url: f,
@@ -7076,17 +7095,17 @@ async function Yc(e, t, n, r) {
7076
7095
  keysDir: a
7077
7096
  }) });
7078
7097
  if (p !== 200 || m == null) {
7079
- let e = Bc(m), t = e ? ` (${p}: ${e})` : ` (${p})`;
7098
+ let e = Vc(m), t = e ? ` (${p}: ${e})` : ` (${p})`;
7080
7099
  throw Error(`peer ops fetch failed${t}`);
7081
7100
  }
7082
7101
  let h = m.ops;
7083
7102
  if (!Array.isArray(h)) throw Error("invalid ops response");
7084
- let g = Wc(e, h, t), [_, v] = Gc(e, c, l, i), y = `${n}/v1/ops`;
7103
+ let g = Gc(e, h, t), [_, v] = Kc(e, c, l, i), y = `${n}/v1/ops`;
7085
7104
  if (_.length > 0) {
7086
- let e = ec(_, Lc);
7087
- for (let t of e) await qc(y, l, t, a);
7105
+ let e = nc(_, Rc);
7106
+ for (let t of e) await Jc(y, l, t, a);
7088
7107
  }
7089
- return v && (nc(e, t, { lastAcked: v }), c = v), Uc(e, t), Hc(e, t, {
7108
+ return v && (ic(e, t, { lastAcked: v }), c = v), Wc(e, t), Uc(e, t, {
7090
7109
  ok: !0,
7091
7110
  opsIn: g.inserted,
7092
7111
  opsOut: _.length
@@ -7106,8 +7125,8 @@ async function Yc(e, t, n, r) {
7106
7125
  }
7107
7126
  }
7108
7127
  }
7109
- let f = Vc(u);
7110
- return d || (f = "no dialable peer addresses"), f ||= "sync failed without diagnostic detail", Hc(e, t, {
7128
+ let f = Hc(u);
7129
+ return d || (f = "no dialable peer addresses"), f ||= "sync failed without diagnostic detail", Uc(e, t, {
7111
7130
  ok: !1,
7112
7131
  error: f
7113
7132
  }), {
@@ -7118,15 +7137,15 @@ async function Yc(e, t, n, r) {
7118
7137
  addressErrors: u
7119
7138
  };
7120
7139
  }
7121
- async function Xc(e, t, n) {
7140
+ async function Zc(e, t, n) {
7122
7141
  let r = j(e, { schema: R }).select({ addresses_json: W.addresses_json }).from(W).where(O(W.peer_device_id, t)).get(), i = [];
7123
7142
  if (r?.addresses_json) try {
7124
7143
  let e = JSON.parse(r.addresses_json);
7125
7144
  Array.isArray(e) && (i = e.filter((e) => typeof e == "string"));
7126
7145
  } catch {}
7127
- return Yc(e, t, i, n);
7146
+ return Xc(e, t, i, n);
7128
7147
  }
7129
- var Zc = [
7148
+ var Qc = [
7130
7149
  "no route to host",
7131
7150
  "connection refused",
7132
7151
  "network is unreachable",
@@ -7137,33 +7156,33 @@ var Zc = [
7137
7156
  "errno 61",
7138
7157
  "errno 60",
7139
7158
  "errno 111"
7140
- ], Qc = 120, $c = 1800;
7141
- function el(e) {
7159
+ ], $c = 120, el = 1800;
7160
+ function tl(e) {
7142
7161
  if (!e) return !1;
7143
7162
  let t = e.toLowerCase();
7144
- return Zc.some((e) => t.includes(e));
7163
+ return Qc.some((e) => t.includes(e));
7145
7164
  }
7146
- function tl(e, t, n = 10) {
7165
+ function nl(e, t, n = 10) {
7147
7166
  let r = j(e, { schema: R }).select({
7148
7167
  ok: K.ok,
7149
7168
  error: K.error
7150
7169
  }).from(K).where(O(K.peer_device_id, t)).orderBy(D(K.started_at)).limit(n).all(), i = 0;
7151
7170
  for (let e of r) {
7152
7171
  if (e.ok) break;
7153
- if (el(e.error)) i++;
7172
+ if (tl(e.error)) i++;
7154
7173
  else break;
7155
7174
  }
7156
7175
  return i;
7157
7176
  }
7158
- function nl(e) {
7177
+ function rl(e) {
7159
7178
  if (e <= 1) return 0;
7160
7179
  let t = Math.min(e - 1, 8);
7161
- return Math.min(Qc * 2 ** (t - 1), $c) * (.5 + Math.random() * .5);
7180
+ return Math.min($c * 2 ** (t - 1), el) * (.5 + Math.random() * .5);
7162
7181
  }
7163
- function rl(e, t) {
7164
- let n = tl(e, t);
7182
+ function il(e, t) {
7183
+ let n = nl(e, t);
7165
7184
  if (n < 2) return !1;
7166
- let r = nl(n);
7185
+ let r = rl(n);
7167
7186
  if (r <= 0) return !1;
7168
7187
  let i = j(e, { schema: R }).select({ started_at: K.started_at }).from(K).where(O(K.peer_device_id, t)).orderBy(D(K.started_at)).limit(1).get();
7169
7188
  if (!i?.started_at) return !1;
@@ -7176,7 +7195,7 @@ function rl(e, t) {
7176
7195
  }
7177
7196
  //#endregion
7178
7197
  //#region src/sync-daemon.ts
7179
- function il(e) {
7198
+ function al(e) {
7180
7199
  let t = j(e, { schema: R }), n = (/* @__PURE__ */ new Date()).toISOString();
7181
7200
  t.insert(cn).values({
7182
7201
  id: 1,
@@ -7186,7 +7205,7 @@ function il(e) {
7186
7205
  set: { last_ok_at: A`excluded.last_ok_at` }
7187
7206
  }).run();
7188
7207
  }
7189
- function al(e, t, n) {
7208
+ function ol(e, t, n) {
7190
7209
  let r = j(e, { schema: R }), i = (/* @__PURE__ */ new Date()).toISOString();
7191
7210
  r.insert(cn).values({
7192
7211
  id: 1,
@@ -7202,12 +7221,12 @@ function al(e, t, n) {
7202
7221
  }
7203
7222
  }).run();
7204
7223
  }
7205
- async function ol(e, t) {
7206
- jc();
7224
+ async function sl(e, t) {
7225
+ Mc();
7207
7226
  let n = j(e, { schema: R }).select({ peer_device_id: W.peer_device_id }).from(W).all(), r = [];
7208
7227
  for (let i of n) {
7209
7228
  let n = i.peer_device_id;
7210
- if (rl(e, n)) {
7229
+ if (il(e, n)) {
7211
7230
  r.push({
7212
7231
  ok: !1,
7213
7232
  skipped: !0,
@@ -7215,7 +7234,7 @@ async function ol(e, t) {
7215
7234
  });
7216
7235
  continue;
7217
7236
  }
7218
- let a = await Xc(e, n, { keysDir: t });
7237
+ let a = await Zc(e, n, { keysDir: t });
7219
7238
  r.push({
7220
7239
  ok: a.ok,
7221
7240
  error: a.error,
@@ -7225,11 +7244,11 @@ async function ol(e, t) {
7225
7244
  }
7226
7245
  return r;
7227
7246
  }
7228
- async function sl(e) {
7229
- let t = e?.intervalS ?? 120, n = zn(e?.dbPath), r = e?.keysDir, i = e?.signal, a = Wn(n), o = null;
7247
+ async function cl(e) {
7248
+ let t = e?.intervalS ?? 120, n = Bn(e?.dbPath), r = e?.keysDir, i = e?.signal, a = Gn(n), o = null;
7230
7249
  try {
7231
- let [t] = _r(a, { keysDir: r });
7232
- jc() && e?.port && (o = Mc(t, e.port));
7250
+ let [t] = yr(a, { keysDir: r });
7251
+ Mc() && e?.port && (o = Nc(t, e.port));
7233
7252
  } finally {
7234
7253
  a.close();
7235
7254
  }
@@ -7237,13 +7256,13 @@ async function sl(e) {
7237
7256
  o?.close();
7238
7257
  return;
7239
7258
  }
7240
- if (await cl(n, r), i?.aborted) {
7259
+ if (await ll(n, r), i?.aborted) {
7241
7260
  o?.close();
7242
7261
  return;
7243
7262
  }
7244
7263
  return new Promise((e) => {
7245
7264
  let a = !1, s = setInterval(() => {
7246
- a || (a = !0, cl(n, r).finally(() => {
7265
+ a || (a = !0, ll(n, r).finally(() => {
7247
7266
  a = !1;
7248
7267
  }));
7249
7268
  }, t * 1e3), c = () => {
@@ -7258,30 +7277,30 @@ async function sl(e) {
7258
7277
  }
7259
7278
  });
7260
7279
  }
7261
- async function cl(e, t) {
7262
- let n = Wn(e);
7280
+ async function ll(e, t) {
7281
+ let n = Gn(e);
7263
7282
  try {
7264
- await ol(n, t), il(n);
7283
+ await sl(n, t), al(n);
7265
7284
  } catch (e) {
7266
- al(n, e instanceof Error ? e.message : String(e), e instanceof Error ? e.stack ?? "" : "");
7285
+ ol(n, e instanceof Error ? e.message : String(e), e instanceof Error ? e.stack ?? "" : "");
7267
7286
  } finally {
7268
7287
  n.close();
7269
7288
  }
7270
7289
  }
7271
7290
  //#endregion
7272
7291
  //#region src/test-utils.ts
7273
- var ll = "\n CREATE TABLE IF NOT EXISTS sessions (\n id INTEGER PRIMARY KEY,\n started_at TEXT NOT NULL,\n ended_at TEXT,\n cwd TEXT,\n project TEXT,\n git_remote TEXT,\n git_branch TEXT,\n user TEXT,\n tool_version TEXT,\n metadata_json TEXT,\n import_key TEXT\n );\n\n CREATE TABLE IF NOT EXISTS artifacts (\n id INTEGER PRIMARY KEY,\n session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,\n kind TEXT NOT NULL,\n path TEXT,\n content_text TEXT,\n content_hash TEXT,\n created_at TEXT NOT NULL,\n metadata_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_artifacts_session_kind ON artifacts(session_id, kind);\n\n CREATE TABLE IF NOT EXISTS memory_items (\n id INTEGER PRIMARY KEY,\n session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,\n kind TEXT NOT NULL,\n title TEXT NOT NULL,\n subtitle TEXT,\n body_text TEXT NOT NULL,\n confidence REAL DEFAULT 0.5,\n tags_text TEXT DEFAULT '',\n active INTEGER DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n metadata_json TEXT,\n actor_id TEXT,\n actor_display_name TEXT,\n visibility TEXT,\n workspace_id TEXT,\n workspace_kind TEXT,\n origin_device_id TEXT,\n origin_source TEXT,\n trust_state TEXT,\n facts TEXT,\n narrative TEXT,\n concepts TEXT,\n files_read TEXT,\n files_modified TEXT,\n user_prompt_id INTEGER,\n prompt_number INTEGER,\n deleted_at TEXT,\n rev INTEGER DEFAULT 0,\n import_key TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_memory_items_active_created ON memory_items(active, created_at DESC);\n CREATE INDEX IF NOT EXISTS idx_memory_items_session ON memory_items(session_id);\n\n CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(\n title, body_text, tags_text,\n content='memory_items',\n content_rowid='id'\n );\n\n CREATE TRIGGER IF NOT EXISTS memory_items_ai AFTER INSERT ON memory_items BEGIN\n INSERT INTO memory_fts(rowid, title, body_text, tags_text)\n VALUES (new.id, new.title, new.body_text, new.tags_text);\n END;\n\n DROP TRIGGER IF EXISTS memory_items_au;\n CREATE TRIGGER memory_items_au AFTER UPDATE ON memory_items BEGIN\n INSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)\n VALUES('delete', old.id, old.title, old.body_text, old.tags_text);\n INSERT INTO memory_fts(rowid, title, body_text, tags_text)\n VALUES (new.id, new.title, new.body_text, new.tags_text);\n END;\n\n DROP TRIGGER IF EXISTS memory_items_ad;\n CREATE TRIGGER memory_items_ad AFTER DELETE ON memory_items BEGIN\n INSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)\n VALUES('delete', old.id, old.title, old.body_text, old.tags_text);\n END;\n\n CREATE TABLE IF NOT EXISTS usage_events (\n id INTEGER PRIMARY KEY,\n session_id INTEGER REFERENCES sessions(id) ON DELETE SET NULL,\n event TEXT NOT NULL,\n tokens_read INTEGER DEFAULT 0,\n tokens_written INTEGER DEFAULT 0,\n tokens_saved INTEGER DEFAULT 0,\n created_at TEXT NOT NULL,\n metadata_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_usage_events_event_created ON usage_events(event, created_at DESC);\n CREATE INDEX IF NOT EXISTS idx_usage_events_session ON usage_events(session_id);\n\n CREATE TABLE IF NOT EXISTS raw_events (\n id INTEGER PRIMARY KEY,\n source TEXT NOT NULL DEFAULT 'opencode',\n stream_id TEXT NOT NULL DEFAULT '',\n opencode_session_id TEXT NOT NULL,\n event_id TEXT,\n event_seq INTEGER NOT NULL,\n event_type TEXT NOT NULL,\n ts_wall_ms INTEGER,\n ts_mono_ms REAL,\n payload_json TEXT NOT NULL,\n created_at TEXT NOT NULL,\n UNIQUE(source, stream_id, event_seq),\n UNIQUE(source, stream_id, event_id)\n );\n CREATE INDEX IF NOT EXISTS idx_raw_events_session_seq ON raw_events(opencode_session_id, event_seq);\n CREATE INDEX IF NOT EXISTS idx_raw_events_created_at ON raw_events(created_at DESC);\n\n CREATE TABLE IF NOT EXISTS raw_event_sessions (\n source TEXT NOT NULL DEFAULT 'opencode',\n stream_id TEXT NOT NULL DEFAULT '',\n opencode_session_id TEXT NOT NULL,\n cwd TEXT,\n project TEXT,\n started_at TEXT,\n last_seen_ts_wall_ms INTEGER,\n last_received_event_seq INTEGER NOT NULL DEFAULT -1,\n last_flushed_event_seq INTEGER NOT NULL DEFAULT -1,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (source, stream_id)\n );\n\n CREATE TABLE IF NOT EXISTS opencode_sessions (\n source TEXT NOT NULL DEFAULT 'opencode',\n stream_id TEXT NOT NULL DEFAULT '',\n opencode_session_id TEXT NOT NULL,\n session_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n PRIMARY KEY (source, stream_id)\n );\n CREATE INDEX IF NOT EXISTS idx_opencode_sessions_session_id ON opencode_sessions(session_id);\n\n CREATE TABLE IF NOT EXISTS raw_event_flush_batches (\n id INTEGER PRIMARY KEY,\n source TEXT NOT NULL DEFAULT 'opencode',\n stream_id TEXT NOT NULL DEFAULT '',\n opencode_session_id TEXT NOT NULL,\n start_event_seq INTEGER NOT NULL,\n end_event_seq INTEGER NOT NULL,\n extractor_version TEXT NOT NULL,\n status TEXT NOT NULL,\n error_message TEXT,\n error_type TEXT,\n observer_provider TEXT,\n observer_model TEXT,\n observer_runtime TEXT,\n attempt_count INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n UNIQUE(source, stream_id, start_event_seq, end_event_seq, extractor_version)\n );\n CREATE INDEX IF NOT EXISTS idx_raw_event_flush_batches_session ON raw_event_flush_batches(opencode_session_id, created_at DESC);\n CREATE INDEX IF NOT EXISTS idx_raw_event_flush_batches_status ON raw_event_flush_batches(status, updated_at DESC);\n\n CREATE TABLE IF NOT EXISTS user_prompts (\n id INTEGER PRIMARY KEY,\n session_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,\n project TEXT,\n prompt_text TEXT NOT NULL,\n prompt_number INTEGER,\n created_at TEXT NOT NULL,\n created_at_epoch INTEGER NOT NULL,\n metadata_json TEXT,\n import_key TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_user_prompts_session ON user_prompts(session_id);\n CREATE INDEX IF NOT EXISTS idx_user_prompts_project ON user_prompts(project);\n CREATE INDEX IF NOT EXISTS idx_user_prompts_created ON user_prompts(created_at_epoch DESC);\n\n CREATE TABLE IF NOT EXISTS session_summaries (\n id INTEGER PRIMARY KEY,\n session_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,\n project TEXT,\n request TEXT,\n investigated TEXT,\n learned TEXT,\n completed TEXT,\n next_steps TEXT,\n notes TEXT,\n files_read TEXT,\n files_edited TEXT,\n prompt_number INTEGER,\n created_at TEXT NOT NULL,\n created_at_epoch INTEGER NOT NULL,\n metadata_json TEXT,\n import_key TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_session_summaries_session ON session_summaries(session_id);\n CREATE INDEX IF NOT EXISTS idx_session_summaries_project ON session_summaries(project);\n CREATE INDEX IF NOT EXISTS idx_session_summaries_created ON session_summaries(created_at_epoch DESC);\n\n CREATE TABLE IF NOT EXISTS replication_ops (\n op_id TEXT PRIMARY KEY,\n entity_type TEXT NOT NULL,\n entity_id TEXT NOT NULL,\n op_type TEXT NOT NULL,\n payload_json TEXT,\n clock_rev INTEGER NOT NULL,\n clock_updated_at TEXT NOT NULL,\n clock_device_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_replication_ops_created ON replication_ops(created_at, op_id);\n CREATE INDEX IF NOT EXISTS idx_replication_ops_entity ON replication_ops(entity_type, entity_id);\n\n CREATE TABLE IF NOT EXISTS replication_cursors (\n peer_device_id TEXT PRIMARY KEY,\n last_applied_cursor TEXT,\n last_acked_cursor TEXT,\n updated_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS sync_peers (\n peer_device_id TEXT PRIMARY KEY,\n name TEXT,\n pinned_fingerprint TEXT,\n public_key TEXT,\n addresses_json TEXT,\n claimed_local_actor INTEGER NOT NULL DEFAULT 0,\n actor_id TEXT,\n projects_include_json TEXT,\n projects_exclude_json TEXT,\n created_at TEXT NOT NULL,\n last_seen_at TEXT,\n last_sync_at TEXT,\n last_error TEXT\n );\n\n CREATE TABLE IF NOT EXISTS sync_nonces (\n nonce TEXT PRIMARY KEY,\n device_id TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS sync_device (\n device_id TEXT PRIMARY KEY,\n public_key TEXT NOT NULL,\n fingerprint TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS sync_attempts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n peer_device_id TEXT NOT NULL,\n started_at TEXT NOT NULL,\n finished_at TEXT,\n ok INTEGER NOT NULL,\n ops_in INTEGER NOT NULL,\n ops_out INTEGER NOT NULL,\n error TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_sync_attempts_peer_started ON sync_attempts(peer_device_id, started_at);\n\n CREATE TABLE IF NOT EXISTS sync_daemon_state (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n last_error TEXT,\n last_traceback TEXT,\n last_error_at TEXT,\n last_ok_at TEXT\n );\n\n CREATE TABLE IF NOT EXISTS raw_event_ingest_samples (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),\n inserted_events INTEGER NOT NULL DEFAULT 0,\n skipped_invalid INTEGER NOT NULL DEFAULT 0,\n skipped_duplicate INTEGER NOT NULL DEFAULT 0,\n skipped_conflict INTEGER NOT NULL DEFAULT 0\n );\n\n CREATE TABLE IF NOT EXISTS raw_event_ingest_stats (\n id INTEGER PRIMARY KEY,\n inserted_events INTEGER NOT NULL DEFAULT 0,\n skipped_events INTEGER NOT NULL DEFAULT 0,\n skipped_invalid INTEGER NOT NULL DEFAULT 0,\n skipped_duplicate INTEGER NOT NULL DEFAULT 0,\n skipped_conflict INTEGER NOT NULL DEFAULT 0,\n updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))\n );\n\n CREATE TABLE IF NOT EXISTS actors (\n actor_id TEXT PRIMARY KEY,\n display_name TEXT NOT NULL,\n is_local INTEGER NOT NULL DEFAULT 0,\n status TEXT NOT NULL DEFAULT 'active',\n merged_into_actor_id TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_actors_is_local ON actors(is_local);\n CREATE INDEX IF NOT EXISTS idx_actors_status ON actors(status);\n CREATE INDEX IF NOT EXISTS idx_sync_peers_actor_id ON sync_peers(actor_id);\n";
7274
- function ul(e) {
7275
- e.exec(ll), e.pragma("user_version = 6");
7276
- }
7292
+ var ul = "\n CREATE TABLE IF NOT EXISTS sessions (\n id INTEGER PRIMARY KEY,\n started_at TEXT NOT NULL,\n ended_at TEXT,\n cwd TEXT,\n project TEXT,\n git_remote TEXT,\n git_branch TEXT,\n user TEXT,\n tool_version TEXT,\n metadata_json TEXT,\n import_key TEXT\n );\n\n CREATE TABLE IF NOT EXISTS artifacts (\n id INTEGER PRIMARY KEY,\n session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,\n kind TEXT NOT NULL,\n path TEXT,\n content_text TEXT,\n content_hash TEXT,\n created_at TEXT NOT NULL,\n metadata_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_artifacts_session_kind ON artifacts(session_id, kind);\n\n CREATE TABLE IF NOT EXISTS memory_items (\n id INTEGER PRIMARY KEY,\n session_id INTEGER NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,\n kind TEXT NOT NULL,\n title TEXT NOT NULL,\n subtitle TEXT,\n body_text TEXT NOT NULL,\n confidence REAL DEFAULT 0.5,\n tags_text TEXT DEFAULT '',\n active INTEGER DEFAULT 1,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n metadata_json TEXT,\n actor_id TEXT,\n actor_display_name TEXT,\n visibility TEXT,\n workspace_id TEXT,\n workspace_kind TEXT,\n origin_device_id TEXT,\n origin_source TEXT,\n trust_state TEXT,\n facts TEXT,\n narrative TEXT,\n concepts TEXT,\n files_read TEXT,\n files_modified TEXT,\n user_prompt_id INTEGER,\n prompt_number INTEGER,\n deleted_at TEXT,\n rev INTEGER DEFAULT 0,\n import_key TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_memory_items_active_created ON memory_items(active, created_at DESC);\n CREATE INDEX IF NOT EXISTS idx_memory_items_session ON memory_items(session_id);\n\n CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(\n title, body_text, tags_text,\n content='memory_items',\n content_rowid='id'\n );\n\n CREATE TRIGGER IF NOT EXISTS memory_items_ai AFTER INSERT ON memory_items BEGIN\n INSERT INTO memory_fts(rowid, title, body_text, tags_text)\n VALUES (new.id, new.title, new.body_text, new.tags_text);\n END;\n\n DROP TRIGGER IF EXISTS memory_items_au;\n CREATE TRIGGER memory_items_au AFTER UPDATE ON memory_items BEGIN\n INSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)\n VALUES('delete', old.id, old.title, old.body_text, old.tags_text);\n INSERT INTO memory_fts(rowid, title, body_text, tags_text)\n VALUES (new.id, new.title, new.body_text, new.tags_text);\n END;\n\n DROP TRIGGER IF EXISTS memory_items_ad;\n CREATE TRIGGER memory_items_ad AFTER DELETE ON memory_items BEGIN\n INSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)\n VALUES('delete', old.id, old.title, old.body_text, old.tags_text);\n END;\n\n CREATE TABLE IF NOT EXISTS usage_events (\n id INTEGER PRIMARY KEY,\n session_id INTEGER REFERENCES sessions(id) ON DELETE SET NULL,\n event TEXT NOT NULL,\n tokens_read INTEGER DEFAULT 0,\n tokens_written INTEGER DEFAULT 0,\n tokens_saved INTEGER DEFAULT 0,\n created_at TEXT NOT NULL,\n metadata_json TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_usage_events_event_created ON usage_events(event, created_at DESC);\n CREATE INDEX IF NOT EXISTS idx_usage_events_session ON usage_events(session_id);\n\n CREATE TABLE IF NOT EXISTS raw_events (\n id INTEGER PRIMARY KEY,\n source TEXT NOT NULL DEFAULT 'opencode',\n stream_id TEXT NOT NULL DEFAULT '',\n opencode_session_id TEXT NOT NULL,\n event_id TEXT,\n event_seq INTEGER NOT NULL,\n event_type TEXT NOT NULL,\n ts_wall_ms INTEGER,\n ts_mono_ms REAL,\n payload_json TEXT NOT NULL,\n created_at TEXT NOT NULL,\n UNIQUE(source, stream_id, event_seq),\n UNIQUE(source, stream_id, event_id)\n );\n CREATE INDEX IF NOT EXISTS idx_raw_events_session_seq ON raw_events(opencode_session_id, event_seq);\n CREATE INDEX IF NOT EXISTS idx_raw_events_created_at ON raw_events(created_at DESC);\n\n CREATE TABLE IF NOT EXISTS raw_event_sessions (\n source TEXT NOT NULL DEFAULT 'opencode',\n stream_id TEXT NOT NULL DEFAULT '',\n opencode_session_id TEXT NOT NULL,\n cwd TEXT,\n project TEXT,\n started_at TEXT,\n last_seen_ts_wall_ms INTEGER,\n last_received_event_seq INTEGER NOT NULL DEFAULT -1,\n last_flushed_event_seq INTEGER NOT NULL DEFAULT -1,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (source, stream_id)\n );\n\n CREATE TABLE IF NOT EXISTS opencode_sessions (\n source TEXT NOT NULL DEFAULT 'opencode',\n stream_id TEXT NOT NULL DEFAULT '',\n opencode_session_id TEXT NOT NULL,\n session_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,\n created_at TEXT NOT NULL,\n PRIMARY KEY (source, stream_id)\n );\n CREATE INDEX IF NOT EXISTS idx_opencode_sessions_session_id ON opencode_sessions(session_id);\n\n CREATE TABLE IF NOT EXISTS raw_event_flush_batches (\n id INTEGER PRIMARY KEY,\n source TEXT NOT NULL DEFAULT 'opencode',\n stream_id TEXT NOT NULL DEFAULT '',\n opencode_session_id TEXT NOT NULL,\n start_event_seq INTEGER NOT NULL,\n end_event_seq INTEGER NOT NULL,\n extractor_version TEXT NOT NULL,\n status TEXT NOT NULL,\n error_message TEXT,\n error_type TEXT,\n observer_provider TEXT,\n observer_model TEXT,\n observer_runtime TEXT,\n attempt_count INTEGER NOT NULL DEFAULT 0,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n UNIQUE(source, stream_id, start_event_seq, end_event_seq, extractor_version)\n );\n CREATE INDEX IF NOT EXISTS idx_raw_event_flush_batches_session ON raw_event_flush_batches(opencode_session_id, created_at DESC);\n CREATE INDEX IF NOT EXISTS idx_raw_event_flush_batches_status ON raw_event_flush_batches(status, updated_at DESC);\n\n CREATE TABLE IF NOT EXISTS user_prompts (\n id INTEGER PRIMARY KEY,\n session_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,\n project TEXT,\n prompt_text TEXT NOT NULL,\n prompt_number INTEGER,\n created_at TEXT NOT NULL,\n created_at_epoch INTEGER NOT NULL,\n metadata_json TEXT,\n import_key TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_user_prompts_session ON user_prompts(session_id);\n CREATE INDEX IF NOT EXISTS idx_user_prompts_project ON user_prompts(project);\n CREATE INDEX IF NOT EXISTS idx_user_prompts_created ON user_prompts(created_at_epoch DESC);\n\n CREATE TABLE IF NOT EXISTS session_summaries (\n id INTEGER PRIMARY KEY,\n session_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,\n project TEXT,\n request TEXT,\n investigated TEXT,\n learned TEXT,\n completed TEXT,\n next_steps TEXT,\n notes TEXT,\n files_read TEXT,\n files_edited TEXT,\n prompt_number INTEGER,\n created_at TEXT NOT NULL,\n created_at_epoch INTEGER NOT NULL,\n metadata_json TEXT,\n import_key TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_session_summaries_session ON session_summaries(session_id);\n CREATE INDEX IF NOT EXISTS idx_session_summaries_project ON session_summaries(project);\n CREATE INDEX IF NOT EXISTS idx_session_summaries_created ON session_summaries(created_at_epoch DESC);\n\n CREATE TABLE IF NOT EXISTS replication_ops (\n op_id TEXT PRIMARY KEY,\n entity_type TEXT NOT NULL,\n entity_id TEXT NOT NULL,\n op_type TEXT NOT NULL,\n payload_json TEXT,\n clock_rev INTEGER NOT NULL,\n clock_updated_at TEXT NOT NULL,\n clock_device_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_replication_ops_created ON replication_ops(created_at, op_id);\n CREATE INDEX IF NOT EXISTS idx_replication_ops_entity ON replication_ops(entity_type, entity_id);\n\n CREATE TABLE IF NOT EXISTS replication_cursors (\n peer_device_id TEXT PRIMARY KEY,\n last_applied_cursor TEXT,\n last_acked_cursor TEXT,\n updated_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS sync_peers (\n peer_device_id TEXT PRIMARY KEY,\n name TEXT,\n pinned_fingerprint TEXT,\n public_key TEXT,\n addresses_json TEXT,\n claimed_local_actor INTEGER NOT NULL DEFAULT 0,\n actor_id TEXT,\n projects_include_json TEXT,\n projects_exclude_json TEXT,\n created_at TEXT NOT NULL,\n last_seen_at TEXT,\n last_sync_at TEXT,\n last_error TEXT\n );\n\n CREATE TABLE IF NOT EXISTS sync_nonces (\n nonce TEXT PRIMARY KEY,\n device_id TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS sync_device (\n device_id TEXT PRIMARY KEY,\n public_key TEXT NOT NULL,\n fingerprint TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS sync_attempts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n peer_device_id TEXT NOT NULL,\n started_at TEXT NOT NULL,\n finished_at TEXT,\n ok INTEGER NOT NULL,\n ops_in INTEGER NOT NULL,\n ops_out INTEGER NOT NULL,\n error TEXT\n );\n CREATE INDEX IF NOT EXISTS idx_sync_attempts_peer_started ON sync_attempts(peer_device_id, started_at);\n\n CREATE TABLE IF NOT EXISTS sync_daemon_state (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n last_error TEXT,\n last_traceback TEXT,\n last_error_at TEXT,\n last_ok_at TEXT\n );\n\n CREATE TABLE IF NOT EXISTS raw_event_ingest_samples (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now')),\n inserted_events INTEGER NOT NULL DEFAULT 0,\n skipped_invalid INTEGER NOT NULL DEFAULT 0,\n skipped_duplicate INTEGER NOT NULL DEFAULT 0,\n skipped_conflict INTEGER NOT NULL DEFAULT 0\n );\n\n CREATE TABLE IF NOT EXISTS raw_event_ingest_stats (\n id INTEGER PRIMARY KEY,\n inserted_events INTEGER NOT NULL DEFAULT 0,\n skipped_events INTEGER NOT NULL DEFAULT 0,\n skipped_invalid INTEGER NOT NULL DEFAULT 0,\n skipped_duplicate INTEGER NOT NULL DEFAULT 0,\n skipped_conflict INTEGER NOT NULL DEFAULT 0,\n updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))\n );\n\n CREATE TABLE IF NOT EXISTS actors (\n actor_id TEXT PRIMARY KEY,\n display_name TEXT NOT NULL,\n is_local INTEGER NOT NULL DEFAULT 0,\n status TEXT NOT NULL DEFAULT 'active',\n merged_into_actor_id TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_actors_is_local ON actors(is_local);\n CREATE INDEX IF NOT EXISTS idx_actors_status ON actors(status);\n CREATE INDEX IF NOT EXISTS idx_sync_peers_actor_id ON sync_peers(actor_id);\n";
7277
7293
  function dl(e) {
7294
+ e.exec(ul), e.pragma("user_version = 6");
7295
+ }
7296
+ function fl(e) {
7278
7297
  let t = (/* @__PURE__ */ new Date()).toISOString(), n = e.prepare("INSERT INTO sessions(started_at, cwd, project, user, tool_version) VALUES (?, ?, ?, ?, ?)").run(t, "/tmp/test", "test-project", "test-user", "test");
7279
7298
  return Number(n.lastInsertRowid);
7280
7299
  }
7281
7300
  //#endregion
7282
7301
  //#region src/index.ts
7283
- var fl = "0.20.0-alpha.3";
7302
+ var pl = "0.20.0-alpha.4";
7284
7303
  //#endregion
7285
- export { fe as Api, gn as CODEMEM_CONFIG_ENV_OVERRIDES, L as CoordinatorStore, Gt as DEFAULT_COORDINATOR_DB_PATH, Rn as DEFAULT_DB_PATH, Cc as DEFAULT_SERVICE_TYPE, yr as DEFAULT_TIME_WINDOW_S, Ri as LOW_SIGNAL_TOOLS, me as MAPPABLE_CLAUDE_HOOK_EVENTS, Fn as MIN_COMPATIBLE_SCHEMA, yc as MemoryStore, mo as ObserverAuthAdapter, $ as ObserverAuthError, Go as ObserverClient, $s as RawEventSweeper, Pn as SCHEMA_VERSION, vr as SIGNATURE_VERSION, da as TRIVIAL_REQUESTS, fl as VERSION, Br as _resetEmbeddingClient, xc as addressDedupeKey, Mc as advertiseMdns, dc as applyReplicationOps, Yn as assertSchemaReady, ks as backfillVectors, Jn as backupOnFirstAccess, Xi as budgetToolEvents, wr as buildAuthHeaders, Fc as buildBaseUrl, br as buildCanonicalRequest, co as buildCodexHeaders, Ci as buildFilterClauses, ri as buildImportKey, je as buildIngestPayloadFromHook, Hs as buildMemoryPack, Us as buildMemoryPackAsync, ua as buildObserverPrompt, Ae as buildRawEventEnvelopeFromHook, Js as buildSessionContext, ga as buildTranscript, ec as chunkOpsBySize, Rr as chunkText, Ra as cleanOrphanSessions, Er as cleanupNonces, ac as clockTuple, Wn as connect, Qt as connectCoordinator, tl as consecutiveConnectivityFailures, Fr as createCoordinatorApp, zc as cursorAdvances, Ht as decodeInvitePayload, Cs as dedupeOrderedIds, ha as deriveRequest, Nc as discoverPeersViaMdns, Hr as embedTexts, Vt as encodeInvitePayload, _r as ensureDeviceIdentity, Ms as estimateTokens, Ui as eventToToolEvent, is as expandQuery, Ds as explain, li as exportMemories, Gi as extractAdapterEvent, _a as extractAssistantMessages, va as extractAssistantUsage, Wt as extractInvitePayload, ao as extractOAuthAccess, oo as extractOAuthAccountId, so as extractOAuthExpires, ya as extractPrompts, ic as extractReplicationOps, Wi as extractToolEvents, tr as fingerprintPublicKey, ma as firstSentence, Ys as flushRawEvents, J as fromJson, pr as generateKeypair, _n as getCodememConfigPath, bn as getCodememEnvOverrides, Vr as getEmbeddingClient, Sn as getOpenCodeProviderConfig, jn as getProviderApiKey, kn as getProviderBaseUrl, An as getProviderHeaders, On as getProviderOptions, qa as getRawEventStatus, Ja as getReliabilityMetrics, tc as getReplicationCursor, qn as getSchemaVersion, Aa as hasMeaningfulObservation, Lr as hashText, _i as importMemories, Ia as ingest, za as ingestMain, Ga as initDatabase, ul as initTestSchema, dl as insertTestSession, Ut as inviteLink, el as isConnectivityError, Kn as isEmbeddingDisabled, zi as isInternalMemoryTool, $i as isLowSignalObservation, oc as isNewerClock, ji as isSensitiveFieldName, pa as isTrivialRequest, os as kindBonus, Cn as listCustomProviders, ko as loadObserverConfig, mn as loadOpenCodeConfig, no as loadOpenCodeOAuthCache, Tc as loadPeerAddresses, lr as loadPrivateKey, or as loadPrivateKeyKeychain, cr as loadPublicKey, uc as loadReplicationOpsSince, Gn as loadSqliteVec, Oe as mapClaudeHookPayload, Pc as mdnsAddressesForPeer, jc as mdnsEnabled, Sc as mergeAddresses, ii as mergeSummaryMetadata, Un as migrateLegacyDbPath, ba as normalizeAdapterEvents, bc as normalizeAddress, Qi as normalizeObservation, ye as normalizeProjectLabel, fa as normalizeRequestText, Bi as normalizeToolName, ka as parseObserverResponse, Ua as parsePositiveMemoryId, Ha as parseStrictInteger, nl as peerBackoffSeconds, Ki as projectAdapterToolEvent, Gr as projectBasename, qr as projectClause, Kr as projectColumnClause, Jr as projectMatchesFilter, Ya as rawEventsGate, uo as readAuthFile, vn as readCodememConfigFile, ui as readImportPayload, as as recencyScore, Tr as recordNonce, Oc as recordPeerSuccess, sc as recordReplicationOp, Dc as recordSyncAttempt, $a as redactText, vo as renderObserverHeaders, Ic as requestJson, vs as rerankResults, Mn as resolveCustomProviderDefaultModel, wn as resolveCustomProviderFromModel, Nn as resolveCustomProviderModel, zn as resolveDbPath, Se as resolveHookProject, sr as resolveKeyPaths, ro as resolveOAuthProvider, Tn as resolvePlaceholder, Xr as resolveProject, Xa as retryRawEventFailures, lo as runAuthCommand, sl as runSyncDaemon, Xc as runSyncPass, Pi as sanitizePayload, Li as sanitizeToolOutput, R as schema, ys as search, wc as selectDialAddresses, As as semanticSearch, Wr as serializeFloat32, Ac as setPeerLocalActorClaim, kc as setPeerProjectFilter, nc as setReplicationCursor, al as setSyncDaemonError, il as setSyncDaemonOk, rl as shouldSkipOfflinePeer, xr as signRequest, ar as storePrivateKeyKeychain, Os as storeVectors, fn as stripJsonComments, Oi as stripPrivate, Mi as stripPrivateObj, pn as stripTrailingCommas, ol as syncDaemonTick, Yc as syncOnce, Jc as syncPassPreflight, Xn as tableExists, xs as timeline, Y as toJson, X as toJsonNullable, Ec as updatePeerAddresses, Ka as vacuumDatabase, gr as validateExistingKeypair, Sr as verifySignature, yn as writeCodememConfigFile };
7304
+ export { fe as Api, _n as CODEMEM_CONFIG_ENV_OVERRIDES, L as CoordinatorStore, Gt as DEFAULT_COORDINATOR_DB_PATH, zn as DEFAULT_DB_PATH, wc as DEFAULT_SERVICE_TYPE, xr as DEFAULT_TIME_WINDOW_S, Bi as LOW_SIGNAL_TOOLS, me as MAPPABLE_CLAUDE_HOOK_EVENTS, In as MIN_COMPATIBLE_SCHEMA, bc as MemoryStore, go as ObserverAuthAdapter, Q as ObserverAuthError, qo as ObserverClient, tc as RawEventSweeper, Fn as SCHEMA_VERSION, br as SIGNATURE_VERSION, pa as TRIVIAL_REQUESTS, pl as VERSION, Hr as _resetEmbeddingClient, Sc as addressDedupeKey, Nc as advertiseMdns, pc as applyReplicationOps, Xn as assertSchemaReady, js as backfillVectors, Yn as backupOnFirstAccess, Qi as budgetToolEvents, Er as buildAuthHeaders, Ic as buildBaseUrl, Sr as buildCanonicalRequest, uo as buildCodexHeaders, Ti as buildFilterClauses, ai as buildImportKey, je as buildIngestPayloadFromHook, Ws as buildMemoryPack, Gs as buildMemoryPackAsync, fa as buildObserverPrompt, Ae as buildRawEventEnvelopeFromHook, Xs as buildSessionContext, va as buildTranscript, nc as chunkOpsBySize, Br as chunkText, Ba as cleanOrphanSessions, Or as cleanupNonces, sc as clockTuple, Gn as connect, Qt as connectCoordinator, nl as consecutiveConnectivityFailures, Lr as createCoordinatorApp, Bc as cursorAdvances, Ht as decodeInvitePayload, Ts as dedupeOrderedIds, _a as deriveRequest, Pc as discoverPeersViaMdns, Wr as embedTexts, Vt as encodeInvitePayload, yr as ensureDeviceIdentity, Ps as estimateTokens, Gi as eventToToolEvent, os as expandQuery, ks as explain, di as exportMemories, qi as extractAdapterEvent, ya as extractAssistantMessages, ba as extractAssistantUsage, Wt as extractInvitePayload, so as extractOAuthAccess, co as extractOAuthAccountId, lo as extractOAuthExpires, xa as extractPrompts, oc as extractReplicationOps, Ki as extractToolEvents, rr as fingerprintPublicKey, ga as firstSentence, Zs as flushRawEvents, q as fromJson, Qn as fromJsonStrict, hr as generateKeypair, vn as getCodememConfigPath, xn as getCodememEnvOverrides, Ur as getEmbeddingClient, Cn as getOpenCodeProviderConfig, Mn as getProviderApiKey, An as getProviderBaseUrl, jn as getProviderHeaders, kn as getProviderOptions, Ya as getRawEventStatus, Xa as getReliabilityMetrics, rc as getReplicationCursor, Jn as getSchemaVersion, Ma as hasMeaningfulObservation, zr as hashText, yi as importMemories, Ra as ingest, Va as ingestMain, qa as initDatabase, dl as initTestSchema, fl as insertTestSession, Ut as inviteLink, tl as isConnectivityError, qn as isEmbeddingDisabled, Vi as isInternalMemoryTool, ta as isLowSignalObservation, cc as isNewerClock, Ni as isSensitiveFieldName, ha as isTrivialRequest, cs as kindBonus, wn as listCustomProviders, jo as loadObserverConfig, hn as loadOpenCodeConfig, io as loadOpenCodeOAuthCache, Ec as loadPeerAddresses, dr as loadPrivateKey, cr as loadPrivateKeyKeychain, ur as loadPublicKey, fc as loadReplicationOpsSince, Kn as loadSqliteVec, Oe as mapClaudeHookPayload, Fc as mdnsAddressesForPeer, Mc as mdnsEnabled, Cc as mergeAddresses, oi as mergeSummaryMetadata, Wn as migrateLegacyDbPath, Sa as normalizeAdapterEvents, xc as normalizeAddress, ea as normalizeObservation, ye as normalizeProjectLabel, ma as normalizeRequestText, Hi as normalizeToolName, ja as parseObserverResponse, Ga as parsePositiveMemoryId, Wa as parseStrictInteger, rl as peerBackoffSeconds, Ji as projectAdapterToolEvent, qr as projectBasename, Yr as projectClause, Jr as projectColumnClause, Xr as projectMatchesFilter, Za as rawEventsGate, po as readAuthFile, yn as readCodememConfigFile, fi as readImportPayload, ss as recencyScore, Dr as recordNonce, kc as recordPeerSuccess, lc as recordReplicationOp, Oc as recordSyncAttempt, to as redactText, bo as renderObserverHeaders, Lc as requestJson, bs as rerankResults, Nn as resolveCustomProviderDefaultModel, Tn as resolveCustomProviderFromModel, Pn as resolveCustomProviderModel, Bn as resolveDbPath, Se as resolveHookProject, lr as resolveKeyPaths, ao as resolveOAuthProvider, En as resolvePlaceholder, Qr as resolveProject, Qa as retryRawEventFailures, fo as runAuthCommand, cl as runSyncDaemon, Zc as runSyncPass, Ii as sanitizePayload, zi as sanitizeToolOutput, R as schema, xs as search, Tc as selectDialAddresses, Ms as semanticSearch, Kr as serializeFloat32, jc as setPeerLocalActorClaim, Ac as setPeerProjectFilter, ic as setReplicationCursor, ol as setSyncDaemonError, al as setSyncDaemonOk, il as shouldSkipOfflinePeer, Cr as signRequest, sr as storePrivateKeyKeychain, As as storeVectors, pn as stripJsonComments, Ai as stripPrivate, Pi as stripPrivateObj, mn as stripTrailingCommas, sl as syncDaemonTick, Xc as syncOnce, Yc as syncPassPreflight, Zn as tableExists, Cs as timeline, J as toJson, Y as toJsonNullable, Dc as updatePeerAddresses, Ja as vacuumDatabase, vr as validateExistingKeypair, wr as verifySignature, bn as writeCodememConfigFile };
7286
7305
 
7287
7306
  //# sourceMappingURL=index.js.map