Coverage for src/governed_harness/cli/render.py: 54%

367 statements  

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

1"""Human-readable rendering of CLI results. 

2 

3JSON stays the contract for scripts: it is printed whenever standard output is not a terminal 

4or ``--json`` is given. On a terminal (or with ``--no-json``) the same data is rendered as text: 

5known shapes (runs, tasks, findings, execution status, review brief) get a dedicated layout and 

6anything else falls back to an indented ``key: value`` listing. Rendering never changes the 

7data, only how it is shown.""" 

8 

9from __future__ import annotations 

10 

11import re 

12import sys 

13from collections.abc import Callable, Mapping, Sequence 

14from typing import Any 

15 

16_CAMEL = re.compile(r"(?<=[a-z0-9])([A-Z])") 

17_NEXT_HEADING = "Next:" 

18 

19 

20def wants_json(flag: bool | None, stream: Any = None) -> bool: 

21 """``True``/``False`` when the user chose; otherwise JSON unless the stream is a terminal.""" 

22 if flag is not None: 

23 return flag 

24 target = stream if stream is not None else sys.stdout 

25 try: 

26 return not bool(target.isatty()) 

27 except (AttributeError, ValueError): 

28 return True 

29 

30 

31def label(key: str) -> str: 

32 """``changeSetDigest`` -> ``change set digest``.""" 

33 return _CAMEL.sub(lambda match: " " + match.group(1).lower(), key).replace("_", " ") 

34 

35 

36def short(value: object, width: int = 72) -> str: 

37 text = " ".join(str(value).split()) 

38 return text if len(text) <= width else text[: width - 1] + "…" 

39 

40 

41def _scalar(value: object) -> str: 

42 if value is None: 42 ↛ 43line 42 didn't jump to line 43 because the condition on line 42 was never true

43 return "-" 

44 if isinstance(value, bool): 44 ↛ 45line 44 didn't jump to line 45 because the condition on line 44 was never true

45 return "yes" if value else "no" 

46 return str(value) 

47 

48 

49def _is_scalar(value: object) -> bool: 

50 return value is None or isinstance(value, str | int | float | bool) 

51 

52 

53def _generic_entry(name: str, item: object, indent: int) -> list[str]: 

54 """One ``key: value`` entry of a mapping; a nested value goes below its key.""" 

55 pad = " " * indent 

56 if _is_scalar(item): 

57 return [f"{pad}{name}: {_scalar(item)}"] 

58 if isinstance(item, Sequence) and not item: 

59 return [f"{pad}{name}: -"] 

60 if isinstance(item, Sequence) and all(_is_scalar(entry) for entry in item): 

61 return [f"{pad}{name}: " + ", ".join(_scalar(entry) for entry in item)] 

62 if isinstance(item, Mapping) and not item: 62 ↛ 63line 62 didn't jump to line 63 because the condition on line 62 was never true

63 return [f"{pad}{name}: -"] 

64 return [f"{pad}{name}:", *generic(item, indent + 1)] 

65 

66 

67def _generic_item(index: int, item: object, indent: int) -> list[str]: 

68 """One item of a sequence: ``- value``, or ``[index]`` with the item below it.""" 

69 pad = " " * indent 

70 if _is_scalar(item): 70 ↛ 71line 70 didn't jump to line 71 because the condition on line 70 was never true

71 return [f"{pad}- {_scalar(item)}"] 

72 return [f"{pad}[{index}]", *generic(item, indent + 1)] 

73 

74 

75def generic(value: object, indent: int = 0) -> list[str]: 

76 pad = " " * indent 

77 if _is_scalar(value): 77 ↛ 78line 77 didn't jump to line 78 because the condition on line 77 was never true

78 return [pad + _scalar(value)] 

79 if isinstance(value, Mapping): 

80 lines: list[str] = [] 

81 for key, item in value.items(): 

82 lines.extend(_generic_entry(label(str(key)), item, indent)) 

83 return lines 

84 if isinstance(value, Sequence): 84 ↛ 89line 84 didn't jump to line 89 because the condition on line 84 was always true

85 lines = [] 

86 for index, item in enumerate(value, start=1): 

87 lines.extend(_generic_item(index, item, indent)) 

88 return lines 

89 return [pad + str(value)] 

90 

91 

92def table(rows: Sequence[Sequence[str]], headers: Sequence[str]) -> list[str]: 

93 widths = [len(item) for item in headers] 

94 for row in rows: 

95 widths = [max(width, len(cell)) for width, cell in zip(widths, row, strict=True)] 

96 line = " ".join(header.ljust(width) for header, width in zip(headers, widths, strict=True)) 

97 rule = " ".join("-" * width for width in widths) 

98 body = [ 

99 " ".join(cell.ljust(width) for cell, width in zip(row, widths, strict=True)).rstrip() 

100 for row in rows 

101 ] 

102 return [line.rstrip(), rule, *body] 

103 

104 

105def _location(finding: Mapping[str, Any]) -> str: 

106 location = finding.get("location") or {} 

107 where = location.get("path") or "-" 

108 if location.get("startLine"): 

109 where += f":{location['startLine']}" 

110 return str(where) 

111 

112 

113def _runs(items: Sequence[Mapping[str, Any]]) -> list[str]: 

114 if not items: 114 ↛ 116line 114 didn't jump to line 116 because the condition on line 114 was always true

115 return ["No runs recorded. Start one with: harness run start --task <taskId>"] 

116 rows = [ 

117 [ 

118 str(item["executionId"]), 

119 str(item["taskId"]), 

120 str(item["currentPhase"]), 

121 str(item["status"]), 

122 str(item.get("updatedAt", ""))[:19], 

123 ] 

124 for item in items 

125 ] 

126 return table(rows, ["RUN", "TASK", "PHASE", "STATUS", "UPDATED"]) 

127 

128 

129def _tasks(items: Sequence[Mapping[str, Any]]) -> list[str]: 

130 if not items: 

131 return ["No tasks recorded. Create one with: harness task create --file task.yaml"] 

132 rows = [ 

133 [ 

134 str(item["taskId"]), 

135 short(item.get("title", ""), 48), 

136 str(len(item.get("acceptanceCriteria") or ())), 

137 str(item.get("implementation", {}).get("mode", "-")), 

138 ] 

139 for item in items 

140 ] 

141 return table(rows, ["TASK", "TITLE", "CRITERIA", "IMPLEMENTATION"]) 

142 

143 

144def _findings(items: Sequence[Mapping[str, Any]]) -> list[str]: 

145 if not items: 

146 return ["No findings were recorded."] 

147 rows = [ 

148 [ 

149 str(item["severity"]), 

150 str(item["ruleId"]), 

151 _location(item), 

152 short(item.get("message", ""), 60), 

153 ] 

154 for item in items 

155 ] 

156 return table(rows, ["SEVERITY", "RULE", "LOCATION", "MESSAGE"]) 

157 

158 

159def execution_headline(execution: Mapping[str, Any]) -> str: 

160 """One line that says what the run is waiting for, without changing the stored status.""" 

161 status = execution.get("status") 

162 phase = execution.get("currentPhase") 

163 run_id = execution.get("executionId") 

164 if status == "BLOCKED" and phase == "DECISION": 164 ↛ 166line 164 didn't jump to line 166 because the condition on line 164 was always true

165 return f"Run {run_id}: automated phases finished, waiting for a human decision." 

166 if status == "PASSED": 

167 return f"Run {run_id}: closed (PASSED)." 

168 if status == "CANCELLED": 

169 return f"Run {run_id}: cancelled." 

170 if status in {"FAILED", "BLOCKED", "INCONCLUSIVE", "TIMED_OUT", "ERROR"}: 

171 reason = execution.get("terminalReason") 

172 suffix = f" ({reason})" if reason else "" 

173 return f"Run {run_id}: {status} in {phase}{suffix}." 

174 return f"Run {run_id}: {status} in {phase}." 

175 

176 

177def next_steps(execution: Mapping[str, Any]) -> list[str]: 

178 """The commands a person most likely needs next, ready to copy.""" 

179 run_id = execution.get("executionId") 

180 status = execution.get("status") 

181 phase = execution.get("currentPhase") 

182 if status == "BLOCKED" and phase == "DECISION": 182 ↛ 187line 182 didn't jump to line 187 because the condition on line 182 was always true

183 return [ 

184 f"harness review --run {run_id}", 

185 f"harness gate decide --run {run_id} (interactive on a terminal)", 

186 ] 

187 if status == "PASSED": 

188 return [ 

189 f"harness trace --run {run_id} --format markdown", 

190 f"harness retrospect --run {run_id}", 

191 ] 

192 if status == "CANCELLED": 

193 return [] 

194 if phase == "INTENT" and status == "BLOCKED": 

195 return [ 

196 f"harness task questions --task {execution.get('taskId')}", 

197 f"harness task clarify --task {execution.get('taskId')} --file answers.yaml", 

198 ] 

199 if status in {"FAILED", "BLOCKED", "INCONCLUSIVE", "TIMED_OUT", "ERROR"}: 

200 return [ 

201 f"harness review --run {run_id}", 

202 f"harness run continue --run {run_id} (after fixing the cause)", 

203 f"harness run cancel --run {run_id}", 

204 ] 

205 return [f"harness run continue --run {run_id}"] 

206 

207 

208def _execution(value: Mapping[str, Any]) -> list[str]: 

209 lines = [execution_headline(value), ""] 

210 for key in ("taskId", "currentPhase", "status", "attempt", "changeSetDigest"): 

211 if key in value: 

212 lines.append(f"{label(key)}: {_scalar(value.get(key))}") 

213 steps = next_steps(value) 

214 if steps: 214 ↛ 216line 214 didn't jump to line 216 because the condition on line 214 was always true

215 lines.extend(["", _NEXT_HEADING, *(f" {step}" for step in steps)]) 

216 return lines 

217 

218 

219def _status(value: Mapping[str, Any]) -> list[str]: 

220 execution = value["execution"] 

221 lines = _execution(execution) 

222 gate = value.get("gate") 

223 lines.append("") 

224 if gate: 

225 lines.append(f"gate: {gate['status']} ({', '.join(gate['reasonCodes'])})") 

226 else: 

227 lines.append("gate: not evaluated yet") 

228 decision = value.get("humanDecision") 

229 if decision: 

230 lines.append(f"human decision: {decision['decision']} by {decision['actor']['actorId']}") 

231 summary = value.get("validationSummary", {}) 

232 by_status = ", ".join(f"{key} {count}" for key, count in summary.get("byStatus", {}).items()) 

233 lines.append(f"validations: {summary.get('total', 0)} ({by_status or 'none'})") 

234 findings = value.get("findings", {}) 

235 by_severity = ", ".join( 

236 f"{key} {count}" for key, count in findings.get("bySeverity", {}).items() 

237 ) 

238 lines.append(f"findings: {findings.get('total', 0)} ({by_severity or 'none'})") 

239 lines.append(f"event chain valid: {_scalar(value.get('eventChainValid'))}") 

240 lines.extend(["", "Phases:"]) 

241 rows = [ 

242 [ 

243 str(item["phaseId"]), 

244 str(item["attempt"]), 

245 str(item["status"]), 

246 short(item["summary"], 60), 

247 ] 

248 for item in value.get("phases", []) 

249 ] 

250 lines.extend(" " + line for line in table(rows, ["PHASE", "ATTEMPT", "STATUS", "SUMMARY"])) 

251 return lines 

252 

253 

254def _decision(value: Mapping[str, Any]) -> list[str]: 

255 decision = value["decision"] 

256 lines = [ 

257 f"Recorded {decision['decision']} by {decision['actor']['actorId']} " 

258 f"for {decision['changeSetDigest']}." 

259 ] 

260 if decision.get("expiresAt"): 

261 lines.append(f"The exception expires at {decision['expiresAt']}.") 

262 lines.extend(["", *_execution(value["execution"])]) 

263 return lines 

264 

265 

266def _doctor(value: Mapping[str, Any]) -> list[str]: 

267 lines = [f"harness {value.get('version')}: {value.get('status')}", ""] 

268 for name, check in value.get("checks", {}).items(): 

269 detail = next( 

270 ( 

271 str(check[key]) 

272 for key in ("message", "version", "mechanism", "path", "provider", "head") 

273 if check.get(key) 

274 ), 

275 "", 

276 ) 

277 lines.append(f"{check.get('status', '-'):<15} {label(name):<22} {short(detail, 60)}") 

278 for item in check.get("validators", ()): 

279 lines.append( 

280 f"{'':<15} {item['id']:<20} {item['status']}" 

281 + (f" - {item['message']}" if item.get("message") else "") 

282 ) 

283 if check.get("hint"): 

284 lines.append(f"{'':<15} fix: {check['hint']}") 

285 for item in check.get("validators", ()): 

286 if item.get("hint"): 

287 lines.append(f"{'':<15} fix {item['id']}: {item['hint']}") 

288 return lines 

289 

290 

291def _init(value: Mapping[str, Any]) -> list[str]: 

292 lines = [f"Wrote {value['configuration']}"] 

293 profiles = ", ".join( 

294 f"{item['profileId']} ({item['confidence']:.2f})" for item in value.get("profiles", []) 

295 ) 

296 lines.append(f"Detected profiles: {profiles or 'none'}") 

297 ignore = value.get("ignore") 

298 if isinstance(ignore, Mapping): 

299 lines.append(f"{ignore['file']}: {ignore['entry']} {ignore['status']}") 

300 elif "gitignore" in value: 

301 lines.append(f".gitignore: .harness/ {value['gitignore']}") 

302 if value.get("exampleTask"): 

303 lines.append(f"Example task: {value['exampleTask']}") 

304 lines.extend(["", _NEXT_HEADING, *(f" {step}" for step in value.get("next", []))]) 

305 return lines 

306 

307 

308def _review_asked(brief: Mapping[str, Any]) -> list[str]: 

309 """The header of the brief and what was asked.""" 

310 run = brief["run"] 

311 waiting = ", waiting for your decision" if run["awaitingDecision"] else "" 

312 lines = [ 

313 f"Decision brief - run {run['executionId']} ({run['status']} in " 

314 f"{run['currentPhase']}{waiting})", 

315 f"ChangeSet {run['changeSetDigest'] or 'not computed yet'}", 

316 "", 

317 "What was asked", 

318 f" {brief['asked']['title']}", 

319 f" intent: {short(brief['asked']['intent'], 100)}", 

320 ] 

321 for item in brief["asked"]["requirements"]: 

322 lines.append(f" requirement {item['requirementId']}: {short(item['text'], 90)}") 

323 for item in brief["asked"]["acceptanceCriteria"]: 

324 lines.append( 

325 f" criterion {item['criterionId']} [{item['priority']}]: {short(item['text'], 90)}" 

326 ) 

327 for item in brief["asked"]["constraints"]: 327 ↛ 328line 327 didn't jump to line 328 because the loop on line 327 never started

328 lines.append(f" constraint: {short(item, 100)}") 

329 lines.extend(_assumption_lines(brief["asked"].get("assumptions"))) 

330 return lines 

331 

332 

333def _review_changed(changed: Mapping[str, Any]) -> list[str]: 

334 totals = changed.get("totals") or {"files": 0, "additions": 0, "deletions": 0} 

335 lines = [ 

336 "", 

337 f"What changed ({totals['files']} file(s), +{totals['additions']} -{totals['deletions']})", 

338 ] 

339 for item in changed.get("files", []): 

340 lines.append( 

341 f" {item['status']:<9} {item['path']} +{item['additions']} -{item['deletions']}" 

342 ) 

343 return lines 

344 

345 

346def _review_gate(gate: Mapping[str, Any] | None) -> list[str]: 

347 if not gate: 347 ↛ 348line 347 didn't jump to line 348 because the condition on line 347 was never true

348 return ["", "Gate: not evaluated yet"] 

349 return [ 

350 "", 

351 f"Gate {gate['status']}", 

352 *(f" - {item['explanation']}" for item in gate["reasons"]), 

353 ] 

354 

355 

356def _review_risks(risks: Sequence[Mapping[str, Any]]) -> list[str]: 

357 lines = ["", f"Risks ({len(risks)})"] 

358 if not risks: 358 ↛ 359line 358 didn't jump to line 359 because the condition on line 358 was never true

359 lines.append(" no current finding") 

360 for item in risks: 

361 flag = "BLOCKS" if item["blocking"] else "info" 

362 lines.append( 

363 f" {flag:<6} {item['severity']:<8} {item['ruleId']} {item['location']} " 

364 f"{short(item['message'], 80)}" 

365 ) 

366 return lines 

367 

368 

369def _review_verified(verified: Mapping[str, Any]) -> list[str]: 

370 lines = ["", f"Verified on {verified['changeSetDigest']}"] 

371 for item in verified["validations"]: 

372 kind = "mandatory" if item["mandatory"] else "optional" 

373 retry = f", {item['attempts']} attempts" if item["attempts"] > 1 else "" 

374 lines.append(f" {item['status']:<14} {item['validatorId']} ({kind}{retry})") 

375 for item in verified["requirements"]: 

376 tests = ", ".join(item["tests"]) or "no test" 

377 lines.append(f" requirement {item['requirementId']}: {tests}") 

378 return lines 

379 

380 

381def _review_not_verified(brief: Mapping[str, Any]) -> list[str]: 

382 if not brief.get("notVerified"): 382 ↛ 383line 382 didn't jump to line 383 because the condition on line 382 was never true

383 return [] 

384 return ["", "Not verified", *(f" - {item}" for item in brief["notVerified"])] 

385 

386 

387def _review_exceptions(exceptions: Sequence[Mapping[str, Any]]) -> list[str]: 

388 if not exceptions: 388 ↛ 390line 388 didn't jump to line 390 because the condition on line 388 was always true

389 return [] 

390 return [ 

391 "", 

392 "Exceptions in force", 

393 *( 

394 f" {item['exceptionId']} by {item['actorId']} until {item['expiresAt']}: " 

395 f"{short(item['rationale'], 70)}" 

396 for item in exceptions 

397 ), 

398 ] 

399 

400 

401def _review_history(history: Mapping[str, Any]) -> list[str]: 

402 lines = [ 

403 "", 

404 "History: " 

405 f"{history['implementationAttempts']} implementation attempt(s), " 

406 f"{history['verificationAttempts']} verification attempt(s), " 

407 f"{history['automaticCorrections']} automatic correction(s), " 

408 f"{history['requestedChanges']} requested change(s), " 

409 f"{history['providerRetries']} provider retry(ies), " 

410 f"{history['supersededFindings']} superseded finding(s)", 

411 ] 

412 if history["passedAfterRetry"]: 412 ↛ 413line 412 didn't jump to line 413 because the condition on line 412 was never true

413 lines.append( 

414 " passed only after an earlier failure on this digest: " 

415 + ", ".join(history["passedAfterRetry"]) 

416 ) 

417 return lines 

418 

419 

420def _review_delta_changes(delta: Mapping[str, Any]) -> list[str]: 

421 """The files and findings that changed since the last decision.""" 

422 lines: list[str] = [] 

423 for key in ("added", "changed", "removed"): 

424 if delta["files"][key]: 

425 lines.append(f" files {key}: {', '.join(delta['files'][key])}") 

426 for key, title in (("findingsResolved", "resolved"), ("findingsNew", "new")): 

427 for item in delta[key]: 

428 lines.append(f" {title}: {item['ruleId']} {item['location']}") 

429 return lines 

430 

431 

432def _review_delta(delta: Mapping[str, Any] | None) -> list[str]: 

433 if not delta: 433 ↛ 435line 433 didn't jump to line 435 because the condition on line 433 was always true

434 return [] 

435 since = delta["sinceDecision"] 

436 lines = [ 

437 "", 

438 f"Since the last decision ({since['decision']} by {since['actorId']} on " 

439 f"{since['changeSetDigest']})", 

440 ] 

441 if delta.get("unchanged"): 

442 lines.append(" the ChangeSet is the one that decision was bound to") 

443 else: 

444 lines.extend(_review_delta_changes(delta)) 

445 return lines 

446 

447 

448def _review_provenance(provenance: Mapping[str, Any] | None) -> list[str]: 

449 if not provenance: 449 ↛ 450line 449 didn't jump to line 450 because the condition on line 449 was never true

450 return [] 

451 return [ 

452 "", 

453 f"Provenance: {provenance['agentFiles']} file(s) written by an agent invocation, " 

454 f"{provenance['outOfBandFiles']} changed out of band", 

455 *(f" out of band: {path}" for path in provenance["outOfBandPaths"]), 

456 ] 

457 

458 

459def _review_self_report(report: Mapping[str, Any]) -> list[str]: 

460 return [ 

461 "", 

462 f"Agent self-report (REPORTED, not verified) of {report['invocationId']}", 

463 *(f" assumption: {item}" for item in report["assumptions"]), 

464 *( 

465 f" low confidence: {item.get('path') or '-'}: {item['description']}" 

466 for item in report["lowConfidenceAreas"] 

467 ), 

468 *( 

469 f" unrequested change: {item.get('path') or '-'}: {item['description']}" 

470 for item in report["unrequestedChanges"] 

471 ), 

472 *(f" problem: {item}" for item in report["problems"]), 

473 ] 

474 

475 

476def _review(brief: Mapping[str, Any]) -> list[str]: 

477 lines = _review_asked(brief) 

478 changed = brief["changed"] 

479 lines.extend(_review_changed(changed)) 

480 lines.extend(_review_gate(brief.get("gate"))) 

481 lines.extend(_review_risks(brief.get("risks", []))) 

482 lines.extend(_review_verified(brief["verified"])) 

483 lines.extend(_review_not_verified(brief)) 

484 lines.extend(_review_exceptions(brief.get("exceptions") or [])) 

485 lines.extend(_review_history(brief["history"])) 

486 lines.extend(_review_delta(brief.get("delta"))) 

487 lines.extend(_review_provenance(brief.get("provenance"))) 

488 for report in brief.get("selfReports") or []: 488 ↛ 489line 488 didn't jump to line 489 because the loop on line 488 never started

489 lines.extend(_review_self_report(report)) 

490 lines.extend(_ladder_sections(brief)) 

491 if brief.get("next"): 491 ↛ 493line 491 didn't jump to line 493 because the condition on line 491 was always true

492 lines.extend(["", _NEXT_HEADING, *(f" {step}" for step in brief["next"])]) 

493 if changed.get("diff"): 493 ↛ 494line 493 didn't jump to line 494 because the condition on line 493 was never true

494 lines.extend(["", "Diff", changed["diff"]]) 

495 return lines 

496 

497 

498def _ladder_sections(brief: Mapping[str, Any]) -> list[str]: 

499 """Certification, preflight, deferred items, checklist, contract and interruptions (#55).""" 

500 return [ 

501 *_certification_lines(brief.get("certification")), 

502 *_preflight_lines(brief.get("preflight")), 

503 *_deferred_lines(brief.get("deferred") or []), 

504 *_checklist_lines(brief.get("checklist") or []), 

505 *_contract_lines(brief.get("contract")), 

506 *_interruption_lines(brief.get("interruptions")), 

507 ] 

508 

509 

510def _certification_lines(certification: Mapping[str, Any] | None) -> list[str]: 

511 if not certification: 511 ↛ 513line 511 didn't jump to line 513 because the condition on line 511 was always true

512 return [] 

513 lines = ["", f"Certification {certification['status']} ({certification['trigger']})"] 

514 for item in certification["criteria"]: 

515 declared = "" if item["declared"] else " (default level)" 

516 lines.append( 

517 f" {item['status']:<14} {item['criterionId']}: requires {item['required']}" 

518 f"{declared}, reached {item['achieved'] or 'no rung'}" 

519 ) 

520 return lines 

521 

522 

523def _preflight_lines(preflight: Mapping[str, Any] | None) -> list[str]: 

524 if not preflight: 524 ↛ 526line 524 didn't jump to line 526 because the condition on line 524 was always true

525 return [] 

526 lines = ["", f"Preflight {preflight['status']}"] 

527 lines.extend(f" - {short(reason, 100)}" for reason in preflight.get("reasons") or []) 

528 decision = preflight.get("decision") 

529 if decision: 

530 lines.append( 

531 f" continued uncertified by {decision['actorId']}: {short(decision['rationale'], 70)}" 

532 ) 

533 return lines 

534 

535 

536def _deferred_lines(deferred: Sequence[Mapping[str, Any]]) -> list[str]: 

537 if not deferred: 537 ↛ 539line 537 didn't jump to line 539 because the condition on line 537 was always true

538 return [] 

539 return [ 

540 "", 

541 "Deferred verification", 

542 *( 

543 f" {item['status']:<8} {item['itemId']} ({short(item['where'], 40)}), expires " 

544 f"{item['expiresAt'][:19]}" 

545 for item in deferred 

546 ), 

547 ] 

548 

549 

550def _checklist_lines(checklist: Sequence[Mapping[str, Any]]) -> list[str]: 

551 if not checklist: 551 ↛ 553line 551 didn't jump to line 553 because the condition on line 551 was always true

552 return [] 

553 lines = ["", "Checklist (ticked by the person who decides)"] 

554 for item in checklist: 

555 mark = "x" if item["checked"] else " " 

556 files = f" [{', '.join(item['attachments'])}]" if item["attachments"] else "" 

557 lines.append(f" [{mark}] {item['itemId']}: {short(item['text'], 80)}{files}") 

558 return lines 

559 

560 

561def _contract_lines(contract: Mapping[str, Any] | None) -> list[str]: 

562 if not contract: 562 ↛ 564line 562 didn't jump to line 564 because the condition on line 562 was always true

563 return [] 

564 state = "confirmed" if contract.get("confirmed") else "not confirmed" 

565 lines = ["", f"Operational contract ({state}, {contract['digest'][:19]})"] 

566 for item in contract.get("items", []): 

567 value = item["value"] 

568 shown = ", ".join(map(str, value)) if isinstance(value, list) else _scalar(value) 

569 lines.append(f" {label(item['field']):<20} {short(shown, 70)} ({item['source']})") 

570 lines.extend(_assumption_lines(contract.get("assumptions"))) 

571 return lines 

572 

573 

574def _assumption_lines(assumptions: Any) -> list[str]: 

575 """The points the agent review left open, recorded as assumptions (#79).""" 

576 return [ 

577 f" assumption {item.get('assumptionId')}: {short(str(item.get('question')), 90)}" 

578 for item in assumptions or [] 

579 if isinstance(item, Mapping) 

580 ] 

581 

582 

583def _interruption_lines(interruptions: Mapping[str, Any] | None) -> list[str]: 

584 if not interruptions: 584 ↛ 586line 584 didn't jump to line 586 because the condition on line 584 was always true

585 return [] 

586 budget = "over budget" if interruptions["overBudget"] else "within budget" 

587 return [ 

588 "", 

589 f"Interruptions: {interruptions['count']} of a target of " 

590 f"{interruptions['target']} ({budget})", 

591 *( 

592 f" stop: {item['condition']} - {short(item.get('detail') or '', 70)}" 

593 for item in interruptions.get("stops") or [] 

594 ), 

595 ] 

596 

597 

598def _exceptions(items: Sequence[Mapping[str, Any]]) -> list[str]: 

599 if not items: 599 ↛ 600line 599 didn't jump to line 600 because the condition on line 599 was never true

600 return ["No exceptions recorded."] 

601 rows = [ 

602 [ 

603 str(item["exceptionId"]), 

604 str(item["status"]), 

605 str(item["expiresAt"])[:19], 

606 str(item["actorId"]), 

607 str(len(item["scope"])), 

608 str(len(item["appliedIn"])), 

609 short(item.get("followUp") or "-", 30), 

610 ] 

611 for item in items 

612 ] 

613 return table(rows, ["EXCEPTION", "STATUS", "EXPIRES", "BY", "SCOPES", "USED IN", "FOLLOW-UP"]) 

614 

615 

616def _decision_detail(item: Mapping[str, Any]) -> str: 

617 detail = f"gate {item['gateStatus']}, {item['blockingFindings']} blocking finding(s)" 

618 risks = item.get("acknowledgeRisks") or [] 

619 if risks: 

620 detail += f", acknowledge risk(s): {', '.join(risks)}" 

621 return detail 

622 

623 

624def _deferred_detail(item: Mapping[str, Any]) -> str: 

625 warning = f", {item['warning']}" if item.get("warning") else "" 

626 return f"{item['itemId']} ({short(item['where'], 30)}) {item['status']}{warning}" 

627 

628 

629_INBOX_DETAILS: dict[str, Callable[[Mapping[str, Any]], str]] = { 

630 "decision": _decision_detail, 

631 "deferred": _deferred_detail, 

632 "preflight": lambda _item: "preflight UNAVAILABLE: continue uncertified or fix the environment", 

633 "clarification": lambda item: f"{item['questions']} question(s)", 

634} 

635 

636 

637def _inbox_detail(item: Mapping[str, Any]) -> str: 

638 """What the entry waits on; the waits before DECISION of #73 carry their own summary.""" 

639 detail = _INBOX_DETAILS.get(str(item["kind"])) 

640 return detail(item) if detail else str(item.get("summary") or "") 

641 

642 

643def _inbox(items: Sequence[Mapping[str, Any]]) -> list[str]: 

644 if not items: 644 ↛ 645line 644 didn't jump to line 645 because the condition on line 644 was never true

645 return ["Nothing waits for a person."] 

646 rows = [ 

647 [ 

648 str(item["kind"]), 

649 str(item["executionId"]), 

650 short(item["taskTitle"], 36), 

651 _inbox_detail(item), 

652 f"{item['waitingHours']} h", 

653 str(item["next"]), 

654 ] 

655 for item in items 

656 ] 

657 return table(rows, ["WAITS FOR", "RUN", "TASK", "STATE", "WAITING", "NEXT"]) 

658 

659 

660def _health(value: Mapping[str, Any]) -> list[str]: 

661 lines = [ 

662 f"{value['runs']} run(s), {value['correctedRuns']} with corrections; outcomes: " 

663 + ", ".join(f"{key.lower()} {count}" for key, count in value["outcomes"].items()), 

664 "", 

665 ] 

666 rows = [ 

667 [ 

668 str(item["ruleId"]), 

669 str(item["fired"]), 

670 str(item["runs"]), 

671 str(item["blockedGates"]), 

672 str(item["excepted"]), 

673 str(item["correctedRuns"]), 

674 str(item["rejectedRuns"]), 

675 str(item["runsWithLaterOutcomes"]), 

676 item["signal"] or "-", 

677 ] 

678 for item in value["rules"] 

679 ] 

680 lines.extend( 

681 table( 

682 rows, 

683 [ 

684 "RULE", 

685 "FIRED", 

686 "RUNS", 

687 "BLOCKED", 

688 "EXCEPTED", 

689 "CORRECTED", 

690 "REJECTED", 

691 "OUTCOMES", 

692 "SIGNAL", 

693 ], 

694 ) 

695 if rows 

696 else ["No findings recorded."] 

697 ) 

698 lines.extend(["", "Validators:"]) 

699 lines.extend( 

700 f" {item['validatorId']} ({'mandatory' if item['mandatory'] else 'optional'}): " 

701 f"{item['notPassed']} of {item['results']} result(s) not passed in {item['runs']} run(s)" 

702 for item in value["validators"] 

703 ) 

704 return lines 

705 

706 

707Renderer = Callable[[Any], list[str]] 

708 

709RENDERERS: dict[str, Renderer] = { 

710 "runs": _runs, 

711 "tasks": _tasks, 

712 "findings": _findings, 

713 "execution": _execution, 

714 "status": _status, 

715 "decision": _decision, 

716 "doctor": _doctor, 

717 "init": _init, 

718 "review": _review, 

719 "exceptions": _exceptions, 

720 "inbox": _inbox, 

721 "health": _health, 

722} 

723 

724 

725def register(kind: str, renderer: Renderer) -> None: 

726 RENDERERS[kind] = renderer 

727 

728 

729def render_human(value: object, kind: str | None = None) -> str: 

730 renderer = RENDERERS.get(kind or "") 

731 lines = renderer(value) if renderer else generic(value) 

732 return "\n".join(lines)