-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.lua
More file actions
757 lines (660 loc) · 26.3 KB
/
Copy pathconfig.lua
File metadata and controls
757 lines (660 loc) · 26.3 KB
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
--[[
================================================================================
CONFIGURATION MODULE - PROVIDER-AGNOSTIC REFACTORING GUIDE
================================================================================
PURPOSE:
Manages layered configuration with defaults, user overrides, project overrides,
and environment variables. Validates structure and provides merged configuration
to all subsystems.
ARCHITECTURAL PRINCIPLES:
1. Configuration is data, not behavior
2. Provider-specific config is isolated in services.* sections
3. Core config is provider-agnostic
4. Validation catches errors early
5. No business logic in config
CURRENT ARCHITECTURAL VIOLATIONS:
☐ Auto mode logic embedded in config (should be in protocol layer)
☐ Provider-specific defaults mixed with core defaults
☐ No schema validation (only structure validation)
REQUIRED REFACTORING:
1. SEPARATE CONCERNS (Priority: MEDIUM)
CURRENT: Config module handles auto-mode handler enabling
LINES: 296-336 in _load_config()
ISSUE: Configuration should not modify handler enabled flags
SHOULD: Protocol layer decides which handlers to initialize
SPLIT:
- Config: Loads and merges user preferences
- Protocol: Interprets "auto" mode and enables handlers
2. ADD SCHEMA VALIDATION (Priority: LOW)
CURRENT: Basic nil checks and type assertions
SHOULD: Full JSON-schema style validation
- Required fields
- Type checking (string, number, boolean, table)
- Enum validation (mode must be "auto"|"claude"|"opencode"|etc)
- Range validation (timeout > 0, port in valid range)
- Custom validators (path exists, etc)
3. DOCUMENT PROVIDER CONFIG SECTIONS (Priority: HIGH)
Each services.* section should document:
- Which handler uses it
- What each option does
- Valid value ranges
- Provider-specific vs shared options
PROVIDER-SPECIFIC VS GENERIC CONFIGURATION:
GENERIC (core plugin config):
- services.default: Which provider to use
- services.fallback: Try others if primary fails
- services.timeout: Global connection timeout
- diff.*: Core diff display options
- logging.*: Log file and level
- ui.*: UI behavior (immersive, selection tracking)
- terminal.*: Tmux integration settings
PROVIDER-SPECIFIC (services.* subsections):
- services.claude.*: Claude Code MCP config
- discovery_timeout: Lock file scanning
- clear_before_ide: Tmux /ide workflow
- tools: MCP tool whitelist
- diff.force_blocking: Claude requires blocking diffs
- services.opencode.*: OpenCode HTTP/SSE config
- port: Explicit port (nil = auto-discover)
- auto_reconnect: Reconnect SSE on heartbeat timeout
- diff.*: OpenCode-specific diff options
- services.gemini.*: Gemini config (not yet implemented)
- services.codex.*: Codex config (not yet implemented)
CONFIGURATION LAYERS (priority order, highest wins):
1. Defaults (in this file)
- Sensible defaults for all options
- Documented inline
2. Project config (.diffusion.lua in project root)
- Project-specific overrides
- Checked into version control
- Loaded via _apply_project_config()
3. User config (passed to setup())
- User's init.lua configuration
- Highest priority for user preferences
- Merged in _load_config()
4. Runtime overrides (not yet implemented)
- :DiffusionConfig command
- Temporary session overrides
- Not persisted
AUTO MODE CONFIGURATION DETAILS:
Current Implementation (lines 296-336):
- When services.default = "auto"
- Auto-enables claude.enabled = true
- Auto-enables opencode.enabled = true
- Unless user explicitly set enabled = false
Issues:
- Config module shouldn't change handler enabled flags
- Violates separation of concerns
- Protocol layer should handle auto-detection
Correct Approach:
- Config: Just store services.default = "auto"
- Protocol: Read config.services.default
- Protocol: If "auto", call each handler.is_available()
- Protocol: Enable first available handler
- Protocol: User explicit enabled flags still respected
REFACTORING CHECKLIST:
☐ Move auto-mode logic from config to protocol layer
☐ Document all provider-specific config options
☐ Add schema validation with helpful error messages
☐ Extract config merging logic to separate function
☐ Add config validation tests
☐ Document configuration layer priority
☐ Update this header as refactoring progresses
NOTE: This header must be updated as each refactoring task is completed.
Mark checkboxes with ☑ when done.
================================================================================
--]]
-- Configuration management for diffusion.nvim
-- Handles layered configuration with validation and defaults
local Config = {}
Config._instance = nil
-- Default configuration
local defaults = {
-- Service configuration
services = {
-- Auto-detection mode: automatically detect and use available AI service
-- "auto": Check for active Claude or OpenCode connections and use the first available
-- Priority order: Claude -> Gemini -> OpenCode -> Codex
-- When "auto" is set, both Claude and OpenCode handlers are enabled automatically
-- The system checks for actual availability (lock files, running servers, etc.)
-- "claude": Explicitly use Claude Code (must be enabled)
-- "opencode": Explicitly use OpenCode (must be enabled)
-- "gemini": Explicitly use Gemini (must be enabled)
-- "codex": Explicitly use Codex (must be enabled)
default = "auto",
fallback = true, -- Try other service if primary fails
timeout = 30000, -- Connection timeout (ms)
retry_attempts = 3, -- Number of retry attempts
-- When false (default), only one MCP-WebSocket provider (claude/codex/pi)
-- may have an active client connection at a time. The first to connect
-- claims the slot; others receive HTTP 503 at the WS handshake until the
-- owner disconnects. When true, all enabled providers can be connected
-- concurrently (the legacy behavior).
allow_multiple_providers = false,
claude = {
enabled = false, -- Disabled by default - user must explicitly enable
discovery_timeout = 5000, -- Lock file discovery timeout
tmux = {
auto_reconnect = true, -- Send /ide to Claude pane on startup
clear_before_ide = true, -- Send Ctrl-C before /ide to clear input
focus_after_send = false, -- Navigate to Claude pane after send_message/send_selection
},
tools = { -- Enabled MCP tools
"openFile",
"openDiff",
"showDiff",
"dismissDiff",
"closeAllDiffTabs",
"getCurrentSelection",
"saveDocument",
"getDiagnostics"
},
diff = {
force_blocking = true, -- Claude requires blocking
winbar_style = "claude_branded", -- Show Claude-branded winbar
auto_navigate = true, -- Auto-navigate after save
context_lines = 3, -- Minimal context for Claude
highlight_duration_ms = 2000, -- Shorter highlight duration
concurrent_limit = 3, -- Conservative limit for Claude
timeout_ms = 30000 -- Claude MCP timeout
}
},
opencode = {
enabled = true,
-- HTTP/SSE connection configuration
-- OpenCode must be started with --port <N> to expose its HTTP server
port = nil, -- Explicit port (nil = auto-discover via pgrep+lsof)
auto_reconnect = true, -- Reconnect SSE if heartbeat times out
api_timeout = 5, -- HTTP request timeout in seconds
tools = {
"openFile",
"showDiff",
"dismissDiff",
"getCurrentSelection",
"saveDocument"
},
diff = {
force_blocking = false, -- OpenCode uses events, not blocking
supports_streaming = true, -- Real-time content updates via SSE
concurrent_limit = 10, -- Higher concurrency than Claude
winbar_style = "opencode_clean", -- Minimal, clean styling
auto_dismiss = true, -- Auto-dismiss on permission.replied
context_lines = 5, -- More context for review
highlight_duration_ms = 3000 -- Standard highlight duration
}
},
gemini = {
enabled = false, -- Disabled by default, user must enable
discovery_timeout = 5000, -- Port discovery timeout
auto_reconnection = true, -- Enable automatic reconnection
connection = {
host = "localhost",
port_range = {3000, 3100},
timeout = 5000,
retry_attempts = 3
},
tools = { -- Enabled MCP tools
"openDiff",
"closeDiff",
"openFile",
"saveDocument",
"getCurrentSelection",
"getOpenEditors",
"getDiagnostics"
},
diff = {
force_blocking = true, -- Gemini uses blocking like Claude
winbar_style = "gemini_branded", -- Show Gemini-branded winbar
auto_navigate = true, -- Auto-navigate after save
context_lines = 3, -- Minimal context for Gemini
highlight_duration_ms = 2000, -- Shorter highlight duration
concurrent_limit = 5, -- Moderate limit for Gemini
timeout_ms = 30000, -- Gemini MCP timeout
preview_mode = true -- Always preview diffs
},
adapter = {
tool_timeout = 10000,
retry_attempts = 3,
cache_file_content = true
}
},
codex = {
enabled = true,
discovery_timeout = 5000,
tools = { -- Enabled MCP tools
"openFile",
"openDiff",
"showDiff",
"dismissDiff",
"getCurrentSelection",
"saveDocument",
"getDiagnostics"
},
diff = {
adaptive_blocking = true, -- Block only for HTTP mode
fallback_polling = true, -- Poll for updates if needed
winbar_style = "codex_minimal", -- Simple status display
batch_updates = true, -- Batch multiple updates
timeout_ms = 15000, -- Longer timeout for HTTP
concurrent_limit = 5, -- Moderate concurrency
context_lines = 4 -- Standard context
}
},
pi = {
enabled = false, -- Opt-in; requires pi-diffusion-bridge extension
discovery_timeout = 5000,
-- Tool registry is owned by protocol/mcp/tools.lua; per-service tool
-- allow-lists are not honored.
diff = {
force_blocking = true, -- Block until user accepts/rejects
winbar_style = "pi_minimal",
timeout_ms = 30000,
concurrent_limit = 3,
context_lines = 3
}
}
},
-- Provider behavior configuration (provider-agnostic switches)
providers = {
default = {
file_operations = "internal", -- internal|external
diff_dismissal = "auto", -- manual|auto
response_mode = "immediate", -- immediate|deferred
navigation_trigger = "on_accept", -- on_accept|on_dismiss|never
handle_file_operations = true
},
claude = {
file_operations = "external",
diff_dismissal = "manual",
response_mode = "deferred",
navigation_trigger = "on_dismiss",
handle_file_operations = false
},
opencode = {
file_operations = "external", -- OpenCode edits files directly
diff_dismissal = "auto", -- Auto-dismiss on permission.replied event
response_mode = "immediate", -- Send accept/reject right away via HTTP
navigation_trigger = "on_dismiss", -- Navigate when diff is dismissed
handle_file_operations = false -- We don't write - OpenCode does
},
codex = {
file_operations = "internal",
diff_dismissal = "auto",
response_mode = "immediate",
navigation_trigger = "on_accept",
handle_file_operations = true
},
gemini = {
file_operations = "external",
diff_dismissal = "manual",
response_mode = "deferred",
navigation_trigger = "on_dismiss",
handle_file_operations = false
},
pi = {
file_operations = "external", -- Pi writes files after we approve
diff_dismissal = "manual",
response_mode = "deferred", -- Block MCP response until user decides
navigation_trigger = "on_dismiss",
handle_file_operations = false
}
},
-- WebSocket server configuration
server = {
host = "127.0.0.1", -- Server host (localhost only)
port_range = {10000, 65535}, -- Available port range
auth_timeout = 30000, -- Authentication timeout (ms)
max_connections = 10, -- Maximum concurrent connections
keepalive_interval = 30000 -- Ping interval (ms)
},
-- Diff system configuration
diff = {
-- Display Options
default_mode = "unified", -- "split" | "unified"
vertical_split = true, -- Use vertical splits
show_diff_stats = true, -- Show +/- counts in winbar
auto_balance_windows = true, -- Balance window sizes
-- Behavior Options
auto_close_on_accept = true, -- Close diff after accept
auto_close_on_reject = true, -- Close diff after reject
auto_navigate_on_accept = true, -- Auto-navigate to file after accept
follow_file_changes = false, -- Navigate to file after save
-- Visual Options
show_line_numbers = true, -- Absolute line numbers
context_lines = 4, -- Context before folding
highlight_changed_lines = true, -- Highlight after navigation
highlight_duration_ms = 3000, -- How long to highlight
-- Protocol Options
force_blocking = false, -- Force blocking mode always
concurrent_diffs = true, -- Allow multiple diffs
max_concurrent_diffs = 10, -- Limit concurrent diffs
-- Legacy Options (for backward compatibility)
mode = "tab", -- "tab", "split", "floating"
position = "right", -- "left", "right", "above", "below"
auto_accept = false, -- Auto-accept changes
show_controls = true, -- Show interactive controls
timeout = 30000, -- Response timeout (ms)
cleanup_delay = 5000, -- Cleanup delay after response (ms)
buffer_naming = "unique", -- "unique", "descriptive", "simple"
unified_enabled = true, -- Allow unified diff view
show_hints = true, -- Show key hints as virtual text
diff_cmd = "diff -u" -- External diff command for unified view
},
-- UI configuration
ui = {
immersive_mode = false, -- Enable immersive mode
selection_debounce = 50, -- Selection update debounce (ms)
show_notifications = true, -- Show status notifications
track_selections = true -- Track selection changes
},
-- Logging configuration
logging = {
enabled = true, -- Enable logging
level = "DEBUG", -- "DEBUG", "INFO", "WARN", "ERROR"
file = nil -- Log file path (nil = default)
},
-- Key mappings
keymaps = {
send_selection = '<leader>ds', -- Send selection to AI
send_file = '<leader>df', -- Send whole file
toggle_immersive = '<leader>di', -- Toggle immersive mode
accept_diff = '<CR>', -- Accept diff changes
reject_diff = '<Esc>' -- Reject diff changes
},
-- Terminal / tmux integration
terminal = {
mode = "auto", -- "auto", "native", "terminal", "tmux"
tmux = {
pane_reuse = true,
session_name_strategy = "cwd", -- or "fixed"
tmux_keymaps = true -- install default tmux pane nav maps
}
},
-- Auto-start plugin on setup
auto_start = true
}
function Config:new()
local instance = {
_config = nil,
_user_config = nil,
_project_config = nil
}
setmetatable(instance, { __index = self })
return instance
end
function Config:setup(user_config)
if Config._instance then
-- If called again with a non-empty config, update the stored user config
-- and reload. This prevents stale singletons from no-args setup() calls.
if user_config and next(user_config) then
Config._instance._user_config = user_config
local config = Config:_load_config()
Config._instance._config = config
return config
end
return Config._instance._config
end
Config._instance = self:new()
-- Store user config for reference
Config._instance._user_config = user_config or {}
-- Load layered configuration
local config = self:_load_config()
-- Validate configuration
local validation_result = self:_validate_config(config)
if not validation_result.valid then
error("Invalid configuration: " .. table.concat(validation_result.errors, ", "))
end
Config._instance._config = config
return config
end
function Config:_load_config()
local config = vim.deepcopy(defaults)
-- Layer 4: Environment variables
config = self:_apply_env_vars(config)
-- Layer 3: Project config
config = self:_apply_project_config(config)
-- Layer 2: User config
config = vim.tbl_deep_extend("force", config, Config._instance._user_config)
-- Post-processing: Enable both Claude and OpenCode when auto mode is selected
--
-- Auto-detection workflow:
-- 1. Enable both Claude and OpenCode handlers (unless user explicitly disabled them)
-- 2. At runtime, Protocol:detect_service() calls each handler's is_available() method
-- 3. Claude checks for lock files in ~/.claude/ide/ with active PIDs
-- 4. OpenCode checks for running HTTP servers via _find_servers()
-- 5. First available service in priority order is selected automatically
-- 6. If no service is actively available, fallback to first enabled handler
if config.services.default == "auto" then
-- Auto mode requires both handlers to be enabled for detection
-- Override only if not explicitly set by user
if Config._instance._user_config.services
and Config._instance._user_config.services.claude
and Config._instance._user_config.services.claude.enabled ~= nil then
-- User explicitly set claude.enabled, respect it
else
config.services.claude.enabled = true
end
if Config._instance._user_config.services
and Config._instance._user_config.services.opencode
and Config._instance._user_config.services.opencode.enabled ~= nil then
-- User explicitly set opencode.enabled, respect it
else
config.services.opencode.enabled = true
end
end
-- Layer 1: Runtime overrides (applied later as needed)
return config
end
function Config:_apply_env_vars(config)
-- Service default
if vim.env.DIFFUSION_DEFAULT_SERVICE then
config.services.default = vim.env.DIFFUSION_DEFAULT_SERVICE
end
-- OpenCode server URL
if vim.env.OPENCODE_SERVER_URL then
config.services.opencode.server_url = vim.env.OPENCODE_SERVER_URL
end
-- Logging level
if vim.env.DIFFUSION_LOG_LEVEL then
config.logging.level = vim.env.DIFFUSION_LOG_LEVEL
end
-- Diff default mode
if vim.env.DIFFUSION_DIFF_DEFAULT_MODE then
config.diff.default_mode = vim.env.DIFFUSION_DIFF_DEFAULT_MODE
end
-- Claude tmux settings from env
if vim.env.DIFFUSION_CLAUDE_TMUX_AUTO_RECONNECT then
config.services.claude.tmux.auto_reconnect = vim.env.DIFFUSION_CLAUDE_TMUX_AUTO_RECONNECT == "true"
end
if vim.env.DIFFUSION_CLAUDE_TMUX_CLEAR_BEFORE_IDE then
config.services.claude.tmux.clear_before_ide = vim.env.DIFFUSION_CLAUDE_TMUX_CLEAR_BEFORE_IDE == "true"
end
if vim.env.DIFFUSION_CLAUDE_TMUX_FOCUS_AFTER_SEND then
config.services.claude.tmux.focus_after_send = vim.env.DIFFUSION_CLAUDE_TMUX_FOCUS_AFTER_SEND == "true"
end
return config
end
function Config:_apply_project_config(config)
local project_config_paths = {
vim.fn.getcwd() .. "/.diffusion.lua",
vim.fn.getcwd() .. "/.diffusion.json"
}
for _, path in ipairs(project_config_paths) do
if vim.fn.filereadable(path) == 1 then
local success, project_config = pcall(function()
if vim.endswith(path, ".lua") then
return loadfile(path)()
else
local content = vim.fn.readfile(path)
return vim.fn.json_decode(table.concat(content, "\n"))
end
end)
if success and type(project_config) == "table" then
Config._instance._project_config = project_config
config = vim.tbl_deep_extend("force", config, project_config)
break
end
end
end
return config
end
function Config:_validate_config(config)
local result = { valid = true, errors = {} }
-- Validate services configuration
local valid_services = {"auto", "claude", "opencode", "codex", "gemini", "pi"}
if config.services.default and not vim.tbl_contains(valid_services, config.services.default) then
table.insert(result.errors, "services.default must be one of: " .. table.concat(valid_services, ", "))
result.valid = false
end
-- Validate enabled flags are booleans
for _, service in ipairs({"claude", "opencode", "codex", "gemini"}) do
if config.services[service] and config.services[service].enabled ~= nil then
if type(config.services[service].enabled) ~= "boolean" then
table.insert(result.errors, "services." .. service .. ".enabled must be a boolean")
result.valid = false
end
end
end
-- Validate server configuration
if config.server.host ~= "127.0.0.1" and config.server.host ~= "localhost" then
table.insert(result.errors, "server.host must be '127.0.0.1' or 'localhost' for security")
result.valid = false
end
if config.server.port_range[1] < 1024 or config.server.port_range[2] > 65535 then
table.insert(result.errors, "server.port_range must be within 1024-65535")
result.valid = false
end
-- Validate diff configuration
if not vim.tbl_contains({"split", "unified"}, config.diff.default_mode) then
table.insert(result.errors, "diff.default_mode must be 'split' or 'unified'")
result.valid = false
end
if not vim.tbl_contains({"left", "right", "above", "below"}, config.diff.position) then
table.insert(result.errors, "diff.position must be 'left', 'right', 'above', or 'below'")
result.valid = false
end
-- Validate logging configuration
if not vim.tbl_contains({"DEBUG", "INFO", "WARN", "ERROR"}, config.logging.level) then
table.insert(result.errors, "logging.level must be 'DEBUG', 'INFO', 'WARN', or 'ERROR'")
result.valid = false
end
-- Validate Claude tmux settings
if config.services.claude.tmux then
local tmux = config.services.claude.tmux
if tmux.auto_reconnect ~= nil and type(tmux.auto_reconnect) ~= "boolean" then
table.insert(result.errors, "services.claude.tmux.auto_reconnect must be a boolean")
result.valid = false
end
if tmux.clear_before_ide ~= nil and type(tmux.clear_before_ide) ~= "boolean" then
table.insert(result.errors, "services.claude.tmux.clear_before_ide must be a boolean")
result.valid = false
end
if tmux.focus_after_send ~= nil and type(tmux.focus_after_send) ~= "boolean" then
table.insert(result.errors, "services.claude.tmux.focus_after_send must be a boolean")
result.valid = false
end
end
-- Validate numeric values
local numeric_validations = {
{"services.timeout", config.services.timeout, 1000, 300000},
{"server.auth_timeout", config.server.auth_timeout, 1000, 300000},
{"diff.timeout", config.diff.timeout, 1000, 300000},
{"ui.selection_debounce", config.ui.selection_debounce, 10, 1000}
}
for _, validation in ipairs(numeric_validations) do
local path, value, min_val, max_val = validation[1], validation[2], validation[3], validation[4]
if type(value) ~= "number" or value < min_val or value > max_val then
table.insert(result.errors, string.format("%s must be a number between %d and %d", path, min_val, max_val))
result.valid = false
end
end
return result
end
-- Get current configuration
function Config:get()
if not Config._instance then
error("Configuration not initialized. Call setup() first.")
end
return Config._instance._config
end
-- Update configuration at runtime
function Config:update(path, value)
if not Config._instance then
error("Configuration not initialized. Call setup() first.")
end
local config = Config._instance._config
self:_set_nested_value(config, path, value)
-- Re-validate after update
local validation_result = self:_validate_config(config)
if not validation_result.valid then
error("Invalid configuration update: " .. table.concat(validation_result.errors, ", "))
end
-- Emit configuration change event
local events = require('diffusion.utils.events')
if events then
events:emit("config_changed", { path = path, value = value })
end
return true
end
-- Get nested configuration value
function Config:get_nested(path)
if not Config._instance then
return nil
end
return self:_get_nested_value(Config._instance._config, path)
end
-- Helper to set nested values
function Config:_set_nested_value(tbl, path, value)
local keys = vim.split(path, ".", { plain = true })
local current = tbl
for i = 1, #keys - 1 do
local key = keys[i]
if current[key] == nil then
current[key] = {}
end
current = current[key]
end
current[keys[#keys]] = value
end
-- Helper to get nested values
function Config:_get_nested_value(tbl, path)
local keys = vim.split(path, ".", { plain = true })
local current = tbl
for _, key in ipairs(keys) do
if type(current) ~= "table" or current[key] == nil then
return nil
end
current = current[key]
end
return current
end
-- Get configuration summary for debugging
function Config:summary()
if not Config._instance then
return "Configuration not initialized"
end
local config = Config._instance._config
return {
services = {
default = config.services.default,
claude_enabled = config.services.claude.enabled,
claude_tmux = config.services.claude.tmux,
gemini_enabled = config.services.gemini and config.services.gemini.enabled or false,
opencode_enabled = config.services.opencode.enabled,
codex_enabled = config.services.codex and config.services.codex.enabled or false
},
server = {
host = config.server.host,
port_range = config.server.port_range
},
diff = {
mode = config.diff.mode,
position = config.diff.position
},
logging = {
enabled = config.logging.enabled,
level = config.logging.level
}
}
end
return Config