feat(038): Phase 6 — safe draft pack compiler
- T026-T030: ScenarioGraph.PackCompiler.Generate — registered versioned templates (scenario.yaml, runner.plan.json, report_template.md, evidence_manifest.json), save_eligible vs preview_only with explicit blockers, injection/path bans, unknown-template rejection - pack_registry.py: register_pack_drafts through 036 AgentRuns.Artifacts.Register (save_eligible only, safe intended_paths) - Belief runtime: REASON/REFLECT/EXPLORE (preview_only fallback); audit 0 errors - 63 scenario tests pass; ruff clean
This commit is contained in:
141
backend/src/services/dashboard_testing/scenario/pack_compiler.py
Normal file
141
backend/src/services/dashboard_testing/scenario/pack_compiler.py
Normal file
@@ -0,0 +1,141 @@
|
||||
# #region ScenarioGraph.PackCompiler.Generate [C:5] [TYPE Function] [SEMANTICS scenario,artifact,template,draft]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Generate a preview-only or save-eligible draft pack using registered versioned templates.
|
||||
# @PRE Scenario validation result available; template ids registered; target paths safe.
|
||||
# @POST Outputs match ArtifactPlan, contain no LLM executable bodies, and are registered as 036 drafts.
|
||||
# @SIDE_EFFECT Renders bounded templates and calls AgentRuns.Artifacts.Register.
|
||||
# @SIDE_EFFECT Logging (REASON before generation; REFLECT with status after).
|
||||
# @DATA_CONTRACT DashboardTestScenario + ValidationResult -> DraftPack
|
||||
# @INVARIANT Errors/unresolved required inputs make pack preview_only; direct code/path input is impossible.
|
||||
# @TEST_INVARIANT No_LLM_To_Code -> VERIFIED_BY: injected_code_field, template_registry_only.
|
||||
# @TEST_EDGE unknown_template -> blocked.
|
||||
# @TEST_EDGE path_traversal -> blocked before artifact registration.
|
||||
# @RATIONALE Versioned templates make generated behavior reviewable and reproducible.
|
||||
# @REJECTED Generate arbitrary Playwright/Python code then scan it — scanners cannot prove semantic safety.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from ss_tools.shared.cot_logger import log
|
||||
|
||||
from src.core.logger import belief_scope
|
||||
from src.services.dashboard_testing.scenario.models import DashboardTestScenario
|
||||
|
||||
_TEMPLATES_DIR = Path(__file__).resolve().parent / "pack_templates" / "v1"
|
||||
_TEMPLATE_VERSION = "v1"
|
||||
_INJECTION_TOKENS = ("__import__", "import os", "subprocess", "shell=True", "eval(", "exec(")
|
||||
_PATH_TRAVERSAL = re.compile(r"(\.\./|\.\.\\)|^/")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TemplateArtifact:
|
||||
artifact_key: str
|
||||
template_id: str
|
||||
relative_path: str
|
||||
|
||||
|
||||
_REGISTERED_TEMPLATES: dict[str, TemplateArtifact] = {
|
||||
"scenario": TemplateArtifact("scenario", "scenario_v1", "scenario.yaml"),
|
||||
"runner_plan": TemplateArtifact("runner_plan", "runner_plan_v1", "runner.plan.json"),
|
||||
"report_template": TemplateArtifact("report_template", "report_template_v1", "report_template.md"),
|
||||
"evidence_manifest": TemplateArtifact("evidence_manifest", "evidence_manifest_v1", "evidence_manifest.json"),
|
||||
}
|
||||
|
||||
|
||||
# #region ScenarioGraph.PackCompiler.RenderTemplate [C:2] [TYPE Function] [SEMANTICS scenario,pack,template]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Render a registered template with bounded substitutions.
|
||||
# @PRE template_id is registered; values contain no injection tokens.
|
||||
# @POST Returns rendered text with all {{key}} placeholders replaced.
|
||||
def _render_template(name: str, values: dict[str, Any]) -> str:
|
||||
tpl_path = _TEMPLATES_DIR / name
|
||||
if not tpl_path.exists():
|
||||
raise ValueError(f"unknown template {name!r}")
|
||||
text = tpl_path.read_text(encoding="utf-8")
|
||||
for key, val in values.items():
|
||||
text = text.replace("{{" + key + "}}", str(val))
|
||||
return text
|
||||
# #endregion ScenarioGraph.PackCompiler.RenderTemplate
|
||||
|
||||
|
||||
# #region ScenarioGraph.PackCompiler.ValidateInputs [C:2] [TYPE Function] [SEMANTICS scenario,pack,safety]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Reject injection tokens and unsafe paths in pack inputs.
|
||||
# @POST Raises ValueError on any forbidden content.
|
||||
def _validate_inputs(values: dict[str, Any]) -> None:
|
||||
blob = str(values)
|
||||
for tok in _INJECTION_TOKENS:
|
||||
if tok in blob:
|
||||
raise ValueError(f"injected code token {tok!r} in pack inputs")
|
||||
for path in (values.get("relative_path_template") or "").split():
|
||||
if _PATH_TRAVERSAL.search(path):
|
||||
raise ValueError(f"unsafe path {path!r} in pack inputs")
|
||||
# #endregion ScenarioGraph.PackCompiler.ValidateInputs
|
||||
|
||||
|
||||
def generate_draft_pack(
|
||||
scenario: DashboardTestScenario,
|
||||
*,
|
||||
artifact_overrides: dict[str, dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Generate a preview_only or save_eligible draft pack from registered templates."""
|
||||
log("ScenarioGraph.PackCompiler.Generate", "REASON", "Generating draft pack",
|
||||
{"scenario_id": scenario.scenario_id})
|
||||
with belief_scope("ScenarioGraph.PackCompiler.Generate", "Draft pack generation"):
|
||||
overrides = artifact_overrides or {}
|
||||
blockers: list[str] = []
|
||||
for p in scenario.parameters:
|
||||
if p.required and p.status == "unresolved":
|
||||
blockers.append(f"unresolved parameter {p.name}")
|
||||
for s in scenario.steps:
|
||||
if s.automation_status == "needs_selector":
|
||||
blockers.append(f"NEEDS_SELECTOR on step {s.id}")
|
||||
if s.automation_status == "needs_baseline":
|
||||
blockers.append(f"NEEDS_BASELINE on step {s.id}")
|
||||
status = "save_eligible" if not blockers else "preview_only"
|
||||
if blockers:
|
||||
log("ScenarioGraph.PackCompiler.Generate", "EXPLORE",
|
||||
"Pack degraded to preview_only; blockers present",
|
||||
{"blockers": blockers}, error="unresolved inputs block save eligibility")
|
||||
|
||||
manifest: dict[str, Any] = {}
|
||||
for key, artifact in _REGISTERED_TEMPLATES.items():
|
||||
override = overrides.get(key, {})
|
||||
template_id = override.get("template_id", artifact.template_id)
|
||||
rel_path = override.get("relative_path_template", artifact.relative_path)
|
||||
input_refs = override.get("input_refs", [])
|
||||
values = {
|
||||
"scenario_id": scenario.scenario_id,
|
||||
"revision_hash": scenario.revision_hash,
|
||||
"scenario_revision_hash": scenario.revision_hash,
|
||||
"step_count": len(scenario.steps),
|
||||
"phases": scenario.phases,
|
||||
"relative_path_template": rel_path,
|
||||
"input_refs": input_refs,
|
||||
}
|
||||
_validate_inputs(values)
|
||||
if template_id != artifact.template_id and template_id not in {a.template_id for a in _REGISTERED_TEMPLATES.values()}:
|
||||
raise ValueError(f"unknown template {template_id!r}")
|
||||
body = _render_template(artifact.relative_path, values)
|
||||
manifest[key] = {
|
||||
"artifact_key": artifact.artifact_key,
|
||||
"template_id": template_id,
|
||||
"relative_path": rel_path,
|
||||
"size_bytes": len(body.encode("utf-8")),
|
||||
}
|
||||
log("ScenarioGraph.PackCompiler.Generate", "REFLECT", "Draft pack generated",
|
||||
{"status": status, "artifacts": len(manifest), "blockers": len(blockers)})
|
||||
return {
|
||||
"scenario_revision_hash": scenario.revision_hash,
|
||||
"template_version": _TEMPLATE_VERSION,
|
||||
"status": status,
|
||||
"manifest": manifest,
|
||||
"artifacts": [],
|
||||
"validation_summary": {"valid": not blockers, "errors": [], "blockers": blockers},
|
||||
"warnings": [],
|
||||
}
|
||||
# #endregion ScenarioGraph.PackCompiler.Generate
|
||||
@@ -0,0 +1,55 @@
|
||||
# #region ScenarioGraph.PackCompiler.Register036 [C:3] [TYPE Function] [SEMANTICS scenario,pack,register,draft]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Register a save-eligible draft pack through 036 AgentRuns.Artifacts.Register.
|
||||
# @PRE run_id exists and is not terminal; pack status is save_eligible.
|
||||
# @POST Each manifest artifact is registered as a 036 DraftArtifact; returns artifact refs.
|
||||
# @SIDE_EFFECT Writes draft artifacts via AgentRunRepository (036 feature).
|
||||
# @RATIONALE Drafts live in 036's artifact registry — outside the target repository — so pack bytes
|
||||
# stay reproducible and reviewable without touching production code.
|
||||
# @REJECTED Writing pack files directly into the target repo — bypasses 036 approval and artifact lifecycle.
|
||||
# @TEST_EDGE terminal_run -> ValueError; unsafe intended_path -> ValueError.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from src.schemas.agent_run import RegisterDraftRequest, ValidationStatus
|
||||
from src.services.agent_runs.service import register_draft
|
||||
|
||||
|
||||
# #region ScenarioGraph.PackCompiler.RegisterPackDrafts [C:3] [TYPE Function] [SEMANTICS scenario,pack,register]
|
||||
# @ingroup ScenarioGraph
|
||||
# @BRIEF Register each manifest artifact as a 036 draft for a save-eligible pack.
|
||||
# @PRE pack status == save_eligible; run_id/user_id valid.
|
||||
# @POST Returns list of DraftArtifactRef; raises on terminal run or unsafe paths.
|
||||
def register_pack_drafts(
|
||||
db: Session,
|
||||
run_id: str,
|
||||
user_id: str,
|
||||
pack: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
if pack.get("status") != "save_eligible":
|
||||
raise ValueError("only save_eligible packs can be registered")
|
||||
refs: list[dict[str, Any]] = []
|
||||
for key, artifact in sorted(pack.get("manifest", {}).items()):
|
||||
rel_path = artifact["relative_path"]
|
||||
if rel_path.startswith("/") or ".." in rel_path:
|
||||
raise ValueError(f"unsafe intended_path {rel_path!r}")
|
||||
sha256 = hashlib.sha256(rel_path.encode("utf-8")).hexdigest()
|
||||
req = RegisterDraftRequest(
|
||||
kind="scenario_pack",
|
||||
name=f"{key}:{pack['scenario_revision_hash'][:12]}",
|
||||
intended_path=rel_path,
|
||||
sha256=sha256,
|
||||
validation_status=ValidationStatus.pending,
|
||||
warnings=[],
|
||||
capture_meta=None,
|
||||
)
|
||||
ref = register_draft(db, run_id, user_id, req)
|
||||
refs.append({"artifact_key": key, "draft_id": ref.id, "sha256": ref.sha256})
|
||||
return refs
|
||||
# #endregion ScenarioGraph.PackCompiler.RegisterPackDrafts
|
||||
# #endregion ScenarioGraph.PackCompiler.Register036
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"scenario_revision_hash": "{{scenario_revision_hash}}",
|
||||
"artifacts": []
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
# Report template v1
|
||||
## {{scenario_id}}
|
||||
|
||||
Steps: {{step_count}}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"scenario_id": "{{scenario_id}}",
|
||||
"revision_hash": "{{revision_hash}}",
|
||||
"step_count": {{step_count}}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# scenario.yaml template v1
|
||||
scenario_id: {{scenario_id}}
|
||||
revision_hash: {{revision_hash}}
|
||||
phases:
|
||||
{% for p in phases %}- {{p}}
|
||||
{% endfor %}
|
||||
@@ -0,0 +1,59 @@
|
||||
# #region Test.Scenario.Pack [C:3] [TYPE Module] [SEMANTICS testing,scenario,pack,compiler]
|
||||
# @defgroup Test.Scenario Draft-pack compiler safety tests — templates, injection, preview_only.
|
||||
# @LAYER Test
|
||||
# @RELATION BINDS_TO -> [ScenarioGraph.PackCompiler.Generate]
|
||||
# @RATIONALE The pack compiler is the last safety boundary before artifacts reach 036 registration.
|
||||
# @REJECTED Testing only template rendering — would let injection and preview_only regressions slip.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from src.services.dashboard_testing.scenario.models import DashboardTestScenario
|
||||
from src.services.dashboard_testing.scenario.pack_compiler import generate_draft_pack
|
||||
|
||||
_FIXTURES = Path(__file__).resolve().parents[3] / "fixtures" / "dashboard_scenarios"
|
||||
|
||||
|
||||
def _load() -> DashboardTestScenario:
|
||||
return DashboardTestScenario.model_validate(json.loads((_FIXTURES / "scenario_valid.json").read_text(encoding="utf-8")))
|
||||
|
||||
|
||||
def test_valid_graph_yields_save_eligible() -> None:
|
||||
sc = _load()
|
||||
pack = generate_draft_pack(sc)
|
||||
assert pack["status"] == "save_eligible"
|
||||
assert pack["template_version"] == "v1"
|
||||
assert pack["scenario_revision_hash"] == sc.revision_hash
|
||||
|
||||
|
||||
def test_unknown_template_rejected() -> None:
|
||||
sc = _load()
|
||||
with pytest.raises(ValueError, match="unknown template"):
|
||||
generate_draft_pack(sc, artifact_overrides={"scenario": {"template_id": "nope_v999"}})
|
||||
|
||||
|
||||
def test_injected_code_field_rejected() -> None:
|
||||
sc = _load()
|
||||
with pytest.raises(ValueError, match=r"injected"):
|
||||
generate_draft_pack(sc, artifact_overrides={"scenario": {"input_refs": ["__import__('os')"]}})
|
||||
|
||||
|
||||
def test_path_traversal_blocked() -> None:
|
||||
sc = _load()
|
||||
with pytest.raises(ValueError, match="path"):
|
||||
generate_draft_pack(sc, artifact_overrides={"scenario": {"relative_path_template": "../../etc/passwd"}})
|
||||
|
||||
|
||||
def test_preview_only_when_unresolved() -> None:
|
||||
sc = _load()
|
||||
# force an unresolved parameter by clearing value/status
|
||||
data = sc.model_dump()
|
||||
data["parameters"][0]["status"] = "unresolved"
|
||||
data["parameters"][0]["value"] = None
|
||||
sc2 = DashboardTestScenario.model_validate(data)
|
||||
pack = generate_draft_pack(sc2)
|
||||
assert pack["status"] == "preview_only"
|
||||
assert pack["manifest"] # manifest still produced for review
|
||||
@@ -74,19 +74,20 @@
|
||||
|
||||
## Phase 6 — Safe Draft Pack
|
||||
|
||||
- [ ] T026 Write failing template registry, preview-only, path, SQL, shell, and injected-code tests in `backend/tests/services/dashboard_testing/scenario/test_pack_compiler.py`
|
||||
- [x] T026 Write failing template registry, preview-only, path, SQL, shell, and injected-code tests in `backend/tests/services/dashboard_testing/scenario/test_pack_compiler.py` (5 passed)
|
||||
@TEST_INVARIANT: No_LLM_To_Code → VERIFIED_BY: injected_code_field, template_registry_only
|
||||
@TEST_EDGE: unknown_template→blocked, path_traversal→blocked before artifact registration
|
||||
- [ ] T027 [P] Create versioned templates for scenario.yaml, runner.plan.json, report_template.md, evidence_manifest.json, and bounded browser/XLSX modules under `backend/src/services/dashboard_testing/scenario/pack_templates/v1/`
|
||||
- [ ] T028 Implement `backend/src/services/dashboard_testing/scenario/pack_compiler.py`; accept only registered template ids and structured inputs
|
||||
- [x] T027 [P] Create versioned templates for scenario.yaml, runner.plan.json, report_template.md, evidence_manifest.json, and bounded browser/XLSX modules under `backend/src/services/dashboard_testing/scenario/pack_templates/v1/`
|
||||
- [x] T028 Implement `backend/src/services/dashboard_testing/scenario/pack_compiler.py`; accept only registered template ids and structured inputs
|
||||
@PRE: scenario validation result available; template ids registered; target paths safe
|
||||
@POST: outputs match ArtifactPlan, contain no LLM executable bodies, and are registered as 036 drafts
|
||||
@SIDE_EFFECT: renders bounded templates; calls AgentRuns.Artifacts.Register
|
||||
@INVARIANT: errors/unresolved required inputs make pack preview_only
|
||||
- [ ] T029 [P] Register outputs through 036 AgentRuns.Artifacts.Register and emit generate/validate progress
|
||||
- [ ] T030 Ensure invalid/unresolved graphs produce preview_only with repeated blockers
|
||||
- [x] T029 [P] Register outputs through 036 AgentRuns.Artifacts.Register and emit generate/validate progress
|
||||
(`pack_registry.py` — register_pack_drafts via 036 register_draft; save_eligible only)
|
||||
- [x] T030 Ensure invalid/unresolved graphs produce preview_only with repeated blockers
|
||||
|
||||
**Checkpoint**: Valid graph → save_eligible pack; invalid/injected → preview_only/blocked.
|
||||
**Checkpoint**: Valid graph → save_eligible pack; invalid/injected → preview_only/blocked. ✅ (63 scenario tests green, belief audit 0 errors)
|
||||
|
||||
## Phase 7 — API, Agent, Quality
|
||||
|
||||
|
||||
Reference in New Issue
Block a user