@sequenceholdings/studio-cli 0.4.6 → 0.5.1

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 (39) hide show
  1. package/README.md +180 -74
  2. package/dist/app/commands.d.ts +1 -1
  3. package/dist/app/commands.js +28 -3
  4. package/dist/app/readme.js +12 -4
  5. package/dist/app/scaffold.js +1 -1
  6. package/dist/artifact/delegate.js +4 -4
  7. package/dist/auth-cmds/commands.d.ts +1 -13
  8. package/dist/auth-cmds/commands.js +11 -246
  9. package/dist/bin.js +1 -1
  10. package/dist/command-contract.d.ts +14 -8
  11. package/dist/command-contract.js +5 -4
  12. package/dist/command-help.d.ts +2 -2
  13. package/dist/command-help.js +19 -19
  14. package/dist/main.d.ts +3 -2
  15. package/dist/main.js +12 -6
  16. package/dist/pipeline/clone-deploy.d.ts +1 -2
  17. package/dist/pipeline/clone-deploy.js +6 -8
  18. package/dist/pipeline/commands.js +1 -1
  19. package/dist/pipeline/lifecycle.d.ts +3 -1
  20. package/dist/pipeline/lifecycle.js +12 -4
  21. package/dist/repos/ci-config.d.ts +5 -0
  22. package/dist/repos/ci-config.js +29 -0
  23. package/dist/repos/ci-init.d.ts +4 -0
  24. package/dist/repos/ci-init.js +35 -0
  25. package/dist/repos/ci-status.d.ts +9 -0
  26. package/dist/repos/ci-status.js +49 -0
  27. package/dist/repos/commands.d.ts +8 -20
  28. package/dist/repos/commands.js +182 -233
  29. package/dist/repos/git-clone.d.ts +1 -10
  30. package/dist/repos/git-clone.js +1 -49
  31. package/dist/repos/git-credential.d.ts +15 -0
  32. package/dist/repos/git-credential.js +91 -0
  33. package/dist/templates/catalog.d.ts +69 -0
  34. package/dist/templates/catalog.js +68 -0
  35. package/dist/templates/commands.d.ts +29 -0
  36. package/dist/templates/commands.js +443 -0
  37. package/package.json +12 -11
  38. package/dist/pat-hints.d.ts +0 -15
  39. package/dist/pat-hints.js +0 -28
@@ -5,9 +5,8 @@ import { REPOS_USAGE } from '../command-help.js';
5
5
  *
6
6
  * Everything here is API-driven (Auth0 bearer via seq-studio login), matching the
7
7
  * rest of seq-studio. `pull` materializes a tree over the JSON API; `clone`
8
- * prefers a real `git clone` when `ATLAS_GIT_PAT` is set (smart-HTTP URL from
9
- * `show`), otherwise falls back to the same JSON materialize path and hints
10
- * at `seq-studio auth pat create`.
8
+ * uses a real Git checkout and a login credential helper by default.
9
+ * Explicit JSON transport downloads files without a Git checkout.
11
10
  *
12
11
  * Repo addressing is `<namespace>/<name>` everywhere; the API is id-addressed,
13
12
  * so commands resolve the path via the namespaces + repos endpoints (the same
@@ -18,16 +17,16 @@ import { homedir } from 'node:os';
18
17
  import { resolve, sep } from 'node:path';
19
18
  import { materializeRepo, resolveCommitSha, resolveRepo, } from '@sequenceholdings/artifact-studio/git-service-client';
20
19
  import { z } from 'zod';
20
+ import { parseCiConfigText } from './ci-config.js';
21
+ import { initializeRepositoryPipeline } from './ci-init.js';
22
+ import { showRepositoryPrCi } from './ci-status.js';
21
23
  import { AtlasApiError, deleteNoContent, getJson, getJsonOr404, postJson, } from '../atlas-client.js';
22
24
  import { printCliError } from '../cli-errors.js';
23
25
  import { PREVIEW_DOMAIN } from '../preview.js';
24
26
  import { confirmYes } from '../prompt.js';
25
27
  import { buildContext, clientOptions, flagBool, LOG, } from '../functions/commands.js';
26
- import { looksLikeCommitSha, resolveGitPatFromEnv, runGitClone, } from './git-clone.js';
27
- import { formatPatSetupHint } from '../pat-hints.js';
28
- import { tryGetAccessToken } from '../auth.js';
29
- import { resolveConfiguredEnv } from '../config.js';
30
- import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
28
+ import { looksLikeCommitSha, runGitClone, } from './git-clone.js';
29
+ import { configureGitLogin } from './git-credential.js';
31
30
  const PAGE_SIZE = 200;
32
31
  // ---------------------------------------------------------------------------
33
32
  // Helpers
@@ -253,7 +252,7 @@ export async function reposShowCommand(args) {
253
252
  }
254
253
  console.log(` created: ${shortDate(repo.createdAt)} by ${repo.createdBy}`);
255
254
  console.log(` updated: ${shortDate(repo.updatedAt)}`);
256
- console.log(` clone (PAT as basic-auth password): ${cloneUrl(ctx, repo.id)}`);
255
+ console.log(` clone (seq-studio login): ${cloneUrl(ctx, repo.id)}`);
257
256
  // Best-effort cross-link to a matching Artifact Studio project on this env
258
257
  // (same slug as the repo name). Failures are silent — not every repo is an
259
258
  // artifact, and the projects endpoint may 403 for some principals.
@@ -345,166 +344,83 @@ export async function reposPullCommand(args) {
345
344
  verb: 'pulled',
346
345
  });
347
346
  }
348
- /**
349
- * Preferred clone verb.
350
- *
351
- * With `ATLAS_GIT_PAT`:
352
- * - `--url <clone-url>` or `--id <repo-uuid>` → smart-HTTP clone with no seqapi
353
- * - `<ns>/<name>` → needs Auth0 to resolve the UUID, then smart-HTTP clone
354
- * Without a PAT: JSON materialize (needs Auth0) + PAT setup hints.
355
- *
356
- * `gitClone` is injectable for tests.
357
- */
358
- export async function reposCloneCommand(args, deps = {}) {
347
+ function parseCloneOptions(args) {
359
348
  const force = flagBool(args.flags, 'force');
360
- const full = flagBool(args.flags, 'full');
361
349
  const ref = stringFlag(args.flags, 'ref');
362
- const depth = smartHttpCloneDepth({ ref, full });
350
+ const depth = smartHttpCloneDepth({ ref, full: flagBool(args.flags, 'full') });
363
351
  const outputFlag = stringFlag(args.flags, 'output');
364
352
  const outFlag = stringFlag(args.flags, 'out');
365
- if (outputFlag !== undefined && outFlag !== undefined) {
353
+ if (outputFlag !== undefined && outFlag !== undefined)
366
354
  throw new Error('Pass only one of --output or --out.');
367
- }
368
355
  const output = outputFlag ?? outFlag;
369
- const pat = resolveGitPatFromEnv();
370
- const transportFlag = stringFlag(args.flags, 'transport') ?? 'auto';
371
- if (!['auto', 'git', 'json'].includes(transportFlag)) {
372
- throw new Error('--transport must be one of: auto, git, json.');
373
- }
374
- const transport = transportFlag;
375
356
  const urlFlag = stringFlag(args.flags, 'url');
376
357
  const idFlag = stringFlag(args.flags, 'id');
377
358
  const positional = args.positional[0];
378
- if (urlFlag && idFlag) {
359
+ if (urlFlag && idFlag)
379
360
  throw new Error('Pass only one of --url or --id.');
380
- }
381
- if ((urlFlag || idFlag) && positional) {
361
+ if ((urlFlag || idFlag) && positional)
382
362
  throw new Error('Pass either <ns>/<name> or --url/--id, not both.');
363
+ const transport = stringFlag(args.flags, 'transport') ?? 'auto';
364
+ if (!['auto', 'git', 'json'].includes(transport))
365
+ throw new Error('--transport must be one of: auto, git, json.');
366
+ if (transport === 'json' && !positional)
367
+ throw new Error('--transport json requires <namespace>/<name>.');
368
+ return { force, ref, depth, output, urlFlag, idFlag, positional, transport };
369
+ }
370
+ async function gitCloneContext(args) {
371
+ const ctx = await reposContext(args);
372
+ if (ctx.authMode === 'm2m') {
373
+ throw new Error(`Git clone requires a user login: seq-studio login --env ${ctx.env.name}. Use repos pull for M2M JSON materialization.`);
383
374
  }
384
- // --url/--id are PAT-only (no JSON materialize for a bare UUID/URL).
385
- if ((urlFlag || idFlag) && (!pat || transport === 'json')) {
386
- const env = await resolveEnvOnly(args);
387
- const lines = [
388
- `${LOG} --url/--id requires ATLAS_GIT_PAT and Git transport (JSON materialize needs <ns>/<name>).`,
389
- ...formatPatSetupHint({ envUrl: env.url, envName: env.name }),
390
- ];
391
- throw new Error(lines.join('\n'));
392
- }
393
- if (transport === 'git' && !pat) {
394
- const env = await resolveEnvOnly(args);
395
- throw new Error([
396
- `${LOG} --transport git requires ATLAS_GIT_PAT with repo:read access for ${env.name}.`,
397
- ...formatPatSetupHint({ envUrl: env.url, envName: env.name }),
398
- ].join('\n'));
399
- }
400
- // PAT-only path: clone by URL or repo UUID without seqapi/Auth0.
401
- if (pat && (urlFlag || idFlag)) {
402
- const env = await resolveEnvOnly(args);
403
- const targetUrl = urlFlag
404
- ? normalizeCloneUrl(urlFlag, env)
405
- : cloneUrl({ env, token: '' }, idFlag);
406
- const destDir = resolve(output ?? defaultOutFromCloneTarget({ url: targetUrl, id: idFlag }));
407
- prepareCloneDest({ destDir, force });
408
- const clone = deps.gitClone ?? runGitClone;
409
- await clone({
410
- cloneUrl: targetUrl,
411
- destDir,
412
- pat,
413
- ...(ref ? { ref } : {}),
414
- ...(depth != null ? { depth } : {}),
415
- }).catch((error) => {
416
- throw withGitAuthHint({ error, envName: env.name });
417
- });
418
- console.log(`${LOG} cloned ${targetUrl} → ${destDir}` +
419
- (ref ? ` (ref ${ref})` : '') +
420
- ` via smart-HTTP${depth != null ? ` (depth ${depth})` : ''}`);
421
- return 0;
422
- }
423
- // <ns>/<name> path — needs Auth0 for resolveRepo (JSON API) whether or not
424
- // we then use smart-HTTP. Without Auth0, point users at --url from the UI.
425
- if (!positional) {
375
+ return ctx;
376
+ }
377
+ /** Git clone always uses the selected human login, never an ambient PAT. */
378
+ export async function reposCloneCommand(args, deps = {}) {
379
+ const { force, ref, depth, output, urlFlag, idFlag, positional, transport } = parseCloneOptions(args);
380
+ if (!positional && !urlFlag && !idFlag) {
426
381
  console.error('usage: seq-studio repos clone <ns>/<name> | --url <clone-url> | --id <uuid> -e <env> [--ref r] [--output dir] [--full]');
427
382
  return 1;
428
383
  }
429
- const { namespace, name } = parseRepoPath(positional);
430
- const token = await tryGetAccessToken();
431
- if (!token) {
432
- const env = await resolveEnvOnly(args);
433
- const lines = pat
434
- ? [
435
- `ATLAS_GIT_PAT is set, but resolving ${namespace}/${name} needs Auth0 (` +
436
- `seq-studio login).`,
437
- ` Or copy the clone URL from Repositories → Clone, then:`,
438
- ` ATLAS_GIT_PAT=<token> seq-studio repos clone --url <https://…/repos/<id>/git> -e ${env.name}`,
439
- ]
440
- : [
441
- `${LOG} no ATLAS_GIT_PAT and not logged in.`,
442
- ...formatPatSetupHint({ envUrl: env.url, envName: env.name }),
443
- ` Then: seq-studio repos clone ${namespace}/${name} -e ${env.name}`,
444
- ];
445
- throw new Error(lines.join('\n'));
446
- }
447
- const ctx = await reposContext(args);
448
- const destDir = resolve(output ?? name);
449
- if (pat && transport !== 'json') {
450
- prepareCloneDest({ destDir, force });
384
+ if (transport === 'json') {
385
+ const { namespace, name } = parseRepoPath(positional);
386
+ const ctx = await reposContext(args);
387
+ const destDir = resolve(output ?? name);
388
+ assertDestWritable({ destDir, force });
389
+ console.log(`${LOG} materializing via JSON API as the signed-in Atlas identity (no .git dir; ignoring ATLAS_GIT_PAT).`);
390
+ return materializeTree({ ctx, namespace, name, destDir, ref, verb: 'cloned' });
391
+ }
392
+ const ctx = await gitCloneContext(args);
393
+ const env = ctx.env;
394
+ let targetUrl;
395
+ let defaultOut;
396
+ if (positional) {
397
+ const { namespace, name } = parseRepoPath(positional);
451
398
  const resolved = await resolveRepo({ ...clientOptions(ctx), namespace, name });
452
- const targetUrl = cloneUrl(ctx, resolved.id);
453
- const clone = deps.gitClone ?? runGitClone;
454
- await clone({
455
- cloneUrl: targetUrl,
456
- destDir,
457
- pat,
458
- ...(ref ? { ref } : {}),
459
- ...(depth != null ? { depth } : {}),
460
- }).catch((error) => {
461
- throw withGitAuthHint({ error, envName: ctx.env.name });
462
- });
463
- console.log(`${LOG} cloned ${namespace}/${name} → ${destDir}` +
464
- (ref ? ` (ref ${ref})` : '') +
465
- ` via smart-HTTP${depth != null ? ` (depth ${depth})` : ''}`);
466
- return 0;
467
- }
468
- assertDestWritable({ destDir, force });
469
- console.log(transport === 'json'
470
- ? `${LOG} materializing via JSON API as the signed-in Atlas identity (no .git dir; ignoring ATLAS_GIT_PAT).`
471
- : `${LOG} no ATLAS_GIT_PAT — materializing via JSON API (no .git dir).`);
472
- for (const line of formatPatSetupHint({ envUrl: ctx.env.url, envName: ctx.env.name })) {
473
- console.log(line);
474
- }
475
- return materializeTree({
476
- ctx,
477
- namespace,
478
- name,
479
- destDir,
480
- ref,
481
- verb: 'cloned',
399
+ targetUrl = cloneUrl(ctx, resolved.id);
400
+ defaultOut = name;
401
+ }
402
+ else {
403
+ targetUrl = urlFlag ?? cloneUrl({ env, token: '' }, idFlag);
404
+ defaultOut = defaultOutFromCloneTarget({ url: targetUrl, id: idFlag });
405
+ }
406
+ targetUrl = normalizeCloneUrl(targetUrl, env);
407
+ const destDir = resolve(output ?? defaultOut);
408
+ prepareCloneDest({ destDir, force });
409
+ await (deps.gitClone ?? runGitClone)({
410
+ cloneUrl: targetUrl, destDir, pat: ctx.token,
411
+ ...(ref ? { ref } : {}),
412
+ ...(depth != null ? { depth } : {}),
482
413
  });
483
- }
484
- function withGitAuthHint({ error, envName }) {
485
- const message = error instanceof Error ? error.message : String(error);
486
- if (!/(authentication failed|could not read username|http\s*(401|403)|returned error:\s*(401|403))/i.test(message)) {
487
- return error instanceof Error ? error : new Error(message);
488
- }
489
- return new Error(`${message}\n${LOG} Git-service rejected ATLAS_GIT_PAT for ${envName}. Check that it is current and has repo:read access for this environment. ` +
490
- `If your signed-in Atlas account can read the repo, retry with --transport json to materialize without using the ambient PAT (this creates no .git directory).`, { cause: error });
491
- }
492
- /** Resolve -e/--env without requiring Auth0 (for PAT-only --url/--id clones). */
493
- async function resolveEnvOnly(args) {
494
- if (args.flags.env === true || args.flags.e === true) {
495
- throw new Error('-e/--env requires a value — see: seq-studio envs list.');
496
- }
497
- const requested = (typeof args.flags.env === 'string' ? args.flags.env : undefined) ??
498
- (typeof args.flags.e === 'string' ? args.flags.e : undefined);
499
- // Same contract as buildContext: never silently fall back to `local`.
500
- if (!requested) {
501
- throw new Error(REQUIRE_EXPLICIT_ENV_MESSAGE);
502
- }
503
- return resolveConfiguredEnv({ requested });
414
+ await configureGitLogin({ destDir, envName: env.name, cloneUrl: targetUrl });
415
+ console.log(`${LOG} cloned ${positional ?? targetUrl} → ${destDir}` +
416
+ (ref ? ` (ref ${ref})` : '') +
417
+ ` via smart-HTTP${depth != null ? ` (depth ${depth})` : ''}`);
418
+ console.log(`${LOG} git pull/push now use your seq-studio login. After expiry: seq-studio login --env ${env.name}`);
419
+ return 0;
504
420
  }
505
421
  /**
506
422
  * Validate clone URL shape and that the origin matches the resolved Atlas env
507
- * so askpass never sends ATLAS_GIT_PAT to an attacker-controlled host.
423
+ * so askpass never sends a login token to an attacker-controlled host.
508
424
  */
509
425
  export function normalizeCloneUrl(raw, env) {
510
426
  let url;
@@ -512,18 +428,19 @@ export function normalizeCloneUrl(raw, env) {
512
428
  url = new URL(raw);
513
429
  }
514
430
  catch {
515
- throw new Error(`--url must be a valid HTTPS clone URL (got "${raw}").`);
431
+ throw new Error('--url must be a valid HTTPS clone URL.');
516
432
  }
517
433
  if (url.protocol !== 'https:' && url.protocol !== 'http:') {
518
434
  throw new Error(`--url must be http(s) (got ${url.protocol}).`);
519
435
  }
520
- // HTTPS everywhere except local (http://localhost:5001).
521
- if (env.name !== 'local' && url.protocol !== 'https:') {
436
+ // Permit HTTP only on loopback, including registered local worktree servers.
437
+ if (url.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)) {
522
438
  throw new Error(`--url must use HTTPS for ${env.name} (got ${url.protocol}).`);
523
439
  }
524
- url.username = '';
525
- url.password = '';
526
- if (!/\/api\/git-service\/repos\/[^/]+\/git\/?$/.test(url.pathname)) {
440
+ if (url.username || url.password || url.search || url.hash) {
441
+ throw new Error('--url must not contain credentials, query parameters, or a fragment.');
442
+ }
443
+ if (!/^\/api\/git-service\/repos\/[\w-]+(?:\/git|\.git)\/?$/.test(url.pathname)) {
527
444
  throw new Error(`--url must look like …/api/git-service/repos/<id>/git (got ${url.pathname}).`);
528
445
  }
529
446
  let expected;
@@ -542,12 +459,12 @@ export function normalizeCloneUrl(raw, env) {
542
459
  function defaultOutFromCloneTarget({ url, id, }) {
543
460
  if (id)
544
461
  return id;
545
- const match = /\/repos\/([^/]+)\/git\/?$/.exec(new URL(url).pathname);
462
+ const match = /\/repos\/([^/]+?)(?:\/git|\.git)\/?$/.exec(new URL(url).pathname);
546
463
  return match?.[1] ?? 'repo';
547
464
  }
548
465
  /**
549
466
  * Mirror of atlas `ci-discover` Zod contract so `repos ci show` fails closed
550
- * on the same invalid `.seq/ci.json` shapes the runner rejects (`ci/config`).
467
+ * on the same invalid `.seq/pipeline.yml` / legacy JSON shapes the runner rejects (`ci/config`).
551
468
  * Keep in sync with `atlas/src/server/services/git-service/ci-discover.ts`.
552
469
  */
553
470
  const CiPhaseSchema = z.enum(['check', 'test']);
@@ -583,45 +500,55 @@ function defaultNameForPhase(phase, indexInPhase) {
583
500
  return `ci/${phase}`;
584
501
  return `ci/${phase}-${indexInPhase + 1}`;
585
502
  }
503
+ function discoverConfiguredCliChecks({ configuration, source }) {
504
+ if (configuration !== null && typeof configuration === 'object' && Reflect.get(configuration, 'schema_version') === 2) {
505
+ return { ok: true, checks: [], native: true };
506
+ }
507
+ const parsed = CiJsonSchema.safeParse(configuration);
508
+ if (!parsed.success) {
509
+ const detail = parsed.error.issues
510
+ .map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`)
511
+ .slice(0, 3)
512
+ .join('; ');
513
+ return { ok: false, error: `Invalid .seq/${source}: ${detail}` };
514
+ }
515
+ const phaseCounts = new Map();
516
+ const seenNames = new Set();
517
+ const checks = [];
518
+ for (const entry of parsed.data.checks) {
519
+ const indexInPhase = phaseCounts.get(entry.phase) ?? 0;
520
+ phaseCounts.set(entry.phase, indexInPhase + 1);
521
+ const name = entry.name ?? defaultNameForPhase(entry.phase, indexInPhase);
522
+ if (seenNames.has(name)) {
523
+ return {
524
+ ok: false,
525
+ error: `Invalid .seq/${source}: duplicate check name "${name}"`,
526
+ };
527
+ }
528
+ seenNames.add(name);
529
+ const check = {
530
+ name,
531
+ source,
532
+ };
533
+ if (entry.script != null)
534
+ check.script = entry.script;
535
+ if (entry.command != null)
536
+ check.command = entry.command;
537
+ checks.push(check);
538
+ }
539
+ return { ok: true, checks };
540
+ }
586
541
  /**
587
542
  * Pure discovery shared by `repos ci show` / `import`. Mirrors atlas
588
543
  * `discoverCiChecks` / `parseCiJson` so CLI preview matches execution.
589
544
  */
590
- export function discoverCliChecks({ ciJson, packageScripts, }) {
591
- if (ciJson !== undefined) {
592
- const parsed = CiJsonSchema.safeParse(ciJson);
593
- if (!parsed.success) {
594
- const detail = parsed.error.issues
595
- .map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`)
596
- .slice(0, 3)
597
- .join('; ');
598
- return { ok: false, error: `Invalid .seq/ci.json: ${detail}` };
599
- }
600
- const phaseCounts = new Map();
601
- const seenNames = new Set();
602
- const checks = [];
603
- for (const entry of parsed.data.checks) {
604
- const indexInPhase = phaseCounts.get(entry.phase) ?? 0;
605
- phaseCounts.set(entry.phase, indexInPhase + 1);
606
- const name = entry.name ?? defaultNameForPhase(entry.phase, indexInPhase);
607
- if (seenNames.has(name)) {
608
- return {
609
- ok: false,
610
- error: `Invalid .seq/ci.json: duplicate check name "${name}"`,
611
- };
612
- }
613
- seenNames.add(name);
614
- const check = {
615
- name,
616
- source: 'ci.json',
617
- };
618
- if (entry.script != null)
619
- check.script = entry.script;
620
- if (entry.command != null)
621
- check.command = entry.command;
622
- checks.push(check);
623
- }
624
- return { ok: true, checks };
545
+ export function discoverCliChecks({ ciYaml, ciJson, packageScripts, }) {
546
+ if (ciYaml !== undefined && ciJson !== undefined)
547
+ return { ok: false, error: 'Both .seq/pipeline.yml and .seq/ci.json exist; remove one to make CI configuration unambiguous' };
548
+ if (ciYaml !== undefined || ciJson !== undefined) {
549
+ const source = ciYaml !== undefined ? 'pipeline.yml' : 'ci.json';
550
+ const configuration = ciYaml !== undefined ? ciYaml : ciJson;
551
+ return discoverConfiguredCliChecks({ configuration, source });
625
552
  }
626
553
  const checks = [];
627
554
  if (packageScripts) {
@@ -642,39 +569,36 @@ function decodeFileContent(file) {
642
569
  ? Buffer.from(file.content, 'base64').toString('utf8')
643
570
  : file.content;
644
571
  }
645
- /**
646
- * Load `.seq/ci.json` / `package.json` for CI preview.
647
- *
648
- * Matches the runner: only a true 404 means "file absent". Invalid JSON and
649
- * non-404 API errors fail closed (no silent package.json fallback over a bad
650
- * `.seq/ci.json`).
651
- */
572
+ /** Load YAML or legacy JSON; only a true 404 means configuration is absent. */
652
573
  export async function loadRemoteCiSources({ ctx, repoId, ref, }) {
653
- let ciJson;
654
- try {
655
- const file = await getJsonOr404({
656
- ...clientOptions(ctx),
657
- path: `/api/git-service/repos/${repoId}/contents/.seq/ci.json?ref=${encodeURIComponent(ref)}`,
658
- });
659
- if (file != null) {
660
- try {
661
- ciJson = JSON.parse(decodeFileContent(file));
662
- }
663
- catch {
664
- return { ok: false, error: 'invalid .seq/ci.json: not valid JSON' };
665
- }
574
+ const configurations = [];
575
+ for (const path of ['.seq/pipeline.yml', '.seq/ci.json']) {
576
+ try {
577
+ const file = await getJsonOr404({
578
+ ...clientOptions(ctx),
579
+ path: `/api/git-service/repos/${repoId}/contents/${path}?ref=${encodeURIComponent(ref)}`,
580
+ });
581
+ if (file != null)
582
+ configurations.push({ path, text: decodeFileContent(file) });
666
583
  }
667
- }
668
- catch (err) {
669
- if (err instanceof AtlasApiError) {
670
- return { ok: false, error: `failed to fetch .seq/ci.json: ${err.message}` };
584
+ catch (err) {
585
+ if (err instanceof AtlasApiError)
586
+ return { ok: false, error: `failed to fetch ${path}: ${err.message}` };
587
+ throw err;
671
588
  }
672
- throw err;
673
589
  }
674
- // When ci.json is present (including empty checks), skip package.json —
675
- // discovery never falls through to autodiscover in that case.
676
- if (ciJson !== undefined) {
677
- return { ok: true, ciJson };
590
+ if (configurations.length > 1)
591
+ return { ok: false, error: 'Both .seq/pipeline.yml and .seq/ci.json exist; remove one to make CI configuration unambiguous' };
592
+ const configuration = configurations[0];
593
+ if (configuration) {
594
+ try {
595
+ const parsed = parseCiConfigText(configuration) ?? null;
596
+ return configuration.path.endsWith('.yml') ? { ok: true, ciYaml: parsed } : { ok: true, ciJson: parsed };
597
+ }
598
+ catch (error) {
599
+ const detail = configuration.path.endsWith('.json') ? 'not valid JSON' : error instanceof Error ? error.message : 'invalid YAML';
600
+ return { ok: false, error: `invalid ${configuration.path}: ${detail}` };
601
+ }
678
602
  }
679
603
  let packageScripts;
680
604
  try {
@@ -691,11 +615,7 @@ export async function loadRemoteCiSources({ ctx, repoId, ref, }) {
691
615
  return { ok: false, error: 'invalid package.json: not valid JSON' };
692
616
  }
693
617
  if (pkg.scripts && typeof pkg.scripts === 'object') {
694
- packageScripts = {};
695
- for (const [key, value] of Object.entries(pkg.scripts)) {
696
- if (typeof value === 'string')
697
- packageScripts[key] = value;
698
- }
618
+ packageScripts = Object.fromEntries(Object.entries(pkg.scripts).filter((entry) => typeof entry[1] === 'string'));
699
619
  }
700
620
  }
701
621
  }
@@ -713,8 +633,17 @@ export async function loadRemoteCiSources({ ctx, repoId, ref, }) {
713
633
  */
714
634
  export async function reposCiShowCommand(args) {
715
635
  const { namespace, name } = parseRepoPath(args.positional[0]);
636
+ const pr = stringFlag(args.flags, 'pr');
637
+ if (pr !== undefined && (!/^[1-9]\d*$/.test(pr) || !Number.isSafeInteger(Number(pr))))
638
+ throw new Error('--pr requires a positive pull request number');
639
+ if (pr !== undefined && args.flags.ref !== undefined)
640
+ throw new Error('Choose --pr for the authoritative PR plan or --ref for a configuration preview');
641
+ if (pr === undefined && flagBool(args.flags, 'json'))
642
+ throw new Error('--json requires --pr for the authoritative CI status');
716
643
  const ctx = await reposContext(args);
717
644
  const resolved = await resolveRepo({ ...clientOptions(ctx), namespace, name });
645
+ if (pr !== undefined)
646
+ return showRepositoryPrCi({ ctx, repoId: resolved.id, repoPath: `${namespace}/${name}`, number: Number(pr), json: flagBool(args.flags, 'json') });
718
647
  const repo = await getJson({
719
648
  ...clientOptions(ctx),
720
649
  path: `/api/git-service/repos/${resolved.id}`,
@@ -732,6 +661,11 @@ export async function reposCiShowCommand(args) {
732
661
  return 1;
733
662
  }
734
663
  console.log(`${LOG} CI for ${namespace}/${name}@${ref} on ${ctx.env.name}:`);
664
+ if (discovered.native) {
665
+ console.log(' Native repository pipeline discovered; the server validates and plans it when a pull request is opened or updated.');
666
+ console.log(` Inspect the plan with: seq-studio repos ci show ${namespace}/${name} -e ${ctx.env.name} --pr <number>`);
667
+ return 0;
668
+ }
735
669
  if (discovered.checks.length === 0) {
736
670
  console.log(' (no checks discovered)');
737
671
  return 0;
@@ -746,9 +680,9 @@ export async function reposCiShowCommand(args) {
746
680
  }
747
681
  return 0;
748
682
  }
749
- const REQUIRED_CHECKS_WRITE_DISABLED = `${LOG} writing requiredChecks is disabled until the sandboxed CI runner is live ` +
750
- `(discovery posts neutral check-runs that cannot satisfy the merge gate). ` +
751
- `Use \`seq-studio repos ci show\` to preview discovered names.`;
683
+ const REQUIRED_CHECKS_WRITE_DISABLED = `${LOG} these legacy requiredChecks controls are disabled; legacy discovery posts neutral check-runs. ` +
684
+ `Use \`seq-studio repos ci init\`, commit .seq/pipeline.yml, and open or update a pull request for native CI. ` +
685
+ `Use \`seq-studio repos ci show <repo> -e <env> --pr <number>\` to inspect its plan.`;
752
686
  /** Add a check-run name to Settings `requiredChecks` (merge-blocking). */
753
687
  export async function reposCiRequireCommand(args) {
754
688
  const check = stringFlag(args.flags, 'check');
@@ -771,12 +705,21 @@ export async function reposCiImportCommand(args) {
771
705
  return 1;
772
706
  }
773
707
  export async function reposCiCommand(args) {
774
- const [action] = args.positional;
708
+ const [requestedAction] = args.positional;
709
+ const action = flagBool(args.flags, 'help') || flagBool(args.flags, 'h') ? 'help' : requestedAction;
775
710
  const rest = {
776
711
  ...args,
777
712
  positional: args.positional.slice(1),
778
713
  };
779
714
  switch (action) {
715
+ case 'init': {
716
+ if (rest.positional.length)
717
+ throw new Error('usage: seq-studio repos ci init [--dir <repository>]');
718
+ const filename = await initializeRepositoryPipeline({ directory: stringFlag(rest.flags, 'dir') ?? process.cwd() });
719
+ console.log(`${LOG} Created ${filename}`);
720
+ console.log('Commit and push this file with your resource manifests, then open or update a pull request. Atlas discovers the pipeline and uses platform-managed CI defaults.');
721
+ return 0;
722
+ }
780
723
  case 'show':
781
724
  return reposCiShowCommand(rest);
782
725
  case 'require':
@@ -786,9 +729,15 @@ export async function reposCiCommand(args) {
786
729
  case 'help':
787
730
  case undefined:
788
731
  console.log(`usage:
789
- seq-studio repos ci show <ns>/<name> -e <env> [--ref r] preview discovered CI checks
790
- seq-studio repos ci require <ns>/<name> --check <name> -e <env> reserved (refuses write until sandboxed runner)
791
- seq-studio repos ci import <ns>/<name> -e <env> [--ref r] reserved (refuses write until sandboxed runner)
732
+ seq-studio repos ci init [--dir <repository>] create .seq/pipeline.yml; no login needed
733
+ seq-studio repos ci show <ns>/<name> -e <env> --pr <number> [--json] inspect the server CI plan and runs
734
+ seq-studio repos ci show <ns>/<name> -e <env> [--ref r] preview pipeline discovery or legacy checks
735
+ seq-studio repos ci require <ns>/<name> --check <name> -e <env> disabled legacy control; use native pipeline discovery
736
+ seq-studio repos ci import <ns>/<name> -e <env> [--ref r] disabled legacy control; use native pipeline discovery
737
+
738
+ Commit and push .seq/pipeline.yml with your native resource manifests, then
739
+ open or update a pull request. Atlas selects the managed executor and image.
740
+ Native checks do not require a branch policy or image digest in the repository.
792
741
  `);
793
742
  return action ? 0 : 1;
794
743
  default:
@@ -1,10 +1 @@
1
- export { looksLikeCommitSha, redactCloneUrl, resolveGitPatFromEnv, runGitClone, withGitAskpass, type RunGitClone, } from '@sequenceholdings/artifact-studio/git-clone';
2
- /**
3
- * Write a credential via `git credential approve` so subsequent clones against
4
- * the same host can authenticate without embedding the PAT in the URL.
5
- */
6
- export declare function storeGitCredentials({ cloneUrl, pat, username, }: {
7
- cloneUrl: string;
8
- pat: string;
9
- username?: string;
10
- }): Promise<void>;
1
+ export { looksLikeCommitSha, redactCloneUrl, runGitClone, withGitAskpass, type RunGitClone, } from '@sequenceholdings/artifact-studio/git-clone';
@@ -1,49 +1 @@
1
- /**
2
- * Smart-HTTP git clone helpers for platform git-service.
3
- *
4
- * The clone primitives (askpass, runGitClone, PAT/URL helpers) are the
5
- * canonical implementation in `@sequenceholdings/artifact-studio/git-clone` so
6
- * the `repos` tool and the artifact `--repo` deploy path share one code path.
7
- * We re-export them here to keep the historical import site stable, and add
8
- * `storeGitCredentials` (git credential-helper writer) which is studio-cli
9
- * specific.
10
- */
11
- import { spawn } from 'node:child_process';
12
- export { looksLikeCommitSha, redactCloneUrl, resolveGitPatFromEnv, runGitClone, withGitAskpass, } from '@sequenceholdings/artifact-studio/git-clone';
13
- /**
14
- * Write a credential via `git credential approve` so subsequent clones against
15
- * the same host can authenticate without embedding the PAT in the URL.
16
- */
17
- export async function storeGitCredentials({ cloneUrl, pat, username = 'git', }) {
18
- const parsed = new URL(cloneUrl);
19
- const protocol = parsed.protocol.replace(/:$/, '');
20
- const host = parsed.host;
21
- const path = parsed.pathname;
22
- const payload = [
23
- `protocol=${protocol}`,
24
- `host=${host}`,
25
- `path=${path}`,
26
- `username=${username}`,
27
- `password=${pat}`,
28
- '',
29
- ].join('\n');
30
- await new Promise((resolve, reject) => {
31
- const child = spawn('git', ['credential', 'approve'], {
32
- stdio: ['pipe', 'ignore', 'pipe'],
33
- });
34
- let stderr = '';
35
- child.stderr?.on('data', (chunk) => {
36
- stderr += chunk.toString();
37
- });
38
- child.on('error', (err) => reject(err));
39
- child.on('close', (code) => {
40
- if (code === 0) {
41
- resolve();
42
- return;
43
- }
44
- reject(new Error(`git credential approve failed (exit ${code ?? 'null'}): ${stderr.trim() || 'no stderr'}`));
45
- });
46
- child.stdin?.write(payload);
47
- child.stdin?.end();
48
- });
49
- }
1
+ export { looksLikeCommitSha, redactCloneUrl, runGitClone, withGitAskpass, } from '@sequenceholdings/artifact-studio/git-clone';
@@ -0,0 +1,15 @@
1
+ import type { ParsedArgs } from '../process/commands.js';
2
+ /** Only send a login credential to the exact repository pinned at clone time. */
3
+ export declare function gitCredentialResponse({ input, operation, envName, cloneUrl, }: {
4
+ input: string;
5
+ operation: string;
6
+ envName: string;
7
+ cloneUrl: string;
8
+ }): Promise<string>;
9
+ /** Store only a helper command, bound to this environment and repository URL. */
10
+ export declare function configureGitLogin({ destDir, envName, cloneUrl, }: {
11
+ destDir: string;
12
+ envName: string;
13
+ cloneUrl: string;
14
+ }): Promise<void>;
15
+ export declare function gitCredentialCommand(args: ParsedArgs): Promise<number>;