@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,355 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { lstat, mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { dump as yamlDump, load as yamlLoad } from 'js-yaml';
5
+ import { z } from 'zod';
6
+ /**
7
+ * `seq-studio repo init`: make a GitHub checkout a Sequence repository. Writes only files it owns, marked with a
8
+ * managed header, and only what's missing or stale; `check` reports the same without writing.
9
+ */
10
+ export const TEMPLATE_VERSION = 1;
11
+ export const MANAGED_MARKER = 'Managed by seq-studio';
12
+ export const SEQ_CI_REPOSITORY = 'sequenceholdings/seq-ci';
13
+ export const githubSettingsSchema = z.object({
14
+ schema_version: z.literal(1),
15
+ org: z.string().regex(/^[a-z][a-z0-9_]*$/),
16
+ branches: z.object({ dev: z.string().min(1), release: z.string().min(1) }).strict(),
17
+ /** Exact seq-ci release the workflows call, e.g. `v1.0.0`. Renovate bumps it. */
18
+ seq_ci: z.string().regex(/^v[0-9]+\.[0-9]+\.[0-9]+$/),
19
+ /** The git-service repository (`<namespace>/<name>`) this repository's Managed Pipelines stay released under. */
20
+ release_repository: z.string().regex(/^[a-z0-9][a-z0-9_-]*\/[A-Za-z0-9._-]+$/).optional(),
21
+ /**
22
+ * Whether the dev branch's deploys reuse what a pull request's CI built and checked from the change it merged
23
+ * (`reuse`), or build everything again (`rebuild`). `repo connect --stage staging` records it on the Atlas. Reuse is
24
+ * sound only while the dev branch's ruleset requires no approvals, as `repo init` sets it: whoever opens a pull request
25
+ * can then already merge and deploy it. Once reviews are required, set `rebuild` and rerun `repo connect`.
26
+ */
27
+ pull_request_builds: z.enum(['reuse', 'rebuild']).optional(),
28
+ /**
29
+ * Whether a promoted prod deploy reuses what the org's staging Atlas built, checked and runs for the same commit, for
30
+ * each environment-neutral target (`reuse`), or builds everything again (`rebuild`, the default when absent).
31
+ * `repo connect --stage prod` records it on the prod Atlas.
32
+ */
33
+ promoted_builds: z.enum(['reuse', 'rebuild']).optional(),
34
+ }).strict();
35
+ export const GITHUB_SETTINGS_PATH = '.seq/github.yml';
36
+ const header = (path) => `# ${MANAGED_MARKER} (template ${TEMPLATE_VERSION}). Change it with \`seq-studio repo init\`; check it with \`seq-studio repo init --check\`.\n# ${path}\n`;
37
+ export function pipelineWorkflow({ settings }) {
38
+ return `${header('.github/workflows/seq.yml')}name: seq
39
+ on:
40
+ pull_request: {}
41
+ merge_group: {}
42
+ push:
43
+ branches: [${JSON.stringify(settings.branches.dev)}, ${JSON.stringify(settings.branches.release)}]
44
+ concurrency:
45
+ group: seq-\${{ github.ref }}
46
+ cancel-in-progress: \${{ github.event_name == 'pull_request' }}
47
+ permissions: {}
48
+ jobs:
49
+ seq:
50
+ uses: ${SEQ_CI_REPOSITORY}/.github/workflows/pipeline.yml@${settings.seq_ci}
51
+ permissions: { contents: read, id-token: write, pull-requests: write, checks: write }
52
+ secrets: inherit
53
+ `;
54
+ }
55
+ export function promoteWorkflow({ settings }) {
56
+ return `${header('.github/workflows/seq-promote.yml')}name: seq promote
57
+ on:
58
+ workflow_dispatch:
59
+ inputs:
60
+ sha: { description: "Commit on ${settings.branches.dev} to release (default: its tip)", required: false }
61
+ permissions: {}
62
+ jobs:
63
+ promote:
64
+ uses: ${SEQ_CI_REPOSITORY}/.github/workflows/promote.yml@${settings.seq_ci}
65
+ with:
66
+ sha: \${{ inputs.sha }}
67
+ permissions: { contents: read, id-token: write }
68
+ secrets: inherit
69
+ `;
70
+ }
71
+ export function renovateConfig() {
72
+ return `${JSON.stringify({ $schema: 'https://docs.renovatebot.com/renovate-schema.json', extends: [`github>${SEQ_CI_REPOSITORY}//renovate/default`] }, null, 2)}\n`;
73
+ }
74
+ export function agentSkill({ settings }) {
75
+ return `---
76
+ name: sequence-platform
77
+ description: Read before using seq-studio or changing anything under .seq/, sequence.app.yml or a primitive manifest in this repository.
78
+ ---
79
+ <!-- ${MANAGED_MARKER} (template ${TEMPLATE_VERSION}). -->
80
+
81
+ This repository deploys to the Sequence platform for the \`${settings.org}\` org.
82
+
83
+ - Read the platform docs first: \`seq-studio docs search "<topic>" -e <env>\`, then \`seq-studio docs read <slug> -e <env>\` (\`seq-studio envs list\` prints the environments). They match the deployed platform version; use them rather than guessing command shapes.
84
+ - Every pull request needs exactly one type label: \`type: bug\`, \`type: performance\`, \`type: enhancement\`, \`type: feature\` or \`type: chore\` (see .github/pr-types.json). Pick it yourself when you open the pull request (\`gh pr create --label "type: …"\`).
85
+ - \`${settings.branches.dev}\` deploys to staging; \`${settings.branches.release}\` deploys to prod and moves only through the Promote workflow in GitHub.
86
+ - Never use \`--break-glass\` unless the user explicitly asks for it in this conversation and gives the reason.
87
+ `;
88
+ }
89
+ /** The PR-type check's status context: every pull request into the dev branch needs exactly one `type: *` label. */
90
+ export const PR_TYPE_CHECK = 'pr-type';
91
+ const PR_TYPE_SCRIPT_PATH = '.github/scripts/seq-pr-type.mjs';
92
+ const PR_TYPES_PATH = '.github/pr-types.json';
93
+ /** The shared PR-type script and taxonomy, as studio-cli ships them (studio's own PR check runs the same copy). */
94
+ function prTypeTemplate(name) {
95
+ return readFileSync(new URL(`../../templates/github/${name}`, import.meta.url), 'utf8');
96
+ }
97
+ /**
98
+ * Every pull request needs exactly one `type: *` label (bug, performance, enhancement, feature, chore) so merged work
99
+ * can be measured by kind. With no label, Claude picks one when the repository can see an `ANTHROPIC_API_KEY` secret;
100
+ * otherwise the check fails and says which labels to add. The script and taxonomy run from the base commit, never the
101
+ * pull request's head, because the job holds a write-scoped token.
102
+ */
103
+ export function prTypeWorkflow({ settings }) {
104
+ return `${header('.github/workflows/seq-pr-type.yml')}name: PR type
105
+ on:
106
+ pull_request:
107
+ types: [opened, reopened, ready_for_review, synchronize, labeled, unlabeled]
108
+ push:
109
+ branches: [${JSON.stringify(settings.branches.dev)}]
110
+ paths: [${JSON.stringify(PR_TYPES_PATH)}]
111
+ workflow_dispatch: {}
112
+ permissions: {}
113
+ jobs:
114
+ ${PR_TYPE_CHECK}:
115
+ name: ${PR_TYPE_CHECK}
116
+ if: github.event_name == 'pull_request'
117
+ runs-on: ubuntu-latest
118
+ timeout-minutes: 5
119
+ concurrency:
120
+ group: pr-type-\${{ github.event.pull_request.number }}
121
+ cancel-in-progress: true
122
+ permissions: { contents: read, issues: write, pull-requests: write }
123
+ steps:
124
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
125
+ with:
126
+ ref: \${{ github.event.pull_request.base.sha }}
127
+ sparse-checkout: |
128
+ ${PR_TYPES_PATH}
129
+ ${PR_TYPE_SCRIPT_PATH}
130
+ sparse-checkout-cone-mode: false
131
+ persist-credentials: false
132
+ - name: Require exactly one type label
133
+ env:
134
+ GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
135
+ ANTHROPIC_API_KEY: \${{ secrets.ANTHROPIC_API_KEY }}
136
+ PR_TYPES_PATH: ${PR_TYPES_PATH}
137
+ # Label events only re-check: classifying on unlabeled would race an author swapping types.
138
+ PR_TYPE_CLASSIFY: \${{ github.event.action != 'labeled' && github.event.action != 'unlabeled' }}
139
+ # The base commit predates the check only on the pull request that introduces it.
140
+ run: |
141
+ if [ ! -f ${PR_TYPE_SCRIPT_PATH} ]; then
142
+ echo "::notice::The PR type check is not on the base branch yet; skipping until it merges."
143
+ exit 0
144
+ fi
145
+ node ${PR_TYPE_SCRIPT_PATH}
146
+ sync-labels:
147
+ name: sync labels
148
+ if: github.event_name != 'pull_request'
149
+ runs-on: ubuntu-latest
150
+ timeout-minutes: 5
151
+ permissions: { contents: read, issues: write }
152
+ steps:
153
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
154
+ with:
155
+ sparse-checkout: |
156
+ ${PR_TYPES_PATH}
157
+ ${PR_TYPE_SCRIPT_PATH}
158
+ sparse-checkout-cone-mode: false
159
+ persist-credentials: false
160
+ - name: Create or update type labels
161
+ env:
162
+ GITHUB_TOKEN: \${{ secrets.GITHUB_TOKEN }}
163
+ PR_TYPES_PATH: ${PR_TYPES_PATH}
164
+ run: node ${PR_TYPE_SCRIPT_PATH} sync-labels
165
+ `;
166
+ }
167
+ export function prTypeScript() {
168
+ return `// ${MANAGED_MARKER} (template ${TEMPLATE_VERSION}). Change it with \`seq-studio repo init\`; check it with \`seq-studio repo init --check\`.\n${prTypeTemplate('pr-type.mjs')}`;
169
+ }
170
+ export function prTypesTaxonomy() {
171
+ const taxonomy = JSON.parse(prTypeTemplate('pr-types.json'));
172
+ return `${JSON.stringify({ ...taxonomy, $comment: `${MANAGED_MARKER} (template ${TEMPLATE_VERSION}). Change it with \`seq-studio repo init\`. Add a type, never rename one: renaming splits the trend lines.` }, null, 2)}\n`;
173
+ }
174
+ const AGENTS_POINTER = 'Before using seq-studio here, read .claude/skills/sequence-platform/SKILL.md.';
175
+ export function managedFiles({ settings }) {
176
+ return [
177
+ { path: GITHUB_SETTINGS_PATH, content: `# ${MANAGED_MARKER}. Repository-level GitHub settings until .seq/repository.yml version 2 carries them.\n${yamlDump(settings)}` },
178
+ { path: '.github/workflows/seq.yml', content: pipelineWorkflow({ settings }) },
179
+ { path: '.github/workflows/seq-promote.yml', content: promoteWorkflow({ settings }) },
180
+ { path: 'renovate.json', content: renovateConfig() },
181
+ { path: '.claude/skills/sequence-platform/SKILL.md', content: agentSkill({ settings }) },
182
+ { path: '.github/workflows/seq-pr-type.yml', content: prTypeWorkflow({ settings }) },
183
+ { path: PR_TYPE_SCRIPT_PATH, content: prTypeScript() },
184
+ { path: PR_TYPES_PATH, content: prTypesTaxonomy() },
185
+ ];
186
+ }
187
+ async function readOptional(path) {
188
+ try {
189
+ const info = await lstat(path);
190
+ if (!info.isFile())
191
+ throw new Error(`${path} must be a regular file`);
192
+ return await readFile(path, 'utf8');
193
+ }
194
+ catch (error) {
195
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT')
196
+ return null;
197
+ throw error;
198
+ }
199
+ }
200
+ function statusOf({ existing, content }) {
201
+ if (existing === null)
202
+ return 'missing';
203
+ if (existing === content)
204
+ return 'current';
205
+ return existing.includes(MANAGED_MARKER) ? 'stale' : 'unmanaged';
206
+ }
207
+ /** Existing settings win over defaults, so rerunning never changes a repository's org or branches. */
208
+ export async function resolveSettings({ directory, org, dev, release, seqCi, releaseRepository, pullRequestBuilds }) {
209
+ const existing = await readOptional(join(resolve(directory), GITHUB_SETTINGS_PATH));
210
+ const current = existing === null ? undefined : githubSettingsSchema.parse(yamlLoad(existing));
211
+ const settings = { schema_version: 1, org: org ?? current?.org, branches: { dev: dev ?? current?.branches.dev ?? 'staging', release: release ?? current?.branches.release ?? 'main' },
212
+ seq_ci: seqCi ?? current?.seq_ci ?? 'v1.0.5',
213
+ // On by default: the dev branch ruleset below requires no approvals.
214
+ pull_request_builds: pullRequestBuilds ?? current?.pull_request_builds ?? 'reuse',
215
+ ...((releaseRepository ?? current?.release_repository) ? { release_repository: releaseRepository ?? current?.release_repository } : {}),
216
+ ...(current?.promoted_builds ? { promoted_builds: current.promoted_builds } : {}) };
217
+ if (!settings.org)
218
+ throw new Error('repo init needs --org the first time (for example --org banksouth)');
219
+ if (settings.branches.dev === settings.branches.release)
220
+ throw new Error('The dev and release branches must differ');
221
+ return githubSettingsSchema.parse(settings);
222
+ }
223
+ /**
224
+ * Report, or with `write`, create every managed file that's missing or stale. Never overwrites a file it doesn't own:
225
+ * an unmanaged file at a managed path is reported and left alone.
226
+ */
227
+ export async function initializeGitHubRepository({ directory, settings, write }) {
228
+ const root = resolve(directory);
229
+ if (!(await lstat(join(root, '.git')).catch(() => null)))
230
+ throw new Error('repo init must run at the root of a git checkout');
231
+ const reports = [];
232
+ for (const file of managedFiles({ settings })) {
233
+ const path = join(root, file.path);
234
+ const status = statusOf({ existing: await readOptional(path), content: file.content });
235
+ reports.push({ path: file.path, status });
236
+ if (write && (status === 'missing' || status === 'stale')) {
237
+ await mkdir(dirname(path), { recursive: true });
238
+ await writeFile(path, file.content);
239
+ }
240
+ }
241
+ const agentsPath = join(root, 'AGENTS.md');
242
+ const agents = await readOptional(agentsPath);
243
+ const hasPointer = agents?.includes(AGENTS_POINTER) ?? false;
244
+ reports.push({ path: 'AGENTS.md', status: hasPointer ? 'current' : agents === null ? 'missing' : 'stale' });
245
+ if (write && !hasPointer)
246
+ await writeFile(agentsPath, `${agents ? `${agents.trimEnd()}\n\n` : ''}${AGENTS_POINTER}\n`);
247
+ return reports;
248
+ }
249
+ /** The Sequence CI GitHub App (`sequence-ci`): prod Atlas moves release branches as it, their rulesets' bypass actor. */
250
+ export const SEQUENCE_CI_APP = { id: 5689400, slug: 'sequence-ci' };
251
+ const APP_BYPASS = { actor_id: SEQUENCE_CI_APP.id, actor_type: 'Integration', bypass_mode: 'always' };
252
+ /** The org secrets seq-ci's workflows read: read-only pull credentials, each visible to all the org's private repositories. */
253
+ /** The App's key is not among them: only prod Atlases hold it, and they move release branches as the App. */
254
+ export const SEQ_CI_SECRETS = ['SEQ_CI_IMAGE_PULL_KEY', 'SEQ_CI_REGISTRY_AUTH'];
255
+ /**
256
+ * The branch rulesets `repo init` keeps on a repository, by name. The dev branch requires `seq / checks`, `pr-type` and no
257
+ * approvals: what `pull_request_builds: reuse` relies on (`githubSettingsSchema`). It doesn't require pull requests to
258
+ * be up to date with the branch: every push to it builds and checks again before deploying, reusing a pull request's
259
+ * builds only when the merged tree carries every change that pull request's last run tested.
260
+ */
261
+ export function githubRulesets({ settings }) {
262
+ const ruleset = (branch, rules) => ({ name: `seq: ${branch}`,
263
+ body: { name: `seq: ${branch}`, target: 'branch', enforcement: 'active', conditions: { ref_name: { include: [`refs/heads/${branch}`], exclude: [] } }, rules } });
264
+ return [
265
+ ruleset(settings.branches.dev, [
266
+ { type: 'deletion' }, { type: 'non_fast_forward' }, { type: 'pull_request', parameters: { required_approving_review_count: 0, dismiss_stale_reviews_on_push: false, require_code_owner_review: false, require_last_push_approval: false, required_review_thread_resolution: false } },
267
+ { type: 'required_status_checks', parameters: { strict_required_status_checks_policy: false, required_status_checks: [{ context: 'seq / checks' }, { context: PR_TYPE_CHECK }] } },
268
+ ]),
269
+ { ...ruleset(settings.branches.release, [{ type: 'deletion' }, { type: 'non_fast_forward' }, { type: 'update' }]), bypass: [APP_BYPASS] },
270
+ ].map(({ bypass = [], ...entry }) => ({ ...entry, body: { ...entry.body, bypass_actors: bypass } }));
271
+ }
272
+ const SECRET_SCANNING = { security_and_analysis: { secret_scanning: { status: 'enabled' }, secret_scanning_push_protection: { status: 'enabled' } } };
273
+ /** The GitHub API calls that set branch rules and secret scanning on a repository that has none yet, for an admin to run. */
274
+ export function githubSettingsCommands({ repository, settings }) {
275
+ return [
276
+ ...githubRulesets({ settings }).map((ruleset) => ['gh', 'api', '--method', 'POST', `repos/${repository}/rulesets`, '--input', '-', JSON.stringify(ruleset.body)]),
277
+ ['gh', 'api', '--method', 'PATCH', `repos/${repository}`, '--input', '-', JSON.stringify(SECRET_SCANNING)],
278
+ ];
279
+ }
280
+ /**
281
+ * Apply the rulesets and secret scanning, reconciling by ruleset name: an existing `seq: <branch>` ruleset is updated in
282
+ * place, keeping any bypass actors an admin added alongside the Sequence CI App's, never duplicated.
283
+ */
284
+ export async function applyGitHubSettings({ repository, settings, api }) {
285
+ const existing = await api({ method: 'GET', path: `repos/${repository}/rulesets?per_page=100` });
286
+ const listed = Array.isArray(existing) ? existing.filter((entry) => typeof entry?.id === 'number' && typeof entry?.name === 'string') : [];
287
+ const result = { created: [], updated: [] };
288
+ for (const ruleset of githubRulesets({ settings })) {
289
+ const match = listed.find((entry) => entry.name === ruleset.name);
290
+ if (!match) {
291
+ await api({ method: 'POST', path: `repos/${repository}/rulesets`, body: ruleset.body });
292
+ result.created.push(ruleset.name);
293
+ continue;
294
+ }
295
+ const current = await api({ method: 'GET', path: `repos/${repository}/rulesets/${match.id}` });
296
+ const kept = current && typeof current === 'object' && Array.isArray(Reflect.get(current, 'bypass_actors')) ? Reflect.get(current, 'bypass_actors') : [];
297
+ const key = (actor) => actor && typeof actor === 'object' ? `${String(Reflect.get(actor, 'actor_type'))}:${String(Reflect.get(actor, 'actor_id'))}` : '';
298
+ const bypass = [...kept, ...ruleset.body.bypass_actors.filter((actor) => !kept.some((entry) => key(entry) === key(actor)))];
299
+ await api({ method: 'PUT', path: `repos/${repository}/rulesets/${match.id}`, body: { ...ruleset.body, bypass_actors: bypass } });
300
+ result.updated.push(ruleset.name);
301
+ }
302
+ await api({ method: 'PATCH', path: `repos/${repository}`, body: SECRET_SCANNING });
303
+ return result;
304
+ }
305
+ /**
306
+ * Make sure a repository has what seq-ci's workflows need from the org: the `SEQ_CI_*` secrets, and the Sequence CI
307
+ * App's installation, which Promote's App token is scoped to. Both are org-wide (secrets visible to all private
308
+ * repositories, the App on all repositories), so a repository admin who isn't an org owner only confirms them.
309
+ * Should an org owner have narrowed either to selected repositories, an owner's `admin:org` token adds this one;
310
+ * anyone else gets `missing` back, naming what an owner must fix. Idempotent.
311
+ */
312
+ export async function ensureSeqCi({ repository, api }) {
313
+ const [org] = repository.split('/');
314
+ const repo = await api({ method: 'GET', path: `repos/${repository}` });
315
+ const repoId = repo && typeof repo === 'object' ? Reflect.get(repo, 'id') : undefined;
316
+ if (typeof repoId !== 'number')
317
+ throw new Error(`GitHub returned no id for ${repository}`);
318
+ const visible = await api({ method: 'GET', path: `repos/${repository}/actions/organization-secrets?per_page=100` });
319
+ const entries = visible && typeof visible === 'object' ? Reflect.get(visible, 'secrets') : undefined;
320
+ const names = new Set(Array.isArray(entries) ? entries.map((entry) => entry?.name) : []);
321
+ const secrets = { shared: [], missing: [] };
322
+ for (const name of SEQ_CI_SECRETS) {
323
+ if (names.has(name)) {
324
+ secrets.shared.push(name);
325
+ continue;
326
+ }
327
+ try {
328
+ await api({ method: 'PUT', path: `orgs/${org}/actions/secrets/${name}/repositories/${repoId}` });
329
+ secrets.shared.push(name);
330
+ }
331
+ catch {
332
+ secrets.missing.push(name);
333
+ }
334
+ }
335
+ return { secrets, installation: await ensureInstallation({ org: org, repoId, api }) };
336
+ }
337
+ async function ensureInstallation({ org, repoId, api }) {
338
+ let listed;
339
+ // Listing an org's installations takes an org owner; for anyone else the App's coverage goes unverified.
340
+ try {
341
+ listed = await api({ method: 'GET', path: `orgs/${org}/installations?per_page=100` });
342
+ }
343
+ catch {
344
+ return 'unchecked';
345
+ }
346
+ const installations = listed && typeof listed === 'object' ? Reflect.get(listed, 'installations') : undefined;
347
+ const installation = Array.isArray(installations) ? installations.find((entry) => entry?.app_id === SEQUENCE_CI_APP.id) : undefined;
348
+ if (!installation || typeof installation.id !== 'number')
349
+ return 'missing';
350
+ // An installation on all repositories already covers this one; GitHub refuses to add a repository to it.
351
+ if (installation.repository_selection === 'all')
352
+ return 'all';
353
+ await api({ method: 'PUT', path: `user/installations/${installation.id}/repositories/${repoId}` });
354
+ return 'added';
355
+ }
@@ -0,0 +1,50 @@
1
+ import type { ParsedArgs } from '../argv.js';
2
+ import { type GitHubSettings } from './github-init.js';
3
+ import { applyGitHubSettingsWithReport } from './github-init-command.js';
4
+ export interface CommandResult {
5
+ status: number | null;
6
+ stdout: string;
7
+ stderr: string;
8
+ }
9
+ /** Runs an external command; injectable so tests never touch `gh`, `git` or GitHub. */
10
+ export type RunCommand = (command: string, args: readonly string[], options?: {
11
+ cwd?: string;
12
+ }) => CommandResult;
13
+ export declare const defaultRunCommand: RunCommand;
14
+ /** `owner/name`, validated the way GitHub names them; throws with a usable message otherwise. */
15
+ export declare function parseGitHubRepository(value: unknown): {
16
+ owner: string;
17
+ name: string;
18
+ slug: string;
19
+ };
20
+ export declare function githubCloneUrl(slug: string): string;
21
+ /** Everything that must hold before anything is created. Returns the resolved target. */
22
+ export declare function preflightGitHubInit({ args, target, run }: {
23
+ args: ParsedArgs;
24
+ target: string;
25
+ run: RunCommand;
26
+ }): {
27
+ slug: string;
28
+ root: string;
29
+ };
30
+ /** The commit, push and connect steps after a successful `init --github`. */
31
+ export declare function githubNextSteps({ root, slug, settings, applied, env }: {
32
+ root: string;
33
+ slug: string;
34
+ settings: GitHubSettings;
35
+ applied: boolean;
36
+ env: string | undefined;
37
+ }): string[];
38
+ /**
39
+ * Run the whole flow. `scaffold` writes the app into `root` (an initialized,
40
+ * empty Git checkout) and returns its exit code.
41
+ */
42
+ export declare function runInitWithGitHub({ args, target, scaffold, run, apply }: {
43
+ args: ParsedArgs;
44
+ target: string;
45
+ scaffold: (root: string) => Promise<number>;
46
+ run?: RunCommand;
47
+ apply?: typeof applyGitHubSettingsWithReport;
48
+ }): Promise<number>;
49
+ /** The same parsed arguments without the GitHub-only flags, for the scaffold itself. */
50
+ export declare function withoutGitHubFlags(args: ParsedArgs): ParsedArgs;
@@ -0,0 +1,181 @@
1
+ /**
2
+ * `seq-studio init <dir> --github <owner>/<name> --org <org>`: start an app in
3
+ * its own new GitHub repository, ready for seq-ci. One command does what used to
4
+ * be four: create the repository with `gh`, `git init` the directory, scaffold
5
+ * the app, point `origin` at GitHub and write the `repo init` files.
6
+ *
7
+ * Creating a repository is opt-in. Without `--github`, `init` keeps its existing
8
+ * behavior, so an app that belongs in an existing repository (a monorepo) is
9
+ * still scaffolded into it with plain `init <subdir>`. `--github` inside an
10
+ * existing checkout is refused for the same reason.
11
+ *
12
+ * Every local refusal happens before anything is created, and the scaffold runs
13
+ * before the GitHub repository is created, so a failed scaffold leaves nothing
14
+ * behind on GitHub. Nothing is committed or pushed: the exact commands are
15
+ * printed instead, as with `--repo`.
16
+ */
17
+ import { spawnSync } from 'node:child_process';
18
+ import { existsSync, mkdirSync, readdirSync } from 'node:fs';
19
+ import { isAbsolute, relative, resolve } from 'node:path';
20
+ import { LOG } from '../functions/commands.js';
21
+ import { initializeGitHubRepository, resolveSettings } from './github-init.js';
22
+ import { applyGitHubSettingsWithReport } from './github-init-command.js';
23
+ export const defaultRunCommand = (command, args, options) => {
24
+ const result = spawnSync(command, [...args], { cwd: options?.cwd, encoding: 'utf8' });
25
+ if (result.error)
26
+ return { status: null, stdout: '', stderr: result.error.message };
27
+ return { status: result.status, stdout: result.stdout ?? '', stderr: result.stderr ?? '' };
28
+ };
29
+ const GITHUB_REPOSITORY = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]{1,100}$/;
30
+ /** `owner/name`, validated the way GitHub names them; throws with a usable message otherwise. */
31
+ export function parseGitHubRepository(value) {
32
+ if (typeof value !== 'string' || !GITHUB_REPOSITORY.test(value) || value.endsWith('.git')) {
33
+ throw new Error('--github needs <owner>/<name>, for example --github my-org/loan-tools');
34
+ }
35
+ const [owner, name] = value.split('/');
36
+ return { owner, name, slug: value };
37
+ }
38
+ export function githubCloneUrl(slug) {
39
+ return `https://github.com/${slug}.git`;
40
+ }
41
+ function flag(args, name) {
42
+ const value = args.flags[name];
43
+ return typeof value === 'string' ? value : undefined;
44
+ }
45
+ /** Everything that must hold before anything is created. Returns the resolved target. */
46
+ export function preflightGitHubInit({ args, target, run }) {
47
+ if (args.flags.repo !== undefined) {
48
+ throw new Error('Use --github (a new GitHub repository) or --repo (a platform git-service repository), not both.');
49
+ }
50
+ if (args.flags.template !== undefined && args.flags.template !== 'react-vite' && args.flags.template !== 'nextjs') {
51
+ throw new Error('--github scaffolds a new app; start it without a published --template.');
52
+ }
53
+ const { slug } = parseGitHubRepository(args.flags.github);
54
+ if (!flag(args, 'org')) {
55
+ throw new Error('--github needs --org <org>: the Sequence org this repository deploys for (written to .seq/github.yml).');
56
+ }
57
+ const root = resolve(target);
58
+ const inside = run('git', ['-C', nearestExisting(root), 'rev-parse', '--show-toplevel']);
59
+ if (inside.status === 0) {
60
+ throw new Error(`${target} is inside the Git checkout ${inside.stdout.trim()}. --github starts an app in its own new repository. ` +
61
+ 'To add the app to that repository instead, run init without --github; to set that checkout up for GitHub, run seq-studio repo init there.');
62
+ }
63
+ if (existsSync(root) && readdirSync(root).length > 0) {
64
+ throw new Error(`${target} exists and is not empty. --github scaffolds into a new or empty directory.`);
65
+ }
66
+ const auth = run('gh', ['auth', 'status']);
67
+ if (auth.status !== 0) {
68
+ throw new Error(auth.status === null
69
+ ? '--github needs the GitHub CLI (gh). Install it from https://cli.github.com, run gh auth login, then retry.'
70
+ : '--github needs gh to be signed in: run gh auth login, then retry.');
71
+ }
72
+ const existing = run('gh', ['repo', 'view', slug, '--json', 'name']);
73
+ if (existing.status === 0) {
74
+ throw new Error(`${slug} already exists on GitHub. Clone it and run seq-studio repo init in the clone, or pick another name.`);
75
+ }
76
+ return { slug, root };
77
+ }
78
+ function nearestExisting(path) {
79
+ let current = path;
80
+ while (!existsSync(current)) {
81
+ const parent = resolve(current, '..');
82
+ if (parent === current)
83
+ return current;
84
+ current = parent;
85
+ }
86
+ return current;
87
+ }
88
+ function shellArg(value) {
89
+ return /^[\w./:@=+-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
90
+ }
91
+ function displayPath(path) {
92
+ const fromCwd = relative(process.cwd(), path);
93
+ if (fromCwd === '')
94
+ return '.';
95
+ return fromCwd.startsWith('..') || isAbsolute(fromCwd) ? path : fromCwd;
96
+ }
97
+ /** The commit, push and connect steps after a successful `init --github`. */
98
+ export function githubNextSteps({ root, slug, settings, applied, env }) {
99
+ const dir = shellArg(displayPath(root));
100
+ const gitC = `git -C ${dir}`;
101
+ const { dev, release } = settings.branches;
102
+ const envFlag = env ? `-e ${shellArg(env)}` : '-e <env>';
103
+ const lines = [
104
+ `${LOG} ${slug} is ready but nothing is committed. Commit and push both branches:`,
105
+ ` ${gitC} add -A && ${gitC} commit -m ${shellArg(`Scaffold ${slug.split('/')[1]}`)}`,
106
+ ` ${gitC} push -u origin HEAD:${shellArg(release)} && ${gitC} push origin HEAD:${shellArg(dev)}`,
107
+ ];
108
+ if (!applied) {
109
+ lines.push(`${LOG} then apply the branch rulesets and secret scanning (needs admin on ${slug}, which its creator has):`);
110
+ lines.push(` (cd ${dir} && seq-studio repo init --apply-github)`);
111
+ }
112
+ lines.push(`${LOG} then let it deploy (${dev} → staging, ${release} → prod through Promote):`);
113
+ lines.push(` (cd ${dir} && seq-studio repo connect ${envFlag} --stage staging)`);
114
+ lines.push(` (cd ${dir} && seq-studio repo connect ${envFlag} --stage prod)`);
115
+ return lines;
116
+ }
117
+ /**
118
+ * Run the whole flow. `scaffold` writes the app into `root` (an initialized,
119
+ * empty Git checkout) and returns its exit code.
120
+ */
121
+ export async function runInitWithGitHub({ args, target, scaffold, run = defaultRunCommand, apply = applyGitHubSettingsWithReport }) {
122
+ let slug;
123
+ let root;
124
+ let settings;
125
+ try {
126
+ ;
127
+ ({ slug, root } = preflightGitHubInit({ args, target, run }));
128
+ mkdirSync(root, { recursive: true });
129
+ // Settings first: they validate --org/--dev/--release before anything else is written.
130
+ settings = await resolveSettings({
131
+ directory: root, org: flag(args, 'org'), dev: flag(args, 'dev'), release: flag(args, 'release'),
132
+ });
133
+ const init = run('git', ['init', '-b', settings.branches.release, root]);
134
+ if (init.status !== 0)
135
+ throw new Error(`git init failed: ${init.stderr.trim()}`);
136
+ }
137
+ catch (error) {
138
+ console.error(`${LOG} ${error instanceof Error ? error.message : String(error)}`);
139
+ return 1;
140
+ }
141
+ const code = await scaffold(root);
142
+ if (code !== 0) {
143
+ console.error(`${LOG} the scaffold failed, so ${slug} was not created on GitHub. Fix the error and rerun in an empty directory.`);
144
+ return code;
145
+ }
146
+ try {
147
+ const created = run('gh', ['repo', 'create', slug, '--private']);
148
+ if (created.status !== 0)
149
+ throw new Error(`gh repo create ${slug} failed: ${created.stderr.trim()}`);
150
+ console.log(`${LOG} created ${slug} on GitHub (private)`);
151
+ const origin = run('git', ['-C', root, 'remote', 'add', 'origin', githubCloneUrl(slug)]);
152
+ if (origin.status !== 0)
153
+ throw new Error(`git remote add origin failed: ${origin.stderr.trim()}`);
154
+ const reports = await initializeGitHubRepository({ directory: root, settings, write: true });
155
+ const written = reports.filter((report) => report.status === 'missing' || report.status === 'stale').map((report) => report.path);
156
+ console.log(`${LOG} wrote ${written.join(', ')} for org ${settings.org} (dev ${settings.branches.dev}, release ${settings.branches.release})`);
157
+ }
158
+ catch (error) {
159
+ console.error(`${LOG} ${error instanceof Error ? error.message : String(error)}`);
160
+ console.error(`${LOG} the app is scaffolded in ${root}; finish with gh repo create, git remote add origin and seq-studio repo init there.`);
161
+ return 1;
162
+ }
163
+ let applied = false;
164
+ if (args.flags['apply-github'] === true) {
165
+ const applyCode = await apply({ repository: slug, settings, say: (text) => process.stdout.write(text) });
166
+ if (applyCode !== 0)
167
+ return applyCode;
168
+ applied = true;
169
+ }
170
+ const env = flag(args, 'env') ?? flag(args, 'e');
171
+ for (const line of githubNextSteps({ root, slug, settings, applied, env }))
172
+ console.log(line);
173
+ return 0;
174
+ }
175
+ /** The same parsed arguments without the GitHub-only flags, for the scaffold itself. */
176
+ export function withoutGitHubFlags(args) {
177
+ const flags = { ...args.flags };
178
+ for (const name of ['github', 'org', 'dev', 'release', 'apply-github'])
179
+ delete flags[name];
180
+ return { ...args, flags };
181
+ }
@@ -1,5 +1,5 @@
1
1
  import type { ParsedArgs } from '../process/commands.js';
2
- export declare const PULLS_USAGE = "usage:\n seq-studio repos pulls list <ns>/<name> -e <env> [--state open|closed|merged] [--limit N] [--cursor <cursor>]\n seq-studio repos pulls show <ns>/<name> <number> -e <env>\n seq-studio repos pulls create <ns>/<name> --head <branch> --base <branch> --title <title> -e <env> [--body-file <path>]\n seq-studio repos pulls diff <ns>/<name> <number> -e <env> [--max-files N]\n seq-studio repos pulls merge <ns>/<name> <number> -e <env> [--method squash|merge|ff] [--message <text>] [--yes]\n seq-studio repos pulls edit <ns>/<name> <number> -e <env> [--title <title>] [--body <text> | --body-file <path>]\n seq-studio repos pulls close <ns>/<name> <number> -e <env>\n seq-studio repos pulls comment <ns>/<name> <number> -e <env> (--body <text> | --body-file <path>)\n [--path <file> --line N [--side LEFT|RIGHT] [--commit <sha>]] [--reply-to <comment-id>]\n seq-studio repos pulls comments <ns>/<name> <number> -e <env> [--limit N] [--cursor <cursor>]\n seq-studio repos pulls resolve <ns>/<name> <number> <root-comment-id> -e <env>\n seq-studio repos pulls unresolve <ns>/<name> <number> <root-comment-id> -e <env>\n seq-studio repos pulls review <ns>/<name> <number> -e <env> (--approve | --request-changes | --comment)\n [--body <text> | --body-file <path>] [--commit <sha>]\n seq-studio repos pulls reviews <ns>/<name> <number> -e <env> [--limit N] [--cursor <cursor>]\n seq-studio repos pulls checks <ns>/<name> <number> -e <env> [--head <sha>]\n\n All results are JSON (--json is accepted). Authenticate: seq-studio login --env <env>.\n create needs repository write; merge needs merge/admin authority and passing server\n review/check policy. There is no policy bypass. Review show and diff before merging.\n Merge operates on the current branch head under server policy. When repository CI\n checks the branch, merge sends the checked head and base revisions; a newer push\n makes the server refuse until checks rerun. Default merge method: squash.\n list returns one page with nextCursor; pass --cursor to continue.\n create, show and list add a web url field to each Pull (<env>/repositories/<ns>/<name>/pull/<n>).\n diff compares live base/head branches for open Pulls, recorded SHAs for terminal\n Pulls, and reports truncated when its file\n limit is reached (default 100, maximum 500).\n edit changes an open Pull's title and/or description (at least one). It needs the\n Pull's author or repository write; merged and closed Pulls cannot be edited. It\n prints the updated Pull like show.\n close needs to be the Pull's author or have repository write; it is idempotent.\n comment adds a Pull comment; --path and --line anchor it to a diff line (side RIGHT\n and the branch's current commit unless --side/--commit say otherwise), and\n --reply-to answers an existing thread. review records approve, request-changes, or\n comment against the commit the Pull's branch points at now (or --commit). checks prints the check runs,\n CI plan and runs, and merge gates (mergeability, reviews, code owners) in one object.\n resolve and unresolve require repository read access and a root comment UUID from\n comments; the server rejects replies. They return the updated comment as JSON.\n repos pull (singular) materializes files; repos pulls manages review requests.\n";
2
+ export declare const PULLS_USAGE = "usage:\n seq-studio repos pulls list <ns>/<name> -e <env> [--state open|closed|merged] [--limit N] [--cursor <cursor>]\n seq-studio repos pulls show <ns>/<name> <number> -e <env>\n seq-studio repos pulls create <ns>/<name> --head <branch> --base <branch> --title <title> -e <env> [--body-file <path>] [--type <type>]\n seq-studio repos pulls diff <ns>/<name> <number> -e <env> [--max-files N]\n seq-studio repos pulls merge <ns>/<name> <number> -e <env> [--method squash|merge|ff] [--message <text>] [--yes]\n seq-studio repos pulls edit <ns>/<name> <number> -e <env> [--title <title>] [--body <text> | --body-file <path>] [--type <type>]\n seq-studio repos pulls close <ns>/<name> <number> -e <env>\n seq-studio repos pulls comment <ns>/<name> <number> -e <env> (--body <text> | --body-file <path>)\n [--path <file> --line N [--side LEFT|RIGHT] [--commit <sha>]] [--reply-to <comment-id>]\n seq-studio repos pulls comments <ns>/<name> <number> -e <env> [--limit N] [--cursor <cursor>]\n seq-studio repos pulls resolve <ns>/<name> <number> <root-comment-id> -e <env>\n seq-studio repos pulls unresolve <ns>/<name> <number> <root-comment-id> -e <env>\n seq-studio repos pulls review <ns>/<name> <number> -e <env> (--approve | --request-changes | --comment)\n [--body <text> | --body-file <path>] [--commit <sha>]\n seq-studio repos pulls reviews <ns>/<name> <number> -e <env> [--limit N] [--cursor <cursor>]\n seq-studio repos pulls checks <ns>/<name> <number> -e <env> [--head <sha>]\n\n All results are JSON (--json is accepted). Authenticate: seq-studio login --env <env>.\n create needs repository write; merge needs merge/admin authority and passing server\n review/check policy. There is no policy bypass. Review show and diff before merging.\n Merge operates on the current branch head under server policy. When repository CI\n checks the branch, merge sends the checked head and base revisions; a newer push\n makes the server refuse until checks rerun. Default merge method: squash.\n list returns one page with nextCursor; pass --cursor to continue.\n create, show and list add a web url field to each Pull (<env>/repositories/<ns>/<name>/pull/<n>).\n diff compares live base/head branches for open Pulls, recorded SHAs for terminal\n Pulls, and reports truncated when its file\n limit is reached (default 100, maximum 500).\n Every Pull has a type: bug, performance, enhancement, feature, or chore. It is\n required to merge and feeds bug/performance/feature trend metrics. Pass --type\n on create (agents: always pick one); omit it and a classifier assigns one\n shortly after the Pull opens. edit --type corrects it.\n edit changes an open Pull's title, description, and/or type (at least one). It needs the\n Pull's author or repository write; merged and closed Pulls cannot be edited. It\n prints the updated Pull like show.\n close needs to be the Pull's author or have repository write; it is idempotent.\n comment adds a Pull comment; --path and --line anchor it to a diff line (side RIGHT\n and the branch's current commit unless --side/--commit say otherwise), and\n --reply-to answers an existing thread. review records approve, request-changes, or\n comment against the commit the Pull's branch points at now (or --commit). checks prints the check runs,\n CI plan and runs, and merge gates (mergeability, reviews, code owners) in one object.\n resolve and unresolve require repository read access and a root comment UUID from\n comments; the server rejects replies. They return the updated comment as JSON.\n repos pull (singular) materializes files; repos pulls manages review requests.\n";
3
3
  /** Only the revisions this command needs from GET .../pulls/<n>/ci. */
4
4
  interface PullCiStatus {
5
5
  plan?: {
@@ -17,6 +17,9 @@ export declare function checkedMergeRevision({ fetchStatus }: {
17
17
  expectedHeadSha: string;
18
18
  expectedBaseSha: string;
19
19
  } | Record<string, never>>;
20
+ /** Mirrors the server's Pull types (atlas git-service `pull-types.ts`); the server is the authority. */
21
+ export declare const PULL_TYPES: readonly ["bug", "performance", "enhancement", "feature", "chore"];
22
+ export declare function pullTypeFlag(args: ParsedArgs): string | undefined;
20
23
  /** Atlas web URL for a Pull: <env origin>/repositories/<ns>/<name>/pull/<number>. */
21
24
  export declare function pullWebUrl({ baseUrl, repoPath, number }: {
22
25
  baseUrl: string;
@@ -35,6 +38,7 @@ export declare function commentBody(args: ParsedArgs): Promise<object>;
35
38
  export declare function editBody(args: ParsedArgs): Promise<{
36
39
  title?: string;
37
40
  body?: string;
41
+ type?: string;
38
42
  }>;
39
43
  export declare function reviewInput(args: ParsedArgs): Promise<{
40
44
  state: string;