context-mode 1.0.149 → 1.0.150

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.
@@ -1,65 +0,0 @@
1
- /**
2
- * db-lock — Per-DB lockfile primitive for single-writer enforcement (#560).
3
- *
4
- * Issue #560: multiple context-mode MCP servers writing the same on-disk
5
- * SQLite content store unbounded the WAL — readers held shared locks
6
- * indefinitely so `wal_checkpoint(TRUNCATE)` never fired, and the only
7
- * existing truncation path is `closeDB`'s checkpoint on graceful exit
8
- * (which #559's zombie servers never reach). Result: 238MB+ WAL files
9
- * and ctx_search hangs.
10
- *
11
- * This module provides a tiny atomic-write primitive sitting in front of
12
- * `new Database(...)`. The first opener writes its PID into
13
- * `<dbPath>.lock` via O_EXCL (`flag: 'wx'`). Subsequent openers either:
14
- *
15
- * - find the lockfile + see the PID is alive → throw
16
- * DatabaseLockedError with the reporter's verbatim message;
17
- * - find the lockfile + see the PID is dead → claim it, with a re-read
18
- * check to resolve a same-instant race between two stale-claimers.
19
- *
20
- * The lockfile is the PRIMARY single-writer defense. The SQLiteBase ctor
21
- * also applies `locking_mode = EXCLUSIVE` as a SECONDARY defense
22
- * (belt-and-braces) — the lockfile owns the user-facing UX, EXCLUSIVE
23
- * catches the narrow race window between the lockfile check and the
24
- * actual `Database(...)` open.
25
- *
26
- * Per-process tmp DBs (those under `os.tmpdir()`) skip the lockfile
27
- * entirely — those are the existing `defaultDBPath()` shape and embed
28
- * `process.pid` already, so cross-instance contention is impossible.
29
- *
30
- * `isProcessAlive` is COPIED from `store.ts:187` — not imported — to
31
- * keep `db-base.ts` (which imports this module) free of any dependency
32
- * on `store.ts` (which itself imports from `db-base.ts`). See
33
- * PR-559-560-FIX-DESIGN.md regression risks #4.
34
- */
35
- /** User-facing failure used by SQLiteBase to surface the contention. */
36
- export declare class DatabaseLockedError extends Error {
37
- readonly pid: number;
38
- readonly dbPath: string;
39
- constructor(pid: number, dbPath: string);
40
- }
41
- export interface AcquireOptions {
42
- dbPath: string;
43
- }
44
- export interface AcquireResult {
45
- /** True when the lockfile was skipped because dbPath is under tmpdir. */
46
- skipped: boolean;
47
- }
48
- /**
49
- * Atomically claim the lockfile for `dbPath`. Throws `DatabaseLockedError`
50
- * if another live process holds it. Silently claims stale lockfiles whose
51
- * owning PID is dead.
52
- */
53
- export declare function acquireDbLock(opts: AcquireOptions): AcquireResult;
54
- export interface ReleaseOptions {
55
- dbPath: string;
56
- }
57
- /**
58
- * Drop the lockfile for `dbPath`. Swallows all errors so callers can
59
- * always invoke this in a finally / cleanup path without try/catch —
60
- * mirrors the shape of `db-base.ts closeDB`.
61
- *
62
- * Skipped (no-op) when `dbPath` is under tmpdir — symmetric with
63
- * `acquireDbLock`'s skip-gate.
64
- */
65
- export declare function releaseDbLock(opts: ReleaseOptions): void;
@@ -1,166 +0,0 @@
1
- /**
2
- * db-lock — Per-DB lockfile primitive for single-writer enforcement (#560).
3
- *
4
- * Issue #560: multiple context-mode MCP servers writing the same on-disk
5
- * SQLite content store unbounded the WAL — readers held shared locks
6
- * indefinitely so `wal_checkpoint(TRUNCATE)` never fired, and the only
7
- * existing truncation path is `closeDB`'s checkpoint on graceful exit
8
- * (which #559's zombie servers never reach). Result: 238MB+ WAL files
9
- * and ctx_search hangs.
10
- *
11
- * This module provides a tiny atomic-write primitive sitting in front of
12
- * `new Database(...)`. The first opener writes its PID into
13
- * `<dbPath>.lock` via O_EXCL (`flag: 'wx'`). Subsequent openers either:
14
- *
15
- * - find the lockfile + see the PID is alive → throw
16
- * DatabaseLockedError with the reporter's verbatim message;
17
- * - find the lockfile + see the PID is dead → claim it, with a re-read
18
- * check to resolve a same-instant race between two stale-claimers.
19
- *
20
- * The lockfile is the PRIMARY single-writer defense. The SQLiteBase ctor
21
- * also applies `locking_mode = EXCLUSIVE` as a SECONDARY defense
22
- * (belt-and-braces) — the lockfile owns the user-facing UX, EXCLUSIVE
23
- * catches the narrow race window between the lockfile check and the
24
- * actual `Database(...)` open.
25
- *
26
- * Per-process tmp DBs (those under `os.tmpdir()`) skip the lockfile
27
- * entirely — those are the existing `defaultDBPath()` shape and embed
28
- * `process.pid` already, so cross-instance contention is impossible.
29
- *
30
- * `isProcessAlive` is COPIED from `store.ts:187` — not imported — to
31
- * keep `db-base.ts` (which imports this module) free of any dependency
32
- * on `store.ts` (which itself imports from `db-base.ts`). See
33
- * PR-559-560-FIX-DESIGN.md regression risks #4.
34
- */
35
- import { writeFileSync, readFileSync, unlinkSync } from "node:fs";
36
- import { tmpdir } from "node:os";
37
- /** User-facing failure used by SQLiteBase to surface the contention. */
38
- export class DatabaseLockedError extends Error {
39
- pid;
40
- dbPath;
41
- constructor(pid, dbPath) {
42
- super(`Another context-mode server is already running (PID: ${pid}). ` +
43
- `Stop it before starting a new instance.`);
44
- this.name = "DatabaseLockedError";
45
- this.pid = pid;
46
- this.dbPath = dbPath;
47
- }
48
- }
49
- /**
50
- * Liveness probe — a 6-line copy of `store.ts:187 isProcessAlive`.
51
- * Sends signal 0 (no-op kill) which only verifies that the kernel
52
- * recognizes the PID + that the caller has permission to signal it.
53
- *
54
- * Copied (not imported) so this module stays leaf-level and `db-base.ts`
55
- * does not pick up a transitive dependency on `store.ts` — `store.ts`
56
- * already imports from `db-base.ts`, so the reverse would create a
57
- * circular dep that breaks under bun:sqlite's lazy load path.
58
- */
59
- function isProcessAlive(pid) {
60
- try {
61
- process.kill(pid, 0);
62
- return true;
63
- }
64
- catch {
65
- return false;
66
- }
67
- }
68
- function lockPathFor(dbPath) {
69
- return `${dbPath}.lock`;
70
- }
71
- /**
72
- * tmpdir skip-gate — per-process DBs (e.g. defaultDBPath() output) embed
73
- * `process.pid` so cross-instance contention is impossible by
74
- * construction. We never want to install a lockfile on the test runner's
75
- * tmp scratch path either.
76
- */
77
- function isUnderTmpdir(dbPath) {
78
- // Trailing-slash normalize — tmpdir() may or may not include it on the
79
- // current platform, and dbPath may be exactly tmpdir() when callers
80
- // join() with no separator (rare but cheap to guard).
81
- const tmp = tmpdir();
82
- return dbPath === tmp || dbPath.startsWith(tmp + "/") || dbPath.startsWith(tmp + "\\");
83
- }
84
- /**
85
- * Atomically claim the lockfile for `dbPath`. Throws `DatabaseLockedError`
86
- * if another live process holds it. Silently claims stale lockfiles whose
87
- * owning PID is dead.
88
- */
89
- export function acquireDbLock(opts) {
90
- const { dbPath } = opts;
91
- if (isUnderTmpdir(dbPath))
92
- return { skipped: true };
93
- const lockPath = lockPathFor(dbPath);
94
- const ownPid = String(process.pid);
95
- // Fast path: O_EXCL atomic create — succeeds iff the lockfile did not
96
- // exist. This is the single race-free moment that grants ownership.
97
- try {
98
- writeFileSync(lockPath, ownPid, { flag: "wx" });
99
- return { skipped: false };
100
- }
101
- catch (err) {
102
- const code = err?.code;
103
- if (code !== "EEXIST")
104
- throw err;
105
- // Fall through to liveness check.
106
- }
107
- // Slow path: lockfile exists. Read the PID, probe liveness.
108
- let existingPidStr;
109
- try {
110
- existingPidStr = readFileSync(lockPath, "utf-8").trim();
111
- }
112
- catch {
113
- // Lockfile vanished between EEXIST and read — race won by another
114
- // claimer that already finished cleanup. Retry once via the fast
115
- // path; if even that fails, surface as locked (best-effort).
116
- try {
117
- writeFileSync(lockPath, ownPid, { flag: "wx" });
118
- return { skipped: false };
119
- }
120
- catch {
121
- throw new DatabaseLockedError(0, dbPath);
122
- }
123
- }
124
- const existingPid = Number.parseInt(existingPidStr, 10);
125
- if (Number.isFinite(existingPid) && existingPid > 0 && isProcessAlive(existingPid)) {
126
- throw new DatabaseLockedError(existingPid, dbPath);
127
- }
128
- // Stale lockfile — owning PID is dead (or unparseable). Claim it.
129
- // We do NOT use { flag: 'wx' } here because we deliberately want to
130
- // overwrite the dead-PID record. Then re-read to confirm we won the
131
- // race against any other process also seeing the same stale lock.
132
- writeFileSync(lockPath, ownPid, { flag: "w" });
133
- let writtenPid;
134
- try {
135
- writtenPid = Number.parseInt(readFileSync(lockPath, "utf-8").trim(), 10);
136
- }
137
- catch {
138
- // Vanished again — extremely unlikely. Surface as locked rather than
139
- // proceeding with no guarantee.
140
- throw new DatabaseLockedError(0, dbPath);
141
- }
142
- if (writtenPid !== process.pid) {
143
- // Lost the stale-claim race to another concurrent claimer.
144
- throw new DatabaseLockedError(writtenPid, dbPath);
145
- }
146
- return { skipped: false };
147
- }
148
- /**
149
- * Drop the lockfile for `dbPath`. Swallows all errors so callers can
150
- * always invoke this in a finally / cleanup path without try/catch —
151
- * mirrors the shape of `db-base.ts closeDB`.
152
- *
153
- * Skipped (no-op) when `dbPath` is under tmpdir — symmetric with
154
- * `acquireDbLock`'s skip-gate.
155
- */
156
- export function releaseDbLock(opts) {
157
- const { dbPath } = opts;
158
- if (isUnderTmpdir(dbPath))
159
- return;
160
- try {
161
- unlinkSync(lockPathFor(dbPath));
162
- }
163
- catch {
164
- // Already gone, permission denied, etc. — best-effort.
165
- }
166
- }