dsh-context-mode 0.1.2 → 0.2.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/LICENSING.md +37 -0
- package/README.md +40 -14
- package/lib/types/cjk.d.ts +54 -0
- package/lib/types/cjk.d.ts.map +1 -0
- package/lib/types/cjk.js +64 -0
- package/lib/types/index.d.ts.map +1 -1
- package/lib/types/index.js +71 -22
- package/lib/types/output-containment.d.ts +35 -0
- package/lib/types/output-containment.d.ts.map +1 -0
- package/lib/types/output-containment.js +103 -0
- package/lib/types/routing.d.ts +3 -1
- package/lib/types/routing.d.ts.map +1 -1
- package/lib/types/routing.js +81 -6
- package/lib/types/session-memory.d.ts.map +1 -1
- package/lib/types/session-memory.js +14 -3
- package/package.json +9 -5
- package/skills/context-mode/SKILL.md +104 -11
- package/vendor/context-mode/LICENSE +94 -0
- package/vendor/context-mode/server.bundle.mjs +1126 -0
- package/vendor/context-mode/src/cli.ts +2040 -0
- package/vendor/context-mode/src/db-base.ts +617 -0
- package/vendor/context-mode/src/executor.ts +785 -0
- package/vendor/context-mode/src/exit-classify.ts +33 -0
- package/vendor/context-mode/src/fetch-cache.ts +15 -0
- package/vendor/context-mode/src/lifecycle.ts +305 -0
- package/vendor/context-mode/src/platform/client-map.ts +45 -0
- package/vendor/context-mode/src/platform/detect.ts +645 -0
- package/vendor/context-mode/src/platform/dsh.ts +206 -0
- package/vendor/context-mode/src/platform/types.ts +503 -0
- package/vendor/context-mode/src/runPool.ts +81 -0
- package/vendor/context-mode/src/runtime.ts +765 -0
- package/vendor/context-mode/src/search/auto-memory.ts +200 -0
- package/vendor/context-mode/src/search/ctx-search-schema.ts +143 -0
- package/vendor/context-mode/src/search/flood-guard.ts +111 -0
- package/vendor/context-mode/src/search/unified.ts +176 -0
- package/vendor/context-mode/src/security.ts +889 -0
- package/vendor/context-mode/src/server.ts +4991 -0
- package/vendor/context-mode/src/session/analytics.ts +3085 -0
- package/vendor/context-mode/src/session/db.ts +1726 -0
- package/vendor/context-mode/src/session/error-classifier.ts +392 -0
- package/vendor/context-mode/src/session/event-emit.ts +132 -0
- package/vendor/context-mode/src/session/extract.ts +2958 -0
- package/vendor/context-mode/src/session/index.ts +130 -0
- package/vendor/context-mode/src/session/model-prices.json +429 -0
- package/vendor/context-mode/src/session/persist-tool-calls.ts +128 -0
- package/vendor/context-mode/src/session/pricing.ts +191 -0
- package/vendor/context-mode/src/session/project-attribution.ts +309 -0
- package/vendor/context-mode/src/session/purge.ts +338 -0
- package/vendor/context-mode/src/session/retrieval-marker.ts +65 -0
- package/vendor/context-mode/src/session/snapshot.ts +577 -0
- package/vendor/context-mode/src/store-directory.ts +290 -0
- package/vendor/context-mode/src/store.ts +2071 -0
- package/vendor/context-mode/src/truncate.ts +154 -0
- package/vendor/context-mode/src/types.ts +147 -0
- package/vendor/context-mode/src/util/claude-config.ts +95 -0
- package/vendor/context-mode/src/util/hook-config.ts +78 -0
- package/vendor/context-mode/src/util/jsonc.ts +70 -0
- package/vendor/context-mode/src/util/plugin-cache-integrity.ts +167 -0
- package/vendor/context-mode/src/util/project-dir.ts +347 -0
- package/vendor/context-mode/src/util/sibling-mcp.ts +228 -0
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* purgeSession — deep module that wipes ALL session-related on-disk artifacts
|
|
3
|
+
* for a single project directory.
|
|
4
|
+
*
|
|
5
|
+
* Why a deep module instead of an inline handler:
|
|
6
|
+
* - The previous inline ctx_purge handler was 100+ lines split across three
|
|
7
|
+
* try/catch blocks. Only ONE of those blocks knew about the case-fold
|
|
8
|
+
* migration's dual-hash legacy filenames, so a partial upgrade could
|
|
9
|
+
* leak orphaned events.md / .cleanup files on macOS / Windows.
|
|
10
|
+
* - Centralizing the logic here means: one canonical sidecar list, one
|
|
11
|
+
* uniform dual-hash sweep, one place to add new file kinds.
|
|
12
|
+
*
|
|
13
|
+
* Worktree separation guarantee (carried over from the case-fold migration):
|
|
14
|
+
* Every path this module touches is derived deterministically from the input
|
|
15
|
+
* `projectDir`. There is NO `readdirSync` + glob-filter loop. Different
|
|
16
|
+
* worktrees → different physical paths → different canonical hashes →
|
|
17
|
+
* different file names → cannot collapse worktrees on disk.
|
|
18
|
+
*
|
|
19
|
+
* SQLite sidecar handling:
|
|
20
|
+
* Each `.db` file may be accompanied by `-wal` (write-ahead log) and `-shm`
|
|
21
|
+
* (shared memory index) sidecars. We unlink the triple unconditionally —
|
|
22
|
+
* missing sidecars are not an error. This matches the canonical SQLite
|
|
23
|
+
* sidecar naming used elsewhere (see refs/platforms/zed/crates/sqlez:
|
|
24
|
+
* `[main, "{main}-wal", "{main}-shm"]`).
|
|
25
|
+
*
|
|
26
|
+
* Cross-platform notes:
|
|
27
|
+
* - All paths are joined via `node:path.join` so Windows backslash
|
|
28
|
+
* separators and POSIX forward slashes both work.
|
|
29
|
+
* - On macOS / Windows (case-insensitive FS) we sweep BOTH the canonical
|
|
30
|
+
* (lowercased) and legacy (raw-cased) project-dir hash variants for the
|
|
31
|
+
* session-related kinds. On Linux the two hashes coincide, so the dual
|
|
32
|
+
* sweep collapses into a single unique-path pass.
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
import { existsSync, unlinkSync } from "node:fs";
|
|
36
|
+
import { join } from "node:path";
|
|
37
|
+
import { loadDatabase } from "../db-base.js";
|
|
38
|
+
import {
|
|
39
|
+
getWorktreeSuffix,
|
|
40
|
+
hashProjectDirCanonical,
|
|
41
|
+
hashProjectDirLegacy,
|
|
42
|
+
SessionDB,
|
|
43
|
+
} from "./db.js";
|
|
44
|
+
|
|
45
|
+
/** Canonical SQLite sidecar suffixes. The empty string is the main DB. */
|
|
46
|
+
const SQLITE_SIDECARS = ["", "-wal", "-shm"] as const;
|
|
47
|
+
|
|
48
|
+
export interface PurgeOpts {
|
|
49
|
+
/**
|
|
50
|
+
* Absolute path to the project root. Drives every other path the module
|
|
51
|
+
* touches via the project-dir hash. MUST be the same string the rest of
|
|
52
|
+
* the system uses (e.g. `getProjectDir()`); otherwise the wrong DB is
|
|
53
|
+
* targeted. Worktree separation is preserved — only files matching
|
|
54
|
+
* THIS projectDir's hash are unlinked.
|
|
55
|
+
*/
|
|
56
|
+
projectDir: string;
|
|
57
|
+
/**
|
|
58
|
+
* Adapter-specific session directory (e.g. `~/.claude/context-mode/sessions`).
|
|
59
|
+
* Holds: `<hash><suffix>.db`, `<hash><suffix>-events.md`,
|
|
60
|
+
* `<hash><suffix>.cleanup`.
|
|
61
|
+
*/
|
|
62
|
+
sessionsDir: string;
|
|
63
|
+
/**
|
|
64
|
+
* Absolute path to the per-project FTS5 knowledge-base DB
|
|
65
|
+
* (e.g. `~/.claude/context-mode/content/<hash>.db`). When omitted no
|
|
66
|
+
* FTS5 wipe runs. Caller is responsible for closing any open handle
|
|
67
|
+
* BEFORE invoking purgeSession (Windows file locks).
|
|
68
|
+
*
|
|
69
|
+
* Use `contentDir` instead for new code — it dual-sweeps the canonical
|
|
70
|
+
* AND legacy raw-casing variants, mirroring the session events pattern.
|
|
71
|
+
* `storePath` remains for callers that have already pre-resolved a single
|
|
72
|
+
* absolute path and only want to wipe that exact file.
|
|
73
|
+
*/
|
|
74
|
+
storePath?: string;
|
|
75
|
+
/**
|
|
76
|
+
* Per-platform FTS5 content directory (e.g.
|
|
77
|
+
* `~/.claude/context-mode/content`). When provided, purgeSession sweeps
|
|
78
|
+
* BOTH the canonical and legacy raw-casing hash variants of the FTS5
|
|
79
|
+
* store inside this directory plus their `-wal` / `-shm` sidecars. This
|
|
80
|
+
* is the recommended input — covers a partial upgrade where the user
|
|
81
|
+
* had been writing to a legacy raw-casing FTS5 file before the case-fold
|
|
82
|
+
* migration landed.
|
|
83
|
+
*
|
|
84
|
+
* Mutually-additive with `storePath`: if both are passed, both are swept
|
|
85
|
+
* (de-duped on path). Closing FTS5 handles before invoking is still the
|
|
86
|
+
* caller's responsibility.
|
|
87
|
+
*/
|
|
88
|
+
contentDir?: string;
|
|
89
|
+
/**
|
|
90
|
+
* Legacy shared content directory at `~/.context-mode/content`. When
|
|
91
|
+
* omitted, the legacy content sweep is skipped.
|
|
92
|
+
*/
|
|
93
|
+
legacyContentDir?: string;
|
|
94
|
+
/**
|
|
95
|
+
* Hash used to locate the legacy shared content DB. Required when
|
|
96
|
+
* `legacyContentDir` is provided. Computed by the caller because the
|
|
97
|
+
* legacy code-path uses a different hash function than the canonical
|
|
98
|
+
* session DB hash.
|
|
99
|
+
*/
|
|
100
|
+
contentHash?: string;
|
|
101
|
+
/**
|
|
102
|
+
* Issue #520 — scoped purge.
|
|
103
|
+
*
|
|
104
|
+
* - `"project"` (default when omitted for back-compat callers that
|
|
105
|
+
* only pass `confirm:true` at the MCP layer): wipe ALL session
|
|
106
|
+
* artifacts for `projectDir`. This is the legacy destructive
|
|
107
|
+
* behavior preserved verbatim.
|
|
108
|
+
* - `"session"`: wipe ONLY the rows for `sessionId` inside the
|
|
109
|
+
* project's SessionDB plus FTS5 chunks tagged with that
|
|
110
|
+
* `session_id`. Project-wide files (events.md, content store
|
|
111
|
+
* file, stats file) are left intact. Requires `sessionId`.
|
|
112
|
+
*
|
|
113
|
+
* When `scope` is omitted but `sessionId` is set, behavior implies
|
|
114
|
+
* `scope:"session"` (a sessionId-only call cannot mean "wipe the
|
|
115
|
+
* whole project"). When neither is set, behavior implies
|
|
116
|
+
* `scope:"project"` for back-compat with the original handler.
|
|
117
|
+
*/
|
|
118
|
+
scope?: "session" | "project";
|
|
119
|
+
/**
|
|
120
|
+
* Session identifier whose rows should be wiped from the project's
|
|
121
|
+
* SessionDB and tagged FTS5 chunks. Only consulted when `scope ===
|
|
122
|
+
* "session"`. The `session_events`, `session_meta`, and
|
|
123
|
+
* `session_resume` rows for this id are removed; rows for other
|
|
124
|
+
* sessions in the same DB are preserved. Match SessionDB.deleteSession
|
|
125
|
+
* semantics (see src/session/db.ts).
|
|
126
|
+
*/
|
|
127
|
+
sessionId?: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface PurgeResult {
|
|
131
|
+
/**
|
|
132
|
+
* Human-readable labels rendered to the user by the ctx_purge handler.
|
|
133
|
+
* MUST stay backward-compatible with the existing UI strings:
|
|
134
|
+
* "knowledge base (FTS5)", "session events DB", "session events markdown".
|
|
135
|
+
* Each label appears at most once, and only when at least one matching
|
|
136
|
+
* file was actually unlinked.
|
|
137
|
+
*/
|
|
138
|
+
deleted: string[];
|
|
139
|
+
/**
|
|
140
|
+
* Every full path that was successfully `unlink`ed. Surfaced for tests
|
|
141
|
+
* and for diagnostic logging — NEVER shown to end users (the labels
|
|
142
|
+
* above carry the human story).
|
|
143
|
+
*/
|
|
144
|
+
wipedPaths: string[];
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Try to unlink one path; report success without throwing on ENOENT etc. */
|
|
148
|
+
function tryUnlink(p: string, wipedPaths: string[]): boolean {
|
|
149
|
+
try {
|
|
150
|
+
unlinkSync(p);
|
|
151
|
+
wipedPaths.push(p);
|
|
152
|
+
return true;
|
|
153
|
+
} catch {
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Unlink a SQLite db at `path` plus its `-wal` / `-shm` sidecars.
|
|
160
|
+
* Returns true when the MAIN db file (not a sidecar) was removed.
|
|
161
|
+
*/
|
|
162
|
+
function tryUnlinkSqliteTriple(path: string, wipedPaths: string[]): boolean {
|
|
163
|
+
let mainRemoved = false;
|
|
164
|
+
for (const suffix of SQLITE_SIDECARS) {
|
|
165
|
+
const removed = tryUnlink(`${path}${suffix}`, wipedPaths);
|
|
166
|
+
if (removed && suffix === "") mainRemoved = true;
|
|
167
|
+
}
|
|
168
|
+
return mainRemoved;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Wipe every session-related on-disk artifact for `projectDir`.
|
|
173
|
+
*
|
|
174
|
+
* This function never throws on missing files (a fresh install is a no-op).
|
|
175
|
+
* It throws only when given an invalid argument (e.g. `legacyContentDir`
|
|
176
|
+
* without `contentHash`), which is a programmer bug not a runtime concern.
|
|
177
|
+
*/
|
|
178
|
+
export function purgeSession(opts: PurgeOpts): PurgeResult {
|
|
179
|
+
const { projectDir, sessionsDir, storePath, contentDir, legacyContentDir, contentHash, sessionId, scope } = opts;
|
|
180
|
+
const deleted: string[] = [];
|
|
181
|
+
const wipedPaths: string[] = [];
|
|
182
|
+
|
|
183
|
+
// Issue #520 — scope discipline.
|
|
184
|
+
// Resolve effective scope: explicit `scope` wins; otherwise infer
|
|
185
|
+
// "session" iff sessionId is given, else "project".
|
|
186
|
+
const effectiveScope: "session" | "project" =
|
|
187
|
+
scope ?? (sessionId ? "session" : "project");
|
|
188
|
+
|
|
189
|
+
if (effectiveScope === "session" && !sessionId) {
|
|
190
|
+
throw new TypeError(
|
|
191
|
+
"purgeSession: scope:'session' requires sessionId. " +
|
|
192
|
+
"Pass scope:'project' for the legacy whole-project wipe."
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ── Session-scoped path (issue #520). ─────────────────────────────────
|
|
197
|
+
// Wipe ONLY this sessionId's rows from the project's SessionDB. The DB
|
|
198
|
+
// file itself, the events.md sidecar, the FTS5 store, and the stats
|
|
199
|
+
// file are all left intact — those are project-scoped concerns. The
|
|
200
|
+
// label "session rows for <id>" appears once when at least one row was
|
|
201
|
+
// removed, mirroring the project-scoped UI contract.
|
|
202
|
+
if (effectiveScope === "session" && sessionId) {
|
|
203
|
+
const worktreeSuffix = getWorktreeSuffix(projectDir);
|
|
204
|
+
const canonicalHash = hashProjectDirCanonical(projectDir);
|
|
205
|
+
const legacyHash = hashProjectDirLegacy(projectDir);
|
|
206
|
+
const hashes = canonicalHash === legacyHash
|
|
207
|
+
? [canonicalHash]
|
|
208
|
+
: [canonicalHash, legacyHash];
|
|
209
|
+
let rowsRemoved = false;
|
|
210
|
+
for (const h of hashes) {
|
|
211
|
+
const dbPath = join(sessionsDir, `${h}${worktreeSuffix}.db`);
|
|
212
|
+
if (!existsSync(dbPath)) continue;
|
|
213
|
+
let db: SessionDB | null = null;
|
|
214
|
+
try {
|
|
215
|
+
db = new SessionDB({ dbPath });
|
|
216
|
+
const before = db.getEvents(sessionId).length;
|
|
217
|
+
db.deleteSession(sessionId);
|
|
218
|
+
if (before > 0) rowsRemoved = true;
|
|
219
|
+
} catch {
|
|
220
|
+
// Best-effort — corrupt DB is logged elsewhere; do not block purge.
|
|
221
|
+
} finally {
|
|
222
|
+
// close() releases the handle WITHOUT deleting the file —
|
|
223
|
+
// this is what makes the scoped wipe non-destructive at the
|
|
224
|
+
// file-system level. Using cleanup() here would erase the
|
|
225
|
+
// entire DB (main + WAL + SHM), defeating per-session scope.
|
|
226
|
+
try { db?.close(); } catch { /* best effort */ }
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (rowsRemoved) deleted.push(`session rows for ${sessionId}`);
|
|
230
|
+
|
|
231
|
+
// Per-session FTS5 chunk wipe. The chunks table has a `session_id
|
|
232
|
+
// UNINDEXED` column (src/store.ts schema). The public index() path
|
|
233
|
+
// currently inserts NULL — but a future per-session-tagged path
|
|
234
|
+
// (e.g. tool-call indexing keyed to a session) will populate it,
|
|
235
|
+
// and the SQL contract here keeps that future correct from day one.
|
|
236
|
+
// Today this is a safe no-op against existing data.
|
|
237
|
+
//
|
|
238
|
+
// Caller is responsible for closing any persistent ContentStore
|
|
239
|
+
// handle BEFORE invoking purgeSession (Windows file lock). The
|
|
240
|
+
// ctx_purge handler does this via _store?.cleanup() before delegating.
|
|
241
|
+
const ftsTargets: string[] = [];
|
|
242
|
+
if (storePath && existsSync(storePath)) ftsTargets.push(storePath);
|
|
243
|
+
if (contentDir) {
|
|
244
|
+
const canonicalH = hashProjectDirCanonical(projectDir);
|
|
245
|
+
const legacyH = hashProjectDirLegacy(projectDir);
|
|
246
|
+
const hh = canonicalH === legacyH ? [canonicalH] : [canonicalH, legacyH];
|
|
247
|
+
for (const h of hh) {
|
|
248
|
+
const p = join(contentDir, `${h}.db`);
|
|
249
|
+
if (existsSync(p) && !ftsTargets.includes(p)) ftsTargets.push(p);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
let chunksRemoved = false;
|
|
253
|
+
for (const path of ftsTargets) {
|
|
254
|
+
try {
|
|
255
|
+
const Database = loadDatabase();
|
|
256
|
+
const fts = new Database(path, { timeout: 30000 });
|
|
257
|
+
try {
|
|
258
|
+
const before = (fts.prepare(
|
|
259
|
+
"SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?"
|
|
260
|
+
).get(sessionId) as { c: number }).c;
|
|
261
|
+
fts.prepare("DELETE FROM chunks WHERE session_id = ?").run(sessionId);
|
|
262
|
+
fts.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(sessionId);
|
|
263
|
+
if (before > 0) chunksRemoved = true;
|
|
264
|
+
} finally {
|
|
265
|
+
try { fts.close(); } catch { /* best effort */ }
|
|
266
|
+
}
|
|
267
|
+
} catch {
|
|
268
|
+
// Best-effort — schema mismatch / corrupt DB / missing FTS5 must not
|
|
269
|
+
// block the per-session SessionDB wipe that already succeeded.
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
if (chunksRemoved) deleted.push(`FTS5 chunks for ${sessionId}`);
|
|
273
|
+
|
|
274
|
+
return { deleted, wipedPaths };
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// ── 1. Knowledge base FTS5 store (per-platform). ──────────────────────
|
|
278
|
+
// Two input modes:
|
|
279
|
+
// - `storePath`: single absolute path; pre-resolved by caller. Wipes
|
|
280
|
+
// exactly that file plus -wal / -shm sidecars. Back-compat path.
|
|
281
|
+
// - `contentDir`: directory; purgeSession derives BOTH canonical and
|
|
282
|
+
// legacy raw-casing variants of the FTS5 store filename (matches
|
|
283
|
+
// the case-fold migration pattern from `resolveContentStorePath`)
|
|
284
|
+
// and sweeps each with sidecars. Recommended for new callers.
|
|
285
|
+
// Both inputs may be supplied; paths are de-duped via the unlink-or-fail
|
|
286
|
+
// semantics of `tryUnlinkSqliteTriple`. The "knowledge base (FTS5)"
|
|
287
|
+
// label appears at most once.
|
|
288
|
+
let storeFound = false;
|
|
289
|
+
if (storePath && tryUnlinkSqliteTriple(storePath, wipedPaths)) storeFound = true;
|
|
290
|
+
if (contentDir) {
|
|
291
|
+
const canonicalHash = hashProjectDirCanonical(projectDir);
|
|
292
|
+
const legacyHash = hashProjectDirLegacy(projectDir);
|
|
293
|
+
const storeHashes = canonicalHash === legacyHash
|
|
294
|
+
? [canonicalHash]
|
|
295
|
+
: [canonicalHash, legacyHash];
|
|
296
|
+
for (const h of storeHashes) {
|
|
297
|
+
const path = join(contentDir, `${h}.db`);
|
|
298
|
+
if (tryUnlinkSqliteTriple(path, wipedPaths)) storeFound = true;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (storeFound) deleted.push("knowledge base (FTS5)");
|
|
302
|
+
|
|
303
|
+
// ── 2. Legacy shared content DB at ~/.context-mode/content/<hash>.db.
|
|
304
|
+
// Same reasoning as (1) — single hash, legacy code-path only.
|
|
305
|
+
if (legacyContentDir) {
|
|
306
|
+
if (!contentHash) {
|
|
307
|
+
throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");
|
|
308
|
+
}
|
|
309
|
+
const legacyPath = join(legacyContentDir, `${contentHash}.db`);
|
|
310
|
+
tryUnlinkSqliteTriple(legacyPath, wipedPaths);
|
|
311
|
+
// No user-facing label — this is a silent legacy cleanup.
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// ── 3. Session-events kinds at BOTH canonical AND legacy hashes. ─────
|
|
315
|
+
// This is the bug fix: the prior handler only dual-hashed the .db file
|
|
316
|
+
// (after migration commit a32cc29). events.md and .cleanup were left
|
|
317
|
+
// single-hash, so a casing-drift project on macOS/Windows could leak
|
|
318
|
+
// orphan files past a purge. We now sweep all three uniformly.
|
|
319
|
+
const worktreeSuffix = getWorktreeSuffix(projectDir);
|
|
320
|
+
const canonicalHash = hashProjectDirCanonical(projectDir);
|
|
321
|
+
const legacyHash = hashProjectDirLegacy(projectDir);
|
|
322
|
+
const hashes = canonicalHash === legacyHash
|
|
323
|
+
? [canonicalHash]
|
|
324
|
+
: [canonicalHash, legacyHash];
|
|
325
|
+
|
|
326
|
+
let sessDbFound = false;
|
|
327
|
+
let eventsFound = false;
|
|
328
|
+
for (const h of hashes) {
|
|
329
|
+
const base = join(sessionsDir, `${h}${worktreeSuffix}`);
|
|
330
|
+
if (tryUnlinkSqliteTriple(`${base}.db`, wipedPaths)) sessDbFound = true;
|
|
331
|
+
if (tryUnlink(`${base}-events.md`, wipedPaths)) eventsFound = true;
|
|
332
|
+
tryUnlink(`${base}.cleanup`, wipedPaths); // no user-facing label
|
|
333
|
+
}
|
|
334
|
+
if (sessDbFound) deleted.push("session events DB");
|
|
335
|
+
if (eventsFound) deleted.push("session events markdown");
|
|
336
|
+
|
|
337
|
+
return { deleted, wipedPaths };
|
|
338
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Server→hook bridge for the retrieval ("With context-mode") byte count.
|
|
3
|
+
*
|
|
4
|
+
* WHY THIS EXISTS — context-mode's OWN MCP retrieval tools (ctx_search /
|
|
5
|
+
* ctx_fetch_and_index) never fire a PostToolUse hook for the plugin's own
|
|
6
|
+
* server, so the hook-side `extractMcpToolCall` path can never observe them
|
|
7
|
+
* (verified empirically: 0 `mcp_tool_call` events locally, bytes_retrieved
|
|
8
|
+
* 0/124454 in production D1). The MCP server, however, measures each
|
|
9
|
+
* retrieval response's byte length directly.
|
|
10
|
+
*
|
|
11
|
+
* The server appends that count to a tmp marker keyed by the session DB
|
|
12
|
+
* *basename* — the one identifier the server process and the hook process
|
|
13
|
+
* both resolve reliably (CLAUDE_SESSION_ID is not guaranteed in the server
|
|
14
|
+
* env; the per-project session DB path is). The next PostToolUse fire — which
|
|
15
|
+
* DOES run for ordinary tools (Bash/Read/Edit) — consumes the marker and
|
|
16
|
+
* emits a forwardable event carrying `bytes_retrieved`. Mirrors the existing
|
|
17
|
+
* redirect / latency / rejected marker handshake in posttooluse.mjs.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { appendFileSync, readFileSync, rmSync } from "node:fs";
|
|
21
|
+
import { tmpdir } from "node:os";
|
|
22
|
+
import { basename, join } from "node:path";
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Tmp marker path for a session DB. Keyed by basename so the server (which
|
|
26
|
+
* holds the DB path via getSessionDbPath) and the hook (getSessionDBPath)
|
|
27
|
+
* derive the SAME file. Session DB filenames embed the worktree hash
|
|
28
|
+
* (`<hash>__<suffix>.db`), so basename collisions across projects are
|
|
29
|
+
* negligible.
|
|
30
|
+
*/
|
|
31
|
+
export function retrievalMarkerPath(sessionDbPath: string, tmpDir: string = tmpdir()): string {
|
|
32
|
+
return join(tmpDir, `context-mode-retrieval-${basename(sessionDbPath)}.txt`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Record one retrieval's response byte count. Positive-only (a 0-byte or
|
|
37
|
+
* failed retrieval is not a context cost). Append-only so several retrievals
|
|
38
|
+
* between two hook fires accumulate. Best-effort — never throws into the
|
|
39
|
+
* MCP response path.
|
|
40
|
+
*/
|
|
41
|
+
export function appendRetrievalBytes(sessionDbPath: string, bytes: number, tmpDir?: string): void {
|
|
42
|
+
if (!Number.isFinite(bytes) || bytes <= 0) return;
|
|
43
|
+
try {
|
|
44
|
+
appendFileSync(retrievalMarkerPath(sessionDbPath, tmpDir), `${Math.floor(bytes)}\n`);
|
|
45
|
+
} catch { /* best-effort — never block the MCP response */ }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Sum every recorded retrieval and delete the marker (consume-once) so the
|
|
50
|
+
* next PostToolUse fire cannot re-forward the same bytes. Returns 0 when no
|
|
51
|
+
* marker exists (phantom-event guard).
|
|
52
|
+
*/
|
|
53
|
+
export function consumeRetrievalBytes(sessionDbPath: string, tmpDir?: string): number {
|
|
54
|
+
const path = retrievalMarkerPath(sessionDbPath, tmpDir);
|
|
55
|
+
let total = 0;
|
|
56
|
+
try {
|
|
57
|
+
const raw = readFileSync(path, "utf8");
|
|
58
|
+
for (const line of raw.split("\n")) {
|
|
59
|
+
const n = Number.parseInt(line, 10);
|
|
60
|
+
if (Number.isFinite(n) && n > 0) total += n;
|
|
61
|
+
}
|
|
62
|
+
rmSync(path, { force: true });
|
|
63
|
+
} catch { /* no marker — phantom-event guard */ }
|
|
64
|
+
return total;
|
|
65
|
+
}
|