@floydous/pi-agent-kernel 0.4.3 → 0.6.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 (65) hide show
  1. package/AGENT_KERNEL_SYS_PROMPT.md +15 -12
  2. package/CHANGELOG.md +87 -0
  3. package/README.md +6 -54
  4. package/config.example.toml +1 -8
  5. package/docs/README.md +1 -2
  6. package/docs/architecture.md +2 -3
  7. package/docs/configuration.md +11 -10
  8. package/docs/editing-and-verification.md +21 -8
  9. package/docs/podman-linux-checks.md +24 -0
  10. package/docs/release-discipline.md +10 -0
  11. package/docs/retrieval.md +21 -23
  12. package/docs/testing.md +3 -3
  13. package/grammars/tree-sitter-html.wasm +0 -0
  14. package/package.json +5 -3
  15. package/src/config/agent_kernel_command.ts +60 -625
  16. package/src/config/kernel_config.ts +53 -69
  17. package/src/config/toml.ts +6 -1
  18. package/src/editing/auto_heal.ts +1 -1
  19. package/src/editing/patch.ts +75 -37
  20. package/src/editing/post_edit_verification.ts +20 -14
  21. package/src/editing/smart_anchor.ts +9 -6
  22. package/src/editing/syntax-verify.ts +79 -222
  23. package/src/index.ts +36 -453
  24. package/src/retrieval/html_chunker.ts +526 -0
  25. package/src/retrieval/search_bm25.ts +39 -28
  26. package/src/retrieval/search_chunker.ts +69 -7
  27. package/src/retrieval/search_config.ts +21 -40
  28. package/src/retrieval/search_embedder.ts +14 -31
  29. package/src/retrieval/search_index.ts +338 -129
  30. package/src/retrieval/search_modal.ts +1208 -222
  31. package/src/retrieval/{repomap.ts → tag_extractor.ts} +6 -293
  32. package/src/retrieval/tree_sitter_engine.ts +171 -36
  33. package/src/retrieval/workspace_walker.ts +78 -2
  34. package/src/safety/atomic_write.ts +1 -1
  35. package/src/safety/epistemic_guard.ts +105 -31
  36. package/src/safety/host_environment.ts +180 -0
  37. package/src/safety/output_clamper.ts +97 -27
  38. package/src/tools/code_search_output.ts +11 -2
  39. package/src/tools/code_search_tool.ts +25 -13
  40. package/src/tools/context.ts +11 -10
  41. package/src/tools/edit_tool.ts +243 -154
  42. package/src/tools/read_tool.ts +285 -214
  43. package/src/tools/stream_reader.ts +206 -0
  44. package/src/ui/footer.ts +7 -7
  45. package/docs/lsp.md +0 -31
  46. package/src/lsp/adapters/base.ts +0 -42
  47. package/src/lsp/adapters/index.ts +0 -21
  48. package/src/lsp/adapters/python.ts +0 -37
  49. package/src/lsp/adapters/rust.ts +0 -35
  50. package/src/lsp/adapters/typescript.ts +0 -40
  51. package/src/lsp/index.ts +0 -13
  52. package/src/lsp/lsp_client.ts +0 -765
  53. package/src/lsp/lsp_detector.ts +0 -52
  54. package/src/lsp/lsp_formatter.ts +0 -323
  55. package/src/lsp/lsp_installer.ts +0 -320
  56. package/src/lsp/lsp_manager.ts +0 -202
  57. package/src/lsp/lsp_modal.ts +0 -675
  58. package/src/lsp/lsp_registry.ts +0 -600
  59. package/src/lsp/lsp_types.ts +0 -143
  60. package/src/retrieval/ast_search.ts +0 -999
  61. package/src/retrieval/symbol_reader.ts +0 -228
  62. package/src/tools/ast_search_formatter.ts +0 -161
  63. package/src/tools/ast_search_tool.ts +0 -146
  64. package/src/tools/lsp_tool.ts +0 -794
  65. package/src/tools/repo_map_tool.ts +0 -56
@@ -1,39 +1,139 @@
1
1
  import type { Theme } from "@earendil-works/pi-coding-agent";
2
- import { type Focusable, matchesKey, truncateToWidth, visibleWidth } from "../ui/tui_utils";
2
+ import { type Focusable, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "../ui/tui_utils";
3
3
  import { HybridSearchIndex } from "./search_index";
4
4
  import { SearchProfile } from "./search_config";
5
+ import {
6
+ loadKernelConfig,
7
+ saveGlobalKernelConfig,
8
+ saveProjectKernelConfig,
9
+ removeGlobalKernelConfigKey,
10
+ removeProjectKernelConfigKey,
11
+ getGlobalRawConfig,
12
+ mergeDeep,
13
+ type KernelConfig,
14
+ type KernelConfigOverrides,
15
+ } from "../config/kernel_config";
5
16
 
6
17
  export interface ModalResult {
7
18
  action: string;
8
19
  profile?: SearchProfile;
9
20
  reindexed?: boolean;
21
+ excludedPathsChanged?: boolean;
10
22
  }
11
23
 
12
- export class SearchControlModal implements Focusable {
24
+ export interface ScopeTreeNode {
25
+ id: string; // e.g. "src" or "src/retrieval/search_index.ts"
26
+ name: string; // basename
27
+ relPath: string; // forward-slash relative path
28
+ isDir: boolean;
29
+ depth: number;
30
+ expanded: boolean;
31
+ children: ScopeTreeNode[];
32
+ parent?: ScopeTreeNode;
33
+ fileCount: number;
34
+ chunkCount: number;
35
+ sizeBytes?: number;
36
+ }
37
+
38
+ export interface UnifiedModalOptions {
39
+ initialTab?: 0 | 1 | 2; // 0 = Kernel Settings, 1 = Retrieval Engine, 2 = File Index Scope
40
+ cwd?: string;
41
+ deps?: {
42
+ getConfig: (cwd: string) => KernelConfig;
43
+ invalidateConfig: (cwd: string, ctx?: any) => void;
44
+ clearCaches?: () => void;
45
+ getSearchIndex?: (cwd: string) => any;
46
+ triggerBackgroundIndexing?: (index: any, ctx: any, isFullSync?: boolean) => void;
47
+ };
48
+ ctx?: any;
49
+ }
50
+
51
+ class SearchInput {
52
+ private value = "";
53
+ getValue(): string {
54
+ return this.value;
55
+ }
56
+ setValue(v: string): void {
57
+ this.value = v;
58
+ }
59
+ handleInput(data: string): void {
60
+ if (data === "\x7f" || data === "\b") {
61
+ this.value = this.value.slice(0, -1);
62
+ } else if (data.length === 1 && data >= " " && data <= "~") {
63
+ this.value += data;
64
+ }
65
+ }
66
+ render(width: number, theme?: any): string[] {
67
+ const label = theme?.fg ? theme.fg("dim", " Filter settings: ") : " Filter settings: ";
68
+ const valText = this.value
69
+ ? (theme?.fg ? theme.fg("accent", this.value) : this.value)
70
+ : (theme?.fg ? theme.fg("dim", "(type to filter)") : "(type to filter)");
71
+ return [truncateToWidth(label + valText, width)];
72
+ }
73
+ }
74
+
75
+ function fuzzyFilter<T>(items: T[], query: string, textFn: (item: T) => string): T[] {
76
+ if (!query) return items;
77
+ const lower = query.toLowerCase();
78
+ return items.filter((item) => textFn(item).toLowerCase().includes(lower));
79
+ }
80
+
81
+ interface CategorizedSettingItem {
82
+ category: string;
83
+ id: string;
84
+ label: string;
85
+ currentValue: string;
86
+ values: string[];
87
+ descriptions: Record<string, string>;
88
+ isGlobal: boolean;
89
+ }
90
+
91
+ export class UnifiedControlModal implements Focusable {
13
92
  focused = false;
14
93
 
15
94
  private tui: any;
16
95
  private index: HybridSearchIndex;
17
96
  private theme: Theme;
18
97
  private done: (result: ModalResult | undefined) => void;
19
- private selectedIndex = 0;
20
- private initialProfile: SearchProfile;
98
+ private options: UnifiedModalOptions;
99
+ private currentCwd: string;
100
+
101
+ // Active tab: 0 = Kernel Settings, 1 = Retrieval Engine, 2 = File Index Scope
102
+ private activeTab: 0 | 1 | 2 = 0;
21
103
 
22
- // Menu items categorized
23
- private items: Array<{
104
+ // -------------------------------------------------------------------------
105
+ // TAB 0: KERNEL SETTINGS STATE
106
+ // -------------------------------------------------------------------------
107
+ private settingsItems: CategorizedSettingItem[] = [];
108
+ private filteredSettingsItems: CategorizedSettingItem[] = [];
109
+ private settingsSelectedIndex = 0;
110
+ private searchInput: SearchInput;
111
+ private initialSettingStates = new Map<string, { value: string; isGlobal: boolean }>();
112
+ private categoryOrder = [
113
+ "Retrieval & Exploration",
114
+ "Safety & Verification",
115
+ "Editing Engine",
116
+ "System Guidance & UI",
117
+ ];
118
+
119
+ // -------------------------------------------------------------------------
120
+ // TAB 1: RETRIEVAL ENGINE STATE
121
+ // -------------------------------------------------------------------------
122
+ private initialProfile: SearchProfile;
123
+ private profileSelectedIndex = 0;
124
+ private profileItems: Array<{
24
125
  id: string;
25
126
  category: "profile" | "action";
26
127
  label: string;
27
128
  desc: string;
28
129
  profile?: SearchProfile;
29
130
  }> = [
30
- // Category: Profiles
31
131
  {
32
132
  id: "auto",
33
133
  category: "profile",
34
134
  profile: "auto",
35
135
  label: "Auto Detect",
36
- desc: "Auto-detect Lean (VPS), Hybrid (Laptop), or Full (Desktop)",
136
+ desc: "Auto-detect Lean (fewer than 4 CPUs) or Full (4 or more)",
37
137
  },
38
138
  {
39
139
  id: "lean",
@@ -42,19 +142,12 @@ export class SearchControlModal implements Focusable {
42
142
  label: "Lean Mode",
43
143
  desc: "AST BM25 (0% CPU, 0 MB extra RAM)",
44
144
  },
45
- {
46
- id: "hybrid",
47
- category: "profile",
48
- profile: "hybrid",
49
- label: "Hybrid Mode",
50
- desc: "Throttled 256-dim Matryoshka embeddings",
51
- },
52
145
  {
53
146
  id: "full",
54
147
  category: "profile",
55
148
  profile: "full",
56
149
  label: "Full Mode",
57
- desc: "Multi-core 768-dim embeddings",
150
+ desc: "BM25 + 768-dim code embeddings",
58
151
  },
59
152
  {
60
153
  id: "off",
@@ -63,7 +156,6 @@ export class SearchControlModal implements Focusable {
63
156
  label: "Disable Engine",
64
157
  desc: "Turn off search & free memory",
65
158
  },
66
- // Category: Workspace Actions
67
159
  {
68
160
  id: "reindex",
69
161
  category: "action",
@@ -74,285 +166,1179 @@ export class SearchControlModal implements Focusable {
74
166
  id: "close",
75
167
  category: "action",
76
168
  label: "Close Panel",
77
- desc: "Dismiss this dialog",
169
+ desc: "Dismiss this dialog and apply changes",
78
170
  },
79
171
  ];
80
172
 
173
+ // -------------------------------------------------------------------------
174
+ // TAB 2: FILE INDEX SCOPE STATE
175
+ // -------------------------------------------------------------------------
176
+ private treeRoots: ScopeTreeNode[] = [];
177
+ private treeCursorIndex = 0;
178
+ private treeScrollOffset = 0;
179
+ private excludedPaths: Set<string>;
180
+ private initialExcludedPaths: Set<string>;
181
+
81
182
  constructor(
82
183
  tui: any,
83
184
  index: HybridSearchIndex,
84
185
  theme: Theme,
85
- done: (result: ModalResult | undefined) => void
186
+ done: (result: ModalResult | undefined) => void,
187
+ options: UnifiedModalOptions = {},
86
188
  ) {
87
189
  this.tui = tui;
88
190
  this.index = index;
89
191
  this.theme = theme;
90
192
  this.done = done;
91
- this.initialProfile = index.getProfile();
193
+ this.options = options;
194
+ this.currentCwd = options.cwd || (index?.getCwd ? index.getCwd() : process.cwd());
195
+
196
+ // Tab selection: defaults to options.initialTab if provided,
197
+ // or 1 if invoked as legacy SearchControlModal without options.
198
+ if (options.initialTab !== undefined) {
199
+ this.activeTab = options.initialTab;
200
+ } else {
201
+ this.activeTab = 1;
202
+ }
92
203
 
93
- // Set initial cursor to current active profile
94
- const currentProfile = this.initialProfile;
95
- const idx = this.items.findIndex((item) => item.profile === currentProfile);
96
- if (idx >= 0) this.selectedIndex = idx;
204
+ // Initial profile setup
205
+ this.initialProfile = index?.getProfile ? index.getProfile() : "lean";
206
+ const activeProfileName = this.initialProfile === "hybrid" ? "full" : this.initialProfile;
207
+ const pIdx = this.profileItems.findIndex((item) => item.profile === activeProfileName);
208
+ if (pIdx >= 0) this.profileSelectedIndex = pIdx;
209
+
210
+ // Excluded paths setup
211
+ this.excludedPaths = new Set(index?.getExcludedPaths ? index.getExcludedPaths() : []);
212
+ this.initialExcludedPaths = new Set(this.excludedPaths);
213
+
214
+ // Initialize Tab 0 Settings
215
+ this.searchInput = new SearchInput();
216
+ this.initSettingsTab();
217
+
218
+ // Initialize Tab 2 Scope Tree
219
+ this.buildScopeTree();
97
220
  }
98
221
 
222
+ // =========================================================================
223
+ // TAB 0: KERNEL SETTINGS LOGIC
224
+ // =========================================================================
225
+ private initSettingsTab(): void {
226
+ const currentConfig = this.options.deps?.getConfig
227
+ ? this.options.deps.getConfig(this.currentCwd)
228
+ : loadKernelConfig(this.currentCwd);
229
+
230
+ const globalRaw = getGlobalRawConfig();
231
+ const checkIsGlobal = (id: string): boolean => {
232
+ if (id === "profile") return globalRaw.retrieval?.default_profile !== undefined;
233
+ if (id === "epistemic") return globalRaw.safety?.enable_epistemic_guard !== undefined;
234
+ if (id === "max_lines") return globalRaw.safety?.max_lines !== undefined;
235
+ if (id === "editing") return globalRaw.editing?.mode !== undefined;
236
+ if (id === "read_mode") return globalRaw.editing?.read_mode !== undefined;
237
+ if (id === "normalize_dots") return globalRaw.editing?.normalize_fullwidth_dots !== undefined;
238
+ if (id === "guidance") return globalRaw.instructions?.enabled !== undefined;
239
+ if (id === "host_environment") return globalRaw.instructions?.host_environment !== undefined;
240
+ if (id === "pi_docs") return globalRaw.instructions?.pi_docs !== undefined;
241
+ if (id === "footer") return globalRaw.ui?.enable_pastel_footer !== undefined;
242
+ return false;
243
+ };
244
+
245
+ this.settingsItems = [
246
+ {
247
+ category: "Retrieval & Exploration",
248
+ id: "profile",
249
+ label: "Retrieval Engine Profile",
250
+ currentValue: currentConfig.retrieval.default_profile,
251
+ values: ["auto", "lean", "full", "off"],
252
+ isGlobal: checkIsGlobal("profile"),
253
+ descriptions: {
254
+ auto: "Auto profile: Selects lean below 4 CPU cores and full otherwise.",
255
+ lean: "Lean profile: BM25 keyword index + AST code chunking. Zero RAM overhead, sub-millisecond retrieval.",
256
+ full: "Full profile: BM25 keyword index fused with 768d gte-modernbert-base code embeddings (~147 MB model).",
257
+ hybrid: "Hybrid: alias of the full profile.",
258
+ off: "Off profile: Retrieval subsystem disabled. Searches return empty results.",
259
+ },
260
+ },
261
+ {
262
+ category: "Safety & Verification",
263
+ id: "epistemic",
264
+ label: "Epistemic Guard (Read-before-write)",
265
+ currentValue: currentConfig.safety.enable_epistemic_guard ? "enabled" : "disabled",
266
+ values: ["enabled", "disabled"],
267
+ isGlobal: checkIsGlobal("epistemic"),
268
+ descriptions: {
269
+ enabled: "Epistemic Guard active: Enforces strict read-before-write validation, preventing hallucinated edits.",
270
+ disabled: "Epistemic Guard inactive: Allows unconstrained edits without prior read operations.",
271
+ },
272
+ },
273
+ {
274
+ category: "Safety & Verification",
275
+ id: "max_lines",
276
+ label: "Output Clamping Line Limit",
277
+ currentValue: `${currentConfig.safety.max_lines} lines`,
278
+ values: ["40 lines", "100 lines", "200 lines"],
279
+ isGlobal: checkIsGlobal("max_lines"),
280
+ descriptions: {
281
+ "40 lines": "40 lines maximum: Compact output windowing, best for low-context models.",
282
+ "100 lines": "100 lines maximum (recommended default): Balanced diagnostic context with spillover logging.",
283
+ "200 lines": "200 lines maximum: Expansive terminal output for deep test traces and large outputs.",
284
+ },
285
+ },
286
+ {
287
+ category: "Editing Engine",
288
+ id: "editing",
289
+ label: "Editing Mode (Smart Anchors)",
290
+ currentValue: currentConfig.editing.mode === "smart_anchor" ? "smart_anchor" : "standard",
291
+ values: ["smart_anchor", "standard"],
292
+ isGlobal: checkIsGlobal("editing"),
293
+ descriptions: {
294
+ smart_anchor: "Smart Anchors: syntax validation, lexical delimiter balancing, and line-hint disambiguation.",
295
+ standard: "Standard editing: exact string replacement with delimiter auto-healing disabled.",
296
+ },
297
+ },
298
+ {
299
+ category: "Editing Engine",
300
+ id: "read_mode",
301
+ label: "Reading Anchor Protocol",
302
+ currentValue: currentConfig.editing.read_mode,
303
+ values: ["plain", "anchored", "auto"],
304
+ isGlobal: checkIsGlobal("read_mode"),
305
+ descriptions: {
306
+ plain: "Plain text reads: Clean, unanchored reading protocol. Reduces token consumption by ~84%.",
307
+ anchored: "Anchored reads: Injects LINE#HASH prefixes on every line for strict positional pinning.",
308
+ auto: "Adaptive reading: Defaults to clean plain text, automatically falling back to anchored reads when resolving ambiguous edit targets.",
309
+ },
310
+ },
311
+ {
312
+ category: "Editing Engine",
313
+ id: "normalize_dots",
314
+ label: "Fullwidth Dot Normalization",
315
+ currentValue: currentConfig.editing.normalize_fullwidth_dots !== false ? "enabled" : "disabled",
316
+ values: ["enabled", "disabled"],
317
+ isGlobal: checkIsGlobal("normalize_dots"),
318
+ descriptions: {
319
+ enabled: "Fullwidth dot normalization enabled: Converts Unicode fullwidth full stop (U+FF0E '.') to ASCII '.' in edit operations.",
320
+ disabled: "Fullwidth dot normalization disabled: Preserves Unicode fullwidth full stop verbatim.",
321
+ },
322
+ },
323
+ {
324
+ category: "System Guidance & UI",
325
+ id: "guidance",
326
+ label: "Agent Guidance Prompt",
327
+ currentValue: currentConfig.instructions.enabled ? "enabled" : "disabled",
328
+ values: ["enabled", "disabled"],
329
+ isGlobal: checkIsGlobal("guidance"),
330
+ descriptions: {
331
+ enabled: "Kernel guidance active: Injects empirical tool discipline, grounding rules, and search strategies into the system prompt.",
332
+ disabled: "Kernel guidance inactive: Omits kernel prompt injection, running with default model prompt.",
333
+ },
334
+ },
335
+ {
336
+ category: "System Guidance & UI",
337
+ id: "host_environment",
338
+ label: "Host Environment Info",
339
+ currentValue: currentConfig.instructions.host_environment !== false ? "enabled" : "disabled",
340
+ values: ["enabled", "disabled"],
341
+ isGlobal: checkIsGlobal("host_environment"),
342
+ descriptions: {
343
+ enabled: "Host environment active: Injects factual host OS, shell, line ending policy, and toolchain versions into system prompt.",
344
+ disabled: "Host environment inactive: Omits host platform and toolchain probing from system prompt.",
345
+ },
346
+ },
347
+ {
348
+ category: "System Guidance & UI",
349
+ id: "pi_docs",
350
+ label: "Pi Docs System Guidance (pi-docs)",
351
+ currentValue: currentConfig.instructions.pi_docs ? "enabled" : "disabled",
352
+ values: ["enabled", "disabled"],
353
+ isGlobal: checkIsGlobal("pi_docs"),
354
+ descriptions: {
355
+ enabled: "Pi docs included: Injects documentation guidance for Pi extensions, tools, and theme authoring.",
356
+ disabled: "Pi docs omitted: Strips the Pi documentation block to optimize prompt cache hit rate and token consumption.",
357
+ },
358
+ },
359
+ {
360
+ category: "System Guidance & UI",
361
+ id: "footer",
362
+ label: "Pastel Status Footer",
363
+ currentValue: currentConfig.ui.enable_pastel_footer ? "enabled" : "disabled",
364
+ values: ["enabled", "disabled"],
365
+ isGlobal: checkIsGlobal("footer"),
366
+ descriptions: {
367
+ enabled: "Pastel footer active: Displays terminal statusline at bottom showing active model, search index, and memory.",
368
+ disabled: "Pastel footer inactive: Disables bottom statusline for an uncluttered minimal workspace.",
369
+ },
370
+ },
371
+ ];
372
+
373
+ this.filteredSettingsItems = this.settingsItems;
374
+ for (const item of this.settingsItems) {
375
+ this.initialSettingStates.set(item.id, {
376
+ value: item.currentValue,
377
+ isGlobal: Boolean(item.isGlobal),
378
+ });
379
+ }
380
+ }
381
+
382
+ private applySettingsFilter(query: string): void {
383
+ if (query) {
384
+ const matches = fuzzyFilter(
385
+ this.settingsItems,
386
+ query,
387
+ (item: CategorizedSettingItem) => {
388
+ const descAll = item.descriptions ? Object.values(item.descriptions).join(" ") : "";
389
+ return `${item.category} ${item.label} ${descAll} ${item.id}`;
390
+ },
391
+ );
392
+ const catGroups = new Map<string, CategorizedSettingItem[]>();
393
+ for (const item of matches) {
394
+ const list = catGroups.get(item.category) || [];
395
+ list.push(item);
396
+ catGroups.set(item.category, list);
397
+ }
398
+ const result: CategorizedSettingItem[] = [];
399
+ for (const cat of this.categoryOrder) {
400
+ const list = catGroups.get(cat);
401
+ if (list) result.push(...list);
402
+ }
403
+ this.filteredSettingsItems = result;
404
+ } else {
405
+ this.filteredSettingsItems = this.settingsItems;
406
+ }
407
+ this.settingsSelectedIndex = 0;
408
+ }
409
+
410
+ private activateSettingItem(): void {
411
+ const item = this.filteredSettingsItems[this.settingsSelectedIndex];
412
+ if (!item || !item.values || item.values.length === 0) return;
413
+ const curIdx = item.values.indexOf(item.currentValue);
414
+ const nextIdx = (curIdx + 1) % item.values.length;
415
+ item.currentValue = item.values[nextIdx];
416
+
417
+ // If profile setting was cycled in Tab 0, keep Tab 1 in sync
418
+ if (item.id === "profile") {
419
+ const newProf = item.currentValue as SearchProfile;
420
+ const pIdx = this.profileItems.findIndex((pi) => pi.profile === (newProf === "hybrid" ? "full" : newProf));
421
+ if (pIdx >= 0) this.profileSelectedIndex = pIdx;
422
+ }
423
+ }
424
+
425
+ private toggleGlobalSetting(): void {
426
+ const item = this.filteredSettingsItems[this.settingsSelectedIndex];
427
+ if (!item) return;
428
+ item.isGlobal = !item.isGlobal;
429
+ }
430
+
431
+ private applySettingsChanges(): boolean {
432
+ let hasChanges = false;
433
+ const globalUpdates: KernelConfigOverrides = {};
434
+ const projectUpdates: KernelConfigOverrides = {};
435
+ const revertedGlobals: Array<{ section: string; key: string }> = [];
436
+ const revertedProjects: Array<{ section: string; key: string }> = [];
437
+
438
+ const createPatchForSetting = (id: string, value: string): { patch: KernelConfigOverrides } => {
439
+ const patch: KernelConfigOverrides = {};
440
+ if (id === "profile") {
441
+ patch.retrieval = { default_profile: value as "auto" | "lean" | "hybrid" | "full" | "off" };
442
+ } else if (id === "epistemic") {
443
+ patch.safety = { enable_epistemic_guard: value === "enabled" };
444
+ } else if (id === "editing") {
445
+ patch.editing = { mode: value as "smart_anchor" | "standard" };
446
+ } else if (id === "read_mode") {
447
+ patch.editing = { read_mode: value as "auto" | "plain" | "anchored" };
448
+ } else if (id === "normalize_dots") {
449
+ patch.editing = { normalize_fullwidth_dots: value === "enabled" };
450
+ } else if (id === "guidance") {
451
+ patch.instructions = { enabled: value === "enabled" };
452
+ } else if (id === "host_environment") {
453
+ patch.instructions = { host_environment: value === "enabled" };
454
+ } else if (id === "pi_docs") {
455
+ patch.instructions = { pi_docs: value === "enabled" };
456
+ } else if (id === "footer") {
457
+ patch.ui = { enable_pastel_footer: value === "enabled" };
458
+ } else if (id === "max_lines") {
459
+ const num = parseInt(value, 10);
460
+ if (Number.isSafeInteger(num)) {
461
+ patch.safety = { max_lines: num };
462
+ }
463
+ }
464
+ return { patch };
465
+ };
466
+
467
+ const getSettingSectionAndKey = (id: string): { section: string; key: string } | null => {
468
+ switch (id) {
469
+ case "profile": return { section: "retrieval", key: "default_profile" };
470
+ case "epistemic": return { section: "safety", key: "enable_epistemic_guard" };
471
+ case "max_lines": return { section: "safety", key: "max_lines" };
472
+ case "editing": return { section: "editing", key: "mode" };
473
+ case "read_mode": return { section: "editing", key: "read_mode" };
474
+ case "normalize_dots": return { section: "editing", key: "normalize_fullwidth_dots" };
475
+ case "guidance": return { section: "instructions", key: "enabled" };
476
+ case "host_environment": return { section: "instructions", key: "host_environment" };
477
+ case "pi_docs": return { section: "instructions", key: "pi_docs" };
478
+ case "footer": return { section: "ui", key: "enable_pastel_footer" };
479
+ default: return null;
480
+ }
481
+ };
482
+
483
+ for (const item of this.settingsItems) {
484
+ const initial = this.initialSettingStates.get(item.id);
485
+ if (!initial) continue;
486
+
487
+ const valueChanged = item.currentValue !== initial.value;
488
+ const scopeChanged = Boolean(item.isGlobal) !== Boolean(initial.isGlobal);
489
+
490
+ if (valueChanged || scopeChanged) {
491
+ hasChanges = true;
492
+ const { patch } = createPatchForSetting(item.id, item.currentValue);
493
+
494
+ if (item.isGlobal) {
495
+ mergeDeep(globalUpdates, patch);
496
+ if (!initial.isGlobal) {
497
+ const meta = getSettingSectionAndKey(item.id);
498
+ if (meta) revertedProjects.push(meta);
499
+ }
500
+ } else {
501
+ if (initial.isGlobal) {
502
+ const meta = getSettingSectionAndKey(item.id);
503
+ if (meta) revertedGlobals.push(meta);
504
+ }
505
+ mergeDeep(projectUpdates, patch);
506
+ }
507
+ }
508
+ }
509
+
510
+ if (hasChanges) {
511
+ try {
512
+ if (Object.keys(globalUpdates).length > 0) {
513
+ saveGlobalKernelConfig(globalUpdates);
514
+ }
515
+ if (Object.keys(projectUpdates).length > 0) {
516
+ saveProjectKernelConfig(this.currentCwd, projectUpdates);
517
+ }
518
+ for (const { section, key } of revertedGlobals) {
519
+ removeGlobalKernelConfigKey(section, key);
520
+ }
521
+ for (const { section, key } of revertedProjects) {
522
+ removeProjectKernelConfigKey(this.currentCwd, section, key);
523
+ }
524
+
525
+ this.options.deps?.invalidateConfig?.(this.currentCwd, this.options.ctx);
526
+ this.options.deps?.clearCaches?.();
527
+ this.options.ctx?.ui?.notify?.("Applied Agent Kernel configuration changes.", "info");
528
+ } catch (error) {
529
+ console.error("[agent-kernel] Configuration apply failed:", error);
530
+ }
531
+ }
532
+ return hasChanges;
533
+ }
534
+
535
+ // =========================================================================
536
+ // TAB 2: FILE INDEX SCOPE LOGIC
537
+ // =========================================================================
538
+ private buildScopeTree(): void {
539
+ const files = this.index?.getIndexableFiles ? this.index.getIndexableFiles() : [];
540
+
541
+ for (const relPath of files) {
542
+ const normPath = relPath.replace(/\\/g, "/");
543
+ const parts = normPath.split("/");
544
+ let currentChildren = this.treeRoots;
545
+ let currentParent: ScopeTreeNode | undefined = undefined;
546
+ let currentAccum = "";
547
+
548
+ for (let i = 0; i < parts.length; i++) {
549
+ const part = parts[i];
550
+ const isLast = i === parts.length - 1;
551
+ currentAccum = currentAccum ? `${currentAccum}/${part}` : part;
552
+
553
+ if (isLast) {
554
+ const chunkCount = this.index?.getChunkCountForFile ? this.index.getChunkCountForFile(normPath) : 1;
555
+ const fileNode: ScopeTreeNode = {
556
+ id: normPath,
557
+ name: part,
558
+ relPath: normPath,
559
+ isDir: false,
560
+ depth: i,
561
+ expanded: false,
562
+ children: [],
563
+ parent: currentParent,
564
+ fileCount: 1,
565
+ chunkCount,
566
+ };
567
+ currentChildren.push(fileNode);
568
+ } else {
569
+ let dirNode = currentChildren.find((c) => c.isDir && c.name === part);
570
+ if (!dirNode) {
571
+ dirNode = {
572
+ id: currentAccum,
573
+ name: part,
574
+ relPath: currentAccum,
575
+ isDir: true,
576
+ depth: i,
577
+ expanded: i === 0,
578
+ children: [],
579
+ parent: currentParent,
580
+ fileCount: 0,
581
+ chunkCount: 0,
582
+ };
583
+ currentChildren.push(dirNode);
584
+ }
585
+ currentParent = dirNode;
586
+ currentChildren = dirNode.children;
587
+ }
588
+ }
589
+ }
590
+
591
+ const aggregateCounts = (nodes: ScopeTreeNode[]): { files: number; chunks: number } => {
592
+ let totalFiles = 0;
593
+ let totalChunks = 0;
594
+ for (const node of nodes) {
595
+ if (node.isDir) {
596
+ const sub = aggregateCounts(node.children);
597
+ node.fileCount = sub.files;
598
+ node.chunkCount = sub.chunks;
599
+ totalFiles += sub.files;
600
+ totalChunks += sub.chunks;
601
+ } else {
602
+ totalFiles += 1;
603
+ totalChunks += node.chunkCount;
604
+ }
605
+ }
606
+ nodes.sort((a, b) => {
607
+ if (a.isDir !== b.isDir) return a.isDir ? -1 : 1;
608
+ return a.name.localeCompare(b.name);
609
+ });
610
+ return { files: totalFiles, chunks: totalChunks };
611
+ };
612
+
613
+ aggregateCounts(this.treeRoots);
614
+ }
615
+
616
+ private isPathExcluded(relPath: string): boolean {
617
+ const norm = relPath.replace(/\\/g, "/").replace(/^(\.\/)+/, "").replace(/^\/+|\/+$/g, "");
618
+ for (const p of this.excludedPaths) {
619
+ const cleanP = p.replace(/\\/g, "/").replace(/^(\.\/)+/, "").replace(/^\/+|\/+$/g, "");
620
+ if (!cleanP) continue;
621
+ if (norm === cleanP || norm.startsWith(cleanP + "/")) {
622
+ return true;
623
+ }
624
+ }
625
+ return false;
626
+ }
627
+
628
+ private getFolderSelectionState(node: ScopeTreeNode): "all" | "some" | "none" {
629
+ let total = 0;
630
+ let selected = 0;
631
+
632
+ const check = (n: ScopeTreeNode) => {
633
+ for (const child of n.children) {
634
+ if (child.isDir) {
635
+ check(child);
636
+ } else {
637
+ total++;
638
+ if (!this.isPathExcluded(child.relPath)) {
639
+ selected++;
640
+ }
641
+ }
642
+ }
643
+ };
644
+ check(node);
645
+
646
+ if (total === 0) return "all";
647
+ if (selected === total) return "all";
648
+ if (selected === 0) return "none";
649
+ return "some";
650
+ }
651
+
652
+ private unexcludeNode(node: ScopeTreeNode): void {
653
+ this.excludedPaths.delete(node.relPath);
654
+
655
+ const clearChildren = (n: ScopeTreeNode) => {
656
+ for (const c of n.children) {
657
+ this.excludedPaths.delete(c.relPath);
658
+ if (c.isDir) clearChildren(c);
659
+ }
660
+ };
661
+ if (node.isDir) clearChildren(node);
662
+
663
+ let p = node.parent;
664
+ while (p) {
665
+ if (this.excludedPaths.has(p.relPath)) {
666
+ this.excludedPaths.delete(p.relPath);
667
+ const excludeSubtreeExcept = (dir: ScopeTreeNode, targetPath: string) => {
668
+ for (const c of dir.children) {
669
+ if (c.relPath === targetPath) continue;
670
+ if (c.isDir) {
671
+ if (targetPath.startsWith(c.relPath + "/")) {
672
+ excludeSubtreeExcept(c, targetPath);
673
+ } else {
674
+ this.excludedPaths.add(c.relPath);
675
+ }
676
+ } else {
677
+ this.excludedPaths.add(c.relPath);
678
+ }
679
+ }
680
+ };
681
+ excludeSubtreeExcept(p, node.relPath);
682
+ }
683
+ p = p.parent;
684
+ }
685
+ }
686
+
687
+ private toggleNodeSelection(node: ScopeTreeNode): void {
688
+ if (!node.isDir) {
689
+ const isExcluded = this.isPathExcluded(node.relPath);
690
+ if (isExcluded) {
691
+ this.unexcludeNode(node);
692
+ } else {
693
+ this.excludedPaths.add(node.relPath);
694
+ }
695
+ } else {
696
+ const state = this.getFolderSelectionState(node);
697
+ if (state === "all") {
698
+ this.excludedPaths.add(node.relPath);
699
+ const clearSub = (dir: ScopeTreeNode) => {
700
+ for (const c of dir.children) {
701
+ this.excludedPaths.delete(c.relPath);
702
+ if (c.isDir) clearSub(c);
703
+ }
704
+ };
705
+ clearSub(node);
706
+ } else {
707
+ this.unexcludeNode(node);
708
+ }
709
+ }
710
+ this.tui?.requestRender?.();
711
+ }
712
+
713
+ private getVisibleTreeNodes(): ScopeTreeNode[] {
714
+ const visible: ScopeTreeNode[] = [];
715
+ const traverse = (nodes: ScopeTreeNode[]) => {
716
+ for (const node of nodes) {
717
+ visible.push(node);
718
+ if (node.isDir && node.expanded) {
719
+ traverse(node.children);
720
+ }
721
+ }
722
+ };
723
+ traverse(this.treeRoots);
724
+ return visible;
725
+ }
726
+
727
+ private hasExcludedPathsChanged(): boolean {
728
+ if (this.excludedPaths.size !== this.initialExcludedPaths.size) return true;
729
+ for (const p of this.excludedPaths) {
730
+ if (!this.initialExcludedPaths.has(p)) return true;
731
+ }
732
+ return false;
733
+ }
734
+
735
+ // =========================================================================
736
+ // KEYBOARD INPUT DISPATCHER
737
+ // =========================================================================
99
738
  async handleInput(data: string): Promise<void> {
100
- if (matchesKey(data, "escape") || matchesKey(data, "q") || matchesKey(data, "ctrl+c")) {
101
- const currentProfile = this.index.getProfile();
102
- const changed = currentProfile !== this.initialProfile;
103
- this.done({ action: "close", profile: currentProfile, reindexed: changed });
739
+ // Universal dismiss on Esc / q
740
+ if (
741
+ matchesKey(data, "escape") ||
742
+ matchesKey(data, "q") ||
743
+ matchesKey(data, "ctrl+c")
744
+ ) {
745
+ this.finishModal("close");
104
746
  return;
105
747
  }
106
748
 
107
- if (matchesKey(data, "up") || matchesKey(data, "k")) {
108
- this.selectedIndex = (this.selectedIndex - 1 + this.items.length) % this.items.length;
749
+ // Universal Tab switching: 0 -> 1 -> 2 -> 0
750
+ if (matchesKey(data, "tab")) {
751
+ this.activeTab = ((this.activeTab + 1) % 3) as 0 | 1 | 2;
752
+ this.tui?.requestRender?.();
753
+ return;
754
+ }
755
+ if (data === "1") {
756
+ this.activeTab = 0;
757
+ this.tui?.requestRender?.();
758
+ return;
759
+ }
760
+ if (data === "2") {
761
+ this.activeTab = 1;
762
+ this.tui?.requestRender?.();
763
+ return;
764
+ }
765
+ if (data === "3") {
766
+ this.activeTab = 2;
109
767
  this.tui?.requestRender?.();
110
768
  return;
111
769
  }
112
770
 
113
- if (matchesKey(data, "down") || matchesKey(data, "j")) {
114
- this.selectedIndex = (this.selectedIndex + 1) % this.items.length;
771
+ // ------------------ DISPATCH: TAB 0 (KERNEL SETTINGS) ------------------
772
+ if (this.activeTab === 0) {
773
+ if (data === "G" || data === "\x07") {
774
+ this.toggleGlobalSetting();
775
+ this.tui?.requestRender?.();
776
+ return;
777
+ }
778
+ if (matchesKey(data, "return") || (data === " " && this.searchInput.getValue().length === 0)) {
779
+ this.activateSettingItem();
780
+ this.tui?.requestRender?.();
781
+ return;
782
+ }
783
+ if (matchesKey(data, "up") || matchesKey(data, "k")) {
784
+ if (this.filteredSettingsItems.length > 0) {
785
+ this.settingsSelectedIndex =
786
+ this.settingsSelectedIndex === 0
787
+ ? this.filteredSettingsItems.length - 1
788
+ : this.settingsSelectedIndex - 1;
789
+ this.tui?.requestRender?.();
790
+ }
791
+ return;
792
+ }
793
+ if (matchesKey(data, "down") || matchesKey(data, "j")) {
794
+ if (this.filteredSettingsItems.length > 0) {
795
+ this.settingsSelectedIndex =
796
+ this.settingsSelectedIndex === this.filteredSettingsItems.length - 1
797
+ ? 0
798
+ : this.settingsSelectedIndex + 1;
799
+ this.tui?.requestRender?.();
800
+ }
801
+ return;
802
+ }
803
+
804
+ // Forward typing to search bar
805
+ this.searchInput.handleInput(data);
806
+ this.applySettingsFilter(this.searchInput.getValue());
115
807
  this.tui?.requestRender?.();
116
808
  return;
117
809
  }
118
810
 
119
- if (matchesKey(data, "return") || matchesKey(data, "space")) {
120
- const item = this.items[this.selectedIndex];
121
- if (!item) return;
811
+ // ------------------ DISPATCH: TAB 1 (RETRIEVAL ENGINE) ------------------
812
+ if (this.activeTab === 1) {
813
+ if (matchesKey(data, "left") || matchesKey(data, "h")) {
814
+ this.activeTab = 0;
815
+ this.tui?.requestRender?.();
816
+ return;
817
+ }
818
+ if (matchesKey(data, "right") || matchesKey(data, "l")) {
819
+ this.activeTab = 2;
820
+ this.tui?.requestRender?.();
821
+ return;
822
+ }
122
823
 
123
- if (item.category === "profile" && item.profile) {
124
- this.index.setProfile(item.profile);
125
- const changed = item.profile !== this.initialProfile;
126
- this.done({ action: "select", profile: item.profile, reindexed: changed });
824
+ if (matchesKey(data, "up") || matchesKey(data, "k")) {
825
+ this.profileSelectedIndex =
826
+ (this.profileSelectedIndex - 1 + this.profileItems.length) % this.profileItems.length;
827
+ this.tui?.requestRender?.();
127
828
  return;
128
829
  }
129
830
 
130
- if (item.id === "reindex") {
131
- const currentProfile = this.index.getProfile();
132
- this.done({ action: "reindex", profile: currentProfile, reindexed: true });
831
+ if (matchesKey(data, "down") || matchesKey(data, "j")) {
832
+ this.profileSelectedIndex = (this.profileSelectedIndex + 1) % this.profileItems.length;
833
+ this.tui?.requestRender?.();
834
+ return;
835
+ }
836
+
837
+ if (matchesKey(data, "return") || matchesKey(data, "space")) {
838
+ const item = this.profileItems[this.profileSelectedIndex];
839
+ if (!item) return;
840
+
841
+ if (item.category === "profile" && item.profile) {
842
+ this.index?.setProfile?.(item.profile);
843
+ this.finishModal("select", item.profile);
844
+ return;
845
+ }
846
+
847
+ if (item.id === "reindex") {
848
+ this.finishModal("reindex");
849
+ return;
850
+ }
851
+
852
+ if (item.id === "close") {
853
+ this.finishModal("close");
854
+ return;
855
+ }
856
+ }
857
+ return;
858
+ }
859
+
860
+ // ------------------ DISPATCH: TAB 2 (FILE INDEX SCOPE) ------------------
861
+ const visibleNodes = this.getVisibleTreeNodes();
862
+ if (visibleNodes.length === 0) {
863
+ if (matchesKey(data, "left") || matchesKey(data, "h")) {
864
+ this.activeTab = 1;
865
+ this.tui?.requestRender?.();
866
+ }
867
+ return;
868
+ }
869
+
870
+ if (this.treeCursorIndex >= visibleNodes.length) {
871
+ this.treeCursorIndex = Math.max(0, visibleNodes.length - 1);
872
+ }
873
+ const currentNode = visibleNodes[this.treeCursorIndex];
874
+
875
+ if (matchesKey(data, "up") || matchesKey(data, "k")) {
876
+ this.treeCursorIndex = Math.max(0, this.treeCursorIndex - 1);
877
+ this.tui?.requestRender?.();
878
+ return;
879
+ }
880
+
881
+ if (matchesKey(data, "down") || matchesKey(data, "j")) {
882
+ this.treeCursorIndex = Math.min(visibleNodes.length - 1, this.treeCursorIndex + 1);
883
+ this.tui?.requestRender?.();
884
+ return;
885
+ }
886
+
887
+ if (matchesKey(data, "left") || matchesKey(data, "h")) {
888
+ if (currentNode && currentNode.isDir && currentNode.expanded) {
889
+ currentNode.expanded = false;
890
+ this.tui?.requestRender?.();
133
891
  return;
134
892
  }
893
+ if (currentNode && currentNode.parent) {
894
+ const parentIdx = visibleNodes.findIndex((n) => n.id === currentNode.parent?.id);
895
+ if (parentIdx >= 0) {
896
+ this.treeCursorIndex = parentIdx;
897
+ this.tui?.requestRender?.();
898
+ return;
899
+ }
900
+ }
901
+ this.activeTab = 1;
902
+ this.tui?.requestRender?.();
903
+ return;
904
+ }
135
905
 
136
- if (item.id === "close") {
137
- const currentProfile = this.index.getProfile();
138
- const changed = currentProfile !== this.initialProfile;
139
- this.done({ action: "close", profile: currentProfile, reindexed: changed });
906
+ if (matchesKey(data, "right") || matchesKey(data, "l")) {
907
+ if (currentNode && currentNode.isDir && !currentNode.expanded) {
908
+ currentNode.expanded = true;
909
+ this.tui?.requestRender?.();
140
910
  return;
141
911
  }
142
912
  }
913
+
914
+ if (matchesKey(data, "space") || data === "x" || data === "X") {
915
+ if (currentNode) {
916
+ this.toggleNodeSelection(currentNode);
917
+ }
918
+ return;
919
+ }
920
+
921
+ if (matchesKey(data, "return")) {
922
+ if (currentNode) {
923
+ if (currentNode.isDir) {
924
+ currentNode.expanded = !currentNode.expanded;
925
+ this.tui?.requestRender?.();
926
+ } else {
927
+ this.toggleNodeSelection(currentNode);
928
+ }
929
+ }
930
+ }
931
+ }
932
+
933
+ private finishModal(action: "select" | "reindex" | "close", selectedProfile?: SearchProfile): void {
934
+ // 1. Commit any changes from Tab 0 Settings
935
+ this.applySettingsChanges();
936
+
937
+ // 2. Commit any changes from Tab 1 Retrieval Mode
938
+ const currentProfile = this.index?.getProfile ? this.index.getProfile() : this.initialProfile;
939
+ const profileChanged = selectedProfile !== undefined && selectedProfile !== this.initialProfile;
940
+
941
+ // 3. Commit any changes from Tab 2 Scope
942
+ const hasScopeChanges = this.hasExcludedPathsChanged();
943
+ if (hasScopeChanges) {
944
+ if (this.index?.setExcludedPaths) {
945
+ this.index.setExcludedPaths(this.excludedPaths);
946
+ }
947
+ try {
948
+ saveProjectKernelConfig(this.currentCwd, {
949
+ retrieval: { excluded_paths: Array.from(this.excludedPaths) },
950
+ });
951
+ this.options.deps?.invalidateConfig?.(this.currentCwd, this.options.ctx);
952
+ } catch (error) {
953
+ console.error("[agent-kernel] Failed to save excluded paths to project config:", error);
954
+ }
955
+ }
956
+
957
+ this.done({
958
+ action,
959
+ profile: selectedProfile || currentProfile,
960
+ reindexed: action === "reindex" || profileChanged,
961
+ excludedPathsChanged: hasScopeChanges,
962
+ });
143
963
  }
144
964
 
965
+ invalidate(): void {}
966
+
967
+ // =========================================================================
968
+ // RENDER DISPATCHER
969
+ // =========================================================================
145
970
  render(width: number): string[] {
146
- const cardWidth = Math.min(108, Math.max(20, width - 4));
147
- const innerW = Math.max(1, cardWidth - 2);
971
+ const lines: string[] = [];
972
+ const borderColor = (s: string) => (this.theme?.fg ? this.theme.fg("border", s) : `\x1b[38;5;240m${s}\x1b[0m`);
973
+
974
+ // Top dynamic border
975
+ lines.push(borderColor("─".repeat(Math.max(1, width))));
976
+ lines.push("");
977
+
978
+ // Tab Bar Header (3 Tabs)
979
+ const tab0Active = this.activeTab === 0;
980
+ const tab1Active = this.activeTab === 1;
981
+ const tab2Active = this.activeTab === 2;
982
+
983
+ const tab0Text = "Kernel Settings";
984
+ const tab1Text = "Retrieval Engine";
985
+ const tab2Text = "File Index Scope";
986
+
987
+ const tab0Rendered = tab0Active
988
+ ? (this.theme?.fg ? this.theme.fg("accent", this.theme.bold(tab0Text)) : `\x1b[1;36m${tab0Text}\x1b[0m`)
989
+ : (this.theme?.fg ? this.theme.fg("muted", tab0Text) : `\x1b[90m${tab0Text}\x1b[0m`);
990
+
991
+ const tab1Rendered = tab1Active
992
+ ? (this.theme?.fg ? this.theme.fg("accent", this.theme.bold(tab1Text)) : `\x1b[1;36m${tab1Text}\x1b[0m`)
993
+ : (this.theme?.fg ? this.theme.fg("muted", tab1Text) : `\x1b[90m${tab1Text}\x1b[0m`);
994
+
995
+ const tab2Rendered = tab2Active
996
+ ? (this.theme?.fg ? this.theme.fg("accent", this.theme.bold(tab2Text)) : `\x1b[1;36m${tab2Text}\x1b[0m`)
997
+ : (this.theme?.fg ? this.theme.fg("muted", tab2Text) : `\x1b[90m${tab2Text}\x1b[0m`);
998
+
999
+ const tabSep = this.theme?.fg ? this.theme.fg("dim", " │ ") : " │ ";
1000
+ lines.push(` ${tab0Rendered}${tabSep}${tab1Rendered}${tabSep}${tab2Rendered}`);
1001
+ lines.push("");
1002
+ lines.push(borderColor("─".repeat(Math.max(1, width))));
148
1003
 
149
- const pad = (s: string, len: number) => {
150
- const vis = visibleWidth(s);
151
- if (vis > len) {
152
- return truncateToWidth(s, len, "...");
1004
+ // ------------------ RENDER: TAB 0 (KERNEL SETTINGS) ------------------
1005
+ if (this.activeTab === 0) {
1006
+ lines.push(...this.searchInput.render(width, this.theme));
1007
+ lines.push("");
1008
+
1009
+ if (this.filteredSettingsItems.length === 0) {
1010
+ lines.push(this.theme?.fg ? this.theme.fg("dim", " No matching settings") : " No matching settings");
1011
+ lines.push("");
1012
+ lines.push(
1013
+ this.theme?.fg
1014
+ ? this.theme.fg("dim", " Type to search · Enter/Space to cycle · Esc to cancel")
1015
+ : " Type to search · Enter/Space to cycle · Esc to cancel",
1016
+ );
1017
+ lines.push(borderColor("─".repeat(Math.max(1, width))));
1018
+ return lines;
153
1019
  }
154
- return s + " ".repeat(Math.max(0, len - vis));
155
- };
156
1020
 
157
- // Signature Dark Slate / Charcoal Minimalist Theme Palette
158
- const reset = "\x1b[0m";
159
- const bgCard = "\x1b[48;5;234m"; // Dark charcoal matte card background
160
-
161
- // Clean Monochrome & Dark Slate Foreground Colors (TrueColor with fallback-safe ANSI escapes)
162
- const fgBorder = "\x1b[38;5;240m"; // Refined dark slate/gray border (#585858)
163
- const fgTitle = "\x1b[1;38;5;255m"; // Pure crisp white bold title
164
- const fgSubHeader = "\x1b[1;38;5;250m"; // Light silver bold for section headers (#bcbcbc)
165
- const fgActive = "\x1b[1;38;5;255m"; // Pure white highlight for active/selected item
166
- const fgSelected = "\x1b[38;5;252m"; // Crisp light gray for selected radios (#d0d0d0)
167
- const fgStatusReady = "\x1b[38;5;250m"; // Light slate for ready status
168
- const fgValue = "\x1b[38;5;252m"; // Crisp silver-gray for metrics and values
169
- const fgNotice = "\x1b[38;5;215m"; // Soft muted amber for download/sync alerts
170
- const fgMuted = "\x1b[38;5;245m"; // Mid slate gray (#8a8a8a) for labels
171
- const fgDim = "\x1b[38;5;239m"; // Dimmed charcoal gray (#4e4e4e) for secondary text and bullets
172
-
173
- const row = (content: string) =>
174
- bgCard + fgBorder + "│" + reset + bgCard + pad(content, innerW) + fgBorder + "│" + reset;
175
-
176
- const status = this.index.getStatus();
177
- const currentProfile = this.index.getProfile();
178
-
179
- // Determine semantic color for model status
180
- let modelColor = fgMuted;
181
- if (status.modelStatus.includes("Active in RAM")) {
182
- modelColor = fgActive;
183
- } else if (status.modelStatus.includes("Active (BM25")) {
184
- modelColor = fgStatusReady;
185
- } else if (status.modelStatus.includes("Cached on disk")) {
186
- modelColor = fgValue;
187
- } else if (status.modelStatus.includes("Not downloaded")) {
188
- modelColor = fgNotice;
189
- } else if (status.modelStatus === "Disabled") {
190
- modelColor = fgDim;
191
- }
192
-
193
- const cardLines: string[] = [];
194
-
195
- // Header
196
- cardLines.push(bgCard + fgBorder + `╭${"─".repeat(innerW)}╮` + reset);
197
- cardLines.push(row(` ${fgTitle}Codebase Retrieval Engine${reset}${bgCard} ${fgDim}(Hybrid AST & Vector)`));
198
- cardLines.push(bgCard + fgBorder + `├${"─".repeat(innerW)}┤` + reset);
199
-
200
- // Status section
201
- cardLines.push(row(` ${fgSubHeader}Status:`));
202
- cardLines.push(
203
- row(
204
- ` ${fgMuted}Engine : ${fgActive}${status.engineState}${fgMuted} (${fgValue}${status.pipelineDesc}${fgMuted})`
205
- )
206
- );
207
- cardLines.push(
208
- row(
209
- ` ${fgMuted}Default : ${fgTitle}${currentProfile.toUpperCase()}${fgMuted} ${fgDim}(~/.pi/agent/search_settings.json)`
210
- )
211
- );
212
- cardLines.push(
213
- row(
214
- ` ${fgMuted}Active : ${fgValue}${status.effectiveProfile.toUpperCase()}${fgMuted} (${fgDim}${status.hardwareInfo}${fgMuted})`
215
- )
216
- );
217
- cardLines.push(
218
- row(
219
- ` ${fgMuted}Index : ${fgValue}${status.chunkCount}${fgMuted} chunks in ${fgValue}${status.fileCount}${fgMuted} files | ${status.vectorCount > 0 ? fgValue : fgDim}${status.vectorCount} vectors`
220
- )
221
- );
222
- cardLines.push(
223
- row(
224
- ` ${fgMuted}Model : ${modelColor}${status.modelStatus}`
225
- )
226
- );
227
- cardLines.push(
228
- row(
229
- ` ${fgMuted}Memory : ${fgMuted}RSS ${fgValue}${status.rssMemoryMB} MB`
230
- )
231
- );
232
-
233
- cardLines.push(bgCard + fgBorder + `├${"─".repeat(innerW)}┤` + reset);
234
- cardLines.push(row(` ${fgSubHeader}Engine Profiles:`));
235
-
236
- // Render profile items
237
- for (let i = 0; i < this.items.length; i++) {
238
- const item = this.items[i];
239
- if (item.category === "profile") {
240
- const isSelected = i === this.selectedIndex;
241
- const isCurrentProfile = item.profile === currentProfile;
242
-
243
- const cursor = isSelected ? `${fgTitle} > ` : " ";
244
- const radio = isCurrentProfile ? `${fgSelected}[x]` : `${fgDim}[ ]`;
1021
+ const maxLabelWidth = Math.min(
1022
+ 38,
1023
+ Math.max(...this.filteredSettingsItems.map((i) => visibleWidth(i.label))),
1024
+ );
1025
+ let currentCat: string | null = null;
1026
+
1027
+ for (let i = 0; i < this.filteredSettingsItems.length; i++) {
1028
+ const item = this.filteredSettingsItems[i];
1029
+ if (item.category !== currentCat) {
1030
+ currentCat = item.category;
1031
+ if (lines.length > 5) lines.push("");
1032
+ const catHeader = this.theme?.fg
1033
+ ? this.theme.fg("accent", this.theme.bold(`[${currentCat}]`))
1034
+ : `\x1b[1;34m[${currentCat}]\x1b[0m`;
1035
+ lines.push(` ${catHeader}`);
1036
+ }
1037
+ const isSelected = i === this.settingsSelectedIndex;
1038
+ const cursor = isSelected
1039
+ ? (this.theme?.fg ? ` ${this.theme.fg("accent", "→ ")}` : " \x1b[36m→ \x1b[0m")
1040
+ : " ";
1041
+ const labelPadded =
1042
+ item.label + " ".repeat(Math.max(0, maxLabelWidth - visibleWidth(item.label)));
1043
+ const labelText = isSelected
1044
+ ? (this.theme?.fg ? this.theme.fg("accent", labelPadded) : `\x1b[36m${labelPadded}\x1b[0m`)
1045
+ : labelPadded;
1046
+
1047
+ const separator = " ";
1048
+ const prefixWidth = visibleWidth(cursor);
1049
+ const usedWidth = prefixWidth + maxLabelWidth + visibleWidth(separator);
1050
+ const valueMaxWidth = Math.max(10, width - usedWidth - 2);
1051
+ const truncatedVal = truncateToWidth(item.currentValue, valueMaxWidth, "");
1052
+
1053
+ let valueText: string;
1054
+ if (item.isGlobal) {
1055
+ const yellowStr = this.theme?.fg
1056
+ ? this.theme.fg("warning", truncatedVal)
1057
+ : `\x1b[33m${truncatedVal}\x1b[0m`;
1058
+ valueText = isSelected
1059
+ ? (this.theme?.fg ? this.theme.bold(yellowStr) : `\x1b[1;33m${truncatedVal}\x1b[0m`)
1060
+ : yellowStr;
1061
+ } else {
1062
+ valueText = isSelected
1063
+ ? (this.theme?.fg ? this.theme.fg("accent", truncatedVal) : `\x1b[36m${truncatedVal}\x1b[0m`)
1064
+ : (this.theme?.fg ? this.theme.fg("muted", truncatedVal) : `\x1b[90m${truncatedVal}\x1b[0m`);
1065
+ }
1066
+
1067
+ lines.push(truncateToWidth(cursor + labelText + separator + valueText, width));
1068
+ }
1069
+
1070
+ const selectedItem = this.filteredSettingsItems[this.settingsSelectedIndex];
1071
+ const currentDesc = selectedItem?.descriptions?.[selectedItem.currentValue] || "";
1072
+ if (currentDesc) {
1073
+ lines.push("");
1074
+ const wrapped = wrapTextWithAnsi(currentDesc, width - 6);
1075
+ for (const line of wrapped) {
1076
+ lines.push(this.theme?.fg ? ` ${this.theme.fg("dim", line)}` : ` \x1b[2m${line}\x1b[0m`);
1077
+ }
1078
+ }
1079
+
1080
+ lines.push("");
1081
+ const hintText = " Type search · Enter/Space cycle · G toggle global · Tab next tab · Esc close & apply";
1082
+ lines.push(this.theme?.fg ? this.theme.fg("dim", hintText) : `\x1b[2m${hintText}\x1b[0m`);
1083
+ lines.push(borderColor("─".repeat(Math.max(1, width))));
1084
+ return lines;
1085
+ }
1086
+
1087
+ // ------------------ RENDER: TAB 1 (RETRIEVAL ENGINE) ------------------
1088
+ if (this.activeTab === 1) {
1089
+ const status = this.index?.getStatus ? this.index.getStatus() : {
1090
+ engineState: "ready",
1091
+ pipelineDesc: "BM25",
1092
+ effectiveProfile: "lean",
1093
+ chunkCount: 0,
1094
+ fileCount: 0,
1095
+ vectorCount: 0,
1096
+ rssMemoryMB: 0,
1097
+ hardwareInfo: "",
1098
+ isModelCached: false,
1099
+ modelStatus: "ready",
1100
+ };
1101
+ const currentProfile = this.index?.getProfile ? this.index.getProfile() : this.initialProfile;
1102
+
1103
+ const title = this.theme?.fg
1104
+ ? this.theme.fg("accent", this.theme.bold("Codebase Retrieval Engine"))
1105
+ : "\x1b[1;36mCodebase Retrieval Engine\x1b[0m";
1106
+ lines.push(` ${title}`);
1107
+
1108
+ const statusParts = [
1109
+ `Status: ${status.engineState}`,
1110
+ `Active: ${status.effectiveProfile.toUpperCase()}`,
1111
+ `${status.chunkCount} chunks in ${status.fileCount} files`,
1112
+ ];
1113
+ if (status.vectorCount > 0) statusParts.push(`${status.vectorCount} vectors`);
1114
+ statusParts.push(`RSS ${status.rssMemoryMB} MB`);
1115
+ const statusSummary = statusParts.join(" · ");
1116
+ lines.push(this.theme?.fg ? ` ${this.theme.fg("muted", statusSummary)}` : ` \x1b[90m${statusSummary}\x1b[0m`);
1117
+ lines.push("");
1118
+
1119
+ let currentCat: string | null = null;
1120
+ const maxLabelWidth = 22;
1121
+
1122
+ for (let i = 0; i < this.profileItems.length; i++) {
1123
+ const item = this.profileItems[i];
1124
+ const catLabel = item.category === "profile" ? "Engine Profiles" : "Workspace Actions";
1125
+ if (catLabel !== currentCat) {
1126
+ currentCat = catLabel;
1127
+ if (lines.length > 7) lines.push("");
1128
+ const catHeader = this.theme?.fg
1129
+ ? this.theme.fg("accent", this.theme.bold(`[${currentCat}]`))
1130
+ : `\x1b[1;34m[${currentCat}]\x1b[0m`;
1131
+ lines.push(` ${catHeader}`);
1132
+ }
1133
+
1134
+ const isSelected = i === this.profileSelectedIndex;
1135
+ const isCurrentProfile =
1136
+ item.category === "profile" &&
1137
+ item.profile === (currentProfile === "hybrid" ? "full" : currentProfile);
1138
+
1139
+ const cursor = isSelected
1140
+ ? (this.theme?.fg ? ` ${this.theme.fg("accent", "→ ")}` : " \x1b[36m→ \x1b[0m")
1141
+ : " ";
245
1142
 
1143
+ let indicator = " ";
1144
+ if (item.category === "profile") {
1145
+ indicator = isCurrentProfile
1146
+ ? (this.theme?.fg ? this.theme.fg("accent", "◉") : "\x1b[36m◉\x1b[0m")
1147
+ : (this.theme?.fg ? this.theme.fg("muted", "○") : "\x1b[90m○\x1b[0m");
1148
+ } else {
1149
+ indicator = item.id === "reindex"
1150
+ ? (this.theme?.fg ? this.theme.fg("accent", "↺") : "\x1b[36m↺\x1b[0m")
1151
+ : (this.theme?.fg ? this.theme.fg("dim", "✕") : "\x1b[2m✕\x1b[0m");
1152
+ }
1153
+
1154
+ const labelPadded = item.label + " ".repeat(Math.max(0, maxLabelWidth - visibleWidth(item.label)));
246
1155
  const labelText = isSelected
247
- ? `${fgActive}${item.label}`
248
- : isCurrentProfile
249
- ? `${fgSelected}${item.label}`
250
- : `${fgMuted}${item.label}`;
1156
+ ? (this.theme?.fg ? this.theme.fg("accent", labelPadded) : `\x1b[36m${labelPadded}\x1b[0m`)
1157
+ : labelPadded;
251
1158
 
252
1159
  let descExtra = "";
253
- if (item.profile === "hybrid" || item.profile === "full") {
1160
+ if (item.profile === "full") {
254
1161
  if (!status.isModelCached) {
255
- descExtra = ` ${fgNotice}(Not downloaded, ~135 MB)`;
1162
+ descExtra = this.theme?.fg ? ` ${this.theme.fg("warning", "(~147 MB download)")}` : " (~147 MB download)";
256
1163
  } else {
257
- descExtra = ` ${fgStatusReady}(ready)`;
1164
+ descExtra = this.theme?.fg ? ` ${this.theme.fg("success", "(ready)")}` : " (ready)";
258
1165
  }
259
1166
  }
260
1167
 
261
- const descText = `${fgDim}- ${item.desc}${descExtra}`;
262
- const lineStr = `${cursor}${radio} ${labelText} ${descText}`;
1168
+ const descStr = `${item.desc}${descExtra}`;
1169
+ const descText = this.theme?.fg ? this.theme.fg("dim", descStr) : `\x1b[2m${descStr}\x1b[0m`;
263
1170
 
264
- cardLines.push(row(lineStr));
1171
+ const lineContent = `${cursor}${indicator} ${labelText} ${descText}`;
1172
+ lines.push(truncateToWidth(lineContent, width));
265
1173
  }
266
- }
267
1174
 
268
- cardLines.push(bgCard + fgBorder + `├${"─".repeat(innerW)}┤` + reset);
269
- cardLines.push(row(` ${fgSubHeader}Workspace Actions:`));
1175
+ const selected = this.profileItems[this.profileSelectedIndex];
1176
+ if (selected) {
1177
+ lines.push("");
1178
+ let detailText = selected.desc;
1179
+ if (selected.id === "auto") {
1180
+ detailText = `Auto-detect: selects Lean on machines with < 4 CPUs, or Full on machines with >= 4 CPUs (detected: ${status.hardwareInfo}).`;
1181
+ } else if (selected.id === "lean") {
1182
+ detailText = "Lean mode: fast AST BM25 lexical keyword search. Uses 0% CPU background overhead and 0 MB extra RAM.";
1183
+ } else if (selected.id === "full") {
1184
+ detailText = `Full mode: hybrid AST BM25 + 768-dim vector embeddings (Alibaba-NLP/gte-modernbert-base). Model status: ${status.modelStatus}.`;
1185
+ } else if (selected.id === "off") {
1186
+ detailText = "Disable engine: unloads code search index and embeddings from memory, removing code_search from active tools.";
1187
+ } else if (selected.id === "reindex") {
1188
+ detailText = "Re-index workspace: clears cached AST chunks and vector embeddings, rescanning all workspace source files.";
1189
+ } else if (selected.id === "close") {
1190
+ detailText = "Close panel: dismisses this settings dialog without making further changes.";
1191
+ }
270
1192
 
271
- // Render action items
272
- for (let i = 0; i < this.items.length; i++) {
273
- const item = this.items[i];
274
- if (item.category === "action") {
275
- const isSelected = i === this.selectedIndex;
276
- const cursor = isSelected ? `${fgTitle} > ` : " ";
277
- const bullet = `${fgDim}[-]`;
1193
+ const wrapped = wrapTextWithAnsi(detailText, width - 6);
1194
+ for (const w of wrapped) {
1195
+ lines.push(this.theme?.fg ? ` ${this.theme.fg("dim", w)}` : ` \x1b[2m${w}\x1b[0m`);
1196
+ }
1197
+ }
278
1198
 
279
- const labelText = isSelected
280
- ? `${fgActive}${item.label}`
281
- : `${fgMuted}${item.label}`;
1199
+ lines.push("");
1200
+ const hintText = " ↑/↓: navigate · Enter/Space: select · Tab: next tab · Esc: close & apply";
1201
+ lines.push(this.theme?.fg ? this.theme.fg("dim", hintText) : `\x1b[2m${hintText}\x1b[0m`);
1202
+ lines.push(borderColor("─".repeat(Math.max(1, width))));
1203
+ return lines;
1204
+ }
282
1205
 
283
- const descText = `${fgDim}- ${item.desc}`;
284
- const lineStr = `${cursor}${bullet} ${labelText} ${descText}`;
1206
+ // ------------------ RENDER: TAB 2 (FILE INDEX SCOPE) ------------------
1207
+ const visibleNodes = this.getVisibleTreeNodes();
285
1208
 
286
- cardLines.push(row(lineStr));
287
- }
1209
+ let totalIndexedFiles = 0;
1210
+ let totalIndexedChunks = 0;
1211
+ for (const root of this.treeRoots) {
1212
+ const countActive = (n: ScopeTreeNode) => {
1213
+ for (const c of n.children) {
1214
+ if (c.isDir) {
1215
+ countActive(c);
1216
+ } else if (!this.isPathExcluded(c.relPath)) {
1217
+ totalIndexedFiles++;
1218
+ totalIndexedChunks += c.chunkCount;
1219
+ }
1220
+ }
1221
+ };
1222
+ countActive(root);
288
1223
  }
289
1224
 
290
- cardLines.push(bgCard + fgBorder + `├${"─".repeat(innerW)}┤` + reset);
291
- cardLines.push(
292
- row(
293
- ` ${fgDim}Up/Down: Navigate | Enter: Select/Toggle | Esc: Close`
294
- )
295
- );
296
- cardLines.push(bgCard + fgBorder + `╰${"─".repeat(innerW)}╯` + reset);
1225
+ const scopeHeader = this.theme?.fg
1226
+ ? this.theme.fg("accent", this.theme.bold("Workspace Index Scope"))
1227
+ : "\x1b[1;36mWorkspace Index Scope\x1b[0m";
1228
+ const scopeStats = `${totalIndexedFiles} files selected · ${totalIndexedChunks} chunks indexed`;
1229
+ lines.push(` ${scopeHeader} ${this.theme?.fg ? this.theme.fg("muted", `(${scopeStats})`) : `(${scopeStats})`}`);
1230
+ lines.push("");
297
1231
 
298
- // Terminal height resolution for full-viewport coverage
299
- const termHeight =
300
- this.tui?.terminal?.rows ||
301
- (process.stdout && process.stdout.rows ? process.stdout.rows : 24);
1232
+ if (visibleNodes.length === 0) {
1233
+ lines.push(this.theme?.fg ? this.theme.fg("muted", " No indexable source code files found in workspace.") : " No indexable source code files found in workspace.");
1234
+ } else {
1235
+ if (this.treeCursorIndex >= visibleNodes.length) {
1236
+ this.treeCursorIndex = Math.max(0, visibleNodes.length - 1);
1237
+ }
1238
+ const maxVisibleRows = 10;
1239
+ if (this.treeCursorIndex < this.treeScrollOffset) {
1240
+ this.treeScrollOffset = this.treeCursorIndex;
1241
+ } else if (this.treeCursorIndex >= this.treeScrollOffset + maxVisibleRows) {
1242
+ this.treeScrollOffset = Math.max(0, this.treeCursorIndex - maxVisibleRows + 1);
1243
+ }
302
1244
 
303
- // Layout calculations for full-screen backdrop framing
304
- const leftPad = Math.max(0, Math.floor((width - cardWidth) / 2));
305
- const rightPad = Math.max(0, width - cardWidth - leftPad);
1245
+ const visibleSlice = visibleNodes.slice(this.treeScrollOffset, this.treeScrollOffset + maxVisibleRows);
306
1246
 
307
- // Dark monochrome backdrop: deep black background with dark gray stippling
308
- const scrim = (len: number) =>
309
- len <= 0 ? "" : "\x1b[48;5;232m\x1b[38;5;234m" + "░".repeat(len) + reset;
1247
+ if (this.treeScrollOffset > 0) {
1248
+ lines.push(this.theme?.fg ? this.theme.fg("dim", ` ▲ +${this.treeScrollOffset} more above`) : ` ▲ +${this.treeScrollOffset} more above`);
1249
+ }
310
1250
 
311
- // Deep dark right drop shadow
312
- const shadowRight = (len: number) => {
313
- if (len <= 0) return "";
314
- return "\x1b[48;5;232m\x1b[38;5;233m▌" + reset + scrim(len - 1);
315
- };
1251
+ for (let i = 0; i < visibleSlice.length; i++) {
1252
+ const node = visibleSlice[i];
1253
+ const absoluteIndex = this.treeScrollOffset + i;
1254
+ const isCursor = absoluteIndex === this.treeCursorIndex;
316
1255
 
317
- // Deep dark bottom drop shadow
318
- const shadowBottom = (left: number, card: number, right: number) => {
319
- return (
320
- scrim(left) +
321
- "\x1b[48;5;232m\x1b[38;5;233m" +
322
- "▀".repeat(card) +
323
- reset +
324
- scrim(right)
325
- );
326
- };
1256
+ const cursor = isCursor
1257
+ ? (this.theme?.fg ? ` ${this.theme.fg("accent", "→ ")}` : " \x1b[36m→ \x1b[0m")
1258
+ : " ";
327
1259
 
328
- const totalCardRows = cardLines.length + 1; // Card lines + bottom shadow row
329
- const topPad = Math.max(0, Math.floor((termHeight - totalCardRows) / 2));
330
- const bottomPad = Math.max(0, termHeight - totalCardRows - topPad);
1260
+ let checkbox = "□ ";
1261
+ if (!node.isDir) {
1262
+ const isExcluded = this.isPathExcluded(node.relPath);
1263
+ checkbox = isExcluded
1264
+ ? (this.theme?.fg ? `${this.theme.fg("muted", "□")} ` : "□ ")
1265
+ : (this.theme?.fg ? `${this.theme.fg("accent", "■")} ` : "■ ");
1266
+ } else {
1267
+ const state = this.getFolderSelectionState(node);
1268
+ if (state === "all") {
1269
+ checkbox = this.theme?.fg ? `${this.theme.fg("accent", "■")} ` : "■ ";
1270
+ } else if (state === "some") {
1271
+ checkbox = this.theme?.fg ? `${this.theme.fg("warning", "◪")} ` : "◪ ";
1272
+ } else {
1273
+ checkbox = this.theme?.fg ? `${this.theme.fg("muted", "□")} ` : "□ ";
1274
+ }
1275
+ }
331
1276
 
332
- const fullLines: string[] = [];
1277
+ const expandGlyph = node.isDir
1278
+ ? (node.expanded ? "▾ " : "▸ ")
1279
+ : " ";
333
1280
 
334
- // Top backdrop scrim rows to fill viewport from top down to modal
335
- for (let i = 0; i < topPad; i++) {
336
- fullLines.push(scrim(width));
337
- }
1281
+ const indent = " ".repeat(node.depth);
1282
+ const nameStr = node.isDir ? `${node.name}/` : node.name;
1283
+ const labelText = isCursor
1284
+ ? (this.theme?.fg ? this.theme.fg("accent", nameStr) : `\x1b[36m${nameStr}\x1b[0m`)
1285
+ : (node.isDir ? (this.theme?.fg ? this.theme.bold(nameStr) : nameStr) : nameStr);
1286
+
1287
+ let badgeStr = "";
1288
+ if (node.isDir) {
1289
+ badgeStr = `(${node.chunkCount} chunks · ${node.fileCount} files)`;
1290
+ } else {
1291
+ badgeStr = `(${node.chunkCount} chunk${node.chunkCount === 1 ? "" : "s"})`;
1292
+ }
1293
+ const badgeText = this.theme?.fg ? this.theme.fg("dim", badgeStr) : `\x1b[2m${badgeStr}\x1b[0m`;
1294
+
1295
+ const rowLine = `${cursor}${checkbox} ${indent}${expandGlyph}${labelText} ${badgeText}`;
1296
+ lines.push(truncateToWidth(rowLine, width));
1297
+ }
338
1298
 
339
- // Centered card rows with left/right scrim and right shadow
340
- for (let i = 0; i < cardLines.length; i++) {
341
- const line = scrim(leftPad) + cardLines[i] + shadowRight(rightPad);
342
- fullLines.push(line);
1299
+ const remainingBelow = visibleNodes.length - (this.treeScrollOffset + visibleSlice.length);
1300
+ if (remainingBelow > 0) {
1301
+ lines.push(this.theme?.fg ? this.theme.fg("dim", ` ▼ +${remainingBelow} more below`) : ` ▼ +${remainingBelow} more below`);
1302
+ }
343
1303
  }
344
1304
 
345
- // Bottom shadow row
346
- fullLines.push(shadowBottom(leftPad, cardWidth, rightPad));
1305
+ const currentNode = visibleNodes[this.treeCursorIndex];
1306
+ if (currentNode) {
1307
+ lines.push("");
1308
+ if (!currentNode.isDir) {
1309
+ const isExcluded = this.isPathExcluded(currentNode.relPath);
1310
+ const statusTag = isExcluded
1311
+ ? (this.theme?.fg ? this.theme.fg("warning", "EXCLUDED") : "EXCLUDED")
1312
+ : (this.theme?.fg ? this.theme.fg("success", "INDEXED") : "INDEXED");
1313
+
1314
+ const previewTitle = this.theme?.fg
1315
+ ? this.theme.fg("accent", `Preview: ${currentNode.relPath}`)
1316
+ : `Preview: ${currentNode.relPath}`;
1317
+ lines.push(` ${previewTitle} ${this.theme?.fg ? this.theme.fg("dim", `[${statusTag}]`) : `[${statusTag}]`}`);
347
1318
 
348
- // Bottom backdrop scrim rows to fill viewport down to bottom edge
349
- for (let i = 0; i < bottomPad; i++) {
350
- fullLines.push(scrim(width));
1319
+ const previewDetail = `Will produce ${currentNode.chunkCount} code chunk(s) (functions, classes, semantic AST blocks)`;
1320
+ lines.push(this.theme?.fg ? ` ${this.theme.fg("dim", previewDetail)}` : ` \x1b[2m${previewDetail}\x1b[0m`);
1321
+ } else {
1322
+ const state = this.getFolderSelectionState(currentNode);
1323
+ const stateText = state === "all" ? "ALL INCLUDED" : state === "some" ? "PARTIALLY INCLUDED" : "ALL EXCLUDED";
1324
+ const previewTitle = this.theme?.fg
1325
+ ? this.theme.fg("accent", `Preview Folder: ${currentNode.relPath}/`)
1326
+ : `Preview Folder: ${currentNode.relPath}/`;
1327
+ lines.push(` ${previewTitle} ${this.theme?.fg ? this.theme.fg("dim", `[${stateText}]`) : `[${stateText}]`}`);
1328
+
1329
+ const previewDetail = `Contains ${currentNode.fileCount} code file(s) across this directory tree (${currentNode.chunkCount} total chunks)`;
1330
+ lines.push(this.theme?.fg ? ` ${this.theme.fg("dim", previewDetail)}` : ` \x1b[2m${previewDetail}\x1b[0m`);
1331
+ }
351
1332
  }
352
1333
 
353
- return fullLines;
354
- }
1334
+ lines.push("");
1335
+ const hintText = " ↑/↓: navigate · Space: toggle [x] · Enter/→: expand · Tab: next tab · Esc: close & apply";
1336
+ lines.push(this.theme?.fg ? this.theme.fg("dim", hintText) : `\x1b[2m${hintText}\x1b[0m`);
1337
+ lines.push(borderColor("─".repeat(Math.max(1, width))));
355
1338
 
356
- invalidate(): void {}
357
- dispose(): void {}
1339
+ return lines;
1340
+ }
358
1341
  }
1342
+
1343
+ // Backwards-compatible export alias for any legacy callers
1344
+ export { UnifiedControlModal as SearchControlModal };