@sequenceholdings/studio-cli 0.9.10 → 0.9.12

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.
@@ -0,0 +1,97 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, join } from 'node:path';
5
+ import { currentVersion } from './update-check.js';
6
+ import { edgeAuthHeaders } from './edge-auth-headers.js';
7
+ const preferencePath = () => join(homedir(), '.config', 'lattice', 'telemetry.json');
8
+ const targets = new Map();
9
+ let active = false;
10
+ function commandOutcome(exitCode, error) {
11
+ if (exitCode === 0)
12
+ return 'success';
13
+ if (exitCode === 130 || exitCode === 143)
14
+ return 'cancelled';
15
+ if (error instanceof Error && error.name === 'AbortError')
16
+ return 'cancelled';
17
+ return 'failure';
18
+ }
19
+ function commandHttpStatus(error) {
20
+ if (typeof error !== 'object' || error === null || !('status' in error))
21
+ return undefined;
22
+ const status = Number(error.status);
23
+ return Number.isInteger(status) && status >= 400 && status <= 599 ? status : undefined;
24
+ }
25
+ function commandErrorCategory(error, status) {
26
+ if (status === 401)
27
+ return 'auth';
28
+ if (status === 403)
29
+ return 'permission';
30
+ if (status === 400 || status === 422)
31
+ return 'validation';
32
+ if (status === 408 || status === 504)
33
+ return 'timeout';
34
+ if (status && status >= 500)
35
+ return 'server';
36
+ if (error instanceof Error && error.name === 'TimeoutError')
37
+ return 'timeout';
38
+ const cause = error instanceof Error ? error.cause : undefined;
39
+ const code = typeof cause === 'object' && cause !== null && 'code' in cause ? cause.code : undefined;
40
+ if (typeof code === 'string' && ['ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ENETUNREACH'].includes(code))
41
+ return 'network';
42
+ return 'unknown';
43
+ }
44
+ /** Called only after the existing auth path has verified the token and target. */
45
+ export function recordAuthenticatedCliTarget(baseUrl, token) {
46
+ if (!active)
47
+ return;
48
+ targets.set(baseUrl.replace(/\/$/, ''), token);
49
+ }
50
+ export function beginCommandTelemetry() {
51
+ targets.clear();
52
+ active = true;
53
+ return performance.now();
54
+ }
55
+ export async function telemetryEnabled() {
56
+ if (process.env.SEQ_STUDIO_TELEMETRY?.toLowerCase() === 'off')
57
+ return false;
58
+ try {
59
+ return JSON.parse(await readFile(preferencePath(), 'utf8')).enabled !== false;
60
+ }
61
+ catch {
62
+ return true;
63
+ }
64
+ }
65
+ export async function setTelemetryEnabled(enabled) {
66
+ const path = preferencePath();
67
+ await mkdir(dirname(path), { recursive: true });
68
+ await writeFile(path, JSON.stringify({ enabled }) + '\n', { mode: 0o600 });
69
+ }
70
+ export async function finishCommandTelemetry(input) {
71
+ active = false;
72
+ const target = targets.size === 1 ? [...targets][0] : null;
73
+ targets.clear();
74
+ if (!input.command || !target || !(await telemetryEnabled()))
75
+ return;
76
+ const [baseUrl, token] = target;
77
+ const durationMs = Math.max(0, Math.min(86_400_000, Math.round(performance.now() - input.startedAt)));
78
+ const httpStatus = commandHttpStatus(input.error);
79
+ const outcome = commandOutcome(input.exitCode, input.error);
80
+ const errorCategory = outcome === 'failure' ? commandErrorCategory(input.error, httpStatus) : undefined;
81
+ try {
82
+ await fetch(new URL('/api/platform/cli-command-events', baseUrl), {
83
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(1_500),
84
+ headers: {
85
+ Authorization: `Bearer ${token}`,
86
+ 'Content-Type': 'application/json',
87
+ 'x-sequence-client': 'seq-studio',
88
+ 'x-sequence-client-version': currentVersion(),
89
+ ...edgeAuthHeaders(baseUrl),
90
+ },
91
+ body: JSON.stringify({ id: randomUUID(), command: input.command, outcome, durationMs, errorCategory, httpStatus }),
92
+ });
93
+ }
94
+ catch {
95
+ // Best effort: telemetry cannot change a command result.
96
+ }
97
+ }
@@ -0,0 +1 @@
1
+ export declare function edgeAuthHeaders(baseUrl: string): Record<string, string>;
@@ -0,0 +1,40 @@
1
+ import { PREVIEW_DOMAIN } from './preview.js';
2
+ const CF_ACCESS_DOMAIN = 'seqholdings.com';
3
+ function previewAccessHeaders(baseUrl) {
4
+ const secret = process.env.PREVIEW_ACCESS_HEADER?.trim();
5
+ if (!secret)
6
+ return {};
7
+ try {
8
+ const parsed = new URL(baseUrl);
9
+ if (parsed.protocol !== 'https:')
10
+ return {};
11
+ if (!parsed.hostname.toLowerCase().endsWith(`.${PREVIEW_DOMAIN}`))
12
+ return {};
13
+ return { 'x-preview-access': secret };
14
+ }
15
+ catch {
16
+ return {};
17
+ }
18
+ }
19
+ /** Only send Cloudflare credentials to HTTPS origins in the company domain. */
20
+ function cfAccessHeaders(baseUrl) {
21
+ const clientId = process.env.CF_ACCESS_CLIENT_ID?.trim();
22
+ const clientSecret = process.env.CF_ACCESS_CLIENT_SECRET?.trim();
23
+ if (!clientId || !clientSecret)
24
+ return {};
25
+ try {
26
+ const parsed = new URL(baseUrl);
27
+ if (parsed.protocol !== 'https:')
28
+ return {};
29
+ const hostname = parsed.hostname.toLowerCase();
30
+ if (hostname !== CF_ACCESS_DOMAIN && !hostname.endsWith(`.${CF_ACCESS_DOMAIN}`))
31
+ return {};
32
+ return { 'CF-Access-Client-Id': clientId, 'CF-Access-Client-Secret': clientSecret };
33
+ }
34
+ catch {
35
+ return {};
36
+ }
37
+ }
38
+ export function edgeAuthHeaders(baseUrl) {
39
+ return { ...previewAccessHeaders(baseUrl), ...cfAccessHeaders(baseUrl) };
40
+ }
@@ -258,7 +258,7 @@ function:
258
258
  title: ${id}
259
259
  description: Describe what this function does.
260
260
 
261
- runtime: nodejs20
261
+ runtime: nodejs24
262
262
  entrypoint: handler
263
263
 
264
264
  limits:
@@ -606,7 +606,8 @@ export const managedFunctionManifestSchema = z.object({
606
606
  description: z.string().max(2000).optional(),
607
607
  immutable_release: functionImmutableReleaseSchema.optional(),
608
608
  }),
609
- runtime: z.enum(['nodejs20', 'nodejs24']).default('nodejs20'),
609
+ /** Omitted means Node 24; Atlas keeps each stored version on its admitted runtime. */
610
+ runtime: z.enum(['nodejs20', 'nodejs24']).default('nodejs24'),
610
611
  entrypoint: z.string().min(1).max(255).default('handler'),
611
612
  limits: managedFunctionWorkloadLimitsSchema,
612
613
  /**
package/dist/main.d.ts CHANGED
@@ -24,4 +24,6 @@
24
24
  * seq-studio doctor check token + env + writer gate
25
25
  * seq-studio help show usage
26
26
  */
27
+ /** Only command words from the router; never operands, flags, paths, or arguments. */
28
+ export declare function commandTelemetryName(argv: string[]): string | null;
27
29
  export declare function run(argv?: string[]): Promise<number>;
package/dist/main.js CHANGED
@@ -51,11 +51,12 @@ const TOP_LEVEL_USAGE = `usage:
51
51
  seq-studio orm <sub> [args] init | generate | validate | plan | apply | deployment-policy | execute | read | sql | diff | migrate-from-yaml | import
52
52
  seq-studio service-accounts <sub> list | show | create (requires provisioning authority)
53
53
  seq-studio access <sub> definitions | list | grant | revoke | resolve
54
- seq-studio principals <sub> search | users search | groups list | groups show
54
+ seq-studio principals <sub> search | users search | groups list/show/create/members
55
55
  seq-studio envs <sub> add | list environments
56
56
  seq-studio login [--env <name>] authenticate in the browser
57
57
  seq-studio logout [--env <name>] remove one realm's cached user tokens
58
58
  seq-studio doctor [-e <env>] [--json] [--offline] diagnose config, auth, toolchain, and writer gate
59
+ seq-studio telemetry enable|disable|status control authenticated command metrics
59
60
  seq-studio version print the installed version
60
61
  seq-studio capabilities [--json] describe command availability and access
61
62
  seq-studio help show this message
@@ -108,10 +109,37 @@ const SUBCOMMANDS = {
108
109
  principals: new Set(['search', 'users', 'groups']),
109
110
  auth: new Set(['whoami', 'git-credential', 'pat']),
110
111
  feedback: new Set(['submit']),
111
- orm: new Set(['init', 'generate', 'validate', 'plan', 'apply', 'deployment-policy', 'execute', 'namespaces', 'describe', 'read', 'sql', 'diff', 'migrate-from-yaml', 'import']),
112
+ orm: new Set(['init', 'generate', 'validate', 'plan', 'apply', 'history', 'deployment-policy', 'execute', 'namespaces', 'describe', 'read', 'sql', 'diff', 'migrate-from-yaml', 'import']),
112
113
  pipeline: new Set(['list', 'assets', 'search', 'describe', 'schema', 'sample', 'query', 'init', 'validate', 'repin-orm', 'codegen', 'adopt', 'unbind', 'retire', 'plan', 'deploy', 'status', 'migrate', 'promote', 'rollback', 'run-now']),
113
114
  envs: new Set(['add', 'list']),
114
115
  };
116
+ const TELEMETRY_EXCLUDED = new Set(['validate', 'telemetry', 'version', 'capabilities', 'help', 'login', 'logout', 'envs']);
117
+ const TELEMETRY_TOP_LEVEL = new Set(['init', 'add', 'deploy', 'doctor']);
118
+ const TELEMETRY_NESTED = {
119
+ 'process runs': new Set(['start', 'retry', 'list', 'show', 'cancel']),
120
+ 'process bundle': new Set(['build', 'pull', 'archive', 'inspect', 'list', 'publish']),
121
+ };
122
+ /** Only command words from the router; never operands, flags, paths, or arguments. */
123
+ export function commandTelemetryName(argv) {
124
+ if (argv.some((arg) => arg === '--help' || arg === '-h'))
125
+ return null;
126
+ const [namespace, sub] = argv;
127
+ if (!namespace || TELEMETRY_EXCLUDED.has(namespace))
128
+ return null;
129
+ if (namespace === 'doctor' && (argv.includes('--offline') || argv.includes('--offline=true')))
130
+ return null;
131
+ if (namespace === 'auth' && sub === 'git-credential')
132
+ return null;
133
+ if (TELEMETRY_TOP_LEVEL.has(namespace))
134
+ return namespace;
135
+ if (!sub || !SUBCOMMANDS[namespace]?.has(sub))
136
+ return null;
137
+ const command = `${namespace} ${sub}`;
138
+ const nested = TELEMETRY_NESTED[command];
139
+ if (!nested)
140
+ return command;
141
+ return argv[2] && nested.has(argv[2]) ? `${command} ${argv[2]}` : null;
142
+ }
115
143
  export async function run(argv = process.argv.slice(2)) {
116
144
  if (!requestsMachineOutput(argv))
117
145
  return dispatch(argv);
@@ -254,6 +282,25 @@ async function dispatch(argv) {
254
282
  return runCapabilities([sub, ...rest].filter((value) => Boolean(value)));
255
283
  case 'doctor':
256
284
  return (await import('./process/commands.js')).doctorCommand(parseArgs([sub, ...rest].filter(Boolean)));
285
+ case 'telemetry': {
286
+ const { setTelemetryEnabled, telemetryEnabled } = await import('./command-telemetry.js');
287
+ if (sub === '--help' || sub === '-h' || sub === 'help') {
288
+ console.log('usage: seq-studio telemetry enable|disable|status');
289
+ return 0;
290
+ }
291
+ if (rest.length > 0) {
292
+ console.error('usage: seq-studio telemetry enable|disable|status');
293
+ return 1;
294
+ }
295
+ if (sub === 'enable' || sub === 'disable')
296
+ await setTelemetryEnabled(sub === 'enable');
297
+ else if (sub !== 'status') {
298
+ console.error('usage: seq-studio telemetry enable|disable|status');
299
+ return 1;
300
+ }
301
+ console.log(`Command telemetry: ${await telemetryEnabled() ? 'on' : 'off'}`);
302
+ return 0;
303
+ }
257
304
  default:
258
305
  console.error(`unknown command: ${namespace}`);
259
306
  console.error(TOP_LEVEL_USAGE);
@@ -0,0 +1,53 @@
1
+ /** Mirrors `SOURCE_ENV` in `@sequenceholdings/orm/cli`; older pinned packages ignore it. */
2
+ export declare const ORM_SOURCE_ENV = "SEQUENCE_ORM_SOURCE";
3
+ export interface OrmApplySource {
4
+ repository_id: string;
5
+ commit: string;
6
+ path: string;
7
+ dirty?: boolean;
8
+ }
9
+ /** The Git Service repository a clone's origin names, when that origin is the target environment's own Git Service. */
10
+ export declare function gitServiceRepoIdFromOrigin({ originUrl, targetUrl }: {
11
+ originUrl: string;
12
+ targetUrl: string;
13
+ }): string | null;
14
+ /** Source of an apply from a local checkout; null outside a clone of the target's Git Service. */
15
+ export declare function localOrmApplySource({ dir, targetUrl }: {
16
+ dir: string;
17
+ targetUrl: string;
18
+ }): OrmApplySource | null;
19
+ /** Source of an apply materialized from `--repo`; the commit is the one the resolver pinned. */
20
+ export declare function repoOrmApplySource({ targetUrl, token, namespace, name, commit, path }: {
21
+ targetUrl: string;
22
+ token: string;
23
+ namespace: string;
24
+ name: string;
25
+ commit: string | null;
26
+ path: string | undefined;
27
+ }): Promise<OrmApplySource | null>;
28
+ /** Whether the target records apply sources; an older Atlas rejects the unknown `source` field. */
29
+ export declare function targetRecordsApplySource({ targetUrl, token }: {
30
+ targetUrl: string;
31
+ token: string;
32
+ }): Promise<boolean>;
33
+ /**
34
+ * Hand the apply's Git Service source to the pinned ORM package, which sends
35
+ * it for the namespace's activation history. Best effort: an unresolvable
36
+ * source or an older Atlas leaves the activation recorded as `reported`.
37
+ */
38
+ export declare function exportApplySource({ auth, targetUrl, resolve }: {
39
+ auth: {
40
+ token: string;
41
+ } | null;
42
+ targetUrl: string;
43
+ resolve: () => Promise<OrmApplySource | null>;
44
+ }): Promise<void>;
45
+ /** `orm apply <dir>` from a local checkout; every other subcommand sends no source. */
46
+ export declare function exportLocalApplySource({ sub, auth, targetUrl, dir }: {
47
+ sub: string;
48
+ auth: {
49
+ token: string;
50
+ } | null;
51
+ targetUrl: string | undefined;
52
+ dir?: string;
53
+ }): Promise<void>;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The Git Service source an `orm apply` came from. The pinned ORM package
3
+ * reads it from SEQUENCE_ORM_SOURCE and sends it with the apply; Atlas checks
4
+ * it against Git Service and records the result on the namespace's activation
5
+ * history. A claim never authorizes anything, so a missing or wrong one only
6
+ * means the activation is recorded as `reported`.
7
+ */
8
+ import { execFileSync } from 'node:child_process';
9
+ import { resolveRepo } from '@sequenceholdings/artifact-studio/git-service-client';
10
+ import { localGitMetadata, localSourceRoot } from '@sequenceholdings/artifact-studio/source-resolver';
11
+ /** Mirrors `SOURCE_ENV` in `@sequenceholdings/orm/cli`; older pinned packages ignore it. */
12
+ export const ORM_SOURCE_ENV = 'SEQUENCE_ORM_SOURCE';
13
+ const GIT_SERVICE_REPO_PATH = /^\/api\/git-service\/repos\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\/git\/?$/i;
14
+ /** The Git Service repository a clone's origin names, when that origin is the target environment's own Git Service. */
15
+ export function gitServiceRepoIdFromOrigin({ originUrl, targetUrl }) {
16
+ try {
17
+ const origin = new URL(originUrl);
18
+ if (origin.host !== new URL(targetUrl).host)
19
+ return null;
20
+ return origin.pathname.match(GIT_SERVICE_REPO_PATH)?.[1]?.toLowerCase() ?? null;
21
+ }
22
+ catch {
23
+ return null;
24
+ }
25
+ }
26
+ /** Source of an apply from a local checkout; null outside a clone of the target's Git Service. */
27
+ export function localOrmApplySource({ dir, targetUrl }) {
28
+ let originUrl;
29
+ try {
30
+ originUrl = String(execFileSync('git', ['remote', 'get-url', 'origin'], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] })).trim();
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ const repositoryId = gitServiceRepoIdFromOrigin({ originUrl, targetUrl });
36
+ const { gitCommit, gitDirty } = localGitMetadata(dir);
37
+ if (!repositoryId || !gitCommit)
38
+ return null;
39
+ return { repository_id: repositoryId, commit: gitCommit, path: localSourceRoot(dir), ...(gitDirty === null ? {} : { dirty: gitDirty }) };
40
+ }
41
+ /** Source of an apply materialized from `--repo`; the commit is the one the resolver pinned. */
42
+ export async function repoOrmApplySource({ targetUrl, token, namespace, name, commit, path }) {
43
+ if (!commit)
44
+ return null;
45
+ const repo = await resolveRepo({ baseUrl: targetUrl, token, namespace, name });
46
+ return { repository_id: repo.id, commit, path: path ?? '.', dirty: false };
47
+ }
48
+ /** Whether the target records apply sources; an older Atlas rejects the unknown `source` field. */
49
+ export async function targetRecordsApplySource({ targetUrl, token }) {
50
+ try {
51
+ const response = await fetch(new URL('/api/orm/runtime-capabilities', targetUrl), { headers: { authorization: `Bearer ${token}` } });
52
+ if (!response.ok)
53
+ return false;
54
+ const body = await response.json();
55
+ return typeof body === 'object' && body !== null && 'activationSource' in body && body.activationSource === true;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
61
+ /**
62
+ * Hand the apply's Git Service source to the pinned ORM package, which sends
63
+ * it for the namespace's activation history. Best effort: an unresolvable
64
+ * source or an older Atlas leaves the activation recorded as `reported`.
65
+ */
66
+ export async function exportApplySource({ auth, targetUrl, resolve }) {
67
+ delete process.env[ORM_SOURCE_ENV];
68
+ if (!auth || !(await targetRecordsApplySource({ targetUrl, token: auth.token })))
69
+ return;
70
+ try {
71
+ const source = await resolve();
72
+ if (source)
73
+ process.env[ORM_SOURCE_ENV] = JSON.stringify(source);
74
+ else
75
+ console.warn('[seq-studio] apply source unknown (not a clone of this environment\'s Git Service); the activation is recorded as reported');
76
+ }
77
+ catch (error) {
78
+ console.warn(`[seq-studio] could not resolve the apply source: ${error instanceof Error ? error.message : String(error)}`);
79
+ }
80
+ }
81
+ /** `orm apply <dir>` from a local checkout; every other subcommand sends no source. */
82
+ export async function exportLocalApplySource({ sub, auth, targetUrl, dir = '.' }) {
83
+ if (sub !== 'apply' || !targetUrl)
84
+ return;
85
+ await exportApplySource({ auth, targetUrl, resolve: async () => localOrmApplySource({ dir, targetUrl }) });
86
+ }
@@ -16,8 +16,9 @@ import { explicitOrSandboxEnv, normalizeShortEnvFlag, readEnvFromArgv, withoutEn
16
16
  import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
17
17
  import { resolveFunctionSourceDir } from '../functions/source-selection.js';
18
18
  import { warnBeforeHostDeploy } from '../manifest-roles-notice.js';
19
- import { ORM_DEPLOYMENT_POLICY_HELP, ORM_DISCOVER_HELP, ORM_EXECUTE_HELP, ORM_HELP } from '../command-help.js';
19
+ import { ORM_DEPLOYMENT_POLICY_HELP, ORM_DISCOVER_HELP, ORM_EXECUTE_HELP, ORM_HELP, ORM_HISTORY_HELP } from '../command-help.js';
20
20
  import { ormVersionMismatch, requiresSchemaVersionCheck } from './version-guard.js';
21
+ import { exportApplySource, exportLocalApplySource, repoOrmApplySource } from './apply-source.js';
21
22
  /**
22
23
  * ORM subcommands that talk to Atlas — must not silently target `local`.
23
24
  * `init`, `generate`, `validate`, `diff`, `migrate-from-yaml`, and `import` are offline.
@@ -142,6 +143,12 @@ async function runOrmFromRepo({ sub, selection, auth, targetUrl, ormCli, }) {
142
143
  'committed migrations are out of date — run `seq-studio orm diff` in the repository, commit the migration, and retry.');
143
144
  return 1;
144
145
  }
146
+ if (sub === 'apply') {
147
+ await exportApplySource({ auth, targetUrl, resolve: () => repoOrmApplySource({
148
+ targetUrl, token: auth.token, namespace: selection.spec.namespace, name: selection.spec.name,
149
+ commit: source.provenance.gitCommit, path: selection.path,
150
+ }) });
151
+ }
145
152
  const args = [dir, ...selection.rest];
146
153
  await warnBeforeHostDeploy({ sub, deploySub: 'apply', args, file: 'namespace.yaml' });
147
154
  return await ormCli.runCli([sub, ...args]);
@@ -183,9 +190,17 @@ export function formatOrmDependencyFailure(message) {
183
190
  * CLI: discovery reads Atlas's registry, and ad-hoc reads go through the ORM
184
191
  * client. None of them needs a namespace directory.
185
192
  */
186
- const NATIVE_ORM_SUBS = new Set(['namespaces', 'describe', 'operation', 'read', 'sql', 'deployment-policy']);
193
+ const NATIVE_ORM_SUBS = new Set(['namespaces', 'describe', 'operation', 'read', 'sql', 'deployment-policy', 'history']);
187
194
  async function runNativeOrmCommand(sub, rest) {
188
195
  const help = rest.includes('--help') || rest.includes('-h');
196
+ if (sub === 'history') {
197
+ if (help) {
198
+ console.log(ORM_HISTORY_HELP);
199
+ return 0;
200
+ }
201
+ const { ormHistoryCommand } = await import('./history.js');
202
+ return ormHistoryCommand(parseArgs(rest));
203
+ }
189
204
  if (sub === 'deployment-policy') {
190
205
  if (help) {
191
206
  console.log(ORM_DEPLOYMENT_POLICY_HELP);
@@ -320,6 +335,7 @@ export async function runOrmCommand(sub, rest) {
320
335
  return 1;
321
336
  }
322
337
  }
338
+ await exportLocalApplySource({ sub, auth, targetUrl, dir: positionalDir(normalized) });
323
339
  await warnBeforeHostDeploy({ sub, deploySub: 'apply', args: normalized, file: 'namespace.yaml' });
324
340
  return runCli([sub, ...normalized]);
325
341
  }
@@ -1 +1 @@
1
- export declare const ORM_USAGE = "usage:\n seq-studio orm init <dir> [--repo <ns>/<name>]\n scaffold a namespace package (v2: TypeScript schema + GraphQL documents);\n --repo scaffolds into a git-service repo (see Init into a repo below)\n seq-studio orm generate [dir] write schema.graphql + operations.manifest.json + typePolicies.gen.ts (offline; runs consumer codegen when codegen.ts is present)\n seq-studio orm generate [dir] --migration-export [--check]\n export reviewed ORM inputs for a coordinated pipeline migration; --check verifies without writing\n seq-studio orm validate [dir] parse + validate definitions and verify committed migrations are in sync\n seq-studio orm plan [dir] -e <env> compile definitions and diff against the registry\n seq-studio orm apply [dir] -e <env> [--timeout <duration>] [--no-wait]\n author the migration, register, apply, and refresh the generated outputs (the everyday command);\n waits until the new version is live (default up to 20m; e.g. --timeout 90s), --no-wait returns once queued\n seq-studio orm plan|apply --repo <ns>/<name> [--path <dir>] [--ref <ref>] -e <env>\n plan/apply a namespace committed to a platform git-service repo (CI deploy-from-git);\n --path selects the namespace directory (default: repo root). A remote apply never\n authors migrations: the committed ledger must already match the definitions.\n seq-studio orm execute <namespace> <operation> -e <env> [--variables-file <file>] [--var <name>=<value>]...\n run the deployed version's persisted operation by name as the caller (no checkout)\n seq-studio orm execute <operation> [dir] --variables-file <file> -e <env>\n execute from the checkout manifest through the installed ORM package\n both execute forms accept --variables-file - (or /dev/stdin) for JSON stdin until EOF\n seq-studio orm read <namespace> <table> -e <env> [--where c=op.v]... [--select c,...] [--order c.desc] [--limit N] [--offset N] [--json|--jsonl]\n read rows of a deployed v2 namespace as the caller (row-level security applies)\n seq-studio orm sql <namespace> --query <sql> | --file <path> -e <env> [--param name[:type]=v]... | [--params <json-object>] [--json|--jsonl]\n run read-only SQL against a deployed v2 namespace as the caller\n seq-studio orm namespaces -e <env> [--limit N] [--offset N] [--json]\n list the namespaces you can read\n seq-studio orm deployment-policy <namespace> -e <env> [--mode manual|ci] [--repo <ns>/<name> --branch <branch> --target <target-key>] [--json]\n inspect or explicitly change the namespace's deployment controller\n seq-studio orm describe <namespace> [<table> | --operations] -e <env> [--json]\n show a namespace's tables, views, and persisted operations (with variables), or one table's columns and actions\n seq-studio orm diff [dir] write/verify the committed migration standalone (--check is the offline CI gate; --allow-destructive consents; --rebase records a v1 -> v2 conversion)\n seq-studio orm migrate-from-yaml <dir> convert a v1 YAML namespace to the v2 TypeScript format (offline; migrations/ preserved)\n seq-studio orm import [dir] --spec <file> | --table <t> --from <schema.table> --map <target=source,...>\n plan a batched copy from an existing Postgres relation into an owned table (writes a SQL script; no database connection)\n\n Environments: see `seq-studio envs list` (built-in: local; more are\n discovered after you authenticate).\n Authenticate with: seq-studio login\n\n Init into a repo: --repo <ns>/<name> on an init command creates that platform\n git-service repo if missing (same name rules as repos create), then clones it\n into <dir> and scaffolds there, or, when <dir> is inside a Git checkout, sets\n it as that checkout's origin (a different existing origin is refused). It\n needs -e <env>, or an agent sandbox. Nothing is committed or pushed; the\n command prints the git add, commit, and push to run.\n In a git-service checkout (with or without --repo), orm init, functions init\n and artifact init also declare the scaffold under resources in\n .seq/repository.yml, so repository CI checks and deploys it. A scaffold inside\n a declared application is not declared; add it to that app with seq-studio add.\n";
1
+ export declare const ORM_USAGE = "usage:\n seq-studio orm init <dir> [--repo <ns>/<name>]\n scaffold a namespace package (v2: TypeScript schema + GraphQL documents);\n --repo scaffolds into a git-service repo (see Init into a repo below)\n seq-studio orm generate [dir] write schema.graphql + operations.manifest.json + typePolicies.gen.ts (offline; runs consumer codegen when codegen.ts is present)\n seq-studio orm generate [dir] --migration-export [--check]\n export reviewed ORM inputs for a coordinated pipeline migration; --check verifies without writing\n seq-studio orm validate [dir] parse + validate definitions and verify committed migrations are in sync\n seq-studio orm plan [dir] -e <env> compile definitions and diff against the registry\n seq-studio orm apply [dir] -e <env> [--timeout <duration>] [--no-wait]\n author the migration, register, apply, and refresh the generated outputs (the everyday command);\n waits until the new version is live (default up to 20m; e.g. --timeout 90s), --no-wait returns once queued\n seq-studio orm plan|apply --repo <ns>/<name> [--path <dir>] [--ref <ref>] -e <env>\n plan/apply a namespace committed to a platform git-service repo (CI deploy-from-git);\n --path selects the namespace directory (default: repo root). A remote apply never\n authors migrations: the committed ledger must already match the definitions.\n seq-studio orm execute <namespace> <operation> -e <env> [--variables-file <file>] [--var <name>=<value>]...\n run the deployed version's persisted operation by name as the caller (no checkout)\n seq-studio orm execute <operation> [dir] --variables-file <file> -e <env>\n execute from the checkout manifest through the installed ORM package\n both execute forms accept --variables-file - (or /dev/stdin) for JSON stdin until EOF\n seq-studio orm read <namespace> <table> -e <env> [--where c=op.v]... [--select c,...] [--order c.desc] [--limit N] [--offset N] [--json|--jsonl]\n read rows of a deployed v2 namespace as the caller (row-level security applies)\n seq-studio orm sql <namespace> --query <sql> | --file <path> -e <env> [--param name[:type]=v]... | [--params <json-object>] [--json|--jsonl]\n run read-only SQL against a deployed v2 namespace as the caller\n qualify tables and double-quote mixed-case columns (e.g. SELECT \"loanNumber\" FROM lending.loans)\n seq-studio orm namespaces -e <env> [--limit N] [--offset N] [--json]\n list the namespaces you can read\n seq-studio orm history <namespace> -e <env> [--limit N] [--json]\n seq-studio orm deployment-policy <namespace> -e <env> [--mode manual|ci] [--repo <ns>/<name> --branch <branch> --target <target-key>] [--json]\n inspect or explicitly change the namespace's deployment controller\n seq-studio orm describe <namespace> [<table> | --operations] -e <env> [--json]\n show a namespace's tables, views, and persisted operations (with variables), or one table's columns and actions\n seq-studio orm diff [dir] write/verify the committed migration standalone (--check is the offline CI gate; --allow-destructive consents; --rebase records a v1 -> v2 conversion)\n seq-studio orm migrate-from-yaml <dir> convert a v1 YAML namespace to the v2 TypeScript format (offline; migrations/ preserved)\n seq-studio orm import [dir] --spec <file> | --table <t> --from <schema.table> --map <target=source,...>\n plan a batched copy from an existing Postgres relation into an owned table (writes a SQL script; no database connection)\n\n Environments: see `seq-studio envs list` (built-in: local; more are\n discovered after you authenticate).\n Authenticate with: seq-studio login\n\n Init into a repo: --repo <ns>/<name> on an init command creates that platform\n git-service repo if missing (same name rules as repos create), then clones it\n into <dir> and scaffolds there, or, when <dir> is inside a Git checkout, sets\n it as that checkout's origin (a different existing origin is refused). It\n needs -e <env>, or an agent sandbox. Nothing is committed or pushed; the\n command prints the git add, commit, and push to run.\n In a git-service checkout (with or without --repo), orm init, functions init\n and artifact init also declare the scaffold under resources in\n .seq/repository.yml, so repository CI checks and deploys it. A scaffold inside\n a declared application is not declared; add it to that app with seq-studio add.\n";
package/dist/orm/help.js CHANGED
@@ -24,8 +24,10 @@ export const ORM_USAGE = `usage:
24
24
  read rows of a deployed v2 namespace as the caller (row-level security applies)
25
25
  seq-studio orm sql <namespace> --query <sql> | --file <path> -e <env> [--param name[:type]=v]... | [--params <json-object>] [--json|--jsonl]
26
26
  run read-only SQL against a deployed v2 namespace as the caller
27
+ qualify tables and double-quote mixed-case columns (e.g. SELECT "loanNumber" FROM lending.loans)
27
28
  seq-studio orm namespaces -e <env> [--limit N] [--offset N] [--json]
28
29
  list the namespaces you can read
30
+ seq-studio orm history <namespace> -e <env> [--limit N] [--json]
29
31
  seq-studio orm deployment-policy <namespace> -e <env> [--mode manual|ci] [--repo <ns>/<name> --branch <branch> --target <target-key>] [--json]
30
32
  inspect or explicitly change the namespace's deployment controller
31
33
  seq-studio orm describe <namespace> [<table> | --operations] -e <env> [--json]
@@ -0,0 +1,23 @@
1
+ import type { ParsedArgs } from '../argv.js';
2
+ export interface ActivationRow {
3
+ id: string;
4
+ kind: 'schema' | 'operations' | 'attest';
5
+ version_id: string;
6
+ operation_set_id: string | null;
7
+ provenance_class: 'repository_verified' | 'ci_intent' | 'reported';
8
+ source_repository_id: string | null;
9
+ source_commit: string | null;
10
+ source_branch: string | null;
11
+ source_path: string | null;
12
+ intent_id: string | null;
13
+ ledger_ordinal: number | null;
14
+ reported_source: Record<string, unknown> | null;
15
+ actor_sub: string;
16
+ activated_at: string;
17
+ }
18
+ /** One line per activation: when, who, what moved, and where it came from. */
19
+ export declare function formatActivation({ row, active }: {
20
+ row: ActivationRow;
21
+ active: boolean;
22
+ }): string;
23
+ export declare function ormHistoryCommand(args: ParsedArgs): Promise<number>;
@@ -0,0 +1,58 @@
1
+ import { getJson } from '../atlas-client.js';
2
+ import { printCliError } from '../cli-errors.js';
3
+ import { validateCommandInput } from '../command-input.js';
4
+ import { buildContext, clientOptions } from '../functions/commands.js';
5
+ const DEFAULT_LIMIT = 20;
6
+ function limitFlag(args) {
7
+ const raw = args.flags.limit;
8
+ if (raw === undefined)
9
+ return DEFAULT_LIMIT;
10
+ const limit = Number(raw);
11
+ if (!Number.isInteger(limit) || limit < 1 || limit > 500)
12
+ throw new Error('--limit must be an integer from 1 to 500.');
13
+ return limit;
14
+ }
15
+ /** One line per activation: when, who, what moved, and where it came from. */
16
+ export function formatActivation({ row, active }) {
17
+ const actor = row.actor_sub.replace(/^google-apps\|/, '');
18
+ const what = row.kind === 'schema' ? `schema ${row.version_id.slice(0, 8)}${row.ledger_ordinal === null ? '' : ` (ledger ${row.ledger_ordinal})`}`
19
+ : row.kind === 'operations' ? `operations ${row.operation_set_id?.slice(0, 8) ?? '-'}`
20
+ : `attest ${row.version_id.slice(0, 8)}`;
21
+ const claimed = row.reported_source;
22
+ const where = row.provenance_class === 'reported'
23
+ ? `reported${typeof claimed?.commit === 'string' ? ` ${claimed.commit.slice(0, 12)}` : ''}${typeof claimed?.verification_failure === 'string' ? ` (${claimed.verification_failure})` : ''}`
24
+ : `${row.provenance_class === 'ci_intent' ? 'ci' : 'verified'} ${row.source_commit?.slice(0, 12)} on ${row.source_branch} at ${row.source_path === '' ? '.' : row.source_path}`;
25
+ return `${active ? '*' : ' '} ${row.activated_at.slice(0, 19).replace('T', ' ')}Z ${what.padEnd(28)} ${actor.padEnd(32)} ${where}`;
26
+ }
27
+ export async function ormHistoryCommand(args) {
28
+ try {
29
+ validateCommandInput({ args, flags: { limit: 'string' }, positional: 1 });
30
+ const namespace = args.positional[0];
31
+ if (!namespace)
32
+ throw new Error('usage: seq-studio orm history <namespace> -e <env> [--limit N] [--json]');
33
+ const limit = limitFlag(args);
34
+ const options = clientOptions(await buildContext(args));
35
+ const result = await getJson({
36
+ ...options,
37
+ path: `/api/orm/namespaces/${encodeURIComponent(namespace)}?versions_limit=1&ledger_limit=1&activations_limit=${limit}`,
38
+ });
39
+ if (result.activations === undefined)
40
+ throw new Error('This Atlas does not record activation history yet.');
41
+ if (args.flags.json === true) {
42
+ console.log(JSON.stringify({ namespace, activations: result.activations, activations_total: result.activations_total }, null, 2));
43
+ return 0;
44
+ }
45
+ if (result.activations.length === 0) {
46
+ console.log(`${namespace}: no activations recorded yet (history starts with the first apply after it shipped)`);
47
+ return 0;
48
+ }
49
+ console.log(`${namespace}: ${result.activations_total ?? result.activations.length} activation(s), newest first; * = live`);
50
+ for (const row of result.activations)
51
+ console.log(formatActivation({ row, active: row.id === result.namespace.active_activation_id }));
52
+ return 0;
53
+ }
54
+ catch (error) {
55
+ printCliError(error);
56
+ return 1;
57
+ }
58
+ }
@@ -12,7 +12,7 @@
12
12
  */
13
13
  import type { SqlQueryParameter, SqlQueryVariables } from '@sequenceholdings/orm/client';
14
14
  import type { ParsedArgs } from '../process/commands.js';
15
- export declare const ORM_READ_USAGE = "usage:\n seq-studio orm read <namespace> <table> -e <env> [--where <column>=<op>.<value>]...\n [--select <col,...>] [--order <column>[.asc|.desc]]... [--limit N] [--offset N] [--json | --jsonl]\n seq-studio orm sql <namespace> (--query <sql> | --file <path>) -e <env>\n [--param <name>[:<type>]=<value>]... | [--params <json-object>] [--json | --jsonl]\n\n Reads run as you against an ORM v2 namespace: its grants, row-level security,\n and a read-only SQL grammar apply on the server, which returns at most 1,000 rows.\n\n --where operators: eq, ne, gt, gte, lt, lte, in, is\n --where status=eq.open --where balance=gte.1000 --where id=in.(a,b,c) --where closed_at=is.null\n sql binds :name placeholders. --param types: text (default), uuid, date, timestamptz,\n numeric, bigint, integer, double, boolean. --params takes the wire shape, e.g.\n '{\"limit\": {\"type\": \"integer\", \"value\": 5}}', and allows null values.\n sql must reference every table as <namespace>.<table> (SELECT id FROM lending.loans, not\n FROM loans); unqualified names and queries without a table (SELECT 1) are rejected.\n The grammar is read-only SELECT with joins, CTEs, UNION, aggregates, and comparison\n operators (no LIKE or IN).\n --json prints a JSON array of row objects; --jsonl prints one row object per line.\n Without either, rows print as a table. Counts, truncation, and paging hints go to stderr.\n";
15
+ export declare const ORM_READ_USAGE = "usage:\n seq-studio orm read <namespace> <table> -e <env> [--where <column>=<op>.<value>]...\n [--select <col,...>] [--order <column>[.asc|.desc]]... [--limit N] [--offset N] [--json | --jsonl]\n seq-studio orm sql <namespace> (--query <sql> | --file <path>) -e <env>\n [--param <name>[:<type>]=<value>]... | [--params <json-object>] [--json | --jsonl]\n\n Reads run as you against an ORM v2 namespace: its grants, row-level security,\n and a read-only SQL grammar apply on the server, which returns at most 1,000 rows.\n\n --where operators: eq, ne, gt, gte, lt, lte, in, is\n --where status=eq.open --where balance=gte.1000 --where id=in.(a,b,c) --where closed_at=is.null\n sql binds :name placeholders. --param types: text (default), uuid, date, timestamptz,\n numeric, bigint, integer, double, boolean. --params takes the wire shape, e.g.\n '{\"limit\": {\"type\": \"integer\", \"value\": 5}}', and allows null values.\n sql must reference every table as <namespace>.<table> (SELECT id FROM lending.loans, not\n FROM loans); unqualified names and queries without a table (SELECT 1) are rejected.\n Quote mixed-case column names: SELECT \"loanNumber\" FROM lending.loans.\n The grammar is read-only SELECT with joins, CTEs, UNION, aggregates, and comparison\n operators (no LIKE or IN).\n --json prints a JSON array of row objects; --jsonl prints one row object per line.\n Without either, rows print as a table. Counts, truncation, and paging hints go to stderr.\n";
16
16
  export interface ReadFilter {
17
17
  column: string;
18
18
  op: string;
package/dist/orm/read.js CHANGED
@@ -32,6 +32,7 @@ export const ORM_READ_USAGE = `usage:
32
32
  '{"limit": {"type": "integer", "value": 5}}', and allows null values.
33
33
  sql must reference every table as <namespace>.<table> (SELECT id FROM lending.loans, not
34
34
  FROM loans); unqualified names and queries without a table (SELECT 1) are rejected.
35
+ Quote mixed-case column names: SELECT "loanNumber" FROM lending.loans.
35
36
  The grammar is read-only SELECT with joins, CTEs, UNION, aggregates, and comparison
36
37
  operators (no LIKE or IN).
37
38
  --json prints a JSON array of row objects; --jsonl prints one row object per line.
@@ -301,8 +302,9 @@ function isRejectedSql(error) {
301
302
  return error instanceof Error && error.name === 'OrmOperationError' && Reflect.get(error, 'code') === 'BAD_USER_INPUT';
302
303
  }
303
304
  export function sqlGrammarHint(namespace) {
304
- return `[seq-studio] hint: reference every table as <namespace>.<table> (e.g. SELECT count(*) FROM ${namespace}.<table>); `
305
- + 'unqualified names and queries without a table are rejected. The grammar is read-only SELECT with joins, '
305
+ return `[seq-studio] hint: check table qualification (e.g. SELECT count(*) FROM ${namespace}.<table>) `
306
+ + 'and double-quote mixed-case columns (e.g. SELECT "loanNumber" FROM '
307
+ + `${namespace}.<table>). Unqualified tables and queries without a table are rejected. The grammar is read-only SELECT with joins, `
306
308
  + 'CTEs, UNION, aggregates (count, sum, avg, min, max), lower/upper/length, and comparison operators; '
307
309
  + 'it has no LIKE or IN. See: seq-studio orm sql --help.';
308
310
  }
@@ -11,6 +11,7 @@
11
11
  * The SDK is lazy-imported like `@sequenceholdings/orm` so public installs of
12
12
  * the CLI without the package get a clear install hint instead of a crash.
13
13
  */
14
+ import { cliAttributionHeaders } from '../cli-attribution.js';
14
15
  import { pipelineSourceError } from './source.js';
15
16
  import { mkdir, readFile, writeFile } from 'node:fs/promises';
16
17
  import { existsSync } from 'node:fs';
@@ -277,7 +278,7 @@ export function buildExternalAssetsRequest({ source, knownOrigins, token, }) {
277
278
  return {
278
279
  url,
279
280
  init: {
280
- headers: { authorization: `Bearer ${token}` },
281
+ headers: { authorization: `Bearer ${token}`, ...cliAttributionHeaders() },
281
282
  redirect: 'manual',
282
283
  },
283
284
  };
@@ -30,6 +30,9 @@ const INGESTION_BODY = `
30
30
  # Where the ingestion code runs: databricks (API pulls) | edge-worker (on-prem VM).
31
31
  # ('upload' is reserved — not yet supported.)
32
32
  runtime: databricks
33
+ # Optional source schema for both raw files and materialized source tables.
34
+ # Omitted preserves legacy bronze paths; changing an existing stage needs migration.
35
+ # source_schema: raw
33
36
  # databricks runtime pulls from an external system (symbolic refs, never secrets).
34
37
  # Secure-by-default: declare a credential for authenticated APIs. Attach a
35
38
  # managed secret to it per deploy target (seq-studio secrets attach <NAME>
@@ -48,8 +51,8 @@ source:
48
51
  feeds:
49
52
  # One feed = one stream of raw files into the volume landing zone.
50
53
  # The platform derives (per-source catalog, never the deployment catalog):
51
- # /Volumes/src_<source>/bronze/<feed>/batch_id=<ts>/, the bronze table
52
- # src_<source>.bronze.<feed>, envelope columns (batch_id, ingested_at,
54
+ # /Volumes/src_<source>/<source_schema>/<feed>/batch_id=<ts>/, the source table
55
+ # src_<source>.<source_schema>.<feed>, envelope columns (batch_id, ingested_at,
53
56
  # source_system, content_hash), and a presence manifest for full_snapshot.
54
57
  my_feed:
55
58
  # full_snapshot | incremental | event_stream