@sequenceholdings/studio-cli 0.1.29 → 0.1.31

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/README.md CHANGED
@@ -365,6 +365,7 @@ compiled to canonical SQL before registration.
365
365
  |---------|--------------|
366
366
  | `seq-studio orm init <dir>` | Scaffold one v2 namespace package (`sequence.config.ts`, `schema/*.ts`, `graphql/**`, and codegen config). |
367
367
  | `seq-studio orm generate [dir]` | Generate `schema.graphql`, `operations.manifest.json`, `typePolicies.gen.ts`, and consumer codegen when `codegen.ts` is present. |
368
+ | `seq-studio orm generate [dir] --migration-export [--check]` | Export `orm.migration.json` after validating the committed ORM migration. Pipeline migration planning recompiles these declarative inputs. `--check` compares against the current source and operations without writing; use it in CI. |
368
369
  | `seq-studio orm validate [dir]` | Parse and compile the namespace, then verify its committed migration chain is current. |
369
370
  | `seq-studio orm plan [dir] -e <env>` | Compare the compiled namespace with registry state without applying database changes. |
370
371
  | `seq-studio orm diff [dir] [--check]` | Author the next committed migration, or verify the migration/snapshot chain offline for CI. |
@@ -685,6 +686,14 @@ to the CLI's copy — not the artifact's declared semver. Deployments record
685
686
  `cliVersion` + `atlasUiVersion`. Contract:
686
687
  `@sequenceholdings/artifact-studio` → `VERSION-PIN.md`.
687
688
 
689
+ Studio CLI 0.1.31 carries Artifact Studio 0.2.5 with Atlas UI 3.1.2 pinned
690
+ exactly. Ordinary builds use canonical, mode-aware `tokens.css`; new projects
691
+ use matching editor dependencies. Before rebuilding an older artifact, migrate
692
+ numbered black/white opacity utilities to semantic roles and check a preview in
693
+ light and dark mode. Legacy stylesheet entry points remain temporary aliases;
694
+ they do not restore retired utilities. Existing deployed bundles change only
695
+ when rebuilt and activated.
696
+
688
697
  ### Source for `build` / `plan` / `deploy`
689
698
 
690
699
  These three commands read their source tree from one of three places — the rest
@@ -823,6 +832,7 @@ install it alongside the CLI to use this family.
823
832
  |---------|--------------|
824
833
  | `seq-studio pipeline init --type ingestion\|transformation\|serving <name> [--dir <dir>]` | Scaffold `<name>.stage.yml` (commented per-kind template) plus a `src/` Databricks-notebook entrypoint stub (begins with `# Databricks notebook source`; serving stages are declarative — no stub). Refuses to overwrite an existing spec |
825
834
  | `seq-studio pipeline validate [dir] [--assets <file\|url>] [--orm-contracts <file\|url>] [--json]` | Run the full offline spec gate: envelope + body validation, `schema_ref` resolution, and repo-level graph validation (reference resolution, single-writer, cycles, column subsets, serving projection checks). Auto-loads `orm-contracts.json` from the pipeline dir when present. Exit 0/1 |
835
+ | `seq-studio pipeline repin-orm [dir] -e <env> [--target <id>] [--dry-run]` | Resolve the environment's pipeline target (or use `--target` when ambiguous), fetch its active ORM v2 contracts, verify those serving projections remain compatible, then update `orm-contracts.json` and their `satisfies.content_hash` pins. Refuses to write when compatibility fails |
826
836
  | `seq-studio pipeline plan --repo pipelines/<slug> --ref <sha\|branch> -e <env> [--target <id>] [--json]` | Enqueue and poll a durable Pipeline plan (materialize → SDK/`validateSpecGraph` → compile → live-diff → provision findings). Fails closed listing **every** missing target binding (alert channels, workspace, Databricks `source.credential`) plus Data Sync edge-worker machine/operation/`credEnvFamilies` mismatches before registry writes. Does **not** run Databricks `bundle validate` (that is a Trigger deploy-path hard gate). Exit 1 on destructive findings (CI-safe). `--json` emits the completed stable plan envelope |
827
837
  | `seq-studio pipeline deploy --repo pipelines/<slug> --ref <sha\|branch> -e <env> [--target <id>] [--approved-by <sub>] [--allow-destructive <resource-key> ...] [--run-now] [--wait-timeout <duration>] [--no-wait]` | Plan then enqueue deploy; Trigger runs `bundle validate` then `bundle deploy` against reviewed bytes. Default is plant-only (jobs are created, not run). `--run-now` runs in-unit producer roots after bundle deploy; serving refresh provisioning completes before producer trigger.after tasks can run. If a producer fails, the terminal status includes the remote Databricks task/event error when available. `--allow-destructive` is repeatable and must exactly name every deletion/recreation finding in the immutable plan; only authenticated `@seqholdings.com` users may authorize it; permission, ownership, schedule-drift, and provisioning blockers cannot be overridden. Polls to terminal unless `--no-wait`. Targets that require approval need `--approved-by` naming the authenticated caller. |
828
838
  | `seq-studio pipeline status --deployment-id <id> -e <env> [--json]` | Fetch the current remote deployment status without changing it. Use this public command to continue monitoring after local polling stops |
@@ -847,8 +857,108 @@ monitoring. Internal operators also receive the equivalent `seqapi` command;
847
857
  failures include the status detail, and any available Trigger run ID is shown.
848
858
  `--json` output is unchanged.
849
859
 
860
+ ### Coordinated schema migrations (Preview, staff access)
861
+
862
+ Ordinary plans include a report comparing deployed output declarations with
863
+ physical Delta schemas and their Lakebase serving tables. Missing inventory and
864
+ unsupported dependencies are reported explicitly. This report is advisory;
865
+ ordinary deployment behavior remains unchanged.
866
+
867
+ Commit a versioned `migrations/<id>.yml` manifest, then add `--migration <id>` to
868
+ `pipeline plan` to prepare its execution plan. The manifest declares participating pipeline repositories,
869
+ column additions/type changes, stages that rebuild their complete writer scopes,
870
+ and acceptance checks. Every participant ref resolves to an immutable commit.
871
+ The assessment validates all proposed shared writers together.
872
+
873
+ For example, after changing both writers' Spark code and output declarations to
874
+ produce decimal balances, the root repository can declare:
875
+
876
+ ```yaml
877
+ schema_version: 1
878
+ id: decimal-balances
879
+ participants:
880
+ - { repo: pipelines/secondary-ledger, ref: main }
881
+ changes:
882
+ - { stage: gold, output: gold.accounts, columns: [balance], kind: change_column_type }
883
+ - { repo: pipelines/secondary-ledger, stage: gold, output: gold.accounts, columns: [balance], kind: change_column_type }
884
+ rebuild:
885
+ - { stage: gold, mode: full_writer_scope }
886
+ - { repo: pipelines/secondary-ledger, stage: gold, mode: full_writer_scope }
887
+ orm:
888
+ - { repo: namespaces/finance, ref: main, path: '.', namespace: finance }
889
+ checks:
890
+ - { kind: row_count, stage: gold, output: gold.accounts, comparison: equal }
891
+ - { kind: orm_operation, namespace: finance, operation: VerifyAccounts }
892
+ ```
893
+
894
+ The old and new types come from deployed and proposed output declarations.
895
+ Business calculations stay in Spark; the migration specifies coordination and
896
+ acceptance criteria. `VerifyAccounts` must be a persisted read operation in the
897
+ pinned ORM export. Each changed shared writer must participate.
898
+
899
+ For an ORM participant, update the namespace source, run `orm diff`, then
900
+ `orm generate --migration-export`, and commit the generated files with the
901
+ source. Run `orm generate --migration-export --check` in CI to catch stale
902
+ exports. Atlas reads the pinned JSON export and recompiles its schema and
903
+ operations; it does not execute the repository's TypeScript. The export checksum
904
+ detects inconsistent contents; the reviewed Git commit provides provenance.
905
+
906
+ Planning returns a migration run ID and immutable plan hash after checking
907
+ native schemas, serving dependencies, participating releases and ORM consumers.
908
+ It does not pause jobs or change native tables. Review that plan, then use its
909
+ run ID and hash with the separate migration lifecycle:
910
+
911
+ ```sh
912
+ seq-studio pipeline plan --repo pipelines/example --ref main --migration decimal-balances -e staging
913
+ seq-studio pipeline migrate start --run-id <run-id> --plan-hash <plan-hash> -e staging
914
+ seq-studio pipeline migrate status --run-id <run-id> -e staging
915
+ seq-studio pipeline migrate resume --run-id <run-id> --plan-hash <plan-hash> -e staging
916
+ seq-studio pipeline migrate cancel --run-id <run-id> --plan-hash <plan-hash> -e staging
917
+ ```
918
+
919
+ The planning user must authorize start, resume and cancellation against the same
920
+ target and hash. The API queues a durable worker; closing the CLI does not stop
921
+ it. `status --json` includes phase progress, native operation IDs, worker state,
922
+ retained reservations and validation results. A queued task is distinguished
923
+ from a worker that has actually claimed the migration. Failed or unknown native
924
+ work remains visible even when a parent task is retrying.
925
+
926
+ The worker pauses and drains the captured jobs, builds candidates with the pinned
927
+ Spark code, runs declared acceptance checks, publishes validated Delta data,
928
+ reconciles Snapshot copies and views, installs the new jobs while paused, and
929
+ activates pipeline and ORM registry pointers together. New serving stages can
930
+ attach to an existing producer job. Their new copies, physical identities,
931
+ projections and public views are verified before activation. Original schedules
932
+ resume only after consumer checks pass.
933
+
934
+ Before publication, cancellation stops candidate work and restores original
935
+ schedules. After publication, it retains reservations and backups for forward
936
+ recovery; it does not promise automatic rollback. Resume first reconciles the
937
+ recorded native operations so a lost response does not duplicate completed work.
938
+
939
+ V1 supports managed batch Spark writers, declared column additions/type changes,
940
+ Snapshot copies, supported SQL views and ORM v2 exports. Primary-key changes,
941
+ stateful DLT/CDF migrations, unknown dependencies and unmodeled resources block
942
+ planning. Spark packages must use the migration runtime bindings and remain
943
+ reviewed, trusted code. Existing inherited Databricks permissions are accepted,
944
+ as in ordinary pipeline deployments. Candidate checks enforce migration-issued
945
+ grants and owned resources, but do not sandbox code from unrelated tables it can
946
+ already access. These commands remain Sequence-staff-only; their supporting
947
+ HTTP endpoints are internal. Untrusted authors require a separately verified
948
+ execution-identity boundary before this restriction can be lifted.
949
+
850
950
  ### Managed Pipelines asset identity
851
951
 
952
+ For native Polars transformations, use `engine: polars` and a regular Python
953
+ `entrypoint`. Deployment creates a serverless Python file task;
954
+ `pipeline run-now` starts it with its declared defaults and resolved input/output
955
+ bindings as Python command-line arguments. Use `trigger: { manual: true }` for an
956
+ explicit-run-only stage, or `cron`/`after` for scheduled chaining. Configure pip
957
+ requirements with the JSON-string `config.python_dependencies`; the default
958
+ installs `polars==1.34.0` and `deltalake==1.2.1`. `config.driver_memory_gb` is rejected because
959
+ this serverless Python task contract cannot honor it. See the
960
+ [pipeline spec Python argument contract](../pipeline-spec/README.md#native-polars-jobs).
961
+
852
962
  Compiled Databricks assets use stable, environment-qualified identities: display names are `{env}-MP-{type}-{stage}` (with `-trigger` for a scheduled DLT runner), DAB resource keys are `mp_{type}_{stage_snake_case}` (with `_trigger` for that runner), task keys are `{type}_{task}`, and bundles are `{env}-MP-pipelines-{domain}`. Compiled jobs and pipelines also carry `mp: "true"` and `mp_type: <type>` tags.
853
963
 
854
964
  Changing a DAB resource key is a delete-and-create operation. Treat these identities as the existing-resource contract when planning, adopting, unbinding, or inspecting a Managed Pipeline; Unity Catalog catalogs, volumes, tables, and synced tables are not renamed by this convention.
@@ -17,6 +17,8 @@ const ORM_NETWORK_SUBS = new Set(['plan', 'apply', 'execute']);
17
17
  const ORM_USAGE = `usage:
18
18
  seq-studio orm init <dir> scaffold a namespace package (v2: TypeScript schema + GraphQL documents)
19
19
  seq-studio orm generate [dir] write schema.graphql + operations.manifest.json + typePolicies.gen.ts (offline; runs consumer codegen when codegen.ts is present)
20
+ seq-studio orm generate [dir] --migration-export [--check]
21
+ export reviewed ORM inputs for a coordinated pipeline migration; --check verifies without writing
20
22
  seq-studio orm validate [dir] parse + validate definitions and verify committed migrations are in sync
21
23
  seq-studio orm plan [dir] -e <env> compile definitions and diff against the registry
22
24
  seq-studio orm apply [dir] -e <env> author the migration, register, apply, and refresh the generated outputs (the everyday command)
@@ -0,0 +1,16 @@
1
+ import type { OrmSyncedTableContract } from '@sequenceholdings/orm';
2
+ import type { ResolvedEnv } from '../config.js';
3
+ type OrmModule = typeof import('@sequenceholdings/orm');
4
+ interface ContractStage {
5
+ readonly satisfies: {
6
+ readonly namespace: string;
7
+ readonly table: string;
8
+ };
9
+ }
10
+ export declare function loadActiveOrmContracts({ env, orm, stages, token, }: {
11
+ env: ResolvedEnv;
12
+ orm: OrmModule;
13
+ stages: readonly ContractStage[];
14
+ token: string;
15
+ }): Promise<Record<string, OrmSyncedTableContract>>;
16
+ export {};
@@ -0,0 +1,36 @@
1
+ import { z } from 'zod';
2
+ import { getJson } from '../atlas-client.js';
3
+ const namespaceResponseSchema = z.object({
4
+ active_definition: z.unknown().nullable(),
5
+ active_definition_format: z.number().int().nullable(),
6
+ });
7
+ export async function loadActiveOrmContracts({ env, orm, stages, token, }) {
8
+ const namespaces = [...new Set(stages.map((stage) => stage.satisfies.namespace))];
9
+ const definitions = new Map();
10
+ await Promise.all(namespaces.map(async (namespace) => {
11
+ const response = namespaceResponseSchema.parse(await getJson({
12
+ baseUrl: env.url,
13
+ token,
14
+ path: `/api/orm/namespaces/${encodeURIComponent(namespace)}`,
15
+ }));
16
+ if (response.active_definition_format !== 2 || response.active_definition === null) {
17
+ throw new Error(`ORM namespace '${namespace}' has no active v2 definition in ${env.name}`);
18
+ }
19
+ definitions.set(namespace, orm.canonicalDefinitionSchema.parse(response.active_definition));
20
+ }));
21
+ const contracts = {};
22
+ for (const stage of stages) {
23
+ const binding = stage.satisfies;
24
+ const key = `${binding.namespace}.${binding.table}`;
25
+ const definition = definitions.get(binding.namespace);
26
+ const table = definition?.tables.find((candidate) => candidate.table === binding.table);
27
+ if (!table) {
28
+ throw new Error(`active ORM definition does not contain synced table '${key}'`);
29
+ }
30
+ contracts[key] = orm.extractOrmSyncedTableContract({
31
+ namespace: binding.namespace,
32
+ table,
33
+ });
34
+ }
35
+ return contracts;
36
+ }
@@ -0,0 +1,25 @@
1
+ export interface PendingFileWrite {
2
+ readonly path: string;
3
+ readonly contents: string;
4
+ }
5
+ export interface FileWriteOperations {
6
+ readonly copy: (input: {
7
+ source: string;
8
+ destination: string;
9
+ }) => Promise<void>;
10
+ readonly move: (input: {
11
+ source: string;
12
+ destination: string;
13
+ }) => Promise<void>;
14
+ readonly remove: (input: {
15
+ path: string;
16
+ }) => Promise<void>;
17
+ readonly write: (input: {
18
+ path: string;
19
+ contents: string;
20
+ }) => Promise<void>;
21
+ }
22
+ export declare function commitFileWrites({ writes, operations, }: {
23
+ writes: readonly PendingFileWrite[];
24
+ operations?: FileWriteOperations;
25
+ }): Promise<void>;
@@ -0,0 +1,74 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { copyFile, rename, rm, writeFile } from 'node:fs/promises';
3
+ const DEFAULT_FILE_WRITE_OPERATIONS = {
4
+ copy: async ({ source, destination }) => copyFile(source, destination),
5
+ move: async ({ source, destination }) => rename(source, destination),
6
+ remove: async ({ path }) => rm(path, { force: true }),
7
+ write: async ({ path, contents }) => writeFile(path, contents, 'utf8'),
8
+ };
9
+ export async function commitFileWrites({ writes, operations = DEFAULT_FILE_WRITE_OPERATIONS, }) {
10
+ const transactionId = randomUUID();
11
+ const files = writes.map((write, index) => ({
12
+ ...write,
13
+ stagedPath: `${write.path}.repin-stage-${transactionId}-${index}`,
14
+ backupPath: `${write.path}.repin-backup-${transactionId}-${index}`,
15
+ hadOriginal: false,
16
+ committed: false,
17
+ }));
18
+ try {
19
+ for (const file of files) {
20
+ await operations.write({ path: file.stagedPath, contents: file.contents });
21
+ }
22
+ for (const file of files) {
23
+ try {
24
+ await operations.copy({ source: file.path, destination: file.backupPath });
25
+ file.hadOriginal = true;
26
+ }
27
+ catch (error) {
28
+ if (!(error instanceof Error && Reflect.get(error, 'code') === 'ENOENT'))
29
+ throw error;
30
+ }
31
+ }
32
+ for (const file of files) {
33
+ await operations.move({ source: file.stagedPath, destination: file.path });
34
+ file.committed = true;
35
+ }
36
+ }
37
+ catch (error) {
38
+ const rollbackFailures = [];
39
+ const recoveryBackups = new Set();
40
+ for (const file of [...files].reverse()) {
41
+ if (!file.committed)
42
+ continue;
43
+ try {
44
+ if (file.hadOriginal) {
45
+ await operations.move({ source: file.backupPath, destination: file.path });
46
+ }
47
+ else {
48
+ await operations.remove({ path: file.path });
49
+ }
50
+ }
51
+ catch (rollbackError) {
52
+ rollbackFailures.push(rollbackError);
53
+ if (file.hadOriginal)
54
+ recoveryBackups.add(file.backupPath);
55
+ }
56
+ }
57
+ await cleanupFiles({ files, operations, preserveBackups: recoveryBackups });
58
+ if (rollbackFailures.length > 0) {
59
+ throw new AggregateError([error, ...rollbackFailures], 'ORM repin file update failed and rollback was incomplete; recovery backups: ' +
60
+ ([...recoveryBackups].join(', ') || 'none'));
61
+ }
62
+ throw error;
63
+ }
64
+ await cleanupFiles({ files, operations });
65
+ }
66
+ async function cleanupFiles({ files, operations, preserveBackups = new Set(), }) {
67
+ await Promise.allSettled(files.flatMap((file) => {
68
+ const cleanup = [operations.remove({ path: file.stagedPath })];
69
+ if (!preserveBackups.has(file.backupPath)) {
70
+ cleanup.push(operations.remove({ path: file.backupPath }));
71
+ }
72
+ return cleanup;
73
+ }));
74
+ }
@@ -33,14 +33,21 @@ const PIPELINE_USAGE = `usage:
33
33
  supplies ORM synced-table contracts for serving satisfies pins. Exits 1 on
34
34
  any error-severity finding.
35
35
 
36
+ seq-studio pipeline repin-orm [dir] -e <env> [--target <id>] [--dry-run]
37
+ fetch active ORM synced-table contracts, verify serving compatibility,
38
+ then update orm-contracts.json and every matching satisfies.content_hash;
39
+ target is inferred when the environment exposes exactly one
40
+
36
41
  seq-studio pipeline codegen tables [--from <authoring.ts>] [--dir <dir>] [--dry-run] [--force]
37
42
  emit one <stage>.stage.yml per table from a typed PerTableIngestionAuthoring
38
43
  module (default export, authoring, or silverlakeAuthoring export name)
39
44
 
40
- seq-studio pipeline plan --repo pipelines/<slug> --ref <sha|branch> -e <env> [--target <id>] [--json]
45
+ seq-studio pipeline plan --repo pipelines/<slug> --ref <sha|branch> -e <env> [--target <id>] [--migration <id>] [--json]
41
46
  enqueue a durable plan, poll progress, then print the completed
42
47
  materialize + SDK/graph + compile + live-diff + provision findings
43
48
  (no Databricks CLI / DAB validate on Atlas); exit 1 on destructive findings
49
+ --migration adds a coordinated writer/ORM assessment; it cannot be
50
+ applied through ordinary deploy
44
51
 
45
52
  seq-studio pipeline deploy --repo pipelines/<slug> --ref <sha|branch> -e <env>
46
53
  [--target <id>] [--approved-by <sub>]
@@ -58,6 +65,11 @@ const PIPELINE_USAGE = `usage:
58
65
  seq-studio pipeline status --deployment-id <id> -e <env> [--json]
59
66
  fetch the current status of a remote deployment without changing it
60
67
 
68
+ seq-studio pipeline migrate status --run-id <id> -e <env> [--target <id>] [--json]
69
+ seq-studio pipeline migrate <start|resume|cancel> --run-id <id> --plan-hash <hash> -e <env> [--target <id>] [--json]
70
+ report migration phases, retained native attempts, and failed/retrying
71
+ tasks; this read does not start or resume any work
72
+
61
73
  seq-studio pipeline promote --stage <slug> --version <v> -e <env>
62
74
  [--target <id>] [--repo pipelines/<slug>] [--approved-by <you>]
63
75
  [--wait-timeout <duration>] [--no-wait]
@@ -393,6 +405,10 @@ export async function runPipelineCommand(sub, args) {
393
405
  return pipelineInitCommand(args);
394
406
  case 'validate':
395
407
  return pipelineValidateCommand(args);
408
+ case 'repin-orm': {
409
+ const { pipelineRepinOrmCommand } = await import('./repin-orm.js');
410
+ return pipelineRepinOrmCommand(args);
411
+ }
396
412
  case 'codegen': {
397
413
  const codegenSub = args.positional[0];
398
414
  if (codegenSub === 'tables') {
@@ -422,6 +438,10 @@ export async function runPipelineCommand(sub, args) {
422
438
  const { pipelineStatusCommand } = await import('./lifecycle.js');
423
439
  return pipelineStatusCommand(args);
424
440
  }
441
+ case 'migrate': {
442
+ const { runPipelineMigrationCommand } = await import('./migrations.js');
443
+ return runPipelineMigrationCommand(args);
444
+ }
425
445
  case 'promote': {
426
446
  const { pipelinePromoteCommand } = await import('./lifecycle.js');
427
447
  return pipelinePromoteCommand(args);
@@ -24,7 +24,21 @@ export interface PlanApiResponse {
24
24
  commit: string;
25
25
  environment: string;
26
26
  bundleName: string;
27
+ migrationAssessment?: {
28
+ mode: 'assessment';
29
+ contracts: {
30
+ findings: Array<{
31
+ severity: string;
32
+ }>;
33
+ };
34
+ };
27
35
  };
36
+ migration?: {
37
+ runId: string;
38
+ planHash: string;
39
+ migrationId: string;
40
+ environment: string;
41
+ } | null;
28
42
  deploymentIds: string[];
29
43
  stageIds: string[];
30
44
  text: string;
@@ -40,7 +54,21 @@ export interface DeploymentDetail {
40
54
  statusDetail: string | null;
41
55
  triggerRunId?: string | null;
42
56
  }
57
+ export interface PipelineTarget {
58
+ id: string;
59
+ label: string;
60
+ requiresApproval: boolean;
61
+ }
62
+ export declare function envAndToken(args: ParsedArgs): Promise<{
63
+ env: ResolvedEnv;
64
+ token: string;
65
+ }>;
43
66
  export declare function deployEnvironmentForEnv(env: ResolvedEnv): string;
67
+ export declare function resolvePipelineTarget({ args, env, token, }: {
68
+ args: ParsedArgs;
69
+ env: ResolvedEnv;
70
+ token: string;
71
+ }): Promise<PipelineTarget>;
44
72
  export declare function pipelinePlanCommand(args: ParsedArgs): Promise<number>;
45
73
  export declare function pipelineDeployCommand(args: ParsedArgs): Promise<number>;
46
74
  export declare function pipelineStatusCommand(args: ParsedArgs): Promise<number>;
@@ -36,7 +36,7 @@ function deploymentStatusLabel(detail) {
36
36
  return `${detail.status} — ${detail.statusDetail}`;
37
37
  return detail.status;
38
38
  }
39
- async function envAndToken(args) {
39
+ export async function envAndToken(args) {
40
40
  const requested = typeof args.flags.e === 'string' ? args.flags.e : typeof args.flags.env === 'string' ? args.flags.env : undefined;
41
41
  if (!requested) {
42
42
  throw new Error('missing -e/--env <environment>');
@@ -82,7 +82,7 @@ function repeatedFlagStrings(args, key) {
82
82
  export function deployEnvironmentForEnv(env) {
83
83
  return env.name === 'local' ? 'dev' : env.name;
84
84
  }
85
- async function resolvePipelineTarget({ args, env, token, }) {
85
+ export async function resolvePipelineTarget({ args, env, token, }) {
86
86
  const requested = flagString(args.flags, 'target');
87
87
  const inferredId = requested ?? deployEnvironmentForEnv(env);
88
88
  if (!requested) {
@@ -108,8 +108,9 @@ async function resolvePipelineTarget({ args, env, token, }) {
108
108
  export async function pipelinePlanCommand(args) {
109
109
  const repo = flagString(args.flags, 'repo');
110
110
  const ref = flagString(args.flags, 'ref');
111
+ const migrationId = flagString(args.flags, 'migration');
111
112
  if (!repo || !ref) {
112
- console.error('usage: seq-studio pipeline plan --repo pipelines/<slug> --ref <sha|branch> -e <env> [--json]');
113
+ console.error('usage: seq-studio pipeline plan --repo pipelines/<slug> --ref <sha|branch> -e <env> [--migration <id>] [--json]');
113
114
  return 1;
114
115
  }
115
116
  const { env, token } = await envAndToken(args);
@@ -130,6 +131,7 @@ export async function pipelinePlanCommand(args) {
130
131
  repo,
131
132
  ref,
132
133
  environment: target.id,
134
+ ...(migrationId ? { migrationId } : {}),
133
135
  });
134
136
  }
135
137
  catch (error) {
@@ -143,9 +145,15 @@ export async function pipelinePlanCommand(args) {
143
145
  console.log(response.text);
144
146
  printFindingsTable(response.plan.findings);
145
147
  }
146
- return response.plan.hasDestructive ? 1 : 0;
148
+ if (migrationId && response.migration)
149
+ return 0;
150
+ return response.plan.hasDestructive || response.plan.migrationAssessment?.contracts.findings.some((finding) => finding.severity === 'error') ? 1 : 0;
147
151
  }
148
152
  export async function pipelineDeployCommand(args) {
153
+ if (args.flags.migration !== undefined) {
154
+ console.error(`${LOG} --migration belongs to pipeline plan; an assessment cannot be applied as an ordinary deployment`);
155
+ return 1;
156
+ }
149
157
  const repo = flagString(args.flags, 'repo');
150
158
  const ref = flagString(args.flags, 'ref');
151
159
  const deploymentId = flagString(args.flags, 'deployment-id');
@@ -504,12 +512,12 @@ async function pollDeployment({ baseUrl, token, deploymentId, environment, timeo
504
512
  `(or, for internal operators: seqapi get /api/data-pipelines/deployments/${deploymentId} -e ${environment})`);
505
513
  return 1;
506
514
  }
507
- async function enqueueAndWaitForPlan({ baseUrl, token, repo, ref, environment, }) {
515
+ async function enqueueAndWaitForPlan({ baseUrl, token, repo, ref, environment, migrationId, }) {
508
516
  const enqueue = await postJson({
509
517
  baseUrl,
510
518
  token,
511
519
  path: '/api/data-pipelines/pipelines/plan',
512
- body: { repo, ref, environment },
520
+ body: { repo, ref, environment, ...(migrationId ? { migration_id: migrationId } : {}) },
513
521
  });
514
522
  console.log(`${LOG} enqueued plan ${enqueue.planRequestId} (trigger=${enqueue.triggerRunId ?? 'n/a'})`);
515
523
  const detail = await waitForPlanRequest({
@@ -525,6 +533,7 @@ async function enqueueAndWaitForPlan({ baseUrl, token, repo, ref, environment, }
525
533
  deploymentIds: detail.deploymentIds,
526
534
  stageIds: detail.stageIds,
527
535
  text: detail.text,
536
+ ...(detail.migration ? { migration: detail.migration } : {}),
528
537
  };
529
538
  }
530
539
  async function waitForPlanRequest({ baseUrl, token, planRequestId, }) {
@@ -0,0 +1,2 @@
1
+ import type { ParsedArgs } from '../process/commands.js';
2
+ export declare function runPipelineMigrationCommand(args: ParsedArgs): Promise<number>;
@@ -0,0 +1,61 @@
1
+ import { z } from 'zod';
2
+ import { getJson, postJson } from '../atlas-client.js';
3
+ import { envAndToken, resolvePipelineTarget } from './lifecycle.js';
4
+ const LOG = '[seq-studio]';
5
+ const USAGE = 'usage: seq-studio pipeline migrate <status|start|resume|cancel> --run-id <id> -e <env> [--target <id>] [--plan-hash <hash>] [--json]';
6
+ function printStatus(detail) {
7
+ console.log(`${LOG} migration ${detail.migrationId} (${detail.runId}): ${detail.status}`);
8
+ console.log(`${LOG} ${detail.repo} → ${detail.environment}`);
9
+ if (detail.statusDetail)
10
+ console.log(`${LOG} ${detail.statusDetail}`);
11
+ for (const phase of detail.phases)
12
+ console.log(`${LOG} ${phase.phase}: ${phase.completedSteps}/${phase.totalSteps} steps verified${phase.needsAttention ? ' — needs attention' : ''}`);
13
+ for (const step of detail.steps.filter((item) => item.needsAttention || item.status === 'running')) {
14
+ console.log(`${LOG} ${step.resource}: ${step.status}${step.errorCode ? ` (${step.errorCode})` : ''}`);
15
+ for (const attempt of step.attempts)
16
+ console.log(`${LOG} attempt ${attempt.number}: ${attempt.status}${attempt.operationId ? `; native ${attempt.operationId}` : ''}`);
17
+ }
18
+ if (detail.cancelRequested && !['cancelled', 'succeeded'].includes(detail.status))
19
+ console.log(`${LOG} cancellation requested; the worker stops at a safe checkpoint`);
20
+ if (detail.status === 'recovery_required')
21
+ console.log(`${LOG} ${detail.publicationStarted ? 'publication has begun; ' : ''}resource reservations are retained for recovery`);
22
+ }
23
+ export async function runPipelineMigrationCommand(args) {
24
+ const runId = args.flags['run-id'];
25
+ const action = args.positional[0];
26
+ const planHash = args.flags['plan-hash'];
27
+ if (!['status', 'start', 'resume', 'cancel'].includes(action ?? '') || !z.uuid().safeParse(runId).success || (action !== 'status' && !z.string().regex(/^[a-f0-9]{64}$/).safeParse(planHash).success)) {
28
+ console.error(USAGE);
29
+ return 1;
30
+ }
31
+ try {
32
+ const { env, token } = await envAndToken(args);
33
+ const target = await resolvePipelineTarget({ args, env, token });
34
+ if (action !== 'status') {
35
+ const result = await postJson({ baseUrl: env.url, token,
36
+ path: `/api/data-pipelines/migrations/${runId}`, body: { action, environment: target.id, planHash },
37
+ });
38
+ if (args.flags.json === true || args.flags.json === 'true')
39
+ console.log(JSON.stringify(result, null, 2));
40
+ else {
41
+ console.log(`${LOG} migration ${result.runId}: ${result.status}${result.triggerRunId ? ` (worker=${result.triggerRunId})` : ''}`);
42
+ console.log(`${LOG} check progress: seq-studio pipeline migrate status --run-id ${result.runId} -e ${env.name} --target ${target.id}`);
43
+ if (result.status === 'recovery_required')
44
+ console.log(`${LOG} migration needs recovery; inspect status before resuming`);
45
+ }
46
+ return result.status === 'recovery_required' ? 1 : 0;
47
+ }
48
+ const detail = await getJson({ baseUrl: env.url, token,
49
+ path: `/api/data-pipelines/migrations/${runId}?environment=${encodeURIComponent(target.id)}`,
50
+ });
51
+ if (args.flags.json === true || args.flags.json === 'true')
52
+ console.log(JSON.stringify(detail, null, 2));
53
+ else
54
+ printStatus(detail);
55
+ return ['failed', 'recovery_required'].includes(detail.status) || detail.steps.some((step) => step.needsAttention) ? 1 : 0;
56
+ }
57
+ catch (error) {
58
+ console.error(`${LOG} migration ${action} failed: ${error instanceof Error ? error.message : String(error)}`);
59
+ return 1;
60
+ }
61
+ }
@@ -0,0 +1,2 @@
1
+ import type { ParsedArgs } from '../process/commands.js';
2
+ export declare function pipelineRepinOrmCommand(args: ParsedArgs): Promise<number>;
@@ -0,0 +1,196 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { z } from 'zod';
4
+ import { getAccessToken } from '../auth.js';
5
+ import { resolveEnvWithDiscovery } from '../config.js';
6
+ import { loadActiveOrmContracts } from './active-orm-contracts.js';
7
+ import { commitFileWrites } from './atomic-file-writes.js';
8
+ import { resolvePipelineTarget } from './lifecycle.js';
9
+ const LOG = '[seq-studio]';
10
+ const ORM_CONTRACTS_FILENAME = 'orm-contracts.json';
11
+ async function loadModules() {
12
+ return {
13
+ spec: await import('@sequenceholdings/pipeline-spec'),
14
+ orm: await import('@sequenceholdings/orm'),
15
+ };
16
+ }
17
+ function requestedEnvironment(args) {
18
+ const value = args.flags.e ?? args.flags.env;
19
+ return typeof value === 'string' ? value : undefined;
20
+ }
21
+ function hasOrmPin(stage) {
22
+ return stage.type === 'serving' && stage.satisfies !== undefined;
23
+ }
24
+ async function loadExistingCatalog({ path, spec, }) {
25
+ let raw;
26
+ try {
27
+ raw = await readFile(path, 'utf8');
28
+ }
29
+ catch (error) {
30
+ if (error instanceof Error && Reflect.get(error, 'code') === 'ENOENT')
31
+ return {};
32
+ throw error;
33
+ }
34
+ const parsed = JSON.parse(raw);
35
+ spec.ormContractCatalogSchema.parse(parsed);
36
+ return z.record(z.string(), z.unknown()).parse(parsed);
37
+ }
38
+ function assertNoUntargetedContractCollisions({ contracts, pinnedStages, target, }) {
39
+ for (const stage of pinnedStages) {
40
+ if (stage.environments.includes(target))
41
+ continue;
42
+ const key = `${stage.satisfies.namespace}.${stage.satisfies.table}`;
43
+ const refreshed = contracts[key];
44
+ if (refreshed && refreshed.content_hash !== stage.satisfies.content_hash) {
45
+ throw new Error(`cannot repin '${key}' for target '${target}': untargeted stage '${stage.stage}' ` +
46
+ `pins ${stage.satisfies.content_hash.slice(0, 12)}… while ${target} requires ` +
47
+ `${refreshed.content_hash.slice(0, 12)}…; align the environments' ORM contracts first`);
48
+ }
49
+ }
50
+ }
51
+ function environmentNameForTarget(target) {
52
+ if (target === 'dev')
53
+ return 'local';
54
+ if (target === 'staging' || target === 'production' || target === 'banksouth')
55
+ return target;
56
+ return undefined;
57
+ }
58
+ async function assertSharedStageContractsAgree({ contracts, orm, stages, target, }) {
59
+ const otherTargets = new Set(stages.flatMap((stage) => stage.environments.filter((candidate) => candidate !== target)));
60
+ for (const otherTarget of otherTargets) {
61
+ const environmentName = environmentNameForTarget(otherTarget);
62
+ if (!environmentName) {
63
+ throw new Error(`cannot verify shared ORM pins for target '${otherTarget}'; ` +
64
+ 'split multi-target stages or use environment-specific pins');
65
+ }
66
+ const otherEnv = await resolveEnvWithDiscovery({ requested: environmentName });
67
+ const otherToken = await getAccessToken({ env: otherEnv.name, targetUrl: otherEnv.url });
68
+ const sharedStages = stages.filter((stage) => stage.environments.includes(otherTarget));
69
+ const otherContracts = await loadActiveOrmContracts({
70
+ env: otherEnv,
71
+ orm,
72
+ stages: sharedStages,
73
+ token: otherToken,
74
+ });
75
+ for (const stage of sharedStages) {
76
+ const key = `${stage.satisfies.namespace}.${stage.satisfies.table}`;
77
+ if (contracts[key]?.content_hash !== otherContracts[key]?.content_hash) {
78
+ throw new Error(`cannot repin shared stage '${stage.stage}': active ORM contract '${key}' ` +
79
+ `differs between targets '${target}' and '${otherTarget}'`);
80
+ }
81
+ }
82
+ }
83
+ }
84
+ function replacePinnedHash({ contents, currentHash, nextHash, file, }) {
85
+ const pattern = new RegExp(`(^\\s*content_hash:\\s*)(["']?)${currentHash}\\2(\\s*(?:#.*)?$)`, 'gm');
86
+ const matches = [...contents.matchAll(pattern)];
87
+ if (matches.length !== 1) {
88
+ throw new Error(`${file}: expected exactly one satisfies.content_hash value '${currentHash}', found ${matches.length}`);
89
+ }
90
+ return contents.replace(pattern, `$1$2${nextHash}$2$3`);
91
+ }
92
+ export async function pipelineRepinOrmCommand(args) {
93
+ const requested = requestedEnvironment(args);
94
+ if (!requested) {
95
+ console.error('usage: seq-studio pipeline repin-orm [dir] -e <env> [--target <id>] [--dry-run]');
96
+ return 1;
97
+ }
98
+ const dirArg = args.positional[0] ?? '.';
99
+ const dir = resolve(dirArg);
100
+ const dryRun = args.flags['dry-run'] === true || args.flags['dry-run'] === 'true';
101
+ try {
102
+ const { spec, orm } = await loadModules();
103
+ const pipeline = await spec.loadSpecDirectory(dir);
104
+ const allPinnedStages = pipeline.stages.filter(hasOrmPin);
105
+ if (allPinnedStages.length === 0) {
106
+ console.log(`${LOG} no ORM satisfies pins found in ${dirArg}`);
107
+ return 0;
108
+ }
109
+ const env = await resolveEnvWithDiscovery({ requested });
110
+ const token = await getAccessToken({ env: env.name, targetUrl: env.url });
111
+ const target = (await resolvePipelineTarget({ args, env, token })).id;
112
+ const pinnedStages = allPinnedStages.filter((stage) => stage.environments.includes(target));
113
+ if (pinnedStages.length === 0) {
114
+ console.log(`${LOG} no ORM satisfies pins target ${target} in ${dirArg}`);
115
+ return 0;
116
+ }
117
+ const contracts = await loadActiveOrmContracts({ env, orm, stages: pinnedStages, token });
118
+ const nextHashes = new Map();
119
+ for (const stage of pinnedStages) {
120
+ const binding = stage.satisfies;
121
+ const key = `${binding.namespace}.${binding.table}`;
122
+ const contract = contracts[key];
123
+ if (!contract)
124
+ throw new Error(`missing active ORM contract for '${key}'`);
125
+ nextHashes.set(stage.stage, contract.content_hash);
126
+ }
127
+ await assertSharedStageContractsAgree({
128
+ contracts,
129
+ orm,
130
+ stages: pinnedStages,
131
+ target,
132
+ });
133
+ assertNoUntargetedContractCollisions({
134
+ contracts,
135
+ pinnedStages: allPinnedStages,
136
+ target,
137
+ });
138
+ const catalogPath = join(dir, ORM_CONTRACTS_FILENAME);
139
+ const existingContracts = await loadExistingCatalog({ path: catalogPath, spec });
140
+ const mergedContracts = { ...existingContracts, ...contracts };
141
+ const catalog = spec.ormContractCatalogSchema.parse(mergedContracts);
142
+ const compatibilityErrors = pinnedStages.flatMap((stage) => {
143
+ const contentHash = nextHashes.get(stage.stage);
144
+ if (!contentHash)
145
+ throw new Error(`missing active ORM contract for stage '${stage.stage}'`);
146
+ const key = `${stage.satisfies.namespace}.${stage.satisfies.table}`;
147
+ return spec
148
+ .checkServingSatisfiesOrmContract({
149
+ projection: {
150
+ columns: spec.requireResolvedColumns(stage.projection.columns, `${stage.stage}.projection.columns`),
151
+ primary_key: stage.projection.primary_key,
152
+ },
153
+ satisfies: { ...stage.satisfies, content_hash: contentHash },
154
+ contract: catalog[key],
155
+ })
156
+ .filter((finding) => finding.severity === 'error');
157
+ });
158
+ if (compatibilityErrors.length > 0) {
159
+ compatibilityErrors.forEach((finding) => console.error(`error(${finding.code}): ${finding.message}`));
160
+ console.error(`${LOG} refusing to repin: active ORM contracts are incompatible`);
161
+ return 1;
162
+ }
163
+ const writes = [];
164
+ for (const stage of pinnedStages) {
165
+ const file = pipeline.files.find((candidate) => candidate === `${stage.stage}.stage.yml` ||
166
+ candidate === `${stage.stage}.stage.yaml`) ?? `${stage.stage}.stage.yml`;
167
+ const current = await readFile(join(dir, file), 'utf8');
168
+ const nextHash = nextHashes.get(stage.stage);
169
+ if (!nextHash)
170
+ throw new Error(`missing active ORM contract for stage '${stage.stage}'`);
171
+ writes.push({
172
+ path: join(dir, file),
173
+ contents: replacePinnedHash({
174
+ contents: current,
175
+ currentHash: stage.satisfies.content_hash,
176
+ nextHash,
177
+ file,
178
+ }),
179
+ });
180
+ }
181
+ writes.push({
182
+ path: catalogPath,
183
+ contents: `${JSON.stringify(mergedContracts, null, 2)}\n`,
184
+ });
185
+ if (!dryRun) {
186
+ await commitFileWrites({ writes });
187
+ }
188
+ const changed = pinnedStages.filter((stage) => stage.satisfies.content_hash !== nextHashes.get(stage.stage)).length;
189
+ console.log(`${LOG} ${dryRun ? 'would repin' : 'repinned'} ${changed} of ${pinnedStages.length} ORM contract pin(s) from ${env.name}`);
190
+ return 0;
191
+ }
192
+ catch (error) {
193
+ console.error(`${LOG} ORM repin failed: ${error instanceof Error ? error.message : String(error)}`);
194
+ return 1;
195
+ }
196
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sequenceholdings/studio-cli",
3
- "version": "0.1.29",
3
+ "version": "0.1.31",
4
4
  "description": "Unified Sequence Studio CLI — `seq-studio init` / `add` / `deploy` (app monorepos), `seq-studio agents`, `seq-studio process` (Lattice), `seq-studio artifact`, `seq-studio functions` / `secrets`, `seq-studio repos`, and `seq-studio auth pat`. Includes Auth0 browser login shared with seqapi.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -42,7 +42,7 @@
42
42
  "tsx": "^4.20.3",
43
43
  "zod": "^4.1.13",
44
44
  "@sequenceholdings/agent-spec": "0.1.2",
45
- "@sequenceholdings/artifact-studio": "0.2.3",
45
+ "@sequenceholdings/artifact-studio": "0.2.5",
46
46
  "@sequenceholdings/lattice": "0.1.3"
47
47
  },
48
48
  "peerDependencies": {
@@ -62,8 +62,8 @@
62
62
  "@types/node": "^22.0.0",
63
63
  "typescript": "^5.6.0",
64
64
  "vitest": "^4.1.11",
65
- "@sequenceholdings/orm": "2.0.0",
66
- "@sequenceholdings/pipeline-spec": "0.1.0"
65
+ "@sequenceholdings/pipeline-spec": "0.1.0",
66
+ "@sequenceholdings/orm": "2.0.0"
67
67
  },
68
68
  "engines": {
69
69
  "node": ">=20"