dap-engine 0.3.0__py3-none-any.whl

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.
Files changed (48) hide show
  1. dap_engine/__init__.py +3 -0
  2. dap_engine/__main__.py +80 -0
  3. dap_engine/api/__init__.py +0 -0
  4. dap_engine/api/agents.py +546 -0
  5. dap_engine/api/deps.py +60 -0
  6. dap_engine/api/health.py +20 -0
  7. dap_engine/api/pipelines.py +428 -0
  8. dap_engine/api/projects.py +191 -0
  9. dap_engine/api/runs.py +694 -0
  10. dap_engine/api/runtimes.py +29 -0
  11. dap_engine/api/schemas.py +331 -0
  12. dap_engine/api/settings.py +288 -0
  13. dap_engine/app.py +438 -0
  14. dap_engine/auth/__init__.py +23 -0
  15. dap_engine/auth/admin_users_routes.py +134 -0
  16. dap_engine/auth/api_token_routes.py +345 -0
  17. dap_engine/auth/api_tokens.py +147 -0
  18. dap_engine/auth/audit.py +91 -0
  19. dap_engine/auth/audit_routes.py +125 -0
  20. dap_engine/auth/db.py +135 -0
  21. dap_engine/auth/oauth.py +41 -0
  22. dap_engine/auth/policies.py +64 -0
  23. dap_engine/auth/schemas.py +37 -0
  24. dap_engine/auth/users.py +400 -0
  25. dap_engine/contracts.py +205 -0
  26. dap_engine/execution/__init__.py +30 -0
  27. dap_engine/execution/conditions.py +87 -0
  28. dap_engine/execution/node_executor.py +363 -0
  29. dap_engine/execution/output_parser.py +162 -0
  30. dap_engine/execution/run_orchestrator.py +213 -0
  31. dap_engine/execution/run_registry.py +158 -0
  32. dap_engine/execution/runner.py +422 -0
  33. dap_engine/execution/validator.py +580 -0
  34. dap_engine/persistence/__init__.py +0 -0
  35. dap_engine/persistence/_common.py +24 -0
  36. dap_engine/persistence/agents.py +410 -0
  37. dap_engine/persistence/db.py +179 -0
  38. dap_engine/persistence/migrations.py +739 -0
  39. dap_engine/persistence/models.py +569 -0
  40. dap_engine/persistence/pipelines.py +328 -0
  41. dap_engine/persistence/projects.py +256 -0
  42. dap_engine/persistence/repository.py +101 -0
  43. dap_engine/persistence/runs.py +482 -0
  44. dap_engine/py.typed +0 -0
  45. dap_engine-0.3.0.dist-info/METADATA +49 -0
  46. dap_engine-0.3.0.dist-info/RECORD +48 -0
  47. dap_engine-0.3.0.dist-info/WHEEL +4 -0
  48. dap_engine-0.3.0.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,569 @@
1
+ """SQLAlchemy 2.0 ORM models.
2
+
3
+ Versioning model:
4
+ - `agents` and `pipelines` hold stable identity and a pointer to the current version.
5
+ - `agent_versions` and `pipeline_versions` hold the full immutable configuration per
6
+ version. Updating an agent/pipeline always creates a new version row; previous
7
+ versions remain unchanged so runs can reference exact configurations forever.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import uuid
13
+ from datetime import UTC, datetime
14
+ from typing import Any
15
+
16
+ from fastapi_users.db import SQLAlchemyBaseOAuthAccountTableUUID, SQLAlchemyBaseUserTableUUID
17
+ from fastapi_users_db_sqlalchemy.generics import GUID
18
+ from sqlalchemy import (
19
+ JSON,
20
+ DateTime,
21
+ Float,
22
+ ForeignKey,
23
+ Index,
24
+ Integer,
25
+ String,
26
+ Text,
27
+ UniqueConstraint,
28
+ )
29
+ from sqlalchemy.dialects.postgresql import JSONB
30
+ from sqlalchemy.orm import DeclarativeBase, Mapped, declared_attr, mapped_column, relationship
31
+
32
+
33
+ class Base(DeclarativeBase):
34
+ pass
35
+
36
+
37
+ # ---------------------------------------------------------------------------
38
+ # Users (auth — v0.3, see #299)
39
+ # ---------------------------------------------------------------------------
40
+
41
+
42
+ class UserORM(SQLAlchemyBaseUserTableUUID, Base):
43
+ """Authenticated user.
44
+
45
+ Inherits the ``id`` (UUID), ``email`` (unique), ``hashed_password``,
46
+ ``is_active``, ``is_superuser``, ``is_verified`` columns from
47
+ ``SQLAlchemyBaseUserTableUUID``. We extend with audit timestamps and
48
+ a soft-delete column.
49
+
50
+ Naming note: the fastapi-users default ``__tablename__`` is ``user``
51
+ (singular). We override to ``users`` to match the rest of the schema
52
+ (``agents``, ``pipelines``, ``runs``, ``projects``, …).
53
+
54
+ Soft-delete: the ``UserManager.delete`` override (in
55
+ ``auth/users.py``) writes ``deleted_at`` + flips ``is_active=False``
56
+ instead of issuing ``DELETE FROM users``. This keeps the row alive
57
+ so any future FK pointing at the user — e.g. the ``user_id`` column
58
+ that lands on ``agents`` / ``pipelines`` / ``projects`` / ``runs`` in
59
+ a follow-up sub-PR — remains valid without cascading data loss.
60
+ Hard delete (admin-initiated, GDPR right-to-erasure) is exposed
61
+ separately in Phase C/E.
62
+ """
63
+
64
+ __tablename__ = "users"
65
+
66
+ # `default` runs Python-side on ORM `User(...)` construction (which is
67
+ # how fastapi-users creates rows). `onupdate` keeps `updated_at` fresh
68
+ # on subsequent UPDATEs without callers having to remember.
69
+ created_at: Mapped[datetime] = mapped_column(
70
+ DateTime(timezone=True),
71
+ nullable=False,
72
+ default=lambda: datetime.now(UTC),
73
+ )
74
+ updated_at: Mapped[datetime] = mapped_column(
75
+ DateTime(timezone=True),
76
+ nullable=False,
77
+ default=lambda: datetime.now(UTC),
78
+ onupdate=lambda: datetime.now(UTC),
79
+ )
80
+ deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
81
+ last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
82
+
83
+ # Linked OAuth identities. Eager-loaded ("joined") because fastapi-users'
84
+ # SQLAlchemyUserDatabase reads this list on every login lookup; lazy
85
+ # loading would emit a separate SELECT per request.
86
+ oauth_accounts: Mapped[list[OAuthAccountORM]] = relationship(
87
+ "OAuthAccountORM",
88
+ lazy="joined",
89
+ cascade="all, delete-orphan",
90
+ )
91
+
92
+
93
+ class ApiTokenORM(Base):
94
+ """Long-lived API token for CLI / scripts (#299, sub-A3).
95
+
96
+ Tokens are opaque random strings (``dap_<43-char-base64>``) issued
97
+ via ``POST /auth/api-tokens``. The raw token is shown to the caller
98
+ exactly once at creation time; the database stores only the SHA-256
99
+ hash and the first 8 chars (``token_prefix``) for indexed lookup.
100
+
101
+ Why SHA-256 instead of bcrypt/argon2: the token has 256 bits of
102
+ entropy, so brute-force is infeasible regardless of hash speed; a
103
+ cryptographic but cheap hash keeps every authenticated request
104
+ inexpensive. (Password hashes use slow KDFs because passwords have
105
+ far less entropy and offline cracking is the realistic threat —
106
+ that calculus doesn't apply here.)
107
+
108
+ Lifecycle:
109
+ - ``revoked_at`` set on ``DELETE /auth/api-tokens/{id}`` — the
110
+ verify path treats any non-NULL value as "rejected"
111
+ - ``expires_at`` optional. NULL means "no expiry"; a past timestamp
112
+ is treated as revoked
113
+ - ``last_used_at`` is touched on every successful auth so admins
114
+ can spot stale tokens; not on the hot path under a tx (we update
115
+ it best-effort and tolerate races)
116
+ """
117
+
118
+ __tablename__ = "api_tokens"
119
+ __table_args__ = (
120
+ # Lookup happens on every authenticated CLI call: select by
121
+ # prefix (cheap, indexed), then SHA-256 verify the candidates.
122
+ # Almost always one match per prefix; the verify step exists
123
+ # purely to defeat collisions (very unlikely with 8 chars from a 64-
124
+ # symbol alphabet) and to be timing-attack-resistant.
125
+ Index("ix_api_tokens_token_prefix", "token_prefix"),
126
+ Index("ix_api_tokens_user_id", "user_id"),
127
+ )
128
+
129
+ id: Mapped[uuid.UUID] = mapped_column(GUID, primary_key=True, default=uuid.uuid4)
130
+ user_id: Mapped[uuid.UUID] = mapped_column(
131
+ GUID,
132
+ ForeignKey("users.id", ondelete="cascade"),
133
+ nullable=False,
134
+ )
135
+ # Human-readable label set by the user at create time
136
+ # (e.g. "ci-pipeline", "personal-laptop").
137
+ name: Mapped[str] = mapped_column(String(255), nullable=False)
138
+ token_prefix: Mapped[str] = mapped_column(String(8), nullable=False)
139
+ token_hash: Mapped[str] = mapped_column(String(64), nullable=False)
140
+ created_at: Mapped[datetime] = mapped_column(
141
+ DateTime(timezone=True),
142
+ nullable=False,
143
+ default=lambda: datetime.now(UTC),
144
+ )
145
+ expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
146
+ last_used_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
147
+ revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
148
+
149
+
150
+ class AuditLogORM(Base):
151
+ """Append-only audit trail of security-relevant events (#299, sub-A4).
152
+
153
+ Captures the *what* + *who* + *when* of operator-visible auth /
154
+ ownership events. ``event_type`` is a stable string key (e.g.
155
+ ``user.registered``, ``user.logged_in``, ``api_token.created``,
156
+ ``api_token.revoked``); ``event_data`` is a free-form JSON
157
+ payload for per-event details (target user id, token prefix, IP
158
+ address from the request, …).
159
+
160
+ Lifecycle:
161
+ - **Append-only**: rows are never updated or deleted by application
162
+ code. A retention policy (e.g. monthly partition pruning) can
163
+ reclaim space later if growth becomes a concern (Phase E).
164
+ - ``user_id`` is nullable so events that happen *before* the actor
165
+ is identified (e.g. failed login by an unknown email) can still
166
+ be recorded.
167
+ - No FK to ``users.id`` either — the row should survive even if
168
+ the user account is hard-deleted (audit integrity > referential
169
+ cleanliness).
170
+ """
171
+
172
+ __tablename__ = "audit_log"
173
+ __table_args__ = (
174
+ # Admin filter UI lists by user, by event type, or by both. The
175
+ # composite leads with user_id since "show me what user X did"
176
+ # is the primary investigation flow; event_type alone falls back
177
+ # to a small filtered scan.
178
+ Index("ix_audit_log_user_event", "user_id", "event_type"),
179
+ Index("ix_audit_log_created_at", "created_at"),
180
+ )
181
+
182
+ id: Mapped[uuid.UUID] = mapped_column(GUID, primary_key=True, default=uuid.uuid4)
183
+ # Nullable: pre-auth events (failed login by unknown email) and
184
+ # system events (migration, scheduled cleanup) have no actor.
185
+ user_id: Mapped[uuid.UUID | None] = mapped_column(GUID, nullable=True)
186
+ event_type: Mapped[str] = mapped_column(String(100), nullable=False)
187
+ # JSONB on PostgreSQL — supports native JSON path queries (the admin
188
+ # panel will filter by ``event_data->>'token_id'`` etc.) and matches
189
+ # the migration's CREATE TABLE column type. ``JSON.with_variant(JSONB,
190
+ # "postgresql")`` keeps the SQLite path on plain JSON (TEXT under the
191
+ # hood, no native operators but the column type is dialect-aware).
192
+ event_data: Mapped[dict[str, Any] | None] = mapped_column(
193
+ JSON().with_variant(JSONB, "postgresql"),
194
+ nullable=True,
195
+ )
196
+ created_at: Mapped[datetime] = mapped_column(
197
+ DateTime(timezone=True),
198
+ nullable=False,
199
+ default=lambda: datetime.now(UTC),
200
+ )
201
+
202
+
203
+ class OAuthAccountORM(SQLAlchemyBaseOAuthAccountTableUUID, Base):
204
+ """Linked OAuth identity (GitHub, Google, …).
205
+
206
+ Inherits id (UUID), oauth_name, access_token, expires_at,
207
+ refresh_token, account_id, account_email columns from
208
+ SQLAlchemyBaseOAuthAccountTableUUID.
209
+
210
+ ``user_id`` is overridden because the parent helper hardcodes
211
+ ``ForeignKey("user.id", …)`` (singular table name) but our user
212
+ table is ``users`` (plural — see UserORM.__tablename__). Without
213
+ the override, SQLAlchemy raises NoReferencedTableError on import.
214
+
215
+ Indexes are declared at the ORM level so ``Base.metadata.create_all``
216
+ creates them on fresh DBs (it runs *before* ``apply_migrations`` —
217
+ see ``persistence/db.py``). The migration provides idempotent
218
+ fallbacks for existing DBs that predate this release.
219
+ """
220
+
221
+ __tablename__ = "oauth_accounts"
222
+ __table_args__ = (
223
+ # Every callback resolves an existing OAuth identity by
224
+ # ``(oauth_name, account_id)``; without this composite the lookup
225
+ # is a full table scan on every login (and login frequency
226
+ # scales with active-user count).
227
+ Index("ix_oauth_accounts_provider_account", "oauth_name", "account_id"),
228
+ )
229
+
230
+ @declared_attr
231
+ def user_id(cls) -> Mapped[uuid.UUID]:
232
+ return mapped_column(
233
+ GUID,
234
+ ForeignKey("users.id", ondelete="cascade"),
235
+ nullable=False,
236
+ # User-scoped queries (list / unlink an OAuth account from
237
+ # the admin panel in Phase C) hit this column on every page;
238
+ # an explicit single-column index keeps those fast even when
239
+ # the composite above doesn't help (it leads with oauth_name).
240
+ index=True,
241
+ )
242
+
243
+
244
+ # ---------------------------------------------------------------------------
245
+ # Agents
246
+ # ---------------------------------------------------------------------------
247
+
248
+
249
+ class AgentORM(Base):
250
+ """Logical agent — stable identity + pointer to current version."""
251
+
252
+ __tablename__ = "agents"
253
+ __table_args__ = (
254
+ # Listing endpoints filter by user_id ("my agents") on every page;
255
+ # keep the index aligned with the dominant access pattern.
256
+ Index("ix_agents_user_id", "user_id"),
257
+ )
258
+
259
+ id: Mapped[str] = mapped_column(String, primary_key=True)
260
+ # Owner of the agent. CASCADE on user delete is intentional — a user
261
+ # row that's been hard-deleted (admin / GDPR path, Phase C/E) takes
262
+ # their owned data with it. Soft-deleted users keep their rows.
263
+ # Owner of this row — set on every new resource by the route
264
+ # handlers (sub-A4b). Nullable on the SQL side so the migration
265
+ # can ADD COLUMN against pre-v0.3 dev DBs without DEFAULT
266
+ # acrobatics; the backfill (#13) populates existing rows from a
267
+ # synthetic ``system`` user, and Phase A's enforcement PR (sub-A4b)
268
+ # will switch the application-layer contract to "always set on
269
+ # create" — at which point the DB column flips to NOT NULL on
270
+ # PostgreSQL (SQLite ALTER COLUMN limitations leave it nullable
271
+ # there, but the ORM contract still holds).
272
+ user_id: Mapped[uuid.UUID | None] = mapped_column(
273
+ GUID,
274
+ ForeignKey("users.id", ondelete="cascade"),
275
+ nullable=True,
276
+ )
277
+ name: Mapped[str] = mapped_column(String, nullable=False)
278
+ role: Mapped[str] = mapped_column(String, nullable=False)
279
+ current_version: Mapped[int] = mapped_column(Integer, nullable=False)
280
+
281
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
282
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
283
+ archived_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
284
+
285
+ versions: Mapped[list[AgentVersionORM]] = relationship(
286
+ back_populates="agent",
287
+ cascade="all, delete-orphan",
288
+ order_by="AgentVersionORM.version",
289
+ )
290
+
291
+
292
+ class AgentVersionORM(Base):
293
+ """Immutable agent version — full configuration snapshot.
294
+
295
+ Includes display name so version history is fully recoverable even when
296
+ the agent is renamed.
297
+ """
298
+
299
+ __tablename__ = "agent_versions"
300
+ __table_args__ = (
301
+ UniqueConstraint("agent_id", "version", name="uq_agent_versions_agent_version"),
302
+ )
303
+
304
+ id: Mapped[str] = mapped_column(String, primary_key=True)
305
+ agent_id: Mapped[str] = mapped_column(String, ForeignKey("agents.id"), nullable=False)
306
+ version: Mapped[int] = mapped_column(Integer, nullable=False)
307
+
308
+ name: Mapped[str] = mapped_column(String, nullable=False)
309
+ runtime_id: Mapped[str] = mapped_column(String, nullable=False)
310
+ runtime_config: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
311
+ prompt_template: Mapped[str] = mapped_column(Text, nullable=False)
312
+ # JSON column stores ``list[str]`` (PipelineState field names) as of
313
+ # v0.5; older rows may still hold a dict — the Pydantic Agent model
314
+ # coerces those at read-time. See packages/types/.../agent.py.
315
+ input_schema: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
316
+ output_schema: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
317
+ constraints: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
318
+ budget_limit_usd: Mapped[float | None] = mapped_column(Float, nullable=True)
319
+ timeout_ms: Mapped[int] = mapped_column(Integer, nullable=False, default=60_000)
320
+
321
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
322
+
323
+ agent: Mapped[AgentORM] = relationship(back_populates="versions")
324
+
325
+
326
+ # ---------------------------------------------------------------------------
327
+ # Pipelines
328
+ # ---------------------------------------------------------------------------
329
+
330
+
331
+ class PipelineORM(Base):
332
+ """Logical pipeline — stable identity + pointer to current version."""
333
+
334
+ __tablename__ = "pipelines"
335
+ __table_args__ = (Index("ix_pipelines_user_id", "user_id"),)
336
+
337
+ id: Mapped[str] = mapped_column(String, primary_key=True)
338
+ # Owner of this row — set on every new resource by the route
339
+ # handlers (sub-A4b). Nullable on the SQL side so the migration
340
+ # can ADD COLUMN against pre-v0.3 dev DBs without DEFAULT
341
+ # acrobatics; the backfill (#13) populates existing rows from a
342
+ # synthetic ``system`` user, and Phase A's enforcement PR (sub-A4b)
343
+ # will switch the application-layer contract to "always set on
344
+ # create" — at which point the DB column flips to NOT NULL on
345
+ # PostgreSQL (SQLite ALTER COLUMN limitations leave it nullable
346
+ # there, but the ORM contract still holds).
347
+ user_id: Mapped[uuid.UUID | None] = mapped_column(
348
+ GUID,
349
+ ForeignKey("users.id", ondelete="cascade"),
350
+ nullable=True,
351
+ )
352
+ name: Mapped[str] = mapped_column(String, nullable=False)
353
+ description: Mapped[str] = mapped_column(Text, nullable=False, default="")
354
+ current_version: Mapped[int] = mapped_column(Integer, nullable=False)
355
+
356
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
357
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
358
+ archived_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
359
+
360
+ versions: Mapped[list[PipelineVersionORM]] = relationship(
361
+ back_populates="pipeline",
362
+ cascade="all, delete-orphan",
363
+ order_by="PipelineVersionORM.version",
364
+ )
365
+
366
+
367
+ class PipelineVersionORM(Base):
368
+ """Immutable pipeline version — DAG snapshot.
369
+
370
+ Includes name and description so version history reflects the metadata
371
+ at the time of each save.
372
+ """
373
+
374
+ __tablename__ = "pipeline_versions"
375
+ __table_args__ = (
376
+ UniqueConstraint(
377
+ "pipeline_id",
378
+ "version",
379
+ name="uq_pipeline_versions_pipeline_version",
380
+ ),
381
+ )
382
+
383
+ id: Mapped[str] = mapped_column(String, primary_key=True)
384
+ pipeline_id: Mapped[str] = mapped_column(String, ForeignKey("pipelines.id"), nullable=False)
385
+ version: Mapped[int] = mapped_column(Integer, nullable=False)
386
+
387
+ name: Mapped[str] = mapped_column(String, nullable=False)
388
+ description: Mapped[str] = mapped_column(Text, nullable=False, default="")
389
+ schema_version: Mapped[str] = mapped_column(String, nullable=False, default="langgraph/1.0")
390
+ state_schema_ref: Mapped[str] = mapped_column(String, nullable=False)
391
+ entry_point: Mapped[str] = mapped_column(String, nullable=False)
392
+ nodes: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
393
+ edges: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
394
+ defaults: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
395
+ ui_metadata: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True, default=None)
396
+
397
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
398
+
399
+ pipeline: Mapped[PipelineORM] = relationship(back_populates="versions")
400
+
401
+
402
+ # ---------------------------------------------------------------------------
403
+ # Projects (v0.6) — workspace + workflow bindings
404
+ # ---------------------------------------------------------------------------
405
+
406
+
407
+ class ProjectORM(Base):
408
+ """A project: working directory + binding of workflow kinds to pipelines.
409
+
410
+ Single unversioned table — each project has one current-state row that
411
+ is updated in place (only agents and pipelines are versioned). Bindings
412
+ live in the JSON ``pipelines`` column; layered env vars in ``env_vars``.
413
+ Both validated at write time by ``repo.create_project`` / ``update_project``.
414
+ """
415
+
416
+ __tablename__ = "projects"
417
+ __table_args__ = (Index("ix_projects_user_id", "user_id"),)
418
+
419
+ id: Mapped[str] = mapped_column(String, primary_key=True)
420
+ # Owner of this row — set on every new resource by the route
421
+ # handlers (sub-A4b). Nullable on the SQL side so the migration
422
+ # can ADD COLUMN against pre-v0.3 dev DBs without DEFAULT
423
+ # acrobatics; the backfill (#13) populates existing rows from a
424
+ # synthetic ``system`` user, and Phase A's enforcement PR (sub-A4b)
425
+ # will switch the application-layer contract to "always set on
426
+ # create" — at which point the DB column flips to NOT NULL on
427
+ # PostgreSQL (SQLite ALTER COLUMN limitations leave it nullable
428
+ # there, but the ORM contract still holds).
429
+ user_id: Mapped[uuid.UUID | None] = mapped_column(
430
+ GUID,
431
+ ForeignKey("users.id", ondelete="cascade"),
432
+ nullable=True,
433
+ )
434
+ name: Mapped[str] = mapped_column(String, nullable=False)
435
+ description: Mapped[str] = mapped_column(Text, nullable=False, default="")
436
+
437
+ working_directory: Mapped[str | None] = mapped_column(String, nullable=True)
438
+ repo_url: Mapped[str | None] = mapped_column(String, nullable=True)
439
+ default_branch: Mapped[str] = mapped_column(String, nullable=False, default="main")
440
+
441
+ pipelines: Mapped[dict[str, str]] = mapped_column(JSON, nullable=False, default=dict)
442
+ env_vars: Mapped[dict[str, str]] = mapped_column(JSON, nullable=False, default=dict)
443
+
444
+ created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
445
+ updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
446
+ archived_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
447
+
448
+
449
+ # ---------------------------------------------------------------------------
450
+ # Runs (no schema change in F2)
451
+ # ---------------------------------------------------------------------------
452
+
453
+
454
+ class RunORM(Base):
455
+ """Pipeline execution instance — immutable FK to pipeline_versions row."""
456
+
457
+ __tablename__ = "runs"
458
+
459
+ id: Mapped[str] = mapped_column(String, primary_key=True)
460
+ # Owner of this row — set on every new resource by the route
461
+ # handlers (sub-A4b). Nullable on the SQL side so the migration
462
+ # can ADD COLUMN against pre-v0.3 dev DBs without DEFAULT
463
+ # acrobatics; the backfill (#13) populates existing rows from a
464
+ # synthetic ``system`` user, and Phase A's enforcement PR (sub-A4b)
465
+ # will switch the application-layer contract to "always set on
466
+ # create" — at which point the DB column flips to NOT NULL on
467
+ # PostgreSQL (SQLite ALTER COLUMN limitations leave it nullable
468
+ # there, but the ORM contract still holds).
469
+ user_id: Mapped[uuid.UUID | None] = mapped_column(
470
+ GUID,
471
+ ForeignKey("users.id", ondelete="cascade"),
472
+ nullable=True,
473
+ )
474
+ # Owning project (v0.6, #64). FK with NO cascade — archiving a
475
+ # project leaves its runs intact for historical inspection.
476
+ # Nullable for ad-hoc / legacy runs triggered without a project.
477
+ project_id: Mapped[str | None] = mapped_column(
478
+ String, ForeignKey("projects.id"), nullable=True, default=None
479
+ )
480
+ pipeline_id: Mapped[str] = mapped_column(String, nullable=False)
481
+ pipeline_version: Mapped[int] = mapped_column(Integer, nullable=False)
482
+
483
+ trigger_source: Mapped[str] = mapped_column(String, nullable=False)
484
+ initial_state: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
485
+
486
+ current_node: Mapped[str | None] = mapped_column(String, nullable=True)
487
+ node_statuses: Mapped[dict[str, str]] = mapped_column(JSON, nullable=False, default=dict)
488
+
489
+ final_status: Mapped[str] = mapped_column(String, nullable=False)
490
+ # Operator-facing reason for a non-success terminal status. Populated by
491
+ # ``mark_stale_running_runs_as_failed`` on engine restart (#260) so the
492
+ # dashboard / CLI can show why a run was forcibly terminated; ``None``
493
+ # for runs that finished cleanly or were aborted/paused via a normal
494
+ # operator action.
495
+ failure_reason: Mapped[str | None] = mapped_column(Text, nullable=True, default=None)
496
+ started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
497
+ ended_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
498
+ tokens_used: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
499
+ cost_usd: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
500
+
501
+ state_snapshots: Mapped[list[StateSnapshotORM]] = relationship(
502
+ back_populates="run",
503
+ cascade="all, delete-orphan",
504
+ order_by="StateSnapshotORM.timestamp",
505
+ )
506
+ node_logs: Mapped[list[NodeExecutionLogORM]] = relationship(
507
+ back_populates="run",
508
+ cascade="all, delete-orphan",
509
+ order_by="NodeExecutionLogORM.started_at",
510
+ )
511
+
512
+ __table_args__ = (
513
+ # ``list_runs`` unfiltered: ORDER BY started_at DESC (#251).
514
+ Index("ix_runs_started_at", "started_at"),
515
+ # Project-scoped runs view: ``WHERE project_id = ? ORDER BY started_at
516
+ # DESC``. Composite folds filter + sort into one index walk on SQLite,
517
+ # which can't bitmap-intersect single-column indexes (#251).
518
+ Index("ix_runs_project_started", "project_id", "started_at"),
519
+ # Per-pipeline runs view: same shape with ``pipeline_id`` (#251).
520
+ Index("ix_runs_pipeline_started", "pipeline_id", "started_at"),
521
+ # Owner-scoped listings (admin cross-user view + dashboard's
522
+ # "my runs" tab in Phase B). The composites above lead with
523
+ # project_id / pipeline_id, so they don't help the user-only
524
+ # filter; this single-column index keeps the access pattern
525
+ # symmetric with the other resource tables (sub-A4a, #299).
526
+ Index("ix_runs_user_id", "user_id"),
527
+ )
528
+
529
+
530
+ class StateSnapshotORM(Base):
531
+ __tablename__ = "state_snapshots"
532
+
533
+ id: Mapped[str] = mapped_column(String, primary_key=True)
534
+ run_id: Mapped[str] = mapped_column(String, ForeignKey("runs.id"), nullable=False)
535
+ node_id: Mapped[str] = mapped_column(String, nullable=False)
536
+ timestamp: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
537
+ state: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
538
+
539
+ run: Mapped[RunORM] = relationship(back_populates="state_snapshots")
540
+
541
+
542
+ class NodeExecutionLogORM(Base):
543
+ __tablename__ = "node_execution_logs"
544
+
545
+ id: Mapped[str] = mapped_column(String, primary_key=True)
546
+ run_id: Mapped[str] = mapped_column(String, ForeignKey("runs.id"), nullable=False)
547
+ node_id: Mapped[str] = mapped_column(String, nullable=False)
548
+ agent_id: Mapped[str] = mapped_column(String, nullable=False)
549
+ runtime_id: Mapped[str] = mapped_column(String, nullable=False)
550
+ started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
551
+ ended_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
552
+ prompt_xml: Mapped[str] = mapped_column(Text, nullable=False)
553
+ stdout: Mapped[str] = mapped_column(Text, nullable=False, default="")
554
+ stderr: Mapped[str] = mapped_column(Text, nullable=False, default="")
555
+ output_json: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True)
556
+ tokens_used: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
557
+ cost_usd: Mapped[float] = mapped_column(Float, nullable=False, default=0.0)
558
+ duration_ms: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
559
+ status: Mapped[str] = mapped_column(String, nullable=False)
560
+ error_message: Mapped[str | None] = mapped_column(Text, nullable=True)
561
+ extra_data: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True)
562
+
563
+ run: Mapped[RunORM] = relationship(back_populates="node_logs")
564
+
565
+ __table_args__ = (
566
+ # ``get_run`` populates node_statuses by ``WHERE run_id = ? ORDER BY
567
+ # started_at`` on every detail fetch — high-frequency polling (#251).
568
+ Index("ix_node_execution_logs_run_started", "run_id", "started_at"),
569
+ )