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,328 @@
1
+ """Pipeline persistence — CRUD on PipelineORM / PipelineVersionORM.
2
+
3
+ Ownership: every read / write helper takes the actor's ``user_id``
4
+ (plus an ``is_admin`` flag for the cross-user admin path). Non-admins
5
+ only see their own rows; an attempt to read or mutate someone else's
6
+ pipeline raises ``NotFoundError`` (anti-enumeration — same rule
7
+ ``agents.py`` applies and that ``api-tokens`` already enforces).
8
+
9
+ Pipelines reference agents by ``node.agent_id`` strings. The DAG
10
+ validator (``execution.validator``) only checks for *existence* —
11
+ it does **not** enforce agent-level ownership. A user is allowed to
12
+ build a pipeline on top of any agent whose id they know; v0.3
13
+ ownership scope is the *pipeline* row, not transitive references.
14
+ That keeps shared / admin-curated agent libraries usable.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import uuid
20
+ from collections.abc import Sequence
21
+
22
+ from dap_types import Pipeline
23
+ from dap_types.pipeline import PipelineDefaults, PipelineEdge, PipelineNode
24
+ from sqlalchemy import ColumnElement, func, select, tuple_
25
+ from sqlalchemy.orm import Session
26
+
27
+ from dap_engine.auth.audit import record_audit_event
28
+ from dap_engine.contracts import PipelineCreate, PipelineUpdate
29
+ from dap_engine.persistence._common import NotFoundError, _new_id, _now
30
+ from dap_engine.persistence.models import PipelineORM, PipelineVersionORM
31
+
32
+
33
+ def _ownership_filter(
34
+ actor_id: uuid.UUID,
35
+ is_admin: bool,
36
+ ) -> list[ColumnElement[bool]]:
37
+ """Return ``[]`` for admins, else a single-clause filter for the actor.
38
+
39
+ Centralised so every list query gets the rule without copy-paste.
40
+ Admins see all rows (including legacy NULL ``user_id`` rows from
41
+ the pre-v0.3 backfill); non-admins only see rows they own.
42
+ """
43
+ if is_admin:
44
+ return []
45
+ return [PipelineORM.user_id == actor_id]
46
+
47
+
48
+ def _pipeline_from_orm(
49
+ pipeline: PipelineORM,
50
+ version: PipelineVersionORM,
51
+ *,
52
+ is_current: bool,
53
+ ) -> Pipeline:
54
+ return Pipeline(
55
+ id=pipeline.id,
56
+ name=pipeline.name if is_current else version.name,
57
+ description=pipeline.description if is_current else version.description,
58
+ version=version.version,
59
+ schema_version=version.schema_version, # type: ignore[arg-type]
60
+ state_schema_ref=version.state_schema_ref,
61
+ entry_point=version.entry_point,
62
+ nodes=[PipelineNode.model_validate(n) for n in version.nodes],
63
+ edges=[PipelineEdge.model_validate(e) for e in version.edges],
64
+ defaults=PipelineDefaults.model_validate(version.defaults),
65
+ created_at=pipeline.created_at,
66
+ updated_at=pipeline.updated_at if is_current else version.created_at,
67
+ is_active=pipeline.archived_at is None,
68
+ ui_metadata=version.ui_metadata,
69
+ )
70
+
71
+
72
+ def create_pipeline(
73
+ session: Session,
74
+ payload: PipelineCreate,
75
+ *,
76
+ user_id: uuid.UUID,
77
+ ) -> Pipeline:
78
+ """Create a new pipeline owned by ``user_id`` and write an audit row."""
79
+ now = _now()
80
+ pipeline = PipelineORM(
81
+ id=_new_id(),
82
+ user_id=user_id,
83
+ name=payload.name,
84
+ description=payload.description,
85
+ current_version=1,
86
+ created_at=now,
87
+ updated_at=now,
88
+ archived_at=None,
89
+ )
90
+ version = PipelineVersionORM(
91
+ id=_new_id(),
92
+ pipeline_id=pipeline.id,
93
+ version=1,
94
+ name=payload.name,
95
+ description=payload.description,
96
+ schema_version=payload.schema_version,
97
+ state_schema_ref=payload.state_schema_ref,
98
+ entry_point=payload.entry_point,
99
+ nodes=[n.model_dump(mode="json") for n in payload.nodes],
100
+ edges=[e.model_dump(mode="json") for e in payload.edges],
101
+ defaults=payload.defaults.model_dump(mode="json"),
102
+ ui_metadata=payload.ui_metadata,
103
+ created_at=now,
104
+ )
105
+ session.add(pipeline)
106
+ session.add(version)
107
+ session.flush()
108
+ record_audit_event(
109
+ session,
110
+ user_id=user_id,
111
+ event_type="pipeline.created",
112
+ event_data={"pipeline_id": pipeline.id, "name": payload.name},
113
+ )
114
+ return _pipeline_from_orm(pipeline, version, is_current=True)
115
+
116
+
117
+ def update_pipeline(
118
+ session: Session,
119
+ pipeline_id: str,
120
+ payload: PipelineUpdate,
121
+ *,
122
+ actor_id: uuid.UUID,
123
+ is_admin: bool,
124
+ ) -> Pipeline:
125
+ """Update a pipeline. Non-admins can only touch their own rows."""
126
+ pipeline = session.get(PipelineORM, pipeline_id)
127
+ if pipeline is None or pipeline.archived_at is not None:
128
+ raise NotFoundError(f"Pipeline not found: {pipeline_id}")
129
+ if not is_admin and pipeline.user_id != actor_id:
130
+ # Anti-enumeration: cross-user lookup looks indistinguishable
131
+ # from "doesn't exist".
132
+ raise NotFoundError(f"Pipeline not found: {pipeline_id}")
133
+
134
+ now = _now()
135
+ new_version_number = pipeline.current_version + 1
136
+
137
+ if payload.name is not None:
138
+ pipeline.name = payload.name
139
+ if payload.description is not None:
140
+ pipeline.description = payload.description
141
+ pipeline.current_version = new_version_number
142
+ pipeline.updated_at = now
143
+
144
+ version = PipelineVersionORM(
145
+ id=_new_id(),
146
+ pipeline_id=pipeline.id,
147
+ version=new_version_number,
148
+ name=pipeline.name,
149
+ description=pipeline.description,
150
+ schema_version=payload.schema_version,
151
+ state_schema_ref=payload.state_schema_ref,
152
+ entry_point=payload.entry_point,
153
+ nodes=[n.model_dump(mode="json") for n in payload.nodes],
154
+ edges=[e.model_dump(mode="json") for e in payload.edges],
155
+ defaults=payload.defaults.model_dump(mode="json"),
156
+ ui_metadata=payload.ui_metadata,
157
+ created_at=now,
158
+ )
159
+ session.add(version)
160
+ session.flush()
161
+ record_audit_event(
162
+ session,
163
+ user_id=actor_id,
164
+ event_type="pipeline.updated",
165
+ event_data={"pipeline_id": pipeline.id, "version": new_version_number},
166
+ )
167
+ return _pipeline_from_orm(pipeline, version, is_current=True)
168
+
169
+
170
+ def archive_pipeline(
171
+ session: Session,
172
+ pipeline_id: str,
173
+ *,
174
+ actor_id: uuid.UUID,
175
+ is_admin: bool,
176
+ ) -> None:
177
+ """Archive a pipeline. Non-admins can only archive their own rows."""
178
+ pipeline = session.get(PipelineORM, pipeline_id)
179
+ if pipeline is None:
180
+ raise NotFoundError(f"Pipeline not found: {pipeline_id}")
181
+ if not is_admin and pipeline.user_id != actor_id:
182
+ raise NotFoundError(f"Pipeline not found: {pipeline_id}")
183
+ if pipeline.archived_at is not None:
184
+ return # idempotent
185
+ pipeline.archived_at = _now()
186
+ session.flush()
187
+ record_audit_event(
188
+ session,
189
+ user_id=actor_id,
190
+ event_type="pipeline.archived",
191
+ event_data={"pipeline_id": pipeline.id},
192
+ )
193
+
194
+
195
+ def get_pipeline(
196
+ session: Session,
197
+ pipeline_id: str,
198
+ *,
199
+ actor_id: uuid.UUID,
200
+ is_admin: bool,
201
+ ) -> Pipeline:
202
+ """Fetch a pipeline. Non-admins only see their own."""
203
+ pipeline = session.get(PipelineORM, pipeline_id)
204
+ if pipeline is None:
205
+ raise NotFoundError(f"Pipeline not found: {pipeline_id}")
206
+ if not is_admin and pipeline.user_id != actor_id:
207
+ raise NotFoundError(f"Pipeline not found: {pipeline_id}")
208
+ version = _get_pipeline_version_orm(session, pipeline_id, pipeline.current_version)
209
+ return _pipeline_from_orm(pipeline, version, is_current=True)
210
+
211
+
212
+ def get_pipeline_version(
213
+ session: Session,
214
+ pipeline_id: str,
215
+ version: int,
216
+ *,
217
+ actor_id: uuid.UUID,
218
+ is_admin: bool,
219
+ ) -> Pipeline:
220
+ pipeline = session.get(PipelineORM, pipeline_id)
221
+ if pipeline is None:
222
+ raise NotFoundError(f"Pipeline not found: {pipeline_id}")
223
+ if not is_admin and pipeline.user_id != actor_id:
224
+ raise NotFoundError(f"Pipeline not found: {pipeline_id}")
225
+ version_orm = _get_pipeline_version_orm(session, pipeline_id, version)
226
+ return _pipeline_from_orm(
227
+ pipeline,
228
+ version_orm,
229
+ is_current=version == pipeline.current_version,
230
+ )
231
+
232
+
233
+ def list_pipeline_versions(
234
+ session: Session,
235
+ pipeline_id: str,
236
+ *,
237
+ actor_id: uuid.UUID,
238
+ is_admin: bool,
239
+ ) -> list[Pipeline]:
240
+ pipeline = session.get(PipelineORM, pipeline_id)
241
+ if pipeline is None:
242
+ raise NotFoundError(f"Pipeline not found: {pipeline_id}")
243
+ if not is_admin and pipeline.user_id != actor_id:
244
+ raise NotFoundError(f"Pipeline not found: {pipeline_id}")
245
+ versions = session.scalars(
246
+ select(PipelineVersionORM)
247
+ .where(PipelineVersionORM.pipeline_id == pipeline_id)
248
+ .order_by(PipelineVersionORM.version)
249
+ ).all()
250
+ return [
251
+ _pipeline_from_orm(pipeline, v, is_current=v.version == pipeline.current_version)
252
+ for v in versions
253
+ ]
254
+
255
+
256
+ def list_pipelines(
257
+ session: Session,
258
+ *,
259
+ actor_id: uuid.UUID,
260
+ is_admin: bool,
261
+ archived: bool = False,
262
+ offset: int = 0,
263
+ limit: int = 50,
264
+ ) -> tuple[Sequence[Pipeline], int]:
265
+ where_clauses: list[ColumnElement[bool]] = []
266
+ where_clauses.extend(_ownership_filter(actor_id, is_admin))
267
+ if not archived:
268
+ where_clauses.append(PipelineORM.archived_at.is_(None))
269
+
270
+ total = session.scalar(select(func.count()).select_from(PipelineORM).where(*where_clauses)) or 0
271
+
272
+ # JOIN on (pipeline_id, current_version): see list_agents in agents.py.
273
+ rows = session.execute(
274
+ select(PipelineORM, PipelineVersionORM)
275
+ .join(
276
+ PipelineVersionORM,
277
+ (PipelineVersionORM.pipeline_id == PipelineORM.id)
278
+ & (PipelineVersionORM.version == PipelineORM.current_version),
279
+ )
280
+ .where(*where_clauses)
281
+ .order_by(PipelineORM.created_at.desc())
282
+ .offset(offset)
283
+ .limit(limit)
284
+ ).all()
285
+
286
+ items = [_pipeline_from_orm(pipeline, version, is_current=True) for pipeline, version in rows]
287
+ return items, total
288
+
289
+
290
+ def _get_pipeline_version_orm(
291
+ session: Session,
292
+ pipeline_id: str,
293
+ version: int,
294
+ ) -> PipelineVersionORM:
295
+ version_orm = session.scalar(
296
+ select(PipelineVersionORM)
297
+ .where(PipelineVersionORM.pipeline_id == pipeline_id)
298
+ .where(PipelineVersionORM.version == version)
299
+ )
300
+ if version_orm is None:
301
+ raise NotFoundError(f"Pipeline version not found: {pipeline_id}@v{version}")
302
+ return version_orm
303
+
304
+
305
+ def _current_pipeline_versions(session: Session) -> list[PipelineVersionORM]:
306
+ """Fetch only the *current* version row of every non-archived pipeline.
307
+
308
+ Composite ``(pipeline_id, version)`` IN keeps the version-table scan
309
+ bounded by the number of non-archived pipelines, instead of every
310
+ historical revision. Imported by ``agents.pipelines_using_agent``
311
+ and ``agents.count_pipelines_using_agents``.
312
+
313
+ Does **not** filter by ``user_id`` — it powers the agent-side
314
+ "is this agent in use?" hint, which (as documented on
315
+ ``pipelines_using_agent``) requires upstream ownership gating in
316
+ the agents-layer caller. That contract is unchanged by sub-A4b2b.
317
+ """
318
+ pipelines = session.scalars(select(PipelineORM).where(PipelineORM.archived_at.is_(None))).all()
319
+ if not pipelines:
320
+ return []
321
+ keys = [(p.id, p.current_version) for p in pipelines]
322
+ return list(
323
+ session.scalars(
324
+ select(PipelineVersionORM).where(
325
+ tuple_(PipelineVersionORM.pipeline_id, PipelineVersionORM.version).in_(keys),
326
+ ),
327
+ ).all()
328
+ )
@@ -0,0 +1,256 @@
1
+ """Project persistence — CRUD on ProjectORM (v0.6 workspace + workflow bindings).
2
+
3
+ Ownership: every read / write helper takes the actor's ``user_id``
4
+ (plus an ``is_admin`` flag for the cross-user admin path). Non-admins
5
+ only see their own rows; an attempt to read or mutate someone else's
6
+ project raises ``NotFoundError`` (anti-enumeration — same rule
7
+ ``agents.py`` and ``pipelines.py`` apply).
8
+
9
+ Projects bind workflow kinds to ``pipeline_id`` strings. The binding
10
+ validator (:func:`_validate_pipeline_bindings`) enforces that the
11
+ caller owns every pipeline they bind — otherwise a non-admin could
12
+ attach a foreign pipeline_id and trigger it via
13
+ ``POST /projects/{id}/run/{kind}``. Admins bypass that check (same
14
+ pattern as the row-level ownership filter).
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import uuid
20
+ from collections.abc import Sequence
21
+
22
+ from dap_types import Project
23
+ from sqlalchemy import ColumnElement, func, select
24
+ from sqlalchemy.orm import Session
25
+
26
+ from dap_engine.auth.audit import record_audit_event
27
+ from dap_engine.contracts import ProjectCreate, ProjectUpdate
28
+ from dap_engine.persistence._common import NotFoundError, _new_id, _now
29
+ from dap_engine.persistence.models import PipelineORM, ProjectORM
30
+
31
+
32
+ def _ownership_filter(
33
+ actor_id: uuid.UUID,
34
+ is_admin: bool,
35
+ ) -> list[ColumnElement[bool]]:
36
+ """Return ``[]`` for admins, else a single-clause filter for the actor.
37
+
38
+ Centralised so every list query gets the rule without copy-paste.
39
+ Admins see all rows (including legacy NULL ``user_id`` rows from
40
+ the pre-v0.3 backfill); non-admins only see rows they own.
41
+ """
42
+ if is_admin:
43
+ return []
44
+ return [ProjectORM.user_id == actor_id]
45
+
46
+
47
+ def _project_from_orm(project: ProjectORM) -> Project:
48
+ return Project(
49
+ id=project.id,
50
+ name=project.name,
51
+ description=project.description,
52
+ working_directory=project.working_directory,
53
+ repo_url=project.repo_url,
54
+ default_branch=project.default_branch,
55
+ pipelines=dict(project.pipelines),
56
+ env_vars=dict(project.env_vars),
57
+ created_at=project.created_at,
58
+ updated_at=project.updated_at,
59
+ archived_at=project.archived_at,
60
+ )
61
+
62
+
63
+ def _validate_pipeline_bindings(
64
+ session: Session,
65
+ bindings: dict[str, str],
66
+ *,
67
+ actor_id: uuid.UUID,
68
+ is_admin: bool,
69
+ ) -> None:
70
+ """Reject bindings that reference unknown / archived / blank / foreign pipelines.
71
+
72
+ Caller maps the resulting ``ValueError`` to a 422 — this is a
73
+ user-fixable input problem, not a programmer error.
74
+
75
+ Blank pipeline ids should already be rejected by the API request
76
+ schema (``ProjectCreate`` / ``ProjectUpdate``); we re-check here so
77
+ internal callers (or future schemas that bypass the validator)
78
+ still fail loudly instead of silently persisting an invalid state.
79
+
80
+ Ownership: non-admin callers can only bind pipelines they own.
81
+ Foreign pipeline_ids are surfaced as ``unknown pipeline_id(s)`` —
82
+ same wording the "doesn't exist" case uses — so a probe can't
83
+ distinguish "someone else owns this id" from "no such id" through
84
+ the error body (anti-enumeration; matches the 404 pattern the row-
85
+ level gates use elsewhere).
86
+ """
87
+ if not bindings:
88
+ return
89
+ blank_kinds = sorted({k for k, v in bindings.items() if not v or not v.strip()})
90
+ if blank_kinds:
91
+ msg = f"blank pipeline id for kind(s): {', '.join(blank_kinds)}"
92
+ raise ValueError(msg)
93
+
94
+ bound_ids = sorted(set(bindings.values()))
95
+ pipeline_query = select(PipelineORM).where(PipelineORM.id.in_(bound_ids))
96
+ if not is_admin:
97
+ # Non-admins: only pipelines they own are findable. Foreign
98
+ # rows look "unknown" to them — see docstring.
99
+ pipeline_query = pipeline_query.where(PipelineORM.user_id == actor_id)
100
+ found = session.scalars(pipeline_query).all()
101
+ by_id = {p.id: p for p in found}
102
+
103
+ unknown = [pid for pid in bound_ids if pid not in by_id]
104
+ archived = [pid for pid in bound_ids if pid in by_id and by_id[pid].archived_at is not None]
105
+
106
+ problems: list[str] = []
107
+ if unknown:
108
+ problems.append(f"unknown pipeline_id(s): {', '.join(unknown)}")
109
+ if archived:
110
+ problems.append(f"archived pipeline_id(s): {', '.join(archived)}")
111
+ if problems:
112
+ raise ValueError("; ".join(problems))
113
+
114
+
115
+ def create_project(
116
+ session: Session,
117
+ payload: ProjectCreate,
118
+ *,
119
+ user_id: uuid.UUID,
120
+ is_admin: bool,
121
+ ) -> Project:
122
+ """Create a project owned by ``user_id`` and write an audit row.
123
+
124
+ ``is_admin`` rides along so the binding validator can let admins
125
+ attach pipelines owned by anyone (e.g. an admin curating shared
126
+ workflows). For non-admin creators, every bound pipeline_id must
127
+ be owned by the creator.
128
+ """
129
+ _validate_pipeline_bindings(session, payload.pipelines, actor_id=user_id, is_admin=is_admin)
130
+ now = _now()
131
+ project = ProjectORM(
132
+ id=_new_id(),
133
+ user_id=user_id,
134
+ name=payload.name,
135
+ description=payload.description,
136
+ working_directory=payload.working_directory,
137
+ repo_url=payload.repo_url,
138
+ default_branch=payload.default_branch,
139
+ pipelines=dict(payload.pipelines),
140
+ env_vars=dict(payload.env_vars),
141
+ created_at=now,
142
+ updated_at=now,
143
+ archived_at=None,
144
+ )
145
+ session.add(project)
146
+ session.flush()
147
+ record_audit_event(
148
+ session,
149
+ user_id=user_id,
150
+ event_type="project.created",
151
+ event_data={"project_id": project.id, "name": payload.name},
152
+ )
153
+ return _project_from_orm(project)
154
+
155
+
156
+ def update_project(
157
+ session: Session,
158
+ project_id: str,
159
+ payload: ProjectUpdate,
160
+ *,
161
+ actor_id: uuid.UUID,
162
+ is_admin: bool,
163
+ ) -> Project:
164
+ """Update a project. Non-admins can only touch their own rows."""
165
+ project = session.get(ProjectORM, project_id)
166
+ if project is None or project.archived_at is not None:
167
+ raise NotFoundError(f"Project not found: {project_id}")
168
+ if not is_admin and project.user_id != actor_id:
169
+ # Anti-enumeration: cross-user lookup looks indistinguishable
170
+ # from "doesn't exist".
171
+ raise NotFoundError(f"Project not found: {project_id}")
172
+ _validate_pipeline_bindings(session, payload.pipelines, actor_id=actor_id, is_admin=is_admin)
173
+
174
+ project.name = payload.name
175
+ project.description = payload.description
176
+ project.working_directory = payload.working_directory
177
+ project.repo_url = payload.repo_url
178
+ project.default_branch = payload.default_branch
179
+ project.pipelines = dict(payload.pipelines)
180
+ project.env_vars = dict(payload.env_vars)
181
+ project.updated_at = _now()
182
+ session.flush()
183
+ record_audit_event(
184
+ session,
185
+ user_id=actor_id,
186
+ event_type="project.updated",
187
+ event_data={"project_id": project.id},
188
+ )
189
+ return _project_from_orm(project)
190
+
191
+
192
+ def archive_project(
193
+ session: Session,
194
+ project_id: str,
195
+ *,
196
+ actor_id: uuid.UUID,
197
+ is_admin: bool,
198
+ ) -> None:
199
+ """Archive a project. Non-admins can only archive their own rows."""
200
+ project = session.get(ProjectORM, project_id)
201
+ if project is None:
202
+ raise NotFoundError(f"Project not found: {project_id}")
203
+ if not is_admin and project.user_id != actor_id:
204
+ raise NotFoundError(f"Project not found: {project_id}")
205
+ if project.archived_at is not None:
206
+ return # idempotent
207
+ project.archived_at = _now()
208
+ session.flush()
209
+ record_audit_event(
210
+ session,
211
+ user_id=actor_id,
212
+ event_type="project.archived",
213
+ event_data={"project_id": project.id},
214
+ )
215
+
216
+
217
+ def get_project(
218
+ session: Session,
219
+ project_id: str,
220
+ *,
221
+ actor_id: uuid.UUID,
222
+ is_admin: bool,
223
+ ) -> Project:
224
+ """Fetch a project. Non-admins only see their own."""
225
+ project = session.get(ProjectORM, project_id)
226
+ if project is None:
227
+ raise NotFoundError(f"Project not found: {project_id}")
228
+ if not is_admin and project.user_id != actor_id:
229
+ raise NotFoundError(f"Project not found: {project_id}")
230
+ return _project_from_orm(project)
231
+
232
+
233
+ def list_projects(
234
+ session: Session,
235
+ *,
236
+ actor_id: uuid.UUID,
237
+ is_admin: bool,
238
+ archived: bool = False,
239
+ offset: int = 0,
240
+ limit: int = 50,
241
+ ) -> tuple[Sequence[Project], int]:
242
+ where_clauses: list[ColumnElement[bool]] = []
243
+ where_clauses.extend(_ownership_filter(actor_id, is_admin))
244
+ if not archived:
245
+ where_clauses.append(ProjectORM.archived_at.is_(None))
246
+
247
+ total = session.scalar(select(func.count()).select_from(ProjectORM).where(*where_clauses)) or 0
248
+
249
+ projects_orm = session.scalars(
250
+ select(ProjectORM)
251
+ .where(*where_clauses)
252
+ .order_by(ProjectORM.created_at.desc())
253
+ .offset(offset)
254
+ .limit(limit)
255
+ ).all()
256
+ return [_project_from_orm(p) for p in projects_orm], total
@@ -0,0 +1,101 @@
1
+ """Repository layer — public façade re-exporting per-entity helpers (#253).
2
+
3
+ Implementation lives in per-entity modules under
4
+ ``dap_engine.persistence``:
5
+
6
+ - :mod:`dap_engine.persistence.agents`
7
+ - :mod:`dap_engine.persistence.pipelines`
8
+ - :mod:`dap_engine.persistence.projects`
9
+ - :mod:`dap_engine.persistence.runs`
10
+ - :mod:`dap_engine.persistence._common` (shared ``NotFoundError`` /
11
+ id / timestamp helpers)
12
+
13
+ Existing callers continue using ``from dap_engine.persistence import
14
+ repository as repo`` and call ``repo.foo()`` — the names below
15
+ preserve that surface so the split is transparent at the import
16
+ layer.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from dap_engine.persistence._common import NotFoundError
22
+ from dap_engine.persistence.agents import (
23
+ archive_agent,
24
+ count_pipelines_using_agents,
25
+ create_agent,
26
+ get_agent,
27
+ get_agent_template,
28
+ get_agent_version,
29
+ get_agents_by_ids,
30
+ list_agent_versions,
31
+ list_agents,
32
+ pipelines_using_agent,
33
+ update_agent,
34
+ )
35
+ from dap_engine.persistence.pipelines import (
36
+ archive_pipeline,
37
+ create_pipeline,
38
+ get_pipeline,
39
+ get_pipeline_version,
40
+ list_pipeline_versions,
41
+ list_pipelines,
42
+ update_pipeline,
43
+ )
44
+ from dap_engine.persistence.projects import (
45
+ archive_project,
46
+ create_project,
47
+ get_project,
48
+ list_projects,
49
+ update_project,
50
+ )
51
+ from dap_engine.persistence.runs import (
52
+ create_run,
53
+ finalize_run,
54
+ get_run,
55
+ get_run_node_log,
56
+ get_run_state,
57
+ list_run_state_history,
58
+ list_runs,
59
+ mark_stale_running_runs_as_failed,
60
+ pause_run,
61
+ try_claim_resume,
62
+ try_claim_revive,
63
+ )
64
+
65
+ __all__ = [
66
+ "NotFoundError",
67
+ "archive_agent",
68
+ "archive_pipeline",
69
+ "archive_project",
70
+ "count_pipelines_using_agents",
71
+ "create_agent",
72
+ "create_pipeline",
73
+ "create_project",
74
+ "create_run",
75
+ "finalize_run",
76
+ "get_agent",
77
+ "get_agent_template",
78
+ "get_agent_version",
79
+ "get_agents_by_ids",
80
+ "get_pipeline",
81
+ "get_pipeline_version",
82
+ "get_project",
83
+ "get_run",
84
+ "get_run_node_log",
85
+ "get_run_state",
86
+ "list_agent_versions",
87
+ "list_agents",
88
+ "list_pipeline_versions",
89
+ "list_pipelines",
90
+ "list_projects",
91
+ "list_run_state_history",
92
+ "list_runs",
93
+ "mark_stale_running_runs_as_failed",
94
+ "pause_run",
95
+ "pipelines_using_agent",
96
+ "try_claim_resume",
97
+ "try_claim_revive",
98
+ "update_agent",
99
+ "update_pipeline",
100
+ "update_project",
101
+ ]