dap-prompt-dsl 0.3.0__tar.gz

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.
@@ -0,0 +1,87 @@
1
+ # --- Python ---
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ .venv/
8
+ venv/
9
+ env/
10
+ *.egg-info/
11
+ *.egg
12
+ dist/
13
+ build/
14
+ .eggs/
15
+ pip-log.txt
16
+ pip-delete-this-directory.txt
17
+
18
+ # uv
19
+ .uv-cache/
20
+
21
+ # Type checkers / linters
22
+ .mypy_cache/
23
+ .ruff_cache/
24
+ .pyright/
25
+ .pytype/
26
+
27
+ # pytest / coverage
28
+ .pytest_cache/
29
+ .coverage
30
+ .coverage.*
31
+ htmlcov/
32
+ .tox/
33
+ .nox/
34
+ coverage.xml
35
+ *.cover
36
+
37
+ # --- Node (dashboard) ---
38
+ node_modules/
39
+ .pnpm-store/
40
+ .next/
41
+ out/
42
+ *.tsbuildinfo
43
+ .turbo/
44
+
45
+ # --- Environment ---
46
+ .env
47
+ .env.local
48
+ .env.*.local
49
+
50
+ # --- DAP local state ---
51
+ .dap/
52
+ *.db
53
+ *.db-journal
54
+ *.db-wal
55
+ *.db-shm
56
+
57
+ # --- Logs ---
58
+ logs/
59
+ *.log
60
+ npm-debug.log*
61
+ pnpm-debug.log*
62
+
63
+ # --- IDE / Agents ---
64
+ .vscode/
65
+ .idea/
66
+ *.swp
67
+ *.swo
68
+ .claude/
69
+
70
+ # --- OS ---
71
+ .DS_Store
72
+ Thumbs.db
73
+
74
+ # --- Cache ---
75
+ .cache/
76
+ .eslintcache
77
+
78
+ # --- Built artefacts ---
79
+ # Dashboard bundle staged into the dap-cli wheel by
80
+ # scripts/build-dashboard-bundle.sh — regenerated on demand from
81
+ # apps/dashboard/.next. The ``.gitkeep`` is retained so hatchling's
82
+ # ``force-include`` always finds the directory; dev wheels built
83
+ # without running the bundle script ship an effectively-empty
84
+ # ``_dashboard/`` and ``dap start`` falls back to "dashboard not
85
+ # bundled".
86
+ apps/cli/src/dap_cli/_dashboard/*
87
+ !apps/cli/src/dap_cli/_dashboard/.gitkeep
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.4
2
+ Name: dap-prompt-dsl
3
+ Version: 0.3.0
4
+ Summary: Prompt Builder — Jinja2 → XML compiler for DAP agent prompts
5
+ Requires-Python: >=3.13
6
+ Requires-Dist: defusedxml>=0.7.1
7
+ Requires-Dist: jinja2>=3.1.4
8
+ Requires-Dist: pydantic>=2.9.2
9
+ Description-Content-Type: text/markdown
10
+
11
+ # dap-prompt-dsl
12
+
13
+ Prompt Builder — kompilator JSON context + Jinja2 template → walidowany XML prompt dla DAP agentów.
14
+
15
+ ## Why
16
+
17
+ DAP zasada: **prompt jest kodem**. Każdy agent ma `prompt_template` (Jinja2) i `input_schema`. Builder jest **deterministyczną pure function** — input → output, brak side effects, brak LLM. Sandbox + defused parser dla bezpieczeństwa.
18
+
19
+ ## Usage
20
+
21
+ ```python
22
+ from dap_prompt_dsl import build_prompt
23
+
24
+ result = build_prompt(
25
+ template="<agent_prompt><role>{{ role }}</role></agent_prompt>",
26
+ context={"role": "test_author"},
27
+ )
28
+ # BuildResult(xml="...", warnings=[], valid=True)
29
+ ```
30
+
31
+ ## Bezpieczeństwo
32
+
33
+ - **Jinja2 SandboxedEnvironment** — agent prompt_template może pochodzić z user input (dashboard); sandbox blokuje access do dunder methods, file I/O.
34
+ - **defusedxml** dla parsowania — protections XXE, billion laughs, external entities.
@@ -0,0 +1,24 @@
1
+ # dap-prompt-dsl
2
+
3
+ Prompt Builder — kompilator JSON context + Jinja2 template → walidowany XML prompt dla DAP agentów.
4
+
5
+ ## Why
6
+
7
+ DAP zasada: **prompt jest kodem**. Każdy agent ma `prompt_template` (Jinja2) i `input_schema`. Builder jest **deterministyczną pure function** — input → output, brak side effects, brak LLM. Sandbox + defused parser dla bezpieczeństwa.
8
+
9
+ ## Usage
10
+
11
+ ```python
12
+ from dap_prompt_dsl import build_prompt
13
+
14
+ result = build_prompt(
15
+ template="<agent_prompt><role>{{ role }}</role></agent_prompt>",
16
+ context={"role": "test_author"},
17
+ )
18
+ # BuildResult(xml="...", warnings=[], valid=True)
19
+ ```
20
+
21
+ ## Bezpieczeństwo
22
+
23
+ - **Jinja2 SandboxedEnvironment** — agent prompt_template może pochodzić z user input (dashboard); sandbox blokuje access do dunder methods, file I/O.
24
+ - **defusedxml** dla parsowania — protections XXE, billion laughs, external entities.
@@ -0,0 +1,18 @@
1
+ [project]
2
+ name = "dap-prompt-dsl"
3
+ version = "0.3.0"
4
+ description = "Prompt Builder — Jinja2 → XML compiler for DAP agent prompts"
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ dependencies = [
8
+ "jinja2>=3.1.4",
9
+ "defusedxml>=0.7.1",
10
+ "pydantic>=2.9.2",
11
+ ]
12
+
13
+ [build-system]
14
+ requires = ["hatchling"]
15
+ build-backend = "hatchling.build"
16
+
17
+ [tool.hatch.build.targets.wheel]
18
+ packages = ["src/dap_prompt_dsl"]
@@ -0,0 +1,26 @@
1
+ from dap_prompt_dsl.builder import (
2
+ RESERVED_METADATA_KEYS,
3
+ BuildResult,
4
+ PromptBuildError,
5
+ build_prompt,
6
+ )
7
+ from dap_prompt_dsl.context import (
8
+ ImplementerContext,
9
+ PromptContextBase,
10
+ TestAuthorContext,
11
+ VerifierContext,
12
+ )
13
+ from dap_prompt_dsl.validator import ValidationOutcome, validate_xml
14
+
15
+ __all__ = [
16
+ "RESERVED_METADATA_KEYS",
17
+ "BuildResult",
18
+ "ImplementerContext",
19
+ "PromptBuildError",
20
+ "PromptContextBase",
21
+ "TestAuthorContext",
22
+ "ValidationOutcome",
23
+ "VerifierContext",
24
+ "build_prompt",
25
+ "validate_xml",
26
+ ]
@@ -0,0 +1,210 @@
1
+ """Render Jinja2 template with context, validate XML output."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from typing import Any
7
+
8
+ from jinja2 import StrictUndefined, TemplateSyntaxError, UndefinedError
9
+ from jinja2.exceptions import TemplateError
10
+ from jinja2.sandbox import SandboxedEnvironment
11
+ from pydantic import BaseModel, ConfigDict
12
+
13
+ from dap_prompt_dsl.validator import DEFAULT_ROOT, validate_xml
14
+
15
+ # StrictUndefined formats its message as ``'<name>' is undefined`` for
16
+ # the simple top-level case we're trying to surface. Anything more
17
+ # exotic (attribute access, etc.) keeps the generic hint.
18
+ _UNDEFINED_NAME_PATTERN = re.compile(r"'([^']+)' is undefined")
19
+
20
+
21
+ class PromptBuildError(Exception):
22
+ """Raised when template rendering fails (Jinja syntax / undefined variable)."""
23
+
24
+
25
+ class BuildResult(BaseModel):
26
+ """Result of prompt build operation."""
27
+
28
+ model_config = ConfigDict(extra="forbid")
29
+
30
+ xml: str
31
+ valid: bool
32
+ warnings: list[str] = []
33
+ errors: list[str] = []
34
+
35
+
36
+ def _make_sandbox() -> SandboxedEnvironment:
37
+ """Sandboxed Jinja2 — blocks attribute access to dunder methods, file I/O, etc.
38
+
39
+ StrictUndefined turns missing context fields into errors instead of silent
40
+ empty strings — surfaces problems early.
41
+ """
42
+ return SandboxedEnvironment(
43
+ autoescape=False, # XML output, we rely on validator
44
+ keep_trailing_newline=True,
45
+ undefined=StrictUndefined,
46
+ )
47
+
48
+
49
+ #: Reserved metadata keys that ``build_prompt`` always lifts into the
50
+ #: render context regardless of ``input_schema`` projection. These are
51
+ #: agent identity (not pipeline state), so templates can reference them
52
+ #: without having to declare them as inputs. Add to this set sparingly —
53
+ #: every key is a name the agent's prompt template can never use for
54
+ #: pipeline state without a clash.
55
+ RESERVED_METADATA_KEYS: frozenset[str] = frozenset({"role"})
56
+
57
+
58
+ def build_prompt(
59
+ template: str,
60
+ context: dict[str, Any],
61
+ *,
62
+ expected_root: str = DEFAULT_ROOT,
63
+ input_schema: list[str] | None = None,
64
+ agent_metadata: dict[str, Any] | None = None,
65
+ ) -> BuildResult:
66
+ """Render template with context, validate XML output.
67
+
68
+ Pure function: same input → same output, no side effects.
69
+
70
+ When ``input_schema`` is supplied and non-empty, the render context
71
+ is projected to that subset — only fields the agent has declared as
72
+ inputs are visible to the template. A reference to anything else
73
+ fails with a descriptive ``PromptBuildError`` pointing at the
74
+ schema as the fix. When ``input_schema`` is ``None`` or empty, the
75
+ context is passed through unchanged (backward compat with v0.4
76
+ agents that haven't declared a contract yet).
77
+
78
+ ``agent_metadata`` is merged into the render context *after*
79
+ projection — the agent's identity (currently ``role``, see
80
+ :data:`RESERVED_METADATA_KEYS`) is always visible to the template
81
+ regardless of ``input_schema``. This lets the built-in templates
82
+ use ``{{ role }}`` without forcing every agent to declare ``role``
83
+ as an input. Caller-supplied ``context`` keys win over
84
+ ``agent_metadata`` keys on collision so existing pipelines that
85
+ happen to put ``role`` into PipelineState aren't disrupted.
86
+
87
+ Only keys present in :data:`RESERVED_METADATA_KEYS` are accepted —
88
+ arbitrary metadata would let callers silently bypass
89
+ ``input_schema`` projection for any field, which is exactly what
90
+ the projection is there to prevent. Unknown keys raise
91
+ :class:`PromptBuildError`.
92
+
93
+ Raises:
94
+ PromptBuildError: when template fails to render (syntax error,
95
+ undefined variable in StrictUndefined mode),
96
+ or when ``agent_metadata`` carries a key
97
+ outside :data:`RESERVED_METADATA_KEYS`.
98
+
99
+ Returns:
100
+ BuildResult with rendered xml + validation outcome. The XML is returned
101
+ even if invalid (so callers can show diagnostics), but `valid=False`.
102
+ """
103
+ env = _make_sandbox()
104
+
105
+ if agent_metadata:
106
+ unknown = sorted(set(agent_metadata) - RESERVED_METADATA_KEYS)
107
+ if unknown:
108
+ allowed = ", ".join(sorted(RESERVED_METADATA_KEYS))
109
+ raise PromptBuildError(
110
+ f"agent_metadata contains unsupported key(s): {', '.join(unknown)}. "
111
+ f"Reserved metadata keys are: {allowed}.",
112
+ )
113
+
114
+ # ``_project_context`` returns the caller's context object directly
115
+ # when no projection is needed. Copy before merging metadata so we
116
+ # never mutate the caller's dict — this would otherwise leak
117
+ # ``role`` into ``PipelineState.model_dump()`` between node calls.
118
+ render_context = dict(_project_context(context, input_schema))
119
+ if agent_metadata:
120
+ for key, value in agent_metadata.items():
121
+ # Caller context wins on collision — this only fills in
122
+ # metadata keys the caller didn't supply themselves.
123
+ render_context.setdefault(key, value)
124
+
125
+ try:
126
+ compiled = env.from_string(template)
127
+ rendered = compiled.render(**render_context)
128
+ except TemplateSyntaxError as exc:
129
+ raise PromptBuildError(f"Template syntax error: {exc.message}") from exc
130
+ except UndefinedError as exc:
131
+ raise PromptBuildError(
132
+ _format_undefined_error(exc, input_schema, render_context),
133
+ ) from exc
134
+ except TemplateError as exc:
135
+ raise PromptBuildError(f"Template error: {exc}") from exc
136
+
137
+ outcome = validate_xml(rendered, expected_root=expected_root)
138
+
139
+ return BuildResult(
140
+ xml=rendered,
141
+ valid=outcome.valid,
142
+ warnings=outcome.warnings,
143
+ errors=outcome.errors,
144
+ )
145
+
146
+
147
+ def _project_context(
148
+ context: dict[str, Any],
149
+ input_schema: list[str] | None,
150
+ ) -> dict[str, Any]:
151
+ """Restrict render context to declared input fields when schema is set.
152
+
153
+ Empty or ``None`` schema → pass-through (backward compat with agents
154
+ that pre-date #58). Anything not in ``input_schema`` is dropped so a
155
+ template referencing it triggers the standard
156
+ :class:`jinja2.UndefinedError` from ``StrictUndefined``.
157
+ """
158
+ if not input_schema:
159
+ return context
160
+ return {name: context[name] for name in input_schema if name in context}
161
+
162
+
163
+ def _format_undefined_error(
164
+ exc: UndefinedError,
165
+ input_schema: list[str] | None,
166
+ render_context: dict[str, Any],
167
+ ) -> str:
168
+ """Build a descriptive message for ``UndefinedError`` in StrictUndefined mode.
169
+
170
+ Two distinct failure modes when ``input_schema`` is set:
171
+
172
+ 1. Template references a field the agent didn't declare → fix is
173
+ to extend ``input_schema`` (or remove the reference).
174
+ 2. Field IS declared but the caller didn't supply it in the
175
+ context → fix is to add it to the runtime/preview payload, not
176
+ to touch ``input_schema``.
177
+
178
+ We extract the offending name from the Jinja message and pick the
179
+ right hint. Falls back to the generic schema reminder when the
180
+ name can't be parsed (exotic message shapes from attribute access,
181
+ etc.).
182
+ """
183
+ base = f"Template references undefined variable: {exc.message}"
184
+ if not input_schema:
185
+ return base
186
+
187
+ declared = ", ".join(input_schema)
188
+ name = _extract_undefined_name(exc.message)
189
+
190
+ if name is not None and name in input_schema and name not in render_context:
191
+ # Declared, but caller didn't supply it.
192
+ return (
193
+ f"{base}. The field is declared in agent.input_schema but no "
194
+ f"value was supplied — pass it in the render context."
195
+ )
196
+
197
+ # Either the name isn't in the schema, or we couldn't parse the
198
+ # message — both point at the schema as the place to edit.
199
+ return (
200
+ f"{base}. Add the field to agent.input_schema or update the "
201
+ f"template. Currently declared inputs: {declared}."
202
+ )
203
+
204
+
205
+ def _extract_undefined_name(message: str | None) -> str | None:
206
+ """Pull the offending name out of a StrictUndefined error message."""
207
+ if not message:
208
+ return None
209
+ match = _UNDEFINED_NAME_PATTERN.search(message)
210
+ return match.group(1) if match else None
@@ -0,0 +1,67 @@
1
+ """Typed context helpers for common agent roles.
2
+
3
+ These are convenience Pydantic models that match expected shapes for built-in
4
+ roles. Custom agents can pass any dict[str, Any] to build_prompt — these types
5
+ just provide structure + validation when the role matches.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pydantic import BaseModel, ConfigDict, Field
11
+
12
+
13
+ class PromptContextBase(BaseModel):
14
+ """Base for typed contexts. Custom agents may extend this or pass dicts."""
15
+
16
+ model_config = ConfigDict(extra="allow")
17
+
18
+ role: str
19
+ task: str
20
+ constraints: list[str] = Field(default_factory=list)
21
+
22
+
23
+ class CodeContext(BaseModel):
24
+ model_config = ConfigDict(extra="forbid")
25
+
26
+ language: str
27
+ framework: str | None = None
28
+ existing_files: list[str] = Field(default_factory=list)
29
+
30
+
31
+ class UserStory(BaseModel):
32
+ model_config = ConfigDict(extra="forbid")
33
+
34
+ id: str
35
+ description: str
36
+ acceptance_criteria: list[str] = Field(default_factory=list)
37
+
38
+
39
+ class OutputSpec(BaseModel):
40
+ model_config = ConfigDict(extra="forbid")
41
+
42
+ format: str
43
+ location: str | None = None
44
+
45
+
46
+ class TestAuthorContext(PromptContextBase):
47
+ """Context expected by Test Authoring Agent."""
48
+
49
+ user_story: UserStory
50
+ code_context: CodeContext
51
+ output: OutputSpec
52
+
53
+
54
+ class ImplementerContext(PromptContextBase):
55
+ """Context for Implementation Agent (make tests green)."""
56
+
57
+ failing_test_output: str
58
+ allowed_files: list[str] = Field(default_factory=list)
59
+ code_context: CodeContext | None = None
60
+
61
+
62
+ class VerifierContext(PromptContextBase):
63
+ """Context for Verifier Agent (DoD check)."""
64
+
65
+ modified_files: list[str]
66
+ test_output: str
67
+ coverage_report: str | None = None
File without changes
@@ -0,0 +1,57 @@
1
+ """XML well-formedness + root element validation.
2
+
3
+ Uses defusedxml to protect against XXE, billion laughs, external entities.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Final
9
+
10
+ from defusedxml import ElementTree as DefusedET
11
+ from pydantic import BaseModel, ConfigDict
12
+
13
+ DEFAULT_ROOT: Final[str] = "agent_prompt"
14
+
15
+
16
+ class ValidationOutcome(BaseModel):
17
+ """Result of XML validation."""
18
+
19
+ model_config = ConfigDict(extra="forbid")
20
+
21
+ valid: bool
22
+ root_element: str | None = None
23
+ errors: list[str] = []
24
+ warnings: list[str] = []
25
+
26
+
27
+ def validate_xml(xml: str, *, expected_root: str = DEFAULT_ROOT) -> ValidationOutcome:
28
+ """Validate XML well-formedness and root element.
29
+
30
+ Returns ValidationOutcome with valid=True only if:
31
+ - XML parses cleanly via defusedxml
32
+ - Root element matches `expected_root`
33
+ """
34
+ errors: list[str] = []
35
+ warnings: list[str] = []
36
+ root_element: str | None = None
37
+
38
+ try:
39
+ root = DefusedET.fromstring(xml)
40
+ except DefusedET.ParseError as exc:
41
+ errors.append(f"XML parse error: {exc}")
42
+ return ValidationOutcome(valid=False, root_element=None, errors=errors, warnings=warnings)
43
+ except Exception as exc: # defusedxml may raise EntitiesForbidden, DTDForbidden, ...
44
+ errors.append(f"XML rejected: {type(exc).__name__}: {exc}")
45
+ return ValidationOutcome(valid=False, root_element=None, errors=errors, warnings=warnings)
46
+
47
+ root_element = root.tag
48
+
49
+ if root_element != expected_root:
50
+ errors.append(f"Root element must be <{expected_root}>, got <{root_element}>")
51
+
52
+ return ValidationOutcome(
53
+ valid=not errors,
54
+ root_element=root_element,
55
+ errors=errors,
56
+ warnings=warnings,
57
+ )