agentic-sdlc-system 0.1.0__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 (113) hide show
  1. agentic_sdlc/__init__.py +14 -0
  2. agentic_sdlc/adapters/__init__.py +24 -0
  3. agentic_sdlc/adapters/base.py +209 -0
  4. agentic_sdlc/adapters/claude.py +122 -0
  5. agentic_sdlc/adapters/codex.py +116 -0
  6. agentic_sdlc/adapters/process.py +188 -0
  7. agentic_sdlc/agents/__init__.py +6 -0
  8. agentic_sdlc/agents/prompts.py +251 -0
  9. agentic_sdlc/agents/roles.py +183 -0
  10. agentic_sdlc/build/__init__.py +18 -0
  11. agentic_sdlc/build/accessibility.py +233 -0
  12. agentic_sdlc/build/adr.py +235 -0
  13. agentic_sdlc/build/android_deploy.py +195 -0
  14. agentic_sdlc/build/android_review_rules.py +250 -0
  15. agentic_sdlc/build/architecture_specs.py +238 -0
  16. agentic_sdlc/build/build_adapter.py +216 -0
  17. agentic_sdlc/build/ci_templates.py +151 -0
  18. agentic_sdlc/build/compose_testing.py +285 -0
  19. agentic_sdlc/build/coverage.py +221 -0
  20. agentic_sdlc/build/device_adapter.py +482 -0
  21. agentic_sdlc/build/emulator.py +89 -0
  22. agentic_sdlc/build/emulator_matrix.py +276 -0
  23. agentic_sdlc/build/emulator_snapshots.py +209 -0
  24. agentic_sdlc/build/gradle_catalog.py +298 -0
  25. agentic_sdlc/build/ios_adapter.py +192 -0
  26. agentic_sdlc/build/manifest.py +61 -0
  27. agentic_sdlc/build/performance.py +213 -0
  28. agentic_sdlc/build/release_manager.py +250 -0
  29. agentic_sdlc/build/robolectric.py +262 -0
  30. agentic_sdlc/build/security.py +362 -0
  31. agentic_sdlc/build/sprint_manager.py +305 -0
  32. agentic_sdlc/build/versioning.py +275 -0
  33. agentic_sdlc/build/visual_regression.py +194 -0
  34. agentic_sdlc/chat/__init__.py +5 -0
  35. agentic_sdlc/chat/interface.py +464 -0
  36. agentic_sdlc/cli.py +475 -0
  37. agentic_sdlc/config.py +46 -0
  38. agentic_sdlc/doctor.py +142 -0
  39. agentic_sdlc/feedback/__init__.py +22 -0
  40. agentic_sdlc/feedback/acceptance.py +71 -0
  41. agentic_sdlc/feedback/intake.py +131 -0
  42. agentic_sdlc/git_ops/__init__.py +18 -0
  43. agentic_sdlc/git_ops/github.py +174 -0
  44. agentic_sdlc/git_ops/worktree.py +177 -0
  45. agentic_sdlc/memory/__init__.py +17 -0
  46. agentic_sdlc/memory/layers.py +224 -0
  47. agentic_sdlc/memory/reflection.py +192 -0
  48. agentic_sdlc/onboard/__init__.py +6 -0
  49. agentic_sdlc/onboard/scanner.py +588 -0
  50. agentic_sdlc/onboard/wizard.py +303 -0
  51. agentic_sdlc/prompts/arch_reviewer.md +35 -0
  52. agentic_sdlc/prompts/architect.md +52 -0
  53. agentic_sdlc/prompts/classifier.md +25 -0
  54. agentic_sdlc/prompts/codebase_analyst.md +31 -0
  55. agentic_sdlc/prompts/deployer.md +36 -0
  56. agentic_sdlc/prompts/developer.md +21 -0
  57. agentic_sdlc/prompts/po_reviewer.md +30 -0
  58. agentic_sdlc/prompts/product_owner.md +34 -0
  59. agentic_sdlc/prompts/qa_classifier.md +34 -0
  60. agentic_sdlc/prompts/qa_test_author.md +17 -0
  61. agentic_sdlc/prompts/reviewer.md +29 -0
  62. agentic_sdlc/providers/__init__.py +34 -0
  63. agentic_sdlc/providers/api_anthropic.py +248 -0
  64. agentic_sdlc/providers/api_apply.py +303 -0
  65. agentic_sdlc/providers/api_openai.py +290 -0
  66. agentic_sdlc/providers/base.py +190 -0
  67. agentic_sdlc/providers/cli_claude.py +150 -0
  68. agentic_sdlc/providers/cli_codex.py +155 -0
  69. agentic_sdlc/providers/cli_copilot.py +127 -0
  70. agentic_sdlc/providers/cli_cursor.py +161 -0
  71. agentic_sdlc/providers/registry.py +268 -0
  72. agentic_sdlc/rag/__init__.py +23 -0
  73. agentic_sdlc/rag/collections.py +211 -0
  74. agentic_sdlc/rag/embeddings.py +82 -0
  75. agentic_sdlc/rag/indexers.py +241 -0
  76. agentic_sdlc/rag/retriever.py +231 -0
  77. agentic_sdlc/reporting.py +74 -0
  78. agentic_sdlc/runner/__init__.py +5 -0
  79. agentic_sdlc/runner/test_runner.py +206 -0
  80. agentic_sdlc/scaffold.py +165 -0
  81. agentic_sdlc/schemas/__init__.py +82 -0
  82. agentic_sdlc/schemas/build.py +179 -0
  83. agentic_sdlc/schemas/config.py +367 -0
  84. agentic_sdlc/schemas/enums.py +161 -0
  85. agentic_sdlc/schemas/feedback.py +86 -0
  86. agentic_sdlc/schemas/findings.py +87 -0
  87. agentic_sdlc/schemas/results.py +104 -0
  88. agentic_sdlc/schemas/state.py +270 -0
  89. agentic_sdlc/schemas/task.py +51 -0
  90. agentic_sdlc/stack/__init__.py +9 -0
  91. agentic_sdlc/stack/advisor.py +372 -0
  92. agentic_sdlc/stack/templates.py +388 -0
  93. agentic_sdlc/store/__init__.py +6 -0
  94. agentic_sdlc/store/artifacts.py +57 -0
  95. agentic_sdlc/store/journal.py +153 -0
  96. agentic_sdlc/util.py +91 -0
  97. agentic_sdlc/workflow/__init__.py +23 -0
  98. agentic_sdlc/workflow/build_node.py +162 -0
  99. agentic_sdlc/workflow/controller.py +229 -0
  100. agentic_sdlc/workflow/deploy_node.py +287 -0
  101. agentic_sdlc/workflow/github_integration.py +334 -0
  102. agentic_sdlc/workflow/graph.py +217 -0
  103. agentic_sdlc/workflow/nodes.py +1548 -0
  104. agentic_sdlc/workflow/planning_nodes.py +308 -0
  105. agentic_sdlc/workflow/router.py +134 -0
  106. agentic_sdlc/workflow/sandbox.py +418 -0
  107. agentic_sdlc/workflow/services.py +89 -0
  108. agentic_sdlc/workflow/watcher.py +122 -0
  109. agentic_sdlc_system-0.1.0.dist-info/METADATA +345 -0
  110. agentic_sdlc_system-0.1.0.dist-info/RECORD +113 -0
  111. agentic_sdlc_system-0.1.0.dist-info/WHEEL +5 -0
  112. agentic_sdlc_system-0.1.0.dist-info/entry_points.txt +2 -0
  113. agentic_sdlc_system-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,14 @@
1
+ """Agentic SDLC orchestrator.
2
+
3
+ A reusable, local-first controller that coordinates the Codex CLI and the
4
+ Claude Code CLI (through their existing subscription-authenticated runtimes)
5
+ to drive a software change from implementation through independent review,
6
+ regression testing, repair, final verification, mobile build/install, and
7
+ human acceptance on a configured phone.
8
+
9
+ The orchestrator is its own project and Git repository. It never builds itself
10
+ inside a target application's source tree; instead it creates isolated Git
11
+ worktrees per task and operates the target through configuration.
12
+ """
13
+
14
+ __version__ = "0.1.0"
@@ -0,0 +1,24 @@
1
+ """Real CLI adapters and process supervision.
2
+
3
+ Fakes for tests live in agentic_sdlc.adapters.fakes and must NEVER replace the
4
+ real adapters in a live run.
5
+ """
6
+
7
+ from .base import AgentAdapter, AgentRequest, classify_failure
8
+ from .claude import ClaudeAdapter
9
+ from .codex import CodexAdapter
10
+ from .process import EnvPolicy, ProcessResult, process_alive, process_command, run
11
+
12
+ __all__ = [
13
+ "AgentAdapter", "AgentRequest", "classify_failure",
14
+ "ClaudeAdapter", "CodexAdapter",
15
+ "EnvPolicy", "ProcessResult", "process_alive", "process_command", "run",
16
+ ]
17
+
18
+
19
+ def get_adapter(tool: str) -> AgentAdapter:
20
+ if tool == "codex":
21
+ return CodexAdapter()
22
+ if tool == "claude":
23
+ return ClaudeAdapter()
24
+ raise ValueError(f"unknown tool: {tool!r}")
@@ -0,0 +1,209 @@
1
+ """Shared adapter interface for the Codex and Claude Code CLIs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from dataclasses import dataclass, field
8
+ from typing import Any, Dict, List, Optional, Tuple
9
+
10
+ from ..schemas.enums import AgentRole
11
+ from ..schemas.results import AgentInvocationResult
12
+ from ..store.artifacts import ArtifactStore
13
+ from ..util import bound_text
14
+ from .process import EnvPolicy, run
15
+
16
+
17
+ @dataclass
18
+ class AgentRequest:
19
+ """One worker invocation request."""
20
+
21
+ role: str # developer|reviewer|qa
22
+ prompt: str # full task/instruction text (passed via stdin)
23
+ model: str
24
+ effort: str = "high"
25
+ cwd: Optional[str] = None
26
+ add_dirs: List[str] = field(default_factory=list)
27
+ timeout_seconds: int = 1800
28
+ # JSON schema the final structured output must satisfy (required when set).
29
+ output_schema: Optional[Dict[str, Any]] = None
30
+ require_structured: bool = False
31
+ # Resume a prior worker session by id (exact id; never "most recent").
32
+ resume_session_id: Optional[str] = None
33
+ session_id: Optional[str] = None # explicit new session id to assign
34
+ read_only: bool = False # reviewer: must not modify the checkout
35
+ system_prompt: Optional[str] = None
36
+ extra_args: List[str] = field(default_factory=list)
37
+ env_policy: EnvPolicy = field(default_factory=EnvPolicy)
38
+
39
+
40
+ class AgentAdapter:
41
+ """Base class. Subclasses build argv and parse the CLI's output envelope."""
42
+
43
+ tool_name = "base"
44
+
45
+ def __init__(self, binary: str, sandbox=None) -> None:
46
+ self.binary = binary
47
+ self._sandbox = sandbox
48
+
49
+ # --- to implement in subclasses ---
50
+
51
+ def build_argv(self, req: AgentRequest, schema_path: Optional[str]) -> List[str]:
52
+ raise NotImplementedError
53
+
54
+ def parse(
55
+ self, req: AgentRequest, stdout: str, stderr: str, exit_code: Optional[int]
56
+ ) -> Tuple[bool, Optional[str], Optional[str], Optional[str], bool, Optional[str]]:
57
+ """Return (ok, failure_kind, final_message, resolved_model,
58
+ structured_valid, session_id)."""
59
+ raise NotImplementedError
60
+
61
+ def extract_structured(self, final_message: Optional[str]) -> Optional[dict]:
62
+ """Best-effort parse of the final message as the structured output."""
63
+ if not final_message:
64
+ return None
65
+ text = final_message.strip()
66
+ # Strip code fences if present.
67
+ if text.startswith("```"):
68
+ text = text.strip("`")
69
+ if "\n" in text:
70
+ text = text.split("\n", 1)[1]
71
+ try:
72
+ return json.loads(text)
73
+ except json.JSONDecodeError:
74
+ # Try to locate the first/last brace.
75
+ start = text.find("{")
76
+ end = text.rfind("}")
77
+ if start != -1 and end != -1 and end > start:
78
+ try:
79
+ return json.loads(text[start : end + 1])
80
+ except json.JSONDecodeError:
81
+ return None
82
+ return None
83
+
84
+ # --- shared invocation path ---
85
+
86
+ def invoke(
87
+ self, req: AgentRequest, store: ArtifactStore, phase: str
88
+ ) -> Tuple[AgentInvocationResult, Optional[dict]]:
89
+ schema_path = None
90
+ if req.output_schema is not None:
91
+ schema_path = os.path.join(store.artifacts_dir, f"{req.role}-{phase}-schema.json")
92
+ with open(schema_path, "w", encoding="utf-8") as fh:
93
+ json.dump(req.output_schema, fh)
94
+
95
+ # Apply sandbox CLI enforcement when configured.
96
+ self._apply_sandbox(req)
97
+
98
+ # Pre-execution snapshot for post-exec verification.
99
+ pre_snapshot = None
100
+ verifier = None
101
+ if self._sandbox and req.cwd:
102
+ from ..workflow.sandbox import PostExecVerifier
103
+ verifier = PostExecVerifier(req.cwd)
104
+ pre_snapshot = verifier.snapshot()
105
+
106
+ argv = self.build_argv(req, schema_path)
107
+ env = req.env_policy.build()
108
+ proc = run(
109
+ argv,
110
+ cwd=req.cwd,
111
+ env=env,
112
+ stdin_text=req.prompt,
113
+ timeout_seconds=req.timeout_seconds,
114
+ )
115
+
116
+ # Persist full logs as artifacts (redacted).
117
+ log = store.write_text(
118
+ f"{req.role}-{phase}-{self.tool_name}.log",
119
+ f"$ {' '.join(argv)}\n\n=== STDOUT ===\n{proc.stdout}\n\n=== STDERR ===\n{proc.stderr}",
120
+ kind="log",
121
+ label=f"{req.role} {self.tool_name} invocation",
122
+ phase=phase,
123
+ )
124
+
125
+ if proc.timed_out:
126
+ result = AgentInvocationResult(
127
+ role=req.role, tool=self.tool_name,
128
+ requested_model=req.model, requested_effort=req.effort,
129
+ ok=False, exit_code=proc.exit_code, timed_out=True,
130
+ failure_kind="timeout", log_artifact=log.path,
131
+ error_message=f"Worker exceeded {req.timeout_seconds}s and was terminated.",
132
+ )
133
+ return result, None
134
+
135
+ ok, failure_kind, final_message, resolved_model, structured_valid, session_id = self.parse(
136
+ req, proc.stdout, proc.stderr, proc.exit_code
137
+ )
138
+
139
+ structured = None
140
+ if ok and req.output_schema is not None:
141
+ structured = self.extract_structured(final_message)
142
+ if req.require_structured and structured is None:
143
+ ok = False
144
+ failure_kind = "schema"
145
+ structured_valid = False
146
+
147
+ result = AgentInvocationResult(
148
+ role=req.role, tool=self.tool_name,
149
+ requested_model=req.model, requested_effort=req.effort,
150
+ resolved_model=resolved_model,
151
+ resolved_model_available=(failure_kind != "unsupported_model"),
152
+ ok=ok, exit_code=proc.exit_code, timed_out=False,
153
+ failure_kind=failure_kind,
154
+ final_message=bound_text(final_message or ""),
155
+ session_id=session_id or req.session_id,
156
+ structured_output_valid=structured_valid,
157
+ log_artifact=log.path,
158
+ error_message=None if ok else (failure_kind or "worker failed"),
159
+ )
160
+
161
+ # Post-execution verification: detect unauthorized file changes.
162
+ if verifier and pre_snapshot is not None and result.ok:
163
+ role_enum = self._resolve_role(req.role)
164
+ if role_enum is not None:
165
+ vr = verifier.verify(role_enum, pre_snapshot)
166
+ if not vr.ok:
167
+ result.ok = False
168
+ result.failure_kind = "sandbox_violation"
169
+ result.error_message = vr.message
170
+
171
+ return result, structured
172
+
173
+
174
+ def _resolve_role(self, role_str: str) -> Optional[AgentRole]:
175
+ """Map a role string to an AgentRole enum, or None if unrecognized."""
176
+ try:
177
+ return AgentRole(role_str)
178
+ except ValueError:
179
+ return None
180
+
181
+ def _apply_sandbox(self, req: AgentRequest) -> None:
182
+ """Apply sandbox CLI enforcement to the request if sandbox is configured."""
183
+ if not self._sandbox:
184
+ return
185
+ role = self._resolve_role(req.role)
186
+ if role is None:
187
+ return
188
+ enforcement = self._sandbox.cli_flags(role, adapter=self.tool_name)
189
+ req.read_only = enforcement.read_only
190
+ req.extra_args = enforcement.extra_args + req.extra_args
191
+
192
+
193
+ def classify_failure(stderr: str, exit_code: Optional[int]) -> str:
194
+ """Heuristically classify a worker failure from stderr/exit."""
195
+ s = (stderr or "").lower()
196
+ if any(k in s for k in ("not authenticated", "unauthorized", "please log in", "login required", "auth")):
197
+ if "quota" not in s and "rate limit" not in s:
198
+ return "auth"
199
+ if any(k in s for k in ("quota", "rate limit", "usage limit", "insufficient_quota", "429")):
200
+ return "quota"
201
+ if any(k in s for k in ("permission denied", "not permitted", "forbidden")):
202
+ return "permission"
203
+ if any(k in s for k in ("unknown model", "unsupported model", "model not found", "invalid model")):
204
+ return "unsupported_model"
205
+ if any(k in s for k in ("interrupted", "sigint", "cancelled")):
206
+ return "interrupted"
207
+ if exit_code not in (0, None):
208
+ return "process"
209
+ return "unknown"
@@ -0,0 +1,122 @@
1
+ """Claude Code CLI adapter.
2
+
3
+ Non-interactive invocation with:
4
+ claude -p --output-format json --model <model> --effort <effort>
5
+ [--json-schema <file>] [--add-dir ...] [--allowedTools/--disallowedTools]
6
+ [--session-id <uuid> | --resume <id>] --permission-mode <mode>
7
+ Prompt text is piped via stdin. The JSON envelope is parsed for is_error /
8
+ result / session_id / model. Reviewer sessions run read-only (no edit tools)
9
+ and the controller independently verifies the checkout is unchanged.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import uuid
16
+ from typing import List, Optional, Tuple
17
+
18
+ from .base import AgentAdapter, AgentRequest, classify_failure
19
+
20
+
21
+ class ClaudeAdapter(AgentAdapter):
22
+ tool_name = "claude"
23
+
24
+ def __init__(self, binary: str = "claude", sandbox=None) -> None:
25
+ super().__init__(binary, sandbox=sandbox)
26
+
27
+ def build_argv(self, req: AgentRequest, schema_path: Optional[str]) -> List[str]:
28
+ argv = [
29
+ self.binary,
30
+ "-p",
31
+ "--output-format", "json",
32
+ "--model", req.model,
33
+ "--effort", req.effort,
34
+ ]
35
+ if req.system_prompt:
36
+ argv += ["--append-system-prompt", req.system_prompt]
37
+ for d in req.add_dirs:
38
+ argv += ["--add-dir", d]
39
+
40
+ if req.read_only:
41
+ # Reviewer: allow only read/search tools; deny all mutation.
42
+ argv += [
43
+ "--allowedTools", "Read", "Grep", "Glob",
44
+ "--disallowedTools", "Edit", "Write", "NotebookEdit", "Bash",
45
+ "--permission-mode", "plan",
46
+ ]
47
+ else:
48
+ # QA / test author: may edit test files and run tests.
49
+ argv += ["--permission-mode", "acceptEdits"]
50
+
51
+ if schema_path:
52
+ import json as _json
53
+ with open(schema_path, "r", encoding="utf-8") as _fh:
54
+ schema_text = _fh.read().strip()
55
+ argv += ["--json-schema", schema_text]
56
+
57
+ if req.resume_session_id:
58
+ argv += ["--resume", req.resume_session_id]
59
+ else:
60
+ sid = req.session_id or str(uuid.uuid4())
61
+ req.session_id = sid
62
+ argv += ["--session-id", sid]
63
+
64
+ argv += req.extra_args
65
+ return argv
66
+
67
+ def parse(
68
+ self, req: AgentRequest, stdout: str, stderr: str, exit_code: Optional[int]
69
+ ) -> Tuple[bool, Optional[str], Optional[str], Optional[str], bool, Optional[str]]:
70
+ resolved_model: Optional[str] = None
71
+ session_id: Optional[str] = req.session_id
72
+ final_message: Optional[str] = None
73
+
74
+ envelope = None
75
+ text = (stdout or "").strip()
76
+ if text:
77
+ try:
78
+ envelope = json.loads(text)
79
+ except json.JSONDecodeError:
80
+ # Could be stream-json lines; take the last JSON object.
81
+ for line in reversed(text.splitlines()):
82
+ line = line.strip()
83
+ if line.startswith("{"):
84
+ try:
85
+ envelope = json.loads(line)
86
+ break
87
+ except json.JSONDecodeError:
88
+ continue
89
+
90
+ if isinstance(envelope, dict):
91
+ resolved_model = (
92
+ envelope.get("model")
93
+ or (envelope.get("usage") or {}).get("model")
94
+ or resolved_model
95
+ )
96
+ session_id = envelope.get("session_id") or session_id
97
+ is_error = bool(envelope.get("is_error")) or envelope.get("subtype") not in (
98
+ None, "success",
99
+ )
100
+ # Prefer validated structured output, else the result text.
101
+ if "structured_output" in envelope and envelope["structured_output"] is not None:
102
+ so = envelope["structured_output"]
103
+ final_message = so if isinstance(so, str) else json.dumps(so)
104
+ else:
105
+ res = envelope.get("result")
106
+ final_message = res if isinstance(res, str) else (
107
+ json.dumps(res) if res is not None else None
108
+ )
109
+
110
+ if exit_code not in (0, None):
111
+ kind = classify_failure(stderr + "\n" + text, exit_code)
112
+ return False, kind, final_message, resolved_model, False, session_id
113
+ if is_error:
114
+ kind = classify_failure((final_message or "") + "\n" + stderr, exit_code)
115
+ kind = kind if kind != "unknown" else "envelope_error"
116
+ return False, kind, final_message, resolved_model, False, session_id
117
+ return True, None, final_message, resolved_model, True, session_id
118
+
119
+ # No parseable envelope.
120
+ if exit_code not in (0, None):
121
+ return False, classify_failure(stderr, exit_code), None, resolved_model, False, session_id
122
+ return False, "envelope_error", None, resolved_model, False, session_id
@@ -0,0 +1,116 @@
1
+ """Codex CLI adapter (`codex exec`).
2
+
3
+ Non-interactive invocation with:
4
+ codex exec -m <model> -c model_reasoning_effort=<effort> -C <cwd>
5
+ --skip-git-repo-check --json -o <lastmsg> [--output-schema <file>]
6
+ Prompt text is piped via stdin. The final message is read from the
7
+ --output-last-message file; --json gives the JSONL event stream for the log
8
+ and for extracting the resolved model.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ from typing import List, Optional, Tuple
16
+
17
+ from .base import AgentAdapter, AgentRequest, classify_failure
18
+
19
+
20
+ class CodexAdapter(AgentAdapter):
21
+ tool_name = "codex"
22
+
23
+ def __init__(self, binary: str = "codex", sandbox=None) -> None:
24
+ super().__init__(binary, sandbox=sandbox)
25
+ self._last_message_path: Optional[str] = None
26
+
27
+ def build_argv(self, req: AgentRequest, schema_path: Optional[str]) -> List[str]:
28
+ # Write the final message to a dedicated file so parsing is robust.
29
+ self._last_message_path = os.path.join(
30
+ os.path.dirname(schema_path) if schema_path else ".",
31
+ f"{req.role}-codex-last.txt",
32
+ )
33
+ argv = [
34
+ self.binary, "exec",
35
+ "-m", req.model,
36
+ "-c", f"model_reasoning_effort={json.dumps(req.effort)}",
37
+ "--skip-git-repo-check",
38
+ "--json",
39
+ "-o", self._last_message_path,
40
+ ]
41
+ if req.cwd:
42
+ argv += ["-C", req.cwd]
43
+ for d in req.add_dirs:
44
+ argv += ["--add-dir", d]
45
+
46
+ # Sandbox / approval policy by role.
47
+ if req.read_only:
48
+ argv += ["-s", "read-only"]
49
+ else:
50
+ # --approve-for-me implies workspace-write sandbox; passing both
51
+ # is rejected by codex >=0.167.
52
+ argv += ["--approve-for-me"]
53
+
54
+ if schema_path:
55
+ argv += ["--output-schema", schema_path]
56
+ argv += req.extra_args
57
+ # Prompt is read from stdin.
58
+ argv += ["-"]
59
+ return argv
60
+
61
+ def _read_last_message(self) -> Optional[str]:
62
+ if self._last_message_path and os.path.exists(self._last_message_path):
63
+ try:
64
+ with open(self._last_message_path, "r", encoding="utf-8") as fh:
65
+ return fh.read()
66
+ except OSError:
67
+ return None
68
+ return None
69
+
70
+ def parse(
71
+ self, req: AgentRequest, stdout: str, stderr: str, exit_code: Optional[int]
72
+ ) -> Tuple[bool, Optional[str], Optional[str], Optional[str], bool, Optional[str]]:
73
+ resolved_model: Optional[str] = None
74
+ session_id: Optional[str] = None
75
+ envelope_error: Optional[str] = None
76
+
77
+ # Parse JSONL events for model / session / errors.
78
+ for line in (stdout or "").splitlines():
79
+ line = line.strip()
80
+ if not line or not line.startswith("{"):
81
+ continue
82
+ try:
83
+ evt = json.loads(line)
84
+ except json.JSONDecodeError:
85
+ continue
86
+ # Model id may appear on a session/config/turn event.
87
+ for key in ("model", "model_id"):
88
+ if isinstance(evt.get(key), str):
89
+ resolved_model = evt[key]
90
+ msg = evt.get("msg") if isinstance(evt.get("msg"), dict) else evt
91
+ if isinstance(msg, dict):
92
+ for key in ("model", "model_id"):
93
+ if isinstance(msg.get(key), str):
94
+ resolved_model = msg[key]
95
+ for key in ("session_id", "thread_id"):
96
+ if session_id is None and isinstance(msg.get(key), str):
97
+ session_id = msg.get(key)
98
+ etype = str(evt.get("type") or msg.get("type") or "")
99
+ if "error" in etype.lower():
100
+ envelope_error = json.dumps(msg)[:500]
101
+
102
+ final_message = self._read_last_message()
103
+
104
+ if exit_code not in (0, None):
105
+ kind = classify_failure(stderr + "\n" + (envelope_error or ""), exit_code)
106
+ return False, kind, final_message, resolved_model, False, session_id
107
+
108
+ if envelope_error:
109
+ kind = classify_failure(envelope_error, exit_code)
110
+ kind = kind if kind != "unknown" else "envelope_error"
111
+ return False, kind, final_message, resolved_model, False, session_id
112
+
113
+ if final_message is None and req.require_structured:
114
+ return False, "schema", None, resolved_model, False, session_id
115
+
116
+ return True, None, final_message, resolved_model, True, session_id
@@ -0,0 +1,188 @@
1
+ """Subprocess supervision.
2
+
3
+ - Commands run in their own process group (start_new_session) so a timeout or
4
+ cancellation stops the worker and all its children, never unrelated user
5
+ processes.
6
+ - Worker arguments are passed as an argument list (no shell interpolation).
7
+ Trusted, user-approved project commands may run through the shell via
8
+ run_shell(); untrusted input is never shelled.
9
+ - Output is captured in full to an artifact and bounded in memory.
10
+ - The worker env is controlled so unrelated API-key settings do not change the
11
+ billing route of subscription-authenticated CLIs.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import signal
18
+ import subprocess
19
+ import threading
20
+ import time
21
+ from dataclasses import dataclass, field
22
+ from typing import Dict, List, Optional
23
+
24
+
25
+ @dataclass
26
+ class ProcessResult:
27
+ argv: List[str]
28
+ exit_code: Optional[int]
29
+ stdout: str
30
+ stderr: str
31
+ timed_out: bool
32
+ duration_seconds: float
33
+ pid: Optional[int] = None
34
+ pgid: Optional[int] = None
35
+ cancelled: bool = False
36
+
37
+
38
+ @dataclass
39
+ class EnvPolicy:
40
+ """Controls the environment handed to a worker process."""
41
+
42
+ # Keys stripped from the inherited env (force subscription auth routes).
43
+ strip_keys: List[str] = field(
44
+ default_factory=lambda: [
45
+ "ANTHROPIC_API_KEY",
46
+ "ANTHROPIC_AUTH_TOKEN",
47
+ "OPENAI_API_KEY",
48
+ "OPENAI_BASE_URL",
49
+ "CLAUDE_CODE_USE_BEDROCK",
50
+ "CLAUDE_CODE_USE_VERTEX",
51
+ ]
52
+ )
53
+ # Extra keys explicitly set for the worker.
54
+ set_vars: Dict[str, str] = field(default_factory=dict)
55
+ # If False, strip_keys is ignored (inherit everything).
56
+ enforce: bool = True
57
+
58
+ def build(self, base: Optional[Dict[str, str]] = None) -> Dict[str, str]:
59
+ env = dict(base if base is not None else os.environ)
60
+ if self.enforce:
61
+ for k in self.strip_keys:
62
+ env.pop(k, None)
63
+ env.update(self.set_vars)
64
+ return env
65
+
66
+
67
+ def _kill_group(pgid: int, sig: int) -> None:
68
+ try:
69
+ os.killpg(pgid, sig)
70
+ except (ProcessLookupError, PermissionError):
71
+ pass
72
+
73
+
74
+ def run(
75
+ argv: List[str],
76
+ *,
77
+ cwd: Optional[str] = None,
78
+ env: Optional[Dict[str, str]] = None,
79
+ stdin_text: Optional[str] = None,
80
+ timeout_seconds: Optional[float] = None,
81
+ kill_grace_seconds: float = 5.0,
82
+ shell: bool = False,
83
+ ) -> ProcessResult:
84
+ """Run a command in its own process group with a bounded timeout.
85
+
86
+ argv is a list for direct exec. When shell=True, argv must be a single-item
87
+ list holding a trusted shell command string (used ONLY for user-approved
88
+ project commands).
89
+ """
90
+ start = time.monotonic()
91
+ popen_kwargs = dict(
92
+ cwd=cwd,
93
+ env=env,
94
+ stdin=subprocess.PIPE if stdin_text is not None else subprocess.DEVNULL,
95
+ stdout=subprocess.PIPE,
96
+ stderr=subprocess.PIPE,
97
+ start_new_session=True, # new process group => os.setsid
98
+ )
99
+ try:
100
+ if shell:
101
+ if len(argv) != 1:
102
+ raise ValueError("shell=True requires a single command string in argv")
103
+ proc = subprocess.Popen(argv[0], shell=True, **popen_kwargs) # noqa: S602 (trusted)
104
+ else:
105
+ proc = subprocess.Popen(argv, **popen_kwargs)
106
+ except (FileNotFoundError, PermissionError) as exc:
107
+ # Missing/again not-executable binary: return a failed result rather
108
+ # than raising, so optional-tool probes degrade gracefully.
109
+ return ProcessResult(
110
+ argv=(argv if not shell else ["sh", "-c", argv[0]]),
111
+ exit_code=127, stdout="", stderr=f"{type(exc).__name__}: {exc}",
112
+ timed_out=False, duration_seconds=time.monotonic() - start,
113
+ )
114
+
115
+ pgid = None
116
+ try:
117
+ pgid = os.getpgid(proc.pid)
118
+ except ProcessLookupError:
119
+ pass
120
+
121
+ out_buf: Dict[str, bytes] = {}
122
+ timed_out = False
123
+
124
+ def _communicate() -> None:
125
+ try:
126
+ o, e = proc.communicate(
127
+ input=stdin_text.encode("utf-8") if stdin_text is not None else None
128
+ )
129
+ out_buf["out"] = o or b""
130
+ out_buf["err"] = e or b""
131
+ except Exception as exc: # pragma: no cover - defensive
132
+ out_buf["out"] = out_buf.get("out", b"")
133
+ out_buf["err"] = out_buf.get("err", b"") + str(exc).encode()
134
+
135
+ thread = threading.Thread(target=_communicate, daemon=True)
136
+ thread.start()
137
+ thread.join(timeout_seconds)
138
+
139
+ if thread.is_alive():
140
+ # Timed out: stop the whole group.
141
+ timed_out = True
142
+ if pgid is not None:
143
+ _kill_group(pgid, signal.SIGTERM)
144
+ else:
145
+ proc.terminate()
146
+ thread.join(kill_grace_seconds)
147
+ if thread.is_alive():
148
+ if pgid is not None:
149
+ _kill_group(pgid, signal.SIGKILL)
150
+ else:
151
+ proc.kill()
152
+ thread.join(kill_grace_seconds)
153
+
154
+ duration = time.monotonic() - start
155
+ exit_code = proc.poll()
156
+ stdout = out_buf.get("out", b"").decode("utf-8", "replace")
157
+ stderr = out_buf.get("err", b"").decode("utf-8", "replace")
158
+ return ProcessResult(
159
+ argv=(argv if not shell else ["sh", "-c", argv[0]]),
160
+ exit_code=exit_code,
161
+ stdout=stdout,
162
+ stderr=stderr,
163
+ timed_out=timed_out,
164
+ duration_seconds=duration,
165
+ pid=proc.pid,
166
+ pgid=pgid,
167
+ )
168
+
169
+
170
+ def process_alive(pid: int) -> bool:
171
+ try:
172
+ os.kill(pid, 0)
173
+ return True
174
+ except ProcessLookupError:
175
+ return False
176
+ except PermissionError:
177
+ return True
178
+
179
+
180
+ def process_command(pid: int) -> Optional[str]:
181
+ """Best-effort read of a pid's command line, for identity verification
182
+ before terminating a leftover worker on resume."""
183
+ try:
184
+ with open(f"/proc/{pid}/cmdline", "rb") as fh:
185
+ raw = fh.read()
186
+ return raw.replace(b"\x00", b" ").decode("utf-8", "replace").strip()
187
+ except (FileNotFoundError, ProcessLookupError, PermissionError):
188
+ return None
@@ -0,0 +1,6 @@
1
+ """Agent role definitions and prompt building."""
2
+
3
+ from .roles import ROLE_REGISTRY, RoleDef, get_role
4
+ from .prompts import PromptBuilder
5
+
6
+ __all__ = ["ROLE_REGISTRY", "RoleDef", "get_role", "PromptBuilder"]