@pugi/cli 0.1.0-alpha.9 → 0.1.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/README.md +33 -0
- package/assets/pugi-mascot.ansi +41 -0
- package/dist/commands/deploy.js +439 -0
- package/dist/core/agents/loader.js +104 -0
- package/dist/core/agents/registry.js +1 -1
- package/dist/core/consensus/anvil-fanout.js +276 -0
- package/dist/core/consensus/diff-capture.js +382 -0
- package/dist/core/consensus/rubric.js +233 -0
- package/dist/core/context/index.js +21 -0
- package/dist/core/context/pugiignore.js +316 -0
- package/dist/core/context/repo-skeleton.js +533 -0
- package/dist/core/context/watcher.js +342 -0
- package/dist/core/context/working-set.js +165 -0
- package/dist/core/edits/dispatch.js +185 -0
- package/dist/core/edits/index.js +15 -0
- package/dist/core/edits/layer-a-apply.js +217 -0
- package/dist/core/edits/layer-b-apply.js +211 -0
- package/dist/core/edits/layer-c-apply.js +160 -0
- package/dist/core/edits/layer-d-ast.js +29 -0
- package/dist/core/edits/marker-parser.js +401 -0
- package/dist/core/edits/security-gate.js +223 -0
- package/dist/core/edits/worktree.js +229 -0
- package/dist/core/engine/native-pugi.js +6 -1
- package/dist/core/engine/prompts.js +4 -1
- package/dist/core/engine/tool-bridge.js +33 -1
- package/dist/core/lsp/client.js +631 -0
- package/dist/core/repl/ask.js +512 -0
- package/dist/core/repl/cancellation.js +98 -0
- package/dist/core/repl/dispatch-fsm.js +220 -0
- package/dist/core/repl/privacy-banner.js +71 -0
- package/dist/core/repl/session.js +1896 -13
- package/dist/core/repl/slash-commands.js +59 -32
- package/dist/core/repl/store/index.js +12 -0
- package/dist/core/repl/store/jsonl-log.js +321 -0
- package/dist/core/repl/store/lockfile.js +155 -0
- package/dist/core/repl/store/session-store.js +792 -0
- package/dist/core/repl/store/types.js +44 -0
- package/dist/core/repl/store/uuid-v7.js +68 -0
- package/dist/core/repl/workspace-context.js +72 -1
- package/dist/core/skills/loader.js +454 -0
- package/dist/core/skills/sources.js +480 -0
- package/dist/core/skills/trust.js +172 -0
- package/dist/runtime/cli.js +767 -10
- package/dist/runtime/commands/agents.js +385 -0
- package/dist/runtime/commands/config.js +338 -8
- package/dist/runtime/commands/lsp.js +184 -0
- package/dist/runtime/commands/patch.js +111 -0
- package/dist/runtime/commands/review-consensus.js +399 -0
- package/dist/runtime/commands/skills.js +401 -0
- package/dist/runtime/commands/worktree.js +133 -0
- package/dist/tools/apply-patch.js +314 -0
- package/dist/tools/file-tools.js +90 -0
- package/dist/tools/lsp-tools.js +189 -0
- package/dist/tools/registry.js +18 -0
- package/dist/tools/web-fetch.js +1 -1
- package/dist/tui/agent-tree-pane.js +9 -0
- package/dist/tui/ask-cli.js +52 -0
- package/dist/tui/ask-modal.js +211 -0
- package/dist/tui/conversation-pane.js +48 -3
- package/dist/tui/input-box.js +48 -5
- package/dist/tui/markdown-render.js +266 -0
- package/dist/tui/repl-render.js +185 -0
- package/dist/tui/repl-splash-mascot.js +130 -0
- package/dist/tui/repl-splash.js +7 -1
- package/dist/tui/repl.js +82 -11
- package/dist/tui/status-bar.js +63 -3
- package/dist/tui/tool-stream-pane.js +91 -0
- package/package.json +11 -5
|
@@ -0,0 +1,792 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SessionStore — Sprint α6.4 (PR-PUGI-CLI-SESSION-STORE).
|
|
3
|
+
*
|
|
4
|
+
* SQLite-indexed, JSONL-durable session store. The JSONL log is the
|
|
5
|
+
* source of truth; the SQLite tables are a queryable cache. Layout:
|
|
6
|
+
*
|
|
7
|
+
* ~/.pugi/projects/<project-slug>/
|
|
8
|
+
* session.db SQLite index (sessions + FTS5)
|
|
9
|
+
* session.lock PID lockfile
|
|
10
|
+
* sessions/<session-id>/
|
|
11
|
+
* events.0.jsonl active append log
|
|
12
|
+
* events.1.jsonl older rotations (50 MB threshold)
|
|
13
|
+
*
|
|
14
|
+
* The store lives entirely under `$HOME/.pugi/` per the local-first
|
|
15
|
+
* invariants memo (`feedback_no_landing_oes_secondary_2026_05_23.md`)
|
|
16
|
+
* — never write inside the repo unless the operator explicitly opts in
|
|
17
|
+
* via `--workspace`. The repo's `.pugi/` directory (touched by `pugi
|
|
18
|
+
* init`) is a SEPARATE concept used for artifacts + per-repo settings.
|
|
19
|
+
*
|
|
20
|
+
* Why node:sqlite over better-sqlite3:
|
|
21
|
+
*
|
|
22
|
+
* - Zero install-time native build. better-sqlite3 needs prebuilt
|
|
23
|
+
* binaries for every Node ABI × platform; missing a wheel forces
|
|
24
|
+
* a node-gyp compile that fails on bare-metal CI agents without
|
|
25
|
+
* a C++ toolchain. Pugi CLI ships via npm to operators who almost
|
|
26
|
+
* certainly do not have build-essential installed.
|
|
27
|
+
* - Available since Node 22.5.0 (stable subset; LTS as of 2026). Our
|
|
28
|
+
* `engines.node` is pinned to `>=22.5.0` in apps/pugi-cli +
|
|
29
|
+
* packages/pugi-sdk so npm refuses to install the CLI on Node 20.x
|
|
30
|
+
* instead of crash-on-import. CI runs Node 22 (matrix-free; see
|
|
31
|
+
* `.github/workflows/ci.yml`).
|
|
32
|
+
* - Marked Experimental by Node — silenced via process.emitWarning
|
|
33
|
+
* suppression at boot. The API surface we use (DatabaseSync,
|
|
34
|
+
* StatementSync, exec/prepare) is the stable subset that has
|
|
35
|
+
* shipped unchanged since Node 22.5.
|
|
36
|
+
*
|
|
37
|
+
* Schema is created at first open. `schema_meta` carries a single row
|
|
38
|
+
* `('version', '1')`; future migrations bump the version + run the
|
|
39
|
+
* delta. v1 is the only schema this PR ships.
|
|
40
|
+
*/
|
|
41
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
42
|
+
import { existsSync, mkdirSync } from 'node:fs';
|
|
43
|
+
import { homedir } from 'node:os';
|
|
44
|
+
import { resolve } from 'node:path';
|
|
45
|
+
import { JsonlEventLog } from './jsonl-log.js';
|
|
46
|
+
import { takeLock } from './lockfile.js';
|
|
47
|
+
import { uuidV7 } from './uuid-v7.js';
|
|
48
|
+
const SCHEMA_VERSION = '1';
|
|
49
|
+
const SCHEMA_SQL = `
|
|
50
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
51
|
+
id TEXT PRIMARY KEY,
|
|
52
|
+
created_at INTEGER NOT NULL,
|
|
53
|
+
updated_at INTEGER NOT NULL,
|
|
54
|
+
workspace_root TEXT NOT NULL,
|
|
55
|
+
branch TEXT,
|
|
56
|
+
project_slug TEXT NOT NULL,
|
|
57
|
+
title TEXT,
|
|
58
|
+
turn_count INTEGER NOT NULL DEFAULT 0,
|
|
59
|
+
event_count INTEGER NOT NULL DEFAULT 0,
|
|
60
|
+
model TEXT,
|
|
61
|
+
tenant_id TEXT,
|
|
62
|
+
status TEXT NOT NULL DEFAULT 'active'
|
|
63
|
+
);
|
|
64
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_updated ON sessions(updated_at DESC);
|
|
65
|
+
CREATE INDEX IF NOT EXISTS idx_sessions_project ON sessions(project_slug, updated_at DESC);
|
|
66
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS sessions_fts USING fts5(
|
|
67
|
+
id UNINDEXED,
|
|
68
|
+
title,
|
|
69
|
+
body,
|
|
70
|
+
tokenize='unicode61'
|
|
71
|
+
);
|
|
72
|
+
CREATE TABLE IF NOT EXISTS schema_meta (
|
|
73
|
+
key TEXT PRIMARY KEY,
|
|
74
|
+
value TEXT NOT NULL
|
|
75
|
+
);
|
|
76
|
+
`;
|
|
77
|
+
/** Default list limit. Operators rarely scroll past the most recent 50. */
|
|
78
|
+
const DEFAULT_LIST_LIMIT = 50;
|
|
79
|
+
/** Hard cap on list limit. Protects the picker UI from huge result sets. */
|
|
80
|
+
const MAX_LIST_LIMIT = 1000;
|
|
81
|
+
/** Default search limit. */
|
|
82
|
+
const DEFAULT_SEARCH_LIMIT = 20;
|
|
83
|
+
/** Hard cap on search limit. */
|
|
84
|
+
const MAX_SEARCH_LIMIT = 200;
|
|
85
|
+
/** Title truncation per spec §4.2 MUST-ship #1. */
|
|
86
|
+
const TITLE_MAX_CHARS = 80;
|
|
87
|
+
/**
|
|
88
|
+
* Resolve the absolute path of the per-project store directory under
|
|
89
|
+
* `$HOME/.pugi/projects/<slug>/`. Exported so the CLI dispatcher can
|
|
90
|
+
* print the location in `pugi doctor` output.
|
|
91
|
+
*/
|
|
92
|
+
export function resolveProjectStoreDir(projectSlug, homeOverride) {
|
|
93
|
+
const home = homeOverride ?? homedir();
|
|
94
|
+
return resolve(home, '.pugi', 'projects', sanitiseSlugForFs(projectSlug));
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Concrete SessionStore implementation. Construct, then `open()` to
|
|
98
|
+
* bind one session; `close()` to release the lock + SQLite handle.
|
|
99
|
+
*/
|
|
100
|
+
export class SqliteSessionStore {
|
|
101
|
+
projectSlug;
|
|
102
|
+
home;
|
|
103
|
+
now;
|
|
104
|
+
killProbe;
|
|
105
|
+
projectDir;
|
|
106
|
+
db = null;
|
|
107
|
+
lock = null;
|
|
108
|
+
/**
|
|
109
|
+
* Active JSONL log for the currently-open session. `null` between
|
|
110
|
+
* `open()` calls. Only one session is bound at a time — the REPL
|
|
111
|
+
* runs one session per REPL lifetime; multi-session is a CLI-only
|
|
112
|
+
* concern (`pugi sessions list`).
|
|
113
|
+
*/
|
|
114
|
+
activeLog = null;
|
|
115
|
+
activeSessionId = null;
|
|
116
|
+
constructor(opts) {
|
|
117
|
+
this.projectSlug = opts.projectSlug;
|
|
118
|
+
this.home = opts.home ?? homedir();
|
|
119
|
+
this.now = opts.now ?? Date.now;
|
|
120
|
+
this.killProbe = opts.killProbe;
|
|
121
|
+
this.projectDir = resolveProjectStoreDir(this.projectSlug, this.home);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Open the SQLite connection + take the lockfile + insert-or-reopen
|
|
125
|
+
* the session row. Idempotent in the sense that a second `open()`
|
|
126
|
+
* with the same session id reuses the connection and returns the
|
|
127
|
+
* existing row. A second `open()` with a different id rebinds the
|
|
128
|
+
* active log to the new session (the SQLite connection stays).
|
|
129
|
+
*/
|
|
130
|
+
async open(input) {
|
|
131
|
+
if (!existsSync(this.projectDir)) {
|
|
132
|
+
mkdirSync(this.projectDir, { recursive: true, mode: 0o700 });
|
|
133
|
+
}
|
|
134
|
+
if (this.db === null) {
|
|
135
|
+
this.takeLockOrThrow();
|
|
136
|
+
this.openDatabase();
|
|
137
|
+
}
|
|
138
|
+
const id = input.id ?? uuidV7(this.now);
|
|
139
|
+
const sessionDir = resolve(this.projectDir, 'sessions', id);
|
|
140
|
+
if (!existsSync(sessionDir)) {
|
|
141
|
+
mkdirSync(sessionDir, { recursive: true, mode: 0o700 });
|
|
142
|
+
}
|
|
143
|
+
// Rebind the active JSONL log to the new session id.
|
|
144
|
+
if (this.activeLog && this.activeSessionId !== id) {
|
|
145
|
+
this.activeLog.close();
|
|
146
|
+
this.activeLog = null;
|
|
147
|
+
}
|
|
148
|
+
if (!this.activeLog) {
|
|
149
|
+
this.activeLog = new JsonlEventLog({ sessionDir, now: this.now });
|
|
150
|
+
this.activeSessionId = id;
|
|
151
|
+
}
|
|
152
|
+
const existing = this.getSessionSync(id);
|
|
153
|
+
if (existing) {
|
|
154
|
+
// Reopen path: bump updated_at so the listing reflects activity.
|
|
155
|
+
return this.updateSessionMetaSync(id, {});
|
|
156
|
+
}
|
|
157
|
+
return this.insertSessionSync({
|
|
158
|
+
id,
|
|
159
|
+
workspaceRoot: input.workspaceRoot,
|
|
160
|
+
projectSlug: this.projectSlug,
|
|
161
|
+
branch: input.branch ?? null,
|
|
162
|
+
model: input.model ?? null,
|
|
163
|
+
tenantId: input.tenantId ?? null,
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Append one event. Writes the JSONL line first (durable truth),
|
|
168
|
+
* then updates the SQLite cache. On the first non-empty `user`
|
|
169
|
+
* event, sets the session title if it is still null.
|
|
170
|
+
*/
|
|
171
|
+
async appendEvent(event) {
|
|
172
|
+
const log = this.requireActiveLog();
|
|
173
|
+
const db = this.requireDb();
|
|
174
|
+
const sessionId = this.requireSessionId();
|
|
175
|
+
log.append(event);
|
|
176
|
+
const ts = this.now();
|
|
177
|
+
const isUserTurn = event.kind === 'user';
|
|
178
|
+
const titlePatch = this.maybeTitleFromEvent(sessionId, event);
|
|
179
|
+
// Single UPDATE: bump event_count, bump updated_at, conditionally
|
|
180
|
+
// bump turn_count and set title. Splitting into multiple statements
|
|
181
|
+
// would race the lockfile if a second process slipped through.
|
|
182
|
+
const sql = `
|
|
183
|
+
UPDATE sessions
|
|
184
|
+
SET event_count = event_count + 1,
|
|
185
|
+
updated_at = ?,
|
|
186
|
+
turn_count = turn_count + ${isUserTurn ? 1 : 0},
|
|
187
|
+
title = COALESCE(title, ?)
|
|
188
|
+
WHERE id = ?
|
|
189
|
+
`;
|
|
190
|
+
db.prepare(sql).run(ts, titlePatch ?? null, sessionId);
|
|
191
|
+
// Mirror the user-turn body into FTS so substring search hits
|
|
192
|
+
// every previous user turn, not just the most recent one.
|
|
193
|
+
// Previously this called `upsertFtsRow(... body)` which did
|
|
194
|
+
// DELETE+INSERT and DROPPED every prior turn from the FTS body.
|
|
195
|
+
// We append-with-newline to the existing body so subsequent
|
|
196
|
+
// searches still hit terms from earlier turns.
|
|
197
|
+
if (event.kind === 'user') {
|
|
198
|
+
const body = extractEventText(event);
|
|
199
|
+
if (body.length > 0) {
|
|
200
|
+
this.appendFtsBody(sessionId, body);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
async listSessions(opts) {
|
|
205
|
+
const db = this.requireDb();
|
|
206
|
+
const limit = clampLimit(opts?.limit ?? DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT);
|
|
207
|
+
// Default: active+archived (suppress aborted). Caller opts into
|
|
208
|
+
// 'all' explicitly to see aborted rows, or names one status to
|
|
209
|
+
// narrow further. Spec'd on `SessionListOptions.status` in
|
|
210
|
+
// ./types.ts — keep this branch in lockstep with that doc comment.
|
|
211
|
+
const statusFilter = opts?.status ?? 'active+archived';
|
|
212
|
+
const cursor = opts?.cursor;
|
|
213
|
+
const where = [];
|
|
214
|
+
const params = [];
|
|
215
|
+
if (opts?.project) {
|
|
216
|
+
where.push('project_slug = ?');
|
|
217
|
+
params.push(opts.project);
|
|
218
|
+
}
|
|
219
|
+
if (statusFilter === 'all') {
|
|
220
|
+
// No status clause — return every row regardless of status.
|
|
221
|
+
}
|
|
222
|
+
else if (statusFilter === 'active+archived') {
|
|
223
|
+
// Default path — suppress 'aborted' rows from the listing.
|
|
224
|
+
where.push(`status != 'aborted'`);
|
|
225
|
+
}
|
|
226
|
+
else {
|
|
227
|
+
where.push('status = ?');
|
|
228
|
+
params.push(statusFilter);
|
|
229
|
+
}
|
|
230
|
+
if (cursor) {
|
|
231
|
+
// Pagination cursor: return rows STRICTLY older than the cursor
|
|
232
|
+
// row's updated_at. We resolve the cursor's updated_at in a
|
|
233
|
+
// single subquery so an invalid cursor degrades to an empty
|
|
234
|
+
// result instead of a hard error.
|
|
235
|
+
where.push('updated_at < (SELECT updated_at FROM sessions WHERE id = ?)');
|
|
236
|
+
params.push(cursor);
|
|
237
|
+
}
|
|
238
|
+
const whereClause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';
|
|
239
|
+
const sql = `
|
|
240
|
+
SELECT id, created_at, updated_at, workspace_root, branch, project_slug,
|
|
241
|
+
title, turn_count, event_count, model, tenant_id, status
|
|
242
|
+
FROM sessions
|
|
243
|
+
${whereClause}
|
|
244
|
+
ORDER BY updated_at DESC
|
|
245
|
+
LIMIT ?
|
|
246
|
+
`;
|
|
247
|
+
const stmt = db.prepare(sql);
|
|
248
|
+
const rows = stmt.all(...params, limit);
|
|
249
|
+
return rows.map(rawToSession);
|
|
250
|
+
}
|
|
251
|
+
async loadEvents(sessionId, opts) {
|
|
252
|
+
const log = this.logForSession(sessionId);
|
|
253
|
+
// For the ACTIVE session we share the long-lived JsonlEventLog
|
|
254
|
+
// owned by `this.activeLog`; we must NOT close it. For any other
|
|
255
|
+
// session we constructed a fresh JsonlEventLog inside
|
|
256
|
+
// logForSession; close it here so the file descriptor it opens
|
|
257
|
+
// lazily during read does not leak. Without this guard, repeated
|
|
258
|
+
// loadEvents() calls for inactive sessions accumulated fds and
|
|
259
|
+
// tripped EMFILE under high load.
|
|
260
|
+
const isActive = this.activeLog === log;
|
|
261
|
+
try {
|
|
262
|
+
return log.read(opts);
|
|
263
|
+
}
|
|
264
|
+
finally {
|
|
265
|
+
if (!isActive) {
|
|
266
|
+
log.close();
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
async getSession(sessionId) {
|
|
271
|
+
return this.getSessionSync(sessionId);
|
|
272
|
+
}
|
|
273
|
+
async updateSessionMeta(sessionId, patch) {
|
|
274
|
+
return this.updateSessionMetaSync(sessionId, patch);
|
|
275
|
+
}
|
|
276
|
+
async search(query, opts) {
|
|
277
|
+
const trimmed = query.trim();
|
|
278
|
+
if (trimmed.length === 0) {
|
|
279
|
+
throw new Error('SessionStore.search requires a non-empty query');
|
|
280
|
+
}
|
|
281
|
+
const db = this.requireDb();
|
|
282
|
+
const limit = clampLimit(opts?.limit ?? DEFAULT_SEARCH_LIMIT, MAX_SEARCH_LIMIT);
|
|
283
|
+
// FTS5 MATCH on title+body. Always wrap as a quoted phrase + escape
|
|
284
|
+
// embedded `"` so an unbalanced quote in the operator's input
|
|
285
|
+
// (`pugi sessions --search 'cabinet"'`) cannot crash SQLite with
|
|
286
|
+
// `SQLITE_ERROR: fts5: syntax error`. The wrapper is defensive —
|
|
287
|
+
// operator-typed FTS5 syntax (`body:cabinet OR title:sidebar`) is
|
|
288
|
+
// intentionally NOT supported anymore; the upside is "no surprise
|
|
289
|
+
// crash on a stray quote" and the downside is "no power-user FTS5
|
|
290
|
+
// syntax", which the spec accepts.
|
|
291
|
+
const ftsQuery = sanitiseFtsQuery(trimmed);
|
|
292
|
+
// FTS5 requires MATCH against the virtual-table name itself; the
|
|
293
|
+
// column-restricted form (`f.body MATCH ?`) is rejected with
|
|
294
|
+
// `unable to use function MATCH in the requested context`. We
|
|
295
|
+
// search title+body together by matching against `sessions_fts`.
|
|
296
|
+
const sql = `
|
|
297
|
+
SELECT s.id, s.created_at, s.updated_at, s.workspace_root, s.branch,
|
|
298
|
+
s.project_slug, s.title, s.turn_count, s.event_count, s.model,
|
|
299
|
+
s.tenant_id, s.status
|
|
300
|
+
FROM sessions_fts f
|
|
301
|
+
JOIN sessions s ON s.id = f.id
|
|
302
|
+
WHERE sessions_fts MATCH ?
|
|
303
|
+
ORDER BY s.updated_at DESC
|
|
304
|
+
LIMIT ?
|
|
305
|
+
`;
|
|
306
|
+
let rows;
|
|
307
|
+
try {
|
|
308
|
+
rows = db.prepare(sql).all(ftsQuery, limit);
|
|
309
|
+
}
|
|
310
|
+
catch (error) {
|
|
311
|
+
// Wrap SQLITE_ERROR from FTS5 so the CLI can print a single-line
|
|
312
|
+
// operator-friendly message + exit 2 instead of dumping a stack.
|
|
313
|
+
// The dispatcher branches on error.code === 'EFTS5_SYNTAX'.
|
|
314
|
+
if (isSqliteError(error)) {
|
|
315
|
+
throw new FtsSyntaxError(ftsQuery, error);
|
|
316
|
+
}
|
|
317
|
+
throw error;
|
|
318
|
+
}
|
|
319
|
+
return rows.map(rawToSession);
|
|
320
|
+
}
|
|
321
|
+
async close() {
|
|
322
|
+
if (this.activeLog) {
|
|
323
|
+
this.activeLog.close();
|
|
324
|
+
this.activeLog = null;
|
|
325
|
+
this.activeSessionId = null;
|
|
326
|
+
}
|
|
327
|
+
if (this.db) {
|
|
328
|
+
try {
|
|
329
|
+
this.db.close();
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
/* idempotent — already closed */
|
|
333
|
+
}
|
|
334
|
+
this.db = null;
|
|
335
|
+
}
|
|
336
|
+
if (this.lock) {
|
|
337
|
+
this.lock.release();
|
|
338
|
+
this.lock = null;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Open the per-project SQLite file in read-only mode WITHOUT taking
|
|
343
|
+
* the lockfile and WITHOUT inserting a session row. The caller
|
|
344
|
+
* receives a small view that supports `list` / `search` / `get` and
|
|
345
|
+
* must call `close()` when done.
|
|
346
|
+
*
|
|
347
|
+
* SQLite supports multiple concurrent readers even when a writer
|
|
348
|
+
* holds an OS-level lock, so this view is safe to open while a live
|
|
349
|
+
* REPL is writing in the same project.
|
|
350
|
+
*
|
|
351
|
+
* Used by `pugi resume --list`, `pugi sessions --local`, `pugi
|
|
352
|
+
* sessions --search`, and `pugi resume <id>` so those read-only
|
|
353
|
+
* commands no longer mint a stub session row + pollute the listing.
|
|
354
|
+
*/
|
|
355
|
+
static async openReadOnly(projectStoreDir) {
|
|
356
|
+
const dbPath = resolve(projectStoreDir, 'session.db');
|
|
357
|
+
if (!existsSync(dbPath)) {
|
|
358
|
+
throw Object.assign(new Error(`No session database at ${dbPath}`), { code: 'ENOENT' });
|
|
359
|
+
}
|
|
360
|
+
// node:sqlite DatabaseSync accepts a `{ readOnly: true }` option
|
|
361
|
+
// which maps to SQLITE_OPEN_READONLY. The option form is the
|
|
362
|
+
// documented API; the file-URI form (file:...?mode=ro) also works.
|
|
363
|
+
const db = new DatabaseSync(dbPath, { readOnly: true });
|
|
364
|
+
return new SqliteSessionStoreReadOnlyView(db);
|
|
365
|
+
}
|
|
366
|
+
/* ------------------------------------------------------------ */
|
|
367
|
+
/* Internals */
|
|
368
|
+
/* ------------------------------------------------------------ */
|
|
369
|
+
takeLockOrThrow() {
|
|
370
|
+
const lockPath = resolve(this.projectDir, 'session.lock');
|
|
371
|
+
// Surface SessionLockBusyError as-is so the dispatcher can branch
|
|
372
|
+
// on `error.code === 'EBUSY_SESSION_LOCK'`. Anything else
|
|
373
|
+
// (EACCES, ENOSPC) propagates so the caller sees the real cause.
|
|
374
|
+
this.lock = takeLock(lockPath, this.killProbe ? { kill: this.killProbe } : undefined);
|
|
375
|
+
}
|
|
376
|
+
openDatabase() {
|
|
377
|
+
const dbPath = resolve(this.projectDir, 'session.db');
|
|
378
|
+
this.db = new DatabaseSync(dbPath);
|
|
379
|
+
// WAL mode: writers do not block readers. The lockfile already
|
|
380
|
+
// serialises us across processes, but WAL keeps an in-process
|
|
381
|
+
// read query from blocking the append-event writer.
|
|
382
|
+
this.db.exec('PRAGMA journal_mode = WAL');
|
|
383
|
+
// synchronous=NORMAL is safe with WAL and avoids the per-fsync
|
|
384
|
+
// hit on every COMMIT. Crash safety is provided by the JSONL log
|
|
385
|
+
// (the source of truth), not by SQLite — losing the index after
|
|
386
|
+
// power loss is recoverable via `pugi sessions --rebuild`.
|
|
387
|
+
this.db.exec('PRAGMA synchronous = NORMAL');
|
|
388
|
+
this.db.exec('PRAGMA foreign_keys = ON');
|
|
389
|
+
this.db.exec(SCHEMA_SQL);
|
|
390
|
+
// Stamp the schema version. INSERT OR IGNORE so a reopen against
|
|
391
|
+
// an existing v1 database is a no-op.
|
|
392
|
+
this.db
|
|
393
|
+
.prepare('INSERT OR IGNORE INTO schema_meta(key, value) VALUES (?, ?)')
|
|
394
|
+
.run('version', SCHEMA_VERSION);
|
|
395
|
+
}
|
|
396
|
+
requireDb() {
|
|
397
|
+
if (!this.db)
|
|
398
|
+
throw new Error('SessionStore is not open');
|
|
399
|
+
return this.db;
|
|
400
|
+
}
|
|
401
|
+
requireActiveLog() {
|
|
402
|
+
if (!this.activeLog) {
|
|
403
|
+
throw new Error('SessionStore has no active session — call open() first');
|
|
404
|
+
}
|
|
405
|
+
return this.activeLog;
|
|
406
|
+
}
|
|
407
|
+
requireSessionId() {
|
|
408
|
+
if (!this.activeSessionId) {
|
|
409
|
+
throw new Error('SessionStore has no active session id');
|
|
410
|
+
}
|
|
411
|
+
return this.activeSessionId;
|
|
412
|
+
}
|
|
413
|
+
logForSession(sessionId) {
|
|
414
|
+
if (this.activeSessionId === sessionId && this.activeLog) {
|
|
415
|
+
return this.activeLog;
|
|
416
|
+
}
|
|
417
|
+
const sessionDir = resolve(this.projectDir, 'sessions', sessionId);
|
|
418
|
+
return new JsonlEventLog({ sessionDir, now: this.now });
|
|
419
|
+
}
|
|
420
|
+
getSessionSync(sessionId) {
|
|
421
|
+
const db = this.requireDb();
|
|
422
|
+
const stmt = db.prepare(`
|
|
423
|
+
SELECT id, created_at, updated_at, workspace_root, branch, project_slug,
|
|
424
|
+
title, turn_count, event_count, model, tenant_id, status
|
|
425
|
+
FROM sessions
|
|
426
|
+
WHERE id = ?
|
|
427
|
+
`);
|
|
428
|
+
const row = stmt.get(sessionId);
|
|
429
|
+
return row ? rawToSession(row) : null;
|
|
430
|
+
}
|
|
431
|
+
insertSessionSync(input) {
|
|
432
|
+
const db = this.requireDb();
|
|
433
|
+
const ts = this.now();
|
|
434
|
+
db.prepare(`
|
|
435
|
+
INSERT INTO sessions
|
|
436
|
+
(id, created_at, updated_at, workspace_root, branch, project_slug,
|
|
437
|
+
title, turn_count, event_count, model, tenant_id, status)
|
|
438
|
+
VALUES (?, ?, ?, ?, ?, ?, NULL, 0, 0, ?, ?, 'active')
|
|
439
|
+
`).run(input.id, ts, ts, input.workspaceRoot, input.branch, input.projectSlug, input.model, input.tenantId);
|
|
440
|
+
// Seed an empty FTS row so the title patch path can rely on a
|
|
441
|
+
// single UPDATE OR REPLACE without first checking for the row.
|
|
442
|
+
this.upsertFtsRow(input.id, '', '');
|
|
443
|
+
return {
|
|
444
|
+
id: input.id,
|
|
445
|
+
createdAt: ts,
|
|
446
|
+
updatedAt: ts,
|
|
447
|
+
workspaceRoot: input.workspaceRoot,
|
|
448
|
+
branch: input.branch,
|
|
449
|
+
projectSlug: input.projectSlug,
|
|
450
|
+
title: null,
|
|
451
|
+
turnCount: 0,
|
|
452
|
+
eventCount: 0,
|
|
453
|
+
model: input.model,
|
|
454
|
+
tenantId: input.tenantId,
|
|
455
|
+
status: 'active',
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
updateSessionMetaSync(sessionId, patch) {
|
|
459
|
+
const db = this.requireDb();
|
|
460
|
+
const ts = this.now();
|
|
461
|
+
// Build a dynamic UPDATE. We only allow fields declared on
|
|
462
|
+
// SessionRowPatch to land in SQL; an unknown key throws so the
|
|
463
|
+
// caller sees the bug at the call site.
|
|
464
|
+
const ALLOWED_PATCH_FIELDS = new Set([
|
|
465
|
+
'workspaceRoot',
|
|
466
|
+
'branch',
|
|
467
|
+
'projectSlug',
|
|
468
|
+
'title',
|
|
469
|
+
'turnCount',
|
|
470
|
+
'eventCount',
|
|
471
|
+
'model',
|
|
472
|
+
'tenantId',
|
|
473
|
+
'status',
|
|
474
|
+
]);
|
|
475
|
+
const sets = ['updated_at = ?'];
|
|
476
|
+
const params = [ts];
|
|
477
|
+
for (const key of Object.keys(patch)) {
|
|
478
|
+
if (!ALLOWED_PATCH_FIELDS.has(key)) {
|
|
479
|
+
throw new Error(`SessionStore.updateSessionMeta: unknown field '${String(key)}'`);
|
|
480
|
+
}
|
|
481
|
+
const column = camelToSnake(key);
|
|
482
|
+
sets.push(`${column} = ?`);
|
|
483
|
+
params.push(patch[key] === undefined ? null : patch[key]);
|
|
484
|
+
}
|
|
485
|
+
params.push(sessionId);
|
|
486
|
+
const sql = `UPDATE sessions SET ${sets.join(', ')} WHERE id = ?`;
|
|
487
|
+
const result = db.prepare(sql).run(...params);
|
|
488
|
+
if (Number(result.changes) === 0) {
|
|
489
|
+
throw new Error(`SessionStore.updateSessionMeta: session '${sessionId}' not found`);
|
|
490
|
+
}
|
|
491
|
+
// Mirror title changes into the FTS row.
|
|
492
|
+
if (patch.title !== undefined) {
|
|
493
|
+
this.upsertFtsRow(sessionId, patch.title ?? '', this.bodyForFts(sessionId));
|
|
494
|
+
}
|
|
495
|
+
const row = this.getSessionSync(sessionId);
|
|
496
|
+
if (!row) {
|
|
497
|
+
throw new Error(`SessionStore.updateSessionMeta: session '${sessionId}' vanished after UPDATE`);
|
|
498
|
+
}
|
|
499
|
+
return row;
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Pick a title from a fresh `user` event when the session does not
|
|
503
|
+
* yet have one. Returns the truncated title or null when no patch
|
|
504
|
+
* should be applied. Idempotent — once title is non-null, subsequent
|
|
505
|
+
* calls return null.
|
|
506
|
+
*/
|
|
507
|
+
maybeTitleFromEvent(sessionId, event) {
|
|
508
|
+
if (event.kind !== 'user')
|
|
509
|
+
return null;
|
|
510
|
+
const existing = this.getSessionSync(sessionId);
|
|
511
|
+
if (!existing || existing.title)
|
|
512
|
+
return null;
|
|
513
|
+
const text = extractEventText(event);
|
|
514
|
+
if (text.length === 0)
|
|
515
|
+
return null;
|
|
516
|
+
return text.slice(0, TITLE_MAX_CHARS);
|
|
517
|
+
}
|
|
518
|
+
upsertFtsRow(sessionId, title, body) {
|
|
519
|
+
const db = this.requireDb();
|
|
520
|
+
// FTS5 virtual tables don't support UPSERT — emulate with delete +
|
|
521
|
+
// insert. Cheap because each session has one FTS row.
|
|
522
|
+
db.prepare('DELETE FROM sessions_fts WHERE id = ?').run(sessionId);
|
|
523
|
+
db.prepare('INSERT INTO sessions_fts (id, title, body) VALUES (?, ?, ?)')
|
|
524
|
+
.run(sessionId, title, body);
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Append text to the FTS body of one session, preserving every prior
|
|
528
|
+
* turn. Reads the current row, concatenates `body + '\n' + addition`,
|
|
529
|
+
* and rewrites the row via the DELETE+INSERT path because FTS5
|
|
530
|
+
* virtual tables do not support UPDATE on the content column in the
|
|
531
|
+
* external-content-table configuration we use.
|
|
532
|
+
*
|
|
533
|
+
* Each session has at most one FTS row (one row per session id), so
|
|
534
|
+
* the read-modify-write here is O(1) on the FTS index.
|
|
535
|
+
*
|
|
536
|
+
* Wrapped in BEGIN IMMEDIATE / COMMIT so a concurrent ReadOnlyView
|
|
537
|
+
* cannot observe the brief "row deleted" window between the DELETE
|
|
538
|
+
* and the INSERT that upsertFtsRow performs. BEGIN IMMEDIATE acquires
|
|
539
|
+
* the write lock at BEGIN time, failing fast on contention instead of
|
|
540
|
+
* leaving the txn half-applied. On any error we ROLLBACK and rethrow
|
|
541
|
+
* so the caller's catch surface stays unchanged.
|
|
542
|
+
*/
|
|
543
|
+
appendFtsBody(sessionId, addition) {
|
|
544
|
+
const db = this.requireDb();
|
|
545
|
+
db.exec('BEGIN IMMEDIATE');
|
|
546
|
+
try {
|
|
547
|
+
const existingBody = this.bodyForFts(sessionId);
|
|
548
|
+
const existingTitle = this.titleForFts(sessionId);
|
|
549
|
+
const nextBody = existingBody.length === 0
|
|
550
|
+
? addition
|
|
551
|
+
: `${existingBody}\n${addition}`;
|
|
552
|
+
this.upsertFtsRow(sessionId, existingTitle, nextBody);
|
|
553
|
+
db.exec('COMMIT');
|
|
554
|
+
}
|
|
555
|
+
catch (err) {
|
|
556
|
+
try {
|
|
557
|
+
db.exec('ROLLBACK');
|
|
558
|
+
}
|
|
559
|
+
catch {
|
|
560
|
+
// Swallow rollback failures; the original error is the one
|
|
561
|
+
// worth surfacing. SQLite auto-rolls back when the txn handle
|
|
562
|
+
// goes out of scope if ROLLBACK itself fails.
|
|
563
|
+
}
|
|
564
|
+
throw err;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
titleForFts(sessionId) {
|
|
568
|
+
const row = this.getSessionSync(sessionId);
|
|
569
|
+
return row?.title ?? '';
|
|
570
|
+
}
|
|
571
|
+
bodyForFts(sessionId) {
|
|
572
|
+
const db = this.requireDb();
|
|
573
|
+
const stmt = db.prepare('SELECT body FROM sessions_fts WHERE id = ?');
|
|
574
|
+
const row = stmt.get(sessionId);
|
|
575
|
+
return row?.body ?? '';
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
/**
|
|
579
|
+
* Read-only view returned by `SqliteSessionStore.openReadOnly`. Holds
|
|
580
|
+
* a DatabaseSync handle opened with `readOnly: true`; no lockfile, no
|
|
581
|
+
* inserts. Exists so `pugi sessions --local` / `pugi resume --list` /
|
|
582
|
+
* `pugi sessions --search` / `pugi resume <id>` can read the store
|
|
583
|
+
* without polluting the session history with a stub row on every call.
|
|
584
|
+
*/
|
|
585
|
+
export class SqliteSessionStoreReadOnlyView {
|
|
586
|
+
db;
|
|
587
|
+
constructor(db) {
|
|
588
|
+
this.db = db;
|
|
589
|
+
}
|
|
590
|
+
async list(opts) {
|
|
591
|
+
const limit = clampLimit(opts?.limit ?? DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT);
|
|
592
|
+
const statusFilter = opts?.status ?? 'active+archived';
|
|
593
|
+
const cursor = opts?.cursor;
|
|
594
|
+
const where = [];
|
|
595
|
+
const params = [];
|
|
596
|
+
if (opts?.project) {
|
|
597
|
+
where.push('project_slug = ?');
|
|
598
|
+
params.push(opts.project);
|
|
599
|
+
}
|
|
600
|
+
if (statusFilter === 'all') {
|
|
601
|
+
// No status clause.
|
|
602
|
+
}
|
|
603
|
+
else if (statusFilter === 'active+archived') {
|
|
604
|
+
where.push(`status != 'aborted'`);
|
|
605
|
+
}
|
|
606
|
+
else {
|
|
607
|
+
where.push('status = ?');
|
|
608
|
+
params.push(statusFilter);
|
|
609
|
+
}
|
|
610
|
+
if (cursor) {
|
|
611
|
+
where.push('updated_at < (SELECT updated_at FROM sessions WHERE id = ?)');
|
|
612
|
+
params.push(cursor);
|
|
613
|
+
}
|
|
614
|
+
const whereClause = where.length > 0 ? `WHERE ${where.join(' AND ')}` : '';
|
|
615
|
+
const sql = `
|
|
616
|
+
SELECT id, created_at, updated_at, workspace_root, branch, project_slug,
|
|
617
|
+
title, turn_count, event_count, model, tenant_id, status
|
|
618
|
+
FROM sessions
|
|
619
|
+
${whereClause}
|
|
620
|
+
ORDER BY updated_at DESC
|
|
621
|
+
LIMIT ?
|
|
622
|
+
`;
|
|
623
|
+
const rows = this.db
|
|
624
|
+
.prepare(sql)
|
|
625
|
+
.all(...params, limit);
|
|
626
|
+
return rows.map(rawToSession);
|
|
627
|
+
}
|
|
628
|
+
async search(query, opts) {
|
|
629
|
+
const trimmed = query.trim();
|
|
630
|
+
if (trimmed.length === 0) {
|
|
631
|
+
throw new Error('SessionStore.search requires a non-empty query');
|
|
632
|
+
}
|
|
633
|
+
const limit = clampLimit(opts?.limit ?? DEFAULT_SEARCH_LIMIT, MAX_SEARCH_LIMIT);
|
|
634
|
+
const ftsQuery = sanitiseFtsQuery(trimmed);
|
|
635
|
+
const sql = `
|
|
636
|
+
SELECT s.id, s.created_at, s.updated_at, s.workspace_root, s.branch,
|
|
637
|
+
s.project_slug, s.title, s.turn_count, s.event_count, s.model,
|
|
638
|
+
s.tenant_id, s.status
|
|
639
|
+
FROM sessions_fts f
|
|
640
|
+
JOIN sessions s ON s.id = f.id
|
|
641
|
+
WHERE sessions_fts MATCH ?
|
|
642
|
+
ORDER BY s.updated_at DESC
|
|
643
|
+
LIMIT ?
|
|
644
|
+
`;
|
|
645
|
+
let rows;
|
|
646
|
+
try {
|
|
647
|
+
rows = this.db.prepare(sql).all(ftsQuery, limit);
|
|
648
|
+
}
|
|
649
|
+
catch (error) {
|
|
650
|
+
if (isSqliteError(error)) {
|
|
651
|
+
throw new FtsSyntaxError(ftsQuery, error);
|
|
652
|
+
}
|
|
653
|
+
throw error;
|
|
654
|
+
}
|
|
655
|
+
return rows.map(rawToSession);
|
|
656
|
+
}
|
|
657
|
+
async get(sessionId) {
|
|
658
|
+
const stmt = this.db.prepare(`
|
|
659
|
+
SELECT id, created_at, updated_at, workspace_root, branch, project_slug,
|
|
660
|
+
title, turn_count, event_count, model, tenant_id, status
|
|
661
|
+
FROM sessions
|
|
662
|
+
WHERE id = ?
|
|
663
|
+
`);
|
|
664
|
+
const row = stmt.get(sessionId);
|
|
665
|
+
return row ? rawToSession(row) : null;
|
|
666
|
+
}
|
|
667
|
+
async close() {
|
|
668
|
+
try {
|
|
669
|
+
this.db.close();
|
|
670
|
+
}
|
|
671
|
+
catch {
|
|
672
|
+
/* idempotent */
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
function rawToSession(raw) {
|
|
677
|
+
return {
|
|
678
|
+
id: raw.id,
|
|
679
|
+
createdAt: Number(raw.created_at),
|
|
680
|
+
updatedAt: Number(raw.updated_at),
|
|
681
|
+
workspaceRoot: raw.workspace_root,
|
|
682
|
+
branch: raw.branch,
|
|
683
|
+
projectSlug: raw.project_slug,
|
|
684
|
+
title: raw.title,
|
|
685
|
+
turnCount: Number(raw.turn_count),
|
|
686
|
+
eventCount: Number(raw.event_count),
|
|
687
|
+
model: raw.model,
|
|
688
|
+
tenantId: raw.tenant_id,
|
|
689
|
+
status: coerceStatus(raw.status),
|
|
690
|
+
};
|
|
691
|
+
}
|
|
692
|
+
function coerceStatus(raw) {
|
|
693
|
+
if (raw === 'active' || raw === 'archived' || raw === 'aborted') {
|
|
694
|
+
return raw;
|
|
695
|
+
}
|
|
696
|
+
// Defence-in-depth — unknown status means a future schema wrote it.
|
|
697
|
+
// Treat as active so the row still appears in the picker.
|
|
698
|
+
return 'active';
|
|
699
|
+
}
|
|
700
|
+
function camelToSnake(input) {
|
|
701
|
+
return input.replace(/[A-Z]/g, (m) => `_${m.toLowerCase()}`);
|
|
702
|
+
}
|
|
703
|
+
function clampLimit(raw, max) {
|
|
704
|
+
if (!Number.isFinite(raw) || raw <= 0)
|
|
705
|
+
return 1;
|
|
706
|
+
if (raw > max)
|
|
707
|
+
return max;
|
|
708
|
+
return Math.floor(raw);
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Sanitise a project slug for filesystem use. Same rules as
|
|
712
|
+
* `slugForCwd` in history.ts (lowercase alphanum + hyphen, collapse
|
|
713
|
+
* runs of hyphens, empty -> `default`). Re-implemented inline to
|
|
714
|
+
* avoid a circular import with the repl module.
|
|
715
|
+
*/
|
|
716
|
+
function sanitiseSlugForFs(raw) {
|
|
717
|
+
const cleaned = raw.replace(/[^a-z0-9-]/gi, '-').toLowerCase().replace(/-+/g, '-');
|
|
718
|
+
const trimmed = cleaned.replace(/^-+|-+$/g, '');
|
|
719
|
+
return trimmed.length === 0 ? 'default' : trimmed;
|
|
720
|
+
}
|
|
721
|
+
/**
|
|
722
|
+
* Pull a human-readable text body out of an event payload. We support
|
|
723
|
+
* three shapes the producer commonly emits:
|
|
724
|
+
*
|
|
725
|
+
* - `{ text: string }` — explicit text body.
|
|
726
|
+
* - `{ brief: string }` — REPL `dispatch` brief.
|
|
727
|
+
* - `string` — payload is the body itself.
|
|
728
|
+
*
|
|
729
|
+
* Anything else returns the empty string so a typo at the call site
|
|
730
|
+
* silently degrades to "no FTS body" rather than crashing the writer.
|
|
731
|
+
*/
|
|
732
|
+
function extractEventText(event) {
|
|
733
|
+
const payload = event.payload;
|
|
734
|
+
if (typeof payload === 'string')
|
|
735
|
+
return payload;
|
|
736
|
+
if (typeof payload === 'object' && payload !== null) {
|
|
737
|
+
const candidate = payload.text
|
|
738
|
+
?? payload.brief;
|
|
739
|
+
if (typeof candidate === 'string')
|
|
740
|
+
return candidate;
|
|
741
|
+
}
|
|
742
|
+
return '';
|
|
743
|
+
}
|
|
744
|
+
/**
|
|
745
|
+
* Sanitise a plain-text query for FTS5 MATCH binding. Always wraps the
|
|
746
|
+
* input in double-quoted phrase syntax and doubles any embedded `"` so
|
|
747
|
+
* a stray quote in the operator's input cannot break out of the phrase
|
|
748
|
+
* and trip FTS5's parser.
|
|
749
|
+
*
|
|
750
|
+
* Trade-off: power-user FTS5 syntax (`body:cabinet OR title:sidebar`)
|
|
751
|
+
* is no longer reachable — every input is treated as a literal token
|
|
752
|
+
* or phrase. The spec accepts this in exchange for "never crashes on a
|
|
753
|
+
* stray punctuation character". Hyphens, colons, asterisks, and
|
|
754
|
+
* parentheses all degrade to literal matches inside the quoted phrase.
|
|
755
|
+
*
|
|
756
|
+
* The complementary defence in `search()` wraps the prepare/all call in
|
|
757
|
+
* try/catch + rethrows as `FtsSyntaxError`. Belt + suspenders: even if
|
|
758
|
+
* a future input shape slips past this helper, the error message is
|
|
759
|
+
* still operator-readable instead of a stack trace.
|
|
760
|
+
*/
|
|
761
|
+
function sanitiseFtsQuery(query) {
|
|
762
|
+
return `"${query.replace(/"/g, '""')}"`;
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* SQLite errors land on the JS side with `error.code` strings like
|
|
766
|
+
* `'SQLITE_ERROR'`, `'SQLITE_CONSTRAINT_UNIQUE'`, etc. We treat any
|
|
767
|
+
* `SQLITE_*` code as recoverable for the FTS5 syntax wrap — operator
|
|
768
|
+
* input is the only realistic source of these errors during search.
|
|
769
|
+
*/
|
|
770
|
+
function isSqliteError(error) {
|
|
771
|
+
if (typeof error !== 'object' || error === null)
|
|
772
|
+
return false;
|
|
773
|
+
const code = error.code;
|
|
774
|
+
return typeof code === 'string' && code.startsWith('SQLITE_');
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* Thrown by `search()` when SQLite rejects an FTS5 query as malformed.
|
|
778
|
+
* The CLI dispatcher branches on `error.code === 'EFTS5_SYNTAX'` to
|
|
779
|
+
* surface a one-line operator-friendly message + exit 2.
|
|
780
|
+
*/
|
|
781
|
+
export class FtsSyntaxError extends Error {
|
|
782
|
+
code = 'EFTS5_SYNTAX';
|
|
783
|
+
query;
|
|
784
|
+
cause;
|
|
785
|
+
constructor(query, cause) {
|
|
786
|
+
super(`Invalid search query (FTS5 syntax error): ${query}`);
|
|
787
|
+
this.name = 'FtsSyntaxError';
|
|
788
|
+
this.query = query;
|
|
789
|
+
this.cause = cause;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
//# sourceMappingURL=session-store.js.map
|