@sequenceholdings/studio-cli 0.7.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +351 -49
  2. package/dist/access/commands.d.ts +1 -1
  3. package/dist/access/commands.js +102 -55
  4. package/dist/access/custom-role-hosts.d.ts +3 -0
  5. package/dist/access/custom-role-hosts.js +88 -0
  6. package/dist/access/group-rosters.d.ts +6 -0
  7. package/dist/access/group-rosters.js +33 -0
  8. package/dist/access/host-contract.d.ts +55 -0
  9. package/dist/access/host-contract.js +33 -0
  10. package/dist/access/hosts.d.ts +4 -0
  11. package/dist/access/hosts.js +60 -0
  12. package/dist/access/principal.d.ts +16 -0
  13. package/dist/access/principal.js +36 -0
  14. package/dist/access/roles.d.ts +18 -0
  15. package/dist/access/roles.js +89 -0
  16. package/dist/access/tier-hosts.d.ts +12 -0
  17. package/dist/access/tier-hosts.js +206 -0
  18. package/dist/agents/commands.d.ts +1 -1
  19. package/dist/agents/commands.js +76 -16
  20. package/dist/agents/scaffold.js +8 -3
  21. package/dist/app/commands.js +37 -12
  22. package/dist/app/manifest.d.ts +2 -2
  23. package/dist/app/official-source.d.ts +4 -2
  24. package/dist/app/official-source.js +6 -4
  25. package/dist/app/readme.js +2 -2
  26. package/dist/app/workspace-model.js +4 -0
  27. package/dist/app/workspace-scaffold.js +5 -3
  28. package/dist/app/workspace.d.ts +2 -0
  29. package/dist/app/workspace.js +1 -1
  30. package/dist/artifact/delegate.js +26 -3
  31. package/dist/artifact/sandbox.js +2 -1
  32. package/dist/atlas-client.d.ts +15 -8
  33. package/dist/atlas-client.js +140 -64
  34. package/dist/bin.js +9 -1
  35. package/dist/cli-errors.js +4 -0
  36. package/dist/command-contract.d.ts +8 -2
  37. package/dist/command-contract.js +3 -2
  38. package/dist/command-help.d.ts +8 -6
  39. package/dist/command-help.js +50 -12
  40. package/dist/env-flags.d.ts +7 -0
  41. package/dist/env-flags.js +23 -0
  42. package/dist/functions/commands.js +66 -11
  43. package/dist/functions/manifest.d.ts +5 -0
  44. package/dist/functions/manifest.js +44 -23
  45. package/dist/functions/service-account-guidance.d.ts +21 -0
  46. package/dist/functions/service-account-guidance.js +62 -0
  47. package/dist/functions/workspace.d.ts +11 -0
  48. package/dist/functions/workspace.js +52 -0
  49. package/dist/main.d.ts +2 -1
  50. package/dist/main.js +12 -3
  51. package/dist/orm/delegate.js +49 -6
  52. package/dist/orm/execute.js +11 -5
  53. package/dist/orm/failures.d.ts +32 -0
  54. package/dist/orm/failures.js +75 -0
  55. package/dist/orm/read.js +3 -3
  56. package/dist/orm/version-guard.d.ts +3 -0
  57. package/dist/orm/version-guard.js +63 -0
  58. package/dist/pipeline/commands.js +4 -1
  59. package/dist/principals/commands.d.ts +3 -0
  60. package/dist/principals/commands.js +124 -0
  61. package/dist/process/runs.d.ts +4 -3
  62. package/dist/process/runs.js +52 -10
  63. package/dist/release-age.d.ts +1 -1
  64. package/dist/release-age.js +1 -0
  65. package/dist/repos/commands.d.ts +44 -0
  66. package/dist/repos/commands.js +55 -15
  67. package/dist/repos/init-repo.d.ts +45 -0
  68. package/dist/repos/init-repo.js +257 -0
  69. package/dist/sandbox-unpushed-warning.d.ts +23 -0
  70. package/dist/sandbox-unpushed-warning.js +86 -0
  71. package/dist/service-accounts/commands.js +15 -3
  72. package/dist/templates/commands.d.ts +14 -2
  73. package/dist/templates/commands.js +70 -16
  74. package/dist/templates/process/pnpm-workspace.yaml +1 -0
  75. package/package.json +14 -11
  76. package/templates/process/pnpm-workspace.yaml +1 -0
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Deploy-time guidance for a Managed Function that needs a service account and
3
+ * names none. The manifest schema refuses it offline with a generic message;
4
+ * `functions deploy` can reach Atlas, so it also says whether this caller may
5
+ * create an account and which accounts they can already attach — the same
6
+ * facts `seq-studio service-accounts list` shows. Mirrors the server's refusal
7
+ * (atlas/src/server/services/managed-functions/service-account-guidance.ts).
8
+ */
9
+ import { type ClientOptions } from '../atlas-client.js';
10
+ /** The requirements carried by the manifest schema's missing-account issue, or null for any other error. */
11
+ export declare function missingServiceAccountRequirements(error: unknown): string[] | null;
12
+ export declare function formatMissingServiceAccount({ requirements, canCreate, attachable }: {
13
+ requirements: readonly string[];
14
+ canCreate: boolean;
15
+ attachable: readonly string[];
16
+ }): string;
17
+ /** Null when Atlas cannot answer; the caller then falls back to the schema's message. */
18
+ export declare function missingServiceAccountGuidance({ client, requirements }: {
19
+ client: ClientOptions;
20
+ requirements: readonly string[];
21
+ }): Promise<string | null>;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Deploy-time guidance for a Managed Function that needs a service account and
3
+ * names none. The manifest schema refuses it offline with a generic message;
4
+ * `functions deploy` can reach Atlas, so it also says whether this caller may
5
+ * create an account and which accounts they can already attach — the same
6
+ * facts `seq-studio service-accounts list` shows. Mirrors the server's refusal
7
+ * (atlas/src/server/services/managed-functions/service-account-guidance.ts).
8
+ */
9
+ import { getJson } from '../atlas-client.js';
10
+ import { SERVICE_ACCOUNT_REQUIRED } from './manifest.js';
11
+ const MAX_LISTED_ACCOUNTS = 10;
12
+ function isRecord(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ /** The requirements carried by the manifest schema's missing-account issue, or null for any other error. */
16
+ export function missingServiceAccountRequirements(error) {
17
+ if (!(error instanceof Error) || error.name !== 'ZodError')
18
+ return null;
19
+ const issues = Reflect.get(error, 'issues');
20
+ if (!Array.isArray(issues))
21
+ return null;
22
+ for (const issue of issues) {
23
+ const params = isRecord(issue) ? issue.params : undefined;
24
+ if (isRecord(params) && params.code === SERVICE_ACCOUNT_REQUIRED && Array.isArray(params.requirements)) {
25
+ return params.requirements.filter((entry) => typeof entry === 'string');
26
+ }
27
+ }
28
+ return null;
29
+ }
30
+ export function formatMissingServiceAccount({ requirements, canCreate, attachable }) {
31
+ const lines = [
32
+ `This function needs a service account: it acts as itself, not as its caller, for ${requirements.join(', ')}. ` +
33
+ 'Name one with a top-level `service_account: <slug>` in managed-function.yml. ' +
34
+ 'Data access on behalf of the caller alone (capabilities.data without `service: true`) needs no account.',
35
+ ];
36
+ if (attachable.length > 0) {
37
+ lines.push(`Accounts you can attach (you hold the actor role): ${attachable.join(', ')}.`);
38
+ }
39
+ lines.push(canCreate
40
+ ? 'You can create one: `seq-studio service-accounts create <slug> --display-name "<name>" -e <env>`, then add ' +
41
+ '`service_account: <slug>` and redeploy. As its creator you hold the actor role needed to attach it.'
42
+ : 'You cannot create service accounts (that needs Can create on Service Accounts). Ask someone who holds it to create ' +
43
+ 'one and grant you its actor role, or attach an existing account you hold the actor role on.');
44
+ return lines.join('\n');
45
+ }
46
+ /** Null when Atlas cannot answer; the caller then falls back to the schema's message. */
47
+ export async function missingServiceAccountGuidance({ client, requirements }) {
48
+ try {
49
+ const body = await getJson({ ...client, path: '/api/service-accounts' });
50
+ if (!isRecord(body) || !Array.isArray(body.serviceAccounts))
51
+ return null;
52
+ const attachable = body.serviceAccounts
53
+ .filter((account) => isRecord(account) && typeof account.slug === 'string' && account.disabled !== true)
54
+ .map((account) => String(account.slug))
55
+ .sort()
56
+ .slice(0, MAX_LISTED_ACCOUNTS);
57
+ return formatMissingServiceAccount({ requirements, canCreate: body.canCreate === true, attachable });
58
+ }
59
+ catch {
60
+ return null;
61
+ }
62
+ }
@@ -0,0 +1,11 @@
1
+ /** Select source packages, not deployment prerequisites or Application members.
2
+ * Remote discovery is bounded by the materialized tree; local discovery stops at
3
+ * the nearest Git root. Nothing reads the caller's cwd for a remote source.
4
+ */
5
+ export declare function prepareFunctionWorkspace({ dir, repoDir }: {
6
+ dir: string;
7
+ repoDir?: string;
8
+ }): Promise<{
9
+ dir: string;
10
+ cleanup: () => Promise<void>;
11
+ }>;
@@ -0,0 +1,52 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { realpath } from 'node:fs/promises';
3
+ import { dirname, join } from 'node:path';
4
+ import { APP_MANIFEST_FILENAME, loadAppManifest } from '../app/manifest.js';
5
+ import { resolveContainedPrimitivePath } from '../app/paths.js';
6
+ import { prepareAppWorkspace } from '../app/workspace.js';
7
+ import { DEPENDENCY_SECTIONS, isWithin, readWorkspacePackage } from '../app/workspace-model.js';
8
+ /** Select source packages, not deployment prerequisites or Application members.
9
+ * Remote discovery is bounded by the materialized tree; local discovery stops at
10
+ * the nearest Git root. Nothing reads the caller's cwd for a remote source.
11
+ */
12
+ export async function prepareFunctionWorkspace({ dir, repoDir }) {
13
+ const unchanged = { dir, cleanup: async () => { } };
14
+ if (!existsSync(join(dir, 'package.json')))
15
+ return unchanged;
16
+ const pkg = await readWorkspacePackage({ dir });
17
+ if (!DEPENDENCY_SECTIONS.some(section => Object.values(pkg[section] ?? {}).some(value => value.startsWith('workspace:')))) {
18
+ return unchanged;
19
+ }
20
+ const selected = await realpath(dir);
21
+ const boundary = repoDir === undefined ? undefined : await realpath(repoDir);
22
+ if (boundary && !isWithin({ root: boundary, path: selected }))
23
+ throw Error('Function source is outside the materialized repository');
24
+ let root = selected;
25
+ while (!existsSync(join(root, APP_MANIFEST_FILENAME))) {
26
+ const parent = dirname(root);
27
+ if (root === boundary || existsSync(join(root, '.git')) || parent === root) {
28
+ throw Error('Workspace dependencies require a containing sequence.app.yml with declared packages and the selected function');
29
+ }
30
+ root = parent;
31
+ }
32
+ if (!isWithin({ root, path: await realpath(join(root, APP_MANIFEST_FILENAME)) })) {
33
+ throw Error('App manifest is outside the containing repository');
34
+ }
35
+ const manifest = await loadAppManifest(root);
36
+ const entries = [];
37
+ for (const entry of manifest.primitives.filter(entry => entry.kind === 'function')) {
38
+ if (await resolveContainedPrimitivePath({ rootDir: root, entryPath: entry.path }) === selected)
39
+ entries.push(entry);
40
+ }
41
+ const entry = entries[0];
42
+ if (entries.length !== 1 || !entry)
43
+ throw Error('sequence.app.yml must declare exactly one function at the selected source directory');
44
+ const prepared = await prepareAppWorkspace({ rootDir: root, manifest, entries: [entry],
45
+ paths: new Map([[entry.id, selected]]), preserveFunctionEnv: false });
46
+ const compiled = prepared.paths.get(entry.id);
47
+ if (!compiled) {
48
+ await prepared.cleanup();
49
+ throw Error('Workspace compilation did not produce the selected function');
50
+ }
51
+ return { dir: compiled, cleanup: prepared.cleanup };
52
+ }
package/dist/main.d.ts CHANGED
@@ -16,7 +16,8 @@
16
16
  * seq-studio auth <sub> manage Git authentication
17
17
  * seq-studio feedback submit submit agent feedback
18
18
  * seq-studio service-accounts <sub> provision runtime identities
19
- * seq-studio access <sub> manage runtime resource access
19
+ * seq-studio access <sub> manage resource access on every primitive
20
+ * seq-studio principals <sub> find users, groups and service accounts to grant
20
21
  * seq-studio envs <sub> add/list environments
21
22
  * seq-studio login authenticate interactively with Auth0
22
23
  * seq-studio logout remove cached user tokens
package/dist/main.js CHANGED
@@ -16,7 +16,8 @@
16
16
  * seq-studio auth <sub> manage Git authentication
17
17
  * seq-studio feedback submit submit agent feedback
18
18
  * seq-studio service-accounts <sub> provision runtime identities
19
- * seq-studio access <sub> manage runtime resource access
19
+ * seq-studio access <sub> manage resource access on every primitive
20
+ * seq-studio principals <sub> find users, groups and service accounts to grant
20
21
  * seq-studio envs <sub> add/list environments
21
22
  * seq-studio login authenticate interactively with Auth0
22
23
  * seq-studio logout remove cached user tokens
@@ -49,6 +50,7 @@ const TOP_LEVEL_USAGE = `usage:
49
50
  seq-studio orm <sub> [args] init | generate | validate | plan | apply | execute | read | sql | diff | migrate-from-yaml | import
50
51
  seq-studio service-accounts <sub> list | show | create (requires provisioning authority)
51
52
  seq-studio access <sub> definitions | list | grant | revoke | resolve
53
+ seq-studio principals <sub> search | users search | groups list | groups show
52
54
  seq-studio envs <sub> add | list environments
53
55
  seq-studio login [--env <name>] authenticate in the browser
54
56
  seq-studio logout [--env <name>] remove one realm's cached user tokens
@@ -58,6 +60,8 @@ const TOP_LEVEL_USAGE = `usage:
58
60
  seq-studio help show this message
59
61
 
60
62
  Authenticate with: seq-studio login
63
+ init, orm init, functions init, artifact init, and agents init take
64
+ --repo <ns>/<name> to scaffold straight into a git-service repo; commit and push from there.
61
65
  In an agent sandbox, SEQ_STUDIO_BASE_URL + SEQ_STUDIO_TOKEN_FILE select the
62
66
  deployment and token instead (no login; -e optional).
63
67
  Where supported, --json writes structured stdout; check exit status and pagination.
@@ -75,7 +79,7 @@ const PROCESS_USAGE = `usage:
75
79
  seq-studio process apply --repo <namespace>/<name> [--ref <r>] -e <env> [--only <id1,id2,...>] [--platform-managed]
76
80
  seq-studio process promote <processId> --version <v> [-e <env>]
77
81
  seq-studio process pull <processId> [--version <v>] [-e <env>] [--out <dir>] [--no-children]
78
- seq-studio process runs start|list|show|cancel [args] -e <env> (see process runs --help)
82
+ seq-studio process runs start|retry|list|show|cancel [args] -e <env> (see process runs --help)
79
83
  seq-studio process test [-e <env>] [--offline]
80
84
  seq-studio process simulate <process-id>
81
85
  seq-studio process bundle build [-o file.json]
@@ -98,7 +102,8 @@ const SUBCOMMANDS = {
98
102
  repos: new Set(['list', 'namespaces', 'show', 'identity', 'create', 'clone', 'pull', 'pulls', 'delete', 'ci']),
99
103
  templates: new Set(['publish', 'sync', 'list']),
100
104
  'service-accounts': new Set(['list', 'show', 'create']),
101
- access: new Set(['definitions', 'resolve', 'list', 'grant', 'revoke']),
105
+ access: new Set(['definitions', 'resolve', 'list', 'grant', 'revoke', 'roles']),
106
+ principals: new Set(['search', 'users', 'groups']),
102
107
  auth: new Set(['whoami', 'git-credential', 'pat']),
103
108
  feedback: new Set(['submit']),
104
109
  orm: new Set(['init', 'generate', 'validate', 'plan', 'apply', 'execute', 'namespaces', 'describe', 'read', 'sql', 'diff', 'migrate-from-yaml', 'import']),
@@ -192,6 +197,10 @@ export async function run(argv = process.argv.slice(2)) {
192
197
  const { runAccessCommand } = await import('./access/commands.js');
193
198
  return runAccessCommand(sub, parseArgs(rest));
194
199
  }
200
+ case 'principals': {
201
+ const { runPrincipalsCommand } = await import('./principals/commands.js');
202
+ return runPrincipalsCommand(sub, parseArgs(rest));
203
+ }
195
204
  case 'feedback':
196
205
  return (await import('./feedback/commands.js')).runFeedbackCommand(sub, parseArgs(rest));
197
206
  case 'auth': {
@@ -11,11 +11,12 @@ import { parseSourceSpec, resolveArtifactSource, } from '@sequenceholdings/artif
11
11
  import { getAccessToken, tryGetAccessTokenWithMode } from '../auth.js';
12
12
  import { sourceAuthMode } from '../sandbox-auth.js';
13
13
  import { resolveConfiguredEnv } from '../config.js';
14
- import { explicitOrSandboxEnv, normalizeShortEnvFlag, readEnvFromArgv } from '../env-flags.js';
14
+ import { explicitOrSandboxEnv, normalizeShortEnvFlag, readEnvFromArgv, withoutEnvFlag } from '../env-flags.js';
15
15
  import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
16
16
  import { resolveFunctionSourceDir } from '../functions/source-selection.js';
17
17
  import { warnBeforeHostDeploy } from '../manifest-roles-notice.js';
18
- import { ORM_DISCOVER_HELP, ORM_EXECUTE_HELP, ORM_HELP } from '../command-help.js';
18
+ import { INIT_INTO_REPO_HELP, ORM_DISCOVER_HELP, ORM_EXECUTE_HELP, ORM_HELP } from '../command-help.js';
19
+ import { ormVersionMismatch, requiresSchemaVersionCheck } from './version-guard.js';
19
20
  /**
20
21
  * ORM subcommands that talk to Atlas — must not silently target `local`.
21
22
  * `init`, `generate`, `validate`, `diff`, `migrate-from-yaml`, and `import` are offline.
@@ -24,13 +25,17 @@ const ORM_NETWORK_SUBS = new Set(['plan', 'apply', 'execute']);
24
25
  /** Subcommands that may read their namespace from a git-service repo (`--repo`). */
25
26
  const ORM_REPO_SUBS = new Set(['plan', 'apply']);
26
27
  const ORM_USAGE = `usage:
27
- seq-studio orm init <dir> scaffold a namespace package (v2: TypeScript schema + GraphQL documents)
28
+ seq-studio orm init <dir> [--repo <ns>/<name>]
29
+ scaffold a namespace package (v2: TypeScript schema + GraphQL documents);
30
+ --repo scaffolds into a git-service repo (see Init into a repo below)
28
31
  seq-studio orm generate [dir] write schema.graphql + operations.manifest.json + typePolicies.gen.ts (offline; runs consumer codegen when codegen.ts is present)
29
32
  seq-studio orm generate [dir] --migration-export [--check]
30
33
  export reviewed ORM inputs for a coordinated pipeline migration; --check verifies without writing
31
34
  seq-studio orm validate [dir] parse + validate definitions and verify committed migrations are in sync
32
35
  seq-studio orm plan [dir] -e <env> compile definitions and diff against the registry
33
- seq-studio orm apply [dir] -e <env> author the migration, register, apply, and refresh the generated outputs (the everyday command)
36
+ seq-studio orm apply [dir] -e <env> [--timeout <duration>] [--no-wait]
37
+ author the migration, register, apply, and refresh the generated outputs (the everyday command);
38
+ waits until the new version is live (default up to 20m; e.g. --timeout 90s), --no-wait returns once queued
34
39
  seq-studio orm plan|apply --repo <ns>/<name> [--path <dir>] [--ref <ref>] -e <env>
35
40
  plan/apply a namespace committed to a platform git-service repo (CI deploy-from-git);
36
41
  --path selects the namespace directory (default: repo root). A remote apply never
@@ -55,7 +60,8 @@ const ORM_USAGE = `usage:
55
60
  Environments: see \`seq-studio envs list\` (built-in: local; more are
56
61
  discovered after you authenticate).
57
62
  Authenticate with: seq-studio login
58
- `;
63
+
64
+ ${INIT_INTO_REPO_HELP}`;
59
65
  /**
60
66
  * Classify an ERR_MODULE_NOT_FOUND from importing `@sequenceholdings/orm/cli`:
61
67
  * is the orm package itself absent, or is it present but a dependency (e.g.
@@ -116,7 +122,8 @@ export function extractOrmRepoSelection(argv) {
116
122
  function positionalDir(args) {
117
123
  for (let i = 0; i < args.length; i++) {
118
124
  const arg = args[i];
119
- if (arg === '--env') {
125
+ // Flags whose value is a separate argument (`-e` is normalized to `--env`).
126
+ if (arg === '--env' || arg === '--timeout') {
120
127
  i += 1;
121
128
  continue;
122
129
  }
@@ -158,6 +165,11 @@ async function runOrmFromRepo({ sub, selection, auth, targetUrl, ormCli, }) {
158
165
  repoDir: source.dir,
159
166
  ...(selection.path !== undefined ? { path: selection.path } : {}),
160
167
  });
168
+ const mismatch = await ormVersionMismatch(dir);
169
+ if (mismatch) {
170
+ console.error(`[seq-studio] ${mismatch}`);
171
+ return 1;
172
+ }
161
173
  aliasOrmModuleForRemoteSource(ormCli.ORM_MODULE_PATH_ENV);
162
174
  // A local apply authors any missing migration into the working tree for
163
175
  // review. A clone is discarded, so an authored migration would be applied
@@ -245,6 +257,27 @@ async function runWithoutOrmPackage({ sub, rest, normalized }) {
245
257
  const args = parseArgs(rest);
246
258
  return (await isDeployedExecute(args)) ? ormExecuteDeployedCommand(args) : null;
247
259
  }
260
+ /**
261
+ * `orm init <dir> --repo <ns>/<name>`: prepare the git-service checkout, then
262
+ * scaffold into it through the ordinary init. Null when `--repo` is absent.
263
+ * (On plan/apply, `--repo` instead selects a remote source; see above.)
264
+ */
265
+ async function runOrmInitWithRepo(normalized) {
266
+ if (normalized.includes('--help') || normalized.includes('-h'))
267
+ return null;
268
+ const { extractRepoFlag, runInitWithRepo } = await import('../repos/init-repo.js');
269
+ const { repo, rest: initArgv } = extractRepoFlag(normalized);
270
+ if (repo === undefined)
271
+ return null;
272
+ const args = parseArgs(normalized);
273
+ const target = positionalDir(initArgv);
274
+ if (!target) {
275
+ console.error('usage: seq-studio orm init <dir> [--repo <ns>/<name>]');
276
+ return 1;
277
+ }
278
+ // The environment is for the repository setup; init itself is offline.
279
+ return runInitWithRepo({ args, target, scaffold: () => runOrmCommand('init', withoutEnvFlag(initArgv)) });
280
+ }
248
281
  export async function runOrmCommand(sub, rest) {
249
282
  if (!sub || sub === 'help' || sub === '--help' || sub === '-h') {
250
283
  console.log(ORM_USAGE);
@@ -253,6 +286,9 @@ export async function runOrmCommand(sub, rest) {
253
286
  if (NATIVE_ORM_SUBS.has(sub))
254
287
  return runNativeOrmCommand(sub, rest);
255
288
  const normalized = normalizeShortEnvFlag(rest);
289
+ const repoInit = sub === 'init' ? await runOrmInitWithRepo(normalized) : null;
290
+ if (repoInit !== null)
291
+ return repoInit;
256
292
  const answered = await runWithoutOrmPackage({ sub, rest, normalized });
257
293
  if (answered !== null)
258
294
  return answered;
@@ -306,6 +342,13 @@ export async function runOrmCommand(sub, rest) {
306
342
  });
307
343
  if (repoSelection)
308
344
  return runOrmFromRepo({ sub, selection: repoSelection, auth, targetUrl, ormCli });
345
+ if (requiresSchemaVersionCheck(sub)) {
346
+ const mismatch = await ormVersionMismatch(positionalDir(normalized) ?? '.');
347
+ if (mismatch) {
348
+ console.error(`[seq-studio] ${mismatch}`);
349
+ return 1;
350
+ }
351
+ }
309
352
  await warnBeforeHostDeploy({ sub, deploySub: 'apply', args: normalized, file: 'namespace.yaml' });
310
353
  return runCli([sub, ...normalized]);
311
354
  }
@@ -15,6 +15,7 @@ import { getJsonOr404, postJsonResponse } from '../atlas-client.js';
15
15
  import { printCliError } from '../cli-errors.js';
16
16
  import { validateCommandInput } from '../command-input.js';
17
17
  import { buildContext, clientOptions } from '../functions/commands.js';
18
+ import { dataPlaneFailure, failureNextStep, failureSummary } from './failures.js';
18
19
  import { operationDetailSchema, operationsPageSchema, parseResponse, } from './discover-schema.js';
19
20
  /** The operation detail route's name grammar (a GraphQL name). */
20
21
  const OPERATION_NAME = /^[_A-Za-z][_0-9A-Za-z]{0,254}$/;
@@ -154,9 +155,9 @@ function parseEnvelope(body) {
154
155
  }
155
156
  }
156
157
  function failureMessage({ namespace, operation, status, envelope }) {
157
- const first = Array.isArray(envelope?.errors) ? envelope.errors[0] : undefined;
158
- const code = typeof first?.extensions?.code === 'string' ? first.extensions.code : null;
159
- const detail = typeof first?.message === 'string' ? `${first.message}${code ? ` (${code})` : ''}` : `HTTP ${status}`;
158
+ const failure = dataPlaneFailure({ status, errors: envelope?.errors });
159
+ const { code } = failure;
160
+ const detail = failureSummary(failure);
160
161
  const lines = [`${namespace}.${operation.name} failed: ${detail}`];
161
162
  if (code === 'BAD_USER_INPUT' && operation.variables.length > 0) {
162
163
  lines.push(`Variables: ${variablesLabel(operation.variables)}`);
@@ -169,8 +170,13 @@ function failureMessage({ namespace, operation, status, envelope }) {
169
170
  lines.push(`It requires ${[capability ? `capability ${capability}` : null, role ? `role ${role}` : null].filter(Boolean).join(' and ')}.`);
170
171
  }
171
172
  }
172
- if (status === 404) {
173
- lines.push('The deployed operation was not found when it ran; the namespace may have just been redeployed. Retry.');
173
+ if (status === 404 && failure.details.cause === 'unknown_operation') {
174
+ lines.push('The deployed operation changed between lookup and execution (the namespace was just redeployed). Retry.');
175
+ }
176
+ else {
177
+ const next = failureNextStep({ failure, namespace });
178
+ if (next && code !== 'BAD_USER_INPUT' && code !== 'FORBIDDEN')
179
+ lines.push(next);
174
180
  }
175
181
  return lines.join('\n');
176
182
  }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Human output for a refusal from the ORM data endpoint. The server's GraphQL
3
+ * envelope carries `{message, extensions: {code, details?}}`; `details` names
4
+ * the variable, column, constraint, or requirement at fault (schema names
5
+ * only, never values). Every ORM command prints refusals through here so the
6
+ * same error reads the same way from `execute`, `read`, and `sql`.
7
+ */
8
+ export interface DataPlaneFailure {
9
+ status: number | null;
10
+ code: string | null;
11
+ message: string | null;
12
+ details: Readonly<Record<string, string>>;
13
+ }
14
+ /** The first error of a data-plane envelope (or of an ORM client error's `errors`). */
15
+ export declare function dataPlaneFailure({ status, errors }: {
16
+ status: number | null;
17
+ errors: unknown;
18
+ }): DataPlaneFailure;
19
+ /** `message (CODE) [variable: x, column: y]`, or `HTTP <status>` when the server sent no envelope. */
20
+ export declare function failureSummary(failure: DataPlaneFailure): string;
21
+ /** One recovery step for the refusal, or null when the message already says it. */
22
+ export declare function failureNextStep({ failure, namespace }: {
23
+ failure: DataPlaneFailure;
24
+ namespace: string;
25
+ }): string | null;
26
+ /** An ORM client error (`@sequenceholdings/orm/client`), matched by name: the CLI may load its own copy. */
27
+ export declare function ormClientFailure(error: unknown): DataPlaneFailure | null;
28
+ /** Print any ORM command error: data-plane refusals with their details and next step, everything else as usual. */
29
+ export declare function printOrmCommandError({ error, namespace }: {
30
+ error: unknown;
31
+ namespace: string;
32
+ }): void;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Human output for a refusal from the ORM data endpoint. The server's GraphQL
3
+ * envelope carries `{message, extensions: {code, details?}}`; `details` names
4
+ * the variable, column, constraint, or requirement at fault (schema names
5
+ * only, never values). Every ORM command prints refusals through here so the
6
+ * same error reads the same way from `execute`, `read`, and `sql`.
7
+ */
8
+ import { LOG, printCliError } from '../cli-errors.js';
9
+ function isRecord(value) {
10
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
11
+ }
12
+ function stringFields(value) {
13
+ if (!isRecord(value))
14
+ return {};
15
+ return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === 'string'));
16
+ }
17
+ /** The first error of a data-plane envelope (or of an ORM client error's `errors`). */
18
+ export function dataPlaneFailure({ status, errors }) {
19
+ const first = Array.isArray(errors) ? errors[0] : undefined;
20
+ const extensions = isRecord(first) && isRecord(first.extensions) ? first.extensions : {};
21
+ return {
22
+ status,
23
+ code: typeof extensions.code === 'string' ? extensions.code : null,
24
+ message: isRecord(first) && typeof first.message === 'string' ? first.message : null,
25
+ details: stringFields(extensions.details),
26
+ };
27
+ }
28
+ /** `message (CODE) [variable: x, column: y]`, or `HTTP <status>` when the server sent no envelope. */
29
+ export function failureSummary(failure) {
30
+ const fields = Object.entries(failure.details).map(([key, value]) => `${key}: ${value}`);
31
+ const base = failure.message ?? (failure.status === null ? 'request failed' : `HTTP ${failure.status}`);
32
+ return `${base}${failure.code ? ` (${failure.code})` : ''}${fields.length ? ` [${fields.join(', ')}]` : ''}`;
33
+ }
34
+ /** One recovery step for the refusal, or null when the message already says it. */
35
+ export function failureNextStep({ failure, namespace }) {
36
+ const { code, details } = failure;
37
+ if (code === 'NOT_FOUND' && details.cause === 'unknown_operation') {
38
+ return `Next step: list the deployed operations with \`seq-studio orm describe ${namespace} --operations\`, and run one by name with \`seq-studio orm execute ${namespace} <operation>\`.`;
39
+ }
40
+ if (code === 'NOT_FOUND') {
41
+ return 'Next step: confirm `-e` targets the right environment; `seq-studio orm namespaces` lists the namespaces you can read. A namespace you cannot read looks the same as one that does not exist.';
42
+ }
43
+ if (code === 'FORBIDDEN' && details.requirement) {
44
+ return `Next step: ask an admin of ${namespace} to assign you a role that grants ${details.requirement.replace(/^(capability|role):/, '$1 ')} (\`seq-studio access\`).`;
45
+ }
46
+ if (code === 'BAD_USER_INPUT' && details.variable) {
47
+ return `Next step: fix variable $${details.variable}; \`seq-studio orm describe ${namespace} --operations\` lists each operation's variables and types.`;
48
+ }
49
+ return null;
50
+ }
51
+ /** An ORM client error (`@sequenceholdings/orm/client`), matched by name: the CLI may load its own copy. */
52
+ export function ormClientFailure(error) {
53
+ if (!(error instanceof Error) || error.name !== 'OrmOperationError')
54
+ return null;
55
+ const status = Reflect.get(error, 'status');
56
+ const failure = dataPlaneFailure({ status: typeof status === 'number' ? status : null, errors: Reflect.get(error, 'errors') });
57
+ const code = Reflect.get(error, 'code');
58
+ return {
59
+ ...failure,
60
+ code: failure.code ?? (typeof code === 'string' ? code : null),
61
+ message: failure.message ?? error.message,
62
+ };
63
+ }
64
+ /** Print any ORM command error: data-plane refusals with their details and next step, everything else as usual. */
65
+ export function printOrmCommandError({ error, namespace }) {
66
+ const failure = ormClientFailure(error);
67
+ if (!failure) {
68
+ printCliError(error);
69
+ return;
70
+ }
71
+ console.error(`${LOG} ${failureSummary(failure)}`);
72
+ const next = failureNextStep({ failure, namespace });
73
+ if (next)
74
+ console.error(`${LOG} ${next}`);
75
+ }
package/dist/orm/read.js CHANGED
@@ -12,9 +12,9 @@
12
12
  */
13
13
  import { readFile } from 'node:fs/promises';
14
14
  import { postJsonResponse } from '../atlas-client.js';
15
- import { printCliError } from '../cli-errors.js';
16
15
  import { validateCommandInput } from '../command-input.js';
17
16
  import { buildContext, clientOptions } from '../functions/commands.js';
17
+ import { printOrmCommandError } from './failures.js';
18
18
  import { table } from '../text-table.js';
19
19
  export const ORM_READ_USAGE = `usage:
20
20
  seq-studio orm read <namespace> <table> -e <env> [--where <column>=<op>.<value>]...
@@ -264,7 +264,7 @@ export async function ormReadCommand(args) {
264
264
  return 0;
265
265
  }
266
266
  catch (error) {
267
- printCliError(error);
267
+ printOrmCommandError({ error, namespace: args.positional[0] ?? '<namespace>' });
268
268
  return 1;
269
269
  }
270
270
  }
@@ -290,7 +290,7 @@ export async function ormSqlCommand(args) {
290
290
  return 0;
291
291
  }
292
292
  catch (error) {
293
- printCliError(error);
293
+ printOrmCommandError({ error, namespace: args.positional[0] ?? '<namespace>' });
294
294
  if (isRejectedSql(error))
295
295
  console.error(sqlGrammarHint(args.positional[0] ?? '<namespace>'));
296
296
  return 1;
@@ -0,0 +1,3 @@
1
+ export declare function requiresSchemaVersionCheck(sub: string): boolean;
2
+ /** Fail before compiling a v2 schema with an ORM outside its declared range. */
3
+ export declare function ormVersionMismatch(dir: string): Promise<string | null>;
@@ -0,0 +1,63 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { satisfies, validRange } from 'semver';
5
+ const SCHEMA_SUBCOMMANDS = new Set(['generate', 'validate', 'plan', 'apply', 'diff']);
6
+ export function requiresSchemaVersionCheck(sub) {
7
+ return SCHEMA_SUBCOMMANDS.has(sub);
8
+ }
9
+ function missingFile(error) {
10
+ return error instanceof Error && 'code' in error && error.code === 'ENOENT';
11
+ }
12
+ function dependencyRange(manifest) {
13
+ if (typeof manifest !== 'object' || manifest === null)
14
+ return undefined;
15
+ for (const field of ['dependencies', 'devDependencies']) {
16
+ const section = Reflect.get(manifest, field);
17
+ if (typeof section === 'object' && section !== null) {
18
+ const range = Reflect.get(section, '@sequenceholdings/orm');
19
+ if (range !== undefined)
20
+ return range;
21
+ }
22
+ }
23
+ return undefined;
24
+ }
25
+ /** Fail before compiling a v2 schema with an ORM outside its declared range. */
26
+ export async function ormVersionMismatch(dir) {
27
+ const configPath = join(resolve(dir), 'sequence.config.ts');
28
+ try {
29
+ await readFile(configPath);
30
+ }
31
+ catch (error) {
32
+ if (missingFile(error))
33
+ return null; // v1 namespace
34
+ throw error;
35
+ }
36
+ const manifestPath = join(resolve(dir), 'package.json');
37
+ let manifest;
38
+ try {
39
+ manifest = JSON.parse(await readFile(manifestPath, 'utf8'));
40
+ }
41
+ catch (error) {
42
+ if (missingFile(error))
43
+ return null; // unversioned source
44
+ throw new Error(`could not read ${manifestPath}: ${error instanceof Error ? error.message : String(error)}`);
45
+ }
46
+ const range = dependencyRange(manifest);
47
+ if (range === undefined || (typeof range === 'string' && range.startsWith('workspace:')))
48
+ return null;
49
+ if (typeof range !== 'string' || !validRange(range)) {
50
+ return `invalid @sequenceholdings/orm range "${String(range)}" in ${manifestPath}`;
51
+ }
52
+ // Resolve beside this CLI, matching the delegated ORM import in every installation layout.
53
+ const ormPackagePath = fileURLToPath(new URL('../package.json', import.meta.resolve('@sequenceholdings/orm/cli')));
54
+ const ormManifest = JSON.parse(await readFile(ormPackagePath, 'utf8'));
55
+ const version = typeof ormManifest === 'object' && ormManifest !== null
56
+ ? Reflect.get(ormManifest, 'version') : undefined;
57
+ if (typeof version !== 'string' || !satisfies(version, range)) {
58
+ return `this seq-studio loads @sequenceholdings/orm ${typeof version === 'string' ? version : '(unknown version)'}, ` +
59
+ `but ${manifestPath} requires ${range}. Run the namespace-local CLI after installing its dependencies, ` +
60
+ 'or upgrade seq-studio and @sequenceholdings/orm together.';
61
+ }
62
+ return null;
63
+ }
@@ -58,7 +58,10 @@ ${PIPELINE_DISCOVERY_USAGE}
58
58
  For an existing target release unit, --source-env reads a repository
59
59
  from a separately authenticated registered
60
60
  environment; -e still selects the target. The target verifies and snapshots
61
- source bytes before queuing. Not available with --dir or migrations.
61
+ source bytes before queuing. Reviewed pipeline.config.yml source_paths
62
+ can select runtime files/directories while preserving pipeline metadata
63
+ and the release identity. Snapshot and Git-fetch size limits still apply.
64
+ Not available with --dir or migrations.
62
65
  enqueue a durable plan, poll progress, then print the completed
63
66
  materialize + SDK/graph + compile + live-diff + provision findings
64
67
  (no Databricks CLI / DAB validate on Atlas); exit 1 on destructive findings
@@ -0,0 +1,3 @@
1
+ import type { ParsedArgs } from '../process/commands.js';
2
+ export declare const PRINCIPALS_USAGE = "usage:\n seq-studio principals search <query> -e <env> [--types user,group,service-account,organization] [--limit <n>]\n seq-studio principals users search <query> -e <env> [--limit <n>]\n seq-studio principals groups list -e <env> [--search <query>] [--limit <n>] [--page <n>]\n seq-studio principals groups show <group-id> -e <env> [--limit <n>] [--offset <n>]\n\n Find the people, groups, service accounts and organizations YOU may grant\n access to, with the exact ids seq-studio access grant takes. Results are JSON;\n each principal carries \"grant\": { \"principalType\", \"principalId\" }.\n Queries need at least 2 characters. search defaults to user,group,service-account.\n\n You see exactly what the Atlas pickers show you, never more:\n people: active users in your organization (Sequence operators: everyone);\n groups: groups you belong to (platform admins: every group), never deleted ones;\n service accounts: accounts you hold actor on; organizations: your own tenant.\n groups show lists a visible group's active members, paged (default 50 per\n page); a group you can't see is reported as not found.\n Authenticate: seq-studio login --env <env> (agent sandbox tokens work too).\n";
3
+ export declare function runPrincipalsCommand(sub: string | undefined, args: ParsedArgs): Promise<number>;