@getengram/cli 0.6.1 → 0.7.0
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/README.md +1 -1
- package/dist/commands/auth.d.ts.map +1 -1
- package/dist/commands/auth.js +38 -11
- package/dist/commands/auth.js.map +1 -1
- package/dist/commands/conversations.d.ts.map +1 -1
- package/dist/commands/conversations.js +8 -2
- package/dist/commands/conversations.js.map +1 -1
- package/dist/commands/exclude.d.ts.map +1 -1
- package/dist/commands/exclude.js +73 -21
- package/dist/commands/exclude.js.map +1 -1
- package/dist/commands/import.d.ts +30 -3
- package/dist/commands/import.d.ts.map +1 -1
- package/dist/commands/import.js +374 -45
- package/dist/commands/import.js.map +1 -1
- package/dist/commands/login.d.ts.map +1 -1
- package/dist/commands/login.js +144 -29
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/search.js +2 -2
- package/dist/commands/search.js.map +1 -1
- package/dist/commands/status.d.ts +16 -0
- package/dist/commands/status.d.ts.map +1 -0
- package/dist/commands/status.js +51 -0
- package/dist/commands/status.js.map +1 -0
- package/dist/commands/store.d.ts.map +1 -1
- package/dist/commands/store.js +19 -3
- package/dist/commands/store.js.map +1 -1
- package/dist/commands/upgrade.d.ts +24 -0
- package/dist/commands/upgrade.d.ts.map +1 -1
- package/dist/commands/upgrade.js +64 -15
- package/dist/commands/upgrade.js.map +1 -1
- package/dist/commands/usage.d.ts +44 -0
- package/dist/commands/usage.d.ts.map +1 -1
- package/dist/commands/usage.js +79 -19
- package/dist/commands/usage.js.map +1 -1
- package/dist/commands/vault.d.ts +11 -2
- package/dist/commands/vault.d.ts.map +1 -1
- package/dist/commands/vault.js +372 -53
- package/dist/commands/vault.js.map +1 -1
- package/dist/config-file.d.ts +74 -0
- package/dist/config-file.d.ts.map +1 -0
- package/dist/config-file.js +152 -0
- package/dist/config-file.js.map +1 -0
- package/dist/config-guard.d.ts +96 -0
- package/dist/config-guard.d.ts.map +1 -0
- package/dist/config-guard.js +184 -0
- package/dist/config-guard.js.map +1 -0
- package/dist/config.d.ts +48 -4
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +101 -12
- package/dist/config.js.map +1 -1
- package/dist/daemon/as-root.d.ts +46 -0
- package/dist/daemon/as-root.d.ts.map +1 -0
- package/dist/daemon/as-root.js +64 -0
- package/dist/daemon/as-root.js.map +1 -0
- package/dist/daemon/backoff.d.ts +26 -0
- package/dist/daemon/backoff.d.ts.map +1 -0
- package/dist/daemon/backoff.js +37 -0
- package/dist/daemon/backoff.js.map +1 -0
- package/dist/daemon/codex-parser.d.ts +38 -4
- package/dist/daemon/codex-parser.d.ts.map +1 -1
- package/dist/daemon/codex-parser.js +111 -23
- package/dist/daemon/codex-parser.js.map +1 -1
- package/dist/daemon/command-path.d.ts +13 -0
- package/dist/daemon/command-path.d.ts.map +1 -0
- package/dist/daemon/command-path.js +35 -0
- package/dist/daemon/command-path.js.map +1 -0
- package/dist/daemon/commands.d.ts +146 -5
- package/dist/daemon/commands.d.ts.map +1 -1
- package/dist/daemon/commands.js +2766 -316
- package/dist/daemon/commands.js.map +1 -1
- package/dist/daemon/db.d.ts +255 -27
- package/dist/daemon/db.d.ts.map +1 -1
- package/dist/daemon/db.js +749 -53
- package/dist/daemon/db.js.map +1 -1
- package/dist/daemon/exclusions.d.ts +23 -3
- package/dist/daemon/exclusions.d.ts.map +1 -1
- package/dist/daemon/exclusions.js +91 -21
- package/dist/daemon/exclusions.js.map +1 -1
- package/dist/daemon/homebrew.d.ts +26 -0
- package/dist/daemon/homebrew.d.ts.map +1 -0
- package/dist/daemon/homebrew.js +43 -0
- package/dist/daemon/homebrew.js.map +1 -0
- package/dist/daemon/instance.d.ts +427 -0
- package/dist/daemon/instance.d.ts.map +1 -0
- package/dist/daemon/instance.js +1201 -0
- package/dist/daemon/instance.js.map +1 -0
- package/dist/daemon/key-source.d.ts +41 -0
- package/dist/daemon/key-source.d.ts.map +1 -0
- package/dist/daemon/key-source.js +89 -0
- package/dist/daemon/key-source.js.map +1 -0
- package/dist/daemon/launch.d.ts +56 -0
- package/dist/daemon/launch.d.ts.map +1 -0
- package/dist/daemon/launch.js +153 -0
- package/dist/daemon/launch.js.map +1 -0
- package/dist/daemon/launchd.d.ts +215 -0
- package/dist/daemon/launchd.d.ts.map +1 -0
- package/dist/daemon/launchd.js +527 -0
- package/dist/daemon/launchd.js.map +1 -0
- package/dist/daemon/login-start.d.ts +2 -0
- package/dist/daemon/login-start.d.ts.map +1 -0
- package/dist/daemon/login-start.js +25 -0
- package/dist/daemon/login-start.js.map +1 -0
- package/dist/daemon/ownership.d.ts +123 -0
- package/dist/daemon/ownership.d.ts.map +1 -0
- package/dist/daemon/ownership.js +245 -0
- package/dist/daemon/ownership.js.map +1 -0
- package/dist/daemon/package-runner.d.ts +28 -0
- package/dist/daemon/package-runner.d.ts.map +1 -0
- package/dist/daemon/package-runner.js +113 -0
- package/dist/daemon/package-runner.js.map +1 -0
- package/dist/daemon/parser.d.ts +45 -7
- package/dist/daemon/parser.d.ts.map +1 -1
- package/dist/daemon/parser.js +153 -53
- package/dist/daemon/parser.js.map +1 -1
- package/dist/daemon/powershell.d.ts +25 -0
- package/dist/daemon/powershell.d.ts.map +1 -0
- package/dist/daemon/powershell.js +30 -0
- package/dist/daemon/powershell.js.map +1 -0
- package/dist/daemon/preflight.d.ts.map +1 -1
- package/dist/daemon/preflight.js +5 -1
- package/dist/daemon/preflight.js.map +1 -1
- package/dist/daemon/prune.d.ts +101 -0
- package/dist/daemon/prune.d.ts.map +1 -0
- package/dist/daemon/prune.js +287 -0
- package/dist/daemon/prune.js.map +1 -0
- package/dist/daemon/queue-error.d.ts +47 -0
- package/dist/daemon/queue-error.d.ts.map +1 -0
- package/dist/daemon/queue-error.js +59 -0
- package/dist/daemon/queue-error.js.map +1 -0
- package/dist/daemon/root-daemon.d.ts +60 -0
- package/dist/daemon/root-daemon.d.ts.map +1 -0
- package/dist/daemon/root-daemon.js +86 -0
- package/dist/daemon/root-daemon.js.map +1 -0
- package/dist/daemon/scoop.d.ts +52 -0
- package/dist/daemon/scoop.d.ts.map +1 -0
- package/dist/daemon/scoop.js +84 -0
- package/dist/daemon/scoop.js.map +1 -0
- package/dist/daemon/scrubber.d.ts +396 -14
- package/dist/daemon/scrubber.d.ts.map +1 -1
- package/dist/daemon/scrubber.js +915 -52
- package/dist/daemon/scrubber.js.map +1 -1
- package/dist/daemon/status.d.ts +306 -11
- package/dist/daemon/status.d.ts.map +1 -1
- package/dist/daemon/status.js +568 -43
- package/dist/daemon/status.js.map +1 -1
- package/dist/daemon/supervise.d.ts +78 -0
- package/dist/daemon/supervise.d.ts.map +1 -0
- package/dist/daemon/supervise.js +121 -0
- package/dist/daemon/supervise.js.map +1 -0
- package/dist/daemon/supervisor.d.ts +18 -0
- package/dist/daemon/supervisor.d.ts.map +1 -0
- package/dist/daemon/supervisor.js +56 -0
- package/dist/daemon/supervisor.js.map +1 -0
- package/dist/daemon/syncer.d.ts +380 -21
- package/dist/daemon/syncer.d.ts.map +1 -1
- package/dist/daemon/syncer.js +1432 -182
- package/dist/daemon/syncer.js.map +1 -1
- package/dist/daemon/systemd.d.ts +109 -0
- package/dist/daemon/systemd.d.ts.map +1 -0
- package/dist/daemon/systemd.js +363 -0
- package/dist/daemon/systemd.js.map +1 -0
- package/dist/daemon/types.d.ts +58 -6
- package/dist/daemon/types.d.ts.map +1 -1
- package/dist/daemon/vault-changed.d.ts +29 -0
- package/dist/daemon/vault-changed.d.ts.map +1 -0
- package/dist/daemon/vault-changed.js +47 -0
- package/dist/daemon/vault-changed.js.map +1 -0
- package/dist/daemon/vault-key-missing.d.ts +70 -0
- package/dist/daemon/vault-key-missing.d.ts.map +1 -0
- package/dist/daemon/vault-key-missing.js +125 -0
- package/dist/daemon/vault-key-missing.js.map +1 -0
- package/dist/daemon/watcher.d.ts +87 -4
- package/dist/daemon/watcher.d.ts.map +1 -1
- package/dist/daemon/watcher.js +286 -36
- package/dist/daemon/watcher.js.map +1 -1
- package/dist/daemon/worker-main.js +352 -64
- package/dist/daemon/worker-main.js.map +1 -1
- package/dist/daemon/worker.js +19 -1
- package/dist/daemon/worker.js.map +1 -1
- package/dist/import-resume.d.ts +163 -0
- package/dist/import-resume.d.ts.map +1 -0
- package/dist/import-resume.js +267 -0
- package/dist/import-resume.js.map +1 -0
- package/dist/index.js +242 -33
- package/dist/index.js.map +1 -1
- package/dist/message-bounds.d.ts +52 -0
- package/dist/message-bounds.d.ts.map +1 -0
- package/dist/message-bounds.js +157 -0
- package/dist/message-bounds.js.map +1 -0
- package/dist/output.d.ts +14 -0
- package/dist/output.d.ts.map +1 -1
- package/dist/output.js +33 -5
- package/dist/output.js.map +1 -1
- package/dist/private-files.d.ts +126 -0
- package/dist/private-files.d.ts.map +1 -0
- package/dist/private-files.js +372 -0
- package/dist/private-files.js.map +1 -0
- package/dist/server-url.d.ts +31 -0
- package/dist/server-url.d.ts.map +1 -0
- package/dist/server-url.js +47 -0
- package/dist/server-url.js.map +1 -0
- package/dist/vault-key.d.ts +122 -0
- package/dist/vault-key.d.ts.map +1 -0
- package/dist/vault-key.js +273 -0
- package/dist/vault-key.js.map +1 -0
- package/package.json +2 -2
package/dist/daemon/db.js
CHANGED
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import Database from "better-sqlite3";
|
|
2
2
|
import { mkdirSync } from "node:fs";
|
|
3
|
-
import { dirname } from "node:path";
|
|
3
|
+
import { basename, dirname } from "node:path";
|
|
4
|
+
import { createPrivateFileSync, PRIVATE_DIR_MODE, restrictSync } from "../private-files.js";
|
|
5
|
+
import { claudeProjectDir } from "./parser.js";
|
|
6
|
+
/** Queue id for messages whose conversation doesn't exist yet. */
|
|
7
|
+
export function pendingConversationId(sessionId) {
|
|
8
|
+
return `pending:${sessionId}`;
|
|
9
|
+
}
|
|
4
10
|
const SCHEMA = `
|
|
5
11
|
CREATE TABLE IF NOT EXISTS file_offsets (
|
|
6
12
|
file_path TEXT PRIMARY KEY,
|
|
@@ -43,14 +49,214 @@ CREATE TABLE IF NOT EXISTS excluded_sessions (
|
|
|
43
49
|
delete_pending TEXT,
|
|
44
50
|
created_at TEXT NOT NULL
|
|
45
51
|
);
|
|
52
|
+
|
|
53
|
+
-- Sessions whose conversation hasn't been created on the server yet
|
|
54
|
+
-- (engram#370). Their messages wait in pending_messages under
|
|
55
|
+
-- 'pending:<session_id>'. A row here is written in the same transaction as
|
|
56
|
+
-- those messages and removed in the same transaction that moves them onto
|
|
57
|
+
-- the real conversation, so neither a restart nor a failed create can
|
|
58
|
+
-- strand them: the flush loop retries every row here until it lands.
|
|
59
|
+
CREATE TABLE IF NOT EXISTS pending_sessions (
|
|
60
|
+
session_id TEXT PRIMARY KEY,
|
|
61
|
+
meta TEXT NOT NULL,
|
|
62
|
+
created_at TEXT NOT NULL,
|
|
63
|
+
updated_at TEXT NOT NULL
|
|
64
|
+
);
|
|
46
65
|
`;
|
|
66
|
+
/**
|
|
67
|
+
* Schema version 1 (engram#594): every queued capture, session mapping and
|
|
68
|
+
* pending remote delete records WHICH API key it belongs to, so a capture
|
|
69
|
+
* queued while one account was signed in is never sent with another
|
|
70
|
+
* account's key.
|
|
71
|
+
*
|
|
72
|
+
* key_fp is the SHA-256 hex of the key, the same hash the server keeps in
|
|
73
|
+
* api_keys.key_hash; the key itself is never stored here. NULL or '' means
|
|
74
|
+
* "no key": a row from before version 1, or one queued while signed out.
|
|
75
|
+
* The next key the daemon runs with claims those (claimLegacy).
|
|
76
|
+
*
|
|
77
|
+
* session_map is rebuilt with the conversation id as its key, because one
|
|
78
|
+
* transcript session can now have a conversation in each account that
|
|
79
|
+
* captured part of it, and an opt-out has to find every one of them.
|
|
80
|
+
*/
|
|
81
|
+
const SESSION_MAP_V1 = `
|
|
82
|
+
CREATE TABLE session_map_v1 (
|
|
83
|
+
conversation_id TEXT PRIMARY KEY,
|
|
84
|
+
session_id TEXT NOT NULL,
|
|
85
|
+
key_fp TEXT NOT NULL DEFAULT '',
|
|
86
|
+
project_dir TEXT,
|
|
87
|
+
cwd TEXT,
|
|
88
|
+
git_branch TEXT,
|
|
89
|
+
created_at TEXT NOT NULL
|
|
90
|
+
);
|
|
91
|
+
INSERT OR IGNORE INTO session_map_v1
|
|
92
|
+
(conversation_id, session_id, key_fp, project_dir, cwd, git_branch, created_at)
|
|
93
|
+
SELECT conversation_id, session_id, '', project_dir, cwd, git_branch, created_at
|
|
94
|
+
FROM session_map ORDER BY created_at, rowid;
|
|
95
|
+
DROP TABLE session_map;
|
|
96
|
+
ALTER TABLE session_map_v1 RENAME TO session_map;
|
|
97
|
+
`;
|
|
98
|
+
const SCHEMA_V1 = `
|
|
99
|
+
CREATE INDEX IF NOT EXISTS idx_session_map_session
|
|
100
|
+
ON session_map(session_id, key_fp);
|
|
101
|
+
|
|
102
|
+
CREATE INDEX IF NOT EXISTS idx_pending_unsent_key
|
|
103
|
+
ON pending_messages(key_fp, conversation_id) WHERE sent_at IS NULL;
|
|
104
|
+
|
|
105
|
+
-- Conversations to delete on the server because their session was opted
|
|
106
|
+
-- out (engram#462), each under the key of the account that holds it. A
|
|
107
|
+
-- delete is only ever sent with that account's key; one for an account
|
|
108
|
+
-- that isn't signed in waits here until it is.
|
|
109
|
+
CREATE TABLE IF NOT EXISTS remote_deletes (
|
|
110
|
+
conversation_id TEXT PRIMARY KEY,
|
|
111
|
+
key_fp TEXT,
|
|
112
|
+
session_id TEXT,
|
|
113
|
+
created_at TEXT NOT NULL
|
|
114
|
+
);
|
|
115
|
+
`;
|
|
116
|
+
/**
|
|
117
|
+
* Schema version 2 (engram#598): sent rows are found by when they were
|
|
118
|
+
* sent, so pruning them reads this index, never the text they hold. Only
|
|
119
|
+
* sent rows are in it.
|
|
120
|
+
*/
|
|
121
|
+
const SCHEMA_V2 = `
|
|
122
|
+
CREATE INDEX IF NOT EXISTS idx_pending_sent
|
|
123
|
+
ON pending_messages(sent_at) WHERE sent_at IS NOT NULL;
|
|
124
|
+
`;
|
|
125
|
+
/**
|
|
126
|
+
* Schema version 3 (engram#593): conversations Engram answered it doesn't
|
|
127
|
+
* have — deleted there, or not this account's, which the server doesn't
|
|
128
|
+
* tell apart. Their queued messages stay here and aren't sent, and the
|
|
129
|
+
* conversation is never created again. The daemon asks again a few times
|
|
130
|
+
* over the next days (GONE_RECHECK_MS in syncer.ts), then stops asking.
|
|
131
|
+
*
|
|
132
|
+
* One row per conversation, whichever key its messages were queued under:
|
|
133
|
+
* a conversation id is one account's, and its messages are only ever sent
|
|
134
|
+
* with a key of that account.
|
|
135
|
+
*/
|
|
136
|
+
const SCHEMA_V3 = `
|
|
137
|
+
CREATE TABLE IF NOT EXISTS gone_conversations (
|
|
138
|
+
conversation_id TEXT PRIMARY KEY,
|
|
139
|
+
gone_at INTEGER NOT NULL, -- ms since the epoch: the first such answer
|
|
140
|
+
checked_at INTEGER NOT NULL, -- ms since the epoch: the latest such answer
|
|
141
|
+
checks INTEGER NOT NULL -- how many such answers so far
|
|
142
|
+
);
|
|
143
|
+
`;
|
|
144
|
+
/**
|
|
145
|
+
* Schema version 4 (engram#685): whether a row records which server it was
|
|
146
|
+
* captured for. key_fp names the account (accountFingerprint): the key's
|
|
147
|
+
* fingerprint alone on the default server, and with the server's tag on any
|
|
148
|
+
* other. Before version 4 the key's fingerprint stood for whatever server
|
|
149
|
+
* was configured, so a row from then, or one an older daemon writes after
|
|
150
|
+
* a downgrade, has server_known = 0: its server isn't known. A server
|
|
151
|
+
* other than the default is asked about such rows, never about those
|
|
152
|
+
* recorded for the default server (ownershipCandidates in syncer.ts).
|
|
153
|
+
*/
|
|
154
|
+
const SERVER_KNOWN_TABLES = ["pending_messages", "session_map", "remote_deletes"];
|
|
155
|
+
/** The schema version this code brings a daemon.db up to (user_version). */
|
|
156
|
+
export const SCHEMA_VERSION = 4;
|
|
157
|
+
/**
|
|
158
|
+
* Deletes up to `limit` rows sent before a time, oldest first (engram#598).
|
|
159
|
+
* The outer `sent_at IS NOT NULL` repeats the subquery's on purpose: a row
|
|
160
|
+
* that hasn't been sent is never deleted here, whatever the subquery picks.
|
|
161
|
+
* Exported for the query-plan test.
|
|
162
|
+
*/
|
|
163
|
+
export const PRUNE_SENT_SQL = `
|
|
164
|
+
DELETE FROM pending_messages
|
|
165
|
+
WHERE id IN (SELECT id FROM pending_messages
|
|
166
|
+
WHERE sent_at IS NOT NULL AND sent_at < ?
|
|
167
|
+
ORDER BY sent_at LIMIT ?)
|
|
168
|
+
AND sent_at IS NOT NULL`;
|
|
169
|
+
/** `at` the way SQLite's datetime('now') writes sent_at: UTC, to the second. */
|
|
170
|
+
export function sqliteTime(at) {
|
|
171
|
+
return at.toISOString().slice(0, 19).replace("T", " ");
|
|
172
|
+
}
|
|
173
|
+
function hasColumn(db, table, column) {
|
|
174
|
+
return db.pragma(`table_info(${table})`).some((c) => c.name === column);
|
|
175
|
+
}
|
|
176
|
+
function hasTable(db, table) {
|
|
177
|
+
return (db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = ?").get(table) !==
|
|
178
|
+
undefined);
|
|
179
|
+
}
|
|
180
|
+
/** Bring a daemon.db up to SCHEMA_VERSION in ONE transaction: a crash
|
|
181
|
+
* part-way leaves it at the version it had, exactly as it was, and the
|
|
182
|
+
* next start retries. */
|
|
183
|
+
function migrate(db) {
|
|
184
|
+
db.transaction(() => {
|
|
185
|
+
const version = db.pragma("user_version", { simple: true });
|
|
186
|
+
if (version >= SCHEMA_VERSION)
|
|
187
|
+
return;
|
|
188
|
+
if (version < 1) {
|
|
189
|
+
if (!hasColumn(db, "pending_messages", "key_fp")) {
|
|
190
|
+
db.exec("ALTER TABLE pending_messages ADD COLUMN key_fp TEXT");
|
|
191
|
+
}
|
|
192
|
+
if (!hasColumn(db, "session_map", "key_fp"))
|
|
193
|
+
db.exec(SESSION_MAP_V1);
|
|
194
|
+
db.exec(SCHEMA_V1);
|
|
195
|
+
}
|
|
196
|
+
db.exec(SCHEMA_V2);
|
|
197
|
+
db.exec(SCHEMA_V3);
|
|
198
|
+
for (const table of SERVER_KNOWN_TABLES) {
|
|
199
|
+
if (!hasColumn(db, table, "server_known")) {
|
|
200
|
+
db.exec(`ALTER TABLE ${table} ADD COLUMN server_known INTEGER NOT NULL DEFAULT 0`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
db.pragma(`user_version = ${SCHEMA_VERSION}`);
|
|
204
|
+
}).immediate();
|
|
205
|
+
}
|
|
47
206
|
export class DaemonDb {
|
|
48
207
|
db;
|
|
49
|
-
|
|
50
|
-
|
|
208
|
+
/** False only for a read-only open of a daemon.db that an older daemon
|
|
209
|
+
* still owns (no key_fp yet). That daemon sends every queued row with
|
|
210
|
+
* its own key, so they all count as pending, none as held. */
|
|
211
|
+
keyed;
|
|
212
|
+
/** False only for a read-only open of a daemon.db that an older daemon
|
|
213
|
+
* still owns (before version 3): no conversation is set aside there. */
|
|
214
|
+
goneKnown;
|
|
215
|
+
/** False only for a read-only open of a daemon.db that an older daemon
|
|
216
|
+
* still owns (before version 4): no row records its server there. */
|
|
217
|
+
serversKnown;
|
|
218
|
+
/**
|
|
219
|
+
* `readonly` is for the CLI reading a daemon's database while the daemon
|
|
220
|
+
* runs: it changes nothing (no schema, no migration, no -wal file of its
|
|
221
|
+
* own making) and throws instead of creating a file that isn't there.
|
|
222
|
+
*/
|
|
223
|
+
constructor(dbPath, options = {}) {
|
|
224
|
+
if (options.readonly) {
|
|
225
|
+
this.db = new Database(dbPath, { readonly: true, fileMustExist: true });
|
|
226
|
+
this.keyed = hasColumn(this.db, "pending_messages", "key_fp");
|
|
227
|
+
this.goneKnown = hasTable(this.db, "gone_conversations");
|
|
228
|
+
this.serversKnown = hasColumn(this.db, "pending_messages", "server_known");
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
// The queue holds captured transcript text, so its files are the
|
|
232
|
+
// user's alone (engram#627). The database file is created 0600 before
|
|
233
|
+
// SQLite opens it, and SQLite gives the -wal and -shm files it creates
|
|
234
|
+
// the database file's mode. Files from before the fix are set to 0600
|
|
235
|
+
// first. By path on purpose: opening and closing the database file
|
|
236
|
+
// here would drop locks this process holds on it through SQLite.
|
|
237
|
+
mkdirSync(dirname(dbPath), { recursive: true, mode: PRIVATE_DIR_MODE });
|
|
238
|
+
createPrivateFileSync(dbPath);
|
|
239
|
+
for (const file of [dbPath, `${dbPath}-wal`, `${dbPath}-shm`])
|
|
240
|
+
restrictSync(file);
|
|
51
241
|
this.db = new Database(dbPath);
|
|
242
|
+
// What is deleted from the queue doesn't stay in the file (engram#598).
|
|
243
|
+
// A new file gives the space it frees back to the disk (only possible
|
|
244
|
+
// before its first table; an older file is converted by compact()).
|
|
245
|
+
// secure_delete overwrites deleted text with zeros instead of leaving
|
|
246
|
+
// it in free pages, and journal_size_limit = 0 cuts the write-ahead log
|
|
247
|
+
// back each time it starts over, so earlier versions of pages don't
|
|
248
|
+
// linger at its end either.
|
|
249
|
+
if (this.db.prepare("SELECT 1 FROM sqlite_schema LIMIT 1").get() === undefined) {
|
|
250
|
+
this.db.pragma("auto_vacuum = INCREMENTAL");
|
|
251
|
+
}
|
|
52
252
|
this.db.pragma("journal_mode = WAL");
|
|
253
|
+
this.db.pragma("secure_delete = ON");
|
|
254
|
+
this.db.pragma("journal_size_limit = 0");
|
|
53
255
|
this.db.exec(SCHEMA);
|
|
256
|
+
migrate(this.db);
|
|
257
|
+
this.keyed = true;
|
|
258
|
+
this.goneKnown = true;
|
|
259
|
+
this.serversKnown = true;
|
|
54
260
|
}
|
|
55
261
|
// ── File offsets ──
|
|
56
262
|
getFileOffset(filePath) {
|
|
@@ -68,18 +274,29 @@ export class DaemonDb {
|
|
|
68
274
|
.run(filePath, offset);
|
|
69
275
|
}
|
|
70
276
|
// ── Session map ──
|
|
71
|
-
|
|
277
|
+
/** The session's conversation in the account `keyFp` belongs to (the
|
|
278
|
+
* newest, if more than one was ever created there). */
|
|
279
|
+
getConversationId(sessionId, keyFp) {
|
|
72
280
|
const row = this.db
|
|
73
|
-
.prepare(
|
|
74
|
-
|
|
281
|
+
.prepare(`SELECT conversation_id FROM session_map
|
|
282
|
+
WHERE session_id = ? AND key_fp = ?
|
|
283
|
+
ORDER BY rowid DESC LIMIT 1`)
|
|
284
|
+
.get(sessionId, keyFp);
|
|
75
285
|
return row?.conversation_id ?? null;
|
|
76
286
|
}
|
|
77
|
-
setSessionMap(sessionId, conversationId, meta) {
|
|
287
|
+
setSessionMap(sessionId, conversationId, meta, keyFp) {
|
|
78
288
|
this.db
|
|
79
289
|
.prepare(`INSERT OR REPLACE INTO session_map
|
|
80
|
-
(session_id,
|
|
81
|
-
VALUES (?, ?, ?, ?, ?, datetime('now'))`)
|
|
82
|
-
.run(sessionId,
|
|
290
|
+
(conversation_id, session_id, key_fp, project_dir, cwd, git_branch, created_at, server_known)
|
|
291
|
+
VALUES (?, ?, ?, ?, ?, ?, datetime('now'), 1)`)
|
|
292
|
+
.run(conversationId, sessionId, keyFp, meta.projectDir ?? null, meta.cwd ?? null, meta.gitBranch ?? null);
|
|
293
|
+
}
|
|
294
|
+
/** True when the session already has a conversation under a key other
|
|
295
|
+
* than `keyFp` — one that may turn out to be the same account's. */
|
|
296
|
+
mappedUnderOtherKey(sessionId, keyFp) {
|
|
297
|
+
return (this.db
|
|
298
|
+
.prepare("SELECT 1 FROM session_map WHERE session_id = ? AND key_fp <> ? LIMIT 1")
|
|
299
|
+
.get(sessionId, keyFp) !== undefined);
|
|
83
300
|
}
|
|
84
301
|
// ── Excluded sessions (engram#462) ──
|
|
85
302
|
isSessionExcluded(sessionId) {
|
|
@@ -87,64 +304,295 @@ export class DaemonDb {
|
|
|
87
304
|
.prepare("SELECT 1 FROM excluded_sessions WHERE session_id = ?")
|
|
88
305
|
.get(sessionId) !== undefined);
|
|
89
306
|
}
|
|
90
|
-
|
|
307
|
+
/** Record the opt-out. An existing row is kept as it is: a delete it still
|
|
308
|
+
* carries from before version 1 is claimed later (claimLegacy). */
|
|
309
|
+
markSessionExcluded(sessionId, reason) {
|
|
91
310
|
this.db
|
|
92
|
-
.prepare(`INSERT OR
|
|
311
|
+
.prepare(`INSERT OR IGNORE INTO excluded_sessions
|
|
93
312
|
(session_id, reason, delete_pending, created_at)
|
|
94
|
-
VALUES (?, ?,
|
|
95
|
-
.run(sessionId, reason
|
|
313
|
+
VALUES (?, ?, NULL, datetime('now'))`)
|
|
314
|
+
.run(sessionId, reason);
|
|
96
315
|
}
|
|
97
|
-
/** Conversations
|
|
98
|
-
* after part of the session had synced)
|
|
99
|
-
|
|
316
|
+
/** Conversations still to delete on the server with the key `keyFp`
|
|
317
|
+
* (the opt-out arrived after part of the session had synced), oldest
|
|
318
|
+
* first. */
|
|
319
|
+
getPendingRemoteDeletes(keyFp) {
|
|
100
320
|
return this.db
|
|
101
|
-
.prepare(
|
|
102
|
-
|
|
321
|
+
.prepare(`SELECT conversation_id, session_id FROM remote_deletes
|
|
322
|
+
WHERE key_fp = ? ORDER BY created_at, rowid`)
|
|
323
|
+
.all(keyFp);
|
|
103
324
|
}
|
|
104
|
-
clearPendingRemoteDelete(
|
|
325
|
+
clearPendingRemoteDelete(conversationId) {
|
|
105
326
|
this.db
|
|
106
|
-
.prepare("
|
|
107
|
-
.run(
|
|
327
|
+
.prepare("DELETE FROM remote_deletes WHERE conversation_id = ?")
|
|
328
|
+
.run(conversationId);
|
|
108
329
|
}
|
|
109
|
-
/**
|
|
110
|
-
*
|
|
330
|
+
/**
|
|
331
|
+
* Drop every local row for a conversation, sent or not — used when the
|
|
332
|
+
* user opts a session out. Returns how many of them had never been sent
|
|
333
|
+
* (engram#628): a sent row is only this machine's record of a message the
|
|
334
|
+
* server already has, and counting those told the user that messages
|
|
335
|
+
* were dropped before they could be sent when none were.
|
|
336
|
+
*/
|
|
111
337
|
deleteAllForConversation(conversationId) {
|
|
112
|
-
return this.db
|
|
113
|
-
|
|
114
|
-
|
|
338
|
+
return this.db.transaction(() => {
|
|
339
|
+
const { c: unsent } = this.db
|
|
340
|
+
.prepare("SELECT COUNT(*) AS c FROM pending_messages WHERE conversation_id = ? AND sent_at IS NULL")
|
|
341
|
+
.get(conversationId);
|
|
342
|
+
this.db.prepare("DELETE FROM pending_messages WHERE conversation_id = ?").run(conversationId);
|
|
343
|
+
this.db.prepare("DELETE FROM gone_conversations WHERE conversation_id = ?").run(conversationId);
|
|
344
|
+
return unsent;
|
|
345
|
+
})();
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Opt a session out on this machine, in ONE transaction (engram#584):
|
|
349
|
+
* mark it excluded, record a server-side delete for its conversation in
|
|
350
|
+
* EVERY account that has one (each under that account's key), and drop
|
|
351
|
+
* everything queued for it, whichever key it was queued under. Returns
|
|
352
|
+
* those conversations and how many of the messages dropped had never been
|
|
353
|
+
* sent.
|
|
354
|
+
*
|
|
355
|
+
* As separate steps, a failure part-way could mark the session excluded
|
|
356
|
+
* and leave its queue in place, still due to be sent. Nothing would ever
|
|
357
|
+
* drop it: an excluded session returns before the drop is reached.
|
|
358
|
+
*/
|
|
359
|
+
excludeSession(sessionId, reason) {
|
|
360
|
+
return this.db.transaction(() => {
|
|
361
|
+
this.markSessionExcluded(sessionId, reason);
|
|
362
|
+
const mapped = this.db
|
|
363
|
+
.prepare(`SELECT conversation_id, key_fp, server_known FROM session_map
|
|
364
|
+
WHERE session_id = ? ORDER BY rowid`)
|
|
365
|
+
.all(sessionId);
|
|
366
|
+
// A delete is for the server its conversation is on: what the mapping
|
|
367
|
+
// records about that server, the delete records too (engram#685).
|
|
368
|
+
const remember = this.db.prepare(`INSERT OR IGNORE INTO remote_deletes
|
|
369
|
+
(conversation_id, key_fp, session_id, created_at, server_known)
|
|
370
|
+
VALUES (?, ?, ?, datetime('now'), ?)`);
|
|
371
|
+
let dropped = this.dropPendingSession(sessionId);
|
|
372
|
+
for (const r of mapped) {
|
|
373
|
+
remember.run(r.conversation_id, r.key_fp || null, sessionId, r.server_known);
|
|
374
|
+
dropped += this.deleteAllForConversation(r.conversation_id);
|
|
375
|
+
}
|
|
376
|
+
const conversations = mapped.map((r) => ({ conversationId: r.conversation_id, keyFp: r.key_fp }));
|
|
377
|
+
return { conversations, dropped };
|
|
378
|
+
})();
|
|
379
|
+
}
|
|
380
|
+
/** A create that was in flight when its session was opted out: delete
|
|
381
|
+
* the new conversation on the server (with the key that created it) and
|
|
382
|
+
* drop whatever is queued for the session, in ONE transaction. */
|
|
383
|
+
excludeCreatedConversation(sessionId, conversationId, keyFp) {
|
|
384
|
+
this.db.transaction(() => {
|
|
385
|
+
this.db
|
|
386
|
+
.prepare(`INSERT OR IGNORE INTO remote_deletes
|
|
387
|
+
(conversation_id, key_fp, session_id, created_at, server_known)
|
|
388
|
+
VALUES (?, ?, ?, datetime('now'), 1)`)
|
|
389
|
+
.run(conversationId, keyFp, sessionId);
|
|
390
|
+
this.dropPendingSession(sessionId);
|
|
391
|
+
this.deleteAllForConversation(conversationId);
|
|
392
|
+
})();
|
|
393
|
+
}
|
|
394
|
+
// ── Pending sessions (engram#370) ──
|
|
395
|
+
/** Queue messages for a session that has no conversation yet, recording
|
|
396
|
+
* the session in the same transaction (latest metadata wins). */
|
|
397
|
+
enqueuePendingSession(sessionId, meta, messages, keyFp) {
|
|
398
|
+
const upsert = this.db.prepare(`INSERT INTO pending_sessions (session_id, meta, created_at, updated_at)
|
|
399
|
+
VALUES (?, ?, datetime('now'), datetime('now'))
|
|
400
|
+
ON CONFLICT(session_id)
|
|
401
|
+
DO UPDATE SET meta = excluded.meta, updated_at = excluded.updated_at`);
|
|
402
|
+
this.db.transaction(() => {
|
|
403
|
+
upsert.run(sessionId, JSON.stringify({ ...meta, sessionId }));
|
|
404
|
+
this.enqueue(pendingConversationId(sessionId), messages, keyFp);
|
|
405
|
+
})();
|
|
406
|
+
}
|
|
407
|
+
/** Sessions waiting for their conversation that have messages queued
|
|
408
|
+
* under `keyFp`, oldest first. A row whose metadata can't be read still
|
|
409
|
+
* comes back (with placeholder metadata): its messages must never be
|
|
410
|
+
* stranded by a bad meta blob. */
|
|
411
|
+
getPendingSessions(keyFp) {
|
|
412
|
+
const rows = this.db
|
|
413
|
+
.prepare(`SELECT session_id, meta FROM pending_sessions ps
|
|
414
|
+
WHERE EXISTS (
|
|
415
|
+
SELECT 1 FROM pending_messages pm
|
|
416
|
+
WHERE pm.sent_at IS NULL AND pm.key_fp IS ?
|
|
417
|
+
AND pm.conversation_id = 'pending:' || ps.session_id)
|
|
418
|
+
ORDER BY created_at, session_id`)
|
|
419
|
+
.all(keyFp);
|
|
420
|
+
return rows.map((r) => ({
|
|
421
|
+
sessionId: r.session_id,
|
|
422
|
+
meta: parseStoredMeta(r.session_id, r.meta),
|
|
423
|
+
}));
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Finish a pending session for one account in ONE transaction: record the
|
|
427
|
+
* mapping (when `meta` is given — a fresh create), move the messages
|
|
428
|
+
* queued under `keyFp` onto the real conversation, and forget the
|
|
429
|
+
* pending row once nothing is left under the temporary id. Messages
|
|
430
|
+
* another key queued for the same session stay where they are, for that
|
|
431
|
+
* account. A crash can't leave messages under the temporary id with
|
|
432
|
+
* nothing left to retry them. Returns the number of messages moved.
|
|
433
|
+
*/
|
|
434
|
+
completePendingSession(sessionId, conversationId, keyFp, meta) {
|
|
435
|
+
return this.db.transaction(() => {
|
|
436
|
+
if (meta)
|
|
437
|
+
this.setSessionMap(sessionId, conversationId, meta, keyFp);
|
|
438
|
+
const pendingId = pendingConversationId(sessionId);
|
|
439
|
+
const moved = this.db
|
|
440
|
+
.prepare(`UPDATE pending_messages SET conversation_id = ?
|
|
441
|
+
WHERE conversation_id = ? AND sent_at IS NULL AND key_fp = ?`)
|
|
442
|
+
.run(conversationId, pendingId, keyFp).changes;
|
|
443
|
+
const left = this.db
|
|
444
|
+
.prepare("SELECT 1 FROM pending_messages WHERE conversation_id = ? AND sent_at IS NULL LIMIT 1")
|
|
445
|
+
.get(pendingId);
|
|
446
|
+
if (left === undefined) {
|
|
447
|
+
this.db.prepare("DELETE FROM pending_sessions WHERE session_id = ?").run(sessionId);
|
|
448
|
+
}
|
|
449
|
+
return moved;
|
|
450
|
+
})();
|
|
451
|
+
}
|
|
452
|
+
/** Drop a pending session and everything queued under its temporary id
|
|
453
|
+
* (opt-out). Returns how many of those messages had never been sent. */
|
|
454
|
+
dropPendingSession(sessionId) {
|
|
455
|
+
return this.db.transaction(() => {
|
|
456
|
+
const dropped = this.deleteAllForConversation(pendingConversationId(sessionId));
|
|
457
|
+
this.db
|
|
458
|
+
.prepare("DELETE FROM pending_sessions WHERE session_id = ?")
|
|
459
|
+
.run(sessionId);
|
|
460
|
+
return dropped;
|
|
461
|
+
})();
|
|
462
|
+
}
|
|
463
|
+
/**
|
|
464
|
+
* Messages queued under 'pending:<id>' with no pending_sessions row —
|
|
465
|
+
* left by a daemon older than engram#370, whose session record lived only
|
|
466
|
+
* in memory and died with that process. Give each such session a row so
|
|
467
|
+
* the flush loop creates its conversation like any other; the metadata is
|
|
468
|
+
* rebuilt from the transcript path when daemon.db still tracks one.
|
|
469
|
+
* Returns the adopted session ids.
|
|
470
|
+
*/
|
|
471
|
+
adoptOrphanedPendingRows() {
|
|
472
|
+
const orphans = this.db
|
|
473
|
+
.prepare(`SELECT DISTINCT substr(conversation_id, 9) AS session_id
|
|
474
|
+
FROM pending_messages
|
|
475
|
+
WHERE sent_at IS NULL
|
|
476
|
+
AND substr(conversation_id, 1, 8) = 'pending:'
|
|
477
|
+
AND substr(conversation_id, 9) NOT IN (SELECT session_id FROM pending_sessions)`)
|
|
478
|
+
.all();
|
|
479
|
+
if (orphans.length === 0)
|
|
480
|
+
return [];
|
|
481
|
+
const candidates = this.db.prepare("SELECT file_path FROM file_offsets WHERE instr(file_path, ?) > 0 ORDER BY updated_at DESC");
|
|
482
|
+
const insert = this.db.prepare(`INSERT OR IGNORE INTO pending_sessions (session_id, meta, created_at, updated_at)
|
|
483
|
+
VALUES (?, ?, datetime('now'), datetime('now'))`);
|
|
484
|
+
this.db.transaction(() => {
|
|
485
|
+
for (const { session_id } of orphans) {
|
|
486
|
+
const paths = session_id
|
|
487
|
+
? candidates.all(session_id).map((r) => r.file_path)
|
|
488
|
+
: [];
|
|
489
|
+
const filePath = paths.find((p) => isTranscriptOf(p, session_id));
|
|
490
|
+
insert.run(session_id, JSON.stringify(recoveredSessionMeta(session_id, filePath)));
|
|
491
|
+
}
|
|
492
|
+
})();
|
|
493
|
+
return orphans.map((o) => o.session_id);
|
|
115
494
|
}
|
|
116
495
|
// ── Pending messages ──
|
|
117
|
-
|
|
496
|
+
/** Queue messages for the account signed in when they were captured
|
|
497
|
+
* (`null`: none was, so no server is known either). */
|
|
498
|
+
enqueue(conversationId, messages, keyFp) {
|
|
118
499
|
const stmt = this.db.prepare(`INSERT INTO pending_messages
|
|
119
|
-
(conversation_id, role, content, tool_call_id, tool_name, metadata, created_at
|
|
120
|
-
|
|
500
|
+
(conversation_id, role, content, tool_call_id, tool_name, metadata, created_at, key_fp,
|
|
501
|
+
server_known)
|
|
502
|
+
VALUES (?, ?, ?, ?, ?, ?, datetime('now'), ?, ?)`);
|
|
503
|
+
const serverKnown = keyFp === null ? 0 : 1;
|
|
121
504
|
const insertMany = this.db.transaction((msgs) => {
|
|
122
505
|
for (const m of msgs) {
|
|
123
|
-
stmt.run(conversationId, m.role, m.content, m.toolCallId ?? null, m.toolName ?? null, m.metadata ? JSON.stringify(m.metadata) : null);
|
|
506
|
+
stmt.run(conversationId, m.role, m.content, m.toolCallId ?? null, m.toolName ?? null, m.metadata ? JSON.stringify(m.metadata) : null, keyFp, serverKnown);
|
|
124
507
|
}
|
|
125
508
|
});
|
|
126
509
|
insertMany(messages);
|
|
127
510
|
}
|
|
128
|
-
/**
|
|
129
|
-
|
|
511
|
+
/** Conversation ids with unsent messages queued under `keyFp`, but for
|
|
512
|
+
* those Engram said it doesn't have (engram#593). */
|
|
513
|
+
getPendingConversationIds(keyFp) {
|
|
130
514
|
const rows = this.db
|
|
131
|
-
.prepare(
|
|
132
|
-
|
|
515
|
+
.prepare(`SELECT DISTINCT conversation_id FROM pending_messages
|
|
516
|
+
WHERE sent_at IS NULL AND key_fp IS ?${this.notGone()}`)
|
|
517
|
+
.all(keyFp);
|
|
133
518
|
return rows.map((r) => r.conversation_id);
|
|
134
519
|
}
|
|
135
|
-
|
|
136
|
-
|
|
520
|
+
// ── Conversations Engram doesn't have (engram#593) ──
|
|
521
|
+
/**
|
|
522
|
+
* Record that Engram answered it has no conversation `conversationId`
|
|
523
|
+
* (deleted, or not this account's), at `at` (ms). Its queued messages
|
|
524
|
+
* stay here and are no longer sent, until clearGone. Returns how many
|
|
525
|
+
* times in a row Engram has answered so, this one included.
|
|
526
|
+
*/
|
|
527
|
+
markGone(conversationId, at) {
|
|
528
|
+
const row = this.db
|
|
529
|
+
.prepare(`INSERT INTO gone_conversations (conversation_id, gone_at, checked_at, checks)
|
|
530
|
+
VALUES (?, ?, ?, 1)
|
|
531
|
+
ON CONFLICT(conversation_id)
|
|
532
|
+
DO UPDATE SET checked_at = excluded.checked_at, checks = checks + 1
|
|
533
|
+
RETURNING checks`)
|
|
534
|
+
.get(conversationId, at, at);
|
|
535
|
+
return row.checks;
|
|
536
|
+
}
|
|
537
|
+
/** Engram has the conversation after all: its messages are sent again. */
|
|
538
|
+
clearGone(conversationId) {
|
|
539
|
+
this.db.prepare("DELETE FROM gone_conversations WHERE conversation_id = ?").run(conversationId);
|
|
540
|
+
}
|
|
541
|
+
/** The conversations Engram said it doesn't have that have unsent
|
|
542
|
+
* messages queued under `keyFp`: when it last said so, and how many
|
|
543
|
+
* times. */
|
|
544
|
+
getGoneConversations(keyFp) {
|
|
545
|
+
if (!this.goneKnown)
|
|
546
|
+
return [];
|
|
547
|
+
const rows = this.db
|
|
548
|
+
.prepare(`SELECT conversation_id, checked_at, checks FROM gone_conversations g
|
|
549
|
+
WHERE EXISTS (
|
|
550
|
+
SELECT 1 FROM pending_messages pm
|
|
551
|
+
WHERE pm.conversation_id = g.conversation_id
|
|
552
|
+
AND pm.sent_at IS NULL AND pm.key_fp IS ?)
|
|
553
|
+
ORDER BY gone_at, conversation_id`)
|
|
554
|
+
.all(keyFp);
|
|
555
|
+
return rows.map((r) => ({
|
|
556
|
+
conversationId: r.conversation_id,
|
|
557
|
+
checkedAt: r.checked_at,
|
|
558
|
+
checks: r.checks,
|
|
559
|
+
}));
|
|
560
|
+
}
|
|
561
|
+
/** Unsent messages of one conversation, whichever key queued them. */
|
|
562
|
+
getUnsentCount(conversationId) {
|
|
563
|
+
return this.count("conversation_id = ?", conversationId);
|
|
564
|
+
}
|
|
565
|
+
/** Unsent messages of conversations Engram said it doesn't have,
|
|
566
|
+
* whichever key queued them: they're kept here, and not sent. */
|
|
567
|
+
getNotSentCount() {
|
|
568
|
+
if (!this.goneKnown)
|
|
569
|
+
return 0;
|
|
570
|
+
return this.count("conversation_id IN (SELECT conversation_id FROM gone_conversations)");
|
|
571
|
+
}
|
|
572
|
+
/** The condition that leaves out conversations Engram said it doesn't
|
|
573
|
+
* have; none for a daemon.db from before version 3. */
|
|
574
|
+
notGone() {
|
|
575
|
+
return this.goneKnown
|
|
576
|
+
? " AND conversation_id NOT IN (SELECT conversation_id FROM gone_conversations)"
|
|
577
|
+
: "";
|
|
578
|
+
}
|
|
579
|
+
/** Dequeue up to `limit` unsent messages a conversation has under `keyFp`. */
|
|
580
|
+
dequeue(conversationId, limit, keyFp) {
|
|
137
581
|
return this.db
|
|
138
582
|
.prepare(`SELECT * FROM pending_messages
|
|
139
|
-
WHERE conversation_id = ? AND sent_at IS NULL
|
|
583
|
+
WHERE conversation_id = ? AND sent_at IS NULL AND key_fp IS ?
|
|
140
584
|
ORDER BY id ASC LIMIT ?`)
|
|
141
|
-
.all(conversationId, limit);
|
|
585
|
+
.all(conversationId, keyFp, limit);
|
|
142
586
|
}
|
|
143
|
-
/**
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
587
|
+
/** Replace queued messages' content with its scrubbed text (engram#588). */
|
|
588
|
+
updateContents(rows) {
|
|
589
|
+
if (rows.length === 0)
|
|
590
|
+
return;
|
|
591
|
+
const stmt = this.db.prepare("UPDATE pending_messages SET content = ? WHERE id = ?");
|
|
592
|
+
this.db.transaction((rs) => {
|
|
593
|
+
for (const r of rs)
|
|
594
|
+
stmt.run(r.content, r.id);
|
|
595
|
+
})(rows);
|
|
148
596
|
}
|
|
149
597
|
markSent(ids) {
|
|
150
598
|
if (ids.length === 0)
|
|
@@ -155,26 +603,227 @@ export class DaemonDb {
|
|
|
155
603
|
WHERE id IN (${placeholders})`)
|
|
156
604
|
.run(...ids);
|
|
157
605
|
}
|
|
158
|
-
|
|
159
|
-
|
|
606
|
+
// ── Pruning sent rows (engram#598) ──
|
|
607
|
+
/**
|
|
608
|
+
* Delete up to `limit` rows that were sent before `before`, oldest first,
|
|
609
|
+
* and return how many were deleted. A row is marked sent only once the
|
|
610
|
+
* server has confirmed it has the messages (markSent), and a row that
|
|
611
|
+
* hasn't been sent is never deleted here, however old it is.
|
|
612
|
+
*/
|
|
613
|
+
pruneSent(before, limit) {
|
|
614
|
+
return this.db.prepare(PRUNE_SENT_SQL).run(sqliteTime(before), limit).changes;
|
|
615
|
+
}
|
|
616
|
+
storage() {
|
|
617
|
+
const read = (pragma) => this.db.pragma(pragma, { simple: true });
|
|
618
|
+
return {
|
|
619
|
+
pageSize: read("page_size"),
|
|
620
|
+
pages: read("page_count"),
|
|
621
|
+
freePages: read("freelist_count"),
|
|
622
|
+
incremental: read("auto_vacuum") === 2,
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
/** Give up to `pages` free pages back to the disk (a file in incremental
|
|
626
|
+
* mode only; elsewhere this does nothing). Returns how many went. */
|
|
627
|
+
releaseFreePages(pages) {
|
|
628
|
+
const before = this.storage().freePages;
|
|
629
|
+
this.db.pragma(`incremental_vacuum(${Math.max(1, Math.floor(pages))})`);
|
|
630
|
+
return before - this.storage().freePages;
|
|
631
|
+
}
|
|
632
|
+
/** Copy the write-ahead log into the file and empty it, so the log
|
|
633
|
+
* keeps no copy of pages since changed. False when a reader in another
|
|
634
|
+
* process kept it from finishing; the next one does. */
|
|
635
|
+
checkpoint() {
|
|
636
|
+
// Without waiting: for a reader that is behind, it would wait out the
|
|
637
|
+
// whole busy timeout, and the daemon with it.
|
|
638
|
+
const wait = this.db.pragma("busy_timeout", { simple: true });
|
|
639
|
+
this.db.pragma("busy_timeout = 0");
|
|
640
|
+
try {
|
|
641
|
+
const [result] = this.db.pragma("wal_checkpoint(TRUNCATE)");
|
|
642
|
+
return result?.busy === 0;
|
|
643
|
+
}
|
|
644
|
+
finally {
|
|
645
|
+
this.db.pragma(`busy_timeout = ${wait}`);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Rewrite the file with only what it holds now, and switch it to giving
|
|
650
|
+
* freed space back from then on (engram#598). For a daemon.db from
|
|
651
|
+
* before that: its free pages may still hold text deleted or rewritten
|
|
652
|
+
* before secure_delete was on, and its space never went back to the
|
|
653
|
+
* disk. One VACUUM, which is a single transaction: if it fails part-way
|
|
654
|
+
* (a full disk), the file is as it was. Every row keeps its rowid.
|
|
655
|
+
*/
|
|
656
|
+
compact() {
|
|
657
|
+
this.db.pragma("auto_vacuum = INCREMENTAL");
|
|
658
|
+
this.db.exec("VACUUM");
|
|
659
|
+
}
|
|
660
|
+
/** Unsent messages queued under `keyFp`; every unsent message when no
|
|
661
|
+
* key is given. Neither counts the messages of a conversation Engram
|
|
662
|
+
* said it doesn't have (engram#593): those aren't sent. */
|
|
663
|
+
getPendingCount(keyFp) {
|
|
664
|
+
if (keyFp === undefined || !this.keyed)
|
|
665
|
+
return this.count(`1 = 1${this.notGone()}`);
|
|
666
|
+
return this.count(`key_fp IS ?${this.notGone()}`, keyFp);
|
|
667
|
+
}
|
|
668
|
+
/** Unsent messages waiting for an account other than `keyFp` (`null`:
|
|
669
|
+
* every unsent message — nobody is signed in to send them), but for
|
|
670
|
+
* those of a conversation Engram said it doesn't have. */
|
|
671
|
+
getHeldCount(keyFp) {
|
|
672
|
+
if (!this.keyed)
|
|
673
|
+
return 0;
|
|
674
|
+
if (keyFp === null)
|
|
675
|
+
return this.count(`1 = 1${this.notGone()}`);
|
|
676
|
+
return this.count(`key_fp IS NOT ?${this.notGone()}`, keyFp);
|
|
677
|
+
}
|
|
678
|
+
count(where, ...params) {
|
|
160
679
|
return this.db
|
|
161
|
-
.prepare(
|
|
162
|
-
.get().c;
|
|
680
|
+
.prepare(`SELECT COUNT(*) AS c FROM pending_messages WHERE sent_at IS NULL AND ${where}`)
|
|
681
|
+
.get(...params).c;
|
|
682
|
+
}
|
|
683
|
+
// ── Which key a queued row belongs to (engram#594) ──
|
|
684
|
+
/** Every other key something here is queued or mapped under. */
|
|
685
|
+
otherKeyFps(keyFp) {
|
|
686
|
+
return this.db
|
|
687
|
+
.prepare(`SELECT key_fp FROM pending_messages
|
|
688
|
+
WHERE sent_at IS NULL AND key_fp IS NOT NULL AND key_fp <> '' AND key_fp <> ?
|
|
689
|
+
UNION
|
|
690
|
+
SELECT key_fp FROM session_map WHERE key_fp <> '' AND key_fp <> ?
|
|
691
|
+
UNION
|
|
692
|
+
SELECT key_fp FROM remote_deletes
|
|
693
|
+
WHERE key_fp IS NOT NULL AND key_fp <> '' AND key_fp <> ?`)
|
|
694
|
+
.all(keyFp, keyFp, keyFp).map((r) => r.key_fp);
|
|
695
|
+
}
|
|
696
|
+
/**
|
|
697
|
+
* Hand what is queued or mapped under each of `from` to `toFp`, in ONE
|
|
698
|
+
* transaction — for keys the server confirmed are the same account's (a
|
|
699
|
+
* rotated or re-issued key, engram#594). With `unknownServerOnly`, only
|
|
700
|
+
* the rows that don't record their server move (engram#685): those
|
|
701
|
+
* recorded for the default server stay its own. What moves records the
|
|
702
|
+
* server it now goes to.
|
|
703
|
+
*/
|
|
704
|
+
adoptKeys(from, toFp) {
|
|
705
|
+
const statements = (only) => ({
|
|
706
|
+
messages: this.db.prepare(`UPDATE pending_messages SET key_fp = ?, server_known = 1
|
|
707
|
+
WHERE sent_at IS NULL AND key_fp = ?${only}`),
|
|
708
|
+
sessions: this.db.prepare(`UPDATE session_map SET key_fp = ?, server_known = 1 WHERE key_fp = ?${only}`),
|
|
709
|
+
deletes: this.db.prepare(`UPDATE remote_deletes SET key_fp = ?, server_known = 1 WHERE key_fp = ?${only}`),
|
|
710
|
+
});
|
|
711
|
+
const all = statements("");
|
|
712
|
+
const unknownOnly = statements(" AND server_known = 0");
|
|
713
|
+
return this.db.transaction(() => {
|
|
714
|
+
const moved = { messages: 0, sessions: 0, deletes: 0 };
|
|
715
|
+
for (const { fp, unknownServerOnly } of from) {
|
|
716
|
+
if (!fp || fp === toFp)
|
|
717
|
+
continue;
|
|
718
|
+
const s = unknownServerOnly ? unknownOnly : all;
|
|
719
|
+
moved.messages += s.messages.run(toFp, fp).changes;
|
|
720
|
+
moved.sessions += s.sessions.run(toFp, fp).changes;
|
|
721
|
+
moved.deletes += s.deletes.run(toFp, fp).changes;
|
|
722
|
+
}
|
|
723
|
+
return moved;
|
|
724
|
+
})();
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* The keys something here is queued, mapped or to be deleted under
|
|
728
|
+
* without a record of its server (engram#685): from before version 4,
|
|
729
|
+
* or from an older daemon. Rows queued while no key was in use aren't
|
|
730
|
+
* among them: claimLegacy gives those to an account, server and all.
|
|
731
|
+
*/
|
|
732
|
+
unknownServerFps() {
|
|
733
|
+
return this.db
|
|
734
|
+
.prepare(`SELECT key_fp FROM pending_messages
|
|
735
|
+
WHERE sent_at IS NULL AND server_known = 0 AND key_fp IS NOT NULL AND key_fp <> ''
|
|
736
|
+
UNION
|
|
737
|
+
SELECT key_fp FROM session_map WHERE server_known = 0 AND key_fp <> ''
|
|
738
|
+
UNION
|
|
739
|
+
SELECT key_fp FROM remote_deletes
|
|
740
|
+
WHERE server_known = 0 AND key_fp IS NOT NULL AND key_fp <> ''`)
|
|
741
|
+
.all().map((r) => r.key_fp);
|
|
742
|
+
}
|
|
743
|
+
/**
|
|
744
|
+
* Give the account `keyFp` everything that belongs to no key: rows from
|
|
745
|
+
* before version 1 and rows queued while signed out, the session mappings
|
|
746
|
+
* from before version 1, and the opt-out deletes an older daemon left in
|
|
747
|
+
* excluded_sessions. What it gets is its own, its server's included
|
|
748
|
+
* (engram#685). ONE transaction.
|
|
749
|
+
*/
|
|
750
|
+
claimLegacy(keyFp) {
|
|
751
|
+
this.db.transaction(() => {
|
|
752
|
+
// Two statements so each is an index search, not a scan of the queue.
|
|
753
|
+
this.db
|
|
754
|
+
.prepare(`UPDATE pending_messages SET key_fp = ?, server_known = 1
|
|
755
|
+
WHERE sent_at IS NULL AND key_fp IS NULL`)
|
|
756
|
+
.run(keyFp);
|
|
757
|
+
this.db
|
|
758
|
+
.prepare(`UPDATE pending_messages SET key_fp = ?, server_known = 1
|
|
759
|
+
WHERE sent_at IS NULL AND key_fp = ''`)
|
|
760
|
+
.run(keyFp);
|
|
761
|
+
this.db
|
|
762
|
+
.prepare("UPDATE session_map SET key_fp = ?, server_known = 1 WHERE key_fp = ''")
|
|
763
|
+
.run(keyFp);
|
|
764
|
+
this.db
|
|
765
|
+
.prepare(`INSERT OR IGNORE INTO remote_deletes
|
|
766
|
+
(conversation_id, key_fp, session_id, created_at, server_known)
|
|
767
|
+
SELECT delete_pending, ?, session_id, created_at, 1
|
|
768
|
+
FROM excluded_sessions WHERE delete_pending IS NOT NULL`)
|
|
769
|
+
.run(keyFp);
|
|
770
|
+
this.db
|
|
771
|
+
.prepare("UPDATE excluded_sessions SET delete_pending = NULL WHERE delete_pending IS NOT NULL")
|
|
772
|
+
.run();
|
|
773
|
+
this.db
|
|
774
|
+
.prepare("UPDATE remote_deletes SET key_fp = ?, server_known = 1 WHERE key_fp IS NULL OR key_fp = ''")
|
|
775
|
+
.run(keyFp);
|
|
776
|
+
})();
|
|
163
777
|
}
|
|
164
778
|
// ── Stats ──
|
|
165
|
-
|
|
779
|
+
/**
|
|
780
|
+
* `pendingMessages` are the unsent messages the account `keyFp` will send,
|
|
781
|
+
* and `heldMessages` the ones waiting for another account. No `keyFp`:
|
|
782
|
+
* every unsent message is pending. `null`: nobody is signed in, so every
|
|
783
|
+
* unsent message is held. `unknownServerFp` (engram#685): the key's own
|
|
784
|
+
* fingerprint, for an account on a server other than the default — what
|
|
785
|
+
* the key queued without a record of its server is sent there too, once
|
|
786
|
+
* that server confirms the key (see ownershipCandidates in syncer.ts).
|
|
787
|
+
* `notSentMessages` are those of conversations Engram said it doesn't
|
|
788
|
+
* have (engram#593), whoever is signed in: they're in neither of the
|
|
789
|
+
* other two.
|
|
790
|
+
*/
|
|
791
|
+
getStats(keyFp, unknownServerFp) {
|
|
166
792
|
const files = this.db
|
|
167
793
|
.prepare("SELECT COUNT(*) as c FROM file_offsets")
|
|
168
794
|
.get().c;
|
|
169
|
-
const pending = this.db
|
|
170
|
-
.prepare("SELECT COUNT(*) as c FROM pending_messages WHERE sent_at IS NULL")
|
|
171
|
-
.get().c;
|
|
172
795
|
const sessions = this.db
|
|
173
|
-
.prepare("SELECT COUNT(
|
|
796
|
+
.prepare("SELECT COUNT(DISTINCT session_id) as c FROM session_map")
|
|
174
797
|
.get().c;
|
|
798
|
+
let pending;
|
|
799
|
+
let held;
|
|
800
|
+
if (keyFp === undefined || !this.keyed) {
|
|
801
|
+
pending = this.getPendingCount();
|
|
802
|
+
held = 0;
|
|
803
|
+
}
|
|
804
|
+
else if (keyFp === null) {
|
|
805
|
+
pending = 0;
|
|
806
|
+
held = this.getHeldCount(null);
|
|
807
|
+
}
|
|
808
|
+
else if (unknownServerFp === undefined || unknownServerFp === keyFp) {
|
|
809
|
+
pending = this.getPendingCount(keyFp);
|
|
810
|
+
held = this.getHeldCount(keyFp);
|
|
811
|
+
}
|
|
812
|
+
else {
|
|
813
|
+
// Every row of a daemon.db from before version 4 is without a record
|
|
814
|
+
// of its server. Neither IS nor server_known (NOT NULL) yields NULL,
|
|
815
|
+
// so NOT takes exactly the rest.
|
|
816
|
+
const mine = this.serversKnown
|
|
817
|
+
? "(key_fp IS ? OR (key_fp IS ? AND server_known = 0))"
|
|
818
|
+
: "(key_fp IS ? OR key_fp IS ?)";
|
|
819
|
+
pending = this.count(`${mine}${this.notGone()}`, keyFp, unknownServerFp);
|
|
820
|
+
held = this.count(`NOT ${mine}${this.notGone()}`, keyFp, unknownServerFp);
|
|
821
|
+
}
|
|
175
822
|
return {
|
|
176
823
|
trackedFiles: files,
|
|
177
824
|
pendingMessages: pending,
|
|
825
|
+
heldMessages: held,
|
|
826
|
+
notSentMessages: this.getNotSentCount(),
|
|
178
827
|
sessionsMapped: sessions,
|
|
179
828
|
};
|
|
180
829
|
}
|
|
@@ -182,4 +831,51 @@ export class DaemonDb {
|
|
|
182
831
|
this.db.close();
|
|
183
832
|
}
|
|
184
833
|
}
|
|
834
|
+
/** Placeholder metadata for a session whose own was lost. */
|
|
835
|
+
function unknownSessionMeta(sessionId) {
|
|
836
|
+
return { sessionId, projectDir: "", recovered: true };
|
|
837
|
+
}
|
|
838
|
+
function parseStoredMeta(sessionId, raw) {
|
|
839
|
+
try {
|
|
840
|
+
const meta = JSON.parse(raw);
|
|
841
|
+
if (meta &&
|
|
842
|
+
typeof meta === "object" &&
|
|
843
|
+
typeof meta.projectDir === "string") {
|
|
844
|
+
return { ...meta, sessionId };
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
catch {
|
|
848
|
+
// fall through to the placeholder
|
|
849
|
+
}
|
|
850
|
+
return unknownSessionMeta(sessionId);
|
|
851
|
+
}
|
|
852
|
+
/** True when `filePath` is the transcript file named for `sessionId`:
|
|
853
|
+
* Claude Code writes `<id>.jsonl`, Codex `rollout-<time>-<id>.jsonl`. */
|
|
854
|
+
function isTranscriptOf(filePath, sessionId) {
|
|
855
|
+
const name = basename(filePath);
|
|
856
|
+
return name === `${sessionId}.jsonl` || name.endsWith(`-${sessionId}.jsonl`);
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Best-effort metadata for an orphaned session (engram#370). The transcript
|
|
860
|
+
* path tells us the host and, for Claude Code, the project; anything we
|
|
861
|
+
* can't tell stays empty (the conversation is titled by host). Exported for
|
|
862
|
+
* tests.
|
|
863
|
+
*/
|
|
864
|
+
export function recoveredSessionMeta(sessionId, filePath) {
|
|
865
|
+
// One separator for the checks below: Windows paths use backslashes
|
|
866
|
+
// (engram#602).
|
|
867
|
+
const normalized = filePath?.replace(/\\/g, "/");
|
|
868
|
+
if (filePath && normalized?.includes("/.claude/projects/")) {
|
|
869
|
+
return {
|
|
870
|
+
sessionId,
|
|
871
|
+
projectDir: claudeProjectDir(filePath),
|
|
872
|
+
host: "claude-code",
|
|
873
|
+
recovered: true,
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
if (normalized && /(^|\/)rollout-[^/]*\.jsonl$/.test(normalized)) {
|
|
877
|
+
return { sessionId, projectDir: "", host: "codex", recovered: true };
|
|
878
|
+
}
|
|
879
|
+
return unknownSessionMeta(sessionId);
|
|
880
|
+
}
|
|
185
881
|
//# sourceMappingURL=db.js.map
|