@sequenceholdings/studio-cli 0.9.20 → 0.9.21

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 (55) hide show
  1. package/README.md +131 -11
  2. package/dist/app/commands.js +2 -0
  3. package/dist/app/deploy.js +2 -0
  4. package/dist/app/lockfile-preflight.d.ts +31 -0
  5. package/dist/app/lockfile-preflight.js +47 -0
  6. package/dist/app/repository-index.d.ts +5 -1
  7. package/dist/app/repository-index.js +9 -3
  8. package/dist/auth.d.ts +13 -9
  9. package/dist/auth.js +98 -20
  10. package/dist/cli-errors.js +6 -1
  11. package/dist/command-contract.d.ts +13 -1
  12. package/dist/command-contract.js +3 -1
  13. package/dist/command-help.d.ts +1 -1
  14. package/dist/command-help.js +8 -1
  15. package/dist/config.d.ts +14 -0
  16. package/dist/config.js +29 -3
  17. package/dist/docs/commands.d.ts +16 -0
  18. package/dist/docs/commands.js +168 -0
  19. package/dist/docs/help.d.ts +2 -0
  20. package/dist/docs/help.js +12 -0
  21. package/dist/envs/commands.js +10 -2
  22. package/dist/host-token.d.ts +19 -4
  23. package/dist/host-token.js +50 -10
  24. package/dist/main.d.ts +1 -0
  25. package/dist/main.js +20 -2
  26. package/dist/orm/discover-operations.d.ts +1 -1
  27. package/dist/orm/discover-operations.js +3 -3
  28. package/dist/orm/discover-schema.d.ts +0 -5
  29. package/dist/orm/discover-schema.js +0 -3
  30. package/dist/pipeline/commands.d.ts +0 -7
  31. package/dist/pipeline/commands.js +16 -67
  32. package/dist/pipeline/discovery.d.ts +1 -1
  33. package/dist/pipeline/discovery.js +6 -6
  34. package/dist/process/build.d.ts +2 -5
  35. package/dist/process/build.js +4 -49
  36. package/dist/repos/commands.d.ts +11 -1
  37. package/dist/repos/commands.js +78 -11
  38. package/dist/repos/git-credential.d.ts +12 -5
  39. package/dist/repos/git-credential.js +63 -36
  40. package/dist/repos/github-connect-command.d.ts +35 -0
  41. package/dist/repos/github-connect-command.js +250 -0
  42. package/dist/repos/github-init-command.d.ts +5 -0
  43. package/dist/repos/github-init-command.js +106 -0
  44. package/dist/repos/github-init.d.ts +133 -0
  45. package/dist/repos/github-init.js +265 -0
  46. package/dist/scaffold-guidance.d.ts +10 -2
  47. package/dist/scaffold-guidance.js +27 -2
  48. package/dist/templates/guidance/AGENTS.md +15 -8
  49. package/package.json +7 -7
  50. package/release-summary.json +2 -1
  51. package/templates/guidance/AGENTS.md +15 -8
  52. package/dist/pipeline/active-orm-contracts.d.ts +0 -16
  53. package/dist/pipeline/active-orm-contracts.js +0 -36
  54. package/dist/pipeline/repin-orm.d.ts +0 -2
  55. package/dist/pipeline/repin-orm.js +0 -207
@@ -12,9 +12,11 @@ import { REPOS_USAGE } from '../command-help.js';
12
12
  * so commands resolve the path via the namespaces + repos endpoints (the same
13
13
  * dance the Repositories UI does — there is no /repos/by-path endpoint).
14
14
  */
15
+ import { execFile } from 'node:child_process';
15
16
  import { existsSync, readdirSync, rmSync } from 'node:fs';
16
17
  import { homedir } from 'node:os';
17
- import { resolve, sep } from 'node:path';
18
+ import { join, resolve, sep } from 'node:path';
19
+ import { promisify } from 'node:util';
18
20
  import { materializeRepo, resolveCommitSha, resolveRepo, } from '@sequenceholdings/artifact-studio/git-service-client';
19
21
  import { z } from 'zod';
20
22
  import { parseCiConfigText } from './ci-config.js';
@@ -24,10 +26,12 @@ import { AtlasApiError, deleteNoContent, getJson, getJsonOr404, postJson, } from
24
26
  import { printCliError } from '../cli-errors.js';
25
27
  import { PREVIEW_DOMAIN } from '../preview.js';
26
28
  import { confirmYes } from '../prompt.js';
29
+ import { guideClonedCheckout } from '../scaffold-guidance.js';
27
30
  import { buildContext, clientOptions, flagBool, LOG, } from '../functions/commands.js';
28
31
  import { looksLikeCommitSha, runGitClone, } from './git-clone.js';
29
- import { configureGitLogin } from './git-credential.js';
32
+ import { configureGitLogin, resolveGitHelperLauncher } from './git-credential.js';
30
33
  import { isSandboxTokenMode } from '../sandbox-auth.js';
34
+ const execFileAsync = promisify(execFile);
31
35
  const PAGE_SIZE = 200;
32
36
  // ---------------------------------------------------------------------------
33
37
  // Helpers
@@ -429,24 +433,52 @@ async function gitCloneContext(args) {
429
433
  /**
430
434
  * Clone over smart-HTTP into `destDir` (absent or empty unless `force`) and
431
435
  * bind the checkout's credential helper to this environment and repository.
436
+ * The launcher Git will run is resolved first, so nothing is cloned that could
437
+ * not be wired up; any later failure removes what the clone wrote.
432
438
  */
433
- async function cloneCheckout({ ctx, targetUrl, destDir, force, ref, depth, gitClone, }) {
439
+ async function cloneCheckout({ ctx, targetUrl, destDir, force, ref, depth, gitClone, resolveLauncher, }) {
440
+ const launcher = await (resolveLauncher ?? resolveGitHelperLauncher)();
434
441
  prepareCloneDest({ destDir, force });
435
- await (gitClone ?? runGitClone)({
436
- cloneUrl: targetUrl, destDir, pat: ctx.token,
437
- ...(ref ? { ref } : {}),
438
- ...(depth != null ? { depth } : {}),
439
- });
440
- await configureGitLogin({ destDir, envName: ctx.env.name, cloneUrl: targetUrl });
442
+ const existed = existsSync(destDir);
443
+ try {
444
+ await (gitClone ?? runGitClone)({
445
+ cloneUrl: targetUrl, destDir, pat: ctx.token,
446
+ ...(ref ? { ref } : {}),
447
+ ...(depth != null ? { depth } : {}),
448
+ });
449
+ await configureGitLogin({ destDir, envName: ctx.env.name, cloneUrl: targetUrl, launcher });
450
+ }
451
+ catch (error) {
452
+ rollBackClone({ destDir, existed });
453
+ throw error;
454
+ }
455
+ }
456
+ /** Remove a failed clone: the directory it created, or what it wrote into an empty one. */
457
+ function rollBackClone({ destDir, existed }) {
458
+ try {
459
+ if (!existed) {
460
+ rmSync(destDir, { recursive: true, force: true });
461
+ return;
462
+ }
463
+ for (const entry of readdirSync(destDir))
464
+ rmSync(join(destDir, entry), { recursive: true, force: true });
465
+ }
466
+ catch (cleanupError) {
467
+ console.error(`${LOG} could not remove the partial clone at ${destDir}: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`);
468
+ }
441
469
  }
442
470
  /**
443
471
  * Clone a resolved repository's default branch (shallow, like `repos clone`)
444
472
  * into an absent or empty `destDir`. Returns the origin URL it configured.
445
473
  */
446
- export async function cloneRepoById({ ctx, repoId, destDir, gitClone, }) {
474
+ export async function cloneRepoById({ ctx, repoId, destDir, gitClone, resolveLauncher, }) {
447
475
  assertGitCheckoutAuth(ctx);
448
476
  const targetUrl = normalizeCloneUrl(cloneUrl(ctx, repoId), ctx.env);
449
- await cloneCheckout({ ctx, targetUrl, destDir, force: false, depth: smartHttpCloneDepth({ full: false }), ...(gitClone ? { gitClone } : {}) });
477
+ await cloneCheckout({
478
+ ctx, targetUrl, destDir, force: false, depth: smartHttpCloneDepth({ full: false }),
479
+ ...(gitClone ? { gitClone } : {}),
480
+ ...(resolveLauncher ? { resolveLauncher } : {}),
481
+ });
450
482
  return targetUrl;
451
483
  }
452
484
  /** Git clone always uses the selected human login, never an ambient PAT. */
@@ -485,6 +517,7 @@ export async function reposCloneCommand(args, deps = {}) {
485
517
  ...(ref ? { ref } : {}),
486
518
  ...(depth != null ? { depth } : {}),
487
519
  ...(deps.gitClone ? { gitClone: deps.gitClone } : {}),
520
+ ...(deps.resolveLauncher ? { resolveLauncher: deps.resolveLauncher } : {}),
488
521
  });
489
522
  console.log(`${LOG} cloned ${positional ?? targetUrl} → ${destDir}` +
490
523
  (ref ? ` (ref ${ref})` : '') +
@@ -493,6 +526,12 @@ export async function reposCloneCommand(args, deps = {}) {
493
526
  // The sandbox's token file is rewritten before every tool call; there is no login.
494
527
  ? `${LOG} git pull/push now use this agent sandbox's Atlas credential, which renews on every tool call.`
495
528
  : `${LOG} git pull/push now use your seq-studio login. After expiry: seq-studio login --env ${env.name}`);
529
+ try {
530
+ console.log(`${LOG} ${await guideClonedCheckout({ directory: destDir, envName: env.name })}`);
531
+ }
532
+ catch (error) {
533
+ console.error(`${LOG} could not add agent guidance: ${error instanceof Error ? error.message : String(error)}`);
534
+ }
496
535
  return 0;
497
536
  }
498
537
  /**
@@ -533,6 +572,32 @@ export function normalizeCloneUrl(raw, env) {
533
572
  }
534
573
  return url.toString().replace(/\/$/, '');
535
574
  }
575
+ async function gitOutput(cwd, args) {
576
+ return (await execFileAsync('git', ['-C', cwd, ...args])).stdout.trim();
577
+ }
578
+ /**
579
+ * Bind the credential helper to an existing checkout of a git-service
580
+ * repository: one cloned by plain `git clone`, by an older CLI whose clone
581
+ * stopped before configuring login, or whose launcher moved in an upgrade.
582
+ */
583
+ export async function reposAttachLoginCommand(args, deps = {}) {
584
+ const dir = resolve(args.positional[0] ?? '.');
585
+ const remote = stringFlag(args.flags, 'remote') ?? 'origin';
586
+ let root;
587
+ let remoteUrl;
588
+ try {
589
+ root = await gitOutput(dir, ['rev-parse', '--show-toplevel']);
590
+ remoteUrl = await gitOutput(root, ['remote', 'get-url', remote]);
591
+ }
592
+ catch {
593
+ throw new Error(`${dir} is not a Git checkout with a '${remote}' remote. Pass the checkout directory and --remote <name>.`);
594
+ }
595
+ const ctx = await gitCloneContext(args);
596
+ const cloneUrl = normalizeCloneUrl(remoteUrl, ctx.env);
597
+ await configureGitLogin({ destDir: root, envName: ctx.env.name, cloneUrl, launcher: await (deps.resolveLauncher ?? resolveGitHelperLauncher)() });
598
+ console.log(`${LOG} ${root}: git pull/push to ${cloneUrl} now use your seq-studio login for ${ctx.env.name}.`);
599
+ return 0;
600
+ }
536
601
  function defaultOutFromCloneTarget({ url, id, }) {
537
602
  if (id)
538
603
  return id;
@@ -870,6 +935,8 @@ export async function runReposCommand(sub, args) {
870
935
  return await reposCreateCommand(args);
871
936
  case 'clone':
872
937
  return await reposCloneCommand(args);
938
+ case 'attach-login':
939
+ return await reposAttachLoginCommand(args);
873
940
  case 'pull':
874
941
  return await reposPullCommand(args);
875
942
  case 'delete':
@@ -7,17 +7,24 @@ export declare function gitCredentialResponse({ input, operation, envName, clone
7
7
  envName?: string;
8
8
  cloneUrl?: string;
9
9
  }): Promise<string>;
10
- /** Select the stable launcher that invoked this CLI, not the first one on a later Git PATH. */
11
- export declare function resolveGitHelperLauncher({ scriptPath, launcherHint, searchPath, }?: {
10
+ /**
11
+ * The command Git runs to reach this CLI, as argv. Prefers a stable installed
12
+ * launcher (SEQ_STUDIO_LAUNCHER, the invocation path, or one on PATH) that runs
13
+ * this exact build, so a later PATH change cannot make Git run a different
14
+ * CLI. Without one (`node …/dist/bin.js`), it pins this node and script;
15
+ * `repos attach-login` re-binds a checkout after an upgrade moves either.
16
+ */
17
+ export declare function resolveGitHelperLauncher({ scriptPath, launcherHint, searchPath, nodePath, }?: {
12
18
  scriptPath?: string;
13
19
  launcherHint?: string;
14
20
  searchPath?: string;
15
- }): Promise<string>;
21
+ nodePath?: string;
22
+ }): Promise<string[]>;
16
23
  /** Store only a helper command, bound to this environment and repository URL. */
17
- export declare function configureGitLogin({ destDir, envName, cloneUrl, launcherPath, }: {
24
+ export declare function configureGitLogin({ destDir, envName, cloneUrl, launcher, }: {
18
25
  destDir: string;
19
26
  envName: string;
20
27
  cloneUrl: string;
21
- launcherPath?: string;
28
+ launcher?: readonly string[];
22
29
  }): Promise<void>;
23
30
  export declare function gitCredentialCommand(args: ParsedArgs): Promise<number>;
@@ -2,7 +2,7 @@ import { execFile } from 'node:child_process';
2
2
  import { readFile, realpath } from 'node:fs/promises';
3
3
  import { basename, delimiter, dirname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { promisify } from 'node:util';
5
- import { getAccessTokenWithMode } from '../auth.js';
5
+ import { DevboxOwnerTokenMissingError, getAccessTokenWithMode, NotLoggedInError } from '../auth.js';
6
6
  import { resolveConfiguredEnv } from '../config.js';
7
7
  import { isSandboxOrigin, readSandboxToken, sandboxTarget } from '../sandbox-auth.js';
8
8
  const exec = promisify(execFile);
@@ -89,15 +89,35 @@ export async function gitCredentialResponse({ input, operation, envName, cloneUr
89
89
  if (url.protocol !== 'https:' && !(url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname))) {
90
90
  throw new Error('Git login credentials require HTTPS (except local loopback).');
91
91
  }
92
+ let auth;
92
93
  try {
93
- const auth = await getAccessTokenWithMode({ env: env.name, targetUrl: env.url, allowInteractiveLogin: false });
94
- if (auth.authMode !== 'user' || !auth.token || /[\r\n\0]/.test(auth.token))
95
- throw new Error('User login required');
96
- return `username=git\npassword=${auth.token}\n\n`;
94
+ auth = await getAccessTokenWithMode({ env: env.name, targetUrl: env.url, allowInteractiveLogin: false });
97
95
  }
98
- catch {
99
- throw new Error(`Git login unavailable. Run seq-studio login --env ${envName}, then retry. Machine identities cannot authenticate Git; use supported JSON source workflows.`);
96
+ catch (error) {
97
+ throw new Error(gitLoginUnavailableMessage({ envName, error }));
98
+ }
99
+ if (auth.authMode !== 'user' || !auth.token || /[\r\n\0]/.test(auth.token)) {
100
+ throw new Error(`Git needs a person's login for ${envName}, and only a machine identity is available. Machine identities cannot authenticate Git; use supported JSON source workflows (seq-studio repos pull).`);
101
+ }
102
+ return `username=git\npassword=${auth.token}\n\n`;
103
+ }
104
+ /**
105
+ * Git prints this to whoever ran it, often an agent. There is no refresh
106
+ * token by design, so a login ends after about 12 hours; say so, and say who
107
+ * can renew it, rather than leaving an agent to retry. Other failures keep
108
+ * their detail out of Git's output.
109
+ */
110
+ function gitLoginUnavailableMessage({ envName, error }) {
111
+ if (error instanceof DevboxOwnerTokenMissingError)
112
+ return `Git login unavailable. ${error.message}`;
113
+ const renew = `A person must renew it: run \`seq-studio login --env ${envName}\` in a terminal with a browser, then retry the git command. ` +
114
+ 'An agent cannot complete a browser login; retrying git will not help until then. ' +
115
+ `Check with \`seq-studio auth whoami -e ${envName}\`.`;
116
+ if (error instanceof NotLoggedInError) {
117
+ const expired = error.message.includes('expired');
118
+ return `Git login unavailable: ${expired ? `your seq-studio login for ${envName} has expired (logins last about 12 hours and are not refreshed)` : `there is no seq-studio login for ${envName}`}. ${renew}`;
100
119
  }
120
+ return `Git login unavailable for ${envName}. ${renew}`;
101
121
  }
102
122
  function shellQuote(value) {
103
123
  return `'${value.replace(/'/g, "'\\''")}'`;
@@ -114,43 +134,50 @@ async function shimRunsScript(candidate, script, target) {
114
134
  }
115
135
  return false;
116
136
  }
117
- /** Select the stable launcher that invoked this CLI, not the first one on a later Git PATH. */
118
- export async function resolveGitHelperLauncher({ scriptPath = process.argv[1], launcherHint = process.env.SEQ_STUDIO_LAUNCHER, searchPath = process.env.PATH, } = {}) {
137
+ /** Whether `candidate` runs exactly `script`: a link to it, or a generated shim that execs it. */
138
+ async function launchesScript(candidate, script, target) {
139
+ try {
140
+ if (await realpath(candidate) === target)
141
+ return true;
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ try {
147
+ return await shimRunsScript(candidate, script, target);
148
+ }
149
+ catch {
150
+ return false;
151
+ }
152
+ }
153
+ /**
154
+ * The command Git runs to reach this CLI, as argv. Prefers a stable installed
155
+ * launcher (SEQ_STUDIO_LAUNCHER, the invocation path, or one on PATH) that runs
156
+ * this exact build, so a later PATH change cannot make Git run a different
157
+ * CLI. Without one (`node …/dist/bin.js`), it pins this node and script;
158
+ * `repos attach-login` re-binds a checkout after an upgrade moves either.
159
+ */
160
+ export async function resolveGitHelperLauncher({ scriptPath = process.argv[1], launcherHint = process.env.SEQ_STUDIO_LAUNCHER, searchPath = process.env.PATH, nodePath = process.execPath, } = {}) {
119
161
  if (!scriptPath || !isAbsolute(scriptPath))
120
162
  throw new Error('Cannot identify the seq-studio launcher. Run repos clone through an installed seq-studio command.');
121
163
  const script = resolve(scriptPath);
122
- if (launcherHint && isAbsolute(launcherHint) && basename(launcherHint) === 'seq-studio') {
123
- try {
124
- // Our installed shell shim exports its own path before execing this build.
125
- // Require the shim to target this exact script, so an inherited hint from
126
- // another installation cannot make Git run a different CLI.
127
- if ((await readFile(launcherHint, 'utf8')).includes(`exec node "${script}" "$@"`))
128
- return resolve(launcherHint);
129
- }
130
- catch { /* Stale or unrelated launcher; look for a matching executable. */ }
131
- }
132
- if (basename(script) === 'seq-studio')
133
- return script; // Node preserves the symlink invocation path.
134
164
  const target = await realpath(script);
165
+ // An inherited hint from another installation is ignored unless it runs this build.
166
+ if (launcherHint && isAbsolute(launcherHint) && await launchesScript(launcherHint, script, target))
167
+ return [resolve(launcherHint)];
168
+ if (basename(script) === 'seq-studio')
169
+ return [script]; // Node preserves the symlink invocation path.
135
170
  for (const directory of (searchPath ?? '').split(delimiter).filter(Boolean)) {
136
171
  const candidate = join(directory, 'seq-studio');
137
- try {
138
- if (await realpath(candidate) === target)
139
- return resolve(candidate);
140
- }
141
- catch { /* Not an installed launcher in this PATH entry. */ }
142
- try {
143
- if (await shimRunsScript(candidate, script, target))
144
- return resolve(candidate);
145
- }
146
- catch { /* Not a matching generated shim. */ }
147
- }
148
- throw new Error('Cannot identify a stable seq-studio launcher for Git. Install this CLI with install-cli.sh or invoke its installed executable, then clone again.');
172
+ if (await launchesScript(candidate, script, target))
173
+ return [resolve(candidate)];
174
+ }
175
+ return [nodePath, script];
149
176
  }
150
177
  /** Store only a helper command, bound to this environment and repository URL. */
151
- export async function configureGitLogin({ destDir, envName, cloneUrl, launcherPath, }) {
152
- const launcher = launcherPath ?? await resolveGitHelperLauncher();
153
- const helper = `!${shellQuote(launcher)} auth git-credential --env ${shellQuote(envName)} --url ${shellQuote(cloneUrl)}`;
178
+ export async function configureGitLogin({ destDir, envName, cloneUrl, launcher, }) {
179
+ const command = launcher ?? await resolveGitHelperLauncher();
180
+ const helper = `!${command.map(shellQuote).join(' ')} auth git-credential --env ${shellQuote(envName)} --url ${shellQuote(cloneUrl)}`;
154
181
  const config = async (...args) => { await exec('git', ['-C', destDir, 'config', '--local', ...args]); };
155
182
  // An empty helper resets inherited credential stores for this URL. That keeps
156
183
  // an Auth0 access token out of the user's global store/keychain on approval.
@@ -0,0 +1,35 @@
1
+ import type { ParsedArgs } from '../argv.js';
2
+ export declare const REPO_CONNECT_USAGE = "usage:\n seq-studio repo connect -e <env> --stage staging|prod [--adopt <namespace/repo>:<branch>] [--dir <checkout>] [--json]\n seq-studio repo disconnect -e <env> [--dir <checkout>] [--yes]\n seq-studio repo status -e <env> [--stage staging|prod] [--limit <n>] [--dir <checkout>] [--json]\n seq-studio repo bind -e <env> --stage staging|prod [--dry-run] [--dir <checkout>] [--json]\n\n connect: let this GitHub repository deploy to one stage of an Atlas. The dev branch deploys to staging and the\n release branch to prod (from .seq/github.yml); the Atlas's branch policy pins the images of the repository's\n seq-ci release. --adopt moves a git-service branch's deployments here: its bindings and the resources it controls,\n and it drops to checks-only. release group (Sequence Staff) only; --adopt also needs merge rights on the git-service repository.\n\n disconnect: stop all GitHub deploys of this repository to the Atlas, including queued and retried ones.\n\n status: this repository's releases on the Atlas, newest first, with each target's deployment state.\n\n bind: for a repository whose resources were deployed by hand before it deployed from CI, bind each target to the\n one existing, ready resource of exactly its name that you may deploy, and make the branch its controller. Run it\n after connect and before the first deploy, or every existing resource plans as a new create. Only targets the\n stage's plan deploys are bound: one scoped to other stages (its own or its Application's stages in\n .seq/repository.yml) is skipped and reported. --dry-run previews.\n\n Managed Pipelines are released under the name in .seq/github.yml's release_repository (seq-studio repo init\n --release-repository apps/platform-billing). If a git-service repository of that name exists on the Atlas, they\n keep releasing under it (you need its identity receipt and merge rights); otherwise connect claims the name for\n this repository, and no other repository can use it there.\n\n Uses gh (authenticated) to read the repository id and seq-ci's pinned images.";
3
+ /** The candidate and Next.js images a seq-ci release pins, read from its pipeline workflow. */
4
+ export declare function seqCiImages({ workflowText, release }: {
5
+ workflowText: string;
6
+ release: string;
7
+ }): {
8
+ image: string;
9
+ nextImage: string;
10
+ };
11
+ /**
12
+ * The staging Atlas a seq-ci release's pipeline names for `org` (its `SEQ_CI_ATLAS_ORIGINS`): where a prod deploy reads
13
+ * promoted builds from. The prod Atlas records it on the release branch's policy and contacts only that origin.
14
+ */
15
+ export declare function seqCiStagingOrigin({ workflowText, org }: {
16
+ workflowText: string;
17
+ org: string;
18
+ }): string;
19
+ /** `--adopt namespace/repo:branch`. */
20
+ export declare function parseAdopt(value: string): {
21
+ namespace: string;
22
+ name: string;
23
+ branch: string;
24
+ };
25
+ /** A preflight refusal arrives as JSON naming each denied operation; anything else is already prose. */
26
+ export declare function readableReason(reason: string): string;
27
+ interface TreeEntry {
28
+ path: string;
29
+ mode: string;
30
+ sha: string;
31
+ }
32
+ /** The committed tree at HEAD: what CI deploys, never uncommitted edits. */
33
+ export declare function parseLsTree(output: string): TreeEntry[];
34
+ export declare function runRepoConnectCommand(sub: 'connect' | 'disconnect' | 'status' | 'bind', args: ParsedArgs): Promise<number>;
35
+ export {};
@@ -0,0 +1,250 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { resolveRepo } from '@sequenceholdings/artifact-studio/git-service-client';
3
+ import { load as yamlLoad } from 'js-yaml';
4
+ import { deleteJson, getJson, postJson } from '../atlas-client.js';
5
+ import { confirmYes } from '../prompt.js';
6
+ import { buildContext, clientOptions } from '../functions/commands.js';
7
+ import { githubRepositoryFromRemote } from './github-init-command.js';
8
+ import { resolveSettings, SEQ_CI_REPOSITORY } from './github-init.js';
9
+ export const REPO_CONNECT_USAGE = `usage:
10
+ seq-studio repo connect -e <env> --stage staging|prod [--adopt <namespace/repo>:<branch>] [--dir <checkout>] [--json]
11
+ seq-studio repo disconnect -e <env> [--dir <checkout>] [--yes]
12
+ seq-studio repo status -e <env> [--stage staging|prod] [--limit <n>] [--dir <checkout>] [--json]
13
+ seq-studio repo bind -e <env> --stage staging|prod [--dry-run] [--dir <checkout>] [--json]
14
+
15
+ connect: let this GitHub repository deploy to one stage of an Atlas. The dev branch deploys to staging and the
16
+ release branch to prod (from .seq/github.yml); the Atlas's branch policy pins the images of the repository's
17
+ seq-ci release. --adopt moves a git-service branch's deployments here: its bindings and the resources it controls,
18
+ and it drops to checks-only. release group (Sequence Staff) only; --adopt also needs merge rights on the git-service repository.
19
+
20
+ disconnect: stop all GitHub deploys of this repository to the Atlas, including queued and retried ones.
21
+
22
+ status: this repository's releases on the Atlas, newest first, with each target's deployment state.
23
+
24
+ bind: for a repository whose resources were deployed by hand before it deployed from CI, bind each target to the
25
+ one existing, ready resource of exactly its name that you may deploy, and make the branch its controller. Run it
26
+ after connect and before the first deploy, or every existing resource plans as a new create. Only targets the
27
+ stage's plan deploys are bound: one scoped to other stages (its own or its Application's stages in
28
+ .seq/repository.yml) is skipped and reported. --dry-run previews.
29
+
30
+ Managed Pipelines are released under the name in .seq/github.yml's release_repository (seq-studio repo init
31
+ --release-repository apps/platform-billing). If a git-service repository of that name exists on the Atlas, they
32
+ keep releasing under it (you need its identity receipt and merge rights); otherwise connect claims the name for
33
+ this repository, and no other repository can use it there.
34
+
35
+ Uses gh (authenticated) to read the repository id and seq-ci's pinned images.`;
36
+ const ZERO_DIGEST = /@sha256:0{64}$/;
37
+ function flag(args, name) {
38
+ const value = args.flags[name];
39
+ return typeof value === 'string' ? value : undefined;
40
+ }
41
+ function gh(args) {
42
+ const result = spawnSync('gh', args, { encoding: 'utf8' });
43
+ if (result.error || result.status !== 0)
44
+ throw new Error(`gh ${args.slice(0, 2).join(' ')} failed: ${(result.stderr || result.error?.message || '').trim() || 'is gh installed and logged in?'}`);
45
+ return result.stdout.trim();
46
+ }
47
+ /** The GitHub repository a checkout's origin names, and its numeric id (stable across renames). */
48
+ function githubRepository({ directory }) {
49
+ const remote = spawnSync('git', ['remote', 'get-url', 'origin'], { cwd: directory, encoding: 'utf8' });
50
+ const repository = remote.status === 0 ? githubRepositoryFromRemote(remote.stdout) : null;
51
+ if (!repository)
52
+ throw new Error('The checkout\'s origin is not a github.com repository');
53
+ const id = gh(['api', `repos/${repository}`, '--jq', '.id']);
54
+ if (!/^[0-9]{1,20}$/.test(id))
55
+ throw new Error(`GitHub returned no id for ${repository}`);
56
+ return { repository, id };
57
+ }
58
+ /** The candidate and Next.js images a seq-ci release pins, read from its pipeline workflow. */
59
+ export function seqCiImages({ workflowText, release }) {
60
+ const workflow = yamlLoad(workflowText);
61
+ const env = workflow && typeof workflow === 'object' ? Reflect.get(workflow, 'env') : undefined;
62
+ const read = (name) => {
63
+ const value = env && typeof env === 'object' ? Reflect.get(env, name) : undefined;
64
+ if (typeof value !== 'string' || !/^[^\s@]+@sha256:[0-9a-f]{64}$/.test(value))
65
+ throw new Error(`seq-ci ${release} does not pin ${name} by digest`);
66
+ if (ZERO_DIGEST.test(value))
67
+ throw new Error(`seq-ci ${release} has no published images yet (${name} is a placeholder)`);
68
+ return value;
69
+ };
70
+ return { image: read('SEQ_CI_CANDIDATE_IMAGE'), nextImage: read('SEQ_CI_NEXT_IMAGE') };
71
+ }
72
+ /**
73
+ * The staging Atlas a seq-ci release's pipeline names for `org` (its `SEQ_CI_ATLAS_ORIGINS`): where a prod deploy reads
74
+ * promoted builds from. The prod Atlas records it on the release branch's policy and contacts only that origin.
75
+ */
76
+ export function seqCiStagingOrigin({ workflowText, org }) {
77
+ const workflow = yamlLoad(workflowText);
78
+ const env = workflow && typeof workflow === 'object' ? Reflect.get(workflow, 'env') : undefined;
79
+ const raw = env && typeof env === 'object' ? Reflect.get(env, 'SEQ_CI_ATLAS_ORIGINS') : undefined;
80
+ let origins;
81
+ try {
82
+ origins = typeof raw === 'string' ? JSON.parse(raw) : undefined;
83
+ }
84
+ catch {
85
+ origins = undefined;
86
+ }
87
+ const forOrg = origins && typeof origins === 'object' ? Reflect.get(origins, org) : undefined;
88
+ const staging = forOrg && typeof forOrg === 'object' ? Reflect.get(forOrg, 'staging') : undefined;
89
+ if (typeof staging !== 'string' || !/^https:\/\/[a-z0-9.-]+$/.test(staging))
90
+ throw new Error(`seq-ci names no staging Atlas for org ${org}; promoted_builds: reuse needs one`);
91
+ return staging;
92
+ }
93
+ function readSeqCiWorkflow({ settings }) {
94
+ const content = gh(['api', `repos/${SEQ_CI_REPOSITORY}/contents/.github/workflows/pipeline.yml?ref=${settings.seq_ci}`, '--jq', '.content']);
95
+ return Buffer.from(content, 'base64').toString('utf8');
96
+ }
97
+ /** `--adopt namespace/repo:branch`. */
98
+ export function parseAdopt(value) {
99
+ const match = /^([^/\s:]+)\/([^/\s:]+):(\S+)$/.exec(value);
100
+ if (!match)
101
+ throw new Error('--adopt takes <namespace>/<repo>:<branch>, e.g. apps/banksouth:staging');
102
+ return { namespace: match[1], name: match[2], branch: match[3] };
103
+ }
104
+ function stageOf(args) {
105
+ const stage = flag(args, 'stage');
106
+ if (stage !== 'staging' && stage !== 'prod')
107
+ throw new Error('--stage must be staging or prod: the stage this Atlas serves');
108
+ return stage;
109
+ }
110
+ async function connect(args) {
111
+ const directory = flag(args, 'dir') ?? '.';
112
+ const stage = stageOf(args);
113
+ const settings = await resolveSettings({ directory });
114
+ const branch = stage === 'staging' ? settings.branches.dev : settings.branches.release;
115
+ const { repository, id } = githubRepository({ directory });
116
+ const workflowText = readSeqCiWorkflow({ settings });
117
+ const images = seqCiImages({ workflowText, release: settings.seq_ci });
118
+ // Only the release branch reuses promoted builds, from the staging Atlas this seq-ci release deploys the org's dev branch to.
119
+ const promotedBuildsFrom = stage === 'prod' && settings.promoted_builds === 'reuse' ? seqCiStagingOrigin({ workflowText, org: settings.org }) : undefined;
120
+ const ctx = await buildContext(args);
121
+ const adoptFlag = flag(args, 'adopt');
122
+ const adopt = adoptFlag ? parseAdopt(adoptFlag) : undefined;
123
+ const source = adopt ? await resolveRepo({ ...clientOptions(ctx), namespace: adopt.namespace, name: adopt.name }) : undefined;
124
+ const { connections } = await postJson({ ...clientOptions(ctx), path: '/api/ci/github/connections', body: {
125
+ githubRepositoryId: id, githubRepository: repository, branches: [{ branch, stage }], ...images,
126
+ ...(adopt && source ? { adopt: { repoId: source.id, branch: adopt.branch, githubBranch: branch } } : {}),
127
+ ...(settings.release_repository ? { releaseRepository: settings.release_repository } : {}),
128
+ // Only the dev branch's deploys reuse pull-request builds; Atlas ignores it for prod.
129
+ ...(stage === 'staging' ? { pullRequestBuilds: settings.pull_request_builds ?? 'reuse' } : {}),
130
+ ...(promotedBuildsFrom ? { promotedBuildsFrom } : {})
131
+ } });
132
+ if (args.flags.json === true) {
133
+ process.stdout.write(`${JSON.stringify({ repository, githubRepositoryId: id, connections, ...images }, null, 2)}\n`);
134
+ return 0;
135
+ }
136
+ process.stdout.write(`Connected ${repository} on ${ctx.env.name}: ${branch} deploys to ${stage}, with seq-ci ${settings.seq_ci}'s images.\n`);
137
+ if (stage === 'staging')
138
+ process.stdout.write(settings.pull_request_builds === 'rebuild' ? 'Every deploy builds and checks each target it deploys.\n'
139
+ : `Deploys reuse what a pull request's CI built and checked from the change it merged. ${branch} must require no approvals; once it does, set pull_request_builds: rebuild in .seq/github.yml and reconnect.\n`);
140
+ if (stage === 'prod')
141
+ process.stdout.write(promotedBuildsFrom ? `Promoted deploys reuse what ${promotedBuildsFrom} built and runs for the same commit; Next.js apps, managed functions and environment-specific builds still build.\n`
142
+ : 'Every promoted deploy builds and checks each target it deploys (promoted_builds: reuse in .seq/github.yml reuses staging\'s builds).\n');
143
+ if (adopt)
144
+ process.stdout.write(`Adopted ${adopt.namespace}/${adopt.name}:${adopt.branch}: its bindings and resources are ${branch}'s now, and it runs checks only.\n`);
145
+ return 0;
146
+ }
147
+ async function disconnect(args) {
148
+ const { repository, id } = githubRepository({ directory: flag(args, 'dir') ?? '.' });
149
+ const ctx = await buildContext(args);
150
+ if (!await confirmYes({ preview: [`Stop every GitHub deploy of ${repository} to ${ctx.env.name}, including queued and retried ones.`], confirmed: args.flags.yes === true }))
151
+ return 1;
152
+ const { revoked } = await deleteJson({ ...clientOptions(ctx), path: `/api/ci/github/connections?githubRepositoryId=${id}` });
153
+ process.stdout.write(`Disconnected ${repository} from ${ctx.env.name} (${revoked} connection${revoked === 1 ? '' : 's'}).\n`);
154
+ return 0;
155
+ }
156
+ /** A preflight refusal arrives as JSON naming each denied operation; anything else is already prose. */
157
+ export function readableReason(reason) {
158
+ try {
159
+ const parsed = JSON.parse(reason);
160
+ const targets = parsed && typeof parsed === 'object' ? Reflect.get(parsed, 'targets') : undefined;
161
+ const denied = Array.isArray(targets) ? targets.filter((entry) => !!entry && typeof entry === 'object' && Reflect.get(entry, 'decision') !== 'allowed' && typeof Reflect.get(entry, 'reason') === 'string') : [];
162
+ if (denied.length)
163
+ return denied.map((entry) => entry.reason).join('; ');
164
+ }
165
+ catch { /* prose */ }
166
+ return reason;
167
+ }
168
+ async function status(args) {
169
+ const { repository, id } = githubRepository({ directory: flag(args, 'dir') ?? '.' });
170
+ const ctx = await buildContext(args);
171
+ const query = new URLSearchParams({ githubRepositoryId: id, limit: flag(args, 'limit') ?? '10', ...(flag(args, 'stage') ? { stage: stageOf(args) } : {}) });
172
+ const page = await getJson({ ...clientOptions(ctx), path: `/api/ci/github/releases?${query}` });
173
+ if (args.flags.json === true) {
174
+ process.stdout.write(`${JSON.stringify(page, null, 2)}\n`);
175
+ return 0;
176
+ }
177
+ if (!page.releases.length) {
178
+ process.stdout.write(`${repository} has no releases on ${ctx.env.name} yet.\n`);
179
+ return 0;
180
+ }
181
+ for (const release of page.releases) {
182
+ process.stdout.write(`${release.createdAt} ${release.stage.padEnd(7)} ${release.commitSha.slice(0, 7)} ${release.applicationId} ${release.state}${release.source === 'break-glass' ? ' (break-glass)' : ''}\n`);
183
+ for (const target of release.targets)
184
+ process.stdout.write(` ${target.state.padEnd(10)} ${target.key}${target.reason ? ` ${readableReason(target.reason)}` : ''}\n`);
185
+ if (release.error)
186
+ process.stdout.write(` error: ${release.error}\n`);
187
+ }
188
+ return 0;
189
+ }
190
+ /** The committed tree at HEAD: what CI deploys, never uncommitted edits. */
191
+ export function parseLsTree(output) {
192
+ return output.split('\0').filter(Boolean).map((line) => {
193
+ const match = /^(\d{6}) (blob|commit) ([0-9a-f]{40})\t(.+)$/s.exec(line);
194
+ if (!match)
195
+ throw new Error(`Unexpected git ls-tree line: ${line.slice(0, 80)}`);
196
+ return { mode: match[1], sha: match[3], path: match[4] };
197
+ });
198
+ }
199
+ function git(directory, args) {
200
+ const result = spawnSync('git', args, { cwd: directory, maxBuffer: 512 * 1024 * 1024 });
201
+ if (result.status !== 0)
202
+ throw new Error(`git ${args[0]} failed: ${result.stderr.toString().trim()}`);
203
+ return result.stdout;
204
+ }
205
+ async function bind(args) {
206
+ const directory = flag(args, 'dir') ?? '.';
207
+ const stage = stageOf(args);
208
+ const { id } = githubRepository({ directory });
209
+ const headSha = git(directory, ['rev-parse', 'HEAD']).toString().trim();
210
+ const headEntries = parseLsTree(git(directory, ['ls-tree', '-r', '-z', '--full-tree', headSha]).toString('utf8'));
211
+ const ctx = await buildContext(args);
212
+ const body = { githubRepositoryId: id, stage, headSha, headEntries, dryRun: args.flags['dry-run'] === true };
213
+ // Atlas names the planner files it reads; only their bytes are sent.
214
+ let result = await postJson({ ...clientOptions(ctx), path: '/api/ci/github/bindings', body });
215
+ if ('needContent' in result) {
216
+ const content = Object.fromEntries(result.needContent.map((oid) => [oid, git(directory, ['cat-file', 'blob', oid]).toString('base64')]));
217
+ result = await postJson({ ...clientOptions(ctx), path: '/api/ci/github/bindings', body: { ...body, content } });
218
+ }
219
+ if ('needContent' in result)
220
+ throw new Error('Atlas still lacks planner files after they were sent');
221
+ if (args.flags.json === true) {
222
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
223
+ return 0;
224
+ }
225
+ const verb = result.saved ? 'Bound' : 'Would bind';
226
+ for (const entry of result.bound)
227
+ process.stdout.write(`${verb.padEnd(11)} ${entry.key} -> ${entry.name}\n`);
228
+ for (const key of result.alreadyBound)
229
+ process.stdout.write(`${'Bound'.padEnd(11)} ${key} (already)\n`);
230
+ for (const entry of result.ambiguous)
231
+ process.stdout.write(`${'Ambiguous'.padEnd(11)} ${entry.key}: ${entry.names.join(', ')}; bind it in Atlas Settings\n`);
232
+ for (const key of result.notFound)
233
+ process.stdout.write(`${'New'.padEnd(11)} ${key} (no existing resource; the first deploy creates it)\n`);
234
+ for (const entry of result.skipped ?? [])
235
+ process.stdout.write(`${'Skipped'.padEnd(11)} ${entry.key} (stages: ${entry.stages.join(', ')})\n`);
236
+ return 0;
237
+ }
238
+ export async function runRepoConnectCommand(sub, args) {
239
+ if (args.flags.help) {
240
+ process.stdout.write(`${REPO_CONNECT_USAGE}\n`);
241
+ return 0;
242
+ }
243
+ if (sub === 'connect')
244
+ return connect(args);
245
+ if (sub === 'disconnect')
246
+ return disconnect(args);
247
+ if (sub === 'bind')
248
+ return bind(args);
249
+ return status(args);
250
+ }
@@ -0,0 +1,5 @@
1
+ import type { ParsedArgs } from '../argv.js';
2
+ export declare const REPO_INIT_USAGE = "usage:\n seq-studio repo init [--org <org>] [--dev <branch>] [--release <branch>] [--seq-ci <vX.Y.Z>] [--release-repository <namespace/name>]\n [--pull-request-builds reuse|rebuild] [--dir <checkout>] [--apply-github] [--json]\n seq-studio repo init --check [--dir <checkout>] [--json]\n\n Make a GitHub checkout a Sequence repository: .seq/github.yml (org and branches), the seq and seq promote\n workflows, Renovate config, and an agent skill pointing at the platform docs. Writes only what's missing or\n stale, and never overwrites a file it doesn't manage. --check reports the same and writes nothing (exit 3 when\n anything is missing or stale).\n\n Branch rulesets and secret scanning need admin rights on the repository (not the org): --apply-github runs them\n with gh and confirms the repository can read seq-ci's org secrets; without it, the gh commands are printed for an\n admin. Commit and push the written files yourself.\n\n --pull-request-builds (default reuse): whether the dev branch's deploys reuse what a pull request's CI built and\n checked from the change it merged. Sound only while the dev branch needs no approvals, as these rulesets set it;\n once reviews are required, use rebuild. repo connect --stage staging records it on the Atlas.";
3
+ /** `org/name` from a github.com origin, or null when the origin is elsewhere. */
4
+ export declare function githubRepositoryFromRemote(url: string): string | null;
5
+ export declare function runRepoInitCommand(args: ParsedArgs): Promise<number>;