Coverage for src/governed_harness/configuration/models.py: 95%
741 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-12 16:06 +0000
1from __future__ import annotations
3import re
4import sys
5from pathlib import Path, PureWindowsPath
6from typing import Any, Literal
8from pydantic import (
9 BaseModel,
10 ConfigDict,
11 Field,
12 SerializerFunctionWrapHandler,
13 field_validator,
14 model_serializer,
15 model_validator,
16)
18from governed_harness.configuration.agent_contract import AgentContractConfig
19from governed_harness.configuration.agent_results import (
20 AcceptanceTestsConfig,
21 AgentCallConfig,
22 AgentRoutingConfig,
23 AmbiguityReview,
24 AmbiguityReviewConfig,
25 ArchitectureConfig,
26 BudgetConfig,
27 ContextConfig,
28 ContractRetryConfig,
29 InvariantCheck,
30 MemoryConfig,
31 PlanningConfig,
32 Policy,
33 RiskAction,
34 SarifInput,
35 TestQualityConfig,
36 off_from_yaml,
37)
38from governed_harness.configuration.api import ApiConfig
39from governed_harness.configuration.engineering import (
40 ArchitectureSettings,
41 ForgeConfig,
42 PrinciplesConfig,
43 ProjectSetupMode,
44 StandardsConfig,
45 TestingConfig,
46)
47from governed_harness.configuration.friction import FrictionConfig, MetricsConfig
48from governed_harness.configuration.ladder import (
49 CommentPolicy,
50 ContractMode,
51 EnvironmentConfig,
52 InstructionsConfig,
53 InterruptionConfig,
54 IsolationConfig,
55 LadderConfig,
56 MutationConfig,
57 ProfileVerification,
58 PullRequestConfig,
59)
60from governed_harness.configuration.review import ReviewPanelConfig
61from governed_harness.domain.enums import FindingSeverity, PhaseId
62from governed_harness.domain.models import ProbeDefinition
65class ConfigModel(BaseModel):
66 model_config = ConfigDict(extra="forbid", populate_by_name=True, frozen=True)
69class WorkspaceUnitConfig(ConfigModel):
70 unit_id: str = Field(alias="unitId")
71 root: str
72 profile: str | None = None
75SnapshotMode = Literal["walk", "git"]
76BaselineMode = Literal["text", "manifest"]
79class WorkspaceConfig(ConfigModel):
80 """The workspace root and, since 2.0, how the workspace is read for large repositories.
82 * ``snapshot: git`` lists the files through Git (tracked plus untracked files that
83 ``.gitignore`` does not exclude), so ignored files such as ``.env`` or build output are
84 neither hashed nor stored; ``walk`` (or absent) walks every file as in 1.0.0.
85 * ``baseline: manifest`` stores the baseline as a manifest of digests; the text of a file
86 is stored only when it enters the ChangeSet (taken from Git or from a per-file blob kept
87 for untracked files), instead of the text of every file.
88 * ``snapshotCache: true`` reuses the digest of a file whose size and modification time did
89 not change since the last snapshot of the run.
91 Absent keys keep the 1.0.0 behaviour and are left out of the serialized configuration."""
93 root: str = ".."
94 units: tuple[WorkspaceUnitConfig, ...] = Field(
95 default=(),
96 description="Declarative: declared units are not used by the engine.",
97 json_schema_extra={"x-declarative": True},
98 )
99 snapshot: SnapshotMode | None = None
100 baseline: BaselineMode | None = None
101 snapshot_cache: bool | None = Field(default=None, alias="snapshotCache")
102 isolation: IsolationConfig | None = None
103 """Since #55: worktree isolation per run (``mode: worktree``)."""
105 @model_serializer(mode="wrap")
106 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
107 data: dict[str, Any] = handler(self)
108 for name, alias in (
109 ("snapshot", "snapshot"),
110 ("baseline", "baseline"),
111 ("snapshot_cache", "snapshotCache"),
112 ("isolation", "isolation"),
113 ):
114 if getattr(self, name) is None:
115 data.pop(name, None)
116 data.pop(alias, None)
117 return data
120class CapabilityRule(ConfigModel):
121 capability: str
122 scope: tuple[str, ...]
123 approval_required: bool = Field(default=False, alias="approvalRequired")
124 conditions: dict[str, Any] = Field(default_factory=dict)
127class CapabilitiesConfig(ConfigModel):
128 """``grants`` are the project's capabilities. Under ``governance.phaseCapabilities`` (#4)
129 they narrow the profiles' (``profile ∩ project``) and ``extend`` is the explicit way to add
130 a scope no profile grants (a device lab's command, an agent CLI); without the key both are
131 added to the profiles' scopes, as in 1.0.0."""
133 default: Literal["deny"] = "deny"
134 grants: tuple[CapabilityRule, ...] = ()
135 extend: tuple[CapabilityRule, ...] | None = None
137 @model_serializer(mode="wrap")
138 def _omit_absent_extend(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
139 data: dict[str, Any] = handler(self)
140 if self.extend is None:
141 data.pop("extend", None)
142 return data
145DEFAULT_TRANSIENT_PATTERNS: tuple[str, ...] = (
146 "timed out",
147 "connection reset",
148 "went to sleep",
149 "overloaded",
150 "429",
151 "529",
152 "rate limit",
153 "usage limit",
154)
155"""Messages that mark a command-provider failure as transient when
156``runtime.providerTransientPatterns`` is not set (case-insensitive substrings)."""
158DEFAULT_UNSUPPORTED_CLAIM_SEVERITY = FindingSeverity.MEDIUM
160_OPTIONAL_RUNTIME_FIELDS = {
161 "agent_sandbox": "agentSandbox",
162 "sandbox_write_paths": "sandboxWritePaths",
163 "verification_corrections": "verificationCorrections",
164 "provider_feedback": "providerFeedback",
165 "unsupported_claim_severity": "unsupportedClaimSeverity",
166 "provider_retries": "providerRetries",
167 "provider_retry_delay_seconds": "providerRetryDelaySeconds",
168 "provider_transient_patterns": "providerTransientPatterns",
169 "gate_contract": "gateContract",
170 "reproduce_first": "reproduceFirst",
171 "extended_redaction": "extendedRedaction",
172 "state_dir": "stateDir",
173 "contract_retry": "contractRetry",
174}
175"""Optional runtime keys left out of the serialized configuration while they are unset."""
177AgentSandboxMode = Literal["enforce", "off"]
179DEFAULT_AGENT_SANDBOX: AgentSandboxMode = "off"
180"""Mode of a project.yaml without ``runtime.agentSandbox`` (files written before 2.0)."""
182DEFAULT_SANDBOX_WRITE_PATHS: tuple[tuple[str, str], ...] = (
183 # An allow-list entry of the agent's write sandbox, not a file the harness creates: Bandit
184 # B108 and Sonar S5443 (publicly writable directory) do not apply to a path nothing writes.
185 (
186 "/tmp", # NOSONAR(S5443) # nosec B108
187 "Shared temporary directory (/private/tmp on macOS): compilers, npm and git use it.",
188 ),
189 (
190 "/var/folders",
191 "Per-user temporary and cache directories of macOS (/private/var/folders); $TMPDIR "
192 "lives here.",
193 ),
194 ("~/.claude", "Claude Code keeps its settings, session state, todos and logs here."),
195 (
196 "~/.claude.json*",
197 "Claude Code rewrites its configuration file through temporary, backup and lock files "
198 "next to it (~/.claude.json.backup, ~/.claude.json.lock, ...).",
199 ),
200 ("~/.cache", "XDG cache directory used by agent CLIs, pip, uv and many tools."),
201 ("~/Library/Caches", "Per-user cache directory of macOS (CLI update checks, node caches)."),
202 ("~/.config", "XDG configuration directory where agent CLIs keep state and credentials."),
203 ("~/.npm", "npm cache and logs: npx-launched agents and MCP servers write here."),
204)
205"""Write paths ``harness init`` declares, with the reason for each. The workspace and the
206resolved ``$TMPDIR`` are always writable and are not listed."""
208_SANDBOX_PATH_FORBIDDEN = frozenset('"\\$?[]{}')
211def _sandbox_mode_from_yaml(value: Any) -> Any:
212 # YAML 1.1 (PyYAML) reads a bare ``off`` as false; a hand-written ``agentSandbox: off`` must
213 # mean what it says.
214 return "off" if value is False else value
217def _is_state_dir_path(value: str) -> bool:
218 """A ``runtime.stateDir`` path: absolute or under ``~/``. On Windows an absolute path also
219 starts with a drive or a UNC share (``C:\\...``, ``\\\\server\\share``)."""
220 if value.startswith(("/", "~/")):
221 return True
222 return sys.platform == "win32" and PureWindowsPath(value).is_absolute()
225class RuntimeConfig(ConfigModel):
226 """Process bounds and, since 2.0, the agent sandbox and the feedback loop around the agent
227 provider.
229 The sandbox and loop settings are optional: a key that is absent keeps the 1.0.0 behaviour
230 and is left out of the serialized configuration, so the snapshot digest of an existing
231 project does not change. ``harness init`` writes them."""
233 command_timeout_seconds: int = Field(default=900, alias="commandTimeoutSeconds", ge=1)
234 max_output_bytes: int = Field(default=1_000_000, alias="maxOutputBytes", ge=1024)
235 max_parallel: int = Field(
236 default=2,
237 alias="maxParallel",
238 ge=1,
239 le=32,
240 description=(
241 "Under governance.enforceWorkflow, the most validators declared parallelSafe that a "
242 "parallelizable VERIFICATION runs at once; otherwise phases and validators run one "
243 "at a time."
244 ),
245 )
246 allow_network: bool = Field(
247 default=False,
248 alias="allowNetwork",
249 description=(
250 "Network access of the agent sandbox: false denies outbound connections under "
251 "governance.applyNetworkPolicy and runtime.agentSandbox: enforce; otherwise "
252 "declarative."
253 ),
254 )
255 agent_sandbox: AgentSandboxMode | None = Field(default=None, alias="agentSandbox")
256 sandbox_write_paths: tuple[str, ...] | None = Field(default=None, alias="sandboxWritePaths")
258 @field_validator("agent_sandbox", mode="before")
259 @classmethod
260 def _bare_off_is_off(cls, value: Any) -> Any:
261 return _sandbox_mode_from_yaml(value)
263 @field_validator("sandbox_write_paths")
264 @classmethod
265 def _write_paths_are_absolute(cls, value: tuple[str, ...] | None) -> tuple[str, ...] | None:
266 for path in value or ():
267 if not (path == "~" or path.startswith(("/", "~/"))):
268 raise ValueError(f"sandbox write path must be absolute or start with ~/: {path!r}")
269 if any(ord(char) < 32 for char in path) or _SANDBOX_PATH_FORBIDDEN & set(path):
270 raise ValueError(
271 f"sandbox write path must not contain quotes, backslashes, $, control "
272 f"characters or glob patterns other than a trailing *: {path!r}"
273 )
274 if "*" in path.rstrip("*") or path.count("*") > 1:
275 raise ValueError(f"only a single trailing * is allowed: {path!r}")
276 if path.rstrip("/*") == "":
277 raise ValueError("the file system root is not a sandbox write path; use 'off'")
278 return value
280 @property
281 def effective_agent_sandbox(self) -> AgentSandboxMode:
282 """The agent sandbox mode: ``off`` when ``agentSandbox`` is absent."""
283 return self.agent_sandbox or DEFAULT_AGENT_SANDBOX
285 verification_corrections: int | None = Field(
286 default=None, alias="verificationCorrections", ge=0, le=10
287 )
288 provider_feedback: bool | None = Field(default=None, alias="providerFeedback")
289 unsupported_claim_severity: FindingSeverity | None = Field(
290 default=None, alias="unsupportedClaimSeverity"
291 )
292 provider_retries: int | None = Field(default=None, alias="providerRetries", ge=0, le=10)
293 provider_retry_delay_seconds: float | None = Field(
294 default=None, alias="providerRetryDelaySeconds", ge=0, le=3600
295 )
296 provider_transient_patterns: tuple[str, ...] | None = Field(
297 default=None, alias="providerTransientPatterns"
298 )
299 extended_redaction: bool | None = Field(default=None, alias="extendedRedaction")
300 """Since 2.0: also redact model-API keys (``sk-ant-``, ``sk-``, ``AIza``), Slack tokens,
301 JSON Web Tokens and credentials in URLs from every stored artifact and from the agent's
302 summary. Absent or false keeps the 1.0.0 rules."""
304 gate_contract: bool | None = Field(default=None, alias="gateContract")
305 """Since 2.0 (#52): the implement request carries the gate contract (validators, review
306 rules, blocking severities, the workspace path and the ``harness check`` command) and the
307 agent's permissions derived from the capability grants."""
308 contract_retry: ContractRetryConfig | None = Field(default=None, alias="contractRetry")
309 """Since #80: a read-only call whose answer breaks its contract is retried once (on
310 ``fallbackProvider`` when configured) before the phase blocks; both attempts are recorded."""
311 reproduce_first: bool | None = Field(default=None, alias="reproduceFirst")
312 """Since 2.0 (#52): a correction attempt that changes nothing is a finding, and a correction
313 after REQUEST_CHANGES must add a test that fails before it and passes after it."""
314 state_dir: str | None = Field(default=None, alias="stateDir")
315 """Since #55: where the run registry (state database and artifacts) lives. ``auto`` is the
316 user's data directory (``$HARNESS_STATE_DIR``, else the platform's application-data
317 directory); an absolute path or one starting with ``~/`` is used as given. Absent: the
318 1.0.0 ``.harness/state.db`` of the workspace."""
320 @field_validator("state_dir")
321 @classmethod
322 def _state_dir(cls, value: str | None) -> str | None:
323 if value is None or value == "auto":
324 return value
325 if not _is_state_dir_path(value) or "$" in value: 325 ↛ 326line 325 didn't jump to line 326 because the condition on line 325 was never true
326 raise ValueError(
327 f"stateDir is auto, an absolute path or a path that starts with ~/: {value!r}"
328 )
329 return value
331 @field_validator("provider_transient_patterns")
332 @classmethod
333 def patterns_must_not_be_blank(cls, value: tuple[str, ...] | None) -> tuple[str, ...] | None:
334 if value is not None and any(not item.strip() for item in value):
335 raise ValueError("providerTransientPatterns must not contain blank patterns")
336 return value
338 @property
339 def correction_limit(self) -> int:
340 """Automatic corrections after a failed VERIFICATION: 0 when the key is absent."""
341 return self.verification_corrections or 0
343 @property
344 def claim_check_enabled(self) -> bool:
345 """The unsupported-claim check belongs to the verification loop: it runs when
346 ``verificationCorrections`` is set, with any value."""
347 return self.verification_corrections is not None
349 @property
350 def claim_severity(self) -> FindingSeverity:
351 return self.unsupported_claim_severity or DEFAULT_UNSUPPORTED_CLAIM_SEVERITY
353 @property
354 def feedback_enabled(self) -> bool:
355 return bool(self.provider_feedback)
357 @property
358 def retry_limit(self) -> int:
359 return self.provider_retries or 0
361 @property
362 def retry_delay_seconds(self) -> float:
363 return self.provider_retry_delay_seconds or 0.0
365 @property
366 def transient_patterns(self) -> tuple[str, ...]:
367 if self.provider_transient_patterns is None:
368 return DEFAULT_TRANSIENT_PATTERNS
369 return self.provider_transient_patterns
371 @model_serializer(mode="wrap")
372 def _omit_absent_optional_settings(
373 self, handler: SerializerFunctionWrapHandler
374 ) -> dict[str, Any]:
375 # Like the intake section: a file without the sandbox or loop keys serializes as before,
376 # so the configuration snapshot (and its digest) of a project written for 1.0.0 does not
377 # change.
378 data: dict[str, Any] = handler(self)
379 for name, alias in _OPTIONAL_RUNTIME_FIELDS.items():
380 if getattr(self, name) is None:
381 data.pop(name, None)
382 data.pop(alias, None)
383 return data
386AgentProviderKind = Literal["command", "claude-code", "codex", "gemini-cli", "aider"]
387"""``command`` speaks the harness JSON protocol; the others are built-in adapters (since 2.0)
388that run the agent CLI in its non-interactive mode and read its own output."""
390NATIVE_PROVIDER_KINDS: tuple[str, ...] = ("claude-code", "codex", "gemini-cli", "aider")
392NATIVE_DEFAULT_COMMANDS: dict[str, tuple[str, ...]] = {
393 "claude-code": ("claude",),
394 "codex": ("codex",),
395 "gemini-cli": ("gemini",),
396 "aider": ("aider",),
397}
398"""The executable a built-in adapter runs when the provider sets no ``command``."""
400_ENV_NAME = re.compile(r"^[A-Za-z_]\w{0,127}$", re.ASCII)
403class ProviderEnvReference(ConfigModel):
404 """A provider environment variable whose value is read from the harness's environment
405 when the provider starts: the value never appears in ``project.yaml`` or the snapshot."""
407 from_env: str = Field(alias="fromEnv")
409 @field_validator("from_env")
410 @classmethod
411 def _is_env_name(cls, value: str) -> str:
412 if not _ENV_NAME.match(value): 412 ↛ 413line 412 didn't jump to line 413 because the condition on line 412 was never true
413 raise ValueError(f"fromEnv is not an environment variable name: {value!r}")
414 return value
417class AgentProviderConfiguration(ConfigModel):
418 """An agent provider.
420 Since 2.0 a provider may also declare ``kind`` (a built-in adapter), ``args`` (extra
421 command-line arguments of a built-in adapter), ``passEnv`` (variables of the harness's
422 environment passed as they are) and ``env`` (variables set for the provider, as a literal
423 value or ``{fromEnv: NAME}``). Values that come from the environment are redacted from
424 every artifact. Absent keys keep the 1.0.0 behaviour and are left out of the serialized
425 configuration."""
427 kind: AgentProviderKind = "command"
428 command: tuple[str, ...] | None = None
429 model: str | None = None
430 args: tuple[str, ...] | None = None
431 pass_env: tuple[str, ...] | None = Field(default=None, alias="passEnv")
432 env: dict[str, str | ProviderEnvReference] | None = None
434 @field_validator("command")
435 @classmethod
436 def command_must_not_be_empty(cls, value: tuple[str, ...] | None) -> tuple[str, ...] | None:
437 if value is not None and not value: 437 ↛ 438line 437 didn't jump to line 438 because the condition on line 437 was never true
438 raise ValueError("agent provider command must not be empty")
439 return value
441 @field_validator("pass_env")
442 @classmethod
443 def _pass_env_names(cls, value: tuple[str, ...] | None) -> tuple[str, ...] | None:
444 for name in value or ():
445 if not _ENV_NAME.match(name): 445 ↛ 446line 445 didn't jump to line 446 because the condition on line 445 was never true
446 raise ValueError(f"passEnv entry is not an environment variable name: {name!r}")
447 return value
449 @field_validator("env")
450 @classmethod
451 def _env_names(
452 cls, value: dict[str, str | ProviderEnvReference] | None
453 ) -> dict[str, str | ProviderEnvReference] | None:
454 for name in value or {}:
455 if not _ENV_NAME.match(name): 455 ↛ 456line 455 didn't jump to line 456 because the condition on line 455 was never true
456 raise ValueError(f"env key is not an environment variable name: {name!r}")
457 return value
459 @model_validator(mode="after")
460 def _command_for_command_kind(self) -> AgentProviderConfiguration:
461 if self.kind == "command" and self.command is None: 461 ↛ 462line 461 didn't jump to line 462 because the condition on line 461 was never true
462 raise ValueError("a provider of kind command needs a command")
463 if self.kind == "command" and self.args is not None: 463 ↛ 464line 463 didn't jump to line 464 because the condition on line 463 was never true
464 raise ValueError("args applies to the built-in adapters; put it in command")
465 return self
467 @property
468 def native(self) -> bool:
469 return self.kind in NATIVE_PROVIDER_KINDS
471 @property
472 def effective_command(self) -> tuple[str, ...]:
473 """``command``, or the default executable of a built-in adapter."""
474 return self.command or NATIVE_DEFAULT_COMMANDS.get(self.kind, ())
476 @model_serializer(mode="wrap")
477 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
478 data: dict[str, Any] = handler(self)
479 for name, field in type(self).model_fields.items():
480 if name in {"model", "kind"}:
481 continue
482 if getattr(self, name) is None:
483 data.pop(name, None)
484 data.pop(field.alias or name, None)
485 return data
488CriteriaPolicy = Literal["enforce", "warn", "off"]
489IntakeLanguage = Literal["auto", "en", "es"]
491DEFAULT_CRITERIA_POLICY: CriteriaPolicy = "warn"
492"""Policy of a project.yaml without ``intake.criteriaPolicy`` (files written before 2.0)."""
495class IntakeConfig(ConfigModel):
496 """How INTENT treats acceptance criteria that cannot be observed.
498 ``enforce`` blocks INTENT until a person answers the clarification questions, ``warn``
499 records the questions as evidence and low-severity findings and lets the run continue,
500 ``off`` skips the assessment.
502 Since 2.0 (#37): ``ambiguityReview: agent`` also asks an agent (call kind ``clarify``) for
503 ambiguity and completeness questions once per task revision, ``clarifyAgent`` chooses its
504 provider, model and effort, and ``validateAnswers`` checks a person's answers for references
505 to documents or requirements the task and the workspace do not contain. Absent keys keep the
506 1.0.0 behaviour.
508 Since #79 ``ambiguityReview`` may also be an object (``mode``, ``maxRounds``,
509 ``maxQuestions``, ``onExhausted``): the review converges and, after its last round, records
510 the open points as assumptions or keeps INTENT blocked. The bare ``agent`` keeps the single-round
511 review."""
513 criteria_policy: CriteriaPolicy = Field(default=DEFAULT_CRITERIA_POLICY, alias="criteriaPolicy")
514 ambiguity_review: AmbiguityReview | AmbiguityReviewConfig | None = Field(
515 default=None, alias="ambiguityReview"
516 )
517 clarify_agent: AgentCallConfig | None = Field(default=None, alias="clarifyAgent")
518 validate_answers: bool | None = Field(default=None, alias="validateAnswers")
519 operational_contract: ContractMode | None = Field(default=None, alias="operationalContract")
520 """Since #55: the operational contract at intake. ``batch`` adds the contract questions to
521 the one clarification request INTENT sends anyway and records the contract summary bound to
522 the task digest; ``enforce`` also asks for every missing item and needs a person to confirm
523 the summary (``harness task confirm``); ``off`` records nothing."""
524 interruptions: InterruptionConfig | None = None
525 """Since #55: the interruption budget and the stop conditions of a run."""
527 project_setup: ProjectSetupMode | None = Field(default=None, alias="projectSetup")
528 """Since 2.0 (#56): ``ask`` makes INTENT ask, once per project, the architecture, the
529 testing strategy and the standards of a new project, and of an existing project whatever
530 detection could not establish (rule ``P1``)."""
532 language: IntakeLanguage | None = None
533 """Since 2.0: the language of the deterministic INTENT rules (C0 to C3, T1). ``en`` and
534 ``es`` choose it, ``auto`` detects it from the task text (Spanish when the task has more
535 Spanish than English function words and Spanish marks, otherwise English). Words are
536 Unicode tokens compared without diacritics, ``es`` adds the Spanish vocabularies to the
537 English ones and asks the questions in Spanish; rule and question ids do not change.
538 Absent keeps the earlier rules: ASCII words, English vocabularies and questions."""
540 @field_validator("ambiguity_review", "operational_contract", "project_setup", mode="before")
541 @classmethod
542 def _bare_off(cls, value: Any) -> Any:
543 return off_from_yaml(value)
545 @property
546 def agent_review_enabled(self) -> bool:
547 value = self.ambiguity_review
548 if isinstance(value, AmbiguityReviewConfig):
549 return value.enabled
550 return value == "agent"
552 @property
553 def ambiguity_settings(self) -> AmbiguityReviewConfig | None:
554 """The converging review's settings (#79): only under the object form of
555 ``ambiguityReview``; the bare ``agent`` keeps the single-round review."""
556 value = self.ambiguity_review
557 return value if isinstance(value, AmbiguityReviewConfig) and value.enabled else None
559 @model_serializer(mode="wrap")
560 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
561 data: dict[str, Any] = handler(self)
562 for name in (
563 "ambiguity_review",
564 "clarify_agent",
565 "validate_answers",
566 "operational_contract",
567 "interruptions",
568 "project_setup",
569 "language",
570 ):
571 if getattr(self, name) is None:
572 data.pop(name, None)
573 data.pop(type(self).model_fields[name].alias or name, None)
574 return data
577RequirementTraceabilityPolicy = Literal["enforce", "warn", "off"]
579DEFAULT_REQUIREMENT_TRACEABILITY: RequirementTraceabilityPolicy = "off"
580"""Policy of a project.yaml without ``verification.requirementTraceability`` (files written
581before 2.0): no traceability check, as in 1.0.0."""
584class VerificationConfig(ConfigModel):
585 """What VERIFICATION does with identified requirements that no test names.
587 ``enforce`` records each one as a ``HIGH`` finding, which fails the gate under the default
588 ``findingBlockSeverities``; ``warn`` records it as a ``LOW`` finding; ``off`` skips the
589 check."""
591 requirement_traceability: RequirementTraceabilityPolicy = Field(
592 default=DEFAULT_REQUIREMENT_TRACEABILITY, alias="requirementTraceability"
593 )
594 output_parsers: bool | None = Field(default=None, alias="outputParsers")
595 """Since 2.0: parse the output of failing command validators (JUnit XML, Ruff, Mypy, ESLint,
596 tsc, SARIF, pytest) into one finding per reported problem, with file, line and rule. Absent
597 or false keeps the single summary finding of 1.0.0."""
599 # ----- since 2.0, agent results (#40, #52); every key absent keeps 1.0.0 -----------------
600 interface: Policy | None = None
601 """Conformance of a task's declared interface (``metadata.interface``): ``enforce`` makes a
602 mismatch HIGH, ``warn`` LOW."""
603 architecture: ArchitectureConfig | None = None
604 security_patterns: bool | None = Field(default=None, alias="securityPatterns")
605 """Unrestricted pickle/marshal of stored data, persisted card numbers or CVC, and weak
606 password hashing are HIGH findings."""
607 constraints: Policy | None = None
608 """Verifiable task constraints (standard library only, no clock or random, annotated public
609 API, no float money, no stubs) recognised from the task or listed in ``metadata.checks``."""
610 ratchet: Policy | None = None
611 """Optional validators (Ruff, Mypy) must not report more problems than on the baseline."""
612 invariants: tuple[InvariantCheck, ...] | None = None
613 differential: bool | None = None
614 """Run a failing mandatory validator on the baseline and block only introduced failures."""
615 weakened_controls: Policy | None = Field(default=None, alias="weakenedControls")
616 test_quality: TestQualityConfig | None = Field(default=None, alias="testQuality")
617 secrets: Literal["context", "pattern"] | None = None
618 """``context``: the secret check of the independent review weighs where a literal is
619 (tests, environment assignments, values the task declares) and detects evasion."""
620 sarif: tuple[SarifInput, ...] | None = None
621 risk_factors: dict[str, RiskAction] | None = Field(default=None, alias="riskFactors")
622 acceptance_tests: AcceptanceTestsConfig | None = Field(default=None, alias="acceptanceTests")
623 reverify_on_change: bool | None = Field(default=None, alias="reverifyOnChange")
624 """Since 2.0 (#78): ``run continue`` on a run waiting in DECISION whose ChangeSet changed
625 outside the run records the change as evidence and runs VERIFICATION again on the new
626 ChangeSet. Absent or false keeps the earlier behaviour: the gate of the new ChangeSet has
627 no validation of it and is ``INCONCLUSIVE``, so the change needs a new run or a
628 ``REQUEST_CHANGES``."""
629 # ----- since #55: the verification ladder ----------------------------------------------
630 ladder: LadderConfig | None = None
631 probes: tuple[ProbeDefinition, ...] | None = None
632 """Behaviour probes of the project (each task may declare more)."""
633 mutation: MutationConfig | None = None
634 principles: PrinciplesConfig | None = None
635 """Since 2.0 (#56): engineering principles as deterministic proxies (duplication, size and
636 complexity, dependency direction, inheritance depth, unused public API, Boy Scout scope) and
637 a checklist inside the existing review call."""
639 @field_validator("probes")
640 @classmethod
641 def _unique_probes(
642 cls, value: tuple[ProbeDefinition, ...] | None
643 ) -> tuple[ProbeDefinition, ...] | None:
644 ids = [item.probe_id for item in value or ()]
645 if len(set(ids)) != len(ids): 645 ↛ 646line 645 didn't jump to line 646 because the condition on line 645 was never true
646 raise ValueError("probe ids must be unique")
647 return value
649 @field_validator("interface", "constraints", "ratchet", "weakened_controls", mode="before")
650 @classmethod
651 def _bare_off(cls, value: Any) -> Any:
652 return off_from_yaml(value)
654 @field_validator("risk_factors")
655 @classmethod
656 def _known_factors(cls, value: dict[str, RiskAction] | None) -> dict[str, RiskAction] | None:
657 from governed_harness.configuration.agent_results import RISK_FACTORS
659 unknown = sorted(set(value or {}) - set(RISK_FACTORS))
660 if unknown: 660 ↛ 661line 660 didn't jump to line 661 because the condition on line 660 was never true
661 raise ValueError(
662 f"unknown risk factor(s): {', '.join(unknown)}; known: {', '.join(RISK_FACTORS)}"
663 )
664 return value
666 @model_serializer(mode="wrap")
667 def _omit_absent_parsers(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
668 data: dict[str, Any] = handler(self)
669 for name, field in type(self).model_fields.items():
670 if name != "requirement_traceability" and getattr(self, name) is None:
671 data.pop(name, None)
672 data.pop(field.alias or name, None)
673 return data
676DEFAULT_EXCEPTION_DAYS = 30
677"""Validity of an exception when neither the decision nor ``review.exceptionDays`` sets one."""
680class ReviewConfig(ConfigModel):
681 """How a person's exceptions are recorded (since 2.0).
683 With ``exceptions: true`` an ``APPROVE_EXCEPTION`` decision records an exception with an
684 expiry, a scope (the findings it covers, by rule, path and fingerprint), optional
685 alternative evidence and a follow-up. While it is in force, a later run of the project does
686 not block on the findings it covers; once it expires they block again, and a run waiting in
687 DECISION on an expired exception is blocked. Absent or false keeps the 1.0.0 behaviour: an
688 exception is a decision with a rationale and no expiry."""
690 exceptions: bool | None = None
691 exception_days: int | None = Field(default=None, alias="exceptionDays", ge=1, le=365)
692 agent_review: Policy | None = Field(default=None, alias="agentReview")
693 """Since 2.0 (#38): a second agent (call kind ``review``) reviews the ChangeSet in
694 INDEPENDENT_REVIEW; under ``enforce`` its HIGH and CRITICAL findings block the gate."""
695 reviewer: AgentCallConfig | None = None
696 structured_changes: bool | None = Field(default=None, alias="structuredChanges")
697 """Since 2.0 (#52): REQUEST_CHANGES may carry blocking items with a verifiable condition
698 that VERIFICATION checks until the run closes."""
699 manual_checklist: bool | None = Field(default=None, alias="manualChecklist")
700 """Since #55: items only a person can verify (``manual`` criteria and the task's
701 ``checklist``) are ticked in DECISION (``gate decide --check``); APPROVE needs them all."""
702 panel: ReviewPanelConfig | None = None
703 """Since #57: the review panel (reviewers by domain, layered rule catalog, output
704 contract, deterministic verdict) replaces the single reviewer in INDEPENDENT_REVIEW and runs
705 outside governed runs with ``harness review-code``."""
707 @field_validator("agent_review", mode="before")
708 @classmethod
709 def _bare_off(cls, value: Any) -> Any:
710 return off_from_yaml(value)
712 @model_serializer(mode="wrap")
713 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
714 data: dict[str, Any] = handler(self)
715 for name, field in type(self).model_fields.items():
716 if getattr(self, name) is None:
717 data.pop(name, None)
718 data.pop(field.alias or name, None)
719 return data
722NotificationEvent = Literal["decision.pending", "run.finished", "exception.granted"]
724_WEBHOOK_ENV_NAME = re.compile(r"^[A-Za-z_]\w{0,127}$", re.ASCII)
727class WebhookConfig(ConfigModel):
728 """A URL that receives a JSON ``POST`` when a run waits for a decision or finishes.
730 ``urlEnv`` names an environment variable that holds the URL, so a URL that carries a token
731 (Slack, Teams) stays out of ``project.yaml`` and of the configuration snapshot. The payload
732 carries identifiers, statuses and digests only: no rationale, no output, no secret."""
734 url: str | None = None
735 url_env: str | None = Field(default=None, alias="urlEnv")
736 events: tuple[NotificationEvent, ...] = ("decision.pending", "run.finished")
737 retries: int = Field(default=2, ge=0, le=10)
738 timeout_seconds: float = Field(default=5.0, alias="timeoutSeconds", gt=0, le=60)
740 @model_validator(mode="after")
741 def _one_target(self) -> WebhookConfig:
742 if (self.url is None) == (self.url_env is None):
743 raise ValueError("a webhook needs exactly one of url or urlEnv")
744 if self.url is not None and not self.url.startswith(("http://", "https://")):
745 raise ValueError("a webhook url must start with http:// or https://")
746 if self.url_env is not None and not _WEBHOOK_ENV_NAME.match(self.url_env):
747 raise ValueError(f"urlEnv is not an environment variable name: {self.url_env!r}")
748 if not self.events:
749 raise ValueError("a webhook needs at least one event")
750 return self
753class NotificationsConfig(ConfigModel):
754 """Webhooks notified when a run waits for a human decision or finishes (since 2.0).
755 Absent: nothing is sent, as in 1.0.0."""
757 webhooks: tuple[WebhookConfig, ...] = ()
760class RetrospectiveConfig(ConfigModel):
761 """With ``causal: true`` (since 2.0) the retrospective attributes every blocked gate and
762 correction cycle to the reason code, validator or rule that caused it, ignores optional
763 validators that had no effect on the gate, and is also generated when a run is rejected or
764 cancelled. Absent or false keeps the 1.0.0 retrospective."""
766 causal: bool | None = None
768 @model_serializer(mode="wrap")
769 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
770 data: dict[str, Any] = handler(self)
771 if self.causal is None: 771 ↛ 772line 771 didn't jump to line 772 because the condition on line 771 was never true
772 data.pop("causal", None)
773 return data
776DeciderIdentity = Literal["git", "default"]
777StopTheLine = Literal["restore", "block", "off"]
778ChainAnchorMode = Literal["file", "git-note", "off"]
779UnanchoredEvents = Literal["warn", "fail"]
780RiskProfile = Literal["auto", "light", "full"]
782DEFAULT_TRUSTED_HOSTS: tuple[str, ...] = ("127.0.0.1", "localhost", "::1")
783"""Host names ``harness init`` lets the local API answer to (``governance.trustedHosts``)."""
785DEFAULT_DECISION_EXPIRY_HOURS = 72
786"""Validity of a human decision that ``harness init`` writes (``governance.decisionExpiryHours``)."""
789class GovernanceConfig(ConfigModel):
790 """Integrity settings of the human decisions, the workspace and the record (since 2.0).
792 Every key is optional: a key that is absent keeps the 1.0.0 behaviour and is left out of
793 the serialized configuration, so the snapshot digest of an existing project does not
794 change. ``harness init`` writes them all.
796 * ``deciderIdentity``: ``git`` records the Git user (``user.email``, ``user.name``) as the
797 person who decides when no ``--actor`` is given; ``default`` (or absent) keeps the fixed
798 ``human.local`` and ``human.web`` identifiers.
799 * ``confirmDecisionDigest``: on a terminal, ``harness gate decide`` shows the decision and
800 asks for the first characters of the ChangeSet digest before recording it.
801 * ``trustedHosts``: the local API answers only requests whose ``Host`` is one of these
802 names (DNS-rebinding protection); absent, every host is accepted.
803 * ``verifyRecords``: ``trace`` (every format) verifies the run first (event chain, records
804 against events, artifact digests, anchor) and refuses to export a run that fails, and
805 ``status`` adds the result of the record check.
806 * ``chainAnchor``: ``file`` or ``git-note`` keeps a copy of the head of each run's event
807 chain outside ``.harness`` so that ``harness verify`` detects a truncated chain.
808 * ``unanchoredEvents`` (#149): how ``harness verify`` treats the events after the anchored
809 head, which the anchor does not cover. ``warn`` lists them as a warning and ``fail`` also
810 fails the run; under either, a ``retention.artifacts.pruned`` event excuses a missing
811 artifact only when it is within the anchored part of the chain. Absent, the events after
812 the anchor are only counted (``eventsAfterAnchor``) and every prune event excuses, as in
813 1.x.
814 * ``pinTaskRevision``: a run works on the task revision it was created with (or a revision
815 made through ``task clarify``), ``task create`` refuses a task id that has an open run, and
816 a decision is bound to the acceptance-contract digest frozen in SPECIFICATION.
817 * ``protectExcludedPaths``: what the ChangeSet leaves out (``.git``, ``.harness``, virtual
818 environments, ``node_modules``, ``dist``, ``build``, symbolic links) is fingerprinted
819 around every agent invocation and a change is a ``CRITICAL`` finding that fails the gate;
820 the agent sandbox keeps ``.harness`` and ``.git`` read-only, and the profiles' write grants
821 on ``.harness/**`` and ``.git/**`` are dropped.
822 * ``workspaceLease``: one harness process at a time executes phases in a workspace
823 (``.harness/lease.json`` with pid, host and heartbeat); an interrupted phase is recorded
824 as ``INTERRUPTED``, and ``run continue`` terminates the process groups a killed harness
825 left and restores the workspace an interrupted IMPLEMENTATION attempt found.
826 * ``applyWorkflowSettings``: the workflow's per-phase ``maxAttempts``, ``timeoutSeconds`` and
827 ``exitGate`` take effect.
828 * ``decisionExpiryHours``: a human decision expires (``expiresAt``) that many hours after it
829 is recorded; an expired decision does not let DECISION pass.
830 * ``applyProfilePolicies``: the profile policies ``missingTestCommand`` and
831 ``missingTestScript`` set the status of an unavailable mandatory validator, and a
832 ``coverage`` policy with ``minimumPercent`` adds a mandatory coverage validator (Python).
833 * ``applyNetworkPolicy``: ``runtime.allowNetwork: false`` denies outbound network access
834 to the agent under ``runtime.agentSandbox: enforce``.
835 * ``stopTheLine`` (#52): when a run stops without an approval (rejected, failed, timed
836 out, cancelled), ``restore`` keeps its changes as a quarantined patch and restores the
837 workspace to the baseline, ``block`` refuses new runs in the workspace until a person
838 quarantines them (``harness run quarantine``).
839 * ``phasePermissions`` (#52): every agent request carries the permissions of its call kind,
840 derived from the capability grants (read-only for clarify, review and plan), recorded as
841 evidence.
842 * ``phaseCapabilities`` (#4): the grants are the profile's narrowed by the project's (a
843 project narrows, never widens, a profile), every grant made while a phase runs keeps only
844 the capabilities the phase allows (the workflow's ``allowedCapabilities``), an agent call
845 outside IMPLEMENTATION is read-only and may start only its own command, an agent's own
846 command is started only when a ``process.execute`` grant allows it (otherwise a ``HIGH``
847 ``capabilities.command-denied`` finding blocks the phase, #87), and the resolved grants of
848 each phase attempt are recorded as evidence.
849 * ``applyRepositoryPolicies`` (#5): ``policies.repositoryContentTrusted: false`` makes
850 repository content (instruction files included) quoted, untrusted context of every agent
851 request with a prompt-injection notice, and the review panel flags instructions in changed
852 files; ``policies.destructiveActionsDefault: deny`` refuses destructive commands (recursive
853 deletes outside the workspace, force pushes, history rewrites, dropped data, ownership or
854 permission changes outside the workspace) unless a ``process.destructive`` grant allows
855 them, with a finding for each attempt.
856 * ``enforceWorkflow`` (#3): the workflow's ``exitGate`` and transition conditions are
857 evaluated from the run's records after a phase attempt passes (an unmet condition leaves
858 the attempt ``BLOCKED`` with a ``phase.exit_gate.unmet`` event), ``dependsOn`` decides
859 which phase may start, and ``parallelizable`` lets the validators declared
860 ``parallelSafe`` of a parallelizable ``VERIFICATION`` run at once, up to
861 ``runtime.maxParallel``. An unknown gate or condition is a configuration error.
862 * ``riskProfile``: the governance profile of each task by its risk. ``auto`` gives a task
863 the router sizes ``S`` with no risk flag (no security term, no ``riskPaths`` match, no
864 verification beyond ``L1``) the **light** profile and every other task the **full** one;
865 ``light`` gives the light profile to every task without a risk flag, whatever its size;
866 ``full`` gives every task the full profile (no fast lane). The light profile is the
867 fast lane of ``friction.fastLane`` (its ``skip`` and ``verification`` when configured,
868 else the defaults) plus no ``locate`` call and no ``planApproval: risk`` checkpoint; it
869 keeps the nine phases, the mandatory validators, the frozen acceptance tests, the
870 fail-closed gate, the digest-bound human decision and the event chain, and a ChangeSet
871 with a risk factor still takes the run out of it. Any value also reads the ``security``
872 risk flag with the contextual detector (``agents.risk_terms``) instead of the 1.x word
873 list. Absent, the fast lane is ``friction.fastLane`` alone, as in 1.x."""
875 decider_identity: DeciderIdentity | None = Field(default=None, alias="deciderIdentity")
876 confirm_decision_digest: bool | None = Field(default=None, alias="confirmDecisionDigest")
877 trusted_hosts: tuple[str, ...] | None = Field(default=None, alias="trustedHosts")
878 verify_records: bool | None = Field(default=None, alias="verifyRecords")
879 chain_anchor: ChainAnchorMode | None = Field(default=None, alias="chainAnchor")
880 unanchored_events: UnanchoredEvents | None = Field(default=None, alias="unanchoredEvents")
881 pin_task_revision: bool | None = Field(default=None, alias="pinTaskRevision")
882 protect_excluded_paths: bool | None = Field(default=None, alias="protectExcludedPaths")
883 workspace_lease: bool | None = Field(default=None, alias="workspaceLease")
884 apply_workflow_settings: bool | None = Field(default=None, alias="applyWorkflowSettings")
885 decision_expiry_hours: int | None = Field(
886 default=None, alias="decisionExpiryHours", ge=1, le=8760
887 )
888 apply_profile_policies: bool | None = Field(default=None, alias="applyProfilePolicies")
889 apply_network_policy: bool | None = Field(default=None, alias="applyNetworkPolicy")
890 stop_the_line: StopTheLine | None = Field(default=None, alias="stopTheLine")
891 phase_permissions: bool | None = Field(default=None, alias="phasePermissions")
892 phase_capabilities: bool | None = Field(default=None, alias="phaseCapabilities")
893 apply_repository_policies: bool | None = Field(default=None, alias="applyRepositoryPolicies")
894 enforce_workflow: bool | None = Field(default=None, alias="enforceWorkflow")
895 risk_profile: RiskProfile | None = Field(default=None, alias="riskProfile")
897 @field_validator("stop_the_line", mode="before")
898 @classmethod
899 def _bare_off(cls, value: Any) -> Any:
900 return off_from_yaml(value)
902 @field_validator("trusted_hosts")
903 @classmethod
904 def _hosts_are_names(cls, value: tuple[str, ...] | None) -> tuple[str, ...] | None:
905 for host in value or ():
906 if not host.strip() or any(char.isspace() or char == "/" for char in host): 906 ↛ 907line 906 didn't jump to line 907 because the condition on line 906 was never true
907 raise ValueError(f"trusted host must be a host name or address: {host!r}")
908 return value
910 @property
911 def git_decider(self) -> bool:
912 return self.decider_identity == "git"
914 @model_serializer(mode="wrap")
915 def _omit_absent_settings(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
916 data: dict[str, Any] = handler(self)
917 for name, field in type(self).model_fields.items():
918 if getattr(self, name) is None:
919 data.pop(name, None)
920 data.pop(field.alias or name, None)
921 return data
924class ProjectConfiguration(ConfigModel):
925 config_version: Literal["1.0"] = Field(alias="configVersion")
926 project_id: str = Field(alias="projectId")
927 workspace: WorkspaceConfig
928 profiles: tuple[str, ...] = ("auto",)
929 workflow: str = "default_development"
930 capabilities: CapabilitiesConfig = Field(default_factory=CapabilitiesConfig)
931 validators: tuple[str, ...] = ()
932 policies: dict[str, Any] = Field(default_factory=dict)
933 agent_provider: str = Field(default="simulated", alias="agentProvider")
934 agent_providers: dict[str, AgentProviderConfiguration] = Field(
935 default_factory=dict, alias="agentProviders"
936 )
937 runtime: RuntimeConfig = Field(default_factory=RuntimeConfig)
938 retention: dict[str, Any] = Field(
939 default_factory=dict,
940 description=(
941 "artifactDays and eventDays: what harness gc removes for runs that ended longer ago."
942 ),
943 )
944 intake: IntakeConfig | None = None
945 verification: VerificationConfig | None = None
946 governance: GovernanceConfig | None = None
947 review: ReviewConfig | None = None
948 notifications: NotificationsConfig | None = None
949 retrospective: RetrospectiveConfig | None = None
950 planning: PlanningConfig | None = None
951 context: ContextConfig | None = None
952 budget: BudgetConfig | None = None
953 memory: MemoryConfig | None = None
954 agent_routing: AgentRoutingConfig | None = Field(default=None, alias="agentRouting")
955 agent_contract: AgentContractConfig | None = Field(default=None, alias="agentContract")
956 """Since #97: the versioned request and response contract of agent calls, the cap of
957 iterations and the token budget and time limit by task size."""
958 toolchain: ToolchainConfig | None = None
959 provenance: ProvenanceConfig | None = None
960 delivery: DeliveryConfig | None = None
961 environment: EnvironmentConfig | None = None
962 """Since #55: the generic environment preflight of DISCOVERY and ``harness doctor``."""
963 instructions: InstructionsConfig | None = None
964 """Since #55: the agent instruction files ``harness config lint`` reads."""
965 standards: StandardsConfig | None = None
966 testing: TestingConfig | None = None
967 architecture: ArchitectureSettings | None = None
968 friction: FrictionConfig | None = None
969 """Since #58: the fast lane, pre-authorised approval, change types and friction targets."""
970 metrics: MetricsConfig | None = None
971 """Since #58: the price table and the narrative command of ``harness metrics``."""
972 api: ApiConfig | None = None
973 """Since #18: authentication and roles of ``harness api serve``; absent, no authentication
974 as in 1.0.0."""
976 @property
977 def friction_settings(self) -> FrictionConfig:
978 """The friction settings, all absent (1.0.0 behaviour) when the section is."""
979 return self.friction or FrictionConfig()
981 @property
982 def api_settings(self) -> ApiConfig:
983 """The API settings: authentication off (1.0.0 behaviour) when the section is absent."""
984 return self.api or ApiConfig(auth="off")
986 @property
987 def toolchain_settings(self) -> ToolchainConfig:
988 return self.toolchain or ToolchainConfig()
990 @property
991 def provenance_settings(self) -> ProvenanceConfig:
992 return self.provenance or ProvenanceConfig()
994 @property
995 def delivery_settings(self) -> DeliveryConfig:
996 return self.delivery or DeliveryConfig()
998 @property
999 def governance_settings(self) -> GovernanceConfig:
1000 """The governance settings, all absent (1.0.0 behaviour) when the section is."""
1001 return self.governance or GovernanceConfig()
1003 @property
1004 def output_parsers_enabled(self) -> bool:
1005 """Whether failing command validators are parsed into located findings."""
1006 return bool(self.verification and self.verification.output_parsers)
1008 @property
1009 def exceptions_enabled(self) -> bool:
1010 """Whether APPROVE_EXCEPTION records a scoped exception with an expiry."""
1011 return bool(self.review and self.review.exceptions)
1013 @property
1014 def exception_days(self) -> int:
1015 days = self.review.exception_days if self.review else None
1016 return days or DEFAULT_EXCEPTION_DAYS
1018 @property
1019 def causal_retrospective(self) -> bool:
1020 return bool(self.retrospective and self.retrospective.causal)
1022 @property
1023 def webhooks(self) -> tuple[WebhookConfig, ...]:
1024 return self.notifications.webhooks if self.notifications else ()
1026 @field_validator("profiles")
1027 @classmethod
1028 def at_least_one_profile(cls, value: tuple[str, ...]) -> tuple[str, ...]:
1029 if not value: 1029 ↛ 1030line 1029 didn't jump to line 1030 because the condition on line 1029 was never true
1030 return ("auto",)
1031 return value
1033 @model_validator(mode="after")
1034 def _known_fallback_provider(self) -> ProjectConfiguration:
1035 """``runtime.contractRetry.fallbackProvider`` (#80) names a provider that can answer a
1036 read-only call: ``simulated`` or an entry of ``agentProviders``."""
1037 retry = self.runtime.contract_retry
1038 name = retry.fallback_provider if retry is not None else None
1039 if name is not None and name != "simulated" and name not in self.agent_providers:
1040 raise ValueError(
1041 f"runtime.contractRetry.fallbackProvider {name!r} is not in agentProviders"
1042 )
1043 return self
1045 @property
1046 def criteria_policy(self) -> CriteriaPolicy:
1047 """The effective acceptance-criteria policy: ``warn`` when ``intake`` is absent."""
1048 return self.intake.criteria_policy if self.intake else DEFAULT_CRITERIA_POLICY
1050 @property
1051 def requirement_traceability(self) -> RequirementTraceabilityPolicy:
1052 """The effective requirement-traceability policy: ``off`` when ``verification`` is
1053 absent."""
1054 return (
1055 self.verification.requirement_traceability
1056 if self.verification
1057 else DEFAULT_REQUIREMENT_TRACEABILITY
1058 )
1060 @model_serializer(mode="wrap")
1061 def _omit_absent_intake(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
1062 # A file without the section serializes as before, so the configuration snapshot
1063 # (and its digest) of a project written for 1.0.0 does not change.
1064 data: dict[str, Any] = handler(self)
1065 if self.intake is None:
1066 data.pop("intake", None)
1067 if self.verification is None:
1068 data.pop("verification", None)
1069 for section in (
1070 "governance",
1071 "review",
1072 "notifications",
1073 "retrospective",
1074 "planning",
1075 "context",
1076 "budget",
1077 "memory",
1078 "toolchain",
1079 "provenance",
1080 "delivery",
1081 "environment",
1082 "instructions",
1083 "standards",
1084 "testing",
1085 "architecture",
1086 "friction",
1087 "metrics",
1088 "api",
1089 ):
1090 if getattr(self, section) is None:
1091 data.pop(section, None)
1092 if self.agent_routing is None:
1093 data.pop("agent_routing", None)
1094 data.pop("agentRouting", None)
1095 if self.agent_contract is None:
1096 data.pop("agent_contract", None)
1097 data.pop("agentContract", None)
1098 return data
1101class DetectorMarker(ConfigModel):
1102 marker: str
1103 weight: float = Field(gt=0, le=1)
1106OutputParser = Literal[
1107 "auto",
1108 "sarif",
1109 "junit",
1110 "ruff",
1111 "mypy",
1112 "eslint",
1113 "tsc",
1114 "pytest",
1115 "checkstyle",
1116 "rubocop",
1117 "cargo",
1118 "msbuild",
1119 "none",
1120]
1121IssueLevel = Literal["error", "warning", "note"]
1124class ValidatorDefinition(ConfigModel):
1125 """A validator of a profile or, since 2.0, of the project (``toolchain.validators``).
1127 The keys added in 2.0 (``parser``, ``severity``, ``failureSeverity``, ``passEnv``,
1128 ``parallelSafe``) are
1129 left out of the serialized definition while they are absent, so a resolved configuration
1130 without them keeps its digest."""
1132 validator_id: str = Field(alias="id")
1133 command: tuple[str, ...] | None = None
1134 mandatory: bool = True
1135 when_available: bool = Field(default=False, alias="whenAvailable")
1136 script: str | None = None
1137 timeout_seconds: int | None = Field(default=None, alias="timeoutSeconds", ge=1)
1138 parser: OutputParser | None = None
1139 """Parse a failing run's output into located findings with this parser (``auto``: every
1140 known format, as ``verification.outputParsers``; ``none``: never). Absent: follow
1141 ``verification.outputParsers``."""
1142 severity: dict[IssueLevel, FindingSeverity] | None = None
1143 """Severity of a parsed issue by its level (default: error as the failure finding, warning
1144 LOW, note INFO)."""
1145 failure_severity: FindingSeverity | None = Field(default=None, alias="failureSeverity")
1146 """Severity of the finding of a failing run (default HIGH when mandatory, MEDIUM
1147 otherwise)."""
1148 pass_env: tuple[str, ...] | None = Field(default=None, alias="passEnv")
1149 """Variables of the harness's environment the command receives as they are."""
1150 parallel_safe: bool | None = Field(default=None, alias="parallelSafe")
1151 """The command writes nothing another validator reads or writes, so under
1152 ``governance.enforceWorkflow`` it may run at the same time as the other parallel-safe
1153 validators of a parallelizable VERIFICATION (#3). Absent: it runs alone, as in 1.0.0."""
1155 @field_validator("pass_env")
1156 @classmethod
1157 def _pass_env_names(cls, value: tuple[str, ...] | None) -> tuple[str, ...] | None:
1158 for name in value or ():
1159 if not _ENV_NAME.match(name): 1159 ↛ 1160line 1159 didn't jump to line 1160 because the condition on line 1159 was never true
1160 raise ValueError(f"passEnv entry is not an environment variable name: {name!r}")
1161 return value
1163 @model_serializer(mode="wrap")
1164 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
1165 data: dict[str, Any] = handler(self)
1166 for name, alias in (
1167 ("parser", "parser"),
1168 ("severity", "severity"),
1169 ("failure_severity", "failureSeverity"),
1170 ("pass_env", "passEnv"),
1171 ("parallel_safe", "parallelSafe"),
1172 ):
1173 if getattr(self, name) is None:
1174 data.pop(name, None)
1175 data.pop(alias, None)
1176 return data
1179class TechnologyProfileDefinition(ConfigModel):
1180 profile_version: Literal["1.0"] = Field(alias="profileVersion")
1181 profile_id: str = Field(alias="profileId")
1182 technology: str
1183 detectors: tuple[DetectorMarker, ...]
1184 default_commands: dict[str, tuple[str, ...]] = Field(
1185 default_factory=dict, alias="defaultCommands"
1186 )
1187 default_validators: tuple[str, ...] = Field(default=(), alias="defaultValidators")
1188 validators: tuple[ValidatorDefinition, ...] = ()
1189 policies: dict[str, Any] = Field(default_factory=dict)
1190 capabilities: dict[str, tuple[str, ...]] = Field(default_factory=dict)
1191 verification: ProfileVerification | None = None
1192 """Since #55: the profile's verification capabilities per rung of the ladder. Left out of
1193 the serialized profile when absent."""
1195 @model_serializer(mode="wrap")
1196 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
1197 data: dict[str, Any] = handler(self)
1198 if self.verification is None: 1198 ↛ 1200line 1198 didn't jump to line 1200 because the condition on line 1198 was always true
1199 data.pop("verification", None)
1200 return data
1203class WorkflowPhaseDefinition(ConfigModel):
1204 phase_id: PhaseId = Field(alias="id")
1205 purpose: str
1206 depends_on: tuple[PhaseId, ...] = Field(
1207 default=(),
1208 alias="dependsOn",
1209 description=(
1210 "Earlier phases whose latest attempt must have passed before this phase starts, "
1211 "under governance.enforceWorkflow (the order of the nine phases stays fixed)."
1212 ),
1213 )
1214 required: bool = True
1215 parallelizable: bool = Field(
1216 default=False,
1217 description=(
1218 "Under governance.enforceWorkflow, the phase's independent read-only work may run "
1219 "at once: the validators declared parallelSafe of VERIFICATION. Phases themselves "
1220 "and the sub-tasks of a decomposition run one at a time on the run's workspace."
1221 ),
1222 )
1223 allowed_capabilities: tuple[str, ...] = Field(
1224 default=(),
1225 alias="allowedCapabilities",
1226 description=(
1227 "Capabilities a grant made while the phase runs may carry, under "
1228 "governance.phaseCapabilities (issue #4); without it grants are per run."
1229 ),
1230 )
1231 validators: tuple[str, ...] = Field(
1232 default=(),
1233 description="Declarative: the validators come from the profiles and the project.",
1234 json_schema_extra={"x-declarative": True},
1235 )
1236 exit_gate: str = Field(
1237 alias="exitGate",
1238 description=(
1239 "Name of the condition the phase must meet to pass: evaluated from the run's "
1240 "records under governance.enforceWorkflow (an unmet one leaves the attempt "
1241 "BLOCKED); recorded with each attempt (exitGate, exitGateMet) under "
1242 "governance.applyWorkflowSettings or governance.enforceWorkflow."
1243 ),
1244 )
1245 timeout_seconds: int = Field(
1246 default=1800,
1247 alias="timeoutSeconds",
1248 ge=1,
1249 description=(
1250 "Wall-clock budget of one attempt of the phase under governance.applyWorkflowSettings."
1251 ),
1252 )
1253 max_attempts: int = Field(
1254 default=1,
1255 alias="maxAttempts",
1256 ge=1,
1257 le=20,
1258 description=(
1259 "Failed attempts of the phase after which it is not started again, under "
1260 "governance.applyWorkflowSettings."
1261 ),
1262 )
1265class WorkflowTransitionDefinition(ConfigModel):
1266 source: PhaseId = Field(alias="from")
1267 target: PhaseId = Field(alias="to")
1268 condition: str
1269 invalidates: tuple[PhaseId, ...] = ()
1272class WorkflowDefinition(ConfigModel):
1273 workflow_version: Literal["1.0"] = Field(alias="workflowVersion")
1274 workflow_id: str = Field(alias="workflowId")
1275 description: str = ""
1276 phases: tuple[WorkflowPhaseDefinition, ...]
1277 transitions: tuple[WorkflowTransitionDefinition, ...]
1278 invariants: tuple[str, ...] = Field(
1279 default=(),
1280 description="Declarative: names of invariants the engine enforces in code.",
1281 json_schema_extra={"x-declarative": True},
1282 )
1284 @model_validator(mode="after")
1285 def validate_graph(self) -> WorkflowDefinition:
1286 primary = tuple(phase.phase_id for phase in self.phases)
1287 expected = (
1288 PhaseId.INTENT,
1289 PhaseId.DISCOVERY,
1290 PhaseId.SPECIFICATION,
1291 PhaseId.PLANNING,
1292 PhaseId.IMPLEMENTATION,
1293 PhaseId.VERIFICATION,
1294 PhaseId.INDEPENDENT_REVIEW,
1295 PhaseId.DECISION,
1296 PhaseId.CLOSURE,
1297 )
1298 if primary != expected: 1298 ↛ 1299line 1298 didn't jump to line 1299 because the condition on line 1298 was never true
1299 raise ValueError(f"normative phases must remain ordered and complete: {expected}")
1300 return self
1303class ResolvedConfiguration(ConfigModel):
1304 project: ProjectConfiguration
1305 workspace_root: Path
1306 profiles: tuple[TechnologyProfileDefinition, ...]
1307 workflow: WorkflowDefinition
1308 effective_capabilities: tuple[CapabilityRule, ...]
1309 effective_validators: tuple[ValidatorDefinition, ...]
1310 effective_policies: dict[str, Any]
1311 source_files: tuple[str, ...]
1314# ----- 2.0 sections of wave 4 (integration and scale) ----------------------------------------
1315ProfileDetection = Literal["best", "all"]
1316InterpreterMode = Literal["system", "auto"]
1319def _omit_none(model: BaseModel, data: dict[str, Any]) -> dict[str, Any]:
1320 for name, field in type(model).model_fields.items():
1321 if getattr(model, name) is None:
1322 data.pop(name, None)
1323 data.pop(field.alias or name, None)
1324 return data
1327class ToolchainConfig(ConfigModel):
1328 """Project-defined profiles, validators and interpreter (since 2.0).
1330 * ``profilePaths``: YAML files (or directories of ``*.yaml`` files) with technology
1331 profiles in the format of the built-in ones, relative to the workspace root. ``profiles``
1332 may name them by ``profileId`` and ``auto`` detects them by their ``detectors``.
1333 * ``profileDetection: all`` selects every detected profile under ``profiles: [auto]``
1334 (several profiles per repository); ``best`` (or absent) selects the best one.
1335 * ``interpreter: auto`` runs the validators whose command starts with ``python`` with the
1336 project's interpreter: ``.venv`` or ``venv`` in the workspace, else ``uv run --no-sync
1337 python`` with ``uv.lock``, else ``poetry run python`` with ``poetry.lock``; ``system``
1338 (or absent) keeps ``python`` from ``PATH``.
1339 * ``validators``: validators of the project. An entry with the id of a selected validator
1340 replaces its definition (for example ``python.pytest`` with ``uv run pytest``); any other
1341 entry is added. Each needs a ``command`` and may set ``parser``, ``severity``,
1342 ``failureSeverity`` and ``passEnv``.
1344 Absent keys keep the 1.0.0 behaviour and are left out of the serialized configuration."""
1346 profile_paths: tuple[str, ...] | None = Field(default=None, alias="profilePaths")
1347 profile_detection: ProfileDetection | None = Field(default=None, alias="profileDetection")
1348 interpreter: InterpreterMode | None = None
1349 validators: tuple[ValidatorDefinition, ...] | None = None
1350 extended_profiles: bool | None = Field(default=None, alias="extendedProfiles")
1351 """Since #55: also detect the built-in profiles of Go, Rust, Java/Kotlin (Gradle and
1352 Maven), Swift and Android."""
1354 @field_validator("profile_paths")
1355 @classmethod
1356 def _relative_paths(cls, value: tuple[str, ...] | None) -> tuple[str, ...] | None:
1357 for item in value or ():
1358 if not item.strip() or Path(item).is_absolute() or ".." in Path(item).parts: 1358 ↛ 1359line 1358 didn't jump to line 1359 because the condition on line 1358 was never true
1359 raise ValueError(f"profile path must be relative to the workspace: {item!r}")
1360 return value
1362 @field_validator("validators")
1363 @classmethod
1364 def _validators_have_commands(
1365 cls, value: tuple[ValidatorDefinition, ...] | None
1366 ) -> tuple[ValidatorDefinition, ...] | None:
1367 seen: set[str] = set()
1368 for item in value or ():
1369 if not item.command: 1369 ↛ 1370line 1369 didn't jump to line 1370 because the condition on line 1369 was never true
1370 raise ValueError(f"project validator {item.validator_id!r} needs a command")
1371 if item.validator_id in seen: 1371 ↛ 1372line 1371 didn't jump to line 1372 because the condition on line 1371 was never true
1372 raise ValueError(f"project validator {item.validator_id!r} is declared twice")
1373 seen.add(item.validator_id)
1374 return value
1376 @model_serializer(mode="wrap")
1377 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
1378 return _omit_none(self, handler(self))
1381class ProvenanceConfig(ConfigModel):
1382 """Provenance per component (since 2.0).
1384 * ``agentSnapshots``: after each agent invocation the harness records a manifest of the
1385 digests of the files in the ChangeSet scope. A later difference that no invocation
1386 produced is attributed, per file, as an out-of-band edit, and the provenance of every
1387 ChangeSet file (the invocation that last wrote it, or ``OUT_OF_BAND``) is recorded as
1388 evidence.
1389 * ``selfReport``: the request asks the agent for a structured self-report (assumptions,
1390 alternatives discarded, low-confidence areas, unrequested changes); the answer is stored
1391 as data of quality ``REPORTED`` and contrasted with the ChangeSet, never as a check.
1393 Absent keys keep the 1.0.0 behaviour and are left out of the serialized configuration."""
1395 agent_snapshots: bool | None = Field(default=None, alias="agentSnapshots")
1396 self_report: bool | None = Field(default=None, alias="selfReport")
1398 @model_serializer(mode="wrap")
1399 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
1400 return _omit_none(self, handler(self))
1403ClosureCommitMode = Literal["off", "branch", "head"]
1404PublisherTransport = Literal["gh", "api"]
1406DEFAULT_CLOSURE_BRANCH = "harness/{runId}"
1407"""Branch a ``closureCommit: branch`` commit is written to."""
1409_BRANCH_FORBIDDEN = re.compile(r"(\.\.|[\s~^:?*\[\\]|@\{|//|^/|/$|\.lock$|^-)")
1412class PublisherConfig(ConfigModel):
1413 """Where ``harness pr publish`` posts the decision brief and the SARIF report."""
1415 kind: Literal["github"] = "github"
1416 transport: PublisherTransport = "gh"
1417 repository: str | None = None
1418 token_env: str = Field(default="GITHUB_TOKEN", alias="tokenEnv")
1419 api_url: str = Field(default="https://api.github.com", alias="apiUrl")
1420 sarif: bool = True
1422 @field_validator("repository")
1423 @classmethod
1424 def _owner_name(cls, value: str | None) -> str | None:
1425 if value is not None and not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", value): 1425 ↛ 1426line 1425 didn't jump to line 1426 because the condition on line 1425 was never true
1426 raise ValueError(f"repository must be owner/name: {value!r}")
1427 return value
1429 @field_validator("token_env")
1430 @classmethod
1431 def _token_env_name(cls, value: str) -> str:
1432 if not _ENV_NAME.match(value): 1432 ↛ 1433line 1432 didn't jump to line 1433 because the condition on line 1432 was never true
1433 raise ValueError(f"tokenEnv is not an environment variable name: {value!r}")
1434 return value
1436 @field_validator("api_url")
1437 @classmethod
1438 def _https(cls, value: str) -> str:
1439 if not value.startswith(("https://", "http://127.0.0.1", "http://localhost")): 1439 ↛ 1440line 1439 didn't jump to line 1440 because the condition on line 1439 was never true
1440 raise ValueError("apiUrl must use https (or point to localhost)")
1441 return value.rstrip("/")
1444class DeliveryConfig(ConfigModel):
1445 """What CLOSURE delivers to version control (since 2.0).
1447 * ``closureCommit: branch`` writes the approved ChangeSet as one commit on a new branch
1448 (``branch``, default ``harness/{runId}``) whose parent is ``HEAD``, without touching the
1449 working tree, the index or the current branch; ``head`` commits it on the current branch
1450 (only the ChangeSet paths). The commit carries the trailers ``Harness-Run``,
1451 ``Harness-ChangeSet`` and ``Harness-Decision`` (and ``Harness-Exception`` for an
1452 ``APPROVE_EXCEPTION``), and is created only if its diff recomputes to the approved
1453 ChangeSet digest. ``off`` (or absent): the harness never commits, as in 1.0.0.
1454 * ``publisher``: defaults of ``harness pr publish``."""
1456 closure_commit: ClosureCommitMode | None = Field(default=None, alias="closureCommit")
1457 branch: str | None = None
1458 publisher: PublisherConfig | None = None
1459 # ----- since #55: complete delivery -----------------------------------------------------
1460 stage: bool | None = None
1461 """When the operational contract does not authorise a push, stage the run's files (only
1462 them, never ``add -A``) so the change waits in the index for the person."""
1463 push: bool | None = None
1464 """Push the closure commit's branch, honouring the repository's hooks (never
1465 ``--no-verify``); the task's contract may say otherwise."""
1466 pull_request: PullRequestConfig | None = Field(default=None, alias="pullRequest")
1467 record_commit_author: bool | None = Field(default=None, alias="recordCommitAuthor")
1468 """``delivery.commit.created`` also records the commit's ``author`` (name and email as Git
1469 shows them) and ``subject``, after the redaction of secrets, so that a bundle answers who
1470 wrote the commit and with what message. Absent or false: the event is as before."""
1471 comment: CommentPolicy | None = None
1472 """Comment the decision brief on the pull request: ``notClean`` (exceptions, findings,
1473 partial certification), ``always`` or ``never``."""
1474 forge: ForgeConfig | None = None
1475 """Since 2.0 (#56): the forge of ``harness pr publish`` and ``harness pr create`` (GitHub,
1476 GitLab, Bitbucket, Azure DevOps, Gitea), detected from ``origin`` unless set."""
1478 @field_validator("branch")
1479 @classmethod
1480 def _branch_template(cls, value: str | None) -> str | None:
1481 if value is None: 1481 ↛ 1482line 1481 didn't jump to line 1482 because the condition on line 1481 was never true
1482 return value
1483 sample = value.replace("{runId}", "run_x").replace("{taskId}", "task_x")
1484 if not sample.strip() or _BRANCH_FORBIDDEN.search(sample) or "{" in sample: 1484 ↛ 1485line 1484 didn't jump to line 1485 because the condition on line 1484 was never true
1485 raise ValueError(
1486 f"branch must be a valid branch name; only {{runId}} and {{taskId}} are "
1487 f"replaced: {value!r}"
1488 )
1489 return value
1491 @property
1492 def mode(self) -> ClosureCommitMode:
1493 return self.closure_commit or "off"
1495 @property
1496 def branch_template(self) -> str:
1497 return self.branch or DEFAULT_CLOSURE_BRANCH
1499 @model_serializer(mode="wrap")
1500 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]:
1501 return _omit_none(self, handler(self))
1504ProjectConfiguration.model_rebuild()