@everystack/server 0.3.3 → 0.3.5

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@everystack/server",
3
- "version": "0.3.3",
3
+ "version": "0.3.5",
4
4
  "description": "Server runtime primitives for Lambda — event adapters, routing, SSR, image processing",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": "Scalable Technology, Inc. <licensing@scalable.technology>",
@@ -72,6 +72,10 @@
72
72
  "./media": {
73
73
  "types": "./src/media.ts",
74
74
  "default": "./src/media.ts"
75
+ },
76
+ "./pipeline": {
77
+ "types": "./src/pipeline.ts",
78
+ "default": "./src/pipeline.ts"
75
79
  }
76
80
  },
77
81
  "peerDependencies": {
@@ -139,8 +143,8 @@
139
143
  "sst": "4.13.1",
140
144
  "ts-jest": "29.4.9",
141
145
  "typescript": "5.9.3",
142
- "@everystack/auth": "0.3.1",
143
- "@everystack/cli": "0.3.27"
146
+ "@everystack/cli": "0.3.31",
147
+ "@everystack/auth": "0.3.1"
144
148
  },
145
149
  "scripts": {
146
150
  "test": "jest",
package/src/backup-run.ts CHANGED
@@ -37,8 +37,42 @@ export interface BackupSummary {
37
37
  lastModified?: string;
38
38
  }
39
39
 
40
+ /**
41
+ * Lazily load an optional-peer AWS SDK client, turning a missing dependency into a one-line
42
+ * install remedy instead of a raw `ERR_MODULE_NOT_FOUND` deep in the ops Lambda. The `@aws-sdk/*`
43
+ * clients are optional peers of @everystack/server (a V1 app needs none of them), so a consumer
44
+ * whose ops function runs db:backup must install them — this names which, not "Cannot find
45
+ * package". Takes a thunk so the `import()` stays a literal — statically analyzable and typed.
46
+ */
47
+ export async function importOptionalAws<T>(
48
+ load: () => Promise<T>,
49
+ pkg: string,
50
+ feature: string,
51
+ ): Promise<T> {
52
+ try {
53
+ return await load();
54
+ } catch (err: unknown) {
55
+ const code = (err as { code?: string })?.code;
56
+ const message = String((err as { message?: string })?.message ?? err);
57
+ if (
58
+ code === 'ERR_MODULE_NOT_FOUND' ||
59
+ code === 'MODULE_NOT_FOUND' ||
60
+ /Cannot find (package|module)/.test(message)
61
+ ) {
62
+ throw new Error(
63
+ `${feature} needs ${pkg}, which isn't installed (it's an optional peer dependency of @everystack/server). Install it:\n pnpm add ${pkg}`,
64
+ );
65
+ }
66
+ throw err;
67
+ }
68
+ }
69
+
40
70
  async function getS3(region?: string): Promise<any> {
41
- const { S3Client } = await import('@aws-sdk/client-s3');
71
+ const { S3Client } = await importOptionalAws(
72
+ () => import('@aws-sdk/client-s3'),
73
+ '@aws-sdk/client-s3',
74
+ 'db:backup',
75
+ );
42
76
  return new S3Client(region ? { region } : {});
43
77
  }
44
78
 
@@ -57,8 +91,16 @@ export async function runBackup(deps: BackupRunDeps, stage: string): Promise<Bac
57
91
  const id = backupId(stage, stamp, shortId);
58
92
 
59
93
  const s3 = await getS3(region);
60
- const { Upload } = await import('@aws-sdk/lib-storage');
61
- const { DeleteObjectCommand, PutObjectCommand, HeadObjectCommand } = await import('@aws-sdk/client-s3');
94
+ const { Upload } = await importOptionalAws(
95
+ () => import('@aws-sdk/lib-storage'),
96
+ '@aws-sdk/lib-storage',
97
+ 'db:backup',
98
+ );
99
+ const { DeleteObjectCommand, PutObjectCommand, HeadObjectCommand } = await importOptionalAws(
100
+ () => import('@aws-sdk/client-s3'),
101
+ '@aws-sdk/client-s3',
102
+ 'db:backup',
103
+ );
62
104
 
63
105
  const child = spawn('pg_dump', pgDumpArgs(), { env, stdio: ['ignore', 'pipe', 'pipe'] });
64
106
  let stderr = '';
@@ -0,0 +1,423 @@
1
+ /**
2
+ * @everystack/server/pipeline — the ingest pipeline framework (Phase 3).
3
+ *
4
+ * A pipeline reproduces data from committed source: an ordered set of STAGES,
5
+ * each a function that reads source and writes rows idempotently. You never
6
+ * copy data between environments — you re-run the same committed source + the
7
+ * same stage code and get the same rows ("sync by reproduction").
8
+ *
9
+ * everystack owns the HARNESS — the stage contract, the topological order, the
10
+ * provenance-lane wall (automated/curated/frozen), resume, and the memoir
11
+ * (everystack.pipeline_log). The consumer owns the STAGES: their
12
+ * fetch/parse/transform/load code, their source files, their table and column
13
+ * names, their provenance values. Ingest logic never enters the framework,
14
+ * exactly as schema and migrations never do.
15
+ *
16
+ * A stage is a FUNCTION, not a spawned script, so the same stage runs unchanged
17
+ * in three places: a local process (`pipeline:run --database-url`), the ops
18
+ * Lambda (`pipeline:run --stage`, credential-free), or — later — a worker.
19
+ *
20
+ * See docs/plans/ingest-pipeline-framework.md.
21
+ */
22
+
23
+ /** Read/write SQL against the target, inside whatever transaction the caller holds. */
24
+ export type PipelineQuery = (sql: string) => Promise<any[]>;
25
+
26
+ /**
27
+ * The connection the orchestrator drives. `transaction` runs a stage's writes
28
+ * and its memoir row as one atomic unit; `query` is for the pre-flight ensure
29
+ * and the best-effort failure record (which must land OUTSIDE the rolled-back
30
+ * stage transaction).
31
+ */
32
+ export interface PipelineRunner {
33
+ query: PipelineQuery;
34
+ transaction: <T>(fn: (tx: PipelineQuery) => Promise<T>) => Promise<T>;
35
+ }
36
+
37
+ /** The provenance lane — the wall between the two reproduction audiences. */
38
+ export type StageLane = 'automated' | 'curated' | 'frozen';
39
+
40
+ /** What a stage reports back for the memoir (both optional — a stage may write nothing). */
41
+ export interface StageResult {
42
+ /** Rows this stage wrote, for the memoir. */
43
+ rows?: number;
44
+ /** Content hash of the source this stage reproduced from — Phase 4's verify reads it. */
45
+ sourceHash?: string;
46
+ }
47
+
48
+ /** What a stage receives. The framework builds it; the consumer's run() uses it. */
49
+ export interface StageContext {
50
+ /** The transactional runner for this stage's writes. */
51
+ runner: PipelineQuery;
52
+ /** This stage's provenance tag (`provenance` override, else `${lane}:${id}`). */
53
+ provenance: string;
54
+ /** True → compute/preview, write nothing. */
55
+ dryRun: boolean;
56
+ /** Emit a progress line. */
57
+ log: (message: string) => void;
58
+ /**
59
+ * The idempotency helper: delete the rows this stage owns before re-inserting.
60
+ * `DELETE FROM <table> WHERE <column> = <this stage's provenance>`. The stage
61
+ * owns the actual insert; the framework owns only the provenance-replace shape.
62
+ */
63
+ replaceProvenance: (table: string, column: string) => Promise<void>;
64
+ }
65
+
66
+ export interface Stage {
67
+ id: string;
68
+ lane: StageLane;
69
+ /** Data/topo edges — a dependency runs before its dependent. */
70
+ dependsOn?: string[];
71
+ /** Ordering-only edges (run after, but no data dependency). */
72
+ after?: string[];
73
+ /** Refuses the ops-Lambda executor — this stage is too big, run it local-direct. */
74
+ heavy?: boolean;
75
+ /** Provenance tag for the memoir + the replace helper. Default `${lane}:${id}`. */
76
+ provenance?: string;
77
+ run: (ctx: StageContext) => Promise<StageResult | void>;
78
+ }
79
+
80
+ export interface Pipeline {
81
+ stages: Stage[];
82
+ }
83
+
84
+ /** Identity for defineStage — a stage is a plain descriptor. */
85
+ export function defineStage(stage: Stage): Stage {
86
+ return stage;
87
+ }
88
+
89
+ /** Compose stages into a pipeline, validating unique ids and resolvable edges. */
90
+ export function definePipeline(stages: Stage[]): Pipeline {
91
+ const ids = new Set<string>();
92
+ for (const s of stages) {
93
+ if (ids.has(s.id)) throw new Error(`pipeline has a duplicate stage id: "${s.id}"`);
94
+ ids.add(s.id);
95
+ }
96
+ for (const s of stages) {
97
+ for (const dep of [...(s.dependsOn ?? []), ...(s.after ?? [])]) {
98
+ if (!ids.has(dep)) {
99
+ throw new Error(`stage "${s.id}" depends on "${dep}", which is not a stage in this pipeline`);
100
+ }
101
+ }
102
+ }
103
+ return { stages };
104
+ }
105
+
106
+ /** The provenance tag a stage writes under. */
107
+ export function stageProvenance(stage: Stage): string {
108
+ return stage.provenance ?? `${stage.lane}:${stage.id}`;
109
+ }
110
+
111
+ /**
112
+ * Deterministic topological sort over dependsOn ∪ after edges. Stable: with no
113
+ * edge between two stages, declared order wins (so a re-run is byte-stable).
114
+ * Throws on an unknown edge or a cycle (naming a stage on the cycle).
115
+ */
116
+ export function topoSortStages(stages: Stage[]): Stage[] {
117
+ const byId = new Map(stages.map((s) => [s.id, s]));
118
+ const indegree = new Map<string, number>(stages.map((s) => [s.id, 0]));
119
+ const dependents = new Map<string, string[]>(stages.map((s) => [s.id, []]));
120
+
121
+ for (const s of stages) {
122
+ for (const dep of [...(s.dependsOn ?? []), ...(s.after ?? [])]) {
123
+ if (!byId.has(dep)) {
124
+ throw new Error(`stage "${s.id}" depends on unknown stage "${dep}"`);
125
+ }
126
+ indegree.set(s.id, (indegree.get(s.id) ?? 0) + 1);
127
+ dependents.get(dep)!.push(s.id);
128
+ }
129
+ }
130
+
131
+ // Kahn's algorithm; the ready queue is kept in declared order for stability.
132
+ const declaredIndex = new Map(stages.map((s, i) => [s.id, i]));
133
+ const ready = stages.filter((s) => (indegree.get(s.id) ?? 0) === 0).map((s) => s.id);
134
+ const sorted: Stage[] = [];
135
+ while (ready.length > 0) {
136
+ ready.sort((a, b) => declaredIndex.get(a)! - declaredIndex.get(b)!);
137
+ const id = ready.shift()!;
138
+ sorted.push(byId.get(id)!);
139
+ for (const next of dependents.get(id)!) {
140
+ indegree.set(next, (indegree.get(next) ?? 0) - 1);
141
+ if (indegree.get(next) === 0) ready.push(next);
142
+ }
143
+ }
144
+
145
+ if (sorted.length !== stages.length) {
146
+ const remaining = stages.filter((s) => !sorted.includes(s)).map((s) => s.id);
147
+ throw new Error(`pipeline has a dependency cycle involving: ${remaining.join(', ')}`);
148
+ }
149
+ return sorted;
150
+ }
151
+
152
+ export interface SelectOptions {
153
+ /** rebuild → automated + frozen; curate → curated; else all lanes. */
154
+ lane?: 'rebuild' | 'curate' | 'all';
155
+ /** Keep stages whose id contains this substring. */
156
+ only?: string;
157
+ /** Slice the ordered list from this stage id (inclusive). */
158
+ from?: string;
159
+ /** Slice the ordered list to this stage id (inclusive). */
160
+ to?: string;
161
+ }
162
+
163
+ const laneKeeps = (lane: SelectOptions['lane'], stageLane: StageLane): boolean => {
164
+ if (lane === 'rebuild') return stageLane === 'automated' || stageLane === 'frozen';
165
+ if (lane === 'curate') return stageLane === 'curated';
166
+ return true;
167
+ };
168
+
169
+ /** Filter an already-ordered stage list by lane, --only, and --from/--to. */
170
+ export function selectStages(ordered: Stage[], opts: SelectOptions): Stage[] {
171
+ let selected = ordered;
172
+ if (opts.from || opts.to) {
173
+ const start = opts.from ? selected.findIndex((s) => s.id === opts.from) : 0;
174
+ const endIdx = opts.to ? selected.findIndex((s) => s.id === opts.to) : selected.length - 1;
175
+ if (start === -1) throw new Error(`--from names no stage: "${opts.from}"`);
176
+ if (endIdx === -1) throw new Error(`--to names no stage: "${opts.to}"`);
177
+ selected = selected.slice(start, endIdx + 1);
178
+ }
179
+ selected = selected.filter((s) => laneKeeps(opts.lane, s.lane));
180
+ if (opts.only) selected = selected.filter((s) => s.id.includes(opts.only!));
181
+ return selected;
182
+ }
183
+
184
+ // ---------------------------------------------------------------------------
185
+ // The memoir — everystack.pipeline_log (append-only, sibling to backfill_log).
186
+ // ---------------------------------------------------------------------------
187
+
188
+ export const ENSURE_PIPELINE_SQL: string[] = [
189
+ 'CREATE SCHEMA IF NOT EXISTS everystack',
190
+ `CREATE TABLE IF NOT EXISTS everystack.pipeline_log (
191
+ id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
192
+ applied_at timestamptz NOT NULL DEFAULT now(),
193
+ run_id text NOT NULL,
194
+ stage_id text NOT NULL,
195
+ lane text NOT NULL,
196
+ source_hash text,
197
+ rows integer,
198
+ actor text,
199
+ git_ref text,
200
+ duration_ms integer,
201
+ outcome text NOT NULL
202
+ )`,
203
+ ];
204
+
205
+ const sqlStr = (v: string | null | undefined): string =>
206
+ v === null || v === undefined ? 'NULL' : `'${String(v).replace(/'/g, "''")}'`;
207
+ const sqlNum = (v: number | null | undefined): string =>
208
+ v === null || v === undefined || !Number.isFinite(v) ? 'NULL' : String(Math.trunc(v));
209
+
210
+ export interface PipelineLogEntry {
211
+ runId: string;
212
+ stageId: string;
213
+ lane: StageLane;
214
+ sourceHash?: string | null;
215
+ rows?: number | null;
216
+ actor?: string | null;
217
+ gitRef?: string | null;
218
+ durationMs?: number | null;
219
+ outcome: 'applied' | 'failed';
220
+ }
221
+
222
+ export function renderPipelineLogInsert(e: PipelineLogEntry): string {
223
+ return `INSERT INTO everystack.pipeline_log (run_id, stage_id, lane, source_hash, rows, actor, git_ref, duration_ms, outcome)
224
+ VALUES (${sqlStr(e.runId)}, ${sqlStr(e.stageId)}, ${sqlStr(e.lane)}, ${sqlStr(e.sourceHash)}, ${sqlNum(e.rows)}, ${sqlStr(e.actor)}, ${sqlStr(e.gitRef)}, ${sqlNum(e.durationMs)}, ${sqlStr(e.outcome)})`;
225
+ }
226
+
227
+ /**
228
+ * The most recently touched run_id in the memoir — what `--resume` picks up
229
+ * with no explicit run id. Null when the pipeline has never run here.
230
+ */
231
+ export async function latestRunId(query: PipelineQuery): Promise<string | null> {
232
+ try {
233
+ const rows = await query('SELECT run_id FROM everystack.pipeline_log ORDER BY id DESC LIMIT 1');
234
+ return rows.length > 0 ? String(rows[0].run_id) : null;
235
+ } catch {
236
+ // No memoir yet (table absent) — nothing to resume.
237
+ return null;
238
+ }
239
+ }
240
+
241
+ /** A one-line summary of a pipeline's most recent run — the visibility surface. */
242
+ export interface PipelineRunSummary {
243
+ runId: string;
244
+ /** applied_at of the run's last row (a string as the driver returns it). */
245
+ at: string | null;
246
+ /** Stages whose LATEST attempt under this run succeeded. */
247
+ applied: number;
248
+ /** Stages whose LATEST attempt failed (an incomplete run — resume). */
249
+ failed: number;
250
+ failedStages: string[];
251
+ }
252
+
253
+ /**
254
+ * Summarize the most recent run for db:sync / db:plan to surface — the analog
255
+ * of the pending-backfill nudge. Read-only; null when the pipeline has never
256
+ * run here (or the memoir table is absent). Counts the LATEST attempt per stage
257
+ * so a resumed-and-fixed stage reads as applied, not failed.
258
+ */
259
+ export async function readLastRun(query: PipelineQuery): Promise<PipelineRunSummary | null> {
260
+ try {
261
+ const latest = await query('SELECT run_id FROM everystack.pipeline_log ORDER BY id DESC LIMIT 1');
262
+ if (latest.length === 0) return null;
263
+ const runId = String(latest[0].run_id);
264
+ const rows = await query(
265
+ `SELECT stage_id, outcome, applied_at FROM everystack.pipeline_log WHERE run_id = ${sqlStr(runId)} ORDER BY id`,
266
+ );
267
+ const latestByStage = new Map<string, string>();
268
+ let at: string | null = null;
269
+ for (const r of rows) {
270
+ latestByStage.set(String(r.stage_id), String(r.outcome));
271
+ if (r.applied_at != null) at = String(r.applied_at);
272
+ }
273
+ const failedStages = [...latestByStage].filter(([, o]) => o === 'failed').map(([s]) => s);
274
+ const applied = [...latestByStage.values()].filter((o) => o === 'applied').length;
275
+ return { runId, at, applied, failed: failedStages.length, failedStages };
276
+ } catch {
277
+ return null;
278
+ }
279
+ }
280
+
281
+ /** The stage ids that already succeeded under a given run — the resume set. */
282
+ export async function readAppliedStages(query: PipelineQuery, runId: string): Promise<Set<string>> {
283
+ const rows = await query(
284
+ `SELECT stage_id FROM everystack.pipeline_log WHERE run_id = ${sqlStr(runId)} AND outcome = 'applied'`,
285
+ );
286
+ return new Set(rows.map((r: any) => String(r.stage_id)));
287
+ }
288
+
289
+ // ---------------------------------------------------------------------------
290
+ // The orchestrator — pure over an injected runner, identical local and ops-routed.
291
+ // ---------------------------------------------------------------------------
292
+
293
+ export interface RunPipelineOptions extends SelectOptions {
294
+ /** Groups a multi-stage run for resume; caller supplies it (a uuid). */
295
+ runId: string;
296
+ /** Skip stages already applied under runId. */
297
+ resume?: boolean;
298
+ /** Print the plan, run nothing. */
299
+ dryRun?: boolean;
300
+ /** Keep going past a failed stage (default: fail-fast). */
301
+ continueOnError?: boolean;
302
+ actor?: string | null;
303
+ gitRef?: string | null;
304
+ /** Injectable clock for tests. */
305
+ now?: () => number;
306
+ /** Emit a progress line. */
307
+ log?: (message: string) => void;
308
+ }
309
+
310
+ export type StageOutcome = 'applied' | 'skipped' | 'failed' | 'dry-run';
311
+
312
+ export interface StageRunResult {
313
+ stageId: string;
314
+ outcome: StageOutcome;
315
+ rows?: number;
316
+ durationMs?: number;
317
+ error?: string;
318
+ }
319
+
320
+ export interface PipelineRunOutcome {
321
+ runId: string;
322
+ /** The ordered, selected stage ids — the plan. */
323
+ plan: string[];
324
+ results: StageRunResult[];
325
+ failed: boolean;
326
+ }
327
+
328
+ /**
329
+ * Reproduce the pipeline against the target: topo-order, filter to the selected
330
+ * lane/range, then run each stage inside its own transaction — the stage's
331
+ * writes AND its memoir row commit together. A throw rolls the stage back,
332
+ * records a best-effort `failed` row outside the transaction, and (unless
333
+ * continueOnError) stops, marking the rest skipped. dry-run returns the plan and
334
+ * runs nothing.
335
+ */
336
+ export async function runPipeline(
337
+ runner: PipelineRunner,
338
+ pipeline: Pipeline,
339
+ options: RunPipelineOptions,
340
+ ): Promise<PipelineRunOutcome> {
341
+ const now = options.now ?? Date.now;
342
+ const log = options.log ?? (() => {});
343
+ const ordered = topoSortStages(pipeline.stages);
344
+ const selected = selectStages(ordered, options);
345
+ const plan = selected.map((s) => s.id);
346
+
347
+ if (options.dryRun) {
348
+ return {
349
+ runId: options.runId,
350
+ plan,
351
+ results: selected.map((s) => ({ stageId: s.id, outcome: 'dry-run' as const })),
352
+ failed: false,
353
+ };
354
+ }
355
+
356
+ await runner.query(ENSURE_PIPELINE_SQL.join(';\n'));
357
+ const alreadyApplied = options.resume
358
+ ? await readAppliedStages(runner.query, options.runId)
359
+ : new Set<string>();
360
+
361
+ const results: StageRunResult[] = [];
362
+ let stopped = false;
363
+
364
+ for (const stage of selected) {
365
+ if (stopped) {
366
+ results.push({ stageId: stage.id, outcome: 'skipped' });
367
+ continue;
368
+ }
369
+ if (options.resume && alreadyApplied.has(stage.id)) {
370
+ results.push({ stageId: stage.id, outcome: 'skipped' });
371
+ continue;
372
+ }
373
+
374
+ const provenance = stageProvenance(stage);
375
+ const started = now();
376
+ try {
377
+ const result = await runner.transaction(async (tx) => {
378
+ const ctx: StageContext = {
379
+ runner: tx,
380
+ provenance,
381
+ dryRun: false,
382
+ log,
383
+ replaceProvenance: async (table, column) => {
384
+ await tx(`DELETE FROM ${table} WHERE ${column} = ${sqlStr(provenance)}`);
385
+ },
386
+ };
387
+ const r = (await stage.run(ctx)) ?? {};
388
+ await tx(renderPipelineLogInsert({
389
+ runId: options.runId,
390
+ stageId: stage.id,
391
+ lane: stage.lane,
392
+ sourceHash: r.sourceHash ?? null,
393
+ rows: r.rows ?? null,
394
+ actor: options.actor ?? null,
395
+ gitRef: options.gitRef ?? null,
396
+ durationMs: now() - started,
397
+ outcome: 'applied',
398
+ }));
399
+ return r;
400
+ });
401
+ results.push({ stageId: stage.id, outcome: 'applied', rows: result.rows, durationMs: now() - started });
402
+ } catch (err: any) {
403
+ const message = String(err?.message ?? err);
404
+ // Best-effort failure memoir, OUTSIDE the rolled-back stage transaction.
405
+ try {
406
+ await runner.query(ENSURE_PIPELINE_SQL.join(';\n'));
407
+ await runner.query(renderPipelineLogInsert({
408
+ runId: options.runId,
409
+ stageId: stage.id,
410
+ lane: stage.lane,
411
+ durationMs: now() - started,
412
+ outcome: 'failed',
413
+ }));
414
+ } catch {
415
+ // the memoir is best-effort on failure
416
+ }
417
+ results.push({ stageId: stage.id, outcome: 'failed', durationMs: now() - started, error: message });
418
+ if (!options.continueOnError) stopped = true;
419
+ }
420
+ }
421
+
422
+ return { runId: options.runId, plan, results, failed: results.some((r) => r.outcome === 'failed') };
423
+ }
package/src/plugin.ts CHANGED
@@ -7,6 +7,7 @@
7
7
  */
8
8
 
9
9
  import type { Handler, Route, LogSink, ServerCacheConfig } from './index';
10
+ import type { Pipeline } from './pipeline';
10
11
  import type {
11
12
  APIGatewayProxyEventV2,
12
13
  APIGatewayProxyStructuredResultV2,
@@ -490,6 +491,13 @@ export interface DbPluginOptions {
490
491
  backupBucket?: string;
491
492
  /** AWS region for the backups bucket (defaults to the Lambda's AWS_REGION). */
492
493
  backupRegion?: string;
494
+ /**
495
+ * The app's ingest pipeline (built with definePipeline). When provided, registers the
496
+ * credential-free `pipeline:run` action: the orchestrator runs IN this Lambda over the
497
+ * operator connection, so a deployed stage's small curated overlays reproduce via IAM,
498
+ * never a held database URL. Stages marked `heavy` are refused here (run them local-direct).
499
+ */
500
+ pipeline?: Pipeline;
493
501
  }
494
502
 
495
503
  /**
@@ -508,6 +516,24 @@ export function dbPlugin(options: DbPluginOptions): Plugin {
508
516
  // connection can be least-privilege and RLS-gated.
509
517
  const opsDb = ctx.adminDb ?? ctx.db;
510
518
 
519
+ // Resolve the logical-backup dependencies (bucket + operator URL) once —
520
+ // shared by db:backup/db:backups/db:restore and by db:apply's auto-snapshot
521
+ // before a destructive staged apply. Returns `{ error }` when unconfigured.
522
+ const resolveBackupDeps = async (): Promise<
523
+ { deps: { bucket: string; region?: string; adminUrl: string } } | { error: string }
524
+ > => {
525
+ const bucket = options.backupBucket;
526
+ if (!bucket) {
527
+ return { error: 'backup storage not configured — pass backupBucket to dbPlugin (e.g. Resource.Backups.name)' };
528
+ }
529
+ const { getAdminDatabaseUrl, getMasterDatabaseUrl } = await import('./db');
530
+ const adminUrl = getAdminDatabaseUrl() ?? getMasterDatabaseUrl();
531
+ if (!adminUrl) {
532
+ return { error: 'no operator connection available (ADMIN_DATABASE_URL / Resource.Database)' };
533
+ }
534
+ return { deps: { bucket, region: options.backupRegion ?? process.env.AWS_REGION, adminUrl } };
535
+ };
536
+
511
537
  // --- migrate ---
512
538
  actions.migrate = async (_payload, _ctx) => {
513
539
  const { runMigrations } = await import('./migrate');
@@ -759,19 +785,6 @@ export function dbPlugin(options: DbPluginOptions): Plugin {
759
785
  // dedicated private backups bucket. Restore is destructive and requires an explicit confirm in
760
786
  // the payload (the CLI sets it after the user confirms). See backup-run.ts.
761
787
  {
762
- const resolveBackupDeps = async () => {
763
- const bucket = options.backupBucket;
764
- if (!bucket) {
765
- return { error: 'backup storage not configured — pass backupBucket to dbPlugin (e.g. Resource.Backups.name)' as string };
766
- }
767
- const { getAdminDatabaseUrl, getMasterDatabaseUrl } = await import('./db');
768
- const adminUrl = getAdminDatabaseUrl() ?? getMasterDatabaseUrl();
769
- if (!adminUrl) {
770
- return { error: 'no operator connection available (ADMIN_DATABASE_URL / Resource.Database)' as string };
771
- }
772
- return { deps: { bucket, region: options.backupRegion ?? process.env.AWS_REGION, adminUrl } };
773
- };
774
-
775
788
  actions['db:backup'] = async (payload, ctx) => {
776
789
  const r = await resolveBackupDeps();
777
790
  if ('error' in r) return { error: r.error };
@@ -814,6 +827,123 @@ export function dbPlugin(options: DbPluginOptions): Plugin {
814
827
  };
815
828
  }
816
829
 
830
+ // --- db:apply — the credential-free staged write (Phase 2) ---
831
+ // The staged half of db:apply: the CLI computes the plan and the
832
+ // checkout-bound verdicts (the fast-forward/descent rule, the destructive
833
+ // approver check — neither can be recomputed here: one needs the git
834
+ // checkout, the other the caller's real IAM identity); THIS action does the
835
+ // write against the operator connection. Verify the concurrency lock, apply
836
+ // the DDL in one transaction, stamp everystack.schema_log with the plan_ref,
837
+ // and verify the target landed on plan.to — the same executeApplyPlan the
838
+ // direct --database-url path runs, only here the connection never leaves the
839
+ // Lambda. A destructive plan snapshots first (db:backup), in order.
840
+ actions['db:apply'] = async (payload, ctx) => {
841
+ const { plan, actor, gitRef, descentVerdict, authorityVerdict, stage } =
842
+ (payload ?? {}) as {
843
+ plan?: any;
844
+ actor?: string | null;
845
+ gitRef?: string | null;
846
+ descentVerdict?: { ok: boolean; reason?: string };
847
+ authorityVerdict?: { ok: boolean; reason?: string };
848
+ stage?: string;
849
+ };
850
+ if (!plan || typeof plan !== 'object' || !Array.isArray(plan.statements)) {
851
+ return { error: 'db:apply requires { plan } — a reviewed edge minted by db:plan' };
852
+ }
853
+ const { executeApplyPlan, PLAN_VERSION } = await import('@everystack/cli/apply');
854
+ if (plan.v !== PLAN_VERSION) {
855
+ return { error: `plan version ${plan.v} is not this server's ${PLAN_VERSION} — re-mint with a matching db:plan` };
856
+ }
857
+
858
+ const { sql } = await import('drizzle-orm');
859
+ const runner = async (query: string): Promise<any[]> => {
860
+ const result: any = await opsDb.execute(sql.raw(query));
861
+ return Array.isArray(result) ? result : result?.rows ?? [];
862
+ };
863
+
864
+ const destructive = Number(plan.destructive) > 0;
865
+ let snapshotId: string | undefined;
866
+ try {
867
+ const result = await executeApplyPlan(runner, plan, {
868
+ actor: actor ?? null,
869
+ gitRef: gitRef ?? null,
870
+ // Descent/authority are decided by the CLI (checkout + caller identity)
871
+ // and enforced + recorded here, in order, atomic with the lock.
872
+ ...(descentVerdict
873
+ ? { verifyDescent: async () => (descentVerdict.ok ? { ok: true as const } : { ok: false as const, reason: descentVerdict.reason ?? 'descent refused' }) }
874
+ : {}),
875
+ ...(destructive && authorityVerdict
876
+ ? { verifyAuthority: async () => (authorityVerdict.ok ? { ok: true as const } : { ok: false as const, reason: authorityVerdict.reason ?? 'authority refused' }) }
877
+ : {}),
878
+ // Losing data is hard: the snapshot runs HERE, after the lock/descent/
879
+ // authority gates pass and before the DDL. It uses the same logical
880
+ // backup as db:backup, on the operator connection.
881
+ ...(destructive
882
+ ? {
883
+ beforeDestructive: async () => {
884
+ const r = await resolveBackupDeps();
885
+ if ('error' in r) {
886
+ throw new Error(`snapshot before a destructive apply is impossible — ${r.error}`);
887
+ }
888
+ const { runBackup } = await import('./backup-run');
889
+ const backup: any = await runBackup(r.deps, stage ?? ctx.environment ?? 'default');
890
+ snapshotId = backup?.id;
891
+ },
892
+ }
893
+ : {}),
894
+ });
895
+ return snapshotId ? { ...result, snapshotId } : result;
896
+ } catch (err: any) {
897
+ return { error: err?.message || String(err) };
898
+ }
899
+ };
900
+
901
+ // --- pipeline:run — the credential-free ingest reproduction (Phase 3, Brick 5) ---
902
+ // The orchestrator runs HERE, in the ops Lambda, over the operator connection: a
903
+ // deployed stage's small curated overlays reproduce via IAM, never a held URL. The
904
+ // pipeline definition is the one the app bundled into this Lambda (like `seed`); the
905
+ // CLI passes only the run options. A `heavy` stage is refused — it belongs local-direct.
906
+ if (options.pipeline) {
907
+ const pipeline = options.pipeline;
908
+ actions['pipeline:run'] = async (payload, _ctx) => {
909
+ const runOpts: any = { ...((payload ?? {}) as Record<string, unknown>) };
910
+ const { runPipeline, topoSortStages, selectStages, latestRunId } = await import('./pipeline');
911
+
912
+ let selected;
913
+ try {
914
+ selected = selectStages(topoSortStages(pipeline.stages), runOpts);
915
+ } catch (err: any) {
916
+ return { error: err?.message || String(err) };
917
+ }
918
+ const heavy = selected.filter((s) => s.heavy).map((s) => s.id);
919
+ if (heavy.length > 0) {
920
+ return { error: `stage(s) ${heavy.join(', ')} are marked heavy — too big for the ops Lambda. Run them local-direct: pipeline:run --database-url <url>.` };
921
+ }
922
+
923
+ const { sql } = await import('drizzle-orm');
924
+ const asRows = (r: any): any[] => (Array.isArray(r) ? r : r?.rows ?? []);
925
+ const runner = {
926
+ query: async (q: string) => asRows(await opsDb.execute(sql.raw(q))),
927
+ transaction: async <T>(fn: (tx: (q: string) => Promise<any[]>) => Promise<T>): Promise<T> =>
928
+ opsDb.transaction(async (tx: any) => fn(async (q: string) => asRows(await tx.execute(sql.raw(q))))),
929
+ };
930
+
931
+ // Resume with no explicit run id picks up the latest run on THIS stage.
932
+ if (runOpts.resume && !runOpts.runId) {
933
+ const latest = await latestRunId(runner.query);
934
+ if (!latest) return { error: 'nothing to resume — this pipeline has not run on this stage yet.' };
935
+ runOpts.runId = latest;
936
+ }
937
+ if (!runOpts.runId) return { error: 'pipeline:run requires a runId' };
938
+
939
+ try {
940
+ return await runPipeline(runner, pipeline, runOpts);
941
+ } catch (err: any) {
942
+ return { error: err?.message || String(err) };
943
+ }
944
+ };
945
+ }
946
+
817
947
  // --- console ---
818
948
  if (options.allowConsole !== false) {
819
949
  actions['console:meta'] = async (_payload, ctx) => {