@sequenceholdings/studio-cli 0.9.10 → 0.9.13

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.
@@ -13,10 +13,22 @@ export const INIT_INTO_REPO_HELP = ` Init into a repo: --repo <ns>/<name> on an
13
13
  .seq/repository.yml, so repository CI checks and deploys it. A scaffold inside
14
14
  a declared application is not declared; add it to that app with seq-studio add.
15
15
  `;
16
+ export const ORM_HISTORY_HELP = `usage:
17
+ seq-studio orm history <namespace> -e <env> [--limit N] [--json]
18
+
19
+ Lists every change to the namespace's live schema and operations, newest
20
+ first: when, who, what moved, and the Git Service source. "verified" and "ci"
21
+ sources were checked by Atlas against the repository; "reported" means Atlas
22
+ could not tie the change to a pushed commit on a release branch, with the
23
+ reason when one was claimed. "break_glass" is an admin override made with
24
+ orm apply --unverified-source "<reason>". * marks the live activation.
25
+ History starts with the first apply after the environment recorded it.
26
+ `;
16
27
  export const ORM_DEPLOYMENT_POLICY_HELP = `usage:
17
28
  seq-studio orm deployment-policy <namespace> -e <env> [--json]
18
29
  seq-studio orm deployment-policy <namespace> -e <env> --mode ci --repo <ns>/<name> --branch <branch> --target <target-key>
19
30
  seq-studio orm deployment-policy <namespace> -e <env> --mode manual
31
+ seq-studio orm deployment-policy <namespace> -e <env> --mode source --repo <ns>/<name> --branch <branch> --path <dir>
20
32
 
21
33
  Existing namespaces default to manual deployment. CI mode rejects direct ORM
22
34
  registration, schema apply, and operations-only activation on the server;
@@ -24,14 +36,20 @@ export const ORM_DEPLOYMENT_POLICY_HELP = `usage:
24
36
  Enabling CI mode requires namespace Admin, repository Admin, and an existing
25
37
  automatic branch binding to this namespace. Restoring manual mode requires
26
38
  namespace Admin. This changes deployment policy; it does not deploy source.
39
+
40
+ Source mode keeps direct applies but accepts only ones Atlas verifies came
41
+ from that repository, branch and package directory (pass --path . for the
42
+ repository root). It requires namespace Admin and repository Read. Namespace
43
+ admins can still apply with --unverified-source "<reason>", which is recorded.
27
44
  `;
28
45
  export const ORM_HELP = `usage:
29
46
  seq-studio orm init <dir> [--repo <ns>/<name>]
30
47
  seq-studio orm generate [dir] [--migration-export] [--check]
31
48
  seq-studio orm validate [dir]
32
49
  seq-studio orm plan [dir] -e <env>
33
- seq-studio orm apply [dir] -e <env> [--timeout <duration>] [--no-wait]
34
- seq-studio orm deployment-policy <namespace> -e <env> [--mode manual|ci] [--repo <ns>/<name> --branch <branch> --target <target-key>] [--json]
50
+ seq-studio orm apply [dir] -e <env> [--timeout <duration>] [--no-wait] [--unverified-source "<reason>"]
51
+ seq-studio orm history <namespace> -e <env> [--limit N] [--json]
52
+ seq-studio orm deployment-policy <namespace> -e <env> [--mode manual|ci|source] [--repo <ns>/<name> --branch <branch> (--target <target-key> | --path <dir>)] [--json]
35
53
  seq-studio orm execute <namespace> <operation> -e <env> [--variables-file <file>] [--var <name>=<value>]...
36
54
  seq-studio orm execute <operation> [dir] --variables-file <file> -e <env>
37
55
  seq-studio orm namespaces -e <env> [--limit N] [--offset N] [--json]
@@ -50,7 +68,11 @@ export const ORM_HELP = `usage:
50
68
  apply waits until the new version is live and serving (default up to 20m), then
51
69
  prints "live:"; --no-wait returns once the apply is queued.
52
70
  CI-managed namespaces reject direct apply; use the enrolled repository's merge
53
- workflow. deployment-policy reads or explicitly changes this namespace setting.
71
+ workflow. Source-pinned namespaces accept only applies Atlas verifies against
72
+ their repository, branch and package path, and an environment can require a
73
+ verified source for every apply. A namespace admin may record an audited
74
+ exception with --unverified-source "<reason>". deployment-policy reads or
75
+ explicitly changes this namespace setting.
54
76
  namespaces lists what you can read; describe shows its tables and operations.
55
77
  Run seq-studio orm describe --help for the output.
56
78
  execute <namespace> <operation> runs the deployed version's persisted operation by
@@ -107,12 +129,16 @@ export const FUNCTIONS_USAGE = `usage:
107
129
  seq-studio functions invoke -e <env> [--data JSON | --data @file | --stdin]
108
130
  invoke a function and print its response
109
131
  seq-studio functions logs -e <env> [--limit N] [--since t] function logs (reader-gated)
110
- seq-studio functions promote <version> -e <env> make a version live
111
- seq-studio functions rollback [<version>] -e <env> redeploy a prior version
112
- seq-studio functions delete -e <env> [--yes] archive function + tear down its runtime
132
+ seq-studio functions promote <version> -e <env> [--fn <slug>]
133
+ make a version live
134
+ seq-studio functions rollback [<version>] -e <env> [--fn <slug>]
135
+ redeploy a prior version
136
+ seq-studio functions delete -e <env> [--fn <slug>] [--yes]
137
+ archive function + tear down its runtime
113
138
  (version history is retained)
114
139
 
115
140
  Flags: -e/--env <env|preview:<slug>> (required for network commands; see: seq-studio envs list) · --fn <slug> · --dir <path>
141
+ --fn selects a deployed function without a local manifest; otherwise the manifest in --dir (default .) supplies its slug
116
142
  --path <repo-subdirectory> (remote build/deploy only) select one function in a multi-function repo
117
143
  --from-env-file <path> (default: .env) source file for secret values
118
144
  --no-wait · --yes
@@ -283,6 +309,8 @@ export const ORM_EXECUTE_HELP = `usage:
283
309
  `;
284
310
  /** read and sql print their own grammar help from the delegate. */
285
311
  function ormHelp(sub) {
312
+ if (sub === 'history')
313
+ return ORM_HISTORY_HELP;
286
314
  if (sub === 'deployment-policy')
287
315
  return ORM_DEPLOYMENT_POLICY_HELP;
288
316
  if (sub === 'namespaces' || sub === 'describe')
@@ -0,0 +1,11 @@
1
+ /** Called only after the existing auth path has verified the token and target. */
2
+ export declare function recordAuthenticatedCliTarget(baseUrl: string, token: string): void;
3
+ export declare function beginCommandTelemetry(): number;
4
+ export declare function telemetryEnabled(): Promise<boolean>;
5
+ export declare function setTelemetryEnabled(enabled: boolean): Promise<void>;
6
+ export declare function finishCommandTelemetry(input: {
7
+ command: string | null;
8
+ startedAt: number;
9
+ exitCode: number;
10
+ error?: unknown;
11
+ }): Promise<void>;
@@ -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,76 @@
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
+ /** Mirrors `UNVERIFIED_SOURCE_REASON_ENV` in `@sequenceholdings/orm/cli`. */
29
+ export declare const ORM_UNVERIFIED_SOURCE_REASON_ENV = "SEQUENCE_ORM_UNVERIFIED_SOURCE_REASON";
30
+ /** Pull `--unverified-source <reason>` (or `=reason`) off the argv; only `apply` accepts it. */
31
+ export declare function takeUnverifiedSourceFlag({ sub, argv }: {
32
+ sub: string;
33
+ argv: readonly string[];
34
+ }): {
35
+ reason?: string;
36
+ args: string[];
37
+ } | {
38
+ error: string;
39
+ };
40
+ export interface ApplySourceCapabilities {
41
+ /** The target records apply sources; an older Atlas rejects the unknown `source` field. */
42
+ records: boolean;
43
+ /** The target refuses applies whose source it cannot verify. */
44
+ enforced: boolean;
45
+ }
46
+ export declare function applySourceCapabilities({ targetUrl, token }: {
47
+ targetUrl: string;
48
+ token: string;
49
+ }): Promise<ApplySourceCapabilities>;
50
+ /**
51
+ * Hand the apply's Git Service source, and any override reason, to the pinned
52
+ * ORM package, which sends them with the apply. Returns why the apply cannot
53
+ * succeed when the target enforces verified sources and this one plainly will
54
+ * not verify, so the caller stops before registering anything.
55
+ */
56
+ export declare function exportApplySource({ auth, targetUrl, resolve, unverifiedReason, dryRun }: {
57
+ auth: {
58
+ token: string;
59
+ } | null;
60
+ targetUrl: string;
61
+ resolve: () => Promise<OrmApplySource | null>;
62
+ unverifiedReason?: string;
63
+ /** A rehearsal on a disposable fork activates nothing, so it is never refused for its source. */
64
+ dryRun?: boolean;
65
+ }): Promise<string | null>;
66
+ /** `orm apply <dir>` from a local checkout; every other subcommand sends no source. */
67
+ export declare function exportLocalApplySource({ sub, auth, targetUrl, dir, unverifiedReason, dryRun }: {
68
+ sub: string;
69
+ auth: {
70
+ token: string;
71
+ } | null;
72
+ targetUrl: string | undefined;
73
+ dir?: string;
74
+ unverifiedReason?: string;
75
+ dryRun?: boolean;
76
+ }): Promise<string | null>;
@@ -0,0 +1,127 @@
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
+ /** Mirrors `UNVERIFIED_SOURCE_REASON_ENV` in `@sequenceholdings/orm/cli`. */
49
+ export const ORM_UNVERIFIED_SOURCE_REASON_ENV = 'SEQUENCE_ORM_UNVERIFIED_SOURCE_REASON';
50
+ const UNVERIFIED_SOURCE_FLAG = '--unverified-source';
51
+ /** Pull `--unverified-source <reason>` (or `=reason`) off the argv; only `apply` accepts it. */
52
+ export function takeUnverifiedSourceFlag({ sub, argv }) {
53
+ const args = [];
54
+ let reason;
55
+ for (let index = 0; index < argv.length; index += 1) {
56
+ const arg = argv[index];
57
+ if (arg !== UNVERIFIED_SOURCE_FLAG && !arg.startsWith(`${UNVERIFIED_SOURCE_FLAG}=`)) {
58
+ args.push(arg);
59
+ continue;
60
+ }
61
+ const value = arg === UNVERIFIED_SOURCE_FLAG ? argv[(index += 1)] : arg.slice(UNVERIFIED_SOURCE_FLAG.length + 1);
62
+ if (value === undefined || value.startsWith('-') || value.trim().length < 10) {
63
+ return { error: `${UNVERIFIED_SOURCE_FLAG} needs a reason of at least 10 characters, e.g. ${UNVERIFIED_SOURCE_FLAG} "incident 123 hotfix before merge"` };
64
+ }
65
+ reason = value.trim();
66
+ }
67
+ if (reason !== undefined && sub !== 'apply')
68
+ return { error: `${UNVERIFIED_SOURCE_FLAG} applies only to apply` };
69
+ return reason === undefined ? { args } : { reason, args };
70
+ }
71
+ export async function applySourceCapabilities({ targetUrl, token }) {
72
+ try {
73
+ const response = await fetch(new URL('/api/orm/runtime-capabilities', targetUrl), { headers: { authorization: `Bearer ${token}` } });
74
+ if (!response.ok)
75
+ return { records: false, enforced: false };
76
+ const body = await response.json();
77
+ if (typeof body !== 'object' || body === null)
78
+ return { records: false, enforced: false };
79
+ const records = 'activationSource' in body && body.activationSource === true;
80
+ return { records, enforced: records && 'requireVerifiedSource' in body && body.requireVerifiedSource === true };
81
+ }
82
+ catch {
83
+ return { records: false, enforced: false };
84
+ }
85
+ }
86
+ /**
87
+ * Hand the apply's Git Service source, and any override reason, to the pinned
88
+ * ORM package, which sends them with the apply. Returns why the apply cannot
89
+ * succeed when the target enforces verified sources and this one plainly will
90
+ * not verify, so the caller stops before registering anything.
91
+ */
92
+ export async function exportApplySource({ auth, targetUrl, resolve, unverifiedReason, dryRun = false }) {
93
+ delete process.env[ORM_SOURCE_ENV];
94
+ delete process.env[ORM_UNVERIFIED_SOURCE_REASON_ENV];
95
+ const capabilities = auth ? await applySourceCapabilities({ targetUrl, token: auth.token }) : { records: false, enforced: false };
96
+ if (!capabilities.records)
97
+ return null;
98
+ if (unverifiedReason)
99
+ process.env[ORM_UNVERIFIED_SOURCE_REASON_ENV] = unverifiedReason;
100
+ let source = null;
101
+ try {
102
+ source = await resolve();
103
+ }
104
+ catch (error) {
105
+ console.warn(`[seq-studio] could not resolve the apply source: ${error instanceof Error ? error.message : String(error)}`);
106
+ }
107
+ if (source)
108
+ process.env[ORM_SOURCE_ENV] = JSON.stringify(source);
109
+ const problem = !source ? 'is not a clone of this environment\'s Git Service' : source.dirty ? 'has uncommitted changes in the ORM package' : null;
110
+ if (!problem)
111
+ return null;
112
+ if (capabilities.enforced && !unverifiedReason && !dryRun) {
113
+ return `This environment applies ORM changes only from a pushed commit Atlas can verify, and this checkout ${problem}. ` +
114
+ `Commit and push the package (run \`seq-studio orm diff\` first so its migration is committed), then apply again or use --repo. ` +
115
+ `Namespace admins can override with ${UNVERIFIED_SOURCE_FLAG} "<reason>".`;
116
+ }
117
+ if (dryRun)
118
+ return null;
119
+ console.warn(`[seq-studio] this checkout ${problem}; the activation is recorded as ${unverifiedReason ? 'break_glass' : 'reported'}`);
120
+ return null;
121
+ }
122
+ /** `orm apply <dir>` from a local checkout; every other subcommand sends no source. */
123
+ export async function exportLocalApplySource({ sub, auth, targetUrl, dir = '.', unverifiedReason, dryRun }) {
124
+ if (sub !== 'apply' || !targetUrl)
125
+ return null;
126
+ return exportApplySource({ auth, targetUrl, unverifiedReason, dryRun, resolve: async () => localOrmApplySource({ dir, targetUrl }) });
127
+ }
@@ -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, takeUnverifiedSourceFlag } 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.
@@ -113,7 +114,7 @@ function aliasOrmModuleForRemoteSource(envName) {
113
114
  // error names the missing module.
114
115
  }
115
116
  }
116
- async function runOrmFromRepo({ sub, selection, auth, targetUrl, ormCli, }) {
117
+ async function runOrmFromRepo({ sub, selection, auth, targetUrl, ormCli, unverifiedReason, }) {
117
118
  if (!auth || !targetUrl) {
118
119
  console.error('[seq-studio] orm --repo needs a target environment and auth. Pass -e <env> and run `seq-studio login`.');
119
120
  return 1;
@@ -142,6 +143,14 @@ 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
+ const refusal = sub === 'apply' ? await exportApplySource({ auth, targetUrl, unverifiedReason, dryRun: selection.rest.includes('--dry-run'), resolve: () => repoOrmApplySource({
147
+ targetUrl, token: auth.token, namespace: selection.spec.namespace, name: selection.spec.name,
148
+ commit: source.provenance.gitCommit, path: selection.path,
149
+ }) }) : null;
150
+ if (refusal) {
151
+ console.error(`[seq-studio] ${refusal}`);
152
+ return 1;
153
+ }
145
154
  const args = [dir, ...selection.rest];
146
155
  await warnBeforeHostDeploy({ sub, deploySub: 'apply', args, file: 'namespace.yaml' });
147
156
  return await ormCli.runCli([sub, ...args]);
@@ -183,9 +192,17 @@ export function formatOrmDependencyFailure(message) {
183
192
  * CLI: discovery reads Atlas's registry, and ad-hoc reads go through the ORM
184
193
  * client. None of them needs a namespace directory.
185
194
  */
186
- const NATIVE_ORM_SUBS = new Set(['namespaces', 'describe', 'operation', 'read', 'sql', 'deployment-policy']);
195
+ const NATIVE_ORM_SUBS = new Set(['namespaces', 'describe', 'operation', 'read', 'sql', 'deployment-policy', 'history']);
187
196
  async function runNativeOrmCommand(sub, rest) {
188
197
  const help = rest.includes('--help') || rest.includes('-h');
198
+ if (sub === 'history') {
199
+ if (help) {
200
+ console.log(ORM_HISTORY_HELP);
201
+ return 0;
202
+ }
203
+ const { ormHistoryCommand } = await import('./history.js');
204
+ return ormHistoryCommand(parseArgs(rest));
205
+ }
189
206
  if (sub === 'deployment-policy') {
190
207
  if (help) {
191
208
  console.log(ORM_DEPLOYMENT_POLICY_HELP);
@@ -256,7 +273,12 @@ export async function runOrmCommand(sub, rest) {
256
273
  }
257
274
  if (NATIVE_ORM_SUBS.has(sub))
258
275
  return runNativeOrmCommand(sub, rest);
259
- const normalized = normalizeShortEnvFlag(rest);
276
+ const unverified = takeUnverifiedSourceFlag({ sub, argv: normalizeShortEnvFlag(rest) });
277
+ if ('error' in unverified) {
278
+ console.error(`[seq-studio] ${unverified.error}`);
279
+ return 1;
280
+ }
281
+ const { reason: unverifiedReason, args: normalized } = unverified;
260
282
  const repoInit = sub === 'init' ? await runOrmInitWithRepo(normalized) : null;
261
283
  if (repoInit !== null)
262
284
  return repoInit;
@@ -312,13 +334,16 @@ export async function runOrmCommand(sub, rest) {
312
334
  }
313
335
  });
314
336
  if (repoSelection)
315
- return runOrmFromRepo({ sub, selection: repoSelection, auth, targetUrl, ormCli });
316
- if (requiresSchemaVersionCheck(sub)) {
317
- const mismatch = await ormVersionMismatch(positionalDir(normalized) ?? '.');
318
- if (mismatch) {
319
- console.error(`[seq-studio] ${mismatch}`);
320
- return 1;
321
- }
337
+ return runOrmFromRepo({ sub, selection: repoSelection, auth, targetUrl, ormCli, unverifiedReason });
338
+ return runLocalOrm({ sub, normalized, auth, targetUrl, unverifiedReason, runCli });
339
+ }
340
+ /** A namespace directory on disk: check its ORM version, attach the apply source, then forward. */
341
+ async function runLocalOrm({ sub, normalized, auth, targetUrl, unverifiedReason, runCli }) {
342
+ const problem = (requiresSchemaVersionCheck(sub) ? await ormVersionMismatch(positionalDir(normalized) ?? '.') : null) ??
343
+ await exportLocalApplySource({ sub, auth, targetUrl, dir: positionalDir(normalized), unverifiedReason, dryRun: normalized.includes('--dry-run') });
344
+ if (problem) {
345
+ console.error(`[seq-studio] ${problem}`);
346
+ return 1;
322
347
  }
323
348
  await warnBeforeHostDeploy({ sub, deploySub: 'apply', args: normalized, file: 'namespace.yaml' });
324
349
  return runCli([sub, ...normalized]);