@codemem/core 0.48.1 → 0.49.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/better-sqlite-coordinator-store.d.ts.map +1 -1
- package/dist/coordinator-account-connection-link.d.ts +1 -1
- package/dist/coordinator-account-connection-link.d.ts.map +1 -1
- package/dist/coordinator-account-connection-schema.d.ts +1 -1
- package/dist/coordinator-account-link-status-client.d.ts +4 -0
- package/dist/coordinator-account-link-status-client.d.ts.map +1 -1
- package/dist/coordinator-api.d.ts.map +1 -1
- package/dist/coordinator-auth-device-claim-eligibility.d.ts +12 -1
- package/dist/coordinator-auth-device-claim-eligibility.d.ts.map +1 -1
- package/dist/coordinator-auth-historical-store-test-fixture.d.ts.map +1 -1
- package/dist/coordinator-auth-link.d.ts +1 -0
- package/dist/coordinator-auth-link.d.ts.map +1 -1
- package/dist/coordinator-device-claim-binding-contract.d.ts +37 -0
- package/dist/coordinator-device-claim-binding-contract.d.ts.map +1 -0
- package/dist/coordinator-device-claim-binding-reuse.d.ts +21 -0
- package/dist/coordinator-device-claim-binding-reuse.d.ts.map +1 -0
- package/dist/coordinator-device-claim-binding-sql.d.ts +32 -0
- package/dist/coordinator-device-claim-binding-sql.d.ts.map +1 -0
- package/dist/coordinator-device-claim-binding.d.ts +21 -0
- package/dist/coordinator-device-claim-binding.d.ts.map +1 -0
- package/dist/coordinator-device-rebind-browser.d.ts +1 -1
- package/dist/coordinator-device-rebind-ceremony.d.ts.map +1 -1
- package/dist/coordinator-device-rebind-commit.d.ts.map +1 -1
- package/dist/coordinator-device-rebind-proof.d.ts +1 -0
- package/dist/coordinator-device-rebind-proof.d.ts.map +1 -1
- package/dist/coordinator-device-rebind-schema.d.ts +4 -3
- package/dist/coordinator-device-rebind-schema.d.ts.map +1 -1
- package/dist/coordinator-device-self-bind-authority.d.ts +20 -0
- package/dist/coordinator-device-self-bind-authority.d.ts.map +1 -0
- package/dist/coordinator-device-self-bind-test-fixtures.d.ts +103 -0
- package/dist/coordinator-device-self-bind-test-fixtures.d.ts.map +1 -0
- package/dist/coordinator-device-setup-client.d.ts +26 -0
- package/dist/coordinator-device-setup-client.d.ts.map +1 -0
- package/dist/coordinator-device-setup-http.d.ts +9 -0
- package/dist/coordinator-device-setup-http.d.ts.map +1 -0
- package/dist/{coordinator-runtime-DjVICtRs.js → coordinator-runtime-kbPwxxKq.js} +164 -163
- package/dist/{coordinator-runtime-DjVICtRs.js.map → coordinator-runtime-kbPwxxKq.js.map} +1 -1
- package/dist/db.d.ts.map +1 -1
- package/dist/feed-contract.d.ts +59 -0
- package/dist/feed-contract.d.ts.map +1 -0
- package/dist/feed-contract.js +187 -0
- package/dist/feed-contract.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +7823 -7641
- package/dist/index.js.map +1 -1
- package/dist/ingest-events.d.ts.map +1 -1
- package/dist/ingest-pipeline.d.ts +38 -2
- package/dist/ingest-pipeline.d.ts.map +1 -1
- package/dist/internal/cloudflare-coordinator.js +1022 -1021
- package/dist/internal/cloudflare-coordinator.js.map +1 -1
- package/dist/internal/relay-runtime.js +36 -36
- package/dist/linked-legacy-setup-test-fixtures.d.ts +69 -0
- package/dist/linked-legacy-setup-test-fixtures.d.ts.map +1 -0
- package/dist/operational-status.d.ts +3 -0
- package/dist/operational-status.d.ts.map +1 -1
- package/dist/{owner-enrollment-start-DFVkODlJ.js → owner-enrollment-start-BtoRKf3z.js} +2871 -2656
- package/dist/owner-enrollment-start-BtoRKf3z.js.map +1 -0
- package/dist/owner-qualified-consumer-access-test-harness.d.ts.map +1 -1
- package/dist/owner-qualified-consumer-adversarial-test-harness.d.ts +1 -1
- package/dist/owner-qualified-consumer-adversarial-test-harness.d.ts.map +1 -1
- package/dist/owner-qualified-consumer-test-harness.d.ts +3 -0
- package/dist/owner-qualified-consumer-test-harness.d.ts.map +1 -1
- package/dist/owner-qualified-headless-test-harness.d.ts +1 -1
- package/dist/owner-qualified-headless-test-harness.d.ts.map +1 -1
- package/dist/project-scope-settings.d.ts.map +1 -1
- package/dist/raw-event-flush.d.ts.map +1 -1
- package/dist/raw-event-ingest.d.ts.map +1 -1
- package/dist/{relay-health-DhxMrW_S.js → relay-health-zrKtNQLQ.js} +16 -16
- package/dist/{relay-health-DhxMrW_S.js.map → relay-health-zrKtNQLQ.js.map} +1 -1
- package/dist/{relay-peer-client-CpY-lVbi.js → relay-peer-client-0XpekgnZ.js} +4446 -1978
- package/dist/relay-peer-client-0XpekgnZ.js.map +1 -0
- package/dist/schema-bootstrap.d.ts.map +1 -1
- package/dist/scope-membership-cache-read-B6z47l2W.js +4114 -0
- package/dist/scope-membership-cache-read-B6z47l2W.js.map +1 -0
- package/dist/scope-membership-cache-read.d.ts +60 -0
- package/dist/scope-membership-cache-read.d.ts.map +1 -0
- package/dist/scope-membership-cache.d.ts +2 -57
- package/dist/scope-membership-cache.d.ts.map +1 -1
- package/dist/scope-membership-semantics-B8qXaMqx.js +205 -0
- package/dist/scope-membership-semantics-B8qXaMqx.js.map +1 -0
- package/dist/semantic-worker-entry.js +1 -1
- package/dist/{semantic-worker-job-BmwXMG7v.js → semantic-worker-job-CMjFE5cp.js} +3 -3
- package/dist/{semantic-worker-job-BmwXMG7v.js.map → semantic-worker-job-CMjFE5cp.js.map} +1 -1
- package/dist/{semantic-worker-ranking-D31rfYAT.js → semantic-worker-ranking-it8Zs3qb.js} +18 -18
- package/dist/{semantic-worker-ranking-D31rfYAT.js.map → semantic-worker-ranking-it8Zs3qb.js.map} +1 -1
- package/dist/store.d.ts.map +1 -1
- package/dist/{sync-auth-constants-Cb8-a8lE.js → sync-auth-constants-DvALG0T0.js} +3099 -2874
- package/dist/sync-auth-constants-DvALG0T0.js.map +1 -0
- package/dist/sync-reachability-pass-Bi4GBi-x.js +2 -0
- package/dist/{sync-reachability-pass-EOj3hEau.js → sync-reachability-pass-BpDt2z4y.js} +2466 -2565
- package/dist/sync-reachability-pass-BpDt2z4y.js.map +1 -0
- package/dist/sync-status-indexes.d.ts +4 -0
- package/dist/sync-status-indexes.d.ts.map +1 -0
- package/dist/{validated-vector-index-audit-OuQct6jU.js → validated-vector-index-audit-B64yhEBF.js} +50 -50
- package/dist/validated-vector-index-audit-B64yhEBF.js.map +1 -0
- package/dist/vector-backfill-queue.d.ts +6 -0
- package/dist/vector-backfill-queue.d.ts.map +1 -1
- package/dist/vector-cutover-validation.d.ts +1 -0
- package/dist/vector-cutover-validation.d.ts.map +1 -1
- package/dist/vector-migration.d.ts +1 -0
- package/dist/vector-migration.d.ts.map +1 -1
- package/dist/vectors.d.ts +8 -2
- package/dist/vectors.d.ts.map +1 -1
- package/package.json +9 -4
- package/dist/owner-enrollment-start-DFVkODlJ.js.map +0 -1
- package/dist/relay-admission-proof-DjvC-e6G.js +0 -78
- package/dist/relay-admission-proof-DjvC-e6G.js.map +0 -1
- package/dist/relay-peer-client-CpY-lVbi.js.map +0 -1
- package/dist/scope-membership-cache-ByHJl5gt.js +0 -6549
- package/dist/scope-membership-cache-ByHJl5gt.js.map +0 -1
- package/dist/sync-auth-constants-Cb8-a8lE.js.map +0 -1
- package/dist/sync-reachability-pass-C6SYfltg.js +0 -2
- package/dist/sync-reachability-pass-EOj3hEau.js.map +0 -1
- package/dist/validated-vector-index-audit-OuQct6jU.js.map +0 -1
|
@@ -0,0 +1,4114 @@
|
|
|
1
|
+
import { a as e, d as t, f as n, h as r, i, l as a, n as o, p as s, r as c, s as l } from "./scope-membership-semantics-B8qXaMqx.js";
|
|
2
|
+
import { t as u } from "./relay-ed25519-BNMhPehl.js";
|
|
3
|
+
import { createHash as d, randomUUID as f } from "node:crypto";
|
|
4
|
+
import { closeSync as p, copyFileSync as ee, existsSync as m, fchmodSync as te, fchownSync as ne, fsyncSync as re, ftruncateSync as ie, lstatSync as ae, mkdirSync as oe, openSync as se, readFileSync as h, readlinkSync as ce, realpathSync as le, renameSync as ue, statSync as de, unlinkSync as g, writeSync as fe } from "node:fs";
|
|
5
|
+
import { basename as pe, dirname as _, isAbsolute as me, join as v, resolve as he } from "node:path";
|
|
6
|
+
import { homedir as y } from "node:os";
|
|
7
|
+
import { execFileSync as ge } from "node:child_process";
|
|
8
|
+
import _e from "better-sqlite3";
|
|
9
|
+
import * as ve from "sqlite-vec";
|
|
10
|
+
import { sql as b } from "drizzle-orm";
|
|
11
|
+
import { index as x, integer as S, primaryKey as C, real as w, sqliteTable as T, text as E, uniqueIndex as D } from "drizzle-orm/sqlite-core";
|
|
12
|
+
//#region \0rolldown/runtime.js
|
|
13
|
+
var ye = Object.defineProperty, be = (e, t) => {
|
|
14
|
+
let n = {};
|
|
15
|
+
for (var r in e) ye(n, r, {
|
|
16
|
+
get: e[r],
|
|
17
|
+
enumerable: !0
|
|
18
|
+
});
|
|
19
|
+
return t || ye(n, Symbol.toStringTag, { value: "Module" }), n;
|
|
20
|
+
};
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/memory-local-capture.ts
|
|
23
|
+
function xe(e, t, n) {
|
|
24
|
+
if (O(e, "actors") && e.prepare("SELECT 1 FROM actors WHERE actor_id IN (?, ?, ?)\n AND (is_local <> 1 OR status <> 'active' OR merged_into_actor_id IS NOT NULL) LIMIT 1").get("local:local", `local:${t}`, n ?? `local:${t}`)) throw Error("device_adoption_actor_conflict");
|
|
25
|
+
}
|
|
26
|
+
function O(e, t) {
|
|
27
|
+
return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t) !== void 0;
|
|
28
|
+
}
|
|
29
|
+
function Se(e) {
|
|
30
|
+
e.exec("CREATE TABLE IF NOT EXISTS memory_local_capture (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n capture_id TEXT NOT NULL UNIQUE,\n created_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS memory_local_capture_adoption (\n capture_id TEXT PRIMARY KEY NOT NULL REFERENCES memory_local_capture(capture_id),\n device_id TEXT NOT NULL,\n public_key TEXT NOT NULL,\n fingerprint TEXT NOT NULL,\n created_at TEXT NOT NULL\n );");
|
|
31
|
+
for (let t of ["memory_local_capture", "memory_local_capture_adoption"]) e.exec(`CREATE TRIGGER IF NOT EXISTS ${t}_no_update
|
|
32
|
+
BEFORE UPDATE ON ${t}
|
|
33
|
+
BEGIN SELECT RAISE(ABORT, 'memory_local_capture_immutable'); END;
|
|
34
|
+
CREATE TRIGGER IF NOT EXISTS ${t}_no_delete
|
|
35
|
+
BEFORE DELETE ON ${t}
|
|
36
|
+
BEGIN SELECT RAISE(ABORT, 'memory_local_capture_immutable'); END;
|
|
37
|
+
CREATE TRIGGER IF NOT EXISTS ${t}_no_replace
|
|
38
|
+
BEFORE INSERT ON ${t}
|
|
39
|
+
WHEN EXISTS (SELECT 1 FROM ${t})
|
|
40
|
+
BEGIN SELECT RAISE(ABORT, 'memory_local_capture_immutable'); END;`);
|
|
41
|
+
}
|
|
42
|
+
function Ce(e) {
|
|
43
|
+
return O(e, "memory_local_capture") ? e.prepare("SELECT capture_id FROM memory_local_capture WHERE id = 1").get() ?? null : null;
|
|
44
|
+
}
|
|
45
|
+
function we(e) {
|
|
46
|
+
let t = Ce(e);
|
|
47
|
+
return !t || !O(e, "memory_local_capture_adoption") ? !1 : !e.prepare("SELECT 1 FROM memory_local_capture_adoption WHERE capture_id = ?").get(t.capture_id);
|
|
48
|
+
}
|
|
49
|
+
function Te(e) {
|
|
50
|
+
if (!O(e, "sync_device")) return null;
|
|
51
|
+
let t = e.prepare("SELECT device_id, public_key, fingerprint FROM sync_device LIMIT 2").all();
|
|
52
|
+
return t.length === 1 ? t[0] ?? null : null;
|
|
53
|
+
}
|
|
54
|
+
function Ee(e) {
|
|
55
|
+
let [t, n] = e.trim().split(/\s+/u);
|
|
56
|
+
return t === "ssh-ed25519" && n ? `${t} ${n}` : null;
|
|
57
|
+
}
|
|
58
|
+
function De(e, t, n) {
|
|
59
|
+
let r = Ee(e.public_key);
|
|
60
|
+
return e.device_id === t && r !== null && n !== void 0 && Ee(n) === r && s(e.public_key) === e.fingerprint;
|
|
61
|
+
}
|
|
62
|
+
function Oe(e) {
|
|
63
|
+
if (!e.inTransaction) throw Error("memory_source_transaction_required");
|
|
64
|
+
let t = Ce(e);
|
|
65
|
+
if (t) return t.capture_id;
|
|
66
|
+
Se(e);
|
|
67
|
+
let n = `local-capture-v1:${f()}`;
|
|
68
|
+
return e.prepare("INSERT INTO memory_local_capture(id, capture_id, created_at) VALUES (1, ?, ?)").run(n, (/* @__PURE__ */ new Date()).toISOString()), n;
|
|
69
|
+
}
|
|
70
|
+
function ke(e, t, n) {
|
|
71
|
+
if (!e.inTransaction) throw Error("memory_source_transaction_required");
|
|
72
|
+
let r = Ce(e);
|
|
73
|
+
if (!r || n.runtimeDeviceId && n.runtimeDeviceId !== "local" && n.runtimeDeviceId !== t) return;
|
|
74
|
+
let i = Te(e), a = n.expectedPublicKey ?? n.loadExpectedPublicKey?.();
|
|
75
|
+
if (!i || !De(i, t, a)) return;
|
|
76
|
+
let o = e.prepare("SELECT device_id, public_key, fingerprint FROM memory_local_capture_adoption WHERE capture_id = ?").get(r.capture_id);
|
|
77
|
+
if (o) {
|
|
78
|
+
if (o.device_id !== i.device_id || o.public_key !== i.public_key || o.fingerprint !== i.fingerprint) throw Error("memory_local_capture_adoption_conflict");
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
xe(e, t, n.actorId), e.prepare("INSERT INTO memory_local_capture_adoption(capture_id, device_id, public_key, fingerprint, created_at)\n VALUES (?, ?, ?, ?, ?)").run(r.capture_id, i.device_id, i.public_key, i.fingerprint, (/* @__PURE__ */ new Date()).toISOString());
|
|
82
|
+
}
|
|
83
|
+
function Ae(e, t, n = {}) {
|
|
84
|
+
if (!O(e, "memory_source_bindings") || !e.prepare("SELECT 1 FROM memory_source_bindings WHERE evidence = 'local_creation' LIMIT 1").get()) return [];
|
|
85
|
+
let r = Ce(e), i = Te(e);
|
|
86
|
+
if (!i) {
|
|
87
|
+
let n = !O(e, "sync_device") || !e.prepare("SELECT 1 FROM sync_device LIMIT 1").get(), i = O(e, "memory_local_capture_adoption") && e.prepare("SELECT 1 FROM memory_local_capture_adoption LIMIT 1").get();
|
|
88
|
+
return n && !i && t === "local" && r ? [r.capture_id] : [];
|
|
89
|
+
}
|
|
90
|
+
if (i.device_id !== t || !De(i, t, n.expectedPublicKey ?? n.loadExpectedPublicKey?.())) return [];
|
|
91
|
+
let a = [t];
|
|
92
|
+
if (!r || !O(e, "memory_local_capture_adoption")) return a;
|
|
93
|
+
let o = e.prepare("SELECT device_id, public_key, fingerprint FROM memory_local_capture_adoption WHERE capture_id = ?").get(r.capture_id);
|
|
94
|
+
return o && o.device_id === i.device_id && o.public_key === i.public_key && o.fingerprint === i.fingerprint && a.push(r.capture_id), a;
|
|
95
|
+
}
|
|
96
|
+
//#endregion
|
|
97
|
+
//#region src/memory-source-identity.ts
|
|
98
|
+
var je = "memory-source-v1:", Me = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u;
|
|
99
|
+
function Ne(e) {
|
|
100
|
+
e.exec("CREATE TABLE IF NOT EXISTS memory_source_bindings (\n entity_id TEXT PRIMARY KEY,\n source_device_id TEXT NOT NULL,\n evidence TEXT NOT NULL CHECK(evidence IN ('local_creation', 'authenticated_namespace')),\n created_at TEXT NOT NULL\n );\n CREATE TRIGGER IF NOT EXISTS memory_source_bindings_no_update\n BEFORE UPDATE ON memory_source_bindings\n BEGIN SELECT RAISE(ABORT, 'memory_source_binding_immutable'); END;\n CREATE TRIGGER IF NOT EXISTS memory_source_bindings_no_delete\n BEFORE DELETE ON memory_source_bindings\n BEGIN SELECT RAISE(ABORT, 'memory_source_binding_immutable'); END;\n CREATE TRIGGER IF NOT EXISTS memory_source_bindings_no_replace\n BEFORE INSERT ON memory_source_bindings\n WHEN EXISTS (SELECT 1 FROM memory_source_bindings WHERE entity_id = NEW.entity_id)\n BEGIN SELECT RAISE(ABORT, 'memory_source_binding_immutable'); END;");
|
|
101
|
+
}
|
|
102
|
+
function Pe(e) {
|
|
103
|
+
return typeof e == "string" && e.length > 0 && e.length <= 256 && e.trim() === e && !/[\p{Cc}\p{Cf}\p{Cs}]/u.test(e);
|
|
104
|
+
}
|
|
105
|
+
function Fe(e) {
|
|
106
|
+
if (typeof e != "string" || e.length > 1500 || !e.startsWith(je)) return null;
|
|
107
|
+
let [t, n, r] = e.slice(17).split(":");
|
|
108
|
+
if (!t || !n || r !== void 0 || !Me.test(n)) return null;
|
|
109
|
+
let i = Buffer.from(t, "base64url").toString("utf8");
|
|
110
|
+
return !Pe(i) || Buffer.from(i).toString("base64url") !== t ? null : i;
|
|
111
|
+
}
|
|
112
|
+
function Ie(e, t) {
|
|
113
|
+
let n = e.prepare("SELECT source_device_id, evidence FROM memory_source_bindings WHERE entity_id = ?").get(t);
|
|
114
|
+
return n ? {
|
|
115
|
+
entityId: t,
|
|
116
|
+
sourceDeviceId: n.source_device_id,
|
|
117
|
+
evidence: n.evidence
|
|
118
|
+
} : null;
|
|
119
|
+
}
|
|
120
|
+
function Le(e, t) {
|
|
121
|
+
if (!e.inTransaction) throw Error("memory_source_transaction_required");
|
|
122
|
+
let n = Ie(e, t.entityId);
|
|
123
|
+
if (n) {
|
|
124
|
+
if (n.sourceDeviceId !== t.sourceDeviceId) throw Error("memory_source_binding_conflict");
|
|
125
|
+
return n;
|
|
126
|
+
}
|
|
127
|
+
return e.prepare("INSERT INTO memory_source_bindings(entity_id, source_device_id, evidence, created_at)\n VALUES (?, ?, ?, ?)").run(t.entityId, t.sourceDeviceId, t.evidence, (/* @__PURE__ */ new Date()).toISOString()), t;
|
|
128
|
+
}
|
|
129
|
+
function Re(e) {
|
|
130
|
+
let t = e.prepare("SELECT device_id FROM sync_device").all(), n = t[0]?.device_id;
|
|
131
|
+
if (t.length !== 1 || !n || !Pe(n)) throw Error("memory_source_local_device_required");
|
|
132
|
+
return Le(e, {
|
|
133
|
+
entityId: `${je}${Buffer.from(n).toString("base64url")}:${f()}`,
|
|
134
|
+
sourceDeviceId: n,
|
|
135
|
+
evidence: "local_creation"
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
function ze(e, t, n = {}) {
|
|
139
|
+
if (!e.inTransaction) throw Error("memory_source_transaction_required");
|
|
140
|
+
let r = [];
|
|
141
|
+
if (e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'sync_device'").get() && (r = e.prepare("SELECT device_id, public_key, fingerprint FROM sync_device LIMIT 2").all()), r.length > 0) {
|
|
142
|
+
let i = r[0];
|
|
143
|
+
return r.length !== 1 || !i || i.device_id !== t || !Pe(t) || !De(i, t, n.expectedPublicKey ?? n.loadExpectedPublicKey?.()) ? null : Re(e);
|
|
144
|
+
}
|
|
145
|
+
if (t !== "local") return null;
|
|
146
|
+
let i = Oe(e);
|
|
147
|
+
return Le(e, {
|
|
148
|
+
entityId: `memory-local-capture-v1:${Buffer.from(i).toString("base64url")}:${f()}`,
|
|
149
|
+
sourceDeviceId: i,
|
|
150
|
+
evidence: "local_creation"
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
//#endregion
|
|
154
|
+
//#region src/home.ts
|
|
155
|
+
function k() {
|
|
156
|
+
return process.env.HOME?.trim() || y();
|
|
157
|
+
}
|
|
158
|
+
//#endregion
|
|
159
|
+
//#region src/observer-config.ts
|
|
160
|
+
function A(e) {
|
|
161
|
+
let t = [], n = !1, r = !1;
|
|
162
|
+
for (let i = 0; i < e.length; i++) {
|
|
163
|
+
let a = e.charAt(i);
|
|
164
|
+
if (r) {
|
|
165
|
+
t.push(a), r = !1;
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (a === "\\" && n) {
|
|
169
|
+
t.push(a), r = !0;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (a === "\"") {
|
|
173
|
+
n = !n, t.push(a);
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
if (!n && a === "/" && i + 1 < e.length) {
|
|
177
|
+
let t = e.charAt(i + 1);
|
|
178
|
+
if (t === "/") {
|
|
179
|
+
let t = i + 2;
|
|
180
|
+
for (; t < e.length && e.charAt(t) !== "\n";) t++;
|
|
181
|
+
i = t - 1;
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (t === "*") {
|
|
185
|
+
let t = i + 2;
|
|
186
|
+
for (; t < e.length - 1;) {
|
|
187
|
+
if (e.charAt(t) === "*" && e.charAt(t + 1) === "/") {
|
|
188
|
+
t += 2;
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
t++;
|
|
192
|
+
}
|
|
193
|
+
i = t - 1;
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
t.push(a);
|
|
198
|
+
}
|
|
199
|
+
return t.join("");
|
|
200
|
+
}
|
|
201
|
+
function j(e) {
|
|
202
|
+
let t = [], n = !1, r = !1;
|
|
203
|
+
for (let i = 0; i < e.length; i++) {
|
|
204
|
+
let a = e.charAt(i);
|
|
205
|
+
if (r) {
|
|
206
|
+
t.push(a), r = !1;
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (a === "\\" && n) {
|
|
210
|
+
t.push(a), r = !0;
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
if (a === "\"") {
|
|
214
|
+
n = !n, t.push(a);
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (!n && a === ",") {
|
|
218
|
+
let t = i + 1;
|
|
219
|
+
for (; t < e.length && /\s/.test(e.charAt(t));) t++;
|
|
220
|
+
if (t < e.length && (e.charAt(t) === "]" || e.charAt(t) === "}")) continue;
|
|
221
|
+
}
|
|
222
|
+
t.push(a);
|
|
223
|
+
}
|
|
224
|
+
return t.join("");
|
|
225
|
+
}
|
|
226
|
+
function M() {
|
|
227
|
+
let e = v(k(), ".config", "opencode"), t = [v(e, "opencode.json"), v(e, "opencode.jsonc")].find((e) => m(e));
|
|
228
|
+
if (!t) return {};
|
|
229
|
+
let n;
|
|
230
|
+
try {
|
|
231
|
+
n = h(t, "utf-8");
|
|
232
|
+
} catch {
|
|
233
|
+
return {};
|
|
234
|
+
}
|
|
235
|
+
try {
|
|
236
|
+
return JSON.parse(n);
|
|
237
|
+
} catch {}
|
|
238
|
+
try {
|
|
239
|
+
let e = j(A(n));
|
|
240
|
+
return JSON.parse(e);
|
|
241
|
+
} catch {
|
|
242
|
+
return {};
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
function N(e) {
|
|
246
|
+
return e.startsWith("~/") ? v(k(), e.slice(2)) : e;
|
|
247
|
+
}
|
|
248
|
+
function Be(e) {
|
|
249
|
+
return /^[A-Za-z0-9._:-]+$/.test(e) && !/^\.+$/.test(e);
|
|
250
|
+
}
|
|
251
|
+
function P(e) {
|
|
252
|
+
let t = e.trim();
|
|
253
|
+
if (!t || !Be(t)) throw Error(`Invalid workspace id for config path: ${e}`);
|
|
254
|
+
return v(k(), ".codemem", "workspaces", t, "config", "codemem.json");
|
|
255
|
+
}
|
|
256
|
+
function Ve() {
|
|
257
|
+
let e = process.env.CODEMEM_RUNTIME_ROOT?.trim();
|
|
258
|
+
if (e) {
|
|
259
|
+
let t = N(e);
|
|
260
|
+
if (me(t)) return v(t, "config", "codemem.json");
|
|
261
|
+
}
|
|
262
|
+
let t = process.env.CODEMEM_WORKSPACE_ID?.trim();
|
|
263
|
+
return !t || !Be(t) ? null : P(t);
|
|
264
|
+
}
|
|
265
|
+
function He() {
|
|
266
|
+
let e = v(k(), ".config", "codemem");
|
|
267
|
+
return [v(e, "config.json"), v(e, "config.jsonc")].find((e) => m(e)) ?? v(e, "config.json");
|
|
268
|
+
}
|
|
269
|
+
function Ue() {
|
|
270
|
+
return qe(void 0, "write").resolved.path;
|
|
271
|
+
}
|
|
272
|
+
function We(e) {
|
|
273
|
+
return Xe(P(e));
|
|
274
|
+
}
|
|
275
|
+
var Ge = {
|
|
276
|
+
actor_id: "CODEMEM_ACTOR_ID",
|
|
277
|
+
actor_display_name: "CODEMEM_ACTOR_DISPLAY_NAME",
|
|
278
|
+
claude_command: "CODEMEM_CLAUDE_COMMAND",
|
|
279
|
+
codex_command: "CODEMEM_CODEX_COMMAND",
|
|
280
|
+
observer_provider: "CODEMEM_OBSERVER_PROVIDER",
|
|
281
|
+
observer_model: "CODEMEM_OBSERVER_MODEL",
|
|
282
|
+
observer_temperature: "CODEMEM_OBSERVER_TEMPERATURE",
|
|
283
|
+
observer_openai_use_responses: "CODEMEM_OBSERVER_OPENAI_USE_RESPONSES",
|
|
284
|
+
observer_max_output_tokens: "CODEMEM_OBSERVER_MAX_OUTPUT_TOKENS",
|
|
285
|
+
observer_reasoning_effort: "CODEMEM_OBSERVER_REASONING_EFFORT",
|
|
286
|
+
observer_reasoning_summary: "CODEMEM_OBSERVER_REASONING_SUMMARY",
|
|
287
|
+
observer_tier_routing_enabled: "CODEMEM_OBSERVER_TIER_ROUTING_ENABLED",
|
|
288
|
+
observer_simple_provider: "CODEMEM_OBSERVER_SIMPLE_PROVIDER",
|
|
289
|
+
observer_simple_model: "CODEMEM_OBSERVER_SIMPLE_MODEL",
|
|
290
|
+
observer_simple_temperature: "CODEMEM_OBSERVER_SIMPLE_TEMPERATURE",
|
|
291
|
+
observer_rich_provider: "CODEMEM_OBSERVER_RICH_PROVIDER",
|
|
292
|
+
observer_rich_model: "CODEMEM_OBSERVER_RICH_MODEL",
|
|
293
|
+
observer_rich_temperature: "CODEMEM_OBSERVER_RICH_TEMPERATURE",
|
|
294
|
+
observer_rich_reasoning_effort: "CODEMEM_OBSERVER_RICH_REASONING_EFFORT",
|
|
295
|
+
observer_rich_reasoning_summary: "CODEMEM_OBSERVER_RICH_REASONING_SUMMARY",
|
|
296
|
+
observer_rich_max_output_tokens: "CODEMEM_OBSERVER_RICH_MAX_OUTPUT_TOKENS",
|
|
297
|
+
observer_output_mode: "CODEMEM_OBSERVER_OUTPUT_MODE",
|
|
298
|
+
observer_base_url: "CODEMEM_OBSERVER_BASE_URL",
|
|
299
|
+
observer_runtime: "CODEMEM_OBSERVER_RUNTIME",
|
|
300
|
+
observer_auth_source: "CODEMEM_OBSERVER_AUTH_SOURCE",
|
|
301
|
+
observer_auth_file: "CODEMEM_OBSERVER_AUTH_FILE",
|
|
302
|
+
observer_auth_command: "CODEMEM_OBSERVER_AUTH_COMMAND",
|
|
303
|
+
observer_auth_timeout_ms: "CODEMEM_OBSERVER_AUTH_TIMEOUT_MS",
|
|
304
|
+
observer_auth_cache_ttl_s: "CODEMEM_OBSERVER_AUTH_CACHE_TTL_S",
|
|
305
|
+
observer_headers: "CODEMEM_OBSERVER_HEADERS",
|
|
306
|
+
observer_max_chars: "CODEMEM_OBSERVER_MAX_CHARS",
|
|
307
|
+
observer_max_tokens: "CODEMEM_OBSERVER_MAX_TOKENS",
|
|
308
|
+
pack_observation_limit: "CODEMEM_PACK_OBSERVATION_LIMIT",
|
|
309
|
+
pack_session_limit: "CODEMEM_PACK_SESSION_LIMIT",
|
|
310
|
+
sync_enabled: "CODEMEM_SYNC_ENABLED",
|
|
311
|
+
sync_device_name: "CODEMEM_SYNC_DEVICE_NAME",
|
|
312
|
+
sync_host: "CODEMEM_SYNC_HOST",
|
|
313
|
+
sync_port: "CODEMEM_SYNC_PORT",
|
|
314
|
+
sync_interval_s: "CODEMEM_SYNC_INTERVAL_S",
|
|
315
|
+
sync_mdns: "CODEMEM_SYNC_MDNS",
|
|
316
|
+
sync_advertise: "CODEMEM_SYNC_ADVERTISE",
|
|
317
|
+
sync_coordinator_url: "CODEMEM_SYNC_COORDINATOR_URL",
|
|
318
|
+
sync_coordinator_group: "CODEMEM_SYNC_COORDINATOR_GROUP",
|
|
319
|
+
sync_coordinator_groups: "CODEMEM_SYNC_COORDINATOR_GROUPS",
|
|
320
|
+
sync_coordinator_timeout_s: "CODEMEM_SYNC_COORDINATOR_TIMEOUT_S",
|
|
321
|
+
sync_coordinator_presence_ttl_s: "CODEMEM_SYNC_COORDINATOR_PRESENCE_TTL_S",
|
|
322
|
+
sync_coordinator_admin_secret: "CODEMEM_SYNC_COORDINATOR_ADMIN_SECRET",
|
|
323
|
+
sync_relay_enabled: "CODEMEM_SYNC_RELAY_ENABLED",
|
|
324
|
+
sync_relay_service_key: "CODEMEM_SYNC_RELAY_SERVICE_KEY",
|
|
325
|
+
sync_retention_enabled: "CODEMEM_SYNC_RETENTION_ENABLED",
|
|
326
|
+
sync_retention_max_age_days: "CODEMEM_SYNC_RETENTION_MAX_AGE_DAYS",
|
|
327
|
+
sync_retention_max_size_mb: "CODEMEM_SYNC_RETENTION_MAX_SIZE_MB",
|
|
328
|
+
sync_retention_interval_s: "CODEMEM_SYNC_RETENTION_INTERVAL_S",
|
|
329
|
+
sync_retention_max_runtime_ms: "CODEMEM_SYNC_RETENTION_MAX_RUNTIME_MS",
|
|
330
|
+
sync_retention_max_ops_per_pass: "CODEMEM_SYNC_RETENTION_MAX_OPS_PER_PASS",
|
|
331
|
+
sync_projects_include: "CODEMEM_SYNC_PROJECTS_INCLUDE",
|
|
332
|
+
sync_projects_exclude: "CODEMEM_SYNC_PROJECTS_EXCLUDE",
|
|
333
|
+
sync_ops_limit: "CODEMEM_SYNC_OPS_LIMIT",
|
|
334
|
+
raw_events_sweeper_interval_s: "CODEMEM_RAW_EVENTS_SWEEPER_INTERVAL_S",
|
|
335
|
+
raw_events_retention_enabled: "CODEMEM_RAW_EVENTS_RETENTION_ENABLED",
|
|
336
|
+
raw_events_retention_max_age_days: "CODEMEM_RAW_EVENTS_RETENTION_MAX_AGE_DAYS"
|
|
337
|
+
};
|
|
338
|
+
function Ke(e) {
|
|
339
|
+
if (e == null) return null;
|
|
340
|
+
if (Array.isArray(e)) {
|
|
341
|
+
let t = e.filter((e) => typeof e == "string" && e.trim() !== "");
|
|
342
|
+
return t.length > 0 ? t : null;
|
|
343
|
+
}
|
|
344
|
+
if (typeof e != "string") return null;
|
|
345
|
+
let t = e.trim();
|
|
346
|
+
if (!t) return null;
|
|
347
|
+
try {
|
|
348
|
+
let e = JSON.parse(t);
|
|
349
|
+
if (Array.isArray(e) && e.every((e) => typeof e == "string")) {
|
|
350
|
+
let t = e.filter((e) => e.trim() !== "");
|
|
351
|
+
return t.length > 0 ? t : null;
|
|
352
|
+
}
|
|
353
|
+
} catch {}
|
|
354
|
+
let n = t.split(/\s+/).filter((e) => e !== "");
|
|
355
|
+
return n.length > 0 ? n : null;
|
|
356
|
+
}
|
|
357
|
+
function qe(e, t = "read") {
|
|
358
|
+
let n = [];
|
|
359
|
+
if (e?.trim()) {
|
|
360
|
+
let t = N(e.trim());
|
|
361
|
+
n.push({
|
|
362
|
+
path: t,
|
|
363
|
+
source: "cli-flag",
|
|
364
|
+
reason: `--config ${e}`,
|
|
365
|
+
exists: m(t),
|
|
366
|
+
valid: !0
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
let r = process.env.CODEMEM_CONFIG?.trim();
|
|
370
|
+
if (r) {
|
|
371
|
+
let e = N(r);
|
|
372
|
+
n.push({
|
|
373
|
+
path: e,
|
|
374
|
+
source: "env-codemem-config",
|
|
375
|
+
reason: `CODEMEM_CONFIG='${r}'`,
|
|
376
|
+
exists: m(e),
|
|
377
|
+
valid: !0
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
let i = process.env.CODEMEM_RUNTIME_ROOT?.trim();
|
|
381
|
+
if (i) {
|
|
382
|
+
let e = N(i), t = me(e), r = v(e, "config", "codemem.json");
|
|
383
|
+
n.push({
|
|
384
|
+
path: r,
|
|
385
|
+
source: "env-runtime-root",
|
|
386
|
+
reason: t ? `CODEMEM_RUNTIME_ROOT='${i}'` : `CODEMEM_RUNTIME_ROOT='${i}' is relative, not absolute`,
|
|
387
|
+
exists: t ? m(r) : !1,
|
|
388
|
+
valid: t
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
let a = process.env.CODEMEM_WORKSPACE_ID?.trim();
|
|
392
|
+
if (a) {
|
|
393
|
+
let e = Be(a), t = e ? P(a) : v(k(), ".codemem", "workspaces", a, "config", "codemem.json");
|
|
394
|
+
n.push({
|
|
395
|
+
path: t,
|
|
396
|
+
source: "env-workspace-id",
|
|
397
|
+
reason: e ? `CODEMEM_WORKSPACE_ID='${a}'` : `CODEMEM_WORKSPACE_ID='${a}' failed safety check`,
|
|
398
|
+
exists: e ? m(t) : !1,
|
|
399
|
+
valid: e
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
let o = He();
|
|
403
|
+
n.push({
|
|
404
|
+
path: o,
|
|
405
|
+
source: "legacy-global",
|
|
406
|
+
reason: "legacy global config",
|
|
407
|
+
exists: m(o),
|
|
408
|
+
valid: !0
|
|
409
|
+
});
|
|
410
|
+
let s = (e) => e.source === "cli-flag" || e.source === "env-codemem-config", c;
|
|
411
|
+
if (t === "write") c = n.findIndex((e) => e.valid);
|
|
412
|
+
else {
|
|
413
|
+
let e = n.findIndex((e) => s(e) && e.valid);
|
|
414
|
+
if (e >= 0) c = e;
|
|
415
|
+
else {
|
|
416
|
+
let e = n.findIndex((e) => e.valid && e.exists);
|
|
417
|
+
c = e >= 0 ? e : n.findIndex((e) => e.valid);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
c < 0 && (c = n.length - 1);
|
|
421
|
+
let l = n[c] ?? n[n.length - 1];
|
|
422
|
+
if (!l) throw Error("No config path candidates were generated");
|
|
423
|
+
let u = n.filter((e, t) => t !== c);
|
|
424
|
+
for (let e of u) e.source === "env-runtime-root" && e.reason.includes("is relative") || e.source === "env-workspace-id" && e.reason.includes("failed safety check") || t === "read" && !e.exists && (e.reason += " (does not exist)");
|
|
425
|
+
return {
|
|
426
|
+
resolved: l,
|
|
427
|
+
fallbackChain: u
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
function Je() {
|
|
431
|
+
return qe(void 0, "read").resolved.path;
|
|
432
|
+
}
|
|
433
|
+
function Ye() {
|
|
434
|
+
return Xe(Je());
|
|
435
|
+
}
|
|
436
|
+
function Xe(e) {
|
|
437
|
+
let t = N(e);
|
|
438
|
+
if (!m(t)) return {};
|
|
439
|
+
let n;
|
|
440
|
+
try {
|
|
441
|
+
n = h(t, "utf-8");
|
|
442
|
+
} catch {
|
|
443
|
+
return {};
|
|
444
|
+
}
|
|
445
|
+
if (!n.trim()) return {};
|
|
446
|
+
try {
|
|
447
|
+
let e = JSON.parse(n);
|
|
448
|
+
return typeof e == "object" && e && !Array.isArray(e) ? e : {};
|
|
449
|
+
} catch {}
|
|
450
|
+
try {
|
|
451
|
+
let e = j(A(n)), t = JSON.parse(e);
|
|
452
|
+
return typeof t == "object" && t && !Array.isArray(t) ? t : {};
|
|
453
|
+
} catch {
|
|
454
|
+
return {};
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
var F = class extends Error {
|
|
458
|
+
code;
|
|
459
|
+
constructor(e, t, n) {
|
|
460
|
+
super(t, n), this.name = "CodememConfigMutationError", this.code = e;
|
|
461
|
+
}
|
|
462
|
+
}, I;
|
|
463
|
+
function Ze() {
|
|
464
|
+
if (I !== void 0) return I;
|
|
465
|
+
try {
|
|
466
|
+
ge("/bin/cp", ["--version"], { stdio: "ignore" }), I = !0;
|
|
467
|
+
} catch (e) {
|
|
468
|
+
if (e instanceof Error && "code" in e && e.code === "ENOENT" || e instanceof Error && "status" in e && typeof e.status == "number") return I = !1, I;
|
|
469
|
+
throw new F("unreadable", "Cannot update config because extended access metadata support could not be checked.", { cause: e });
|
|
470
|
+
}
|
|
471
|
+
return I;
|
|
472
|
+
}
|
|
473
|
+
function Qe(e) {
|
|
474
|
+
ge("/usr/bin/chflags", ["0", "/dev/fd/3"], { stdio: [
|
|
475
|
+
"ignore",
|
|
476
|
+
"pipe",
|
|
477
|
+
"pipe",
|
|
478
|
+
e
|
|
479
|
+
] });
|
|
480
|
+
}
|
|
481
|
+
function $e(e, t) {
|
|
482
|
+
let n, r;
|
|
483
|
+
if (process.platform === "darwin" ? (n = [
|
|
484
|
+
"-p",
|
|
485
|
+
e,
|
|
486
|
+
"/dev/fd/3"
|
|
487
|
+
], r = { ...process.env }, delete r.COPYFILE_DISABLE) : process.platform === "linux" && Ze() && (n = [
|
|
488
|
+
"--preserve=mode,ownership,xattr",
|
|
489
|
+
"--",
|
|
490
|
+
e,
|
|
491
|
+
"/proc/self/fd/3"
|
|
492
|
+
]), !n) return !1;
|
|
493
|
+
try {
|
|
494
|
+
return ge("/bin/cp", n, {
|
|
495
|
+
env: r,
|
|
496
|
+
stdio: [
|
|
497
|
+
"ignore",
|
|
498
|
+
"pipe",
|
|
499
|
+
"pipe",
|
|
500
|
+
t
|
|
501
|
+
]
|
|
502
|
+
}), process.platform === "darwin" && Qe(t), !0;
|
|
503
|
+
} catch (n) {
|
|
504
|
+
if (process.platform === "darwin") try {
|
|
505
|
+
Qe(t);
|
|
506
|
+
} catch {}
|
|
507
|
+
throw new F("unreadable", `Cannot update config because extended access metadata from ${e} could not be preserved.`, { cause: n });
|
|
508
|
+
}
|
|
509
|
+
}
|
|
510
|
+
var et = {
|
|
511
|
+
open: se,
|
|
512
|
+
close: p,
|
|
513
|
+
chown: ne,
|
|
514
|
+
chmod: te,
|
|
515
|
+
truncate: ie,
|
|
516
|
+
sync: re,
|
|
517
|
+
write: fe,
|
|
518
|
+
rename: ue,
|
|
519
|
+
unlink: g,
|
|
520
|
+
seedMetadata: $e
|
|
521
|
+
}, tt = {
|
|
522
|
+
close: p,
|
|
523
|
+
unlink: g
|
|
524
|
+
};
|
|
525
|
+
function nt(e) {
|
|
526
|
+
return d("sha256").update(e).digest("hex");
|
|
527
|
+
}
|
|
528
|
+
function rt(e) {
|
|
529
|
+
if (!e.trim()) return {
|
|
530
|
+
status: "invalid",
|
|
531
|
+
reason: "empty"
|
|
532
|
+
};
|
|
533
|
+
for (let t of [e, j(A(e))]) try {
|
|
534
|
+
let e = JSON.parse(t);
|
|
535
|
+
return typeof e == "object" && e && !Array.isArray(e) ? {
|
|
536
|
+
status: "valid",
|
|
537
|
+
data: e
|
|
538
|
+
} : {
|
|
539
|
+
status: "invalid",
|
|
540
|
+
reason: "non_object"
|
|
541
|
+
};
|
|
542
|
+
} catch {}
|
|
543
|
+
return {
|
|
544
|
+
status: "invalid",
|
|
545
|
+
reason: "parse_error"
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
function it(e) {
|
|
549
|
+
let t = e ? N(e) : Ue();
|
|
550
|
+
if (!m(t)) return {
|
|
551
|
+
status: "missing",
|
|
552
|
+
path: t,
|
|
553
|
+
revision: "missing"
|
|
554
|
+
};
|
|
555
|
+
let n, r;
|
|
556
|
+
try {
|
|
557
|
+
n = h(t, "utf8");
|
|
558
|
+
let e = de(t, { bigint: !0 });
|
|
559
|
+
r = {
|
|
560
|
+
mode: Number(e.mode & 511n),
|
|
561
|
+
uid: Number(e.uid),
|
|
562
|
+
gid: Number(e.gid),
|
|
563
|
+
ctimeNs: e.ctimeNs,
|
|
564
|
+
dev: e.dev,
|
|
565
|
+
ino: e.ino
|
|
566
|
+
};
|
|
567
|
+
} catch {
|
|
568
|
+
return {
|
|
569
|
+
status: "unreadable",
|
|
570
|
+
path: t
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
let i = rt(n);
|
|
574
|
+
return i.status === "invalid" ? {
|
|
575
|
+
...i,
|
|
576
|
+
path: t
|
|
577
|
+
} : {
|
|
578
|
+
...i,
|
|
579
|
+
path: t,
|
|
580
|
+
revision: nt(n),
|
|
581
|
+
...r
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
function at(e, t) {
|
|
585
|
+
try {
|
|
586
|
+
t(e);
|
|
587
|
+
} catch (e) {
|
|
588
|
+
if ((e instanceof Error && "code" in e ? String(e.code) : "") !== "ENOENT") throw e;
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
function ot(e, t, n) {
|
|
592
|
+
try {
|
|
593
|
+
at(e, t);
|
|
594
|
+
} catch (e) {
|
|
595
|
+
if (!n) throw e;
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
function L(e) {
|
|
599
|
+
let t = /* @__PURE__ */ new Set(), n = e;
|
|
600
|
+
for (;;) {
|
|
601
|
+
if (t.has(n)) throw new F("unreadable", `Cannot update config because ${e} contains a symbolic-link cycle.`);
|
|
602
|
+
t.add(n);
|
|
603
|
+
try {
|
|
604
|
+
return le(n);
|
|
605
|
+
} catch {}
|
|
606
|
+
try {
|
|
607
|
+
if (ae(n).isSymbolicLink()) {
|
|
608
|
+
let e = ce(n);
|
|
609
|
+
n = me(e) ? e : he(_(n), e);
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
return n;
|
|
613
|
+
} catch {
|
|
614
|
+
try {
|
|
615
|
+
return v(le(_(n)), pe(n));
|
|
616
|
+
} catch {
|
|
617
|
+
return n;
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
function st(e, t) {
|
|
623
|
+
let n = null;
|
|
624
|
+
try {
|
|
625
|
+
n = t.open(_(e), "r"), t.sync(n);
|
|
626
|
+
} catch {} finally {
|
|
627
|
+
if (n != null) try {
|
|
628
|
+
t.close(n);
|
|
629
|
+
} catch {}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
function ct(e, t, n) {
|
|
633
|
+
let r = Buffer.from(t, "utf8"), i = 0;
|
|
634
|
+
for (; i < r.length;) {
|
|
635
|
+
let t = n(e, r, i, r.length - i, i);
|
|
636
|
+
if (t === 0) throw Error("Config replacement write made no progress");
|
|
637
|
+
i += t;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
function lt(e, t, n, r = et, i, { followSymlink: a = !0 } = {}) {
|
|
641
|
+
let o = a ? L(e) : e, s = `${o}.tmp-${process.pid}-${f()}`, c = null, l = !1;
|
|
642
|
+
try {
|
|
643
|
+
let e = typeof n == "number" ? n : n?.mode;
|
|
644
|
+
if (c = r.open(s, "wx", e ?? 384), typeof n == "object" && r.seedMetadata?.(o, c) === !0) {
|
|
645
|
+
if (!r.truncate) throw Error("Seeded config replacement requires truncate");
|
|
646
|
+
r.truncate(c, 0);
|
|
647
|
+
}
|
|
648
|
+
typeof n == "object" && process.platform !== "win32" && r.chown?.(c, n.uid, n.gid), e != null && r.chmod(c, e), ct(c, t, r.write), r.sync(c);
|
|
649
|
+
let a = c;
|
|
650
|
+
c = null, r.close(a), i?.(), r.rename(s, o), l = !0, st(o, r);
|
|
651
|
+
} finally {
|
|
652
|
+
try {
|
|
653
|
+
c != null && r.close(c);
|
|
654
|
+
} finally {
|
|
655
|
+
ot(s, r.unlink, l);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
function ut(e) {
|
|
660
|
+
if (e.status === "missing") return {};
|
|
661
|
+
if (e.status === "valid") return e.data;
|
|
662
|
+
throw e.status === "unreadable" ? new F("unreadable", `Cannot update config because ${e.path} could not be read.`) : new F("invalid", `Cannot update config because ${e.path} is not a valid JSON object.`);
|
|
663
|
+
}
|
|
664
|
+
function dt(e) {
|
|
665
|
+
if (!m(e)) return "missing";
|
|
666
|
+
try {
|
|
667
|
+
return nt(h(e, "utf8"));
|
|
668
|
+
} catch {
|
|
669
|
+
return "unreadable";
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
function ft(e) {
|
|
673
|
+
if (!m(e)) return "missing";
|
|
674
|
+
try {
|
|
675
|
+
let t = de(e, { bigint: !0 });
|
|
676
|
+
return {
|
|
677
|
+
mode: Number(t.mode & 511n),
|
|
678
|
+
uid: Number(t.uid),
|
|
679
|
+
gid: Number(t.gid),
|
|
680
|
+
ctimeNs: t.ctimeNs,
|
|
681
|
+
dev: t.dev,
|
|
682
|
+
ino: t.ino
|
|
683
|
+
};
|
|
684
|
+
} catch {
|
|
685
|
+
return "unreadable";
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
function pt(e, t) {
|
|
689
|
+
return typeof e != "string" && mt(e, t) && e.ctimeNs === t.ctimeNs && e.dev === t.dev && e.ino === t.ino;
|
|
690
|
+
}
|
|
691
|
+
function mt(e, t) {
|
|
692
|
+
return typeof e != "string" && e.mode === t.mode && e.uid === t.uid && e.gid === t.gid;
|
|
693
|
+
}
|
|
694
|
+
function ht(e) {
|
|
695
|
+
if (e.status === "valid") return {
|
|
696
|
+
mode: e.mode,
|
|
697
|
+
uid: e.uid,
|
|
698
|
+
gid: e.gid
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
function gt(e) {
|
|
702
|
+
let t = `${e}.lock`;
|
|
703
|
+
try {
|
|
704
|
+
return {
|
|
705
|
+
fd: se(t, "wx", 384),
|
|
706
|
+
path: t
|
|
707
|
+
};
|
|
708
|
+
} catch (n) {
|
|
709
|
+
throw (n instanceof Error && "code" in n ? String(n.code) : "") === "EEXIST" ? new F("busy", `Cannot update config because another writer is updating ${e}. Retry the save; if no save is active, remove the stale lock at ${t}.`, { cause: n }) : new F("unreadable", `Cannot update config because its writer lock could not be created at ${t}.`, { cause: n });
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
function _t(e, t) {
|
|
713
|
+
let n;
|
|
714
|
+
try {
|
|
715
|
+
t.close(e.fd);
|
|
716
|
+
} catch (e) {
|
|
717
|
+
n = e;
|
|
718
|
+
}
|
|
719
|
+
try {
|
|
720
|
+
at(e.path, t.unlink);
|
|
721
|
+
} catch (e) {
|
|
722
|
+
n ??= e;
|
|
723
|
+
}
|
|
724
|
+
if (n !== void 0) throw n;
|
|
725
|
+
}
|
|
726
|
+
function vt(e, t = tt) {
|
|
727
|
+
let n;
|
|
728
|
+
for (let r of e.reverse()) try {
|
|
729
|
+
_t(r, t);
|
|
730
|
+
} catch (e) {
|
|
731
|
+
n ??= e;
|
|
732
|
+
}
|
|
733
|
+
if (n !== void 0) throw n;
|
|
734
|
+
}
|
|
735
|
+
function yt(e, t, n) {
|
|
736
|
+
try {
|
|
737
|
+
vt(e, n);
|
|
738
|
+
} catch (e) {
|
|
739
|
+
if (!t) throw e;
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
function bt(e) {
|
|
743
|
+
let t = [...new Set(e)].sort((e, t) => e < t ? -1 : +(e > t)), n = [];
|
|
744
|
+
try {
|
|
745
|
+
for (let e of t) oe(_(e), { recursive: !0 }), n.push(gt(e));
|
|
746
|
+
return n;
|
|
747
|
+
} catch (e) {
|
|
748
|
+
try {
|
|
749
|
+
vt(n);
|
|
750
|
+
} catch {}
|
|
751
|
+
throw e;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
function xt(e, t, n) {
|
|
755
|
+
for (let r = 0; r < 3; r += 1) {
|
|
756
|
+
let r = it(e), i = n.fallbackReadPath ?? (t ? Je() : void 0), a = n.expectedMutationPath ? N(n.expectedMutationPath) : L(e), o = r.status === "missing" && i != null ? L(N(i)) : void 0, s = bt([a]), c = L(e) === a, l = o === void 0 || L(N(i ?? e)) === o;
|
|
757
|
+
if (c && l) return {
|
|
758
|
+
preliminaryTarget: r,
|
|
759
|
+
fallbackReadPath: i,
|
|
760
|
+
targetMutationPath: a,
|
|
761
|
+
fallbackMutationPath: o,
|
|
762
|
+
locks: s
|
|
763
|
+
};
|
|
764
|
+
vt(s);
|
|
765
|
+
}
|
|
766
|
+
throw new F("changed", `Cannot update config because ${e} changed before the save. Retry the save.`);
|
|
767
|
+
}
|
|
768
|
+
function St(e, t, n) {
|
|
769
|
+
if (e.status !== "missing" && t.status === "missing") throw new F("changed", `Cannot update config because ${n} changed before the save. Retry the save.`);
|
|
770
|
+
}
|
|
771
|
+
function Ct(e, t, n) {
|
|
772
|
+
if (e.status !== "missing") return e;
|
|
773
|
+
let r = n ?? t;
|
|
774
|
+
return r === t ? e : it(r);
|
|
775
|
+
}
|
|
776
|
+
function wt(e) {
|
|
777
|
+
let t = ft(e.targetMutationPath);
|
|
778
|
+
if (L(e.targetPath) !== e.targetMutationPath || dt(e.targetMutationPath) !== e.expectedRevision || e.expectedMetadata !== void 0 && !mt(t, e.expectedMetadata) || e.expectedIdentity !== void 0 && !pt(t, e.expectedIdentity)) throw new F("changed", `Cannot update config because ${e.targetPath} changed during the save. Retry the save.`);
|
|
779
|
+
if (e.fallbackMutationPath !== void 0 && L(N(e.fallbackReadPath ?? e.targetPath)) !== e.fallbackMutationPath) throw new F("changed", `Cannot update config because ${e.fallbackReadPath} changed during the save. Retry the save.`);
|
|
780
|
+
if (e.inputOutcome.path !== e.targetMutationPath && dt(e.inputOutcome.path) !== e.inputRevision) throw new F("changed", `Cannot update config because ${e.inputOutcome.path} changed during the save. Retry the save.`);
|
|
781
|
+
}
|
|
782
|
+
function Tt(e, t, n) {
|
|
783
|
+
if (n != null && t !== n) throw new F("changed", `Cannot update config because ${e} changed before the save. Retry the save.`);
|
|
784
|
+
}
|
|
785
|
+
function Et(e, t, n) {
|
|
786
|
+
let r = e.status === "valid" ? e.revision : "missing";
|
|
787
|
+
return Tt(t, r, n), {
|
|
788
|
+
expectedRevision: r,
|
|
789
|
+
expectedIdentity: e.status === "valid" ? {
|
|
790
|
+
mode: e.mode,
|
|
791
|
+
uid: e.uid,
|
|
792
|
+
gid: e.gid,
|
|
793
|
+
ctimeNs: e.ctimeNs,
|
|
794
|
+
dev: e.dev,
|
|
795
|
+
ino: e.ino
|
|
796
|
+
} : void 0
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
function Dt(e) {
|
|
800
|
+
lt(e.targetMutationPath, e.text, e.metadata, et, () => wt(e));
|
|
801
|
+
}
|
|
802
|
+
function Ot(e, t, n = {}) {
|
|
803
|
+
let r = t ? N(t) : Ue(), { preliminaryTarget: i, fallbackReadPath: a, targetMutationPath: o, fallbackMutationPath: s, locks: c } = xt(r, t == null, n), l = !1;
|
|
804
|
+
try {
|
|
805
|
+
let t = it(o);
|
|
806
|
+
St(i, t, r);
|
|
807
|
+
let c = Ct(t, o, s ?? a), { expectedRevision: u, expectedIdentity: d } = Et(t, r, n.expectedRevision), f = { ...ut(c) }, p = e(f, t);
|
|
808
|
+
if (p === void 0) return {
|
|
809
|
+
path: r,
|
|
810
|
+
mutationPath: o,
|
|
811
|
+
data: f,
|
|
812
|
+
revision: u
|
|
813
|
+
};
|
|
814
|
+
let ee = c.status === "valid" ? c.revision : c.status, m = `${JSON.stringify(p, null, 2)}\n`;
|
|
815
|
+
return Dt({
|
|
816
|
+
targetPath: r,
|
|
817
|
+
targetMutationPath: o,
|
|
818
|
+
text: m,
|
|
819
|
+
metadata: ht(t),
|
|
820
|
+
expectedRevision: u,
|
|
821
|
+
expectedMetadata: ht(t),
|
|
822
|
+
expectedIdentity: d,
|
|
823
|
+
fallbackReadPath: a,
|
|
824
|
+
fallbackMutationPath: s,
|
|
825
|
+
inputOutcome: c,
|
|
826
|
+
inputRevision: ee
|
|
827
|
+
}), l = !0, {
|
|
828
|
+
path: r,
|
|
829
|
+
mutationPath: o,
|
|
830
|
+
data: p,
|
|
831
|
+
revision: nt(m)
|
|
832
|
+
};
|
|
833
|
+
} finally {
|
|
834
|
+
yt(c, l, n.lockCleanupOperations ?? tt);
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
function kt(e, t, n, r = tt) {
|
|
838
|
+
let i = N(e), a = n ?? L(i), o = gt(a), s = !1;
|
|
839
|
+
try {
|
|
840
|
+
if (L(i) !== a || dt(a) !== t) throw new F("changed", `Cannot restore config because ${i} changed after the save.`);
|
|
841
|
+
g(a), s = !0, st(a, et);
|
|
842
|
+
} finally {
|
|
843
|
+
yt([o], s, r);
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
function At(e, t) {
|
|
847
|
+
return Ot(() => e, t).path;
|
|
848
|
+
}
|
|
849
|
+
function jt(e, t) {
|
|
850
|
+
return At(t, P(e));
|
|
851
|
+
}
|
|
852
|
+
var Mt = /* @__PURE__ */ new Set([
|
|
853
|
+
"observer_provider",
|
|
854
|
+
"observer_model",
|
|
855
|
+
"observer_runtime",
|
|
856
|
+
"observer_base_url",
|
|
857
|
+
"observer_simple_provider",
|
|
858
|
+
"observer_simple_model",
|
|
859
|
+
"observer_rich_provider",
|
|
860
|
+
"observer_rich_model",
|
|
861
|
+
"observer_reasoning_effort",
|
|
862
|
+
"observer_reasoning_summary",
|
|
863
|
+
"observer_rich_reasoning_effort",
|
|
864
|
+
"observer_rich_reasoning_summary",
|
|
865
|
+
"observer_auth_source",
|
|
866
|
+
"observer_auth_file"
|
|
867
|
+
]);
|
|
868
|
+
function Nt(e, t) {
|
|
869
|
+
let n = e === "observer_auth_command";
|
|
870
|
+
if (!t.trim()) return n ? [] : {};
|
|
871
|
+
try {
|
|
872
|
+
let e = JSON.parse(t);
|
|
873
|
+
if (n) return Array.isArray(e) && e.every((e) => typeof e == "string") ? e : void 0;
|
|
874
|
+
if (typeof e == "object" && e && !Array.isArray(e)) return e;
|
|
875
|
+
} catch {}
|
|
876
|
+
}
|
|
877
|
+
function Pt(e, t) {
|
|
878
|
+
if (Mt.has(e)) return t;
|
|
879
|
+
switch (e) {
|
|
880
|
+
case "observer_temperature":
|
|
881
|
+
case "observer_simple_temperature":
|
|
882
|
+
case "observer_rich_temperature":
|
|
883
|
+
case "observer_rich_max_output_tokens":
|
|
884
|
+
case "observer_max_output_tokens": {
|
|
885
|
+
let e = Number(t);
|
|
886
|
+
return Number.isFinite(e) ? e : void 0;
|
|
887
|
+
}
|
|
888
|
+
case "observer_max_chars":
|
|
889
|
+
case "observer_max_tokens":
|
|
890
|
+
case "observer_auth_timeout_ms":
|
|
891
|
+
case "observer_auth_cache_ttl_s": {
|
|
892
|
+
let e = Number.parseInt(t, 10);
|
|
893
|
+
return Number.isFinite(e) ? e : void 0;
|
|
894
|
+
}
|
|
895
|
+
case "observer_tier_routing_enabled":
|
|
896
|
+
case "observer_openai_use_responses": return t === "1" || t === "true";
|
|
897
|
+
case "observer_output_mode": return [
|
|
898
|
+
"auto",
|
|
899
|
+
"json_schema",
|
|
900
|
+
"legacy_xml"
|
|
901
|
+
].includes(t) ? t : void 0;
|
|
902
|
+
case "claude_command":
|
|
903
|
+
case "codex_command": return Ke(t) ?? void 0;
|
|
904
|
+
case "observer_headers":
|
|
905
|
+
case "observer_auth_command": return Nt(e, t);
|
|
906
|
+
default: return t === "" ? void 0 : t;
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
function Ft() {
|
|
910
|
+
let e = {};
|
|
911
|
+
for (let [t, n] of Object.entries(Ge)) {
|
|
912
|
+
let r = process.env[n];
|
|
913
|
+
if (r === void 0) continue;
|
|
914
|
+
let i = Pt(t, r);
|
|
915
|
+
i !== void 0 && (e[t] = i);
|
|
916
|
+
}
|
|
917
|
+
return e;
|
|
918
|
+
}
|
|
919
|
+
function It() {
|
|
920
|
+
let e = {};
|
|
921
|
+
for (let t of Object.keys(Ft())) {
|
|
922
|
+
let n = Ge[t];
|
|
923
|
+
n && (e[t] = n);
|
|
924
|
+
}
|
|
925
|
+
return e;
|
|
926
|
+
}
|
|
927
|
+
function R(e) {
|
|
928
|
+
return typeof e == "object" && e && !Array.isArray(e) ? e : null;
|
|
929
|
+
}
|
|
930
|
+
function z(e) {
|
|
931
|
+
let t = R(M().provider);
|
|
932
|
+
return t ? R(t[e]) ?? {} : {};
|
|
933
|
+
}
|
|
934
|
+
function Lt(e) {
|
|
935
|
+
return Object.keys(z(e)).length > 0;
|
|
936
|
+
}
|
|
937
|
+
function Rt() {
|
|
938
|
+
let e = R(M().provider);
|
|
939
|
+
return e ? new Set(Object.keys(e)) : /* @__PURE__ */ new Set();
|
|
940
|
+
}
|
|
941
|
+
var zt = /* @__PURE__ */ new Set([
|
|
942
|
+
"openai",
|
|
943
|
+
"anthropic",
|
|
944
|
+
"opencode"
|
|
945
|
+
]);
|
|
946
|
+
function Bt(e) {
|
|
947
|
+
return typeof e != "string" || !e.includes("/") ? null : e.split("/")[0]?.trim().toLowerCase() || null;
|
|
948
|
+
}
|
|
949
|
+
function Vt() {
|
|
950
|
+
let e = Rt(), t = M();
|
|
951
|
+
for (let n of ["model", "small_model"]) {
|
|
952
|
+
let r = Bt(t[n]);
|
|
953
|
+
r && e.add(r);
|
|
954
|
+
}
|
|
955
|
+
return e;
|
|
956
|
+
}
|
|
957
|
+
function Ht() {
|
|
958
|
+
let e = Vt();
|
|
959
|
+
for (let t of zt) e.add(t);
|
|
960
|
+
return Array.from(e).sort((e, t) => e.localeCompare(t));
|
|
961
|
+
}
|
|
962
|
+
function Ut(e) {
|
|
963
|
+
let t = Bt(e);
|
|
964
|
+
return t && zt.has(t) ? t : null;
|
|
965
|
+
}
|
|
966
|
+
function Wt(e) {
|
|
967
|
+
return e === "openai" ? "gpt-6-luna" : e === "anthropic" ? "claude-haiku-4-5" : e === "opencode" ? "opencode/gpt-6-luna" : null;
|
|
968
|
+
}
|
|
969
|
+
function Gt(e, t) {
|
|
970
|
+
if (e !== "opencode") return [
|
|
971
|
+
null,
|
|
972
|
+
t || Wt(e),
|
|
973
|
+
{}
|
|
974
|
+
];
|
|
975
|
+
let n = t || Wt(e) || "", r = `${e}/`;
|
|
976
|
+
return [
|
|
977
|
+
"https://opencode.ai/zen/v1",
|
|
978
|
+
(n.toLowerCase().startsWith(r) ? n.slice(r.length) : n) || null,
|
|
979
|
+
{}
|
|
980
|
+
];
|
|
981
|
+
}
|
|
982
|
+
function Kt(e, t) {
|
|
983
|
+
if (!e?.includes("/")) return null;
|
|
984
|
+
let n = e.split("/")[0] ?? "";
|
|
985
|
+
if (!n) return null;
|
|
986
|
+
if (t.has(n)) return n;
|
|
987
|
+
let r = n.toLowerCase();
|
|
988
|
+
return [...t].find((e) => e.toLowerCase() === r) ?? null;
|
|
989
|
+
}
|
|
990
|
+
function qt(e) {
|
|
991
|
+
return Yt(Jt(e));
|
|
992
|
+
}
|
|
993
|
+
function Jt(e) {
|
|
994
|
+
let t = "";
|
|
995
|
+
for (let n = 0; n < e.length; n++) {
|
|
996
|
+
if (e[n] !== "$" || n === e.length - 1) {
|
|
997
|
+
t += e[n];
|
|
998
|
+
continue;
|
|
999
|
+
}
|
|
1000
|
+
if (e[n + 1] === "{") {
|
|
1001
|
+
let r = e.indexOf("}", n + 2);
|
|
1002
|
+
if (r > n + 2) {
|
|
1003
|
+
let i = e.slice(n + 2, r);
|
|
1004
|
+
t += process.env[i] ?? e.slice(n, r + 1), n = r;
|
|
1005
|
+
continue;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
let r = n + 1, i = r;
|
|
1009
|
+
for (; i < e.length;) {
|
|
1010
|
+
let t = e.charCodeAt(i);
|
|
1011
|
+
if (!(t >= 65 && t <= 90 || t >= 97 && t <= 122) && !(t >= 48 && t <= 57) && t !== 95) break;
|
|
1012
|
+
i++;
|
|
1013
|
+
}
|
|
1014
|
+
let a = e.slice(r, i);
|
|
1015
|
+
if (!a || !Number.isNaN(Number(a[0]))) {
|
|
1016
|
+
t += "$";
|
|
1017
|
+
continue;
|
|
1018
|
+
}
|
|
1019
|
+
t += process.env[a] ?? e.slice(n, i), n = i - 1;
|
|
1020
|
+
}
|
|
1021
|
+
return t;
|
|
1022
|
+
}
|
|
1023
|
+
function Yt(e) {
|
|
1024
|
+
if (!e.includes("{file:")) return e;
|
|
1025
|
+
let t = "", n = 0;
|
|
1026
|
+
for (; n < e.length;) {
|
|
1027
|
+
let r = e.indexOf("{file:", n);
|
|
1028
|
+
if (r < 0) {
|
|
1029
|
+
t += e.slice(n);
|
|
1030
|
+
break;
|
|
1031
|
+
}
|
|
1032
|
+
let i = e.indexOf("}", r + 6);
|
|
1033
|
+
if (i < 0) {
|
|
1034
|
+
t += e.slice(n);
|
|
1035
|
+
break;
|
|
1036
|
+
}
|
|
1037
|
+
t += e.slice(n, r);
|
|
1038
|
+
let a = e.slice(r, i + 1), o = e.slice(r + 6, i).trim();
|
|
1039
|
+
if (!o) {
|
|
1040
|
+
t += a, n = i + 1;
|
|
1041
|
+
continue;
|
|
1042
|
+
}
|
|
1043
|
+
let s = Jt(o), c = s.startsWith("~") ? `${k()}${s.slice(1)}` : s;
|
|
1044
|
+
try {
|
|
1045
|
+
t += h(c, "utf-8").trim();
|
|
1046
|
+
} catch {
|
|
1047
|
+
t += a;
|
|
1048
|
+
}
|
|
1049
|
+
n = i + 1;
|
|
1050
|
+
}
|
|
1051
|
+
return t;
|
|
1052
|
+
}
|
|
1053
|
+
function B(e) {
|
|
1054
|
+
return R(e.options) ?? {};
|
|
1055
|
+
}
|
|
1056
|
+
function Xt(e) {
|
|
1057
|
+
let t = B(e), n = t.baseURL || t.baseUrl || t.base_url || e.base_url;
|
|
1058
|
+
return typeof n == "string" && n ? n : null;
|
|
1059
|
+
}
|
|
1060
|
+
function Zt(e) {
|
|
1061
|
+
let t = R(B(e).headers);
|
|
1062
|
+
if (!t) return {};
|
|
1063
|
+
let n = {};
|
|
1064
|
+
for (let [e, r] of Object.entries(t)) typeof e == "string" && typeof r == "string" && (n[e] = qt(r));
|
|
1065
|
+
return n;
|
|
1066
|
+
}
|
|
1067
|
+
function Qt(e) {
|
|
1068
|
+
let t = B(e), n = t.apiKey || e.apiKey;
|
|
1069
|
+
if (typeof n == "string" && n) return qt(n);
|
|
1070
|
+
let r = t.apiKeyEnv ?? t.api_key_env;
|
|
1071
|
+
if (typeof r == "string" && r) {
|
|
1072
|
+
let e = process.env[r];
|
|
1073
|
+
if (e) return e;
|
|
1074
|
+
}
|
|
1075
|
+
return null;
|
|
1076
|
+
}
|
|
1077
|
+
function $t(e) {
|
|
1078
|
+
let t = z(e), n = B(t), r = n.defaultModel ?? n.default_model ?? t.defaultModel ?? t.default_model;
|
|
1079
|
+
if (typeof r == "string" && r) return r.startsWith(`${e}/`) ? r : `${e}/${r}`;
|
|
1080
|
+
let i = R(t.models);
|
|
1081
|
+
if (i) {
|
|
1082
|
+
let t = Object.keys(i)[0];
|
|
1083
|
+
if (typeof t == "string" && t) return `${e}/${t}`;
|
|
1084
|
+
}
|
|
1085
|
+
return null;
|
|
1086
|
+
}
|
|
1087
|
+
function en(e, t) {
|
|
1088
|
+
let n = z(e), r = Xt(n), i = Zt(n), a = t;
|
|
1089
|
+
a ||= $t(e) ?? "";
|
|
1090
|
+
let o = `${e}/`, s = a.toLowerCase().startsWith(o.toLowerCase()) ? a.slice(o.length) : a, c = R(n.models), l = s;
|
|
1091
|
+
if (c) {
|
|
1092
|
+
let e = R(c[s]);
|
|
1093
|
+
e && typeof e.id == "string" && (l = e.id);
|
|
1094
|
+
}
|
|
1095
|
+
return (typeof l != "string" || !l) && (l = null), [
|
|
1096
|
+
r,
|
|
1097
|
+
l,
|
|
1098
|
+
i
|
|
1099
|
+
];
|
|
1100
|
+
}
|
|
1101
|
+
//#endregion
|
|
1102
|
+
//#region src/database-runtime-primitives.ts
|
|
1103
|
+
var tn = 21, nn = [
|
|
1104
|
+
"memory_items",
|
|
1105
|
+
"sessions",
|
|
1106
|
+
"artifacts",
|
|
1107
|
+
"raw_events",
|
|
1108
|
+
"raw_event_sessions",
|
|
1109
|
+
"usage_events"
|
|
1110
|
+
], rn = [
|
|
1111
|
+
...nn,
|
|
1112
|
+
"memory_fts",
|
|
1113
|
+
"coordinator_enrollment_reconciliation_issues"
|
|
1114
|
+
];
|
|
1115
|
+
function an() {
|
|
1116
|
+
let e = process.env.CODEMEM_EMBEDDING_DISABLED?.toLowerCase();
|
|
1117
|
+
return e === "1" || e === "true" || e === "yes";
|
|
1118
|
+
}
|
|
1119
|
+
function on(e) {
|
|
1120
|
+
if (!an() && (ve.load(e), !e.prepare("SELECT vec_version() AS v").get()?.v)) throw Error("sqlite-vec loaded but version check failed");
|
|
1121
|
+
}
|
|
1122
|
+
function V(e) {
|
|
1123
|
+
let t = e.pragma("user_version", { simple: !0 });
|
|
1124
|
+
return typeof t == "number" ? t : 0;
|
|
1125
|
+
}
|
|
1126
|
+
var sn = [{
|
|
1127
|
+
name: "trg_identity_devices_assignment_version",
|
|
1128
|
+
create: "CREATE TRIGGER trg_identity_devices_assignment_version\n AFTER UPDATE OF identity_id ON identity_devices\n WHEN NEW.identity_id <> OLD.identity_id\n BEGIN\n UPDATE identity_devices\n SET assignment_version = OLD.assignment_version + 1\n WHERE device_id = NEW.device_id;\n END"
|
|
1129
|
+
}, {
|
|
1130
|
+
name: "trg_identity_devices_purge_decisions",
|
|
1131
|
+
create: "CREATE TRIGGER trg_identity_devices_purge_decisions\n AFTER DELETE ON identity_devices\n BEGIN\n DELETE FROM policy_team_device_decisions WHERE device_id = OLD.device_id;\n END"
|
|
1132
|
+
}], cn = sn.map(({ name: e, create: t }) => `DROP TRIGGER IF EXISTS ${e};\n${t};`).join("\n");
|
|
1133
|
+
function ln(e) {
|
|
1134
|
+
return e.replace(/\s+/g, " ").trim();
|
|
1135
|
+
}
|
|
1136
|
+
function un(e) {
|
|
1137
|
+
let t = e.prepare("SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?");
|
|
1138
|
+
return sn.every(({ name: e, create: n }) => {
|
|
1139
|
+
let r = t.get(e);
|
|
1140
|
+
return typeof r?.sql == "string" && ln(r.sql) === ln(n);
|
|
1141
|
+
});
|
|
1142
|
+
}
|
|
1143
|
+
//#endregion
|
|
1144
|
+
//#region src/memory-retirement-delivery-schema.ts
|
|
1145
|
+
function dn(e) {
|
|
1146
|
+
e.exec("CREATE TABLE IF NOT EXISTS memory_retirement_deliveries (\n control_id TEXT NOT NULL,\n peer_device_id TEXT NOT NULL,\n entity_id TEXT NOT NULL,\n source_device_id TEXT NOT NULL,\n retired_scope_id TEXT NOT NULL,\n acknowledged_at TEXT,\n PRIMARY KEY (control_id, peer_device_id)\n );\n CREATE INDEX IF NOT EXISTS idx_memory_retirement_deliveries_pending\n ON memory_retirement_deliveries(peer_device_id, source_device_id, acknowledged_at, control_id);\n CREATE TABLE IF NOT EXISTS memory_retirement_peer_trust (\n local_device_id TEXT NOT NULL,\n peer_device_id TEXT NOT NULL,\n public_key TEXT NOT NULL,\n pinned_fingerprint TEXT NOT NULL,\n PRIMARY KEY (local_device_id, peer_device_id)\n );\n CREATE TABLE IF NOT EXISTS memory_retirement_receipts (\n control_id TEXT PRIMARY KEY,\n source_device_id TEXT NOT NULL,\n received_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS memory_retirement_reset_receivers (\n reset_id TEXT PRIMARY KEY, source_device_id TEXT NOT NULL, source_public_key TEXT NOT NULL,\n local_device_id TEXT NOT NULL, boundary TEXT NOT NULL, next_offset INTEGER NOT NULL DEFAULT 0,\n complete INTEGER NOT NULL DEFAULT 0, last_page_digest TEXT\n );\n CREATE TABLE IF NOT EXISTS memory_retirement_reset_manifests (\n reset_id TEXT NOT NULL, peer_device_id TEXT NOT NULL, source_device_id TEXT NOT NULL,\n boundary TEXT NOT NULL, controls_json TEXT NOT NULL,\n PRIMARY KEY(reset_id, peer_device_id, source_device_id)\n );");
|
|
1147
|
+
}
|
|
1148
|
+
//#endregion
|
|
1149
|
+
//#region src/memory-scope-retirement.ts
|
|
1150
|
+
function fn(e) {
|
|
1151
|
+
e.exec("CREATE TABLE IF NOT EXISTS memory_scope_retirements (\n entity_id TEXT NOT NULL,\n source_device_id TEXT NOT NULL,\n retired_scope_id TEXT NOT NULL,\n retired_at TEXT NOT NULL,\n PRIMARY KEY (entity_id, retired_scope_id)\n );\n CREATE TRIGGER IF NOT EXISTS memory_scope_retirements_no_update\n BEFORE UPDATE ON memory_scope_retirements\n BEGIN SELECT RAISE(ABORT, 'memory_retirement_immutable'); END;\n CREATE TRIGGER IF NOT EXISTS memory_scope_retirements_no_delete\n BEFORE DELETE ON memory_scope_retirements\n BEGIN SELECT RAISE(ABORT, 'memory_retirement_immutable'); END;\n CREATE TRIGGER IF NOT EXISTS memory_scope_retirements_no_replace\n BEFORE INSERT ON memory_scope_retirements\n WHEN EXISTS (SELECT 1 FROM memory_scope_retirements WHERE entity_id = NEW.entity_id AND retired_scope_id = NEW.retired_scope_id)\n BEGIN SELECT RAISE(ABORT, 'memory_retirement_immutable'); END;");
|
|
1152
|
+
}
|
|
1153
|
+
function pn(e, t, n) {
|
|
1154
|
+
return n ? !!e.prepare("SELECT 1 FROM memory_scope_retirements WHERE entity_id = ? AND retired_scope_id = ?").get(t, n) : !1;
|
|
1155
|
+
}
|
|
1156
|
+
function mn(e, t, n) {
|
|
1157
|
+
if (pn(e, t, n)) throw Error("memory_scope_retired");
|
|
1158
|
+
}
|
|
1159
|
+
function hn(e, t) {
|
|
1160
|
+
return !!e.prepare("SELECT 1 FROM memory_scope_retirements WHERE entity_id = ? LIMIT 1").get(t);
|
|
1161
|
+
}
|
|
1162
|
+
//#endregion
|
|
1163
|
+
//#region src/memory-ownership-recovery-schema.ts
|
|
1164
|
+
function gn(e) {
|
|
1165
|
+
Ne(e), fn(e), dn(e), e.exec("CREATE TABLE IF NOT EXISTS memory_ownership_recoveries (\n operation_id TEXT PRIMARY KEY,\n actor_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n request_json TEXT NOT NULL,\n reviewed_digest TEXT NOT NULL,\n result_json TEXT NOT NULL,\n created_at TEXT NOT NULL\n );");
|
|
1166
|
+
}
|
|
1167
|
+
//#endregion
|
|
1168
|
+
//#region src/memory-reference-schema.ts
|
|
1169
|
+
var _n = [{
|
|
1170
|
+
name: "memory_file_refs",
|
|
1171
|
+
columns: [
|
|
1172
|
+
"memory_id",
|
|
1173
|
+
"file_path",
|
|
1174
|
+
"relation"
|
|
1175
|
+
],
|
|
1176
|
+
ddl: "CREATE TABLE IF NOT EXISTS memory_file_refs (\n memory_id INTEGER NOT NULL,\n file_path TEXT NOT NULL,\n relation TEXT NOT NULL CHECK(relation IN ('read', 'modified')),\n PRIMARY KEY (memory_id, file_path, relation),\n FOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n )",
|
|
1177
|
+
index: "idx_memory_file_refs_path",
|
|
1178
|
+
indexDdl: "CREATE INDEX IF NOT EXISTS idx_memory_file_refs_path ON memory_file_refs(file_path)"
|
|
1179
|
+
}, {
|
|
1180
|
+
name: "memory_concept_refs",
|
|
1181
|
+
columns: ["memory_id", "concept"],
|
|
1182
|
+
ddl: "CREATE TABLE IF NOT EXISTS memory_concept_refs (\n memory_id INTEGER NOT NULL,\n concept TEXT NOT NULL,\n PRIMARY KEY (memory_id, concept),\n FOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE\n )",
|
|
1183
|
+
index: "idx_memory_concept_refs_concept",
|
|
1184
|
+
indexDdl: "CREATE INDEX IF NOT EXISTS idx_memory_concept_refs_concept ON memory_concept_refs(concept)"
|
|
1185
|
+
}];
|
|
1186
|
+
function vn(e) {
|
|
1187
|
+
let t = /* @__PURE__ */ new Set();
|
|
1188
|
+
for (let n of _n) {
|
|
1189
|
+
let r = e.prepare("SELECT type FROM sqlite_master WHERE name = ? AND type IN ('table', 'view')").get(n.name);
|
|
1190
|
+
if (!r) continue;
|
|
1191
|
+
if (r.type !== "table") throw Error(`memory_reference_schema_incompatible:${n.name}:expected_table`);
|
|
1192
|
+
let i = e.prepare("SELECT name FROM pragma_table_info(?)").all(n.name), a = n.columns.filter((e) => !i.some((t) => t.name === e));
|
|
1193
|
+
if (a.length > 0) throw Error(`memory_reference_schema_incompatible:${a.map((e) => `${n.name}.${e}`).join(",")}`);
|
|
1194
|
+
t.add(n.name);
|
|
1195
|
+
}
|
|
1196
|
+
return t;
|
|
1197
|
+
}
|
|
1198
|
+
function yn(e) {
|
|
1199
|
+
for (let t of _n) try {
|
|
1200
|
+
e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?").get(t.index) || e.exec(t.indexDdl);
|
|
1201
|
+
} catch {}
|
|
1202
|
+
}
|
|
1203
|
+
function bn(e) {
|
|
1204
|
+
let t = vn(e);
|
|
1205
|
+
for (let n of _n) t.has(n.name) || e.exec(n.ddl);
|
|
1206
|
+
yn(e);
|
|
1207
|
+
}
|
|
1208
|
+
//#endregion
|
|
1209
|
+
//#region src/raw-event-flush-claim-schema.ts
|
|
1210
|
+
function xn(e) {
|
|
1211
|
+
return e.prepare("SELECT 1 FROM pragma_table_info('raw_event_flush_batches') WHERE name = 'claim_generation'").get() !== void 0;
|
|
1212
|
+
}
|
|
1213
|
+
function Sn(e) {
|
|
1214
|
+
if (e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'raw_event_flush_batches'").get() && !xn(e)) {
|
|
1215
|
+
if (e.readonly) throw Error("Raw-event claim schema requires a writable database upgrade");
|
|
1216
|
+
try {
|
|
1217
|
+
e.exec("ALTER TABLE raw_event_flush_batches ADD COLUMN claim_generation INTEGER NOT NULL DEFAULT 0");
|
|
1218
|
+
} catch (t) {
|
|
1219
|
+
if (!xn(e)) throw t;
|
|
1220
|
+
}
|
|
1221
|
+
if (!xn(e)) throw Error("Raw-event claim generation is missing after upgrade");
|
|
1222
|
+
}
|
|
1223
|
+
}
|
|
1224
|
+
//#endregion
|
|
1225
|
+
//#region src/relay-service-pin-store.ts
|
|
1226
|
+
var Cn = /* @__PURE__ */ new WeakSet();
|
|
1227
|
+
function H(e) {
|
|
1228
|
+
Cn.has(e) || (e.exec("\n CREATE TABLE IF NOT EXISTS sync_relay_service_pins (\n coordinator_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n pinned_key TEXT NOT NULL,\n first_seen_at TEXT NOT NULL,\n state TEXT NOT NULL CHECK(state IN ('pinned', 'pending_change')),\n candidate_key TEXT,\n candidate_seen_at TEXT,\n last_candidate_key TEXT,\n last_candidate_seen_at TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY(coordinator_id, group_id)\n );\n "), e.inTransaction || Cn.add(e));
|
|
1229
|
+
}
|
|
1230
|
+
function wn(e, t, n) {
|
|
1231
|
+
return e.prepare("SELECT * FROM sync_relay_service_pins WHERE coordinator_id = ? AND group_id = ?").get(t, n);
|
|
1232
|
+
}
|
|
1233
|
+
function Tn(e, t, n) {
|
|
1234
|
+
H(e);
|
|
1235
|
+
let r = wn(e, t, n);
|
|
1236
|
+
return r ? Dn(r) : null;
|
|
1237
|
+
}
|
|
1238
|
+
function En(e) {
|
|
1239
|
+
return H(e), e.prepare("SELECT * FROM sync_relay_service_pins ORDER BY coordinator_id, group_id").all().map(Dn);
|
|
1240
|
+
}
|
|
1241
|
+
function Dn(e) {
|
|
1242
|
+
return {
|
|
1243
|
+
coordinatorId: e.coordinator_id,
|
|
1244
|
+
groupId: e.group_id,
|
|
1245
|
+
pinnedKey: e.pinned_key,
|
|
1246
|
+
firstSeenAt: e.first_seen_at,
|
|
1247
|
+
state: e.state,
|
|
1248
|
+
candidateKey: e.candidate_key,
|
|
1249
|
+
candidateSeenAt: e.candidate_seen_at,
|
|
1250
|
+
lastCandidateKey: e.last_candidate_key,
|
|
1251
|
+
lastCandidateSeenAt: e.last_candidate_seen_at
|
|
1252
|
+
};
|
|
1253
|
+
}
|
|
1254
|
+
function On(e, t, n, r, i) {
|
|
1255
|
+
e.prepare("INSERT INTO sync_relay_service_pins(\n coordinator_id, group_id, pinned_key, first_seen_at, state,\n candidate_key, candidate_seen_at, updated_at\n ) VALUES (?, ?, ?, ?, 'pinned', NULL, NULL, ?)\n ON CONFLICT(coordinator_id, group_id) DO UPDATE SET\n last_candidate_seen_at = CASE WHEN candidate_key IS NOT NULL\n AND candidate_key != excluded.pinned_key\n THEN candidate_seen_at ELSE last_candidate_seen_at END,\n last_candidate_key = CASE WHEN candidate_key IS NOT NULL\n AND candidate_key != excluded.pinned_key\n THEN candidate_key ELSE last_candidate_key END,\n first_seen_at = CASE WHEN pinned_key = excluded.pinned_key\n THEN first_seen_at ELSE excluded.first_seen_at END,\n pinned_key = excluded.pinned_key,\n state = 'pinned',\n candidate_key = NULL,\n candidate_seen_at = NULL,\n updated_at = excluded.updated_at").run(t, n, r, i, i);
|
|
1256
|
+
}
|
|
1257
|
+
function kn(e, t, n, r) {
|
|
1258
|
+
let i = t.candidate_key === n ? t.candidate_seen_at ?? r : r;
|
|
1259
|
+
e.prepare("UPDATE sync_relay_service_pins\n SET state = 'pending_change', candidate_key = ?, candidate_seen_at = ?, updated_at = ?\n WHERE coordinator_id = ? AND group_id = ?").run(n, i, r, t.coordinator_id, t.group_id);
|
|
1260
|
+
}
|
|
1261
|
+
function An(e, t) {
|
|
1262
|
+
H(e);
|
|
1263
|
+
let { coordinatorId: n, groupId: r, advertisedKey: i, operatorKey: a } = t, o = (t.now ?? /* @__PURE__ */ new Date()).toISOString();
|
|
1264
|
+
return e.transaction(() => {
|
|
1265
|
+
let t = wn(e, n, r);
|
|
1266
|
+
if (a !== void 0 || !t) {
|
|
1267
|
+
let t = a ?? i;
|
|
1268
|
+
return On(e, n, r, t, o), {
|
|
1269
|
+
status: "pinned",
|
|
1270
|
+
key: t
|
|
1271
|
+
};
|
|
1272
|
+
}
|
|
1273
|
+
return t.pinned_key === i ? (t.state !== "pinned" && On(e, n, r, i, o), {
|
|
1274
|
+
status: "pinned",
|
|
1275
|
+
key: t.pinned_key
|
|
1276
|
+
}) : (kn(e, t, i, o), {
|
|
1277
|
+
status: "paused",
|
|
1278
|
+
pinnedKey: t.pinned_key,
|
|
1279
|
+
candidateKey: i
|
|
1280
|
+
});
|
|
1281
|
+
}).immediate();
|
|
1282
|
+
}
|
|
1283
|
+
function jn(e, t) {
|
|
1284
|
+
H(e);
|
|
1285
|
+
let n = u(t.candidateKey);
|
|
1286
|
+
if (!n) return !1;
|
|
1287
|
+
let r = (t.now ?? /* @__PURE__ */ new Date()).toISOString();
|
|
1288
|
+
return e.prepare("UPDATE sync_relay_service_pins\n SET pinned_key = candidate_key, first_seen_at = ?, state = 'pinned',\n candidate_key = NULL, candidate_seen_at = NULL, updated_at = ?\n WHERE coordinator_id = ? AND group_id = ?\n AND state = 'pending_change' AND candidate_key = ?").run(r, r, t.coordinatorId, t.groupId, n).changes === 1;
|
|
1289
|
+
}
|
|
1290
|
+
//#endregion
|
|
1291
|
+
//#region src/repository-discovery-index.ts
|
|
1292
|
+
function Mn(e) {
|
|
1293
|
+
return e.prepare("SELECT COUNT(*) FROM sqlite_master WHERE type = 'trigger' AND name IN (\n 'trg_repository_discovery_session_insert',\n 'trg_repository_discovery_session_update',\n 'trg_repository_discovery_session_delete'\n )").pluck().get();
|
|
1294
|
+
}
|
|
1295
|
+
function Nn(e) {
|
|
1296
|
+
e.exec("SAVEPOINT repository_discovery_repair");
|
|
1297
|
+
try {
|
|
1298
|
+
Pn(e), e.exec("RELEASE repository_discovery_repair");
|
|
1299
|
+
} catch (t) {
|
|
1300
|
+
throw e.exec("ROLLBACK TO repository_discovery_repair; RELEASE repository_discovery_repair"), t;
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
function Pn(e) {
|
|
1304
|
+
e.exec("\n CREATE TABLE IF NOT EXISTS repository_discovery_state (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n source_revision INTEGER NOT NULL DEFAULT 0,\n indexed_revision INTEGER NOT NULL DEFAULT -1\n );\n INSERT OR IGNORE INTO repository_discovery_state(id) VALUES (1);\n "), e.prepare("UPDATE repository_discovery_state SET indexed_revision = indexed_revision WHERE id = 1").run();
|
|
1305
|
+
let t = e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'repository_workspace_evidence'").get();
|
|
1306
|
+
(Mn(e) !== 3 || !t) && e.prepare("UPDATE repository_discovery_state\n SET source_revision = source_revision + 1, indexed_revision = -1 WHERE id = 1").run(), e.exec("\n CREATE TABLE IF NOT EXISTS repository_workspace_evidence (\n cwd TEXT PRIMARY KEY,\n recorded_identities_json TEXT NOT NULL,\n filesystem_identity TEXT,\n filesystem_anchor TEXT,\n anchor_mtime_ns TEXT,\n checked_at_ms INTEGER NOT NULL\n );\n CREATE TRIGGER IF NOT EXISTS trg_repository_discovery_session_insert\n AFTER INSERT ON sessions BEGIN\n UPDATE repository_discovery_state SET source_revision = source_revision + 1 WHERE id = 1;\n END;\n CREATE TRIGGER IF NOT EXISTS trg_repository_discovery_session_update\n AFTER UPDATE OF cwd, git_remote, metadata_json ON sessions BEGIN\n UPDATE repository_discovery_state SET source_revision = source_revision + 1 WHERE id = 1;\n END;\n CREATE TRIGGER IF NOT EXISTS trg_repository_discovery_session_delete\n AFTER DELETE ON sessions BEGIN\n UPDATE repository_discovery_state SET source_revision = source_revision + 1 WHERE id = 1;\n END;\n ");
|
|
1307
|
+
}
|
|
1308
|
+
function Fn(e) {
|
|
1309
|
+
try {
|
|
1310
|
+
return Mn(e) === 3 ? e.prepare("SELECT source_revision FROM repository_discovery_state WHERE id = 1").get()?.source_revision ?? null : null;
|
|
1311
|
+
} catch {
|
|
1312
|
+
return null;
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
function In(e) {
|
|
1316
|
+
try {
|
|
1317
|
+
return e.transaction(() => {
|
|
1318
|
+
let t = e.prepare("SELECT source_revision, indexed_revision FROM repository_discovery_state WHERE id = 1").get();
|
|
1319
|
+
return !t || t.source_revision !== t.indexed_revision ? null : e.prepare("SELECT cwd, recorded_identities_json AS recordedIdentitiesJson,\n filesystem_identity AS filesystemIdentity, filesystem_anchor AS filesystemAnchor,\n anchor_mtime_ns AS anchorMtimeNs, checked_at_ms AS checkedAtMs\n FROM repository_workspace_evidence ORDER BY cwd").all();
|
|
1320
|
+
})();
|
|
1321
|
+
} catch {
|
|
1322
|
+
return null;
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
function Ln(e, t, n) {
|
|
1326
|
+
return e.transaction(() => {
|
|
1327
|
+
if (Fn(e) !== t) return !1;
|
|
1328
|
+
e.prepare("DELETE FROM repository_workspace_evidence").run();
|
|
1329
|
+
let r = e.prepare("INSERT INTO repository_workspace_evidence(\n cwd, recorded_identities_json, filesystem_identity, filesystem_anchor,\n anchor_mtime_ns, checked_at_ms\n ) VALUES (?, ?, ?, ?, ?, ?)");
|
|
1330
|
+
for (let e of n) r.run(e.cwd, e.recordedIdentitiesJson, e.filesystemIdentity, e.filesystemAnchor, e.anchorMtimeNs, e.checkedAtMs);
|
|
1331
|
+
return e.prepare("UPDATE repository_discovery_state SET indexed_revision = ? WHERE id = 1").run(t), !0;
|
|
1332
|
+
}).immediate();
|
|
1333
|
+
}
|
|
1334
|
+
//#endregion
|
|
1335
|
+
//#region src/summary-memory.ts
|
|
1336
|
+
function Rn(e) {
|
|
1337
|
+
if (!e) return {};
|
|
1338
|
+
if (typeof e == "string") try {
|
|
1339
|
+
let t = JSON.parse(e);
|
|
1340
|
+
return t && typeof t == "object" && !Array.isArray(t) ? t : {};
|
|
1341
|
+
} catch {
|
|
1342
|
+
return {};
|
|
1343
|
+
}
|
|
1344
|
+
return typeof e == "object" && !Array.isArray(e) ? e : {};
|
|
1345
|
+
}
|
|
1346
|
+
function zn(e) {
|
|
1347
|
+
return Rn(e);
|
|
1348
|
+
}
|
|
1349
|
+
function Bn(e = "memory_items") {
|
|
1350
|
+
let t = e ? `${e}.` : "", n = `${t}kind`, r = `${t}metadata_json`;
|
|
1351
|
+
return `(
|
|
1352
|
+
LOWER(TRIM(COALESCE(${n}, ''))) = 'session_summary'
|
|
1353
|
+
OR CASE WHEN json_valid(COALESCE(${r}, '')) = 1 THEN (
|
|
1354
|
+
COALESCE(json_type(${r}, '$.is_summary') = 'true', 0)
|
|
1355
|
+
OR LOWER(TRIM(COALESCE(json_extract(${r}, '$.source'), ''))) = 'observer_summary'
|
|
1356
|
+
) ELSE 0 END
|
|
1357
|
+
)`;
|
|
1358
|
+
}
|
|
1359
|
+
function Vn(e) {
|
|
1360
|
+
if (String(e.kind ?? "").trim().toLowerCase() === "session_summary") return !0;
|
|
1361
|
+
let t = zn(e.metadata);
|
|
1362
|
+
return t.is_summary === !0 || String(t.source ?? "").trim().toLowerCase() === "observer_summary";
|
|
1363
|
+
}
|
|
1364
|
+
function Hn(e) {
|
|
1365
|
+
if (e === void 0) return {
|
|
1366
|
+
clauses: [],
|
|
1367
|
+
params: []
|
|
1368
|
+
};
|
|
1369
|
+
let t = Bn();
|
|
1370
|
+
return e === null ? {
|
|
1371
|
+
clauses: [`NOT ${t}`],
|
|
1372
|
+
params: []
|
|
1373
|
+
} : {
|
|
1374
|
+
clauses: [`(NOT ${t} OR memory_items.session_id = ?)`],
|
|
1375
|
+
params: [e]
|
|
1376
|
+
};
|
|
1377
|
+
}
|
|
1378
|
+
function Un(e) {
|
|
1379
|
+
if (String(e.kind ?? "").trim().toLowerCase() !== "session_summary") return !1;
|
|
1380
|
+
let t = zn(e.metadata);
|
|
1381
|
+
return t.is_summary !== !0 && String(t.source ?? "").trim().toLowerCase() !== "observer_summary";
|
|
1382
|
+
}
|
|
1383
|
+
function Wn(e, t) {
|
|
1384
|
+
let n = String(e ?? "").trim().toLowerCase();
|
|
1385
|
+
return Vn({
|
|
1386
|
+
kind: n,
|
|
1387
|
+
metadata: t
|
|
1388
|
+
}) ? "session_summary" : n || "change";
|
|
1389
|
+
}
|
|
1390
|
+
//#endregion
|
|
1391
|
+
//#region src/sync-status-indexes.ts
|
|
1392
|
+
var Gn = [{
|
|
1393
|
+
name: "idx_memory_items_embeddable_active",
|
|
1394
|
+
ddl: "CREATE INDEX IF NOT EXISTS idx_memory_items_embeddable_active\n ON memory_items(active)\n WHERE active = 1\n AND TRIM(COALESCE(title, '') || COALESCE(body_text, '')) != ''"
|
|
1395
|
+
}, {
|
|
1396
|
+
name: "idx_replication_ops_type_device_created",
|
|
1397
|
+
ddl: "CREATE INDEX IF NOT EXISTS idx_replication_ops_type_device_created\n ON replication_ops(op_type, device_id, created_at)"
|
|
1398
|
+
}];
|
|
1399
|
+
function Kn(e) {
|
|
1400
|
+
if (!e.readonly) for (let t of Gn) try {
|
|
1401
|
+
if (e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?").get(t.name)) continue;
|
|
1402
|
+
e.exec(t.ddl);
|
|
1403
|
+
} catch {}
|
|
1404
|
+
}
|
|
1405
|
+
//#endregion
|
|
1406
|
+
//#region src/test-schema.generated.ts
|
|
1407
|
+
var qn = "CREATE TABLE IF NOT EXISTS `device_identity_binding_commits` (\n `commit_digest` text PRIMARY KEY NOT NULL,\n `reviewed_inventory_digest` text NOT NULL,\n `request_json` text NOT NULL,\n `outcomes_json` text NOT NULL,\n `write_count` integer NOT NULL,\n `decided_by_identity_id` text NOT NULL,\n `decided_by_device_id` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `device_identity_binding_audit` (\n `event_id` text PRIMARY KEY NOT NULL,\n `commit_digest` text NOT NULL,\n `device_id` text NOT NULL,\n `previous_identity_id` text,\n `target_identity_id` text NOT NULL,\n `action` text NOT NULL,\n `previous_assignment_version` integer,\n `resulting_assignment_version` integer NOT NULL,\n `decided_by_identity_id` text NOT NULL,\n `decided_by_device_id` text NOT NULL,\n `created_at` text NOT NULL,\n FOREIGN KEY (`commit_digest`) REFERENCES `device_identity_binding_commits`(`commit_digest`) ON UPDATE no action ON DELETE no action\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_device_identity_binding_audit_commit_device` ON `device_identity_binding_audit` (`commit_digest`,`device_id`);\nCREATE INDEX IF NOT EXISTS `idx_device_identity_binding_audit_device_created` ON `device_identity_binding_audit` (`device_id`,`created_at`,`event_id`);\nCREATE TABLE IF NOT EXISTS `sessions` (\n `id` integer PRIMARY KEY NOT NULL,\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\nCREATE INDEX IF NOT EXISTS `idx_sessions_started_id` ON `sessions` (`started_at`,`id`);\nCREATE TABLE IF NOT EXISTS `replication_scopes` (\n `scope_id` text PRIMARY KEY NOT NULL,\n `label` text NOT NULL,\n `kind` text DEFAULT 'user' NOT NULL,\n `authority_type` text DEFAULT 'local' NOT NULL,\n `coordinator_id` text,\n `group_id` text,\n `manifest_issuer_device_id` text,\n `membership_epoch` integer DEFAULT 0 NOT NULL,\n `manifest_hash` text,\n `status` text DEFAULT 'active' NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS `idx_replication_scopes_status` ON `replication_scopes` (`status`);\nCREATE INDEX IF NOT EXISTS `idx_replication_scopes_authority_group` ON `replication_scopes` (`coordinator_id`,`group_id`);\nCREATE TABLE IF NOT EXISTS `project_scope_mappings` (\n `id` integer PRIMARY KEY NOT NULL,\n `workspace_identity` text,\n `project_pattern` text NOT NULL,\n `scope_id` text NOT NULL,\n `priority` integer DEFAULT 0 NOT NULL,\n `source` text DEFAULT 'user' NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_workspace_priority` ON `project_scope_mappings` (`workspace_identity`,`priority`);\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_pattern_priority` ON `project_scope_mappings` (`project_pattern`,`priority`);\nCREATE INDEX IF NOT EXISTS `idx_project_scope_mappings_scope` ON `project_scope_mappings` (`scope_id`);\nCREATE TABLE IF NOT EXISTS `scope_memberships` (\n `scope_id` text NOT NULL,\n `device_id` text NOT NULL,\n `role` text DEFAULT 'member' NOT NULL,\n `status` text DEFAULT 'active' NOT NULL,\n `membership_epoch` integer DEFAULT 0 NOT NULL,\n `coordinator_id` text,\n `group_id` text,\n `manifest_issuer_device_id` text,\n `manifest_hash` text,\n `signed_manifest_json` text,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`scope_id`, `device_id`)\n);\n\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_device_status` ON `scope_memberships` (`device_id`,`status`);\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_scope_status` ON `scope_memberships` (`scope_id`,`status`);\nCREATE INDEX IF NOT EXISTS `idx_scope_memberships_authority_group` ON `scope_memberships` (`coordinator_id`,`group_id`);\nCREATE TABLE IF NOT EXISTS `artifacts` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer NOT NULL,\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 FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_artifacts_session_kind` ON `artifacts` (`session_id`,`kind`);\nCREATE TABLE IF NOT EXISTS `memory_items` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer NOT NULL,\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 `dedup_key` text,\n `import_key` text,\n `scope_id` text,\n `project` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_memory_items_active_created` ON `memory_items` (`active`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_memory_items_created_id` ON `memory_items` (`created_at`,`id`);\nCREATE INDEX IF NOT EXISTS `idx_memory_items_origin_device_active` ON `memory_items` (`origin_device_id`,`active`);\nCREATE INDEX IF NOT EXISTS `idx_memory_items_session` ON `memory_items` (`session_id`);\nCREATE INDEX IF NOT EXISTS `idx_memory_items_project` ON `memory_items` (`project`);\nCREATE INDEX IF NOT EXISTS `idx_memory_items_scope_visibility_created` ON `memory_items` (`scope_id`,`visibility`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_memory_items_scope_backfill_pending` ON `memory_items` (`id`) WHERE scope_id IS NULL OR scope_id = '';\nCREATE INDEX IF NOT EXISTS `idx_memory_items_dedup_key_active_created` ON `memory_items` (`dedup_key`,`active`,`created_at`);\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_memory_items_same_session_dedup_unique` ON `memory_items` (`session_id`,`kind`,`visibility`,`workspace_id`,`dedup_key`) WHERE active = 1 AND dedup_key IS NOT NULL;\nCREATE TABLE IF NOT EXISTS `memory_file_refs` (\n `memory_id` integer NOT NULL,\n `file_path` text NOT NULL,\n `relation` text NOT NULL,\n PRIMARY KEY(`memory_id`, `file_path`, `relation`),\n FOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_memory_file_refs_path` ON `memory_file_refs` (`file_path`);\nCREATE TABLE IF NOT EXISTS `memory_concept_refs` (\n `memory_id` integer NOT NULL,\n `concept` text NOT NULL,\n PRIMARY KEY(`memory_id`, `concept`),\n FOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_memory_concept_refs_concept` ON `memory_concept_refs` (`concept`);\nCREATE TABLE IF NOT EXISTS `usage_events` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer,\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 FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE set null\n);\n\nCREATE INDEX IF NOT EXISTS `idx_usage_events_event_created` ON `usage_events` (`event`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_usage_events_session` ON `usage_events` (`session_id`);\nCREATE TABLE IF NOT EXISTS `retrieval_attempts` (\n `attempt_id` text PRIMARY KEY NOT NULL,\n `contract_version` integer NOT NULL,\n `surface` text NOT NULL,\n `trigger` text NOT NULL,\n `started_at` text NOT NULL,\n `completed_at` text,\n `retrieval_status` text NOT NULL,\n `delivery_status` text NOT NULL,\n `candidate_count` integer NOT NULL,\n `selected_count` integer NOT NULL,\n `persisted_candidate_count` integer NOT NULL,\n `recorder_version` text NOT NULL,\n `session_id` integer,\n `source` text,\n `stream_id` text,\n `source_session_id` text,\n `prompt_number` integer,\n `request_id` text,\n `raw_event_start_seq` integer,\n `raw_event_end_seq` integer,\n `experiment_id` text,\n `experiment_cell_id` text,\n `evaluation_checkout_id` text,\n `evaluation_fixture_id` text,\n `evaluation_seed` integer,\n `latency_ms` integer,\n `project` text,\n `scope_id` text,\n `mode` text,\n `limit_requested` integer,\n `token_budget` integer,\n `output_tokens` integer,\n `working_set_file_count` integer,\n `working_set_files_json` text,\n `query_hash_sha256` text,\n `query_char_count` integer,\n `query_token_estimate` integer,\n `filter_summary_json` text,\n `failure_code` text,\n `failure_stage` text,\n `trace_version` integer,\n `automatic_recall_json` text,\n `automatic_recall_key` text,\n `retention_until` text,\n `retention_pinned` integer DEFAULT 0 NOT NULL,\n `retention_finalized_at` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_session_started` ON `retrieval_attempts` (`session_id`,`started_at`);\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_retrieval_attempts_automatic_recall_key` ON `retrieval_attempts` (`automatic_recall_key`);\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_source_stream_started` ON `retrieval_attempts` (`source`,`stream_id`,`started_at`);\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_retention` ON `retrieval_attempts` (`retention_pinned`,`retention_until`);\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_started` ON `retrieval_attempts` (`started_at`,`attempt_id`);\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_surface_started` ON `retrieval_attempts` (`surface`,`started_at`);\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_retrieval_attempts_request_identity` ON `retrieval_attempts` (`source`,`surface`,`request_id`) WHERE request_id IS NOT NULL;\nCREATE INDEX IF NOT EXISTS `idx_retrieval_attempts_experiment_cell` ON `retrieval_attempts` (`experiment_id`,`experiment_cell_id`);\nCREATE TABLE IF NOT EXISTS `retrieval_exposures` (\n `exposure_id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `attempt_id` text NOT NULL,\n `memory_id` integer,\n `memory_import_key` text,\n `origin_device_id` text,\n `rank` integer NOT NULL,\n `disposition` text NOT NULL,\n `section` text,\n `handoff_status` text NOT NULL,\n `memory_rev` integer,\n `memory_updated_at` text,\n `memory_scope_id` text,\n `memory_kind` text,\n `memory_active` integer,\n `memory_deleted_at` text,\n `score_summary_json` text,\n `reason_codes_json` text,\n FOREIGN KEY (`attempt_id`) REFERENCES `retrieval_attempts`(`attempt_id`) ON UPDATE no action ON DELETE cascade,\n FOREIGN KEY (`memory_id`) REFERENCES `memory_items`(`id`) ON UPDATE no action ON DELETE set null\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_retrieval_exposures_attempt_rank` ON `retrieval_exposures` (`attempt_id`,`rank`);\nCREATE INDEX IF NOT EXISTS `idx_retrieval_exposures_memory` ON `retrieval_exposures` (`memory_id`);\nCREATE TABLE IF NOT EXISTS `outcome_evidence` (\n `evidence_id` text PRIMARY KEY NOT NULL,\n `contract_version` integer NOT NULL,\n `dimension` text NOT NULL,\n `evidence_type` text NOT NULL,\n `source_class` text NOT NULL,\n `observed_at` text NOT NULL,\n `producer` text NOT NULL,\n `producer_version` text NOT NULL,\n `status` text NOT NULL,\n `value_type` text,\n `value_integer` integer,\n `value_real` real,\n `value_unit` text,\n `session_id` integer,\n `source` text,\n `stream_id` text,\n `source_session_id` text,\n `prompt_number` integer,\n `raw_event_start_seq` integer,\n `raw_event_end_seq` integer,\n `experiment_id` text,\n `experiment_cell_id` text,\n `window_start_at` text,\n `window_end_at` text,\n `references_json` text,\n `retention_until` text,\n `retention_pinned` integer DEFAULT 0 NOT NULL,\n `retention_finalized_at` text,\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_observed_id` ON `outcome_evidence` (`observed_at`,`evidence_id`);\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_session_observed` ON `outcome_evidence` (`session_id`,`observed_at`);\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_source_stream_observed` ON `outcome_evidence` (`source`,`stream_id`,`observed_at`);\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_type_observed` ON `outcome_evidence` (`evidence_type`,`observed_at`);\nCREATE INDEX IF NOT EXISTS `idx_outcome_evidence_retention` ON `outcome_evidence` (`retention_pinned`,`retention_until`);\nCREATE TABLE IF NOT EXISTS `attribution_assessments` (\n `assessment_id` text PRIMARY KEY NOT NULL,\n `contract_version` integer NOT NULL,\n `subject_type` text NOT NULL,\n `attempt_id` text NOT NULL,\n `exposure_id` integer,\n `dimension` text NOT NULL,\n `impact_label` text NOT NULL,\n `basis` text NOT NULL,\n `confidence_level` text NOT NULL,\n `method` text NOT NULL,\n `method_version` text NOT NULL,\n `created_at` text NOT NULL,\n `claim_type` text DEFAULT 'observational' NOT NULL,\n FOREIGN KEY (`attempt_id`) REFERENCES `retrieval_attempts`(`attempt_id`) ON UPDATE no action ON DELETE cascade,\n FOREIGN KEY (`exposure_id`) REFERENCES `retrieval_exposures`(`exposure_id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_attribution_assessments_attempt_created` ON `attribution_assessments` (`attempt_id`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_attribution_assessments_label_created` ON `attribution_assessments` (`impact_label`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_attribution_assessments_exposure` ON `attribution_assessments` (`exposure_id`);\nCREATE TABLE IF NOT EXISTS `attribution_assessment_evidence` (\n `assessment_id` text NOT NULL,\n `evidence_id` text NOT NULL,\n PRIMARY KEY(`assessment_id`, `evidence_id`),\n FOREIGN KEY (`assessment_id`) REFERENCES `attribution_assessments`(`assessment_id`) ON UPDATE no action ON DELETE cascade,\n FOREIGN KEY (`evidence_id`) REFERENCES `outcome_evidence`(`evidence_id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_attribution_assessment_evidence_evidence` ON `attribution_assessment_evidence` (`evidence_id`,`assessment_id`);\nCREATE TABLE IF NOT EXISTS `raw_events` (\n `id` integer PRIMARY KEY NOT NULL,\n `source` text DEFAULT 'opencode' NOT NULL,\n `stream_id` text DEFAULT '' NOT NULL,\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 `capture_context_json` text,\n `created_at` text NOT NULL\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_raw_events_source_stream_seq` ON `raw_events` (`source`,`stream_id`,`event_seq`);\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_raw_events_source_stream_event_id` ON `raw_events` (`source`,`stream_id`,`event_id`);\nCREATE INDEX IF NOT EXISTS `idx_raw_events_session_seq` ON `raw_events` (`opencode_session_id`,`event_seq`);\nCREATE INDEX IF NOT EXISTS `idx_raw_events_created` ON `raw_events` (`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_raw_events_capture_context` ON `raw_events` (`source`,`stream_id`,`event_seq`) WHERE \"raw_events\".\"capture_context_json\" IS NOT NULL;\nCREATE TABLE IF NOT EXISTS `raw_event_sessions` (\n `source` text DEFAULT 'opencode' NOT NULL,\n `stream_id` text DEFAULT '' NOT NULL,\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 DEFAULT -1 NOT NULL,\n `last_flushed_event_seq` integer DEFAULT -1 NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`source`, `stream_id`)\n);\n\nCREATE INDEX IF NOT EXISTS `idx_raw_event_sessions_pending_updated` ON `raw_event_sessions` (`updated_at`) WHERE \"raw_event_sessions\".\"last_received_event_seq\" > \"raw_event_sessions\".\"last_flushed_event_seq\";\nCREATE TABLE IF NOT EXISTS `opencode_sessions` (\n `source` text DEFAULT 'opencode' NOT NULL,\n `stream_id` text DEFAULT '' NOT NULL,\n `opencode_session_id` text NOT NULL,\n `session_id` integer,\n `created_at` text NOT NULL,\n PRIMARY KEY(`source`, `stream_id`),\n FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_opencode_sessions_session` ON `opencode_sessions` (`session_id`);\nCREATE TABLE IF NOT EXISTS `pi_import_state` (\n `file_path` text PRIMARY KEY NOT NULL,\n `size_bytes` integer NOT NULL,\n `mtime_ms` real NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `raw_event_flush_batches` (\n `id` integer PRIMARY KEY NOT NULL,\n `source` text DEFAULT 'opencode' NOT NULL,\n `stream_id` text DEFAULT '' NOT NULL,\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 `observer_auth_source` text,\n `observer_auth_type` text,\n `observer_error_code` text,\n `observer_error_message` text,\n `attempt_count` integer DEFAULT 0 NOT NULL,\n `claim_generation` integer DEFAULT 0 NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_flush_batches_source_stream_seq_ver` ON `raw_event_flush_batches` (`source`,`stream_id`,`start_event_seq`,`end_event_seq`,`extractor_version`);\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_session_created` ON `raw_event_flush_batches` (`opencode_session_id`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_status_updated` ON `raw_event_flush_batches` (`status`,`updated_at`);\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_observer_status_updated` ON `raw_event_flush_batches` (`status`,`updated_at`) WHERE \"raw_event_flush_batches\".\"observer_provider\" IS NOT NULL;\nCREATE INDEX IF NOT EXISTS `idx_flush_batches_capture_status_updated` ON `raw_event_flush_batches` (`status`,`updated_at`) WHERE \"raw_event_flush_batches\".\"observer_provider\" IS NULL;\nCREATE TABLE IF NOT EXISTS `user_prompts` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer,\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 FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_session` ON `user_prompts` (`session_id`);\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_project` ON `user_prompts` (`project`);\nCREATE INDEX IF NOT EXISTS `idx_user_prompts_epoch` ON `user_prompts` (`created_at_epoch`);\nCREATE TABLE IF NOT EXISTS `session_summaries` (\n `id` integer PRIMARY KEY NOT NULL,\n `session_id` integer,\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 FOREIGN KEY (`session_id`) REFERENCES `sessions`(`id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_session` ON `session_summaries` (`session_id`);\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_project` ON `session_summaries` (`project`);\nCREATE INDEX IF NOT EXISTS `idx_session_summaries_epoch` ON `session_summaries` (`created_at_epoch`);\nCREATE TABLE IF NOT EXISTS `replication_ops` (\n `op_id` text PRIMARY KEY NOT NULL,\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 `scope_id` text\n);\n\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_created` ON `replication_ops` (`created_at`,`op_id`);\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_entity` ON `replication_ops` (`entity_type`,`entity_id`);\nCREATE INDEX IF NOT EXISTS `idx_replication_ops_scope_created` ON `replication_ops` (`scope_id`,`created_at`,`op_id`);\nCREATE TABLE IF NOT EXISTS `replication_cursors` (\n `peer_device_id` text PRIMARY KEY NOT NULL,\n `last_applied_cursor` text,\n `last_acked_cursor` text,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `replication_cursors_v2` (\n `peer_device_id` text NOT NULL,\n `scope_id` text NOT NULL,\n `last_applied_cursor` text,\n `last_acked_cursor` text,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`peer_device_id`, `scope_id`)\n);\n\nCREATE INDEX IF NOT EXISTS `idx_replication_cursors_v2_scope` ON `replication_cursors_v2` (`scope_id`);\nCREATE TABLE IF NOT EXISTS `sync_peers` (\n `peer_device_id` text PRIMARY KEY NOT NULL,\n `name` text,\n `pinned_fingerprint` text,\n `public_key` text,\n `addresses_json` text,\n `manual_addresses_json` text,\n `last_success_address` text,\n `claimed_local_actor` integer DEFAULT 0 NOT NULL,\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 `runtime_version` text,\n `runtime_version_observed_at` text,\n `sync_features_json` text,\n `sync_features_observed_at` text,\n `relay_retry_after` text,\n `relay_rejections` integer DEFAULT 0 NOT NULL,\n `highest_observed_direct_signature_version` integer,\n `discovered_via_coordinator_id` text,\n `discovered_via_group_id` text,\n `trust_provenance` text,\n `pending_bootstrap_grant_id` text\n);\n\nCREATE TABLE IF NOT EXISTS `sync_nonces` (\n `nonce` text PRIMARY KEY NOT NULL,\n `device_id` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `sync_device` (\n `device_id` text PRIMARY KEY NOT NULL,\n `public_key` text NOT NULL,\n `fingerprint` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `sync_attempts` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\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 `local_sync_capability` text,\n `peer_sync_capability` text,\n `negotiated_sync_capability` text,\n `failure_category` text,\n `transport` text\n);\n\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_peer_started` ON `sync_attempts` (`peer_device_id`,`started_at`);\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_occurred` ON `sync_attempts` (CASE WHEN \"finished_at\" IS NULL THEN \"started_at\" ELSE \"finished_at\" END,`id`);\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_error_occurred` ON `sync_attempts` (CASE WHEN \"finished_at\" IS NULL THEN \"started_at\" ELSE \"finished_at\" END,`id`) WHERE \"sync_attempts\".\"ok\" = 0;\nCREATE INDEX IF NOT EXISTS `idx_sync_attempts_success_occurred` ON `sync_attempts` (CASE WHEN \"finished_at\" IS NULL THEN \"started_at\" ELSE \"finished_at\" END,`id`) WHERE \"sync_attempts\".\"ok\" <> 0;\nCREATE TABLE IF NOT EXISTS `sync_scope_rejections` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `peer_device_id` text,\n `op_id` text NOT NULL,\n `entity_type` text NOT NULL,\n `entity_id` text NOT NULL,\n `scope_id` text,\n `reason` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS `idx_sync_scope_rejections_peer_created` ON `sync_scope_rejections` (`peer_device_id`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_sync_scope_rejections_scope_created` ON `sync_scope_rejections` (`scope_id`,`created_at`);\nCREATE TABLE IF NOT EXISTS `sync_daemon_state` (\n `id` integer PRIMARY KEY NOT NULL,\n `last_error` text,\n `last_traceback` text,\n `last_error_at` text,\n `last_ok_at` text,\n `phase` text\n);\n\nCREATE TABLE IF NOT EXISTS `sync_reset_state` (\n `id` integer PRIMARY KEY NOT NULL,\n `generation` integer NOT NULL,\n `snapshot_id` text NOT NULL,\n `baseline_cursor` text,\n `retained_floor_cursor` text,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `sync_reset_state_v2` (\n `scope_id` text PRIMARY KEY NOT NULL,\n `generation` integer NOT NULL,\n `snapshot_id` text NOT NULL,\n `baseline_cursor` text,\n `retained_floor_cursor` text,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `sync_retention_state_v2` (\n `scope_id` text PRIMARY KEY NOT NULL,\n `last_run_at` text,\n `last_duration_ms` integer,\n `last_deleted_ops` integer DEFAULT 0 NOT NULL,\n `last_estimated_bytes_before` integer,\n `last_estimated_bytes_after` integer,\n `retained_floor_cursor` text,\n `last_error` text,\n `last_error_at` text\n);\n\nCREATE TABLE IF NOT EXISTS `raw_event_ingest_samples` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `created_at` text NOT NULL,\n `inserted_events` integer DEFAULT 0 NOT NULL,\n `skipped_invalid` integer DEFAULT 0 NOT NULL,\n `skipped_duplicate` integer DEFAULT 0 NOT NULL,\n `skipped_conflict` integer DEFAULT 0 NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `raw_event_ingest_stats` (\n `id` integer PRIMARY KEY NOT NULL,\n `inserted_events` integer DEFAULT 0 NOT NULL,\n `skipped_events` integer DEFAULT 0 NOT NULL,\n `skipped_invalid` integer DEFAULT 0 NOT NULL,\n `skipped_duplicate` integer DEFAULT 0 NOT NULL,\n `skipped_conflict` integer DEFAULT 0 NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `coordinator_group_preferences` (\n `coordinator_id` text NOT NULL,\n `group_id` text NOT NULL,\n `projects_include_json` text,\n `projects_exclude_json` text,\n `auto_seed_scope` integer DEFAULT 1 NOT NULL,\n `default_space_scope_id` text,\n `auto_grant_default_space_on_join` integer DEFAULT 0 NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`coordinator_id`, `group_id`)\n);\n\nCREATE TABLE IF NOT EXISTS `actors` (\n `actor_id` text PRIMARY KEY NOT NULL,\n `display_name` text NOT NULL,\n `is_local` integer DEFAULT 0 NOT NULL,\n `status` text DEFAULT 'active' NOT NULL,\n `merged_into_actor_id` text,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS `idx_actors_is_local` ON `actors` (`is_local`);\nCREATE INDEX IF NOT EXISTS `idx_actors_status` ON `actors` (`status`);\nCREATE TABLE IF NOT EXISTS `recipient_policy_review_resolutions` (\n `review_item_id` text NOT NULL,\n `source_fingerprint` text NOT NULL,\n `decision` text NOT NULL,\n `decision_input_json` text NOT NULL,\n `preview_json` text NOT NULL,\n `decided_by_identity_id` text NOT NULL,\n `decided_by_device_id` text NOT NULL,\n `resolved_at` text NOT NULL,\n PRIMARY KEY(`review_item_id`, `source_fingerprint`)\n);\n\nCREATE TABLE IF NOT EXISTS `coordinator_enrollment_reconciliation_issues` (\n `coordinator_id` text NOT NULL,\n `group_id` text NOT NULL,\n `kind` text NOT NULL,\n `reference_id` text NOT NULL,\n `code` text NOT NULL,\n `status` text DEFAULT 'open' NOT NULL,\n `first_seen_at` text NOT NULL,\n `last_seen_at` text NOT NULL,\n `resolved_at` text,\n `occurrence_count` integer DEFAULT 1 NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`coordinator_id`, `group_id`, `kind`, `reference_id`, `code`)\n);\n\nCREATE INDEX IF NOT EXISTS `idx_coordinator_enrollment_issues_boundary_status` ON `coordinator_enrollment_reconciliation_issues` (`coordinator_id`,`group_id`,`status`);\nCREATE INDEX IF NOT EXISTS `idx_coordinator_enrollment_issues_status_recent` ON `coordinator_enrollment_reconciliation_issues` (`status`,`last_seen_at`,`resolved_at`);\nCREATE TABLE IF NOT EXISTS `policy_teams` (\n `team_id` text PRIMARY KEY NOT NULL,\n `display_name` text NOT NULL,\n `status` text NOT NULL,\n `device_eligibility_mode` text DEFAULT 'person_all_devices' NOT NULL,\n `provenance` text NOT NULL,\n `revision` text NOT NULL,\n `migration_state` text NOT NULL,\n `source_fingerprint` text,\n `idempotency_key` text NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `policy_teams_idempotency_key_unique` ON `policy_teams` (`idempotency_key`);\nCREATE TABLE IF NOT EXISTS `policy_team_memberships` (\n `team_id` text NOT NULL,\n `identity_id` text NOT NULL,\n `role` text NOT NULL,\n `status` text NOT NULL,\n `provenance` text NOT NULL,\n `revision` text NOT NULL,\n `migration_state` text NOT NULL,\n `source_fingerprint` text,\n `idempotency_key` text NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`team_id`, `identity_id`)\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `policy_team_memberships_idempotency_key_unique` ON `policy_team_memberships` (`idempotency_key`);\nCREATE INDEX IF NOT EXISTS `idx_policy_team_memberships_identity_status` ON `policy_team_memberships` (`identity_id`,`status`);\nCREATE TABLE IF NOT EXISTS `policy_team_device_decisions` (\n `team_id` text NOT NULL,\n `device_id` text NOT NULL,\n `decision` text NOT NULL,\n `assignment_version` integer DEFAULT 0 NOT NULL,\n `provenance` text NOT NULL,\n `revision` text NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`team_id`, `device_id`),\n FOREIGN KEY (`team_id`) REFERENCES `policy_teams`(`team_id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_policy_team_device_decisions_device` ON `policy_team_device_decisions` (`device_id`);\nCREATE TABLE IF NOT EXISTS `identity_devices` (\n `device_id` text PRIMARY KEY NOT NULL,\n `identity_id` text NOT NULL,\n `display_name` text NOT NULL,\n `status` text NOT NULL,\n `provenance` text NOT NULL,\n `revision` text NOT NULL,\n `migration_state` text NOT NULL,\n `assignment_version` integer DEFAULT 0 NOT NULL,\n `source_fingerprint` text,\n `idempotency_key` text NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `identity_devices_idempotency_key_unique` ON `identity_devices` (`idempotency_key`);\nCREATE INDEX IF NOT EXISTS `idx_identity_devices_identity_status` ON `identity_devices` (`identity_id`,`status`);\nCREATE TABLE IF NOT EXISTS `project_recipients` (\n `canonical_project_identity` text NOT NULL,\n `recipient_kind` text NOT NULL,\n `recipient_id` text NOT NULL,\n `status` text NOT NULL,\n `provenance` text NOT NULL,\n `policy_revision` text NOT NULL,\n `migration_state` text NOT NULL,\n `source_fingerprint` text,\n `idempotency_key` text NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`canonical_project_identity`, `recipient_kind`, `recipient_id`)\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `project_recipients_idempotency_key_unique` ON `project_recipients` (`idempotency_key`);\nCREATE INDEX IF NOT EXISTS `idx_project_recipients_project_status` ON `project_recipients` (`canonical_project_identity`,`status`);\nCREATE INDEX IF NOT EXISTS `idx_project_recipients_recipient_status` ON `project_recipients` (`recipient_kind`,`recipient_id`,`status`);\nCREATE TABLE IF NOT EXISTS `legacy_team_setup_drafts` (\n `attempt_id` text PRIMARY KEY NOT NULL,\n `candidate_id` text NOT NULL,\n `coordinator_id` text NOT NULL,\n `group_id` text NOT NULL,\n `state` text DEFAULT 'needs_setup' NOT NULL,\n `display_name` text NOT NULL,\n `roster_fingerprint` text NOT NULL,\n `projection_fingerprint` text NOT NULL,\n `finish_digest` text,\n `safe_error_code` text,\n `completed_team_id` text,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL,\n `completed_at` text,\n `superseded_at` text\n);\n\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_drafts_candidate_state` ON `legacy_team_setup_drafts` (`candidate_id`,`state`,`created_at`);\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_drafts_state_updated` ON `legacy_team_setup_drafts` (`state`,`updated_at`);\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_drafts_finish_digest` ON `legacy_team_setup_drafts` (`finish_digest`);\nCREATE TABLE IF NOT EXISTS `legacy_team_setup_completions` (\n `attempt_id` text NOT NULL,\n `finish_digest` text NOT NULL,\n `candidate_ref` text NOT NULL,\n `confirmed_access_delta_digest` text NOT NULL,\n `completed_team_id` text NOT NULL,\n `response_json` text NOT NULL,\n `completed_at` text NOT NULL,\n `created_at` text NOT NULL\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_legacy_team_setup_completions_attempt_finish` ON `legacy_team_setup_completions` (`attempt_id`,`finish_digest`);\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_completions_exact_replay` ON `legacy_team_setup_completions` (`candidate_ref`,`attempt_id`,`finish_digest`,`confirmed_access_delta_digest`);\nCREATE TABLE IF NOT EXISTS `legacy_team_setup_draft_devices` (\n `attempt_id` text NOT NULL,\n `device_id` text NOT NULL,\n `device_ref` text NOT NULL,\n `key_fingerprint` text NOT NULL,\n `display_name` text NOT NULL,\n `enabled` integer NOT NULL,\n `existing_identity_id` text,\n `existing_assignment_version` integer,\n `verified_evidence_kind` text,\n `identity_evidence` text,\n `decision` text DEFAULT 'unresolved' NOT NULL,\n `target_identity_id` text,\n `expected_assignment_kind` text,\n `expected_assignment_version` integer,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`attempt_id`, `device_id`),\n FOREIGN KEY (`attempt_id`) REFERENCES `legacy_team_setup_drafts`(`attempt_id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_legacy_team_setup_devices_attempt_ref` ON `legacy_team_setup_draft_devices` (`attempt_id`,`device_ref`);\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_devices_attempt_decision` ON `legacy_team_setup_draft_devices` (`attempt_id`,`decision`);\nCREATE TABLE IF NOT EXISTS `legacy_team_setup_draft_projects` (\n `attempt_id` text NOT NULL,\n `project_ref` text NOT NULL,\n `source_project_identity` text NOT NULL,\n `display_name` text NOT NULL,\n `source_fingerprint` text NOT NULL,\n `resolution_kind` text DEFAULT 'unresolved' NOT NULL,\n `resolved_project_identity` text,\n `target_scope_id` text,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`attempt_id`, `project_ref`),\n FOREIGN KEY (`attempt_id`) REFERENCES `legacy_team_setup_drafts`(`attempt_id`) ON UPDATE no action ON DELETE cascade\n);\n\nCREATE INDEX IF NOT EXISTS `idx_legacy_team_setup_projects_attempt_resolution` ON `legacy_team_setup_draft_projects` (`attempt_id`,`resolution_kind`);\nCREATE TABLE IF NOT EXISTS `recipient_managed_project_projections` (\n `canonical_project_identity` text NOT NULL,\n `display_name` text NOT NULL,\n `managed_scope_id` text NOT NULL,\n `coordinator_id` text NOT NULL,\n `group_id` text NOT NULL,\n `recipient_identity_id` text NOT NULL,\n `accepting_device_id` text NOT NULL,\n `source_operation_id` text NOT NULL,\n `reviewed_project_set_digest` text NOT NULL,\n `status` text DEFAULT 'active' NOT NULL,\n `accepted_at` text NOT NULL,\n `revoked_at` text,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`source_operation_id`, `canonical_project_identity`)\n);\n\nCREATE INDEX IF NOT EXISTS `idx_recipient_managed_projects_identity_status` ON `recipient_managed_project_projections` (`recipient_identity_id`,`status`);\nCREATE INDEX IF NOT EXISTS `idx_recipient_managed_projects_scope_authority` ON `recipient_managed_project_projections` (`managed_scope_id`,`coordinator_id`,`group_id`,`status`);\nCREATE TABLE IF NOT EXISTS `recipient_policy_authority_states` (\n `canonical_project_identity` text PRIMARY KEY NOT NULL,\n `authority_state` text DEFAULT 'legacy' NOT NULL,\n `generation` integer DEFAULT 0 NOT NULL,\n `desired_devices_digest` text,\n `current_devices_digest` text,\n `stable_parity_evidence_digest` text,\n `stable_parity_passed_at` text,\n `fresh_snapshot_fingerprint` text,\n `fresh_snapshot_observed_at` text,\n `safe_error_code` text,\n `state_changed_at` text NOT NULL,\n `last_error_at` text,\n `attempt_count` integer DEFAULT 0 NOT NULL,\n `last_attempt_at` text,\n `wake_epoch` integer DEFAULT 0 NOT NULL,\n `last_completed_at` text,\n `lease_owner` text,\n `lease_acquired_at` text,\n `lease_expires_at` text,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS `recipient_policy_reconciliation_steps` (\n `canonical_project_identity` text NOT NULL,\n `generation` integer NOT NULL,\n `step_key` text NOT NULL,\n `effect_id` text NOT NULL,\n `payload_digest` text NOT NULL,\n `status` text DEFAULT 'pending' NOT NULL,\n `attempt_count` integer DEFAULT 0 NOT NULL,\n `started_at` text,\n `completed_at` text,\n `last_attempt_at` text,\n `safe_error_code` text,\n `error_at` text,\n `lease_owner` text,\n `lease_acquired_at` text,\n `lease_expires_at` text,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`canonical_project_identity`, `generation`, `step_key`)\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS `idx_recipient_policy_reconciliation_steps_effect` ON `recipient_policy_reconciliation_steps` (`effect_id`);\nCREATE INDEX IF NOT EXISTS `idx_recipient_policy_reconciliation_steps_status` ON `recipient_policy_reconciliation_steps` (`canonical_project_identity`,`status`);\nCREATE INDEX IF NOT EXISTS `idx_recipient_policy_reconciliation_steps_pending_refresh` ON `recipient_policy_reconciliation_steps` (`canonical_project_identity`,`generation`,`step_key`) WHERE \"recipient_policy_reconciliation_steps\".\"status\" IN ('pending', 'running', 'failed') AND \"recipient_policy_reconciliation_steps\".\"step_key\" GLOB 'refresh-after-revocations-v2:*';\nCREATE TABLE IF NOT EXISTS `recipient_policy_deny_overlays` (\n `canonical_project_identity` text NOT NULL,\n `scope_id` text NOT NULL,\n `device_id` text NOT NULL,\n `generation` integer NOT NULL,\n `reason_code` text NOT NULL,\n `created_at` text NOT NULL,\n `updated_at` text NOT NULL,\n PRIMARY KEY(`canonical_project_identity`, `scope_id`, `device_id`)\n);\n\nCREATE INDEX IF NOT EXISTS `idx_recipient_policy_deny_overlays_scope_device` ON `recipient_policy_deny_overlays` (`scope_id`,`device_id`);", Jn = "idx_usage_events_public_aggregate_cover";
|
|
1408
|
+
function Yn(e) {
|
|
1409
|
+
if (!e.readonly) try {
|
|
1410
|
+
if (e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = ?").get(Jn)) return;
|
|
1411
|
+
e.exec("CREATE INDEX IF NOT EXISTS idx_usage_events_public_aggregate_cover\n ON usage_events (\n event,\n CASE WHEN json_valid(metadata_json)\n THEN json_extract(metadata_json, '$.token_usage.source') ELSE NULL END,\n tokens_read, tokens_written, tokens_saved, session_id\n )\n WHERE event != 'observer_recovery_scope_denial'\n AND event NOT GLOB 'observer_recovery_call_clock:*'");
|
|
1412
|
+
} catch {}
|
|
1413
|
+
}
|
|
1414
|
+
//#endregion
|
|
1415
|
+
//#region src/vector-corpus-epoch.ts
|
|
1416
|
+
var Xn = [
|
|
1417
|
+
[
|
|
1418
|
+
"insert",
|
|
1419
|
+
"AFTER INSERT",
|
|
1420
|
+
""
|
|
1421
|
+
],
|
|
1422
|
+
[
|
|
1423
|
+
"delete",
|
|
1424
|
+
"AFTER DELETE",
|
|
1425
|
+
""
|
|
1426
|
+
],
|
|
1427
|
+
[
|
|
1428
|
+
"update",
|
|
1429
|
+
"AFTER UPDATE",
|
|
1430
|
+
"WHEN OLD.id IS NOT NEW.id OR OLD.title IS NOT NEW.title OR OLD.body_text IS NOT NEW.body_text OR OLD.active IS NOT NEW.active"
|
|
1431
|
+
]
|
|
1432
|
+
].map(([e, t, n]) => ({
|
|
1433
|
+
name: `vector_corpus_epoch_${e}`,
|
|
1434
|
+
sql: `CREATE TRIGGER vector_corpus_epoch_${e} ${t} ON memory_items ${n}
|
|
1435
|
+
BEGIN UPDATE vector_corpus_epoch SET epoch = epoch + 1 WHERE id = 1; END`
|
|
1436
|
+
}));
|
|
1437
|
+
function Zn(e) {
|
|
1438
|
+
let t = e.prepare("SELECT sql FROM sqlite_schema WHERE type = 'trigger' AND name = ?");
|
|
1439
|
+
return Xn.every(({ name: e, sql: n }) => t.get(e)?.sql === n);
|
|
1440
|
+
}
|
|
1441
|
+
function Qn(e) {
|
|
1442
|
+
if (!e.readonly) try {
|
|
1443
|
+
$n(e);
|
|
1444
|
+
} catch {}
|
|
1445
|
+
}
|
|
1446
|
+
function $n(e) {
|
|
1447
|
+
let t = e.prepare("PRAGMA table_info(memory_items)").all();
|
|
1448
|
+
[
|
|
1449
|
+
"id",
|
|
1450
|
+
"title",
|
|
1451
|
+
"body_text",
|
|
1452
|
+
"active"
|
|
1453
|
+
].every((e) => t.some((t) => t.name === e)) && er(e).epoch === null && e.transaction(() => {
|
|
1454
|
+
if (e.exec("CREATE TABLE IF NOT EXISTS vector_corpus_epoch (id INTEGER PRIMARY KEY CHECK (id = 1), epoch INTEGER NOT NULL CHECK (typeof(epoch) = 'integer' AND epoch >= 0))"), !(!e.prepare("INSERT OR IGNORE INTO vector_corpus_epoch VALUES (1, 0)").run().changes && Zn(e))) {
|
|
1455
|
+
for (let { name: t, sql: n } of Xn) e.exec(`DROP TRIGGER IF EXISTS ${t}`), e.exec(n);
|
|
1456
|
+
e.exec("UPDATE vector_corpus_epoch SET epoch = epoch + 1 WHERE id = 1");
|
|
1457
|
+
}
|
|
1458
|
+
}).immediate();
|
|
1459
|
+
}
|
|
1460
|
+
function er(e) {
|
|
1461
|
+
let t = Number(e.pragma("schema_version", { simple: !0 }));
|
|
1462
|
+
try {
|
|
1463
|
+
return Zn(e) ? {
|
|
1464
|
+
schemaVersion: t,
|
|
1465
|
+
epoch: e.prepare("SELECT CAST(epoch AS TEXT) AS epoch FROM vector_corpus_epoch WHERE id = 1 AND typeof(epoch) = 'integer' AND epoch >= 0").get()?.epoch ?? null
|
|
1466
|
+
} : {
|
|
1467
|
+
schemaVersion: t,
|
|
1468
|
+
epoch: null
|
|
1469
|
+
};
|
|
1470
|
+
} catch {
|
|
1471
|
+
return {
|
|
1472
|
+
schemaVersion: t,
|
|
1473
|
+
epoch: null
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
}
|
|
1477
|
+
//#endregion
|
|
1478
|
+
//#region src/schema-bootstrap.ts
|
|
1479
|
+
function tr(e) {
|
|
1480
|
+
if (!(e.readonly || !U(e, "memory_items")) && !e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'idx_memory_items_scope_aggregates'").get() && !(!W(e, "memory_items", "scope_id") || !W(e, "memory_items", "project"))) try {
|
|
1481
|
+
e.exec(`CREATE INDEX IF NOT EXISTS idx_memory_items_scope_aggregates
|
|
1482
|
+
ON memory_items(scope_id, active, session_id, TRIM(tags_text) != '',
|
|
1483
|
+
${Bn("")}, project)`);
|
|
1484
|
+
} catch {}
|
|
1485
|
+
}
|
|
1486
|
+
var nr = "\nCREATE TRIGGER IF NOT EXISTS trg_retrieval_exposures_detach_unavailable_memory\nAFTER INSERT ON retrieval_exposures\nWHEN NEW.memory_id IS NOT NULL AND NOT EXISTS (\n SELECT 1 FROM memory_items\n WHERE memory_items.id = NEW.memory_id\n AND memory_items.active != 0\n AND memory_items.deleted_at IS NULL\n AND (\n (\n NEW.memory_import_key IS NOT NULL\n AND TRIM(NEW.memory_import_key) != ''\n AND import_key IS NOT NULL\n AND TRIM(import_key) != ''\n AND NEW.memory_import_key = import_key\n AND (\n NEW.origin_device_id IS NULL\n OR TRIM(NEW.origin_device_id) = ''\n OR (\n origin_device_id IS NOT NULL\n AND TRIM(origin_device_id) != ''\n AND NEW.origin_device_id = origin_device_id\n )\n )\n )\n OR (\n (NEW.memory_import_key IS NULL OR TRIM(NEW.memory_import_key) = '')\n AND NEW.memory_rev = rev\n AND julianday(NEW.memory_updated_at) IS NOT NULL\n AND julianday(updated_at) IS NOT NULL\n AND julianday(NEW.memory_updated_at) = julianday(updated_at)\n AND NEW.memory_scope_id IS scope_id\n AND NEW.memory_kind = kind\n AND NEW.memory_active = active\n AND NEW.memory_deleted_at IS deleted_at\n )\n )\n)\nBEGIN\n UPDATE retrieval_exposures SET memory_id = NULL WHERE exposure_id = NEW.exposure_id;\nEND;\n", rr = `
|
|
1487
|
+
CREATE TABLE IF NOT EXISTS retrieval_attempts (
|
|
1488
|
+
attempt_id TEXT PRIMARY KEY NOT NULL,
|
|
1489
|
+
contract_version INTEGER NOT NULL,
|
|
1490
|
+
surface TEXT NOT NULL,
|
|
1491
|
+
trigger TEXT NOT NULL,
|
|
1492
|
+
started_at TEXT NOT NULL,
|
|
1493
|
+
completed_at TEXT,
|
|
1494
|
+
retrieval_status TEXT NOT NULL,
|
|
1495
|
+
delivery_status TEXT NOT NULL,
|
|
1496
|
+
candidate_count INTEGER NOT NULL,
|
|
1497
|
+
selected_count INTEGER NOT NULL,
|
|
1498
|
+
persisted_candidate_count INTEGER NOT NULL,
|
|
1499
|
+
recorder_version TEXT NOT NULL,
|
|
1500
|
+
session_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,
|
|
1501
|
+
source TEXT,
|
|
1502
|
+
stream_id TEXT,
|
|
1503
|
+
source_session_id TEXT,
|
|
1504
|
+
prompt_number INTEGER,
|
|
1505
|
+
request_id TEXT,
|
|
1506
|
+
raw_event_start_seq INTEGER,
|
|
1507
|
+
raw_event_end_seq INTEGER,
|
|
1508
|
+
experiment_id TEXT,
|
|
1509
|
+
experiment_cell_id TEXT,
|
|
1510
|
+
evaluation_checkout_id TEXT,
|
|
1511
|
+
evaluation_fixture_id TEXT,
|
|
1512
|
+
evaluation_seed INTEGER,
|
|
1513
|
+
latency_ms INTEGER,
|
|
1514
|
+
project TEXT,
|
|
1515
|
+
scope_id TEXT,
|
|
1516
|
+
mode TEXT,
|
|
1517
|
+
limit_requested INTEGER,
|
|
1518
|
+
token_budget INTEGER,
|
|
1519
|
+
output_tokens INTEGER,
|
|
1520
|
+
working_set_file_count INTEGER,
|
|
1521
|
+
working_set_files_json TEXT,
|
|
1522
|
+
query_hash_sha256 TEXT,
|
|
1523
|
+
query_char_count INTEGER,
|
|
1524
|
+
query_token_estimate INTEGER,
|
|
1525
|
+
filter_summary_json TEXT,
|
|
1526
|
+
failure_code TEXT,
|
|
1527
|
+
failure_stage TEXT,
|
|
1528
|
+
trace_version INTEGER,
|
|
1529
|
+
automatic_recall_json TEXT,
|
|
1530
|
+
automatic_recall_key TEXT,
|
|
1531
|
+
retention_until TEXT,
|
|
1532
|
+
retention_pinned INTEGER NOT NULL DEFAULT 0,
|
|
1533
|
+
retention_finalized_at TEXT
|
|
1534
|
+
);
|
|
1535
|
+
|
|
1536
|
+
CREATE INDEX IF NOT EXISTS idx_retrieval_attempts_session_started
|
|
1537
|
+
ON retrieval_attempts(session_id, started_at);
|
|
1538
|
+
CREATE INDEX IF NOT EXISTS idx_retrieval_attempts_source_stream_started
|
|
1539
|
+
ON retrieval_attempts(source, stream_id, started_at);
|
|
1540
|
+
CREATE INDEX IF NOT EXISTS idx_retrieval_attempts_retention
|
|
1541
|
+
ON retrieval_attempts(retention_pinned, retention_until);
|
|
1542
|
+
CREATE INDEX IF NOT EXISTS idx_retrieval_attempts_started
|
|
1543
|
+
ON retrieval_attempts(started_at, attempt_id);
|
|
1544
|
+
CREATE INDEX IF NOT EXISTS idx_retrieval_attempts_surface_started
|
|
1545
|
+
ON retrieval_attempts(surface, started_at);
|
|
1546
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_retrieval_attempts_request_identity
|
|
1547
|
+
ON retrieval_attempts(source, surface, request_id) WHERE request_id IS NOT NULL;
|
|
1548
|
+
CREATE INDEX IF NOT EXISTS idx_retrieval_attempts_experiment_cell
|
|
1549
|
+
ON retrieval_attempts(experiment_id, experiment_cell_id);
|
|
1550
|
+
|
|
1551
|
+
CREATE TABLE IF NOT EXISTS retrieval_exposures (
|
|
1552
|
+
exposure_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
|
|
1553
|
+
attempt_id TEXT NOT NULL REFERENCES retrieval_attempts(attempt_id) ON DELETE CASCADE,
|
|
1554
|
+
memory_id INTEGER REFERENCES memory_items(id) ON DELETE SET NULL,
|
|
1555
|
+
memory_import_key TEXT,
|
|
1556
|
+
origin_device_id TEXT,
|
|
1557
|
+
rank INTEGER NOT NULL,
|
|
1558
|
+
disposition TEXT NOT NULL,
|
|
1559
|
+
section TEXT,
|
|
1560
|
+
handoff_status TEXT NOT NULL,
|
|
1561
|
+
memory_rev INTEGER,
|
|
1562
|
+
memory_updated_at TEXT,
|
|
1563
|
+
memory_scope_id TEXT,
|
|
1564
|
+
memory_kind TEXT,
|
|
1565
|
+
memory_active INTEGER,
|
|
1566
|
+
memory_deleted_at TEXT,
|
|
1567
|
+
score_summary_json TEXT,
|
|
1568
|
+
reason_codes_json TEXT
|
|
1569
|
+
);
|
|
1570
|
+
|
|
1571
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_retrieval_exposures_attempt_rank
|
|
1572
|
+
ON retrieval_exposures(attempt_id, rank);
|
|
1573
|
+
CREATE INDEX IF NOT EXISTS idx_retrieval_exposures_memory
|
|
1574
|
+
ON retrieval_exposures(memory_id);
|
|
1575
|
+
|
|
1576
|
+
CREATE TABLE IF NOT EXISTS outcome_evidence (
|
|
1577
|
+
evidence_id TEXT PRIMARY KEY NOT NULL,
|
|
1578
|
+
contract_version INTEGER NOT NULL,
|
|
1579
|
+
dimension TEXT NOT NULL,
|
|
1580
|
+
evidence_type TEXT NOT NULL,
|
|
1581
|
+
source_class TEXT NOT NULL,
|
|
1582
|
+
observed_at TEXT NOT NULL,
|
|
1583
|
+
producer TEXT NOT NULL,
|
|
1584
|
+
producer_version TEXT NOT NULL,
|
|
1585
|
+
status TEXT NOT NULL,
|
|
1586
|
+
value_type TEXT,
|
|
1587
|
+
value_integer INTEGER,
|
|
1588
|
+
value_real REAL,
|
|
1589
|
+
value_unit TEXT,
|
|
1590
|
+
session_id INTEGER REFERENCES sessions(id) ON DELETE CASCADE,
|
|
1591
|
+
source TEXT,
|
|
1592
|
+
stream_id TEXT,
|
|
1593
|
+
source_session_id TEXT,
|
|
1594
|
+
prompt_number INTEGER,
|
|
1595
|
+
raw_event_start_seq INTEGER,
|
|
1596
|
+
raw_event_end_seq INTEGER,
|
|
1597
|
+
experiment_id TEXT,
|
|
1598
|
+
experiment_cell_id TEXT,
|
|
1599
|
+
window_start_at TEXT,
|
|
1600
|
+
window_end_at TEXT,
|
|
1601
|
+
references_json TEXT,
|
|
1602
|
+
retention_until TEXT,
|
|
1603
|
+
retention_pinned INTEGER NOT NULL DEFAULT 0,
|
|
1604
|
+
retention_finalized_at TEXT
|
|
1605
|
+
);
|
|
1606
|
+
|
|
1607
|
+
CREATE INDEX IF NOT EXISTS idx_outcome_evidence_observed_id
|
|
1608
|
+
ON outcome_evidence(observed_at, evidence_id);
|
|
1609
|
+
CREATE INDEX IF NOT EXISTS idx_outcome_evidence_session_observed
|
|
1610
|
+
ON outcome_evidence(session_id, observed_at);
|
|
1611
|
+
CREATE INDEX IF NOT EXISTS idx_outcome_evidence_source_stream_observed
|
|
1612
|
+
ON outcome_evidence(source, stream_id, observed_at);
|
|
1613
|
+
CREATE INDEX IF NOT EXISTS idx_outcome_evidence_type_observed
|
|
1614
|
+
ON outcome_evidence(evidence_type, observed_at);
|
|
1615
|
+
CREATE INDEX IF NOT EXISTS idx_outcome_evidence_retention
|
|
1616
|
+
ON outcome_evidence(retention_pinned, retention_until);
|
|
1617
|
+
|
|
1618
|
+
CREATE TABLE IF NOT EXISTS attribution_assessments (
|
|
1619
|
+
assessment_id TEXT PRIMARY KEY NOT NULL,
|
|
1620
|
+
contract_version INTEGER NOT NULL,
|
|
1621
|
+
subject_type TEXT NOT NULL,
|
|
1622
|
+
attempt_id TEXT NOT NULL REFERENCES retrieval_attempts(attempt_id) ON DELETE CASCADE,
|
|
1623
|
+
exposure_id INTEGER REFERENCES retrieval_exposures(exposure_id) ON DELETE CASCADE,
|
|
1624
|
+
dimension TEXT NOT NULL,
|
|
1625
|
+
impact_label TEXT NOT NULL,
|
|
1626
|
+
basis TEXT NOT NULL,
|
|
1627
|
+
confidence_level TEXT NOT NULL,
|
|
1628
|
+
method TEXT NOT NULL,
|
|
1629
|
+
method_version TEXT NOT NULL,
|
|
1630
|
+
created_at TEXT NOT NULL,
|
|
1631
|
+
claim_type TEXT NOT NULL DEFAULT 'observational'
|
|
1632
|
+
);
|
|
1633
|
+
|
|
1634
|
+
CREATE INDEX IF NOT EXISTS idx_attribution_assessments_attempt_created
|
|
1635
|
+
ON attribution_assessments(attempt_id, created_at);
|
|
1636
|
+
CREATE INDEX IF NOT EXISTS idx_attribution_assessments_label_created
|
|
1637
|
+
ON attribution_assessments(impact_label, created_at);
|
|
1638
|
+
CREATE INDEX IF NOT EXISTS idx_attribution_assessments_exposure
|
|
1639
|
+
ON attribution_assessments(exposure_id);
|
|
1640
|
+
|
|
1641
|
+
CREATE TABLE IF NOT EXISTS attribution_assessment_evidence (
|
|
1642
|
+
assessment_id TEXT NOT NULL REFERENCES attribution_assessments(assessment_id) ON DELETE CASCADE,
|
|
1643
|
+
evidence_id TEXT NOT NULL REFERENCES outcome_evidence(evidence_id) ON DELETE CASCADE,
|
|
1644
|
+
PRIMARY KEY (assessment_id, evidence_id)
|
|
1645
|
+
);
|
|
1646
|
+
|
|
1647
|
+
CREATE INDEX IF NOT EXISTS idx_attribution_assessment_evidence_evidence
|
|
1648
|
+
ON attribution_assessment_evidence(evidence_id, assessment_id);
|
|
1649
|
+
|
|
1650
|
+
-- Intentionally handwritten: Drizzle models tables/indexes but not SQLite triggers.
|
|
1651
|
+
-- This keeps soft deletion aligned with the FK's physical-delete SET NULL behavior.
|
|
1652
|
+
CREATE TRIGGER IF NOT EXISTS trg_retrieval_exposures_detach_deleted_memory
|
|
1653
|
+
AFTER UPDATE OF active, deleted_at ON memory_items
|
|
1654
|
+
WHEN NEW.active = 0 OR NEW.deleted_at IS NOT NULL
|
|
1655
|
+
BEGIN
|
|
1656
|
+
UPDATE retrieval_exposures SET memory_id = NULL WHERE memory_id = NEW.id;
|
|
1657
|
+
END;
|
|
1658
|
+
|
|
1659
|
+
-- Foreign keys are checked when the INSERT statement finishes, after AFTER
|
|
1660
|
+
-- triggers run, so unavailable or identity-mismatched references can be detached
|
|
1661
|
+
-- without losing the immutable exposure snapshot.
|
|
1662
|
+
-- Keyless/privacy-redacted linkage requires every memory snapshot field to match.
|
|
1663
|
+
-- This narrows, but cannot eliminate, the risk of linking a reused numeric ID.
|
|
1664
|
+
${nr}
|
|
1665
|
+
|
|
1666
|
+
-- Defensive identity check for callers that disable foreign-key enforcement
|
|
1667
|
+
-- while replacing memory rows. Normal writable connections keep foreign keys on,
|
|
1668
|
+
-- so ON DELETE SET NULL detaches the link before an ID can be reused.
|
|
1669
|
+
-- There is intentionally no keyless fallback here: replacement cannot prove
|
|
1670
|
+
-- continuity with a previously linked memory.
|
|
1671
|
+
CREATE TRIGGER IF NOT EXISTS trg_retrieval_exposures_detach_reused_memory_id
|
|
1672
|
+
AFTER INSERT ON memory_items
|
|
1673
|
+
WHEN EXISTS (SELECT 1 FROM retrieval_exposures WHERE memory_id = NEW.id)
|
|
1674
|
+
BEGIN
|
|
1675
|
+
UPDATE retrieval_exposures
|
|
1676
|
+
SET memory_id = NULL
|
|
1677
|
+
WHERE memory_id = NEW.id
|
|
1678
|
+
AND (
|
|
1679
|
+
COALESCE(NEW.active, 0) = 0
|
|
1680
|
+
OR NEW.deleted_at IS NOT NULL
|
|
1681
|
+
OR memory_import_key IS NULL
|
|
1682
|
+
OR TRIM(memory_import_key) = ''
|
|
1683
|
+
OR NEW.import_key IS NULL
|
|
1684
|
+
OR TRIM(NEW.import_key) = ''
|
|
1685
|
+
OR memory_import_key != NEW.import_key
|
|
1686
|
+
OR (
|
|
1687
|
+
origin_device_id IS NOT NULL
|
|
1688
|
+
AND TRIM(origin_device_id) != ''
|
|
1689
|
+
AND (
|
|
1690
|
+
NEW.origin_device_id IS NULL
|
|
1691
|
+
OR TRIM(NEW.origin_device_id) = ''
|
|
1692
|
+
OR origin_device_id != NEW.origin_device_id
|
|
1693
|
+
)
|
|
1694
|
+
)
|
|
1695
|
+
);
|
|
1696
|
+
END;
|
|
1697
|
+
`, ir = /* @__PURE__ */ "retrieval_attempts.retrieval_exposures.outcome_evidence.attribution_assessments.attribution_assessment_evidence.idx_retrieval_attempts_session_started.idx_retrieval_attempts_source_stream_started.idx_retrieval_attempts_retention.idx_retrieval_attempts_started.idx_retrieval_attempts_surface_started.idx_retrieval_attempts_request_identity.idx_retrieval_attempts_experiment_cell.idx_retrieval_exposures_attempt_rank.idx_retrieval_exposures_memory.idx_outcome_evidence_observed_id.idx_outcome_evidence_session_observed.idx_outcome_evidence_source_stream_observed.idx_outcome_evidence_type_observed.idx_outcome_evidence_retention.idx_attribution_assessments_attempt_created.idx_attribution_assessments_label_created.idx_attribution_assessments_exposure.idx_attribution_assessment_evidence_evidence.trg_retrieval_exposures_detach_deleted_memory.trg_retrieval_exposures_detach_unavailable_memory.trg_retrieval_exposures_detach_reused_memory_id".split("."), ar = "\nCREATE TABLE IF NOT EXISTS legacy_team_setup_drafts (\n attempt_id TEXT PRIMARY KEY NOT NULL,\n candidate_id TEXT NOT NULL,\n coordinator_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n state TEXT NOT NULL DEFAULT 'needs_setup',\n display_name TEXT NOT NULL,\n roster_fingerprint TEXT NOT NULL,\n projection_fingerprint TEXT NOT NULL,\n finish_digest TEXT,\n safe_error_code TEXT,\n completed_team_id TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n completed_at TEXT,\n superseded_at TEXT\n);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_drafts_candidate_state\n ON legacy_team_setup_drafts(candidate_id, state, created_at);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_drafts_state_updated\n ON legacy_team_setup_drafts(state, updated_at);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_drafts_finish_digest\n ON legacy_team_setup_drafts(finish_digest);\n\nCREATE TABLE IF NOT EXISTS legacy_team_setup_completions (\n attempt_id TEXT NOT NULL,\n finish_digest TEXT NOT NULL,\n candidate_ref TEXT NOT NULL,\n confirmed_access_delta_digest TEXT NOT NULL,\n completed_team_id TEXT NOT NULL,\n response_json TEXT NOT NULL,\n completed_at TEXT NOT NULL,\n created_at TEXT NOT NULL\n);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_legacy_team_setup_completions_attempt_finish\n ON legacy_team_setup_completions(attempt_id, finish_digest);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_completions_exact_replay\n ON legacy_team_setup_completions(\n candidate_ref,\n attempt_id,\n finish_digest,\n confirmed_access_delta_digest\n );\n\nCREATE TABLE IF NOT EXISTS legacy_team_setup_draft_devices (\n attempt_id TEXT NOT NULL REFERENCES legacy_team_setup_drafts(attempt_id) ON DELETE CASCADE,\n device_id TEXT NOT NULL,\n device_ref TEXT NOT NULL,\n key_fingerprint TEXT NOT NULL,\n display_name TEXT NOT NULL,\n enabled INTEGER NOT NULL,\n existing_identity_id TEXT,\n existing_assignment_version INTEGER,\n verified_evidence_kind TEXT,\n identity_evidence TEXT,\n decision TEXT NOT NULL DEFAULT 'unresolved',\n target_identity_id TEXT,\n expected_assignment_kind TEXT,\n expected_assignment_version INTEGER,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (attempt_id, device_id)\n);\nCREATE UNIQUE INDEX IF NOT EXISTS idx_legacy_team_setup_devices_attempt_ref\n ON legacy_team_setup_draft_devices(attempt_id, device_ref);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_devices_attempt_decision\n ON legacy_team_setup_draft_devices(attempt_id, decision);\n\nCREATE TABLE IF NOT EXISTS legacy_team_setup_draft_projects (\n attempt_id TEXT NOT NULL REFERENCES legacy_team_setup_drafts(attempt_id) ON DELETE CASCADE,\n project_ref TEXT NOT NULL,\n source_project_identity TEXT NOT NULL,\n display_name TEXT NOT NULL,\n source_fingerprint TEXT NOT NULL,\n resolution_kind TEXT NOT NULL DEFAULT 'unresolved',\n resolved_project_identity TEXT,\n target_scope_id TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (attempt_id, project_ref)\n);\nCREATE INDEX IF NOT EXISTS idx_legacy_team_setup_projects_attempt_resolution\n ON legacy_team_setup_draft_projects(attempt_id, resolution_kind);\n";
|
|
1698
|
+
function or(e) {
|
|
1699
|
+
e.exec(ar), e.prepare("SELECT \"unique\" AS is_unique\n FROM pragma_index_list('legacy_team_setup_drafts')\n WHERE name = 'idx_legacy_team_setup_drafts_finish_digest'\n LIMIT 1").get()?.is_unique === 1 && e.exec("\n DROP INDEX idx_legacy_team_setup_drafts_finish_digest;\n CREATE INDEX idx_legacy_team_setup_drafts_finish_digest\n ON legacy_team_setup_drafts(finish_digest);\n ");
|
|
1700
|
+
for (let [t, n, r] of [
|
|
1701
|
+
[
|
|
1702
|
+
"legacy_team_setup_drafts",
|
|
1703
|
+
"safe_error_code",
|
|
1704
|
+
"TEXT"
|
|
1705
|
+
],
|
|
1706
|
+
[
|
|
1707
|
+
"legacy_team_setup_drafts",
|
|
1708
|
+
"completed_team_id",
|
|
1709
|
+
"TEXT"
|
|
1710
|
+
],
|
|
1711
|
+
[
|
|
1712
|
+
"legacy_team_setup_draft_devices",
|
|
1713
|
+
"verified_evidence_kind",
|
|
1714
|
+
"TEXT"
|
|
1715
|
+
],
|
|
1716
|
+
[
|
|
1717
|
+
"legacy_team_setup_draft_devices",
|
|
1718
|
+
"identity_evidence",
|
|
1719
|
+
"TEXT"
|
|
1720
|
+
],
|
|
1721
|
+
[
|
|
1722
|
+
"legacy_team_setup_draft_projects",
|
|
1723
|
+
"target_scope_id",
|
|
1724
|
+
"TEXT"
|
|
1725
|
+
]
|
|
1726
|
+
]) W(e, t, n) || e.exec(`ALTER TABLE ${t} ADD COLUMN ${n} ${r}`);
|
|
1727
|
+
cr(e);
|
|
1728
|
+
}
|
|
1729
|
+
var sr = "identity_evidence IS NULL AND attempt_id IN (\n SELECT attempt_id FROM legacy_team_setup_drafts WHERE state IN ('needs_setup', 'in_progress'))";
|
|
1730
|
+
function cr(e) {
|
|
1731
|
+
if (e.prepare(`SELECT 1 FROM legacy_team_setup_draft_devices WHERE ${sr} LIMIT 1`).get()) try {
|
|
1732
|
+
e.exec(`UPDATE legacy_team_setup_draft_devices
|
|
1733
|
+
SET identity_evidence = CASE WHEN device_id IS (
|
|
1734
|
+
SELECT CASE WHEN COUNT(*) = 1 THEN MAX(device_id) END FROM sync_device
|
|
1735
|
+
) THEN 'self' ELSE 'label' END
|
|
1736
|
+
WHERE ${sr}`);
|
|
1737
|
+
} catch {
|
|
1738
|
+
e.exec(`UPDATE legacy_team_setup_draft_devices SET identity_evidence = 'label'
|
|
1739
|
+
WHERE ${sr}`);
|
|
1740
|
+
}
|
|
1741
|
+
}
|
|
1742
|
+
var lr = `
|
|
1743
|
+
${rr}
|
|
1744
|
+
|
|
1745
|
+
${ar}
|
|
1746
|
+
|
|
1747
|
+
CREATE TABLE IF NOT EXISTS policy_team_device_decisions (
|
|
1748
|
+
team_id TEXT NOT NULL REFERENCES policy_teams(team_id) ON DELETE CASCADE,
|
|
1749
|
+
device_id TEXT NOT NULL,
|
|
1750
|
+
decision TEXT NOT NULL,
|
|
1751
|
+
assignment_version INTEGER NOT NULL DEFAULT 0,
|
|
1752
|
+
provenance TEXT NOT NULL,
|
|
1753
|
+
revision TEXT NOT NULL,
|
|
1754
|
+
created_at TEXT NOT NULL,
|
|
1755
|
+
updated_at TEXT NOT NULL,
|
|
1756
|
+
PRIMARY KEY (team_id, device_id)
|
|
1757
|
+
);
|
|
1758
|
+
CREATE INDEX IF NOT EXISTS idx_policy_team_device_decisions_device
|
|
1759
|
+
ON policy_team_device_decisions(device_id);
|
|
1760
|
+
|
|
1761
|
+
CREATE INDEX IF NOT EXISTS idx_sync_peers_actor_id ON sync_peers(actor_id);
|
|
1762
|
+
|
|
1763
|
+
CREATE TABLE IF NOT EXISTS sync_peer_signature_state (
|
|
1764
|
+
peer_device_id TEXT PRIMARY KEY NOT NULL,
|
|
1765
|
+
highest_observed_direct_signature_version INTEGER NOT NULL
|
|
1766
|
+
);
|
|
1767
|
+
|
|
1768
|
+
CREATE TABLE IF NOT EXISTS coordinator_enrollment_reconciliation_issues (
|
|
1769
|
+
coordinator_id TEXT NOT NULL,
|
|
1770
|
+
group_id TEXT NOT NULL,
|
|
1771
|
+
kind TEXT NOT NULL,
|
|
1772
|
+
reference_id TEXT NOT NULL,
|
|
1773
|
+
code TEXT NOT NULL,
|
|
1774
|
+
status TEXT NOT NULL DEFAULT 'open',
|
|
1775
|
+
first_seen_at TEXT NOT NULL,
|
|
1776
|
+
last_seen_at TEXT NOT NULL,
|
|
1777
|
+
resolved_at TEXT,
|
|
1778
|
+
occurrence_count INTEGER NOT NULL DEFAULT 1,
|
|
1779
|
+
updated_at TEXT NOT NULL,
|
|
1780
|
+
PRIMARY KEY (coordinator_id, group_id, kind, reference_id, code)
|
|
1781
|
+
);
|
|
1782
|
+
|
|
1783
|
+
CREATE INDEX IF NOT EXISTS idx_coordinator_enrollment_issues_boundary_status
|
|
1784
|
+
ON coordinator_enrollment_reconciliation_issues(coordinator_id, group_id, status);
|
|
1785
|
+
|
|
1786
|
+
CREATE INDEX IF NOT EXISTS idx_coordinator_enrollment_issues_status_recent
|
|
1787
|
+
ON coordinator_enrollment_reconciliation_issues(status, last_seen_at, resolved_at);
|
|
1788
|
+
|
|
1789
|
+
CREATE TABLE IF NOT EXISTS recipient_policy_review_resolutions (
|
|
1790
|
+
review_item_id TEXT NOT NULL,
|
|
1791
|
+
source_fingerprint TEXT NOT NULL,
|
|
1792
|
+
decision TEXT NOT NULL,
|
|
1793
|
+
decision_input_json TEXT NOT NULL,
|
|
1794
|
+
preview_json TEXT NOT NULL,
|
|
1795
|
+
decided_by_identity_id TEXT NOT NULL,
|
|
1796
|
+
decided_by_device_id TEXT NOT NULL,
|
|
1797
|
+
resolved_at TEXT NOT NULL,
|
|
1798
|
+
PRIMARY KEY (review_item_id, source_fingerprint)
|
|
1799
|
+
);
|
|
1800
|
+
|
|
1801
|
+
CREATE TABLE IF NOT EXISTS device_identity_binding_commits (
|
|
1802
|
+
commit_digest TEXT PRIMARY KEY NOT NULL,
|
|
1803
|
+
reviewed_inventory_digest TEXT NOT NULL,
|
|
1804
|
+
request_json TEXT NOT NULL,
|
|
1805
|
+
outcomes_json TEXT NOT NULL,
|
|
1806
|
+
write_count INTEGER NOT NULL,
|
|
1807
|
+
decided_by_identity_id TEXT NOT NULL,
|
|
1808
|
+
decided_by_device_id TEXT NOT NULL,
|
|
1809
|
+
created_at TEXT NOT NULL
|
|
1810
|
+
);
|
|
1811
|
+
|
|
1812
|
+
CREATE TABLE IF NOT EXISTS device_identity_binding_audit (
|
|
1813
|
+
event_id TEXT PRIMARY KEY NOT NULL,
|
|
1814
|
+
commit_digest TEXT NOT NULL REFERENCES device_identity_binding_commits(commit_digest),
|
|
1815
|
+
device_id TEXT NOT NULL,
|
|
1816
|
+
previous_identity_id TEXT,
|
|
1817
|
+
target_identity_id TEXT NOT NULL,
|
|
1818
|
+
action TEXT NOT NULL,
|
|
1819
|
+
previous_assignment_version INTEGER,
|
|
1820
|
+
resulting_assignment_version INTEGER NOT NULL,
|
|
1821
|
+
decided_by_identity_id TEXT NOT NULL,
|
|
1822
|
+
decided_by_device_id TEXT NOT NULL,
|
|
1823
|
+
created_at TEXT NOT NULL
|
|
1824
|
+
);
|
|
1825
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_device_identity_binding_audit_commit_device
|
|
1826
|
+
ON device_identity_binding_audit(commit_digest, device_id);
|
|
1827
|
+
CREATE INDEX IF NOT EXISTS idx_device_identity_binding_audit_device_created
|
|
1828
|
+
ON device_identity_binding_audit(device_id, created_at, event_id);
|
|
1829
|
+
|
|
1830
|
+
CREATE TABLE IF NOT EXISTS recipient_policy_authority_states (
|
|
1831
|
+
canonical_project_identity TEXT PRIMARY KEY NOT NULL,
|
|
1832
|
+
authority_state TEXT NOT NULL DEFAULT 'legacy',
|
|
1833
|
+
generation INTEGER NOT NULL DEFAULT 0,
|
|
1834
|
+
desired_devices_digest TEXT,
|
|
1835
|
+
current_devices_digest TEXT,
|
|
1836
|
+
stable_parity_evidence_digest TEXT,
|
|
1837
|
+
stable_parity_passed_at TEXT,
|
|
1838
|
+
fresh_snapshot_fingerprint TEXT,
|
|
1839
|
+
fresh_snapshot_observed_at TEXT,
|
|
1840
|
+
safe_error_code TEXT,
|
|
1841
|
+
state_changed_at TEXT NOT NULL,
|
|
1842
|
+
last_error_at TEXT,
|
|
1843
|
+
attempt_count INTEGER NOT NULL DEFAULT 0,
|
|
1844
|
+
last_attempt_at TEXT,
|
|
1845
|
+
wake_epoch INTEGER NOT NULL DEFAULT 0,
|
|
1846
|
+
last_completed_at TEXT,
|
|
1847
|
+
lease_owner TEXT,
|
|
1848
|
+
lease_acquired_at TEXT,
|
|
1849
|
+
lease_expires_at TEXT,
|
|
1850
|
+
created_at TEXT NOT NULL,
|
|
1851
|
+
updated_at TEXT NOT NULL
|
|
1852
|
+
);
|
|
1853
|
+
CREATE TABLE IF NOT EXISTS recipient_policy_reconciliation_steps (
|
|
1854
|
+
canonical_project_identity TEXT NOT NULL,
|
|
1855
|
+
generation INTEGER NOT NULL,
|
|
1856
|
+
step_key TEXT NOT NULL,
|
|
1857
|
+
effect_id TEXT NOT NULL,
|
|
1858
|
+
payload_digest TEXT NOT NULL,
|
|
1859
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
1860
|
+
attempt_count INTEGER NOT NULL DEFAULT 0,
|
|
1861
|
+
started_at TEXT,
|
|
1862
|
+
completed_at TEXT,
|
|
1863
|
+
last_attempt_at TEXT,
|
|
1864
|
+
safe_error_code TEXT,
|
|
1865
|
+
error_at TEXT,
|
|
1866
|
+
lease_owner TEXT,
|
|
1867
|
+
lease_acquired_at TEXT,
|
|
1868
|
+
lease_expires_at TEXT,
|
|
1869
|
+
created_at TEXT NOT NULL,
|
|
1870
|
+
updated_at TEXT NOT NULL,
|
|
1871
|
+
PRIMARY KEY (canonical_project_identity, generation, step_key)
|
|
1872
|
+
);
|
|
1873
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_effect
|
|
1874
|
+
ON recipient_policy_reconciliation_steps(effect_id);
|
|
1875
|
+
CREATE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_status
|
|
1876
|
+
ON recipient_policy_reconciliation_steps(canonical_project_identity, status);
|
|
1877
|
+
CREATE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_pending_refresh
|
|
1878
|
+
ON recipient_policy_reconciliation_steps(canonical_project_identity, generation, step_key)
|
|
1879
|
+
WHERE status IN ('pending', 'running', 'failed')
|
|
1880
|
+
AND step_key GLOB 'refresh-after-revocations-v2:*';
|
|
1881
|
+
CREATE TABLE IF NOT EXISTS recipient_policy_deny_overlays (
|
|
1882
|
+
canonical_project_identity TEXT NOT NULL,
|
|
1883
|
+
scope_id TEXT NOT NULL,
|
|
1884
|
+
device_id TEXT NOT NULL,
|
|
1885
|
+
generation INTEGER NOT NULL,
|
|
1886
|
+
reason_code TEXT NOT NULL,
|
|
1887
|
+
created_at TEXT NOT NULL,
|
|
1888
|
+
updated_at TEXT NOT NULL,
|
|
1889
|
+
PRIMARY KEY (canonical_project_identity, scope_id, device_id)
|
|
1890
|
+
);
|
|
1891
|
+
CREATE INDEX IF NOT EXISTS idx_recipient_policy_deny_overlays_scope_device
|
|
1892
|
+
ON recipient_policy_deny_overlays(scope_id, device_id);
|
|
1893
|
+
|
|
1894
|
+
CREATE TABLE IF NOT EXISTS recipient_managed_project_projections (
|
|
1895
|
+
canonical_project_identity TEXT NOT NULL,
|
|
1896
|
+
display_name TEXT NOT NULL,
|
|
1897
|
+
managed_scope_id TEXT NOT NULL,
|
|
1898
|
+
coordinator_id TEXT NOT NULL,
|
|
1899
|
+
group_id TEXT NOT NULL,
|
|
1900
|
+
recipient_identity_id TEXT NOT NULL,
|
|
1901
|
+
accepting_device_id TEXT NOT NULL,
|
|
1902
|
+
source_operation_id TEXT NOT NULL,
|
|
1903
|
+
reviewed_project_set_digest TEXT NOT NULL,
|
|
1904
|
+
status TEXT NOT NULL DEFAULT 'active',
|
|
1905
|
+
accepted_at TEXT NOT NULL,
|
|
1906
|
+
revoked_at TEXT,
|
|
1907
|
+
created_at TEXT NOT NULL,
|
|
1908
|
+
updated_at TEXT NOT NULL,
|
|
1909
|
+
PRIMARY KEY (source_operation_id, canonical_project_identity)
|
|
1910
|
+
);
|
|
1911
|
+
CREATE INDEX IF NOT EXISTS idx_recipient_managed_projects_identity_status
|
|
1912
|
+
ON recipient_managed_project_projections(recipient_identity_id, status);
|
|
1913
|
+
CREATE INDEX IF NOT EXISTS idx_recipient_managed_projects_scope_authority
|
|
1914
|
+
ON recipient_managed_project_projections(managed_scope_id, coordinator_id, group_id, status);
|
|
1915
|
+
|
|
1916
|
+
CREATE TABLE IF NOT EXISTS share_operations (
|
|
1917
|
+
operation_id TEXT PRIMARY KEY NOT NULL,
|
|
1918
|
+
state TEXT NOT NULL,
|
|
1919
|
+
inviter_actor_id TEXT NOT NULL,
|
|
1920
|
+
inviter_device_ids_json TEXT NOT NULL,
|
|
1921
|
+
person_id TEXT NOT NULL,
|
|
1922
|
+
person_kind TEXT NOT NULL,
|
|
1923
|
+
pending_person_operation_id TEXT,
|
|
1924
|
+
teammate_name TEXT NOT NULL,
|
|
1925
|
+
history_policy TEXT NOT NULL,
|
|
1926
|
+
reviewed_project_set_digest TEXT NOT NULL,
|
|
1927
|
+
coordinator_group_id TEXT NOT NULL,
|
|
1928
|
+
coordinator_invite_id TEXT,
|
|
1929
|
+
invite_token_digest TEXT NOT NULL,
|
|
1930
|
+
invite_expires_at TEXT NOT NULL,
|
|
1931
|
+
recipient_actor_id TEXT,
|
|
1932
|
+
recipient_display_name TEXT,
|
|
1933
|
+
recipient_device_id TEXT,
|
|
1934
|
+
recipient_device_display_name TEXT,
|
|
1935
|
+
recipient_public_key TEXT,
|
|
1936
|
+
recipient_fingerprint TEXT,
|
|
1937
|
+
acceptance_consumed_at TEXT,
|
|
1938
|
+
trust_state TEXT,
|
|
1939
|
+
bootstrap_grant_id TEXT,
|
|
1940
|
+
created_at TEXT NOT NULL,
|
|
1941
|
+
updated_at TEXT NOT NULL
|
|
1942
|
+
);
|
|
1943
|
+
CREATE INDEX IF NOT EXISTS idx_share_operations_state_updated
|
|
1944
|
+
ON share_operations(state, updated_at);
|
|
1945
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_share_operations_invite_digest
|
|
1946
|
+
ON share_operations(invite_token_digest);
|
|
1947
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_share_operations_pending_person_operation
|
|
1948
|
+
ON share_operations(pending_person_operation_id)
|
|
1949
|
+
WHERE pending_person_operation_id IS NOT NULL;
|
|
1950
|
+
CREATE TABLE IF NOT EXISTS share_operation_projects (
|
|
1951
|
+
operation_id TEXT NOT NULL,
|
|
1952
|
+
canonical_project_identity TEXT NOT NULL,
|
|
1953
|
+
display_name TEXT NOT NULL,
|
|
1954
|
+
identity_source TEXT NOT NULL,
|
|
1955
|
+
existing_memory_count INTEGER NOT NULL,
|
|
1956
|
+
ordinal INTEGER NOT NULL,
|
|
1957
|
+
PRIMARY KEY (operation_id, canonical_project_identity)
|
|
1958
|
+
);
|
|
1959
|
+
CREATE TABLE IF NOT EXISTS share_operation_steps (
|
|
1960
|
+
operation_id TEXT NOT NULL,
|
|
1961
|
+
step_key TEXT NOT NULL,
|
|
1962
|
+
effect_id TEXT NOT NULL,
|
|
1963
|
+
status TEXT NOT NULL,
|
|
1964
|
+
attempt_count INTEGER NOT NULL DEFAULT 0,
|
|
1965
|
+
started_at TEXT,
|
|
1966
|
+
completed_at TEXT,
|
|
1967
|
+
last_attempt_at TEXT,
|
|
1968
|
+
safe_error_code TEXT,
|
|
1969
|
+
updated_at TEXT NOT NULL,
|
|
1970
|
+
PRIMARY KEY (operation_id, step_key)
|
|
1971
|
+
);
|
|
1972
|
+
|
|
1973
|
+
CREATE TABLE IF NOT EXISTS sync_retention_state (
|
|
1974
|
+
id INTEGER PRIMARY KEY,
|
|
1975
|
+
last_run_at TEXT,
|
|
1976
|
+
last_duration_ms INTEGER,
|
|
1977
|
+
last_deleted_ops INTEGER NOT NULL DEFAULT 0,
|
|
1978
|
+
last_estimated_bytes_before INTEGER,
|
|
1979
|
+
last_estimated_bytes_after INTEGER,
|
|
1980
|
+
retained_floor_cursor TEXT,
|
|
1981
|
+
last_error TEXT,
|
|
1982
|
+
last_error_at TEXT
|
|
1983
|
+
);
|
|
1984
|
+
|
|
1985
|
+
CREATE TABLE IF NOT EXISTS maintenance_jobs (
|
|
1986
|
+
kind TEXT PRIMARY KEY,
|
|
1987
|
+
title TEXT NOT NULL,
|
|
1988
|
+
status TEXT NOT NULL,
|
|
1989
|
+
message TEXT,
|
|
1990
|
+
progress_current INTEGER NOT NULL DEFAULT 0,
|
|
1991
|
+
progress_total INTEGER,
|
|
1992
|
+
progress_unit TEXT NOT NULL DEFAULT 'items',
|
|
1993
|
+
metadata_json TEXT,
|
|
1994
|
+
started_at TEXT,
|
|
1995
|
+
updated_at TEXT NOT NULL,
|
|
1996
|
+
finished_at TEXT,
|
|
1997
|
+
error TEXT
|
|
1998
|
+
);
|
|
1999
|
+
|
|
2000
|
+
CREATE INDEX IF NOT EXISTS idx_maintenance_jobs_status_updated
|
|
2001
|
+
ON maintenance_jobs(status, updated_at);
|
|
2002
|
+
|
|
2003
|
+
CREATE TABLE IF NOT EXISTS sync_scope_rejections (
|
|
2004
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2005
|
+
peer_device_id TEXT,
|
|
2006
|
+
op_id TEXT NOT NULL,
|
|
2007
|
+
entity_type TEXT NOT NULL,
|
|
2008
|
+
entity_id TEXT NOT NULL,
|
|
2009
|
+
scope_id TEXT,
|
|
2010
|
+
reason TEXT NOT NULL,
|
|
2011
|
+
created_at TEXT NOT NULL
|
|
2012
|
+
);
|
|
2013
|
+
|
|
2014
|
+
CREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_peer_created
|
|
2015
|
+
ON sync_scope_rejections(peer_device_id, created_at);
|
|
2016
|
+
|
|
2017
|
+
CREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_scope_created
|
|
2018
|
+
ON sync_scope_rejections(scope_id, created_at);
|
|
2019
|
+
|
|
2020
|
+
-- import_key is the primary lookup key from replication_ops.entity_id back to
|
|
2021
|
+
-- the source memory. The scope-backfill runner's selectReplicationOpScopeCandidates
|
|
2022
|
+
-- query joins on it for every unstamped op; without this index a Pi 4 with
|
|
2023
|
+
-- ~17k memories and ~35k ops scans the full memory_items table on every batch
|
|
2024
|
+
-- tick. The partial WHERE clause keeps the index small (most rows have
|
|
2025
|
+
-- import_key set; the few that don't aren't searchable anyway).
|
|
2026
|
+
CREATE INDEX IF NOT EXISTS idx_memory_items_import_key
|
|
2027
|
+
ON memory_items(import_key)
|
|
2028
|
+
WHERE import_key IS NOT NULL;
|
|
2029
|
+
|
|
2030
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS memory_fts USING fts5(
|
|
2031
|
+
title, body_text, tags_text,
|
|
2032
|
+
content='memory_items',
|
|
2033
|
+
content_rowid='id'
|
|
2034
|
+
);
|
|
2035
|
+
|
|
2036
|
+
CREATE TRIGGER IF NOT EXISTS memory_items_ai AFTER INSERT ON memory_items BEGIN
|
|
2037
|
+
INSERT INTO memory_fts(rowid, title, body_text, tags_text)
|
|
2038
|
+
VALUES (new.id, new.title, new.body_text, new.tags_text);
|
|
2039
|
+
END;
|
|
2040
|
+
|
|
2041
|
+
DROP TRIGGER IF EXISTS memory_items_au;
|
|
2042
|
+
CREATE TRIGGER memory_items_au AFTER UPDATE ON memory_items BEGIN
|
|
2043
|
+
INSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)
|
|
2044
|
+
VALUES('delete', old.id, old.title, old.body_text, old.tags_text);
|
|
2045
|
+
INSERT INTO memory_fts(rowid, title, body_text, tags_text)
|
|
2046
|
+
VALUES (new.id, new.title, new.body_text, new.tags_text);
|
|
2047
|
+
END;
|
|
2048
|
+
|
|
2049
|
+
DROP TRIGGER IF EXISTS memory_items_ad;
|
|
2050
|
+
CREATE TRIGGER memory_items_ad AFTER DELETE ON memory_items BEGIN
|
|
2051
|
+
INSERT INTO memory_fts(memory_fts, rowid, title, body_text, tags_text)
|
|
2052
|
+
VALUES('delete', old.id, old.title, old.body_text, old.tags_text);
|
|
2053
|
+
END;
|
|
2054
|
+
|
|
2055
|
+
CREATE TABLE IF NOT EXISTS memory_file_refs (
|
|
2056
|
+
memory_id INTEGER NOT NULL,
|
|
2057
|
+
file_path TEXT NOT NULL,
|
|
2058
|
+
relation TEXT NOT NULL CHECK(relation IN ('read', 'modified')),
|
|
2059
|
+
PRIMARY KEY (memory_id, file_path, relation),
|
|
2060
|
+
FOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE
|
|
2061
|
+
);
|
|
2062
|
+
|
|
2063
|
+
CREATE INDEX IF NOT EXISTS idx_memory_file_refs_path
|
|
2064
|
+
ON memory_file_refs(file_path);
|
|
2065
|
+
|
|
2066
|
+
CREATE TABLE IF NOT EXISTS memory_concept_refs (
|
|
2067
|
+
memory_id INTEGER NOT NULL,
|
|
2068
|
+
concept TEXT NOT NULL,
|
|
2069
|
+
PRIMARY KEY (memory_id, concept),
|
|
2070
|
+
FOREIGN KEY (memory_id) REFERENCES memory_items(id) ON DELETE CASCADE
|
|
2071
|
+
);
|
|
2072
|
+
|
|
2073
|
+
CREATE INDEX IF NOT EXISTS idx_memory_concept_refs_concept
|
|
2074
|
+
ON memory_concept_refs(concept);
|
|
2075
|
+
|
|
2076
|
+
CREATE TABLE IF NOT EXISTS coordinator_group_preferences (
|
|
2077
|
+
coordinator_id TEXT NOT NULL,
|
|
2078
|
+
group_id TEXT NOT NULL,
|
|
2079
|
+
projects_include_json TEXT,
|
|
2080
|
+
projects_exclude_json TEXT,
|
|
2081
|
+
auto_seed_scope INTEGER NOT NULL DEFAULT 1,
|
|
2082
|
+
default_space_scope_id TEXT,
|
|
2083
|
+
auto_grant_default_space_on_join INTEGER NOT NULL DEFAULT 0,
|
|
2084
|
+
updated_at TEXT NOT NULL,
|
|
2085
|
+
PRIMARY KEY (coordinator_id, group_id)
|
|
2086
|
+
);
|
|
2087
|
+
|
|
2088
|
+
CREATE TABLE IF NOT EXISTS scope_membership_cache_state (
|
|
2089
|
+
coordinator_id TEXT NOT NULL,
|
|
2090
|
+
group_id TEXT NOT NULL,
|
|
2091
|
+
last_refresh_at TEXT NOT NULL,
|
|
2092
|
+
last_success_at TEXT,
|
|
2093
|
+
last_error TEXT,
|
|
2094
|
+
updated_at TEXT NOT NULL,
|
|
2095
|
+
refresh_revision INTEGER NOT NULL DEFAULT 0,
|
|
2096
|
+
PRIMARY KEY (coordinator_id, group_id)
|
|
2097
|
+
);
|
|
2098
|
+
`, ur = "\nCREATE VIRTUAL TABLE IF NOT EXISTS memory_vectors USING vec0(\n embedding float[384],\n memory_id INTEGER,\n chunk_index INTEGER,\n content_hash TEXT,\n model TEXT\n);\n";
|
|
2099
|
+
function dr(e) {
|
|
2100
|
+
if (!an()) try {
|
|
2101
|
+
fr(e) || on(e), e.exec(ur);
|
|
2102
|
+
} catch {
|
|
2103
|
+
return;
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
function fr(e) {
|
|
2107
|
+
try {
|
|
2108
|
+
let t = e.prepare("SELECT vec_version() AS v").get();
|
|
2109
|
+
return typeof t?.v == "string" && t.v.length > 0;
|
|
2110
|
+
} catch {
|
|
2111
|
+
return !1;
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
function pr(e) {
|
|
2115
|
+
e.transaction(() => {
|
|
2116
|
+
e.exec(qn), e.exec(lr), or(e), Dr(e), Sn(e), gr(e), vr(e), mr(e), hr(e), Cr(e), wr(e), gn(e), tr(e), Yn(e), Kn(e), Qn(e), Tr(e), e.pragma("user_version = 21");
|
|
2117
|
+
}).immediate(), dr(e);
|
|
2118
|
+
}
|
|
2119
|
+
function mr(e) {
|
|
2120
|
+
W(e, "sync_peers", "manual_addresses_json") || e.exec("ALTER TABLE sync_peers ADD COLUMN manual_addresses_json TEXT");
|
|
2121
|
+
}
|
|
2122
|
+
function hr(e) {
|
|
2123
|
+
W(e, "sync_peers", "last_success_address") || e.exec("ALTER TABLE sync_peers ADD COLUMN last_success_address TEXT");
|
|
2124
|
+
}
|
|
2125
|
+
function gr(e) {
|
|
2126
|
+
W(e, "policy_teams", "device_eligibility_mode") || e.exec("ALTER TABLE policy_teams ADD COLUMN device_eligibility_mode TEXT NOT NULL DEFAULT 'person_all_devices'"), W(e, "identity_devices", "assignment_version") || e.exec("ALTER TABLE identity_devices ADD COLUMN assignment_version INTEGER NOT NULL DEFAULT 0"), W(e, "policy_team_device_decisions", "assignment_version") || e.exec("ALTER TABLE policy_team_device_decisions ADD COLUMN assignment_version INTEGER NOT NULL DEFAULT 0"), yr(e);
|
|
2127
|
+
}
|
|
2128
|
+
function _r(e) {
|
|
2129
|
+
if (U(e, "sync_peers") && !W(e, "sync_peers", "highest_observed_direct_signature_version")) try {
|
|
2130
|
+
e.exec("ALTER TABLE sync_peers ADD COLUMN highest_observed_direct_signature_version INTEGER");
|
|
2131
|
+
} catch (t) {
|
|
2132
|
+
if ((t instanceof Error ? t.message.toLowerCase() : "").includes("duplicate column name") && W(e, "sync_peers", "highest_observed_direct_signature_version")) return;
|
|
2133
|
+
throw t;
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
function vr(e) {
|
|
2137
|
+
U(e, "sync_peers") && (_r(e), U(e, "sync_peer_signature_state") || e.exec("\n CREATE TABLE IF NOT EXISTS sync_peer_signature_state (\n peer_device_id TEXT PRIMARY KEY NOT NULL,\n highest_observed_direct_signature_version INTEGER NOT NULL\n );\n "), e.prepare("SELECT 1 FROM sync_peers AS peer\n LEFT JOIN sync_peer_signature_state AS state USING (peer_device_id)\n WHERE peer.highest_observed_direct_signature_version IS NOT NULL\n AND (state.peer_device_id IS NULL\n OR state.highest_observed_direct_signature_version\n < peer.highest_observed_direct_signature_version)\n LIMIT 1").get() && e.exec("\n INSERT INTO sync_peer_signature_state(\n peer_device_id, highest_observed_direct_signature_version\n )\n SELECT peer_device_id, highest_observed_direct_signature_version\n FROM sync_peers\n WHERE highest_observed_direct_signature_version IS NOT NULL\n ON CONFLICT(peer_device_id) DO UPDATE SET\n highest_observed_direct_signature_version = excluded.highest_observed_direct_signature_version\n WHERE sync_peer_signature_state.highest_observed_direct_signature_version\n < excluded.highest_observed_direct_signature_version;\n "));
|
|
2138
|
+
}
|
|
2139
|
+
function yr(e) {
|
|
2140
|
+
e.exec(cn);
|
|
2141
|
+
}
|
|
2142
|
+
function br(e) {
|
|
2143
|
+
if (!U(e, "sessions") || !U(e, "memory_items") || (Sr(e), e.exec("DROP TRIGGER IF EXISTS trg_attribution_evidence_delete_orphan"), !W(e, "memory_items", "import_key") || !W(e, "memory_items", "origin_device_id"))) return;
|
|
2144
|
+
let t = ir.map(() => "?").join(", ");
|
|
2145
|
+
e.prepare(`SELECT COUNT(*) AS count FROM sqlite_master WHERE name IN (${t})`).get(...ir)?.count !== ir.length && e.exec(rr), xr(e), Cr(e), wr(e);
|
|
2146
|
+
}
|
|
2147
|
+
function xr(e) {
|
|
2148
|
+
let t = e.prepare("SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = 'trg_retrieval_exposures_detach_unavailable_memory'").pluck().get();
|
|
2149
|
+
t?.includes("NEW.memory_import_key IS NOT NULL") && t.includes("NEW.memory_import_key = import_key") && t.includes("NEW.origin_device_id = origin_device_id") && t.includes("NEW.memory_rev = rev") && t.includes("julianday(NEW.memory_updated_at) = julianday(updated_at)") || e.transaction(() => {
|
|
2150
|
+
e.exec(`
|
|
2151
|
+
DROP TRIGGER IF EXISTS trg_retrieval_exposures_detach_unavailable_memory;
|
|
2152
|
+
${nr}
|
|
2153
|
+
`);
|
|
2154
|
+
}).immediate();
|
|
2155
|
+
}
|
|
2156
|
+
function Sr(e) {
|
|
2157
|
+
if (!W(e, "memory_items", "deleted_at")) try {
|
|
2158
|
+
e.exec("ALTER TABLE memory_items ADD COLUMN deleted_at TEXT");
|
|
2159
|
+
} catch (t) {
|
|
2160
|
+
if ((t instanceof Error ? t.message.toLowerCase() : "").includes("duplicate column name") && W(e, "memory_items", "deleted_at")) return;
|
|
2161
|
+
throw t;
|
|
2162
|
+
}
|
|
2163
|
+
}
|
|
2164
|
+
function Cr(e) {
|
|
2165
|
+
for (let [t, n] of [
|
|
2166
|
+
["evaluation_checkout_id", "TEXT"],
|
|
2167
|
+
["evaluation_fixture_id", "TEXT"],
|
|
2168
|
+
["evaluation_seed", "INTEGER"],
|
|
2169
|
+
["retention_finalized_at", "TEXT"],
|
|
2170
|
+
["automatic_recall_json", "TEXT"],
|
|
2171
|
+
["automatic_recall_key", "TEXT"]
|
|
2172
|
+
]) e.prepare("SELECT 1 FROM pragma_table_info('retrieval_attempts') WHERE name = ? LIMIT 1").get(t) === void 0 && e.exec(`ALTER TABLE retrieval_attempts ADD COLUMN ${t} ${n}`);
|
|
2173
|
+
e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_retrieval_attempts_automatic_recall_key ON retrieval_attempts(automatic_recall_key)");
|
|
2174
|
+
}
|
|
2175
|
+
function wr(e) {
|
|
2176
|
+
if (!W(e, "outcome_evidence", "retention_finalized_at")) try {
|
|
2177
|
+
e.exec("ALTER TABLE outcome_evidence ADD COLUMN retention_finalized_at TEXT");
|
|
2178
|
+
} catch (t) {
|
|
2179
|
+
if ((t instanceof Error ? t.message.toLowerCase() : "").includes("duplicate column name") && W(e, "outcome_evidence", "retention_finalized_at")) return;
|
|
2180
|
+
throw t;
|
|
2181
|
+
}
|
|
2182
|
+
}
|
|
2183
|
+
function Tr(e) {
|
|
2184
|
+
let t = rn.filter((t) => !U(e, t));
|
|
2185
|
+
if (t.length > 0) throw Error(`Schema bootstrap failed; missing required tables: ${t.join(", ")}`);
|
|
2186
|
+
}
|
|
2187
|
+
function Er(e) {
|
|
2188
|
+
return (e.prepare("SELECT COUNT(*) AS count\n FROM sqlite_master\n WHERE name NOT LIKE 'sqlite\\_%' ESCAPE '\\'").get()?.count ?? 0) === 0;
|
|
2189
|
+
}
|
|
2190
|
+
function U(e, t) {
|
|
2191
|
+
return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1").get(t) !== void 0;
|
|
2192
|
+
}
|
|
2193
|
+
function W(e, t, n) {
|
|
2194
|
+
return e.prepare("SELECT 1 FROM pragma_table_info(?) WHERE name = ? LIMIT 1").get(t, n) !== void 0;
|
|
2195
|
+
}
|
|
2196
|
+
function Dr(e) {
|
|
2197
|
+
if (Ar(e) || !U(e, "raw_events")) return;
|
|
2198
|
+
let t = e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'idx_raw_events_capture_context'").get();
|
|
2199
|
+
W(e, "raw_events", "capture_context_json") && t || e.transaction(() => {
|
|
2200
|
+
W(e, "raw_events", "capture_context_json") || e.exec("ALTER TABLE raw_events ADD COLUMN capture_context_json TEXT"), [
|
|
2201
|
+
"source",
|
|
2202
|
+
"stream_id",
|
|
2203
|
+
"event_seq"
|
|
2204
|
+
].every((t) => W(e, "raw_events", t)) && e.exec("CREATE INDEX IF NOT EXISTS idx_raw_events_capture_context\n ON raw_events(source, stream_id, event_seq) WHERE capture_context_json IS NOT NULL");
|
|
2205
|
+
}).immediate();
|
|
2206
|
+
}
|
|
2207
|
+
function Or(e) {
|
|
2208
|
+
!Ar(e) && kr(e) && pr(e);
|
|
2209
|
+
}
|
|
2210
|
+
function kr(e) {
|
|
2211
|
+
return V(e) === 0 && Er(e);
|
|
2212
|
+
}
|
|
2213
|
+
function Ar(e) {
|
|
2214
|
+
return e.readonly === !0;
|
|
2215
|
+
}
|
|
2216
|
+
//#endregion
|
|
2217
|
+
//#region src/sync-transfer-activity.ts
|
|
2218
|
+
var jr = /* @__PURE__ */ new WeakSet();
|
|
2219
|
+
function G(e) {
|
|
2220
|
+
jr.has(e) || (e.exec("\n CREATE TABLE IF NOT EXISTS sync_transfer_observations (\n peer_device_id TEXT NOT NULL,\n direction TEXT NOT NULL CHECK(direction IN ('send', 'receive')),\n source TEXT NOT NULL DEFAULT 'initiated' CHECK(source IN ('initiated', 'inbound')),\n observed_since TEXT NOT NULL,\n last_attempt_at TEXT NOT NULL,\n last_success_at TEXT,\n error_code TEXT,\n PRIMARY KEY(peer_device_id, direction, source)\n );\n CREATE TABLE IF NOT EXISTS sync_transfer_receipts (\n peer_device_id TEXT NOT NULL,\n direction TEXT NOT NULL,\n kind TEXT NOT NULL CHECK(kind IN ('operation', 'snapshot')),\n transfer_id TEXT NOT NULL,\n observed_at TEXT NOT NULL,\n PRIMARY KEY(peer_device_id, direction, kind, transfer_id)\n );\n CREATE INDEX IF NOT EXISTS idx_sync_transfer_receipts_recent\n ON sync_transfer_receipts(peer_device_id, direction, observed_at, kind);\n "), e.inTransaction || jr.add(e));
|
|
2221
|
+
}
|
|
2222
|
+
function Mr(e, t, n, r = {}) {
|
|
2223
|
+
G(e);
|
|
2224
|
+
let i = (r.now ?? /* @__PURE__ */ new Date()).toISOString();
|
|
2225
|
+
e.prepare("INSERT INTO sync_transfer_observations\n (peer_device_id, direction, source, observed_since, last_attempt_at, last_success_at, error_code)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(peer_device_id, direction, source) DO UPDATE SET\n last_attempt_at = excluded.last_attempt_at,\n last_success_at = COALESCE(excluded.last_success_at, last_success_at),\n error_code = CASE\n WHEN excluded.error_code IS NULL AND ? = 1 THEN error_code\n WHEN excluded.error_code IS NULL AND ? = 1 AND error_code IN ('apply_failed', 'scope_rejected')\n THEN error_code\n WHEN excluded.error_code = 'exchange_failed' AND error_code IN ('apply_failed', 'scope_rejected')\n THEN error_code ELSE excluded.error_code END\n ").run(t, n, r.source ?? "initiated", i, i, r.errorCode ? null : i, r.errorCode ?? null, +!!r.preserveError, +!!r.preserveScopedError);
|
|
2226
|
+
}
|
|
2227
|
+
function Nr(e, t, n, r, i = {}) {
|
|
2228
|
+
G(e);
|
|
2229
|
+
let a = (i.now ?? /* @__PURE__ */ new Date()).toISOString(), o = e.prepare("INSERT OR IGNORE INTO sync_transfer_receipts\n (peer_device_id, direction, kind, transfer_id, observed_at) VALUES (?, ?, ?, ?, ?)");
|
|
2230
|
+
for (let e of r) o.run(t, n, i.kind ?? "operation", e, a);
|
|
2231
|
+
}
|
|
2232
|
+
function Pr() {
|
|
2233
|
+
return {
|
|
2234
|
+
lastAttemptAt: null,
|
|
2235
|
+
lastSuccessAt: null,
|
|
2236
|
+
errorCode: null,
|
|
2237
|
+
operations24h: null,
|
|
2238
|
+
snapshotItems24h: null,
|
|
2239
|
+
observedSince: null
|
|
2240
|
+
};
|
|
2241
|
+
}
|
|
2242
|
+
function Fr(e, t, n = {}) {
|
|
2243
|
+
let r = new Map(t.map((e) => [e, {
|
|
2244
|
+
send: Pr(),
|
|
2245
|
+
receive: Pr()
|
|
2246
|
+
}]));
|
|
2247
|
+
if (t.length === 0) return r;
|
|
2248
|
+
G(e);
|
|
2249
|
+
let i = n.now ? new Date(n.now) : /* @__PURE__ */ new Date(), a = (/* @__PURE__ */ new Date(i.getTime() - 864e5)).toISOString();
|
|
2250
|
+
for (let n = 0; n < t.length; n += 400) {
|
|
2251
|
+
let o = t.slice(n, n + 400), s = o.map(() => "?").join(","), c = e.prepare(`SELECT o.peer_device_id, o.direction,
|
|
2252
|
+
MIN(o.observed_since) AS observed_since,
|
|
2253
|
+
MAX(o.last_attempt_at) AS last_attempt_at,
|
|
2254
|
+
MAX(o.last_success_at) AS last_success_at,
|
|
2255
|
+
(SELECT e.error_code FROM sync_transfer_observations e
|
|
2256
|
+
WHERE e.peer_device_id = o.peer_device_id AND e.direction = o.direction AND e.error_code IS NOT NULL
|
|
2257
|
+
ORDER BY CASE WHEN e.error_code IN ('apply_failed', 'scope_rejected') THEN 0 ELSE 1 END,
|
|
2258
|
+
e.last_attempt_at DESC LIMIT 1) AS error_code,
|
|
2259
|
+
(SELECT count(*) FROM sync_transfer_receipts r WHERE r.peer_device_id = o.peer_device_id
|
|
2260
|
+
AND r.direction = o.direction AND r.observed_at >= ? AND r.observed_at <= ? AND r.kind = 'operation') AS operations,
|
|
2261
|
+
(SELECT count(*) FROM sync_transfer_receipts r WHERE r.peer_device_id = o.peer_device_id
|
|
2262
|
+
AND r.direction = o.direction AND r.observed_at >= ? AND r.observed_at <= ? AND r.kind = 'snapshot') AS snapshots
|
|
2263
|
+
FROM sync_transfer_observations o WHERE o.peer_device_id IN (${s})
|
|
2264
|
+
GROUP BY o.peer_device_id, o.direction
|
|
2265
|
+
`).all(a, i.toISOString(), a, i.toISOString(), ...o);
|
|
2266
|
+
for (let e of c) {
|
|
2267
|
+
let t = r.get(e.peer_device_id);
|
|
2268
|
+
t && (t[e.direction] = {
|
|
2269
|
+
lastAttemptAt: e.last_attempt_at,
|
|
2270
|
+
lastSuccessAt: e.last_success_at,
|
|
2271
|
+
errorCode: e.error_code,
|
|
2272
|
+
observedSince: e.observed_since,
|
|
2273
|
+
operations24h: e.operations,
|
|
2274
|
+
snapshotItems24h: e.snapshots
|
|
2275
|
+
});
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
return r;
|
|
2279
|
+
}
|
|
2280
|
+
//#endregion
|
|
2281
|
+
//#region src/db.ts
|
|
2282
|
+
var Ir = 6, K = v(y(), ".codemem", "mem.sqlite");
|
|
2283
|
+
function Lr(e) {
|
|
2284
|
+
if (e) return N(e);
|
|
2285
|
+
let t = process.env.CODEMEM_DB;
|
|
2286
|
+
return t ? N(t) : K;
|
|
2287
|
+
}
|
|
2288
|
+
var Rr = [v(y(), ".codemem.sqlite"), v(y(), ".opencode-mem.sqlite")], zr = ["-wal", "-shm"];
|
|
2289
|
+
function Br(e, t) {
|
|
2290
|
+
oe(_(t), { recursive: !0 });
|
|
2291
|
+
let n = [[e, t], ...zr.map((n) => [e + n, t + n])];
|
|
2292
|
+
for (let [e, t] of n) if (m(e)) try {
|
|
2293
|
+
ue(e, t);
|
|
2294
|
+
} catch {
|
|
2295
|
+
try {
|
|
2296
|
+
ee(e, t);
|
|
2297
|
+
try {
|
|
2298
|
+
g(e);
|
|
2299
|
+
} catch {}
|
|
2300
|
+
} catch (e) {
|
|
2301
|
+
if (m(t)) continue;
|
|
2302
|
+
throw e;
|
|
2303
|
+
}
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
function Vr(e) {
|
|
2307
|
+
if (e === K && !m(e)) {
|
|
2308
|
+
for (let t of Rr) if (m(t)) {
|
|
2309
|
+
Br(t, e);
|
|
2310
|
+
return;
|
|
2311
|
+
}
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
function Hr(e = K) {
|
|
2315
|
+
Vr(e), oe(_(e), { recursive: !0 });
|
|
2316
|
+
let t = new _e(e);
|
|
2317
|
+
try {
|
|
2318
|
+
t.pragma("foreign_keys = ON"), t.pragma("busy_timeout = 5000");
|
|
2319
|
+
let e = kr(t) || Gr(t);
|
|
2320
|
+
if (Or(t), !e) return t;
|
|
2321
|
+
if (Sn(t), !t.memory) {
|
|
2322
|
+
let e = t.pragma("journal_mode = WAL", { simple: !0 });
|
|
2323
|
+
e.toLowerCase() !== "wal" && console.warn(`Failed to enable WAL mode (got ${e}). Concurrent access may not work correctly.`);
|
|
2324
|
+
}
|
|
2325
|
+
return t.pragma("synchronous = NORMAL"), t.pragma("cache_size = -65536"), t.pragma("mmap_size = 1073741824"), t.pragma("temp_store = MEMORY"), t;
|
|
2326
|
+
} catch (e) {
|
|
2327
|
+
throw t.close(), e;
|
|
2328
|
+
}
|
|
2329
|
+
}
|
|
2330
|
+
function Ur(e = K, t = {}) {
|
|
2331
|
+
let n = new _e(e, {
|
|
2332
|
+
readonly: !0,
|
|
2333
|
+
fileMustExist: !0
|
|
2334
|
+
});
|
|
2335
|
+
try {
|
|
2336
|
+
return n.pragma("foreign_keys = ON"), n.pragma("busy_timeout = 5000"), n.pragma("cache_size = -65536"), n.pragma("mmap_size = 1073741824"), n.pragma("temp_store = MEMORY"), Wr(n, t.warn), n;
|
|
2337
|
+
} catch (e) {
|
|
2338
|
+
throw n.close(), e;
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
function Wr(e, t = console.warn) {
|
|
2342
|
+
let n = V(e);
|
|
2343
|
+
if (n === 0) throw Error("Database schema is not initialized (read-only open). Point at an initialized codemem database.");
|
|
2344
|
+
if (n < 6) throw Error(`Database schema version ${n} is older than minimum compatible (6).`);
|
|
2345
|
+
n > 21 && t(`Database schema version ${n} is newer than this TS runtime (21). Running in read-only compatibility mode.`);
|
|
2346
|
+
let r = nn.filter((t) => !q(e, t));
|
|
2347
|
+
if (r.length > 0) throw Error(`Required tables missing: ${r.join(", ")}. The database may be corrupt or from an incompatible version.`);
|
|
2348
|
+
}
|
|
2349
|
+
function Gr(e) {
|
|
2350
|
+
return rn.every((t) => q(e, t));
|
|
2351
|
+
}
|
|
2352
|
+
function Kr(e) {
|
|
2353
|
+
try {
|
|
2354
|
+
return !!e.prepare("SELECT 1 FROM sqlite_stat1 LIMIT 1").pluck().get();
|
|
2355
|
+
} catch {
|
|
2356
|
+
return !1;
|
|
2357
|
+
}
|
|
2358
|
+
}
|
|
2359
|
+
function qr(e) {
|
|
2360
|
+
Xr(e, () => {
|
|
2361
|
+
e.pragma("optimize"), !Kr(e) && (!q(e, "memory_items") || !q(e, "memory_fts") || (e.exec("ANALYZE"), e.pragma("optimize")));
|
|
2362
|
+
});
|
|
2363
|
+
}
|
|
2364
|
+
function Jr(e) {
|
|
2365
|
+
let t = e?.code;
|
|
2366
|
+
return t === "SQLITE_BUSY" || t === "SQLITE_LOCKED";
|
|
2367
|
+
}
|
|
2368
|
+
function Yr(e) {
|
|
2369
|
+
Xr(e, () => e.pragma("optimize"));
|
|
2370
|
+
}
|
|
2371
|
+
function Xr(e, t) {
|
|
2372
|
+
let n = e.pragma("busy_timeout", { simple: !0 });
|
|
2373
|
+
e.pragma("busy_timeout = 0");
|
|
2374
|
+
try {
|
|
2375
|
+
t();
|
|
2376
|
+
} catch (e) {
|
|
2377
|
+
if (!Jr(e)) throw e;
|
|
2378
|
+
} finally {
|
|
2379
|
+
e.pragma(`busy_timeout = ${Number(n) || 0}`);
|
|
2380
|
+
}
|
|
2381
|
+
}
|
|
2382
|
+
function Zr(e) {
|
|
2383
|
+
Or(e);
|
|
2384
|
+
let t = V(e);
|
|
2385
|
+
if (t === 0) throw Error("Database schema is not initialized. Initialize the SQLite database with the current TypeScript runtime before retrying.");
|
|
2386
|
+
if (t < 6) throw Error(`Database schema version ${t} is older than minimum compatible (6). Upgrade the database schema with the current TypeScript runtime before retrying.`);
|
|
2387
|
+
t > 21 && console.warn(`Database schema version ${t} is newer than this TS runtime (21). Running in compatibility mode — additive schema changes are tolerated.`);
|
|
2388
|
+
let n = nn.filter((t) => !q(e, t));
|
|
2389
|
+
if (n.length > 0) throw Error(`Required tables missing: ${n.join(", ")}. The database may be corrupt or from an incompatible version.`);
|
|
2390
|
+
if (!q(e, "memory_fts")) throw Error("FTS5 index (memory_fts) is missing. Rebuild the database schema with the current TypeScript runtime before retrying.");
|
|
2391
|
+
}
|
|
2392
|
+
function q(e, t) {
|
|
2393
|
+
return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(t) !== void 0;
|
|
2394
|
+
}
|
|
2395
|
+
function J(e, t, n) {
|
|
2396
|
+
return q(e, t) ? e.prepare("SELECT 1 FROM pragma_table_info(?) WHERE name = ? LIMIT 1").get(t, n) !== void 0 : !1;
|
|
2397
|
+
}
|
|
2398
|
+
function Y(e, t, n, r) {
|
|
2399
|
+
if (!J(e, t, n)) try {
|
|
2400
|
+
e.exec(`ALTER TABLE ${t} ADD COLUMN ${n} ${r}`);
|
|
2401
|
+
} catch (r) {
|
|
2402
|
+
if ((r instanceof Error ? r.message.toLowerCase() : "").includes("duplicate column name") && J(e, t, n)) return;
|
|
2403
|
+
throw r;
|
|
2404
|
+
}
|
|
2405
|
+
}
|
|
2406
|
+
var Qr = "recipient_policy_device_eligibility_schema_incompatible";
|
|
2407
|
+
function $r(e) {
|
|
2408
|
+
!q(e, "identity_devices") || !J(e, "identity_devices", "identity_id") || !J(e, "identity_devices", "assignment_version") || !q(e, "policy_team_device_decisions") || !J(e, "policy_team_device_decisions", "device_id") || un(e) || e.transaction(() => e.exec(cn)).immediate();
|
|
2409
|
+
}
|
|
2410
|
+
function ei(e) {
|
|
2411
|
+
e.exec("\n CREATE TABLE IF NOT EXISTS device_identity_binding_commits (\n commit_digest TEXT PRIMARY KEY NOT NULL,\n reviewed_inventory_digest TEXT NOT NULL,\n request_json TEXT NOT NULL,\n outcomes_json TEXT NOT NULL,\n write_count INTEGER NOT NULL,\n decided_by_identity_id TEXT NOT NULL,\n decided_by_device_id TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS device_identity_binding_audit (\n event_id TEXT PRIMARY KEY NOT NULL,\n commit_digest TEXT NOT NULL REFERENCES device_identity_binding_commits(commit_digest),\n device_id TEXT NOT NULL,\n previous_identity_id TEXT,\n target_identity_id TEXT NOT NULL,\n action TEXT NOT NULL,\n previous_assignment_version INTEGER,\n resulting_assignment_version INTEGER NOT NULL,\n decided_by_identity_id TEXT NOT NULL,\n decided_by_device_id TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n CREATE UNIQUE INDEX IF NOT EXISTS idx_device_identity_binding_audit_commit_device\n ON device_identity_binding_audit(commit_digest, device_id);\n CREATE INDEX IF NOT EXISTS idx_device_identity_binding_audit_device_created\n ON device_identity_binding_audit(device_id, created_at, event_id);\n ");
|
|
2412
|
+
}
|
|
2413
|
+
function ti(e) {
|
|
2414
|
+
if (q(e, "memory_items")) try {
|
|
2415
|
+
e.exec("CREATE INDEX IF NOT EXISTS idx_memory_items_created_id ON memory_items(created_at, id)");
|
|
2416
|
+
} catch {}
|
|
2417
|
+
}
|
|
2418
|
+
function ni(e) {
|
|
2419
|
+
if (q(e, "sessions")) try {
|
|
2420
|
+
e.exec("CREATE INDEX IF NOT EXISTS idx_sessions_started_id ON sessions(started_at, id)");
|
|
2421
|
+
} catch {}
|
|
2422
|
+
}
|
|
2423
|
+
function ri(e) {
|
|
2424
|
+
if (q(e, "sync_attempts")) try {
|
|
2425
|
+
e.exec("\n CREATE INDEX IF NOT EXISTS idx_sync_attempts_occurred\n ON sync_attempts(\n CASE WHEN finished_at IS NULL THEN started_at ELSE finished_at END,\n id\n );\n CREATE INDEX IF NOT EXISTS idx_sync_attempts_error_occurred\n ON sync_attempts(\n CASE WHEN finished_at IS NULL THEN started_at ELSE finished_at END,\n id\n )\n WHERE ok = 0;\n CREATE INDEX IF NOT EXISTS idx_sync_attempts_success_occurred\n ON sync_attempts(\n CASE WHEN finished_at IS NULL THEN started_at ELSE finished_at END,\n id\n )\n WHERE ok <> 0;\n ");
|
|
2426
|
+
} catch {}
|
|
2427
|
+
}
|
|
2428
|
+
function ii(e) {
|
|
2429
|
+
if (q(e, "raw_event_sessions")) try {
|
|
2430
|
+
e.exec("CREATE INDEX IF NOT EXISTS idx_raw_event_sessions_pending_updated\n ON raw_event_sessions(updated_at)\n WHERE last_received_event_seq > last_flushed_event_seq");
|
|
2431
|
+
} catch {}
|
|
2432
|
+
}
|
|
2433
|
+
function ai(e) {
|
|
2434
|
+
if (q(e, "raw_event_flush_batches")) try {
|
|
2435
|
+
e.exec("\n CREATE INDEX IF NOT EXISTS idx_flush_batches_observer_status_updated\n ON raw_event_flush_batches(status, updated_at)\n WHERE observer_provider IS NOT NULL;\n CREATE INDEX IF NOT EXISTS idx_flush_batches_capture_status_updated\n ON raw_event_flush_batches(status, updated_at)\n WHERE observer_provider IS NULL;\n ");
|
|
2436
|
+
} catch {}
|
|
2437
|
+
}
|
|
2438
|
+
function oi(e) {
|
|
2439
|
+
if (![
|
|
2440
|
+
"policy_teams",
|
|
2441
|
+
"policy_team_memberships",
|
|
2442
|
+
"identity_devices",
|
|
2443
|
+
"project_recipients",
|
|
2444
|
+
"policy_team_device_decisions"
|
|
2445
|
+
].some((t) => q(e, t))) return;
|
|
2446
|
+
let t = [];
|
|
2447
|
+
for (let [n, r] of [["policy_teams", "device_eligibility_mode"], ["identity_devices", "assignment_version"]]) try {
|
|
2448
|
+
J(e, n, r) || t.push(`${n}.${r}`);
|
|
2449
|
+
} catch {
|
|
2450
|
+
t.push(`${n}.${r}`);
|
|
2451
|
+
}
|
|
2452
|
+
for (let n of [
|
|
2453
|
+
"team_id",
|
|
2454
|
+
"device_id",
|
|
2455
|
+
"decision",
|
|
2456
|
+
"assignment_version"
|
|
2457
|
+
]) try {
|
|
2458
|
+
J(e, "policy_team_device_decisions", n) || t.push(`policy_team_device_decisions.${n}`);
|
|
2459
|
+
} catch {
|
|
2460
|
+
t.push(`policy_team_device_decisions.${n}`);
|
|
2461
|
+
}
|
|
2462
|
+
if (t.length > 0) throw Error(`${Qr}:${t.join(",")}`);
|
|
2463
|
+
}
|
|
2464
|
+
function si(e) {
|
|
2465
|
+
q(e, "sync_peers") && (Y(e, "sync_peers", "runtime_version", "TEXT"), Y(e, "sync_peers", "runtime_version_observed_at", "TEXT"), Y(e, "sync_peers", "sync_features_json", "TEXT"), Y(e, "sync_peers", "sync_features_observed_at", "TEXT"), Y(e, "sync_peers", "relay_retry_after", "TEXT"), Y(e, "sync_peers", "relay_rejections", "INTEGER NOT NULL DEFAULT 0"));
|
|
2466
|
+
}
|
|
2467
|
+
function ci(e) {
|
|
2468
|
+
q(e, "sync_attempts") && Y(e, "sync_attempts", "failure_category", "TEXT");
|
|
2469
|
+
}
|
|
2470
|
+
function li(e) {
|
|
2471
|
+
q(e, "sync_attempts") && Y(e, "sync_attempts", "transport", "TEXT");
|
|
2472
|
+
}
|
|
2473
|
+
function ui(e, t, n) {
|
|
2474
|
+
if (!Number.isSafeInteger(n) || n < 1) throw RangeError("Direct signature version must be a positive safe integer");
|
|
2475
|
+
return e.transaction(() => {
|
|
2476
|
+
let r = e.prepare("INSERT INTO sync_peer_signature_state(\n peer_device_id, highest_observed_direct_signature_version\n )\n SELECT ?, ?\n WHERE EXISTS (\n SELECT 1 FROM sync_peers WHERE peer_device_id = ?\n )\n ON CONFLICT(peer_device_id) DO UPDATE SET\n highest_observed_direct_signature_version = excluded.highest_observed_direct_signature_version\n WHERE sync_peer_signature_state.highest_observed_direct_signature_version\n < excluded.highest_observed_direct_signature_version").run(t, n, t);
|
|
2477
|
+
return e.prepare("UPDATE sync_peers\n SET highest_observed_direct_signature_version = ?\n WHERE peer_device_id = ?\n AND (\n highest_observed_direct_signature_version IS NULL\n OR highest_observed_direct_signature_version < ?\n )").run(n, t, n), r.changes > 0;
|
|
2478
|
+
})();
|
|
2479
|
+
}
|
|
2480
|
+
function di(e) {
|
|
2481
|
+
try {
|
|
2482
|
+
let t = e.prepare("SELECT applied_schema_version AS v FROM schema_compat_state WHERE id = 1 LIMIT 1").get();
|
|
2483
|
+
return typeof t?.v == "number" && t.v >= 21;
|
|
2484
|
+
} catch {
|
|
2485
|
+
return !1;
|
|
2486
|
+
}
|
|
2487
|
+
}
|
|
2488
|
+
function fi(e) {
|
|
2489
|
+
try {
|
|
2490
|
+
e.prepare("INSERT INTO schema_compat_state(id, applied_schema_version, applied_at)\n VALUES (1, ?, ?)\n ON CONFLICT(id) DO UPDATE SET\n applied_schema_version = excluded.applied_schema_version,\n applied_at = excluded.applied_at").run(21, (/* @__PURE__ */ new Date()).toISOString());
|
|
2491
|
+
} catch {}
|
|
2492
|
+
}
|
|
2493
|
+
function pi(e) {
|
|
2494
|
+
try {
|
|
2495
|
+
if (!e.prepare("SELECT 1 FROM memory_items AS m\n JOIN sessions AS s ON s.id = m.session_id\n WHERE m.project IS NULL AND s.project IS NOT NULL\n LIMIT 1").get()) return;
|
|
2496
|
+
e.exec("UPDATE memory_items\n SET project = (\n SELECT s.project FROM sessions s\n WHERE s.id = memory_items.session_id\n )\n WHERE project IS NULL");
|
|
2497
|
+
} catch {}
|
|
2498
|
+
}
|
|
2499
|
+
function mi(e, t) {
|
|
2500
|
+
let n = t.replaceAll("\"", "\"\"");
|
|
2501
|
+
return e.prepare(`PRAGMA index_info("${n}")`).all().map((e) => String(e.name ?? "")).filter(Boolean);
|
|
2502
|
+
}
|
|
2503
|
+
var hi = "CREATE INDEX idx_share_operation_steps_effect_id_nonempty ON share_operation_steps(effect_id) WHERE effect_id <> ''";
|
|
2504
|
+
function gi(e) {
|
|
2505
|
+
return e.replace(/\s+/g, " ").replace(/\s*\(\s*/g, "(").replace(/\s*\)\s*/g, ") ").trim();
|
|
2506
|
+
}
|
|
2507
|
+
function _i(e) {
|
|
2508
|
+
let t = e.prepare("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = 'idx_share_operation_steps_effect_id_nonempty'").get();
|
|
2509
|
+
return typeof t?.sql == "string" && gi(t.sql) === gi(hi);
|
|
2510
|
+
}
|
|
2511
|
+
function vi(e) {
|
|
2512
|
+
if (!q(e, "share_operation_steps") || !J(e, "share_operation_steps", "effect_id")) return;
|
|
2513
|
+
let t = e.prepare("PRAGMA index_list('share_operation_steps')").all().some((t) => t.unique === 1 && t.name !== "idx_share_operation_steps_effect_id_nonempty" && mi(e, t.name).join(",") === "effect_id");
|
|
2514
|
+
t && e.transaction(() => {
|
|
2515
|
+
e.exec("\n DROP INDEX IF EXISTS idx_share_operation_steps_effect_id_nonempty;\n ALTER TABLE share_operation_steps RENAME TO share_operation_steps_unique_legacy;\n CREATE TABLE share_operation_steps (\n operation_id TEXT NOT NULL,\n step_key TEXT NOT NULL,\n effect_id TEXT NOT NULL,\n status TEXT NOT NULL,\n attempt_count INTEGER NOT NULL DEFAULT 0,\n started_at TEXT,\n completed_at TEXT,\n last_attempt_at TEXT,\n safe_error_code TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (operation_id, step_key)\n );\n INSERT INTO share_operation_steps(\n operation_id, step_key, effect_id, status, attempt_count, started_at,\n completed_at, last_attempt_at, safe_error_code, updated_at\n ) SELECT operation_id, step_key, effect_id, status, attempt_count, started_at,\n completed_at, last_attempt_at, safe_error_code, updated_at\n FROM share_operation_steps_unique_legacy;\n DROP TABLE share_operation_steps_unique_legacy;\n ");
|
|
2516
|
+
})(), !(!t && _i(e)) && e.exec("\n DROP INDEX IF EXISTS idx_share_operation_steps_effect_id_nonempty;\n CREATE INDEX IF NOT EXISTS idx_share_operation_steps_effect_id_nonempty\n ON share_operation_steps(effect_id)\n WHERE effect_id <> '';\n ");
|
|
2517
|
+
}
|
|
2518
|
+
var yi = !1;
|
|
2519
|
+
function bi(e) {
|
|
2520
|
+
try {
|
|
2521
|
+
br(e);
|
|
2522
|
+
} catch {
|
|
2523
|
+
yi || (yi = !0, console.warn("[codemem] Retrieval evidence storage is unavailable; continuing without attribution data."));
|
|
2524
|
+
}
|
|
2525
|
+
}
|
|
2526
|
+
function xi(e) {
|
|
2527
|
+
for (let [t, n, r] of [
|
|
2528
|
+
[
|
|
2529
|
+
"policy_teams",
|
|
2530
|
+
"device_eligibility_mode",
|
|
2531
|
+
"TEXT NOT NULL DEFAULT 'person_all_devices'"
|
|
2532
|
+
],
|
|
2533
|
+
[
|
|
2534
|
+
"identity_devices",
|
|
2535
|
+
"assignment_version",
|
|
2536
|
+
"INTEGER NOT NULL DEFAULT 0"
|
|
2537
|
+
],
|
|
2538
|
+
[
|
|
2539
|
+
"policy_team_device_decisions",
|
|
2540
|
+
"assignment_version",
|
|
2541
|
+
"INTEGER NOT NULL DEFAULT 0"
|
|
2542
|
+
]
|
|
2543
|
+
]) try {
|
|
2544
|
+
Y(e, t, n, r);
|
|
2545
|
+
} catch {}
|
|
2546
|
+
}
|
|
2547
|
+
function Si(e) {
|
|
2548
|
+
q(e, "recipient_policy_authority_states") && Y(e, "recipient_policy_authority_states", "wake_epoch", "INTEGER NOT NULL DEFAULT 0");
|
|
2549
|
+
}
|
|
2550
|
+
function Ci(e) {
|
|
2551
|
+
if (Sn(e), Qn(e), q(e, "sync_peers") && !J(e, "sync_peers", "manual_addresses_json")) try {
|
|
2552
|
+
e.exec("ALTER TABLE sync_peers ADD COLUMN manual_addresses_json TEXT");
|
|
2553
|
+
} catch (t) {
|
|
2554
|
+
if (!J(e, "sync_peers", "manual_addresses_json")) throw t;
|
|
2555
|
+
}
|
|
2556
|
+
if (q(e, "sync_peers") && !J(e, "sync_peers", "last_success_address")) try {
|
|
2557
|
+
e.exec("ALTER TABLE sync_peers ADD COLUMN last_success_address TEXT");
|
|
2558
|
+
} catch (t) {
|
|
2559
|
+
if (!J(e, "sync_peers", "last_success_address")) throw t;
|
|
2560
|
+
}
|
|
2561
|
+
gn(e), bi(e);
|
|
2562
|
+
try {
|
|
2563
|
+
Nn(e);
|
|
2564
|
+
} catch {}
|
|
2565
|
+
Si(e), si(e), ci(e), li(e), Dr(e), vr(e), ei(e), or(e), ti(e), ni(e), ri(e), ii(e);
|
|
2566
|
+
}
|
|
2567
|
+
function wi(e) {
|
|
2568
|
+
bn(e), Ci(e);
|
|
2569
|
+
let t = di(e);
|
|
2570
|
+
Ei(e, { compatAlreadyApplied: t }), G(e), H(e), tr(e), Yn(e), Kn(e), t || (Ti(e), fi(e));
|
|
2571
|
+
}
|
|
2572
|
+
function Ti(e) {
|
|
2573
|
+
let t = [
|
|
2574
|
+
"coordinator_enrollment_reconciliation_issues",
|
|
2575
|
+
"policy_teams",
|
|
2576
|
+
"policy_team_memberships",
|
|
2577
|
+
"policy_team_device_decisions",
|
|
2578
|
+
"identity_devices",
|
|
2579
|
+
"project_recipients",
|
|
2580
|
+
"recipient_managed_project_projections",
|
|
2581
|
+
"recipient_policy_authority_states",
|
|
2582
|
+
"recipient_policy_reconciliation_steps",
|
|
2583
|
+
"recipient_policy_deny_overlays"
|
|
2584
|
+
].every((t) => q(e, t)), n = V(e);
|
|
2585
|
+
t && n > 0 && n < 21 && e.pragma("user_version = 21");
|
|
2586
|
+
}
|
|
2587
|
+
function Ei(e, { compatAlreadyApplied: t }) {
|
|
2588
|
+
if (!t) {
|
|
2589
|
+
try {
|
|
2590
|
+
e.exec("\n CREATE TABLE IF NOT EXISTS schema_compat_state (\n id INTEGER PRIMARY KEY CHECK (id = 1),\n applied_schema_version INTEGER NOT NULL,\n applied_at TEXT NOT NULL\n )\n ");
|
|
2591
|
+
} catch {}
|
|
2592
|
+
try {
|
|
2593
|
+
e.exec("\n CREATE TABLE IF NOT EXISTS coordinator_enrollment_reconciliation_issues (\n coordinator_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n kind TEXT NOT NULL,\n reference_id TEXT NOT NULL,\n code TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'open',\n first_seen_at TEXT NOT NULL,\n last_seen_at TEXT NOT NULL,\n resolved_at TEXT,\n occurrence_count INTEGER NOT NULL DEFAULT 1,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (coordinator_id, group_id, kind, reference_id, code)\n );\n CREATE INDEX IF NOT EXISTS idx_coordinator_enrollment_issues_boundary_status\n ON coordinator_enrollment_reconciliation_issues(coordinator_id, group_id, status);\n CREATE INDEX IF NOT EXISTS idx_coordinator_enrollment_issues_status_recent\n ON coordinator_enrollment_reconciliation_issues(status, last_seen_at, resolved_at);\n CREATE TABLE IF NOT EXISTS recipient_policy_review_resolutions (\n review_item_id TEXT NOT NULL,\n source_fingerprint TEXT NOT NULL,\n decision TEXT NOT NULL,\n decision_input_json TEXT NOT NULL,\n preview_json TEXT NOT NULL,\n decided_by_identity_id TEXT NOT NULL,\n decided_by_device_id TEXT NOT NULL,\n resolved_at TEXT NOT NULL,\n PRIMARY KEY (review_item_id, source_fingerprint)\n );\n CREATE TABLE IF NOT EXISTS policy_teams (\n team_id TEXT PRIMARY KEY NOT NULL,\n display_name TEXT NOT NULL,\n status TEXT NOT NULL,\n device_eligibility_mode TEXT NOT NULL DEFAULT 'person_all_devices',\n provenance TEXT NOT NULL,\n revision TEXT NOT NULL,\n migration_state TEXT NOT NULL,\n source_fingerprint TEXT,\n idempotency_key TEXT NOT NULL UNIQUE,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS policy_team_memberships (\n team_id TEXT NOT NULL,\n identity_id TEXT NOT NULL,\n role TEXT NOT NULL,\n status TEXT NOT NULL,\n provenance TEXT NOT NULL,\n revision TEXT NOT NULL,\n migration_state TEXT NOT NULL,\n source_fingerprint TEXT,\n idempotency_key TEXT NOT NULL UNIQUE,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (team_id, identity_id)\n );\n CREATE TABLE IF NOT EXISTS identity_devices (\n device_id TEXT PRIMARY KEY NOT NULL,\n identity_id TEXT NOT NULL,\n display_name TEXT NOT NULL,\n status TEXT NOT NULL,\n provenance TEXT NOT NULL,\n revision TEXT NOT NULL,\n migration_state TEXT NOT NULL,\n assignment_version INTEGER NOT NULL DEFAULT 0,\n source_fingerprint TEXT,\n idempotency_key TEXT NOT NULL UNIQUE,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS policy_team_device_decisions (\n team_id TEXT NOT NULL REFERENCES policy_teams(team_id) ON DELETE CASCADE,\n device_id TEXT NOT NULL,\n decision TEXT NOT NULL,\n assignment_version INTEGER NOT NULL DEFAULT 0,\n provenance TEXT NOT NULL,\n revision TEXT NOT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (team_id, device_id)\n );\n CREATE INDEX IF NOT EXISTS idx_policy_team_device_decisions_device\n ON policy_team_device_decisions(device_id);\n CREATE TABLE IF NOT EXISTS project_recipients (\n canonical_project_identity TEXT NOT NULL,\n recipient_kind TEXT NOT NULL,\n recipient_id TEXT NOT NULL,\n status TEXT NOT NULL,\n provenance TEXT NOT NULL,\n policy_revision TEXT NOT NULL,\n migration_state TEXT NOT NULL,\n source_fingerprint TEXT,\n idempotency_key TEXT NOT NULL UNIQUE,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (canonical_project_identity, recipient_kind, recipient_id)\n );\n CREATE TABLE IF NOT EXISTS recipient_policy_authority_states (\n canonical_project_identity TEXT PRIMARY KEY NOT NULL,\n authority_state TEXT NOT NULL DEFAULT 'legacy',\n generation INTEGER NOT NULL DEFAULT 0,\n desired_devices_digest TEXT,\n current_devices_digest TEXT,\n stable_parity_evidence_digest TEXT,\n stable_parity_passed_at TEXT,\n fresh_snapshot_fingerprint TEXT,\n fresh_snapshot_observed_at TEXT,\n safe_error_code TEXT,\n state_changed_at TEXT NOT NULL,\n last_error_at TEXT,\n attempt_count INTEGER NOT NULL DEFAULT 0,\n last_attempt_at TEXT,\n wake_epoch INTEGER NOT NULL DEFAULT 0,\n last_completed_at TEXT,\n lease_owner TEXT,\n lease_acquired_at TEXT,\n lease_expires_at TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS recipient_policy_reconciliation_steps (\n canonical_project_identity TEXT NOT NULL,\n generation INTEGER NOT NULL,\n step_key TEXT NOT NULL,\n effect_id TEXT NOT NULL,\n payload_digest TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'pending',\n attempt_count INTEGER NOT NULL DEFAULT 0,\n started_at TEXT,\n completed_at TEXT,\n last_attempt_at TEXT,\n safe_error_code TEXT,\n error_at TEXT,\n lease_owner TEXT,\n lease_acquired_at TEXT,\n lease_expires_at TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (canonical_project_identity, generation, step_key)\n );\n CREATE UNIQUE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_effect\n ON recipient_policy_reconciliation_steps(effect_id);\n CREATE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_status\n ON recipient_policy_reconciliation_steps(canonical_project_identity, status);\n CREATE INDEX IF NOT EXISTS idx_recipient_policy_reconciliation_steps_pending_refresh\n ON recipient_policy_reconciliation_steps(canonical_project_identity, generation, step_key)\n WHERE status IN ('pending', 'running', 'failed')\n AND step_key GLOB 'refresh-after-revocations-v2:*';\n CREATE TABLE IF NOT EXISTS recipient_policy_deny_overlays (\n canonical_project_identity TEXT NOT NULL,\n scope_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n generation INTEGER NOT NULL,\n reason_code TEXT NOT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (canonical_project_identity, scope_id, device_id)\n );\n CREATE INDEX IF NOT EXISTS idx_recipient_policy_deny_overlays_scope_device\n ON recipient_policy_deny_overlays(scope_id, device_id);\n CREATE INDEX IF NOT EXISTS idx_policy_team_memberships_identity_status\n ON policy_team_memberships(identity_id, status);\n CREATE INDEX IF NOT EXISTS idx_identity_devices_identity_status\n ON identity_devices(identity_id, status);\n CREATE INDEX IF NOT EXISTS idx_project_recipients_project_status\n ON project_recipients(canonical_project_identity, status);\n CREATE INDEX IF NOT EXISTS idx_project_recipients_recipient_status\n ON project_recipients(recipient_kind, recipient_id, status);\n CREATE TABLE IF NOT EXISTS recipient_managed_project_projections (\n canonical_project_identity TEXT NOT NULL,\n display_name TEXT NOT NULL,\n managed_scope_id TEXT NOT NULL,\n coordinator_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n recipient_identity_id TEXT NOT NULL,\n accepting_device_id TEXT NOT NULL,\n source_operation_id TEXT NOT NULL,\n reviewed_project_set_digest TEXT NOT NULL,\n status TEXT NOT NULL DEFAULT 'active',\n accepted_at TEXT NOT NULL,\n revoked_at TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (source_operation_id, canonical_project_identity)\n );\n CREATE INDEX IF NOT EXISTS idx_recipient_managed_projects_identity_status\n ON recipient_managed_project_projections(recipient_identity_id, status);\n CREATE INDEX IF NOT EXISTS idx_recipient_managed_projects_scope_authority\n ON recipient_managed_project_projections(\n managed_scope_id, coordinator_id, group_id, status\n );\n CREATE TABLE IF NOT EXISTS share_operations (\n operation_id TEXT PRIMARY KEY NOT NULL,\n state TEXT NOT NULL,\n inviter_actor_id TEXT NOT NULL,\n inviter_device_ids_json TEXT NOT NULL,\n person_id TEXT NOT NULL,\n person_kind TEXT NOT NULL,\n pending_person_operation_id TEXT,\n teammate_name TEXT NOT NULL,\n history_policy TEXT NOT NULL,\n reviewed_project_set_digest TEXT NOT NULL,\n coordinator_group_id TEXT NOT NULL,\n coordinator_invite_id TEXT,\n invite_token_digest TEXT NOT NULL,\n invite_expires_at TEXT NOT NULL,\n recipient_actor_id TEXT,\n recipient_display_name TEXT,\n recipient_device_id TEXT,\n recipient_device_display_name TEXT,\n recipient_public_key TEXT,\n recipient_fingerprint TEXT,\n acceptance_consumed_at TEXT,\n trust_state TEXT,\n bootstrap_grant_id TEXT,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE TABLE IF NOT EXISTS share_operation_projects (\n operation_id TEXT NOT NULL,\n canonical_project_identity TEXT NOT NULL,\n display_name TEXT NOT NULL,\n identity_source TEXT NOT NULL,\n existing_memory_count INTEGER NOT NULL,\n ordinal INTEGER NOT NULL,\n PRIMARY KEY (operation_id, canonical_project_identity)\n );\n CREATE TABLE IF NOT EXISTS share_operation_steps (\n operation_id TEXT NOT NULL,\n step_key TEXT NOT NULL,\n effect_id TEXT NOT NULL,\n status TEXT NOT NULL,\n attempt_count INTEGER NOT NULL DEFAULT 0,\n started_at TEXT,\n completed_at TEXT,\n last_attempt_at TEXT,\n safe_error_code TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (operation_id, step_key)\n );\n ");
|
|
2594
|
+
} catch {}
|
|
2595
|
+
xi(e);
|
|
2596
|
+
for (let [t, n] of [
|
|
2597
|
+
["state", "TEXT NOT NULL DEFAULT 'waiting_for_acceptance'"],
|
|
2598
|
+
["inviter_actor_id", "TEXT NOT NULL DEFAULT ''"],
|
|
2599
|
+
["inviter_device_ids_json", "TEXT NOT NULL DEFAULT '[]'"],
|
|
2600
|
+
["person_id", "TEXT NOT NULL DEFAULT ''"],
|
|
2601
|
+
["person_kind", "TEXT NOT NULL DEFAULT 'pending'"],
|
|
2602
|
+
["pending_person_operation_id", "TEXT"],
|
|
2603
|
+
["teammate_name", "TEXT NOT NULL DEFAULT ''"],
|
|
2604
|
+
["history_policy", "TEXT NOT NULL DEFAULT 'existing_and_future'"],
|
|
2605
|
+
["reviewed_project_set_digest", "TEXT NOT NULL DEFAULT ''"],
|
|
2606
|
+
["coordinator_group_id", "TEXT NOT NULL DEFAULT ''"],
|
|
2607
|
+
["coordinator_invite_id", "TEXT"],
|
|
2608
|
+
["invite_token_digest", "TEXT NOT NULL DEFAULT ''"],
|
|
2609
|
+
["invite_expires_at", "TEXT NOT NULL DEFAULT ''"],
|
|
2610
|
+
["recipient_actor_id", "TEXT"],
|
|
2611
|
+
["recipient_display_name", "TEXT"],
|
|
2612
|
+
["recipient_device_id", "TEXT"],
|
|
2613
|
+
["recipient_device_display_name", "TEXT"],
|
|
2614
|
+
["recipient_public_key", "TEXT"],
|
|
2615
|
+
["recipient_fingerprint", "TEXT"],
|
|
2616
|
+
["acceptance_consumed_at", "TEXT"],
|
|
2617
|
+
["trust_state", "TEXT"],
|
|
2618
|
+
["bootstrap_grant_id", "TEXT"],
|
|
2619
|
+
["created_at", "TEXT NOT NULL DEFAULT ''"],
|
|
2620
|
+
["updated_at", "TEXT NOT NULL DEFAULT ''"]
|
|
2621
|
+
]) try {
|
|
2622
|
+
Y(e, "share_operations", t, n);
|
|
2623
|
+
} catch {}
|
|
2624
|
+
for (let [t, n] of [["share_operation_projects", [
|
|
2625
|
+
["display_name", "TEXT NOT NULL DEFAULT ''"],
|
|
2626
|
+
["identity_source", "TEXT NOT NULL DEFAULT ''"],
|
|
2627
|
+
["existing_memory_count", "INTEGER NOT NULL DEFAULT 0"],
|
|
2628
|
+
["ordinal", "INTEGER NOT NULL DEFAULT 0"]
|
|
2629
|
+
]], ["share_operation_steps", [
|
|
2630
|
+
["effect_id", "TEXT NOT NULL DEFAULT ''"],
|
|
2631
|
+
["status", "TEXT NOT NULL DEFAULT 'pending'"],
|
|
2632
|
+
["attempt_count", "INTEGER NOT NULL DEFAULT 0"],
|
|
2633
|
+
["started_at", "TEXT"],
|
|
2634
|
+
["completed_at", "TEXT"],
|
|
2635
|
+
["last_attempt_at", "TEXT"],
|
|
2636
|
+
["safe_error_code", "TEXT"],
|
|
2637
|
+
["updated_at", "TEXT NOT NULL DEFAULT ''"]
|
|
2638
|
+
]]]) for (let [r, i] of n) try {
|
|
2639
|
+
Y(e, t, r, i);
|
|
2640
|
+
} catch {}
|
|
2641
|
+
try {
|
|
2642
|
+
e.exec("\n CREATE INDEX IF NOT EXISTS idx_share_operations_state_updated\n ON share_operations(state, updated_at);\n CREATE UNIQUE INDEX IF NOT EXISTS idx_share_operations_invite_digest\n ON share_operations(invite_token_digest);\n CREATE UNIQUE INDEX IF NOT EXISTS idx_share_operations_pending_person_operation\n ON share_operations(pending_person_operation_id)\n WHERE pending_person_operation_id IS NOT NULL;\n ");
|
|
2643
|
+
} catch {}
|
|
2644
|
+
try {
|
|
2645
|
+
e.exec("\n CREATE TABLE IF NOT EXISTS sync_reset_state (\n id INTEGER PRIMARY KEY,\n generation INTEGER NOT NULL,\n snapshot_id TEXT NOT NULL,\n baseline_cursor TEXT,\n retained_floor_cursor TEXT,\n updated_at TEXT NOT NULL\n )\n ");
|
|
2646
|
+
} catch {}
|
|
2647
|
+
try {
|
|
2648
|
+
e.exec("\n CREATE TABLE IF NOT EXISTS sync_scope_rejections (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n peer_device_id TEXT,\n op_id TEXT NOT NULL,\n entity_type TEXT NOT NULL,\n entity_id TEXT NOT NULL,\n scope_id TEXT,\n reason TEXT NOT NULL,\n created_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_peer_created\n ON sync_scope_rejections(peer_device_id, created_at);\n CREATE INDEX IF NOT EXISTS idx_sync_scope_rejections_scope_created\n ON sync_scope_rejections(scope_id, created_at);\n ");
|
|
2649
|
+
} catch {}
|
|
2650
|
+
try {
|
|
2651
|
+
e.exec("\n CREATE TABLE IF NOT EXISTS sync_reset_state_v2 (\n scope_id TEXT PRIMARY KEY NOT NULL,\n generation INTEGER NOT NULL,\n snapshot_id TEXT NOT NULL,\n baseline_cursor TEXT,\n retained_floor_cursor TEXT,\n updated_at TEXT NOT NULL\n );\n\n CREATE TABLE IF NOT EXISTS sync_retention_state_v2 (\n scope_id TEXT PRIMARY KEY NOT NULL,\n last_run_at TEXT,\n last_duration_ms INTEGER,\n last_deleted_ops INTEGER NOT NULL DEFAULT 0,\n last_estimated_bytes_before INTEGER,\n last_estimated_bytes_after INTEGER,\n retained_floor_cursor TEXT,\n last_error TEXT,\n last_error_at TEXT\n );\n\n CREATE TABLE IF NOT EXISTS replication_cursors_v2 (\n peer_device_id TEXT NOT NULL,\n scope_id TEXT NOT NULL,\n last_applied_cursor TEXT,\n last_acked_cursor TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (peer_device_id, scope_id)\n );\n CREATE INDEX IF NOT EXISTS idx_replication_cursors_v2_scope\n ON replication_cursors_v2(scope_id);\n ");
|
|
2652
|
+
} catch {}
|
|
2653
|
+
if (q(e, "sync_reset_state") && q(e, "sync_reset_state_v2")) try {
|
|
2654
|
+
e.exec("\n INSERT OR IGNORE INTO sync_reset_state_v2\n (scope_id, generation, snapshot_id, baseline_cursor, retained_floor_cursor, updated_at)\n SELECT 'local-default', generation, snapshot_id, baseline_cursor, retained_floor_cursor, updated_at\n FROM sync_reset_state\n WHERE id = 1\n ");
|
|
2655
|
+
} catch {}
|
|
2656
|
+
if (q(e, "sync_retention_state") && q(e, "sync_retention_state_v2")) try {
|
|
2657
|
+
e.exec("\n INSERT OR IGNORE INTO sync_retention_state_v2\n (\n scope_id,\n last_run_at,\n last_duration_ms,\n last_deleted_ops,\n last_estimated_bytes_before,\n last_estimated_bytes_after,\n retained_floor_cursor,\n last_error,\n last_error_at\n )\n SELECT\n 'local-default',\n last_run_at,\n last_duration_ms,\n last_deleted_ops,\n last_estimated_bytes_before,\n last_estimated_bytes_after,\n retained_floor_cursor,\n last_error,\n last_error_at\n FROM sync_retention_state\n WHERE id = 1\n ");
|
|
2658
|
+
} catch {}
|
|
2659
|
+
if (q(e, "replication_cursors") && q(e, "replication_cursors_v2")) try {
|
|
2660
|
+
e.exec("\n INSERT OR IGNORE INTO replication_cursors_v2\n (peer_device_id, scope_id, last_applied_cursor, last_acked_cursor, updated_at)\n SELECT peer_device_id, 'local-default', last_applied_cursor, last_acked_cursor, updated_at\n FROM replication_cursors\n ");
|
|
2661
|
+
} catch {}
|
|
2662
|
+
if (q(e, "sync_daemon_state") && !J(e, "sync_daemon_state", "phase")) try {
|
|
2663
|
+
e.exec("ALTER TABLE sync_daemon_state ADD COLUMN phase TEXT");
|
|
2664
|
+
} catch {}
|
|
2665
|
+
if (q(e, "memory_items")) {
|
|
2666
|
+
try {
|
|
2667
|
+
e.exec("CREATE INDEX IF NOT EXISTS idx_memory_items_origin_device_active ON memory_items(origin_device_id, active)");
|
|
2668
|
+
} catch {}
|
|
2669
|
+
if (!J(e, "memory_items", "dedup_key")) try {
|
|
2670
|
+
e.exec("ALTER TABLE memory_items ADD COLUMN dedup_key TEXT");
|
|
2671
|
+
} catch (t) {
|
|
2672
|
+
if (!((t instanceof Error ? t.message.toLowerCase() : "").includes("duplicate column name") && J(e, "memory_items", "dedup_key"))) throw t;
|
|
2673
|
+
}
|
|
2674
|
+
try {
|
|
2675
|
+
e.exec("CREATE INDEX IF NOT EXISTS idx_memory_items_dedup_key_active_created ON memory_items(dedup_key, active, created_at)");
|
|
2676
|
+
} catch {}
|
|
2677
|
+
try {
|
|
2678
|
+
e.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_memory_items_same_session_dedup_unique ON memory_items(session_id, kind, visibility, workspace_id, dedup_key) WHERE active = 1 AND dedup_key IS NOT NULL");
|
|
2679
|
+
} catch {}
|
|
2680
|
+
Y(e, "memory_items", "scope_id", "TEXT");
|
|
2681
|
+
try {
|
|
2682
|
+
e.exec("CREATE INDEX IF NOT EXISTS idx_memory_items_scope_visibility_created ON memory_items(scope_id, visibility, created_at)");
|
|
2683
|
+
} catch {}
|
|
2684
|
+
try {
|
|
2685
|
+
e.exec("CREATE INDEX IF NOT EXISTS idx_memory_items_scope_backfill_pending ON memory_items(id) WHERE scope_id IS NULL OR scope_id = ''");
|
|
2686
|
+
} catch {}
|
|
2687
|
+
Y(e, "memory_items", "project", "TEXT");
|
|
2688
|
+
try {
|
|
2689
|
+
e.exec("CREATE INDEX IF NOT EXISTS idx_memory_items_project ON memory_items(project)");
|
|
2690
|
+
} catch {}
|
|
2691
|
+
try {
|
|
2692
|
+
e.exec("DROP INDEX IF EXISTS idx_memory_items_visibility;\n DROP INDEX IF EXISTS idx_memory_items_workspace_kind;\n DROP INDEX IF EXISTS idx_memory_items_user_prompt_id;");
|
|
2693
|
+
} catch {}
|
|
2694
|
+
}
|
|
2695
|
+
if (q(e, "replication_ops")) {
|
|
2696
|
+
Y(e, "replication_ops", "scope_id", "TEXT");
|
|
2697
|
+
try {
|
|
2698
|
+
e.exec("CREATE INDEX IF NOT EXISTS idx_replication_ops_scope_created ON replication_ops(scope_id, created_at, op_id)");
|
|
2699
|
+
} catch {}
|
|
2700
|
+
}
|
|
2701
|
+
try {
|
|
2702
|
+
e.exec("\n CREATE TABLE IF NOT EXISTS replication_scopes (\n scope_id TEXT PRIMARY KEY NOT NULL,\n label TEXT NOT NULL,\n kind TEXT NOT NULL DEFAULT 'user',\n authority_type TEXT NOT NULL DEFAULT 'local',\n coordinator_id TEXT,\n group_id TEXT,\n manifest_issuer_device_id TEXT,\n membership_epoch INTEGER NOT NULL DEFAULT 0,\n manifest_hash TEXT,\n status TEXT NOT NULL DEFAULT 'active',\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_replication_scopes_status\n ON replication_scopes(status);\n CREATE INDEX IF NOT EXISTS idx_replication_scopes_authority_group\n ON replication_scopes(coordinator_id, group_id);\n\n CREATE TABLE IF NOT EXISTS project_scope_mappings (\n id INTEGER PRIMARY KEY,\n workspace_identity TEXT,\n project_pattern TEXT NOT NULL,\n scope_id TEXT NOT NULL,\n priority INTEGER NOT NULL DEFAULT 0,\n source TEXT NOT NULL DEFAULT 'user',\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL\n );\n CREATE INDEX IF NOT EXISTS idx_project_scope_mappings_workspace_priority\n ON project_scope_mappings(workspace_identity, priority);\n CREATE INDEX IF NOT EXISTS idx_project_scope_mappings_pattern_priority\n ON project_scope_mappings(project_pattern, priority);\n CREATE INDEX IF NOT EXISTS idx_project_scope_mappings_scope\n ON project_scope_mappings(scope_id);\n\n CREATE TABLE IF NOT EXISTS scope_memberships (\n scope_id TEXT NOT NULL,\n device_id TEXT NOT NULL,\n role TEXT NOT NULL DEFAULT 'member',\n status TEXT NOT NULL DEFAULT 'active',\n membership_epoch INTEGER NOT NULL DEFAULT 0,\n coordinator_id TEXT,\n group_id TEXT,\n manifest_issuer_device_id TEXT,\n manifest_hash TEXT,\n signed_manifest_json TEXT,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (scope_id, device_id)\n );\n CREATE INDEX IF NOT EXISTS idx_scope_memberships_device_status\n ON scope_memberships(device_id, status);\n CREATE INDEX IF NOT EXISTS idx_scope_memberships_scope_status\n ON scope_memberships(scope_id, status);\n CREATE INDEX IF NOT EXISTS idx_scope_memberships_authority_group\n ON scope_memberships(coordinator_id, group_id);\n\n CREATE TABLE IF NOT EXISTS scope_membership_cache_state (\n coordinator_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n last_refresh_at TEXT NOT NULL,\n last_success_at TEXT,\n last_error TEXT,\n updated_at TEXT NOT NULL,\n refresh_revision INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (coordinator_id, group_id)\n );\n ");
|
|
2703
|
+
} catch {}
|
|
2704
|
+
if (q(e, "sync_peers")) {
|
|
2705
|
+
for (let t of [
|
|
2706
|
+
"discovered_via_coordinator_id",
|
|
2707
|
+
"discovered_via_group_id",
|
|
2708
|
+
"trust_provenance",
|
|
2709
|
+
"pending_bootstrap_grant_id"
|
|
2710
|
+
]) if (!J(e, "sync_peers", t)) try {
|
|
2711
|
+
e.exec(`ALTER TABLE sync_peers ADD COLUMN ${t} TEXT`);
|
|
2712
|
+
} catch (n) {
|
|
2713
|
+
if ((n instanceof Error ? n.message.toLowerCase() : "").includes("duplicate column name") && J(e, "sync_peers", t)) continue;
|
|
2714
|
+
throw n;
|
|
2715
|
+
}
|
|
2716
|
+
}
|
|
2717
|
+
if (q(e, "sync_attempts")) {
|
|
2718
|
+
for (let t of [
|
|
2719
|
+
"local_sync_capability",
|
|
2720
|
+
"peer_sync_capability",
|
|
2721
|
+
"negotiated_sync_capability"
|
|
2722
|
+
]) if (!J(e, "sync_attempts", t)) try {
|
|
2723
|
+
e.exec(`ALTER TABLE sync_attempts ADD COLUMN ${t} TEXT`);
|
|
2724
|
+
} catch (n) {
|
|
2725
|
+
if ((n instanceof Error ? n.message.toLowerCase() : "").includes("duplicate column name") && J(e, "sync_attempts", t)) continue;
|
|
2726
|
+
throw n;
|
|
2727
|
+
}
|
|
2728
|
+
}
|
|
2729
|
+
try {
|
|
2730
|
+
e.exec("\n CREATE TABLE IF NOT EXISTS coordinator_group_preferences (\n coordinator_id TEXT NOT NULL,\n group_id TEXT NOT NULL,\n projects_include_json TEXT,\n projects_exclude_json TEXT,\n auto_seed_scope INTEGER NOT NULL DEFAULT 1,\n default_space_scope_id TEXT,\n auto_grant_default_space_on_join INTEGER NOT NULL DEFAULT 0,\n updated_at TEXT NOT NULL,\n PRIMARY KEY (coordinator_id, group_id)\n )\n ");
|
|
2731
|
+
} catch {}
|
|
2732
|
+
for (let { name: t, ddl: n } of [{
|
|
2733
|
+
name: "default_space_scope_id",
|
|
2734
|
+
ddl: "TEXT"
|
|
2735
|
+
}, {
|
|
2736
|
+
name: "auto_grant_default_space_on_join",
|
|
2737
|
+
ddl: "INTEGER NOT NULL DEFAULT 0"
|
|
2738
|
+
}]) if (!J(e, "coordinator_group_preferences", t)) try {
|
|
2739
|
+
e.exec(`ALTER TABLE coordinator_group_preferences ADD COLUMN ${t} ${n}`);
|
|
2740
|
+
} catch (e) {
|
|
2741
|
+
if ((e instanceof Error ? e.message.toLowerCase() : "").includes("duplicate column name")) continue;
|
|
2742
|
+
throw e;
|
|
2743
|
+
}
|
|
2744
|
+
if (q(e, "raw_event_flush_batches")) {
|
|
2745
|
+
for (let { name: t, ddl: n } of [
|
|
2746
|
+
{
|
|
2747
|
+
name: "error_message",
|
|
2748
|
+
ddl: "TEXT"
|
|
2749
|
+
},
|
|
2750
|
+
{
|
|
2751
|
+
name: "error_type",
|
|
2752
|
+
ddl: "TEXT"
|
|
2753
|
+
},
|
|
2754
|
+
{
|
|
2755
|
+
name: "observer_provider",
|
|
2756
|
+
ddl: "TEXT"
|
|
2757
|
+
},
|
|
2758
|
+
{
|
|
2759
|
+
name: "observer_model",
|
|
2760
|
+
ddl: "TEXT"
|
|
2761
|
+
},
|
|
2762
|
+
{
|
|
2763
|
+
name: "observer_runtime",
|
|
2764
|
+
ddl: "TEXT"
|
|
2765
|
+
},
|
|
2766
|
+
{
|
|
2767
|
+
name: "observer_auth_source",
|
|
2768
|
+
ddl: "TEXT"
|
|
2769
|
+
},
|
|
2770
|
+
{
|
|
2771
|
+
name: "observer_auth_type",
|
|
2772
|
+
ddl: "TEXT"
|
|
2773
|
+
},
|
|
2774
|
+
{
|
|
2775
|
+
name: "observer_error_code",
|
|
2776
|
+
ddl: "TEXT"
|
|
2777
|
+
},
|
|
2778
|
+
{
|
|
2779
|
+
name: "observer_error_message",
|
|
2780
|
+
ddl: "TEXT"
|
|
2781
|
+
},
|
|
2782
|
+
{
|
|
2783
|
+
name: "attempt_count",
|
|
2784
|
+
ddl: "INTEGER NOT NULL DEFAULT 0"
|
|
2785
|
+
}
|
|
2786
|
+
]) if (!J(e, "raw_event_flush_batches", t)) try {
|
|
2787
|
+
e.exec(`ALTER TABLE raw_event_flush_batches ADD COLUMN ${t} ${n}`);
|
|
2788
|
+
} catch (n) {
|
|
2789
|
+
if ((n instanceof Error ? n.message.toLowerCase() : "").includes("duplicate column name") && J(e, "raw_event_flush_batches", t)) continue;
|
|
2790
|
+
throw n;
|
|
2791
|
+
}
|
|
2792
|
+
}
|
|
2793
|
+
}
|
|
2794
|
+
ai(e), oi(e), $r(e);
|
|
2795
|
+
try {
|
|
2796
|
+
vi(e);
|
|
2797
|
+
} catch {}
|
|
2798
|
+
pi(e);
|
|
2799
|
+
}
|
|
2800
|
+
function Di(e) {
|
|
2801
|
+
if (!e) return {};
|
|
2802
|
+
try {
|
|
2803
|
+
let t = JSON.parse(e);
|
|
2804
|
+
return typeof t != "object" || !t || Array.isArray(t) ? {} : t;
|
|
2805
|
+
} catch {
|
|
2806
|
+
return console.warn(`[codemem] fromJson: invalid JSON (${e.slice(0, 80)}...)`), {};
|
|
2807
|
+
}
|
|
2808
|
+
}
|
|
2809
|
+
function Oi(e) {
|
|
2810
|
+
if (!e) return {};
|
|
2811
|
+
let t = JSON.parse(e);
|
|
2812
|
+
if (typeof t != "object" || !t || Array.isArray(t)) throw Error(`fromJsonStrict: expected object, got ${Array.isArray(t) ? "array" : typeof t}`);
|
|
2813
|
+
return t;
|
|
2814
|
+
}
|
|
2815
|
+
function ki(e) {
|
|
2816
|
+
return e == null ? "{}" : JSON.stringify(e);
|
|
2817
|
+
}
|
|
2818
|
+
function Ai(e) {
|
|
2819
|
+
return e == null || typeof e == "object" && !Array.isArray(e) && Object.keys(e).length === 0 ? null : JSON.stringify(e);
|
|
2820
|
+
}
|
|
2821
|
+
//#endregion
|
|
2822
|
+
//#region src/schema.ts
|
|
2823
|
+
var ji = /* @__PURE__ */ be({
|
|
2824
|
+
actors: () => ma,
|
|
2825
|
+
artifacts: () => Fi,
|
|
2826
|
+
attributionAssessmentEvidence: () => Hi,
|
|
2827
|
+
attributionAssessments: () => Vi,
|
|
2828
|
+
coordinatorEnrollmentReconciliationIssues: () => ga,
|
|
2829
|
+
coordinatorGroupPreferences: () => pa,
|
|
2830
|
+
deviceIdentityBindingAudit: () => Sa,
|
|
2831
|
+
deviceIdentityBindingCommits: () => xa,
|
|
2832
|
+
identityDevices: () => ba,
|
|
2833
|
+
legacyTeamSetupCompletions: () => Ta,
|
|
2834
|
+
legacyTeamSetupDraftDevices: () => Ea,
|
|
2835
|
+
legacyTeamSetupDraftProjects: () => Da,
|
|
2836
|
+
legacyTeamSetupDrafts: () => wa,
|
|
2837
|
+
maintenanceJobs: () => Ui,
|
|
2838
|
+
memoryConceptRefs: () => Li,
|
|
2839
|
+
memoryFileRefs: () => Ii,
|
|
2840
|
+
memoryItems: () => Z,
|
|
2841
|
+
opencodeSessions: () => qi,
|
|
2842
|
+
outcomeEvidence: () => Bi,
|
|
2843
|
+
piImportState: () => Ki,
|
|
2844
|
+
policyTeamDeviceDecisions: () => ya,
|
|
2845
|
+
policyTeamMemberships: () => va,
|
|
2846
|
+
policyTeams: () => _a,
|
|
2847
|
+
projectRecipients: () => Ca,
|
|
2848
|
+
projectScopeMappings: () => Ni,
|
|
2849
|
+
rawEventFlushBatches: () => Ji,
|
|
2850
|
+
rawEventIngestSamples: () => da,
|
|
2851
|
+
rawEventIngestStats: () => fa,
|
|
2852
|
+
rawEventSessions: () => Gi,
|
|
2853
|
+
rawEvents: () => Wi,
|
|
2854
|
+
recipientManagedProjectProjections: () => Oa,
|
|
2855
|
+
recipientPolicyAuthorityStates: () => ka,
|
|
2856
|
+
recipientPolicyDenyOverlays: () => ja,
|
|
2857
|
+
recipientPolicyReconciliationSteps: () => Aa,
|
|
2858
|
+
recipientPolicyReviewResolutions: () => ha,
|
|
2859
|
+
replicationCursors: () => Qi,
|
|
2860
|
+
replicationCursorsV2: () => $i,
|
|
2861
|
+
replicationOps: () => Zi,
|
|
2862
|
+
replicationScopes: () => Mi,
|
|
2863
|
+
retrievalAttempts: () => Q,
|
|
2864
|
+
retrievalExposures: () => zi,
|
|
2865
|
+
schema: () => Ma,
|
|
2866
|
+
scopeMemberships: () => Pi,
|
|
2867
|
+
sessionSummaries: () => Xi,
|
|
2868
|
+
sessions: () => X,
|
|
2869
|
+
syncAttempts: () => ia,
|
|
2870
|
+
syncDaemonState: () => oa,
|
|
2871
|
+
syncDevice: () => ra,
|
|
2872
|
+
syncNonces: () => na,
|
|
2873
|
+
syncPeerSignatureState: () => ta,
|
|
2874
|
+
syncPeers: () => ea,
|
|
2875
|
+
syncResetState: () => sa,
|
|
2876
|
+
syncResetStateV2: () => ca,
|
|
2877
|
+
syncRetentionState: () => la,
|
|
2878
|
+
syncRetentionStateV2: () => ua,
|
|
2879
|
+
syncScopeRejections: () => aa,
|
|
2880
|
+
usageEvents: () => Ri,
|
|
2881
|
+
userPrompts: () => Yi
|
|
2882
|
+
}), X = T("sessions", {
|
|
2883
|
+
id: S("id").primaryKey(),
|
|
2884
|
+
started_at: E("started_at").notNull(),
|
|
2885
|
+
ended_at: E("ended_at"),
|
|
2886
|
+
cwd: E("cwd"),
|
|
2887
|
+
project: E("project"),
|
|
2888
|
+
git_remote: E("git_remote"),
|
|
2889
|
+
git_branch: E("git_branch"),
|
|
2890
|
+
user: E("user"),
|
|
2891
|
+
tool_version: E("tool_version"),
|
|
2892
|
+
metadata_json: E("metadata_json"),
|
|
2893
|
+
import_key: E("import_key")
|
|
2894
|
+
}, (e) => [x("idx_sessions_started_id").on(e.started_at, e.id)]), Mi = T("replication_scopes", {
|
|
2895
|
+
scope_id: E("scope_id").primaryKey(),
|
|
2896
|
+
label: E("label").notNull(),
|
|
2897
|
+
kind: E("kind").notNull().default("user"),
|
|
2898
|
+
authority_type: E("authority_type").notNull().default("local"),
|
|
2899
|
+
coordinator_id: E("coordinator_id"),
|
|
2900
|
+
group_id: E("group_id"),
|
|
2901
|
+
manifest_issuer_device_id: E("manifest_issuer_device_id"),
|
|
2902
|
+
membership_epoch: S("membership_epoch").notNull().default(0),
|
|
2903
|
+
manifest_hash: E("manifest_hash"),
|
|
2904
|
+
status: E("status").notNull().default("active"),
|
|
2905
|
+
created_at: E("created_at").notNull(),
|
|
2906
|
+
updated_at: E("updated_at").notNull()
|
|
2907
|
+
}, (e) => [x("idx_replication_scopes_status").on(e.status), x("idx_replication_scopes_authority_group").on(e.coordinator_id, e.group_id)]), Ni = T("project_scope_mappings", {
|
|
2908
|
+
id: S("id").primaryKey(),
|
|
2909
|
+
workspace_identity: E("workspace_identity"),
|
|
2910
|
+
project_pattern: E("project_pattern").notNull(),
|
|
2911
|
+
scope_id: E("scope_id").notNull(),
|
|
2912
|
+
priority: S("priority").notNull().default(0),
|
|
2913
|
+
source: E("source").notNull().default("user"),
|
|
2914
|
+
created_at: E("created_at").notNull(),
|
|
2915
|
+
updated_at: E("updated_at").notNull()
|
|
2916
|
+
}, (e) => [
|
|
2917
|
+
x("idx_project_scope_mappings_workspace_priority").on(e.workspace_identity, e.priority),
|
|
2918
|
+
x("idx_project_scope_mappings_pattern_priority").on(e.project_pattern, e.priority),
|
|
2919
|
+
x("idx_project_scope_mappings_scope").on(e.scope_id)
|
|
2920
|
+
]), Pi = T("scope_memberships", {
|
|
2921
|
+
scope_id: E("scope_id").notNull(),
|
|
2922
|
+
device_id: E("device_id").notNull(),
|
|
2923
|
+
role: E("role").notNull().default("member"),
|
|
2924
|
+
status: E("status").notNull().default("active"),
|
|
2925
|
+
membership_epoch: S("membership_epoch").notNull().default(0),
|
|
2926
|
+
coordinator_id: E("coordinator_id"),
|
|
2927
|
+
group_id: E("group_id"),
|
|
2928
|
+
manifest_issuer_device_id: E("manifest_issuer_device_id"),
|
|
2929
|
+
manifest_hash: E("manifest_hash"),
|
|
2930
|
+
signed_manifest_json: E("signed_manifest_json"),
|
|
2931
|
+
updated_at: E("updated_at").notNull()
|
|
2932
|
+
}, (e) => [
|
|
2933
|
+
C({ columns: [e.scope_id, e.device_id] }),
|
|
2934
|
+
x("idx_scope_memberships_device_status").on(e.device_id, e.status),
|
|
2935
|
+
x("idx_scope_memberships_scope_status").on(e.scope_id, e.status),
|
|
2936
|
+
x("idx_scope_memberships_authority_group").on(e.coordinator_id, e.group_id)
|
|
2937
|
+
]), Fi = T("artifacts", {
|
|
2938
|
+
id: S("id").primaryKey(),
|
|
2939
|
+
session_id: S("session_id").notNull().references(() => X.id, { onDelete: "cascade" }),
|
|
2940
|
+
kind: E("kind").notNull(),
|
|
2941
|
+
path: E("path"),
|
|
2942
|
+
content_text: E("content_text"),
|
|
2943
|
+
content_hash: E("content_hash"),
|
|
2944
|
+
created_at: E("created_at").notNull(),
|
|
2945
|
+
metadata_json: E("metadata_json")
|
|
2946
|
+
}, (e) => [x("idx_artifacts_session_kind").on(e.session_id, e.kind)]), Z = T("memory_items", {
|
|
2947
|
+
id: S("id").primaryKey(),
|
|
2948
|
+
session_id: S("session_id").notNull().references(() => X.id, { onDelete: "cascade" }),
|
|
2949
|
+
kind: E("kind").notNull(),
|
|
2950
|
+
title: E("title").notNull(),
|
|
2951
|
+
subtitle: E("subtitle"),
|
|
2952
|
+
body_text: E("body_text").notNull(),
|
|
2953
|
+
confidence: w("confidence").default(.5),
|
|
2954
|
+
tags_text: E("tags_text").default(""),
|
|
2955
|
+
active: S("active").default(1),
|
|
2956
|
+
created_at: E("created_at").notNull(),
|
|
2957
|
+
updated_at: E("updated_at").notNull(),
|
|
2958
|
+
metadata_json: E("metadata_json"),
|
|
2959
|
+
actor_id: E("actor_id"),
|
|
2960
|
+
actor_display_name: E("actor_display_name"),
|
|
2961
|
+
visibility: E("visibility"),
|
|
2962
|
+
workspace_id: E("workspace_id"),
|
|
2963
|
+
workspace_kind: E("workspace_kind"),
|
|
2964
|
+
origin_device_id: E("origin_device_id"),
|
|
2965
|
+
origin_source: E("origin_source"),
|
|
2966
|
+
trust_state: E("trust_state"),
|
|
2967
|
+
facts: E("facts"),
|
|
2968
|
+
narrative: E("narrative"),
|
|
2969
|
+
concepts: E("concepts"),
|
|
2970
|
+
files_read: E("files_read"),
|
|
2971
|
+
files_modified: E("files_modified"),
|
|
2972
|
+
user_prompt_id: S("user_prompt_id"),
|
|
2973
|
+
prompt_number: S("prompt_number"),
|
|
2974
|
+
deleted_at: E("deleted_at"),
|
|
2975
|
+
rev: S("rev").default(0),
|
|
2976
|
+
dedup_key: E("dedup_key"),
|
|
2977
|
+
import_key: E("import_key"),
|
|
2978
|
+
scope_id: E("scope_id"),
|
|
2979
|
+
project: E("project")
|
|
2980
|
+
}, (e) => [
|
|
2981
|
+
x("idx_memory_items_active_created").on(e.active, e.created_at),
|
|
2982
|
+
x("idx_memory_items_created_id").on(e.created_at, e.id),
|
|
2983
|
+
x("idx_memory_items_origin_device_active").on(e.origin_device_id, e.active),
|
|
2984
|
+
x("idx_memory_items_session").on(e.session_id),
|
|
2985
|
+
x("idx_memory_items_project").on(e.project),
|
|
2986
|
+
x("idx_memory_items_scope_visibility_created").on(e.scope_id, e.visibility, e.created_at),
|
|
2987
|
+
x("idx_memory_items_scope_backfill_pending").on(e.id).where(b`scope_id IS NULL OR scope_id = ''`),
|
|
2988
|
+
x("idx_memory_items_dedup_key_active_created").on(e.dedup_key, e.active, e.created_at),
|
|
2989
|
+
D("idx_memory_items_same_session_dedup_unique").on(e.session_id, e.kind, e.visibility, e.workspace_id, e.dedup_key).where(b`active = 1 AND dedup_key IS NOT NULL`)
|
|
2990
|
+
]), Ii = T("memory_file_refs", {
|
|
2991
|
+
memory_id: S("memory_id").notNull().references(() => Z.id, { onDelete: "cascade" }),
|
|
2992
|
+
file_path: E("file_path").notNull(),
|
|
2993
|
+
relation: E("relation").notNull()
|
|
2994
|
+
}, (e) => [C({ columns: [
|
|
2995
|
+
e.memory_id,
|
|
2996
|
+
e.file_path,
|
|
2997
|
+
e.relation
|
|
2998
|
+
] }), x("idx_memory_file_refs_path").on(e.file_path)]), Li = T("memory_concept_refs", {
|
|
2999
|
+
memory_id: S("memory_id").notNull().references(() => Z.id, { onDelete: "cascade" }),
|
|
3000
|
+
concept: E("concept").notNull()
|
|
3001
|
+
}, (e) => [C({ columns: [e.memory_id, e.concept] }), x("idx_memory_concept_refs_concept").on(e.concept)]), Ri = T("usage_events", {
|
|
3002
|
+
id: S("id").primaryKey(),
|
|
3003
|
+
session_id: S("session_id").references(() => X.id, { onDelete: "set null" }),
|
|
3004
|
+
event: E("event").notNull(),
|
|
3005
|
+
tokens_read: S("tokens_read").default(0),
|
|
3006
|
+
tokens_written: S("tokens_written").default(0),
|
|
3007
|
+
tokens_saved: S("tokens_saved").default(0),
|
|
3008
|
+
created_at: E("created_at").notNull(),
|
|
3009
|
+
metadata_json: E("metadata_json")
|
|
3010
|
+
}, (e) => [x("idx_usage_events_event_created").on(e.event, e.created_at), x("idx_usage_events_session").on(e.session_id)]), Q = T("retrieval_attempts", {
|
|
3011
|
+
attempt_id: E("attempt_id").primaryKey(),
|
|
3012
|
+
contract_version: S("contract_version").notNull(),
|
|
3013
|
+
surface: E("surface").notNull(),
|
|
3014
|
+
trigger: E("trigger").notNull(),
|
|
3015
|
+
started_at: E("started_at").notNull(),
|
|
3016
|
+
completed_at: E("completed_at"),
|
|
3017
|
+
retrieval_status: E("retrieval_status").notNull(),
|
|
3018
|
+
delivery_status: E("delivery_status").notNull(),
|
|
3019
|
+
candidate_count: S("candidate_count").notNull(),
|
|
3020
|
+
selected_count: S("selected_count").notNull(),
|
|
3021
|
+
persisted_candidate_count: S("persisted_candidate_count").notNull(),
|
|
3022
|
+
recorder_version: E("recorder_version").notNull(),
|
|
3023
|
+
session_id: S("session_id").references(() => X.id, { onDelete: "cascade" }),
|
|
3024
|
+
source: E("source"),
|
|
3025
|
+
stream_id: E("stream_id"),
|
|
3026
|
+
source_session_id: E("source_session_id"),
|
|
3027
|
+
prompt_number: S("prompt_number"),
|
|
3028
|
+
request_id: E("request_id"),
|
|
3029
|
+
raw_event_start_seq: S("raw_event_start_seq"),
|
|
3030
|
+
raw_event_end_seq: S("raw_event_end_seq"),
|
|
3031
|
+
experiment_id: E("experiment_id"),
|
|
3032
|
+
experiment_cell_id: E("experiment_cell_id"),
|
|
3033
|
+
evaluation_checkout_id: E("evaluation_checkout_id"),
|
|
3034
|
+
evaluation_fixture_id: E("evaluation_fixture_id"),
|
|
3035
|
+
evaluation_seed: S("evaluation_seed"),
|
|
3036
|
+
latency_ms: S("latency_ms"),
|
|
3037
|
+
project: E("project"),
|
|
3038
|
+
scope_id: E("scope_id"),
|
|
3039
|
+
mode: E("mode"),
|
|
3040
|
+
limit_requested: S("limit_requested"),
|
|
3041
|
+
token_budget: S("token_budget"),
|
|
3042
|
+
output_tokens: S("output_tokens"),
|
|
3043
|
+
working_set_file_count: S("working_set_file_count"),
|
|
3044
|
+
working_set_files_json: E("working_set_files_json"),
|
|
3045
|
+
query_hash_sha256: E("query_hash_sha256"),
|
|
3046
|
+
query_char_count: S("query_char_count"),
|
|
3047
|
+
query_token_estimate: S("query_token_estimate"),
|
|
3048
|
+
filter_summary_json: E("filter_summary_json"),
|
|
3049
|
+
failure_code: E("failure_code"),
|
|
3050
|
+
failure_stage: E("failure_stage"),
|
|
3051
|
+
trace_version: S("trace_version"),
|
|
3052
|
+
automatic_recall_json: E("automatic_recall_json"),
|
|
3053
|
+
automatic_recall_key: E("automatic_recall_key"),
|
|
3054
|
+
retention_until: E("retention_until"),
|
|
3055
|
+
retention_pinned: S("retention_pinned").notNull().default(0),
|
|
3056
|
+
retention_finalized_at: E("retention_finalized_at")
|
|
3057
|
+
}, (e) => [
|
|
3058
|
+
x("idx_retrieval_attempts_session_started").on(e.session_id, e.started_at),
|
|
3059
|
+
D("idx_retrieval_attempts_automatic_recall_key").on(e.automatic_recall_key),
|
|
3060
|
+
x("idx_retrieval_attempts_source_stream_started").on(e.source, e.stream_id, e.started_at),
|
|
3061
|
+
x("idx_retrieval_attempts_retention").on(e.retention_pinned, e.retention_until),
|
|
3062
|
+
x("idx_retrieval_attempts_started").on(e.started_at, e.attempt_id),
|
|
3063
|
+
x("idx_retrieval_attempts_surface_started").on(e.surface, e.started_at),
|
|
3064
|
+
D("idx_retrieval_attempts_request_identity").on(e.source, e.surface, e.request_id).where(b`request_id IS NOT NULL`),
|
|
3065
|
+
x("idx_retrieval_attempts_experiment_cell").on(e.experiment_id, e.experiment_cell_id)
|
|
3066
|
+
]), zi = T("retrieval_exposures", {
|
|
3067
|
+
exposure_id: S("exposure_id").primaryKey({ autoIncrement: !0 }),
|
|
3068
|
+
attempt_id: E("attempt_id").notNull().references(() => Q.attempt_id, { onDelete: "cascade" }),
|
|
3069
|
+
memory_id: S("memory_id").references(() => Z.id, { onDelete: "set null" }),
|
|
3070
|
+
memory_import_key: E("memory_import_key"),
|
|
3071
|
+
origin_device_id: E("origin_device_id"),
|
|
3072
|
+
rank: S("rank").notNull(),
|
|
3073
|
+
disposition: E("disposition").notNull(),
|
|
3074
|
+
section: E("section"),
|
|
3075
|
+
handoff_status: E("handoff_status").notNull(),
|
|
3076
|
+
memory_rev: S("memory_rev"),
|
|
3077
|
+
memory_updated_at: E("memory_updated_at"),
|
|
3078
|
+
memory_scope_id: E("memory_scope_id"),
|
|
3079
|
+
memory_kind: E("memory_kind"),
|
|
3080
|
+
memory_active: S("memory_active"),
|
|
3081
|
+
memory_deleted_at: E("memory_deleted_at"),
|
|
3082
|
+
score_summary_json: E("score_summary_json"),
|
|
3083
|
+
reason_codes_json: E("reason_codes_json")
|
|
3084
|
+
}, (e) => [D("idx_retrieval_exposures_attempt_rank").on(e.attempt_id, e.rank), x("idx_retrieval_exposures_memory").on(e.memory_id)]), Bi = T("outcome_evidence", {
|
|
3085
|
+
evidence_id: E("evidence_id").primaryKey(),
|
|
3086
|
+
contract_version: S("contract_version").notNull(),
|
|
3087
|
+
dimension: E("dimension").notNull(),
|
|
3088
|
+
evidence_type: E("evidence_type").notNull(),
|
|
3089
|
+
source_class: E("source_class").notNull(),
|
|
3090
|
+
observed_at: E("observed_at").notNull(),
|
|
3091
|
+
producer: E("producer").notNull(),
|
|
3092
|
+
producer_version: E("producer_version").notNull(),
|
|
3093
|
+
status: E("status").notNull(),
|
|
3094
|
+
value_type: E("value_type"),
|
|
3095
|
+
value_integer: S("value_integer"),
|
|
3096
|
+
value_real: w("value_real"),
|
|
3097
|
+
value_unit: E("value_unit"),
|
|
3098
|
+
session_id: S("session_id").references(() => X.id, { onDelete: "cascade" }),
|
|
3099
|
+
source: E("source"),
|
|
3100
|
+
stream_id: E("stream_id"),
|
|
3101
|
+
source_session_id: E("source_session_id"),
|
|
3102
|
+
prompt_number: S("prompt_number"),
|
|
3103
|
+
raw_event_start_seq: S("raw_event_start_seq"),
|
|
3104
|
+
raw_event_end_seq: S("raw_event_end_seq"),
|
|
3105
|
+
experiment_id: E("experiment_id"),
|
|
3106
|
+
experiment_cell_id: E("experiment_cell_id"),
|
|
3107
|
+
window_start_at: E("window_start_at"),
|
|
3108
|
+
window_end_at: E("window_end_at"),
|
|
3109
|
+
references_json: E("references_json"),
|
|
3110
|
+
retention_until: E("retention_until"),
|
|
3111
|
+
retention_pinned: S("retention_pinned").notNull().default(0),
|
|
3112
|
+
retention_finalized_at: E("retention_finalized_at")
|
|
3113
|
+
}, (e) => [
|
|
3114
|
+
x("idx_outcome_evidence_observed_id").on(e.observed_at, e.evidence_id),
|
|
3115
|
+
x("idx_outcome_evidence_session_observed").on(e.session_id, e.observed_at),
|
|
3116
|
+
x("idx_outcome_evidence_source_stream_observed").on(e.source, e.stream_id, e.observed_at),
|
|
3117
|
+
x("idx_outcome_evidence_type_observed").on(e.evidence_type, e.observed_at),
|
|
3118
|
+
x("idx_outcome_evidence_retention").on(e.retention_pinned, e.retention_until)
|
|
3119
|
+
]), Vi = T("attribution_assessments", {
|
|
3120
|
+
assessment_id: E("assessment_id").primaryKey(),
|
|
3121
|
+
contract_version: S("contract_version").notNull(),
|
|
3122
|
+
subject_type: E("subject_type").notNull(),
|
|
3123
|
+
attempt_id: E("attempt_id").notNull().references(() => Q.attempt_id, { onDelete: "cascade" }),
|
|
3124
|
+
exposure_id: S("exposure_id").references(() => zi.exposure_id, { onDelete: "cascade" }),
|
|
3125
|
+
dimension: E("dimension").notNull(),
|
|
3126
|
+
impact_label: E("impact_label").notNull(),
|
|
3127
|
+
basis: E("basis").notNull(),
|
|
3128
|
+
confidence_level: E("confidence_level").notNull(),
|
|
3129
|
+
method: E("method").notNull(),
|
|
3130
|
+
method_version: E("method_version").notNull(),
|
|
3131
|
+
created_at: E("created_at").notNull(),
|
|
3132
|
+
claim_type: E("claim_type").notNull().default("observational")
|
|
3133
|
+
}, (e) => [
|
|
3134
|
+
x("idx_attribution_assessments_attempt_created").on(e.attempt_id, e.created_at),
|
|
3135
|
+
x("idx_attribution_assessments_label_created").on(e.impact_label, e.created_at),
|
|
3136
|
+
x("idx_attribution_assessments_exposure").on(e.exposure_id)
|
|
3137
|
+
]), Hi = T("attribution_assessment_evidence", {
|
|
3138
|
+
assessment_id: E("assessment_id").notNull().references(() => Vi.assessment_id, { onDelete: "cascade" }),
|
|
3139
|
+
evidence_id: E("evidence_id").notNull().references(() => Bi.evidence_id, { onDelete: "cascade" })
|
|
3140
|
+
}, (e) => [C({ columns: [e.assessment_id, e.evidence_id] }), x("idx_attribution_assessment_evidence_evidence").on(e.evidence_id, e.assessment_id)]), Ui = T("maintenance_jobs", {
|
|
3141
|
+
kind: E("kind").primaryKey(),
|
|
3142
|
+
title: E("title").notNull(),
|
|
3143
|
+
status: E("status").notNull(),
|
|
3144
|
+
message: E("message"),
|
|
3145
|
+
progress_current: S("progress_current").notNull().default(0),
|
|
3146
|
+
progress_total: S("progress_total"),
|
|
3147
|
+
progress_unit: E("progress_unit").notNull().default("items"),
|
|
3148
|
+
metadata_json: E("metadata_json"),
|
|
3149
|
+
started_at: E("started_at"),
|
|
3150
|
+
updated_at: E("updated_at").notNull(),
|
|
3151
|
+
finished_at: E("finished_at"),
|
|
3152
|
+
error: E("error")
|
|
3153
|
+
}, (e) => [x("idx_maintenance_jobs_status_updated").on(e.status, e.updated_at)]), Wi = T("raw_events", {
|
|
3154
|
+
id: S("id").primaryKey(),
|
|
3155
|
+
source: E("source").notNull().default("opencode"),
|
|
3156
|
+
stream_id: E("stream_id").notNull().default(""),
|
|
3157
|
+
opencode_session_id: E("opencode_session_id").notNull(),
|
|
3158
|
+
event_id: E("event_id"),
|
|
3159
|
+
event_seq: S("event_seq").notNull(),
|
|
3160
|
+
event_type: E("event_type").notNull(),
|
|
3161
|
+
ts_wall_ms: S("ts_wall_ms"),
|
|
3162
|
+
ts_mono_ms: w("ts_mono_ms"),
|
|
3163
|
+
payload_json: E("payload_json").notNull(),
|
|
3164
|
+
capture_context_json: E("capture_context_json"),
|
|
3165
|
+
created_at: E("created_at").notNull()
|
|
3166
|
+
}, (e) => [
|
|
3167
|
+
D("idx_raw_events_source_stream_seq").on(e.source, e.stream_id, e.event_seq),
|
|
3168
|
+
D("idx_raw_events_source_stream_event_id").on(e.source, e.stream_id, e.event_id),
|
|
3169
|
+
x("idx_raw_events_session_seq").on(e.opencode_session_id, e.event_seq),
|
|
3170
|
+
x("idx_raw_events_created").on(e.created_at),
|
|
3171
|
+
x("idx_raw_events_capture_context").on(e.source, e.stream_id, e.event_seq).where(b`${e.capture_context_json} IS NOT NULL`)
|
|
3172
|
+
]), Gi = T("raw_event_sessions", {
|
|
3173
|
+
source: E("source").notNull().default("opencode"),
|
|
3174
|
+
stream_id: E("stream_id").notNull().default(""),
|
|
3175
|
+
opencode_session_id: E("opencode_session_id").notNull(),
|
|
3176
|
+
cwd: E("cwd"),
|
|
3177
|
+
project: E("project"),
|
|
3178
|
+
started_at: E("started_at"),
|
|
3179
|
+
last_seen_ts_wall_ms: S("last_seen_ts_wall_ms"),
|
|
3180
|
+
last_received_event_seq: S("last_received_event_seq").notNull().default(-1),
|
|
3181
|
+
last_flushed_event_seq: S("last_flushed_event_seq").notNull().default(-1),
|
|
3182
|
+
updated_at: E("updated_at").notNull()
|
|
3183
|
+
}, (e) => [C({ columns: [e.source, e.stream_id] }), x("idx_raw_event_sessions_pending_updated").on(e.updated_at).where(b`${e.last_received_event_seq} > ${e.last_flushed_event_seq}`)]), Ki = T("pi_import_state", {
|
|
3184
|
+
file_path: E("file_path").primaryKey(),
|
|
3185
|
+
size_bytes: S("size_bytes").notNull(),
|
|
3186
|
+
mtime_ms: w("mtime_ms").notNull(),
|
|
3187
|
+
updated_at: E("updated_at").notNull()
|
|
3188
|
+
}), qi = T("opencode_sessions", {
|
|
3189
|
+
source: E("source").notNull().default("opencode"),
|
|
3190
|
+
stream_id: E("stream_id").notNull().default(""),
|
|
3191
|
+
opencode_session_id: E("opencode_session_id").notNull(),
|
|
3192
|
+
session_id: S("session_id").references(() => X.id, { onDelete: "cascade" }),
|
|
3193
|
+
created_at: E("created_at").notNull()
|
|
3194
|
+
}, (e) => [C({ columns: [e.source, e.stream_id] }), x("idx_opencode_sessions_session").on(e.session_id)]), Ji = T("raw_event_flush_batches", {
|
|
3195
|
+
id: S("id").primaryKey(),
|
|
3196
|
+
source: E("source").notNull().default("opencode"),
|
|
3197
|
+
stream_id: E("stream_id").notNull().default(""),
|
|
3198
|
+
opencode_session_id: E("opencode_session_id").notNull(),
|
|
3199
|
+
start_event_seq: S("start_event_seq").notNull(),
|
|
3200
|
+
end_event_seq: S("end_event_seq").notNull(),
|
|
3201
|
+
extractor_version: E("extractor_version").notNull(),
|
|
3202
|
+
status: E("status").notNull(),
|
|
3203
|
+
error_message: E("error_message"),
|
|
3204
|
+
error_type: E("error_type"),
|
|
3205
|
+
observer_provider: E("observer_provider"),
|
|
3206
|
+
observer_model: E("observer_model"),
|
|
3207
|
+
observer_runtime: E("observer_runtime"),
|
|
3208
|
+
observer_auth_source: E("observer_auth_source"),
|
|
3209
|
+
observer_auth_type: E("observer_auth_type"),
|
|
3210
|
+
observer_error_code: E("observer_error_code"),
|
|
3211
|
+
observer_error_message: E("observer_error_message"),
|
|
3212
|
+
attempt_count: S("attempt_count").notNull().default(0),
|
|
3213
|
+
claim_generation: S("claim_generation").notNull().default(0),
|
|
3214
|
+
created_at: E("created_at").notNull(),
|
|
3215
|
+
updated_at: E("updated_at").notNull()
|
|
3216
|
+
}, (e) => [
|
|
3217
|
+
D("idx_flush_batches_source_stream_seq_ver").on(e.source, e.stream_id, e.start_event_seq, e.end_event_seq, e.extractor_version),
|
|
3218
|
+
x("idx_flush_batches_session_created").on(e.opencode_session_id, e.created_at),
|
|
3219
|
+
x("idx_flush_batches_status_updated").on(e.status, e.updated_at),
|
|
3220
|
+
x("idx_flush_batches_observer_status_updated").on(e.status, e.updated_at).where(b`${e.observer_provider} IS NOT NULL`),
|
|
3221
|
+
x("idx_flush_batches_capture_status_updated").on(e.status, e.updated_at).where(b`${e.observer_provider} IS NULL`)
|
|
3222
|
+
]), Yi = T("user_prompts", {
|
|
3223
|
+
id: S("id").primaryKey(),
|
|
3224
|
+
session_id: S("session_id").references(() => X.id, { onDelete: "cascade" }),
|
|
3225
|
+
project: E("project"),
|
|
3226
|
+
prompt_text: E("prompt_text").notNull(),
|
|
3227
|
+
prompt_number: S("prompt_number"),
|
|
3228
|
+
created_at: E("created_at").notNull(),
|
|
3229
|
+
created_at_epoch: S("created_at_epoch").notNull(),
|
|
3230
|
+
metadata_json: E("metadata_json"),
|
|
3231
|
+
import_key: E("import_key")
|
|
3232
|
+
}, (e) => [
|
|
3233
|
+
x("idx_user_prompts_session").on(e.session_id),
|
|
3234
|
+
x("idx_user_prompts_project").on(e.project),
|
|
3235
|
+
x("idx_user_prompts_epoch").on(e.created_at_epoch)
|
|
3236
|
+
]), Xi = T("session_summaries", {
|
|
3237
|
+
id: S("id").primaryKey(),
|
|
3238
|
+
session_id: S("session_id").references(() => X.id, { onDelete: "cascade" }),
|
|
3239
|
+
project: E("project"),
|
|
3240
|
+
request: E("request"),
|
|
3241
|
+
investigated: E("investigated"),
|
|
3242
|
+
learned: E("learned"),
|
|
3243
|
+
completed: E("completed"),
|
|
3244
|
+
next_steps: E("next_steps"),
|
|
3245
|
+
notes: E("notes"),
|
|
3246
|
+
files_read: E("files_read"),
|
|
3247
|
+
files_edited: E("files_edited"),
|
|
3248
|
+
prompt_number: S("prompt_number"),
|
|
3249
|
+
created_at: E("created_at").notNull(),
|
|
3250
|
+
created_at_epoch: S("created_at_epoch").notNull(),
|
|
3251
|
+
metadata_json: E("metadata_json"),
|
|
3252
|
+
import_key: E("import_key")
|
|
3253
|
+
}, (e) => [
|
|
3254
|
+
x("idx_session_summaries_session").on(e.session_id),
|
|
3255
|
+
x("idx_session_summaries_project").on(e.project),
|
|
3256
|
+
x("idx_session_summaries_epoch").on(e.created_at_epoch)
|
|
3257
|
+
]), Zi = T("replication_ops", {
|
|
3258
|
+
op_id: E("op_id").primaryKey(),
|
|
3259
|
+
entity_type: E("entity_type").notNull(),
|
|
3260
|
+
entity_id: E("entity_id").notNull(),
|
|
3261
|
+
op_type: E("op_type").notNull(),
|
|
3262
|
+
payload_json: E("payload_json"),
|
|
3263
|
+
clock_rev: S("clock_rev").notNull(),
|
|
3264
|
+
clock_updated_at: E("clock_updated_at").notNull(),
|
|
3265
|
+
clock_device_id: E("clock_device_id").notNull(),
|
|
3266
|
+
device_id: E("device_id").notNull(),
|
|
3267
|
+
created_at: E("created_at").notNull(),
|
|
3268
|
+
scope_id: E("scope_id")
|
|
3269
|
+
}, (e) => [
|
|
3270
|
+
x("idx_replication_ops_created").on(e.created_at, e.op_id),
|
|
3271
|
+
x("idx_replication_ops_entity").on(e.entity_type, e.entity_id),
|
|
3272
|
+
x("idx_replication_ops_scope_created").on(e.scope_id, e.created_at, e.op_id)
|
|
3273
|
+
]), Qi = T("replication_cursors", {
|
|
3274
|
+
peer_device_id: E("peer_device_id").primaryKey(),
|
|
3275
|
+
last_applied_cursor: E("last_applied_cursor"),
|
|
3276
|
+
last_acked_cursor: E("last_acked_cursor"),
|
|
3277
|
+
updated_at: E("updated_at").notNull()
|
|
3278
|
+
}), $i = T("replication_cursors_v2", {
|
|
3279
|
+
peer_device_id: E("peer_device_id").notNull(),
|
|
3280
|
+
scope_id: E("scope_id").notNull(),
|
|
3281
|
+
last_applied_cursor: E("last_applied_cursor"),
|
|
3282
|
+
last_acked_cursor: E("last_acked_cursor"),
|
|
3283
|
+
updated_at: E("updated_at").notNull()
|
|
3284
|
+
}, (e) => [C({ columns: [e.peer_device_id, e.scope_id] }), x("idx_replication_cursors_v2_scope").on(e.scope_id)]), ea = T("sync_peers", {
|
|
3285
|
+
peer_device_id: E("peer_device_id").primaryKey(),
|
|
3286
|
+
name: E("name"),
|
|
3287
|
+
pinned_fingerprint: E("pinned_fingerprint"),
|
|
3288
|
+
public_key: E("public_key"),
|
|
3289
|
+
addresses_json: E("addresses_json"),
|
|
3290
|
+
manual_addresses_json: E("manual_addresses_json"),
|
|
3291
|
+
last_success_address: E("last_success_address"),
|
|
3292
|
+
claimed_local_actor: S("claimed_local_actor").notNull().default(0),
|
|
3293
|
+
actor_id: E("actor_id"),
|
|
3294
|
+
projects_include_json: E("projects_include_json"),
|
|
3295
|
+
projects_exclude_json: E("projects_exclude_json"),
|
|
3296
|
+
created_at: E("created_at").notNull(),
|
|
3297
|
+
last_seen_at: E("last_seen_at"),
|
|
3298
|
+
last_sync_at: E("last_sync_at"),
|
|
3299
|
+
last_error: E("last_error"),
|
|
3300
|
+
runtime_version: E("runtime_version"),
|
|
3301
|
+
runtime_version_observed_at: E("runtime_version_observed_at"),
|
|
3302
|
+
sync_features_json: E("sync_features_json"),
|
|
3303
|
+
sync_features_observed_at: E("sync_features_observed_at"),
|
|
3304
|
+
relay_retry_after: E("relay_retry_after"),
|
|
3305
|
+
relay_rejections: S("relay_rejections").notNull().default(0),
|
|
3306
|
+
highest_observed_direct_signature_version: S("highest_observed_direct_signature_version"),
|
|
3307
|
+
discovered_via_coordinator_id: E("discovered_via_coordinator_id"),
|
|
3308
|
+
discovered_via_group_id: E("discovered_via_group_id"),
|
|
3309
|
+
trust_provenance: E("trust_provenance"),
|
|
3310
|
+
pending_bootstrap_grant_id: E("pending_bootstrap_grant_id")
|
|
3311
|
+
}), ta = T("sync_peer_signature_state", {
|
|
3312
|
+
peer_device_id: E("peer_device_id").primaryKey(),
|
|
3313
|
+
highest_observed_direct_signature_version: S("highest_observed_direct_signature_version").notNull()
|
|
3314
|
+
}), na = T("sync_nonces", {
|
|
3315
|
+
nonce: E("nonce").primaryKey(),
|
|
3316
|
+
device_id: E("device_id").notNull(),
|
|
3317
|
+
created_at: E("created_at").notNull()
|
|
3318
|
+
}), ra = T("sync_device", {
|
|
3319
|
+
device_id: E("device_id").primaryKey(),
|
|
3320
|
+
public_key: E("public_key").notNull(),
|
|
3321
|
+
fingerprint: E("fingerprint").notNull(),
|
|
3322
|
+
created_at: E("created_at").notNull()
|
|
3323
|
+
}), ia = T("sync_attempts", {
|
|
3324
|
+
id: S("id").primaryKey({ autoIncrement: !0 }),
|
|
3325
|
+
peer_device_id: E("peer_device_id").notNull(),
|
|
3326
|
+
started_at: E("started_at").notNull(),
|
|
3327
|
+
finished_at: E("finished_at"),
|
|
3328
|
+
ok: S("ok").notNull(),
|
|
3329
|
+
ops_in: S("ops_in").notNull(),
|
|
3330
|
+
ops_out: S("ops_out").notNull(),
|
|
3331
|
+
error: E("error"),
|
|
3332
|
+
local_sync_capability: E("local_sync_capability"),
|
|
3333
|
+
peer_sync_capability: E("peer_sync_capability"),
|
|
3334
|
+
negotiated_sync_capability: E("negotiated_sync_capability"),
|
|
3335
|
+
failure_category: E("failure_category"),
|
|
3336
|
+
transport: E("transport")
|
|
3337
|
+
}, (e) => [
|
|
3338
|
+
x("idx_sync_attempts_peer_started").on(e.peer_device_id, e.started_at),
|
|
3339
|
+
x("idx_sync_attempts_occurred").on(b`CASE WHEN ${e.finished_at} IS NULL THEN ${e.started_at} ELSE ${e.finished_at} END`, e.id),
|
|
3340
|
+
x("idx_sync_attempts_error_occurred").on(b`CASE WHEN ${e.finished_at} IS NULL THEN ${e.started_at} ELSE ${e.finished_at} END`, e.id).where(b`${e.ok} = 0`),
|
|
3341
|
+
x("idx_sync_attempts_success_occurred").on(b`CASE WHEN ${e.finished_at} IS NULL THEN ${e.started_at} ELSE ${e.finished_at} END`, e.id).where(b`${e.ok} <> 0`)
|
|
3342
|
+
]), aa = T("sync_scope_rejections", {
|
|
3343
|
+
id: S("id").primaryKey({ autoIncrement: !0 }),
|
|
3344
|
+
peer_device_id: E("peer_device_id"),
|
|
3345
|
+
op_id: E("op_id").notNull(),
|
|
3346
|
+
entity_type: E("entity_type").notNull(),
|
|
3347
|
+
entity_id: E("entity_id").notNull(),
|
|
3348
|
+
scope_id: E("scope_id"),
|
|
3349
|
+
reason: E("reason").notNull(),
|
|
3350
|
+
created_at: E("created_at").notNull()
|
|
3351
|
+
}, (e) => [x("idx_sync_scope_rejections_peer_created").on(e.peer_device_id, e.created_at), x("idx_sync_scope_rejections_scope_created").on(e.scope_id, e.created_at)]), oa = T("sync_daemon_state", {
|
|
3352
|
+
id: S("id").primaryKey(),
|
|
3353
|
+
last_error: E("last_error"),
|
|
3354
|
+
last_traceback: E("last_traceback"),
|
|
3355
|
+
last_error_at: E("last_error_at"),
|
|
3356
|
+
last_ok_at: E("last_ok_at"),
|
|
3357
|
+
phase: E("phase")
|
|
3358
|
+
}), sa = T("sync_reset_state", {
|
|
3359
|
+
id: S("id").primaryKey(),
|
|
3360
|
+
generation: S("generation").notNull(),
|
|
3361
|
+
snapshot_id: E("snapshot_id").notNull(),
|
|
3362
|
+
baseline_cursor: E("baseline_cursor"),
|
|
3363
|
+
retained_floor_cursor: E("retained_floor_cursor"),
|
|
3364
|
+
updated_at: E("updated_at").notNull()
|
|
3365
|
+
}), ca = T("sync_reset_state_v2", {
|
|
3366
|
+
scope_id: E("scope_id").primaryKey(),
|
|
3367
|
+
generation: S("generation").notNull(),
|
|
3368
|
+
snapshot_id: E("snapshot_id").notNull(),
|
|
3369
|
+
baseline_cursor: E("baseline_cursor"),
|
|
3370
|
+
retained_floor_cursor: E("retained_floor_cursor"),
|
|
3371
|
+
updated_at: E("updated_at").notNull()
|
|
3372
|
+
}), la = T("sync_retention_state", {
|
|
3373
|
+
id: S("id").primaryKey(),
|
|
3374
|
+
last_run_at: E("last_run_at"),
|
|
3375
|
+
last_duration_ms: S("last_duration_ms"),
|
|
3376
|
+
last_deleted_ops: S("last_deleted_ops").notNull().default(0),
|
|
3377
|
+
last_estimated_bytes_before: S("last_estimated_bytes_before"),
|
|
3378
|
+
last_estimated_bytes_after: S("last_estimated_bytes_after"),
|
|
3379
|
+
retained_floor_cursor: E("retained_floor_cursor"),
|
|
3380
|
+
last_error: E("last_error"),
|
|
3381
|
+
last_error_at: E("last_error_at")
|
|
3382
|
+
}), ua = T("sync_retention_state_v2", {
|
|
3383
|
+
scope_id: E("scope_id").primaryKey(),
|
|
3384
|
+
last_run_at: E("last_run_at"),
|
|
3385
|
+
last_duration_ms: S("last_duration_ms"),
|
|
3386
|
+
last_deleted_ops: S("last_deleted_ops").notNull().default(0),
|
|
3387
|
+
last_estimated_bytes_before: S("last_estimated_bytes_before"),
|
|
3388
|
+
last_estimated_bytes_after: S("last_estimated_bytes_after"),
|
|
3389
|
+
retained_floor_cursor: E("retained_floor_cursor"),
|
|
3390
|
+
last_error: E("last_error"),
|
|
3391
|
+
last_error_at: E("last_error_at")
|
|
3392
|
+
}), da = T("raw_event_ingest_samples", {
|
|
3393
|
+
id: S("id").primaryKey({ autoIncrement: !0 }),
|
|
3394
|
+
created_at: E("created_at").notNull(),
|
|
3395
|
+
inserted_events: S("inserted_events").notNull().default(0),
|
|
3396
|
+
skipped_invalid: S("skipped_invalid").notNull().default(0),
|
|
3397
|
+
skipped_duplicate: S("skipped_duplicate").notNull().default(0),
|
|
3398
|
+
skipped_conflict: S("skipped_conflict").notNull().default(0)
|
|
3399
|
+
}), fa = T("raw_event_ingest_stats", {
|
|
3400
|
+
id: S("id").primaryKey(),
|
|
3401
|
+
inserted_events: S("inserted_events").notNull().default(0),
|
|
3402
|
+
skipped_events: S("skipped_events").notNull().default(0),
|
|
3403
|
+
skipped_invalid: S("skipped_invalid").notNull().default(0),
|
|
3404
|
+
skipped_duplicate: S("skipped_duplicate").notNull().default(0),
|
|
3405
|
+
skipped_conflict: S("skipped_conflict").notNull().default(0),
|
|
3406
|
+
updated_at: E("updated_at").notNull()
|
|
3407
|
+
}), pa = T("coordinator_group_preferences", {
|
|
3408
|
+
coordinator_id: E("coordinator_id").notNull(),
|
|
3409
|
+
group_id: E("group_id").notNull(),
|
|
3410
|
+
projects_include_json: E("projects_include_json"),
|
|
3411
|
+
projects_exclude_json: E("projects_exclude_json"),
|
|
3412
|
+
auto_seed_scope: S("auto_seed_scope").notNull().default(1),
|
|
3413
|
+
default_space_scope_id: E("default_space_scope_id"),
|
|
3414
|
+
auto_grant_default_space_on_join: S("auto_grant_default_space_on_join").notNull().default(0),
|
|
3415
|
+
updated_at: E("updated_at").notNull()
|
|
3416
|
+
}, (e) => ({ pk: C({ columns: [e.coordinator_id, e.group_id] }) })), ma = T("actors", {
|
|
3417
|
+
actor_id: E("actor_id").primaryKey(),
|
|
3418
|
+
display_name: E("display_name").notNull(),
|
|
3419
|
+
is_local: S("is_local").notNull().default(0),
|
|
3420
|
+
status: E("status").notNull().default("active"),
|
|
3421
|
+
merged_into_actor_id: E("merged_into_actor_id"),
|
|
3422
|
+
created_at: E("created_at").notNull(),
|
|
3423
|
+
updated_at: E("updated_at").notNull()
|
|
3424
|
+
}, (e) => ({
|
|
3425
|
+
isLocalIdx: x("idx_actors_is_local").on(e.is_local),
|
|
3426
|
+
statusIdx: x("idx_actors_status").on(e.status)
|
|
3427
|
+
})), ha = T("recipient_policy_review_resolutions", {
|
|
3428
|
+
review_item_id: E("review_item_id").notNull(),
|
|
3429
|
+
source_fingerprint: E("source_fingerprint").notNull(),
|
|
3430
|
+
decision: E("decision").notNull(),
|
|
3431
|
+
decision_input_json: E("decision_input_json").notNull(),
|
|
3432
|
+
preview_json: E("preview_json").notNull(),
|
|
3433
|
+
decided_by_identity_id: E("decided_by_identity_id").notNull(),
|
|
3434
|
+
decided_by_device_id: E("decided_by_device_id").notNull(),
|
|
3435
|
+
resolved_at: E("resolved_at").notNull()
|
|
3436
|
+
}, (e) => [C({ columns: [e.review_item_id, e.source_fingerprint] })]), ga = T("coordinator_enrollment_reconciliation_issues", {
|
|
3437
|
+
coordinator_id: E("coordinator_id").notNull(),
|
|
3438
|
+
group_id: E("group_id").notNull(),
|
|
3439
|
+
kind: E("kind").notNull(),
|
|
3440
|
+
reference_id: E("reference_id").notNull(),
|
|
3441
|
+
code: E("code").notNull(),
|
|
3442
|
+
status: E("status").notNull().default("open"),
|
|
3443
|
+
first_seen_at: E("first_seen_at").notNull(),
|
|
3444
|
+
last_seen_at: E("last_seen_at").notNull(),
|
|
3445
|
+
resolved_at: E("resolved_at"),
|
|
3446
|
+
occurrence_count: S("occurrence_count").notNull().default(1),
|
|
3447
|
+
updated_at: E("updated_at").notNull()
|
|
3448
|
+
}, (e) => [
|
|
3449
|
+
C({ columns: [
|
|
3450
|
+
e.coordinator_id,
|
|
3451
|
+
e.group_id,
|
|
3452
|
+
e.kind,
|
|
3453
|
+
e.reference_id,
|
|
3454
|
+
e.code
|
|
3455
|
+
] }),
|
|
3456
|
+
x("idx_coordinator_enrollment_issues_boundary_status").on(e.coordinator_id, e.group_id, e.status),
|
|
3457
|
+
x("idx_coordinator_enrollment_issues_status_recent").on(e.status, e.last_seen_at, e.resolved_at)
|
|
3458
|
+
]), _a = T("policy_teams", {
|
|
3459
|
+
team_id: E("team_id").primaryKey(),
|
|
3460
|
+
display_name: E("display_name").notNull(),
|
|
3461
|
+
status: E("status").notNull(),
|
|
3462
|
+
device_eligibility_mode: E("device_eligibility_mode").notNull().default("person_all_devices"),
|
|
3463
|
+
provenance: E("provenance").notNull(),
|
|
3464
|
+
revision: E("revision").notNull(),
|
|
3465
|
+
migration_state: E("migration_state").notNull(),
|
|
3466
|
+
source_fingerprint: E("source_fingerprint"),
|
|
3467
|
+
idempotency_key: E("idempotency_key").notNull().unique(),
|
|
3468
|
+
created_at: E("created_at").notNull(),
|
|
3469
|
+
updated_at: E("updated_at").notNull()
|
|
3470
|
+
}), va = T("policy_team_memberships", {
|
|
3471
|
+
team_id: E("team_id").notNull(),
|
|
3472
|
+
identity_id: E("identity_id").notNull(),
|
|
3473
|
+
role: E("role").notNull(),
|
|
3474
|
+
status: E("status").notNull(),
|
|
3475
|
+
provenance: E("provenance").notNull(),
|
|
3476
|
+
revision: E("revision").notNull(),
|
|
3477
|
+
migration_state: E("migration_state").notNull(),
|
|
3478
|
+
source_fingerprint: E("source_fingerprint"),
|
|
3479
|
+
idempotency_key: E("idempotency_key").notNull().unique(),
|
|
3480
|
+
created_at: E("created_at").notNull(),
|
|
3481
|
+
updated_at: E("updated_at").notNull()
|
|
3482
|
+
}, (e) => ({
|
|
3483
|
+
pk: C({ columns: [e.team_id, e.identity_id] }),
|
|
3484
|
+
identityStatusIdx: x("idx_policy_team_memberships_identity_status").on(e.identity_id, e.status)
|
|
3485
|
+
})), ya = T("policy_team_device_decisions", {
|
|
3486
|
+
team_id: E("team_id").notNull().references(() => _a.team_id, { onDelete: "cascade" }),
|
|
3487
|
+
device_id: E("device_id").notNull(),
|
|
3488
|
+
decision: E("decision").notNull(),
|
|
3489
|
+
assignment_version: S("assignment_version").notNull().default(0),
|
|
3490
|
+
provenance: E("provenance").notNull(),
|
|
3491
|
+
revision: E("revision").notNull(),
|
|
3492
|
+
created_at: E("created_at").notNull(),
|
|
3493
|
+
updated_at: E("updated_at").notNull()
|
|
3494
|
+
}, (e) => [C({ columns: [e.team_id, e.device_id] }), x("idx_policy_team_device_decisions_device").on(e.device_id)]), ba = T("identity_devices", {
|
|
3495
|
+
device_id: E("device_id").primaryKey(),
|
|
3496
|
+
identity_id: E("identity_id").notNull(),
|
|
3497
|
+
display_name: E("display_name").notNull(),
|
|
3498
|
+
status: E("status").notNull(),
|
|
3499
|
+
provenance: E("provenance").notNull(),
|
|
3500
|
+
revision: E("revision").notNull(),
|
|
3501
|
+
migration_state: E("migration_state").notNull(),
|
|
3502
|
+
assignment_version: S("assignment_version").notNull().default(0),
|
|
3503
|
+
source_fingerprint: E("source_fingerprint"),
|
|
3504
|
+
idempotency_key: E("idempotency_key").notNull().unique(),
|
|
3505
|
+
created_at: E("created_at").notNull(),
|
|
3506
|
+
updated_at: E("updated_at").notNull()
|
|
3507
|
+
}, (e) => ({ identityStatusIdx: x("idx_identity_devices_identity_status").on(e.identity_id, e.status) })), xa = T("device_identity_binding_commits", {
|
|
3508
|
+
commit_digest: E("commit_digest").primaryKey(),
|
|
3509
|
+
reviewed_inventory_digest: E("reviewed_inventory_digest").notNull(),
|
|
3510
|
+
request_json: E("request_json").notNull(),
|
|
3511
|
+
outcomes_json: E("outcomes_json").notNull(),
|
|
3512
|
+
write_count: S("write_count").notNull(),
|
|
3513
|
+
decided_by_identity_id: E("decided_by_identity_id").notNull(),
|
|
3514
|
+
decided_by_device_id: E("decided_by_device_id").notNull(),
|
|
3515
|
+
created_at: E("created_at").notNull()
|
|
3516
|
+
}), Sa = T("device_identity_binding_audit", {
|
|
3517
|
+
event_id: E("event_id").primaryKey(),
|
|
3518
|
+
commit_digest: E("commit_digest").notNull().references(() => xa.commit_digest),
|
|
3519
|
+
device_id: E("device_id").notNull(),
|
|
3520
|
+
previous_identity_id: E("previous_identity_id"),
|
|
3521
|
+
target_identity_id: E("target_identity_id").notNull(),
|
|
3522
|
+
action: E("action").notNull(),
|
|
3523
|
+
previous_assignment_version: S("previous_assignment_version"),
|
|
3524
|
+
resulting_assignment_version: S("resulting_assignment_version").notNull(),
|
|
3525
|
+
decided_by_identity_id: E("decided_by_identity_id").notNull(),
|
|
3526
|
+
decided_by_device_id: E("decided_by_device_id").notNull(),
|
|
3527
|
+
created_at: E("created_at").notNull()
|
|
3528
|
+
}, (e) => [D("idx_device_identity_binding_audit_commit_device").on(e.commit_digest, e.device_id), x("idx_device_identity_binding_audit_device_created").on(e.device_id, e.created_at, e.event_id)]), Ca = T("project_recipients", {
|
|
3529
|
+
canonical_project_identity: E("canonical_project_identity").notNull(),
|
|
3530
|
+
recipient_kind: E("recipient_kind").notNull(),
|
|
3531
|
+
recipient_id: E("recipient_id").notNull(),
|
|
3532
|
+
status: E("status").notNull(),
|
|
3533
|
+
provenance: E("provenance").notNull(),
|
|
3534
|
+
policy_revision: E("policy_revision").notNull(),
|
|
3535
|
+
migration_state: E("migration_state").notNull(),
|
|
3536
|
+
source_fingerprint: E("source_fingerprint"),
|
|
3537
|
+
idempotency_key: E("idempotency_key").notNull().unique(),
|
|
3538
|
+
created_at: E("created_at").notNull(),
|
|
3539
|
+
updated_at: E("updated_at").notNull()
|
|
3540
|
+
}, (e) => ({
|
|
3541
|
+
pk: C({ columns: [
|
|
3542
|
+
e.canonical_project_identity,
|
|
3543
|
+
e.recipient_kind,
|
|
3544
|
+
e.recipient_id
|
|
3545
|
+
] }),
|
|
3546
|
+
projectStatusIdx: x("idx_project_recipients_project_status").on(e.canonical_project_identity, e.status),
|
|
3547
|
+
recipientStatusIdx: x("idx_project_recipients_recipient_status").on(e.recipient_kind, e.recipient_id, e.status)
|
|
3548
|
+
})), wa = T("legacy_team_setup_drafts", {
|
|
3549
|
+
attempt_id: E("attempt_id").primaryKey(),
|
|
3550
|
+
candidate_id: E("candidate_id").notNull(),
|
|
3551
|
+
coordinator_id: E("coordinator_id").notNull(),
|
|
3552
|
+
group_id: E("group_id").notNull(),
|
|
3553
|
+
state: E("state").notNull().default("needs_setup"),
|
|
3554
|
+
display_name: E("display_name").notNull(),
|
|
3555
|
+
roster_fingerprint: E("roster_fingerprint").notNull(),
|
|
3556
|
+
projection_fingerprint: E("projection_fingerprint").notNull(),
|
|
3557
|
+
finish_digest: E("finish_digest"),
|
|
3558
|
+
safe_error_code: E("safe_error_code"),
|
|
3559
|
+
completed_team_id: E("completed_team_id"),
|
|
3560
|
+
created_at: E("created_at").notNull(),
|
|
3561
|
+
updated_at: E("updated_at").notNull(),
|
|
3562
|
+
completed_at: E("completed_at"),
|
|
3563
|
+
superseded_at: E("superseded_at")
|
|
3564
|
+
}, (e) => [
|
|
3565
|
+
x("idx_legacy_team_setup_drafts_candidate_state").on(e.candidate_id, e.state, e.created_at),
|
|
3566
|
+
x("idx_legacy_team_setup_drafts_state_updated").on(e.state, e.updated_at),
|
|
3567
|
+
x("idx_legacy_team_setup_drafts_finish_digest").on(e.finish_digest)
|
|
3568
|
+
]), Ta = T("legacy_team_setup_completions", {
|
|
3569
|
+
attempt_id: E("attempt_id").notNull(),
|
|
3570
|
+
finish_digest: E("finish_digest").notNull(),
|
|
3571
|
+
candidate_ref: E("candidate_ref").notNull(),
|
|
3572
|
+
confirmed_access_delta_digest: E("confirmed_access_delta_digest").notNull(),
|
|
3573
|
+
completed_team_id: E("completed_team_id").notNull(),
|
|
3574
|
+
response_json: E("response_json").notNull(),
|
|
3575
|
+
completed_at: E("completed_at").notNull(),
|
|
3576
|
+
created_at: E("created_at").notNull()
|
|
3577
|
+
}, (e) => [D("idx_legacy_team_setup_completions_attempt_finish").on(e.attempt_id, e.finish_digest), x("idx_legacy_team_setup_completions_exact_replay").on(e.candidate_ref, e.attempt_id, e.finish_digest, e.confirmed_access_delta_digest)]), Ea = T("legacy_team_setup_draft_devices", {
|
|
3578
|
+
attempt_id: E("attempt_id").notNull().references(() => wa.attempt_id, { onDelete: "cascade" }),
|
|
3579
|
+
device_id: E("device_id").notNull(),
|
|
3580
|
+
device_ref: E("device_ref").notNull(),
|
|
3581
|
+
key_fingerprint: E("key_fingerprint").notNull(),
|
|
3582
|
+
display_name: E("display_name").notNull(),
|
|
3583
|
+
enabled: S("enabled", { mode: "boolean" }).notNull(),
|
|
3584
|
+
existing_identity_id: E("existing_identity_id"),
|
|
3585
|
+
existing_assignment_version: S("existing_assignment_version"),
|
|
3586
|
+
verified_evidence_kind: E("verified_evidence_kind"),
|
|
3587
|
+
identity_evidence: E("identity_evidence"),
|
|
3588
|
+
decision: E("decision").notNull().default("unresolved"),
|
|
3589
|
+
target_identity_id: E("target_identity_id"),
|
|
3590
|
+
expected_assignment_kind: E("expected_assignment_kind"),
|
|
3591
|
+
expected_assignment_version: S("expected_assignment_version"),
|
|
3592
|
+
updated_at: E("updated_at").notNull()
|
|
3593
|
+
}, (e) => [
|
|
3594
|
+
C({ columns: [e.attempt_id, e.device_id] }),
|
|
3595
|
+
D("idx_legacy_team_setup_devices_attempt_ref").on(e.attempt_id, e.device_ref),
|
|
3596
|
+
x("idx_legacy_team_setup_devices_attempt_decision").on(e.attempt_id, e.decision)
|
|
3597
|
+
]), Da = T("legacy_team_setup_draft_projects", {
|
|
3598
|
+
attempt_id: E("attempt_id").notNull().references(() => wa.attempt_id, { onDelete: "cascade" }),
|
|
3599
|
+
project_ref: E("project_ref").notNull(),
|
|
3600
|
+
source_project_identity: E("source_project_identity").notNull(),
|
|
3601
|
+
display_name: E("display_name").notNull(),
|
|
3602
|
+
source_fingerprint: E("source_fingerprint").notNull(),
|
|
3603
|
+
resolution_kind: E("resolution_kind").notNull().default("unresolved"),
|
|
3604
|
+
resolved_project_identity: E("resolved_project_identity"),
|
|
3605
|
+
target_scope_id: E("target_scope_id"),
|
|
3606
|
+
updated_at: E("updated_at").notNull()
|
|
3607
|
+
}, (e) => [C({ columns: [e.attempt_id, e.project_ref] }), x("idx_legacy_team_setup_projects_attempt_resolution").on(e.attempt_id, e.resolution_kind)]), Oa = T("recipient_managed_project_projections", {
|
|
3608
|
+
canonical_project_identity: E("canonical_project_identity").notNull(),
|
|
3609
|
+
display_name: E("display_name").notNull(),
|
|
3610
|
+
managed_scope_id: E("managed_scope_id").notNull(),
|
|
3611
|
+
coordinator_id: E("coordinator_id").notNull(),
|
|
3612
|
+
group_id: E("group_id").notNull(),
|
|
3613
|
+
recipient_identity_id: E("recipient_identity_id").notNull(),
|
|
3614
|
+
accepting_device_id: E("accepting_device_id").notNull(),
|
|
3615
|
+
source_operation_id: E("source_operation_id").notNull(),
|
|
3616
|
+
reviewed_project_set_digest: E("reviewed_project_set_digest").notNull(),
|
|
3617
|
+
status: E("status").notNull().default("active"),
|
|
3618
|
+
accepted_at: E("accepted_at").notNull(),
|
|
3619
|
+
revoked_at: E("revoked_at"),
|
|
3620
|
+
created_at: E("created_at").notNull(),
|
|
3621
|
+
updated_at: E("updated_at").notNull()
|
|
3622
|
+
}, (e) => [
|
|
3623
|
+
C({ columns: [e.source_operation_id, e.canonical_project_identity] }),
|
|
3624
|
+
x("idx_recipient_managed_projects_identity_status").on(e.recipient_identity_id, e.status),
|
|
3625
|
+
x("idx_recipient_managed_projects_scope_authority").on(e.managed_scope_id, e.coordinator_id, e.group_id, e.status)
|
|
3626
|
+
]), ka = T("recipient_policy_authority_states", {
|
|
3627
|
+
canonical_project_identity: E("canonical_project_identity").primaryKey(),
|
|
3628
|
+
authority_state: E("authority_state").notNull().default("legacy"),
|
|
3629
|
+
generation: S("generation").notNull().default(0),
|
|
3630
|
+
desired_devices_digest: E("desired_devices_digest"),
|
|
3631
|
+
current_devices_digest: E("current_devices_digest"),
|
|
3632
|
+
stable_parity_evidence_digest: E("stable_parity_evidence_digest"),
|
|
3633
|
+
stable_parity_passed_at: E("stable_parity_passed_at"),
|
|
3634
|
+
fresh_snapshot_fingerprint: E("fresh_snapshot_fingerprint"),
|
|
3635
|
+
fresh_snapshot_observed_at: E("fresh_snapshot_observed_at"),
|
|
3636
|
+
safe_error_code: E("safe_error_code"),
|
|
3637
|
+
state_changed_at: E("state_changed_at").notNull(),
|
|
3638
|
+
last_error_at: E("last_error_at"),
|
|
3639
|
+
attempt_count: S("attempt_count").notNull().default(0),
|
|
3640
|
+
last_attempt_at: E("last_attempt_at"),
|
|
3641
|
+
wake_epoch: S("wake_epoch").notNull().default(0),
|
|
3642
|
+
last_completed_at: E("last_completed_at"),
|
|
3643
|
+
lease_owner: E("lease_owner"),
|
|
3644
|
+
lease_acquired_at: E("lease_acquired_at"),
|
|
3645
|
+
lease_expires_at: E("lease_expires_at"),
|
|
3646
|
+
created_at: E("created_at").notNull(),
|
|
3647
|
+
updated_at: E("updated_at").notNull()
|
|
3648
|
+
}), Aa = T("recipient_policy_reconciliation_steps", {
|
|
3649
|
+
canonical_project_identity: E("canonical_project_identity").notNull(),
|
|
3650
|
+
generation: S("generation").notNull(),
|
|
3651
|
+
step_key: E("step_key").notNull(),
|
|
3652
|
+
effect_id: E("effect_id").notNull(),
|
|
3653
|
+
payload_digest: E("payload_digest").notNull(),
|
|
3654
|
+
status: E("status").notNull().default("pending"),
|
|
3655
|
+
attempt_count: S("attempt_count").notNull().default(0),
|
|
3656
|
+
started_at: E("started_at"),
|
|
3657
|
+
completed_at: E("completed_at"),
|
|
3658
|
+
last_attempt_at: E("last_attempt_at"),
|
|
3659
|
+
safe_error_code: E("safe_error_code"),
|
|
3660
|
+
error_at: E("error_at"),
|
|
3661
|
+
lease_owner: E("lease_owner"),
|
|
3662
|
+
lease_acquired_at: E("lease_acquired_at"),
|
|
3663
|
+
lease_expires_at: E("lease_expires_at"),
|
|
3664
|
+
created_at: E("created_at").notNull(),
|
|
3665
|
+
updated_at: E("updated_at").notNull()
|
|
3666
|
+
}, (e) => [
|
|
3667
|
+
C({ columns: [
|
|
3668
|
+
e.canonical_project_identity,
|
|
3669
|
+
e.generation,
|
|
3670
|
+
e.step_key
|
|
3671
|
+
] }),
|
|
3672
|
+
D("idx_recipient_policy_reconciliation_steps_effect").on(e.effect_id),
|
|
3673
|
+
x("idx_recipient_policy_reconciliation_steps_status").on(e.canonical_project_identity, e.status),
|
|
3674
|
+
x("idx_recipient_policy_reconciliation_steps_pending_refresh").on(e.canonical_project_identity, e.generation, e.step_key).where(b`${e.status} IN ('pending', 'running', 'failed') AND ${e.step_key} GLOB 'refresh-after-revocations-v2:*'`)
|
|
3675
|
+
]), ja = T("recipient_policy_deny_overlays", {
|
|
3676
|
+
canonical_project_identity: E("canonical_project_identity").notNull(),
|
|
3677
|
+
scope_id: E("scope_id").notNull(),
|
|
3678
|
+
device_id: E("device_id").notNull(),
|
|
3679
|
+
generation: S("generation").notNull(),
|
|
3680
|
+
reason_code: E("reason_code").notNull(),
|
|
3681
|
+
created_at: E("created_at").notNull(),
|
|
3682
|
+
updated_at: E("updated_at").notNull()
|
|
3683
|
+
}, (e) => [C({ columns: [
|
|
3684
|
+
e.canonical_project_identity,
|
|
3685
|
+
e.scope_id,
|
|
3686
|
+
e.device_id
|
|
3687
|
+
] }), x("idx_recipient_policy_deny_overlays_scope_device").on(e.scope_id, e.device_id)]), Ma = {
|
|
3688
|
+
deviceIdentityBindingCommits: xa,
|
|
3689
|
+
deviceIdentityBindingAudit: Sa,
|
|
3690
|
+
sessions: X,
|
|
3691
|
+
replicationScopes: Mi,
|
|
3692
|
+
projectScopeMappings: Ni,
|
|
3693
|
+
scopeMemberships: Pi,
|
|
3694
|
+
artifacts: Fi,
|
|
3695
|
+
memoryItems: Z,
|
|
3696
|
+
memoryFileRefs: Ii,
|
|
3697
|
+
memoryConceptRefs: Li,
|
|
3698
|
+
usageEvents: Ri,
|
|
3699
|
+
retrievalAttempts: Q,
|
|
3700
|
+
retrievalExposures: zi,
|
|
3701
|
+
outcomeEvidence: Bi,
|
|
3702
|
+
attributionAssessments: Vi,
|
|
3703
|
+
attributionAssessmentEvidence: Hi,
|
|
3704
|
+
rawEvents: Wi,
|
|
3705
|
+
rawEventSessions: Gi,
|
|
3706
|
+
opencodeSessions: qi,
|
|
3707
|
+
piImportState: Ki,
|
|
3708
|
+
rawEventFlushBatches: Ji,
|
|
3709
|
+
userPrompts: Yi,
|
|
3710
|
+
sessionSummaries: Xi,
|
|
3711
|
+
replicationOps: Zi,
|
|
3712
|
+
replicationCursors: Qi,
|
|
3713
|
+
replicationCursorsV2: $i,
|
|
3714
|
+
syncPeers: ea,
|
|
3715
|
+
syncNonces: na,
|
|
3716
|
+
syncDevice: ra,
|
|
3717
|
+
syncAttempts: ia,
|
|
3718
|
+
syncScopeRejections: aa,
|
|
3719
|
+
syncDaemonState: oa,
|
|
3720
|
+
syncResetState: sa,
|
|
3721
|
+
syncResetStateV2: ca,
|
|
3722
|
+
syncRetentionStateV2: ua,
|
|
3723
|
+
rawEventIngestSamples: da,
|
|
3724
|
+
rawEventIngestStats: fa,
|
|
3725
|
+
coordinatorGroupPreferences: pa,
|
|
3726
|
+
actors: ma,
|
|
3727
|
+
recipientPolicyReviewResolutions: ha,
|
|
3728
|
+
coordinatorEnrollmentReconciliationIssues: ga,
|
|
3729
|
+
policyTeams: _a,
|
|
3730
|
+
policyTeamMemberships: va,
|
|
3731
|
+
policyTeamDeviceDecisions: ya,
|
|
3732
|
+
identityDevices: ba,
|
|
3733
|
+
projectRecipients: Ca,
|
|
3734
|
+
legacyTeamSetupDrafts: wa,
|
|
3735
|
+
legacyTeamSetupCompletions: Ta,
|
|
3736
|
+
legacyTeamSetupDraftDevices: Ea,
|
|
3737
|
+
legacyTeamSetupDraftProjects: Da,
|
|
3738
|
+
recipientManagedProjectProjections: Oa,
|
|
3739
|
+
recipientPolicyAuthorityStates: ka,
|
|
3740
|
+
recipientPolicyReconciliationSteps: Aa,
|
|
3741
|
+
recipientPolicyDenyOverlays: ja
|
|
3742
|
+
};
|
|
3743
|
+
//#endregion
|
|
3744
|
+
//#region src/recipient-policy-deny-overlay.ts
|
|
3745
|
+
function Na(e) {
|
|
3746
|
+
return {
|
|
3747
|
+
canonicalProjectIdentity: String(e.canonical_project_identity),
|
|
3748
|
+
scopeId: String(e.scope_id),
|
|
3749
|
+
deviceId: String(e.device_id),
|
|
3750
|
+
generation: Number(e.generation),
|
|
3751
|
+
reasonCode: String(e.reason_code),
|
|
3752
|
+
createdAt: String(e.created_at),
|
|
3753
|
+
updatedAt: String(e.updated_at)
|
|
3754
|
+
};
|
|
3755
|
+
}
|
|
3756
|
+
function Pa(e, t) {
|
|
3757
|
+
let n = e.prepare("SELECT * FROM recipient_policy_deny_overlays\n WHERE scope_id = ? AND device_id = ?\n ORDER BY canonical_project_identity\n LIMIT 1").get(t.scopeId, t.deviceId);
|
|
3758
|
+
return n ? Na(n) : null;
|
|
3759
|
+
}
|
|
3760
|
+
//#endregion
|
|
3761
|
+
//#region src/scope-membership-snapshot.ts
|
|
3762
|
+
function Fa(e, t) {
|
|
3763
|
+
if (!e || typeof e != "object" || Array.isArray(e)) throw Error("Invalid current scope snapshot.");
|
|
3764
|
+
let n = e;
|
|
3765
|
+
if (n[t] !== 1 || !Array.isArray(n.items)) throw Error("Current scope snapshot version 1 and items required.");
|
|
3766
|
+
return n;
|
|
3767
|
+
}
|
|
3768
|
+
function Ia(e, r) {
|
|
3769
|
+
t(e, l);
|
|
3770
|
+
let i = e;
|
|
3771
|
+
if (n(i, r)) throw Error("Invalid scope source or status.");
|
|
3772
|
+
return i;
|
|
3773
|
+
}
|
|
3774
|
+
function La(e, t) {
|
|
3775
|
+
let n = Fa(e, "version").items.map((e) => Ia(e, t));
|
|
3776
|
+
if (new Set(n.map((e) => e.scope_id)).size !== n.length) throw Error("Duplicate scope in catalog.");
|
|
3777
|
+
return n;
|
|
3778
|
+
}
|
|
3779
|
+
function Ra(e, t) {
|
|
3780
|
+
return Object.fromEntries(t.map((t) => [t, e[t]]));
|
|
3781
|
+
}
|
|
3782
|
+
function za(n, o) {
|
|
3783
|
+
if (!n || typeof n != "object" || Array.isArray(n)) throw Error("Invalid current scope member.");
|
|
3784
|
+
let s = n;
|
|
3785
|
+
t(s.membership, e), t(s.enrollment, i);
|
|
3786
|
+
let { membership: c, enrollment: l } = s, u = r(l.public_key);
|
|
3787
|
+
if (!a(o, c) || l.enabled !== 1 || l.group_id !== o.group_id || l.device_id !== c.device_id || u.kind !== "ed25519" || d("sha256").update(u.blob).digest("hex") !== s.key_id) throw Error("Current scope member evidence mismatch.");
|
|
3788
|
+
return {
|
|
3789
|
+
membership: Ra(c, e),
|
|
3790
|
+
enrollment: Ra(l, i),
|
|
3791
|
+
key_id: s.key_id
|
|
3792
|
+
};
|
|
3793
|
+
}
|
|
3794
|
+
function Ba(e, t, n, r) {
|
|
3795
|
+
let i = Fa(e, "authorization_version"), a = Ia(i.scope, n);
|
|
3796
|
+
if (a.scope_id !== t.scope_id || a.membership_epoch < t.membership_epoch || a.coordinator_id !== t.coordinator_id) throw Error("Current scope snapshot source mismatch.");
|
|
3797
|
+
let o = i.items.map((e) => za(e, a));
|
|
3798
|
+
if (new Set(o.map((e) => e.membership.device_id)).size !== o.length) throw Error("Duplicate device in current scope snapshot.");
|
|
3799
|
+
let s = Ra(a, l);
|
|
3800
|
+
return {
|
|
3801
|
+
scope: {
|
|
3802
|
+
...s,
|
|
3803
|
+
coordinator_id: r
|
|
3804
|
+
},
|
|
3805
|
+
memberships: o.map((e) => ({
|
|
3806
|
+
...e.membership,
|
|
3807
|
+
coordinator_id: r,
|
|
3808
|
+
group_id: n
|
|
3809
|
+
})),
|
|
3810
|
+
sourceCoordinatorId: a.coordinator_id,
|
|
3811
|
+
evidence: {
|
|
3812
|
+
authorization_version: 1,
|
|
3813
|
+
scope: s,
|
|
3814
|
+
items: o
|
|
3815
|
+
}
|
|
3816
|
+
};
|
|
3817
|
+
}
|
|
3818
|
+
//#endregion
|
|
3819
|
+
//#region src/scope-membership-evidence.ts
|
|
3820
|
+
var Va = [
|
|
3821
|
+
"scope_id",
|
|
3822
|
+
"kind",
|
|
3823
|
+
"authority_type",
|
|
3824
|
+
"coordinator_id",
|
|
3825
|
+
"group_id",
|
|
3826
|
+
"manifest_issuer_device_id",
|
|
3827
|
+
"membership_epoch",
|
|
3828
|
+
"manifest_hash",
|
|
3829
|
+
"status"
|
|
3830
|
+
], Ha = [
|
|
3831
|
+
"scope_id",
|
|
3832
|
+
"device_id",
|
|
3833
|
+
"role",
|
|
3834
|
+
"status",
|
|
3835
|
+
"membership_epoch",
|
|
3836
|
+
"coordinator_id",
|
|
3837
|
+
"group_id",
|
|
3838
|
+
"manifest_issuer_device_id",
|
|
3839
|
+
"manifest_hash",
|
|
3840
|
+
"signed_manifest_json"
|
|
3841
|
+
];
|
|
3842
|
+
function Ua(e) {
|
|
3843
|
+
return !!e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get("scope_membership_authorization_evidence");
|
|
3844
|
+
}
|
|
3845
|
+
function Wa(e) {
|
|
3846
|
+
e.exec("CREATE TABLE IF NOT EXISTS scope_membership_authorization_evidence (\n coordinator_id TEXT NOT NULL, group_id TEXT NOT NULL,\n scope_id TEXT NOT NULL, device_id TEXT NOT NULL, evidence_json TEXT NOT NULL,\n PRIMARY KEY (coordinator_id, group_id, scope_id, device_id)\n )");
|
|
3847
|
+
}
|
|
3848
|
+
function Ga(e, t, n) {
|
|
3849
|
+
return n.every((n) => e[n] === t[n]);
|
|
3850
|
+
}
|
|
3851
|
+
function Ka(e, t, n) {
|
|
3852
|
+
let r = e.memberships[0];
|
|
3853
|
+
return r ? Ga(e.scope, t, Va) && e.memberships.length === 1 && Ga(r, n, Ha) : !1;
|
|
3854
|
+
}
|
|
3855
|
+
function qa(e, t) {
|
|
3856
|
+
try {
|
|
3857
|
+
let n = JSON.parse(e), r = Ba(n, n.scope, t.groupId, t.coordinatorId);
|
|
3858
|
+
return r.evidence.items.length === 1 ? r : null;
|
|
3859
|
+
} catch {
|
|
3860
|
+
return null;
|
|
3861
|
+
}
|
|
3862
|
+
}
|
|
3863
|
+
function Ja(e, t) {
|
|
3864
|
+
let n = e.evidence.items[t];
|
|
3865
|
+
if (!n) throw Error("Scope authorization evidence unavailable.");
|
|
3866
|
+
return {
|
|
3867
|
+
...e.evidence,
|
|
3868
|
+
items: [n]
|
|
3869
|
+
};
|
|
3870
|
+
}
|
|
3871
|
+
function Ya(e, t, n, r) {
|
|
3872
|
+
if (r.removalOnly) {
|
|
3873
|
+
Za(e, t, n);
|
|
3874
|
+
return;
|
|
3875
|
+
}
|
|
3876
|
+
Wa(e), e.prepare("DELETE FROM scope_membership_authorization_evidence WHERE coordinator_id = ? AND group_id = ?").run(n.coordinatorId, n.groupId);
|
|
3877
|
+
let i = e.prepare("INSERT INTO scope_membership_authorization_evidence\n (coordinator_id, group_id, scope_id, device_id, evidence_json) VALUES (?, ?, ?, ?, ?)");
|
|
3878
|
+
for (let e of t) for (let [t, r] of e.memberships.entries()) i.run(n.coordinatorId, n.groupId, e.scope.scope_id, r.device_id, JSON.stringify(Ja(e, t)));
|
|
3879
|
+
}
|
|
3880
|
+
function Xa(e, t) {
|
|
3881
|
+
let n = e.evidence.items[0], r = t.evidence.items[0], i = t.memberships[0];
|
|
3882
|
+
return !n || !r || !i ? !1 : Ka(e, t.scope, i) && e.sourceCoordinatorId === t.sourceCoordinatorId && n.key_id === r.key_id && Ga(n.membership, r.membership, Ha) && Ga(n.enrollment, r.enrollment, [
|
|
3883
|
+
"group_id",
|
|
3884
|
+
"device_id",
|
|
3885
|
+
"fingerprint",
|
|
3886
|
+
"enabled"
|
|
3887
|
+
]);
|
|
3888
|
+
}
|
|
3889
|
+
function Za(e, t, n) {
|
|
3890
|
+
if (!Ua(e)) return;
|
|
3891
|
+
let r = e.prepare("SELECT scope_id, device_id, evidence_json\n FROM scope_membership_authorization_evidence WHERE coordinator_id = ? AND group_id = ?").all(n.coordinatorId, n.groupId), i = e.prepare("DELETE FROM scope_membership_authorization_evidence\n WHERE coordinator_id = ? AND group_id = ? AND scope_id = ? AND device_id = ?");
|
|
3892
|
+
for (let e of r) {
|
|
3893
|
+
let r = t.find((t) => t.scope.scope_id === e.scope_id), a = r?.memberships.findIndex((t) => t.device_id === e.device_id) ?? -1, o = qa(e.evidence_json, n), s = r && a >= 0 ? Ba(Ja(r, a), r.evidence.scope, n.groupId, n.coordinatorId) : null;
|
|
3894
|
+
(!o || !s || !Xa(o, s)) && i.run(n.coordinatorId, n.groupId, e.scope_id, e.device_id);
|
|
3895
|
+
}
|
|
3896
|
+
}
|
|
3897
|
+
function Qa(e, t, n, i) {
|
|
3898
|
+
try {
|
|
3899
|
+
if (!t.coordinator_id || !t.group_id || !Ua(e)) return null;
|
|
3900
|
+
let a = {
|
|
3901
|
+
coordinatorId: t.coordinator_id,
|
|
3902
|
+
groupId: t.group_id
|
|
3903
|
+
}, o = e.prepare("SELECT evidence_json FROM scope_membership_authorization_evidence\n WHERE coordinator_id = ? AND group_id = ? AND scope_id = ? AND device_id = ?").get(a.coordinatorId, a.groupId, t.scope_id, n.device_id), s = o && qa(o.evidence_json, a);
|
|
3904
|
+
if (!s || !Ka(s, t, n)) return null;
|
|
3905
|
+
let c = s.evidence.items[0]?.key_id;
|
|
3906
|
+
if (!c) return null;
|
|
3907
|
+
if (i !== void 0) {
|
|
3908
|
+
let e = r(i);
|
|
3909
|
+
if (e.kind !== "ed25519" || d("sha256").update(e.blob).digest("hex") !== c) return null;
|
|
3910
|
+
}
|
|
3911
|
+
return c;
|
|
3912
|
+
} catch {
|
|
3913
|
+
return null;
|
|
3914
|
+
}
|
|
3915
|
+
}
|
|
3916
|
+
//#endregion
|
|
3917
|
+
//#region src/scope-membership-cache-read.ts
|
|
3918
|
+
var $a = 6e4;
|
|
3919
|
+
function $(e) {
|
|
3920
|
+
return e?.trim() || null;
|
|
3921
|
+
}
|
|
3922
|
+
function eo(e, t) {
|
|
3923
|
+
return e.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get("scope_membership_cache_state") ? t ? e.prepare("SELECT coordinator_id, group_id, last_refresh_at, last_success_at, last_error, updated_at\n FROM scope_membership_cache_state\n WHERE coordinator_id = ? AND group_id = ?").all(t.coordinatorId, t.groupId) : e.prepare("SELECT coordinator_id, group_id, last_refresh_at, last_success_at, last_error, updated_at\n FROM scope_membership_cache_state\n ORDER BY coordinator_id ASC, group_id ASC").all() : [];
|
|
3924
|
+
}
|
|
3925
|
+
function to(e, t) {
|
|
3926
|
+
if (e.length === 0) return "unknown";
|
|
3927
|
+
if (e.some((e) => $(e.last_error) != null)) return "stale";
|
|
3928
|
+
let n = t.maxAgeMs ?? 6e4, r = (t.now ?? /* @__PURE__ */ new Date()).getTime();
|
|
3929
|
+
return e.some((e) => {
|
|
3930
|
+
let t = Date.parse(e.last_success_at ?? "");
|
|
3931
|
+
return !Number.isFinite(t) || r - t > n;
|
|
3932
|
+
}) ? "stale" : "fresh";
|
|
3933
|
+
}
|
|
3934
|
+
function no(e) {
|
|
3935
|
+
return !e.scope_label || !e.scope_kind || !e.scope_authority_type ? null : {
|
|
3936
|
+
scope_id: e.scope_id,
|
|
3937
|
+
label: e.scope_label,
|
|
3938
|
+
kind: e.scope_kind,
|
|
3939
|
+
authority_type: e.scope_authority_type,
|
|
3940
|
+
coordinator_id: e.scope_coordinator_id,
|
|
3941
|
+
group_id: e.scope_group_id,
|
|
3942
|
+
manifest_issuer_device_id: e.scope_manifest_issuer_device_id,
|
|
3943
|
+
membership_epoch: e.scope_membership_epoch ?? e.membership_epoch,
|
|
3944
|
+
manifest_hash: e.scope_manifest_hash,
|
|
3945
|
+
status: e.scope_status ?? "active",
|
|
3946
|
+
created_at: e.scope_created_at ?? e.updated_at,
|
|
3947
|
+
updated_at: e.scope_updated_at ?? e.updated_at
|
|
3948
|
+
};
|
|
3949
|
+
}
|
|
3950
|
+
function ro(e, t, n) {
|
|
3951
|
+
let r = n ? " AND coordinator_id = ? AND group_id = ?" : "", i = n ? [
|
|
3952
|
+
t,
|
|
3953
|
+
n.coordinatorId,
|
|
3954
|
+
n.groupId
|
|
3955
|
+
] : [t];
|
|
3956
|
+
return e.prepare(`SELECT scope_id, label, kind, authority_type, coordinator_id, group_id,
|
|
3957
|
+
manifest_issuer_device_id, membership_epoch, manifest_hash, status, created_at, updated_at
|
|
3958
|
+
FROM replication_scopes
|
|
3959
|
+
WHERE scope_id = ?${r}
|
|
3960
|
+
LIMIT 1`).get(...i) ?? null;
|
|
3961
|
+
}
|
|
3962
|
+
function io(e) {
|
|
3963
|
+
return {
|
|
3964
|
+
scope_id: e.scope_id,
|
|
3965
|
+
device_id: e.device_id,
|
|
3966
|
+
role: e.role,
|
|
3967
|
+
status: e.status,
|
|
3968
|
+
membership_epoch: e.membership_epoch,
|
|
3969
|
+
coordinator_id: e.coordinator_id,
|
|
3970
|
+
group_id: e.group_id,
|
|
3971
|
+
manifest_issuer_device_id: e.manifest_issuer_device_id,
|
|
3972
|
+
manifest_hash: e.manifest_hash,
|
|
3973
|
+
signed_manifest_json: e.signed_manifest_json,
|
|
3974
|
+
updated_at: e.updated_at
|
|
3975
|
+
};
|
|
3976
|
+
}
|
|
3977
|
+
function ao(e) {
|
|
3978
|
+
return `SELECT
|
|
3979
|
+
sm.scope_id,
|
|
3980
|
+
sm.device_id,
|
|
3981
|
+
sm.role,
|
|
3982
|
+
sm.status,
|
|
3983
|
+
sm.membership_epoch,
|
|
3984
|
+
sm.coordinator_id,
|
|
3985
|
+
sm.group_id,
|
|
3986
|
+
sm.manifest_issuer_device_id,
|
|
3987
|
+
sm.manifest_hash,
|
|
3988
|
+
sm.signed_manifest_json,
|
|
3989
|
+
sm.updated_at,
|
|
3990
|
+
rs.label AS scope_label,
|
|
3991
|
+
rs.kind AS scope_kind,
|
|
3992
|
+
rs.authority_type AS scope_authority_type,
|
|
3993
|
+
rs.coordinator_id AS scope_coordinator_id,
|
|
3994
|
+
rs.group_id AS scope_group_id,
|
|
3995
|
+
rs.manifest_issuer_device_id AS scope_manifest_issuer_device_id,
|
|
3996
|
+
rs.membership_epoch AS scope_membership_epoch,
|
|
3997
|
+
rs.manifest_hash AS scope_manifest_hash,
|
|
3998
|
+
rs.status AS scope_status,
|
|
3999
|
+
rs.created_at AS scope_created_at,
|
|
4000
|
+
rs.updated_at AS scope_updated_at
|
|
4001
|
+
FROM scope_memberships sm
|
|
4002
|
+
LEFT JOIN replication_scopes rs ON rs.scope_id = sm.scope_id
|
|
4003
|
+
${e}`;
|
|
4004
|
+
}
|
|
4005
|
+
function oo(e, t) {
|
|
4006
|
+
let n = $(e?.coordinator_id) ?? t?.coordinatorId, r = $(e?.group_id) ?? t?.groupId;
|
|
4007
|
+
return n && r ? {
|
|
4008
|
+
coordinatorId: n,
|
|
4009
|
+
groupId: r
|
|
4010
|
+
} : null;
|
|
4011
|
+
}
|
|
4012
|
+
function so(e) {
|
|
4013
|
+
let t = $(e?.coordinator_id), n = $(e?.group_id);
|
|
4014
|
+
return t && n ? {
|
|
4015
|
+
coordinatorId: t,
|
|
4016
|
+
groupId: n
|
|
4017
|
+
} : null;
|
|
4018
|
+
}
|
|
4019
|
+
function co(e, t, n = {}) {
|
|
4020
|
+
let r = $(t);
|
|
4021
|
+
if (!r) throw Error("device_id is required.");
|
|
4022
|
+
let i = [r], a = n.authority ? " AND COALESCE(sm.coordinator_id, rs.coordinator_id) = ? AND COALESCE(sm.group_id, rs.group_id) = ?" : "";
|
|
4023
|
+
n.authority && i.push(n.authority.coordinatorId, n.authority.groupId);
|
|
4024
|
+
let o = e.prepare(`${ao(`WHERE sm.device_id = ? AND sm.status = 'active' AND rs.scope_id IS NOT NULL AND rs.status = 'active' AND sm.membership_epoch >= rs.membership_epoch${a}`)} ORDER BY sm.scope_id ASC`).all(...i), s = eo(e, n.authority ?? null), c = o.filter((t) => Pa(e, {
|
|
4025
|
+
scopeId: t.scope_id,
|
|
4026
|
+
deviceId: r
|
|
4027
|
+
}) == null);
|
|
4028
|
+
return {
|
|
4029
|
+
deviceId: r,
|
|
4030
|
+
freshness: to(s, n),
|
|
4031
|
+
memberships: c.map((e) => ({
|
|
4032
|
+
...io(e),
|
|
4033
|
+
scope: no(e)
|
|
4034
|
+
})),
|
|
4035
|
+
cacheStates: s
|
|
4036
|
+
};
|
|
4037
|
+
}
|
|
4038
|
+
function lo(e, t) {
|
|
4039
|
+
if (!$(t.deviceId) || !$(t.scopeId)) throw Error("device_id and scope_id are required.");
|
|
4040
|
+
return fo(e, t);
|
|
4041
|
+
}
|
|
4042
|
+
function uo(e, t) {
|
|
4043
|
+
let n = fo(e, t);
|
|
4044
|
+
if (!n.authorized || n.scope?.authority_type !== "coordinator") return {
|
|
4045
|
+
...n,
|
|
4046
|
+
keyId: null
|
|
4047
|
+
};
|
|
4048
|
+
let r = n.membership && Qa(e, n.scope, n.membership, t.expectedPublicKey);
|
|
4049
|
+
return r ? {
|
|
4050
|
+
...n,
|
|
4051
|
+
keyId: r
|
|
4052
|
+
} : {
|
|
4053
|
+
...n,
|
|
4054
|
+
authorized: !1,
|
|
4055
|
+
state: "not_authorized",
|
|
4056
|
+
keyId: null
|
|
4057
|
+
};
|
|
4058
|
+
}
|
|
4059
|
+
function fo(e, t) {
|
|
4060
|
+
let n = $(t.deviceId), r = $(t.scopeId);
|
|
4061
|
+
if (!n || !r) throw Error("device_id and scope_id are required.");
|
|
4062
|
+
let { membership: i, scope: a } = po(e, {
|
|
4063
|
+
...t,
|
|
4064
|
+
deviceId: n,
|
|
4065
|
+
scopeId: r
|
|
4066
|
+
}), s = eo(e, oo(i, t.authority ?? so(a))), l = c({
|
|
4067
|
+
membershipEpoch: i?.membership_epoch ?? null,
|
|
4068
|
+
requiredEpoch: a?.membership_epoch ?? null
|
|
4069
|
+
}), u = mo({
|
|
4070
|
+
membership: i,
|
|
4071
|
+
scope: a,
|
|
4072
|
+
epoch: l,
|
|
4073
|
+
policyDenied: !!Pa(e, {
|
|
4074
|
+
deviceId: n,
|
|
4075
|
+
scopeId: r
|
|
4076
|
+
})
|
|
4077
|
+
}), d = null;
|
|
4078
|
+
return u === "revoked" && i && (d = o({
|
|
4079
|
+
scopeId: r,
|
|
4080
|
+
deviceId: n,
|
|
4081
|
+
membershipEpoch: i.membership_epoch
|
|
4082
|
+
})), {
|
|
4083
|
+
deviceId: n,
|
|
4084
|
+
scopeId: r,
|
|
4085
|
+
authorized: u === "authorized",
|
|
4086
|
+
state: u,
|
|
4087
|
+
freshness: to(s, t),
|
|
4088
|
+
epoch: l,
|
|
4089
|
+
revocation: d,
|
|
4090
|
+
membership: i,
|
|
4091
|
+
scope: a,
|
|
4092
|
+
cacheStates: s
|
|
4093
|
+
};
|
|
4094
|
+
}
|
|
4095
|
+
function po(e, t) {
|
|
4096
|
+
let n = t.authority ? " AND COALESCE(sm.coordinator_id, rs.coordinator_id) = ? AND COALESCE(sm.group_id, rs.group_id) = ?" : "", r = t.authority ? [
|
|
4097
|
+
t.deviceId,
|
|
4098
|
+
t.scopeId,
|
|
4099
|
+
t.authority.coordinatorId,
|
|
4100
|
+
t.authority.groupId
|
|
4101
|
+
] : [t.deviceId, t.scopeId], i = e.prepare(`${ao(`WHERE sm.device_id = ? AND sm.scope_id = ?${n} LIMIT 1`)}`).get(...r);
|
|
4102
|
+
return {
|
|
4103
|
+
membership: i ? io(i) : null,
|
|
4104
|
+
scope: i ? no(i) : ro(e, t.scopeId, t.authority ?? null)
|
|
4105
|
+
};
|
|
4106
|
+
}
|
|
4107
|
+
function mo(e) {
|
|
4108
|
+
let { membership: t, scope: n, epoch: r, policyDenied: i } = e;
|
|
4109
|
+
return i ? "policy_denied" : t ? t.status === "revoked" ? "revoked" : n?.status && n.status !== "active" ? "scope_inactive" : n ? r.stale ? "stale_epoch" : t.status === "active" ? "authorized" : "not_authorized" : "scope_unknown" : "not_authorized";
|
|
4110
|
+
}
|
|
4111
|
+
//#endregion
|
|
4112
|
+
export { Oi as $, Rt as $t, X as A, pn as At, Ri as B, N as Bt, $i as C, ke as Cn, Fn as Ct, ji as D, De as Dn, An as Dt, Q as E, Ae as En, Tn as Et, ea as F, Ge as Ft, J as G, Qt as Gt, K as H, Ft as Ht, sa as I, F as It, wi as J, B as Jt, Hr as K, Xt as Kt, ca as L, lt as Lt, oa as M, V as Mt, ra as N, an as Nt, Pi as O, be as On, mn as Ot, na as P, on as Pt, Di as Q, Vt as Qt, la as R, Ke as Rt, Qi as S, Fe as Sn, Ln as St, Mi as T, we as Tn, En as Tt, Ir as U, It as Ut, Yi as V, Je as Vt, Zr as W, z as Wt, ci as X, Ve as Xt, qr as Y, P as Yt, li as Z, Lt as Zt, Ji as _, At as _n, Un as _t, ro as a, it as an, ki as at, Gi as b, ze as bn, Bn as bt, Ba as c, Ut as cn, Fr as ct, ma as d, $t as dn, pr as dt, Ht as en, Vr as et, Fi as f, Kt as fn, Dr as ft, Bi as g, j as gn, zn as gt, qi as h, A as hn, Wn as ht, co as i, Xe as in, q as it, ia as j, tn as jt, Xi as k, hn as kt, Na as l, Gt as ln, Mr as lt, Z as m, qt as mn, er as mt, lo as n, Ot as nn, ui as nt, Ya as o, We as on, Ai as ot, pa as p, en as pn, Or as pt, Ur as q, Zt as qt, uo as r, Ye as rn, Lr as rt, La as s, Wt as sn, G as st, $a as t, M as tn, Yr as tt, Pa as u, qe as un, Nr as ut, da as v, jt as vn, Vn as vt, Zi as w, xe as wn, jn as wt, Wi as x, Ie as xn, In as xt, fa as y, k as yn, Hn as yt, ua as z, kt as zt };
|
|
4113
|
+
|
|
4114
|
+
//# sourceMappingURL=scope-membership-cache-read-B6z47l2W.js.map
|