-
Notifications
You must be signed in to change notification settings - Fork 131
Expand file tree
/
Copy pathconfig_validator.py
More file actions
1916 lines (1737 loc) · 94.8 KB
/
config_validator.py
File metadata and controls
1916 lines (1737 loc) · 94.8 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
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Configuration validation for MassGen YAML/JSON configs.
This module provides comprehensive validation for MassGen configuration files,
checking schema structure, required fields, valid values, and best practices.
Usage:
from massgen.config_validator import ConfigValidator
# Validate a config file
validator = ConfigValidator()
result = validator.validate_config_file("config.yaml")
if result.has_errors():
print(result.format_errors())
sys.exit(1)
if result.has_warnings():
print(result.format_warnings())
# Validate a config dict
result = validator.validate_config(config_dict)
"""
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import yaml
from .backend.capabilities import (
BACKEND_CAPABILITIES,
get_capabilities,
validate_backend_config,
)
from .mcp_tools.config_validator import MCPConfigValidator
@dataclass
class ValidationIssue:
"""Represents a validation error or warning."""
message: str
location: str
suggestion: str | None = None
severity: str = "error" # "error" or "warning"
def __str__(self) -> str:
"""Format issue for display."""
severity_symbol = "❌" if self.severity == "error" else "⚠️"
parts = [f"{severity_symbol} [{self.location}] {self.message}"]
if self.suggestion:
parts.append(f" 💡 Suggestion: {self.suggestion}")
return "\n".join(parts)
@dataclass
class ValidationResult:
"""Aggregates all validation errors and warnings."""
errors: list[ValidationIssue] = field(default_factory=list)
warnings: list[ValidationIssue] = field(default_factory=list)
def add_error(self, message: str, location: str, suggestion: str | None = None) -> None:
"""Add a validation error."""
self.errors.append(ValidationIssue(message, location, suggestion, "error"))
def add_warning(self, message: str, location: str, suggestion: str | None = None) -> None:
"""Add a validation warning."""
self.warnings.append(ValidationIssue(message, location, suggestion, "warning"))
def has_errors(self) -> bool:
"""Check if there are any errors."""
return len(self.errors) > 0
def has_warnings(self) -> bool:
"""Check if there are any warnings."""
return len(self.warnings) > 0
def is_valid(self) -> bool:
"""Check if config is valid (no errors)."""
return not self.has_errors()
def format_errors(self) -> str:
"""Format all errors for display."""
if not self.errors:
return ""
lines = ["\n🔴 Configuration Errors Found:\n"]
lines.extend(str(error) for error in self.errors)
return "\n".join(lines)
def format_warnings(self) -> str:
"""Format all warnings for display."""
if not self.warnings:
return ""
lines = ["\n🟡 Configuration Warnings:\n"]
lines.extend(str(warning) for warning in self.warnings)
return "\n".join(lines)
def format_all(self) -> str:
"""Format all issues for display."""
parts = []
if self.has_errors():
parts.append(self.format_errors())
if self.has_warnings():
parts.append(self.format_warnings())
return "\n".join(parts) if parts else "✅ Configuration is valid!"
def to_dict(self) -> dict[str, Any]:
"""Convert to dictionary for JSON output."""
return {
"valid": self.is_valid(),
"error_count": len(self.errors),
"warning_count": len(self.warnings),
"errors": [{"message": e.message, "location": e.location, "suggestion": e.suggestion} for e in self.errors],
"warnings": [{"message": w.message, "location": w.location, "suggestion": w.suggestion} for w in self.warnings],
}
class ConfigValidator:
"""Validates MassGen configuration files."""
# V1 config keywords that are no longer supported
V1_KEYWORDS = {
"models",
"model_configs",
"num_agents",
"max_rounds",
"consensus_threshold",
"voting_enabled",
"enable_voting",
}
# Valid permission modes for backends that support them
VALID_PERMISSION_MODES = {"default", "acceptEdits", "bypassPermissions", "plan"}
# Valid display types for UI
VALID_DISPLAY_TYPES = {"rich_terminal", "simple", "textual_terminal"}
# Valid voting sensitivity levels
VALID_VOTING_SENSITIVITY = {
"lenient",
"balanced",
"strict",
"roi",
"roi_conservative",
"roi_balanced",
"roi_aggressive",
"sequential",
"adversarial",
"consistency",
"diversity",
"reflective",
"checklist",
"checklist_scored",
"checklist_gated",
}
# Valid answer novelty requirements
VALID_ANSWER_NOVELTY = {"lenient", "balanced", "strict"}
# Valid write modes for isolated write contexts
VALID_WRITE_MODES = {"auto", "worktree", "isolated", "legacy"}
VALID_DRIFT_CONFLICT_POLICIES = {"skip", "prefer_presenter", "fail"}
VALID_NOVELTY_INJECTION = {"none", "gentle", "moderate", "aggressive"}
VALID_ROUND_EVALUATOR_TRANSFORMATION_PRESSURE = {"gentle", "balanced", "aggressive"}
VALID_SUBAGENT_RUNTIME_MODES = {"isolated", "inherited"}
VALID_SUBAGENT_RUNTIME_FALLBACK_MODES = {"inherited"}
VALID_FINAL_ANSWER_STRATEGIES = {"winner_reuse", "winner_present", "synthesize"}
VALID_LEARNING_CAPTURE_MODES = {
"round",
"verification_and_final_only",
"final_only",
}
# Valid gap report modes
VALID_GAP_REPORT_MODES = {"changedoc", "separate", "none"}
def __init__(self):
"""Initialize the validator."""
def validate_config_file(self, config_path: str) -> ValidationResult:
"""
Validate a configuration file.
Args:
config_path: Path to YAML or JSON config file
Returns:
ValidationResult with any errors or warnings found
"""
result = ValidationResult()
# Check file exists
path = Path(config_path)
if not path.exists():
result.add_error(f"Config file not found: {config_path}", "file", "Check the file path")
return result
# Load config file
try:
with open(path) as f:
if path.suffix in [".yaml", ".yml"]:
config = yaml.safe_load(f)
elif path.suffix == ".json":
import json
config = json.load(f)
else:
result.add_error(
f"Unsupported file format: {path.suffix}",
"file",
"Use .yaml, .yml, or .json extension",
)
return result
except Exception as e:
result.add_error(f"Failed to parse config file: {e}", "file", "Check file syntax")
return result
# Validate the loaded config
return self.validate_config(config)
def validate_config(self, config: dict[str, Any]) -> ValidationResult:
"""
Validate a configuration dictionary.
Args:
config: Configuration dictionary
Returns:
ValidationResult with any errors or warnings found
"""
result = ValidationResult()
if not isinstance(config, dict):
result.add_error("Config must be a dictionary/object", "root", "Check YAML/JSON syntax")
return result
# Check for V1 config keywords (instant fail)
self._check_v1_keywords(config, result)
if result.has_errors():
return result # Stop validation if V1 detected
# Validate top-level structure
self._validate_top_level(config, result)
# Validate agents (if present)
if "agents" in config or "agent" in config:
self._validate_agents(config, result)
# Validate orchestrator (if present)
if "orchestrator" in config:
self._validate_orchestrator(config["orchestrator"], result, config=config)
# Validate UI (if present)
if "ui" in config:
self._validate_ui(config["ui"], result)
# Validate memory (if present)
if "memory" in config:
self._validate_memory(config["memory"], result)
# Check for warnings (best practices, deprecations, etc.)
self._check_warnings(config, result)
return result
def _check_v1_keywords(self, config: dict[str, Any], result: ValidationResult) -> None:
"""Check for V1 config keywords and reject them."""
found_v1_keywords = []
for keyword in self.V1_KEYWORDS:
if keyword in config:
found_v1_keywords.append(keyword)
if found_v1_keywords:
result.add_error(
f"V1 config format detected (found: {', '.join(found_v1_keywords)}). " "V1 configs are no longer supported.",
"root",
"Migrate to V2 config format. See docs/source/reference/yaml_schema.rst for the current schema.",
)
def _validate_top_level(self, config: dict[str, Any], result: ValidationResult) -> None:
"""Validate top-level config structure (Level 1)."""
# Require either 'agents' (list) or 'agent' (single)
has_agents = "agents" in config
has_agent = "agent" in config
if not has_agents and not has_agent:
result.add_error(
"Config must have either 'agents' (list) or 'agent' (single agent)",
"root",
"Add 'agents: [...]' for multiple agents or 'agent: {...}' for a single agent",
)
return
if has_agents and has_agent:
result.add_error(
"Config cannot have both 'agents' and 'agent' fields",
"root",
"Use either 'agents' for multiple agents or 'agent' for a single agent",
)
return
# Validate agents is a list (if present)
if has_agents and not isinstance(config["agents"], list):
result.add_error(
f"'agents' must be a list, got {type(config['agents']).__name__}",
"root.agents",
"Use 'agents: [...]' for multiple agents",
)
# Validate agent is a dict (if present)
if has_agent and not isinstance(config["agent"], dict):
result.add_error(
f"'agent' must be a dictionary, got {type(config['agent']).__name__}",
"root.agent",
"Use 'agent: {...}' for a single agent",
)
# Validate global hooks if present
if "hooks" in config:
self._validate_hooks(config["hooks"], "hooks", result)
def _validate_agents(self, config: dict[str, Any], result: ValidationResult) -> None:
"""Validate agent configurations (Level 2)."""
# Get agents list (normalize single agent to list)
if "agents" in config:
agents = config["agents"]
if not isinstance(agents, list):
return # Already reported error in _validate_top_level
else:
agents = [config["agent"]]
# Track agent IDs for duplicate detection
agent_ids: list[str] = []
for i, agent_config in enumerate(agents):
agent_location = f"agents[{i}]" if "agents" in config else "agent"
# Validate agent is a dict
if not isinstance(agent_config, dict):
result.add_error(
f"Agent must be a dictionary, got {type(agent_config).__name__}",
agent_location,
"Use 'id', 'backend', and optional 'system_message' fields",
)
continue
# Validate required field: id
if "id" not in agent_config:
result.add_error("Agent missing required field 'id'", agent_location, "Add 'id: \"agent-name\"'")
else:
agent_id = agent_config["id"]
if not isinstance(agent_id, str):
result.add_error(
f"Agent 'id' must be a string, got {type(agent_id).__name__}",
f"{agent_location}.id",
"Use a string identifier like 'id: \"researcher\"'",
)
elif agent_id in agent_ids:
result.add_error(
f"Duplicate agent ID: '{agent_id}'",
f"{agent_location}.id",
"Each agent must have a unique ID",
)
else:
agent_ids.append(agent_id)
# Validate required field: backend
if "backend" not in agent_config:
result.add_error(
"Agent missing required field 'backend'",
agent_location,
"Add 'backend: {type: ..., model: ...}'",
)
else:
self._validate_backend(agent_config["backend"], f"{agent_location}.backend", result)
# Validate optional field: system_message
if "system_message" in agent_config:
system_message = agent_config["system_message"]
if not isinstance(system_message, str):
result.add_error(
f"Agent 'system_message' must be a string, got {type(system_message).__name__}",
f"{agent_location}.system_message",
"Use a string for the system message",
)
# Validate optional field: voting_sensitivity (per-agent override)
if "voting_sensitivity" in agent_config:
voting_sensitivity = agent_config["voting_sensitivity"]
if voting_sensitivity not in self.VALID_VOTING_SENSITIVITY:
valid_values = ", ".join(sorted(self.VALID_VOTING_SENSITIVITY))
result.add_error(
f"Invalid voting_sensitivity: '{voting_sensitivity}'",
f"{agent_location}.voting_sensitivity",
f"Use one of: {valid_values}",
)
# Validate optional field: subtask (decomposition mode)
if "subtask" in agent_config:
subtask = agent_config["subtask"]
if not isinstance(subtask, str):
result.add_error(
f"Agent 'subtask' must be a string, got {type(subtask).__name__}",
f"{agent_location}.subtask",
"Use a string describing the agent's subtask",
)
if "subagent_agents" in agent_config:
subagent_agents = agent_config["subagent_agents"]
if not isinstance(subagent_agents, list):
result.add_error(
"'subagent_agents' must be a list",
f"{agent_location}.subagent_agents",
"Use a list of agent-like entries with 'backend' and optional 'id'",
)
else:
subagent_ids: list[str] = []
for j, subagent_cfg in enumerate(subagent_agents):
subagent_location = f"{agent_location}.subagent_agents[{j}]"
if not isinstance(subagent_cfg, dict):
result.add_error(
f"Subagent agent must be a dictionary, got {type(subagent_cfg).__name__}",
subagent_location,
"Use 'id' and 'backend' fields",
)
continue
if "id" in subagent_cfg:
subagent_id = subagent_cfg["id"]
if not isinstance(subagent_id, str):
result.add_error(
f"Subagent agent 'id' must be a string, got {type(subagent_id).__name__}",
f"{subagent_location}.id",
"Use a string identifier like 'id: \"local_eval\"'",
)
elif subagent_id in subagent_ids:
result.add_error(
f"Duplicate subagent agent ID: '{subagent_id}'",
f"{subagent_location}.id",
"Each subagent agent ID must be unique within the list",
)
else:
subagent_ids.append(subagent_id)
if "backend" not in subagent_cfg:
result.add_error(
"Subagent agent missing required field 'backend'",
subagent_location,
"Add 'backend: {type: ..., model: ...}'",
)
else:
self._validate_backend(
subagent_cfg["backend"],
f"{subagent_location}.backend",
result,
)
def _validate_backend(self, backend_config: dict[str, Any], location: str, result: ValidationResult) -> None:
"""Validate backend configuration (Level 3)."""
if not isinstance(backend_config, dict):
result.add_error(
f"Backend must be a dictionary, got {type(backend_config).__name__}",
location,
"Use 'type', 'model', and other backend-specific fields",
)
return
# Validate required field: type
if "type" not in backend_config:
result.add_error("Backend missing required field 'type'", location, "Add 'type: \"openai\"' or similar")
return
backend_type = backend_config["type"]
if not isinstance(backend_type, str):
result.add_error(
f"Backend 'type' must be a string, got {type(backend_type).__name__}",
f"{location}.type",
"Use a string like 'openai', 'claude', 'gemini', etc.",
)
return
# Validate backend type is supported
if backend_type not in BACKEND_CAPABILITIES:
valid_types = ", ".join(sorted(BACKEND_CAPABILITIES.keys()))
result.add_error(
f"Unknown backend type: '{backend_type}'",
f"{location}.type",
f"Use one of: {valid_types}",
)
return
# Validate model field
# Model is optional for:
# - ag2 (uses agent_config.llm_config instead)
# - claude_code (has default model)
# - backends with default models in BACKEND_CAPABILITIES
caps = get_capabilities(backend_type)
has_default_model = caps and caps.default_model != "custom"
if backend_type != "ag2" and not has_default_model:
if "model" not in backend_config:
result.add_error("Backend missing required field 'model'", location, "Add 'model: \"model-name\"'")
else:
model = backend_config["model"]
if not isinstance(model, str):
result.add_error(
f"Backend 'model' must be a string, got {type(model).__name__}",
f"{location}.model",
"Use a string model identifier",
)
elif "model" in backend_config:
# Validate type if model is provided (even if optional)
model = backend_config["model"]
if not isinstance(model, str):
result.add_error(
f"Backend 'model' must be a string, got {type(model).__name__}",
f"{location}.model",
"Use a string model identifier",
)
# Validate backend-specific capabilities using existing validator
capability_errors = validate_backend_config(backend_type, backend_config)
for error_msg in capability_errors:
result.add_error(error_msg, location, "Check backend capabilities in documentation")
# Validate permission_mode if present
if "permission_mode" in backend_config:
permission_mode = backend_config["permission_mode"]
if permission_mode not in self.VALID_PERMISSION_MODES:
valid_modes = ", ".join(sorted(self.VALID_PERMISSION_MODES))
result.add_error(
f"Invalid permission_mode: '{permission_mode}'",
f"{location}.permission_mode",
f"Use one of: {valid_modes}",
)
# Validate tool filtering (allowed_tools, exclude_tools, disallowed_tools)
self._validate_tool_filtering(backend_config, location, result)
# Validate MCP servers if present
if "mcp_servers" in backend_config:
try:
MCPConfigValidator.validate_backend_mcp_config(backend_config)
except Exception as e:
result.add_error(
f"MCP configuration error: {str(e)}",
f"{location}.mcp_servers",
"Check MCP server configuration syntax",
)
# Validate boolean fields
boolean_fields = [
"enable_web_search",
"enable_code_execution",
"enable_code_interpreter",
"enable_programmatic_flow",
"enable_tool_search",
"enable_strict_tool_use",
"websocket_mode",
]
for field_name in boolean_fields:
if field_name in backend_config:
value = backend_config[field_name]
if not isinstance(value, bool):
result.add_error(
f"Backend '{field_name}' must be a boolean, got {type(value).__name__}",
f"{location}.{field_name}",
"Use 'true' or 'false'",
)
# Validate output_schema if present (structured outputs)
if "output_schema" in backend_config:
output_schema = backend_config["output_schema"]
if not isinstance(output_schema, dict):
result.add_error(
f"'output_schema' must be a dictionary, got {type(output_schema).__name__}",
f"{location}.output_schema",
"Use a JSON schema object like: {type: object, properties: {...}}",
)
elif not output_schema:
result.add_warning(
"'output_schema' is an empty dictionary",
f"{location}.output_schema",
"Provide a valid JSON schema",
)
elif "type" not in output_schema:
result.add_warning(
"'output_schema' should have a 'type' field",
f"{location}.output_schema",
"Add 'type: object' or similar",
)
# Check for incompatible feature combinations
if backend_config.get("enable_programmatic_flow") and backend_config.get("enable_strict_tool_use"):
result.add_warning(
"Strict tool use is not compatible with programmatic tool calling",
location,
"Strict tool use will be automatically disabled at runtime. ",
)
# Validate hooks if present
if "hooks" in backend_config:
self._validate_hooks(backend_config["hooks"], f"{location}.hooks", result)
# Validate Codex Docker mode requirements
if backend_type == "codex":
execution_mode = backend_config.get("command_line_execution_mode")
if execution_mode == "docker":
# command_line_docker_network_mode is required for Codex in Docker mode
if "command_line_docker_network_mode" not in backend_config:
result.add_error(
"Codex backend in Docker mode requires 'command_line_docker_network_mode'",
f"{location}.command_line_docker_network_mode",
"Add 'command_line_docker_network_mode: bridge' (required for Codex Docker execution)",
)
def _validate_tool_filtering(
self,
backend_config: dict[str, Any],
location: str,
result: ValidationResult,
) -> None:
"""Validate tool filtering parameters."""
# Check allowed_tools
if "allowed_tools" in backend_config:
allowed_tools = backend_config["allowed_tools"]
if not isinstance(allowed_tools, list):
result.add_error(
f"'allowed_tools' must be a list, got {type(allowed_tools).__name__}",
f"{location}.allowed_tools",
"Use a list of tool names",
)
else:
for i, tool in enumerate(allowed_tools):
if not isinstance(tool, str):
result.add_error(
f"'allowed_tools[{i}]' must be a string, got {type(tool).__name__}",
f"{location}.allowed_tools[{i}]",
"Use string tool names",
)
# Check exclude_tools
if "exclude_tools" in backend_config:
exclude_tools = backend_config["exclude_tools"]
if not isinstance(exclude_tools, list):
result.add_error(
f"'exclude_tools' must be a list, got {type(exclude_tools).__name__}",
f"{location}.exclude_tools",
"Use a list of tool names",
)
else:
for i, tool in enumerate(exclude_tools):
if not isinstance(tool, str):
result.add_error(
f"'exclude_tools[{i}]' must be a string, got {type(tool).__name__}",
f"{location}.exclude_tools[{i}]",
"Use string tool names",
)
# Check disallowed_tools (claude_code specific)
if "disallowed_tools" in backend_config:
disallowed_tools = backend_config["disallowed_tools"]
if not isinstance(disallowed_tools, list):
result.add_error(
f"'disallowed_tools' must be a list, got {type(disallowed_tools).__name__}",
f"{location}.disallowed_tools",
"Use a list of tool patterns",
)
else:
for i, tool in enumerate(disallowed_tools):
if not isinstance(tool, str):
result.add_error(
f"'disallowed_tools[{i}]' must be a string, got {type(tool).__name__}",
f"{location}.disallowed_tools[{i}]",
"Use string tool patterns",
)
def _validate_hooks(
self,
hooks_config: dict[str, Any],
location: str,
result: ValidationResult,
) -> None:
"""Validate hooks configuration.
Hooks can be defined at two levels:
- Global (top-level `hooks:`) - applies to all agents
- Per-agent (in `backend.hooks:`) - can extend or override global hooks
"""
if not isinstance(hooks_config, dict):
result.add_error(
f"'hooks' must be a dictionary, got {type(hooks_config).__name__}",
location,
"Use hook types like 'PreToolUse' and 'PostToolUse'",
)
return
valid_hook_types = {"PreToolUse", "PostToolUse"}
for hook_type, hook_list in hooks_config.items():
if hook_type == "override":
# Skip override flag
continue
if hook_type not in valid_hook_types:
result.add_warning(
f"Unknown hook type: '{hook_type}'",
f"{location}.{hook_type}",
f"Use one of: {', '.join(sorted(valid_hook_types))}",
)
continue
# Handle both list format and dict format (with override)
hooks_to_validate = hook_list
if isinstance(hook_list, dict):
hooks_to_validate = hook_list.get("hooks", [])
if "override" in hook_list and not isinstance(hook_list["override"], bool):
result.add_error(
"'override' must be a boolean",
f"{location}.{hook_type}.override",
"Use 'true' or 'false'",
)
if not isinstance(hooks_to_validate, list):
result.add_error(
f"'{hook_type}' must be a list of hooks",
f"{location}.{hook_type}",
"Use a list of hook configurations",
)
continue
# Validate each hook in the list
for i, hook_config in enumerate(hooks_to_validate):
self._validate_single_hook(
hook_config,
f"{location}.{hook_type}[{i}]",
result,
)
def _validate_single_hook(
self,
hook_config: dict[str, Any],
location: str,
result: ValidationResult,
) -> None:
"""Validate a single hook configuration."""
if not isinstance(hook_config, dict):
result.add_error(
f"Hook must be a dictionary, got {type(hook_config).__name__}",
location,
"Use 'handler', 'matcher', 'type', and 'timeout' fields",
)
return
# Validate required field: handler
if "handler" not in hook_config:
result.add_error(
"Hook missing required field 'handler'",
location,
"Add 'handler: \"module.function\"' or 'handler: \"path/to/script.py\"'",
)
else:
handler = hook_config["handler"]
if not isinstance(handler, str):
result.add_error(
f"'handler' must be a string, got {type(handler).__name__}",
f"{location}.handler",
"Use a module path or file path",
)
# Validate optional field: type
if "type" in hook_config:
hook_type = hook_config["type"]
valid_types = {"python"}
if hook_type not in valid_types:
result.add_error(
f"Invalid hook type: '{hook_type}'",
f"{location}.type",
f"Use one of: {', '.join(sorted(valid_types))}",
)
# Validate optional field: matcher
if "matcher" in hook_config:
matcher = hook_config["matcher"]
if not isinstance(matcher, str):
result.add_error(
f"'matcher' must be a string, got {type(matcher).__name__}",
f"{location}.matcher",
"Use a glob pattern like '*' or 'Write|Edit'",
)
# Validate optional field: timeout
if "timeout" in hook_config:
timeout = hook_config["timeout"]
if not isinstance(timeout, (int, float)):
result.add_error(
f"'timeout' must be a number, got {type(timeout).__name__}",
f"{location}.timeout",
"Use a number of seconds like 30 or 60",
)
elif timeout <= 0:
result.add_error(
f"'timeout' must be positive, got {timeout}",
f"{location}.timeout",
"Use a positive number of seconds",
)
# Validate optional field: fail_closed
if "fail_closed" in hook_config:
fail_closed = hook_config["fail_closed"]
if not isinstance(fail_closed, bool):
result.add_error(
f"'fail_closed' must be a boolean, got {type(fail_closed).__name__}",
f"{location}.fail_closed",
"Use true or false",
)
def _validate_orchestrator(self, orchestrator_config: dict[str, Any], result: ValidationResult, config: dict[str, Any] | None = None) -> None:
"""Validate orchestrator configuration (Level 5)."""
location = "orchestrator"
if not isinstance(orchestrator_config, dict):
result.add_error(
f"Orchestrator must be a dictionary, got {type(orchestrator_config).__name__}",
location,
"Use orchestrator fields like snapshot_storage, context_paths, etc.",
)
return
# Validate coordination_mode if present
if "coordination_mode" in orchestrator_config:
coordination_mode = orchestrator_config["coordination_mode"]
valid_modes = ["voting", "decomposition"]
if coordination_mode not in valid_modes:
result.add_error(
f"Invalid coordination_mode: '{coordination_mode}'",
f"{location}.coordination_mode",
f"Use one of: {', '.join(valid_modes)}",
)
# Validate presenter_agent if present
if "presenter_agent" in orchestrator_config:
presenter = orchestrator_config["presenter_agent"]
if not isinstance(presenter, str):
result.add_error(
f"'presenter_agent' must be a string, got {type(presenter).__name__}",
f"{location}.presenter_agent",
"Use an agent ID string like 'integrator'",
)
# Validate final_answer_strategy if present
if "final_answer_strategy" in orchestrator_config:
strategy = orchestrator_config["final_answer_strategy"]
valid_strategies = sorted(self.VALID_FINAL_ANSWER_STRATEGIES)
if strategy is not None and strategy not in self.VALID_FINAL_ANSWER_STRATEGIES:
result.add_error(
f"Invalid final_answer_strategy: '{strategy}'",
f"{location}.final_answer_strategy",
f"Use one of: {', '.join(valid_strategies)}",
)
# Validate context_paths if present
if "context_paths" in orchestrator_config:
context_paths = orchestrator_config["context_paths"]
if not isinstance(context_paths, list):
result.add_error(
f"'context_paths' must be a list, got {type(context_paths).__name__}",
f"{location}.context_paths",
"Use a list of path configurations",
)
else:
for i, path_config in enumerate(context_paths):
if not isinstance(path_config, dict):
result.add_error(
f"'context_paths[{i}]' must be a dictionary",
f"{location}.context_paths[{i}]",
"Use 'path' and 'permission' fields",
)
continue
# Check required field: path
if "path" not in path_config:
result.add_error(
"context_paths entry missing 'path' field",
f"{location}.context_paths[{i}]",
"Add 'path: \"/path/to/dir\"'",
)
# Check permission field
if "permission" in path_config:
permission = path_config["permission"]
if permission not in ["read", "write"]:
result.add_error(
f"Invalid permission: '{permission}'",
f"{location}.context_paths[{i}].permission",
"Use 'read' or 'write'",
)
# Validate coordination if present
if "coordination" in orchestrator_config:
coordination = orchestrator_config["coordination"]
if not isinstance(coordination, dict):
result.add_error(
f"'coordination' must be a dictionary, got {type(coordination).__name__}",
f"{location}.coordination",
"Use coordination fields like enable_planning_mode, max_orchestration_restarts, etc.",
)
else:
# Validate boolean fields
boolean_fields = [
"enable_planning_mode",
"use_two_tier_workspace",
"enable_changedoc",
"round_evaluator_before_checklist",
"orchestrator_managed_round_evaluator",
"round_evaluator_refine",
"round_evaluator_skip_synthesis",
]
for field_name in boolean_fields:
if field_name in coordination:
value = coordination[field_name]
if not isinstance(value, bool):
result.add_error(
f"'{field_name}' must be a boolean, got {type(value).__name__}",
f"{location}.coordination.{field_name}",
"Use 'true' or 'false'",
)
# Deprecation warning for use_two_tier_workspace
if coordination.get("use_two_tier_workspace"):
write_mode = coordination.get("write_mode")
if write_mode:
result.add_warning(
"'use_two_tier_workspace' is deprecated and ignored when 'write_mode' is set. " "Remove 'use_two_tier_workspace' from your config.",
f"{location}.coordination.use_two_tier_workspace",
)
else:
result.add_warning(
"'use_two_tier_workspace' is deprecated. " "Migrate to 'write_mode: auto' for the same functionality with git worktree isolation.",
f"{location}.coordination.use_two_tier_workspace",
)
# Validate integer fields
if "max_orchestration_restarts" in coordination:
value = coordination["max_orchestration_restarts"]
if not isinstance(value, int) or value < 0:
result.add_error(
"'max_orchestration_restarts' must be a non-negative integer",
f"{location}.coordination.max_orchestration_restarts",
"Use a value like 0, 1, 2, etc.",
)
# Hard-break rename: async_subagents -> background_subagents
if "async_subagents" in coordination:
result.add_error(
"'async_subagents' has been removed. Use 'background_subagents' instead.",
f"{location}.coordination.async_subagents",
"Replace with background_subagents: {enabled: true, injection_strategy: 'tool_result'}",
)
# Validate background_subagents if present
if "background_subagents" in coordination:
background_config = coordination["background_subagents"]
if not isinstance(background_config, dict):
result.add_error(
f"'background_subagents' must be a dictionary, got {type(background_config).__name__}",
f"{location}.coordination.background_subagents",
"Use background_subagents: {enabled: true, injection_strategy: 'tool_result'}",
)
else:
# Validate enabled field
if "enabled" in background_config:
enabled = background_config["enabled"]
if not isinstance(enabled, bool):
result.add_error(
f"'background_subagents.enabled' must be a boolean, got {type(enabled).__name__}",
f"{location}.coordination.background_subagents.enabled",
"Use 'true' or 'false'",
)
# Validate injection_strategy field
if "injection_strategy" in background_config:
strategy = background_config["injection_strategy"]
valid_strategies = ["tool_result", "user_message"]
if strategy not in valid_strategies:
result.add_error(
f"Invalid background_subagents.injection_strategy: '{strategy}'",
f"{location}.coordination.background_subagents.injection_strategy",
f"Use one of: {', '.join(valid_strategies)}",
)
# Validate plan_depth if present
if "plan_depth" in coordination:
value = coordination["plan_depth"]
valid_depths = ["dynamic", "shallow", "medium", "deep"]
if value not in valid_depths:
result.add_error(
f"'plan_depth' must be one of {valid_depths}, got '{value}'",
f"{location}.coordination.plan_depth",