crew-agentic 0.9.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 (86) hide show
  1. crew/__init__.py +3 -0
  2. crew/__main__.py +5 -0
  3. crew/agents/__init__.py +0 -0
  4. crew/agents/contracts.py +135 -0
  5. crew/agents/payloads.py +297 -0
  6. crew/agents/permission_server.py +201 -0
  7. crew/agents/prompts/director.md +17 -0
  8. crew/agents/prompts/evaluator.md +11 -0
  9. crew/agents/prompts/implementer.md +16 -0
  10. crew/agents/prompts/reviewer.md +14 -0
  11. crew/agents/prompts/shared.md +10 -0
  12. crew/agents/runtime.py +205 -0
  13. crew/application/__init__.py +0 -0
  14. crew/application/doctor.py +304 -0
  15. crew/application/integrations.py +87 -0
  16. crew/application/project.py +270 -0
  17. crew/cli/__init__.py +0 -0
  18. crew/cli/app.py +784 -0
  19. crew/config/__init__.py +0 -0
  20. crew/config/detect.py +134 -0
  21. crew/config/loader.py +94 -0
  22. crew/config/schema.py +244 -0
  23. crew/context/__init__.py +0 -0
  24. crew/context/collector.py +104 -0
  25. crew/domain/__init__.py +0 -0
  26. crew/domain/enums.py +120 -0
  27. crew/domain/errors.py +77 -0
  28. crew/domain/task_graph.py +131 -0
  29. crew/integrations/__init__.py +7 -0
  30. crew/integrations/adf.py +116 -0
  31. crew/integrations/base.py +109 -0
  32. crew/integrations/docs.py +107 -0
  33. crew/integrations/factory.py +50 -0
  34. crew/integrations/github.py +102 -0
  35. crew/integrations/gitlab.py +108 -0
  36. crew/integrations/http.py +100 -0
  37. crew/integrations/jira.py +80 -0
  38. crew/integrations/markup.py +135 -0
  39. crew/orchestrator/__init__.py +0 -0
  40. crew/orchestrator/engine.py +693 -0
  41. crew/orchestrator/host.py +60 -0
  42. crew/orchestrator/implementation.py +306 -0
  43. crew/orchestrator/integration.py +227 -0
  44. crew/orchestrator/lock.py +42 -0
  45. crew/orchestrator/permissions.py +89 -0
  46. crew/orchestrator/recovery.py +107 -0
  47. crew/orchestrator/review.py +235 -0
  48. crew/orchestrator/state_machine.py +75 -0
  49. crew/orchestrator/support.py +97 -0
  50. crew/persistence/__init__.py +0 -0
  51. crew/persistence/database.py +66 -0
  52. crew/persistence/migrations/env.py +41 -0
  53. crew/persistence/migrations/script.py.mako +25 -0
  54. crew/persistence/migrations/versions/0001_initial_schema.py +211 -0
  55. crew/persistence/migrations/versions/0002_process_started_at.py +26 -0
  56. crew/persistence/migrations/versions/0003_failed_state.py +26 -0
  57. crew/persistence/migrations/versions/0004_command_sandbox.py +26 -0
  58. crew/persistence/migrations/versions/0005_execution_usage.py +30 -0
  59. crew/persistence/migrations/versions/0006_run_links.py +28 -0
  60. crew/persistence/models.py +223 -0
  61. crew/persistence/store.py +403 -0
  62. crew/providers/__init__.py +0 -0
  63. crew/providers/base.py +71 -0
  64. crew/providers/claude_code/__init__.py +0 -0
  65. crew/providers/claude_code/adapter.py +344 -0
  66. crew/providers/claude_code/parser.py +186 -0
  67. crew/providers/fake.py +127 -0
  68. crew/reporting/__init__.py +0 -0
  69. crew/reporting/renderer.py +375 -0
  70. crew/security/__init__.py +0 -0
  71. crew/security/execution_policy.py +319 -0
  72. crew/security/redaction.py +83 -0
  73. crew/security/sandbox.py +163 -0
  74. crew/security/secret_files.py +70 -0
  75. crew/system/__init__.py +5 -0
  76. crew/system/locking.py +66 -0
  77. crew/system/processes.py +132 -0
  78. crew/system/winjob.py +145 -0
  79. crew/workspace/__init__.py +0 -0
  80. crew/workspace/git.py +377 -0
  81. crew/workspace/worktrees.py +143 -0
  82. crew_agentic-0.9.0.dist-info/METADATA +187 -0
  83. crew_agentic-0.9.0.dist-info/RECORD +86 -0
  84. crew_agentic-0.9.0.dist-info/WHEEL +4 -0
  85. crew_agentic-0.9.0.dist-info/entry_points.txt +2 -0
  86. crew_agentic-0.9.0.dist-info/licenses/LICENSE +21 -0
crew/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """CREW — local-first AI development orchestration CLI."""
2
+
3
+ __version__ = "0.9.0"
crew/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Allow ``python -m crew``."""
2
+
3
+ from crew.cli.app import main
4
+
5
+ main()
File without changes
@@ -0,0 +1,135 @@
1
+ """Structured output contracts for each agent role (docs/AGENT_ROLES.md).
2
+
3
+ Provider output is untrusted: it is validated against these models before CREW
4
+ acts on it. The JSON Schema of each model is also handed to the provider so it
5
+ can constrain generation (Claude Code ``--json-schema``).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Literal
11
+
12
+ from pydantic import BaseModel, ConfigDict, Field
13
+
14
+ from crew.domain.enums import FindingCategory, Recommendation, Role, Severity
15
+
16
+
17
+ class _Contract(BaseModel):
18
+ model_config = ConfigDict(extra="ignore", str_strip_whitespace=True)
19
+
20
+
21
+ # ---- Director ---------------------------------------------------------------
22
+
23
+
24
+ class PlannedTask(_Contract):
25
+ id: str = Field(description="Short lowercase ref-safe id, e.g. 'add-health-endpoint'")
26
+ title: str = Field(min_length=3, max_length=200)
27
+ description: str = Field(min_length=10)
28
+ rationale: str = ""
29
+ dependencies: list[str] = Field(default_factory=list, description="ids of prerequisite tasks")
30
+ acceptance_criteria: list[str] = Field(min_length=1)
31
+ expected_files: list[str] = Field(default_factory=list)
32
+
33
+
34
+ class DirectorPlan(_Contract):
35
+ understanding: str = Field(min_length=10, description="Requested outcome in your own words")
36
+ assumptions: list[str] = Field(default_factory=list)
37
+ open_questions: list[str] = Field(default_factory=list)
38
+ approach: str = Field(min_length=10, description="Architecture / design approach")
39
+ scope: list[str] = Field(default_factory=list)
40
+ non_goals: list[str] = Field(default_factory=list)
41
+ tasks: list[PlannedTask] = Field(min_length=1, max_length=12)
42
+ risks: list[str] = Field(default_factory=list)
43
+ verification_strategy: str = ""
44
+ project_notes: list[str] = Field(
45
+ default_factory=list,
46
+ description="Facts every Implementer needs and would otherwise rediscover: exact "
47
+ "build/test commands, layout, conventions, files to imitate",
48
+ )
49
+ blocking_ambiguity: str | None = Field(
50
+ default=None,
51
+ description="Set only if the request is too ambiguous to plan safely; explain why.",
52
+ )
53
+
54
+
55
+ # ---- Implementer ------------------------------------------------------------
56
+
57
+
58
+ class VerificationRecord(_Contract):
59
+ command: str
60
+ exit_code: int | None = None
61
+ summary: str = Field(description="What you observed. Never claim a run you did not perform.")
62
+
63
+
64
+ class ImplementationReport(_Contract):
65
+ summary: str = Field(min_length=5)
66
+ changed_files: list[str] = Field(default_factory=list)
67
+ tests_changed: list[str] = Field(default_factory=list)
68
+ verification: list[VerificationRecord] = Field(default_factory=list)
69
+ limitations: list[str] = Field(default_factory=list)
70
+ scope_notes: str = Field(default="", description="Why scope changed, if it did")
71
+
72
+
73
+ # ---- Reviewer ---------------------------------------------------------------
74
+
75
+
76
+ class Finding(_Contract):
77
+ severity: Severity
78
+ category: FindingCategory
79
+ title: str = Field(min_length=3)
80
+ file: str | None = None
81
+ line_start: int | None = Field(default=None, ge=1)
82
+ line_end: int | None = Field(default=None, ge=1)
83
+ explanation: str = Field(min_length=5)
84
+ evidence: str = ""
85
+ recommendation: str = ""
86
+ blocking: bool
87
+
88
+ @property
89
+ def location(self) -> str:
90
+ if not self.file:
91
+ return "-"
92
+ if self.line_start and self.line_end and self.line_end != self.line_start:
93
+ return f"{self.file}:{self.line_start}-{self.line_end}"
94
+ if self.line_start:
95
+ return f"{self.file}:{self.line_start}"
96
+ return self.file
97
+
98
+
99
+ class ReviewReport(_Contract):
100
+ assessment: str = Field(min_length=5)
101
+ findings: list[Finding] = Field(default_factory=list)
102
+ checks_run: list[str] = Field(default_factory=list)
103
+
104
+ @property
105
+ def blocking_findings(self) -> list[Finding]:
106
+ return [f for f in self.findings if f.blocking]
107
+
108
+
109
+ # ---- External Evaluator -----------------------------------------------------
110
+
111
+
112
+ class RequirementAssessment(_Contract):
113
+ requirement: str
114
+ status: Literal["met", "partially_met", "not_met", "unverifiable"]
115
+ evidence: str = ""
116
+
117
+
118
+ class EvaluationReport(_Contract):
119
+ recommendation: Recommendation
120
+ requirements: list[RequirementAssessment] = Field(min_length=1)
121
+ unresolved_risks: list[str] = Field(default_factory=list)
122
+ discrepancies: list[str] = Field(default_factory=list)
123
+ explanation: str = Field(min_length=5)
124
+
125
+
126
+ CONTRACTS: dict[Role, type[_Contract]] = {
127
+ Role.DIRECTOR: DirectorPlan,
128
+ Role.IMPLEMENTER: ImplementationReport,
129
+ Role.REVIEWER: ReviewReport,
130
+ Role.EVALUATOR: EvaluationReport,
131
+ }
132
+
133
+
134
+ def output_schema(role: Role) -> dict:
135
+ return CONTRACTS[role].model_json_schema()
@@ -0,0 +1,297 @@
1
+ """Builders for the per-role input payloads (the user prompt sent to an agent).
2
+
3
+ Payloads are Markdown with clearly labelled sections so agents can tell the
4
+ original request, approved plan, CREW-recorded evidence and other agents'
5
+ *claims* apart.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from typing import Any
12
+
13
+ from crew.persistence.models import CommandExecution, Run, Task
14
+
15
+ DIFF_MAX_CHARS = 120_000
16
+
17
+
18
+ def _json(value: Any) -> str:
19
+ return json.dumps(value, indent=2, ensure_ascii=False)
20
+
21
+
22
+ def _truncate(text: str, limit: int) -> str:
23
+ return (
24
+ text if len(text) <= limit else text[:limit] + "\n…[diff truncated; inspect files directly]"
25
+ )
26
+
27
+
28
+ SUMMARY_PATCH_CHARS = 12_000
29
+
30
+
31
+ def diff_section(base: str, patch: str, stat: str, files: list[str], *, mode: str = "full") -> str:
32
+ """The integrated change as given to Reviewer and Evaluator.
33
+
34
+ ``full`` embeds the whole patch (bounded by DIFF_MAX_CHARS). ``summary`` gives
35
+ stats, the changed-file list and only the start of the patch, and tells the
36
+ agent to open files itself: far fewer prompt tokens on large changes.
37
+ """
38
+ header = f"# Integrated change (base {base[:12]} → integration branch)"
39
+ if mode == "full":
40
+ return "\n".join([header, "", "```diff", _truncate(patch, DIFF_MAX_CHARS), "```"])
41
+ head = patch[:SUMMARY_PATCH_CHARS]
42
+ more = len(patch) > SUMMARY_PATCH_CHARS
43
+ return "\n".join(
44
+ [
45
+ header,
46
+ "",
47
+ "Your working directory contains the integrated result. The patch below is",
48
+ "abridged; open the changed files with your Read tool to inspect them.",
49
+ "",
50
+ "## Diff stat",
51
+ "",
52
+ "```",
53
+ stat.strip(),
54
+ "```",
55
+ "",
56
+ "## Changed files",
57
+ "",
58
+ *[f"- {f}" for f in files],
59
+ "",
60
+ "## Patch (beginning)" + (" — truncated" if more else ""),
61
+ "",
62
+ "```diff",
63
+ head,
64
+ "```",
65
+ ]
66
+ )
67
+
68
+
69
+ def director_prompt(run: Run, context_md: str, previous_error: str | None = None) -> str:
70
+ parts = [
71
+ "# Original request",
72
+ "",
73
+ run.request,
74
+ "",
75
+ "# Repository context",
76
+ "",
77
+ context_md,
78
+ ]
79
+ if previous_error:
80
+ parts += [
81
+ "",
82
+ "# Your previous plan was rejected by CREW validation",
83
+ "",
84
+ previous_error,
85
+ "Return a corrected plan.",
86
+ ]
87
+ return "\n".join(parts)
88
+
89
+
90
+ def implementer_prompt(run: Run, task: Task, dependency_reports: dict[str, Any]) -> str:
91
+ plan = run.plan or {}
92
+ parts = [
93
+ "# Original request",
94
+ "",
95
+ run.request,
96
+ "",
97
+ "# Approved approach",
98
+ "",
99
+ str(plan.get("approach", "")),
100
+ "",
101
+ *(
102
+ ["# Project notes from the Director", "", *[f"- {n}" for n in notes], ""]
103
+ if (notes := plan.get("project_notes"))
104
+ else []
105
+ ),
106
+ f"# Your task: {task.key} — {task.title}",
107
+ "",
108
+ task.description,
109
+ "",
110
+ "## Acceptance criteria",
111
+ *[f"- {c}" for c in task.acceptance_criteria],
112
+ ]
113
+ if task.expected_files:
114
+ parts += ["", "## Expected areas/files", *[f"- {f}" for f in task.expected_files]]
115
+ if task.rationale:
116
+ parts += ["", "## Rationale", task.rationale]
117
+ if dependency_reports:
118
+ parts += [
119
+ "",
120
+ "## Completed dependency tasks (their changes are already in this worktree)",
121
+ "",
122
+ "```json",
123
+ _json(dependency_reports),
124
+ "```",
125
+ ]
126
+ return "\n".join(parts)
127
+
128
+
129
+ def _commands_md(commands: list[CommandExecution]) -> str:
130
+ if not commands:
131
+ return "_No verification commands are configured; no CREW-run test evidence exists._"
132
+ out = []
133
+ for c in commands:
134
+ argv = " ".join(json.loads(c.argv_json))
135
+ status = "TIMED OUT" if c.timed_out else f"exit {c.exit_code}"
136
+ if c.sandbox and c.sandbox != "none":
137
+ status += f", sandbox {c.sandbox}"
138
+ tail = (c.stdout or "")[-3000:] + ("\n" + c.stderr[-2000:] if c.stderr else "")
139
+ out += [f"### `{argv}` — {status}", "", "```", tail.strip(), "```", ""]
140
+ return "\n".join(out)
141
+
142
+
143
+ def reviewer_prompt(
144
+ run: Run,
145
+ tasks: list[Task],
146
+ diff: str,
147
+ commands: list[CommandExecution],
148
+ previous_review: dict[str, Any] | None,
149
+ ) -> str:
150
+ parts = [
151
+ "# Original request",
152
+ "",
153
+ run.request,
154
+ "",
155
+ "# Approved plan",
156
+ "",
157
+ "```json",
158
+ _json(run.plan),
159
+ "```",
160
+ "",
161
+ "# Task acceptance criteria",
162
+ ]
163
+ for t in tasks:
164
+ parts += [f"## {t.key}: {t.title}", *[f"- {c}" for c in t.acceptance_criteria]]
165
+ parts += [
166
+ "",
167
+ diff,
168
+ "",
169
+ "# Verification evidence recorded by CREW",
170
+ "",
171
+ _commands_md(commands),
172
+ ]
173
+ if previous_review:
174
+ parts += [
175
+ "",
176
+ "# Previous review cycle (check whether blocking findings were resolved)",
177
+ "",
178
+ "```json",
179
+ _json(previous_review),
180
+ "```",
181
+ ]
182
+ return "\n".join(parts)
183
+
184
+
185
+ def conflict_prompt(
186
+ run: Run, into: str, ref: str, files: list[str], reports: dict[str, Any]
187
+ ) -> str:
188
+ return "\n".join(
189
+ [
190
+ "# Resolve a merge conflict",
191
+ "",
192
+ f"CREW merged `{ref}` into {into} in this worktree and Git stopped with",
193
+ "conflicts. Edit the files below so that every conflict is resolved:",
194
+ "",
195
+ *[f"- {f}" for f in files],
196
+ "",
197
+ "Rules:",
198
+ "- Remove every `<<<<<<<`, `=======` and `>>>>>>>` marker.",
199
+ "- Keep the intent of both sides. If both sides made the same change, keep it once.",
200
+ "- Do not change, create or delete any other file and do not refactor; CREW",
201
+ " rejects the resolution if anything else changed. CREW commits the result.",
202
+ "- Do not run `git add`, `git commit` or `git merge` yourself.",
203
+ "",
204
+ "# Original request",
205
+ "",
206
+ run.request,
207
+ "",
208
+ "# What each side was doing (task reports)",
209
+ "",
210
+ "```json",
211
+ _json(reports),
212
+ "```",
213
+ ]
214
+ )
215
+
216
+
217
+ FAILED_OUTPUT_CHARS = 6_000
218
+
219
+
220
+ def failed_verification_description(commands: list[CommandExecution]) -> str:
221
+ """Correction task text for verification commands that failed after integration."""
222
+ lines = [
223
+ "These verification commands, run by CREW on the integrated change, failed.",
224
+ "Make them pass. Fix the cause in the code or in tests this run added; never",
225
+ "weaken, skip or delete existing tests. If a failure is unrelated to this run's",
226
+ "change (it also fails without it), do not touch unrelated code: say so in",
227
+ "`limitations`.",
228
+ "",
229
+ ]
230
+ for c in commands:
231
+ argv = " ".join(json.loads(c.argv_json))
232
+ status = "timed out" if c.timed_out else f"exit {c.exit_code}"
233
+ output = ((c.stdout or "") + ("\n" + c.stderr if c.stderr else "")).strip()
234
+ lines += [
235
+ f"### `{argv}` — {status}",
236
+ "",
237
+ "```",
238
+ output[-FAILED_OUTPUT_CHARS:],
239
+ "```",
240
+ "",
241
+ ]
242
+ return "\n".join(lines)
243
+
244
+
245
+ def correction_description(findings: list[dict[str, Any]]) -> str:
246
+ lines = ["Fix the following blocking review findings in the integrated change:", ""]
247
+ for i, f in enumerate(findings, 1):
248
+ loc = f.get("file") or "-"
249
+ if f.get("line_start"):
250
+ loc += f":{f['line_start']}"
251
+ lines += [
252
+ f"{i}. [{f.get('severity')}/{f.get('category')}] {f.get('title')} ({loc})",
253
+ f" Problem: {f.get('explanation', '')}",
254
+ f" Recommended fix: {f.get('recommendation', '')}",
255
+ ]
256
+ return "\n".join(lines)
257
+
258
+
259
+ def evaluator_prompt(
260
+ run: Run,
261
+ tasks: list[Task],
262
+ diff: str,
263
+ commands: list[CommandExecution],
264
+ reviews: list[dict[str, Any]],
265
+ ) -> str:
266
+ claims = {t.key: t.report for t in tasks if t.report}
267
+ return "\n".join(
268
+ [
269
+ "# Original request (authoritative — do not reinterpret)",
270
+ "",
271
+ run.request,
272
+ "",
273
+ "# Approved plan",
274
+ "",
275
+ "```json",
276
+ _json(run.plan),
277
+ "```",
278
+ "",
279
+ diff,
280
+ "",
281
+ "# Verification evidence recorded by CREW (trustworthy)",
282
+ "",
283
+ _commands_md(commands),
284
+ "",
285
+ "# Reviewer findings, all cycles (re-evaluate, do not copy)",
286
+ "",
287
+ "```json",
288
+ _json(reviews),
289
+ "```",
290
+ "",
291
+ "# Implementer reports (CLAIMS — verify against the diff and evidence)",
292
+ "",
293
+ "```json",
294
+ _json(claims),
295
+ "```",
296
+ ]
297
+ )
@@ -0,0 +1,201 @@
1
+ """CREW permission-prompt tool: a minimal MCP server over stdio.
2
+
3
+ Claude Code runs it (``--mcp-config``) and calls its ``approve`` tool
4
+ (``--permission-prompt-tool mcp__crew__approve``) whenever an agent asks for an
5
+ action its permission rules do not allow. The server:
6
+
7
+ 1. denies DESTRUCTIVE and NETWORK commands outright (execution policy);
8
+ 2. allows requests the developer already allowed *for this run*;
9
+ 3. otherwise writes ``<id>.request.json`` into ``CREW_PERMISSION_DIR`` and waits
10
+ for the CREW driver to write ``<id>.response.json`` (the developer's answer),
11
+ denying after ``CREW_PERMISSION_TIMEOUT`` seconds.
12
+
13
+ It speaks newline-delimited JSON-RPC 2.0 (MCP stdio transport) and depends only
14
+ on the standard library and CREW's execution policy.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import shlex
22
+ import sys
23
+ import time
24
+ import uuid
25
+ from pathlib import Path
26
+ from typing import Any
27
+
28
+ from crew.domain.enums import CommandCategory
29
+ from crew.domain.errors import PolicyViolationError
30
+ from crew.security.execution_policy import classify_command
31
+
32
+ TOOL_NAME = "approve"
33
+ SHELL_TOOLS = ("Bash", "PowerShell")
34
+ POLL_SECONDS = 0.2
35
+ ALLOWLIST_FILE = "allowed.json"
36
+
37
+
38
+ def request_key(tool_name: str, tool_input: dict[str, Any]) -> str:
39
+ """Identity of a request for "allow for this run": tool + exact command/path."""
40
+ detail = (
41
+ tool_input.get("command")
42
+ or tool_input.get("file_path")
43
+ or json.dumps(tool_input, sort_keys=True)
44
+ )
45
+ return f"{tool_name}:{detail}"
46
+
47
+
48
+ def classify_request(tool_name: str, tool_input: dict[str, Any]) -> CommandCategory | None:
49
+ if tool_name not in SHELL_TOOLS:
50
+ return None
51
+ command = str(tool_input.get("command", ""))
52
+ try:
53
+ # punctuation_chars splits operators even when glued to words ("ls;rm").
54
+ lexer = shlex.shlex(command, posix=True, punctuation_chars=True)
55
+ lexer.whitespace_split = True
56
+ argv = list(lexer)
57
+ except ValueError:
58
+ return CommandCategory.DESTRUCTIVE # unparseable shell: treat as unsafe
59
+ if not argv:
60
+ return None
61
+ # Compound commands are judged by their most dangerous part.
62
+ parts: list[list[str]] = [[]]
63
+ for token in argv:
64
+ if token and set(token) <= set("&|;<>()"):
65
+ parts.append([])
66
+ else:
67
+ parts[-1].append(token)
68
+ categories = []
69
+ for part in parts:
70
+ if part:
71
+ try:
72
+ categories.append(classify_command(part))
73
+ except PolicyViolationError:
74
+ categories.append(CommandCategory.DESTRUCTIVE)
75
+ for worst in (CommandCategory.DESTRUCTIVE, CommandCategory.NETWORK):
76
+ if worst in categories:
77
+ return worst
78
+ return categories[0] if categories else None
79
+
80
+
81
+ def _deny(message: str) -> dict[str, Any]:
82
+ return {"behavior": "deny", "message": message}
83
+
84
+
85
+ def _allow(tool_input: dict[str, Any]) -> dict[str, Any]:
86
+ return {"behavior": "allow", "updatedInput": tool_input}
87
+
88
+
89
+ def _read_json(path: Path) -> Any:
90
+ try:
91
+ return json.loads(path.read_text(encoding="utf-8"))
92
+ except (OSError, json.JSONDecodeError):
93
+ return None
94
+
95
+
96
+ def decide(tool_name: str, tool_input: dict[str, Any], directory: Path, timeout: float) -> dict:
97
+ category = classify_request(tool_name, tool_input)
98
+ if category in (CommandCategory.DESTRUCTIVE, CommandCategory.NETWORK):
99
+ return _deny(f"CREW policy: {category.value} commands are never allowed for agents.")
100
+ key = request_key(tool_name, tool_input)
101
+ if key in (_read_json(directory / ALLOWLIST_FILE) or []):
102
+ return _allow(tool_input)
103
+
104
+ request_id = uuid.uuid4().hex[:12]
105
+ request = {
106
+ "id": request_id,
107
+ "run_id": os.environ.get("CREW_RUN_ID"),
108
+ "execution_id": os.environ.get("CREW_EXECUTION_ID"),
109
+ "role": os.environ.get("CREW_ROLE"),
110
+ "tool_name": tool_name,
111
+ "input": tool_input,
112
+ "key": key,
113
+ "category": category.value if category else None,
114
+ "created_at": time.time(),
115
+ }
116
+ directory.mkdir(parents=True, exist_ok=True)
117
+ tmp = directory / f"{request_id}.request.tmp"
118
+ tmp.write_text(json.dumps(request), encoding="utf-8")
119
+ tmp.replace(directory / f"{request_id}.request.json")
120
+
121
+ response_path = directory / f"{request_id}.response.json"
122
+ deadline = time.monotonic() + timeout
123
+ while time.monotonic() < deadline:
124
+ response = _read_json(response_path)
125
+ if isinstance(response, dict):
126
+ if response.get("decision") in ("allow", "allow_run"):
127
+ return _allow(tool_input)
128
+ return _deny(response.get("message") or "Denied by the developer.")
129
+ time.sleep(POLL_SECONDS)
130
+ return _deny("No answer from the developer in time; denied.")
131
+
132
+
133
+ TOOL_SPEC = {
134
+ "name": TOOL_NAME,
135
+ "description": "CREW permission check for actions outside the agent's permission rules.",
136
+ "inputSchema": {
137
+ "type": "object",
138
+ "properties": {
139
+ "tool_name": {"type": "string"},
140
+ "input": {"type": "object"},
141
+ "tool_use_id": {"type": "string"},
142
+ },
143
+ "required": ["tool_name", "input"],
144
+ },
145
+ }
146
+
147
+
148
+ def handle(message: dict[str, Any], directory: Path, timeout: float) -> dict[str, Any] | None:
149
+ """Handle one JSON-RPC message; ``None`` for notifications."""
150
+ method = message.get("method")
151
+ msg_id = message.get("id")
152
+ if msg_id is None:
153
+ return None # notification (e.g. notifications/initialized)
154
+ if method == "initialize":
155
+ params = message.get("params") or {}
156
+ result: Any = {
157
+ "protocolVersion": params.get("protocolVersion", "2025-06-18"),
158
+ "capabilities": {"tools": {}},
159
+ "serverInfo": {"name": "crew", "version": "1"},
160
+ }
161
+ elif method == "tools/list":
162
+ result = {"tools": [TOOL_SPEC]}
163
+ elif method == "tools/call":
164
+ params = message.get("params") or {}
165
+ if params.get("name") != TOOL_NAME:
166
+ return _error(msg_id, -32602, f"unknown tool {params.get('name')!r}")
167
+ args = params.get("arguments") or {}
168
+ raw_input = args.get("input")
169
+ tool_input = raw_input if isinstance(raw_input, dict) else {}
170
+ decision = decide(str(args.get("tool_name", "")), tool_input, directory, timeout)
171
+ result = {"content": [{"type": "text", "text": json.dumps(decision)}]}
172
+ elif method == "ping":
173
+ result = {}
174
+ else:
175
+ return _error(msg_id, -32601, f"method {method!r} not supported")
176
+ return {"jsonrpc": "2.0", "id": msg_id, "result": result}
177
+
178
+
179
+ def _error(msg_id: Any, code: int, text: str) -> dict[str, Any]:
180
+ return {"jsonrpc": "2.0", "id": msg_id, "error": {"code": code, "message": text}}
181
+
182
+
183
+ def main() -> None:
184
+ directory = Path(os.environ["CREW_PERMISSION_DIR"])
185
+ timeout = float(os.environ.get("CREW_PERMISSION_TIMEOUT", "300"))
186
+ for line in sys.stdin:
187
+ line = line.strip()
188
+ if not line:
189
+ continue
190
+ try:
191
+ message = json.loads(line)
192
+ except json.JSONDecodeError:
193
+ continue
194
+ reply = handle(message, directory, timeout)
195
+ if reply is not None:
196
+ sys.stdout.write(json.dumps(reply) + "\n")
197
+ sys.stdout.flush()
198
+
199
+
200
+ if __name__ == "__main__":
201
+ main()
@@ -0,0 +1,17 @@
1
+ ROLE: Director (read-only).
2
+
3
+ Mission: understand the request and the repository, propose a technically sound plan, and break the work into tasks that can each be implemented and verified independently.
4
+
5
+ You may read files and search the repository. You must not edit files.
6
+
7
+ Planning rules:
8
+ - Do not invent APIs, files or conventions; check that they exist.
9
+ - Prefer the smallest coherent solution. Avoid speculative abstractions.
10
+ - Split work into separate tasks only when each can be implemented and verified on its own. One task is fine for small requests. Maximum 12 tasks.
11
+ - Every task has a fixed cost: its Implementer reads the project, builds and runs the tests (measured at roughly $0.4–0.7 per task). Split only where the parts are large or can really run in parallel; do not split a change into many small sequential tasks.
12
+ - In `project_notes`, record what you learned that every Implementer needs: the exact build and test commands, where code and tests live, conventions, and existing files to imitate. They get these notes instead of exploring the repository again.
13
+ - Task ids: short, lowercase, letters/digits/hyphens (e.g. "add-health-endpoint").
14
+ - Use `dependencies` for real ordering constraints. Tasks without dependencies may run in parallel, so avoid parallel tasks that edit the same files; make one depend on the other instead.
15
+ - In `expected_files`, list every file a task will change, including shared ones such as build files and dependency manifests (`pom.xml`, `package.json`, `pyproject.toml`), routers, registries, configuration and changelogs. CREW orders tasks that share a listed file so they never run in parallel; an unlisted shared file is the usual cause of merge conflicts.
16
+ - Every task needs concrete, checkable acceptance criteria.
17
+ - If the request is too ambiguous to plan safely, set `blocking_ambiguity` and explain, instead of guessing.
@@ -0,0 +1,11 @@
1
+ ROLE: External Evaluator (read-only, independent).
2
+
3
+ Mission: decide whether the delivered result satisfies the ORIGINAL request and the APPROVED plan, based on evidence. You must not modify files.
4
+
5
+ Rules:
6
+ - Assess requirement by requirement, citing evidence (files, diff hunks, recorded command results).
7
+ - Do not rely on Implementer claims; they are labelled as claims. Inspect the diff and the CREW-recorded verification results.
8
+ - Re-evaluate the Reviewer findings yourself rather than copying them.
9
+ - Never reinterpret or narrow the original request to make the result pass.
10
+ - Recommendation: ACCEPT (evidence supports completion, no unresolved blocking gap), NEEDS_CHANGES (specific addressable gaps remain), or REJECT (materially fails the request or has an unacceptable defect).
11
+ - Your recommendation is advisory. The developer makes the final decision.