Coverage for src/governed_harness/application/onboarding.py: 77%

187 statements  

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

1"""First-run help: the .gitignore entry, an example task and the environment checks of doctor.""" 

2 

3from __future__ import annotations 

4 

5import json 

6import os 

7import shutil 

8import subprocess # nosec B404 - fixed git and interpreter argv, no shell 

9from enum import StrEnum 

10from pathlib import Path 

11from typing import Any 

12 

13from governed_harness.configuration.models import ResolvedConfiguration, ValidatorDefinition 

14from governed_harness.runtime.process_runner import resolve_executable 

15from governed_harness.runtime.sandbox import SandboxHost 

16from governed_harness.validators.command import _MODULE_MISSING_EXIT_CODE, _MODULE_PROBE 

17 

18GITIGNORE_ENTRY = ".harness/" 

19GITIGNORE_FILE = ".gitignore" 

20 

21EXAMPLE_TASK_NAME = "task.example.yaml" 

22 

23_EXAMPLE_TASK = """\ 

24# Example task written by `harness init`. Copy it, edit it and create it with: 

25# harness task create --file .harness/task.example.yaml 

26# Reference: docs/reference/task-file.md 

27taskId: task_example 

28title: Describe the change in one line 

29intent: >- 

30 Say what should change and why, in terms a reviewer can check against the result. 

31requirements: 

32 # Identified requirements; with verification.requirementTraceability a test must name 

33 # each id (for example test_req_example_behaviour). 

34 - requirementId: req_example 

35 text: State one observable behaviour the change must have. 

36 source: example 

37acceptanceCriteria: 

38 # Observable criteria: an input, an expected result and a condition. INTENT asks 

39 # clarification questions about criteria it cannot check. 

40 - criterionId: ac_example 

41 text: Given input X, the result is Y. 

42constraints: 

43 - Do not change the public interface of {surface}. 

44metadata: 

45 # Paths the agent may change; the ChangeSet only contains these paths. 

46 ownedPaths: 

47{owned} 

48""" 

49 

50_OWNED = { 

51 "python": ["src/", "tests/"], 

52 "node": ["src/", "test/"], 

53} 

54 

55 

56class IgnoreFile(StrEnum): 

57 """Where ``harness init`` writes its ignore entry (#86).""" 

58 

59 EXCLUDE = "exclude" 

60 """The repository's ``info/exclude``: local to the clone, so the tree stays clean.""" 

61 GITIGNORE = "gitignore" 

62 """The workspace ``.gitignore`` (a tracked change).""" 

63 

64 

65_HARNESS_ENTRIES = {".harness", ".harness/", "/.harness", "/.harness/", ".harness/*"} 

66 

67 

68_IGNORE_FILE_NAMES = frozenset({GITIGNORE_FILE, "exclude"}) 

69 

70 

71def _contained(path: Path, root: Path) -> Path: 

72 """The resolved ignore file, refused unless it is a known ignore file inside ``root`` (the 

73 workspace for ``.gitignore``, the repository's Git directory for ``info/exclude``): the 

74 location comes from the command line and from Git, so it is checked before it is written.""" 

75 resolved = path.resolve() 

76 if resolved.name not in _IGNORE_FILE_NAMES or not resolved.is_relative_to(root.resolve()): 

77 raise ValueError(f"Refusing to write an ignore file outside {root}: {path}") 

78 return resolved 

79 

80 

81def _add_entry(path: Path, root: Path) -> str: 

82 """Add ``.harness/`` to an ignore file inside ``root``; returns added, present or created.""" 

83 path = _contained(path, root) 

84 if not path.exists(): 

85 path.parent.mkdir(parents=True, exist_ok=True) 

86 path.write_text(f"{GITIGNORE_ENTRY}\n", encoding="utf-8") 

87 return "created" 

88 text = path.read_text(encoding="utf-8") 

89 if _has_entry(text): 

90 return "present" 

91 # Append the entry rather than rewrite the file: only the fixed entry is written. 

92 addition = ( 

93 f"{GITIGNORE_ENTRY}\n" if not text or text.endswith("\n") else f"\n{GITIGNORE_ENTRY}\n" 

94 ) 

95 with path.open("a", encoding="utf-8") as handle: 

96 handle.write(addition) 

97 return "added" 

98 

99 

100def ensure_gitignore(workspace: Path) -> str: 

101 """Add ``.harness/`` to the workspace .gitignore; returns added, present or created.""" 

102 return _add_entry(workspace / GITIGNORE_FILE, workspace) 

103 

104 

105def _git_location(workspace: Path, *args: str) -> Path | None: 

106 """A path Git reports for the workspace's repository, absolute (``None`` on failure).""" 

107 result = _run(["git", "rev-parse", *args], workspace) 

108 location = result.stdout.strip() 

109 if result.returncode != 0 or not location: 

110 return None 

111 path = Path(location) 

112 return path if path.is_absolute() else workspace / path 

113 

114 

115def _exclude_path(workspace: Path) -> tuple[Path, Path] | None: 

116 """The ``info/exclude`` file of the repository the workspace is in and the repository's 

117 common Git directory that holds it (``None`` outside a Git repository or without Git); a 

118 linked worktree shares its repository's file.""" 

119 if not shutil.which("git"): 119 ↛ 120line 119 didn't jump to line 120 because the condition on line 119 was never true

120 return None 

121 exclude = _git_location(workspace, "--git-path", "info/exclude") 

122 common = _git_location(workspace, "--git-common-dir") 

123 if exclude is None or common is None: 

124 return None 

125 return exclude, common 

126 

127 

128def _shown(path: Path, workspace: Path) -> str: 

129 try: 

130 return path.resolve().relative_to(workspace.resolve()).as_posix() 

131 except ValueError: 

132 return str(path) 

133 

134 

135def ensure_ignored(workspace: Path, target: IgnoreFile = IgnoreFile.EXCLUDE) -> dict[str, str]: 

136 """Make Git ignore ``.harness/`` without dirtying an existing repository (#86). 

137 

138 ``exclude`` (the default) writes the entry to the repository's ``info/exclude``, which Git 

139 reads like a ``.gitignore`` but which is not part of the tree, so the first run of a 

140 brownfield repository finds no uncommitted change caused by ``init``; an entry already in 

141 the ``.gitignore`` is left as it is. Outside a Git repository, or with ``gitignore``, the 

142 entry goes to the workspace ``.gitignore`` as before. Returns the file, the entry and 

143 whether it was added, present or created.""" 

144 gitignore = workspace / GITIGNORE_FILE 

145 exclude = _exclude_path(workspace) if target is IgnoreFile.EXCLUDE else None 

146 if exclude is None or _add_entry_present(gitignore): 

147 status = _add_entry(gitignore, workspace) 

148 return {"file": GITIGNORE_FILE, "entry": GITIGNORE_ENTRY, "status": status} 

149 path, common = exclude 

150 return { 

151 "file": _shown(path, workspace), 

152 "entry": GITIGNORE_ENTRY, 

153 "status": _add_entry(path, common), 

154 } 

155 

156 

157def _add_entry_present(path: Path) -> bool: 

158 """Whether an ignore file exists and already has the harness entry.""" 

159 return path.is_file() and _has_entry(path.read_text(encoding="utf-8")) 

160 

161 

162def _has_entry(text: str) -> bool: 

163 return bool({line.strip() for line in text.splitlines()} & _HARNESS_ENTRIES) 

164 

165 

166def write_example_task(harness_dir: Path, technologies: list[str], *, force: bool) -> Path | None: 

167 """Write the example task unless one exists (or ``force``). Returns the path written.""" 

168 target = harness_dir / EXAMPLE_TASK_NAME 

169 if target.exists() and not force: 169 ↛ 170line 169 didn't jump to line 170 because the condition on line 169 was never true

170 return None 

171 owned = next((_OWNED[item] for item in technologies if item in _OWNED), ["src/"]) 

172 surface = "the package" if "python" in technologies else "the module" 

173 content = _EXAMPLE_TASK.format( 

174 surface=surface, owned="\n".join(f" - {item}" for item in owned) 

175 ) 

176 target.write_text(content, encoding="utf-8") 

177 return target 

178 

179 

180def _run( 

181 argv: list[str], cwd: Path | None, timeout: float = 20.0 

182) -> subprocess.CompletedProcess[str]: 

183 return subprocess.run( # nosec B603 - argv lists built here (git, a validator's interpreter), no shell 

184 [resolve_executable(argv[0]), *argv[1:]], 

185 cwd=cwd, 

186 stdin=subprocess.DEVNULL, 

187 capture_output=True, 

188 text=True, 

189 check=False, 

190 timeout=timeout, 

191 ) 

192 

193 

194def git_identity(cwd: Path | None) -> dict[str, Any]: 

195 if not shutil.which("git"): 195 ↛ 196line 195 didn't jump to line 196 because the condition on line 195 was never true

196 return {"status": "NOT_APPLICABLE", "message": "git is not installed"} 

197 name = _run(["git", "config", "user.name"], cwd).stdout.strip() 

198 email = _run(["git", "config", "user.email"], cwd).stdout.strip() 

199 if name and email: 199 ↛ 201line 199 didn't jump to line 201 because the condition on line 199 was always true

200 return {"status": "PASSED", "name": name, "email": email} 

201 return { 

202 "status": "WARNING", 

203 "message": "Git has no user.name or user.email here", 

204 "hint": 'Set them with `git config user.name "Your Name"` and ' 

205 "`git config user.email you@example.com`; the harness records the person who decides.", 

206 } 

207 

208 

209def repository_checks(workspace: Path) -> dict[str, Any]: 

210 checks: dict[str, Any] = {} 

211 if not shutil.which("git"): 211 ↛ 212line 211 didn't jump to line 212 because the condition on line 211 was never true

212 return checks 

213 inside = _run(["git", "rev-parse", "--is-inside-work-tree"], workspace) 

214 if inside.returncode != 0: 214 ↛ 215line 214 didn't jump to line 215 because the condition on line 214 was never true

215 checks["baseline"] = { 

216 "status": "WARNING", 

217 "message": "the project is not a Git repository", 

218 "hint": "Run `git init` and commit the project: the baseline revision of a run is " 

219 "the commit it starts from.", 

220 } 

221 return checks 

222 head = _run(["git", "rev-parse", "--verify", "HEAD"], workspace) 

223 checks["baseline"] = ( 

224 {"status": "PASSED", "head": head.stdout.strip()} 

225 if head.returncode == 0 

226 else { 

227 "status": "WARNING", 

228 "message": "the repository has no commit", 

229 "hint": "Commit the current state (`git add -A && git commit -m baseline`) so a run " 

230 "can record its baseline revision.", 

231 } 

232 ) 

233 ignored = _run(["git", "check-ignore", "-q", ".harness/state.db"], workspace) 

234 checks["harnessIgnored"] = ( 

235 {"status": "PASSED"} 

236 if ignored.returncode == 0 

237 else { 

238 "status": "WARNING", 

239 "message": ".harness/ is not ignored by Git", 

240 "hint": "Add `.harness/` to .git/info/exclude or .gitignore (`harness init` does " 

241 "it): it holds the state " 

242 "database and artifacts with copies of your code.", 

243 } 

244 ) 

245 return checks 

246 

247 

248def _executable(argv0: str, workspace: Path) -> str | None: 

249 if os.sep in argv0: 249 ↛ 250line 249 didn't jump to line 250 because the condition on line 249 was never true

250 candidate = Path(argv0) if Path(argv0).is_absolute() else workspace / argv0 

251 return str(candidate) if os.access(candidate, os.X_OK) else None 

252 return shutil.which(argv0) 

253 

254 

255def _provider_entry( 

256 provider_id: str, provider: Any, default: str, workspace: Path 

257) -> dict[str, Any]: 

258 """Whether the command of one agent provider is found; only the default one fails.""" 

259 found = _executable(provider.effective_command[0], workspace) 

260 if found: 260 ↛ 261line 260 didn't jump to line 261 because the condition on line 260 was never true

261 status = "PASSED" 

262 elif provider_id == default: 262 ↛ 265line 262 didn't jump to line 265 because the condition on line 262 was always true

263 status = "FAILED" 

264 else: 

265 status = "WARNING" 

266 entry: dict[str, Any] = { 

267 "provider": provider_id, 

268 "command": provider.effective_command[0], 

269 "status": status, 

270 } 

271 if found: 271 ↛ 272line 271 didn't jump to line 272 because the condition on line 271 was never true

272 entry["path"] = found 

273 else: 

274 entry["hint"] = ( 

275 f"Install the agent CLI or adapter {provider.effective_command[0]!r} or put it on PATH; " 

276 f"runs with provider {provider_id!r} fail in IMPLEMENTATION without it." 

277 ) 

278 return entry 

279 

280 

281def provider_checks(resolved: ResolvedConfiguration) -> dict[str, Any]: 

282 project = resolved.project 

283 default = project.agent_provider 

284 checks: dict[str, Any] = {} 

285 if default == "simulated": 

286 checks["agentProvider"] = { 

287 "status": "PASSED", 

288 "provider": "simulated", 

289 "message": "built-in deterministic provider; it calls no agent CLI", 

290 } 

291 others: list[dict[str, Any]] = [] 

292 for provider_id, provider in project.agent_providers.items(): 

293 entry = _provider_entry(provider_id, provider, default, resolved.workspace_root) 

294 if provider_id == default: 294 ↛ 297line 294 didn't jump to line 297 because the condition on line 294 was always true

295 checks["agentProvider"] = entry 

296 else: 

297 others.append(entry) 

298 if "agentProvider" not in checks: 298 ↛ 299line 298 didn't jump to line 299 because the condition on line 298 was never true

299 checks["agentProvider"] = { 

300 "status": "FAILED", 

301 "provider": default, 

302 "hint": f"Declare agentProviders.{default} in project.yaml or set agentProvider.", 

303 } 

304 if others: 304 ↛ 305line 304 didn't jump to line 305 because the condition on line 304 was never true

305 checks["otherAgentProviders"] = { 

306 "status": "WARNING" if any(item["status"] != "PASSED" for item in others) else "PASSED", 

307 "providers": others, 

308 } 

309 return checks 

310 

311 

312def sandbox_check( 

313 resolved: ResolvedConfiguration, host: SandboxHost | None = None 

314) -> dict[str, Any]: 

315 mode = resolved.project.runtime.effective_agent_sandbox 

316 if mode == "off": 316 ↛ 317line 316 didn't jump to line 317 because the condition on line 316 was never true

317 return { 

318 "status": "WARNING", 

319 "mode": "off", 

320 "message": "agent writes are not confined", 

321 "hint": "Set runtime.agentSandbox: enforce to confine a command provider's writes.", 

322 } 

323 host = host or SandboxHost.detect() 

324 mechanism = host.sandbox_exec or host.bwrap 

325 if mechanism: 325 ↛ 326line 325 didn't jump to line 326 because the condition on line 325 was never true

326 return {"status": "PASSED", "mode": mode, "mechanism": mechanism} 

327 command_provider = resolved.project.agent_provider != "simulated" 

328 if host.system == "Linux": 328 ↛ 330line 328 didn't jump to line 330 because the condition on line 328 was always true

329 fix = "Install bubblewrap (for example `apt-get install bubblewrap`)" 

330 elif host.system == "Darwin": 

331 fix = "/usr/bin/sandbox-exec should exist on macOS; check the system installation" 

332 else: 

333 fix = f"No sandbox mechanism is supported on {host.system or 'this platform'}" 

334 return { 

335 "status": "FAILED" if command_provider else "WARNING", 

336 "mode": mode, 

337 "message": "no sandbox mechanism is available on this host", 

338 "hint": f"{fix}, or set runtime.agentSandbox: off to run a command provider unconfined. " 

339 "Until then a command provider's run is BLOCKED; the simulated provider is not affected.", 

340 } 

341 

342 

343def _validator_status(definition: ValidatorDefinition, workspace: Path) -> dict[str, Any]: 

344 entry: dict[str, Any] = {"id": definition.validator_id, "mandatory": definition.mandatory} 

345 missing = "FAILED" if definition.mandatory else "NOT_APPLICABLE" 

346 if definition.command is None: 346 ↛ 347line 346 didn't jump to line 347 because the condition on line 346 was never true

347 return {**entry, "status": missing, "message": "no command is configured"} 

348 if definition.script: 348 ↛ 349line 348 didn't jump to line 349 because the condition on line 348 was never true

349 try: 

350 package = json.loads((workspace / "package.json").read_text(encoding="utf-8")) 

351 scripts = package.get("scripts", {}) 

352 except (OSError, json.JSONDecodeError): 

353 scripts = {} 

354 if definition.script not in scripts: 

355 return { 

356 **entry, 

357 "status": missing, 

358 "message": f"package script {definition.script!r} is not defined", 

359 "hint": f"Add a {definition.script!r} script to package.json.", 

360 } 

361 argv0 = definition.command[0] 

362 if shutil.which(argv0) is None: 

363 return { 

364 **entry, 

365 "status": missing, 

366 "message": f"executable {argv0!r} is not available", 

367 "hint": f"Install {argv0!r} or put it on PATH where the harness runs.", 

368 } 

369 if len(definition.command) >= 3 and definition.command[1] == "-m": 369 ↛ 383line 369 didn't jump to line 383 because the condition on line 369 was always true

370 module = definition.command[2] 

371 try: 

372 probe = _run([argv0, "-c", _MODULE_PROBE, module], workspace, timeout=60) 

373 available = probe.returncode != _MODULE_MISSING_EXIT_CODE 

374 except (OSError, subprocess.TimeoutExpired): 

375 available = False 

376 if not available: 376 ↛ 377line 376 didn't jump to line 377 because the condition on line 376 was never true

377 return { 

378 **entry, 

379 "status": missing, 

380 "message": f"Python module {module!r} is not installed for {argv0!r}", 

381 "hint": f"Install it where the harness runs: `{argv0} -m pip install {module}`.", 

382 } 

383 return {**entry, "status": "PASSED"} 

384 

385 

386def validator_checks(resolved: ResolvedConfiguration) -> dict[str, Any]: 

387 entries = [ 

388 _validator_status(item, resolved.workspace_root) for item in resolved.effective_validators 

389 ] 

390 status = "FAILED" if any(item["status"] == "FAILED" for item in entries) else "PASSED" 

391 return {"status": status, "validators": entries}