@sequenceholdings/studio-cli 0.9.20 → 0.9.22

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 (65) hide show
  1. package/README.md +159 -12
  2. package/dist/app/commands.js +37 -7
  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/app/scaffold.d.ts +3 -1
  9. package/dist/app/scaffold.js +5 -3
  10. package/dist/auth.d.ts +13 -9
  11. package/dist/auth.js +98 -20
  12. package/dist/cli-errors.js +6 -1
  13. package/dist/command-contract.d.ts +13 -1
  14. package/dist/command-contract.js +3 -1
  15. package/dist/command-help.d.ts +1 -1
  16. package/dist/command-help.js +8 -1
  17. package/dist/config.d.ts +14 -0
  18. package/dist/config.js +29 -3
  19. package/dist/docs/commands.d.ts +16 -0
  20. package/dist/docs/commands.js +168 -0
  21. package/dist/docs/help.d.ts +2 -0
  22. package/dist/docs/help.js +12 -0
  23. package/dist/envs/commands.js +10 -2
  24. package/dist/host-token.d.ts +19 -4
  25. package/dist/host-token.js +50 -10
  26. package/dist/main.d.ts +1 -0
  27. package/dist/main.js +20 -2
  28. package/dist/orm/discover-operations.d.ts +1 -1
  29. package/dist/orm/discover-operations.js +3 -3
  30. package/dist/orm/discover-schema.d.ts +0 -5
  31. package/dist/orm/discover-schema.js +0 -3
  32. package/dist/pipeline/commands.d.ts +0 -7
  33. package/dist/pipeline/commands.js +16 -67
  34. package/dist/pipeline/discovery.d.ts +1 -1
  35. package/dist/pipeline/discovery.js +6 -6
  36. package/dist/process/build.d.ts +2 -5
  37. package/dist/process/build.js +4 -49
  38. package/dist/repos/commands.d.ts +11 -1
  39. package/dist/repos/commands.js +78 -11
  40. package/dist/repos/git-credential.d.ts +12 -5
  41. package/dist/repos/git-credential.js +63 -36
  42. package/dist/repos/github-connect-command.d.ts +35 -0
  43. package/dist/repos/github-connect-command.js +250 -0
  44. package/dist/repos/github-init-command.d.ts +16 -0
  45. package/dist/repos/github-init-command.js +116 -0
  46. package/dist/repos/github-init.d.ts +146 -0
  47. package/dist/repos/github-init.js +355 -0
  48. package/dist/repos/init-github.d.ts +50 -0
  49. package/dist/repos/init-github.js +181 -0
  50. package/dist/repos/pulls.d.ts +5 -1
  51. package/dist/repos/pulls.js +31 -9
  52. package/dist/scaffold-guidance.d.ts +10 -2
  53. package/dist/scaffold-guidance.js +27 -2
  54. package/dist/templates/github/pr-type.mjs +285 -0
  55. package/dist/templates/github/pr-types.json +40 -0
  56. package/dist/templates/guidance/AGENTS.md +15 -8
  57. package/package.json +7 -7
  58. package/release-summary.json +3 -1
  59. package/templates/github/pr-type.mjs +285 -0
  60. package/templates/github/pr-types.json +40 -0
  61. package/templates/guidance/AGENTS.md +15 -8
  62. package/dist/pipeline/active-orm-contracts.d.ts +0 -16
  63. package/dist/pipeline/active-orm-contracts.js +0 -36
  64. package/dist/pipeline/repin-orm.d.ts +0 -2
  65. package/dist/pipeline/repin-orm.js +0 -207
@@ -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,16 @@
1
+ import type { ParsedArgs } from '../argv.js';
2
+ import { type GitHubApi, type GitHubSettings } from './github-init.js';
3
+ 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.";
4
+ /** `org/name` from a github.com origin, or null when the origin is elsewhere. */
5
+ export declare function githubRepositoryFromRemote(url: string): string | null;
6
+ /**
7
+ * Apply the branch rulesets and secret scanning with `gh`, and check that the repository can use seq-ci. Shared by
8
+ * `repo init --apply-github` and `init --github --apply-github`; returns the exit code.
9
+ */
10
+ export declare function applyGitHubSettingsWithReport({ repository, settings, say, api }: {
11
+ repository: string;
12
+ settings: GitHubSettings;
13
+ say: (text: string) => void;
14
+ api?: GitHubApi;
15
+ }): Promise<number>;
16
+ export declare function runRepoInitCommand(args: ParsedArgs): Promise<number>;
@@ -0,0 +1,116 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { applyGitHubSettings, ensureSeqCi, githubSettingsCommands, initializeGitHubRepository, resolveSettings, SEQUENCE_CI_APP } from './github-init.js';
3
+ export const REPO_INIT_USAGE = `usage:
4
+ seq-studio repo init [--org <org>] [--dev <branch>] [--release <branch>] [--seq-ci <vX.Y.Z>] [--release-repository <namespace/name>]
5
+ [--pull-request-builds reuse|rebuild] [--dir <checkout>] [--apply-github] [--json]
6
+ seq-studio repo init --check [--dir <checkout>] [--json]
7
+
8
+ Make a GitHub checkout a Sequence repository: .seq/github.yml (org and branches), the seq and seq promote
9
+ workflows, Renovate config, and an agent skill pointing at the platform docs. Writes only what's missing or
10
+ stale, and never overwrites a file it doesn't manage. --check reports the same and writes nothing (exit 3 when
11
+ anything is missing or stale).
12
+
13
+ Branch rulesets and secret scanning need admin rights on the repository (not the org): --apply-github runs them
14
+ with gh and confirms the repository can read seq-ci's org secrets; without it, the gh commands are printed for an
15
+ admin. Commit and push the written files yourself.
16
+
17
+ --pull-request-builds (default reuse): whether the dev branch's deploys reuse what a pull request's CI built and
18
+ checked from the change it merged. Sound only while the dev branch needs no approvals, as these rulesets set it;
19
+ once reviews are required, use rebuild. repo connect --stage staging records it on the Atlas.`;
20
+ function flag(args, name) {
21
+ const value = args.flags[name];
22
+ return typeof value === 'string' ? value : undefined;
23
+ }
24
+ /** `org/name` from a github.com origin, or null when the origin is elsewhere. */
25
+ export function githubRepositoryFromRemote(url) {
26
+ // The host must be exactly github.com: notgithub.com or example.com/github.com/... are not GitHub.
27
+ const match = /^(?:https:\/\/(?:[^@/]+@)?github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+?)(?:\.git)?\/?$/.exec(url.trim());
28
+ return match ? match[1] : null;
29
+ }
30
+ function originRepository(directory) {
31
+ const result = spawnSync('git', ['remote', 'get-url', 'origin'], { cwd: directory, encoding: 'utf8' });
32
+ return result.status === 0 ? githubRepositoryFromRemote(result.stdout) : null;
33
+ }
34
+ const INSTALLATION_NOTES = {
35
+ all: () => 'The Sequence CI App covers every repository.\n',
36
+ added: () => 'Added to the Sequence CI App installation.\n',
37
+ missing: (org) => `The Sequence CI App isn't installed in ${org}; an org owner must install it (https://github.com/apps/${SEQUENCE_CI_APP.slug}/installations/new), then rerun.\n`,
38
+ unchecked: () => 'Sequence CI App installation not checked (that takes an org owner); it covers every repository unless an owner narrowed it.\n',
39
+ };
40
+ const ghApi = async ({ method, path, body }) => {
41
+ const result = spawnSync('gh', ['api', '--method', method, path, ...(body === undefined ? [] : ['--input', '-'])], { input: body === undefined ? undefined : JSON.stringify(body), encoding: 'utf8' });
42
+ if (result.status !== 0)
43
+ throw new Error(`gh api ${method} ${path}: ${result.stderr.trim()}`);
44
+ return result.stdout.trim() ? JSON.parse(result.stdout) : null;
45
+ };
46
+ function printReports(reports) {
47
+ for (const report of reports) {
48
+ const note = report.status === 'unmanaged' ? ' (exists and isn\'t managed by seq-studio; left alone)' : '';
49
+ process.stdout.write(` ${report.status.padEnd(9)} ${report.path}${note}\n`);
50
+ }
51
+ }
52
+ /**
53
+ * Apply the branch rulesets and secret scanning with `gh`, and check that the repository can use seq-ci. Shared by
54
+ * `repo init --apply-github` and `init --github --apply-github`; returns the exit code.
55
+ */
56
+ export async function applyGitHubSettingsWithReport({ repository, settings, say, api = ghApi }) {
57
+ try {
58
+ const applied = await applyGitHubSettings({ repository, settings, api });
59
+ say(`Branch rulesets: created ${applied.created.join(', ') || 'none'}; updated ${applied.updated.join(', ') || 'none'}; the Sequence CI App bypasses ${settings.branches.release}. Secret scanning on.\n`);
60
+ const org = repository.split('/')[0];
61
+ const seqCi = await ensureSeqCi({ repository, api });
62
+ if (seqCi.secrets.shared.length > 0)
63
+ say(`seq-ci org secrets available: ${seqCi.secrets.shared.join(', ')}.\n`);
64
+ say(INSTALLATION_NOTES[seqCi.installation](org));
65
+ if (seqCi.secrets.missing.length > 0) {
66
+ process.stderr.write(`${repository} can't read ${seqCi.secrets.missing.join(', ')}, so seq-ci will fail. An ${org} org owner must make ` +
67
+ `${seqCi.secrets.missing.length === 1 ? 'it' : 'them'} visible to all private repositories (Settings → Secrets and variables → Actions), then rerun.\n`);
68
+ return 1;
69
+ }
70
+ return 0;
71
+ }
72
+ catch (error) {
73
+ process.stderr.write(`GitHub settings failed (admin rights needed?): ${error instanceof Error ? error.message : String(error)}\n`);
74
+ return 1;
75
+ }
76
+ }
77
+ export async function runRepoInitCommand(args) {
78
+ if (args.flags.help) {
79
+ process.stdout.write(`${REPO_INIT_USAGE}\n`);
80
+ return 0;
81
+ }
82
+ const directory = flag(args, 'dir') ?? '.';
83
+ const check = args.flags.check === true;
84
+ const settings = await resolveSettings({ directory, org: flag(args, 'org'), dev: flag(args, 'dev'), release: flag(args, 'release'), seqCi: flag(args, 'seq-ci'),
85
+ releaseRepository: flag(args, 'release-repository'), pullRequestBuilds: flag(args, 'pull-request-builds') });
86
+ const reports = await initializeGitHubRepository({ directory, settings, write: !check });
87
+ const repository = originRepository(directory);
88
+ const commands = repository ? githubSettingsCommands({ repository, settings }) : [];
89
+ if (args.flags.json === true) {
90
+ process.stdout.write(`${JSON.stringify({ settings, repository, files: reports, githubCommands: commands.map((command) => command.slice(0, -1)) }, null, 2)}\n`);
91
+ }
92
+ else {
93
+ process.stdout.write(`${check ? 'Checking' : 'Initialized'} ${repository ?? directory} for org ${settings.org} (dev ${settings.branches.dev}, release ${settings.branches.release}, seq-ci ${settings.seq_ci}, pull-request builds ${settings.pull_request_builds})\n`);
94
+ printReports(reports);
95
+ }
96
+ const outstanding = reports.some((report) => report.status === 'missing' || report.status === 'stale');
97
+ if (check)
98
+ return outstanding ? 3 : 0;
99
+ // Prose goes to stderr under --json, so stdout stays one JSON document.
100
+ const say = (text) => (args.flags.json === true ? process.stderr : process.stdout).write(text);
101
+ if (!repository) {
102
+ process.stderr.write('The origin is not on github.com, so GitHub settings were skipped.\n');
103
+ return 0;
104
+ }
105
+ if (args.flags['apply-github'] === true) {
106
+ const code = await applyGitHubSettingsWithReport({ repository, settings, say });
107
+ if (code !== 0)
108
+ return code;
109
+ }
110
+ else {
111
+ say('\nGitHub settings (need admin rights): rerun with --apply-github, or have an admin run:\n');
112
+ for (const command of commands)
113
+ say(` echo '${command.at(-1)}' | ${command.slice(0, -1).join(' ')}\n`);
114
+ }
115
+ return 0;
116
+ }
@@ -0,0 +1,146 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * `seq-studio repo init`: make a GitHub checkout a Sequence repository. Writes only files it owns, marked with a
4
+ * managed header, and only what's missing or stale; `check` reports the same without writing.
5
+ */
6
+ export declare const TEMPLATE_VERSION = 1;
7
+ export declare const MANAGED_MARKER = "Managed by seq-studio";
8
+ export declare const SEQ_CI_REPOSITORY = "sequenceholdings/seq-ci";
9
+ export declare const githubSettingsSchema: z.ZodObject<{
10
+ schema_version: z.ZodLiteral<1>;
11
+ org: z.ZodString;
12
+ branches: z.ZodObject<{
13
+ dev: z.ZodString;
14
+ release: z.ZodString;
15
+ }, z.core.$strict>;
16
+ seq_ci: z.ZodString;
17
+ release_repository: z.ZodOptional<z.ZodString>;
18
+ pull_request_builds: z.ZodOptional<z.ZodEnum<{
19
+ reuse: "reuse";
20
+ rebuild: "rebuild";
21
+ }>>;
22
+ promoted_builds: z.ZodOptional<z.ZodEnum<{
23
+ reuse: "reuse";
24
+ rebuild: "rebuild";
25
+ }>>;
26
+ }, z.core.$strict>;
27
+ export type GitHubSettings = z.infer<typeof githubSettingsSchema>;
28
+ export declare const GITHUB_SETTINGS_PATH = ".seq/github.yml";
29
+ export declare function pipelineWorkflow({ settings }: {
30
+ settings: GitHubSettings;
31
+ }): string;
32
+ export declare function promoteWorkflow({ settings }: {
33
+ settings: GitHubSettings;
34
+ }): string;
35
+ export declare function renovateConfig(): string;
36
+ export declare function agentSkill({ settings }: {
37
+ settings: GitHubSettings;
38
+ }): string;
39
+ /** The PR-type check's status context: every pull request into the dev branch needs exactly one `type: *` label. */
40
+ export declare const PR_TYPE_CHECK = "pr-type";
41
+ /**
42
+ * Every pull request needs exactly one `type: *` label (bug, performance, enhancement, feature, chore) so merged work
43
+ * can be measured by kind. With no label, Claude picks one when the repository can see an `ANTHROPIC_API_KEY` secret;
44
+ * otherwise the check fails and says which labels to add. The script and taxonomy run from the base commit, never the
45
+ * pull request's head, because the job holds a write-scoped token.
46
+ */
47
+ export declare function prTypeWorkflow({ settings }: {
48
+ settings: GitHubSettings;
49
+ }): string;
50
+ export declare function prTypeScript(): string;
51
+ export declare function prTypesTaxonomy(): string;
52
+ export interface ManagedFile {
53
+ path: string;
54
+ content: string;
55
+ }
56
+ export declare function managedFiles({ settings }: {
57
+ settings: GitHubSettings;
58
+ }): ManagedFile[];
59
+ export type FileStatus = 'missing' | 'stale' | 'current' | 'unmanaged';
60
+ export interface FileReport {
61
+ path: string;
62
+ status: FileStatus;
63
+ }
64
+ /** Existing settings win over defaults, so rerunning never changes a repository's org or branches. */
65
+ export declare function resolveSettings({ directory, org, dev, release, seqCi, releaseRepository, pullRequestBuilds }: {
66
+ directory: string;
67
+ org?: string;
68
+ dev?: string;
69
+ release?: string;
70
+ seqCi?: string;
71
+ releaseRepository?: string;
72
+ pullRequestBuilds?: string;
73
+ }): Promise<GitHubSettings>;
74
+ /**
75
+ * Report, or with `write`, create every managed file that's missing or stale. Never overwrites a file it doesn't own:
76
+ * an unmanaged file at a managed path is reported and left alone.
77
+ */
78
+ export declare function initializeGitHubRepository({ directory, settings, write }: {
79
+ directory: string;
80
+ settings: GitHubSettings;
81
+ write: boolean;
82
+ }): Promise<FileReport[]>;
83
+ /** The Sequence CI GitHub App (`sequence-ci`): prod Atlas moves release branches as it, their rulesets' bypass actor. */
84
+ export declare const SEQUENCE_CI_APP: {
85
+ readonly id: 5689400;
86
+ readonly slug: "sequence-ci";
87
+ };
88
+ /** The org secrets seq-ci's workflows read: read-only pull credentials, each visible to all the org's private repositories. */
89
+ /** The App's key is not among them: only prod Atlases hold it, and they move release branches as the App. */
90
+ export declare const SEQ_CI_SECRETS: readonly ["SEQ_CI_IMAGE_PULL_KEY", "SEQ_CI_REGISTRY_AUTH"];
91
+ /**
92
+ * The branch rulesets `repo init` keeps on a repository, by name. The dev branch requires `seq / checks`, `pr-type` and no
93
+ * approvals: what `pull_request_builds: reuse` relies on (`githubSettingsSchema`). It doesn't require pull requests to
94
+ * be up to date with the branch: every push to it builds and checks again before deploying, reusing a pull request's
95
+ * builds only when the merged tree carries every change that pull request's last run tested.
96
+ */
97
+ export declare function githubRulesets({ settings }: {
98
+ settings: GitHubSettings;
99
+ }): {
100
+ name: string;
101
+ body: Record<string, unknown> & {
102
+ bypass_actors: unknown[];
103
+ };
104
+ }[];
105
+ /** The GitHub API calls that set branch rules and secret scanning on a repository that has none yet, for an admin to run. */
106
+ export declare function githubSettingsCommands({ repository, settings }: {
107
+ repository: string;
108
+ settings: GitHubSettings;
109
+ }): string[][];
110
+ /** One GitHub API call: method, path and JSON body; returns the parsed response. */
111
+ export type GitHubApi = (args: {
112
+ method: 'GET' | 'POST' | 'PUT' | 'PATCH';
113
+ path: string;
114
+ body?: unknown;
115
+ }) => Promise<unknown>;
116
+ /**
117
+ * Apply the rulesets and secret scanning, reconciling by ruleset name: an existing `seq: <branch>` ruleset is updated in
118
+ * place, keeping any bypass actors an admin added alongside the Sequence CI App's, never duplicated.
119
+ */
120
+ export declare function applyGitHubSettings({ repository, settings, api }: {
121
+ repository: string;
122
+ settings: GitHubSettings;
123
+ api: GitHubApi;
124
+ }): Promise<{
125
+ created: string[];
126
+ updated: string[];
127
+ }>;
128
+ /** Whether the Sequence CI App's installation covers the repository; `unchecked` when the caller can't list the org's installations. */
129
+ export type SeqCiInstallation = 'all' | 'added' | 'missing' | 'unchecked';
130
+ /**
131
+ * Make sure a repository has what seq-ci's workflows need from the org: the `SEQ_CI_*` secrets, and the Sequence CI
132
+ * App's installation, which Promote's App token is scoped to. Both are org-wide (secrets visible to all private
133
+ * repositories, the App on all repositories), so a repository admin who isn't an org owner only confirms them.
134
+ * Should an org owner have narrowed either to selected repositories, an owner's `admin:org` token adds this one;
135
+ * anyone else gets `missing` back, naming what an owner must fix. Idempotent.
136
+ */
137
+ export declare function ensureSeqCi({ repository, api }: {
138
+ repository: string;
139
+ api: GitHubApi;
140
+ }): Promise<{
141
+ secrets: {
142
+ shared: string[];
143
+ missing: string[];
144
+ };
145
+ installation: SeqCiInstallation;
146
+ }>;