Coverage for src/governed_harness/configuration/init_project.py: 89%

34 statements  

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

1from __future__ import annotations 

2 

3import re 

4import sys 

5from pathlib import Path 

6 

7import yaml 

8 

9from governed_harness.configuration.agent_contract import DEFAULT_MAX_ITERATIONS 

10from governed_harness.configuration.agent_results import ( 

11 DEFAULT_AMBIGUITY_QUESTIONS, 

12 DEFAULT_AMBIGUITY_ROUNDS, 

13 DEFAULT_COARSE_MODELS, 

14 DEFAULT_CONTEXT_MAX_BYTES, 

15 DEFAULT_CONTEXT_MAX_FILES, 

16 DEFAULT_DECOMPOSITION_THRESHOLD, 

17 DEFAULT_READ_ONLY_EFFORT, 

18 DEFAULT_RISK_ACTIONS, 

19 DEFAULT_SIZE_THRESHOLDS, 

20) 

21from governed_harness.configuration.api import DEFAULT_API_TOKEN_ENV, DEFAULT_API_TOKEN_ROLE 

22from governed_harness.configuration.engineering import ( 

23 DEFAULT_DUPLICATION_WINDOW, 

24 DEFAULT_FEATURES_DIRECTORY, 

25 DEFAULT_INHERITANCE_DEPTH, 

26 DEFAULT_MAX_CARDS, 

27) 

28from governed_harness.configuration.friction import ( 

29 DEFAULT_FAST_LANE_SKIP, 

30 DEFAULT_FRICTION_TARGETS, 

31 DEFAULT_PRE_AUTHORIZATION_HOURS, 

32) 

33from governed_harness.configuration.ladder import ( 

34 DEFAULT_DEFERRED_EXPIRY_DAYS, 

35 DEFAULT_INSTRUCTION_FILES, 

36 DEFAULT_INTERRUPTION_TARGET, 

37 DEFAULT_ISOLATION_BRANCH, 

38 DEFAULT_MUTATION_HUNKS, 

39 DEFAULT_MUTATION_SECONDS, 

40 STOP_CONDITIONS, 

41) 

42from governed_harness.configuration.models import ( 

43 DEFAULT_DECISION_EXPIRY_HOURS, 

44 DEFAULT_EXCEPTION_DAYS, 

45 DEFAULT_SANDBOX_WRITE_PATHS, 

46 DEFAULT_TRUSTED_HOSTS, 

47) 

48from governed_harness.configuration.review import ( 

49 DEFAULT_AUTOFIX_ATTEMPTS, 

50 DEFAULT_BASE_TOKENS, 

51 DEFAULT_CACHE_ENTRIES, 

52 DEFAULT_CACHE_TTL_DAYS, 

53 DEFAULT_MAX_FINDINGS, 

54 DEFAULT_MAX_TOKENS, 

55 DEFAULT_PARALLEL, 

56 DEFAULT_TOKENS_PER_LINE, 

57) 

58from governed_harness.domain.actors import DEFAULT_API_ACTOR 

59from governed_harness.domain.errors import ConfigurationError 

60 

61 

62def project_id_from_path(path: Path) -> str: 

63 slug = re.sub(r"[^a-z0-9]+", "_", path.name.lower()).strip("_") or "local" 

64 return f"project_{slug[:80]}" 

65 

66 

67# Default write-sandbox entries that only exist on POSIX systems. The sandbox paths must be absolute 

68# POSIX paths or start with ``~/`` (the validator rejects drive letters and backslashes), so on 

69# Windows these are left out instead of written as paths that mean nothing there; the entries 

70# under the home directory (``~/.claude``, ``~/.cache``, ...) stay. 

71POSIX_ONLY_SANDBOX_PATHS = frozenset( 

72 {"/tmp", "/var/folders", "~/Library/Caches"} # NOSONAR(S5443) # nosec B108 

73) 

74 

75 

76def default_sandbox_write_paths(platform: str | None = None) -> list[str]: 

77 """``runtime.sandboxWritePaths`` that ``harness init`` writes: the defaults, without the 

78 POSIX-only temporary and cache directories on Windows. POSIX is unchanged.""" 

79 windows = (platform or sys.platform) == "win32" 

80 return [ 

81 path 

82 for path, _ in DEFAULT_SANDBOX_WRITE_PATHS 

83 if not (windows and path in POSIX_ONLY_SANDBOX_PATHS) 

84 ] 

85 

86 

87def initialize_project(path: Path, *, force: bool = False) -> Path: 

88 target = path.resolve(strict=True) 

89 if not target.is_dir(): 89 ↛ 90line 89 didn't jump to line 90 because the condition on line 89 was never true

90 raise ConfigurationError(f"project path is not a directory: {target}") 

91 harness_dir = target / ".harness" 

92 harness_dir.mkdir(parents=True, exist_ok=True, mode=0o700) 

93 config_path = harness_dir / "project.yaml" 

94 if config_path.exists() and not force: 94 ↛ 95line 94 didn't jump to line 95 because the condition on line 94 was never true

95 raise ConfigurationError(f"configuration already exists: {config_path}") 

96 value = { 

97 "configVersion": "1.0", 

98 "projectId": project_id_from_path(target), 

99 "workspace": { 

100 "root": "..", 

101 "units": [], 

102 "snapshot": "git", 

103 "baseline": "manifest", 

104 "snapshotCache": True, 

105 # Runs stay in place unless run start --isolate worktree (or mode: worktree): the 

106 # README quickstart and the documented flows inspect the workspace itself. 

107 "isolation": {"mode": "none", "branch": DEFAULT_ISOLATION_BRANCH, "fetch": True}, 

108 }, 

109 "profiles": ["auto"], 

110 "workflow": "default_development", 

111 "capabilities": {"default": "deny", "grants": []}, 

112 "validators": [], 

113 "policies": { 

114 "requireHumanDecision": True, 

115 "findingBlockSeverities": ["HIGH", "CRITICAL"], 

116 }, 

117 "agentProvider": "simulated", 

118 "runtime": { 

119 "commandTimeoutSeconds": 900, 

120 "maxOutputBytes": 1000000, 

121 "maxParallel": 2, 

122 # Enforced under governance.applyNetworkPolicy: agent CLIs call their model API. 

123 "allowNetwork": True, 

124 "agentSandbox": "enforce", 

125 "sandboxWritePaths": default_sandbox_write_paths(), 

126 "verificationCorrections": 2, 

127 "providerFeedback": True, 

128 "unsupportedClaimSeverity": "MEDIUM", 

129 "providerRetries": 3, 

130 "providerRetryDelaySeconds": 60, 

131 "extendedRedaction": True, 

132 "gateContract": True, 

133 # #80: a read-only answer that breaks its contract gets a second attempt. 

134 "contractRetry": {"mode": "once"}, 

135 "reproduceFirst": True, 

136 "stateDir": "auto", 

137 }, 

138 "retention": {"artifactDays": 30, "eventDays": 365, "orphanArtifacts": True}, 

139 "intake": { 

140 "criteriaPolicy": "enforce", 

141 # #79: the review converges; after its last round the open points become 

142 # explicit assumptions and the run continues. 

143 "ambiguityReview": { 

144 "mode": "agent", 

145 "maxRounds": DEFAULT_AMBIGUITY_ROUNDS, 

146 "maxQuestions": DEFAULT_AMBIGUITY_QUESTIONS, 

147 "onExhausted": "assume", 

148 # 2.0.1: no new call once a round left no question or the stop was recorded. 

149 "skipSettled": True, 

150 # 2.0.1: a poorer request gets more rounds and questions, the basics first. 

151 "depth": "adaptive", 

152 }, 

153 "validateAnswers": True, 

154 "operationalContract": "batch", 

155 "interruptions": { 

156 "target": DEFAULT_INTERRUPTION_TARGET, 

157 "stopConditions": list(STOP_CONDITIONS), 

158 }, 

159 "projectSetup": "ask", 

160 # 2.0: the deterministic INTENT rules follow the task's language (en or es). 

161 "language": "auto", 

162 }, 

163 "verification": { 

164 "requirementTraceability": "enforce", 

165 "outputParsers": True, 

166 "interface": "enforce", 

167 "architecture": { 

168 "maxModuleLines": 800, 

169 "maxFunctionLines": 80, 

170 "maxComplexity": 15, 

171 "severity": "MEDIUM", 

172 }, 

173 "securityPatterns": True, 

174 "constraints": "enforce", 

175 "ratchet": "enforce", 

176 "differential": True, 

177 "weakenedControls": "enforce", 

178 "testQuality": { 

179 "assertions": True, 

180 "interfaceTests": True, 

181 "diffCoverage": 80, 

182 "flakyReruns": 1, 

183 "severity": "MEDIUM", 

184 }, 

185 "secrets": "context", 

186 "riskFactors": dict(DEFAULT_RISK_ACTIONS), 

187 # #94: the frozen files are write-protected and a disputed test waits for a 

188 # person. 

189 "acceptanceTests": {"mode": "agent", "protect": True, "disputes": "person"}, 

190 "reverifyOnChange": True, 

191 "ladder": { 

192 "mode": "enforce", 

193 "defaultLevel": "L1", 

194 "deferredExpiryDays": DEFAULT_DEFERRED_EXPIRY_DAYS, 

195 "preflight": True, 

196 "capabilityDetection": True, 

197 }, 

198 "mutation": { 

199 "mode": "warn", 

200 "maxHunks": DEFAULT_MUTATION_HUNKS, 

201 "maxSeconds": DEFAULT_MUTATION_SECONDS, 

202 }, 

203 "principles": { 

204 "mode": "enforce", 

205 "duplicationWindow": DEFAULT_DUPLICATION_WINDOW, 

206 "maxInheritanceDepth": DEFAULT_INHERITANCE_DEPTH, 

207 "unusedPublic": True, 

208 "boyScout": True, 

209 "checklist": True, 

210 "severity": "MEDIUM", 

211 }, 

212 }, 

213 "review": { 

214 "exceptions": True, 

215 "exceptionDays": DEFAULT_EXCEPTION_DAYS, 

216 "agentReview": "enforce", 

217 "structuredChanges": True, 

218 "manualChecklist": True, 

219 # Wave 7 (#57): the review panel replaces the single reviewer. 

220 "panel": { 

221 "mode": "enforce", 

222 "maxFindings": DEFAULT_MAX_FINDINGS, 

223 "parallel": DEFAULT_PARALLEL, 

224 "budget": { 

225 "baseTokens": DEFAULT_BASE_TOKENS, 

226 "tokensPerLine": DEFAULT_TOKENS_PER_LINE, 

227 "maxTokens": DEFAULT_MAX_TOKENS, 

228 }, 

229 "cache": {"ttlDays": DEFAULT_CACHE_TTL_DAYS, "maxEntries": DEFAULT_CACHE_ENTRIES}, 

230 "runTools": True, 

231 "autoFix": {"mode": "scoped", "maxAttempts": DEFAULT_AUTOFIX_ATTEMPTS}, 

232 "secondOpinion": {"mode": "off"}, 

233 "evidenceRefs": True, 

234 "comment": False, 

235 "mcpServers": [], 

236 }, 

237 }, 

238 "retrospective": {"causal": True}, 

239 "planning": { 

240 "decomposition": "agent", 

241 "threshold": DEFAULT_DECOMPOSITION_THRESHOLD, 

242 "granularity": "adaptive", 

243 "coarseModels": list(DEFAULT_COARSE_MODELS), 

244 }, 

245 "context": { 

246 "manifest": "auto", 

247 "maxFiles": DEFAULT_CONTEXT_MAX_FILES, 

248 "maxBytes": DEFAULT_CONTEXT_MAX_BYTES, 

249 # 2.0.1: one locate call while the task's scope stays the same. 

250 "locate": {"mode": "agent", "reuse": "scope"}, 

251 }, 

252 # Wide on purpose: limits only at the extremes (#42). 

253 "budget": { 

254 "perCall": {"costUsd": 25, "wallSeconds": 7200}, 

255 "perTask": {"costUsd": 200}, 

256 "perRun": {"costUsd": 100, "tokens": 500_000_000, "wallSeconds": 43_200}, 

257 "warnAt": 0.8, 

258 }, 

259 "memory": {"learnFromFindings": "auto", "autoApproveRecurring": False}, 

260 # Wave 11 (#97): the versioned request and response contract of agent calls, one cap of 

261 # iterations per agent and the token budget and time limit by task size. 

262 # 2.0.1: token budgets by call kind, calibrated on the 2.0.0 pilot calls. 

263 "agentContract": { 

264 "mode": "enforce", 

265 "maxIterations": DEFAULT_MAX_ITERATIONS, 

266 "budgetProfile": "by-kind", 

267 }, 

268 # #85: the model the person invoked is the ceiling; cheaper rungs below it. 

269 "agentRouting": { 

270 "mode": "anchored", 

271 "thresholds": {key: list(value) for key, value in DEFAULT_SIZE_THRESHOLDS.items()}, 

272 "maxEscalations": 2, 

273 # 2.0.1: low or medium effort for the first attempt of the read-only calls. 

274 "readOnlyEffort": dict(DEFAULT_READ_ONLY_EFFORT), 

275 }, 

276 "governance": { 

277 "deciderIdentity": "git", 

278 "confirmDecisionDigest": True, 

279 "trustedHosts": list(DEFAULT_TRUSTED_HOSTS), 

280 "verifyRecords": True, 

281 "chainAnchor": "file", 

282 # #149: events after the anchored head are a warning, and do not excuse a prune. 

283 "unanchoredEvents": "warn", 

284 "pinTaskRevision": True, 

285 "protectExcludedPaths": True, 

286 "workspaceLease": True, 

287 "applyWorkflowSettings": True, 

288 "decisionExpiryHours": DEFAULT_DECISION_EXPIRY_HOURS, 

289 "applyProfilePolicies": True, 

290 "applyNetworkPolicy": True, 

291 "stopTheLine": "restore", 

292 "phasePermissions": True, 

293 # Wave 7 (#4): grants narrowed by the project and limited to each phase. 

294 "phaseCapabilities": True, 

295 # Wave 7 (#5): repository content is untrusted, destructive commands are denied. 

296 "applyRepositoryPolicies": True, 

297 "enforceWorkflow": True, 

298 # Governance by risk: small, risk-free tasks take the light profile, the others the 

299 # full one; the security flag is read in context. 

300 "riskProfile": "auto", 

301 }, 

302 "toolchain": {"profileDetection": "all", "interpreter": "auto", "extendedProfiles": True}, 

303 "provenance": {"agentSnapshots": True, "selfReport": True}, 

304 # Nothing leaves the machine unless the task's contract (or a person) authorises it; 

305 # the forge of the pull request is detected from the origin remote (delivery.forge 

306 # only to override it, #56). 

307 "delivery": { 

308 "closureCommit": "branch", 

309 "recordCommitAuthor": True, 

310 "stage": True, 

311 "push": False, 

312 "pullRequest": {"create": False, "draft": True}, 

313 "comment": "notClean", 

314 }, 

315 "environment": {"dirtyTree": "warn", "baseline": "report"}, 

316 "instructions": { 

317 "files": list(DEFAULT_INSTRUCTION_FILES), 

318 "precedence": ["harness", *DEFAULT_INSTRUCTION_FILES], 

319 }, 

320 # Wave 6 (#56): standards packs, testing strategy and architecture. 

321 "standards": { 

322 "packs": ["auto"], 

323 "cards": "auto", 

324 "maxCards": DEFAULT_MAX_CARDS, 

325 "tools": "detect", 

326 }, 

327 "testing": {"strategy": "auto", "featuresDirectory": DEFAULT_FEATURES_DIRECTORY}, 

328 # #93: only the layers a change adds are judged, and the dependencies the baseline 

329 # already has are listed and allowed when a survey's rules are proposed. 

330 "architecture": { 

331 "mode": "agent", 

332 "refresh": "manual", 

333 "enforce": "enforce", 

334 "layerCheck": "differential", 

335 "baselineConflicts": "allow", 

336 # #97: the ten-style catalogue with its experts for a new project and persistent 

337 # reverse engineering documents for an existing one. 

338 "catalogue": "experts", 

339 "documentation": "project", 

340 }, 

341 # Wave 8 (#58): a fast lane for small, risk-free tasks, approval in advance under a 

342 # condition, documentation-only and configuration-only changes, friction targets. 

343 "friction": { 

344 "fastLane": { 

345 "mode": "auto", 

346 "skip": list(DEFAULT_FAST_LANE_SKIP), 

347 "verification": {"affectedTestsFirst": True, "parallel": True, "cache": True}, 

348 }, 

349 "preAuthorization": { 

350 "mode": "allow", 

351 "defaultHours": DEFAULT_PRE_AUTHORIZATION_HOURS, 

352 "maxHours": 72, 

353 }, 

354 "changeTypes": True, 

355 "planApproval": "risk", 

356 "targets": {size: dict(values) for size, values in DEFAULT_FRICTION_TARGETS.items()}, 

357 }, 

358 # #18: harness api serve requires a bearer token on every route. The token of the 

359 # person who starts it comes from tokenEnv, or is generated and shown once; more people 

360 # go under users, each with an id, a role and the NAME of their token's variable. 

361 "api": { 

362 "auth": "token", 

363 "tokenEnv": DEFAULT_API_TOKEN_ENV, 

364 "tokenUser": DEFAULT_API_ACTOR, 

365 "tokenRole": DEFAULT_API_TOKEN_ROLE, 

366 "users": [], 

367 }, 

368 } 

369 config_path.write_text(yaml.safe_dump(value, sort_keys=False), encoding="utf-8") 

370 return config_path