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,200 @@
1
+ /**
2
+ * Auto-memory search — searches CLAUDE.md / AGENTS.md / GEMINI.md / etc.
3
+ * and the platform's persistent memory directory for decisions,
4
+ * preferences, and context from prior sessions.
5
+ *
6
+ * Returns results in a format compatible with the unified search pipeline.
7
+ */
8
+
9
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
10
+ import { join, isAbsolute } from "node:path";
11
+ import { resolveClaudeConfigDir } from "../util/claude-config.js";
12
+ import { hashProjectDirCanonical } from "../session/db.js";
13
+
14
+ const DEBUG = process.env.DEBUG?.includes("context-mode");
15
+
16
+ export interface AutoMemoryResult {
17
+ title: string;
18
+ content: string;
19
+ source: string;
20
+ origin: "auto-memory";
21
+ timestamp?: string;
22
+ }
23
+
24
+ /**
25
+ * Minimal adapter contract used by searchAutoMemory.
26
+ * Avoids depending on the full HookAdapter type to keep this module standalone.
27
+ */
28
+ export interface AutoMemoryAdapter {
29
+ getConfigDir(): string;
30
+ getInstructionFiles(): string[];
31
+ /**
32
+ * `projectDir` is optional for backwards compatibility with legacy
33
+ * callers — when supplied, adapters MUST return a project-scoped path
34
+ * (see HookAdapter.getMemoryDir contract, issue #663).
35
+ */
36
+ getMemoryDir(projectDir?: string): string;
37
+ }
38
+
39
+ /**
40
+ * Search auto-memory files for content matching any of the given queries.
41
+ *
42
+ * When `adapter` is provided, the per-platform conventions are used:
43
+ * 1. Project-level: <projectDir>/<each instructionFile>
44
+ * 2. User-level: <configDir>/<each instructionFile>
45
+ * 3. Memory dir: <memoryDir>/*.md
46
+ *
47
+ * Without an adapter (legacy callers), defaults to Claude conventions
48
+ * (CLAUDE.md + ~/.claude/memory) for backwards compatibility.
49
+ *
50
+ * @param queries Array of search terms
51
+ * @param limit Max results to return
52
+ * @param projectDir Project directory path
53
+ * @param configDir Explicit config dir override (legacy callers)
54
+ * @param adapter Platform adapter — supplies instruction files + memory dir
55
+ * @returns Matching auto-memory results
56
+ */
57
+ export function searchAutoMemory(
58
+ queries: string[],
59
+ limit: number = 5,
60
+ projectDir?: string,
61
+ configDir?: string,
62
+ adapter?: AutoMemoryAdapter,
63
+ ): AutoMemoryResult[] {
64
+ const results: AutoMemoryResult[] = [];
65
+
66
+ // Resolve conventions — adapter wins over explicit configDir, which wins
67
+ // over the historical Claude defaults.
68
+ const instructionFiles = adapter?.getInstructionFiles() ?? ["CLAUDE.md"];
69
+ const adapterConfigDir = adapter?.getConfigDir();
70
+ // Issue #460 round-3: legacy fallback honors $CLAUDE_CONFIG_DIR via the
71
+ // canonical util so callers without an adapter still respect relocated
72
+ // CC config trees (and empty/whitespace env doesn't poison the path).
73
+ const adapterRelative = adapterConfigDir ? resolveAgainst(projectDir, adapterConfigDir) : null;
74
+ const effectiveConfigDir = adapterRelative ?? configDir ?? resolveClaudeConfigDir();
75
+ // Issue #663: scope memory dir by projectDir so parallel projects can't
76
+ // read each other's auto-memory. Adapter-aware path delegates the
77
+ // scoping to the adapter; legacy adapterless fallback applies the same
78
+ // hash directly so the contract holds at both call sites.
79
+ const adapterMemoryDir = adapter?.getMemoryDir(projectDir);
80
+ const fallbackMemoryBase = join(effectiveConfigDir, "memory");
81
+ const fallbackMemoryDir = projectDir
82
+ ? join(fallbackMemoryBase, hashProjectDirCanonical(projectDir))
83
+ : fallbackMemoryBase;
84
+ const memoryDir = adapterMemoryDir
85
+ ? resolveAgainst(projectDir, adapterMemoryDir)
86
+ : fallbackMemoryDir;
87
+
88
+ // Collect candidate files
89
+ const candidates: Array<{ path: string; label: string }> = [];
90
+
91
+ // 1. Project-level instruction files
92
+ if (projectDir) {
93
+ for (const fileName of instructionFiles) {
94
+ const p = join(projectDir, fileName);
95
+ if (existsSync(p)) {
96
+ candidates.push({ path: p, label: `project/${fileName}` });
97
+ }
98
+ }
99
+ }
100
+
101
+ // 2. User-level instruction files (skip when configDir resolves to the
102
+ // project root — already covered by step 1, would emit dup labels).
103
+ if (effectiveConfigDir && effectiveConfigDir !== projectDir) {
104
+ for (const fileName of instructionFiles) {
105
+ const p = join(effectiveConfigDir, fileName);
106
+ if (existsSync(p)) {
107
+ candidates.push({ path: p, label: `user/${fileName}` });
108
+ }
109
+ }
110
+ }
111
+
112
+ // 3. Memory directory
113
+ if (memoryDir && existsSync(memoryDir)) {
114
+ try {
115
+ const files = readdirSync(memoryDir).filter(f => f.endsWith(".md"));
116
+ for (const file of files) {
117
+ candidates.push({
118
+ path: join(memoryDir, file),
119
+ label: `memory/${file}`,
120
+ });
121
+ }
122
+ } catch (e) {
123
+ if (DEBUG) process.stderr.write(`[ctx] auto-memory dir scan failed: ${e}\n`);
124
+ }
125
+ }
126
+
127
+ // Search each candidate file for matching queries
128
+ for (const candidate of candidates) {
129
+ if (results.length >= limit) break;
130
+
131
+ try {
132
+ // Single stat for both size guard and timestamp — saves one syscall
133
+ // per candidate file. Cross-platform: statSync semantics identical
134
+ // on macOS / Linux / Windows; size+mtime read in the same inode probe.
135
+ let stat;
136
+ try {
137
+ stat = statSync(candidate.path);
138
+ if (stat.size > 1_000_000) continue;
139
+ } catch { continue; }
140
+ const content = readFileSync(candidate.path, "utf-8");
141
+ const contentLower = content.toLowerCase();
142
+
143
+ for (const query of queries) {
144
+ if (results.length >= limit) break;
145
+
146
+ const queryLower = query.toLowerCase();
147
+ // Split query into terms, match if any term is found
148
+ const terms = queryLower.split(/\s+/).filter(t => t.length >= 3);
149
+ const matched = terms.some(term => {
150
+ try {
151
+ return new RegExp(`\\b${term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`, "i").test(content);
152
+ } catch {
153
+ return contentLower.includes(term); // fallback for invalid regex
154
+ }
155
+ });
156
+
157
+ if (matched) {
158
+ // Extract a relevant section around the first match
159
+ const firstTermIdx = terms.reduce((best, term) => {
160
+ const idx = contentLower.indexOf(term);
161
+ return idx >= 0 && (best < 0 || idx < best) ? idx : best;
162
+ }, -1);
163
+
164
+ let start = Math.max(0, firstTermIdx - 200);
165
+ let end = Math.min(content.length, firstTermIdx + 500);
166
+ const prevBlank = content.lastIndexOf("\n\n", start);
167
+ const nextBlank = content.indexOf("\n\n", end);
168
+ if (prevBlank >= 0) start = prevBlank + 2;
169
+ if (nextBlank >= 0) end = nextBlank;
170
+ const snippet = content.slice(start, end).trim();
171
+
172
+ results.push({
173
+ title: `[auto-memory] ${candidate.label}`,
174
+ content: snippet,
175
+ source: candidate.label,
176
+ origin: "auto-memory",
177
+ timestamp: stat.mtime.toISOString(),
178
+ });
179
+ break; // one result per file per query batch
180
+ }
181
+ }
182
+ } catch (e) {
183
+ if (DEBUG) process.stderr.write(`[ctx] auto-memory file read failed: ${e}\n`);
184
+ }
185
+ }
186
+
187
+ return results.slice(0, limit);
188
+ }
189
+
190
+ /**
191
+ * Resolve a possibly-relative path (e.g. ".github", "memory") against a
192
+ * project directory. Absolute paths and empty strings are returned as-is
193
+ * (empty == "use projectDir directly").
194
+ */
195
+ function resolveAgainst(projectDir: string | undefined, p: string): string {
196
+ if (!p) return projectDir ?? "";
197
+ if (isAbsolute(p)) return p;
198
+ if (!projectDir) return p;
199
+ return join(projectDir, p);
200
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * ctx_search input-schema builder and project-scope resolver.
3
+ *
4
+ * Issue #737 introduces the optional `project:` parameter used by callers
5
+ * running in the shared-DB mode (`CONTEXT_MODE_PROJECT_DIR` is set). The
6
+ * field is registered conditionally so that in the default per-project DB
7
+ * mode the LLM physically cannot pass it — the parameter does not exist
8
+ * in the tool schema at all, which is a stronger guarantee than runtime
9
+ * validation that depends on the model honouring documentation.
10
+ *
11
+ * The handler in `src/server.ts` consumes both exports:
12
+ * - {@link buildCtxSearchInputSchema} composes the Zod object used at
13
+ * `registerTool` time, spreading the conditional `project` field only
14
+ * when `isSharedMode` is true.
15
+ * - {@link resolveProjectScope} normalises the raw param into the
16
+ * three-state contract consumed by `searchAllSources`:
17
+ * undefined → no filter
18
+ * null → explicit cross-project recall (no filter)
19
+ * string → restrict to that project directory
20
+ */
21
+
22
+ import { z } from "zod";
23
+
24
+ /**
25
+ * Helper that mirrors the Zod coercer used elsewhere in the server for
26
+ * array-shaped tool args. Kept inline so this module has no runtime
27
+ * dependency on `server.ts` (which would create a cycle).
28
+ *
29
+ * Behaviour mirrors `coerceJsonArray` in `server.ts`:
30
+ * 1. Empty / whitespace string → returned untouched so Zod surfaces the
31
+ * "non-empty" error rather than masquerading as `[""]`.
32
+ * 2. Valid JSON array string → parsed and returned.
33
+ * 3. Any other plain string (a bare single query) → lifted to a
34
+ * single-element array. Fixes #627 for the native OpenCode plugin
35
+ * path where some providers deliver `queries: "search term"`.
36
+ */
37
+ function coerceJsonArray(val: unknown): unknown {
38
+ if (typeof val === "string") {
39
+ const trimmed = val.trim();
40
+ if (trimmed.length === 0) return val;
41
+ try {
42
+ const parsed = JSON.parse(val);
43
+ if (Array.isArray(parsed)) return parsed;
44
+ } catch {
45
+ /* fall through — not JSON, treat as bare-string lift */
46
+ }
47
+ return [val];
48
+ }
49
+ return val;
50
+ }
51
+
52
+ /**
53
+ * Build the Zod object passed to `server.registerTool("ctx_search", …)`.
54
+ *
55
+ * The base fields (`queries`, `limit`, `source`, `contentType`, `sort`)
56
+ * are always present and mirror today's contract exactly. The `project`
57
+ * field is only spread in when `isSharedMode` is true. When the host runs
58
+ * with the default per-project DB layout the schema does not expose the
59
+ * field at all, which keeps the tool surface honest about what is
60
+ * actionable in that mode.
61
+ */
62
+ export function buildCtxSearchInputSchema(isSharedMode: boolean) {
63
+ const projectField = isSharedMode
64
+ ? {
65
+ project: z
66
+ .string()
67
+ .optional()
68
+ .describe(
69
+ "Project scope. " +
70
+ "Default (omit): this session's project — auto-resolved from the host adapter. " +
71
+ "'global': span every project in the shared store (cross-project recall). " +
72
+ "<absolute-path>: scope to that specific project directory.",
73
+ ),
74
+ }
75
+ : ({} as Record<string, never>);
76
+
77
+ return z.object({
78
+ queries: z.preprocess(coerceJsonArray, z
79
+ .array(z.string())
80
+ .optional()
81
+ .describe("Array of search queries. Batch ALL questions in one call.")),
82
+ // limit: z.coerce.number() (not z.number()) — OpenCode's native
83
+ // plugin path delivers tool args straight from the LLM provider's
84
+ // tool-call JSON, where several providers stringify primitives
85
+ // (limit:"4" instead of limit:4). Since v1.0.139 / #621 we run
86
+ // inputSchema.parse() on that path, so a plain z.number() rejects
87
+ // "4" with "Expected number, received string". z.coerce mirrors what
88
+ // ctx_batch_execute / ctx_fetch_and_index / ctx_execute already do.
89
+ // Fixes #627.
90
+ limit: z
91
+ .coerce.number()
92
+ .optional()
93
+ .default(3)
94
+ .describe("Results per query (default: 3)"),
95
+ source: z
96
+ .string()
97
+ .optional()
98
+ .describe("Filter to a specific indexed source (partial match)."),
99
+ contentType: z
100
+ .enum(["code", "prose"])
101
+ .optional()
102
+ .describe("Filter results by content type: 'code' or 'prose'."),
103
+ sort: z
104
+ .enum(["relevance", "timeline"])
105
+ .optional()
106
+ .default("relevance")
107
+ .describe(
108
+ "Sort mode. 'relevance' (default): BM25 ranked, current session only. " +
109
+ "'timeline': chronological across current session, prior sessions, and auto-memory.",
110
+ ),
111
+ ...projectField,
112
+ });
113
+ }
114
+
115
+ /**
116
+ * Normalise the raw `project` value into the three-state contract consumed
117
+ * by {@link searchAllSources}.
118
+ *
119
+ * - shared mode OFF → `undefined` (param ignored)
120
+ * - shared mode ON, param `undefined` → current project (`getProjectDirFn()`)
121
+ * - shared mode ON, param `"global"` → `null` (no filter — cross-project)
122
+ * - shared mode ON, param `<string>` → that string verbatim
123
+ *
124
+ * The function is pure so it stays trivially testable without spinning up
125
+ * the MCP server.
126
+ */
127
+ export function resolveProjectScope(
128
+ raw: string | undefined,
129
+ isSharedMode: boolean,
130
+ getProjectDirFn: () => string,
131
+ ): string | null | undefined {
132
+ if (!isSharedMode) return undefined;
133
+ if (raw === undefined) return getProjectDirFn();
134
+ if (raw === "global") return null;
135
+ return raw;
136
+ }
137
+
138
+ /**
139
+ * Module-load snapshot of `CONTEXT_MODE_PROJECT_DIR`. Captured once so the
140
+ * tool schema registered with `server.registerTool` reflects the launch
141
+ * environment — the LLM-visible surface should never flip mid-session.
142
+ */
143
+ export const CTX_SEARCH_SHARED_MODE = !!process.env.CONTEXT_MODE_PROJECT_DIR;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * ctx_search flood-guard — per-agent-context progressive throttle.
3
+ *
4
+ * Background (#79 / #155 / #697): ctx_search carries a progressive throttle
5
+ * so a single actor cannot spam dozens of individual searches and flood the
6
+ * context window instead of batching via ctx_batch_execute. The original
7
+ * implementation kept ONE module-global counter on the MCP server process.
8
+ *
9
+ * Issue #769: a parallel multi-agent fan-out (Claude Code Task/Workflow)
10
+ * runs N subagents concurrently against the SAME per-session MCP server
11
+ * process. With a single global counter their independent calls are summed
12
+ * into one budget, so legitimate fan-out ("10 agents x 2 calls") trips the
13
+ * guard that was only ever meant to catch ONE actor spamming. The budget is
14
+ * tool-availability state that is logically per-agent-context, so the counter
15
+ * must be keyed per agent-context — NOT removed. Single-actor flood
16
+ * protection is preserved exactly; only the bucketing changes.
17
+ *
18
+ * This module is pure and transport-free so the policy is unit-testable
19
+ * without spinning up the MCP server. `src/server.ts` owns the singleton and
20
+ * supplies the per-call agent key (the session/agent id from
21
+ * currentAttribution()).
22
+ */
23
+
24
+ export interface FloodGuardConfig {
25
+ /** Rolling window length in ms. After this elapses a key's counter resets. */
26
+ windowMs: number;
27
+ /** After this many calls in the window, results taper to 1 per query. */
28
+ softCapAfter: number;
29
+ /** After this many calls in the window, the call is hard-blocked. */
30
+ blockAfter: number;
31
+ }
32
+
33
+ export interface FloodDecision {
34
+ /** This key's call count within the current rolling window (1-based). */
35
+ count: number;
36
+ /** Window start timestamp (ms) for this key — used for the "in Ns" message. */
37
+ windowStart: number;
38
+ /** True once count exceeds blockAfter — caller must refuse the search. */
39
+ blocked: boolean;
40
+ /** True once count exceeds softCapAfter — caller trims to 1 result/query. */
41
+ softCapped: boolean;
42
+ }
43
+
44
+ interface Bucket {
45
+ count: number;
46
+ windowStart: number;
47
+ }
48
+
49
+ /**
50
+ * A rolling-window call counter bucketed per agent-context key. Each key gets
51
+ * an independent window + counter, so concurrent subagents do not consume one
52
+ * another's budget while a single greedy actor is still throttled and blocked
53
+ * exactly as before.
54
+ */
55
+ export class FloodGuard {
56
+ readonly #cfg: FloodGuardConfig;
57
+ readonly #buckets = new Map<string, Bucket>();
58
+ /**
59
+ * Hard ceiling on tracked keys — a defensive bound so a pathological host
60
+ * that mints unbounded distinct agent ids cannot grow the map without limit.
61
+ * When exceeded, the oldest-window bucket is evicted (its actor simply gets
62
+ * a fresh window on its next call — fail-open, never a false block).
63
+ */
64
+ readonly #maxKeys: number;
65
+
66
+ constructor(cfg: FloodGuardConfig, maxKeys = 4096) {
67
+ this.#cfg = cfg;
68
+ this.#maxKeys = Math.max(1, maxKeys);
69
+ }
70
+
71
+ /**
72
+ * Record one ctx_search call for `key` at time `now` (ms) and return the
73
+ * throttle decision. Pure aside from the internal per-key counter state.
74
+ */
75
+ record(key: string, now: number = Date.now()): FloodDecision {
76
+ let bucket = this.#buckets.get(key);
77
+
78
+ if (!bucket || now - bucket.windowStart > this.#cfg.windowMs) {
79
+ bucket = { count: 0, windowStart: now };
80
+ this.#buckets.set(key, bucket);
81
+ this.#evictIfNeeded();
82
+ }
83
+
84
+ bucket.count++;
85
+
86
+ return {
87
+ count: bucket.count,
88
+ windowStart: bucket.windowStart,
89
+ blocked: bucket.count > this.#cfg.blockAfter,
90
+ softCapped: bucket.count > this.#cfg.softCapAfter,
91
+ };
92
+ }
93
+
94
+ /** Test/diagnostics helper — number of distinct keys currently tracked. */
95
+ size(): number {
96
+ return this.#buckets.size;
97
+ }
98
+
99
+ #evictIfNeeded(): void {
100
+ if (this.#buckets.size <= this.#maxKeys) return;
101
+ let oldestKey: string | undefined;
102
+ let oldestStart = Infinity;
103
+ for (const [k, b] of this.#buckets) {
104
+ if (b.windowStart < oldestStart) {
105
+ oldestStart = b.windowStart;
106
+ oldestKey = k;
107
+ }
108
+ }
109
+ if (oldestKey !== undefined) this.#buckets.delete(oldestKey);
110
+ }
111
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * Unified multi-source search — merges ContentStore, SessionDB, and
3
+ * auto-memory results into a single ranked or chronological result set.
4
+ *
5
+ * Used by ctx_search when sort="timeline" to search across all sources,
6
+ * or sort="relevance" (default) for ContentStore-only BM25 search.
7
+ */
8
+
9
+ import type { ContentStore, SearchResult } from "../store.js";
10
+ import type { SessionDB, StoredEvent } from "../session/db.js";
11
+ import { searchAutoMemory, type AutoMemoryAdapter } from "./auto-memory.js";
12
+
13
+ const DEBUG = process.env.DEBUG?.includes("context-mode");
14
+
15
+ // ─────────────────────────────────────────────────────────
16
+ // Types
17
+ // ─────────────────────────────────────────────────────────
18
+
19
+ export interface UnifiedSearchResult {
20
+ title: string;
21
+ content: string;
22
+ source: string;
23
+ origin: "current-session" | "prior-session" | "auto-memory";
24
+ timestamp?: string;
25
+ rank?: number;
26
+ matchLayer?: string;
27
+ highlighted?: string;
28
+ contentType?: "code" | "prose";
29
+ }
30
+
31
+ export interface SearchAllSourcesOpts {
32
+ query: string;
33
+ limit: number;
34
+ store: ContentStore;
35
+ sort?: "relevance" | "timeline";
36
+ source?: string;
37
+ contentType?: "code" | "prose";
38
+ sessionDB?: SessionDB | null;
39
+ projectDir?: string;
40
+ configDir?: string;
41
+ /** Detected platform adapter — used for adapter-aware auto-memory. */
42
+ adapter?: AutoMemoryAdapter;
43
+ /**
44
+ * Per-project scope for the ContentStore filter (#737). Only honoured
45
+ * when a `sessionDB` is also supplied (the 2-step IN-clause needs the
46
+ * SessionDB to translate `project_dir` → list of session ids).
47
+ *
48
+ * - `undefined` — no project filter, today's behaviour.
49
+ * - `null` — cross-project recall in shared-DB mode (also no filter).
50
+ * - `string` — restrict ContentStore results to chunks attributed to
51
+ * session ids whose events match this `project_dir`,
52
+ * plus legacy `session_id=''` chunks (public surface).
53
+ */
54
+ projectScope?: string | null;
55
+ }
56
+
57
+ // ─────────────────────────────────────────────────────────
58
+ // Implementation
59
+ // ─────────────────────────────────────────────────────────
60
+
61
+ /**
62
+ * Search across all available sources.
63
+ *
64
+ * - sort="relevance" (default): BM25-ranked results from ContentStore only.
65
+ * - sort="timeline": chronological merge of ContentStore + SessionDB + auto-memory.
66
+ *
67
+ * Errors in any single source are caught and logged — partial results
68
+ * are always returned.
69
+ */
70
+ export function searchAllSources(opts: SearchAllSourcesOpts): UnifiedSearchResult[] {
71
+ const {
72
+ query,
73
+ limit,
74
+ store,
75
+ sort = "relevance",
76
+ source,
77
+ contentType,
78
+ sessionDB,
79
+ projectDir,
80
+ configDir,
81
+ adapter,
82
+ projectScope,
83
+ } = opts;
84
+
85
+ const results: UnifiedSearchResult[] = [];
86
+
87
+ // Capture session start time once — used as proxy for ContentStore items
88
+ // (we don't know exact indexing time, but all content is from current session)
89
+ const sessionStartTime = new Date().toISOString();
90
+
91
+ // ── Project scope (#737) ──
92
+ // Resolve the per-project session-id allow-set ONCE, before the
93
+ // ContentStore call. `projectScope === null` means cross-project recall —
94
+ // an explicit "no filter" choice surfaced by the ctx_search caller — and
95
+ // `undefined` falls back to today's unfiltered behaviour.
96
+ let sessionIdAllowSet: Set<string> | undefined;
97
+ if (typeof projectScope === "string" && sessionDB) {
98
+ try {
99
+ sessionIdAllowSet = new Set(sessionDB.getSessionIdsForProject(projectScope));
100
+ } catch (e) {
101
+ if (DEBUG) process.stderr.write(`[ctx] getSessionIdsForProject failed: ${e}\n`);
102
+ }
103
+ }
104
+
105
+ // ── Source 1: ContentStore (always, both modes) ──
106
+ try {
107
+ const storeResults = store.searchWithFallback(
108
+ query,
109
+ limit,
110
+ source,
111
+ contentType,
112
+ "like",
113
+ sessionIdAllowSet,
114
+ );
115
+ results.push(
116
+ ...storeResults.map((r: SearchResult) => ({
117
+ title: r.title,
118
+ content: r.content,
119
+ source: r.source,
120
+ origin: "current-session" as const,
121
+ timestamp: r.timestamp || sessionStartTime,
122
+ rank: r.rank,
123
+ matchLayer: r.matchLayer,
124
+ highlighted: r.highlighted,
125
+ contentType: r.contentType,
126
+ })),
127
+ );
128
+ } catch (e) {
129
+ if (DEBUG) process.stderr.write(`[ctx] ContentStore search failed: ${e}\n`);
130
+ }
131
+
132
+ // ── Sources 2+3: timeline mode only ──
133
+ if (sort === "timeline") {
134
+ // Source 2: SessionDB — prior session events
135
+ try {
136
+ if (sessionDB) {
137
+ const dbResults = sessionDB.searchEvents(query, limit, projectDir || "", source);
138
+ results.push(
139
+ ...dbResults.map((r: Pick<StoredEvent, "id" | "session_id" | "category" | "type" | "data" | "created_at">) => ({
140
+ title: `[${r.category}] ${r.type}`,
141
+ content: r.data,
142
+ source: "prior-session",
143
+ origin: "prior-session" as const,
144
+ timestamp: r.created_at,
145
+ })),
146
+ );
147
+ }
148
+ } catch (e) {
149
+ if (DEBUG) process.stderr.write(`[ctx] SessionDB search failed: ${e}\n`);
150
+ }
151
+
152
+ // Source 3: Auto-memory
153
+ try {
154
+ const memResults = searchAutoMemory([query], limit, projectDir, configDir, adapter);
155
+ results.push(...memResults);
156
+ } catch (e) {
157
+ if (DEBUG) process.stderr.write(`[ctx] auto-memory search failed: ${e}\n`);
158
+ }
159
+ }
160
+
161
+ // ── Normalize timestamps for consistent sorting ──
162
+ // SQLite datetime('now') → "YYYY-MM-DD HH:MM:SS" (no T, no Z)
163
+ // ISO → "YYYY-MM-DDTHH:MM:SS.sssZ"
164
+ for (const r of results) {
165
+ if (r.timestamp && !r.timestamp.includes("T")) {
166
+ r.timestamp = r.timestamp.replace(" ", "T") + "Z";
167
+ }
168
+ }
169
+
170
+ // ── Sort ──
171
+ if (sort === "timeline") {
172
+ results.sort((a, b) => (a.timestamp || "").localeCompare(b.timestamp || ""));
173
+ }
174
+
175
+ return results.slice(0, limit);
176
+ }