File size: 7,514 Bytes
c706455
 
 
37f9abc
 
c706455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37f9abc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c706455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37f9abc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee30fd7
 
c706455
 
 
 
 
ee30fd7
 
 
 
 
 
 
 
 
 
 
c706455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6231ab
 
 
 
 
 
 
 
 
 
 
 
 
c706455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# This will require some refactoring in the future, e.g. moving some content to "centralized" files for code reuse.

from typing import Annotated
from multi_agent_sdlc.runtime.paths import normalise_relative_path
import re
from pydantic import AfterValidator, Field, StringConstraints

ENTRY_POINT_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*")

MODULE_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$")

DEPENDENCY_PATTERN = re.compile(
    r"^[A-Za-z0-9][A-Za-z0-9._-]*"
    r"(?:\[[A-Za-z0-9._,-]+\])?"
    r"(?:(?:===|==|~=|!=|<=|>=|<|>)[A-Za-z0-9.*+!_-]+)?$"
)

REMOTE_DEPENDENCY_PREFIXES = (
    "http://",
    "https://",
    "git+",
    "ssh://",
    "file:",
)


TEST_DIRECTORY_NAMES = {
    "test",
    "tests",
    "__tests__",
    "spec",
    "specs",
}

PROHIBITED_ENTRY_POINTS = {
    "pytest",
    "ruff",
    "mypy",
    "flake8",
    "coverage",
    "coverage3",
    "pip",
    "pip3",
    "bash",
    "sh",
    "zsh",
    "fish",
    "powershell",
    "pwsh",
}

PROHIBITED_PYTHON_MODULES = {
    "pytest",
    "unittest",
    "coverage",
    "pip",
    "ensurepip",
    "venv",
    "subprocess",
}

PROHIBITED_RUNTIME_PACKAGES = {
    "pytest",
    "pytest-cov",
    "coverage",
    "ruff",
    "mypy",
    "flake8",
    "tox",
    "nox",
}


def validate_entry_point(entry_point: str) -> str:
    """Validate and return a project entry-point name."""

    cleaned = entry_point.strip()

    if not cleaned:
        raise ValueError("Entry point cannot be empty.")

    if cleaned.lower() in PROHIBITED_ENTRY_POINTS:
        raise PermissionError(f"The Coder cannot execute `{cleaned}`.")

    return cleaned


def validate_application_arguments(
    arguments: list[str],
) -> list[str]:
    """Validate arguments passed to an application or module."""

    validated: list[str] = []

    for argument in arguments:
        if not isinstance(argument, str):
            raise TypeError("Every application argument must be a string.")

        if "\n" in argument or "\r" in argument:
            raise PermissionError("Multiline application arguments are not allowed.")

        if "\x00" in argument:
            raise PermissionError(
                "Null bytes are not allowed in application arguments."
            )

        validated.append(argument)

    return validated


def validate_module_name(module: str) -> str:
    """Validate and return an application module name."""

    cleaned = module.strip()

    if not cleaned:
        raise ValueError("Module cannot be empty.")

    if not MODULE_PATTERN.fullmatch(cleaned):
        raise ValueError(f"Invalid Python module name: {cleaned}")

    root_module = cleaned.split(".", maxsplit=1)[0].lower()

    if root_module in PROHIBITED_PYTHON_MODULES:
        raise PermissionError(f"The Coder cannot execute Python module `{cleaned}`.")

    return cleaned


def validate_runtime_dependency(package: str) -> str:
    """Validate and return a runtime dependency specification."""
    cleaned = package.strip()

    if not cleaned:
        raise ValueError("Dependency specification cannot be empty.")

    lowered = cleaned.lower()

    if lowered.startswith(REMOTE_DEPENDENCY_PREFIXES):
        raise PermissionError(
            "Git, URL, SSH, and local-file dependencies are not allowed: " f"{cleaned}"
        )

    if cleaned.startswith("-"):
        raise PermissionError(
            f"Dependency command-line options are not allowed: {cleaned}"
        )

    if "@" in cleaned:
        raise PermissionError(
            f"Direct-reference dependencies are not allowed: {cleaned}"
        )

    if not DEPENDENCY_PATTERN.fullmatch(cleaned):
        raise ValueError(f"Invalid runtime dependency specification: {cleaned}")

    dependency_name = normalise_dependency_name(cleaned)

    if dependency_name in PROHIBITED_RUNTIME_PACKAGES:
        raise PermissionError(
            f"`{cleaned}` is a testing or development dependency. "
            "The Coder may add runtime dependencies only."
        )

    return cleaned


def is_test_related_path(path: str) -> bool:
    """Return True when a path includes a blocked test directory."""
    candidate = normalise_relative_path(path)

    return any(part.lower() in TEST_DIRECTORY_NAMES for part in candidate.parts)


def reject_coder_test_path(path: str) -> None:
    """Prevent the Coder from writing into test-related directories."""
    if is_test_related_path(path):
        raise PermissionError(
            "The Coder cannot create or modify files or directories "
            f"inside test-related paths: {path}. "
            "Test implementation belongs to the Tester. "
            "Do not retry this operation using another tool or path."
        )


def validate_project_relative_path(path: str) -> str:
    candidate = normalise_relative_path(path.strip())
    return candidate.as_posix()


def normalise_dependency_name(specification: str) -> str:
    """Extract the normalised package name from a dependency specification."""
    match = re.match(
        r"^[A-Za-z0-9][A-Za-z0-9._-]*",
        specification,
    )

    if match is None:
        return ""

    return match.group(0).lower().replace("_", "-")


def validate_file_content(content: str) -> str:
    if "\x00" in content:
        raise ValueError("File content cannot contain null bytes.")

    return content


EntryPoint = Annotated[
    str,
    StringConstraints(
        strip_whitespace=True,
        min_length=1,
        max_length=100,
        pattern=r"[A-Za-z0-9][A-Za-z0-9._-]*",
    ),
    AfterValidator(validate_entry_point),
]

StandardInput = Annotated[
    str,
    Field(
        min_length=1,
        max_length=10_000,
        description=(
            "Text sent to the application's standard input. Separate "
            "interactive responses with newline characters. Omit this "
            "argument when no standard input is required."
        ),
    ),
]

ApplicationArguments = Annotated[
    list[str],
    Field(
        max_length=50,
        description="Arguments passed directly to the application.",
    ),
    AfterValidator(validate_application_arguments),
]

ExecutionTimeout = Annotated[
    int,
    Field(
        ge=1,
        le=200,
        description="Maximum application execution time in seconds.",
    ),
]

PythonModuleName = Annotated[
    str,
    Field(
        min_length=1,
        max_length=200,
        description=(
            "A dotted Python module belonging to the generated application. "
            "Testing, package-management, environment-management, and "
            "process-execution modules are prohibited."
        ),
    ),
    AfterValidator(validate_module_name),
]

RuntimeDependency = Annotated[
    str,
    AfterValidator(validate_runtime_dependency),
]


RuntimeDependencies = Annotated[
    list[RuntimeDependency],
    Field(
        min_length=1,
        max_length=20,
        description="Runtime dependencies to add with uv.",
    ),
]

ProjectRelativePath = Annotated[
    str,
    Field(
        min_length=1,
        max_length=500,
        description=(
            "A path relative to the project directory. "
            "Absolute paths and parent-directory traversal are prohibited."
        ),
    ),
    AfterValidator(validate_project_relative_path),
]

FileContent = Annotated[
    str,
    Field(
        max_length=500_000,
        description="Complete UTF-8 text content to write to the file.",
    ),
    AfterValidator(validate_file_content),
]