workflow-coordinator 0.1.0b1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. workflow_coordinator/__init__.py +1 -0
  2. workflow_coordinator/adapter.py +150 -0
  3. workflow_coordinator/claude_adapter.py +289 -0
  4. workflow_coordinator/codex_adapter.py +395 -0
  5. workflow_coordinator/codex_adapter_smoke.py +231 -0
  6. workflow_coordinator/commissioning.py +432 -0
  7. workflow_coordinator/evidence.py +481 -0
  8. workflow_coordinator/execution_boundary.py +187 -0
  9. workflow_coordinator/frontdoor/__init__.py +1 -0
  10. workflow_coordinator/frontdoor/archive.py +1496 -0
  11. workflow_coordinator/frontdoor/audit.py +589 -0
  12. workflow_coordinator/frontdoor/cli.py +42 -0
  13. workflow_coordinator/frontdoor/config.py +287 -0
  14. workflow_coordinator/frontdoor/init.py +228 -0
  15. workflow_coordinator/frontdoor/journal.py +284 -0
  16. workflow_coordinator/frontdoor/lifecycle.py +1093 -0
  17. workflow_coordinator/frontdoor/plan.py +311 -0
  18. workflow_coordinator/frontdoor/postrun.py +254 -0
  19. workflow_coordinator/frontdoor/preservation.py +132 -0
  20. workflow_coordinator/frontdoor/report.py +222 -0
  21. workflow_coordinator/frontdoor/request.py +170 -0
  22. workflow_coordinator/frontdoor/verify.py +137 -0
  23. workflow_coordinator/git_facts.py +1258 -0
  24. workflow_coordinator/implementation_identity.py +68 -0
  25. workflow_coordinator/model.py +958 -0
  26. workflow_coordinator/operator.py +1915 -0
  27. workflow_coordinator/persistence.py +599 -0
  28. workflow_coordinator/prompt.py +272 -0
  29. workflow_coordinator/proof_harness.py +295 -0
  30. workflow_coordinator/reducer.py +2006 -0
  31. workflow_coordinator/resources/agent_operating_contract_v6.txt +97 -0
  32. workflow_coordinator/resources/roles/reviewer.txt +41 -0
  33. workflow_coordinator/resources/roles/simple-self-check.txt +6 -0
  34. workflow_coordinator/resources/roles/worker.txt +24 -0
  35. workflow_coordinator/serialization.py +2392 -0
  36. workflow_coordinator/slice4.py +411 -0
  37. workflow_coordinator/structured_result_schema.py +266 -0
  38. workflow_coordinator/vertical.py +597 -0
  39. workflow_coordinator-0.1.0b1.dist-info/METADATA +120 -0
  40. workflow_coordinator-0.1.0b1.dist-info/RECORD +44 -0
  41. workflow_coordinator-0.1.0b1.dist-info/WHEEL +5 -0
  42. workflow_coordinator-0.1.0b1.dist-info/entry_points.txt +2 -0
  43. workflow_coordinator-0.1.0b1.dist-info/licenses/LICENSE +21 -0
  44. workflow_coordinator-0.1.0b1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,395 @@
1
+ """Codex CLI transport adapter and its OpenAI strict-schema projection.
2
+
3
+ This module owns Codex argv/process behavior and the OpenAI Structured Outputs
4
+ dialect. It derives that dialect projection from canonical semantic facts in
5
+ ``serialization``; it neither parses nor accepts a semantic RoutingResult.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import copy
12
+ import signal
13
+ import subprocess
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from .adapter import (
19
+ ROUTING_RESULT_ENVELOPE_CONTRACT,
20
+ AgentExecutionOutcome,
21
+ AgentExecutionRequest,
22
+ ExecutionNotStartedError,
23
+ Invocation,
24
+ )
25
+ from .persistence import atomic_write_json, atomic_write_text
26
+ from .serialization import (
27
+ ESCALATION_KINDS,
28
+ ESCALATION_REQUIRED_KEYS,
29
+ COMMIT_INTENT_REQUIRED_KEYS,
30
+ EXISTING_FINDING_DELTA_KEYS,
31
+ FINDING_CITATION_KEYS,
32
+ FINDING_TRANSITION_KEYS,
33
+ NEW_FINDING_DELTA_KEYS,
34
+ NEW_FINDING_DELTA_V2_KEYS,
35
+ ROUTING_RESULT_REQUIRED_KEYS,
36
+ ROUTING_RESULT_V2_REQUIRED_KEYS,
37
+ )
38
+ from .model import (
39
+ ConvergenceAssessmentResult,
40
+ CoverageDisposition,
41
+ DiagnosisClassification,
42
+ FindingState,
43
+ Outcome,
44
+ ResultContractKind,
45
+ admits_result_contract_version,
46
+ StrategyAssessmentResult,
47
+ StrategyRevisionKind,
48
+ )
49
+ from .structured_result_schema import StructuredResultSchemaError, structured_result_envelope_schema
50
+
51
+
52
+ class CodexCliError(ExecutionNotStartedError, RuntimeError):
53
+ """A local pre-launch Codex setup or launch failure."""
54
+
55
+
56
+ class OpenAIStrictSchemaError(ValueError):
57
+ """The Codex Structured Outputs projection leaves the supported subset."""
58
+
59
+
60
+ _STRICT_KEYS = frozenset({"type", "additionalProperties", "required", "properties", "items", "enum", "anyOf"})
61
+
62
+
63
+ def assert_openai_strict_schema(schema: dict[str, Any]) -> None:
64
+ """Check the documented strict subset used by this exact projection offline."""
65
+ def walk(node: Any, location: str) -> None:
66
+ if not isinstance(node, dict):
67
+ raise OpenAIStrictSchemaError(f"{location}: schema node is not an object")
68
+ unsupported = set(node) - _STRICT_KEYS
69
+ if unsupported:
70
+ raise OpenAIStrictSchemaError(f"{location}: unsupported keywords {sorted(unsupported)}")
71
+ if "anyOf" in node:
72
+ if set(node) != {"anyOf"}:
73
+ raise OpenAIStrictSchemaError(f"{location}: composition must be a pure anyOf node")
74
+ branches = node["anyOf"]
75
+ if not isinstance(branches, list) or not branches:
76
+ raise OpenAIStrictSchemaError(f"{location}: anyOf must have branches")
77
+ for index, branch in enumerate(branches):
78
+ walk(branch, f"{location}.anyOf[{index}]")
79
+ return
80
+ node_type = node.get("type")
81
+ if node_type is None:
82
+ raise OpenAIStrictSchemaError(f"{location}: explicit type is required")
83
+ types = node_type if isinstance(node_type, list) else [node_type]
84
+ if not types or not all(item in {"object", "array", "string", "integer", "boolean", "null"} for item in types):
85
+ raise OpenAIStrictSchemaError(f"{location}: unsupported type")
86
+ if "object" in types:
87
+ properties = node.get("properties")
88
+ if not isinstance(properties, dict) or node.get("additionalProperties") is not False:
89
+ raise OpenAIStrictSchemaError(f"{location}: object must be strict")
90
+ if set(node.get("required", [])) != set(properties):
91
+ raise OpenAIStrictSchemaError(f"{location}: required must exactly cover properties")
92
+ for name, child in properties.items():
93
+ walk(child, f"{location}.properties.{name}")
94
+ if "array" in types:
95
+ if "items" not in node:
96
+ raise OpenAIStrictSchemaError(f"{location}: array requires items")
97
+ walk(node["items"], f"{location}.items")
98
+ walk(schema, "$")
99
+
100
+
101
+ def _bounded(value: str, limit: int = 16_384) -> str:
102
+ return value[-limit:]
103
+
104
+
105
+ def routing_result_openai_schema(
106
+ contract_version: int = 1, *, permitted_routes: tuple[str, ...]
107
+ ) -> dict[str, Any]:
108
+ """Project canonical RoutingResult facts into the Codex strict dialect."""
109
+ return _result_openai_schema(contract_version, permit_v3=False, permitted_routes=permitted_routes)
110
+
111
+
112
+ def _result_openai_schema(
113
+ contract_version: int, *, permit_v3: bool, permitted_routes: tuple[str, ...]
114
+ ) -> dict[str, Any]:
115
+ """Build the shared result projection for one already-admitted family."""
116
+ if contract_version not in ({1, 2, 3} if permit_v3 else {1, 2}):
117
+ raise OpenAIStrictSchemaError("unsupported RoutingResult contract version")
118
+ if not permitted_routes:
119
+ raise OpenAIStrictSchemaError(
120
+ "requested_route enum requires at least one current-phase permitted route"
121
+ )
122
+ string_array = {"type": "array", "items": {"type": "string"}}
123
+ new_finding = {
124
+ "type": "object", "additionalProperties": False,
125
+ "required": list(
126
+ NEW_FINDING_DELTA_KEYS
127
+ if contract_version == 1
128
+ else NEW_FINDING_DELTA_V2_KEYS
129
+ ),
130
+ "properties": {
131
+ "finding_id": {"type": "null"}, "invariant": {"type": "string"},
132
+ "blocking": {"type": "boolean"},
133
+ "proposed_state": {"type": "string", "enum": [state.value for state in FindingState]},
134
+ "evidence_refs": string_array, "successor_ref": {"type": ["string", "null"]},
135
+ "new_material_evidence": {"type": "boolean"},
136
+ },
137
+ }
138
+
139
+
140
+ if contract_version in {2, 3}:
141
+ new_finding["properties"]["local_ref"] = {"type": ["string", "null"]}
142
+ existing_finding = {
143
+ "type": "object", "additionalProperties": False, "required": list(EXISTING_FINDING_DELTA_KEYS),
144
+ "properties": {
145
+ "finding_id": {"type": "string"},
146
+ "proposed_state": {"type": "string", "enum": [state.value for state in FindingState]},
147
+ "evidence_refs": string_array, "successor_ref": {"type": ["string", "null"]},
148
+ "new_material_evidence": {"type": "boolean"},
149
+ },
150
+ }
151
+ if contract_version == 3:
152
+ citation = {
153
+ "type": "object", "additionalProperties": False,
154
+ "required": list(FINDING_CITATION_KEYS),
155
+ "properties": {
156
+ "finding_id": {"type": "string"}, "evidence_refs": string_array,
157
+ },
158
+ }
159
+
160
+ def target(properties: dict[str, Any]) -> dict[str, Any]:
161
+ return {
162
+ "type": "object", "additionalProperties": False,
163
+ "required": list(properties), "properties": properties,
164
+ }
165
+
166
+ transition = {
167
+ "type": "object", "additionalProperties": False,
168
+ "required": list(FINDING_TRANSITION_KEYS),
169
+ "properties": {
170
+ "finding_id": {"type": "string"}, "evidence_refs": string_array,
171
+ "target": {"anyOf": [
172
+ target({"state": {"type": "string", "enum": [FindingState.RESOLVED.value]}}),
173
+ target({"state": {"type": "string", "enum": [FindingState.RESIDUAL.value]}}),
174
+ target({
175
+ "state": {"type": "string", "enum": [FindingState.SUPERSEDED.value]},
176
+ "successor_ref": {"type": "string"},
177
+ }),
178
+ target({
179
+ "state": {"type": "string", "enum": [FindingState.OPEN.value]},
180
+ "new_material_evidence": {"type": "boolean"},
181
+ }),
182
+ ]},
183
+ },
184
+ }
185
+ finding = {"anyOf": [new_finding, citation, transition]}
186
+ else:
187
+ finding = {"anyOf": [new_finding, existing_finding]}
188
+ escalation = {
189
+ "type": "object", "additionalProperties": False, "required": list(ESCALATION_REQUIRED_KEYS),
190
+ "properties": {"kind": {"type": "string", "enum": list(ESCALATION_KINDS)}, "question": {"type": "string"}},
191
+ }
192
+ commit_intent = {
193
+ "type": "object", "additionalProperties": False,
194
+ "required": list(COMMIT_INTENT_REQUIRED_KEYS),
195
+ "properties": {"paths": string_array, "subject": {"type": "string"}},
196
+ }
197
+ properties = {
198
+ "schema_version": {"type": "integer", "enum": [contract_version]},
199
+ "outcome": {"type": "string", "enum": [outcome.value for outcome in Outcome]},
200
+ "requested_route": {"type": "string", "enum": list(permitted_routes)}, "scope_changed": {"type": "boolean"},
201
+ "requires_human": {"type": "boolean"}, "escalation": {"anyOf": [{"type": "null"}, escalation]},
202
+ "findings": {"type": "array", "items": finding}, "claimed_commits": string_array,
203
+ "commit_intent": {"anyOf": [{"type": "null"}, commit_intent]},
204
+ "evidence_refs": string_array, "summary": {"type": "string"},
205
+ }
206
+ if contract_version in {2, 3}:
207
+ coverage_claim = {
208
+ "type": "object", "additionalProperties": False,
209
+ "required": ["finding_id", "disposition", "evidence_refs"],
210
+ "properties": {
211
+ "finding_id": {"type": "string"},
212
+ "disposition": {
213
+ "type": "string",
214
+ "enum": [item.value for item in CoverageDisposition],
215
+ },
216
+ "evidence_refs": string_array,
217
+ },
218
+ }
219
+ assessment = {
220
+ "type": "object", "additionalProperties": False,
221
+ "required": ["finding_id", "correction_hop_id", "result", "evidence_refs"],
222
+ "properties": {
223
+ "finding_id": {"type": "string"},
224
+ "correction_hop_id": {"type": "string"},
225
+ "result": {
226
+ "type": "string",
227
+ "enum": [item.value for item in ConvergenceAssessmentResult],
228
+ },
229
+ "evidence_refs": string_array,
230
+ },
231
+ }
232
+ diagnosis = {
233
+ "type": "object", "additionalProperties": False,
234
+ "required": ["escape_hop_id", "finding_ids", "classification", "analysis", "evidence_refs"],
235
+ "properties": {"escape_hop_id": {"type": "string"}, "finding_ids": string_array,
236
+ "classification": {"type": "string", "enum": [item.value for item in DiagnosisClassification]},
237
+ "analysis": {"type": "string"}, "evidence_refs": string_array},
238
+ }
239
+ revision = {
240
+ "type": "object", "additionalProperties": False,
241
+ "required": ["escape_hop_id", "diagnosis_hop_id", "finding_ids", "kind", "plan", "evidence_refs"],
242
+ "properties": {"escape_hop_id": {"type": "string"}, "diagnosis_hop_id": {"type": "string"},
243
+ "finding_ids": string_array, "kind": {"type": "string", "enum": [item.value for item in StrategyRevisionKind]},
244
+ "plan": {"type": "string"}, "evidence_refs": string_array},
245
+ }
246
+ strategy_assessment = {
247
+ "type": "object", "additionalProperties": False,
248
+ "required": ["escape_hop_id", "diagnosis_hop_id", "revision_hop_id", "finding_ids", "result", "evidence_refs"],
249
+ "properties": {"escape_hop_id": {"type": "string"}, "diagnosis_hop_id": {"type": "string"},
250
+ "revision_hop_id": {"type": "string"}, "finding_ids": string_array,
251
+ "result": {"type": "string", "enum": [item.value for item in StrategyAssessmentResult]},
252
+ "evidence_refs": string_array},
253
+ }
254
+ properties.update({
255
+ "coverage_claims": {"type": "array", "items": coverage_claim},
256
+ "convergence_assessments": {"type": "array", "items": assessment},
257
+ "diagnosis": {"anyOf": [{"type": "null"}, diagnosis]},
258
+ "strategy_revision": {"anyOf": [{"type": "null"}, revision]},
259
+ "strategy_assessment": {"anyOf": [{"type": "null"}, strategy_assessment]},
260
+ })
261
+ return {
262
+ "type": "object", "additionalProperties": False,
263
+ "required": list(
264
+ ROUTING_RESULT_REQUIRED_KEYS
265
+ if contract_version == 1
266
+ else ROUTING_RESULT_V2_REQUIRED_KEYS
267
+ ),
268
+ "properties": properties,
269
+ }
270
+
271
+
272
+ def projected_result_openai_schema(
273
+ kind: ResultContractKind, contract_version: int, *, permitted_routes: tuple[str, ...]
274
+ ) -> dict[str, Any]:
275
+ """Project one selected semantic family without widening it to RoutingResult."""
276
+ if kind is ResultContractKind.GENERIC_ROUTING_RESULT:
277
+ return routing_result_openai_schema(contract_version, permitted_routes=permitted_routes)
278
+ if kind not in {ResultContractKind.WORK_RESULT, ResultContractKind.REVIEW_VERDICT}:
279
+ raise OpenAIStrictSchemaError(f"unsupported result contract kind: {kind}")
280
+ if not admits_result_contract_version(kind, contract_version):
281
+ raise OpenAIStrictSchemaError("unsupported result contract version")
282
+ schema = copy.deepcopy(
283
+ _result_openai_schema(contract_version, permit_v3=True, permitted_routes=permitted_routes)
284
+ )
285
+ result = schema["properties"]
286
+ required = schema["required"]
287
+ result.pop("outcome")
288
+ required.remove("outcome")
289
+ # Convergence records remain exclusively on the untouched generic family.
290
+ for name in ("coverage_claims", "convergence_assessments", "diagnosis", "strategy_revision", "strategy_assessment"):
291
+ result.pop(name, None)
292
+ if name in required:
293
+ required.remove(name)
294
+ field, values = (
295
+ ("status", [Outcome.COMPLETED.value, Outcome.BLOCKED.value])
296
+ if kind is ResultContractKind.WORK_RESULT
297
+ else ("verdict", ["accept", Outcome.CHANGES_REQUIRED.value])
298
+ )
299
+ result[field] = {"type": "string", "enum": values}
300
+ required.append(field)
301
+ return schema
302
+
303
+
304
+ def structured_result_envelope_openai_schema(
305
+ invocation: Invocation, contract_version: int = 1,
306
+ result_contract_kind: ResultContractKind = ResultContractKind.GENERIC_ROUTING_RESULT,
307
+ *, permitted_routes: tuple[str, ...], finding_authority: tuple[str, ...] | None = None,
308
+ ) -> dict[str, Any]:
309
+ """Return the shared closed WFC schema in Codex's strict dialect."""
310
+ try:
311
+ return structured_result_envelope_schema(
312
+ invocation, contract_version, result_contract_kind,
313
+ permitted_routes=permitted_routes, finding_authority=finding_authority,
314
+ )
315
+ except StructuredResultSchemaError as error:
316
+ raise OpenAIStrictSchemaError(str(error)) from error
317
+
318
+
319
+ @dataclass(frozen=True)
320
+ class CodexCliAdapter:
321
+ """Concrete single-provider implementation of the execution port."""
322
+
323
+ result_directory: Path
324
+ model: str
325
+ reasoning_effort: str
326
+ executable: str = "codex"
327
+
328
+ def __post_init__(self) -> None:
329
+ for name, value in (
330
+ ("model", self.model),
331
+ ("reasoning_effort", self.reasoning_effort),
332
+ ):
333
+ if not isinstance(value, str) or not value.strip():
334
+ raise ValueError(f"Codex CLI {name} must be explicit and non-empty")
335
+ if value.splitlines() != [value] or "\0" in value:
336
+ raise ValueError(f"Codex CLI {name} must be a single-line value")
337
+
338
+ def argv(self, request: AgentExecutionRequest, schema: Path, result: Path) -> tuple[str, ...]:
339
+ return (
340
+ self.executable, "--ask-for-approval", "never", "exec", "--ephemeral", "--json",
341
+ "--color", "never", "--sandbox", "workspace-write", "--model", self.model,
342
+ "-c", f'model_reasoning_effort="{self.reasoning_effort}"',
343
+ "-c", "sandbox_workspace_write.network_access=true", "--cd", str(request.repository.resolve()),
344
+ "--output-schema", str(schema), "--output-last-message", str(result), "-",
345
+ )
346
+
347
+ def execute(self, request: AgentExecutionRequest) -> AgentExecutionOutcome:
348
+ if request.result_contract != ROUTING_RESULT_ENVELOPE_CONTRACT:
349
+ raise CodexCliError(f"unsupported result contract: {request.result_contract}")
350
+ if request.result_contract_kind not in set(ResultContractKind):
351
+ raise CodexCliError(f"unsupported result contract kind: {request.result_contract_kind}")
352
+ if request.timeout_seconds <= 0:
353
+ raise CodexCliError("timeout must be positive")
354
+ if not admits_result_contract_version(
355
+ request.result_contract_kind, request.contract_version
356
+ ):
357
+ raise CodexCliError("unsupported result contract version")
358
+ if not request.permitted_routes:
359
+ raise CodexCliError(
360
+ "current phase has no permitted routes; refusing to dispatch an unroutable invocation"
361
+ )
362
+ try:
363
+ schema = self.result_directory / "structured-result.schema.json"
364
+ result = self.result_directory / "result-message.json"
365
+ atomic_write_json(
366
+ schema,
367
+ structured_result_envelope_openai_schema(
368
+ request.invocation, request.contract_version, request.result_contract_kind,
369
+ permitted_routes=request.permitted_routes,
370
+ finding_authority=request.finding_authority,
371
+ ),
372
+ )
373
+ atomic_write_text(result, "")
374
+ child = subprocess.Popen(
375
+ self.argv(request, schema, result), stdin=subprocess.PIPE, stdout=subprocess.PIPE,
376
+ stderr=subprocess.PIPE, text=True, start_new_session=True,
377
+ )
378
+ except (OSError, ValueError) as error:
379
+ raise CodexCliError("local pre-acceptance executable launch failure") from error
380
+ try:
381
+ stdout, stderr = child.communicate(request.prompt, timeout=request.timeout_seconds)
382
+ timed_out = False
383
+ except subprocess.TimeoutExpired:
384
+ timed_out = True
385
+ os.killpg(child.pid, signal.SIGTERM)
386
+ try:
387
+ stdout, stderr = child.communicate(timeout=3)
388
+ except subprocess.TimeoutExpired:
389
+ os.killpg(child.pid, signal.SIGKILL)
390
+ stdout, stderr = child.communicate()
391
+ candidate = result.read_text(encoding="utf-8") or None
392
+ diagnostics = () if child.returncode == 0 and not timed_out else (
393
+ "Codex CLI timed out" if timed_out else f"Codex CLI exited {child.returncode}",
394
+ )
395
+ return AgentExecutionOutcome(candidate, child.returncode, timed_out, _bounded(stdout), _bounded(stderr), diagnostics)
@@ -0,0 +1,231 @@
1
+ """One-shot Level-3 preparation runner for the Codex adapter boundary.
2
+
3
+ This is intentionally below the coordinator: it creates a disposable Git
4
+ workspace solely for the external CLI working-directory prerequisite, invokes
5
+ the Codex adapter exactly once, and validates the returned routing envelope.
6
+ It does not exercise Run/Hop lifecycle, coordinator Git workflow or authority
7
+ semantics, reduction, or the Slice-4 proof harness. A later real invocation
8
+ remains separately authorized.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import hashlib
15
+ import subprocess
16
+ from pathlib import Path
17
+ from uuid import uuid4
18
+
19
+ from .adapter import (
20
+ ROUTING_RESULT_ENVELOPE_CONTRACT,
21
+ AgentExecutionRequest,
22
+ ExecutionNotStartedError,
23
+ Invocation,
24
+ ResultValidationError,
25
+ validated_result,
26
+ )
27
+ from .codex_adapter import CodexCliAdapter
28
+ from .persistence import atomic_write_json
29
+
30
+
31
+ DEFAULT_TIMEOUT_SECONDS = 120.0
32
+
33
+
34
+ def _prompt(invocation: Invocation) -> str:
35
+ return f"""Return only one structured envelope matching the supplied output schema.
36
+ Use these exact correlation IDs: run_id={invocation.run_id}, hop_id={invocation.hop_id}, invocation_id={invocation.invocation_id}.
37
+ Return a minimal valid RoutingResult: schema_version 1, outcome completed, requested_route done, false scope_changed/requires_human, null escalation, empty findings/commits/evidence, and a concise summary. Do no repository, shell, tool, or Git work."""
38
+
39
+
40
+ def _summary_base(
41
+ invocation: Invocation,
42
+ *,
43
+ executable: str,
44
+ model: str,
45
+ reasoning_effort: str,
46
+ timeout_seconds: float,
47
+ ) -> dict[str, object]:
48
+ return {
49
+ "schema_version": 1,
50
+ "smoke_status": "local_pre_execution_error",
51
+ "run_id": invocation.run_id,
52
+ "hop_id": invocation.hop_id,
53
+ "invocation_id": invocation.invocation_id,
54
+ "executable": executable,
55
+ "model": model,
56
+ "reasoning_effort": reasoning_effort,
57
+ "timeout_seconds": timeout_seconds,
58
+ "result_contract": ROUTING_RESULT_ENVELOPE_CONTRACT,
59
+ "invocation_attempted": False,
60
+ "returncode": None,
61
+ "timed_out": False,
62
+ "diagnostics": [],
63
+ "stdout_tail": "",
64
+ "stderr_tail": "",
65
+ "candidate_result_present": False,
66
+ "semantic_validation_succeeded": False,
67
+ "configured_executable_smoke_succeeded": False,
68
+ }
69
+
70
+
71
+ def _write_summary_best_effort(path: Path, summary: dict[str, object]) -> None:
72
+ """Persist failure evidence without replacing the failure being recorded."""
73
+ try:
74
+ atomic_write_json(path, summary)
75
+ except Exception:
76
+ pass
77
+
78
+
79
+ def _initialize_disposable_git_workspace(workspace: Path) -> None:
80
+ """Initialize only the local CLI prerequisite for a fresh smoke workspace."""
81
+ try:
82
+ subprocess.run(
83
+ ("git", "init"),
84
+ cwd=workspace,
85
+ check=True,
86
+ capture_output=True,
87
+ text=True,
88
+ )
89
+ except subprocess.CalledProcessError as error:
90
+ diagnostics = error.stderr.strip() or error.stdout.strip() or str(error)
91
+ raise OSError(f"disposable workspace git initialization failed: {diagnostics}") from error
92
+
93
+
94
+ def run_smoke(
95
+ smoke_root: Path,
96
+ *,
97
+ executable: str = "codex",
98
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS,
99
+ model: str = "gpt-5.6-terra",
100
+ reasoning_effort: str = "medium",
101
+ ) -> int:
102
+ """Run exactly one adapter invocation, returning a shell-compatible status."""
103
+ try:
104
+ smoke_root.mkdir()
105
+ except FileExistsError:
106
+ # Do not write into an existing root: it is the one-shot execution guard.
107
+ return 2
108
+
109
+ invocation = Invocation(
110
+ run_id=f"SMOKE-{uuid4().hex}", hop_id="H001", invocation_id=f"INV-{uuid4().hex}"
111
+ )
112
+ summary = _summary_base(
113
+ invocation,
114
+ executable=executable,
115
+ model=model,
116
+ reasoning_effort=reasoning_effort,
117
+ timeout_seconds=timeout_seconds,
118
+ )
119
+ summary_path = smoke_root / "smoke-summary.json"
120
+ workspace = smoke_root / "workspace"
121
+ result_directory = smoke_root / "result"
122
+
123
+ try:
124
+ workspace.mkdir()
125
+ result_directory.mkdir()
126
+ except OSError as error:
127
+ summary["diagnostics"] = [str(error)]
128
+ _write_summary_best_effort(summary_path, summary)
129
+ return 1
130
+
131
+ try:
132
+ _initialize_disposable_git_workspace(workspace)
133
+ except OSError as error:
134
+ summary["diagnostics"] = [str(error)]
135
+ _write_summary_best_effort(summary_path, summary)
136
+ return 1
137
+
138
+ try:
139
+ adapter = CodexCliAdapter(
140
+ result_directory=result_directory,
141
+ executable=executable,
142
+ model=model,
143
+ reasoning_effort=reasoning_effort,
144
+ )
145
+ outcome = adapter.execute(
146
+ AgentExecutionRequest(
147
+ invocation=invocation,
148
+ prompt=_prompt(invocation),
149
+ repository=workspace,
150
+ result_contract=ROUTING_RESULT_ENVELOPE_CONTRACT,
151
+ timeout_seconds=timeout_seconds,
152
+ permitted_routes=("done",),
153
+ )
154
+ )
155
+ except ExecutionNotStartedError as error:
156
+ summary["diagnostics"] = [str(error)]
157
+ _write_summary_best_effort(summary_path, summary)
158
+ return 1
159
+ except Exception as error:
160
+ summary.update(invocation_attempted=True, smoke_status="post_execution_error")
161
+ summary["diagnostics"] = [str(error)]
162
+ _write_summary_best_effort(summary_path, summary)
163
+ return 1
164
+
165
+ try:
166
+ summary.update(
167
+ invocation_attempted=True,
168
+ returncode=outcome.returncode,
169
+ timed_out=outcome.timed_out,
170
+ diagnostics=list(outcome.diagnostics),
171
+ stdout_tail=outcome.stdout,
172
+ stderr_tail=outcome.stderr,
173
+ candidate_result_present=outcome.candidate_result is not None,
174
+ )
175
+ schema_path = result_directory / "structured-result.schema.json"
176
+ if schema_path.exists():
177
+ summary["result_schema_sha256"] = hashlib.sha256(schema_path.read_bytes()).hexdigest()
178
+
179
+ validated = None
180
+ if outcome.candidate_result is not None:
181
+ try:
182
+ validated = validated_result(outcome.candidate_result, invocation)
183
+ except ResultValidationError as error:
184
+ summary["diagnostics"] = [*outcome.diagnostics, f"semantic validation failed: {error}"]
185
+ else:
186
+ summary["semantic_validation_succeeded"] = True
187
+ summary["semantic_result_summary"] = {
188
+ "outcome": validated.outcome.value,
189
+ "requested_route": validated.requested_route,
190
+ "summary": validated.summary,
191
+ }
192
+
193
+ transport_succeeded = outcome.returncode == 0 and not outcome.timed_out
194
+ if transport_succeeded and validated is not None:
195
+ summary["smoke_status"] = "succeeded"
196
+ summary["configured_executable_smoke_succeeded"] = True
197
+ exit_code = 0
198
+ elif not transport_succeeded:
199
+ summary["smoke_status"] = "transport_failure"
200
+ exit_code = 1
201
+ else:
202
+ summary["smoke_status"] = "semantic_failure"
203
+ exit_code = 1
204
+ except Exception as error:
205
+ summary["smoke_status"] = "post_execution_error"
206
+ summary["diagnostics"] = [*summary["diagnostics"], str(error)]
207
+ _write_summary_best_effort(summary_path, summary)
208
+ return 1
209
+ atomic_write_json(summary_path, summary)
210
+ return exit_code
211
+
212
+
213
+ def main(argv: list[str] | None = None) -> int:
214
+ parser = argparse.ArgumentParser(description="Run the separately authorized one-shot Codex adapter smoke.")
215
+ parser.add_argument("--smoke-root", type=Path, required=True, help="new durable output directory")
216
+ parser.add_argument("--executable", default="codex")
217
+ parser.add_argument("--timeout-seconds", type=float, default=DEFAULT_TIMEOUT_SECONDS)
218
+ parser.add_argument("--model", default="gpt-5.6-terra")
219
+ parser.add_argument("--reasoning-effort", default="medium")
220
+ args = parser.parse_args(argv)
221
+ return run_smoke(
222
+ args.smoke_root,
223
+ executable=args.executable,
224
+ timeout_seconds=args.timeout_seconds,
225
+ model=args.model,
226
+ reasoning_effort=args.reasoning_effort,
227
+ )
228
+
229
+
230
+ if __name__ == "__main__":
231
+ raise SystemExit(main())