@yahyahammad/venastine 0.3.8 → 0.3.9

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 (128) hide show
  1. package/.env.example +19 -19
  2. package/CONFIG_ARCHITECTURE.md +2030 -2002
  3. package/LICENSE +201 -201
  4. package/README.md +1034 -1034
  5. package/agents/builtin/compactor.md +75 -75
  6. package/agents/builtin/explore.md +77 -77
  7. package/agents/builtin/pipeline-reviewer.md +100 -100
  8. package/agents/builtin/plan.md +106 -106
  9. package/agents/builtin/review.md +74 -74
  10. package/agents/manager.py +261 -261
  11. package/agents/subagent_tool.py +472 -472
  12. package/agents/tui_commands.py +238 -146
  13. package/bin/venastine.mjs +528 -528
  14. package/bin/venastine.py +71 -71
  15. package/cli_commands.py +838 -835
  16. package/config.yaml +13 -0
  17. package/config_edit.py +1301 -1301
  18. package/config_schema.py +971 -966
  19. package/config_update.py +749 -749
  20. package/core/agent_activity.py +256 -256
  21. package/core/ansi.py +452 -452
  22. package/core/approval.py +137 -137
  23. package/core/call_view.py +364 -364
  24. package/core/cancel.py +121 -121
  25. package/core/chatgpt_auth.py +747 -747
  26. package/core/claims_view.py +107 -107
  27. package/core/client.py +2715 -2715
  28. package/core/commands.py +460 -454
  29. package/core/compaction.py +1735 -1735
  30. package/core/config_loader.py +1982 -1982
  31. package/core/connect.py +686 -686
  32. package/core/events.py +123 -123
  33. package/core/file_mentions.py +280 -280
  34. package/core/interaction.py +411 -411
  35. package/core/loop.py +2566 -2566
  36. package/core/memory.py +482 -482
  37. package/core/pipeline_models.py +190 -190
  38. package/core/provider_errors.py +234 -234
  39. package/core/reasoning/authorization.py +130 -130
  40. package/core/reasoning/base.py +219 -219
  41. package/core/reasoning/confidence_scoring.py +484 -484
  42. package/core/reasoning/events.py +149 -149
  43. package/core/reasoning/orchestrator.py +1561 -1561
  44. package/core/reasoning/output_writer.py +345 -345
  45. package/core/reasoning/payload_validation.py +524 -524
  46. package/core/reasoning/pipeline_storage.py +427 -427
  47. package/core/reasoning/scholar.py +458 -458
  48. package/core/reasoning/source_corpus.py +433 -433
  49. package/core/reasoning/source_scoring.py +855 -855
  50. package/core/replay.py +315 -315
  51. package/core/shell_sessions.py +1553 -1553
  52. package/credentials.py +307 -307
  53. package/database.py +333 -333
  54. package/docs/PRIVACY.md +78 -78
  55. package/docs/SECURITY.md +108 -108
  56. package/docs/THIRD_PARTY_NOTICES.md +148 -148
  57. package/env_secrets.py +118 -118
  58. package/json_store.py +343 -343
  59. package/logging_setup.py +295 -295
  60. package/main.py +3433 -3433
  61. package/mcp_client/client.py +733 -733
  62. package/mcp_client/config.py +484 -484
  63. package/mcp_client/registration.py +343 -343
  64. package/memories/manager.py +147 -147
  65. package/memories/tui_commands.py +319 -239
  66. package/package.json +303 -303
  67. package/project_init/config_files.py +282 -282
  68. package/project_init/generator.py +728 -728
  69. package/project_init/manifest.py +418 -418
  70. package/project_init/tui_commands.py +147 -147
  71. package/prompts/critic_pass.md +24 -24
  72. package/prompts/revalidate.md +25 -25
  73. package/prompts/revise.md +17 -17
  74. package/prompts/source_grounding.md +66 -66
  75. package/prompts/system_prompts.py +316 -316
  76. package/providers.json.example +94 -94
  77. package/pyproject.toml +149 -149
  78. package/requirements.txt +295 -295
  79. package/safety/policy_enforcement.py +1082 -1082
  80. package/security/askpass.py +419 -419
  81. package/security/capability.py +207 -207
  82. package/security/confine.py +484 -484
  83. package/security/hosted.py +182 -182
  84. package/security/permissions.py +237 -237
  85. package/security/protected_paths.py +501 -501
  86. package/security/sandbox.py +4108 -4108
  87. package/skills/builtin/math/formal-specification.md +67 -67
  88. package/skills/builtin/math/numerical-methods.md +66 -66
  89. package/skills/builtin/research/experiment-design.md +62 -62
  90. package/skills/builtin/research/reproducibility.md +55 -55
  91. package/skills/builtin/research/source-evaluation.md +70 -70
  92. package/skills/builtin/research/statistical-inference.md +63 -63
  93. package/skills/builtin/research/technical-writing.md +59 -59
  94. package/skills/builtin/software/code-review.md +61 -61
  95. package/skills/builtin/software/debugging.md +61 -61
  96. package/skills/builtin/software/test-design.md +67 -67
  97. package/skills/tui_commands.py +110 -110
  98. package/storage.py +1338 -1338
  99. package/tools/base.py +465 -465
  100. package/tools/builtin/_math_common.py +667 -667
  101. package/tools/builtin/_net_common.py +267 -267
  102. package/tools/builtin/arxiv.py +681 -681
  103. package/tools/builtin/fetch_url.py +371 -371
  104. package/tools/builtin/file_ops.py +720 -720
  105. package/tools/builtin/geometry.py +184 -184
  106. package/tools/builtin/load_skill.py +76 -76
  107. package/tools/builtin/pin.py +227 -227
  108. package/tools/builtin/probability_stats.py +224 -224
  109. package/tools/builtin/project_docs.py +464 -464
  110. package/tools/builtin/remember.py +175 -175
  111. package/tools/builtin/shell.py +980 -980
  112. package/tools/builtin/todo.py +149 -149
  113. package/tools/builtin/web_search.py +328 -328
  114. package/tools/context.py +159 -159
  115. package/tools/isolation.py +387 -387
  116. package/tools/registry.py +1242 -1242
  117. package/tui/app.py +8318 -8307
  118. package/tui/app.tcss +747 -739
  119. package/tui/commands.py +26 -26
  120. package/tui/diffs.py +286 -286
  121. package/tui/history.py +128 -128
  122. package/tui/hosted_driver.py +102 -102
  123. package/tui/markdown.py +1329 -1329
  124. package/tui/meters.py +364 -364
  125. package/tui/ravens.py +146 -146
  126. package/tui/screens.py +1255 -1197
  127. package/tui/themes.py +599 -599
  128. package/tui/widgets.py +3813 -3796
package/config_schema.py CHANGED
@@ -1,966 +1,971 @@
1
- """config_schema.py -- the schema for `config.yaml`, and the only reader of it.
2
-
3
- WHY THIS FILE EXISTS SEPARATELY FROM `config.py`.
4
-
5
- `config.py` is imported by 30 production modules and ~60 test files, and
6
- `core/config_loader.py` imported it too when this file was written. If the
7
- shim had reached back into `core/config_loader` for the values, that would
8
- have been a cycle -- and `config.py` was a LEAF module, importing `os` and
9
- `dataclasses` and nothing else, which is the property that made it safe for
10
- `security/` to depend on. So the reader lives here, one hop away, and this
11
- module imports the stdlib, `ruamel.yaml` and `pydantic` and NOTHING
12
- first-party.
13
-
14
- The loader reads `config_schema` rather than `config` now, so the cycle is
15
- gone from both ends -- which is exactly why this rule has to be stated
16
- rather than left to the import graph to imply. Keep it: an import of
17
- anything under `core/`, `security/` or `tools/` from here puts the cycle
18
- back by a longer route, and there would be nothing in the graph to stop it.
19
-
20
- Three rules about `config.yaml` are load-bearing rather than tidy. All three
21
- are argued at length in CONFIG_ARCHITECTURE.md; this is the summary.
22
-
23
- 1. ONE PATH, RESOLVED FROM `__file__`, WITH NO ENVIRONMENT OVERRIDE.
24
- `config.yaml` ships inside the harness. There is no user tier, no project
25
- tier and no `AGENT_CONFIG_FILE`. That absence is the whole security
26
- argument: `settings.json` rejects `shell_approval_mode`,
27
- `ensemble_models`, `critic_model` and `embedder_model` BY NAME (R12, E2,
28
- G7, SQ7) because a project's `settings.json` beats the user's and arrives
29
- with a directory you cloned. A file with exactly one location, inside the
30
- harness, carries none of that risk -- and an override variable would hand
31
- it back. `AGENT_ENV_FILE` and `APP_DB_PATH` make such a variable look like
32
- the obvious next step here. It is not; those redirect STATE, and this is a
33
- shipped asset.
34
-
35
- 2. READ ONCE, AT IMPORT, WITH THE ENVIRONMENT FOLDED IN THERE.
36
- `security/posture.py` depends on `config` binding at import: that is what
37
- makes `os.environ[...] = ...` unable to move the security posture, while
38
- anything reading `os.environ` at CALL time would follow the mutation
39
- (UN1, and batch 37's asymmetry). `tools/builtin/shell.py` also validates
40
- the approval mode at ITS import, so the values must be final before any
41
- other module runs. Nothing re-reads the file in a live process; an edit
42
- takes effect at the next launch.
43
-
44
- 3. EVERY FIELD IS REQUIRED AND UNKNOWN KEYS ARE REFUSED.
45
- No field here has a default. A `config.yaml` missing a key is a startup
46
- error naming that key, which is the D24 defect made impossible rather than
47
- merely fixed: `fetch_url` was registered and documented as working while
48
- having no `ToolPermissions` field, so `getattr(..., False)` denied every
49
- call to it for as long as the tool existed. A default here would recreate
50
- exactly that -- a value nobody chose, silently in force.
51
- """
52
-
53
- from __future__ import annotations
54
-
55
- import dataclasses
56
- import os
57
- from typing import Annotated, Any, Literal, Optional
58
-
59
- from pydantic import (
60
- BaseModel,
61
- BeforeValidator,
62
- ConfigDict,
63
- Field,
64
- StrictBool,
65
- StrictInt,
66
- ValidationError,
67
- model_validator,
68
- )
69
- from ruamel.yaml import YAML
70
- from ruamel.yaml.error import YAMLError
71
-
72
- # ---------------------------------------------------------------------------
73
- # ---- Where the file is ----------------------------------------------------
74
- # ---------------------------------------------------------------------------
75
-
76
- CONFIG_FILENAME = "config.yaml"
77
- #: The harness root. This file lives at the root beside `config.py`, so the
78
- #: root is its own directory -- resolved from `__file__` rather than from cwd
79
- #: for `core/config_loader.HARNESS_ROOT`'s reason: the harness tier ships with
80
- #: the harness, and every shipped asset in this project resolves this way.
81
- HARNESS_ROOT = os.path.dirname(os.path.abspath(__file__))
82
- CONFIG_PATH = os.path.join(HARNESS_ROOT, CONFIG_FILENAME)
83
-
84
-
85
- # ---------------------------------------------------------------------------
86
- # ---- Scalar types ---------------------------------------------------------
87
- # ---------------------------------------------------------------------------
88
-
89
- def _number_only(value: Any) -> Any:
90
- """Reject a bool or a string where a number is wanted.
91
-
92
- `bool` is a subclass of `int` in Python and pydantic's lax `float` takes
93
- both `True` and `"9.5"`. `core/config_loader._type_ok` goes to the same
94
- trouble for `settings.json` and says why: a `True` sailing through as `1`
95
- is a value nobody wrote. Ints ARE accepted, so `8` is a legal way to
96
- write `8.0` in YAML.
97
- """
98
- if isinstance(value, bool):
99
- raise ValueError("expected a number, got a boolean")
100
- if isinstance(value, str):
101
- raise ValueError("expected a number, got a quoted string")
102
- return value
103
-
104
-
105
- #: A float that accepts an int but never a bool or a quoted string.
106
- #:
107
- #: `allow_inf_nan=False` is the half that is not about tidiness. YAML spells
108
- #: them `.nan` and `.inf`, both parse to legal floats, and a NaN makes every
109
- #: `<` and `>` comparison FALSE -- so `compaction_trigger_fraction: .nan`
110
- #: would mean compaction never fires, silently, with no error ever raised.
111
- #: Refused here once rather than per field.
112
- Number = Annotated[float, BeforeValidator(_number_only),
113
- Field(allow_inf_nan=False)]
114
-
115
- # THE THREE RANGE SHAPES, MIRRORED FROM THE SETTINGS VALIDATOR.
116
- #
117
- # `core/config_loader.py` already expresses exactly these three for
118
- # `settings.json` -- `_UNIT`, `_POSITIVE_INT`, `_NON_NEGATIVE_INT` -- and the
119
- # same values arriving from `config.yaml` had no range check at all, so
120
- # `max_iterations: 0` and `compaction_trigger_fraction: 5.0` were accepted.
121
- # Mirrored rather than imported, deliberately: importing from `core/` is the
122
- # cycle this module exists to avoid. `security/protected_paths.py` carries the
123
- # same kind of deliberate duplicate and says so about `_user_config_dir`.
124
-
125
- #: A number in [0, 1]. Weights, ratios, fractions and authority scores.
126
- Unit = Annotated[float, BeforeValidator(_number_only),
127
- Field(ge=0.0, le=1.0, allow_inf_nan=False)]
128
-
129
- #: A count that must be at least one. A ceiling of zero is not a tighter
130
- #: bound, it is a harness that cannot do the thing at all.
131
- PositiveInt = Annotated[int, Field(strict=True, gt=0)]
132
-
133
- #: A count where zero is a real answer -- no retries, no injected memories.
134
- NonNegativeInt = Annotated[int, Field(strict=True, ge=0)]
135
-
136
- #: A TCP port. `ssh_port` was a lax `int` until #213, so `true` became port
137
- #: 1 and `99999` reached the SSH call before anything said no.
138
- Port = Annotated[int, Field(strict=True, ge=1, le=65535)]
139
-
140
- #: A path that must name something. An empty `db_path` was accepted until
141
- #: #213 and opened SQLite's anonymous temporary database, so every thread
142
- #: and memory vanished at exit without a word. `workspace_dir` is NOT one,
143
- #: deliberately: see its field.
144
- NonEmptyStr = Annotated[str, Field(min_length=1)]
145
-
146
- #: A duration in seconds that must be positive.
147
- PositiveNumber = Annotated[float, BeforeValidator(_number_only),
148
- Field(gt=0.0, allow_inf_nan=False)]
149
-
150
- #: A multiplier where zero is meaningful (`1 + tolerance`).
151
- NonNegativeNumber = Annotated[float, BeforeValidator(_number_only),
152
- Field(ge=0.0, allow_inf_nan=False)]
153
-
154
- #: "always" / "tiered" / "contained" / "never" (§48 CE2 added the third).
155
- #: A closed vocabulary rather than a plain string, so an unknown mode is a
156
- #: startup failure and never a policy that quietly means something else --
157
- #: one direction of a fallback asks about everything and the other about
158
- #: nothing, and a typo cannot pick.
159
- ShellApprovalMode = Literal["always", "tiered", "contained", "never"]
160
-
161
- #: "rederive" / "chain". Validated here AND in
162
- #: `config_loader.effective_compaction`, which checks the value a
163
- #: `settings.json` or a `/compact --strength N` supplied against this list.
164
- CompactionStrategy = Literal["rederive", "chain"]
165
-
166
-
167
- class _Model(BaseModel):
168
- """Common posture: no unknown keys, no mutation after validation."""
169
-
170
- model_config = ConfigDict(extra="forbid", frozen=True)
171
-
172
-
173
- # ---------------------------------------------------------------------------
174
- # ---- The two permission tables --------------------------------------------
175
- # ---------------------------------------------------------------------------
176
- #
177
- # The FIELD NAMES stay declared in Python while the booleans come from YAML,
178
- # and the split is deliberate. `tools/registry.py` checks at import that every
179
- # statically registered tool has a field in `ToolPermissions` and -- with one
180
- # deliberate exception -- in `ToolApprovals` (D24); with the names
181
- # in YAML, omitting one would turn that build-time check into a runtime
182
- # surprise in a data file. With the names here and the fields required, a
183
- # `config.yaml` missing `shell` cannot start the harness at all.
184
- #
185
- # The exception is `shell` in approvals: its approval is governed solely by
186
- # `shell_approval_mode`, and a second switch there could only force `always`
187
- # -- exactly what the mode already says. A test pins this as the SOLE
188
- # exemption, so a future omission cannot ride in on its precedent.
189
- #
190
- # Field ORDER matters and follows `config.py`'s: `ToolPermissions` and
191
- # `ToolApprovals` are rebuilt as real dataclasses from these models, and
192
- # `tests/test_docs_consistency.py` reads `vars(config.ToolPermissions())` to
193
- # check README's approval table names every tool.
194
-
195
- class ToolPermissionsModel(_Model):
196
- """Whether each registered tool may be called at all.
197
-
198
- `security/permissions.is_tool_allowed` constructs `ToolPermissions()`
199
- fresh on every call and returns before any context or approval logic, so
200
- these are a global floor that no agent context or skill can widen (D14).
201
- """
202
-
203
- web_search: StrictBool
204
- fetch_url: StrictBool
205
- get_time: StrictBool
206
- arxiv_search: StrictBool
207
- symbolic_math: StrictBool
208
- linear_algebra: StrictBool
209
- probability_stats: StrictBool
210
- discrete_math: StrictBool
211
- logic: StrictBool
212
- geometry: StrictBool
213
- read: StrictBool
214
- view_image: StrictBool
215
- write: StrictBool
216
- edit: StrictBool
217
- shell: StrictBool
218
- shell_background: StrictBool
219
- shell_monitor: StrictBool
220
- shell_interactive: StrictBool
221
- shell_input: StrictBool
222
- shell_sessions: StrictBool
223
- shell_output: StrictBool
224
- shell_kill: StrictBool
225
- load_skill: StrictBool
226
- spawn_subagent: StrictBool
227
- pin: StrictBool
228
- unpin: StrictBool
229
- remember: StrictBool
230
- read_project_doc: StrictBool
231
- write_project_doc: StrictBool
232
- ask_user: StrictBool
233
- todo_write: StrictBool
234
-
235
-
236
- class ToolApprovalsModel(_Model):
237
- """Whether each tool needs a human yes before it runs.
238
-
239
- Approval ORs across every layer, so a `True` here is a one-way ratchet
240
- that can only ever add prompts. `shell`, `shell_background`,
241
- `shell_monitor` and `shell_interactive` are deliberately absent
242
- (security/permissions.py's
243
- APPROVAL_BY_SHELL_MODE): their approval is governed solely by
244
- `shell_approval_mode` (always / tiered / contained / never), and a
245
- second switch here could only force `always` -- exactly what the mode
246
- already says. An agent's `approval_overrides` keeps its own one-way
247
- power over them through the context layer.
248
- """
249
-
250
- web_search: StrictBool
251
- fetch_url: StrictBool
252
- get_time: StrictBool
253
- arxiv_search: StrictBool
254
- symbolic_math: StrictBool
255
- linear_algebra: StrictBool
256
- probability_stats: StrictBool
257
- discrete_math: StrictBool
258
- logic: StrictBool
259
- geometry: StrictBool
260
- read: StrictBool
261
- view_image: StrictBool
262
- write: StrictBool
263
- edit: StrictBool
264
- shell_input: StrictBool
265
- shell_sessions: StrictBool
266
- shell_output: StrictBool
267
- shell_kill: StrictBool
268
- load_skill: StrictBool
269
- spawn_subagent: StrictBool
270
- pin: StrictBool
271
- unpin: StrictBool
272
- remember: StrictBool
273
- read_project_doc: StrictBool
274
- write_project_doc: StrictBool
275
- ask_user: StrictBool
276
- todo_write: StrictBool
277
-
278
-
279
- # ---------------------------------------------------------------------------
280
- # ---- The whole file -------------------------------------------------------
281
- # ---------------------------------------------------------------------------
282
- #
283
- # Annotations preserve the RUNTIME TYPES consumers already rely on, which is
284
- # why several are looser than they could be:
285
- #
286
- # * `similarity_calibration` stays `dict[str, dict[str, float]]` rather than
287
- # a nested model, because `source_scoring.py` subscripts the band with
288
- # `band["floor"]`.
289
- # * `ensemble_models` is `list[Any] | None`, not a model list, because
290
- # `orchestrator._ensemble_roster` validates the entries itself and reports
291
- # the malformed one -- a schema that rejected them first would move that
292
- # error message and say less.
293
- # * `critic_model` / `embedder_model` stay plain dicts, because
294
- # `core/pipeline_models.resolve` treats them as dicts and the user-tier
295
- # store outranks them (SQ7).
296
-
297
- class HarnessConfig(_Model):
298
- """Every value in `config.yaml`, validated.
299
-
300
- Field order is `config.py`'s section order, so the two can be diffed.
301
- """
302
-
303
- # -- Model / loop ------------------------------------------------------
304
- model_name: str
305
- max_tokens: PositiveInt
306
- max_iterations: PositiveInt
307
- # Batch 91. Zero is a real answer for both: no retry, and no wait.
308
- model_call_max_retries: NonNegativeInt
309
- model_call_retry_base_delay_s: NonNegativeNumber
310
-
311
- # -- Subagents ---------------------------------------------------------
312
- # Zero is a real answer here: `subagent_depth >= this` then refuses
313
- # every spawn, which is a harness with subagents turned off.
314
- subagent_max_depth: NonNegativeInt
315
- subagent_max_parallel: PositiveInt
316
-
317
- # -- Deep research pipeline -------------------------------------------
318
- max_pipeline_retries: NonNegativeInt
319
- max_json_retries: NonNegativeInt
320
-
321
- # -- Ensemble mode -----------------------------------------------------
322
- ensemble_mode: StrictBool
323
- ensemble_models: Optional[list[Any]]
324
-
325
- # -- Sampling-parameter support ---------------------------------------
326
- models_rejecting_sampling_params: frozenset[str]
327
-
328
- # -- Critic / embedder routing ----------------------------------------
329
- critic_model: Optional[dict[str, Any]]
330
- embedder_model: Optional[dict[str, Any]]
331
- similarity_calibration: dict[str, dict[str, Unit]]
332
- default_similarity_calibration: dict[str, Unit]
333
- embedder_prefixes: dict[str, dict[str, str]]
334
-
335
- # -- Source authority --------------------------------------------------
336
- domain_authority_classes: dict[str, Unit]
337
- default_domain_authority: Unit
338
- domain_authority_suffixes: dict[str, str]
339
- authority_adjustment_cap: Unit
340
-
341
- # -- The sources/ artifact --------------------------------------------
342
- persist_source_text: StrictBool
343
-
344
- # -- Scholarly authority (OpenAlex) -----------------------------------
345
- scholar_lookup: StrictBool
346
- scholar_api_url: str
347
- scholar_timeout_s: PositiveNumber
348
- scholar_max_retries: NonNegativeInt
349
- scholar_cache_ttl_s: NonNegativeInt
350
- scholar_mailto: str
351
- scholar_venue_weight: Unit
352
- scholar_citation_weight: Unit
353
- scholar_author_weight: Unit
354
- scholar_venue_credit: dict[str, Unit]
355
- scholar_h_saturation: PositiveInt
356
- scholar_min_cohort_size: PositiveInt
357
- scholar_min_citation_age_days: NonNegativeInt
358
- scholar_retracted_authority: Unit
359
-
360
- # -- Reasoning effort --------------------------------------------------
361
- default_effort: Optional[str]
362
- model_effort_levels: dict[str, list[str]]
363
- default_effort_levels: list[str]
364
- google_thinking_budgets: dict[str, StrictInt]
365
-
366
- # -- Database ----------------------------------------------------------
367
- db_path: NonEmptyStr
368
-
369
- # -- File-ops workspace ------------------------------------------------
370
- # `output_dir` and `workspace_dir_explicit` are deliberately absent --
371
- # see DERIVED_VALUES below. `workspace_is_project` is NOT the second of
372
- # those: it is an ordinary key that FEEDS one (TECHNICAL_DEBT 28).
373
- # A bare `str`, not `NonEmptyStr` (#213, measured): an empty workspace
374
- # is refused BY NAME at `protected_paths.check_workspace`, which answers
375
- # both routes to it -- this key and an empty AGENT_WORKSPACE, which
376
- # folds in here. Refusing it here too would answer the variable's case
377
- # first and worse, as an error about config.yaml.
378
- # test_an_empty_variable_reaches_the_guard_as_an_empty_path pins it.
379
- workspace_dir: str
380
- workspace_is_project: StrictBool
381
- max_file_size_bytes: PositiveInt
382
- max_read_lines: PositiveInt
383
- max_read_chars: PositiveInt
384
- max_image_bytes: PositiveInt
385
-
386
- # -- /init -------------------------------------------------------------
387
- initializer_agent: str
388
- init_read_chars: PositiveInt
389
- init_max_steps: PositiveInt
390
- init_max_hub_chars: PositiveInt
391
- init_diff_shown_lines: PositiveInt
392
-
393
- # -- MCP teardown ------------------------------------------------------
394
- teardown_budget_s: PositiveNumber
395
-
396
- # -- MCP results -------------------------------------------------------
397
- mcp_max_event_bytes: PositiveInt
398
-
399
- # -- Shell / sandbox ---------------------------------------------------
400
- shell_binary: str
401
- allow_insecure_sandbox_fallback: StrictBool
402
- auto_approve_sandbox_fallback: StrictBool
403
- # ROADMAP_v3 §49 slice 3 (SS35). An AUTHORITY key: it decides
404
- # whether a command may leave the container at all. `wsl_distro`
405
- # below is not -- it names WHICH distro, which only matters once
406
- # this one is true.
407
- allow_wsl_backend: StrictBool
408
- wsl_distro: str
409
- # ROADMAP_v3 §49 slice 4 (SS46). One host, flat scalars -- SS36's
410
- # shape, because a remote host is a fact about this machine's
411
- # situation and not about any one command. The agent says
412
- # `backend: "ssh"` and gets THE configured host; it never names one.
413
- allow_ssh_backend: StrictBool
414
- ssh_host: str
415
- ssh_user: str
416
- ssh_port: Port
417
- ssh_identity_file: str
418
- ssh_remote_workspace: str
419
- ssh_host_key: str
420
- ssh_binary: str
421
- shell_approval_mode: ShellApprovalMode
422
- sandbox_docker_image: str
423
- sandbox_timeout_seconds: PositiveInt
424
- sandbox_memory_mb: PositiveInt
425
- sandbox_cpu_seconds: PositiveInt
426
- sandbox_max_pids: PositiveInt
427
- # ROADMAP_v3 §49 (SS12, SS13): background and monitor sessions. Resource
428
- # limits, like the four above -- NOT authority keys and not in the
429
- # frozen posture: none of them decides whether a command is asked about.
430
- shell_session_timeout_cap_s: PositiveInt
431
- shell_session_idle_timeout_s: PositiveInt
432
- shell_session_max_live: PositiveInt
433
- shell_session_max_consecutive_wakes: PositiveInt
434
- shell_session_output_head_chars: PositiveInt
435
- shell_session_output_tail_chars: PositiveInt
436
-
437
- # -- Output redaction / tool isolation --------------------------------
438
- redact_tool_outputs: StrictBool
439
- tool_compute_timeout_s: PositiveInt
440
- network_allowed_commands: list[str]
441
- inert_commands: list[str]
442
-
443
- # -- Research grants and review ---------------------------------------
444
- max_granted_tool_calls: NonNegativeInt
445
- attended_approval_timeout_s: PositiveInt
446
- subagent_review: StrictBool
447
- max_review_findings: NonNegativeInt
448
- max_review_refinements: NonNegativeInt
449
-
450
- # -- Compaction --------------------------------------------------------
451
- compaction_trigger_fraction: Unit
452
- compaction_min_headroom_tokens: PositiveInt
453
- compaction_max_headroom_fraction: Unit
454
- compaction_trigger_tokens: PositiveInt
455
- compaction_warning_margin_tokens: NonNegativeInt
456
- compaction_keep_recent_tokens: NonNegativeInt
457
- compaction_keep_recent_turns: NonNegativeInt
458
- pin_max_trigger_fraction: Unit
459
- compaction_strength: PositiveInt
460
- compaction_max_retries: NonNegativeInt
461
- compaction_target_ratios: dict[int, Unit]
462
- compaction_ratio_tolerance: NonNegativeNumber
463
- compaction_strategy: CompactionStrategy
464
- # The ELEMENT vocabulary, not just the scalar's. Typed `str`, a
465
- # `hybrid` added here passed `effective_compaction`'s membership test
466
- # and then `core/compaction.py` treated anything that is not exactly
467
- # `chain` as `rederive` -- silently, recording `rederive` in the
468
- # checkpoint. Non-empty because an empty roster makes every strategy
469
- # illegal, including the one this file ships.
470
- compaction_strategies: Annotated[tuple[CompactionStrategy, ...],
471
- Field(min_length=1)]
472
- max_injected_memories: NonNegativeInt
473
-
474
- # -- Catalog text ------------------------------------------------------
475
- max_catalog_text_chars: PositiveInt
476
-
477
- # -- Summaries, references, the checklist -----------------------------
478
- compactor_agent: str
479
- summary_target_chars: PositiveInt
480
- max_injected_refs: NonNegativeInt
481
- # Non-empty: this becomes the enum in todo_write's own schema.
482
- todo_statuses: Annotated[tuple[str, ...], Field(min_length=1)]
483
- max_todo_items: NonNegativeInt
484
- compaction_pipeline_backstop_tokens: NonNegativeInt
485
-
486
- # -- Context windows ---------------------------------------------------
487
- model_context_windows: dict[str, PositiveInt]
488
- default_context_window: PositiveInt
489
-
490
- # -- Connecting a model (ROADMAP_v3 §79, HD5) --------------------------
491
- # A public client id; empty hides the sign-in.
492
- hf_oauth_client_id: str
493
-
494
- # -- Tool permissions and approvals -----------------------------------
495
- tool_permissions: ToolPermissionsModel
496
- tool_approvals: ToolApprovalsModel
497
-
498
- @model_validator(mode="after")
499
- def _check_cross_field_defaults(self) -> HarnessConfig:
500
- """Fail fast on a harness default that can never work.
501
-
502
- EVERY CHECK HERE IS AN INVARIANT BETWEEN TWO KEYS OF THIS FILE. A
503
- single field's shape belongs in its annotation; what belongs here is
504
- the pairs -- a value that is individually well-typed and impossible
505
- beside its neighbour. Each one was verified to be ACCEPTED before
506
- this validator grew, and each failed somewhere later and further
507
- from the edit that caused it.
508
-
509
- The four that are about a key the CONSUMER SUBSCRIBES DIRECTLY are
510
- the sharpest, because the annotation could not express them: the
511
- type says `dict[str, Unit]` while `scholar.py` and
512
- `source_scoring.py` index particular keys out of it, so a table that
513
- merely has the right value type still raises `KeyError` in the
514
- middle of a research run, after the model calls are paid for.
515
-
516
- Runtime customisation is unaffected: `/effort` and
517
- `/compact --strength` go through `effort_for()` /
518
- `effective_compaction()`, not the schema, so per-model and
519
- per-invocation levels keep working.
520
- """
521
- if self.compaction_strength not in self.compaction_target_ratios:
522
- raise ValueError(
523
- f"compaction_strength {self.compaction_strength!r} must be "
524
- f"one of {sorted(self.compaction_target_ratios)} "
525
- f"(keys of compaction_target_ratios)")
526
- if (self.default_effort is not None
527
- and self.default_effort not in self.default_effort_levels):
528
- raise ValueError(
529
- f"default_effort {self.default_effort!r} must be null or one "
530
- f"of {self.default_effort_levels} "
531
- f"(members of default_effort_levels)")
532
- # Defence in depth rather than the only guard: `initialize()` calls
533
- # `effective_compaction()`, which already refuses this pair at
534
- # startup on the CLI and TUI paths. Checked here too because it is
535
- # the same shape as the strength pair above, the message names the
536
- # config.yaml key rather than the settings.json one, and a process
537
- # that never calls `initialize()` -- a library import, a bare test --
538
- # otherwise carries the incoherent pair to the first fold.
539
- if self.compaction_strategy not in self.compaction_strategies:
540
- raise ValueError(
541
- f"compaction_strategy {self.compaction_strategy!r} must be "
542
- f"one of {list(self.compaction_strategies)} "
543
- f"(members of compaction_strategies)")
544
-
545
- # -- keys the consumers index directly ----------------------------
546
- for key in ("unknown", "repository"):
547
- if key not in self.scholar_venue_credit:
548
- raise ValueError(
549
- f"scholar_venue_credit must contain {key!r}: "
550
- f"core/reasoning/scholar.py subscripts it for a work "
551
- f"whose location type is unrecognised, and a missing "
552
- f"entry is a KeyError mid research run")
553
- if "restricted_registry" not in self.domain_authority_classes:
554
- raise ValueError(
555
- "domain_authority_classes must contain 'restricted_registry': "
556
- "core/reasoning/source_scoring.py subscripts it for a "
557
- "second-level government or academic host")
558
- unknown_classes = sorted(
559
- {name for name in self.domain_authority_suffixes.values()
560
- if name not in self.domain_authority_classes})
561
- if unknown_classes:
562
- raise ValueError(
563
- f"domain_authority_suffixes maps hosts onto classes that "
564
- f"domain_authority_classes does not define: "
565
- f"{unknown_classes}. source_scoring.py looks the class name "
566
- f"up directly, so each is a KeyError on the first host that "
567
- f"matches that suffix")
568
- bands = {"default_similarity_calibration":
569
- self.default_similarity_calibration}
570
- bands.update({f"similarity_calibration[{name!r}]": band
571
- for name, band in self.similarity_calibration.items()})
572
- for where, band in bands.items():
573
- missing = [edge for edge in ("floor", "ceiling")
574
- if edge not in band]
575
- if missing:
576
- raise ValueError(
577
- f"{where} is missing {missing}: source_scoring.py reads "
578
- f"both edges of every calibration band")
579
- if band["floor"] > band["ceiling"]:
580
- raise ValueError(
581
- f"{where} has floor {band['floor']} above ceiling "
582
- f"{band['ceiling']}, which no similarity can fall inside")
583
- return self
584
-
585
-
586
- # ---------------------------------------------------------------------------
587
- # ---- Environment overrides ------------------------------------------------
588
- # ---------------------------------------------------------------------------
589
- #
590
- # `config.yaml` holds the static default; the variable wins when it is set.
591
- # Applied BEFORE validation, once, inside `load()` -- never at call time, for
592
- # the reason rule 2 in this module's docstring gives.
593
- #
594
- # A declared table rather than five hand-written expressions so the set is
595
- # enumerable: `HARNESS_ENV_VARS` below is what documentation and any future
596
- # config surface can list without going stale.
597
-
598
- #: {UPPER_CASE config name: environment variable}. String-valued only; the
599
- #: variable's value is used verbatim, with no parsing, exactly as
600
- #: `os.environ.get(var, default)` did.
601
- ENV_OVERRIDES = {
602
- "MODEL_NAME": "AGENT_MODEL",
603
- "DB_PATH": "APP_DB_PATH",
604
- "WORKSPACE_DIR": "AGENT_WORKSPACE",
605
- "SHELL_BINARY": "AGENT_SHELL",
606
- "SANDBOX_DOCKER_IMAGE": "AGENT_SANDBOX_IMAGE",
607
- }
608
-
609
- #: Every variable this module reads, including the two that only reach a
610
- #: derived value. `AGENT_WORKSPACE` appears in both.
611
- HARNESS_ENV_VARS = tuple(sorted(
612
- set(ENV_OVERRIDES.values()) | {"AGENT_OUTPUT_DIR", "AGENT_WORKSPACE"}))
613
-
614
- #: The two values with NO `config.yaml` key, because neither is a static
615
- #: default and inventing one would change behaviour. Named here so the
616
- #: round-trip check in `tests/` can tell "absent on purpose" from "forgotten".
617
- #: `workspace_is_project` is NOT the key for the second of these -- it is one
618
- #: of the two inputs `derived_values` reads to compute it, and the other is
619
- #: an environment variable no key can stand in for.
620
- DERIVED_VALUES = ("OUTPUT_DIR", "WORKSPACE_DIR_EXPLICIT")
621
-
622
- #: Keys that need a human at the keyboard. No UNATTENDED surface may write
623
- #: them -- not a settings file, not an environment variable, not a tool
624
- #: call -- and `/config` writes one only behind a confirmation naming what
625
- #: the key permits (batch 84; `config_edit.AUTHORITY_EFFECT` is that
626
- #: sentence, per key, and a test holds the two lists against each other).
627
- #: Four are the frozen security posture
628
- #: (`security/posture.Posture`); three are the Authority rosters that name a
629
- #: provider the harness will call (E2, SQ7); two are the global tool floor.
630
- #:
631
- #: `ensemble_mode` is deliberately NOT here. It is a MODE, persistable in
632
- #: `settings.json` today, and the worst it can do is spend more of a provider
633
- #: the user already chose -- the line `core/config_loader.py` draws between
634
- #: authority and cost.
635
- HARNESS_AUTHORITY_KEYS = frozenset({
636
- "shell_approval_mode",
637
- "allow_insecure_sandbox_fallback",
638
- "auto_approve_sandbox_fallback",
639
- "allow_wsl_backend",
640
- "allow_ssh_backend",
641
- "redact_tool_outputs",
642
- "ensemble_models",
643
- "critic_model",
644
- "embedder_model",
645
- "tool_permissions",
646
- "tool_approvals",
647
- })
648
-
649
-
650
- # ---------------------------------------------------------------------------
651
- # ---- Reading the file -----------------------------------------------------
652
- # ---------------------------------------------------------------------------
653
-
654
- def _reader() -> YAML:
655
- """The import-path reader.
656
-
657
- `typ="safe"` rather than `typ="rt"`: the round-trip parser exists to
658
- preserve comments across a WRITE, and nothing writes this file yet. Safe
659
- mode also refuses `!!python/...` tags outright, which matters for a file
660
- that decides the tool permissions. Both modes raise `DuplicateKeyError` on
661
- a repeated key, so a second `shell_approval_mode` is an error rather than
662
- a silent last-one-wins.
663
-
664
- A future config editor wants `YAML(typ="rt")` instead, on its own write
665
- path -- that is the reason `ruamel.yaml` is the dependency here rather
666
- than the `pyyaml` that `core/config_loader.py` uses for frontmatter.
667
- """
668
- return YAML(typ="safe")
669
-
670
-
671
- def _describe(path: Optional[str]) -> str:
672
- """How to name the file being complained about.
673
-
674
- `config.yaml` for the live document, the caller's path for a candidate.
675
- Hardcoding `CONFIG_FILENAME` made every message about a candidate misname
676
- the file and, worse, offer the live document's remedy -- telling someone
677
- whose draft has a typo that "the package is incomplete" and to "restore
678
- the file from git".
679
- """
680
- if path is None or os.path.abspath(path) == CONFIG_PATH:
681
- return CONFIG_FILENAME
682
- return os.path.basename(path)
683
-
684
-
685
- def read_document(path: Optional[str] = None) -> dict:
686
- """The raw mapping, parsed and nothing else. No validation, no env."""
687
- target = path or CONFIG_PATH
688
- name = _describe(path)
689
- try:
690
- with open(target, encoding="utf-8") as handle:
691
- data = _reader().load(handle)
692
- except FileNotFoundError:
693
- if path is None:
694
- raise ValueError(
695
- f"{CONFIG_FILENAME} is missing at {target}. It ships with the "
696
- f"harness beside config.py and holds every tunable value, so "
697
- f"nothing can start without it. If this is an installed copy, "
698
- f"the package is incomplete; if it is a checkout, restore the "
699
- f"file from git.") from None
700
- raise ValueError(f"{name} does not exist at {target}.") from None
701
- except UnicodeDecodeError as exc:
702
- # A ValueError but NOT an OSError, so the clause below never saw it
703
- # and the message named neither the file nor the remedy. The way to
704
- # arrive here on Windows is Notepad's "ANSI" or "UTF-16" save option.
705
- raise ValueError(
706
- f"{name} at {target} is not valid UTF-8 ({exc}). Save it as "
707
- f"UTF-8 without a byte-order mark; an editor offering \"ANSI\" "
708
- f"or \"UTF-16\" will produce this.") from None
709
- except (OSError, YAMLError) as exc:
710
- raise ValueError(f"{name} at {target} could not be "
711
- f"read: {exc}") from exc
712
- if not isinstance(data, dict):
713
- raise ValueError(
714
- f"{name} at {target} is not a mapping of settings "
715
- f"(parsed as {type(data).__name__}).")
716
- return data
717
-
718
-
719
- def validate(data: dict, source: Optional[str] = None,
720
- overridden: Optional[dict] = None) -> HarnessConfig:
721
- """Validate a raw mapping, reporting every problem at once.
722
-
723
- Raises `ValueError` naming the file and each offending key. A missing key
724
- and an unknown key are both errors -- see rule 3 in the module docstring.
725
-
726
- `overridden` is `{key: environment variable}` for the keys the
727
- environment set (#213). A problem with one of those names the variable,
728
- because the file holds a good value and someone reading only the file
729
- would find nothing wrong with it -- `APP_DB_PATH=` is the case that made
730
- it reachable, now that `db_path` must not be empty.
731
- """
732
- where = source or CONFIG_PATH
733
- name = _describe(source)
734
- try:
735
- return HarnessConfig(**data)
736
- except TypeError as exc:
737
- # `HarnessConfig(**data)` raises before pydantic is entered when a
738
- # key is not a string, so `except ValidationError` never saw it and
739
- # the one input class that most needs the file-and-key message got a
740
- # bare `TypeError: keywords must be strings`. The way to arrive here
741
- # is de-indenting a nested block: `1: 0.4` at column 0 under
742
- # `compaction_target_ratios` parses to a mapping with an int key,
743
- # which passes `read_document`'s mapping guard.
744
- bad = sorted(repr(key) for key in data if not isinstance(key, str))
745
- raise ValueError(
746
- f"{name} at {where} has {'keys' if len(bad) != 1 else 'a key'} "
747
- f"that {'are' if len(bad) != 1 else 'is'} not a setting name: "
748
- f"{', '.join(bad) or exc}. A nested block de-indented to column "
749
- f"0 does this -- check the indentation around them.") from None
750
- except ValidationError as exc:
751
- lines = []
752
- for err in exc.errors():
753
- key = ".".join(str(part) for part in err["loc"]) or "<root>"
754
- variable = (overridden or {}).get(key)
755
- origin = f" (set by {variable})" if variable else ""
756
- lines.append(f" {key}{origin}: {err['msg']}")
757
- raise ValueError(
758
- f"{name} at {where} is not valid "
759
- f"({len(lines)} problem(s)):\n" + "\n".join(lines)) from None
760
-
761
-
762
- def _overlay_env(data: dict) -> dict:
763
- """Fold the environment into the raw document, BEFORE validation.
764
-
765
- Before validation rather than after, and that ordering is the whole
766
- reason this is a separate function. An override applied afterwards would
767
- live only in the namespace `config.py` publishes, so
768
- `config_schema.current()` and `config.<NAME>` would disagree about any
769
- key that has a variable -- silently, and only for whoever adds the sixth
770
- override to a key `core/config_loader.py` happens to read. Folded in
771
- here there is ONE model, with the environment already in it, and an
772
- override goes through the same type check the file's value does.
773
-
774
- Returns a copy with the overrides folded in, leaving the input untouched,
775
- so a caller validating a candidate file does not have its document
776
- rewritten underneath it.
777
- """
778
- merged = dict(data)
779
- for name, variable in ENV_OVERRIDES.items():
780
- override = os.environ.get(variable)
781
- if override is not None:
782
- merged[name.lower()] = override
783
- return merged
784
-
785
-
786
- def _overridden() -> dict:
787
- """`{key: variable}` for each key the environment sets right now --
788
- what `validate` names beside a problem with one of them."""
789
- return {name.lower(): variable
790
- for name, variable in ENV_OVERRIDES.items()
791
- if os.environ.get(variable) is not None}
792
-
793
-
794
- def derived_values(cfg: HarnessConfig) -> dict:
795
- """The two `{UPPER_CASE_NAME: value}` entries with no `config.yaml` key.
796
-
797
- Separate from the model because neither is a static default: one is a
798
- composed path and the other is a question the environment answers and
799
- YAML cannot ask. `DERIVED_VALUES` names them so a completeness check can
800
- tell "absent on purpose" from "forgotten".
801
-
802
- TAKES `cfg` SINCE BATCH 111, because one of the two is no longer a
803
- question about the environment ALONE -- see `WORKSPACE_DIR_EXPLICIT`
804
- below. There is exactly one caller and it already holds the config, so
805
- this costs nothing; what it buys is that the file gets a say in a value
806
- that decides where the work is.
807
- """
808
- return {
809
- # AGENT_OUTPUT_DIR, else `<AGENT_WORKSPACE or ".">/output`. ONE
810
- # expression with no branch, carried over verbatim, and note the
811
- # default is "." here where WORKSPACE_DIR's is "./workspace": an unset
812
- # variable still means `./output` rather than `./workspace/output`.
813
- # There is deliberately no `output_dir` key -- one would have to be
814
- # ignored whenever AGENT_WORKSPACE is named, which is the branch this
815
- # form exists to avoid.
816
- "OUTPUT_DIR": os.environ.get(
817
- "AGENT_OUTPUT_DIR",
818
- os.path.join(os.environ.get("AGENT_WORKSPACE", "."), "output")),
819
- # WAS THE WORKSPACE NAMED AS THE PROJECT? `main()` uses this to
820
- # decide whether the resolved workspace is also the PROJECT PATH.
821
- # TWO ROUTES, AND EACH EXISTS FOR A REASON THE OTHER CANNOT SERVE
822
- # (TECHNICAL_DEBT 28, batch 111):
823
- #
824
- # * `AGENT_WORKSPACE`, by its PRESENCE and never its value. A value
825
- # test here would move the project one level down for everyone
826
- # who set nothing, because the shipped `./workspace` is a
827
- # subdirectory of the launch directory. YAML cannot ask whether a
828
- # variable was named, which is why this half is not a key.
829
- # * `workspace_is_project`, which IS a key, for the reader who has
830
- # no variable to set. Before it, someone who wrote their project
831
- # into `workspace_dir` got the workspace they asked for and a
832
- # project of `os.getcwd()` -- and launched from the install tree,
833
- # a refusal telling them to set a variable they believed they had
834
- # just set. Shipped `false`, so no existing install moves.
835
- #
836
- # OR, not "the file wins" or "the variable wins": both say the same
837
- # thing about the same directory, so there is no precedence question
838
- # to answer, and answering one would mean a user who did both getting
839
- # less than a user who did either.
840
- "WORKSPACE_DIR_EXPLICIT": (cfg.workspace_is_project
841
- or "AGENT_WORKSPACE" in os.environ),
842
- }
843
-
844
-
845
- def as_module_namespace(cfg: HarnessConfig) -> dict:
846
- """`{UPPER_CASE_NAME: value}` for `config.py` to publish as globals.
847
-
848
- Excludes the two permission tables, which `config.py` turns back into
849
- dataclasses, and includes the two derived values. The environment is
850
- already in `cfg` -- see `_overlay_env`.
851
- """
852
- values = {}
853
- for name in HarnessConfig.model_fields:
854
- if name in ("tool_permissions", "tool_approvals"):
855
- continue
856
- values[name.upper()] = getattr(cfg, name)
857
- values.update(derived_values(cfg))
858
- return values
859
-
860
-
861
- def _make_dataclass(name: str, model: BaseModel) -> type:
862
- """Rebuild `ToolPermissions` / `ToolApprovals` as real dataclasses.
863
-
864
- A real dataclass rather than the pydantic model itself, because the whole
865
- codebase depends on the shape: `security/permissions.py` calls
866
- `config.ToolPermissions()` with no arguments, tests mutate an instance's
867
- fields and then swap the module attribute for a factory returning it, and
868
- `tests/test_docs_consistency.py` enumerates `vars(instance)`. A frozen
869
- pydantic model satisfies none of those.
870
- """
871
- fields = [(field, bool, dataclasses.field(default=getattr(model, field)))
872
- for field in type(model).model_fields]
873
- # The binding below (`ToolPermissions` / `ToolApprovals` globals plus the
874
- # idempotent factories) is only half of what makes these PICKLABLE: pickle
875
- # looks the class up by (`__module__`, `__qualname__`), so the module must
876
- # also be right. `make_dataclass` sets `__module__` from the calling frame
877
- # only on 3.12+ (via its `module=` kwarg, which the 3.11 floor cannot
878
- # take); on 3.11 the class is built through `types.new_class`, and
879
- # `type.__new__` backfills a missing `__module__` from the frame doing
880
- # the calling -- inside `types.py`, so pickle looked for
881
- # `types.ToolPermissions` and failed. Assigned explicitly, which works on
882
- # every version. The original `@dataclass class ToolPermissions` in
883
- # config.py pickled fine, so this was a silent shape regression that
884
- # nothing would notice until one of these crossed a process boundary.
885
- cls = dataclasses.make_dataclass(name, fields)
886
- cls.__module__ = __name__
887
- return cls
888
-
889
-
890
- _cached: Optional[HarnessConfig] = None
891
- #: The rebuilt dataclasses, built once. Bound at module level so `pickle` can
892
- #: resolve `config_schema.ToolPermissions` by name, and so the two factories
893
- #: are idempotent -- a second call used to hand back a fresh class whose
894
- #: instances compared unequal to the harness's own, because dataclass
895
- #: `__eq__` requires `other.__class__ is self.__class__`.
896
- ToolPermissions: Optional[type] = None
897
- ToolApprovals: Optional[type] = None
898
-
899
-
900
- def load(path: Optional[str] = None, force: bool = False) -> HarnessConfig:
901
- """Read, validate and cache `config.yaml`.
902
-
903
- Called by `config.py` at import, WITH `force=True` -- see the long note
904
- at that call. Importing `config` is what "bind the configuration now"
905
- means, so that module decides when the file is read; a cache that
906
- outlived a re-import of `config` would hand a fresh `config` the previous
907
- environment's values, which is a technique the suite actually uses.
908
-
909
- `core/config_loader.py` calls this with no arguments to read the shipped
910
- defaults it used to reach through `getattr(config, "<NAME>")`. The cache
911
- means that costs nothing and, more importantly, means the loader and the
912
- `config` module always see the same document.
913
-
914
- `path` JUDGES A CANDIDATE FILE ON ITS OWN, with no environment overlay
915
- and without touching the cache. That is the seam a restart-required
916
- config editor uses, and the overlay is left out for the reason the seam
917
- exists: the file is what the next launch will read, and the environment
918
- it will read it under is not knowable now. With the overlay in, a
919
- candidate missing `db_path` was ACCEPTED whenever `APP_DB_PATH` happened
920
- to be set in the editing shell, and then REFUSED at the startup it was
921
- supposed to be certifying. `force` applies to the live document only, so
922
- combining it with `path` asks for two different things at once and is
923
- refused rather than silently dropped.
924
- """
925
- global _cached
926
- if path is not None:
927
- if force:
928
- raise TypeError(
929
- "load(path=..., force=True) asks for two different things: "
930
- "`path` judges a candidate file and never touches the cache, "
931
- "`force` re-reads the live document into it. Pass one.")
932
- return validate(read_document(path), source=path)
933
- if _cached is None or force:
934
- _cached = validate(_overlay_env(read_document(None)),
935
- overridden=_overridden(),
936
- source=CONFIG_PATH)
937
- return _cached
938
-
939
-
940
- def current() -> HarnessConfig:
941
- """The validated document this process is running on."""
942
- return load()
943
-
944
-
945
- def tool_permissions_dataclass() -> type:
946
- """The `ToolPermissions` class, built once and bound to this module.
947
-
948
- Idempotent, and that matters rather than being tidy: dataclass `__eq__`
949
- compares `other.__class__ is self.__class__`, so a second class built
950
- from the same values produced instances that compared UNEQUAL to the
951
- harness's own, and `isinstance` against the live class was False.
952
- """
953
- global ToolPermissions
954
- if ToolPermissions is None:
955
- ToolPermissions = _make_dataclass(
956
- "ToolPermissions", current().tool_permissions)
957
- return ToolPermissions
958
-
959
-
960
- def tool_approvals_dataclass() -> type:
961
- """The `ToolApprovals` class, built once. See the sibling above."""
962
- global ToolApprovals
963
- if ToolApprovals is None:
964
- ToolApprovals = _make_dataclass(
965
- "ToolApprovals", current().tool_approvals)
966
- return ToolApprovals
1
+ """config_schema.py -- the schema for `config.yaml`, and the only reader of it.
2
+
3
+ WHY THIS FILE EXISTS SEPARATELY FROM `config.py`.
4
+
5
+ `config.py` is imported by 30 production modules and ~60 test files, and
6
+ `core/config_loader.py` imported it too when this file was written. If the
7
+ shim had reached back into `core/config_loader` for the values, that would
8
+ have been a cycle -- and `config.py` was a LEAF module, importing `os` and
9
+ `dataclasses` and nothing else, which is the property that made it safe for
10
+ `security/` to depend on. So the reader lives here, one hop away, and this
11
+ module imports the stdlib, `ruamel.yaml` and `pydantic` and NOTHING
12
+ first-party.
13
+
14
+ The loader reads `config_schema` rather than `config` now, so the cycle is
15
+ gone from both ends -- which is exactly why this rule has to be stated
16
+ rather than left to the import graph to imply. Keep it: an import of
17
+ anything under `core/`, `security/` or `tools/` from here puts the cycle
18
+ back by a longer route, and there would be nothing in the graph to stop it.
19
+
20
+ Three rules about `config.yaml` are load-bearing rather than tidy. All three
21
+ are argued at length in CONFIG_ARCHITECTURE.md; this is the summary.
22
+
23
+ 1. ONE PATH, RESOLVED FROM `__file__`, WITH NO ENVIRONMENT OVERRIDE.
24
+ `config.yaml` ships inside the harness. There is no user tier, no project
25
+ tier and no `AGENT_CONFIG_FILE`. That absence is the whole security
26
+ argument: `settings.json` rejects `shell_approval_mode`,
27
+ `ensemble_models`, `critic_model` and `embedder_model` BY NAME (R12, E2,
28
+ G7, SQ7) because a project's `settings.json` beats the user's and arrives
29
+ with a directory you cloned. A file with exactly one location, inside the
30
+ harness, carries none of that risk -- and an override variable would hand
31
+ it back. `AGENT_ENV_FILE` and `APP_DB_PATH` make such a variable look like
32
+ the obvious next step here. It is not; those redirect STATE, and this is a
33
+ shipped asset.
34
+
35
+ 2. READ ONCE, AT IMPORT, WITH THE ENVIRONMENT FOLDED IN THERE.
36
+ `security/posture.py` depends on `config` binding at import: that is what
37
+ makes `os.environ[...] = ...` unable to move the security posture, while
38
+ anything reading `os.environ` at CALL time would follow the mutation
39
+ (UN1, and batch 37's asymmetry). `tools/builtin/shell.py` also validates
40
+ the approval mode at ITS import, so the values must be final before any
41
+ other module runs. Nothing re-reads the file in a live process; an edit
42
+ takes effect at the next launch.
43
+
44
+ 3. EVERY FIELD IS REQUIRED AND UNKNOWN KEYS ARE REFUSED.
45
+ No field here has a default. A `config.yaml` missing a key is a startup
46
+ error naming that key, which is the D24 defect made impossible rather than
47
+ merely fixed: `fetch_url` was registered and documented as working while
48
+ having no `ToolPermissions` field, so `getattr(..., False)` denied every
49
+ call to it for as long as the tool existed. A default here would recreate
50
+ exactly that -- a value nobody chose, silently in force.
51
+ """
52
+
53
+ from __future__ import annotations
54
+
55
+ import dataclasses
56
+ import os
57
+ from typing import Annotated, Any, Literal, Optional
58
+
59
+ from pydantic import (
60
+ BaseModel,
61
+ BeforeValidator,
62
+ ConfigDict,
63
+ Field,
64
+ StrictBool,
65
+ StrictInt,
66
+ ValidationError,
67
+ model_validator,
68
+ )
69
+ from ruamel.yaml import YAML
70
+ from ruamel.yaml.error import YAMLError
71
+
72
+ # ---------------------------------------------------------------------------
73
+ # ---- Where the file is ----------------------------------------------------
74
+ # ---------------------------------------------------------------------------
75
+
76
+ CONFIG_FILENAME = "config.yaml"
77
+ #: The harness root. This file lives at the root beside `config.py`, so the
78
+ #: root is its own directory -- resolved from `__file__` rather than from cwd
79
+ #: for `core/config_loader.HARNESS_ROOT`'s reason: the harness tier ships with
80
+ #: the harness, and every shipped asset in this project resolves this way.
81
+ HARNESS_ROOT = os.path.dirname(os.path.abspath(__file__))
82
+ CONFIG_PATH = os.path.join(HARNESS_ROOT, CONFIG_FILENAME)
83
+
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # ---- Scalar types ---------------------------------------------------------
87
+ # ---------------------------------------------------------------------------
88
+
89
+ def _number_only(value: Any) -> Any:
90
+ """Reject a bool or a string where a number is wanted.
91
+
92
+ `bool` is a subclass of `int` in Python and pydantic's lax `float` takes
93
+ both `True` and `"9.5"`. `core/config_loader._type_ok` goes to the same
94
+ trouble for `settings.json` and says why: a `True` sailing through as `1`
95
+ is a value nobody wrote. Ints ARE accepted, so `8` is a legal way to
96
+ write `8.0` in YAML.
97
+ """
98
+ if isinstance(value, bool):
99
+ raise ValueError("expected a number, got a boolean")
100
+ if isinstance(value, str):
101
+ raise ValueError("expected a number, got a quoted string")
102
+ return value
103
+
104
+
105
+ #: A float that accepts an int but never a bool or a quoted string.
106
+ #:
107
+ #: `allow_inf_nan=False` is the half that is not about tidiness. YAML spells
108
+ #: them `.nan` and `.inf`, both parse to legal floats, and a NaN makes every
109
+ #: `<` and `>` comparison FALSE -- so `compaction_trigger_fraction: .nan`
110
+ #: would mean compaction never fires, silently, with no error ever raised.
111
+ #: Refused here once rather than per field.
112
+ Number = Annotated[float, BeforeValidator(_number_only),
113
+ Field(allow_inf_nan=False)]
114
+
115
+ # THE THREE RANGE SHAPES, MIRRORED FROM THE SETTINGS VALIDATOR.
116
+ #
117
+ # `core/config_loader.py` already expresses exactly these three for
118
+ # `settings.json` -- `_UNIT`, `_POSITIVE_INT`, `_NON_NEGATIVE_INT` -- and the
119
+ # same values arriving from `config.yaml` had no range check at all, so
120
+ # `max_iterations: 0` and `compaction_trigger_fraction: 5.0` were accepted.
121
+ # Mirrored rather than imported, deliberately: importing from `core/` is the
122
+ # cycle this module exists to avoid. `security/protected_paths.py` carries the
123
+ # same kind of deliberate duplicate and says so about `_user_config_dir`.
124
+
125
+ #: A number in [0, 1]. Weights, ratios, fractions and authority scores.
126
+ Unit = Annotated[float, BeforeValidator(_number_only),
127
+ Field(ge=0.0, le=1.0, allow_inf_nan=False)]
128
+
129
+ #: A count that must be at least one. A ceiling of zero is not a tighter
130
+ #: bound, it is a harness that cannot do the thing at all.
131
+ PositiveInt = Annotated[int, Field(strict=True, gt=0)]
132
+
133
+ #: A count where zero is a real answer -- no retries, no injected memories.
134
+ NonNegativeInt = Annotated[int, Field(strict=True, ge=0)]
135
+
136
+ #: A TCP port. `ssh_port` was a lax `int` until #213, so `true` became port
137
+ #: 1 and `99999` reached the SSH call before anything said no.
138
+ Port = Annotated[int, Field(strict=True, ge=1, le=65535)]
139
+
140
+ #: A path that must name something. An empty `db_path` was accepted until
141
+ #: #213 and opened SQLite's anonymous temporary database, so every thread
142
+ #: and memory vanished at exit without a word. `workspace_dir` is NOT one,
143
+ #: deliberately: see its field.
144
+ NonEmptyStr = Annotated[str, Field(min_length=1)]
145
+
146
+ #: A duration in seconds that must be positive.
147
+ PositiveNumber = Annotated[float, BeforeValidator(_number_only),
148
+ Field(gt=0.0, allow_inf_nan=False)]
149
+
150
+ #: A multiplier where zero is meaningful (`1 + tolerance`).
151
+ NonNegativeNumber = Annotated[float, BeforeValidator(_number_only),
152
+ Field(ge=0.0, allow_inf_nan=False)]
153
+
154
+ #: "always" / "tiered" / "contained" / "never" (§48 CE2 added the third).
155
+ #: A closed vocabulary rather than a plain string, so an unknown mode is a
156
+ #: startup failure and never a policy that quietly means something else --
157
+ #: one direction of a fallback asks about everything and the other about
158
+ #: nothing, and a typo cannot pick.
159
+ ShellApprovalMode = Literal["always", "tiered", "contained", "never"]
160
+
161
+ #: "rederive" / "chain". Validated here AND in
162
+ #: `config_loader.effective_compaction`, which checks the value a
163
+ #: `settings.json` or a `/compact --strength N` supplied against this list.
164
+ CompactionStrategy = Literal["rederive", "chain"]
165
+
166
+
167
+ class _Model(BaseModel):
168
+ """Common posture: no unknown keys, no mutation after validation."""
169
+
170
+ model_config = ConfigDict(extra="forbid", frozen=True)
171
+
172
+
173
+ # ---------------------------------------------------------------------------
174
+ # ---- The two permission tables --------------------------------------------
175
+ # ---------------------------------------------------------------------------
176
+ #
177
+ # The FIELD NAMES stay declared in Python while the booleans come from YAML,
178
+ # and the split is deliberate. `tools/registry.py` checks at import that every
179
+ # statically registered tool has a field in `ToolPermissions` and -- with one
180
+ # deliberate exception -- in `ToolApprovals` (D24); with the names
181
+ # in YAML, omitting one would turn that build-time check into a runtime
182
+ # surprise in a data file. With the names here and the fields required, a
183
+ # `config.yaml` missing `shell` cannot start the harness at all.
184
+ #
185
+ # The exception is `shell` in approvals: its approval is governed solely by
186
+ # `shell_approval_mode`, and a second switch there could only force `always`
187
+ # -- exactly what the mode already says. A test pins this as the SOLE
188
+ # exemption, so a future omission cannot ride in on its precedent.
189
+ #
190
+ # Field ORDER matters and follows `config.py`'s: `ToolPermissions` and
191
+ # `ToolApprovals` are rebuilt as real dataclasses from these models, and
192
+ # `tests/test_docs_consistency.py` reads `vars(config.ToolPermissions())` to
193
+ # check README's approval table names every tool.
194
+
195
+ class ToolPermissionsModel(_Model):
196
+ """Whether each registered tool may be called at all.
197
+
198
+ `security/permissions.is_tool_allowed` constructs `ToolPermissions()`
199
+ fresh on every call and returns before any context or approval logic, so
200
+ these are a global floor that no agent context or skill can widen (D14).
201
+ """
202
+
203
+ web_search: StrictBool
204
+ fetch_url: StrictBool
205
+ get_time: StrictBool
206
+ arxiv_search: StrictBool
207
+ symbolic_math: StrictBool
208
+ linear_algebra: StrictBool
209
+ probability_stats: StrictBool
210
+ discrete_math: StrictBool
211
+ logic: StrictBool
212
+ geometry: StrictBool
213
+ read: StrictBool
214
+ view_image: StrictBool
215
+ write: StrictBool
216
+ edit: StrictBool
217
+ shell: StrictBool
218
+ shell_background: StrictBool
219
+ shell_monitor: StrictBool
220
+ shell_interactive: StrictBool
221
+ shell_input: StrictBool
222
+ shell_sessions: StrictBool
223
+ shell_output: StrictBool
224
+ shell_kill: StrictBool
225
+ load_skill: StrictBool
226
+ spawn_subagent: StrictBool
227
+ pin: StrictBool
228
+ unpin: StrictBool
229
+ remember: StrictBool
230
+ read_project_doc: StrictBool
231
+ write_project_doc: StrictBool
232
+ ask_user: StrictBool
233
+ todo_write: StrictBool
234
+
235
+
236
+ class ToolApprovalsModel(_Model):
237
+ """Whether each tool needs a human yes before it runs.
238
+
239
+ Approval ORs across every layer, so a `True` here is a one-way ratchet
240
+ that can only ever add prompts. `shell`, `shell_background`,
241
+ `shell_monitor` and `shell_interactive` are deliberately absent
242
+ (security/permissions.py's
243
+ APPROVAL_BY_SHELL_MODE): their approval is governed solely by
244
+ `shell_approval_mode` (always / tiered / contained / never), and a
245
+ second switch here could only force `always` -- exactly what the mode
246
+ already says. An agent's `approval_overrides` keeps its own one-way
247
+ power over them through the context layer.
248
+ """
249
+
250
+ web_search: StrictBool
251
+ fetch_url: StrictBool
252
+ get_time: StrictBool
253
+ arxiv_search: StrictBool
254
+ symbolic_math: StrictBool
255
+ linear_algebra: StrictBool
256
+ probability_stats: StrictBool
257
+ discrete_math: StrictBool
258
+ logic: StrictBool
259
+ geometry: StrictBool
260
+ read: StrictBool
261
+ view_image: StrictBool
262
+ write: StrictBool
263
+ edit: StrictBool
264
+ shell_input: StrictBool
265
+ shell_sessions: StrictBool
266
+ shell_output: StrictBool
267
+ shell_kill: StrictBool
268
+ load_skill: StrictBool
269
+ spawn_subagent: StrictBool
270
+ pin: StrictBool
271
+ unpin: StrictBool
272
+ remember: StrictBool
273
+ read_project_doc: StrictBool
274
+ write_project_doc: StrictBool
275
+ ask_user: StrictBool
276
+ todo_write: StrictBool
277
+
278
+
279
+ # ---------------------------------------------------------------------------
280
+ # ---- The whole file -------------------------------------------------------
281
+ # ---------------------------------------------------------------------------
282
+ #
283
+ # Annotations preserve the RUNTIME TYPES consumers already rely on, which is
284
+ # why several are looser than they could be:
285
+ #
286
+ # * `similarity_calibration` stays `dict[str, dict[str, float]]` rather than
287
+ # a nested model, because `source_scoring.py` subscripts the band with
288
+ # `band["floor"]`.
289
+ # * `ensemble_models` is `list[Any] | None`, not a model list, because
290
+ # `orchestrator._ensemble_roster` validates the entries itself and reports
291
+ # the malformed one -- a schema that rejected them first would move that
292
+ # error message and say less.
293
+ # * `critic_model` / `embedder_model` stay plain dicts, because
294
+ # `core/pipeline_models.resolve` treats them as dicts and the user-tier
295
+ # store outranks them (SQ7).
296
+
297
+ class HarnessConfig(_Model):
298
+ """Every value in `config.yaml`, validated.
299
+
300
+ Field order is `config.py`'s section order, so the two can be diffed.
301
+ """
302
+
303
+ # -- Model / loop ------------------------------------------------------
304
+ model_name: str
305
+ max_tokens: PositiveInt
306
+ max_iterations: PositiveInt
307
+ # Batch 91. Zero is a real answer for both: no retry, and no wait.
308
+ model_call_max_retries: NonNegativeInt
309
+ model_call_retry_base_delay_s: NonNegativeNumber
310
+
311
+ # -- Subagents ---------------------------------------------------------
312
+ # Zero is a real answer here: `subagent_depth >= this` then refuses
313
+ # every spawn, which is a harness with subagents turned off.
314
+ subagent_max_depth: NonNegativeInt
315
+ subagent_max_parallel: PositiveInt
316
+
317
+ # -- The active agent (ROADMAP_v3 section 59) --------------------------
318
+ # Names, not AgentDefs: the user and project tiers are discovered after
319
+ # this file is read, so a name is checked when shift+tab is pressed.
320
+ agent_cycle: list[NonEmptyStr]
321
+
322
+ # -- Deep research pipeline -------------------------------------------
323
+ max_pipeline_retries: NonNegativeInt
324
+ max_json_retries: NonNegativeInt
325
+
326
+ # -- Ensemble mode -----------------------------------------------------
327
+ ensemble_mode: StrictBool
328
+ ensemble_models: Optional[list[Any]]
329
+
330
+ # -- Sampling-parameter support ---------------------------------------
331
+ models_rejecting_sampling_params: frozenset[str]
332
+
333
+ # -- Critic / embedder routing ----------------------------------------
334
+ critic_model: Optional[dict[str, Any]]
335
+ embedder_model: Optional[dict[str, Any]]
336
+ similarity_calibration: dict[str, dict[str, Unit]]
337
+ default_similarity_calibration: dict[str, Unit]
338
+ embedder_prefixes: dict[str, dict[str, str]]
339
+
340
+ # -- Source authority --------------------------------------------------
341
+ domain_authority_classes: dict[str, Unit]
342
+ default_domain_authority: Unit
343
+ domain_authority_suffixes: dict[str, str]
344
+ authority_adjustment_cap: Unit
345
+
346
+ # -- The sources/ artifact --------------------------------------------
347
+ persist_source_text: StrictBool
348
+
349
+ # -- Scholarly authority (OpenAlex) -----------------------------------
350
+ scholar_lookup: StrictBool
351
+ scholar_api_url: str
352
+ scholar_timeout_s: PositiveNumber
353
+ scholar_max_retries: NonNegativeInt
354
+ scholar_cache_ttl_s: NonNegativeInt
355
+ scholar_mailto: str
356
+ scholar_venue_weight: Unit
357
+ scholar_citation_weight: Unit
358
+ scholar_author_weight: Unit
359
+ scholar_venue_credit: dict[str, Unit]
360
+ scholar_h_saturation: PositiveInt
361
+ scholar_min_cohort_size: PositiveInt
362
+ scholar_min_citation_age_days: NonNegativeInt
363
+ scholar_retracted_authority: Unit
364
+
365
+ # -- Reasoning effort --------------------------------------------------
366
+ default_effort: Optional[str]
367
+ model_effort_levels: dict[str, list[str]]
368
+ default_effort_levels: list[str]
369
+ google_thinking_budgets: dict[str, StrictInt]
370
+
371
+ # -- Database ----------------------------------------------------------
372
+ db_path: NonEmptyStr
373
+
374
+ # -- File-ops workspace ------------------------------------------------
375
+ # `output_dir` and `workspace_dir_explicit` are deliberately absent --
376
+ # see DERIVED_VALUES below. `workspace_is_project` is NOT the second of
377
+ # those: it is an ordinary key that FEEDS one (TECHNICAL_DEBT 28).
378
+ # A bare `str`, not `NonEmptyStr` (#213, measured): an empty workspace
379
+ # is refused BY NAME at `protected_paths.check_workspace`, which answers
380
+ # both routes to it -- this key and an empty AGENT_WORKSPACE, which
381
+ # folds in here. Refusing it here too would answer the variable's case
382
+ # first and worse, as an error about config.yaml.
383
+ # test_an_empty_variable_reaches_the_guard_as_an_empty_path pins it.
384
+ workspace_dir: str
385
+ workspace_is_project: StrictBool
386
+ max_file_size_bytes: PositiveInt
387
+ max_read_lines: PositiveInt
388
+ max_read_chars: PositiveInt
389
+ max_image_bytes: PositiveInt
390
+
391
+ # -- /init -------------------------------------------------------------
392
+ initializer_agent: str
393
+ init_read_chars: PositiveInt
394
+ init_max_steps: PositiveInt
395
+ init_max_hub_chars: PositiveInt
396
+ init_diff_shown_lines: PositiveInt
397
+
398
+ # -- MCP teardown ------------------------------------------------------
399
+ teardown_budget_s: PositiveNumber
400
+
401
+ # -- MCP results -------------------------------------------------------
402
+ mcp_max_event_bytes: PositiveInt
403
+
404
+ # -- Shell / sandbox ---------------------------------------------------
405
+ shell_binary: str
406
+ allow_insecure_sandbox_fallback: StrictBool
407
+ auto_approve_sandbox_fallback: StrictBool
408
+ # ROADMAP_v3 §49 slice 3 (SS35). An AUTHORITY key: it decides
409
+ # whether a command may leave the container at all. `wsl_distro`
410
+ # below is not -- it names WHICH distro, which only matters once
411
+ # this one is true.
412
+ allow_wsl_backend: StrictBool
413
+ wsl_distro: str
414
+ # ROADMAP_v3 §49 slice 4 (SS46). One host, flat scalars -- SS36's
415
+ # shape, because a remote host is a fact about this machine's
416
+ # situation and not about any one command. The agent says
417
+ # `backend: "ssh"` and gets THE configured host; it never names one.
418
+ allow_ssh_backend: StrictBool
419
+ ssh_host: str
420
+ ssh_user: str
421
+ ssh_port: Port
422
+ ssh_identity_file: str
423
+ ssh_remote_workspace: str
424
+ ssh_host_key: str
425
+ ssh_binary: str
426
+ shell_approval_mode: ShellApprovalMode
427
+ sandbox_docker_image: str
428
+ sandbox_timeout_seconds: PositiveInt
429
+ sandbox_memory_mb: PositiveInt
430
+ sandbox_cpu_seconds: PositiveInt
431
+ sandbox_max_pids: PositiveInt
432
+ # ROADMAP_v3 §49 (SS12, SS13): background and monitor sessions. Resource
433
+ # limits, like the four above -- NOT authority keys and not in the
434
+ # frozen posture: none of them decides whether a command is asked about.
435
+ shell_session_timeout_cap_s: PositiveInt
436
+ shell_session_idle_timeout_s: PositiveInt
437
+ shell_session_max_live: PositiveInt
438
+ shell_session_max_consecutive_wakes: PositiveInt
439
+ shell_session_output_head_chars: PositiveInt
440
+ shell_session_output_tail_chars: PositiveInt
441
+
442
+ # -- Output redaction / tool isolation --------------------------------
443
+ redact_tool_outputs: StrictBool
444
+ tool_compute_timeout_s: PositiveInt
445
+ network_allowed_commands: list[str]
446
+ inert_commands: list[str]
447
+
448
+ # -- Research grants and review ---------------------------------------
449
+ max_granted_tool_calls: NonNegativeInt
450
+ attended_approval_timeout_s: PositiveInt
451
+ subagent_review: StrictBool
452
+ max_review_findings: NonNegativeInt
453
+ max_review_refinements: NonNegativeInt
454
+
455
+ # -- Compaction --------------------------------------------------------
456
+ compaction_trigger_fraction: Unit
457
+ compaction_min_headroom_tokens: PositiveInt
458
+ compaction_max_headroom_fraction: Unit
459
+ compaction_trigger_tokens: PositiveInt
460
+ compaction_warning_margin_tokens: NonNegativeInt
461
+ compaction_keep_recent_tokens: NonNegativeInt
462
+ compaction_keep_recent_turns: NonNegativeInt
463
+ pin_max_trigger_fraction: Unit
464
+ compaction_strength: PositiveInt
465
+ compaction_max_retries: NonNegativeInt
466
+ compaction_target_ratios: dict[int, Unit]
467
+ compaction_ratio_tolerance: NonNegativeNumber
468
+ compaction_strategy: CompactionStrategy
469
+ # The ELEMENT vocabulary, not just the scalar's. Typed `str`, a
470
+ # `hybrid` added here passed `effective_compaction`'s membership test
471
+ # and then `core/compaction.py` treated anything that is not exactly
472
+ # `chain` as `rederive` -- silently, recording `rederive` in the
473
+ # checkpoint. Non-empty because an empty roster makes every strategy
474
+ # illegal, including the one this file ships.
475
+ compaction_strategies: Annotated[tuple[CompactionStrategy, ...],
476
+ Field(min_length=1)]
477
+ max_injected_memories: NonNegativeInt
478
+
479
+ # -- Catalog text ------------------------------------------------------
480
+ max_catalog_text_chars: PositiveInt
481
+
482
+ # -- Summaries, references, the checklist -----------------------------
483
+ compactor_agent: str
484
+ summary_target_chars: PositiveInt
485
+ max_injected_refs: NonNegativeInt
486
+ # Non-empty: this becomes the enum in todo_write's own schema.
487
+ todo_statuses: Annotated[tuple[str, ...], Field(min_length=1)]
488
+ max_todo_items: NonNegativeInt
489
+ compaction_pipeline_backstop_tokens: NonNegativeInt
490
+
491
+ # -- Context windows ---------------------------------------------------
492
+ model_context_windows: dict[str, PositiveInt]
493
+ default_context_window: PositiveInt
494
+
495
+ # -- Connecting a model (ROADMAP_v3 §79, HD5) --------------------------
496
+ # A public client id; empty hides the sign-in.
497
+ hf_oauth_client_id: str
498
+
499
+ # -- Tool permissions and approvals -----------------------------------
500
+ tool_permissions: ToolPermissionsModel
501
+ tool_approvals: ToolApprovalsModel
502
+
503
+ @model_validator(mode="after")
504
+ def _check_cross_field_defaults(self) -> HarnessConfig:
505
+ """Fail fast on a harness default that can never work.
506
+
507
+ EVERY CHECK HERE IS AN INVARIANT BETWEEN TWO KEYS OF THIS FILE. A
508
+ single field's shape belongs in its annotation; what belongs here is
509
+ the pairs -- a value that is individually well-typed and impossible
510
+ beside its neighbour. Each one was verified to be ACCEPTED before
511
+ this validator grew, and each failed somewhere later and further
512
+ from the edit that caused it.
513
+
514
+ The four that are about a key the CONSUMER SUBSCRIBES DIRECTLY are
515
+ the sharpest, because the annotation could not express them: the
516
+ type says `dict[str, Unit]` while `scholar.py` and
517
+ `source_scoring.py` index particular keys out of it, so a table that
518
+ merely has the right value type still raises `KeyError` in the
519
+ middle of a research run, after the model calls are paid for.
520
+
521
+ Runtime customisation is unaffected: `/effort` and
522
+ `/compact --strength` go through `effort_for()` /
523
+ `effective_compaction()`, not the schema, so per-model and
524
+ per-invocation levels keep working.
525
+ """
526
+ if self.compaction_strength not in self.compaction_target_ratios:
527
+ raise ValueError(
528
+ f"compaction_strength {self.compaction_strength!r} must be "
529
+ f"one of {sorted(self.compaction_target_ratios)} "
530
+ f"(keys of compaction_target_ratios)")
531
+ if (self.default_effort is not None
532
+ and self.default_effort not in self.default_effort_levels):
533
+ raise ValueError(
534
+ f"default_effort {self.default_effort!r} must be null or one "
535
+ f"of {self.default_effort_levels} "
536
+ f"(members of default_effort_levels)")
537
+ # Defence in depth rather than the only guard: `initialize()` calls
538
+ # `effective_compaction()`, which already refuses this pair at
539
+ # startup on the CLI and TUI paths. Checked here too because it is
540
+ # the same shape as the strength pair above, the message names the
541
+ # config.yaml key rather than the settings.json one, and a process
542
+ # that never calls `initialize()` -- a library import, a bare test --
543
+ # otherwise carries the incoherent pair to the first fold.
544
+ if self.compaction_strategy not in self.compaction_strategies:
545
+ raise ValueError(
546
+ f"compaction_strategy {self.compaction_strategy!r} must be "
547
+ f"one of {list(self.compaction_strategies)} "
548
+ f"(members of compaction_strategies)")
549
+
550
+ # -- keys the consumers index directly ----------------------------
551
+ for key in ("unknown", "repository"):
552
+ if key not in self.scholar_venue_credit:
553
+ raise ValueError(
554
+ f"scholar_venue_credit must contain {key!r}: "
555
+ f"core/reasoning/scholar.py subscripts it for a work "
556
+ f"whose location type is unrecognised, and a missing "
557
+ f"entry is a KeyError mid research run")
558
+ if "restricted_registry" not in self.domain_authority_classes:
559
+ raise ValueError(
560
+ "domain_authority_classes must contain 'restricted_registry': "
561
+ "core/reasoning/source_scoring.py subscripts it for a "
562
+ "second-level government or academic host")
563
+ unknown_classes = sorted(
564
+ {name for name in self.domain_authority_suffixes.values()
565
+ if name not in self.domain_authority_classes})
566
+ if unknown_classes:
567
+ raise ValueError(
568
+ f"domain_authority_suffixes maps hosts onto classes that "
569
+ f"domain_authority_classes does not define: "
570
+ f"{unknown_classes}. source_scoring.py looks the class name "
571
+ f"up directly, so each is a KeyError on the first host that "
572
+ f"matches that suffix")
573
+ bands = {"default_similarity_calibration":
574
+ self.default_similarity_calibration}
575
+ bands.update({f"similarity_calibration[{name!r}]": band
576
+ for name, band in self.similarity_calibration.items()})
577
+ for where, band in bands.items():
578
+ missing = [edge for edge in ("floor", "ceiling")
579
+ if edge not in band]
580
+ if missing:
581
+ raise ValueError(
582
+ f"{where} is missing {missing}: source_scoring.py reads "
583
+ f"both edges of every calibration band")
584
+ if band["floor"] > band["ceiling"]:
585
+ raise ValueError(
586
+ f"{where} has floor {band['floor']} above ceiling "
587
+ f"{band['ceiling']}, which no similarity can fall inside")
588
+ return self
589
+
590
+
591
+ # ---------------------------------------------------------------------------
592
+ # ---- Environment overrides ------------------------------------------------
593
+ # ---------------------------------------------------------------------------
594
+ #
595
+ # `config.yaml` holds the static default; the variable wins when it is set.
596
+ # Applied BEFORE validation, once, inside `load()` -- never at call time, for
597
+ # the reason rule 2 in this module's docstring gives.
598
+ #
599
+ # A declared table rather than five hand-written expressions so the set is
600
+ # enumerable: `HARNESS_ENV_VARS` below is what documentation and any future
601
+ # config surface can list without going stale.
602
+
603
+ #: {UPPER_CASE config name: environment variable}. String-valued only; the
604
+ #: variable's value is used verbatim, with no parsing, exactly as
605
+ #: `os.environ.get(var, default)` did.
606
+ ENV_OVERRIDES = {
607
+ "MODEL_NAME": "AGENT_MODEL",
608
+ "DB_PATH": "APP_DB_PATH",
609
+ "WORKSPACE_DIR": "AGENT_WORKSPACE",
610
+ "SHELL_BINARY": "AGENT_SHELL",
611
+ "SANDBOX_DOCKER_IMAGE": "AGENT_SANDBOX_IMAGE",
612
+ }
613
+
614
+ #: Every variable this module reads, including the two that only reach a
615
+ #: derived value. `AGENT_WORKSPACE` appears in both.
616
+ HARNESS_ENV_VARS = tuple(sorted(
617
+ set(ENV_OVERRIDES.values()) | {"AGENT_OUTPUT_DIR", "AGENT_WORKSPACE"}))
618
+
619
+ #: The two values with NO `config.yaml` key, because neither is a static
620
+ #: default and inventing one would change behaviour. Named here so the
621
+ #: round-trip check in `tests/` can tell "absent on purpose" from "forgotten".
622
+ #: `workspace_is_project` is NOT the key for the second of these -- it is one
623
+ #: of the two inputs `derived_values` reads to compute it, and the other is
624
+ #: an environment variable no key can stand in for.
625
+ DERIVED_VALUES = ("OUTPUT_DIR", "WORKSPACE_DIR_EXPLICIT")
626
+
627
+ #: Keys that need a human at the keyboard. No UNATTENDED surface may write
628
+ #: them -- not a settings file, not an environment variable, not a tool
629
+ #: call -- and `/config` writes one only behind a confirmation naming what
630
+ #: the key permits (batch 84; `config_edit.AUTHORITY_EFFECT` is that
631
+ #: sentence, per key, and a test holds the two lists against each other).
632
+ #: Four are the frozen security posture
633
+ #: (`security/posture.Posture`); three are the Authority rosters that name a
634
+ #: provider the harness will call (E2, SQ7); two are the global tool floor.
635
+ #:
636
+ #: `ensemble_mode` is deliberately NOT here. It is a MODE, persistable in
637
+ #: `settings.json` today, and the worst it can do is spend more of a provider
638
+ #: the user already chose -- the line `core/config_loader.py` draws between
639
+ #: authority and cost.
640
+ HARNESS_AUTHORITY_KEYS = frozenset({
641
+ "shell_approval_mode",
642
+ "allow_insecure_sandbox_fallback",
643
+ "auto_approve_sandbox_fallback",
644
+ "allow_wsl_backend",
645
+ "allow_ssh_backend",
646
+ "redact_tool_outputs",
647
+ "ensemble_models",
648
+ "critic_model",
649
+ "embedder_model",
650
+ "tool_permissions",
651
+ "tool_approvals",
652
+ })
653
+
654
+
655
+ # ---------------------------------------------------------------------------
656
+ # ---- Reading the file -----------------------------------------------------
657
+ # ---------------------------------------------------------------------------
658
+
659
+ def _reader() -> YAML:
660
+ """The import-path reader.
661
+
662
+ `typ="safe"` rather than `typ="rt"`: the round-trip parser exists to
663
+ preserve comments across a WRITE, and nothing writes this file yet. Safe
664
+ mode also refuses `!!python/...` tags outright, which matters for a file
665
+ that decides the tool permissions. Both modes raise `DuplicateKeyError` on
666
+ a repeated key, so a second `shell_approval_mode` is an error rather than
667
+ a silent last-one-wins.
668
+
669
+ A future config editor wants `YAML(typ="rt")` instead, on its own write
670
+ path -- that is the reason `ruamel.yaml` is the dependency here rather
671
+ than the `pyyaml` that `core/config_loader.py` uses for frontmatter.
672
+ """
673
+ return YAML(typ="safe")
674
+
675
+
676
+ def _describe(path: Optional[str]) -> str:
677
+ """How to name the file being complained about.
678
+
679
+ `config.yaml` for the live document, the caller's path for a candidate.
680
+ Hardcoding `CONFIG_FILENAME` made every message about a candidate misname
681
+ the file and, worse, offer the live document's remedy -- telling someone
682
+ whose draft has a typo that "the package is incomplete" and to "restore
683
+ the file from git".
684
+ """
685
+ if path is None or os.path.abspath(path) == CONFIG_PATH:
686
+ return CONFIG_FILENAME
687
+ return os.path.basename(path)
688
+
689
+
690
+ def read_document(path: Optional[str] = None) -> dict:
691
+ """The raw mapping, parsed and nothing else. No validation, no env."""
692
+ target = path or CONFIG_PATH
693
+ name = _describe(path)
694
+ try:
695
+ with open(target, encoding="utf-8") as handle:
696
+ data = _reader().load(handle)
697
+ except FileNotFoundError:
698
+ if path is None:
699
+ raise ValueError(
700
+ f"{CONFIG_FILENAME} is missing at {target}. It ships with the "
701
+ f"harness beside config.py and holds every tunable value, so "
702
+ f"nothing can start without it. If this is an installed copy, "
703
+ f"the package is incomplete; if it is a checkout, restore the "
704
+ f"file from git.") from None
705
+ raise ValueError(f"{name} does not exist at {target}.") from None
706
+ except UnicodeDecodeError as exc:
707
+ # A ValueError but NOT an OSError, so the clause below never saw it
708
+ # and the message named neither the file nor the remedy. The way to
709
+ # arrive here on Windows is Notepad's "ANSI" or "UTF-16" save option.
710
+ raise ValueError(
711
+ f"{name} at {target} is not valid UTF-8 ({exc}). Save it as "
712
+ f"UTF-8 without a byte-order mark; an editor offering \"ANSI\" "
713
+ f"or \"UTF-16\" will produce this.") from None
714
+ except (OSError, YAMLError) as exc:
715
+ raise ValueError(f"{name} at {target} could not be "
716
+ f"read: {exc}") from exc
717
+ if not isinstance(data, dict):
718
+ raise ValueError(
719
+ f"{name} at {target} is not a mapping of settings "
720
+ f"(parsed as {type(data).__name__}).")
721
+ return data
722
+
723
+
724
+ def validate(data: dict, source: Optional[str] = None,
725
+ overridden: Optional[dict] = None) -> HarnessConfig:
726
+ """Validate a raw mapping, reporting every problem at once.
727
+
728
+ Raises `ValueError` naming the file and each offending key. A missing key
729
+ and an unknown key are both errors -- see rule 3 in the module docstring.
730
+
731
+ `overridden` is `{key: environment variable}` for the keys the
732
+ environment set (#213). A problem with one of those names the variable,
733
+ because the file holds a good value and someone reading only the file
734
+ would find nothing wrong with it -- `APP_DB_PATH=` is the case that made
735
+ it reachable, now that `db_path` must not be empty.
736
+ """
737
+ where = source or CONFIG_PATH
738
+ name = _describe(source)
739
+ try:
740
+ return HarnessConfig(**data)
741
+ except TypeError as exc:
742
+ # `HarnessConfig(**data)` raises before pydantic is entered when a
743
+ # key is not a string, so `except ValidationError` never saw it and
744
+ # the one input class that most needs the file-and-key message got a
745
+ # bare `TypeError: keywords must be strings`. The way to arrive here
746
+ # is de-indenting a nested block: `1: 0.4` at column 0 under
747
+ # `compaction_target_ratios` parses to a mapping with an int key,
748
+ # which passes `read_document`'s mapping guard.
749
+ bad = sorted(repr(key) for key in data if not isinstance(key, str))
750
+ raise ValueError(
751
+ f"{name} at {where} has {'keys' if len(bad) != 1 else 'a key'} "
752
+ f"that {'are' if len(bad) != 1 else 'is'} not a setting name: "
753
+ f"{', '.join(bad) or exc}. A nested block de-indented to column "
754
+ f"0 does this -- check the indentation around them.") from None
755
+ except ValidationError as exc:
756
+ lines = []
757
+ for err in exc.errors():
758
+ key = ".".join(str(part) for part in err["loc"]) or "<root>"
759
+ variable = (overridden or {}).get(key)
760
+ origin = f" (set by {variable})" if variable else ""
761
+ lines.append(f" {key}{origin}: {err['msg']}")
762
+ raise ValueError(
763
+ f"{name} at {where} is not valid "
764
+ f"({len(lines)} problem(s)):\n" + "\n".join(lines)) from None
765
+
766
+
767
+ def _overlay_env(data: dict) -> dict:
768
+ """Fold the environment into the raw document, BEFORE validation.
769
+
770
+ Before validation rather than after, and that ordering is the whole
771
+ reason this is a separate function. An override applied afterwards would
772
+ live only in the namespace `config.py` publishes, so
773
+ `config_schema.current()` and `config.<NAME>` would disagree about any
774
+ key that has a variable -- silently, and only for whoever adds the sixth
775
+ override to a key `core/config_loader.py` happens to read. Folded in
776
+ here there is ONE model, with the environment already in it, and an
777
+ override goes through the same type check the file's value does.
778
+
779
+ Returns a copy with the overrides folded in, leaving the input untouched,
780
+ so a caller validating a candidate file does not have its document
781
+ rewritten underneath it.
782
+ """
783
+ merged = dict(data)
784
+ for name, variable in ENV_OVERRIDES.items():
785
+ override = os.environ.get(variable)
786
+ if override is not None:
787
+ merged[name.lower()] = override
788
+ return merged
789
+
790
+
791
+ def _overridden() -> dict:
792
+ """`{key: variable}` for each key the environment sets right now --
793
+ what `validate` names beside a problem with one of them."""
794
+ return {name.lower(): variable
795
+ for name, variable in ENV_OVERRIDES.items()
796
+ if os.environ.get(variable) is not None}
797
+
798
+
799
+ def derived_values(cfg: HarnessConfig) -> dict:
800
+ """The two `{UPPER_CASE_NAME: value}` entries with no `config.yaml` key.
801
+
802
+ Separate from the model because neither is a static default: one is a
803
+ composed path and the other is a question the environment answers and
804
+ YAML cannot ask. `DERIVED_VALUES` names them so a completeness check can
805
+ tell "absent on purpose" from "forgotten".
806
+
807
+ TAKES `cfg` SINCE BATCH 111, because one of the two is no longer a
808
+ question about the environment ALONE -- see `WORKSPACE_DIR_EXPLICIT`
809
+ below. There is exactly one caller and it already holds the config, so
810
+ this costs nothing; what it buys is that the file gets a say in a value
811
+ that decides where the work is.
812
+ """
813
+ return {
814
+ # AGENT_OUTPUT_DIR, else `<AGENT_WORKSPACE or ".">/output`. ONE
815
+ # expression with no branch, carried over verbatim, and note the
816
+ # default is "." here where WORKSPACE_DIR's is "./workspace": an unset
817
+ # variable still means `./output` rather than `./workspace/output`.
818
+ # There is deliberately no `output_dir` key -- one would have to be
819
+ # ignored whenever AGENT_WORKSPACE is named, which is the branch this
820
+ # form exists to avoid.
821
+ "OUTPUT_DIR": os.environ.get(
822
+ "AGENT_OUTPUT_DIR",
823
+ os.path.join(os.environ.get("AGENT_WORKSPACE", "."), "output")),
824
+ # WAS THE WORKSPACE NAMED AS THE PROJECT? `main()` uses this to
825
+ # decide whether the resolved workspace is also the PROJECT PATH.
826
+ # TWO ROUTES, AND EACH EXISTS FOR A REASON THE OTHER CANNOT SERVE
827
+ # (TECHNICAL_DEBT 28, batch 111):
828
+ #
829
+ # * `AGENT_WORKSPACE`, by its PRESENCE and never its value. A value
830
+ # test here would move the project one level down for everyone
831
+ # who set nothing, because the shipped `./workspace` is a
832
+ # subdirectory of the launch directory. YAML cannot ask whether a
833
+ # variable was named, which is why this half is not a key.
834
+ # * `workspace_is_project`, which IS a key, for the reader who has
835
+ # no variable to set. Before it, someone who wrote their project
836
+ # into `workspace_dir` got the workspace they asked for and a
837
+ # project of `os.getcwd()` -- and launched from the install tree,
838
+ # a refusal telling them to set a variable they believed they had
839
+ # just set. Shipped `false`, so no existing install moves.
840
+ #
841
+ # OR, not "the file wins" or "the variable wins": both say the same
842
+ # thing about the same directory, so there is no precedence question
843
+ # to answer, and answering one would mean a user who did both getting
844
+ # less than a user who did either.
845
+ "WORKSPACE_DIR_EXPLICIT": (cfg.workspace_is_project
846
+ or "AGENT_WORKSPACE" in os.environ),
847
+ }
848
+
849
+
850
+ def as_module_namespace(cfg: HarnessConfig) -> dict:
851
+ """`{UPPER_CASE_NAME: value}` for `config.py` to publish as globals.
852
+
853
+ Excludes the two permission tables, which `config.py` turns back into
854
+ dataclasses, and includes the two derived values. The environment is
855
+ already in `cfg` -- see `_overlay_env`.
856
+ """
857
+ values = {}
858
+ for name in HarnessConfig.model_fields:
859
+ if name in ("tool_permissions", "tool_approvals"):
860
+ continue
861
+ values[name.upper()] = getattr(cfg, name)
862
+ values.update(derived_values(cfg))
863
+ return values
864
+
865
+
866
+ def _make_dataclass(name: str, model: BaseModel) -> type:
867
+ """Rebuild `ToolPermissions` / `ToolApprovals` as real dataclasses.
868
+
869
+ A real dataclass rather than the pydantic model itself, because the whole
870
+ codebase depends on the shape: `security/permissions.py` calls
871
+ `config.ToolPermissions()` with no arguments, tests mutate an instance's
872
+ fields and then swap the module attribute for a factory returning it, and
873
+ `tests/test_docs_consistency.py` enumerates `vars(instance)`. A frozen
874
+ pydantic model satisfies none of those.
875
+ """
876
+ fields = [(field, bool, dataclasses.field(default=getattr(model, field)))
877
+ for field in type(model).model_fields]
878
+ # The binding below (`ToolPermissions` / `ToolApprovals` globals plus the
879
+ # idempotent factories) is only half of what makes these PICKLABLE: pickle
880
+ # looks the class up by (`__module__`, `__qualname__`), so the module must
881
+ # also be right. `make_dataclass` sets `__module__` from the calling frame
882
+ # only on 3.12+ (via its `module=` kwarg, which the 3.11 floor cannot
883
+ # take); on 3.11 the class is built through `types.new_class`, and
884
+ # `type.__new__` backfills a missing `__module__` from the frame doing
885
+ # the calling -- inside `types.py`, so pickle looked for
886
+ # `types.ToolPermissions` and failed. Assigned explicitly, which works on
887
+ # every version. The original `@dataclass class ToolPermissions` in
888
+ # config.py pickled fine, so this was a silent shape regression that
889
+ # nothing would notice until one of these crossed a process boundary.
890
+ cls = dataclasses.make_dataclass(name, fields)
891
+ cls.__module__ = __name__
892
+ return cls
893
+
894
+
895
+ _cached: Optional[HarnessConfig] = None
896
+ #: The rebuilt dataclasses, built once. Bound at module level so `pickle` can
897
+ #: resolve `config_schema.ToolPermissions` by name, and so the two factories
898
+ #: are idempotent -- a second call used to hand back a fresh class whose
899
+ #: instances compared unequal to the harness's own, because dataclass
900
+ #: `__eq__` requires `other.__class__ is self.__class__`.
901
+ ToolPermissions: Optional[type] = None
902
+ ToolApprovals: Optional[type] = None
903
+
904
+
905
+ def load(path: Optional[str] = None, force: bool = False) -> HarnessConfig:
906
+ """Read, validate and cache `config.yaml`.
907
+
908
+ Called by `config.py` at import, WITH `force=True` -- see the long note
909
+ at that call. Importing `config` is what "bind the configuration now"
910
+ means, so that module decides when the file is read; a cache that
911
+ outlived a re-import of `config` would hand a fresh `config` the previous
912
+ environment's values, which is a technique the suite actually uses.
913
+
914
+ `core/config_loader.py` calls this with no arguments to read the shipped
915
+ defaults it used to reach through `getattr(config, "<NAME>")`. The cache
916
+ means that costs nothing and, more importantly, means the loader and the
917
+ `config` module always see the same document.
918
+
919
+ `path` JUDGES A CANDIDATE FILE ON ITS OWN, with no environment overlay
920
+ and without touching the cache. That is the seam a restart-required
921
+ config editor uses, and the overlay is left out for the reason the seam
922
+ exists: the file is what the next launch will read, and the environment
923
+ it will read it under is not knowable now. With the overlay in, a
924
+ candidate missing `db_path` was ACCEPTED whenever `APP_DB_PATH` happened
925
+ to be set in the editing shell, and then REFUSED at the startup it was
926
+ supposed to be certifying. `force` applies to the live document only, so
927
+ combining it with `path` asks for two different things at once and is
928
+ refused rather than silently dropped.
929
+ """
930
+ global _cached
931
+ if path is not None:
932
+ if force:
933
+ raise TypeError(
934
+ "load(path=..., force=True) asks for two different things: "
935
+ "`path` judges a candidate file and never touches the cache, "
936
+ "`force` re-reads the live document into it. Pass one.")
937
+ return validate(read_document(path), source=path)
938
+ if _cached is None or force:
939
+ _cached = validate(_overlay_env(read_document(None)),
940
+ overridden=_overridden(),
941
+ source=CONFIG_PATH)
942
+ return _cached
943
+
944
+
945
+ def current() -> HarnessConfig:
946
+ """The validated document this process is running on."""
947
+ return load()
948
+
949
+
950
+ def tool_permissions_dataclass() -> type:
951
+ """The `ToolPermissions` class, built once and bound to this module.
952
+
953
+ Idempotent, and that matters rather than being tidy: dataclass `__eq__`
954
+ compares `other.__class__ is self.__class__`, so a second class built
955
+ from the same values produced instances that compared UNEQUAL to the
956
+ harness's own, and `isinstance` against the live class was False.
957
+ """
958
+ global ToolPermissions
959
+ if ToolPermissions is None:
960
+ ToolPermissions = _make_dataclass(
961
+ "ToolPermissions", current().tool_permissions)
962
+ return ToolPermissions
963
+
964
+
965
+ def tool_approvals_dataclass() -> type:
966
+ """The `ToolApprovals` class, built once. See the sibling above."""
967
+ global ToolApprovals
968
+ if ToolApprovals is None:
969
+ ToolApprovals = _make_dataclass(
970
+ "ToolApprovals", current().tool_approvals)
971
+ return ToolApprovals