Coverage for src/governed_harness/domain/models.py: 94%

965 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-12 16:06 +0000

1from __future__ import annotations 

2 

3import itertools 

4import re 

5from datetime import UTC, datetime 

6from pathlib import PurePosixPath 

7from typing import Any, Literal 

8 

9from pydantic import ( 

10 BaseModel, 

11 ConfigDict, 

12 Field, 

13 SerializerFunctionWrapHandler, 

14 ValidationInfo, 

15 field_validator, 

16 model_serializer, 

17 model_validator, 

18) 

19 

20from .enums import ( 

21 ActorType, 

22 DecisionKind, 

23 ErrorKind, 

24 EvidenceKind, 

25 FindingSeverity, 

26 MemoryLevel, 

27 MetricQuality, 

28 PhaseId, 

29 ResultStatus, 

30 ValidationKind, 

31 VerificationLevel, 

32) 

33 

34 

35def utc_now() -> datetime: 

36 return datetime.now(UTC) 

37 

38 

39def _to_camel(value: str) -> str: 

40 first, *rest = value.split("_") 

41 return first + "".join(part[:1].upper() + part[1:] for part in rest) 

42 

43 

44class StrictModel(BaseModel): 

45 model_config = ConfigDict( 

46 extra="forbid", 

47 frozen=True, 

48 populate_by_name=True, 

49 alias_generator=_to_camel, 

50 ) 

51 

52 

53class Actor(StrictModel): 

54 actor_type: ActorType 

55 actor_id: str = Field(pattern=r"^[a-z][a-z0-9_.-]{1,127}$") 

56 display_name: str | None = None 

57 version: str | None = None 

58 

59 

60HARNESS_ACTOR = Actor(actor_type=ActorType.HARNESS, actor_id="harness.core") 

61 

62 

63class Provenance(StrictModel): 

64 actor: Actor 

65 core_version: str 

66 configuration_digest: str | None = None 

67 workflow_digest: str | None = None 

68 policy_digest: str | None = None 

69 provider: str | None = None 

70 model: str | None = None 

71 prompt_digest: str | None = None 

72 plugin_id: str | None = None 

73 plugin_version: str | None = None 

74 source_refs: tuple[str, ...] = () 

75 

76 

77class HarnessErrorRecord(StrictModel): 

78 error_id: str 

79 kind: ErrorKind 

80 message: str 

81 actor: Actor 

82 occurred_at: datetime = Field(default_factory=utc_now) 

83 details: dict[str, Any] = Field(default_factory=dict) 

84 

85 

86class Requirement(StrictModel): 

87 requirement_id: str 

88 text: str = Field(min_length=1, max_length=8000) 

89 source: str = "human" 

90 

91 

92def _omit_unset(model: BaseModel, data: dict[str, Any]) -> dict[str, Any]: 

93 """Drop the fields of ``model`` that are ``None`` or an empty tuple or mapping, under both 

94 their name and their alias, so a record without them keeps its stored form and digest.""" 

95 for name, field in type(model).model_fields.items(): 

96 value = getattr(model, name) 

97 if value is None or (isinstance(value, (tuple, dict)) and not value): 

98 data.pop(name, None) 

99 if field.alias: 99 ↛ 101line 99 didn't jump to line 101 because the condition on line 99 was always true

100 data.pop(field.alias, None) 

101 data.pop(_to_camel(name), None) 

102 return data 

103 

104 

105# ----- since 2.0 (#55): the verification ladder of a criterion, probes, the checklist --------- 

106_PROBE_ID = r"^[a-z0-9][a-z0-9_.-]{0,63}$" 

107_ITEM_ID = r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$" 

108_ENV_NAME = r"(?a)^[A-Za-z_]\w{0,127}$" 

109PROBE_PLACEHOLDER = re.compile(r"\{([A-Za-z_]\w*)\}", re.ASCII) 

110"""A ``{name}`` in a probe's command or working directory, filled from the variant.""" 

111 

112 

113class CriterionVerification(StrictModel): 

114 """How an acceptance criterion must be verified: the rung of the ladder it requires and, 

115 for the rungs that need one, how that rung is reached. 

116 

117 * ``probe``: the id of a probe (task or project) whose assertions show the behaviour (L3, 

118 or L2/L4 when the probe declares that level); 

119 * ``tests``: names (or parts of names) of the tests that verify the criterion (L1/L2); 

120 * ``deferred``: where the criterion is verified after the run (a CI job, staging, a device 

121 lab); it stays pending, bound to the ChangeSet digest, until evidence is attached; 

122 * ``manual``: what a person checks; ticked in DECISION (L5).""" 

123 

124 level: VerificationLevel 

125 probe: str | None = Field(default=None, pattern=_PROBE_ID) 

126 tests: tuple[str, ...] = () 

127 deferred: str | None = Field(default=None, min_length=1, max_length=1000) 

128 manual: str | None = Field(default=None, min_length=1, max_length=2000) 

129 

130 @model_validator(mode="after") 

131 def _rung_has_a_path(self) -> CriterionVerification: 

132 if self.level is VerificationLevel.L5 and self.manual is None: 132 ↛ 133line 132 didn't jump to line 133 because the condition on line 132 was never true

133 raise ValueError("a criterion that requires L5 needs 'manual': what a person checks") 

134 if any(not item.strip() for item in self.tests): 134 ↛ 135line 134 didn't jump to line 135 because the condition on line 134 was never true

135 raise ValueError("verification tests must not be blank") 

136 return self 

137 

138 @model_serializer(mode="wrap") 

139 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

140 return _omit_unset(self, handler(self)) 

141 

142 

143class ProbeAssertion(StrictModel): 

144 """A generic assertion on the output of a probe. 

145 

146 * ``exitCode``: the exit code ``equals`` a number; 

147 * ``jsonPath``: the value at ``path`` is ``present`` (true) or absent (``present: false``), 

148 ``equals`` a value or ``matches`` a regular expression; 

149 * ``differs``: the value at ``path`` (JSON) or the whole output (text) is not the same in 

150 every variant (``variants`` narrows the comparison); 

151 * ``order``: the values at ``path`` are ``ascending`` or ``descending``, or ``before`` 

152 appears before ``after`` (in the list at ``path``, or in the text); 

153 * ``text``: the output ``matches`` a regular expression or ``contains`` a text. 

154 

155 ``variants`` names the variants an assertion of any kind checks (every variant when it is 

156 empty); an assertion that names no variant of the probe fails.""" 

157 

158 kind: Literal["exitCode", "jsonPath", "differs", "order", "text"] 

159 path: str | None = None 

160 equals: Any = None 

161 present: bool | None = None 

162 matches: str | None = None 

163 contains: str | None = None 

164 order: Literal["ascending", "descending"] | None = None 

165 before: str | None = None 

166 after: str | None = None 

167 variants: tuple[str, ...] = () 

168 

169 @model_validator(mode="after") 

170 def _complete(self) -> ProbeAssertion: 

171 self._check_syntax() 

172 problem = self._kind_problem() 

173 if problem is not None: 

174 raise ValueError(problem) 

175 return self 

176 

177 def _check_syntax(self) -> None: 

178 """The regular expression compiles and the path is in the supported JSONPath subset.""" 

179 if self.matches is not None: 

180 try: 

181 re.compile(self.matches) 

182 except re.error as error: 

183 raise ValueError(f"invalid regular expression {self.matches!r}: {error}") from error 

184 if self.path is not None: 

185 from governed_harness.ladder.jsonpath import parse_path 

186 

187 parse_path(self.path) 

188 

189 def _kind_problem(self) -> str | None: 

190 """What the assertion's kind needs and it lacks, if anything.""" 

191 kind = self.kind 

192 if kind == "exitCode" and not isinstance(self.equals, int): 192 ↛ 193line 192 didn't jump to line 193 because the condition on line 192 was never true

193 return "an exitCode assertion needs 'equals' with an integer" 

194 if kind == "jsonPath": 

195 return self._json_path_problem() 

196 if kind == "order" and not ( 196 ↛ 200line 196 didn't jump to line 200 because the condition on line 196 was never true

197 (self.path is not None and self.order is not None) 

198 or (self.before is not None and self.after is not None) 

199 ): 

200 return "an order assertion needs path and order, or before and after" 

201 if kind == "text" and (self.matches is None) == (self.contains is None): 201 ↛ 202line 201 didn't jump to line 202 because the condition on line 201 was never true

202 return "a text assertion needs exactly one of matches, contains" 

203 return None 

204 

205 def _json_path_problem(self) -> str | None: 

206 if self.path is None: 206 ↛ 207line 206 didn't jump to line 207 because the condition on line 206 was never true

207 return "a jsonPath assertion needs 'path'" 

208 given = [self.present is not None, self.equals is not None, self.matches is not None] 

209 if sum(given) != 1: 

210 return "a jsonPath assertion needs exactly one of present, equals, matches" 

211 return None 

212 

213 @model_serializer(mode="wrap") 

214 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

215 return _omit_unset(self, handler(self)) 

216 

217 

218class ProbeVariant(StrictModel): 

219 """One combination of the variant matrix: the values of the command's placeholders and 

220 environment variables set for this run of the probe.""" 

221 

222 name: str = Field(min_length=1, max_length=200) 

223 values: dict[str, str] = Field(default_factory=dict) 

224 env: dict[str, str] = Field(default_factory=dict) 

225 

226 @field_validator("env") 

227 @classmethod 

228 def _env_names(cls, value: dict[str, str]) -> dict[str, str]: 

229 for name in value: 

230 if not re.match(_ENV_NAME, name): 230 ↛ 231line 230 didn't jump to line 231 because the condition on line 230 was never true

231 raise ValueError(f"env key is not an environment variable name: {name!r}") 

232 return value 

233 

234 

235class ProbeDefinition(StrictModel): 

236 """A command whose observable output shows a behaviour (a CLI, a script, a local server, 

237 a simulator test), with assertions on that output, run once per variant of its matrix: 

238 on the baseline (preflight) and after the change (VERIFICATION). The command runs without 

239 a shell; ``{name}`` placeholders are filled from the variant. A probe that cannot run is 

240 ``BLOCKED``, never ``PASSED``.""" 

241 

242 probe_id: str = Field(alias="id", pattern=_PROBE_ID) 

243 command: tuple[str, ...] = Field(min_length=1) 

244 cwd: str = "." 

245 pass_env: tuple[str, ...] = () 

246 timeout_seconds: int = Field(default=60, ge=1, le=3600) 

247 output: Literal["json", "text"] = "text" 

248 level: VerificationLevel = VerificationLevel.L3 

249 criteria: tuple[str, ...] = () 

250 matrix: dict[str, tuple[str, ...]] = Field(default_factory=dict) 

251 variants: tuple[ProbeVariant, ...] = () 

252 assertions: tuple[ProbeAssertion, ...] = Field(min_length=1) 

253 

254 @field_validator("cwd") 

255 @classmethod 

256 def _relative_cwd(cls, value: str) -> str: 

257 path = PurePosixPath(value.replace("\\", "/")) 

258 if path.is_absolute() or ".." in path.parts: 

259 raise ValueError(f"a probe cwd must be relative to the workspace: {value!r}") 

260 return value 

261 

262 @field_validator("pass_env") 

263 @classmethod 

264 def _pass_env_names(cls, value: tuple[str, ...]) -> tuple[str, ...]: 

265 for name in value: 

266 if not re.match(_ENV_NAME, name): 

267 raise ValueError(f"passEnv entry is not an environment variable name: {name!r}") 

268 return value 

269 

270 @model_validator(mode="after") 

271 def _variants_fill_placeholders(self) -> ProbeDefinition: 

272 if self.level not in {VerificationLevel.L2, VerificationLevel.L3, VerificationLevel.L4}: 272 ↛ 273line 272 didn't jump to line 273 because the condition on line 272 was never true

273 raise ValueError("a probe verifies L2, L3 or L4") 

274 if self.matrix and self.variants: 274 ↛ 275line 274 didn't jump to line 275 because the condition on line 274 was never true

275 raise ValueError("declare either a matrix or variants, not both") 

276 if any(not values for values in self.matrix.values()): 276 ↛ 277line 276 didn't jump to line 277 because the condition on line 276 was never true

277 raise ValueError("every matrix entry needs at least one value") 

278 needed = { 

279 name for item in (*self.command, self.cwd) for name in PROBE_PLACEHOLDER.findall(item) 

280 } 

281 for variant in self.expanded_variants(): 

282 missing = sorted(needed - set(variant.values)) 

283 if missing: 

284 raise ValueError( 

285 f"variant {variant.name!r} does not set placeholder(s) {', '.join(missing)}" 

286 ) 

287 names = [item.name for item in self.expanded_variants()] 

288 if len(set(names)) != len(names): 288 ↛ 289line 288 didn't jump to line 289 because the condition on line 288 was never true

289 raise ValueError("variant names must be unique") 

290 if any(item.kind == "differs" for item in self.assertions) and len(names) < 2: 

291 raise ValueError("a differs assertion needs at least two variants") 

292 return self 

293 

294 def expanded_variants(self) -> tuple[ProbeVariant, ...]: 

295 """The variants in a fixed order: the declared ones, else the cartesian product of the 

296 matrix (keys sorted, values in their order), else one variant named ``default``.""" 

297 if self.variants: 

298 return self.variants 

299 if not self.matrix: 

300 return (ProbeVariant(name="default"),) 

301 keys = sorted(self.matrix) 

302 return tuple( 

303 ProbeVariant( 

304 name=",".join( 

305 f"{key}={value}" for key, value in zip(keys, combination, strict=True) 

306 ), 

307 values=dict(zip(keys, combination, strict=True)), 

308 ) 

309 for combination in itertools.product(*(self.matrix[key] for key in keys)) 

310 ) 

311 

312 @model_serializer(mode="wrap") 

313 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

314 return _omit_unset(self, handler(self)) 

315 

316 

317class ChecklistItem(StrictModel): 

318 """Something only a person can verify (a layout, a sound, a device behaviour), ticked in 

319 DECISION with ``harness gate decide --check ID``.""" 

320 

321 item_id: str = Field(alias="id", pattern=_ITEM_ID) 

322 text: str = Field(min_length=1, max_length=2000) 

323 

324 

325class OperationalContract(StrictModel): 

326 """The operational contract of a task (#55): what the person and the harness agreed on 

327 before work starts. Every field is optional in the task file; the harness fills the rest 

328 from the project configuration and records the resulting summary, bound to the task 

329 digest, at INTENT.""" 

330 

331 objective: str | None = Field(default=None, max_length=4000) 

332 examples: tuple[str, ...] = () 

333 scope: tuple[str, ...] = () 

334 scope_paths: tuple[str, ...] = () 

335 out_of_scope: tuple[str, ...] = () 

336 definition_of_done: tuple[str, ...] = () 

337 verification_level: VerificationLevel | None = None 

338 branch: str | None = Field(default=None, max_length=200) 

339 create_pull_request: bool | None = None 

340 push: bool | None = None 

341 comment: bool | None = None 

342 coverage_threshold: float | None = Field(default=None, ge=0, le=100) 

343 

344 @field_validator("branch") 

345 @classmethod 

346 def _branch_name(cls, value: str | None) -> str | None: 

347 if value is not None and ( 347 ↛ 350line 347 didn't jump to line 350 because the condition on line 347 was never true

348 not value.strip() or re.search(r"(\.\.|[\s~^:?*\[\\{}]|@\{|//|^/|/$|\.lock$|^-)", value) 

349 ): 

350 raise ValueError(f"branch must be a valid Git branch name: {value!r}") 

351 return value 

352 

353 @model_serializer(mode="wrap") 

354 def _omit_absent(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

355 return _omit_unset(self, handler(self)) 

356 

357 

358class AcceptanceCriterion(StrictModel): 

359 criterion_id: str 

360 text: str = Field(min_length=1, max_length=8000) 

361 verification_hint: str | None = Field(default=None, max_length=4000) 

362 priority: Literal["MUST", "SHOULD", "COULD"] = "MUST" 

363 verification: CriterionVerification | None = None 

364 """Since 2.0 (#55): the rung of the verification ladder the criterion requires. Left out 

365 of the serialized criterion when absent, so tasks written before it keep their digest.""" 

366 

367 @model_serializer(mode="wrap") 

368 def _omit_absent_verification(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

369 data: dict[str, Any] = handler(self) 

370 if self.verification is None: 

371 data.pop("verification", None) 

372 return data 

373 

374 

375class FilePatch(StrictModel): 

376 path: str 

377 operation: Literal["create", "replace", "append", "delete"] 

378 content: str | None = None 

379 expected_sha256: str | None = None 

380 

381 @field_validator("path") 

382 @classmethod 

383 def path_is_relative(cls, value: str) -> str: 

384 path = PurePosixPath(value) 

385 if path.is_absolute() or ".." in path.parts or value in {"", "."}: 

386 raise ValueError("patch path must be a safe workspace-relative path") 

387 return value 

388 

389 @model_validator(mode="after") 

390 def content_matches_operation(self) -> FilePatch: 

391 if self.operation in {"create", "replace", "append"} and self.content is None: 

392 raise ValueError("content is required for create/replace/append") 

393 return self 

394 

395 

396class ImplementationInstruction(StrictModel): 

397 mode: Literal["none", "patch", "command"] = "none" 

398 patches: tuple[FilePatch, ...] = () 

399 argv: tuple[str, ...] = () 

400 cwd: str = "." 

401 

402 @model_validator(mode="after") 

403 def validate_mode(self) -> ImplementationInstruction: 

404 if self.mode == "patch" and not self.patches: 404 ↛ 405line 404 didn't jump to line 405 because the condition on line 404 was never true

405 raise ValueError("patch mode requires at least one patch") 

406 if self.mode == "command" and not self.argv: 406 ↛ 407line 406 didn't jump to line 407 because the condition on line 406 was never true

407 raise ValueError("command mode requires argv") 

408 return self 

409 

410 

411class Task(StrictModel): 

412 """A versioned unit of work. 

413 

414 A task needs at least one acceptance criterion. The only exception is a task marked 

415 ``criteria_pending``: the task loader sets the marker when the project policy 

416 ``intake.criteriaPolicy`` is ``enforce`` and the task file has no criteria, so that INTENT 

417 asks for them (rule ``C0``) instead of the task being refused. The marker is valid only 

418 while the task has no criteria, and it is left out of the serialized task when it is 

419 false, so tasks with criteria keep their stored form and their digest.""" 

420 

421 schema_version: Literal["1.0"] = "1.0" 

422 task_id: str 

423 project_id: str 

424 title: str = Field(min_length=1, max_length=300) 

425 intent: str = Field(min_length=1, max_length=16000) 

426 constraints: tuple[str, ...] = () 

427 requirements: tuple[Requirement, ...] = () 

428 criteria_pending: bool = False 

429 acceptance_criteria: tuple[AcceptanceCriterion, ...] 

430 implementation: ImplementationInstruction = Field(default_factory=ImplementationInstruction) 

431 metadata: dict[str, Any] = Field(default_factory=dict) 

432 created_at: datetime = Field(default_factory=utc_now) 

433 probes: tuple[ProbeDefinition, ...] = () 

434 """Since 2.0 (#55): behaviour probes of this task (added to the project's).""" 

435 checklist: tuple[ChecklistItem, ...] = () 

436 """Since 2.0 (#55): items only a person can verify, ticked in DECISION.""" 

437 contract: OperationalContract | None = None 

438 """Since 2.0 (#55): the operational contract the task declares; the rest comes from the 

439 project configuration.""" 

440 

441 @field_validator("probes") 

442 @classmethod 

443 def _unique_probes(cls, value: tuple[ProbeDefinition, ...]) -> tuple[ProbeDefinition, ...]: 

444 ids = [item.probe_id for item in value] 

445 if len(set(ids)) != len(ids): 

446 raise ValueError("probe ids must be unique within a task") 

447 return value 

448 

449 @field_validator("checklist") 

450 @classmethod 

451 def _unique_items(cls, value: tuple[ChecklistItem, ...]) -> tuple[ChecklistItem, ...]: 

452 ids = [item.item_id for item in value] 

453 if len(set(ids)) != len(ids): 453 ↛ 454line 453 didn't jump to line 454 because the condition on line 453 was never true

454 raise ValueError("checklist item ids must be unique within a task") 

455 return value 

456 

457 @field_validator("acceptance_criteria") 

458 @classmethod 

459 def require_acceptance( 

460 cls, value: tuple[AcceptanceCriterion, ...], info: ValidationInfo 

461 ) -> tuple[AcceptanceCriterion, ...]: 

462 # criteria_pending is declared (and so validated) before acceptance_criteria. 

463 pending = info.data.get("criteria_pending", False) is True 

464 if not value and not pending: 

465 raise ValueError("at least one acceptance criterion is required") 

466 if value and pending: 

467 raise ValueError( 

468 "criteriaPending is only allowed on a task without acceptance criteria" 

469 ) 

470 return value 

471 

472 @model_serializer(mode="wrap") 

473 def _omit_false_criteria_pending( 

474 self, handler: SerializerFunctionWrapHandler 

475 ) -> dict[str, Any]: 

476 data: dict[str, Any] = handler(self) 

477 if not self.criteria_pending: 

478 data.pop("criteriaPending", None) 

479 data.pop("criteria_pending", None) 

480 # Since 2.0 (#55): absent probes, checklist and contract keep the stored form and the 

481 # digest of tasks written before them. 

482 for name in ("probes", "checklist", "contract"): 

483 if not getattr(self, name): 

484 data.pop(name, None) 

485 return data 

486 

487 

488ClarificationRule = Literal["C0", "C1", "C2", "C3", "T1", "A1", "A2", "A3", "P1"] 

489"""``C0``-``C3`` and ``T1`` are the deterministic intent rules; since 2.0 ``A1`` is a question an 

490agent asked in its ambiguity and completeness review (``intake.ambiguityReview``, #37), ``A2`` 

491a question about an answer that refers to something the task and the workspace do not contain 

492(``intake.validateAnswers``), ``A3`` a question of the localisation call about where to 

493intervene (``context.locate``, #55) and ``P1`` a project setup question (architecture, testing 

494strategy, standards) of ``intake.projectSetup`` (#56), with a ``project:<part>`` target.""" 

495 

496 

497class ClarificationQuestion(StrictModel): 

498 """A question raised in INTENT by the deterministic intent assessment or, since 2.0, by the 

499 agent review of the task or the check of earlier answers. 

500 

501 ``target`` is the criterion id the question is about, ``task`` for the task as a whole, 

502 or ``task:<part>`` for a ``C0`` question about a task without acceptance criteria (for 

503 example ``task:results``). ``question_id`` is stable for a given task revision (``Q-1``, 

504 ``Q-2``, ...). ``category`` groups the questions of an agent review (ambiguity, 

505 completeness categories, consistency) and is left out when absent.""" 

506 

507 question_id: str = Field(pattern=r"^Q-[1-9][0-9]*$") 

508 rule_id: ClarificationRule 

509 target: str = Field(min_length=1) 

510 text: str = Field(min_length=1) 

511 category: str | None = None 

512 

513 @model_serializer(mode="wrap") 

514 def _omit_absent_category(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

515 data: dict[str, Any] = handler(self) 

516 if self.category is None: 

517 data.pop("category", None) 

518 return data 

519 

520 

521class ClarificationRequest(StrictModel): 

522 """The questions INTENT asked about one revision of a task, identified by its digest. 

523 

524 Since 2.0 (#55) the same request may carry the operational contract (``contract``): the 

525 summary of what was agreed and the items nobody settled, so that a person answers 

526 everything in one message. A request has at least one question or a contract.""" 

527 

528 schema_version: Literal["1.0"] = "1.0" 

529 request_id: str 

530 execution_id: str 

531 task_id: str 

532 task_digest: str 

533 policy: Literal["enforce", "warn"] 

534 questions: tuple[ClarificationQuestion, ...] = () 

535 created_at: datetime = Field(default_factory=utc_now) 

536 contract: dict[str, Any] | None = None 

537 

538 @model_validator(mode="after") 

539 def _asks_something(self) -> ClarificationRequest: 

540 if not self.questions and self.contract is None: 540 ↛ 541line 540 didn't jump to line 541 because the condition on line 540 was never true

541 raise ValueError("a clarification request needs a question or a contract") 

542 return self 

543 

544 @model_serializer(mode="wrap") 

545 def _omit_absent_contract(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

546 data: dict[str, Any] = handler(self) 

547 if self.contract is None: 

548 data.pop("contract", None) 

549 return data 

550 

551 

552class ClarificationAnswer(StrictModel): 

553 question_id: str 

554 rule_id: ClarificationRule 

555 target: str 

556 question: str 

557 answer: str = Field(min_length=1, max_length=4000) 

558 

559 

560class ClarificationRecord(StrictModel): 

561 """A person's answers to a clarification request and the task revision they produced.""" 

562 

563 schema_version: Literal["1.0"] = "1.0" 

564 clarification_id: str 

565 execution_id: str 

566 task_id: str 

567 request_id: str 

568 actor: Actor 

569 answers: tuple[ClarificationAnswer, ...] = () 

570 replaced_criteria: tuple[str, ...] = () 

571 added_criteria: tuple[str, ...] = () 

572 added_requirements: tuple[str, ...] = () 

573 previous_task_digest: str 

574 task_digest: str 

575 previous_task_ref: str 

576 task_ref: str 

577 recorded_at: datetime = Field(default_factory=utc_now) 

578 contract_answers: dict[str, Any] = Field(default_factory=dict) 

579 """Answers to the operational-contract section (since #55); left out when empty.""" 

580 

581 @model_validator(mode="after") 

582 def _answers_something(self) -> ClarificationRecord: 

583 if not self.answers and not self.contract_answers: 583 ↛ 584line 583 didn't jump to line 584 because the condition on line 583 was never true

584 raise ValueError("a clarification record needs an answer") 

585 return self 

586 

587 @model_serializer(mode="wrap") 

588 def _omit_absent_contract(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

589 data: dict[str, Any] = handler(self) 

590 if not self.contract_answers: 

591 data.pop("contractAnswers", None) 

592 data.pop("contract_answers", None) 

593 return data 

594 

595 

596class PlanStep(StrictModel): 

597 step_id: str 

598 description: str 

599 capabilities: tuple[str, ...] = () 

600 expected_evidence: tuple[str, ...] = () 

601 

602 

603class Plan(StrictModel): 

604 plan_id: str 

605 execution_id: str 

606 task_id: str 

607 steps: tuple[PlanStep, ...] 

608 risks: tuple[str, ...] = () 

609 validator_ids: tuple[str, ...] = () 

610 created_at: datetime = Field(default_factory=utc_now) 

611 provenance: Provenance 

612 

613 

614class CapabilityGrant(StrictModel): 

615 grant_id: str 

616 execution_id: str 

617 actor: Actor 

618 capability: str 

619 scope: tuple[str, ...] 

620 issued_at: datetime = Field(default_factory=utc_now) 

621 expires_at: datetime 

622 conditions: dict[str, Any] = Field(default_factory=dict) 

623 revoked_at: datetime | None = None 

624 approval_required: bool = False 

625 

626 def active_at(self, now: datetime) -> bool: 

627 return self.revoked_at is None and self.issued_at <= now < self.expires_at 

628 

629 

630class ConfigurationSnapshot(StrictModel): 

631 snapshot_id: str 

632 execution_id: str 

633 content_digest: str 

634 artifact_ref: str 

635 created_at: datetime = Field(default_factory=utc_now) 

636 

637 

638class PhaseExecution(StrictModel): 

639 phase_execution_id: str 

640 execution_id: str 

641 phase_id: PhaseId 

642 status: ResultStatus = ResultStatus.PENDING 

643 attempt: int = Field(default=1, ge=1) 

644 started_at: datetime | None = None 

645 finished_at: datetime | None = None 

646 input_digest: str | None = None 

647 output_digest: str | None = None 

648 evidence_refs: tuple[str, ...] = () 

649 artifact_refs: tuple[str, ...] = () 

650 summary: str = "" 

651 errors: tuple[HarnessErrorRecord, ...] = () 

652 

653 

654class Execution(StrictModel): 

655 schema_version: Literal["1.0"] = "1.0" 

656 execution_id: str 

657 project_id: str 

658 task_id: str 

659 workspace: str 

660 status: ResultStatus = ResultStatus.PENDING 

661 current_phase: PhaseId = PhaseId.INTENT 

662 attempt: int = Field(default=1, ge=1) 

663 configuration_digest: str 

664 workflow_digest: str 

665 policy_digest: str 

666 configuration_snapshot_ref: str 

667 workflow_ref: str 

668 baseline_revision: str | None = None 

669 change_set_digest: str | None = None 

670 gate_evaluation_id: str | None = None 

671 human_decision_id: str | None = None 

672 created_at: datetime = Field(default_factory=utc_now) 

673 updated_at: datetime = Field(default_factory=utc_now) 

674 terminal_reason: str | None = None 

675 

676 

677class ToolInvocation(StrictModel): 

678 invocation_id: str 

679 execution_id: str 

680 phase_id: PhaseId 

681 actor: Actor 

682 tool_id: str 

683 argv: tuple[str, ...] = () 

684 cwd: str | None = None 

685 started_at: datetime 

686 finished_at: datetime 

687 status: ResultStatus 

688 exit_code: int | None = None 

689 timed_out: bool = False 

690 cancelled: bool = False 

691 stdout_ref: str | None = None 

692 stderr_ref: str | None = None 

693 resource_usage_ref: str | None = None 

694 provenance: Provenance 

695 

696 

697class AgentInvocation(StrictModel): 

698 invocation_id: str 

699 execution_id: str 

700 phase_id: PhaseId 

701 actor: Actor 

702 provider: str 

703 model: str | None = None 

704 session_id: str | None = None 

705 started_at: datetime 

706 finished_at: datetime 

707 status: ResultStatus 

708 prompt_digest: str 

709 context_manifest_ref: str | None = None 

710 tool_invocation_ids: tuple[str, ...] = () 

711 usage_ref: str | None = None 

712 output_ref: str | None = None 

713 error: HarnessErrorRecord | None = None 

714 call_kind: ( 

715 Literal["implement", "clarify", "review", "plan", "acceptance", "architecture", "locate"] 

716 | None 

717 ) = None 

718 """Since 2.0 (#37): the request kind; left out for an implement call sent in the 1.0 form, 

719 so invocations recorded without the agent-results settings keep their stored form.""" 

720 effort: str | None = None 

721 """Since 2.0 (#44): the reasoning effort the router chose, when it chose one.""" 

722 

723 @model_serializer(mode="wrap") 

724 def _omit_absent_kind(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

725 data: dict[str, Any] = handler(self) 

726 for name, alias in (("call_kind", "callKind"), ("effort", "effort")): 

727 if getattr(self, name) is None: 

728 data.pop(name, None) 

729 data.pop(alias, None) 

730 return data 

731 

732 

733class ChangedFile(StrictModel): 

734 path: str 

735 status: Literal["ADDED", "MODIFIED", "DELETED", "RENAMED", "UNTRACKED"] 

736 additions: int = Field(default=0, ge=0) 

737 deletions: int = Field(default=0, ge=0) 

738 before_digest: str | None = None 

739 after_digest: str | None = None 

740 

741 

742class ChangeSet(StrictModel): 

743 schema_version: Literal["1.0"] = "1.0" 

744 change_set_id: str 

745 execution_id: str 

746 baseline_revision: str | None = None 

747 current_revision: str | None = None 

748 files: tuple[ChangedFile, ...] 

749 diff_ref: str 

750 digest: str 

751 created_at: datetime = Field(default_factory=utc_now) 

752 

753 

754class Artifact(StrictModel): 

755 artifact_id: str 

756 execution_id: str 

757 kind: str 

758 media_type: str 

759 uri: str 

760 digest: str 

761 size_bytes: int = Field(ge=0) 

762 created_at: datetime = Field(default_factory=utc_now) 

763 redacted: bool = False 

764 provenance: Provenance 

765 metadata: dict[str, Any] = Field(default_factory=dict) 

766 

767 

768class Evidence(StrictModel): 

769 evidence_id: str 

770 execution_id: str 

771 phase_id: PhaseId 

772 kind: EvidenceKind 

773 artifact_ref: str 

774 digest: str 

775 summary: str 

776 observed_at: datetime = Field(default_factory=utc_now) 

777 provenance: Provenance 

778 supports: tuple[str, ...] = () 

779 

780 

781class FindingLocation(StrictModel): 

782 path: str | None = None 

783 start_line: int | None = Field(default=None, ge=1) 

784 end_line: int | None = Field(default=None, ge=1) 

785 

786 

787class Finding(StrictModel): 

788 schema_version: Literal["1.0"] = "1.0" 

789 finding_id: str 

790 execution_id: str 

791 validator_id: str 

792 rule_id: str 

793 category: str 

794 severity: FindingSeverity 

795 message: str 

796 location: FindingLocation | None = None 

797 evidence_refs: tuple[str, ...] = () 

798 recommendation: str | None = None 

799 introduced: bool | None = None 

800 created_at: datetime = Field(default_factory=utc_now) 

801 provenance: Provenance 

802 

803 

804class ValidationResult(StrictModel): 

805 schema_version: Literal["1.0"] = "1.0" 

806 validation_result_id: str 

807 execution_id: str 

808 validator_id: str 

809 change_set_digest: str 

810 status: ResultStatus 

811 kind: ValidationKind 

812 mandatory: bool = True 

813 summary: str 

814 finding_ids: tuple[str, ...] = () 

815 evidence_refs: tuple[str, ...] 

816 tool_invocation_ids: tuple[str, ...] = () 

817 started_at: datetime 

818 finished_at: datetime 

819 errors: tuple[HarnessErrorRecord, ...] = () 

820 provenance: Provenance 

821 

822 @field_validator("evidence_refs") 

823 @classmethod 

824 def require_evidence(cls, value: tuple[str, ...]) -> tuple[str, ...]: 

825 if not value: 825 ↛ 826line 825 didn't jump to line 826 because the condition on line 825 was never true

826 raise ValueError("a validation result must reference evidence") 

827 return value 

828 

829 

830class GateEvaluation(StrictModel): 

831 schema_version: Literal["1.0"] = "1.0" 

832 gate_evaluation_id: str 

833 execution_id: str 

834 gate_id: str 

835 status: ResultStatus 

836 change_set_digest: str 

837 policy_digest: str 

838 input_refs: tuple[str, ...] 

839 reason_codes: tuple[str, ...] 

840 requires_human_decision: bool 

841 evaluated_at: datetime = Field(default_factory=utc_now) 

842 provenance: Provenance 

843 

844 

845class ChangeRequestItem(StrictModel): 

846 """A blocking item of a structured REQUEST_CHANGES: what must change and the condition 

847 that verifies it. ``test:<pytest node id>`` must pass; ``absent:<regex>`` must not match 

848 any added line of the ChangeSet; ``text`` items are sent to the agent and shown to the 

849 reviewer but are not checked by a tool.""" 

850 

851 item_id: str = Field(pattern=r"^CR-[1-9][0-9]*$") 

852 description: str = Field(min_length=1, max_length=2000) 

853 condition: str = Field(min_length=1, max_length=1000) 

854 

855 @field_validator("condition") 

856 @classmethod 

857 def _known_condition(cls, value: str) -> str: 

858 kind = value.split(":", 1)[0] if ":" in value else value 

859 if kind not in {"test", "absent", "text"}: 859 ↛ 860line 859 didn't jump to line 860 because the condition on line 859 was never true

860 raise ValueError("a condition is test:<node id>, absent:<regex> or text") 

861 if kind in {"test", "absent"} and not value.split(":", 1)[1].strip(): 861 ↛ 862line 861 didn't jump to line 862 because the condition on line 861 was never true

862 raise ValueError(f"the {kind} condition needs a value") 

863 return value 

864 

865 

866class HumanDecision(StrictModel): 

867 schema_version: Literal["1.0"] = "1.0" 

868 decision_id: str 

869 execution_id: str 

870 gate_evaluation_id: str 

871 actor: Actor 

872 decision: DecisionKind 

873 rationale: str 

874 change_set_digest: str 

875 configuration_digest: str 

876 policy_digest: str 

877 decided_at: datetime = Field(default_factory=utc_now) 

878 expires_at: datetime | None = None 

879 acceptance_contract_digest: str | None = None 

880 """Digest of the acceptance contract frozen in SPECIFICATION that the decision is bound to 

881 (``governance.pinTaskRevision``); left out of the serialized record when absent, so 

882 decisions recorded without the setting keep their stored form.""" 

883 identity_source: Literal["explicit", "git", "fallback", "default"] | None = None 

884 """Where the actor id came from under ``governance.deciderIdentity: git``: ``--actor`` 

885 (``explicit``), the Git user (``git``) or, when Git has no usable identity, the default 

886 actor (``fallback``). Left out when absent, like ``acceptance_contract_digest``.""" 

887 acknowledged_risks: tuple[str, ...] = () 

888 """Risk factors of the ChangeSet the person acknowledged (``verification.riskFactors`` 

889 with ``acknowledge``, #52); left out when empty.""" 

890 change_requests: tuple[ChangeRequestItem, ...] = () 

891 """Blocking items of a structured REQUEST_CHANGES (``review.structuredChanges``, #52); 

892 left out when empty.""" 

893 checked_items: tuple[str, ...] = () 

894 """Manual checklist items the person ticked with this decision (``review.manualChecklist``, 

895 #55); left out when empty.""" 

896 pre_authorization_id: str | None = None 

897 """Since #58: the pre-authorised approval this decision applies. The person decided in 

898 advance, under a condition the harness found to hold for this ChangeSet; the decision is 

899 theirs (``actor``), recorded when the condition was met. Left out when absent.""" 

900 

901 @model_serializer(mode="wrap") 

902 def _omit_absent_contract(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

903 data: dict[str, Any] = handler(self) 

904 for name, alias in ( 

905 ("acceptance_contract_digest", "acceptanceContractDigest"), 

906 ("identity_source", "identitySource"), 

907 ("pre_authorization_id", "preAuthorizationId"), 

908 ): 

909 if getattr(self, name) is None: 

910 data.pop(alias, None) 

911 data.pop(name, None) 

912 for name, alias in ( 

913 ("acknowledged_risks", "acknowledgedRisks"), 

914 ("change_requests", "changeRequests"), 

915 ("checked_items", "checkedItems"), 

916 ): 

917 if not getattr(self, name): 

918 data.pop(alias, None) 

919 data.pop(name, None) 

920 return data 

921 

922 

923PreAuthorizationCondition = Literal["gatePassed", "noRiskFactors", "sizeS"] 

924PRE_AUTHORIZATION_CONDITIONS: tuple[PreAuthorizationCondition, ...] = ( 

925 "gatePassed", 

926 "noRiskFactors", 

927 "sizeS", 

928) 

929 

930 

931class PreAuthorization(StrictModel): 

932 """An approval a person gives in advance, when they confirm the operational contract 

933 (#58, item 3). It is a human decision recorded before the ChangeSet exists, bound to the 

934 contract digest of the run and to a condition: the automatic gate passed, the ChangeSet has 

935 no risk factor and the task is size ``S``. At DECISION the harness records the approval on 

936 the person's behalf only when every condition holds, the contract digest is unchanged and 

937 the pre-authorisation has not expired; otherwise the person is asked as usual.""" 

938 

939 schema_version: Literal["1.0"] = "1.0" 

940 pre_authorization_id: str 

941 execution_id: str 

942 task_id: str 

943 actor: Actor 

944 contract_digest: str 

945 task_digest: str 

946 conditions: tuple[PreAuthorizationCondition, ...] = PRE_AUTHORIZATION_CONDITIONS 

947 rationale: str = Field(min_length=1, max_length=4000) 

948 authorized_at: datetime = Field(default_factory=utc_now) 

949 expires_at: datetime 

950 identity_source: Literal["explicit", "git", "fallback", "default"] | None = None 

951 

952 @field_validator("conditions") 

953 @classmethod 

954 def _every_condition( 

955 cls, value: tuple[PreAuthorizationCondition, ...] 

956 ) -> tuple[PreAuthorizationCondition, ...]: 

957 # The condition of issue #58 is the conjunction of the three; none can be dropped. 

958 if set(value) != set(PRE_AUTHORIZATION_CONDITIONS): 

959 raise ValueError("a pre-authorisation requires gatePassed, noRiskFactors and sizeS") 

960 return value 

961 

962 @model_serializer(mode="wrap") 

963 def _omit_absent_identity(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

964 data: dict[str, Any] = handler(self) 

965 if self.identity_source is None: 965 ↛ 966line 965 didn't jump to line 966 because the condition on line 965 was never true

966 data.pop("identitySource", None) 

967 data.pop("identity_source", None) 

968 return data 

969 

970 

971class ExceptionScope(StrictModel): 

972 """Findings an exception covers: a rule, optionally narrowed to a path and to one finding 

973 fingerprint (``reporting.fingerprint``).""" 

974 

975 rule_id: str = Field(min_length=1) 

976 path: str | None = None 

977 fingerprint: str | None = None 

978 

979 

980class ExceptionRecord(StrictModel): 

981 """A person's exception to blocking findings, recorded with ``APPROVE_EXCEPTION`` when 

982 ``review.exceptions`` is on. 

983 

984 It is bound to the decision and the ChangeSet digest it was granted on, expires at 

985 ``expires_at`` and covers the findings in ``scope``: while it is in force a later run of the 

986 project does not block on them, and once it expires they block again. Alternative evidence 

987 and the follow-up are what the person declared; the harness records them, it does not check 

988 them.""" 

989 

990 schema_version: Literal["1.0"] = "1.0" 

991 exception_id: str 

992 project_id: str 

993 execution_id: str 

994 decision_id: str 

995 gate_evaluation_id: str 

996 actor: Actor 

997 rationale: str = Field(min_length=1) 

998 scope: tuple[ExceptionScope, ...] = () 

999 change_set_digest: str 

1000 granted_at: datetime = Field(default_factory=utc_now) 

1001 expires_at: datetime 

1002 alternative_evidence: str | None = Field(default=None, max_length=4000) 

1003 follow_up: str | None = Field(default=None, max_length=1000) 

1004 provenance: Provenance 

1005 

1006 def active_at(self, now: datetime) -> bool: 

1007 return self.granted_at <= now < self.expires_at 

1008 

1009 

1010FEEDBACK_STREAM_CHARS = 4000 

1011"""Characters kept from the end of each failing validator stream in provider feedback.""" 

1012FEEDBACK_TOTAL_CHARS = 16000 

1013"""Characters of validator output (all streams together) one feedback block may carry.""" 

1014FEEDBACK_MAX_FINDINGS = 20 

1015FEEDBACK_TEXT_CHARS = 1000 

1016"""Characters kept from a finding message, a validator summary or a claim summary.""" 

1017FEEDBACK_RATIONALE_CHARS = 4000 

1018 

1019FeedbackTrigger = Literal["VERIFICATION_FAILED", "CHANGES_REQUESTED", "REVIEW_FINDINGS"] 

1020"""Why a correction attempt was sent back to the agent; ``REVIEW_FINDINGS`` since 2.0 

1021(``review.agentReview``, #38).""" 

1022 

1023 

1024class FeedbackGate(StrictModel): 

1025 """The outcome the feedback is about: the VERIFICATION result (``gate_id`` ``verification``) 

1026 or the delivery gate a person decided on (``delivery_candidate``).""" 

1027 

1028 gate_id: Literal["verification", "delivery_candidate", "independent_review"] 

1029 gate_evaluation_id: str | None = None 

1030 status: ResultStatus 

1031 reason_codes: tuple[str, ...] 

1032 

1033 

1034class FeedbackFinding(StrictModel): 

1035 rule_id: str 

1036 severity: FindingSeverity 

1037 validator_id: str 

1038 location: FindingLocation | None = None 

1039 message: str = Field(max_length=FEEDBACK_TEXT_CHARS) 

1040 

1041 

1042class FeedbackValidator(StrictModel): 

1043 """A mandatory validator that did not pass, with the end of its redacted output.""" 

1044 

1045 validator_id: str 

1046 status: ResultStatus 

1047 summary: str = Field(max_length=FEEDBACK_TEXT_CHARS) 

1048 exit_code: int | None = None 

1049 stdout: str = Field(default="", max_length=FEEDBACK_STREAM_CHARS) 

1050 stderr: str = Field(default="", max_length=FEEDBACK_STREAM_CHARS) 

1051 stdout_truncated: bool = False 

1052 stderr_truncated: bool = False 

1053 

1054 

1055class FeedbackDecision(StrictModel): 

1056 decision: DecisionKind 

1057 rationale: str = Field(max_length=FEEDBACK_RATIONALE_CHARS) 

1058 actor_id: str 

1059 

1060 

1061class ProviderFeedback(StrictModel): 

1062 """Why the previous attempt was not accepted, sent to a command provider as ``feedback``. 

1063 

1064 It is built when a failed VERIFICATION returns the run to IMPLEMENTATION 

1065 (``VERIFICATION_FAILED``) or a person requests changes (``CHANGES_REQUESTED``), only when 

1066 ``runtime.providerFeedback`` is true. Validator output is bounded: the last 

1067 ``FEEDBACK_STREAM_CHARS`` characters of each stream and ``FEEDBACK_TOTAL_CHARS`` in all.""" 

1068 

1069 schema_version: Literal["1.0"] = "1.0" 

1070 attempt: int = Field(ge=2) 

1071 trigger: FeedbackTrigger 

1072 change_set_digest: str 

1073 gate: FeedbackGate 

1074 findings: tuple[FeedbackFinding, ...] = Field(default=(), max_length=FEEDBACK_MAX_FINDINGS) 

1075 omitted_findings: int = Field(default=0, ge=0) 

1076 validators: tuple[FeedbackValidator, ...] = () 

1077 decision: FeedbackDecision | None = None 

1078 

1079 

1080class ResourceUsage(StrictModel): 

1081 usage_id: str 

1082 execution_id: str 

1083 invocation_id: str | None = None 

1084 wall_time_ms: int = Field(ge=0) 

1085 cpu_time_ms: int | None = Field(default=None, ge=0) 

1086 max_rss_bytes: int | None = Field(default=None, ge=0) 

1087 input_tokens: int | None = Field(default=None, ge=0) 

1088 output_tokens: int | None = Field(default=None, ge=0) 

1089 reasoning_tokens: int | None = Field(default=None, ge=0) 

1090 cost_usd: float | None = Field(default=None, ge=0) 

1091 quality: MetricQuality 

1092 limitations: tuple[str, ...] = () 

1093 cache_tokens: int | None = Field(default=None, ge=0) 

1094 """Since #58: the input tokens served from or written to the provider's prompt cache, when 

1095 the provider reports them (already included in ``input_tokens``). Left out when absent, so 

1096 usage recorded before it keeps its stored form.""" 

1097 cache_read_tokens: int | None = Field(default=None, ge=0) 

1098 """Since #70: the part of ``cache_tokens`` (and so of ``input_tokens``) read from the 

1099 provider's prompt cache, when the provider reports the split. The token budget of the agent 

1100 contract does not count it. Left out when absent, like ``cache_tokens``.""" 

1101 

1102 @model_serializer(mode="wrap") 

1103 def _omit_absent_cache(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

1104 data: dict[str, Any] = handler(self) 

1105 if self.cache_tokens is None: 

1106 data.pop("cacheTokens", None) 

1107 data.pop("cache_tokens", None) 

1108 if self.cache_read_tokens is None: 

1109 data.pop("cacheReadTokens", None) 

1110 data.pop("cache_read_tokens", None) 

1111 return data 

1112 

1113 

1114class MemoryRecord(StrictModel): 

1115 memory_id: str 

1116 project_id: str 

1117 task_id: str | None = None 

1118 execution_id: str | None = None 

1119 level: MemoryLevel 

1120 key: str 

1121 value: dict[str, Any] 

1122 provenance: Provenance 

1123 created_at: datetime = Field(default_factory=utc_now) 

1124 valid_until: datetime | None = None 

1125 supersedes: str | None = None 

1126 sensitive: bool = False 

1127 approved: bool = False 

1128 

1129 

1130class RetrospectiveObservation(StrictModel): 

1131 observation_id: str 

1132 statement: str 

1133 evidence_refs: tuple[str, ...] 

1134 

1135 

1136class Recommendation(StrictModel): 

1137 recommendation_id: str 

1138 category: str 

1139 statement: str 

1140 rationale: str 

1141 evidence_refs: tuple[str, ...] 

1142 confidence: float = Field(ge=0, le=1) 

1143 risk: Literal["LOW", "MEDIUM", "HIGH"] 

1144 requires_human_review: bool = True 

1145 

1146 

1147RetrospectiveTrigger = Literal["CLOSED", "REJECTED", "CANCELLED", "ON_DEMAND"] 

1148 

1149 

1150class RetrospectiveCause(StrictModel): 

1151 """What stopped or redirected a run, by reason code (``retrospective.causal``). 

1152 

1153 ``subject`` is the validator, rule or provider the cause is about, never a person; 

1154 ``attempts`` are the VERIFICATION or decision attempts in which it occurred.""" 

1155 

1156 reason_code: str 

1157 subject: str 

1158 phase: PhaseId 

1159 effect: str 

1160 occurrences: int = Field(ge=1) 

1161 attempts: tuple[int, ...] = () 

1162 evidence_refs: tuple[str, ...] = () 

1163 

1164 

1165class Retrospective(StrictModel): 

1166 """Non-mutating observations and recommendations about a run. ``causes`` and ``trigger`` 

1167 are filled only under ``retrospective.causal`` and are left out of the serialized record 

1168 otherwise, so a 1.0.0 retrospective keeps its form.""" 

1169 

1170 retrospective_id: str 

1171 execution_id: str 

1172 observations: tuple[RetrospectiveObservation, ...] 

1173 recommendations: tuple[Recommendation, ...] 

1174 generated_at: datetime = Field(default_factory=utc_now) 

1175 applied_automatically: Literal[False] = False 

1176 provenance: Provenance 

1177 trigger: RetrospectiveTrigger | None = None 

1178 causes: tuple[RetrospectiveCause, ...] = () 

1179 

1180 @model_serializer(mode="wrap") 

1181 def _omit_causal_fields(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: 

1182 data: dict[str, Any] = handler(self) 

1183 if self.trigger is None: 

1184 data.pop("trigger", None) 

1185 if not self.causes: 

1186 data.pop("causes", None) 

1187 return data 

1188 

1189 

1190OutcomeKind = Literal["INCIDENT", "REVERT", "HOTFIX", "REGRESSION", "OTHER"] 

1191 

1192 

1193class OutcomeRecord(StrictModel): 

1194 """Something that happened to a change after its run: an incident, a revert, a hotfix or a 

1195 regression, linked to the run by a person. It feeds the rule health across runs; nothing 

1196 is applied automatically.""" 

1197 

1198 schema_version: Literal["1.0"] = "1.0" 

1199 outcome_id: str 

1200 project_id: str 

1201 execution_id: str 

1202 kind: OutcomeKind 

1203 summary: str = Field(min_length=1, max_length=4000) 

1204 reference: str | None = Field(default=None, max_length=1000) 

1205 change_set_digest: str | None = None 

1206 observed_at: datetime 

1207 recorded_at: datetime = Field(default_factory=utc_now) 

1208 actor: Actor 

1209 provenance: Provenance 

1210 

1211 

1212# ----- wave 4 (since 2.0): provenance per component, agent self-report, evidence bundle ------- 

1213class SelfReportItem(StrictModel): 

1214 path: str | None = Field(default=None, max_length=1000) 

1215 description: str = Field(min_length=1, max_length=1000) 

1216 

1217 

1218class DisputedAcceptanceTest(StrictModel): 

1219 """A frozen acceptance test the agent believes is wrong, and why (#94).""" 

1220 

1221 test: str = Field(min_length=1, max_length=1000) 

1222 reason: str = Field(min_length=1, max_length=1000) 

1223 

1224 

1225class SelfReportContrast(StrictModel): 

1226 """The self-report compared with the ChangeSet recorded after the same invocation.""" 

1227 

1228 change_set_digest: str | None = None 

1229 declared_paths_not_in_change_set: tuple[str, ...] = () 

1230 unrequested_changes_in_change_set: tuple[str, ...] = () 

1231 

1232 

1233class AgentSelfReport(StrictModel): 

1234 """What an agent says about its own work (``provenance.selfReport``): assumptions, 

1235 alternatives it discarded, areas where it is not confident and changes nobody asked for. 

1236 

1237 It is data of quality ``REPORTED``: the harness stores and shows it, contrasts it with the 

1238 ChangeSet, and never treats it as a verification.""" 

1239 

1240 schema_version: Literal["1.0"] = "1.0" 

1241 report_id: str 

1242 execution_id: str 

1243 invocation_id: str 

1244 provider: str 

1245 quality: MetricQuality = MetricQuality.REPORTED 

1246 assumptions: tuple[str, ...] = () 

1247 alternatives_discarded: tuple[str, ...] = () 

1248 low_confidence_areas: tuple[SelfReportItem, ...] = () 

1249 unrequested_changes: tuple[SelfReportItem, ...] = () 

1250 disputed_acceptance_tests: tuple[DisputedAcceptanceTest, ...] = () 

1251 """Frozen acceptance tests the agent believes are wrong (#94); a person decides.""" 

1252 problems: tuple[str, ...] = () 

1253 """What could not be read from the agent's answer (the rest is kept).""" 

1254 contrast: SelfReportContrast | None = None 

1255 created_at: datetime = Field(default_factory=utc_now) 

1256 

1257 

1258ProvenanceSource = Literal["AGENT", "OUT_OF_BAND"] 

1259 

1260 

1261class FileProvenance(StrictModel): 

1262 path: str 

1263 status: Literal["ADDED", "MODIFIED", "DELETED", "RENAMED", "UNTRACKED"] 

1264 digest: str | None = None 

1265 source: ProvenanceSource 

1266 invocation_id: str | None = None 

1267 """The agent invocation after which the file had its current content (``AGENT``).""" 

1268 

1269 

1270class OutOfBandEdit(StrictModel): 

1271 """A ChangeSet file that changed after the last agent invocation without one.""" 

1272 

1273 path: str 

1274 status: Literal["ADDED", "MODIFIED", "DELETED"] 

1275 agent_digest: str | None = None 

1276 current_digest: str | None = None 

1277 after_invocation_id: str | None = None 

1278 detected_in: PhaseId 

1279 

1280 

1281class ComponentProvenance(StrictModel): 

1282 """Who produced each file of a ChangeSet (``provenance.agentSnapshots``).""" 

1283 

1284 schema_version: Literal["1.0"] = "1.0" 

1285 provenance_id: str 

1286 execution_id: str 

1287 change_set_digest: str 

1288 detected_in: PhaseId 

1289 files: tuple[FileProvenance, ...] = () 

1290 out_of_band_edits: tuple[OutOfBandEdit, ...] = () 

1291 agent_snapshot_refs: tuple[str, ...] = () 

1292 created_at: datetime = Field(default_factory=utc_now) 

1293 

1294 

1295class BundleEntry(StrictModel): 

1296 path: str 

1297 digest: str 

1298 size_bytes: int = Field(ge=0) 

1299 

1300 

1301class EvidenceBundleManifest(StrictModel): 

1302 """``manifest.json`` of a portable evidence bundle (``harness export --bundle``): what the 

1303 archive holds and the digest of every entry. ``harness verify --bundle`` checks it without 

1304 the workspace.""" 

1305 

1306 schema_version: Literal["1.0"] = "1.0" 

1307 bundle_format: Literal["governed-harness-bundle/1"] = "governed-harness-bundle/1" 

1308 execution_id: str 

1309 project_id: str 

1310 task_id: str 

1311 status: ResultStatus 

1312 current_phase: PhaseId 

1313 change_set_digest: str | None = None 

1314 decision_id: str | None = None 

1315 event_count: int = Field(ge=0) 

1316 event_chain_head: str | None = None 

1317 core_version: str 

1318 created_at: datetime = Field(default_factory=utc_now) 

1319 entries: tuple[BundleEntry, ...] 

1320 

1321 

1322# ----- since 2.0 (#55): certification, deferred verification and human attachments --------- 

1323CertificationStatus = Literal["CERTIFIED", "PARTIAL", "NOT_CERTIFIED"] 

1324"""Status of a run: every criterion reached its rung, some did (or are pending), none did.""" 

1325CriterionStatus = Literal["CERTIFIED", "PENDING", "NOT_CERTIFIED", "WAIVED"] 

1326"""``PENDING``: the rung is reached only by deferred evidence or a manual check not recorded 

1327yet; ``WAIVED``: a person decided in preflight to continue without it (never certified).""" 

1328 

1329 

1330class LevelEvidence(StrictModel): 

1331 """One piece of recorded evidence that a criterion reached a rung.""" 

1332 

1333 level: VerificationLevel 

1334 source: str 

1335 detail: str 

1336 refs: tuple[str, ...] = () 

1337 

1338 

1339class CriterionCertification(StrictModel): 

1340 criterion_id: str 

1341 required: VerificationLevel 

1342 declared: bool 

1343 """Whether the criterion declares its rung (``verification.level``); a criterion without a 

1344 declaration requires ``verification.ladder.defaultLevel`` and its gap never blocks.""" 

1345 achieved: VerificationLevel | None = None 

1346 status: CriterionStatus 

1347 reason: str 

1348 evidence: tuple[LevelEvidence, ...] = () 

1349 pending: tuple[str, ...] = () 

1350 

1351 

1352class CertificationRecord(StrictModel): 

1353 """The certification of a run's ChangeSet: for each acceptance criterion the rung it 

1354 requires, the rung its recorded evidence reaches and why (``verification.ladder``).""" 

1355 

1356 schema_version: Literal["1.0"] = "1.0" 

1357 certification_id: str 

1358 execution_id: str 

1359 change_set_digest: str 

1360 status: CertificationStatus 

1361 trigger: Literal["VERIFICATION", "DECISION", "EVIDENCE"] 

1362 criteria: tuple[CriterionCertification, ...] = () 

1363 created_at: datetime = Field(default_factory=utc_now) 

1364 

1365 

1366DeferredStatus = Literal["PENDING", "PASSED", "FAILED", "EXPIRED"] 

1367 

1368 

1369class DeferredVerification(StrictModel): 

1370 """A criterion that only CI, staging or a device lab can verify: pending after the run, 

1371 bound to the ChangeSet digest (and to the closure commit once there is one), until 

1372 ``harness evidence attach`` closes it with a JUnit, SARIF or CI status report. A pending 

1373 item expires; an expired one cannot be closed and the criterion is not certified.""" 

1374 

1375 schema_version: Literal["1.0"] = "1.0" 

1376 deferred_id: str 

1377 item_id: str 

1378 project_id: str 

1379 execution_id: str 

1380 task_id: str 

1381 criterion_id: str 

1382 level: VerificationLevel 

1383 where: str 

1384 change_set_digest: str 

1385 commit: str | None = None 

1386 status: DeferredStatus = "PENDING" 

1387 created_at: datetime = Field(default_factory=utc_now) 

1388 expires_at: datetime 

1389 closed_at: datetime | None = None 

1390 evidence_kind: Literal["junit", "sarif", "ci-status"] | None = None 

1391 evidence_ref: str | None = None 

1392 evidence_digest: str | None = None 

1393 summary: str | None = None 

1394 closed_by: Actor | None = None 

1395 

1396 

1397class HumanAttachment(StrictModel): 

1398 """Evidence a person attached (a screenshot, a video, a log): stored as an artifact and 

1399 bound to its digest, to the task revision (intake context) or to a run's ChangeSet and, 

1400 optionally, to a checklist item.""" 

1401 

1402 schema_version: Literal["1.0"] = "1.0" 

1403 attachment_id: str 

1404 project_id: str 

1405 task_id: str 

1406 task_digest: str | None = None 

1407 execution_id: str | None = None 

1408 change_set_digest: str | None = None 

1409 item_id: str | None = None 

1410 artifact_ref: str 

1411 digest: str 

1412 media_type: str 

1413 size_bytes: int = Field(ge=0) 

1414 file_name: str 

1415 note: str | None = Field(default=None, max_length=2000) 

1416 actor: Actor 

1417 attached_at: datetime = Field(default_factory=utc_now)