@sequenceholdings/studio-cli 0.2.0 → 0.2.2

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.
@@ -6,6 +6,9 @@
6
6
  * intentionally not supported — `seq-studio init` / `add` own this file.
7
7
  *
8
8
  * Version 2 is the app deployment graph; version 1 keeps its legacy ordering.
9
+ * Version 3 is version 2 plus Application `roles` (runtime access) and
10
+ * `collaborators` (edit access): the deploy also registers the bundle with
11
+ * Atlas so one role grant covers every member.
9
12
  */
10
13
  import { readFile, writeFile } from 'node:fs/promises';
11
14
  import { join, resolve } from 'node:path';
@@ -14,7 +17,8 @@ import { z } from 'zod';
14
17
  import { currentVersion, isNewerVersion } from '../update-check.js';
15
18
  import { validateManifestGraph } from './manifest-validation.js';
16
19
  export const APP_MANIFEST_FILENAME = 'sequence.app.yml';
17
- export const PRIMITIVE_KINDS = ['orm', 'function', 'agent', 'process', 'pipeline', 'artifact'];
20
+ // Order is the default deploy order: storage (ORM, workspaces) before the code that uses it.
21
+ export const PRIMITIVE_KINDS = ['orm', 'workspace', 'function', 'agent', 'process', 'pipeline', 'artifact'];
18
22
  export function isPrimitiveKind(value) {
19
23
  return PRIMITIVE_KINDS.includes(value);
20
24
  }
@@ -23,18 +27,33 @@ const appIdSchema = z
23
27
  .min(1)
24
28
  .max(64)
25
29
  .regex(/^[a-z][a-z0-9-]*$/, 'app id must be kebab-case (a-z, 0-9, -)');
30
+ /**
31
+ * A runtime dependency: this primitive uses another one while it runs (an
32
+ * artifact calls a function, a function stores files in a workspace). Unlike
33
+ * `depends_on` it doesn't order deploys — it feeds the Application's
34
+ * Dependencies graph in Atlas. `as` is a short label for the edge.
35
+ */
36
+ const primitiveUseSchema = z
37
+ .object({
38
+ primitive: z.string().min(1).max(128),
39
+ as: z.string().min(1).max(64).optional(),
40
+ })
41
+ .strict();
26
42
  const primitiveEntrySchema = z
27
43
  .object({
28
44
  id: z.string().min(1).max(128),
29
45
  kind: z.enum(PRIMITIVE_KINDS),
30
46
  path: z.string().min(1),
31
47
  depends_on: z.array(z.string().min(1)).default([]),
48
+ uses: z.array(primitiveUseSchema).default([]),
32
49
  namespace: z.string().min(1).optional(),
50
+ /** Workspaces V2 workspace name (matches `workspace.name` in the primitive's workspace.yml). */
51
+ name: z.string().regex(/^[a-z][a-z0-9-]{1,62}$/, 'workspace names are lowercase kebab-case, 2-63 characters').optional(),
33
52
  slug: z.string().min(1).optional(),
34
53
  project_id: z.string().min(1).optional(),
35
54
  target: z.string().min(1).optional(),
36
55
  only: z.array(z.string().min(1)).min(1).optional(),
37
- repo: z.string().regex(/^pipelines\/[a-z0-9][a-z0-9-]*$/).optional(),
56
+ repo: z.string().regex(/^(?:pipelines|apps)\/[a-z0-9][a-z0-9-]*$/).optional(),
38
57
  ref: z.string().min(1).refine((ref) => !ref.startsWith('-'), 'ref cannot start with -').optional(),
39
58
  })
40
59
  .strict()
@@ -42,6 +61,12 @@ const primitiveEntrySchema = z
42
61
  if (entry.kind === 'orm' && entry.namespace === undefined) {
43
62
  ctx.addIssue({ code: 'custom', message: `orm primitive "${entry.id}" requires namespace`, path: ['namespace'] });
44
63
  }
64
+ if (entry.kind === 'workspace' && entry.name === undefined) {
65
+ ctx.addIssue({ code: 'custom', message: `workspace primitive "${entry.id}" requires name`, path: ['name'] });
66
+ }
67
+ if (entry.name !== undefined && entry.kind !== 'workspace') {
68
+ ctx.addIssue({ code: 'custom', message: 'name is only used by workspace primitives', path: ['name'] });
69
+ }
45
70
  if (entry.kind === 'function' && entry.slug === undefined) {
46
71
  ctx.addIssue({ code: 'custom', message: `function primitive "${entry.id}" requires slug`, path: ['slug'] });
47
72
  }
@@ -53,11 +78,76 @@ const primitiveEntrySchema = z
53
78
  });
54
79
  }
55
80
  });
81
+ /** Custom-role key grammar, mirroring the Atlas registry. */
82
+ const ROLE_KEY_RE = /^[a-z0-9-]{1,64}$/;
83
+ const roleKeySchema = z.string().regex(ROLE_KEY_RE, 'role/capability keys are kebab-case (a-z, 0-9, -), at most 64 characters');
84
+ /**
85
+ * How YAML names a member's floor (the right to use it at all). `end_user` works
86
+ * on every member; `invoker` is accepted on functions and processes, where it's
87
+ * the native term.
88
+ */
89
+ export const FLOOR_ROLE_ALIASES = ['end_user', 'invoker'];
90
+ export function isFloorRoleAlias(value) {
91
+ return FLOOR_ROLE_ALIASES.includes(value);
92
+ }
93
+ const applicationRoleIncludeSchema = z
94
+ .object({
95
+ primitive: z.string().min(1),
96
+ role: z.string().min(1).max(64).optional(),
97
+ capability: roleKeySchema.optional(),
98
+ })
99
+ .strict()
100
+ .superRefine((include, ctx) => {
101
+ if ((include.role === undefined) === (include.capability === undefined)) {
102
+ ctx.addIssue({ code: 'custom', message: 'set exactly one of role or capability' });
103
+ }
104
+ if (include.role !== undefined && !isFloorRoleAlias(include.role) && !ROLE_KEY_RE.test(include.role)) {
105
+ ctx.addIssue({ code: 'custom', message: `invalid role "${include.role}"`, path: ['role'] });
106
+ }
107
+ });
108
+ const applicationRoleDefinitionSchema = z
109
+ .object({
110
+ description: z.string().max(1024).optional(),
111
+ inherits: z.array(roleKeySchema).default([]),
112
+ includes: z.array(applicationRoleIncludeSchema).default([]),
113
+ })
114
+ .strict();
115
+ /**
116
+ * Application roles (schema_version 3). Seeded on the first deploy that sees
117
+ * each key; after that Atlas owns the role and a changed definition here is
118
+ * reported as drift rather than applied.
119
+ */
120
+ export const applicationRolesSchema = z
121
+ .object({ definitions: z.record(roleKeySchema, applicationRoleDefinitionSchema) })
122
+ .strict();
123
+ /**
124
+ * The member tiers a collaborator role can bundle. Which tier each primitive
125
+ * kind offers is checked in manifest-validation.ts; admin and owner never
126
+ * are — they stay direct grants.
127
+ */
128
+ export const COLLABORATOR_TIERS = ['reader', 'writer', 'editor'];
129
+ const applicationCollaboratorDefinitionSchema = z
130
+ .object({
131
+ description: z.string().max(1024).optional(),
132
+ inherits: z.array(roleKeySchema).default([]),
133
+ includes: z
134
+ .array(z.object({ primitive: z.string().min(1), tier: z.enum(COLLABORATOR_TIERS) }).strict())
135
+ .default([]),
136
+ })
137
+ .strict();
138
+ /**
139
+ * Application collaborator roles (schema_version 3): bundle the tiers that
140
+ * let someone change a member — never use-only access, never admin. Seeded
141
+ * and owned by Atlas the same way `roles` are.
142
+ */
143
+ export const applicationCollaboratorsSchema = z
144
+ .object({ definitions: z.record(roleKeySchema, applicationCollaboratorDefinitionSchema) })
145
+ .strict();
56
146
  const relativeDirectorySchema = z.string().min(1).refine((path) => path.trim() === path && !path.includes('\\') && !/^[A-Za-z]:/.test(path) &&
57
147
  !/[\x00-\x1f]/.test(path) && path.split('/').every((part) => part !== '' && part !== '.' && part !== '..'), 'path must be a relative directory within the app root');
58
148
  export const appManifestSchema = z
59
149
  .object({
60
- schema_version: z.union([z.literal(1), z.literal(2)]),
150
+ schema_version: z.union([z.literal(1), z.literal(2), z.literal(3)]),
61
151
  app: z.object({
62
152
  id: appIdSchema,
63
153
  title: z.string().min(1),
@@ -78,6 +168,8 @@ export const appManifestSchema = z
78
168
  on_error: z.enum(['stop', 'continue']).default('stop'),
79
169
  }).strict()
80
170
  .default({ on_error: 'stop' }),
171
+ roles: applicationRolesSchema.optional(),
172
+ collaborators: applicationCollaboratorsSchema.optional(),
81
173
  }).strict()
82
174
  .superRefine(validateManifestGraph);
83
175
  /** Local helper so schema refinement does not depend on later exports. */
@@ -87,6 +179,10 @@ function defaultDeployOrderForValidation(primitives) {
87
179
  .sort((a, b) => rank(a.kind) - rank(b.kind) || a.id.localeCompare(b.id))
88
180
  .map((entry) => entry.id);
89
181
  }
182
+ /** Versions 2 and 3 share the deployment-graph semantics. */
183
+ export function usesAppGraph(manifest) {
184
+ return manifest.schema_version >= 2;
185
+ }
90
186
  /**
91
187
  * Fail closed when the installed CLI is older than `studio.min_cli`, so an
92
188
  * older binary cannot load / rewrite a manifest that requires newer semantics.
@@ -18,6 +18,7 @@ export function primitiveIdFor({ kind, name }) {
18
18
  case 'agent':
19
19
  case 'process':
20
20
  case 'pipeline':
21
+ case 'workspace':
21
22
  return `${name}-${kind}`;
22
23
  }
23
24
  }
@@ -35,12 +36,14 @@ export function relativePathFor({ kind, appId, name, }) {
35
36
  return join('processes', name);
36
37
  case 'pipeline':
37
38
  return join('pipelines', name);
39
+ case 'workspace':
40
+ return join('workspaces', name);
38
41
  }
39
42
  }
40
43
  function buildPrimitiveEntry({ kind, appId, name, dependsOn, }) {
41
44
  const path = relativePathFor({ kind, appId, name }).replace(/\\/g, '/');
42
45
  const id = primitiveIdFor({ kind, name });
43
- const base = { id, kind, path, depends_on: dependsOn };
46
+ const base = { id, kind, path, depends_on: dependsOn, uses: [] };
44
47
  switch (kind) {
45
48
  case 'orm':
46
49
  return { ...base, namespace: ormNamespaceFromAppId(name) };
@@ -48,6 +51,8 @@ function buildPrimitiveEntry({ kind, appId, name, dependsOn, }) {
48
51
  return { ...base, slug: name };
49
52
  case 'artifact':
50
53
  return { ...base, project_id: name };
54
+ case 'workspace':
55
+ return { ...base, name };
51
56
  case 'agent':
52
57
  case 'process':
53
58
  case 'pipeline':
@@ -131,6 +136,11 @@ export async function scaffoldKind({ kind, appRoot, appId, name, pipelineType =
131
136
  throw new Error(`pipeline init failed for ${absPath}`);
132
137
  }
133
138
  break;
139
+ case 'workspace':
140
+ await mkdir(absPath, { recursive: true });
141
+ // Same file `seq-studio storage init` writes.
142
+ await writeFile(join(absPath, 'workspace.yml'), `workspace:\n name: ${name}\n description: ""\n`, { flag: 'wx' });
143
+ break;
134
144
  }
135
145
  return entry;
136
146
  }
@@ -18,11 +18,13 @@ function primitivePath({ kind, appId, functionName }) {
18
18
  case 'process': return `processes/${appId}`;
19
19
  case 'pipeline': return `pipelines/${appId}`;
20
20
  case 'artifact': return 'artifact';
21
+ case 'workspace': return `workspaces/${appId}`;
21
22
  }
22
23
  }
23
24
  const PRIMITIVE_LABELS = {
24
25
  orm: 'ORM namespace', function: 'Managed Function', agent: 'Typed agent',
25
26
  process: 'Lattice process', pipeline: 'Data Pipeline', artifact: 'Artifact Studio UI',
27
+ workspace: 'Workspaces V2 workspace',
26
28
  };
27
29
  export function renderAppReadme(input) {
28
30
  const title = input.title?.trim() || titleizeSlug(input.appId);
@@ -33,7 +33,7 @@ function applyDefaultDependsOn(primitives) {
33
33
  }
34
34
  export async function initAppMonorepo({ rootDir, appId, kinds, names = defaultScaffoldNames(appId), description, pipelineType, }) {
35
35
  if (kinds.length === 0) {
36
- throw new Error('select at least one primitive via --with orm,function,agent,process,pipeline,artifact (or --orm --function …)');
36
+ throw new Error('select at least one primitive via --with orm,workspace,function,agent,process,pipeline,artifact (or --orm --function …)');
37
37
  }
38
38
  assertScaffoldName(appId);
39
39
  assertScaffoldName(names.functionName);
@@ -124,7 +124,8 @@ export async function addPrimitiveToApp({ rootDir, kind, name, pipelineType, dep
124
124
  entry = { ...entry, depends_on: [orm.id] };
125
125
  }
126
126
  const primitives = [...manifest.primitives, entry];
127
- const upgrade = manifest.schema_version === 1 && ['agent', 'process', 'pipeline'].includes(kind);
127
+ // Kinds version 1 doesn't know upgrade the app to version 2 on add.
128
+ const upgrade = manifest.schema_version === 1 && ['agent', 'process', 'pipeline', 'workspace'].includes(kind);
128
129
  const version = currentVersion();
129
130
  const next = {
130
131
  ...manifest,
@@ -3,7 +3,7 @@ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
3
3
  import { join } from 'node:path';
4
4
  import { dump as yamlDump, load as yamlLoad } from 'js-yaml';
5
5
  import { z } from 'zod';
6
- import { loadAppManifest, writeAppManifest } from './manifest.js';
6
+ import { loadAppManifest, usesAppGraph, writeAppManifest } from './manifest.js';
7
7
  import { currentVersion } from '../update-check.js';
8
8
  const packageSchema = z.looseObject({
9
9
  dependencies: z.record(z.string(), z.string()).optional(),
@@ -43,7 +43,7 @@ export async function scaffoldSharedPackage({ rootDir, appId, name, }) {
43
43
  /** Convert only freshly generated primitive files into members of the app workspace. */
44
44
  export async function joinAppWorkspace({ rootDir, manifest, entries, }) {
45
45
  const workspacePath = join(rootDir, 'pnpm-workspace.yaml');
46
- if (manifest.schema_version !== 2 || !existsSync(workspacePath))
46
+ if (!usesAppGraph(manifest) || !existsSync(workspacePath))
47
47
  return;
48
48
  const config = workspaceSchema.parse(yamlLoad(await readFile(workspacePath, 'utf8')));
49
49
  const paths = new Set(config.packages ?? []);
@@ -103,7 +103,7 @@ export async function scaffoldAppWorkspace({ rootDir, manifest, }) {
103
103
  export async function addSharedPackageToApp({ rootDir, name, }) {
104
104
  const manifest = await loadAppManifest(rootDir);
105
105
  const workspacePath = join(rootDir, 'pnpm-workspace.yaml');
106
- if (manifest.schema_version !== 2 || !existsSync(workspacePath)) {
106
+ if (!usesAppGraph(manifest) || !existsSync(workspacePath)) {
107
107
  throw new Error('adding a shared package requires a version 2 app with a root pnpm-workspace.yaml');
108
108
  }
109
109
  const packageName = `@${manifest.app.id}/${name}`;
@@ -32,6 +32,8 @@ const ARTIFACT_USAGE = `usage:
32
32
  seq-studio artifact whoami -e <env>
33
33
  seq-studio artifact env list
34
34
 
35
+ Add --help or -h to any artifact command to print this usage without running it.
36
+
35
37
  Environments: see \`seq-studio envs list\` (built-in: local; more are
36
38
  discovered after you authenticate).
37
39
 
@@ -70,6 +72,12 @@ export async function runArtifactCommand(sub, rest) {
70
72
  'AUTH0_M2M_CLIENT_SECRET for headless automation.');
71
73
  return 1;
72
74
  }
75
+ // Help must not resolve environments, authenticate, or dispatch a command.
76
+ if (!sub || sub === 'help' || sub === '--help' || sub === '-h' ||
77
+ rest.some((arg) => arg === '--help' || arg === '-h')) {
78
+ console.log(ARTIFACT_USAGE);
79
+ return sub ? 0 : 1;
80
+ }
73
81
  // Never pass a legacy bearer environment variable into the embedded package.
74
82
  delete process.env['ARTIFACT_STUDIO_TOKEN'];
75
83
  // Older artifact-studio versions exposed nested login/logout commands backed
@@ -84,10 +92,6 @@ export async function runArtifactCommand(sub, rest) {
84
92
  await auth[sub]();
85
93
  return 0;
86
94
  }
87
- if (!sub || sub === 'help' || sub === '--help' || sub === '-h') {
88
- console.log(ARTIFACT_USAGE);
89
- return sub ? 0 : 1;
90
- }
91
95
  // `artifact env list` renders the tier-aware discovered catalog instead of
92
96
  // artifact-studio's built-in (local-only) list.
93
97
  if (sub === 'env' && rest[0] === 'list') {
@@ -49,12 +49,16 @@ function nextStepForAtlasError(error) {
49
49
  return 'Next step: rerun deploy — another upload may have taken the version slot.';
50
50
  }
51
51
  if (error.status === 413 || msg.includes('too large')) {
52
+ if (error.path.startsWith('/api/data-pipelines/'))
53
+ return 'Next step: reduce the request size and retry; pipeline query accepts up to 10,000 SQL characters.';
52
54
  return 'Next step: run `seq-studio functions build` and reduce bundle size or dependencies.';
53
55
  }
54
56
  if (error.status === 503) {
55
57
  return 'Next step: wait a few seconds and retry (backend may still be warming up).';
56
58
  }
57
59
  if (error.status === 524 || msg.includes('timeout') || msg.includes('timed out')) {
60
+ if (error.path.startsWith('/api/data-pipelines/'))
61
+ return 'Next step: retry the read; if it persists, confirm the environment and backend availability.';
58
62
  return 'Next step: retry; if it persists check VPN/network, then `seq-studio functions list` or logs to see whether the operation completed.';
59
63
  }
60
64
  return null;
@@ -313,6 +313,8 @@ const TEMPLATE_NPMRC = `# Pins installs to Chainguard, Sequence's internal packa
313
313
  # always re-resolves dependencies against Chainguard server-side, and this
314
314
  # file is never included in the deployed bundle either way.
315
315
  registry=https://libraries.cgr.dev/javascript/
316
+ # Sequence's own packages publish to public npm, as on the deploy worker.
317
+ @sequenceholdings:registry=https://registry.npmjs.org/
316
318
  //libraries.cgr.dev/javascript/:always-auth=true
317
319
  //libraries.cgr.dev/javascript-upstream/:always-auth=true
318
320
  `;
package/dist/main.d.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  * seq-studio agents <sub> manage typed agent definitions
12
12
  * seq-studio secrets <sub> manage org-owned Managed Secrets
13
13
  * seq-studio repos <sub> manage platform git-service repos
14
- * seq-studio pipeline <sub> author + validate Data Pipelines stage specs
14
+ * seq-studio pipeline <sub> discover, query, author and operate Data Pipelines
15
15
  * seq-studio auth <sub> manage git-service PATs
16
16
  * seq-studio envs <sub> add/list/refresh environments
17
17
  * seq-studio login authenticate interactively with Auth0
package/dist/main.js CHANGED
@@ -11,7 +11,7 @@
11
11
  * seq-studio agents <sub> manage typed agent definitions
12
12
  * seq-studio secrets <sub> manage org-owned Managed Secrets
13
13
  * seq-studio repos <sub> manage platform git-service repos
14
- * seq-studio pipeline <sub> author + validate Data Pipelines stage specs
14
+ * seq-studio pipeline <sub> discover, query, author and operate Data Pipelines
15
15
  * seq-studio auth <sub> manage git-service PATs
16
16
  * seq-studio envs <sub> add/list/refresh environments
17
17
  * seq-studio login authenticate interactively with Auth0
@@ -34,7 +34,7 @@ const TOP_LEVEL_USAGE = `usage:
34
34
  seq-studio agents <sub> [args] init | validate | plan | apply | list | show
35
35
  seq-studio secrets <sub> [args] create | set | list | attach | detach | apply
36
36
  seq-studio repos <sub> [args] list | namespaces | show | create | clone | pull | delete
37
- seq-studio pipeline <sub> [args] init | validate — Data Pipelines stage specs
37
+ seq-studio pipeline <sub> [args] search | describe | schema | sample | query | list | assets | init | validate | plan | deploy | status
38
38
  seq-studio auth <sub> [args] pat create | pat list | pat revoke
39
39
  seq-studio orm <sub> [args] init | generate | validate | plan | apply | execute | diff | migrate-from-yaml
40
40
  seq-studio envs <sub> add | list | refresh environments
@@ -17,11 +17,13 @@ import { join, resolve } from 'node:path';
17
17
  import { authenticatedRequestUrl, validateDeploymentBaseUrl, } from '@sequenceholdings/artifact-studio/deployment-validation';
18
18
  import { tryGetAccessToken } from '../auth.js';
19
19
  import { readConfig } from '../config.js';
20
+ import { PIPELINE_DISCOVERY_USAGE, runPipelineDiscoveryCommand } from './discovery.js';
20
21
  import { renderEntrypointStub, renderStageTemplate, STAGE_TYPES, } from './templates.js';
21
22
  const LOG = '[seq-studio]';
22
23
  /** Conventional ORM contract catalog filename beside stage specs (CI auto-loads this). */
23
24
  export const ORM_CONTRACTS_FILENAME = 'orm-contracts.json';
24
25
  const PIPELINE_USAGE = `usage:
26
+ ${PIPELINE_DISCOVERY_USAGE}
25
27
  seq-studio pipeline init --type ingestion|transformation|serving <name> [--dir <dir>]
26
28
  scaffold <name>.stage.yml (commented template) + src/ entrypoint stub
27
29
 
@@ -407,6 +409,15 @@ export async function pipelineValidateCommand(args) {
407
409
  }
408
410
  export async function runPipelineCommand(sub, args) {
409
411
  switch (sub) {
412
+ case 'list':
413
+ case 'assets':
414
+ case 'search':
415
+ case 'describe':
416
+ case 'schema':
417
+ case 'sample':
418
+ case 'query': {
419
+ return runPipelineDiscoveryCommand({ sub, args });
420
+ }
410
421
  case 'init':
411
422
  return pipelineInitCommand(args);
412
423
  case 'validate':
@@ -0,0 +1,8 @@
1
+ import type { ParsedArgs } from '../process/commands.js';
2
+ type DiscoveryCommand = 'list' | 'assets' | 'search' | 'describe' | 'schema' | 'sample' | 'query';
3
+ export declare const PIPELINE_DISCOVERY_USAGE = " seq-studio pipeline list -e <env> [--limit 1..200] [--offset N] [--json]\n list pipeline repositories (default 50 per page), health and descriptions\n\n seq-studio pipeline assets -e <env> [--repo <namespace>/<name>] [--json]\n discover exact asset IDs from the latest declared specs; --repo filters\n both assets and the SDK export. Declarations may not be deployed yet.\n\n seq-studio pipeline search <query> -e <env> [--target <id>] [--repo <namespace>/<name>]\n [--limit 1..100] [--offset N] [--json]\n search active asset/column names and descriptions without contacting Databricks\n Case-insensitive literal text (1..200 characters); default 20 assets per page.\n\n seq-studio pipeline describe <asset> -e <env> [--target <id>] [--repo <namespace>/<name>] [--json]\n read active deployed descriptions and declared columns without contacting Databricks\n Includes deployment/source provenance; physical schema is not verified.\n\n seq-studio pipeline schema <asset> -e <env> [--target <id>] [--json]\n read observed columns, types and available descriptions from the active deployment\n\n seq-studio pipeline sample <asset> -e <env> [--target <id>] [--limit 1..100] [--json]\n preview rows (default 25); output reports deployment and truncation\n\n seq-studio pipeline query <asset> --sql <sql> -e <env> [--target <id>] [--limit 1..1000] [--json]\n run read-only SQL against the virtual relation asset (default limit 1000)\n Example: --sql 'SELECT * FROM asset LIMIT 5'. Cross-asset joins are unsupported.\n\n Discovery requires staff access. Search, then describe a relevant asset; use\n schema to verify physical columns, then sample and query values before authoring.\n Metadata reflects active deployments, not unactivated edits. Descriptions do not prove keys\n or relationships. Use --json for the full response, including deployment context.\n -e selects the connection; --target selects its logical deployment target when needed.\n";
4
+ export declare function runPipelineDiscoveryCommand({ sub, args }: {
5
+ sub: DiscoveryCommand;
6
+ args: ParsedArgs;
7
+ }): Promise<number>;
8
+ export {};
@@ -0,0 +1,249 @@
1
+ import { getAccessToken } from '../auth.js';
2
+ import { getJson, postJson } from '../atlas-client.js';
3
+ import { printCliError } from '../cli-errors.js';
4
+ import { resolveEnvWithDiscovery } from '../config.js';
5
+ import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
6
+ import { resolvePipelineTarget } from './lifecycle.js';
7
+ export const PIPELINE_DISCOVERY_USAGE = ` seq-studio pipeline list -e <env> [--limit 1..200] [--offset N] [--json]
8
+ list pipeline repositories (default 50 per page), health and descriptions
9
+
10
+ seq-studio pipeline assets -e <env> [--repo <namespace>/<name>] [--json]
11
+ discover exact asset IDs from the latest declared specs; --repo filters
12
+ both assets and the SDK export. Declarations may not be deployed yet.
13
+
14
+ seq-studio pipeline search <query> -e <env> [--target <id>] [--repo <namespace>/<name>]
15
+ [--limit 1..100] [--offset N] [--json]
16
+ search active asset/column names and descriptions without contacting Databricks
17
+ Case-insensitive literal text (1..200 characters); default 20 assets per page.
18
+
19
+ seq-studio pipeline describe <asset> -e <env> [--target <id>] [--repo <namespace>/<name>] [--json]
20
+ read active deployed descriptions and declared columns without contacting Databricks
21
+ Includes deployment/source provenance; physical schema is not verified.
22
+
23
+ seq-studio pipeline schema <asset> -e <env> [--target <id>] [--json]
24
+ read observed columns, types and available descriptions from the active deployment
25
+
26
+ seq-studio pipeline sample <asset> -e <env> [--target <id>] [--limit 1..100] [--json]
27
+ preview rows (default 25); output reports deployment and truncation
28
+
29
+ seq-studio pipeline query <asset> --sql <sql> -e <env> [--target <id>] [--limit 1..1000] [--json]
30
+ run read-only SQL against the virtual relation asset (default limit 1000)
31
+ Example: --sql 'SELECT * FROM asset LIMIT 5'. Cross-asset joins are unsupported.
32
+
33
+ Discovery requires staff access. Search, then describe a relevant asset; use
34
+ schema to verify physical columns, then sample and query values before authoring.
35
+ Metadata reflects active deployments, not unactivated edits. Descriptions do not prove keys
36
+ or relationships. Use --json for the full response, including deployment context.
37
+ -e selects the connection; --target selects its logical deployment target when needed.
38
+ `;
39
+ function valueFlag({ args, name }) {
40
+ const value = args.flags[name];
41
+ if (value === true || value?.trim() === '')
42
+ throw new Error(`--${name} requires a value`);
43
+ return value;
44
+ }
45
+ function integerFlag({ args, name, min, max }) {
46
+ const value = valueFlag({ args, name });
47
+ if (value === undefined)
48
+ return undefined;
49
+ const number = Number(value);
50
+ if (!/^\d+$/.test(value) || !Number.isSafeInteger(number) || number < min || number > max) {
51
+ throw new Error(`--${name} must be an integer from ${min} to ${max}`);
52
+ }
53
+ return number;
54
+ }
55
+ function discoveryEnvironment(args) {
56
+ const shortEnv = valueFlag({ args, name: 'e' });
57
+ const longEnv = valueFlag({ args, name: 'env' });
58
+ const values = [shortEnv, longEnv, ...args.repeatedFlags?.env ?? [], ...args.repeatedFlags?.e ?? []].filter(Boolean);
59
+ if (new Set(values).size > 1)
60
+ throw new Error('-e and --env must select the same environment');
61
+ const environment = shortEnv ?? longEnv;
62
+ if (!environment)
63
+ throw new Error(REQUIRE_EXPLICIT_ENV_MESSAGE);
64
+ return environment;
65
+ }
66
+ function validateDiscoveryArguments({ sub, args }) {
67
+ const readsAsset = sub === 'describe' || sub === 'schema' || sub === 'sample' || sub === 'query';
68
+ const readsPositional = readsAsset || sub === 'search';
69
+ const options = {
70
+ list: ['limit', 'offset'], assets: ['repo'], schema: ['target'],
71
+ search: ['target', 'repo', 'limit', 'offset'], describe: ['target', 'repo'],
72
+ sample: ['target', 'limit'], query: ['target', 'limit', 'sql'],
73
+ };
74
+ const allowed = new Set(['e', 'env', 'json', ...options[sub]]);
75
+ for (const flag of Object.keys(args.flags)) {
76
+ if (!allowed.has(flag))
77
+ throw new Error(`unknown option --${flag} for pipeline ${sub}; run seq-studio pipeline ${sub} --help`);
78
+ }
79
+ if (args.positional.length !== (readsPositional ? 1 : 0) || (readsPositional && !args.positional[0]?.trim())) {
80
+ const requirement = sub === 'search'
81
+ ? 'requires one search query; quote queries containing spaces'
82
+ : readsAsset ? 'requires one exact asset ID; discover IDs with pipeline search or pipeline assets' : 'does not accept positional arguments';
83
+ throw new Error(`pipeline ${sub} ${requirement}`);
84
+ }
85
+ const json = args.flags.json;
86
+ if (json !== undefined && json !== true && json !== 'true' && json !== 'false')
87
+ throw new Error('--json is a boolean flag; put the asset ID before options');
88
+ }
89
+ function discoveryOptions({ sub, args }) {
90
+ validateDiscoveryArguments({ sub, args });
91
+ const environment = discoveryEnvironment(args);
92
+ valueFlag({ args, name: 'target' });
93
+ const repo = valueFlag({ args, name: 'repo' });
94
+ if (repo && !/^[^/\s]+\/[^/\s]+$/.test(repo))
95
+ throw new Error('--repo must be <namespace>/<name>');
96
+ const sql = valueFlag({ args, name: 'sql' });
97
+ if (sub === 'query' && !sql)
98
+ throw new Error('pipeline query requires --sql, for example --sql "SELECT * FROM asset LIMIT 5"');
99
+ if (sql && sql.length > 10_000)
100
+ throw new Error('--sql must be at most 10000 characters');
101
+ const query = sub === 'search' ? args.positional[0].trim() : undefined;
102
+ if (query && query.length > 200)
103
+ throw new Error('search query must be at most 200 characters');
104
+ const limit = integerFlag({ args, name: 'limit', min: 1, max: sub === 'list' ? 200 : sub === 'sample' || sub === 'search' ? 100 : 1000 });
105
+ const offset = integerFlag({ args, name: 'offset', min: 0, max: Number.MAX_SAFE_INTEGER });
106
+ return { environment, json: args.flags.json === true || args.flags.json === 'true', repo, sql, query, limit, offset };
107
+ }
108
+ function cell(value) {
109
+ if (value === undefined)
110
+ return '—';
111
+ if (typeof value !== 'string')
112
+ return JSON.stringify(value) ?? '—';
113
+ // Preserve readable text while escaping control characters from source data.
114
+ return value.replace(/\p{Cc}/gu, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`);
115
+ }
116
+ function table({ headers, rows }) {
117
+ const lines = [headers, ...rows].map((row) => row.map(cell));
118
+ const widths = headers.map((_, index) => Math.max(...lines.map((line) => line[index]?.length ?? 0)));
119
+ for (const line of lines)
120
+ console.log(line.map((value, index) => value.padEnd(widths[index] ?? 0)).join(' ').trimEnd());
121
+ }
122
+ function printAssetResult(result) {
123
+ console.log(`Asset: ${cell(result.assetId)}`);
124
+ console.log(`Target: ${cell(result.environment)} | ${cell(result.target.engine)} | ${cell(result.target.fullName)}`);
125
+ console.log(`Deployment: ${cell(result.target.deploymentId)}`);
126
+ if (result.target.volumePath)
127
+ console.log(`Volume: ${cell(result.target.volumePath)}`);
128
+ if (result.description)
129
+ console.log(`Description: ${cell(result.description)}`);
130
+ if (result.mode === 'schema') {
131
+ table({ headers: ['COLUMN', 'TYPE', 'NULLABLE', 'DESCRIPTION'], rows: result.columns.map((column) => [column.name, column.type, column.nullable, column.description]) });
132
+ console.log(`${result.columns.length} column(s) | ${result.durationMs} ms`);
133
+ return;
134
+ }
135
+ table({ headers: result.columns.map((column) => column.name), rows: result.rows.map((row) => result.columns.map((column) => row[column.name])) });
136
+ console.log(`${result.rowCount} row(s) | limit ${result.limit} | truncated: ${result.truncated ? 'yes' : 'no'} | ${result.durationMs} ms`);
137
+ }
138
+ function printMetadataSource({ source, environment }) {
139
+ console.log(`Target: ${cell(environment)} | Source: ${cell(source)} | Physical schema: not verified`);
140
+ }
141
+ function printAssetSearch({ result, environment }) {
142
+ printMetadataSource({ source: result.source, environment });
143
+ table({
144
+ headers: ['ASSET', 'KIND', 'REPOSITORY', 'DESCRIPTION', 'MATCHED COLUMNS'],
145
+ rows: result.assets.map((asset) => {
146
+ const names = asset.matchedColumns.map((column) => column.name).join(', ');
147
+ const remaining = asset.matchedColumnCount - asset.matchedColumns.length;
148
+ const description = asset.description && asset.description.length > 120 ? `${asset.description.slice(0, 117)}...` : asset.description;
149
+ return [asset.assetId, asset.kind, asset.stage.repo, description, remaining > 0 ? `${names} (+${remaining} more)` : names || undefined];
150
+ }),
151
+ });
152
+ const { offset, limit, total } = result.pagination;
153
+ console.log(`${result.assets.length} of ${total} matching asset(s) | offset ${offset}`);
154
+ if (offset + limit < total)
155
+ console.log(`Next page: --offset ${offset + limit} --limit ${limit}`);
156
+ console.log('Use pipeline describe <asset> for full declared metadata, then pipeline schema <asset> to verify physical columns.');
157
+ }
158
+ function printAssetDescription(result) {
159
+ console.log(`Asset: ${cell(result.assetId)} | Kind: ${cell(result.kind)}`);
160
+ console.log(`Repository: ${cell(result.stage.repo)} | Stage: ${cell(result.stage.slug)}`);
161
+ printMetadataSource(result);
162
+ console.log(`Deployment: ${cell(result.deploymentId)} | Source commit: ${cell(result.sourceCommit)}`);
163
+ if (result.description)
164
+ console.log(`Description: ${cell(result.description)}`);
165
+ table({ headers: ['COLUMN', 'DECLARED TYPE', 'DECLARED NULLABLE', 'DESCRIPTION'], rows: result.columns.map((column) => [column.name, column.declaredType, column.declaredNullable, column.description]) });
166
+ console.log(`${result.columns.length} declared column(s). Use pipeline schema <asset> to verify physical columns and types.`);
167
+ }
168
+ export async function runPipelineDiscoveryCommand({ sub, args }) {
169
+ if (args.flags.help || args.flags.h || args.positional.includes('-h')) {
170
+ console.log(PIPELINE_DISCOVERY_USAGE);
171
+ return 0;
172
+ }
173
+ try {
174
+ const options = discoveryOptions({ sub, args });
175
+ const env = await resolveEnvWithDiscovery({ requested: options.environment });
176
+ const token = await getAccessToken({ env: env.name, targetUrl: env.url });
177
+ const client = { baseUrl: env.url, token };
178
+ if (sub === 'list') {
179
+ const params = new URLSearchParams({ limit: String(options.limit ?? 50), offset: String(options.offset ?? 0) });
180
+ const result = await getJson({ ...client, path: `/api/data-pipelines/pipelines?${params}` });
181
+ if (options.json)
182
+ console.log(JSON.stringify(result, null, 2));
183
+ else {
184
+ table({ headers: ['REPOSITORY', 'HEALTH', 'STAGES', 'ENVIRONMENTS', 'DESCRIPTION'], rows: result.pipelines.map((pipeline) => [pipeline.repo, pipeline.health, pipeline.stageCounts.total, pipeline.environments.join(', '), pipeline.description]) });
185
+ const { offset, limit, total } = result.pagination;
186
+ console.log(`${result.pipelines.length} of ${total} pipeline(s) | offset ${offset}`);
187
+ if (offset + limit < total)
188
+ console.log(`Next page: --offset ${offset + limit} --limit ${limit}`);
189
+ }
190
+ }
191
+ else if (sub === 'assets') {
192
+ const result = await getJson({ ...client, path: '/api/data-pipelines/assets' });
193
+ if (options.repo) {
194
+ result.assets = result.assets.filter((asset) => asset.stage.repo === options.repo);
195
+ const ids = new Set(result.assets.map((asset) => asset.id));
196
+ result.export = { ...result.export, assets: Object.fromEntries(Object.entries(result.export.assets).filter(([id]) => ids.has(id))) };
197
+ result.total = result.assets.length;
198
+ }
199
+ if (options.json)
200
+ console.log(JSON.stringify(result, null, 2));
201
+ else {
202
+ table({ headers: ['ASSET', 'KIND', 'REPOSITORY'], rows: result.assets.map((asset) => [asset.id, asset.kind, asset.stage.repo]) });
203
+ console.log(`${result.total} declared asset(s). Use pipeline schema <asset> to inspect the active deployment.`);
204
+ }
205
+ }
206
+ else if (sub === 'search' || sub === 'describe') {
207
+ const target = await resolvePipelineTarget({ args, env, token });
208
+ const params = new URLSearchParams({ environment: target.id });
209
+ if (sub === 'search')
210
+ params.set('q', options.query);
211
+ else
212
+ params.set('assetId', args.positional[0]);
213
+ if (options.repo)
214
+ params.set('repo', options.repo);
215
+ if (sub === 'search') {
216
+ params.set('limit', String(options.limit ?? 20));
217
+ params.set('offset', String(options.offset ?? 0));
218
+ const result = await getJson({ ...client, path: `/api/data-pipelines/assets/search?${params}` });
219
+ if (options.json)
220
+ console.log(JSON.stringify(result, null, 2));
221
+ else
222
+ printAssetSearch({ result, environment: target.id });
223
+ }
224
+ else {
225
+ const result = await getJson({ ...client, path: `/api/data-pipelines/assets/describe?${params}` });
226
+ if (options.json)
227
+ console.log(JSON.stringify(result, null, 2));
228
+ else
229
+ printAssetDescription(result);
230
+ }
231
+ }
232
+ else {
233
+ const target = await resolvePipelineTarget({ args, env, token });
234
+ const result = await postJson({
235
+ ...client, path: '/api/data-pipelines/assets/query',
236
+ body: { assetId: args.positional[0], environment: target.id, mode: sub, ...(options.sql !== undefined ? { sql: options.sql } : {}), ...(options.limit !== undefined ? { limit: options.limit } : {}) },
237
+ });
238
+ if (options.json)
239
+ console.log(JSON.stringify(result, null, 2));
240
+ else
241
+ printAssetResult(result);
242
+ }
243
+ return 0;
244
+ }
245
+ catch (error) {
246
+ printCliError(error);
247
+ return 1;
248
+ }
249
+ }