Coverage for src/governed_harness/api/app.py: 90%
211 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 os
4from collections.abc import Callable, Mapping
5from pathlib import Path
6from typing import Any, Literal, NoReturn
8from fastapi import FastAPI, HTTPException, Request
9from fastapi.responses import HTMLResponse, Response
10from pydantic import BaseModel, ConfigDict
11from starlette.middleware.trustedhost import TrustedHostMiddleware
13from governed_harness import __version__
14from governed_harness.api.auth import (
15 PRINCIPAL_SCOPE_KEY,
16 AuthenticationMiddleware,
17 DecisionAuditLog,
18 Principal,
19 StartToken,
20 TokenAuthenticator,
21 api_settings,
22)
23from governed_harness.application import HarnessApplication
24from governed_harness.application.exceptions import ExceptionOptions
25from governed_harness.configuration import ConfigurationResolver
26from governed_harness.configuration.api import ApiConfig, ApiRole
27from governed_harness.domain.actors import DEFAULT_API_ACTOR
28from governed_harness.domain.enums import DecisionKind
29from governed_harness.domain.errors import HarnessError, IntegrityError, NonHumanActorError
32class DecisionRequest(BaseModel):
33 model_config = ConfigDict(extra="forbid")
34 decision: DecisionKind
35 change_set_digest: str
36 actor_id: str | None = None
37 """The person deciding; without it, the Git user under ``governance.deciderIdentity: git``,
38 otherwise ``human.web``. Agent, validator and harness ids are refused (403)."""
39 rationale: str
40 continue_after: bool = True
41 expires_in: str | None = None
42 expires_at: str | None = None
43 scope: tuple[str, ...] = ()
44 alternative_evidence: str | None = None
45 follow_up: str | None = None
46 checked_items: tuple[str, ...] = ()
47 """Checklist items the person verified (``review.manualChecklist``, #55)."""
50def trusted_hosts(workspace: Path) -> tuple[str, ...] | None:
51 """``governance.trustedHosts`` of the project, ``None`` when it is not set (or there is no
52 valid configuration, which every endpoint then reports)."""
53 try:
54 project = ConfigurationResolver().resolve(workspace).project
55 except (HarnessError, OSError):
56 return None
57 return project.governance_settings.trusted_hosts
60_ERRORS: dict[int, str] = {
61 400: "The workspace configuration or the query is not valid.",
62 401: "Authentication required (api.auth: token).",
63 403: (
64 "The authenticated user lacks the role, the actor is not a person, or the API runs "
65 "without authentication and records no decision."
66 ),
67 404: "The run or its records were not found.",
68 409: "The decision was refused, or the evidence chain does not verify.",
69 500: "The API audit log cannot be written.",
70}
72UNAUTHENTICATED_DECISION_DETAIL = (
73 "the API runs without authentication (no api section in .harness/project.yaml, or "
74 "api.auth: off) and records no decision; add an api section (auth: token) and send "
75 "Authorization: Bearer TOKEN, or decide with harness gate decide"
76)
79def _responses(*codes: int) -> dict[int | str, dict[str, Any]]:
80 """The error responses a route documents in the OpenAPI description."""
81 return {code: {"description": _ERRORS[code]} for code in codes}
84def _answer[T](status: int, call: Callable[[], T]) -> T:
85 """``call()``, any error answered with ``status`` and its message."""
86 try:
87 return call()
88 except Exception as error:
89 raise HTTPException(status_code=status, detail=str(error)) from error
92def create_app(
93 workspace: Path,
94 *,
95 start_token: StartToken | str | None = None,
96 environ: Mapping[str, str] | None = None,
97) -> FastAPI:
98 """The API of ``workspace``. Under the ``api`` section of ``project.yaml`` (#18) every
99 route requires a bearer token: ``start_token`` (``harness api serve`` passes the one it
100 took from ``api.tokenEnv`` or generated; without it, the value of ``api.tokenEnv`` when
101 set) and the tokens of ``api.users``, read from ``environ`` (default ``os.environ``).
102 The notices of the authentication setup (users who cannot sign in) are in
103 ``app.state.auth_notices``."""
104 root = workspace.resolve(strict=True)
105 settings = api_settings(root)
106 application = HarnessApplication()
107 api = FastAPI(
108 title="Governed Agent Harness",
109 version=__version__,
110 description="Local observability and human-decision API for a governed harness workspace.",
111 )
112 notices: list[str] = []
113 api.state.auth_notices = notices
114 audit: DecisionAuditLog | None = None
115 if settings.enabled:
116 source = os.environ if environ is None else environ
117 token = start_token if start_token is not None else source.get(settings.start_token_env)
118 authenticator = TokenAuthenticator.from_settings(settings, token, source, notices)
119 if not authenticator.users:
120 notices.append("no API token is available: every request will be refused (401)")
121 api.add_middleware(
122 AuthenticationMiddleware, authenticator=authenticator, sign_in_page=_SIGN_IN
123 )
124 audit = DecisionAuditLog.for_workspace(root)
125 hosts = trusted_hosts(root)
126 if hosts is not None:
127 # A page on another origin can reach a loopback server through DNS rebinding; requests
128 # whose Host header is not a configured name are answered with 400. Added last, it runs
129 # before the authentication.
130 api.add_middleware(TrustedHostMiddleware, allowed_hosts=list(hosts))
131 _workspace_routes(api, root, application, settings)
132 _run_routes(api, root, application, settings, audit)
133 _registry_routes(api, root, application)
134 _metrics_routes(api, root, application)
136 @api.get("/", response_class=HTMLResponse)
137 def index() -> str:
138 return _dashboard_html()
140 return api
143def _workspace_routes(
144 api: FastAPI, root: Path, application: HarnessApplication, settings: ApiConfig
145) -> None:
146 """The session, the configuration, the health and the runs of the workspace."""
148 @api.get("/api/session", responses=_responses(401, 403))
149 def session(request: Request) -> dict[str, object]:
150 """Who this request is authenticated as (``authentication: off`` without the ``api``
151 section, or with ``api.auth: off``)."""
152 principal = _authorize(settings, request, "viewer")
153 if principal is None:
154 return {"authentication": "off"}
155 return {"authentication": "token", "userId": principal.user_id, "role": principal.role}
157 @api.get("/api/config", responses=_responses(400, 401, 403))
158 def config(request: Request) -> dict[str, object]:
159 """``harness config validate`` of the workspace (role ``admin``)."""
160 _authorize(settings, request, "admin")
161 return _answer(400, lambda: application.validate_config(root))
163 @api.get("/api/health")
164 def health() -> dict[str, object]:
165 return application.doctor(root)
167 @api.get("/api/runs", responses=_responses(400))
168 def runs() -> list[dict[str, object]]:
169 return _answer(
170 400,
171 lambda: [
172 item.model_dump(mode="json", by_alias=True) for item in application.list_runs(root)
173 ],
174 )
177_TRACE_MEDIA = {
178 "json": "application/json",
179 "markdown": "text/markdown",
180 "jsonl": "application/x-ndjson",
181 "sarif": "application/sarif+json",
182}
185def _run_routes(
186 api: FastAPI,
187 root: Path,
188 application: HarnessApplication,
189 settings: ApiConfig,
190 audit: DecisionAuditLog | None,
191) -> None:
192 """The records of one run (status, brief, trace, evidence, retrospective, findings,
193 verification) and its decision."""
195 @api.get("/api/runs/{execution_id}", responses=_responses(404))
196 def run_status(execution_id: str) -> dict[str, object]:
197 return _answer(404, lambda: application.status(root, execution_id))
199 @api.get("/api/runs/{execution_id}/review", responses=_responses(404))
200 def run_review(execution_id: str, diff: bool = False) -> dict[str, object]:
201 return _answer(404, lambda: application.review(root, execution_id, include_diff=diff))
203 @api.get("/api/runs/{execution_id}/trace", responses=_responses(404, 409))
204 def run_trace(
205 execution_id: str, format: Literal["json", "markdown", "jsonl", "sarif"] = "json"
206 ) -> Response:
207 try:
208 data = application.trace(root, execution_id, format)
209 except IntegrityError as error:
210 raise HTTPException(status_code=409, detail=str(error)) from error
211 except Exception as error:
212 raise HTTPException(status_code=404, detail=str(error)) from error
213 return Response(data, media_type=_TRACE_MEDIA[format])
215 @api.get("/api/runs/{execution_id}/evidence", responses=_responses(404))
216 def run_evidence(execution_id: str) -> list[dict[str, object]]:
217 return _answer(404, lambda: application.list_evidence(root, execution_id))
219 @api.get("/api/runs/{execution_id}/retrospective", responses=_responses(404))
220 def run_retrospective(execution_id: str) -> dict[str, object]:
221 return _answer(
222 404,
223 lambda: application.retrospect(root, execution_id).model_dump(
224 mode="json", by_alias=True
225 ),
226 )
228 @api.get("/api/runs/{execution_id}/findings", responses=_responses(404))
229 def run_findings(execution_id: str) -> list[dict[str, object]]:
230 return _answer(
231 404,
232 lambda: [
233 item.model_dump(mode="json", by_alias=True)
234 for item in application.list_findings(root, execution_id)
235 ],
236 )
238 _decision_route(api, root, settings, audit)
240 @api.get("/api/runs/{execution_id}/verification", responses=_responses(404))
241 def run_verification(execution_id: str) -> dict[str, object]:
242 return _answer(404, lambda: application.verification(root, execution_id))
245def _decision_route(
246 api: FastAPI, root: Path, settings: ApiConfig, audit: DecisionAuditLog | None
247) -> None:
248 @api.post("/api/runs/{execution_id}/decision", responses=_responses(401, 403, 409, 500))
249 def decide(execution_id: str, request: DecisionRequest, http: Request) -> dict[str, object]:
250 audited = _Audited(audit, http, execution_id, request)
251 actor_id = _decider(settings, http, request, audited)
252 return _record_decision(root, execution_id, request, actor_id, audited)
255def _decider(
256 settings: ApiConfig, http: Request, request: DecisionRequest, audited: _Audited
257) -> str | None:
258 """The actor of a decision: the authenticated person (a reviewer or an admin, and the
259 ``actor_id`` sent, if any, must be theirs). Without authentication (no ``api`` section, or
260 ``api.auth: off``) no decision is recorded: any process that reached the port could
261 otherwise decide under any human actor id (F13). Reads stay open."""
262 principal = _authorize(settings, http, "viewer")
263 if principal is None:
264 raise HTTPException(status_code=403, detail=UNAUTHENTICATED_DECISION_DETAIL)
265 # The audit attempt is written before anything is decided (if it cannot be written,
266 # nothing is).
267 audited.attempt(principal)
268 if not principal.allows("reviewer"):
269 audited.refuse(
270 403,
271 f"user {principal.user_id} has the role {principal.role}; recording a "
272 "decision needs the role reviewer or admin",
273 )
274 if request.actor_id and request.actor_id != principal.user_id:
275 audited.refuse(
276 403,
277 f"actor_id {request.actor_id!r} is not the authenticated user "
278 f"{principal.user_id!r}; leave it out or send {principal.user_id!r}",
279 )
280 return principal.user_id
283def _record_decision(
284 root: Path,
285 execution_id: str,
286 request: DecisionRequest,
287 actor_id: str | None,
288 audited: _Audited,
289) -> dict[str, object]:
290 try:
291 acting = HarnessApplication() # its notices belong to this request only
292 decision, execution = acting.decide_gate(
293 root,
294 execution_id=execution_id,
295 decision=request.decision,
296 change_set_digest=request.change_set_digest,
297 actor_id=actor_id,
298 rationale=request.rationale,
299 continue_after=request.continue_after,
300 default_actor=DEFAULT_API_ACTOR,
301 exception=ExceptionOptions(
302 expires_in=request.expires_in,
303 expires_at=request.expires_at,
304 scope=request.scope,
305 alternative_evidence=request.alternative_evidence,
306 follow_up=request.follow_up,
307 ),
308 checked_items=request.checked_items,
309 )
310 body: dict[str, object] = {
311 "decision": decision.model_dump(mode="json", by_alias=True),
312 "execution": execution.model_dump(mode="json", by_alias=True),
313 }
314 if acting.notices: 314 ↛ 315line 314 didn't jump to line 315 because the condition on line 314 was never true
315 body["warnings"] = list(acting.notices)
316 except NonHumanActorError as error:
317 audited.refuse(403, str(error), error)
318 except Exception as error:
319 audited.refuse(409, str(error), error)
320 audited.recorded(decision.decision_id, decision.actor.actor_id)
321 return body
324def _registry_routes(api: FastAPI, root: Path, application: HarnessApplication) -> None:
325 """The run registry, the inbox and the exceptions."""
327 @api.get("/api/registry", responses=_responses(400))
328 def registry() -> dict[str, object]:
329 """The projects of the shared run registry (``runtime.stateDir``, #55)."""
330 return _answer(400, application.registry)
332 @api.get("/api/inbox", responses=_responses(400))
333 def pending() -> list[dict[str, object]]:
334 return _answer(400, lambda: application.inbox(root))
336 @api.get("/api/exceptions", responses=_responses(400))
337 def exceptions(status: Literal["all", "active", "expired"] = "all") -> list[dict[str, object]]:
338 return _answer(400, lambda: application.list_exceptions(root, status=status))
341def _metrics_routes(api: FastAPI, root: Path, application: HarnessApplication) -> None:
342 @api.get("/api/metrics", responses=_responses(400))
343 def metrics(
344 since: str | None = None,
345 task: str | None = None,
346 model: str | None = None,
347 agent: str | None = None,
348 all_repos: bool = False,
349 ) -> dict[str, Any]:
350 """``harness metrics --format json`` (#58): computed from the records, no model call."""
351 return _metrics_report(application, root, since, task, model, agent, all_repos)
353 @api.get("/api/metrics/report", response_class=HTMLResponse, responses=_responses(400))
354 def metrics_page(
355 since: str | None = None,
356 task: str | None = None,
357 model: str | None = None,
358 agent: str | None = None,
359 all_repos: bool = False,
360 ) -> str:
361 """The self-contained HTML report of ``harness metrics --format html``."""
362 from governed_harness.metrics import render
364 report = _metrics_report(application, root, since, task, model, agent, all_repos)
365 return render(report, "html")
368def _metrics_report(
369 application: HarnessApplication,
370 root: Path,
371 since: str | None,
372 task: str | None,
373 model: str | None,
374 agent: str | None,
375 all_repos: bool,
376) -> dict[str, Any]:
377 from governed_harness.metrics import Filters, parse_since
379 try:
380 filters = Filters(
381 since=parse_since(since), task=task, model=model, agent=agent, all_repos=all_repos
382 )
383 except ValueError as error:
384 raise HTTPException(status_code=400, detail=str(error)) from error
385 report, _settings = _answer(400, lambda: application.metrics(root, filters=filters))
386 return report
389def _authorize(settings: ApiConfig, request: Request, role: ApiRole) -> Principal | None:
390 """The authenticated person when they hold ``role`` (403 otherwise); ``None`` when the
391 API runs without authentication (no ``api`` section, or ``api.auth: off``)."""
392 if not settings.enabled:
393 return None
394 principal = request.scope.get(PRINCIPAL_SCOPE_KEY)
395 if not isinstance(principal, Principal): 395 ↛ 396line 395 didn't jump to line 396 because the condition on line 395 was never true
396 raise HTTPException(status_code=401, detail="authentication required")
397 if not principal.allows(role):
398 raise HTTPException(
399 status_code=403,
400 detail=f"user {principal.user_id} has the role {principal.role}; this needs {role}",
401 )
402 return principal
405class _Audited:
406 """The audit records of one API decision, written only when authentication is on: an
407 attempt before anything is decided and its outcome. Never a token."""
409 def __init__(
410 self,
411 log: DecisionAuditLog | None,
412 http: Request,
413 execution_id: str,
414 request: DecisionRequest,
415 ) -> None:
416 self.log = log
417 self.record: dict[str, object] = {
418 "route": f"{http.method} {http.url.path}",
419 "executionId": execution_id,
420 "decision": request.decision.value,
421 "changeSetDigest": request.change_set_digest,
422 "requestedActorId": request.actor_id or None,
423 "clientHost": http.client.host if http.client else None,
424 }
426 def _append(self, **fields: object) -> None:
427 if self.log is None: 427 ↛ 428line 427 didn't jump to line 428 because the condition on line 427 was never true
428 return
429 try:
430 self.log.append({**self.record, **fields})
431 except OSError as error:
432 raise HTTPException(
433 status_code=500,
434 detail=f"cannot write the API audit log {self.log.path}: {error.strerror}",
435 ) from error
437 def attempt(self, principal: Principal) -> None:
438 self.record["userId"] = principal.user_id
439 self.record["role"] = principal.role
440 self._append(outcome="attempted")
442 def refuse(self, status: int, detail: str, cause: BaseException | None = None) -> NoReturn:
443 self._append(outcome="refused", status=status, reason=detail)
444 raise HTTPException(status_code=status, detail=detail) from cause
446 def recorded(self, decision_id: str, actor_id: str) -> None:
447 self._append(outcome="recorded", status=200, decisionId=decision_id, actorId=actor_id)
450def _dashboard_html() -> str:
451 return _DASHBOARD
454_DASHBOARD = """<!doctype html>
455<html lang="en">
456<head>
457<meta charset="utf-8">
458<meta name="viewport" content="width=device-width,initial-scale=1">
459<title>Governed Agent Harness</title>
460<style>
461:root { font-family: Inter, ui-sans-serif, system-ui, sans-serif; color-scheme: dark; }
462body { margin: 0; background: #111827; color: #e5e7eb; }
463header { padding: 24px 32px; background: #0f172a; border-bottom: 1px solid #334155; }
464main { display: grid; grid-template-columns: minmax(300px, 34%) 1fr; gap: 20px; padding: 24px 32px; }
465section { background: #1f2937; border: 1px solid #374151; border-radius: 12px; padding: 18px; min-width: 0; }
466h1,h2,h3 { margin: 0 0 12px; } h3 { margin-top: 18px; font-size: 15px; }
467button,input,textarea { box-sizing: border-box; border: 1px solid #475569; border-radius: 8px; background: #111827; color: inherit; padding: 10px; }
468button { cursor: pointer; } .run { width: 100%; text-align: left; margin: 6px 0; }
469.actions { display: grid; grid-template-columns: repeat(4,1fr); gap: 8px; margin-top: 12px; }
470label { display: block; margin-top: 10px; font-size: 13px; } input,textarea { width: 100%; margin-top: 4px; }
471textarea { min-height: 80px; resize: vertical; }
472pre { white-space: pre-wrap; overflow-wrap: anywhere; font-size: 12px; max-height: 50vh; overflow: auto; }
473table { border-collapse: collapse; width: 100%; font-size: 13px; }
474td,th { text-align: left; padding: 4px 6px; border-bottom: 1px solid #374151; vertical-align: top; }
475ul { margin: 4px 0; padding-left: 20px; } li { margin: 2px 0; } code { overflow-wrap: anywhere; }
476.status { font-weight: 700; } .PASSED { color: #34d399; } .BLOCKED,.FAILED,.INCONCLUSIVE { color: #fbbf24; } .ERROR { color: #fb7185; }
477.blocks { color: #fb7185; font-weight: 700; }
478.notice { margin-top: 10px; padding: 9px; border-radius: 8px; background: #0f172a; font-size: 13px; }
479[hidden] { display: none !important; }
480.tabs { display: flex; gap: 8px; padding: 16px 32px 0; } .tabs [aria-selected="true"] { border-color: #34d399; }
481.metrics { margin: 24px 32px; }
482@media (max-width: 850px) { main { grid-template-columns: 1fr; padding: 16px; } .actions { grid-template-columns: 1fr 1fr; } }
483</style>
484</head>
485<body>
486<header><h1>Governed Agent Harness</h1><div>Local observability and explicit, digest-bound human decisions.</div><div id="session" class="notice"></div></header>
487<nav class="tabs" role="tablist" aria-label="Views">
488<button role="tab" id="tab-runs" aria-selected="true" aria-controls="view-runs">Runs</button>
489<button role="tab" id="tab-metrics" aria-selected="false" aria-controls="view-metrics">Metrics</button>
490</nav>
491<section id="view-metrics" role="tabpanel" aria-labelledby="tab-metrics" class="metrics" hidden>
492<h2>Metrics</h2>
493<div class="notice">Computed from the run records, no model call (<code>harness metrics</code>). <label style="display:inline"><input type="checkbox" id="all-repos" style="width:auto"> All repositories of the registry</label> <button id="metrics-refresh">Refresh</button></div>
494<div id="metrics-summary">Loading...</div>
495<iframe id="metrics-report" title="Metrics report" style="width:100%;height:70vh;border:0;margin-top:12px;background:#fff;border-radius:8px"></iframe>
496</section>
497<main id="view-runs" role="tabpanel" aria-labelledby="tab-runs">
498<section><h2>Waiting for a person</h2><div id="inbox">Loading...</div>
499<h2 style="margin-top:20px">Executions</h2><div id="runs">Loading...</div>
500<h2 style="margin-top:20px">Repositories</h2><div id="registry">Loading...</div>
501<div class="notice">Refreshes every 5 seconds.</div></section>
502<section><h2>Selected execution</h2><div id="decision"></div><div id="brief">Select an execution.</div>
503<details><summary>Status (JSON)</summary><pre id="detail"></pre></details></section>
504</main>
505<script>
506let selected = null; let brief = null; let selectedId = null; let decisionKey = null; let session = {authentication:'off'};
507const TOKEN_KEY='governed-harness.api-token';
508function esc(value){ return String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); }
509function apiToken(){ try { return sessionStorage.getItem(TOKEN_KEY); } catch(error){ return null; } }
510function signOut(){ try { sessionStorage.removeItem(TOKEN_KEY); } catch(error){} location.reload(); }
511// Every call of the dashboard goes through request(): it sends the token kept in this tab
512// (api.auth: token) as Authorization: Bearer, and signs out when the server refuses it.
513async function request(url, options){
514 const init={...(options||{})}; const asText=init.asText; delete init.asText;
515 const headers=new Headers(init.headers||{}); const token=apiToken();
516 if(token) headers.set('Authorization','Bearer '+token); init.headers=headers;
517 const response=await fetch(url, init);
518 if(response.status===401 && token){ signOut(); throw new Error('The API token was refused; sign in again.'); }
519 if(asText && response.ok) return await response.text();
520 const body=await response.json();
521 if(!response.ok) throw new Error(body.detail || JSON.stringify(body)); return body;
522}
523async function loadSession(){
524 session=await request('/api/session'); const target=document.getElementById('session');
525 if(session.authentication==='token'){ target.innerHTML=`Signed in as <code>${esc(session.userId)}</code> (${esc(session.role)}) <button id="sign-out">Sign out</button>`; document.getElementById('sign-out').onclick=signOut; }
526 else { target.textContent='No authentication (no api section in project.yaml): keep the server on 127.0.0.1.'; }
527}
528async function loadRuns(){
529 const runs=await request('/api/runs'); const target=document.getElementById('runs'); target.innerHTML='';
530 for(const run of runs){ const button=document.createElement('button'); button.className='run';
531 button.innerHTML=`<span class="status ${esc(run.status)}">${esc(run.status)}</span> ${esc(run.executionId)}<br><small>${esc(run.currentPhase)}</small>`;
532 button.onclick=()=>loadRun(run.executionId); target.appendChild(button); }
533 if(!runs.length) target.textContent='No executions recorded.';
534}
535async function loadRegistry(){
536 const value=await request('/api/registry'); const target=document.getElementById('registry');
537 target.innerHTML=value.projects.length?list(value.projects, p=>`<li><code>${esc(p.projectId)}</code> ${esc(p.workspace)}: ${p.runs.length} run(s)${p.runs.length?`, latest ${esc(p.runs[0].status)} in ${esc(p.runs[0].currentPhase)}`:''}</li>`):'No registry outside the workspaces (runtime.stateDir).';
538}
539async function loadInbox(){
540 const items=await request('/api/inbox'); const target=document.getElementById('inbox'); target.innerHTML='';
541 for(const item of items){ const button=document.createElement('button'); button.className='run';
542 const state=item.kind==='decision'?`gate ${esc(item.gateStatus)}, ${item.blockingFindings} blocking`:item.kind==='deferred'?`${esc(item.itemId)} ${esc(item.status)}${item.warning?', '+esc(item.warning):''}`:item.kind==='preflight'?'preflight UNAVAILABLE':item.kind==='clarification'?`${item.questions} question(s)`:esc(item.summary||'');
543 button.innerHTML=`<b>${esc(item.kind)}</b> ${esc(item.taskTitle)}<br><small>${esc(item.executionId)} - ${state} - ${item.waitingHours} h</small>`;
544 button.onclick=()=>loadRun(item.executionId); target.appendChild(button); }
545 if(!items.length) target.textContent='Nothing waits for a person.';
546}
547async function loadRun(id){
548 selectedId=id;
549 selected=await request('/api/runs/'+encodeURIComponent(id));
550 brief=await request('/api/runs/'+encodeURIComponent(id)+'/review');
551 document.getElementById('detail').textContent=JSON.stringify(selected,null,2);
552 renderBrief(brief);
553 const key=`${id}|${brief.run.awaitingDecision}|${brief.run.changeSetDigest}`;
554 if(key!==decisionKey){ decisionKey=key; renderDecision(id, brief); }
555}
556async function refresh(){
557 try { await loadInbox(); await loadRuns(); await loadRegistry(); if(selectedId){ await loadRun(selectedId); } }
558 catch(error){ document.getElementById('runs').textContent=error.message; }
559}
560function list(items, render){ return items.length ? '<ul>'+items.map(render).join('')+'</ul>' : '<div>none</div>'; }
561function renderBrief(b){
562 const files=b.changed.files.map(f=>`<tr><td>${esc(f.status)}</td><td><code>${esc(f.path)}</code></td><td>+${f.additions} -${f.deletions}</td></tr>`).join('');
563 const risks=b.risks.map(r=>`<tr><td class="${r.blocking?'blocks':''}">${r.blocking?'blocks':'info'}</td><td>${esc(r.severity)}</td><td><code>${esc(r.ruleId)}</code></td><td><code>${esc(r.location)}</code></td><td>${esc(r.message)}</td></tr>`).join('');
564 const checks=b.verified.validations.map(v=>`<tr><td class="${esc(v.status)}">${esc(v.status)}</td><td><code>${esc(v.validatorId)}</code></td><td>${v.mandatory?'mandatory':'optional'}</td><td>${v.attempts}</td></tr>`).join('');
565 let delta='';
566 if(b.delta){ const d=b.delta; delta=`<h3>Since the last decision (${esc(d.sinceDecision.decision)} by ${esc(d.sinceDecision.actorId)})</h3>`+
567 (d.unchanged?'<div>Same ChangeSet as that decision.</div>':
568 `<div>Files added: ${esc(d.files.added.join(', ')||'none')}; changed: ${esc(d.files.changed.join(', ')||'none')}; removed: ${esc(d.files.removed.join(', ')||'none')}</div>`+
569 `<div>Findings resolved: ${d.findingsResolved.length}, new: ${d.findingsNew.length}</div>`); }
570 const exceptions=(b.exceptions||[]).map(e=>`<li><code>${esc(e.exceptionId)}</code> until ${esc(e.expiresAt)}: ${esc(e.rationale)}</li>`).join('');
571 document.getElementById('brief').innerHTML=
572 `<div>Run <code>${esc(b.run.executionId)}</code>: <span class="status ${esc(b.run.status)}">${esc(b.run.status)}</span> in ${esc(b.run.currentPhase)}</div>`+
573 `<h3>What was asked</h3><div><b>${esc(b.asked.title)}</b></div><div>${esc(b.asked.intent)}</div>`+
574 list(b.asked.acceptanceCriteria, c=>`<li><code>${esc(c.criterionId)}</code> ${esc(c.text)}</li>`)+
575 `<h3>What changed</h3><table>${files||'<tr><td>No ChangeSet yet.</td></tr>'}</table>`+
576 `<h3>Gate ${b.gate?esc(b.gate.status):'not evaluated'}</h3>`+(b.gate?list(b.gate.reasons, r=>`<li>${esc(r.explanation)}</li>`):'')+
577 `<h3>Risks (${b.risks.length})</h3><table>${risks||'<tr><td>No current finding.</td></tr>'}</table>`+
578 `<h3>Verified on <code>${esc(b.verified.changeSetDigest)}</code></h3><table>${checks}</table>`+
579 `<h3>Not verified</h3>`+list(b.notVerified, t=>`<li>${esc(t)}</li>`)+
580 (exceptions?`<h3>Exceptions in force</h3><ul>${exceptions}</ul>`:'')+
581 (b.certification?`<h3>Certification ${esc(b.certification.status)}</h3>`+list(b.certification.criteria, c=>`<li><code>${esc(c.criterionId)}</code> ${esc(c.status)}: requires ${esc(c.required)}, reached ${esc(c.achieved||'no rung')}</li>`):'')+
582 (b.deferred?`<h3>Deferred verification</h3>`+list(b.deferred, d=>`<li><code>${esc(d.itemId)}</code> ${esc(d.status)} (${esc(d.where)})</li>`):'')+
583 `<h3>History</h3><div>${b.history.implementationAttempts} implementation and ${b.history.verificationAttempts} verification attempt(s), ${b.history.automaticCorrections} automatic correction(s), ${b.history.requestedChanges} requested change(s), ${b.history.providerRetries} provider retry(ies).</div>`+delta;
584}
585function renderDecision(id, b){
586 const target=document.getElementById('decision'); target.innerHTML='';
587 if(!b.run.awaitingDecision || !b.run.changeSetDigest){ return; }
588 if(session.authentication!=='token'){
589 // Without api.auth: token the API answers 403 to a decision: no form to fill in for nothing.
590 target.innerHTML='<h3>Human gate</h3><div class="notice" id="decision-disabled">Decisions are off: the API runs without authentication and records none. Add an api section (auth: token) or decide with <code>harness gate decide</code>.</div>';
591 return;
592 }
593 target.innerHTML=`<h3>Human gate</h3>
594 <div class="notice">The decision will be bound to <code>${esc(b.run.changeSetDigest)}</code> (${b.changed.files.length} file(s)). Any later change invalidates it.</div>
595 <label>Actor<input id="actor" value="${esc(session.userId)}" readonly></label>
596 <label>Rationale<textarea id="rationale" placeholder="Explain the evidence considered and the reason for the decision. For REQUEST_CHANGES, say what must change."></textarea></label>
597 ${(b.checklist||[]).map(c=>`<label><input type="checkbox" class="check" value="${esc(c.itemId)}" style="width:auto"> ${esc(c.itemId)}: ${esc(c.text)}</label>`).join('')}
598 <div class="actions">
599 <button data-decision="APPROVE">Approve</button>
600 <button data-decision="REQUEST_CHANGES">Request changes</button>
601 <button data-decision="APPROVE_EXCEPTION">Approve exception</button>
602 <button data-decision="REJECT">Reject</button>
603 </div>`;
604 for(const button of target.querySelectorAll('button[data-decision]')){ button.onclick=()=>decide(id, button.dataset.decision); }
605}
606async function decide(id, decision){
607 const rationale=document.getElementById('rationale').value.trim();
608 if(!rationale){ alert('A rationale is required.'); return; }
609 const digest=brief.run.changeSetDigest;
610 const files=brief.changed.files.map(f=>f.path).join('\\n');
611 if(!confirm(`${decision} for\\n${digest}\\n\\nFiles:\\n${files}\\n\\nRecord this decision?`)) return;
612 try {
613 await request('/api/runs/'+encodeURIComponent(id)+'/decision',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({
614 decision,change_set_digest:digest,actor_id:document.getElementById('actor').value,rationale,continue_after:true,
615 checked_items:[...document.querySelectorAll('input.check:checked')].map(i=>i.value)
616 })});
617 decisionKey=null; await refresh();
618 } catch(error){ alert(error.message); }
619}
620// The Metrics tab (#58): the summary from /api/metrics and the self-contained report, fetched
621// with the token and shown in a frame from its text (nothing is loaded from elsewhere).
622function showTab(name){
623 for(const tab of ['runs','metrics']){
624 document.getElementById('tab-'+tab).setAttribute('aria-selected', String(tab===name));
625 document.getElementById('view-'+tab).hidden = tab!==name;
626 }
627 if(name==='metrics') loadMetrics();
628}
629async function loadMetrics(){
630 const query=document.getElementById('all-repos').checked?'?all_repos=true':'';
631 const target=document.getElementById('metrics-summary');
632 try {
633 const m=await request('/api/metrics'+query); const t=m.totals;
634 const rows=[['Runs',t.runs],['Tasks',t.tasks],['Agent calls',t.agentCalls],['Tokens (input + output)',t.tokens.total],
635 ['Reported cost (USD)',t.cost.reportedUsd],['Estimated cost (USD, estimated)',t.cost.estimatedUsd],
636 ['Human interactions',t.humanInteractions],['Approvals',t.approvals],['Features delivered',t.featuresDelivered]];
637 target.innerHTML='<table><caption>Totals</caption><tbody>'+rows.map(r=>`<tr><th scope="row">${esc(r[0])}</th><td>${esc(r[1])}</td></tr>`).join('')+'</tbody></table>';
638 document.getElementById('metrics-report').srcdoc=await request('/api/metrics/report'+query,{asText:true});
639 } catch(error){ target.textContent=error.message; }
640}
641document.getElementById('tab-runs').onclick=()=>showTab('runs');
642document.getElementById('tab-metrics').onclick=()=>showTab('metrics');
643document.getElementById('metrics-refresh').onclick=loadMetrics;
644document.getElementById('all-repos').onchange=loadMetrics;
645loadSession().catch(error => { document.getElementById('session').textContent=error.message; });
646refresh(); setInterval(refresh, 5000);
647</script>
648</body>
649</html>"""
651_SIGN_IN = """<!doctype html>
652<html lang="en">
653<head>
654<meta charset="utf-8">
655<meta name="viewport" content="width=device-width,initial-scale=1">
656<title>Governed Agent Harness: sign in</title>
657<style>
658:root { font-family: Inter, ui-sans-serif, system-ui, sans-serif; color-scheme: dark; }
659body { margin: 0; background: #111827; color: #e5e7eb; display: grid; place-items: center; min-height: 100vh; }
660form { background: #1f2937; border: 1px solid #374151; border-radius: 12px; padding: 24px; width: min(420px, 90vw); }
661input,button { box-sizing: border-box; width: 100%; margin-top: 8px; border: 1px solid #475569; border-radius: 8px; background: #111827; color: inherit; padding: 10px; }
662#error { color: #fb7185; min-height: 1.2em; margin-top: 8px; font-size: 13px; }
663</style>
664</head>
665<body>
666<form id="sign-in">
667<h1>Governed Agent Harness</h1>
668<label>API token<input id="token" type="password" autocomplete="off" required></label>
669<button type="submit">Sign in</button>
670<div id="error"></div>
671<p style="font-size:13px">The token is kept in this tab only (sessionStorage) and sent as Authorization: Bearer.</p>
672</form>
673<script>
674(() => {
675 const key='governed-harness.api-token';
676 async function open(token){
677 const response=await fetch('/', {headers:{'Authorization':'Bearer '+token}, cache:'no-store'});
678 if(!response.ok){
679 try { sessionStorage.removeItem(key); } catch(error){}
680 document.getElementById('error').textContent=response.status===401?'The token was refused.':'The server answered '+response.status+'.';
681 return;
682 }
683 const page=await response.text();
684 try { sessionStorage.setItem(key, token); } catch(error){}
685 document.open(); document.write(page); document.close();
686 }
687 let kept=null; try { kept=sessionStorage.getItem(key); } catch(error){}
688 if(kept) open(kept);
689 document.getElementById('sign-in').onsubmit=(event)=>{ event.preventDefault(); open(document.getElementById('token').value.trim()); };
690})();
691</script>
692</body>
693</html>"""