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 @@
1
+ """Repository-local mechanics for the accepted workflow coordinator slices."""
@@ -0,0 +1,150 @@
1
+ """Provider-neutral execution port and deterministic local test adapters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import subprocess
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+ from typing import Protocol
10
+
11
+ from .model import ResultContractKind, ResultValue, admits_result_contract_version
12
+ from .serialization import ValidationError, review_verdict_from_data, routing_result_from_data, work_result_from_data
13
+
14
+
15
+ class ResultValidationError(ValidationError):
16
+ """An adapter result is malformed, incomplete, or belongs to another invocation."""
17
+
18
+
19
+ class ExecutionResultValidationError(ResultValidationError):
20
+ """A semantic rejection paired with its completed transport outcome."""
21
+
22
+ def __init__(self, outcome: AgentExecutionOutcome, message: str):
23
+ super().__init__(message)
24
+ self.outcome = outcome
25
+
26
+
27
+ class ExecutionNotStartedError(ValueError):
28
+ """A local failure that proves the execution port was not entered."""
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Invocation:
33
+ run_id: str
34
+ hop_id: str
35
+ invocation_id: str
36
+
37
+
38
+ @dataclass(frozen=True)
39
+ class AgentExecutionRequest:
40
+ """Facts the application supplies for one bounded agent invocation.
41
+
42
+ ``result_contract`` identifies the canonical semantic result envelope; its
43
+ provider transport projection is deliberately an adapter concern.
44
+ """
45
+
46
+ invocation: Invocation
47
+ prompt: str
48
+ repository: Path
49
+ result_contract: str
50
+ timeout_seconds: float
51
+ contract_version: int = 1
52
+ result_contract_kind: ResultContractKind = ResultContractKind.GENERIC_ROUTING_RESULT
53
+ # Current-phase route keys a strict-schema adapter may admit for
54
+ # ``requested_route``; empty is only meaningful to adapters that do not
55
+ # project such a schema (a strict-schema adapter must fail closed on empty,
56
+ # never treat it as unconstrained).
57
+ permitted_routes: tuple[str, ...] = ()
58
+ # The admitted phase's own permitted Finding operations, which a
59
+ # strict-schema adapter projects into the ``findings`` surface. ``None``
60
+ # states no authority at all, and keeps the unnarrowed surface; ``()`` is
61
+ # the truthful value for a phase that may author no authoritative
62
+ # disposition. The reducer re-derives and enforces the same authority.
63
+ finding_authority: tuple[str, ...] | None = None
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class AgentExecutionOutcome:
68
+ """Transport facts, before provider-neutral semantic acceptance.
69
+
70
+ A candidate result is intentionally not a ``RoutingResult``. The caller
71
+ must still parse, validate, and correlate it through ``validated_result``.
72
+ """
73
+
74
+ candidate_result: str | None
75
+ returncode: int | None
76
+ timed_out: bool
77
+ stdout: str
78
+ stderr: str
79
+ diagnostics: tuple[str, ...] = ()
80
+
81
+
82
+ ROUTING_RESULT_ENVELOPE_CONTRACT = "routing-result-envelope/v1"
83
+
84
+
85
+ class AgentExecutionPort(Protocol):
86
+ def execute(self, request: AgentExecutionRequest) -> AgentExecutionOutcome: ...
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class FakeAdapter:
91
+ output: str
92
+
93
+ def execute(self, request: AgentExecutionRequest) -> AgentExecutionOutcome:
94
+ return AgentExecutionOutcome(self.output, 0, False, "", "")
95
+
96
+
97
+ @dataclass(frozen=True)
98
+ class SubprocessAdapter:
99
+ """A disposable-fixture adapter, deliberately not a provider SDK."""
100
+
101
+ argv: tuple[str, ...]
102
+
103
+ def execute(self, request: AgentExecutionRequest) -> AgentExecutionOutcome:
104
+ completed = subprocess.run(self.argv, cwd=request.repository, input=request.prompt, text=True,
105
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False)
106
+ return AgentExecutionOutcome(
107
+ completed.stdout if completed.returncode == 0 else None,
108
+ completed.returncode,
109
+ False,
110
+ completed.stdout,
111
+ completed.stderr,
112
+ (f"subprocess adapter exited {completed.returncode}",) if completed.returncode else (),
113
+ )
114
+
115
+
116
+ def validated_result(
117
+ raw: str, expected: Invocation, contract_version: int = 1,
118
+ result_contract_kind: ResultContractKind = ResultContractKind.GENERIC_ROUTING_RESULT,
119
+ ) -> ResultValue:
120
+ if not admits_result_contract_version(result_contract_kind, contract_version):
121
+ raise ResultValidationError("unsupported structured result contract version")
122
+ try:
123
+ envelope = json.loads(raw)
124
+ except json.JSONDecodeError as error:
125
+ raise ResultValidationError("truncated or invalid structured result") from error
126
+ if not isinstance(envelope, dict) or set(envelope) != {"schema_version", "run_id", "hop_id", "invocation_id", "result"}:
127
+ raise ResultValidationError("structured result has missing or unknown envelope fields")
128
+ if envelope["schema_version"] != contract_version:
129
+ raise ResultValidationError("structured result has unsupported schema version")
130
+ actual = (envelope["run_id"], envelope["hop_id"], envelope["invocation_id"])
131
+ wanted = (expected.run_id, expected.hop_id, expected.invocation_id)
132
+ if actual != wanted:
133
+ raise ResultValidationError("structured result identity does not correlate to dispatch")
134
+ try:
135
+ parsers = {
136
+ ResultContractKind.GENERIC_ROUTING_RESULT: routing_result_from_data,
137
+ ResultContractKind.WORK_RESULT: work_result_from_data,
138
+ ResultContractKind.REVIEW_VERDICT: review_verdict_from_data,
139
+ }
140
+ parser = parsers.get(result_contract_kind)
141
+ if parser is None:
142
+ raise ResultValidationError("unsupported result contract kind")
143
+ result = parser(envelope["result"])
144
+ if result.schema_version != contract_version:
145
+ raise ResultValidationError(
146
+ "structured result version does not match the selected contract"
147
+ )
148
+ return result
149
+ except ValidationError as error:
150
+ raise ResultValidationError(str(error)) from error
@@ -0,0 +1,289 @@
1
+ """Claude Code CLI transport with a restricted noninteractive profile."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import shutil
10
+ import signal
11
+ import stat
12
+ import subprocess
13
+ import tempfile
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+
17
+ from .adapter import (
18
+ ROUTING_RESULT_ENVELOPE_CONTRACT,
19
+ AgentExecutionOutcome,
20
+ AgentExecutionRequest,
21
+ ExecutionNotStartedError,
22
+ )
23
+ from .model import ResultContractKind, admits_result_contract_version
24
+ from .persistence import atomic_write_json
25
+ from .structured_result_schema import structured_result_envelope_schema
26
+
27
+
28
+ class ClaudeCliError(ExecutionNotStartedError, RuntimeError):
29
+ """A local pre-launch Claude setup or launch failure."""
30
+
31
+
32
+ _TOOLS = "Read,Glob,Grep,Edit,Write,Bash,WebFetch,WebSearch"
33
+ _ENVIRONMENT_NAMES = ("PATH", "HOME", "USER", "LANG")
34
+
35
+
36
+ def _extra_environment_names() -> tuple[str, ...]:
37
+ """Read comma-separated additional environment names once at construction."""
38
+ value = os.environ.get("WFC_CLAUDE_EXTRA_ENV_NAMES", "")
39
+ return tuple(name.strip() for name in value.split(",")) if value else ()
40
+
41
+ # Claude Code derives its own per-session IPC directory from TMPDIR (keyed by
42
+ # uid, the launch cwd with "/" replaced by "-", and a session UUID) and binds
43
+ # AF_UNIX sockets inside it for the Bash tool's sandbox bridge. AF_UNIX socket
44
+ # paths are capped at 108 bytes (`sockaddr_un.sun_path`); WFC's own ambient
45
+ # TMPDIR is a long, human-readable, Attempt-scoped scratch/state directory
46
+ # name, and inheriting it reliably pushes that derived path past the kernel
47
+ # limit, failing the sandbox bridge even for trivial commands. Give the
48
+ # subprocess a short, invocation-scoped TMPDIR instead of inheriting it.
49
+ _SHORT_TMP_ROOT = Path("/tmp")
50
+
51
+ # Unprivileged, WFC-owned fallback used only when the ambient TMPDIR/TMP/TEMP
52
+ # (or, failing those, the platform tempfile default) resolves to
53
+ # _SHORT_TMP_ROOT itself -- e.g. the stock Ubuntu/WSL default with none of
54
+ # those set, or an operator explicitly setting TMPDIR=/tmp -- which would
55
+ # otherwise make the short symlink and its own real target the same path.
56
+ # Historically mirrored create_attempt_scratch()'s own unprivileged
57
+ # `~/wfc-scratch` default (the now-retired `scripts/wfc_op.py` Harness).
58
+ _WFC_FALLBACK_SCRATCH_ROOT = Path.home() / ".wfc-claude-scratch"
59
+
60
+
61
+ def _external_scratch_root() -> Path:
62
+ """The large-capacity, Attempt-isolated scratch WFC's own launch already
63
+ exports via TMPDIR/TMP/TEMP ahead of the adapter shortening it for the
64
+ subprocess (FD-08); falls back to the platform default outside WFC so
65
+ the adapter still works standalone, without assuming that layout. Never
66
+ returns a path that resolves to _SHORT_TMP_ROOT; falls back to
67
+ _WFC_FALLBACK_SCRATCH_ROOT instead in that degenerate case."""
68
+ for name in ("TMPDIR", "TMP", "TEMP"):
69
+ value = os.environ.get(name)
70
+ if value:
71
+ root = Path(value)
72
+ break
73
+ else:
74
+ root = Path(tempfile.gettempdir())
75
+ if root.resolve() == _SHORT_TMP_ROOT.resolve():
76
+ return _WFC_FALLBACK_SCRATCH_ROOT
77
+ return root
78
+
79
+
80
+ def _supersede_or_reject_leftover(path: Path, description: str) -> None:
81
+ """Deterministically clear a leftover at a WFC-derived, invocation-scoped
82
+ path (e.g. after an unclean prior shutdown of the same invocation),
83
+ without ever touching a path this process does not itself own."""
84
+ try:
85
+ info = path.lstat()
86
+ except FileNotFoundError:
87
+ return
88
+ if info.st_uid != os.geteuid():
89
+ raise ClaudeCliError(f"{description} already exists and is not owned by the current user: {path}")
90
+ if stat.S_ISDIR(info.st_mode):
91
+ shutil.rmtree(path, ignore_errors=True)
92
+ else:
93
+ path.unlink(missing_ok=True)
94
+
95
+
96
+ def _remove_scratch_path(path: Path) -> None:
97
+ """Best-effort removal of either the short TMPDIR symlink or the real
98
+ scratch directory it points at. Never raises, so a failure removing one
99
+ cleanup target can never suppress the other cleanup step or mask an
100
+ in-flight exception from the caller's try block."""
101
+ try:
102
+ if path.is_symlink():
103
+ path.unlink(missing_ok=True)
104
+ else:
105
+ shutil.rmtree(path, ignore_errors=True)
106
+ except OSError:
107
+ pass
108
+
109
+
110
+ def _bounded(value: str, limit: int = 16_384) -> str:
111
+ return value[-limit:]
112
+
113
+
114
+ @dataclass(frozen=True)
115
+ class ClaudeCliAdapter:
116
+ """Concrete Claude Code implementation of the unchanged execution port."""
117
+
118
+ result_directory: Path
119
+ model: str
120
+ reasoning_effort: str
121
+ executable: str = "claude"
122
+ extra_environment_names: tuple[str, ...] = field(default_factory=_extra_environment_names)
123
+
124
+ def __post_init__(self) -> None:
125
+ if not isinstance(self.extra_environment_names, tuple):
126
+ raise ValueError("Claude CLI extra environment names must be a tuple")
127
+ for name in self.extra_environment_names:
128
+ if (not isinstance(name, str) or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name)
129
+ or name.startswith("CLAUDE_CODE_") or name in {"TMPDIR", "TMP", "TEMP"}):
130
+ raise ValueError("invalid or reserved Claude CLI extra environment name")
131
+ for name, value in (("model", self.model), ("reasoning_effort", self.reasoning_effort)):
132
+ if not isinstance(value, str) or not value.strip():
133
+ raise ValueError(f"Claude CLI {name} must be explicit and non-empty")
134
+ if value.splitlines() != [value] or "\0" in value:
135
+ raise ValueError(f"Claude CLI {name} must be a single-line value")
136
+
137
+ def argv(
138
+ self, request: AgentExecutionRequest, serialized_schema: str, settings: Path
139
+ ) -> tuple[str, ...]:
140
+ return (
141
+ self.executable, "-p", "--output-format", "json", "--json-schema", serialized_schema,
142
+ "--model", self.model, "--effort", self.reasoning_effort,
143
+ "--restricted", "--safe-mode", "--strict-mcp-config", "--tools", _TOOLS,
144
+ "--settings", str(settings), "--permission-mode", "acceptEdits",
145
+ "--permission-prompts", "none", "--no-session-persistence", request.prompt,
146
+ )
147
+
148
+ @staticmethod
149
+ def _settings(request: AgentExecutionRequest, external_scratch_dir: Path) -> dict[str, object]:
150
+ scratch = str(external_scratch_dir)
151
+ return {
152
+ "sandbox": {
153
+ "enabled": True,
154
+ "failIfUnavailable": True,
155
+ "allowUnsandboxedCommands": False,
156
+ "filesystem": {
157
+ "denyRead": ["~/"],
158
+ "allowRead": [str(request.repository.resolve()), scratch],
159
+ "allowWrite": [scratch],
160
+ },
161
+ # Claude 2.1.322 merges WebFetch(domain:*) below into the Bash
162
+ # proxy allowlist. This requests broad networking, including
163
+ # potential intranet access, not public-only containment.
164
+ "network": {"allowedDomains": []},
165
+ },
166
+ "permissions": {
167
+ # Restricted mode confines file tools to the working directory.
168
+ "allow": ["Edit", "Write", "WebFetch(domain:*)", "WebSearch", "Bash(curl:*)"],
169
+ "deny": [],
170
+ "blockReadsOutsideWorkingDirectories": True,
171
+ },
172
+ }
173
+
174
+ @staticmethod
175
+ def _invocation_token(request: AgentExecutionRequest) -> str:
176
+ return hashlib.sha256(
177
+ f"{request.invocation.run_id}/{request.invocation.hop_id}/"
178
+ f"{request.invocation.invocation_id}".encode()
179
+ ).hexdigest()[:16]
180
+
181
+ @classmethod
182
+ def _short_subprocess_tmp_dir(cls, request: AgentExecutionRequest) -> Path:
183
+ """A short, deterministic per-invocation TMPDIR symlink path; see
184
+ `_SHORT_TMP_ROOT`. Its real target is `_external_scratch_dir()`."""
185
+ return _SHORT_TMP_ROOT / f"wfc-claude-{cls._invocation_token(request)}"
186
+
187
+ @classmethod
188
+ def _external_scratch_dir(cls, request: AgentExecutionRequest) -> Path:
189
+ """The dedicated, invocation-scoped real directory the short TMPDIR
190
+ symlink points at; see `_external_scratch_root()`."""
191
+ return _external_scratch_root() / f"wfc-claude-{cls._invocation_token(request)}"
192
+
193
+ @staticmethod
194
+ def _candidate_from_wrapper(stdout: str) -> str | None:
195
+ """Return only Claude's successful structured-output member, verbatim."""
196
+ try:
197
+ wrapper = json.loads(stdout)
198
+ except json.JSONDecodeError:
199
+ return None
200
+ if not isinstance(wrapper, dict):
201
+ return None
202
+ if wrapper.get("type") != "result" or wrapper.get("subtype") != "success":
203
+ return None
204
+ if wrapper.get("is_error") is not False:
205
+ return None
206
+ structured_output = wrapper.get("structured_output")
207
+ if not isinstance(structured_output, dict):
208
+ return None
209
+ return json.dumps(structured_output)
210
+
211
+ def execute(self, request: AgentExecutionRequest) -> AgentExecutionOutcome:
212
+ if request.result_contract != ROUTING_RESULT_ENVELOPE_CONTRACT:
213
+ raise ClaudeCliError(f"unsupported result contract: {request.result_contract}")
214
+ if request.result_contract_kind not in set(ResultContractKind):
215
+ raise ClaudeCliError(f"unsupported result contract kind: {request.result_contract_kind}")
216
+ if request.timeout_seconds <= 0:
217
+ raise ClaudeCliError("timeout must be positive")
218
+ if not admits_result_contract_version(request.result_contract_kind, request.contract_version):
219
+ raise ClaudeCliError("unsupported result contract version")
220
+ if not request.permitted_routes:
221
+ raise ClaudeCliError(
222
+ "current phase has no permitted routes; refusing to dispatch an unroutable invocation"
223
+ )
224
+ tmp_dir = self._short_subprocess_tmp_dir(request)
225
+ real_dir = self._external_scratch_dir(request)
226
+ _supersede_or_reject_leftover(real_dir, "external scratch target")
227
+ _supersede_or_reject_leftover(tmp_dir, "short TMPDIR symlink")
228
+ try:
229
+ try:
230
+ real_dir.mkdir(parents=True, mode=0o700)
231
+ real_dir.chmod(0o700)
232
+ real_dir = real_dir.resolve()
233
+ tmp_dir.symlink_to(real_dir, target_is_directory=True)
234
+ schema = self.result_directory / "structured-result.schema.json"
235
+ settings = self.result_directory / "claude-closed-settings.json"
236
+ schema_object = structured_result_envelope_schema(
237
+ request.invocation, request.contract_version, request.result_contract_kind,
238
+ permitted_routes=request.permitted_routes,
239
+ finding_authority=request.finding_authority,
240
+ )
241
+ atomic_write_json(schema, schema_object)
242
+ atomic_write_json(settings, self._settings(request, real_dir))
243
+ environment = {
244
+ name: os.environ[name]
245
+ for name in (*_ENVIRONMENT_NAMES, *self.extra_environment_names)
246
+ if name in os.environ
247
+ }
248
+ environment.update(TMPDIR=str(tmp_dir), TMP=str(tmp_dir), TEMP=str(tmp_dir))
249
+ child = subprocess.Popen(
250
+ self.argv(
251
+ request,
252
+ json.dumps(schema_object, separators=(",", ":"), sort_keys=True),
253
+ settings,
254
+ ),
255
+ cwd=request.repository.resolve(),
256
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,
257
+ start_new_session=True, env=environment,
258
+ )
259
+ except (OSError, ValueError) as error:
260
+ raise ClaudeCliError("local pre-acceptance executable launch failure") from error
261
+ try:
262
+ stdout, stderr = child.communicate(timeout=request.timeout_seconds)
263
+ timed_out = False
264
+ except subprocess.TimeoutExpired:
265
+ timed_out = True
266
+ os.killpg(child.pid, signal.SIGTERM)
267
+ try:
268
+ stdout, stderr = child.communicate(timeout=3)
269
+ except subprocess.TimeoutExpired:
270
+ os.killpg(child.pid, signal.SIGKILL)
271
+ stdout, stderr = child.communicate()
272
+ finally:
273
+ # tmp_dir is normally a symlink (shutil.rmtree() refuses to
274
+ # operate on one, silently no-oping under ignore_errors=True)
275
+ # but may be a plain directory if symlink creation itself never
276
+ # completed; remove each target independently so a failure
277
+ # removing one can never suppress the other or the exception
278
+ # already in flight from the try block above.
279
+ _remove_scratch_path(tmp_dir)
280
+ _remove_scratch_path(real_dir)
281
+ stdout = stdout or ""
282
+ stderr = stderr or ""
283
+ candidate = None if timed_out or child.returncode != 0 else self._candidate_from_wrapper(stdout)
284
+ diagnostics = () if child.returncode == 0 and not timed_out else (
285
+ "Claude CLI timed out" if timed_out else f"Claude CLI exited {child.returncode}",
286
+ )
287
+ return AgentExecutionOutcome(
288
+ candidate, child.returncode, timed_out, _bounded(stdout), _bounded(stderr), diagnostics
289
+ )