Spaces:
Running

File size: 12,849 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
305
306
307
308
309
310
311
312
313
"""Dry run: walk a definition against the tenant's live data with every call as a gateway

preview (validation + Cedar policy + the tool's own ``dry_run``, inside a transaction that is

rolled back). Reads return real rows; writes return the effect they would have. Nothing is

executed, nothing is audited, no approval is created.



The report says, per step and item, whether the call would run automatically, would wait for

a human, or would be denied, and renders that as plain-language lines for the owner.

"""

from __future__ import annotations

import uuid
from typing import Any

from pydantic import ValidationError

from core.gateway.gateway import Gateway, ToolCall
from core.gateway.policy import PolicyOutcome
from core.tools.registry import ToolNotFound
from core.tools.spec import RiskTier, ToolContext, ToolResult, ToolSpec
from core.tools.tenant_tools import ToolUnavailable
from core.workflows import refs
from core.workflows.dsl import Step, WorkflowDefinition, describe
from core.workflows.executor import SIGNOFF_TOOL, is_message_tool, split_args

MAX_PREVIEW_ITEMS = 200  # entries shown per step (all items are still counted)
KEY_ARGS = ("to", "order_number", "template", "amount", "text", "subject", "number", "sku")


def _summary_args(args: dict[str, Any]) -> str:
    keys = [k for k in KEY_ARGS if k in args] or list(args)[:3]
    return ", ".join(f"{k}={args[k]}" for k in keys)


async def _preview(

    gateway: Gateway,

    tenant_id: uuid.UUID,

    actor: str,

    tool: str,

    args: dict[str, Any],

    tainted: bool,

) -> dict[str, Any]:
    from core.gateway.taint import split_taint

    plain, taint = split_taint(args)
    call = ToolCall(
        tenant_id=tenant_id, actor=actor, tool=tool, args=plain, taint=taint, dry_run=True
    )
    try:
        decision, result = await gateway.preview(call)
    except ToolNotFound:
        return {"outcome": "denied", "reason": f"unknown tool {tool}", "args": plain}
    except ValidationError as exc:
        msg = "; ".join(str(e.get("msg")) for e in exc.errors(include_url=False))
        return {"outcome": "error", "reason": f"invalid arguments: {msg}", "args": plain}
    spec = (await gateway.resolve_tool(tenant_id, tool)).spec
    if result is None and spec.risk_tier == RiskTier.T0_READ:
        # Reads without a dry-run mode: run the read itself (no side effects, rolled back),
        # so later steps can reference real data.
        result = await _read(gateway, call)
    entry: dict[str, Any] = {"args": plain, "effect": result.data if result else None}
    if decision.outcome is PolicyOutcome.DENY:
        entry.update(outcome="denied", reason="; ".join(decision.errors or decision.reasons))
    elif result is not None and not result.ok:
        entry.update(outcome="error", reason=result.error)
    elif decision.outcome is PolicyOutcome.REVIEW or spec.risk_tier >= RiskTier.T3_CRITICAL:
        entry.update(
            outcome="needs_approval",
            reason=", ".join(decision.reasons) or "no policy permits it automatically",
        )
    elif any(taint.values()) and spec.sensitive_args:
        entry.update(outcome="needs_approval", reason="untrusted value in a sensitive argument")
    else:
        entry.update(outcome="would_execute", reason=", ".join(decision.reasons) or None)
    entry["tier"] = int(spec.risk_tier)
    return entry


async def _read(gateway: Gateway, call: ToolCall) -> ToolResult:
    tool = await gateway.resolve_tool(call.tenant_id, call.tool)
    async with gateway.db.session(tenant_id=call.tenant_id) as s, s.begin():
        ctx = ToolContext(
            tenant_id=call.tenant_id, actor=call.actor, run_id=None, session=s, dry_run=True
        )
        try:
            result = await tool.handler(tool.spec.input_model.model_validate(call.args), ctx)
        except Exception as exc:
            result = ToolResult(ok=False, error=f"{type(exc).__name__}: {exc}")
        await s.rollback()
    return result


def _data_of(entry: dict[str, Any], spec_tier: int) -> dict[str, Any]:
    """What later steps see: a read's real data; a write's previewed effect."""
    eff = entry.get("effect")
    return dict(eff) if isinstance(eff, dict) else {}


async def dry_run(

    gateway: Gateway,

    tenant_id: uuid.UUID,

    defn: WorkflowDefinition,

    *,

    actor: str = "workflow:dry-run",

    event: dict[str, Any] | None = None,

    fire_time: str | None = None,

) -> dict[str, Any]:
    scope = refs.Scope(
        event=event,
        trigger={"type": defn.trigger.type, "fire_time": fire_time},
        workflow={"id": defn.id, "key": defn.id, "version": defn.version, "name": defn.name},
    )
    steps_out: list[dict[str, Any]] = []
    totals = {"would_execute": 0, "needs_approval": 0, "denied": 0, "error": 0, "skipped": 0}
    messages = 0
    stopped: str | None = None
    for step in defn.steps:
        if stopped:
            steps_out.append({"id": step.id, "kind": step.kind, "status": "not_reached"})
            continue
        try:
            entry = await _dry_step(gateway, tenant_id, actor, defn, step, scope)
        except refs.RefError as exc:
            entry = {
                "id": step.id,
                "kind": step.kind,
                "status": "error",
                "reason": f"reference error: {exc}",
                "items": [],
            }
        for it in entry.get("items", []):
            totals[it["outcome"]] = totals.get(it["outcome"], 0) + 1
            if it["outcome"] in ("would_execute", "needs_approval") and it.get("message"):
                messages += 1
        if entry.get("status") == "error" and not entry.get("items"):
            totals["error"] += 1
        steps_out.append(entry)
        if entry.get("status") in ("error", "denied") and step.on_error == "stop":
            stopped = step.id
    po = defn.policy_overrides
    problems: list[str] = []
    if messages > po.max_messages:
        problems.append(f"{messages} messages exceed max_messages {po.max_messages}")
    if stopped:
        problems.append(f"stops at step {stopped}")
    ok = not problems and totals["denied"] == 0 and totals["error"] == 0
    return {
        "ok": ok,
        "problems": problems,
        "totals": totals,
        "messages": messages,
        "steps": steps_out,
        "lines": _lines(defn, steps_out),
        "plan": describe(defn),
        "definition_hash": defn.content_hash(),
    }


async def _dry_step(

    gateway: Gateway,

    tenant_id: uuid.UUID,

    actor: str,

    defn: WorkflowDefinition,

    step: Step,

    scope: refs.Scope,

) -> dict[str, Any]:
    base: dict[str, Any] = {"id": step.id, "kind": step.kind, "tool": step.tool}
    if step.kind == "wait":
        assert step.wait is not None
        return {
            **base,
            "status": "wait",
            "items": [],
            "summary": f"would wait {step.wait.seconds}s, then continue",
        }
    if step.kind == "approval":
        assert step.approval is not None
        if not refs.all_hold(step.when, scope):
            return {**base, "status": "skipped", "items": [], "summary": "skipped (condition)"}
        text, _ = refs.render(step.approval.summary, scope)
        scope.steps[step.id] = {"signed_off": True}
        return {
            **base,
            "status": "needs_approval",
            "tool": SIGNOFF_TOOL,
            "items": [],
            "summary": f"would ask a human to sign off: {text}",
        }
    try:
        spec: ToolSpec | None = (await gateway.resolve_tool(tenant_id, str(step.tool))).spec
    except (ToolNotFound, ToolUnavailable):
        spec = None
    if spec is None:
        return {**base, "status": "denied", "items": [], "reason": f"unknown tool {step.tool}"}
    signoff = step.requires_approval or spec.name in defn.policy_overrides.require_approval_for
    if step.for_each is None:
        if not refs.all_hold(step.when, scope):
            return {**base, "status": "skipped", "items": [], "summary": "skipped (condition)"}
        args, tainted = split_args(step.args, scope)
        e = await _preview(gateway, tenant_id, actor, spec.name, args, tainted)
        e["message"] = is_message_tool(spec)
        scope.steps[step.id] = _data_of(e, int(spec.risk_tier))
        return {
            **base,
            "status": e["outcome"],
            "items": [e],
            "signoff": signoff,
            "summary": _step_summary(step, [e], signoff),
        }
    items, tainted = refs.resolve(step.for_each, scope)
    if items is None:
        items = []
    if not isinstance(items, list):
        return {
            **base,
            "status": "error",
            "items": [],
            "reason": f"for_each {step.for_each} is not a list",
        }
    cap = min(step.max_items or 10**9, defn.policy_overrides.max_items_per_step)
    if len(items) > cap:
        return {
            **base,
            "status": "denied",
            "items": [],
            "reason": f"{len(items)} items exceed max_items {cap}",
        }
    entries: list[dict[str, Any]] = []
    results: list[dict[str, Any]] = []
    for i, item in enumerate(items):
        iscope = scope.with_item(item, i, tainted)
        if not refs.all_hold(step.when, iscope):
            results.append({"item": item, "status": "skipped"})
            continue
        args, t = split_args(step.args, iscope)
        e = await _preview(gateway, tenant_id, actor, spec.name, args, t)
        e["index"], e["message"] = i, is_message_tool(spec)
        entries.append(e)
        ok = e["outcome"] in ("would_execute", "needs_approval")
        results.append(
            {
                "item": item,
                "status": e["outcome"],
                "data": _data_of(e, int(spec.risk_tier)) if ok else None,
            }
        )
    scope.steps[step.id] = {
        "results": results,
        "count": len(items),
        "done": sum(1 for r in results if r["status"] == "would_execute"),
    }
    worst = "skipped" if not entries else _worst([e["outcome"] for e in entries])
    if any(e["outcome"] in ("denied", "error") for e in entries) and step.on_error == "continue":
        worst = "partial"
    return {
        **base,
        "status": worst,
        "items": entries[:MAX_PREVIEW_ITEMS],
        "count": len(items),
        "selected": len(entries),
        "signoff": signoff,
        "summary": _step_summary(step, entries, signoff, total=len(items)),
    }


_RANK = {"error": 4, "denied": 3, "needs_approval": 2, "would_execute": 1, "skipped": 0}


def _worst(outcomes: list[str]) -> str:
    return max(outcomes, key=lambda o: _RANK.get(o, 0))


def _step_summary(

    step: Step, entries: list[dict[str, Any]], signoff: bool, total: int | None = None

) -> str:
    n = len(entries)
    auto = sum(1 for e in entries if e["outcome"] == "would_execute")
    review = sum(1 for e in entries if e["outcome"] == "needs_approval")
    bad = n - auto - review
    head = f"{step.tool} x{n}" + (f" (of {total} items)" if total is not None else "")
    parts = [f"{auto} automatic", f"{review} need approval"]
    if bad:
        parts.append(f"{bad} denied/failed")
    if signoff:
        parts.append("after a human sign-off")
    return f"{head}: " + ", ".join(parts)


def _lines(defn: WorkflowDefinition, steps: list[dict[str, Any]]) -> list[str]:
    """Human-readable diff: one line per step, then one per would-be call."""
    out: list[str] = []
    for s in steps:
        if s.get("status") == "not_reached":
            out.append(f"[{s['id']}] not reached")
            continue
        out.append(f"[{s['id']}] {s.get('summary') or s.get('reason') or s.get('status')}")
        if s.get("reason") and s.get("summary"):
            out.append(f"    ! {s['reason']}")
        for e in s.get("items", []):
            if e.get("tier", 0) == 0 and e["outcome"] == "would_execute":
                eff = e.get("effect") or {}
                size = next((f"{len(v)} {k}" for k, v in eff.items() if isinstance(v, list)), "")
                out.append(f"    read {_summary_args(e['args'])}" + (f" -> {size}" if size else ""))
                continue
            mark = {"would_execute": "+", "needs_approval": "?", "denied": "x", "error": "x"}.get(
                e["outcome"], " "
            )
            line = f"    {mark} {s.get('tool')}({_summary_args(e['args'])})"
            if e["outcome"] != "would_execute":
                line += f"  [{e['outcome']}: {e.get('reason')}]"
            out.append(line)
    return out