Spaces:
Running

File size: 21,341 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
"""Workflows API (Phase 11): compile, validate, versions, dry run, approve, activate, rollback,

templates, manual runs and self-healing proposals.



Roles: members read; managers compile, draft, dry-run, run, roll back and handle proposals;

only owners approve and activate a version.

"""

from __future__ import annotations

import uuid
from typing import Any

from fastapi import APIRouter, Depends, HTTPException, Query, status
from pydantic import BaseModel, Field
from sqlalchemy import cast, func, select
from sqlalchemy.dialects.postgresql import JSONB

from core.agent.runs import Run
from core.api.routes.events import _ingest, dispatcher
from core.api.routes.runs import services
from core.auth.deps import Principal, current_principal, require_role
from core.events.intake import normalize_manual
from core.events.workers import Dispatcher
from core.services import Services
from core.tenancy.models import Role
from core.tools.registry import ToolRegistry
from core.workflows import compiler, versions
from core.workflows.catalog import pack_templates, tenant_registry, tool_catalog
from core.workflows.dryrun import dry_run
from core.workflows.dsl import WorkflowDefinition, describe
from core.workflows.executor import WORKFLOW_INTENT
from core.workflows.healing import apply_patch
from core.workflows.models import Workflow, WorkflowProposal, WorkflowVersion

router = APIRouter(tags=["workflows"])


class CompileIn(BaseModel):
    text: str = Field(min_length=3, max_length=2000)


class ValidateIn(BaseModel):
    definition: dict[str, Any]


class CreateIn(BaseModel):
    text: str | None = Field(default=None, min_length=3, max_length=2000)
    definition: dict[str, Any] | None = None
    template: str | None = Field(default=None, max_length=200)


class VersionIn(BaseModel):
    definition: dict[str, Any] | None = None
    text: str | None = Field(default=None, min_length=3, max_length=2000)
    note: str | None = Field(default=None, max_length=500)


class DryRunIn(BaseModel):
    event: dict[str, Any] | None = Field(
        default=None, description="sample triggering event payload for event/manual triggers"
    )


class RunIn(BaseModel):
    input: dict[str, Any] = Field(default_factory=dict)


# ------------------------------------------------------------------ helpers


def _iso(v: Any) -> Any:
    return v.isoformat() if v is not None and hasattr(v, "isoformat") else v


def workflow_out(wf: Workflow, latest: WorkflowVersion | None = None) -> dict[str, Any]:
    return {
        "id": str(wf.id),
        "key": wf.key,
        "name": wf.name,
        "description": wf.description,
        "status": wf.status,
        "active_version": wf.active_version,
        "source": wf.source,
        "template": wf.template,
        "created_at": _iso(wf.created_at),
        "updated_at": _iso(wf.updated_at),
        "latest_version": (
            {"version": latest.version, "status": latest.status} if latest is not None else None
        ),
    }


def version_out(v: WorkflowVersion) -> dict[str, Any]:
    try:
        plan = describe(WorkflowDefinition.model_validate(v.definition))
    except Exception:
        plan = []
    return {
        "version": v.version,
        "status": v.status,
        "definition": v.definition,
        "definition_hash": v.definition_hash,
        "nl_source": v.nl_source,
        "plan": plan,
        "checks": v.checks,
        "dry_run": v.dry_run,
        "dry_run_at": _iso(v.dry_run_at),
        "dry_run_current": v.dry_run_hash == v.definition_hash,
        "created_by": v.created_by,
        "created_at": _iso(v.created_at),
        "approved_by": str(v.approved_by) if v.approved_by else None,
        "approved_at": _iso(v.approved_at),
        "activated_at": _iso(v.activated_at),
        "deactivated_at": _iso(v.deactivated_at),
        "parent_version": v.parent_version,
        "note": v.note,
    }


def proposal_out(p: WorkflowProposal) -> dict[str, Any]:
    return {
        "id": str(p.id),
        "workflow_id": str(p.workflow_id),
        "version": p.version,
        "run_id": str(p.run_id),
        "step_id": p.step_id,
        "failure_class": p.failure_class,
        "error": p.error,
        "summary": p.summary,
        "patch": p.patch,
        "status": p.status,
        "applied_version": p.applied_version,
        "created_at": _iso(p.created_at),
        "decided_at": _iso(p.decided_at),
    }


def _lifecycle(exc: versions.LifecycleError) -> HTTPException:
    detail: Any = str(exc)
    if exc.report is not None:
        detail = {"message": str(exc), **exc.report.as_dict()}
    return HTTPException(exc.status, detail)


def _planner(svc: Services) -> Any:
    if svc.runtime is None:
        raise HTTPException(status.HTTP_503_SERVICE_UNAVAILABLE, "agent runtime not configured")
    return svc.runtime.models.planner


async def _registry(svc: Services, p: Principal) -> ToolRegistry:
    """Pack tools plus the tenant's runtime tools (Phase 16 imports)."""
    return await tenant_registry(svc.gateway, p.tenant_id)


async def _compile(svc: Services, p: Principal, text: str) -> compiler.CompileResult:
    reg = await _registry(svc, p)
    offered = await compiler.candidate_tools(svc.db, p.tenant_id, reg, text, search=svc.search)
    try:
        return await compiler.compile_nl(text, _planner(svc), reg, offered)
    except LookupError as exc:  # e.g. a scripted model without a response
        raise HTTPException(status.HTTP_502_BAD_GATEWAY, f"planner model: {exc}") from exc


async def _get_version(

    svc: Services, p: Principal, workflow_id: uuid.UUID, version: int

) -> WorkflowVersion:
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        v = (
            await s.execute(
                select(WorkflowVersion).where(
                    WorkflowVersion.workflow_id == workflow_id, WorkflowVersion.version == version
                )
            )
        ).scalar_one_or_none()
    if v is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "version not found")
    return v


def _templates(svc: Services) -> list[dict[str, Any]]:
    return pack_templates(svc.packs, svc.gateway.registry)


# ------------------------------------------------------------------ static routes


@router.get("/workflows")
async def list_workflows(

    p: Principal = Depends(current_principal), svc: Services = Depends(services)

) -> dict[str, Any]:
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        wfs = list(
            (await s.execute(select(Workflow).order_by(Workflow.created_at.desc()))).scalars()
        )
        latest_q = (
            select(WorkflowVersion)
            .distinct(WorkflowVersion.workflow_id)
            .order_by(WorkflowVersion.workflow_id, WorkflowVersion.version.desc())
        )
        latest = {v.workflow_id: v for v in (await s.execute(latest_q)).scalars()}
        pending = (
            await s.execute(
                select(func.count())
                .select_from(WorkflowProposal)
                .where(WorkflowProposal.status == "pending")
            )
        ).scalar_one()
    return {
        "items": [workflow_out(w, latest.get(w.id)) for w in wfs],
        "pending_proposals": int(pending),
    }


@router.get("/workflows/templates")
async def list_templates(

    p: Principal = Depends(current_principal), svc: Services = Depends(services)

) -> list[dict[str, Any]]:
    return _templates(svc)


@router.get("/workflows/tools")
async def list_tools(

    p: Principal = Depends(current_principal), svc: Services = Depends(services)

) -> list[dict[str, Any]]:
    return tool_catalog(await _registry(svc, p))


@router.post("/workflows/compile")
async def compile_workflow(

    body: CompileIn,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    """Natural language -> DSL draft with static-check results. Nothing is saved."""
    res = await _compile(svc, p, body.text)
    out = res.as_dict()
    out["plan"] = describe(res.definition) if res.definition else []
    return out


@router.post("/workflows/validate")
async def validate_workflow(

    body: ValidateIn,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    defn, report = compiler.check(body.definition, await _registry(svc, p))
    return {
        **report.as_dict(),
        "definition": defn.model_dump(mode="json") if defn else None,
        "plan": describe(defn) if defn else [],
    }


@router.get("/workflows/proposals")
async def list_proposals(

    status_: str | None = Query(default="pending", alias="status"),

    p: Principal = Depends(current_principal),

    svc: Services = Depends(services),

) -> list[dict[str, Any]]:
    q = select(WorkflowProposal).order_by(WorkflowProposal.created_at.desc()).limit(200)
    if status_:
        q = q.where(WorkflowProposal.status == status_)
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        return [proposal_out(x) for x in (await s.execute(q)).scalars()]


@router.post("/workflows/proposals/{proposal_id}/apply")
async def apply_proposal(

    proposal_id: uuid.UUID,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    """Turn a proposed fix into a new DRAFT version (it still needs dry run + approval)."""
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        prop = await s.get(WorkflowProposal, proposal_id)
    if prop is None or prop.status != "pending":
        raise HTTPException(status.HTTP_404_NOT_FOUND, "no pending proposal")
    if not prop.patch:
        raise HTTPException(status.HTTP_409_CONFLICT, "this proposal has no definition change")
    base = await _get_version(svc, p, prop.workflow_id, prop.version)
    try:
        fixed = apply_patch(base.definition, prop.patch)
        v = await versions.add_version(
            svc.db,
            p.tenant_id,
            prop.workflow_id,
            fixed,
            await _registry(svc, p),
            actor=p.actor,
            nl_source=base.nl_source,
            note=f"fix: {prop.summary}",
        )
    except versions.LifecycleError as exc:
        raise _lifecycle(exc) from exc
    async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
        prop2 = await s.get(WorkflowProposal, proposal_id)
        if prop2 is not None:
            prop2.status, prop2.applied_version = "applied", v.version
            prop2.decided_by, prop2.decided_at = p.user_id, func.now()
    return version_out(v)


@router.post("/workflows/proposals/{proposal_id}/dismiss")
async def dismiss_proposal(

    proposal_id: uuid.UUID,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    async with svc.db.session(tenant_id=p.tenant_id) as s, s.begin():
        prop = await s.get(WorkflowProposal, proposal_id)
        if prop is None or prop.status != "pending":
            raise HTTPException(status.HTTP_404_NOT_FOUND, "no pending proposal")
        prop.status, prop.decided_by, prop.decided_at = "dismissed", p.user_id, func.now()
    return {"id": str(proposal_id), "status": "dismissed"}


@router.post("/workflows", status_code=status.HTTP_201_CREATED)
async def create_workflow(

    body: CreateIn,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    """Create from natural language (``text``), a ``definition`` or a pack ``template``.

    The first version is a draft; it needs a dry run, an owner's approval and activation."""
    given = [x for x in (body.text, body.definition, body.template) if x]
    if len(given) != 1:
        raise HTTPException(422, "give exactly one of text, definition or template")
    source, template, nl = "json", None, None
    data: Any = body.definition
    if body.text:
        res = await _compile(svc, p, body.text)
        if res.definition is None or not res.report.ok:
            raise HTTPException(422, {"message": "compile failed", **res.as_dict()})
        data, source, nl = res.definition, "nl", body.text
    elif body.template:
        tpl = next((t for t in _templates(svc) if t["id"] == body.template), None)
        if tpl is None:
            raise HTTPException(status.HTTP_404_NOT_FOUND, "unknown template")
        data, source, template, nl = tpl["definition"], "template", tpl["id"], tpl["nl"]
    try:
        wf, v = await versions.create_workflow(
            svc.db,
            p.tenant_id,
            data,
            await _registry(svc, p),
            actor=p.actor,
            user_id=p.user_id,
            nl_source=nl,
            source=source,
            template=template,
        )
    except versions.LifecycleError as exc:
        raise _lifecycle(exc) from exc
    return {**workflow_out(wf, v), "versions": [version_out(v)]}


# ------------------------------------------------------------------ per workflow


@router.get("/workflows/{workflow_id}")
async def get_workflow(

    workflow_id: uuid.UUID,

    p: Principal = Depends(current_principal),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        wf = await s.get(Workflow, workflow_id)
        if wf is None:
            raise HTTPException(status.HTTP_404_NOT_FOUND, "workflow not found")
        vs = list(
            (
                await s.execute(
                    select(WorkflowVersion)
                    .where(WorkflowVersion.workflow_id == workflow_id)
                    .order_by(WorkflowVersion.version.desc())
                )
            ).scalars()
        )
        props = list(
            (
                await s.execute(
                    select(WorkflowProposal)
                    .where(WorkflowProposal.workflow_id == workflow_id)
                    .order_by(WorkflowProposal.created_at.desc())
                    .limit(50)
                )
            ).scalars()
        )
    return {
        **workflow_out(wf, vs[0] if vs else None),
        "versions": [version_out(v) for v in vs],
        "proposals": [proposal_out(x) for x in props],
    }


@router.get("/workflows/{workflow_id}/versions/{version}")
async def get_version(

    workflow_id: uuid.UUID,

    version: int,

    p: Principal = Depends(current_principal),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    return version_out(await _get_version(svc, p, workflow_id, version))


@router.post("/workflows/{workflow_id}/versions", status_code=status.HTTP_201_CREATED)
async def create_version(

    workflow_id: uuid.UUID,

    body: VersionIn,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    """A new immutable draft version (edited JSON/canvas, or re-compiled from text)."""
    if (body.definition is None) == (body.text is None):
        raise HTTPException(422, "give exactly one of definition or text")
    data: Any = body.definition
    nl = None
    if body.text:
        res = await _compile(svc, p, body.text)
        if res.definition is None or not res.report.ok:
            raise HTTPException(422, {"message": "compile failed", **res.as_dict()})
        data, nl = res.definition, body.text
    try:
        v = await versions.add_version(
            svc.db,
            p.tenant_id,
            workflow_id,
            data,
            await _registry(svc, p),
            actor=p.actor,
            nl_source=nl,
            note=body.note,
        )
    except versions.LifecycleError as exc:
        raise _lifecycle(exc) from exc
    return version_out(v)


@router.post("/workflows/{workflow_id}/versions/{version}/dry-run")
async def dry_run_version(

    workflow_id: uuid.UUID,

    version: int,

    body: DryRunIn | None = None,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    v = await _get_version(svc, p, workflow_id, version)
    defn = WorkflowDefinition.model_validate(v.definition)
    event = None
    if body is not None and body.event is not None:
        event = {"type": "sample", "payload": body.event}
    elif defn.trigger.type in ("event", "manual"):
        event = {"type": "sample", "payload": {}}
    report = await dry_run(svc.gateway, p.tenant_id, defn, actor=p.actor, event=event)
    try:
        v = await versions.record_dry_run(svc.db, p.tenant_id, workflow_id, version, report)
    except versions.LifecycleError as exc:
        raise _lifecycle(exc) from exc
    return version_out(v)


@router.post("/workflows/{workflow_id}/versions/{version}/approve")
async def approve_version(

    workflow_id: uuid.UUID,

    version: int,

    p: Principal = Depends(require_role(Role.OWNER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    try:
        v = await versions.approve(svc.db, p.tenant_id, workflow_id, version, p.user_id)
    except versions.LifecycleError as exc:
        raise _lifecycle(exc) from exc
    return version_out(v)


@router.post("/workflows/{workflow_id}/versions/{version}/activate")
async def activate_version(

    workflow_id: uuid.UUID,

    version: int,

    p: Principal = Depends(require_role(Role.OWNER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    try:
        v = await versions.activate(svc.db, p.tenant_id, workflow_id, version)
    except versions.LifecycleError as exc:
        raise _lifecycle(exc) from exc
    return version_out(v)


@router.post("/workflows/{workflow_id}/rollback")
async def rollback_workflow(

    workflow_id: uuid.UUID,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    try:
        v = await versions.rollback(svc.db, p.tenant_id, workflow_id)
    except versions.LifecycleError as exc:
        raise _lifecycle(exc) from exc
    return {"active_version": v.version if v else None, "status": "active" if v else "paused"}


@router.post("/workflows/{workflow_id}/deactivate")
async def deactivate_workflow(

    workflow_id: uuid.UUID,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

) -> dict[str, Any]:
    try:
        await versions.deactivate(svc.db, p.tenant_id, workflow_id)
    except versions.LifecycleError as exc:
        raise _lifecycle(exc) from exc
    return {"active_version": None, "status": "paused"}


@router.post("/workflows/{workflow_id}/run", status_code=status.HTTP_202_ACCEPTED)
async def run_workflow(

    workflow_id: uuid.UUID,

    body: RunIn | None = None,

    p: Principal = Depends(require_role(Role.MANAGER)),

    svc: Services = Depends(services),

    d: Dispatcher = Depends(dispatcher),

) -> dict[str, Any]:
    """Run the ACTIVE version now (a ``workflow.run`` event, dispatched like any other)."""
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        wf = await s.get(Workflow, workflow_id)
    if wf is None:
        raise HTTPException(status.HTTP_404_NOT_FOUND, "workflow not found")
    if wf.status != "active" or wf.active_version is None:
        raise HTTPException(status.HTTP_409_CONFLICT, "workflow has no active version")
    payload = {
        "workflow_id": str(wf.id),
        "version": wf.active_version,
        "trigger": "manual",
        "input": (body.input if body else {}),
        "requested_by": p.actor,
    }
    ne = normalize_manual(WORKFLOW_INTENT, payload=payload)
    recorded = await _ingest(svc, d, p.tenant_id, [ne])
    return {"event_id": str(recorded[0].event_id), "version": wf.active_version}


@router.get("/workflows/{workflow_id}/runs")
async def workflow_runs(

    workflow_id: uuid.UUID,

    limit: int = Query(default=50, ge=1, le=200),

    p: Principal = Depends(current_principal),

    svc: Services = Depends(services),

) -> list[dict[str, Any]]:
    match = cast({"payload": {"workflow_id": str(workflow_id)}}, JSONB)
    async with svc.db.session(tenant_id=p.tenant_id) as s:
        rows = (
            await s.execute(
                select(Run)
                .where(Run.event.op("@>")(match))
                .order_by(Run.started_at.desc())
                .limit(limit)
            )
        ).scalars()
        return [
            {
                "run_id": str(r.id),
                "status": r.status,
                "version": (r.event.get("payload") or {}).get("version"),
                "trigger": (r.event.get("payload") or {}).get("trigger"),
                "output": r.output,
                "error": r.error,
                "started_at": _iso(r.started_at),
                "ended_at": _iso(r.ended_at),
            }
            for r in rows
        ]