Coverage for src/governed_harness/cli/main.py: 71%
767 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 json
4import sys
5import weakref
6from collections.abc import Callable
7from dataclasses import replace
8from datetime import UTC, datetime
9from functools import partial
10from pathlib import Path
11from typing import Any, NoReturn
13import typer
15from governed_harness import __version__
16from governed_harness.application import HarnessApplication, agent_contract
17from governed_harness.application.exceptions import ExceptionOptions
18from governed_harness.application.hints import default_hint
19from governed_harness.application.onboarding import IgnoreFile
20from governed_harness.cli.render import render_human, wants_json
21from governed_harness.domain.enums import (
22 DecisionKind,
23 MemoryLevel,
24 RecommendationDecision,
25 ResultStatus,
26)
27from governed_harness.domain.errors import ConfigurationError, HarnessError, PolicyViolationError
28from governed_harness.orchestration.acceptance_dispute import DisputeDecision
30# Help texts and option names that several commands share.
31_CURRENT_DIRECTORY = "current directory"
32_PROJECT_HELP = "Project directory"
33_TASK_HELP = "Task identifier (taskId)"
34_RATIONALE_HELP = "Justification recorded"
35_CONTINUE_OPTION = "--continue/--no-continue"
36_CONTINUE_HELP = "Resume the run after recording the decision"
37_OUTPUT_HELP = "Write to this file instead of standard output"
39app = typer.Typer(no_args_is_help=True, help="Governed Agent Harness CLI")
40config_app = typer.Typer(help="Configuration commands")
41task_app = typer.Typer(help="Task commands")
42run_app = typer.Typer(help="Execution lifecycle commands")
43gate_app = typer.Typer(help="Human gate commands")
44evidence_app = typer.Typer(help="Evidence commands")
45findings_app = typer.Typer(help="Finding commands")
46memory_app = typer.Typer(help="Governed memory commands")
47recommendation_app = typer.Typer(help="Retrospective recommendation commands")
48plugins_app = typer.Typer(help="Plugin and extension commands")
49benchmark_app = typer.Typer(help="Benchmark commands")
50api_app = typer.Typer(help="Local API and web dashboard")
51artifact_app = typer.Typer(help="Artifact store commands")
52exceptions_app = typer.Typer(help="Exception ledger commands")
53rules_app = typer.Typer(help="Rule and validator health across runs")
54outcome_app = typer.Typer(help="Outcomes after a run (incidents, reverts, hotfixes)")
55plan_app = typer.Typer(help="Decomposition of large tasks into governed sub-tasks")
56acceptance_app = typer.Typer(help="Independent, frozen acceptance tests")
57budget_app = typer.Typer(help="Governed budget of agent calls")
58routing_app = typer.Typer(help="Model and effort routing of agent calls")
59agent_contract_app = typer.Typer(
60 help="The contract between a parent and its agent calls: schemas, validation, scripts, calls"
61)
62verification_app = typer.Typer(
63 help="Verification ladder: plan, preflight, certification and deferred items"
64)
65pr_app = typer.Typer(
66 help="Pull and merge requests on GitHub, GitLab, Bitbucket, Azure DevOps, Gitea"
67)
68standards_app = typer.Typer(help="Language standards packs: cards and tools")
69architecture_app = typer.Typer(help="Architecture: survey, options, ADR and layer rules")
70project_app = typer.Typer(help="What the harness detects about the project")
71mcp_app = typer.Typer(help="Embedded mode: the harness as an MCP server for an agent session")
72app.add_typer(config_app, name="config")
73app.add_typer(task_app, name="task")
74app.add_typer(run_app, name="run")
75app.add_typer(gate_app, name="gate")
76app.add_typer(evidence_app, name="evidence")
77app.add_typer(findings_app, name="findings")
78app.add_typer(memory_app, name="memory")
79app.add_typer(recommendation_app, name="recommendation")
80app.add_typer(plugins_app, name="plugins")
81app.add_typer(benchmark_app, name="benchmark")
82app.add_typer(api_app, name="api")
83app.add_typer(artifact_app, name="artifact")
84app.add_typer(exceptions_app, name="exceptions")
85app.add_typer(rules_app, name="rules")
86app.add_typer(outcome_app, name="outcome")
87app.add_typer(plan_app, name="plan")
88app.add_typer(acceptance_app, name="acceptance")
89app.add_typer(budget_app, name="budget")
90app.add_typer(routing_app, name="routing")
91app.add_typer(agent_contract_app, name="agent-contract")
92app.add_typer(pr_app, name="pr")
93app.add_typer(verification_app, name="verification")
94app.add_typer(standards_app, name="standards")
95app.add_typer(architecture_app, name="architecture")
96app.add_typer(project_app, name="project")
97app.add_typer(mcp_app, name="mcp")
100ACTOR_HELP = (
101 "Identifier of the person acting (recorded, not authenticated). Defaults to the Git user "
102 "under governance.deciderIdentity: git, otherwise human.local. Ids of agents, validators "
103 "and the harness (agent.*, validator.*, harness.*) are refused with exit code 5."
104)
107JSON_OPTION: Any = typer.Option(
108 None,
109 "--json/--no-json",
110 help="Print JSON, or readable text with --no-json (default: JSON unless standard output "
111 "is a terminal)",
112)
114RUN_OPTION: Any = typer.Option(
115 ...,
116 "--run",
117 help="Run (execution) identifier, `latest` or a unique prefix such as run_1a2b",
118)
119RUN_OPTION_LATEST: Any = typer.Option(
120 "latest",
121 "--run",
122 help="Run (execution) identifier, `latest` or a unique prefix such as run_1a2b",
123)
125_OUTPUT: dict[str, bool | None] = {"json": None}
126"""The global --json/--no-json choice of the current invocation (None: decide by terminal)."""
129def _version_callback(value: bool) -> None:
130 if value:
131 typer.echo(f"harness {__version__}")
132 raise typer.Exit()
135@app.callback()
136def root(
137 version: bool = typer.Option(
138 False,
139 "--version",
140 callback=_version_callback,
141 is_eager=True,
142 help="Print the harness version and exit",
143 ),
144 json_output: bool | None = JSON_OPTION,
145) -> None:
146 """Governed Agent Harness CLI. Output is JSON when standard output is not a terminal (or
147 with --json) and readable text on a terminal (or with --no-json)."""
148 _OUTPUT["json"] = json_output
151def _plain(value: object) -> object:
152 if hasattr(value, "model_dump"):
153 return value.model_dump(mode="json", by_alias=True)
154 if isinstance(value, list):
155 return [
156 item.model_dump(mode="json", by_alias=True) if hasattr(item, "model_dump") else item
157 for item in value
158 ]
159 return value
162def _json_wanted(json_output: bool | None = None) -> bool:
163 return wants_json(json_output if json_output is not None else _OUTPUT["json"])
166def _emit(value: object, json_output: bool | None = None, kind: str | None = None) -> None:
167 value = _plain(value)
168 if _json_wanted(json_output):
169 typer.echo(json.dumps(value, indent=2, ensure_ascii=False, default=str))
170 else:
171 typer.echo(render_human(value, kind))
174_ACTING: weakref.WeakSet[HarnessApplication] = weakref.WeakSet()
177def _acting() -> HarnessApplication:
178 """The application for a human act; its notices (for example a Git identity that could
179 not be used) are printed on standard error by ``_call``."""
180 application = HarnessApplication()
181 _ACTING.add(application)
182 return application
185def _flush_notices() -> None:
186 # One application may serve several calls (gate decide resolves the run first), so its
187 # notices are printed and cleared, and it stays registered while it is in use.
188 for application in _ACTING:
189 for notice in application.notices:
190 typer.echo(f"warning: {notice}", err=True)
191 application.notices.clear()
194Hint = Callable[[BaseException], str | None]
197def _report_error(payload: dict[str, Any]) -> None:
198 if wants_json(_OUTPUT["json"], sys.stderr): 198 ↛ 201line 198 didn't jump to line 201 because the condition on line 198 was always true
199 typer.echo(json.dumps(payload, indent=2), err=True)
200 return
201 typer.echo(f"Error: {payload['error']}", err=True)
202 if payload.get("hint"):
203 typer.echo(f"Hint: {payload['hint']}", err=True)
206def _call[T](operation: Callable[[], T], hint: Hint | None = None) -> T:
207 try:
208 return operation()
209 except HarnessError as error:
210 payload: dict[str, Any] = {"status": "ERROR", "error": str(error)}
211 advice = (hint(error) if hint else None) or default_hint(error)
212 if advice:
213 payload["hint"] = advice
214 _report_error(payload)
215 raise typer.Exit(code=error.exit_code) from error
216 except Exception as error:
217 _report_error({"status": "ERROR", "errorType": type(error).__name__, "error": str(error)})
218 raise typer.Exit(code=1) from error
219 finally:
220 _flush_notices()
223def _exit_for_execution(status: ResultStatus, phase: str) -> None:
224 if status is ResultStatus.PASSED:
225 return
226 if status is ResultStatus.CANCELLED: 226 ↛ 227line 226 didn't jump to line 227 because the condition on line 226 was never true
227 raise typer.Exit(code=130)
228 if status is ResultStatus.BLOCKED and phase == "DECISION":
229 raise typer.Exit(code=4)
230 if status in { 230 ↛ 237line 230 didn't jump to line 237 because the condition on line 230 was always true
231 ResultStatus.BLOCKED,
232 ResultStatus.FAILED,
233 ResultStatus.INCONCLUSIVE,
234 ResultStatus.TIMED_OUT,
235 }:
236 raise typer.Exit(code=6)
237 if status is ResultStatus.ERROR:
238 raise typer.Exit(code=1)
239 if status is ResultStatus.INTERRUPTED:
240 raise typer.Exit(code=6)
243@app.command()
244def init(
245 path: Path = typer.Option(
246 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
247 ),
248 force: bool = typer.Option(False, "--force", help="Replace an existing project configuration"),
249 gitignore: bool = typer.Option(
250 True,
251 "--gitignore/--no-gitignore",
252 help="Make Git ignore .harness/ (state, artifacts and copies of the code live there)",
253 ),
254 ignore_file: IgnoreFile = typer.Option(
255 IgnoreFile.EXCLUDE,
256 "--ignore-file",
257 case_sensitive=False,
258 help="Where the .harness/ entry goes: exclude writes the repository's .git/info/exclude, "
259 "so an existing repository's tree stays clean (the .gitignore outside a Git "
260 "repository); gitignore writes the project's .gitignore",
261 ),
262 example_task: bool = typer.Option(
263 True,
264 "--example-task/--no-example-task",
265 help="Write an example task to .harness/task.example.yaml",
266 ),
267 agent_skills: bool = typer.Option(
268 False,
269 "--agent-skills",
270 help="Also write the skill of the governed flow for Claude Code "
271 "(.claude/skills/harness/SKILL.md) and Codex (.codex/skills/harness/SKILL.md)",
272 ),
273 json_output: bool | None = JSON_OPTION,
274) -> None:
275 """Create .harness/project.yaml for a repository, using the detected technology profiles,
276 make Git ignore .harness/ (in .git/info/exclude, so the tree stays clean) and write an
277 example task. Prints the detected profiles and the next commands."""
278 _emit(
279 _call(
280 lambda: HarnessApplication().init(
281 path,
282 force=force,
283 gitignore=gitignore,
284 example_task=example_task,
285 agent_skills=agent_skills,
286 ignore_file=ignore_file,
287 )
288 ),
289 json_output,
290 kind="init",
291 )
294@app.command()
295def inspect(
296 path: Path = typer.Option(
297 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
298 ),
299 json_output: bool | None = JSON_OPTION,
300) -> None:
301 """Detect the technology profiles of a repository (read-only), with confidence and
302 evidence."""
303 _emit(_call(lambda: HarnessApplication().inspect(path)), json_output)
306@app.command()
307def doctor(
308 path: Path | None = typer.Option(
309 None, "--path", help="Also validate the project in this directory"
310 ),
311 install_hooks: bool = typer.Option(
312 False,
313 "--install-hooks",
314 help="Run the hook installation command the project declares "
315 "(environment.gitHooks.install) before the checks",
316 ),
317 json_output: bool | None = JSON_OPTION,
318) -> None:
319 """Check the local environment (Python and Git required; Node.js and npm reported as
320 NOT_APPLICABLE when absent; Git identity reported) and, with --path, the project: its
321 configuration, the agent CLI of the configured provider on PATH, the agent sandbox mechanism,
322 the validators, the baseline commit and whether .harness/ is ignored by Git. Each check that
323 is not PASSED says how to fix it. Exit code 2 when a required check FAILED; a WARNING does
324 not fail."""
325 result = _call(lambda: HarnessApplication().doctor(path, install_hooks=install_hooks))
326 _emit(result, json_output, kind="doctor")
327 if result["status"] != "PASSED":
328 raise typer.Exit(code=2)
331@config_app.command("validate")
332def config_validate(
333 path: Path = typer.Option(
334 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
335 ),
336 json_output: bool | None = JSON_OPTION,
337) -> None:
338 """Validate the project configuration and print the resolved profiles, workflow,
339 validators, capabilities and policies, the settings that are declared but not applied
340 (`declarative`) and a warning for each one the project relies on (`warnings`)."""
341 _emit(_call(lambda: HarnessApplication().validate_config(path)), json_output)
344@config_app.command("lint")
345def config_lint(
346 path: Path = typer.Option(
347 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
348 ),
349 json_output: bool | None = JSON_OPTION,
350) -> None:
351 """Report contradictions between the harness configuration and the agent instruction files
352 (AGENTS.md, CLAUDE.md, .cursorrules, .cursor/rules, .github/copilot-instructions.md): tool
353 versions, coverage thresholds, statements about the tests and instructions to bypass a
354 control (--no-verify, a forced push, git add -A). Each conflict names the source that wins by
355 `instructions.precedence`. Exit 6 when there is any issue."""
356 result = _call(lambda: HarnessApplication().config_lint(path))
357 _emit(result, json_output)
358 if result["status"] != "PASSED":
359 raise typer.Exit(code=6)
362@task_app.command("create")
363def task_create(
364 file: Path = typer.Option(
365 ..., "--file", exists=True, dir_okay=False, help="Task file (YAML or JSON)"
366 ),
367 path: Path = typer.Option(
368 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
369 ),
370 json_output: bool | None = JSON_OPTION,
371) -> None:
372 """Validate a task file (YAML or JSON) and persist it as a versioned task. A task needs
373 at least one acceptance criterion (exit code 2 otherwise), except under
374 `intake.criteriaPolicy: enforce`: there a task without criteria is stored with
375 `criteriaPending: true` and INTENT asks for its criteria (rule C0). Under
376 `governance.pinTaskRevision: true` a task id that has an open run is refused with exit code 5:
377 revise it with `task clarify` during INTENT or use a new id."""
378 _emit(_call(lambda: HarnessApplication().create_task(path, file)), json_output)
381@task_app.command("list")
382def task_list(
383 path: Path = typer.Option(
384 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
385 ),
386 json_output: bool | None = JSON_OPTION,
387) -> None:
388 """List the tasks persisted in the project."""
389 _emit(_call(lambda: HarnessApplication().list_tasks(path)), json_output, kind="tasks")
392@task_app.command("show")
393def task_show(
394 task: str = typer.Option(..., "--task", help=_TASK_HELP),
395 path: Path = typer.Option(
396 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
397 ),
398) -> None:
399 """Show one persisted task."""
400 _emit(_call(lambda: HarnessApplication().get_task(path, task)))
403@task_app.command("questions")
404def task_questions(
405 task: str = typer.Option(..., "--task", help=_TASK_HELP),
406 path: Path = typer.Option(
407 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
408 ),
409) -> None:
410 """Show the clarification questions INTENT asked about a task: the open request (asked
411 about the current revision of the task), every earlier request and the recorded answers."""
412 _emit(_call(lambda: HarnessApplication().list_clarifications(path, task)))
415@task_app.command("clarify")
416def task_clarify(
417 task: str = typer.Option(..., "--task", help=_TASK_HELP),
418 file: Path = typer.Option(
419 ...,
420 "--file",
421 exists=True,
422 dir_okay=False,
423 help="Answers file (YAML or JSON): answers by question id, optional criteria and "
424 "requirement changes",
425 ),
426 actor: str | None = typer.Option(
427 None,
428 "--actor",
429 help=ACTOR_HELP,
430 show_default=False,
431 ),
432 path: Path = typer.Option(
433 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
434 ),
435) -> None:
436 """Answer the open clarification questions of a task and store the revised task. Run
437 `harness run continue` afterwards to assess the revision in INTENT. An unknown question id
438 or an empty answer exits with 2, no open request with 3, and a task with a run past INTENT
439 or an actor id of an agent, validator or the harness with 5."""
440 _emit(
441 _call(lambda: _acting().clarify_task(path, task_id=task, answers_file=file, actor_id=actor))
442 )
445@task_app.command("confirm")
446def task_confirm(
447 task: str = typer.Option(..., "--task", help=_TASK_HELP),
448 digest: str = typer.Option(
449 ..., "--digest", help="Digest of the operational contract shown by task questions"
450 ),
451 actor: str | None = typer.Option(None, "--actor", help=ACTOR_HELP, show_default=False),
452 pre_approve: bool = typer.Option(
453 False,
454 "--pre-approve",
455 help="Under friction.preAuthorization: also approve the run in advance, applied at "
456 "DECISION only if the gate passed, the ChangeSet has no risk factor and the task is size "
457 "S; otherwise you are asked as usual",
458 ),
459 pre_approve_hours: int | None = typer.Option(
460 None,
461 "--pre-approve-hours",
462 min=1,
463 help="Validity of the pre-authorised approval in hours (default "
464 "friction.preAuthorization.defaultHours, at most maxHours)",
465 ),
466 rationale: str = typer.Option(
467 "", "--rationale", help="Why you approve in advance (recorded with --pre-approve)"
468 ),
469 path: Path = typer.Option(
470 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
471 ),
472) -> None:
473 """Confirm the operational contract of a task's current revision, bound to its digest
474 (`intake.operationalContract`). Under `enforce` INTENT waits for it; then `harness run
475 continue`. With --pre-approve the same act records an approval in advance bound to the
476 contract digest and the condition gate passed, no risk factor, size S. A stale digest, a
477 non-human actor or --pre-approve without `friction.preAuthorization.mode: allow` exits 5."""
478 _emit(
479 _call(
480 lambda: _acting().confirm_contract(
481 path,
482 task_id=task,
483 digest=digest,
484 actor_id=actor,
485 pre_approve=pre_approve,
486 hours=pre_approve_hours,
487 rationale=rationale,
488 )
489 )
490 )
493@app.command("do")
494def do(
495 text: str = typer.Argument(..., help="The change to make, in one sentence or more"),
496 criterion: list[str] | None = typer.Option(
497 None,
498 "--criterion",
499 help="An acceptance criterion (repeatable; default: the text itself)",
500 ),
501 owned: list[str] | None = typer.Option(
502 None, "--owned", help="A workspace path the change may touch (repeatable)"
503 ),
504 title: str | None = typer.Option(None, "--title", help="Task title (default: first line)"),
505 provider: str | None = typer.Option(
506 None, "--provider", help="Agent provider id; defaults to the project agentProvider"
507 ),
508 pre_approve: bool = typer.Option(
509 False,
510 "--pre-approve",
511 help="Approve in advance (friction.preAuthorization): applied at DECISION only if the "
512 "gate passed, the ChangeSet has no risk factor and the task is size S",
513 ),
514 pre_approve_hours: int | None = typer.Option(
515 None, "--pre-approve-hours", min=1, help="Validity of the pre-authorised approval"
516 ),
517 actor: str | None = typer.Option(None, "--actor", help=ACTOR_HELP, show_default=False),
518 interactive: bool = typer.Option(
519 True,
520 "--interactive/--no-interactive",
521 help="On a terminal, answer the questions and decide in the same command",
522 ),
523 path: Path = typer.Option(
524 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
525 ),
526 json_output: bool | None = JSON_OPTION,
527) -> None:
528 """Make a change from TEXT in one command: create the task (the text is its intent and,
529 without --criterion, its acceptance criterion), run it and, on a terminal, answer INTENT's
530 questions and show the decision brief and ask for the decision. No task file is needed.
531 Small, risk-free tasks take the fast lane (`friction.fastLane`). With --pre-approve the
532 approval you give now is applied only when the gate passed, there is no risk factor and the
533 task is size S. Exit codes as `run start`: 0 closed, 4 a decision is pending, 6 stopped."""
534 application = _acting()
535 result = _call(
536 lambda: application.do(
537 path,
538 text,
539 criteria=tuple(criterion or ()),
540 owned_paths=tuple(owned or ()),
541 title=title,
542 provider=provider,
543 pre_approve=pre_approve,
544 hours=pre_approve_hours,
545 actor_id=actor,
546 )
547 )
548 run_id = result["run"]["executionId"]
549 task_id = result["task"]["taskId"]
550 terminal = interactive and sys.stdin.isatty() and sys.stdout.isatty()
551 while terminal and result["questions"]:
552 _answer_intent(application, path, run_id, task_id, result)
553 status = ResultStatus(result["run"]["status"])
554 phase = result["run"]["currentPhase"]
555 if terminal and status is ResultStatus.BLOCKED and phase == "DECISION":
556 status, phase = _decide_on_terminal(application, path, run_id, actor, result)
557 elif status is ResultStatus.BLOCKED and phase == "DECISION":
558 result["next"] = f"harness review --run {run_id}; harness gate decide --run {run_id}"
559 elif status is ResultStatus.BLOCKED and phase == "INTENT":
560 result["next"] = f"harness task questions --task {task_id}"
561 _emit(result, json_output)
562 _exit_for_execution(status, phase)
565def _prompt_answers(questions: list[Any]) -> dict[str, str]:
566 """One non-empty answer per question, asked on the terminal."""
567 answers: dict[str, str] = {}
568 for question in questions:
569 answer = ""
570 while not answer.strip():
571 answer = str(typer.prompt(f"{question['questionId']}: {question['text']}"))
572 answers[question["questionId"]] = answer.strip()
573 return answers
576def _answer_intent(
577 application: HarnessApplication,
578 path: Path,
579 run_id: str,
580 task_id: str,
581 result: dict[str, Any],
582) -> None:
583 """``harness do`` on a terminal: answer INTENT's questions, continue the run and update
584 ``result`` with the run and the questions still open."""
585 typer.echo(f"INTENT asks about {task_id}:")
586 answers = _prompt_answers(result["questions"])
587 _call(partial(application.answer_questions, path, task_id=task_id, answers=answers))
588 execution = _call(lambda: application.continue_run(path, run_id))
589 result["run"] = {
590 "executionId": execution.execution_id,
591 "status": execution.status.value,
592 "currentPhase": execution.current_phase.value,
593 "changeSetDigest": execution.change_set_digest,
594 }
595 result["execution"] = execution.model_dump(mode="json", by_alias=True)
596 result["questions"] = (
597 _open_questions(application, path, run_id)
598 if execution.current_phase.value == "INTENT"
599 else []
600 )
603def _decide_on_terminal(
604 application: HarnessApplication,
605 path: Path,
606 run_id: str,
607 actor: str | None,
608 result: dict[str, Any],
609) -> tuple[ResultStatus, str]:
610 """``harness do`` on a terminal at DECISION: show the brief, ask for the decision and
611 record it; ``result`` gets the decision and the execution."""
612 decision, digest, reason = _interactive_decision(application, path, run_id, None, None, None)
613 checked = _interactive_checklist(application, path, run_id, [])
614 record, execution = _call(
615 lambda: application.decide_gate(
616 path,
617 execution_id=run_id,
618 decision=decision,
619 change_set_digest=digest,
620 actor_id=actor,
621 rationale=reason,
622 checked_items=tuple(checked),
623 ),
624 hint=_decide_hint(application, path, run_id),
625 )
626 result["decision"] = record.model_dump(mode="json", by_alias=True)
627 result["execution"] = execution.model_dump(mode="json", by_alias=True)
628 return execution.status, execution.current_phase.value
631def _open_questions(application: HarnessApplication, path: Path, run_id: str) -> list[Any]:
632 status = _call(lambda: application.status(path, run_id))
633 task_id = status["execution"]["taskId"]
634 request = _call(lambda: application.list_clarifications(path, task_id))["openRequest"]
635 if not request or status["execution"]["status"] != "BLOCKED":
636 return []
637 return [
638 {"questionId": item["questionId"], "text": item["text"]}
639 for item in request.get("questions") or []
640 ]
643@run_app.command("start")
644def run_start(
645 task: str = typer.Option(..., "--task", help=_TASK_HELP),
646 provider: str | None = typer.Option(
647 None, "--provider", help="Agent provider id; defaults to the project agentProvider"
648 ),
649 isolate: str | None = typer.Option(
650 None,
651 "--isolate",
652 help="worktree: run in a Git worktree of its own on a new branch from the updated base "
653 "branch; none: in place (default: workspace.isolation.mode)",
654 ),
655 path: Path = typer.Option(
656 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
657 ),
658 json_output: bool | None = JSON_OPTION,
659) -> None:
660 """Create a run for a task and execute the normative phases until a stop condition. Exit
661 code 4 means the automated phases finished and a human decision is pending; 6 means a
662 validation, policy or blocking condition stopped the run. With --isolate worktree a branch or
663 worktree directory that already exists stops the run (exit 6); nothing is reset or deleted."""
664 execution = _call(lambda: HarnessApplication().start_run(path, task, provider, isolate=isolate))
665 _emit(execution, json_output, kind="execution")
666 _exit_for_execution(execution.status, execution.current_phase.value)
669@run_app.command("continue")
670def run_continue(
671 run: str = RUN_OPTION,
672 path: Path = typer.Option(
673 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
674 ),
675 json_output: bool | None = JSON_OPTION,
676) -> None:
677 """Resume a run from its persisted state, for example after fixing the environment or after
678 REQUEST_CHANGES."""
679 execution = _call(lambda: HarnessApplication().continue_run(path, run))
680 _emit(execution, json_output, kind="execution")
681 _exit_for_execution(execution.status, execution.current_phase.value)
684@run_app.command("cancel")
685def run_cancel(
686 run: str = RUN_OPTION,
687 actor: str | None = typer.Option(
688 None,
689 "--actor",
690 help=ACTOR_HELP,
691 show_default=False,
692 ),
693 path: Path = typer.Option(
694 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
695 ),
696) -> None:
697 """Cancel a run and terminate its active process group. The cancellation is recorded as an
698 event."""
699 execution = _call(lambda: _acting().cancel_run(path, run, actor))
700 _emit(execution, kind="execution")
703@run_app.command("cleanup")
704def run_cleanup(
705 run: str = RUN_OPTION,
706 path: Path = typer.Option(
707 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
708 ),
709) -> None:
710 """Remove the worktree of a finished isolated run (`run start --isolate worktree`). Only a
711 worktree the harness created and without uncommitted changes is removed; its branch is
712 kept. Anything else exits 5."""
713 _emit(_call(lambda: HarnessApplication().cleanup_run(path, run)))
716@verification_app.command("show")
717def verification_show(
718 run: str = RUN_OPTION_LATEST,
719 path: Path = typer.Option(
720 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
721 ),
722) -> None:
723 """Show the verification plan of a run (the rung each criterion requires, the rungs this
724 environment reaches and why), its preflight (READY, PARTIAL or UNAVAILABLE), the
725 certification of its ChangeSet, the deferred items and the manual checklist."""
726 _emit(_call(lambda: HarnessApplication().verification(path, run)))
729@verification_app.command("decide")
730def verification_decide(
731 run: str = RUN_OPTION,
732 continue_uncertified: bool = typer.Option(
733 False,
734 "--continue-uncertified",
735 help="Continue without the rungs the preflight found unreachable (required)",
736 ),
737 rationale: str = typer.Option(..., "--rationale", help=_RATIONALE_HELP),
738 actor: str | None = typer.Option(None, "--actor", help=ACTOR_HELP, show_default=False),
739 continue_after: bool = typer.Option(True, _CONTINUE_OPTION, help=_CONTINUE_HELP),
740 path: Path = typer.Option(
741 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
742 ),
743) -> None:
744 """Decide on a run whose preflight is UNAVAILABLE: continue it uncertified for what this
745 environment cannot verify (those criteria end WAIVED, never certified; the unavailable probes
746 are not run). Recorded on the run with the person and the rationale. A run that does not
747 wait on such a preflight, or a non-human actor, exits 5."""
748 if not continue_uncertified:
749 _report_error(
750 {
751 "status": "ERROR",
752 "error": "--continue-uncertified is required",
753 "hint": "Or fix the environment and run harness run continue.",
754 }
755 )
756 raise typer.Exit(code=2)
757 result = _call(
758 lambda: _acting().decide_verification(
759 path,
760 execution_id=run,
761 rationale=rationale,
762 actor_id=actor,
763 continue_after=continue_after,
764 )
765 )
766 _emit(result)
767 execution = result.get("execution")
768 if execution:
769 _exit_for_execution(ResultStatus(execution["status"]), execution["currentPhase"])
772@plan_app.command("show")
773def plan_show(
774 run: str = RUN_OPTION,
775 path: Path = typer.Option(
776 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
777 ),
778) -> None:
779 """Show the decomposition PLANNING proposed for a run (`planning.decomposition`), its
780 digest, its status and the sub-tasks completed so far."""
781 _emit(_call(lambda: HarnessApplication().plan(path, run)), kind="plan")
784@plan_app.command("decide")
785def plan_decide(
786 run: str = RUN_OPTION,
787 decision: DecisionKind = typer.Option(
788 ..., "--decision", case_sensitive=False, help="APPROVE or REJECT"
789 ),
790 digest: str = typer.Option(
791 ..., "--digest", help="Digest of the proposed plan shown by plan show"
792 ),
793 rationale: str = typer.Option(..., "--rationale", help=_RATIONALE_HELP),
794 actor: str | None = typer.Option(None, "--actor", help=ACTOR_HELP, show_default=False),
795 continue_after: bool = typer.Option(True, _CONTINUE_OPTION, help=_CONTINUE_HELP),
796 path: Path = typer.Option(
797 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
798 ),
799) -> None:
800 """Approve or reject the proposed decomposition, bound to its digest. APPROVE runs the
801 sub-tasks in order, each with its own verification and gate; REJECT keeps the task whole.
802 A stale digest, a non-human actor or a decision other than APPROVE or REJECT exits 5. An
803 APPROVE with --no-continue exits 0 once it is recorded, as gate decide does."""
804 result = _call(
805 lambda: _acting().decide_plan(
806 path,
807 execution_id=run,
808 decision=decision,
809 digest=digest,
810 rationale=rationale,
811 actor_id=actor,
812 continue_after=continue_after,
813 )
814 )
815 _emit(result, kind="plan")
816 execution = result.get("execution")
817 if execution and (continue_after or decision is not DecisionKind.APPROVE):
818 # An APPROVE with --no-continue does not resume the run: the decision is recorded and
819 # the run still shows the wait it was in, which is not a failure of this command (#83).
820 # A REJECT ends the run (exit 6), as gate decide REJECT does.
821 _exit_for_execution(ResultStatus(execution["status"]), execution["currentPhase"])
824@routing_app.command("calibrate")
825def routing_calibrate(
826 path: Path = typer.Option(
827 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
828 ),
829) -> None:
830 """Report the cost per approved task of every routing decision recorded in the project
831 (`agentRouting`), by provider family, call kind, task size, model and effort, and suggest
832 the cheapest implement rung per size among groups with at least two approved runs. Nothing
833 is applied: a person edits `agentRouting.tables`."""
834 _emit(_call(lambda: HarnessApplication().routing_calibration(path)), kind="routing")
837@agent_contract_app.command("schema")
838def agent_contract_schema(
839 contract: str = typer.Argument(..., help="request, response or script"),
840) -> None:
841 """Print the JSON Schema of the request contract (what a parent sends an agent call), of
842 the response contract (what the parent receives) or of a script contract."""
843 _emit(_call(lambda: agent_contract.contract_schema(contract)))
846@agent_contract_app.command("validate")
847def agent_contract_validate(
848 document: str = typer.Argument(..., help="request, response, script or output"),
849 file: Path = typer.Argument(..., help="The JSON file to validate"),
850 kind: str | None = typer.Option(
851 None, "--kind", help="Call kind whose limits `output` is checked against"
852 ),
853) -> None:
854 """Validate a JSON file against a contract; `output` is the JSON an agent prints, checked
855 against the limits of its call kind. Exit 0 when it keeps the contract, 6 when it does not
856 (the violation is printed)."""
857 result = _call(lambda: agent_contract.validate_document(document, file, kind))
858 _emit(result)
859 if not result["valid"]:
860 raise typer.Exit(code=6)
863@agent_contract_app.command("scripts")
864def agent_contract_scripts(
865 script: str | None = typer.Argument(None, help="A script id, such as harness.check"),
866 path: Path = typer.Option(
867 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
868 ),
869) -> None:
870 """List the scripts and commands agents may call as black boxes, or show the contract
871 (invocation, inputs, outputs, errors) of one."""
872 _emit(_call(lambda: agent_contract.script_contracts(path, script)))
875@agent_contract_app.command("calls")
876def agent_contract_calls(
877 run: str = RUN_OPTION,
878 kind: str | None = typer.Option(None, "--kind", help="Show one call kind"),
879 iteration: int | None = typer.Option(None, "--iteration", help="Show one iteration"),
880 path: Path = typer.Option(
881 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
882 ),
883) -> None:
884 """Show the agent calls of a run, the iterations each agent used against its cap and, with
885 --kind (and --iteration), exactly what was sent, what the parent received, and whether the
886 stored request matches its digest and the context the contract allowed."""
887 _emit(_call(lambda: HarnessApplication().agent_calls(path, run, kind, iteration)))
890@budget_app.command("show")
891def budget_show(
892 run: str = RUN_OPTION,
893 path: Path = typer.Option(
894 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
895 ),
896) -> None:
897 """Show the usage of a run and of its task (reported tokens and cost, measured wall time of
898 the agent calls) against the `budget` limits, the limits a person raised and what remains."""
899 _emit(_call(lambda: HarnessApplication().budget(path, run)), kind="budget")
902@budget_app.command("raise")
903def budget_raise(
904 run: str = RUN_OPTION,
905 scope: str = typer.Option(..., "--scope", help="call, task or run"),
906 metric: str = typer.Option(..., "--metric", help="costUsd, tokens or wallSeconds"),
907 limit: float = typer.Option(..., "--to", help="The new limit; it must be above the current"),
908 rationale: str = typer.Option(..., "--rationale", help=_RATIONALE_HELP),
909 actor: str | None = typer.Option(None, "--actor", help=ACTOR_HELP, show_default=False),
910 path: Path = typer.Option(
911 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
912 ),
913) -> None:
914 """Raise a budget limit of a run blocked with budget.exceeded; the raise is recorded on the
915 run's event chain with the person and the rationale, then `harness run continue` resumes the
916 run. A non-human actor, a lower limit or a missing rationale exits 5, with a hint that names
917 `harness budget show` and the command to retry."""
918 _emit(
919 _call(
920 lambda: _acting().raise_budget(
921 path,
922 execution_id=run,
923 scope=scope,
924 metric=metric,
925 limit=limit,
926 rationale=rationale,
927 actor_id=actor,
928 ),
929 hint=_budget_raise_hint(run, scope, metric),
930 ),
931 kind="budget",
932 )
935def _budget_raise_hint(run: str, scope: str, metric: str) -> Hint:
936 """The next step of a refused raise (#157): the limits to read and the command to retry."""
938 def hint(error: BaseException) -> str | None:
939 if not isinstance(error, PolicyViolationError): 939 ↛ 940line 939 didn't jump to line 940 because the condition on line 939 was never true
940 return None
941 return (
942 f"`harness budget show --run {run}` shows the usage and the current limits. A person "
943 "raises a limit above the current one with a rationale: "
944 f"`harness budget raise --run {run} --scope {scope} --metric {metric} --to <limit> "
945 f'--rationale "..."`, then `harness run continue --run {run}`.'
946 )
948 return hint
951@acceptance_app.command("show")
952def acceptance_show(
953 run: str = RUN_OPTION,
954 path: Path = typer.Option(
955 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
956 ),
957) -> None:
958 """Show the acceptance tests proposed for a run (`verification.acceptanceTests`), their
959 digest, their status and, once approved, the frozen files and their digests."""
960 _emit(_call(lambda: HarnessApplication().acceptance(path, run)), kind="acceptance")
963@acceptance_app.command("decide")
964def acceptance_decide(
965 run: str = RUN_OPTION,
966 decision: DecisionKind = typer.Option(
967 ..., "--decision", case_sensitive=False, help="APPROVE or REJECT"
968 ),
969 digest: str = typer.Option(..., "--digest", help="Digest shown by acceptance show"),
970 rationale: str = typer.Option(..., "--rationale", help=_RATIONALE_HELP),
971 actor: str | None = typer.Option(None, "--actor", help=ACTOR_HELP, show_default=False),
972 continue_after: bool = typer.Option(True, _CONTINUE_OPTION, help=_CONTINUE_HELP),
973 path: Path = typer.Option(
974 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
975 ),
976) -> None:
977 """Approve or reject the proposed acceptance tests, bound to their digest. APPROVE writes
978 and freezes them, runs them once on the workspace before the change and resumes the run;
979 every later VERIFICATION checks that they are unchanged and pass. A stale digest or a
980 non-human actor exits 5."""
981 result = _call(
982 lambda: _acting().decide_acceptance(
983 path,
984 execution_id=run,
985 decision=decision,
986 digest=digest,
987 rationale=rationale,
988 actor_id=actor,
989 continue_after=continue_after,
990 )
991 )
992 _emit(result, kind="acceptance")
993 execution = result.get("execution")
994 if execution:
995 _exit_for_execution(ResultStatus(execution["status"]), execution["currentPhase"])
998@acceptance_app.command("dispute")
999def acceptance_dispute(
1000 run: str = RUN_OPTION,
1001 decision: DisputeDecision = typer.Option(
1002 ..., "--decision", case_sensitive=False, help="UPHOLD or REVISE"
1003 ),
1004 digest: str = typer.Option(..., "--digest", help="Digest of the dispute (harness inbox)"),
1005 rationale: str = typer.Option(..., "--rationale", help=_RATIONALE_HELP),
1006 actor: str | None = typer.Option(None, "--actor", help=ACTOR_HELP, show_default=False),
1007 continue_after: bool = typer.Option(True, _CONTINUE_OPTION, help=_CONTINUE_HELP),
1008 path: Path = typer.Option(
1009 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1010 ),
1011) -> None:
1012 """Decide a dispute of the frozen acceptance tests
1013 (`verification.acceptanceTests.disputes`): a run whose VERIFICATION failed only on those
1014 tests, after an implementation whose self-report says a test is wrong, waits for a person
1015 (kind acceptance-dispute in `harness inbox`; `harness acceptance show` lists the disputed
1016 tests and the reasons). UPHOLD keeps the tests: the run verifies again and goes on to its
1017 correction cycles or fails, as without the dispute. REVISE removes the frozen files and
1018 returns the run to SPECIFICATION, where new tests are proposed and wait for `harness
1019 acceptance decide`; once approved and frozen the run verifies the same change again. A
1020 stale digest or a non-human actor exits 5."""
1021 result = _call(
1022 lambda: _acting().decide_acceptance_dispute(
1023 path,
1024 execution_id=run,
1025 decision=decision,
1026 digest=digest,
1027 rationale=rationale,
1028 actor_id=actor,
1029 continue_after=continue_after,
1030 )
1031 )
1032 _emit(result, kind="acceptance")
1033 execution = result.get("execution")
1034 if execution:
1035 _exit_for_execution(ResultStatus(execution["status"]), execution["currentPhase"])
1038@app.command("check")
1039def check(
1040 run: str | None = typer.Option(
1041 None,
1042 "--run",
1043 help="Run whose task and baseline the diff checks use (default: the latest run that "
1044 "wrote a check state)",
1045 ),
1046 path: Path = typer.Option(
1047 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1048 ),
1049 json_output: bool | None = JSON_OPTION,
1050) -> None:
1051 """Run the validators of the gate and the enabled diff checks on the workspace, without
1052 recording anything (`runtime.gateContract`). The agent can run it before it finishes; the
1053 implement request carries the exact command. Exit 0 when every mandatory validator passes
1054 and no enforced check reports a blocking problem, 6 otherwise."""
1055 result = _call(lambda: HarnessApplication().check(path, run))
1056 _emit(result, json_output, kind="check")
1057 if result["status"] != "PASSED":
1058 raise typer.Exit(code=6)
1061@run_app.command("quarantine")
1062def run_quarantine(
1063 run: str = RUN_OPTION,
1064 actor: str | None = typer.Option(
1065 None,
1066 "--actor",
1067 help=ACTOR_HELP,
1068 show_default=False,
1069 ),
1070 path: Path = typer.Option(
1071 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1072 ),
1073) -> None:
1074 """Keep the changes of a run that stopped without approval as a quarantined patch and
1075 restore the workspace to its baseline (`governance.stopTheLine`). This releases a line
1076 blocked by `stopTheLine: block`. A run that is closed or still open for a decision is
1077 refused (exit 5)."""
1078 _emit(_call(lambda: _acting().quarantine_run(path, run, actor)), kind="quarantine")
1081@run_app.command("list")
1082def run_list(
1083 path: Path = typer.Option(
1084 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1085 ),
1086) -> None:
1087 """List the runs of the project, newest first."""
1088 _emit(_call(lambda: HarnessApplication().list_runs(path)), kind="runs")
1091@app.command()
1092def status(
1093 run: str = RUN_OPTION_LATEST,
1094 path: Path = typer.Option(
1095 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1096 ),
1097 json_output: bool | None = JSON_OPTION,
1098) -> None:
1099 """Show the full status projection of a run: phases, validations, findings, gate, human
1100 decision, event-chain check and metrics."""
1101 _emit(_call(lambda: HarnessApplication().status(path, run)), json_output, kind="status")
1104@app.command()
1105def trace(
1106 run: str = RUN_OPTION_LATEST,
1107 format: str = typer.Option(
1108 "markdown", "--format", help="markdown, json, jsonl, sarif or codequality"
1109 ),
1110 output: Path | None = typer.Option(None, "--output", help=_OUTPUT_HELP),
1111 path: Path = typer.Option(
1112 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1113 ),
1114) -> None:
1115 """Export the trace of a run as Markdown, JSON, JSONL, SARIF or a GitLab Code Quality
1116 report (codequality: the findings, with the same fingerprints as SARIF). Under
1117 `governance.verifyRecords: true` the run is verified first (as `harness verify`) and a run
1118 that does not verify is not exported (exit code 6)."""
1119 data = _call(lambda: HarnessApplication().trace(path, run, format))
1120 if output: 1120 ↛ 1121line 1120 didn't jump to line 1121 because the condition on line 1120 was never true
1121 output.parent.mkdir(parents=True, exist_ok=True)
1122 output.write_bytes(data)
1123 typer.echo(str(output))
1124 else:
1125 typer.echo(data.decode("utf-8", "replace"), nl=False)
1128@app.command()
1129def verify(
1130 run: str | None = typer.Option(
1131 None, "--run", help="Run (execution) identifier; without it, every run of the workspace"
1132 ),
1133 bundle: Path | None = typer.Option(
1134 None,
1135 "--bundle",
1136 dir_okay=False,
1137 help="Verify a portable evidence bundle instead (no workspace needed)",
1138 ),
1139 path: Path = typer.Option(
1140 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1141 ),
1142) -> None:
1143 """Verify the record of a run (or of every run): the event chain, the head of the chain
1144 against its anchor outside .harness (`governance.chainAnchor`), every record that has an
1145 event against that event, the execution's pointers and every referenced artifact against its
1146 digest. Prints a report and never repairs anything. With --bundle, verify an evidence bundle
1147 of `harness export` instead: its entries against the manifest, the event chain, the artifacts
1148 and the decision records. Exit code 0 when everything verifies, 6 when any check fails (the
1149 report's `hint` then names the next commands for each run that does not verify), 3 for an
1150 unknown run or bundle."""
1151 if bundle is not None:
1152 if run is not None:
1153 _report_error({"status": "ERROR", "error": "use --run or --bundle, not both"})
1154 raise typer.Exit(code=2)
1155 report = _call(lambda: HarnessApplication.verify_bundle(bundle))
1156 else:
1157 report = _call(lambda: HarnessApplication().verify(path, run))
1158 _emit(report)
1159 if not report["valid"]:
1160 raise typer.Exit(code=6)
1163@app.command()
1164def export(
1165 bundle: Path = typer.Option(
1166 ..., "--bundle", dir_okay=False, help="Write the portable evidence bundle (tar.gz) here"
1167 ),
1168 run: str = RUN_OPTION_LATEST,
1169 path: Path = typer.Option(
1170 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1171 ),
1172) -> None:
1173 """Export a run as a portable evidence bundle: its event chain, records, every artifact they
1174 reference and a manifest with the digest of each entry. `harness verify --bundle` and
1175 `harness verify-approval --bundle` check it without the workspace. A run whose event chain
1176 does not verify is not exported (exit code 5; 6 under `governance.verifyRecords` when the
1177 record does not verify)."""
1178 _emit(_call(lambda: HarnessApplication().export_bundle(path, run, bundle)))
1181@app.command("verify-approval")
1182def verify_approval(
1183 base: str = typer.Option(
1184 ..., "--base", help="Revision the change starts from (the pull request base)"
1185 ),
1186 head: str = typer.Option("HEAD", "--head", help="Revision to verify (the merged tree)"),
1187 bundle: list[Path] | None = typer.Option(
1188 None, "--bundle", help="Evidence bundle with the approval (repeatable)"
1189 ),
1190 workspace: bool = typer.Option(
1191 True,
1192 "--workspace/--no-workspace",
1193 help="Also look for the approval in the workspace's .harness/state.db",
1194 ),
1195 path: Path = typer.Option(
1196 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help="Repository directory"
1197 ),
1198) -> None:
1199 """Check in CI that the range --base..--head is a ChangeSet a person approved: recompute its
1200 ChangeSet digest from the two revisions and require an unexpired APPROVE or
1201 APPROVE_EXCEPTION bound to that digest in a bundle (or the workspace record). Any other
1202 change in the range fails. Exit code 0 when it passes, 5 when no approval matches."""
1203 report = _call(
1204 lambda: HarnessApplication.verify_approval(
1205 path, base=base, head=head, bundles=tuple(bundle or ()), use_workspace=workspace
1206 )
1207 )
1208 _emit(report)
1209 if report["status"] != "PASSED":
1210 raise typer.Exit(code=5)
1213@pr_app.command("publish")
1214def pr_publish(
1215 pull_request: int = typer.Option(..., "--pr", min=1, help="Pull request number"),
1216 run: str = RUN_OPTION_LATEST,
1217 repository: str | None = typer.Option(
1218 None, "--repository", help="owner/name (default: delivery.publisher or the origin remote)"
1219 ),
1220 transport: str | None = typer.Option(
1221 None,
1222 "--transport",
1223 help="gh (the GitHub CLI) or api (HTTPS with the token in delivery.publisher.tokenEnv, "
1224 "GITHUB_TOKEN by default)",
1225 ),
1226 sarif: bool | None = typer.Option(
1227 None, "--sarif/--no-sarif", help="Upload the run's findings to code scanning"
1228 ),
1229 commit: str | None = typer.Option(
1230 None, "--commit", help="Commit the SARIF report belongs to (default: the PR head)"
1231 ),
1232 forge: str | None = typer.Option(
1233 None,
1234 "--forge",
1235 help="github, gitlab, bitbucket, azure-devops or gitea (default: delivery.forge, else "
1236 "detected from the origin remote)",
1237 ),
1238 path: Path = typer.Option(
1239 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1240 ),
1241) -> None:
1242 """Post the decision brief of a run on a pull or merge request (one comment per run,
1243 updated when published again) and attach the run's findings: SARIF to GitHub code scanning,
1244 a Code Insights report on Bitbucket; GitLab and Azure DevOps read the report from CI
1245 artifacts. GitHub is the default; another forge is detected from the origin remote or set
1246 with --forge or delivery.forge. Information only: nothing is decided on the forge."""
1247 _emit(
1248 _call(
1249 lambda: HarnessApplication().publish_pull_request(
1250 path,
1251 run,
1252 pull_request=pull_request,
1253 repository=repository,
1254 transport=transport,
1255 sarif=sarif,
1256 commit_sha=commit,
1257 forge=forge,
1258 )
1259 )
1260 )
1263@pr_app.command("create")
1264def pr_create(
1265 run: str = RUN_OPTION_LATEST,
1266 base: str | None = typer.Option(
1267 None, "--base", help="Target branch (default: delivery.forge.baseBranch)"
1268 ),
1269 head: str | None = typer.Option(
1270 None, "--head", help="Source branch (default: the closure branch of the run)"
1271 ),
1272 title: str | None = typer.Option(None, "--title", help="Title (default: the task title)"),
1273 label: list[str] | None = typer.Option(
1274 None, "--label", help="Label, added to delivery.forge.labels (repeatable)"
1275 ),
1276 draft: bool | None = typer.Option(
1277 None, "--draft/--ready", help="Open it as a draft (default: delivery.forge.draft)"
1278 ),
1279 forge: str | None = typer.Option(
1280 None, "--forge", help="github, gitlab, bitbucket, azure-devops or gitea"
1281 ),
1282 repository: str | None = typer.Option(
1283 None, "--repository", help="Repository path on the forge (default: the origin remote)"
1284 ),
1285 transport: str | None = typer.Option(
1286 None, "--transport", help="cli (gh or glab) or api (HTTPS, token from the environment)"
1287 ),
1288 path: Path = typer.Option(
1289 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1290 ),
1291) -> None:
1292 """Open a pull or merge request from the closure branch of a run (push the branch first),
1293 with the repository's pull request template and the decision brief as its description and
1294 the configured labels. The creation is recorded as a delivery.pull-request.created event.
1295 Nothing is approved on the forge: the approval is the run's digest-bound decision."""
1296 _emit(
1297 _call(
1298 lambda: HarnessApplication().create_pull_request(
1299 path,
1300 run,
1301 head=head,
1302 base=base,
1303 title=title,
1304 labels=tuple(label or ()),
1305 draft=draft,
1306 forge=forge,
1307 repository=repository,
1308 transport=transport,
1309 )
1310 )
1311 )
1314@pr_app.command("status")
1315def pr_status(
1316 commit: str = typer.Option(..., "--commit", help="Commit whose status is set"),
1317 run: str = RUN_OPTION_LATEST,
1318 target_url: str | None = typer.Option(
1319 None, "--target-url", help="Link shown with the status (for example the CI job)"
1320 ),
1321 forge: str | None = typer.Option(
1322 None, "--forge", help="github, gitlab, bitbucket, azure-devops or gitea"
1323 ),
1324 repository: str | None = typer.Option(
1325 None, "--repository", help="Repository path on the forge (default: the origin remote)"
1326 ),
1327 transport: str | None = typer.Option(
1328 None, "--transport", help="cli (gh or glab) or api (HTTPS, token from the environment)"
1329 ),
1330 path: Path = typer.Option(
1331 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1332 ),
1333) -> None:
1334 """Set the commit status governed-harness from a run: success once it closed approved,
1335 pending while it waits for a human decision, failure otherwise."""
1336 _emit(
1337 _call(
1338 lambda: HarnessApplication().pull_request_status(
1339 path,
1340 run,
1341 commit_sha=commit,
1342 target_url=target_url,
1343 forge=forge,
1344 repository=repository,
1345 transport=transport,
1346 )
1347 )
1348 )
1351@pr_app.command("forge")
1352def pr_forge(
1353 path: Path = typer.Option(
1354 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1355 ),
1356) -> None:
1357 """Show the forge the workspace resolves to (delivery.forge or the origin remote), its API
1358 URL, transport and the environment variable its token is read from. Calls nothing."""
1359 _emit(_call(lambda: HarnessApplication().forge(path)))
1362@standards_app.command("show")
1363def standards_show(
1364 lang: str | None = typer.Option(
1365 None, "--lang", help="One pack (python, typescript, java, ...) with all its cards"
1366 ),
1367 file: list[str] | None = typer.Option(
1368 None,
1369 "--file",
1370 help="A workspace path: show the cards an implement call and the review checklist "
1371 "would get for it (repeatable)",
1372 ),
1373 path: Path = typer.Option(
1374 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1375 ),
1376 json_output: bool | None = JSON_OPTION,
1377) -> None:
1378 """Show the language standards packs: the detected and effective packs (repository
1379 overrides applied), their tools and the validators added for the tools the repository
1380 configures; with --lang every card of one pack; with --file the cards selected for those
1381 files. Works without a project configuration. Reads only."""
1382 _emit(
1383 _call(lambda: HarnessApplication().standards(path, pack=lang, files=tuple(file or ()))),
1384 json_output,
1385 )
1388@architecture_app.command("show")
1389def architecture_show(
1390 path: Path = typer.Option(
1391 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1392 ),
1393 json_output: bool | None = JSON_OPTION,
1394) -> None:
1395 """Show the architecture of the project: the configured section, whether the project is
1396 new or existing, the cached survey or the ADR, the layer rules in force with their
1397 forbidden imports, and the source layout the survey cache is keyed by."""
1398 _emit(_call(lambda: HarnessApplication().architecture(path)), json_output)
1401@architecture_app.command("decide")
1402def architecture_decide(
1403 run: str = RUN_OPTION,
1404 digest: str = typer.Option(..., "--digest", help="Digest shown by the blocked phase"),
1405 rationale: str = typer.Option(..., "--rationale", help=_RATIONALE_HELP),
1406 decision: DecisionKind | None = typer.Option(
1407 None,
1408 "--decision",
1409 case_sensitive=False,
1410 help="APPROVE or REJECT the layer rules a survey inferred",
1411 ),
1412 option: str | None = typer.Option(
1413 None, "--option", help="The architecture option chosen for a new project"
1414 ),
1415 style: str | None = typer.Option(
1416 None,
1417 "--style",
1418 help="A style of the catalogue chosen for a new project (architecture.catalogue: experts)",
1419 ),
1420 actor: str | None = typer.Option(None, "--actor", help=ACTOR_HELP, show_default=False),
1421 continue_after: bool = typer.Option(True, _CONTINUE_OPTION, help=_CONTINUE_HELP),
1422 path: Path = typer.Option(
1423 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1424 ),
1425) -> None:
1426 """Decide the architecture, bound to the digest of the proposal: approve or reject the
1427 layer rules a survey inferred (existing project), or choose one of the options of a new
1428 project, which is recorded as an ADR; under architecture.catalogue: experts --style chooses
1429 any style of the catalogue instead. The approved rules are enforced as forbidden
1430 dependencies in VERIFICATION. A stale digest or a non-human actor exits 5."""
1431 result = _call(
1432 lambda: _acting().decide_architecture(
1433 path,
1434 execution_id=run,
1435 digest=digest,
1436 rationale=rationale,
1437 decision=decision,
1438 option=option,
1439 actor_id=actor,
1440 continue_after=continue_after,
1441 style=style,
1442 )
1443 )
1444 _emit(result)
1445 execution = result.get("execution")
1446 if execution:
1447 _exit_for_execution(ResultStatus(execution["status"]), execution["currentPhase"])
1450@architecture_app.command("refresh")
1451def architecture_refresh(
1452 path: Path = typer.Option(
1453 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1454 ),
1455) -> None:
1456 """Mark the cached architecture survey stale: the next run surveys the project again (one
1457 call). Approved rules stay in force until a new survey is decided."""
1458 _emit(_call(lambda: HarnessApplication().refresh_architecture(path)))
1461@mcp_app.command("serve")
1462def mcp_serve(
1463 path: Path = typer.Option(
1464 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1465 ),
1466) -> None:
1467 """Serve the harness to an agent session over stdio (Model Context Protocol, JSON-RPC 2.0,
1468 one message per line). Tools: project, status, inbox, task create, questions and clarify
1469 (the person's answers, marked as relayed), run start (provider session by default) and
1470 continue, check, review and standards. No tool decides for a person: gate, acceptance,
1471 plan and architecture decisions stay in the terminal. Register it, for example, with
1472 claude mcp add harness -- harness mcp serve."""
1473 from governed_harness.embedded.mcp_server import serve_stdio
1475 raise typer.Exit(code=serve_stdio(path.resolve()))
1478@project_app.command("show")
1479def project_show(
1480 path: Path = typer.Option(
1481 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1482 ),
1483 json_output: bool | None = JSON_OPTION,
1484) -> None:
1485 """Show what the harness detects about the project, deterministically and without an
1486 agent call: new or existing (and why), profiles, standards packs, testing strategy,
1487 architecture status, project setup answers and forge."""
1488 _emit(_call(lambda: HarnessApplication().project(path)), json_output)
1491@app.command()
1492def gc(
1493 apply: bool = typer.Option(
1494 False, "--apply", help="Delete what the report lists; without it nothing is deleted"
1495 ),
1496 path: Path = typer.Option(
1497 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1498 ),
1499) -> None:
1500 """Apply the retention settings to runs that ended (closed, cancelled or rejected) longer
1501 ago than them: `retention.artifactDays` deletes the run's artifacts that no kept run uses and
1502 records a `retention.artifacts.pruned` event; `retention.eventDays` removes the run, its
1503 events, records and artifacts. Open runs and memory records are never touched. Without
1504 --apply only the report is printed."""
1505 _emit(_call(lambda: HarnessApplication().gc(path, apply=apply)))
1508@evidence_app.command("list")
1509def evidence_list(
1510 run: str = RUN_OPTION_LATEST,
1511 path: Path = typer.Option(
1512 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1513 ),
1514) -> None:
1515 """List the evidence records of a run with their artifact references and digests."""
1516 _emit(_call(lambda: HarnessApplication().list_evidence(path, run)))
1519@evidence_app.command("attach")
1520def evidence_attach(
1521 file: Path = typer.Option(..., "--file", exists=True, dir_okay=False, help="File to attach"),
1522 run: str | None = typer.Option(None, "--run", help="Run the evidence is about"),
1523 task: str | None = typer.Option(
1524 None, "--task", help="Task the attachment is intake context of (with --manual)"
1525 ),
1526 item: str | None = typer.Option(
1527 None, "--item", help="Deferred item (D-CRITERION) to close, or checklist item"
1528 ),
1529 manual: bool = typer.Option(
1530 False,
1531 "--manual",
1532 help="A person's attachment (screenshot, video, log) instead of a test or CI report",
1533 ),
1534 evidence_format: str = typer.Option(
1535 "auto", "--format", help="auto, junit, sarif or ci-status (deferred items)"
1536 ),
1537 case: str | None = typer.Option(
1538 None, "--case", help="Only the JUnit test cases whose name contains this text"
1539 ),
1540 commit: str | None = typer.Option(
1541 None, "--commit", help="Commit the evidence is about (checked against the item's)"
1542 ),
1543 note: str | None = typer.Option(None, "--note", help="What the attachment shows"),
1544 actor: str | None = typer.Option(None, "--actor", help=ACTOR_HELP, show_default=False),
1545 path: Path = typer.Option(
1546 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1547 ),
1548) -> None:
1549 """Attach evidence. With --run and --item D-CRITERION, close a deferred verification
1550 with a JUnit, SARIF or CI status report (bound to the item's ChangeSet digest and commit;
1551 an expired item exits 5). With --manual, store a person's attachment bound to the run's
1552 ChangeSet (and to a checklist item with --item), or to a task revision as intake context
1553 the agent receives (--task)."""
1554 _emit(
1555 _call(
1556 lambda: _acting().attach_evidence(
1557 path,
1558 file=file,
1559 execution_id=run,
1560 task_id=task,
1561 item=item,
1562 manual=manual,
1563 evidence_format=evidence_format,
1564 case=case,
1565 commit=commit,
1566 note=note,
1567 actor_id=actor,
1568 )
1569 )
1570 )
1573@findings_app.command("list")
1574def findings_list(
1575 run: str = RUN_OPTION_LATEST,
1576 path: Path = typer.Option(
1577 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1578 ),
1579) -> None:
1580 """List the structured findings of a run with severity, rule and location."""
1581 _emit(_call(lambda: HarnessApplication().list_findings(path, run)), kind="findings")
1584def _memory_value(raw: str) -> dict[str, Any]:
1585 """A JSON object is stored as given; any other text is stored under the key ``text``."""
1586 try:
1587 parsed = json.loads(raw)
1588 except json.JSONDecodeError:
1589 return {"text": raw}
1590 return parsed if isinstance(parsed, dict) else {"text": raw}
1593def _memory_deadline(raw: str | None) -> datetime | None:
1594 if raw is None:
1595 return None
1596 try:
1597 value = datetime.fromisoformat(raw)
1598 except ValueError as error:
1599 raise ConfigurationError(f"--valid-until is not an ISO 8601 date: {raw}") from error
1600 return value if value.tzinfo else value.replace(tzinfo=UTC)
1603@memory_app.command("add")
1604def memory_add(
1605 level: MemoryLevel = typer.Option(
1606 ..., "--level", case_sensitive=False, help="Scope of the record"
1607 ),
1608 key: str = typer.Option(..., "--key", help="Stable name of the record within its level"),
1609 value: str = typer.Option(
1610 ..., "--value", help="JSON object, or plain text stored under the key 'text'"
1611 ),
1612 task: str | None = typer.Option(None, "--task", help="Task identifier; required for TASK"),
1613 run: str | None = typer.Option(None, "--run", help="Run identifier; required for EPHEMERAL"),
1614 valid_until: str | None = typer.Option(
1615 None, "--valid-until", help="ISO 8601 instant after which the record no longer applies"
1616 ),
1617 supersedes: str | None = typer.Option(
1618 None, "--supersedes", help="Identifier of the record this one replaces"
1619 ),
1620 sensitive: bool = typer.Option(
1621 False, "--sensitive", help="Withhold the value from the context manifest and the agent"
1622 ),
1623 approve: bool = typer.Option(
1624 False, "--approve", help="Record the entry as approved by the acting person"
1625 ),
1626 actor: str | None = typer.Option(
1627 None,
1628 "--actor",
1629 help=ACTOR_HELP,
1630 show_default=False,
1631 ),
1632 path: Path = typer.Option(
1633 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1634 ),
1635) -> None:
1636 """Record a memory entry with its provenance. NORMATIVE, PROJECT and RETROSPECTIVE entries
1637 enter a context only once approved."""
1638 _emit(
1639 _call(
1640 lambda: _acting().add_memory(
1641 path,
1642 level=level,
1643 key=key,
1644 value=_memory_value(value),
1645 actor_id=actor,
1646 task_id=task,
1647 execution_id=run,
1648 valid_until=_memory_deadline(valid_until),
1649 supersedes=supersedes,
1650 sensitive=sensitive,
1651 approved=approve,
1652 )
1653 )
1654 )
1657@memory_app.command("list")
1658def memory_list(
1659 task: str | None = typer.Option(None, "--task", help="Evaluate the status for this task"),
1660 run: str | None = typer.Option(None, "--run", help="Evaluate the status for this run"),
1661 path: Path = typer.Option(
1662 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1663 ),
1664) -> None:
1665 """List the memory records of the project with their status: active, superseded, expired,
1666 unapproved, limit or out_of_scope."""
1667 _emit(_call(lambda: HarnessApplication().list_memory(path, task_id=task, execution_id=run)))
1670@memory_app.command("manifest")
1671def memory_manifest(
1672 run: str = RUN_OPTION_LATEST,
1673 path: Path = typer.Option(
1674 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1675 ),
1676) -> None:
1677 """Show the context manifest recorded for a run: the records it applied, their digest and
1678 the candidates it excluded with the reason."""
1679 _emit(_call(lambda: HarnessApplication().memory_manifest(path, run)))
1682@memory_app.command("approve")
1683def memory_approve(
1684 memory: str = typer.Option(..., "--memory", help="Memory record identifier"),
1685 actor: str | None = typer.Option(
1686 None,
1687 "--actor",
1688 help=ACTOR_HELP,
1689 show_default=False,
1690 ),
1691 path: Path = typer.Option(
1692 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1693 ),
1694) -> None:
1695 """Approve a proposed record. The approval is a new record that supersedes the proposal;
1696 approving a record that needs no approval or is already approved exits with code 5."""
1697 _emit(_call(lambda: _acting().approve_memory(path, memory_id=memory, actor_id=actor)))
1700@memory_app.command("invalidate")
1701def memory_invalidate(
1702 memory: str = typer.Option(..., "--memory", help="Memory record identifier"),
1703 reason: str = typer.Option(..., "--reason", help="Why the record no longer applies"),
1704 actor: str | None = typer.Option(
1705 None,
1706 "--actor",
1707 help=ACTOR_HELP,
1708 show_default=False,
1709 ),
1710 path: Path = typer.Option(
1711 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1712 ),
1713) -> None:
1714 """Invalidate a record without deleting it: it stops entering any context and the actor and
1715 the reason stay on record."""
1716 _emit(
1717 _call(
1718 lambda: _acting().invalidate_memory(
1719 path, memory_id=memory, actor_id=actor, reason=reason
1720 )
1721 )
1722 )
1725@gate_app.command("decide")
1726# Each parameter is an option of `harness gate decide` (Sonar S107 is suppressed on purpose).
1727def gate_decide(
1728 run: str = RUN_OPTION, # NOSONAR(S107)
1729 decision: DecisionKind | None = typer.Option(
1730 None,
1731 "--decision",
1732 case_sensitive=False,
1733 help="Human decision; asked interactively when omitted on a terminal",
1734 ),
1735 change_set_digest: str | None = typer.Option(
1736 None,
1737 "--change-set-digest",
1738 help="Current ChangeSet digest shown by status or review (sha256:...); confirmed "
1739 "interactively when omitted on a terminal",
1740 ),
1741 rationale: str | None = typer.Option(
1742 None,
1743 "--rationale",
1744 help="Justification recorded with the decision; asked interactively when omitted",
1745 ),
1746 actor: str | None = typer.Option(
1747 None,
1748 "--actor",
1749 help=ACTOR_HELP,
1750 show_default=False,
1751 ),
1752 continue_after: bool = typer.Option(True, _CONTINUE_OPTION, help=_CONTINUE_HELP),
1753 expires_in: str | None = typer.Option(
1754 None,
1755 "--expires-in",
1756 help="APPROVE_EXCEPTION under review.exceptions: validity such as 14d, 36h or 2w "
1757 "(default review.exceptionDays)",
1758 ),
1759 expires_at: str | None = typer.Option(
1760 None, "--expires-at", help="APPROVE_EXCEPTION: ISO 8601 instant the exception expires"
1761 ),
1762 scope: list[str] | None = typer.Option(
1763 None,
1764 "--scope",
1765 help="APPROVE_EXCEPTION: findings covered, as rule or rule:path (repeatable; default: "
1766 "the blocking findings of the gate, by fingerprint)",
1767 ),
1768 alternative_evidence: str | None = typer.Option(
1769 None,
1770 "--alternative-evidence",
1771 help="APPROVE_EXCEPTION: evidence that compensates for the blocking findings",
1772 ),
1773 follow_up: str | None = typer.Option(
1774 None, "--follow-up", help="APPROVE_EXCEPTION: issue or task that will remove the exception"
1775 ),
1776 interactive: bool = typer.Option(
1777 False,
1778 "--interactive",
1779 "-i",
1780 help="Show the decision brief and confirm the ChangeSet digest even when every option "
1781 "is given",
1782 ),
1783 acknowledge_risk: list[str] | None = typer.Option(
1784 None,
1785 "--acknowledge-risk",
1786 help="APPROVE or APPROVE_EXCEPTION under verification.riskFactors: a risk factor of the "
1787 "ChangeSet the decider acknowledges (repeatable; required for every factor whose "
1788 "action is acknowledge)",
1789 ),
1790 check: list[str] | None = typer.Option(
1791 None,
1792 "--check",
1793 help="Under review.manualChecklist: a checklist item the person verified (repeatable); "
1794 "APPROVE needs every item of the run",
1795 ),
1796 change_request: list[str] | None = typer.Option(
1797 None,
1798 "--change-request",
1799 help="REQUEST_CHANGES under review.structuredChanges: a blocking item as "
1800 "'description::condition' where the condition is test:NODE_ID (a pytest node id), "
1801 "absent:REGEX or text (repeatable)",
1802 ),
1803 path: Path = typer.Option(
1804 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
1805 ),
1806) -> None:
1807 """Record a human decision bound to the current ChangeSet digest. A decision for a stale
1808 digest, or APPROVE over a gate that did not pass, is rejected with exit code 5. On a
1809 terminal, omitting --decision, --change-set-digest or --rationale shows the decision brief,
1810 asks for the missing values and asks the person to type the start of the digest the decision
1811 binds to; a digest that is not confirmed records nothing (exit 5). Without a terminal the
1812 three options are required (exit 2). Under `governance.confirmDecisionDigest: true` the
1813 same confirmation is asked on a terminal even when every option is given. An actor id of an
1814 agent, validator or the harness is refused with exit 5; without --actor the decider is the
1815 Git user under `governance.deciderIdentity: git` (human.local, with a warning, when Git has
1816 no identity)."""
1817 application = _acting()
1818 run_id = _call(lambda: application.resolve_run(path, run))
1819 missing = decision is None or change_set_digest is None or rationale is None
1820 terminal = sys.stdin.isatty() and sys.stdout.isatty()
1821 if missing and not (interactive or terminal):
1822 _missing_decision_options(run_id)
1823 exception = ExceptionOptions(
1824 expires_in=expires_in,
1825 expires_at=expires_at,
1826 scope=tuple(scope or ()),
1827 alternative_evidence=alternative_evidence,
1828 follow_up=follow_up,
1829 )
1830 confirm = terminal and _digest_confirmation_configured(path)
1831 checked = list(check or ())
1832 if missing or interactive or confirm:
1833 chosen, digest, reason = _interactive_decision(
1834 application, path, run_id, decision, change_set_digest, rationale
1835 )
1836 exception = _exception_for(chosen, exception, path)
1837 checked = _interactive_checklist(application, path, run_id, checked)
1838 else:
1839 chosen, digest, reason = _given_decision(run_id, decision, change_set_digest, rationale)
1840 record, execution = _call(
1841 lambda: application.decide_gate(
1842 path,
1843 execution_id=run_id,
1844 decision=chosen,
1845 change_set_digest=digest,
1846 actor_id=actor,
1847 rationale=reason,
1848 continue_after=continue_after,
1849 exception=exception,
1850 acknowledged_risks=tuple(acknowledge_risk or ()),
1851 change_requests=tuple(change_request or ()),
1852 checked_items=tuple(checked),
1853 ),
1854 hint=_decide_hint(application, path, run_id),
1855 )
1856 _emit(
1857 {
1858 "decision": record.model_dump(mode="json", by_alias=True),
1859 "execution": execution.model_dump(mode="json", by_alias=True),
1860 },
1861 kind="decision",
1862 )
1863 _exit_for_execution(execution.status, execution.current_phase.value)
1866def _missing_decision_options(run_id: str) -> NoReturn:
1867 """Without a terminal, ``gate decide`` needs the decision, the digest and the rationale."""
1868 _report_error(
1869 {
1870 "status": "ERROR",
1871 "error": "missing --decision, --change-set-digest or --rationale",
1872 "hint": "Pass the three options, or run `harness gate decide --run "
1873 f"{run_id}` on a terminal (or with --interactive) to decide interactively.",
1874 }
1875 )
1876 raise typer.Exit(code=2)
1879def _exception_for(
1880 decision: DecisionKind, exception: ExceptionOptions, path: Path
1881) -> ExceptionOptions:
1882 """Under ``review.exceptions``, an interactive APPROVE_EXCEPTION asks what it records."""
1883 if decision is DecisionKind.APPROVE_EXCEPTION and _exceptions_enabled(path):
1884 return _interactive_exception(exception)
1885 return exception
1888def _given_decision(
1889 run_id: str,
1890 decision: DecisionKind | None,
1891 change_set_digest: str | None,
1892 rationale: str | None,
1893) -> tuple[DecisionKind, str, str]:
1894 """The decision given as options (all three; a missing one exits as above)."""
1895 if decision is None or change_set_digest is None or rationale is None: 1895 ↛ 1896line 1895 didn't jump to line 1896 because the condition on line 1895 was never true
1896 _missing_decision_options(run_id)
1897 return decision, change_set_digest, rationale
1900def _interactive_checklist(
1901 application: HarnessApplication, path: Path, run_id: str, checked: list[str]
1902) -> list[str]:
1903 """Ask about each checklist item of the run that is not ticked yet."""
1904 brief = _call(lambda: application.review(path, run_id))
1905 for item in brief.get("checklist") or []: 1905 ↛ 1906line 1905 didn't jump to line 1906 because the loop on line 1905 never started
1906 if item["itemId"] in checked:
1907 continue
1908 answer = str(
1909 typer.prompt(f"Checked {item['itemId']}: {item['text']}? (yes/no)", default="no")
1910 )
1911 if answer.strip().lower() in {"y", "yes"}:
1912 checked.append(item["itemId"])
1913 return checked
1916def _digest_confirmation_configured(path: Path) -> bool:
1917 """``governance.confirmDecisionDigest``: confirm the digest on a terminal every time."""
1918 try:
1919 return bool(
1920 HarnessApplication().validate_config(path)["governance"]["confirmDecisionDigest"]
1921 )
1922 except Exception: # noqa: BLE001 - decide reports configuration errors itself
1923 return False
1926def _exceptions_enabled(path: Path) -> bool:
1927 try:
1928 return bool(HarnessApplication().validate_config(path)["review"]["exceptions"])
1929 except Exception: # noqa: BLE001 - decide reports configuration errors itself
1930 return False
1933def _interactive_exception(exception: ExceptionOptions) -> ExceptionOptions:
1934 """Ask for what an exception records when the options were not given."""
1936 def ask(question: str) -> str | None:
1937 answer = typer.prompt(question, default="", show_default=False)
1938 return str(answer).strip() or None
1940 # dataclasses.replace returns the type it receives; Sonar types it as DataclassInstance.
1941 answered: ExceptionOptions = replace( # NOSONAR(S5890)
1942 exception,
1943 expires_in=exception.expires_in
1944 if exception.expires_in or exception.expires_at
1945 else ask("Expires in (e.g. 14d, 36h, 2w; empty for the project default)"),
1946 alternative_evidence=exception.alternative_evidence
1947 or ask("Alternative evidence (optional)"),
1948 follow_up=exception.follow_up or ask("Follow-up issue or task (optional)"),
1949 )
1950 return answered # NOSONAR(S5886)
1953DIGEST_CONFIRM_CHARS = 12
1954"""Hex characters of the ChangeSet digest a person types to confirm an interactive decision."""
1957def _interactive_decision(
1958 application: HarnessApplication,
1959 path: Path,
1960 run_id: str,
1961 decision: DecisionKind | None,
1962 change_set_digest: str | None,
1963 rationale: str | None,
1964) -> tuple[DecisionKind, str, str]:
1965 brief = _call(lambda: application.review(path, run_id))
1966 typer.echo(render_human(brief, "review"))
1967 typer.echo("")
1968 current = brief["run"]["changeSetDigest"]
1969 if not brief["run"]["awaitingDecision"] or not current: 1969 ↛ 1970line 1969 didn't jump to line 1970 because the condition on line 1969 was never true
1970 _report_error(
1971 {
1972 "status": "ERROR",
1973 "error": f"run {run_id} is not waiting for a decision "
1974 f"({brief['run']['status']} in {brief['run']['currentPhase']})",
1975 "hint": "; ".join(brief["next"]) or None,
1976 }
1977 )
1978 raise typer.Exit(code=5)
1979 if decision is None:
1980 decision = _prompt_decision()
1981 while not (rationale or "").strip():
1982 rationale = typer.prompt("Rationale (what you checked and why)")
1983 if change_set_digest is not None and change_set_digest != current: 1983 ↛ 1985line 1983 didn't jump to line 1985 because the condition on line 1983 was never true
1984 # Let the engine reject it with its usual message and exit code.
1985 return decision, change_set_digest, str(rationale)
1986 _confirm_digest(decision, current)
1987 return decision, current, str(rationale)
1990def _prompt_decision() -> DecisionKind:
1991 # Validated here rather than with click.Choice: click is not a declared dependency,
1992 # and recent Typer versions no longer install it.
1993 allowed = [item.value for item in DecisionKind]
1994 while True:
1995 choice = str(typer.prompt(f"Decision ({', '.join(allowed)})")).strip().upper()
1996 if choice in allowed: 1996 ↛ 1998line 1996 didn't jump to line 1998 because the condition on line 1996 was always true
1997 return DecisionKind(choice)
1998 typer.echo(f"Choose one of: {', '.join(allowed)}", err=True)
2001def _confirm_digest(decision: DecisionKind, current: str) -> None:
2002 """The person types the start of the digest the decision binds to (exit 5 otherwise)."""
2003 expected = current.removeprefix("sha256:")
2004 typed = typer.prompt(
2005 f"Type the first {DIGEST_CONFIRM_CHARS} characters of the digest to bind this "
2006 f"{decision.value} to {current}"
2007 )
2008 typed = typed.strip().lower().removeprefix("sha256:")
2009 if len(typed) < DIGEST_CONFIRM_CHARS or not expected.startswith(typed):
2010 _report_error(
2011 {
2012 "status": "ERROR",
2013 "error": "the ChangeSet digest was not confirmed; no decision was recorded",
2014 "hint": f"Type at least {DIGEST_CONFIRM_CHARS} characters of {current}.",
2015 }
2016 )
2017 raise typer.Exit(code=5)
2020def _decide_hint(application: HarnessApplication, path: Path, run_id: str) -> Hint:
2021 def hint(error: BaseException) -> str | None:
2022 message = str(error)
2023 try:
2024 status = application.status(path, run_id)
2025 except Exception: # noqa: BLE001 - a hint must never hide the original error
2026 return None
2027 execution = status["execution"]
2028 if "belongs to the agent, validator or harness namespace" in message:
2029 # H44: the refusal named the cause but not who may decide or how.
2030 return (
2031 "Only a person may decide. Read the decision brief with "
2032 f"`harness review --run {run_id}`, then decide yourself with gate decide and "
2033 "your own --actor id (or none, so governance.deciderIdentity applies)."
2034 )
2035 if "does not match the current ChangeSet" in message:
2036 prior = (
2037 ""
2038 if status["humanDecision"]
2039 else " No decision has been recorded on the current digest."
2040 )
2041 return (
2042 f"The current ChangeSet digest is {execution['changeSetDigest']}.{prior} Review "
2043 f"it with `harness review --run {run_id}` and decide on that digest (or omit "
2044 "--change-set-digest on a terminal to confirm it interactively)."
2045 )
2046 if "accepted only in DECISION" in message: 2046 ↛ 2047line 2046 didn't jump to line 2047 because the condition on line 2046 was never true
2047 return (
2048 f"The run is {execution['status']} in {execution['currentPhase']}. Fix the cause "
2049 f"and `harness run continue --run {run_id}`, or `harness run cancel --run "
2050 f"{run_id}`; `harness review --run {run_id}` shows what did not pass."
2051 )
2052 if "APPROVE is only valid" in message:
2053 return (
2054 "The gate did not pass: decide REQUEST_CHANGES with what must change, REJECT, or "
2055 f"APPROVE_EXCEPTION with a rationale. `harness review --run {run_id}` lists the "
2056 "blocking findings."
2057 )
2058 return None
2060 return hint
2063@app.command()
2064def inbox(
2065 json_output: bool | None = JSON_OPTION,
2066 approve: list[str] | None = typer.Option(
2067 None,
2068 "--approve",
2069 help="Batch: APPROVE a run as RUN=sha256:DIGEST, the digest the inbox shows (repeatable)",
2070 ),
2071 reject: list[str] | None = typer.Option(
2072 None, "--reject", help="Batch: REJECT a run as RUN=sha256:DIGEST (repeatable)"
2073 ),
2074 request_changes: list[str] | None = typer.Option(
2075 None,
2076 "--request-changes",
2077 help="Batch: REQUEST_CHANGES on a run as RUN=sha256:DIGEST (repeatable)",
2078 ),
2079 decisions: Path | None = typer.Option(
2080 None,
2081 "--decisions",
2082 exists=True,
2083 dir_okay=False,
2084 help="Batch file (YAML or JSON): a list of run, decision, changeSetDigest and an "
2085 "optional rationale",
2086 ),
2087 batch: bool = typer.Option(
2088 False,
2089 "--batch",
2090 help="On a terminal: decide every pending decision of the inbox one after the other",
2091 ),
2092 rationale: str | None = typer.Option(
2093 None, "--rationale", help="Batch: the rationale recorded with each decision"
2094 ),
2095 actor: str | None = typer.Option(None, "--actor", help=ACTOR_HELP, show_default=False),
2096 path: Path = typer.Option(
2097 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
2098 ),
2099) -> None:
2100 """List the runs of the project that wait for a person, oldest first: a decision in
2101 DECISION (gate status, digest, blocking findings, the risk factors an APPROVE must
2102 acknowledge), answers to clarification questions in INTENT, and every other wait before
2103 DECISION (kind plan, decomposition, acceptance, acceptance-dispute, architecture, contract,
2104 deferred or preflight, with the digest it binds to), each with the next command. With --approve,
2105 --reject, --request-changes, --decisions or --batch it records several decisions, each bound
2106 to its own ChangeSet digest (a batch file may list acknowledgeRisks per decision): a stale
2107 digest or a refused decision is reported for that run (the others are recorded) and the
2108 command exits 5 when any was refused."""
2109 items = _option_batch(approve, reject, request_changes)
2110 if decisions is not None:
2111 items.extend(_file_batch(decisions))
2112 if batch: 2112 ↛ 2113line 2112 didn't jump to line 2113 because the condition on line 2112 was never true
2113 items.extend(_terminal_batch(path))
2114 if not items:
2115 _emit(_call(lambda: HarnessApplication().inbox(path)), json_output, kind="inbox")
2116 return
2117 reason = _batch_rationale(rationale, items)
2118 result = _call(lambda: _acting().decide_batch(path, items, rationale=reason, actor_id=actor))
2119 _emit(result, json_output)
2120 if result["refused"]:
2121 raise typer.Exit(code=5)
2124def _option_batch(
2125 approve: list[str] | None, reject: list[str] | None, request_changes: list[str] | None
2126) -> list[Any]:
2127 """The decisions given as RUN=sha256:DIGEST options, approvals first."""
2128 from governed_harness.application.friction import parse_batch_item
2130 items: list[Any] = []
2131 for values, kind in (
2132 (approve, DecisionKind.APPROVE),
2133 (reject, DecisionKind.REJECT),
2134 (request_changes, DecisionKind.REQUEST_CHANGES),
2135 ):
2136 items.extend(_call(partial(parse_batch_item, value, kind)) for value in values or ())
2137 return items
2140def _file_batch(decisions: Path) -> list[Any]:
2141 import yaml
2143 from governed_harness.application.friction import load_batch_file
2145 raw = _call(lambda: yaml.safe_load(decisions.read_text(encoding="utf-8")))
2146 return list(_call(lambda: load_batch_file(raw)))
2149def _terminal_batch(path: Path) -> list[Any]:
2150 """``--batch``: the decisions asked on a terminal (exit 2 without one)."""
2151 if not (sys.stdin.isatty() and sys.stdout.isatty()):
2152 _report_error(
2153 {
2154 "status": "ERROR",
2155 "error": "--batch needs a terminal",
2156 "hint": "Use --approve RUN=DIGEST or --decisions FILE without a terminal.",
2157 }
2158 )
2159 raise typer.Exit(code=2)
2160 return _interactive_batch(path)
2163def _batch_rationale(rationale: str | None, items: list[Any]) -> str:
2164 """The rationale of the decisions without their own: given, asked on a terminal, or exit
2165 2."""
2166 if rationale is not None or all(item.rationale is not None for item in items): 2166 ↛ 2168line 2166 didn't jump to line 2168 because the condition on line 2166 was always true
2167 return rationale or ""
2168 if sys.stdin.isatty() and sys.stdout.isatty():
2169 return str(typer.prompt("Rationale recorded with each decision"))
2170 _report_error(
2171 {
2172 "status": "ERROR",
2173 "error": "a batch decision needs --rationale (or a rationale per decision)",
2174 }
2175 )
2176 raise typer.Exit(code=2)
2179def _interactive_batch(path: Path) -> list[Any]:
2180 """Ask, for each run waiting for a decision, what to decide; each answer is bound to the
2181 digest shown next to it."""
2182 from governed_harness.application.friction import BatchItem
2184 entries = [
2185 item
2186 for item in _call(lambda: HarnessApplication().inbox(path))
2187 if item.get("kind") == "decision" and item.get("changeSetDigest")
2188 ]
2189 choices = {
2190 "a": DecisionKind.APPROVE,
2191 "r": DecisionKind.REQUEST_CHANGES,
2192 "j": DecisionKind.REJECT,
2193 }
2194 items: list[Any] = []
2195 for entry in entries:
2196 typer.echo(
2197 f"{entry['executionId']} {entry['taskTitle']}\n gate {entry['gateStatus']}, "
2198 f"{entry['blockingFindings']} blocking finding(s), digest {entry['changeSetDigest']}"
2199 )
2200 answer = ""
2201 while answer not in {"a", "r", "j", "s"}:
2202 answer = (
2203 str(typer.prompt(" [a]pprove, [r]equest changes, re[j]ect, [s]kip", default="s"))
2204 .strip()
2205 .lower()[:1]
2206 )
2207 if answer != "s":
2208 risks = _batch_risks(entry) if choices[answer] is DecisionKind.APPROVE else ()
2209 items.append(
2210 BatchItem(
2211 entry["executionId"], choices[answer], entry["changeSetDigest"], None, risks
2212 )
2213 )
2214 if items:
2215 confirmed = str(
2216 typer.prompt(
2217 f"Record {len(items)} decision(s), each bound to the digest shown? (yes/no)",
2218 default="no",
2219 )
2220 )
2221 if confirmed.strip().lower() not in {"y", "yes"}:
2222 raise typer.Exit(code=5)
2223 return items
2226def _batch_risks(entry: dict[str, Any]) -> tuple[str, ...]:
2227 """The risk factors an APPROVE of the inbox entry must acknowledge, each confirmed on the
2228 terminal (#73); one not acknowledged leaves the approval to be refused for that run."""
2229 acknowledged: list[str] = []
2230 for factor in entry.get("acknowledgeRisks") or []:
2231 answer = str(typer.prompt(f" Acknowledge risk factor {factor}? (yes/no)", default="no"))
2232 if answer.strip().lower() in {"y", "yes"}:
2233 acknowledged.append(str(factor))
2234 return tuple(acknowledged)
2237def _print_metrics(text: str, fmt: str, output: Path | None) -> Path | None:
2238 """The report in one format, printed or written to ``output``; the HTML file written."""
2239 if output is None:
2240 typer.echo(text, nl=False)
2241 return None
2242 output.parent.mkdir(parents=True, exist_ok=True)
2243 output.write_text(text, encoding="utf-8")
2244 typer.echo(json.dumps({"file": str(output), "format": fmt}))
2245 return output if fmt == "html" else None
2248@app.command()
2249def metrics(
2250 fmt: str | None = typer.Option(
2251 None,
2252 "--format",
2253 help="html, md, json, csv (one row per run) or prometheus; printed, or written to "
2254 "--output. Without it, metrics.json, metrics.md and metrics.html are written to "
2255 "--output-dir",
2256 ),
2257 output: Path | None = typer.Option(None, "--output", help="File for --format"),
2258 output_dir: Path | None = typer.Option(
2259 None,
2260 "--output-dir",
2261 help="Directory of the three files written without --format (default .harness/metrics)",
2262 ),
2263 open_report: bool = typer.Option(
2264 False, "--open", help="Open the HTML report in the default browser"
2265 ),
2266 since: str | None = typer.Option(
2267 None, "--since", help="Only runs created since DATE (YYYY-MM-DD, ISO 8601, 7d, 2w, 12h)"
2268 ),
2269 task: str | None = typer.Option(None, "--task", help="Only the runs of this task"),
2270 model: str | None = typer.Option(None, "--model", help="Only agent calls of this model"),
2271 agent: str | None = typer.Option(
2272 None, "--agent", help="Only agent calls of this agent provider id"
2273 ),
2274 all_repos: bool = typer.Option(
2275 False,
2276 "--all-repos",
2277 help="Every repository of the run registry (runtime.stateDir), not only this one",
2278 ),
2279 prices: Path | None = typer.Option(
2280 None,
2281 "--prices",
2282 exists=True,
2283 dir_okay=False,
2284 help="Price table (YAML or JSON, USD per million input, output and cache tokens by "
2285 "model id) for providers that report tokens without a cost; overrides metrics.prices",
2286 ),
2287 narrative: bool = typer.Option(
2288 False,
2289 "--narrative",
2290 help="Add a narrative summary: one call to metrics.narrative.command, on demand",
2291 ),
2292 path: Path = typer.Option(
2293 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
2294 ),
2295) -> None:
2296 """Local metrics of the governed runs, with zero model calls: tokens (input, output, cache)
2297 and cost by agent, model, task and phase, models used, lines by agent invocation and by
2298 person, issues resolved and features delivered, time per task, phase, agent call and human
2299 wait, quality, friction against the targets per size and daily and weekly trends. Costs of
2300 providers that report only tokens are estimated from the price table and labelled
2301 estimated. The HTML file is self-contained (inline CSS and SVG, nothing fetched). No
2302 per-person indicator is computed."""
2303 import webbrowser
2305 from governed_harness.application.metrics import write_reports
2306 from governed_harness.metrics import FORMATS, Filters, parse_since, render
2308 if fmt is not None and fmt not in FORMATS:
2309 _report_error(
2310 {"status": "ERROR", "error": f"--format is one of {', '.join(FORMATS)}, got {fmt!r}"}
2311 )
2312 raise typer.Exit(code=2)
2313 try:
2314 filters = Filters(
2315 since=parse_since(since),
2316 task=task,
2317 model=model,
2318 agent=agent,
2319 all_repos=all_repos,
2320 )
2321 except ValueError as error:
2322 _report_error({"status": "ERROR", "error": str(error)})
2323 raise typer.Exit(code=2) from error
2324 report, settings = _call(
2325 lambda: HarnessApplication().metrics(
2326 path, filters=filters, prices_file=prices, narrative=narrative
2327 )
2328 )
2329 html_file: Path | None = None
2330 if fmt is None:
2331 directory = output_dir or Path(settings["harnessDir"]) / "metrics"
2332 written = write_reports(report, directory)
2333 html_file = Path(written["html"])
2334 typer.echo(
2335 json.dumps(
2336 {"files": written, "totals": report["totals"], "filters": report["filters"]},
2337 indent=2,
2338 )
2339 )
2340 else:
2341 html_file = _print_metrics(render(report, fmt), fmt, output)
2342 if open_report: 2342 ↛ 2343line 2342 didn't jump to line 2343 because the condition on line 2342 was never true
2343 if html_file is None:
2344 directory = output_dir or Path(settings["harnessDir"]) / "metrics"
2345 html_file = Path(write_reports(report, directory, ("html",))["html"])
2346 webbrowser.open(html_file.resolve().as_uri())
2349@app.command()
2350def registry(json_output: bool | None = JSON_OPTION) -> None:
2351 """List the projects whose run registry lives in the state directory
2352 (`runtime.stateDir: auto`, `$HARNESS_STATE_DIR` or the user's data directory) with their
2353 latest runs: the runs of several repositories in one place."""
2354 _emit(_call(lambda: HarnessApplication().registry()), json_output)
2357@rules_app.command("health")
2358def rules_health(
2359 since: int | None = typer.Option(
2360 None, "--since", min=1, help="Only runs created in the last N days"
2361 ),
2362 json_output: bool | None = JSON_OPTION,
2363 path: Path = typer.Option(
2364 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
2365 ),
2366) -> None:
2367 """Show how each rule and validator behaved across the runs of the project: how often it
2368 fired, blocked a gate, was excepted, fired on a ChangeSet that was later corrected, fired in
2369 a rejected run or in a run later linked to an outcome. Read-only; nothing is changed and no
2370 figure is per person."""
2371 _emit(
2372 _call(lambda: HarnessApplication().rule_health(path, since_days=since)),
2373 json_output,
2374 kind="health",
2375 )
2378@outcome_app.command("record")
2379def outcome_record(
2380 run: str = RUN_OPTION,
2381 kind: str = typer.Option(..., "--kind", help="INCIDENT, REVERT, HOTFIX, REGRESSION or OTHER"),
2382 summary: str = typer.Option(..., "--summary", help="What happened"),
2383 reference: str | None = typer.Option(
2384 None, "--reference", help="Link or identifier of the incident, revert or fix"
2385 ),
2386 observed_at: str | None = typer.Option(
2387 None, "--observed-at", help="ISO 8601 instant it happened (default: now)"
2388 ),
2389 actor: str | None = typer.Option(
2390 None,
2391 "--actor",
2392 help=ACTOR_HELP,
2393 show_default=False,
2394 ),
2395 json_output: bool | None = JSON_OPTION,
2396 path: Path = typer.Option(
2397 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
2398 ),
2399) -> None:
2400 """Link something that happened after a run (an incident, a revert, a hotfix, a regression)
2401 to it. The outcome feeds `harness rules health` and the causal retrospective; nothing is
2402 applied. An actor id of an agent, validator or the harness exits with 5."""
2403 _emit(
2404 _call(
2405 lambda: _acting().record_outcome(
2406 path,
2407 execution_id=run,
2408 kind=kind,
2409 summary=summary,
2410 reference=reference,
2411 observed_at=observed_at,
2412 actor_id=actor,
2413 )
2414 ),
2415 json_output,
2416 )
2419@outcome_app.command("list")
2420def outcome_list(
2421 run: str | None = typer.Option(None, "--run", help="Only the outcomes of this run"),
2422 json_output: bool | None = JSON_OPTION,
2423 path: Path = typer.Option(
2424 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
2425 ),
2426) -> None:
2427 """List the outcomes linked to the runs of the project, oldest first."""
2428 _emit(_call(lambda: HarnessApplication().list_outcomes(path, run)), json_output)
2431@exceptions_app.command("list")
2432def exceptions_list(
2433 status: str = typer.Option("all", "--status", help="all, active or expired"),
2434 expiring_within: int | None = typer.Option(
2435 None, "--expiring-within", min=0, help="Only active exceptions expiring within N days"
2436 ),
2437 json_output: bool | None = JSON_OPTION,
2438 path: Path = typer.Option(
2439 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
2440 ),
2441) -> None:
2442 """List the exceptions of the project (review.exceptions): who granted each, on which run
2443 and digest, its scope, alternative evidence and follow-up, when it expires and the runs whose
2444 gate relied on it. An expired exception no longer covers any finding."""
2445 _emit(
2446 _call(
2447 lambda: HarnessApplication().list_exceptions(
2448 path, status=status, expiring_within=expiring_within
2449 )
2450 ),
2451 json_output,
2452 kind="exceptions",
2453 )
2456review_app = typer.Typer(invoke_without_command=True)
2457review_rules_app = typer.Typer(help="The review rule catalog and the reviewers' rules blocks")
2458review_hook_app = typer.Typer(help="The pre-push hook of the review panel")
2459app.add_typer(review_app, name="review")
2460review_app.add_typer(review_rules_app, name="rules")
2461review_app.add_typer(review_hook_app, name="hook")
2463PATH_OPTION: Any = typer.Option(
2464 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
2465)
2468@review_app.callback(invoke_without_command=True)
2469def review(
2470 ctx: typer.Context,
2471 run: str = RUN_OPTION_LATEST,
2472 diff: bool = typer.Option(False, "--diff", help="Include the ChangeSet diff (redacted)"),
2473 json_output: bool | None = JSON_OPTION,
2474 path: Path = PATH_OPTION,
2475) -> None:
2476 """Show the decision brief of a run: what was asked, what changed, the risks with file and
2477 line, what was verified on which ChangeSet digest and what was not, active exceptions,
2478 retries and corrections, what changed since the last decision and the exact decide
2479 command. It only reads the record. The subcommands manage the review panel (#57)."""
2480 if ctx.invoked_subcommand is not None:
2481 return
2482 _emit(
2483 _call(lambda: HarnessApplication().review(path, run, include_diff=diff)),
2484 json_output,
2485 kind="review",
2486 )
2489@app.command("review-code")
2490def review_code(
2491 mode: str = typer.Option(
2492 "manual",
2493 "--mode",
2494 help="manual: the branch against its base; hook: the same, fetching the base first (a "
2495 "failed fetch aborts); staged: the index against HEAD",
2496 ),
2497 base: str | None = typer.Option(
2498 None,
2499 "--base",
2500 help="Base branch or commit; default: the pull or merge request base of the CI, the "
2501 "branch convention (review.panel.baseBranches), then the default branch",
2502 ),
2503 head: str = typer.Option("HEAD", "--head", help="The commit to review (manual and hook)"),
2504 provider: str | None = typer.Option(
2505 None, "--provider", help="Provider of the reviewers (an agentProviders id or simulated)"
2506 ),
2507 fallback: str | None = typer.Option(
2508 None, "--fallback-provider", help="Provider of the one retry after an invalid answer"
2509 ),
2510 model: str | None = typer.Option(None, "--model", help="Force one model for every reviewer"),
2511 skip: list[str] | None = typer.Option(
2512 None, "--skip", help="A reviewer id to skip (repeatable)"
2513 ),
2514 pull_request: int | None = typer.Option(
2515 None,
2516 "--pull-request",
2517 help="Pull or merge request number for the comment (default: from the CI environment)",
2518 ),
2519 comment: bool | None = typer.Option(
2520 None,
2521 "--comment/--no-comment",
2522 help="Post one comment per passing result on the pull or merge request (default: "
2523 "review.panel.comment)",
2524 ),
2525 cache: bool = typer.Option(True, "--cache/--no-cache", help="Use the review cache"),
2526 path: Path = PATH_OPTION,
2527 json_output: bool | None = JSON_OPTION,
2528) -> None:
2529 """Review a change with the review panel outside a governed run: reviewers by domain over
2530 diff slices, the layered rule catalog, a fixed output contract and a verdict the harness
2531 recomputes. Rules a tool verifies never reach a model; reviewers run only on their
2532 signals; answers are cached. A passing review is recorded as refs/harness/review/pass/SHA
2533 (or pass-warn). Exit code 6 when the verdict is FAIL or UNKNOWN (under review.panel.mode
2534 enforce) or when hook mode cannot fetch the base."""
2535 result = _call(
2536 lambda: HarnessApplication().review_code(
2537 path,
2538 mode=mode,
2539 base=base,
2540 head=head,
2541 provider=provider,
2542 fallback=fallback,
2543 model=model,
2544 skip=tuple(skip or ()),
2545 pull_request=pull_request,
2546 comment=comment,
2547 cache=cache,
2548 )
2549 )
2550 _emit(result, json_output)
2551 if result.get("blocking"): 2551 ↛ exitline 2551 didn't return from function 'review_code' because the condition on line 2551 was always true
2552 raise typer.Exit(code=6)
2555@review_rules_app.command("show")
2556def review_rules_show(path: Path = PATH_OPTION, json_output: bool | None = JSON_OPTION) -> None:
2557 """Show the effective review rule catalog: the rules of the three layers (built-in,
2558 language packs, project) after precedence and supersedes, the inactive rules and why, the
2559 reviewers and the ones whose rules block drifted. Reads only."""
2560 _emit(_call(lambda: HarnessApplication().review_rules(path)), json_output)
2563@review_rules_app.command("sync")
2564def review_rules_sync(
2565 check: bool = typer.Option(
2566 False, "--check", help="Only report project reviewers whose rules block drifted (exit 6)"
2567 ),
2568 path: Path = PATH_OPTION,
2569 json_output: bool | None = JSON_OPTION,
2570) -> None:
2571 """Write the generated rules block of every project reviewer (.harness/review/agents) from
2572 the catalog, between its BEGIN and END markers; the only writer of that block. With
2573 --check nothing is written and a drift exits with 6."""
2574 result = _call(lambda: HarnessApplication().review_rules_sync(path, check=check))
2575 _emit(result, json_output)
2576 if result["status"] != "PASSED":
2577 raise typer.Exit(code=6)
2580@review_app.command("verify")
2581def review_verify(
2582 sha: str = typer.Option("HEAD", "--sha", help="The commit whose review evidence to check"),
2583 path: Path = PATH_OPTION,
2584 json_output: bool | None = JSON_OPTION,
2585) -> None:
2586 """Check the review evidence of a commit (refs/harness/review/pass/SHA or pass-warn)
2587 without calling any model: the report is bound to the commit, its digest is intact and its
2588 diff is the diff between its base and the commit. Exit code 6 when it does not verify."""
2589 result = _call(lambda: HarnessApplication().review_verify(path, sha))
2590 _emit(result, json_output)
2591 if not result.get("valid"):
2592 raise typer.Exit(code=6)
2595@review_hook_app.command("install")
2596def review_hook_install(
2597 force: bool = typer.Option(
2598 False, "--force", help="Replace a pre-push hook the harness did not write"
2599 ),
2600 path: Path = PATH_OPTION,
2601 json_output: bool | None = JSON_OPTION,
2602) -> None:
2603 """Install a pre-push hook that runs harness review-code --mode hook: a FAIL or UNKNOWN
2604 verdict, or a base that cannot be fetched, stops the push."""
2605 _emit(_call(lambda: HarnessApplication().review_hook_install(path, force=force)), json_output)
2608@review_app.command("variance")
2609def review_variance(
2610 runs: int = typer.Option(3, "--runs", min=2, max=10, help="Identical reviews to run"),
2611 mode: str = typer.Option("manual", "--mode", help="manual or staged"),
2612 base: str | None = typer.Option(None, "--base", help="Base branch or commit"),
2613 provider: str | None = typer.Option(None, "--provider", help="Provider of the reviewers"),
2614 model: str | None = typer.Option(None, "--model", help="Force one model for every reviewer"),
2615 path: Path = PATH_OPTION,
2616 json_output: bool | None = JSON_OPTION,
2617) -> None:
2618 """Run the same review several times without cache and report its variance: verdict
2619 stability, how often each finding appears and the mean pairwise agreement (Jaccard). Every
2620 run calls the reviewers again."""
2621 _emit(
2622 _call(
2623 lambda: HarnessApplication().review_variance(
2624 path, runs=runs, mode=mode, base=base, provider=provider, model=model
2625 )
2626 ),
2627 json_output,
2628 )
2631@artifact_app.command("show")
2632def artifact_show(
2633 reference: str = typer.Argument(
2634 ..., help="artifact://sha256/<hex>, sha256:<hex> or a unique hex prefix (6+ characters)"
2635 ),
2636 describe: bool = typer.Option(
2637 False, "--describe", help="Print the descriptor (digest, size, media type, metadata)"
2638 ),
2639 path: Path = typer.Option(
2640 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
2641 ),
2642) -> None:
2643 """Print an artifact's content after verifying its digest, or its descriptor with
2644 --describe. Artifacts are stored redacted; a digest mismatch exits with 1."""
2645 descriptor, data = _call(lambda: HarnessApplication().show_artifact(path, reference))
2646 if describe:
2647 _emit(descriptor)
2648 return
2649 sys.stdout.flush()
2650 sys.stdout.buffer.write(data)
2651 sys.stdout.flush()
2654@app.command()
2655def retrospect(
2656 run: str = RUN_OPTION_LATEST,
2657 path: Path = typer.Option(
2658 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
2659 ),
2660) -> None:
2661 """Derive non-mutating observations and recommendations from a closed run. Nothing is
2662 applied automatically."""
2663 _emit(_call(lambda: HarnessApplication().retrospect(path, run)))
2666@recommendation_app.command("list")
2667def recommendation_list(
2668 run: str = RUN_OPTION_LATEST,
2669 path: Path = typer.Option(
2670 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
2671 ),
2672) -> None:
2673 """List the retrospective recommendations of a run with the decision recorded for each."""
2674 _emit(_call(lambda: HarnessApplication().list_recommendations(path, run)))
2677@recommendation_app.command("decide")
2678def recommendation_decide(
2679 run: str = RUN_OPTION,
2680 recommendation: str = typer.Option(
2681 ..., "--recommendation", help="Recommendation identifier shown by retrospect"
2682 ),
2683 decision: RecommendationDecision = typer.Option(
2684 ..., "--decision", case_sensitive=False, help="Decision on the recommendation"
2685 ),
2686 rationale: str = typer.Option(
2687 ..., "--rationale", help="Justification recorded with the decision"
2688 ),
2689 statement: str | None = typer.Option(
2690 None, "--statement", help="Edited text of the recommendation; required with EDIT"
2691 ),
2692 actor: str | None = typer.Option(
2693 None,
2694 "--actor",
2695 help=ACTOR_HELP,
2696 show_default=False,
2697 ),
2698 path: Path = typer.Option(
2699 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
2700 ),
2701) -> None:
2702 """Accept, edit or reject a retrospective recommendation. The decision is kept as
2703 retrospective memory: an accepted or edited recommendation enters the context of later
2704 runs, a rejected one stays as history. A second decision on the same recommendation exits
2705 with code 5; nothing is applied to rules, gates or configuration."""
2706 _emit(
2707 _call(
2708 lambda: _acting().decide_recommendation(
2709 path,
2710 execution_id=run,
2711 recommendation_id=recommendation,
2712 decision=decision,
2713 actor_id=actor,
2714 rationale=rationale,
2715 statement=statement,
2716 )
2717 )
2718 )
2721@plugins_app.command("list")
2722def plugins_list() -> None:
2723 """List the built-in extensions and the external plugin protocol version."""
2724 _emit(
2725 {
2726 "builtIns": [
2727 {"id": "profile/python", "kind": "technology-profile", "version": "1.0"},
2728 {"id": "profile/node", "kind": "technology-profile", "version": "1.0"},
2729 {"id": "agent/simulated", "kind": "agent-provider", "version": "1"},
2730 {"id": "review/independent", "kind": "validator", "version": "1"},
2731 ],
2732 "externalProtocol": "1.0",
2733 }
2734 )
2737@benchmark_app.command("run")
2738def benchmark_run(
2739 output: Path | None = typer.Option(None, "--output", help=_OUTPUT_HELP),
2740 iterations: int = typer.Option(
2741 1000, "--iterations", min=10, max=100000, help="Iterations per in-process operation"
2742 ),
2743) -> None:
2744 """Run the synthetic microbenchmarks (hashing, transitions, gates, events, artifacts,
2745 process launch)."""
2746 from governed_harness.benchmark.runner import run_benchmarks
2748 result = _call(lambda: run_benchmarks(iterations=iterations))
2749 data = json.dumps(result, indent=2, sort_keys=True).encode("utf-8")
2750 if output:
2751 output.parent.mkdir(parents=True, exist_ok=True)
2752 output.write_bytes(data)
2753 typer.echo(str(output))
2754 else:
2755 typer.echo(data.decode())
2758@benchmark_app.command("scenarios")
2759def benchmark_scenarios(
2760 output: Path | None = typer.Option(None, "--output", help=_OUTPUT_HELP),
2761 iterations: int = typer.Option(
2762 3, "--iterations", min=1, max=100, help="Repetitions per scenario"
2763 ),
2764) -> None:
2765 """Compare a direct patch-and-test path with the complete governed path on generated Python
2766 and Node.js projects."""
2767 from governed_harness.benchmark.scenarios import run_scenario_benchmarks
2769 result = _call(lambda: run_scenario_benchmarks(iterations=iterations))
2770 data = json.dumps(result, indent=2, sort_keys=True).encode("utf-8")
2771 if output:
2772 output.parent.mkdir(parents=True, exist_ok=True)
2773 output.write_bytes(data)
2774 typer.echo(str(output))
2775 else:
2776 typer.echo(data.decode())
2779@api_app.command("serve")
2780def api_serve(
2781 path: Path = typer.Option(
2782 default_factory=Path.cwd, show_default=_CURRENT_DIRECTORY, help=_PROJECT_HELP
2783 ),
2784 host: str = typer.Option("127.0.0.1", "--host", help="Bind address; keep the loopback default"),
2785 port: int = typer.Option(8765, "--port", min=1, max=65535, help="TCP port"),
2786) -> None:
2787 """Serve the local API and web dashboard. Keep it bound to 127.0.0.1.
2789 With the api section that harness init writes, every route requires Authorization: Bearer
2790 TOKEN. Your token comes from the variable in api.tokenEnv (HARNESS_API_TOKEN by default);
2791 when it is not set, a new token is generated and printed once on standard error. Without
2792 the section there is no authentication, as in 1.0.0."""
2793 import uvicorn
2795 from governed_harness.api import create_app
2796 from governed_harness.api.access_log import log_config
2797 from governed_harness.api.auth import api_settings, start_token
2799 settings = _call(lambda: api_settings(path))
2800 token = None
2801 if settings.enabled:
2802 token = _call(lambda: start_token(settings))
2803 if token.generated:
2804 # Shown once, here only: never logged, stored or sent anywhere else.
2805 typer.echo(
2806 f"API token of {settings.start_user} ({settings.start_role}), shown once: "
2807 f"{token.value}\nSet {settings.start_token_env} to choose it instead.",
2808 err=True,
2809 )
2810 else:
2811 typer.echo(
2812 f"API token of {settings.start_user} ({settings.start_role}) taken from "
2813 f"{token.source}.",
2814 err=True,
2815 )
2816 else:
2817 typer.echo(
2818 "warning: the API has no authentication (no api section in project.yaml, or "
2819 "api.auth: off); anyone who reaches the port can read runs and record decisions.",
2820 err=True,
2821 )
2822 if host not in {"127.0.0.1", "::1", "localhost"}: 2822 ↛ 2823line 2822 didn't jump to line 2823 because the condition on line 2822 was never true
2823 typer.echo(
2824 f"warning: binding to {host} exposes the API beyond this machine; the harness is "
2825 "not a sandbox and the token travels over plain HTTP.",
2826 err=True,
2827 )
2828 api = _call(lambda: create_app(path, start_token=token))
2829 for notice in api.state.auth_notices:
2830 typer.echo(f"warning: {notice}", err=True)
2831 # The access log never holds query strings, where a mistaken token would be written (#174).
2832 uvicorn.run(api, host=host, port=port, log_level="info", log_config=log_config())
2835def main() -> None:
2836 app()
2839if __name__ == "__main__": 2839 ↛ 2840line 2839 didn't jump to line 2840 because the condition on line 2839 was never true
2840 main()