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.
Files changed (60) hide show
  1. package/LICENSING.md +37 -0
  2. package/README.md +40 -14
  3. package/lib/types/cjk.d.ts +54 -0
  4. package/lib/types/cjk.d.ts.map +1 -0
  5. package/lib/types/cjk.js +64 -0
  6. package/lib/types/index.d.ts.map +1 -1
  7. package/lib/types/index.js +71 -22
  8. package/lib/types/output-containment.d.ts +35 -0
  9. package/lib/types/output-containment.d.ts.map +1 -0
  10. package/lib/types/output-containment.js +103 -0
  11. package/lib/types/routing.d.ts +3 -1
  12. package/lib/types/routing.d.ts.map +1 -1
  13. package/lib/types/routing.js +81 -6
  14. package/lib/types/session-memory.d.ts.map +1 -1
  15. package/lib/types/session-memory.js +14 -3
  16. package/package.json +9 -5
  17. package/skills/context-mode/SKILL.md +104 -11
  18. package/vendor/context-mode/LICENSE +94 -0
  19. package/vendor/context-mode/server.bundle.mjs +1126 -0
  20. package/vendor/context-mode/src/cli.ts +2040 -0
  21. package/vendor/context-mode/src/db-base.ts +617 -0
  22. package/vendor/context-mode/src/executor.ts +785 -0
  23. package/vendor/context-mode/src/exit-classify.ts +33 -0
  24. package/vendor/context-mode/src/fetch-cache.ts +15 -0
  25. package/vendor/context-mode/src/lifecycle.ts +305 -0
  26. package/vendor/context-mode/src/platform/client-map.ts +45 -0
  27. package/vendor/context-mode/src/platform/detect.ts +645 -0
  28. package/vendor/context-mode/src/platform/dsh.ts +206 -0
  29. package/vendor/context-mode/src/platform/types.ts +503 -0
  30. package/vendor/context-mode/src/runPool.ts +81 -0
  31. package/vendor/context-mode/src/runtime.ts +765 -0
  32. package/vendor/context-mode/src/search/auto-memory.ts +200 -0
  33. package/vendor/context-mode/src/search/ctx-search-schema.ts +143 -0
  34. package/vendor/context-mode/src/search/flood-guard.ts +111 -0
  35. package/vendor/context-mode/src/search/unified.ts +176 -0
  36. package/vendor/context-mode/src/security.ts +889 -0
  37. package/vendor/context-mode/src/server.ts +4991 -0
  38. package/vendor/context-mode/src/session/analytics.ts +3085 -0
  39. package/vendor/context-mode/src/session/db.ts +1726 -0
  40. package/vendor/context-mode/src/session/error-classifier.ts +392 -0
  41. package/vendor/context-mode/src/session/event-emit.ts +132 -0
  42. package/vendor/context-mode/src/session/extract.ts +2958 -0
  43. package/vendor/context-mode/src/session/index.ts +130 -0
  44. package/vendor/context-mode/src/session/model-prices.json +429 -0
  45. package/vendor/context-mode/src/session/persist-tool-calls.ts +128 -0
  46. package/vendor/context-mode/src/session/pricing.ts +191 -0
  47. package/vendor/context-mode/src/session/project-attribution.ts +309 -0
  48. package/vendor/context-mode/src/session/purge.ts +338 -0
  49. package/vendor/context-mode/src/session/retrieval-marker.ts +65 -0
  50. package/vendor/context-mode/src/session/snapshot.ts +577 -0
  51. package/vendor/context-mode/src/store-directory.ts +290 -0
  52. package/vendor/context-mode/src/store.ts +2071 -0
  53. package/vendor/context-mode/src/truncate.ts +154 -0
  54. package/vendor/context-mode/src/types.ts +147 -0
  55. package/vendor/context-mode/src/util/claude-config.ts +95 -0
  56. package/vendor/context-mode/src/util/hook-config.ts +78 -0
  57. package/vendor/context-mode/src/util/jsonc.ts +70 -0
  58. package/vendor/context-mode/src/util/plugin-cache-integrity.ts +167 -0
  59. package/vendor/context-mode/src/util/project-dir.ts +347 -0
  60. package/vendor/context-mode/src/util/sibling-mcp.ts +228 -0
@@ -0,0 +1,167 @@
1
+ /**
2
+ * TypeScript surface for the start.mjs plugin-cache integrity helper.
3
+ *
4
+ * The actual logic lives in `scripts/plugin-cache-integrity.mjs` (raw
5
+ * `.mjs` so start.mjs can import it without a TS toolchain at boot —
6
+ * #550 fail-fast happens BEFORE any bundle is loaded). This module is
7
+ * the bridge that lets TS consumers (claude-code adapter's
8
+ * getHealthChecks for Algo-D5, the cli doctor surface) call the same
9
+ * function without duplicating the implementation.
10
+ *
11
+ * Single source of truth: scripts/plugin-cache-integrity.mjs. Boot
12
+ * fail-fast (Algo-D4) and doctor diagnostic (Algo-D5) agree
13
+ * byte-for-byte because they call the same exported function.
14
+ *
15
+ * Top-level dynamic import is used (not a static `import` from `.mjs`)
16
+ * because the project is ESM and `import` of a sibling `.mjs` from a
17
+ * `.ts` file relies on the bundler / loader resolving `.mjs`
18
+ * extensions, which esbuild can do but tsc-only typecheck cannot. The
19
+ * dynamic import is resolved by the runtime (Node ESM) regardless of
20
+ * how the consumer was bundled. Errors are caught and surfaced as a
21
+ * FAIL detail — the helper is required to ship in the npm tarball
22
+ * (package.json files[]); a missing helper means the install is
23
+ * fundamentally broken.
24
+ */
25
+
26
+ import { existsSync } from "node:fs";
27
+ import { join } from "node:path";
28
+
29
+ interface IntegrityResult {
30
+ readonly ok: boolean;
31
+ readonly missing: readonly string[];
32
+ }
33
+
34
+ interface IntegrityModule {
35
+ assertPluginCacheIntegrity(args: { pluginRoot: string }): IntegrityResult;
36
+ formatPartialInstallReport(args: {
37
+ pluginRoot: string;
38
+ missing: readonly string[];
39
+ }): string;
40
+ }
41
+
42
+ let cached: IntegrityModule | null = null;
43
+ let cachedError: string | null = null;
44
+
45
+ async function loadHelper(): Promise<IntegrityModule | null> {
46
+ if (cached) return cached;
47
+ if (cachedError) return null;
48
+ try {
49
+ // Resolve relative to this compiled file. After tsc emits to
50
+ // build/util/plugin-cache-integrity.js, the helper sits at
51
+ // ../../scripts/plugin-cache-integrity.mjs. After esbuild bundles
52
+ // src/cli.ts to cli.bundle.mjs at the repo root, the same relative
53
+ // path resolves to ./scripts/plugin-cache-integrity.mjs. Both
54
+ // shapes are walked here.
55
+ const candidates = [
56
+ new URL("../../scripts/plugin-cache-integrity.mjs", import.meta.url),
57
+ new URL("./scripts/plugin-cache-integrity.mjs", import.meta.url),
58
+ ];
59
+ let lastErr: unknown = null;
60
+ for (const url of candidates) {
61
+ try {
62
+ const mod = (await import(url.href)) as IntegrityModule;
63
+ if (typeof mod?.assertPluginCacheIntegrity === "function") {
64
+ cached = mod;
65
+ return cached;
66
+ }
67
+ } catch (err) {
68
+ lastErr = err;
69
+ }
70
+ }
71
+ cachedError =
72
+ lastErr instanceof Error ? lastErr.message : String(lastErr ?? "not found");
73
+ return null;
74
+ } catch (err) {
75
+ cachedError = err instanceof Error ? err.message : String(err);
76
+ return null;
77
+ }
78
+ }
79
+
80
+ // Eagerly start the load on module init so the first synchronous
81
+ // check() call can hit the cache. The promise is unawaited
82
+ // intentionally — by the time any HealthCheck.check() runs (doctor
83
+ // command, well after MCP server boot), the import has resolved.
84
+ void loadHelper();
85
+
86
+ /**
87
+ * Files `start.mjs` needs to launch the MCP server, checked dependency-free
88
+ * (fs only) so this works even when the integrity helper
89
+ * (`scripts/plugin-cache-integrity.mjs`) is itself missing — a missing helper
90
+ * is itself a partial-install symptom, and the operator most needs to know
91
+ * whether the launch entrypoint survived.
92
+ *
93
+ * - `start.mjs` is the plugin `command` target (`.claude-plugin/plugin.json`)
94
+ * and has NO fallback: if absent, `node ${CLAUDE_PLUGIN_ROOT}/start.mjs`
95
+ * fails immediately and the MCP server never starts.
96
+ * - The server is loaded by start.mjs from `server.bundle.mjs`, falling back
97
+ * to `build/server.js`; it is only "missing" when BOTH are absent.
98
+ */
99
+ export function findMissingLaunchFiles(pluginRoot: string): string[] {
100
+ const missing: string[] = [];
101
+ if (!existsSync(join(pluginRoot, "start.mjs"))) {
102
+ missing.push("start.mjs");
103
+ }
104
+ if (
105
+ !existsSync(join(pluginRoot, "server.bundle.mjs")) &&
106
+ !existsSync(join(pluginRoot, "build", "server.js"))
107
+ ) {
108
+ missing.push("server.bundle.mjs (or build/server.js)");
109
+ }
110
+ return missing;
111
+ }
112
+
113
+ /**
114
+ * Run the integrity check synchronously. If the helper module is
115
+ * still loading (not yet cached) returns a FAIL with detail
116
+ * "integrity helper not yet loaded" — caller should retry once the
117
+ * doctor command's IO is complete. In practice the doctor is invoked
118
+ * many MS after module load so this fallback is defensive only.
119
+ */
120
+ export function checkPluginCacheIntegritySync(
121
+ pluginRoot: string,
122
+ ): { status: "OK" | "FAIL"; detail: string } {
123
+ if (cached) {
124
+ const result = cached.assertPluginCacheIntegrity({ pluginRoot });
125
+ if (result.ok) {
126
+ return {
127
+ status: "OK",
128
+ detail: `${pluginRoot} (all required runtime siblings present)`,
129
+ };
130
+ }
131
+ return {
132
+ status: "FAIL",
133
+ detail: `missing: ${result.missing.join(", ")}`,
134
+ };
135
+ }
136
+ if (cachedError) {
137
+ // The integrity helper (scripts/plugin-cache-integrity.mjs) ships in
138
+ // package.json files[]; if it failed to load, the install is already
139
+ // partial. Don't stop at "helper unavailable" — directly surface whether
140
+ // the launch entrypoint survived, because a missing start.mjs / server
141
+ // bundle is exactly what stops the MCP server from starting (and is what
142
+ // an interrupted /ctx-upgrade swap leaves behind).
143
+ const launchMissing = findMissingLaunchFiles(pluginRoot);
144
+ if (launchMissing.length > 0) {
145
+ return {
146
+ status: "FAIL",
147
+ detail:
148
+ `partial install — critical launch files missing: ${launchMissing.join(", ")} ` +
149
+ `(integrity helper also missing: ${cachedError}); the MCP server cannot start. ` +
150
+ `Reinstall: npm install -g context-mode@latest`,
151
+ };
152
+ }
153
+ return {
154
+ status: "FAIL",
155
+ detail: `integrity helper unavailable: ${cachedError}`,
156
+ };
157
+ }
158
+ return {
159
+ status: "FAIL",
160
+ detail: "integrity helper not yet loaded",
161
+ };
162
+ }
163
+
164
+ /** Force-await the helper load. Tests use this to deflake the eager fire-and-forget. */
165
+ export async function ensurePluginCacheIntegrityLoaded(): Promise<void> {
166
+ await loadHelper();
167
+ }
@@ -0,0 +1,347 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+
5
+ import type { PlatformId } from "../platform/types.js";
6
+ import { workspaceEnvVarsFor } from "../platform/detect.js";
7
+
8
+ /**
9
+ * Universal escape hatch. NEVER appears in any platform's foreignWorkspaceEnv()
10
+ * (because it isn't registered in PLATFORM_ENV_VARS), so it survives strict
11
+ * mode and bridge env scrubs. Documented as the cross-strict user override
12
+ * for every adapter (set in `~/.<host>/mcp.json` env when nothing else works).
13
+ */
14
+ const UNIVERSAL_WORKSPACE_ENV = ["CONTEXT_MODE_PROJECT_DIR"] as const;
15
+
16
+ /**
17
+ * Frozen legacy candidate list — preserves bit-for-bit behavior of every
18
+ * non-strict caller (`start.mjs` and any caller that doesn't pass
19
+ * `strictPlatform`). Order is locked for semver compatibility.
20
+ *
21
+ * If a new adapter is added, DO NOT add its workspace var here — register it
22
+ * in `PLATFORM_ENV_VARS` and let strict callers pick it up via
23
+ * `workspaceEnvVarsFor(platform)`. Strict mode is the default forward path.
24
+ */
25
+ const LEGACY_NON_STRICT_CANDIDATES: readonly string[] = [
26
+ "CLAUDE_PROJECT_DIR",
27
+ "GEMINI_PROJECT_DIR",
28
+ "VSCODE_CWD",
29
+ "OPENCODE_PROJECT_DIR",
30
+ "PI_PROJECT_DIR",
31
+ "IDEA_INITIAL_DIRECTORY",
32
+ "CURSOR_CWD",
33
+ "CONTEXT_MODE_PROJECT_DIR",
34
+ ];
35
+
36
+ /**
37
+ * Project-dir resolution helpers — shared between `start.mjs` (the MCP entry
38
+ * point) and `src/server.ts getProjectDir()` (the consumer).
39
+ *
40
+ * Background: when Claude Code runs `/ctx-upgrade`, it kills + respawns the
41
+ * MCP server. The respawn happens with `cwd` set to the plugin install
42
+ * directory (`~/.claude/plugins/cache/context-mode/context-mode/<version>/`).
43
+ * The legacy `start.mjs` then set `CLAUDE_PROJECT_DIR = originalCwd`, which
44
+ * poisoned every downstream `ctx_stats` / SessionDB / hash computation —
45
+ * sessions silently re-rooted under the plugin install path.
46
+ *
47
+ * Defense-in-depth fix (v1.0.113):
48
+ * - `start.mjs` calls `isPluginInstallPath(originalCwd)` and skips the env
49
+ * auto-set when true (no poisoning at the source).
50
+ * - `getProjectDir()` calls `resolveProjectDir(...)` which rejects plugin-
51
+ * pathed env vars and the plugin cwd, preferring `process.env.PWD`
52
+ * (shell-set, survives `process.chdir`) before falling back.
53
+ */
54
+
55
+ /**
56
+ * Detect whether a path lives inside an agent plugin install tree —
57
+ * specifically `<home>/.claude/plugins/cache/<plugin>/<plugin>/<version>/`,
58
+ * `<home>/.codex/plugins/cache/<plugin>/<plugin>/<version>/`, or the
59
+ * marketplace mirror under `<home>/.{claude,codex}/plugins/marketplaces/...`.
60
+ *
61
+ * Cross-OS: matches both POSIX (`/`) and Windows (`\`) path separators.
62
+ * Independent of `home` location — we only care about the agent plugin
63
+ * suffix pattern.
64
+ */
65
+ export function isPluginInstallPath(p: string): boolean {
66
+ if (!p) return false;
67
+ return /[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(p);
68
+ }
69
+
70
+ /**
71
+ * Read the per-session project dir from Claude Code's transcript files.
72
+ *
73
+ * Claude Code writes session transcripts under
74
+ * `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl`. Each line is a JSON
75
+ * event; an early line (typically line 2) carries a `cwd` field with the
76
+ * literal project directory the session is running against. The encoded dir
77
+ * name itself is lossy (`/` and `.` both become `-`), so we read the JSONL.
78
+ *
79
+ * This is the strongest available signal when Claude Code does NOT propagate
80
+ * `CLAUDE_PROJECT_DIR` to the spawned MCP env (the common case when Claude
81
+ * Code is launched from the desktop app rather than `cd <project> && claude`).
82
+ *
83
+ * Returns `undefined` when no transcript exists, the projects dir is empty,
84
+ * or no transcript carries a `cwd` field — caller falls through.
85
+ *
86
+ * Multi-window safety: the most-recently-modified jsonl wins. When the user
87
+ * actively talks to one Claude Code window, that window's transcript is the
88
+ * one being written to RIGHT NOW, so its mtime is freshest. Other windows'
89
+ * transcripts have older mtimes and are correctly ignored.
90
+ */
91
+ export function resolveProjectDirFromTranscript(opts: {
92
+ projectsRoot: string;
93
+ /**
94
+ * Optional freshness guard. Claude Code updates the active transcript while
95
+ * the session is being used; stale transcripts from previous days must not
96
+ * become a global project-dir signal for other hosts that merely have
97
+ * ~/.claude on disk.
98
+ */
99
+ maxAgeMs?: number;
100
+ /** Test seam for maxAgeMs. Defaults to Date.now(). */
101
+ nowMs?: number;
102
+ }): string | undefined {
103
+ if (!fs.existsSync(opts.projectsRoot)) return undefined;
104
+
105
+ let bestPath: string | undefined;
106
+ let bestMtime = 0;
107
+ try {
108
+ for (const dir of fs.readdirSync(opts.projectsRoot)) {
109
+ const dirPath = path.join(opts.projectsRoot, dir);
110
+ let stat;
111
+ try { stat = fs.statSync(dirPath); } catch { continue; }
112
+ if (!stat.isDirectory()) continue;
113
+ let files;
114
+ try { files = fs.readdirSync(dirPath); } catch { continue; }
115
+ for (const f of files) {
116
+ if (!f.endsWith(".jsonl")) continue;
117
+ const fp = path.join(dirPath, f);
118
+ try {
119
+ const m = fs.statSync(fp).mtimeMs;
120
+ if (m > bestMtime) { bestMtime = m; bestPath = fp; }
121
+ } catch { /* skip */ }
122
+ }
123
+ }
124
+ } catch { return undefined; }
125
+
126
+ if (!bestPath) return undefined;
127
+ if (typeof opts.maxAgeMs === "number") {
128
+ const nowMs = opts.nowMs ?? Date.now();
129
+ if (nowMs - bestMtime > opts.maxAgeMs) return undefined;
130
+ }
131
+
132
+ // Read first ~10 lines until we find a cwd field. The jsonl is
133
+ // append-only and can be huge (60+ MB on long sessions) — never load it
134
+ // into memory; stream a small head buffer.
135
+ try {
136
+ const fd = fs.openSync(bestPath, "r");
137
+ try {
138
+ const buf = Buffer.alloc(8192);
139
+ const bytes = fs.readSync(fd, buf, 0, buf.length, 0);
140
+ const text = buf.subarray(0, bytes).toString("utf-8");
141
+ for (const line of text.split("\n").slice(0, 10)) {
142
+ if (!line.trim()) continue;
143
+ try {
144
+ const obj = JSON.parse(line) as { cwd?: unknown };
145
+ if (typeof obj.cwd === "string" && obj.cwd.length > 0) return obj.cwd;
146
+ } catch { /* skip malformed line */ }
147
+ }
148
+ } finally {
149
+ fs.closeSync(fd);
150
+ }
151
+ } catch { /* file vanished mid-read */ }
152
+
153
+ return undefined;
154
+ }
155
+
156
+ /**
157
+ * Issue #45 / c4529042182 — recover the project-cwd from a Codex CLI
158
+ * session log when the spawned MCP child inherits a non-project cwd
159
+ * (e.g. $HOME when Codex was launched from anywhere outside the project).
160
+ *
161
+ * Codex writes its session transcripts to either
162
+ * `${CODEX_HOME ?? ~/.codex}/sessions/<uuid>.jsonl` (CLI) or a dated desktop
163
+ * layout such as
164
+ * `${CODEX_HOME ?? ~/.codex}/sessions/YYYY/MM/DD/rollout-*.jsonl`.
165
+ * The cwd appears on `meta.cwd` for the CLI shape and on
166
+ * `payload.cwd` in `type: "session_meta"` records for Codex Desktop. Codex
167
+ * publishes NO workspace env var to its child MCP processes — so unlike
168
+ * Claude/Pi/Cursor, we have no env signal at all. The session log is the
169
+ * strongest available signal.
170
+ *
171
+ * Mirror of `resolveProjectDirFromTranscript` for Claude Code; differences:
172
+ * • Sessions may live flat or in a dated hierarchy (no per-project encoded
173
+ * subdir like Claude's `~/.claude/projects/<encoded>/`).
174
+ * • The cwd is nested on `meta.cwd` or `payload.cwd`, not top-level `cwd`.
175
+ *
176
+ * Returns `null` when:
177
+ * • `codexHome` or its `sessions/` subdir does not exist.
178
+ * • No `.jsonl` files exist or none has a parseable cwd string.
179
+ * • The newest log is older than `transcriptMaxAgeMs` (multi-window guard).
180
+ * • The resolved cwd points at a plugin install path (poisoned).
181
+ */
182
+ export function resolveCodexSessionCwd(opts?: {
183
+ /** Defaults to `process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex")`. */
184
+ codexHome?: string;
185
+ /**
186
+ * Optional freshness guard — Codex appends to the active log while the
187
+ * session is running, so a stale log from days ago must not become a
188
+ * global project-dir signal.
189
+ */
190
+ transcriptMaxAgeMs?: number;
191
+ /** Test seam for transcriptMaxAgeMs. Defaults to Date.now(). */
192
+ now?: number;
193
+ }): string | null {
194
+ const codexHome =
195
+ opts?.codexHome ?? process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex");
196
+ const sessionsDir = path.join(codexHome, "sessions");
197
+ if (!fs.existsSync(sessionsDir)) return null;
198
+
199
+ const MAX_SCAN_DEPTH = 4; // sessions/YYYY/MM/DD/<file>.jsonl plus one spare.
200
+ const MAX_SCAN_ENTRIES = 10_000;
201
+ let visitedEntries = 0;
202
+ let bestPath: string | undefined;
203
+ let bestMtime = 0;
204
+ const visit = (dir: string, depth: number) => {
205
+ if (visitedEntries >= MAX_SCAN_ENTRIES) return;
206
+ let entries: string[];
207
+ try { entries = fs.readdirSync(dir); } catch { return; }
208
+ entries.sort().reverse();
209
+ for (const entry of entries) {
210
+ if (visitedEntries >= MAX_SCAN_ENTRIES) return;
211
+ visitedEntries++;
212
+ const fp = path.join(dir, entry);
213
+ let stat;
214
+ try { stat = fs.statSync(fp); } catch { continue; }
215
+ if (stat.isDirectory()) {
216
+ if (depth < MAX_SCAN_DEPTH) visit(fp, depth + 1);
217
+ continue;
218
+ }
219
+ if (!stat.isFile() || !entry.endsWith(".jsonl")) continue;
220
+ const m = stat.mtimeMs;
221
+ if (m > bestMtime) { bestMtime = m; bestPath = fp; }
222
+ }
223
+ };
224
+ try {
225
+ visit(sessionsDir, 0);
226
+ } catch { return null; }
227
+
228
+ if (!bestPath) return null;
229
+ if (typeof opts?.transcriptMaxAgeMs === "number") {
230
+ const nowMs = opts.now ?? Date.now();
231
+ if (nowMs - bestMtime > opts.transcriptMaxAgeMs) return null;
232
+ }
233
+
234
+ // Read a bounded head chunk. Codex Desktop's first session_meta line can be
235
+ // larger than Claude/Codex CLI metadata because it includes dynamic tool and
236
+ // instruction fields, but the full transcript can still be tens of MB.
237
+ try {
238
+ const fd = fs.openSync(bestPath, "r");
239
+ try {
240
+ const buf = Buffer.alloc(1024 * 1024);
241
+ const bytes = fs.readSync(fd, buf, 0, buf.length, 0);
242
+ const text = buf.subarray(0, bytes).toString("utf-8");
243
+ for (const line of text.split("\n").slice(0, 10)) {
244
+ if (!line.trim()) continue;
245
+ try {
246
+ const obj = JSON.parse(line) as {
247
+ type?: unknown;
248
+ meta?: { cwd?: unknown };
249
+ payload?: { cwd?: unknown };
250
+ };
251
+ const cwd = obj?.meta?.cwd ??
252
+ (obj?.type === "session_meta" ? obj?.payload?.cwd : undefined);
253
+ if (typeof cwd !== "string" || cwd.length === 0) continue;
254
+ if (isPluginInstallPath(cwd)) return null;
255
+ return cwd;
256
+ } catch { return null; /* malformed session metadata line */ }
257
+ }
258
+ } finally {
259
+ fs.closeSync(fd);
260
+ }
261
+ } catch { return null; /* file vanished mid-read */ }
262
+ return null;
263
+ }
264
+
265
+ /**
266
+ * Pure project-dir resolver. Mirror of the env-var chain inside
267
+ * `src/server.ts getProjectDir()`, but takes its inputs explicitly so the
268
+ * resolver can be exercised under test without process-level mutation.
269
+ *
270
+ * Resolution order:
271
+ * 1. Adapter-priority env vars (CLAUDE / GEMINI / VSCODE / OPENCODE / PI /
272
+ * IDEA / CONTEXT_MODE) — first non-empty AND non-plugin-path wins.
273
+ * 2. Claude Code transcript heuristic — read `cwd` from the most-recently-
274
+ * modified `~/.claude/projects/<encoded>/<session>.jsonl`. This is the
275
+ * most reliable signal when Claude Code launched MCP from a non-project
276
+ * cwd (desktop-app launch, `/ctx-upgrade` respawn, etc.).
277
+ * 3. `process.env.PWD` — shell-set, NOT updated by `process.chdir()`, so
278
+ * it survives the `start.mjs` chdir into the plugin dir. Skipped if
279
+ * it too points at a plugin install path.
280
+ * 4. `cwd` — last resort. Returned even if it is a plugin path; the
281
+ * caller is responsible for rendering a graceful "no project context"
282
+ * message rather than panicking. Keeping the function total preserves
283
+ * operation of project-independent tools (sandbox execute, fetch).
284
+ */
285
+ export function resolveProjectDir(opts: {
286
+ env: Record<string, string | undefined>;
287
+ cwd: string;
288
+ pwd: string | undefined;
289
+ /** Optional override; production code passes `~/.claude/projects`. */
290
+ transcriptsRoot?: string;
291
+ /** Optional freshness guard for Claude Code transcript project recovery. */
292
+ transcriptMaxAgeMs?: number;
293
+ /** Test seam for transcriptMaxAgeMs. Defaults to Date.now(). */
294
+ nowMs?: number;
295
+ /**
296
+ * Issue #545 — opt-in tightening. When set, the candidate list is built
297
+ * algorithmically from `workspaceEnvVarsFor(strictPlatform)` plus the
298
+ * universal escape hatch. Foreign workspace vars (e.g. CLAUDE_PROJECT_DIR
299
+ * leaked into Pi's MCP child env) cannot win, regardless of cascade order.
300
+ *
301
+ * When `undefined`, the legacy literal candidate order is used (semver lock
302
+ * for `start.mjs` and any non-strict consumer).
303
+ */
304
+ strictPlatform?: PlatformId;
305
+ /**
306
+ * Issue #45 — override `${CODEX_HOME ?? ~/.codex}` for tests. When
307
+ * `strictPlatform === "codex"` and the env cascade yields nothing, the
308
+ * resolver reads `meta.cwd` from the newest session.jsonl under
309
+ * `${codexHome}/sessions/`.
310
+ */
311
+ codexHome?: string;
312
+ }): string {
313
+ const {
314
+ env, cwd, pwd, transcriptsRoot, transcriptMaxAgeMs, nowMs, strictPlatform, codexHome,
315
+ } = opts;
316
+ // Build candidate list. Strict path: own workspace vars + universal escape
317
+ // hatch — NO foreign workspace vars, in any order, can win. Non-strict
318
+ // path: frozen legacy literal order for backwards compatibility.
319
+ const candidateVars: readonly string[] = strictPlatform
320
+ ? [...workspaceEnvVarsFor(strictPlatform), ...UNIVERSAL_WORKSPACE_ENV]
321
+ : LEGACY_NON_STRICT_CANDIDATES;
322
+ for (const name of candidateVars) {
323
+ const v = env[name];
324
+ if (v && !isPluginInstallPath(v)) return v;
325
+ }
326
+ if (transcriptsRoot) {
327
+ const fromTranscript = resolveProjectDirFromTranscript({
328
+ projectsRoot: transcriptsRoot,
329
+ maxAgeMs: transcriptMaxAgeMs,
330
+ nowMs,
331
+ });
332
+ if (fromTranscript && !isPluginInstallPath(fromTranscript)) return fromTranscript;
333
+ }
334
+ // Issue #45 — Codex has no workspace env var, so when running under
335
+ // strictPlatform="codex" we fall back to the session-log heuristic
336
+ // between env and PWD. Non-codex platforms skip this branch entirely.
337
+ if (strictPlatform === "codex") {
338
+ const fromCodex = resolveCodexSessionCwd({
339
+ codexHome,
340
+ transcriptMaxAgeMs,
341
+ now: nowMs,
342
+ });
343
+ if (fromCodex) return fromCodex;
344
+ }
345
+ if (pwd && !isPluginInstallPath(pwd)) return pwd;
346
+ return cwd;
347
+ }