symforge 8.16.5

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
//! Search-oriented MCP tool input types and pure request parsing helpers.

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use crate::domain::index::LanguageId;
use crate::live_index::search;

use super::read_tools::{lenient_bool, lenient_option_vec, lenient_u32, lenient_u64};

/// Source-scope vocabulary accepted by `search_knowledge` and `review_knowledge`.
///
/// Both `search_knowledge` and `review_knowledge` compose across all four scopes
/// (Gate L): `current`, `worktrees`, `local_refs`, and `all`.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum KnowledgeSourceScope {
    Current,
    Worktrees,
    LocalRefs,
    All,
}

/// Source scopes advertised by `search_knowledge` and `review_knowledge`
/// (Gate L): both compose across the captured source set, so every implemented
/// P1 scope is advertised.
#[allow(dead_code)]
#[derive(JsonSchema)]
#[serde(rename_all = "snake_case")]
enum AdvertisedSearchKnowledgeSourceScope {
    Current,
    Worktrees,
    LocalRefs,
    All,
}

/// Retrieval voice filter for repository knowledge.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum KnowledgeAuthorityScope {
    Default,
    Current,
    Intent,
    History,
    All,
}

/// Exact Gate I input for `search_knowledge`.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct SearchKnowledgeInput {
    /// Non-empty natural-language or identifier query.
    pub query: String,
    /// Optional normalized repository-relative prefix; traversal is rejected.
    #[serde(default)]
    pub path_prefix: Option<String>,
    /// Captured repository source scope: `current` (default), `worktrees`,
    /// `local_refs`, or `all`. Composed from one captured source set.
    #[serde(default)]
    #[schemars(with = "AdvertisedSearchKnowledgeSourceScope")]
    pub source_scope: Option<KnowledgeSourceScope>,
    /// Authority/retrieval voice filter. Defaults to `default`.
    #[serde(default)]
    pub authority_scope: Option<KnowledgeAuthorityScope>,
    /// One open project id/alias; mutually exclusive with `projects`.
    #[serde(default)]
    pub project: Option<String>,
    /// Explicit open-project ids/aliases or `["*"]`; mutually exclusive with `project`.
    #[serde(default)]
    #[schemars(with = "Vec<String>")]
    pub projects: Option<Vec<String>>,
    /// Maximum number of complete hits. Defaults to ten and is server-bounded.
    #[serde(default, deserialize_with = "lenient_u32")]
    pub limit: Option<u32>,
    /// Bounded response budget; truncation preserves complete provenance.
    #[serde(default, deserialize_with = "lenient_u64")]
    pub max_tokens: Option<u64>,
}

/// Frozen read-only review modes for `review_knowledge`.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ReviewKnowledgeMode {
    Summary,
    Document,
    Remediation,
}

/// Exact Gate J input for `review_knowledge`.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReviewKnowledgeInput {
    /// Review projection: aggregate summary, exact document, or ranked remediation.
    pub mode: ReviewKnowledgeMode,
    /// Exact normalized repository-relative path. Required by `document` mode.
    #[serde(default)]
    pub path: Option<String>,
    /// Optional normalized repository-relative prefix for summary/remediation scope.
    #[serde(default)]
    pub path_prefix: Option<String>,
    /// Captured repository source scope: `current` (default), `worktrees`,
    /// `local_refs`, or `all`. Composed from one captured source set.
    #[serde(default)]
    #[schemars(with = "AdvertisedSearchKnowledgeSourceScope")]
    pub source_scope: Option<KnowledgeSourceScope>,
    /// One open project id/alias; mutually exclusive with `projects`.
    #[serde(default)]
    pub project: Option<String>,
    /// Explicit open-project ids/aliases or `["*"]`; mutually exclusive with `project`.
    #[serde(default)]
    #[schemars(with = "Vec<String>")]
    pub projects: Option<Vec<String>>,
    /// Maximum number of complete dossiers. Defaults to ten and is server-bounded.
    #[serde(default, deserialize_with = "lenient_u32")]
    pub limit: Option<u32>,
    /// Bounded response budget; complete-plan hashes are computed before budgeting.
    #[serde(default, deserialize_with = "lenient_u64")]
    pub max_tokens: Option<u64>,
}

/// Lifecycle value accepted by the repository knowledge policy writer.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum KnowledgePolicyLifecycleInput {
    Active,
    Proposed,
    Accepted,
    Implemented,
    Deferred,
    Rejected,
    Withdrawn,
    Deprecated,
    Superseded,
    Archived,
    Historical,
    Unknown,
}

/// Optional authority-domain assertion accepted by the policy writer.
#[derive(Clone, Copy, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum KnowledgePolicyAuthorityDomainInput {
    CurrentImplementation,
    NormativeIntent,
    Decision,
    Operations,
    Governance,
    HistoricalRecord,
    Unknown,
}

/// Exact byte-identity target guarded by one curation action.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct KnowledgePolicyTargetInput {
    pub path: String,
    pub content_hash: String,
    #[serde(default)]
    #[schemars(with = "[u32; 2]")]
    pub unit_byte_range: Option<[u32; 2]>,
    #[serde(default)]
    pub unit_hash: Option<String>,
}

/// Secret-safe evidence reference stored in the policy ledger.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct KnowledgePolicyEvidenceInput {
    pub rule_id: String,
    #[serde(default)]
    pub knowledge: Option<KnowledgePolicyTargetInput>,
    #[serde(default)]
    pub code_path: Option<String>,
}

/// One complete policy entry for an upsert mutation.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct KnowledgePolicyEntryInput {
    pub entry_id: String,
    pub target: KnowledgePolicyTargetInput,
    pub lifecycle: KnowledgePolicyLifecycleInput,
    #[serde(default)]
    pub authority_domain: Option<KnowledgePolicyAuthorityDomainInput>,
    #[serde(default)]
    pub superseded_by: Option<KnowledgePolicyTargetInput>,
    #[serde(default)]
    pub evidence: Vec<KnowledgePolicyEvidenceInput>,
    pub justification_code: String,
}

/// Ledger-only mutations. Move/delete/document-edit operations are intentionally
/// absent from the closed schema.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(tag = "operation", rename_all = "snake_case", deny_unknown_fields)]
pub enum KnowledgePolicyMutationInput {
    Upsert {
        entry: KnowledgePolicyEntryInput,
    },
    Remove {
        entry_id: String,
        expected_target: KnowledgePolicyTargetInput,
    },
}

/// An explicitly approved review action and its exact policy mutation.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct KnowledgePolicyActionInput {
    pub action_id: String,
    pub mutation: KnowledgePolicyMutationInput,
}

/// Preview-first Gate K input for one current-worktree source.
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct CurateKnowledgeInput {
    pub actions: Vec<KnowledgePolicyActionInput>,
    pub if_source_review_hash: String,
    pub if_manifest_digest: String,
    pub if_policy_digest: String,
    #[serde(default)]
    pub idempotency_key: Option<String>,
    #[serde(default)]
    pub apply: bool,
    #[schemars(required)]
    pub project: Option<String>,
}

/// Input for `search_symbols`.
#[derive(Deserialize, Serialize, JsonSchema)]
pub struct SearchSymbolsInput {
    /// Search query (case-insensitive substring match). Optional when `kind` or `path_prefix` is
    /// provided — omitting `query` enables browse mode.
    #[serde(default)]
    pub query: Option<String>,
    /// Optional kind filter using display names such as `fn`, `class`, or `interface`.
    pub kind: Option<String>,
    /// Optional relative path prefix scope, for example `src/` or `src/protocol`.
    pub path_prefix: Option<String>,
    /// Optional canonical language name such as `Rust`, `TypeScript`, `C#`, or `C++`.
    pub language: Option<String>,
    /// Optional maximum number of matches to return (default 50, capped at 100).
    #[serde(default, deserialize_with = "lenient_u32")]
    pub limit: Option<u32>,
    /// When true, include generated files in the result set.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub include_generated: Option<bool>,
    /// When true, include test files in the result set.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub include_tests: Option<bool>,
    /// When true, include vendored/third-party paths (vendor/, node_modules/, third_party/).
    /// Default false -- vendor noise dominates symbol lookup in repos with embedded grammars.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub include_vendor: Option<bool>,
    /// When true, include personal tooling paths (.claude/gsd-*).
    /// Default false -- personal sidecars rarely answer codebase symbol questions.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub include_personal_tooling: Option<bool>,
    /// When true, return an approximate token cost estimate instead of actual content.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub estimate: Option<bool>,
    /// Optional maximum token budget for the response.
    #[serde(default, deserialize_with = "lenient_u64")]
    pub max_tokens: Option<u64>,
    /// Feature 012 (Phase 3): target a SINGLE open project by id/alias instead of
    /// the session's active project. Mutually exclusive with `projects`. Must be a
    /// project id/alias, NEVER a filesystem path (a path is rejected with a
    /// corrective error pointing at `index_folder(add:true)`). Omitting both
    /// `project` and `projects` targets the active project (today's behavior).
    #[serde(default)]
    pub project: Option<String>,
    /// Feature 012 (Phase 3): target an EXPLICIT subset of open projects by
    /// id/alias, or `["*"]` for every open project. Mutually exclusive with
    /// `project`. An empty list is rejected (no silent "all"). Daemon-only.
    // `#[schemars(with = "Vec<String>")]` keeps this a plain `type: "array"`
    // schema, NOT the `type: ["array", "null"]` union that strict MCP clients
    // reject (mirrors `SearchTextInput::terms`; enforced by
    // `tests/strict_client_schema_compat.rs`); serde keeps the field optional.
    #[serde(default)]
    #[schemars(with = "Vec<String>")]
    pub projects: Option<Vec<String>>,
}

/// Input for `search_text`.
#[derive(Deserialize, Serialize, JsonSchema, Default)]
pub struct SearchTextInput {
    /// Search query (case-insensitive substring match unless `regex` is true).
    pub query: Option<String>,
    /// Optional list of terms to match with OR semantics.
    #[serde(default, deserialize_with = "lenient_option_vec")]
    #[schemars(with = "Vec<String>")]
    pub terms: Option<Vec<String>>,
    /// Interpret `query` as a regex pattern instead of a literal substring.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub regex: Option<bool>,
    /// Optional relative path prefix scope, for example `src/` or `src/protocol`.
    pub path_prefix: Option<String>,
    /// Optional canonical language name such as `Rust`, `TypeScript`, `C#`, or `C++`.
    pub language: Option<String>,
    /// Optional maximum number of matches to return across all files (default 50).
    #[serde(default, deserialize_with = "lenient_u32")]
    pub limit: Option<u32>,
    /// Optional maximum number of matches to return per file (default 5).
    #[serde(default, deserialize_with = "lenient_u32")]
    pub max_per_file: Option<u32>,
    /// When true, include generated files in the result set.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub include_generated: Option<bool>,
    /// When true, include test files AND `#[cfg(test)]` modules in the result
    /// set. Both are EXCLUDED by default, so a query that only matches test
    /// code returns zero source hits (a hint reports how many test matches were
    /// suppressed); set this true to see them.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub include_tests: Option<bool>,
    /// When true, include vendored/third-party paths (vendor/, node_modules/, third_party/).
    /// Default false -- vendor noise dominates results in repos with embedded grammars.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub include_vendor: Option<bool>,
    /// When true, include personal tooling paths (.claude/gsd-*).
    /// Default false -- personal sidecars rarely answer code questions.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub include_personal_tooling: Option<bool>,
    /// Optional repo-relative include glob, for example `src/**/*.ts`.
    pub glob: Option<String>,
    /// Optional repo-relative exclude glob, for example `**/*.spec.ts`.
    pub exclude_glob: Option<String>,
    /// Optional symmetric number of surrounding lines to render around each match.
    #[serde(default, deserialize_with = "lenient_u32")]
    pub context: Option<u32>,
    /// Optional case-sensitivity override. Literal mode defaults to false; regex mode defaults to true.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub case_sensitive: Option<bool>,
    /// When true, require whole-word matches for literal searches. Not supported with `regex=true`.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub whole_word: Option<bool>,
    /// Group matches: "file" (default), "symbol" (one entry per enclosing symbol),
    /// "usage" (exclude imports and comments), or "names" (flat deduplicated list of
    /// symbol names containing matches — useful as input to batch operations).
    pub group_by: Option<String>,
    /// When true, for each match include a compact list of callers of the enclosing symbol.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub follow_refs: Option<bool>,
    /// Max number of file matches to enrich with callers when follow_refs=true (default 3).
    #[serde(default, deserialize_with = "lenient_u32")]
    pub follow_refs_limit: Option<u32>,
    /// When true, re-rank results by semantic importance (caller count, churn, symbol kind)
    /// rather than simple match count. Default: false.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub ranked: Option<bool>,
    /// When true, return an approximate token cost estimate instead of actual content.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub estimate: Option<bool>,
    /// Optional maximum token budget for the response. Output is truncated at a line boundary if exceeded.
    #[serde(default, deserialize_with = "lenient_u64")]
    pub max_tokens: Option<u64>,
    /// When true, interpret `query` as an ast-grep structural pattern instead of a text search.
    /// Matches AST patterns using tree-sitter. Use `$VAR` for single-node metavariables
    /// and `$$$` for multi-node wildcards. Example: `fn $NAME($$$) { $$$ }`.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub structural: Option<bool>,
    /// Feature 012 (Phase 3): target a SINGLE open project by id/alias instead of
    /// the session's active project. Mutually exclusive with `projects`; must be a
    /// project id/alias, never a path. Omitting both targets the active project.
    #[serde(default)]
    pub project: Option<String>,
    /// Feature 012 (Phase 3): target an EXPLICIT subset of open projects by
    /// id/alias, or `["*"]` for every open project. Mutually exclusive with
    /// `project`; an empty list is rejected. Daemon-only.
    // `#[schemars(with = "Vec<String>")]` keeps this a plain `type: "array"`
    // schema, NOT the `type: ["array", "null"]` union that strict MCP clients
    // reject (mirrors `SearchTextInput::terms`; enforced by
    // `tests/strict_client_schema_compat.rs`); serde keeps the field optional.
    #[serde(default)]
    #[schemars(with = "Vec<String>")]
    pub projects: Option<Vec<String>>,
}

/// Input for `search_files`.
#[derive(Deserialize, Serialize, JsonSchema)]
pub struct SearchFilesInput {
    /// Optional explicit project selector (daemon sessions with multiple open
    /// projects): an open project ID or unique project name. Omit for the
    /// session's home project. Local/embedded servers are bound to one project
    /// and refuse a non-matching selector.
    #[serde(default)]
    pub project: Option<String>,
    /// Target an EXPLICIT subset of open projects by id/name, or `["*"]` for
    /// every open project. Mutually exclusive with `project`. Plain fuzzy
    /// query mode only — resolve/coupling modes stay single-project.
    /// Daemon-only.
    // `#[schemars(with = "Vec<String>")]` keeps this a plain `type: "array"`
    // schema, NOT the `type: ["array", "null"]` union that strict MCP clients
    // reject (mirrors the sibling discovery verbs; enforced by
    // `tests/strict_client_schema_compat.rs`); serde keeps the field optional.
    #[serde(default)]
    #[schemars(with = "Vec<String>")]
    pub projects: Option<Vec<String>>,
    /// Filename, folder name, or partial path. Required for search and resolve modes. Optional when `changed_with` is provided.
    #[serde(default)]
    pub query: String,
    /// Optional maximum number of matches to return (default 20, capped at 50).
    #[serde(default, deserialize_with = "lenient_u32")]
    pub limit: Option<u32>,
    /// Optional current file path to boost local results.
    pub current_file: Option<String>,
    /// Deprecated since v7.x: prefer `rank_by="path+cochange"` with
    /// `anchor_path=<path>`. This compatibility path still finds files that
    /// frequently co-change with this file via git temporal coupling, but is
    /// scheduled for removal in v8.x.
    pub changed_with: Option<String>,
    /// Set to true for exact path resolution mode: resolves an ambiguous filename or partial path to one exact project path.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub resolve: Option<bool>,
    /// When true, return an approximate token cost estimate instead of actual content.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub estimate: Option<bool>,
    /// Optional maximum token budget for the response.
    #[serde(default, deserialize_with = "lenient_u64")]
    pub max_tokens: Option<u64>,
    /// When true, append a compact ranking explanation unless ranking diagnostics are disabled by policy.
    /// Missing values default off; `SYMFORGE_DEBUG_RANKING=1` may still default diagnostics on operationally.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub debug_ranking: Option<bool>,
    /// Optional ranking mode. `"frecency"` requests call-time frecency
    /// resolution: available session or persistent history is fused with
    /// path ranking, otherwise the response includes explicit fallback,
    /// unavailable, or disabled-by-policy evidence.
    /// `"path+cochange"` fuses path match with the coupling store when
    /// `anchor_path` is set and ready coupling data exists; otherwise the
    /// response reports call-time preparation, fallback, unavailable, stale,
    /// or disabled-by-policy evidence.
    /// Any other value (including `None`) preserves the default
    /// tier-based ordering exactly.
    ///
    /// The separate `changed_with=` branch is preserved for compatibility.
    #[serde(default)]
    pub rank_by: Option<String>,
    /// Anchor file used as the co-change pivot when `rank_by="path+cochange"`.
    #[serde(default)]
    pub anchor_path: Option<String>,
    /// When true, include vendored/third-party paths (vendor/, node_modules/, third_party/).
    /// Default false -- vendor noise dominates path lookup in repos with embedded grammars.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub include_vendor: Option<bool>,
    /// When true, include personal tooling paths (.claude/gsd-*).
    /// Default false -- personal sidecars rarely answer codebase path questions.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub include_personal_tooling: Option<bool>,
    /// Optional relative path prefix scope, for example `src/` or `src/protocol`.
    pub path_prefix: Option<String>,
}

/// Input for `find_references`.
#[derive(Deserialize, Serialize, JsonSchema)]
pub struct FindReferencesInput {
    /// Symbol name to find references for (or trait/type name when mode='implementations').
    pub name: String,
    /// Filter by reference kind: "call", "import", "type_usage", or "all" (default: "all"). Ignored when mode='implementations'.
    pub kind: Option<String>,
    /// Optional exact-selector path from `search_symbols`, for example `src/db.rs`. Ignored when mode='implementations'.
    pub path: Option<String>,
    /// Optional selected symbol kind such as `fn`, `class`, or `struct`. Ignored when mode='implementations'.
    pub symbol_kind: Option<String>,
    /// Optional selected symbol line from `search_symbols`. Ignored when mode='implementations'.
    #[serde(default, deserialize_with = "lenient_u32")]
    pub symbol_line: Option<u32>,
    /// Maximum number of files/entries to show (default 20 for references, 200 for implementations; capped at 100/500).
    #[serde(default, deserialize_with = "lenient_u32")]
    pub limit: Option<u32>,
    /// Maximum number of reference hits per file (default 10, capped at 50). Ignored when mode='implementations'.
    #[serde(default, deserialize_with = "lenient_u32")]
    pub max_per_file: Option<u32>,
    /// When true, show compact output: file:line [kind] in symbol — no source text (60-75% smaller). Ignored when mode='implementations'.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub compact: Option<bool>,
    /// Mode: "references" (default — call sites, imports, type usages) or "implementations" (trait/interface implementors and implemented traits). When mode='implementations', only name, direction, and limit are used.
    #[serde(default)]
    pub mode: Option<String>,
    /// Search direction for implementations mode: "trait" (find implementors), "type" (find traits a type implements), or "auto" (default: search both).
    #[serde(default)]
    pub direction: Option<String>,
    /// When true, return an approximate token cost estimate instead of actual content.
    #[serde(default, deserialize_with = "lenient_bool")]
    pub estimate: Option<bool>,
    /// Optional maximum token budget for the response.
    #[serde(default, deserialize_with = "lenient_u64")]
    pub max_tokens: Option<u64>,
    /// Feature 012 (Phase 3): target a SINGLE open project by id/alias instead of
    /// the session's active project. Mutually exclusive with `projects`; must be a
    /// project id/alias, never a path. Omitting both targets the active project.
    #[serde(default)]
    pub project: Option<String>,
    /// Feature 012 (Phase 3): target an EXPLICIT subset of open projects by
    /// id/alias, or `["*"]` for every open project. Mutually exclusive with
    /// `project`; an empty list is rejected. Daemon-only.
    // `#[schemars(with = "Vec<String>")]` keeps this a plain `type: "array"`
    // schema, NOT the `type: ["array", "null"]` union that strict MCP clients
    // reject (mirrors `SearchTextInput::terms`; enforced by
    // `tests/strict_client_schema_compat.rs`); serde keeps the field optional.
    #[serde(default)]
    #[schemars(with = "Vec<String>")]
    pub projects: Option<Vec<String>>,
}

pub(crate) fn parse_language_filter(input: Option<&str>) -> Result<Option<LanguageId>, String> {
    let Some(language) = input.map(str::trim).filter(|language| !language.is_empty()) else {
        return Ok(None);
    };

    let normalized = language.to_ascii_lowercase();
    let parsed = match normalized.as_str() {
        "rust" => Some(LanguageId::Rust),
        "python" => Some(LanguageId::Python),
        "javascript" => Some(LanguageId::JavaScript),
        "typescript" => Some(LanguageId::TypeScript),
        "go" => Some(LanguageId::Go),
        "java" => Some(LanguageId::Java),
        "c" => Some(LanguageId::C),
        "c++" => Some(LanguageId::Cpp),
        "c#" => Some(LanguageId::CSharp),
        "ruby" => Some(LanguageId::Ruby),
        "php" => Some(LanguageId::Php),
        "swift" => Some(LanguageId::Swift),
        "kotlin" => Some(LanguageId::Kotlin),
        "dart" => Some(LanguageId::Dart),
        "perl" => Some(LanguageId::Perl),
        "elixir" => Some(LanguageId::Elixir),
        "json" => Some(LanguageId::Json),
        "toml" => Some(LanguageId::Toml),
        "yaml" => Some(LanguageId::Yaml),
        "markdown" | "md" => Some(LanguageId::Markdown),
        "env" => Some(LanguageId::Env),
        "html" => Some(LanguageId::Html),
        "css" => Some(LanguageId::Css),
        "scss" => Some(LanguageId::Scss),
        _ => None,
    };

    parsed.map(Some).ok_or_else(|| {
        "Unsupported language filter. Use one of: Rust, Python, JavaScript, TypeScript, Go, Java, C, C++, C#, Ruby, PHP, Swift, Kotlin, Dart, Perl, Elixir, JSON, TOML, YAML, Markdown, Env, HTML, CSS, SCSS.".to_string()
    })
}

pub(crate) fn normalize_path_prefix(input: Option<&str>) -> search::PathScope {
    let Some(prefix) = input.map(str::trim).filter(|prefix| !prefix.is_empty()) else {
        return search::PathScope::any();
    };

    let normalized = prefix
        .replace('\\', "/")
        .trim_start_matches("./")
        .trim_start_matches('/')
        .trim_end_matches('/')
        .to_string();

    if normalized.is_empty() {
        search::PathScope::any()
    } else {
        search::PathScope::prefix(normalized)
    }
}

pub(crate) fn normalize_search_text_glob(input: Option<&str>) -> Option<String> {
    input
        .map(str::trim)
        .filter(|pattern| !pattern.is_empty())
        .map(|pattern| {
            let normalized = pattern
                .replace('\\', "/")
                .trim_start_matches("./")
                .trim_start_matches('/')
                .to_string();
            // Auto-prefix bare filenames (no glob chars, no path separators)
            // so "foo.rs" matches "**/foo.rs" instead of failing silently.
            if !normalized.contains('*')
                && !normalized.contains('/')
                && !normalized.contains('?')
                && !normalized.contains('[')
            {
                format!("**/{normalized}")
            } else {
                normalized
            }
        })
        .filter(|pattern| !pattern.is_empty())
}

pub(crate) fn search_symbols_options_from_input(
    input: &SearchSymbolsInput,
) -> Result<search::SymbolSearchOptions, String> {
    let is_browse = input
        .query
        .as_ref()
        .map(|q| q.trim().is_empty())
        .unwrap_or(true);
    let default_limit = if is_browse { 20u32 } else { 50u32 };
    Ok(search::SymbolSearchOptions {
        path_scope: normalize_path_prefix(input.path_prefix.as_deref()),
        search_scope: search::SearchScope::Code,
        result_limit: search::ResultLimit::new(
            input.limit.unwrap_or(default_limit).min(100) as usize
        ),
        noise_policy: search::NoisePolicy {
            include_generated: input.include_generated.unwrap_or(false),
            include_tests: input.include_tests.unwrap_or(false),
            include_vendor: input.include_vendor.unwrap_or(false),
            include_ignored: false,
        },
        include_personal_tooling: input.include_personal_tooling.unwrap_or(false),
        language_filter: parse_language_filter(input.language.as_deref())?,
    })
}

pub(crate) fn search_text_options_from_input(
    input: &SearchTextInput,
) -> Result<search::TextSearchOptions, String> {
    let is_regex = input.regex.unwrap_or(false);
    let is_ranked = input.ranked.unwrap_or(false);

    // When regex mode is active the user is doing a targeted, precise search
    // and expects completeness over test noise by default. Vendor remains
    // opt-in because embedded grammars and dependencies can dominate result
    // caps before project code is seen.
    let include_tests = input.include_tests.unwrap_or(is_regex);
    let include_generated = input.include_generated.unwrap_or(false);

    // When ranked=true the user wants results ordered by importance, which
    // requires scanning broadly first.  A low total_limit starves the
    // ranker — boost it so common terms still surface enough files.
    let total_limit = input.limit.unwrap_or(if is_ranked { 200 } else { 50 }) as usize;

    Ok(search::TextSearchOptions {
        path_scope: normalize_path_prefix(input.path_prefix.as_deref()),
        search_scope: search::SearchScope::Code,
        noise_policy: search::NoisePolicy {
            include_generated,
            include_tests,
            include_vendor: input.include_vendor.unwrap_or(false),
            include_ignored: false,
        },
        include_personal_tooling: input.include_personal_tooling.unwrap_or(false),
        language_filter: parse_language_filter(input.language.as_deref())?,
        total_limit,
        max_per_file: input.max_per_file.unwrap_or(5) as usize,
        glob: normalize_search_text_glob(input.glob.as_deref()),
        exclude_glob: normalize_search_text_glob(input.exclude_glob.as_deref()),
        context: input.context.map(|context| context as usize),
        case_sensitive: input.case_sensitive,
        whole_word: input.whole_word.unwrap_or(false),
        ranked: is_ranked,
        churn_scores: None,
    })
}

/// Attempt to fix double-escaped regex character classes (e.g., `\\s` -> `\s`).
/// Returns `Some(fixed)` if the pattern contains likely double-escaped sequences,
/// `None` otherwise.
pub(crate) fn fix_common_double_escapes(pattern: &str) -> Option<String> {
    static RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
        regex::Regex::new(r"\\\\([sdwbntSDWB])").expect("static regex")
    });
    if !RE.is_match(pattern) {
        return None;
    }
    Some(RE.replace_all(pattern, r"\$1").to_string())
}