@sequenceholdings/studio-cli 0.7.2 → 0.9.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.
- package/README.md +414 -55
- package/dist/access/commands.d.ts +1 -1
- package/dist/access/commands.js +102 -55
- package/dist/access/custom-role-hosts.d.ts +3 -0
- package/dist/access/custom-role-hosts.js +88 -0
- package/dist/access/group-rosters.d.ts +6 -0
- package/dist/access/group-rosters.js +33 -0
- package/dist/access/host-contract.d.ts +55 -0
- package/dist/access/host-contract.js +33 -0
- package/dist/access/hosts.d.ts +4 -0
- package/dist/access/hosts.js +60 -0
- package/dist/access/principal.d.ts +16 -0
- package/dist/access/principal.js +36 -0
- package/dist/access/roles.d.ts +18 -0
- package/dist/access/roles.js +89 -0
- package/dist/access/tier-hosts.d.ts +12 -0
- package/dist/access/tier-hosts.js +206 -0
- package/dist/agents/commands.d.ts +1 -1
- package/dist/agents/commands.js +76 -16
- package/dist/agents/scaffold.js +8 -3
- package/dist/app/commands.js +37 -12
- package/dist/app/manifest.d.ts +2 -2
- package/dist/app/official-source.d.ts +4 -2
- package/dist/app/official-source.js +6 -4
- package/dist/app/readme.js +2 -2
- package/dist/app/repository-index.d.ts +6 -0
- package/dist/app/repository-index.js +2 -2
- package/dist/app/workspace-model.js +4 -0
- package/dist/app/workspace-scaffold.js +5 -3
- package/dist/app/workspace.d.ts +2 -0
- package/dist/app/workspace.js +1 -1
- package/dist/artifact/delegate.js +26 -3
- package/dist/artifact/sandbox.js +2 -1
- package/dist/atlas-client.d.ts +15 -8
- package/dist/atlas-client.js +140 -64
- package/dist/bin.js +9 -1
- package/dist/cli-errors.js +4 -0
- package/dist/command-contract.d.ts +8 -2
- package/dist/command-contract.js +3 -2
- package/dist/command-help.d.ts +8 -6
- package/dist/command-help.js +65 -14
- package/dist/env-flags.d.ts +7 -0
- package/dist/env-flags.js +23 -0
- package/dist/functions/commands.js +66 -11
- package/dist/functions/manifest.d.ts +5 -0
- package/dist/functions/manifest.js +44 -23
- package/dist/functions/service-account-guidance.d.ts +21 -0
- package/dist/functions/service-account-guidance.js +62 -0
- package/dist/functions/workspace.d.ts +11 -0
- package/dist/functions/workspace.js +52 -0
- package/dist/machine-output.d.ts +7 -0
- package/dist/machine-output.js +56 -0
- package/dist/main.d.ts +2 -1
- package/dist/main.js +32 -4
- package/dist/orm/delegate.js +49 -6
- package/dist/orm/execute.js +11 -5
- package/dist/orm/failures.d.ts +32 -0
- package/dist/orm/failures.js +75 -0
- package/dist/orm/read.js +3 -3
- package/dist/orm/version-guard.d.ts +3 -0
- package/dist/orm/version-guard.js +63 -0
- package/dist/pipeline/commands.js +4 -1
- package/dist/principals/commands.d.ts +3 -0
- package/dist/principals/commands.js +124 -0
- package/dist/process/commands.js +9 -3
- package/dist/process/human-input-probe.d.ts +23 -0
- package/dist/process/human-input-probe.js +118 -0
- package/dist/process/lint.d.ts +2 -0
- package/dist/process/lint.js +10 -0
- package/dist/process/run-steps.d.ts +112 -0
- package/dist/process/run-steps.js +123 -0
- package/dist/process/runs.d.ts +4 -3
- package/dist/process/runs.js +69 -21
- package/dist/release-age.d.ts +1 -1
- package/dist/release-age.js +1 -0
- package/dist/repos/commands.d.ts +57 -0
- package/dist/repos/commands.js +83 -15
- package/dist/repos/init-repo.d.ts +45 -0
- package/dist/repos/init-repo.js +257 -0
- package/dist/repos/primitive-declaration.d.ts +43 -0
- package/dist/repos/primitive-declaration.js +212 -0
- package/dist/sandbox-unpushed-warning.d.ts +23 -0
- package/dist/sandbox-unpushed-warning.js +86 -0
- package/dist/service-accounts/commands.js +15 -3
- package/dist/templates/commands.d.ts +14 -2
- package/dist/templates/commands.js +70 -16
- package/dist/templates/process/pnpm-workspace.yaml +1 -0
- package/package.json +15 -12
- package/templates/process/pnpm-workspace.yaml +1 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `--repo <namespace>/<name>` on the init commands (`init`, `orm init`,
|
|
3
|
+
* `functions init`, `artifact init`, `agents init`): put the scaffold in a
|
|
4
|
+
* platform git-service repository's working tree from the start, so the work
|
|
5
|
+
* survives a lost laptop or a reset agent sandbox once it is pushed.
|
|
6
|
+
*
|
|
7
|
+
* The repository is created when it does not exist yet. Then either:
|
|
8
|
+
* - clone mode: the target is not inside a Git checkout, so the repository
|
|
9
|
+
* is cloned into the (absent or empty) target and the scaffold lands in
|
|
10
|
+
* the clone; or
|
|
11
|
+
* - origin mode: the target is inside a Git checkout, so the repository
|
|
12
|
+
* becomes that checkout's `origin` (an existing, different origin is
|
|
13
|
+
* refused) and the scaffold lands in that working tree.
|
|
14
|
+
*
|
|
15
|
+
* Nothing is committed or pushed: the init prints the exact commands instead.
|
|
16
|
+
* Every local refusal happens before the repository is created.
|
|
17
|
+
*/
|
|
18
|
+
import { execFile } from 'node:child_process';
|
|
19
|
+
import { existsSync, readdirSync } from 'node:fs';
|
|
20
|
+
import { basename, dirname, isAbsolute, relative, resolve } from 'node:path';
|
|
21
|
+
import { promisify } from 'node:util';
|
|
22
|
+
import { resolveRepo } from '@sequenceholdings/artifact-studio/git-service-client';
|
|
23
|
+
import { AtlasApiError } from '../atlas-client.js';
|
|
24
|
+
import { printCliError } from '../cli-errors.js';
|
|
25
|
+
import { clientOptions, LOG } from '../functions/commands.js';
|
|
26
|
+
import { isSandboxTokenMode } from '../sandbox-auth.js';
|
|
27
|
+
import { assertGitCheckoutAuth, cloneRepoById, cloneUrl, createRepo, normalizeCloneUrl, parseRepoPath, reposContext, stringFlag, } from './commands.js';
|
|
28
|
+
import { configureGitLogin } from './git-credential.js';
|
|
29
|
+
const exec = promisify(execFile);
|
|
30
|
+
const GIT_TIMEOUT_MS = 10_000;
|
|
31
|
+
async function git(args) {
|
|
32
|
+
const { stdout } = await exec('git', args, { encoding: 'utf8', timeout: GIT_TIMEOUT_MS });
|
|
33
|
+
return stdout.trim();
|
|
34
|
+
}
|
|
35
|
+
function nearestExistingDirectory(path) {
|
|
36
|
+
let current = path;
|
|
37
|
+
while (!existsSync(current)) {
|
|
38
|
+
const parent = dirname(current);
|
|
39
|
+
if (parent === current)
|
|
40
|
+
return current;
|
|
41
|
+
current = parent;
|
|
42
|
+
}
|
|
43
|
+
return current;
|
|
44
|
+
}
|
|
45
|
+
/** The Git work tree containing `path` (or its nearest existing ancestor), or null. */
|
|
46
|
+
async function gitWorkTreeRoot(path) {
|
|
47
|
+
try {
|
|
48
|
+
return await git(['-C', nearestExistingDirectory(path), 'rev-parse', '--show-toplevel']);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async function originUrl(root) {
|
|
55
|
+
try {
|
|
56
|
+
return await git(['-C', root, 'remote', 'get-url', 'origin']);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** Compare remotes without echoing them: an old checkout's URL may embed credentials. */
|
|
63
|
+
function sameRemote(a, b) {
|
|
64
|
+
const normalize = (url) => url.trim().replace(/\/+$/, '').replace(/\.git$/, '').replace(/\/git$/, '');
|
|
65
|
+
return normalize(a) === normalize(b);
|
|
66
|
+
}
|
|
67
|
+
export async function inspectLocalCheckout(targetDir) {
|
|
68
|
+
const root = await gitWorkTreeRoot(targetDir);
|
|
69
|
+
if (root)
|
|
70
|
+
return { mode: 'origin', root, origin: await originUrl(root) };
|
|
71
|
+
if (existsSync(targetDir) && readdirSync(targetDir).length > 0) {
|
|
72
|
+
throw new Error(`${targetDir} exists, is not empty, and is not a Git checkout. --repo clones into a new or empty ` +
|
|
73
|
+
'directory, or sets origin on an existing checkout.');
|
|
74
|
+
}
|
|
75
|
+
return { mode: 'clone', targetDir };
|
|
76
|
+
}
|
|
77
|
+
/** Only "this repository does not exist (for you)" returns null; HTTP failures propagate. */
|
|
78
|
+
async function findRepo({ ctx, namespace, name }) {
|
|
79
|
+
try {
|
|
80
|
+
return await resolveRepo({ ...clientOptions(ctx), namespace, name });
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (typeof Reflect.get(Object(error), 'status') === 'number')
|
|
84
|
+
throw error;
|
|
85
|
+
return null;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
async function findOrCreateRepo({ ctx, namespace, name, empty }) {
|
|
89
|
+
const existing = await findRepo({ ctx, namespace, name });
|
|
90
|
+
if (existing)
|
|
91
|
+
return { ...existing, created: false };
|
|
92
|
+
try {
|
|
93
|
+
// A checkout with its own history needs an empty repository to push into;
|
|
94
|
+
// a clone starts from Atlas's seed (README + .seq/identity.json receipt).
|
|
95
|
+
const repo = await createRepo({ ctx, namespace, name, ...(empty ? { gitBackend: 'walgit' } : {}) });
|
|
96
|
+
console.log(`${LOG} created ${namespace}/${name} on ${ctx.env.name}${empty ? ' (empty)' : ''}`);
|
|
97
|
+
return { id: repo.id, defaultBranch: repo.defaultBranch, created: true };
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
// Lost a race with another creator: use the repository that now exists.
|
|
101
|
+
if (error instanceof AtlasApiError && error.status === 409) {
|
|
102
|
+
const raced = await resolveRepo({ ...clientOptions(ctx), namespace, name });
|
|
103
|
+
return { ...raced, created: false };
|
|
104
|
+
}
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The origin URL the credential helper must be bound to. Git selects a
|
|
110
|
+
* `credential.<url>.helper` by the URL the remote actually uses, and the
|
|
111
|
+
* helper answers only for that exact path (useHttpPath), so a kept origin is
|
|
112
|
+
* bound as is: `…/repos/<id>.git` and `…/repos/<id>/git` are different URLs to
|
|
113
|
+
* Git. A missing origin is added as the canonical clone URL. A kept origin
|
|
114
|
+
* that differs from its validated form only by a trailing slash is rewritten
|
|
115
|
+
* to that form, since the helper never answers for a trailing-slash path.
|
|
116
|
+
*/
|
|
117
|
+
async function originForLogin({ ctx, root, origin, repoId }) {
|
|
118
|
+
if (origin === null) {
|
|
119
|
+
const url = cloneUrl(ctx, repoId);
|
|
120
|
+
await git(['-C', root, 'remote', 'add', 'origin', url]);
|
|
121
|
+
return url;
|
|
122
|
+
}
|
|
123
|
+
let normalized;
|
|
124
|
+
try {
|
|
125
|
+
normalized = normalizeCloneUrl(origin, ctx.env);
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
const detail = error instanceof Error ? error.message.replace(/^--url /, '') : String(error);
|
|
129
|
+
throw new Error(`The origin remote of ${root} is not a usable git-service clone URL: ${detail}`);
|
|
130
|
+
}
|
|
131
|
+
if (normalized !== origin)
|
|
132
|
+
await git(['-C', root, 'remote', 'set-url', 'origin', normalized]);
|
|
133
|
+
return normalized;
|
|
134
|
+
}
|
|
135
|
+
/** Quote a printed shell argument only when it needs it. */
|
|
136
|
+
function shellArg(value) {
|
|
137
|
+
return /^[\w./:@=+-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
|
|
138
|
+
}
|
|
139
|
+
function displayPath(path) {
|
|
140
|
+
const fromCwd = relative(process.cwd(), path);
|
|
141
|
+
if (fromCwd === '')
|
|
142
|
+
return '.';
|
|
143
|
+
return fromCwd.startsWith('..') || isAbsolute(fromCwd) ? path : fromCwd;
|
|
144
|
+
}
|
|
145
|
+
export function persistNextSteps({ root, repoPath, envName, defaultBranch, setup }) {
|
|
146
|
+
const dir = shellArg(displayPath(root));
|
|
147
|
+
const gitC = `git -C ${dir}`;
|
|
148
|
+
const lines = [`${LOG} the scaffold is in ${repoPath}'s working tree but not committed. Commit and push it:`];
|
|
149
|
+
if (setup === 'origin-created') {
|
|
150
|
+
// An empty repository has no seed commit, so install its identity receipt here.
|
|
151
|
+
const env = isSandboxTokenMode() ? '' : ` -e ${shellArg(envName)}`;
|
|
152
|
+
lines.push(` seq-studio repos identity ${repoPath}${env} --write --dir ${dir}`);
|
|
153
|
+
}
|
|
154
|
+
const commit = `${gitC} add -A && ${gitC} commit -m ${shellArg(`Scaffold ${basename(root)}`)}`;
|
|
155
|
+
if (setup === 'origin-added') {
|
|
156
|
+
// Commit first: a rebase refuses a working tree the scaffold left with unstaged changes.
|
|
157
|
+
lines.push(` ${commit}`);
|
|
158
|
+
lines.push(` ${gitC} pull --rebase origin ${shellArg(defaultBranch)} # only if ${repoPath} already has commits`);
|
|
159
|
+
lines.push(` ${gitC} push -u origin HEAD`);
|
|
160
|
+
return lines;
|
|
161
|
+
}
|
|
162
|
+
const target = setup === 'origin-created' ? `HEAD:${shellArg(defaultBranch)}` : 'HEAD';
|
|
163
|
+
lines.push(` ${commit} && ${gitC} push -u origin ${target}`);
|
|
164
|
+
return lines;
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Prepare the repository checkout for `target`, run `scaffold` in it, then
|
|
168
|
+
* print how to commit and push. Returns the scaffold's exit code (1 when the
|
|
169
|
+
* repository could not be prepared).
|
|
170
|
+
*/
|
|
171
|
+
export async function runInitWithRepo({ args, target, scaffold, deps = {} }) {
|
|
172
|
+
let repoPath;
|
|
173
|
+
let root;
|
|
174
|
+
let setup;
|
|
175
|
+
let defaultBranch;
|
|
176
|
+
let envName;
|
|
177
|
+
try {
|
|
178
|
+
const { namespace, name } = parseRepoPath(stringFlag(args.flags, 'repo'));
|
|
179
|
+
repoPath = `${namespace}/${name}`;
|
|
180
|
+
const checkout = await inspectLocalCheckout(resolve(target));
|
|
181
|
+
const ctx = await reposContext(args);
|
|
182
|
+
envName = ctx.env.name;
|
|
183
|
+
if (checkout.mode === 'origin' && checkout.origin !== null) {
|
|
184
|
+
const existing = await findRepo({ ctx, namespace, name });
|
|
185
|
+
if (!existing || !sameRemote(checkout.origin, cloneUrl(ctx, existing.id))) {
|
|
186
|
+
throw new Error(`${checkout.root} already has an origin remote that is not ${repoPath} on ${ctx.env.name}. ` +
|
|
187
|
+
`Run the init outside that checkout to clone ${repoPath}, or drop --repo.`);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
if (checkout.mode === 'clone')
|
|
191
|
+
assertGitCheckoutAuth(ctx);
|
|
192
|
+
const repo = await findOrCreateRepo({ ctx, namespace, name, empty: checkout.mode === 'origin' });
|
|
193
|
+
defaultBranch = repo.defaultBranch;
|
|
194
|
+
if (checkout.mode === 'clone') {
|
|
195
|
+
await cloneRepoById({ ctx, repoId: repo.id, destDir: checkout.targetDir, gitClone: deps.gitClone });
|
|
196
|
+
root = checkout.targetDir;
|
|
197
|
+
setup = 'cloned';
|
|
198
|
+
console.log(`${LOG} cloned ${repoPath} → ${root}`);
|
|
199
|
+
}
|
|
200
|
+
else {
|
|
201
|
+
root = checkout.root;
|
|
202
|
+
const url = await originForLogin({ ctx, root, origin: checkout.origin, repoId: repo.id });
|
|
203
|
+
await configureGitLogin({ destDir: root, envName: ctx.env.name, cloneUrl: url });
|
|
204
|
+
setup = checkout.origin !== null ? 'origin-kept' : repo.created ? 'origin-created' : 'origin-added';
|
|
205
|
+
console.log(`${LOG} ${checkout.origin === null ? 'set origin of' : 'using origin of'} ${root} → ${repoPath}`);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
printCliError(error);
|
|
210
|
+
return 1;
|
|
211
|
+
}
|
|
212
|
+
const code = await scaffold();
|
|
213
|
+
if (code !== 0) {
|
|
214
|
+
console.error(`${LOG} ${root} is a checkout of ${repoPath}; commit and push what is there once the error is fixed.`);
|
|
215
|
+
return code;
|
|
216
|
+
}
|
|
217
|
+
for (const line of persistNextSteps({ root, repoPath, envName, defaultBranch, setup }))
|
|
218
|
+
console.log(line);
|
|
219
|
+
return code;
|
|
220
|
+
}
|
|
221
|
+
/** The same parsed arguments with `--repo` removed, for the scaffold itself. */
|
|
222
|
+
export function withoutRepoFlag(args) {
|
|
223
|
+
const flags = { ...args.flags };
|
|
224
|
+
delete flags.repo;
|
|
225
|
+
return { ...args, flags };
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* For delegated init commands that forward raw argv: split `--repo <v>` /
|
|
229
|
+
* `--repo=<v>` off. `repo` is undefined when absent and `true` when given
|
|
230
|
+
* without a value (so the caller can report it like any other flag).
|
|
231
|
+
*/
|
|
232
|
+
export function extractRepoFlag(argv) {
|
|
233
|
+
const rest = [];
|
|
234
|
+
let repo;
|
|
235
|
+
for (let i = 0; i < argv.length; i++) {
|
|
236
|
+
const arg = argv[i];
|
|
237
|
+
if (arg === undefined)
|
|
238
|
+
continue;
|
|
239
|
+
if (arg.startsWith('--repo=')) {
|
|
240
|
+
repo = arg.slice('--repo='.length) || true;
|
|
241
|
+
}
|
|
242
|
+
else if (arg === '--repo') {
|
|
243
|
+
const next = argv[i + 1];
|
|
244
|
+
if (next !== undefined && !next.startsWith('-')) {
|
|
245
|
+
repo = next;
|
|
246
|
+
i += 1;
|
|
247
|
+
}
|
|
248
|
+
else {
|
|
249
|
+
repo = true;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
else {
|
|
253
|
+
rest.push(arg);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return { repo, rest };
|
|
257
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
export type StandalonePrimitiveKind = 'orm' | 'function' | 'artifact';
|
|
2
|
+
export interface ResourceEntry {
|
|
3
|
+
id: string;
|
|
4
|
+
kind: StandalonePrimitiveKind;
|
|
5
|
+
path: string;
|
|
6
|
+
namespace?: string;
|
|
7
|
+
slug?: string;
|
|
8
|
+
project_id?: string;
|
|
9
|
+
}
|
|
10
|
+
export type ResourceDeclarationPlan = {
|
|
11
|
+
action: 'write';
|
|
12
|
+
indexPath: string;
|
|
13
|
+
content: string;
|
|
14
|
+
entry: ResourceEntry;
|
|
15
|
+
created: boolean;
|
|
16
|
+
} | {
|
|
17
|
+
action: 'skip';
|
|
18
|
+
reason?: string;
|
|
19
|
+
};
|
|
20
|
+
/** Plan the index change for a primitive just scaffolded at `dir`. */
|
|
21
|
+
export declare function planResourceDeclaration({ kind, dir }: {
|
|
22
|
+
kind: StandalonePrimitiveKind;
|
|
23
|
+
dir: string;
|
|
24
|
+
}): Promise<ResourceDeclarationPlan>;
|
|
25
|
+
/**
|
|
26
|
+
* After a successful standalone init, declare the scaffold for repository CI.
|
|
27
|
+
* Never changes the init's exit code: a declaration problem is a warning with
|
|
28
|
+
* the manual fix.
|
|
29
|
+
*/
|
|
30
|
+
export declare function declareScaffoldedPrimitive({ kind, dir }: {
|
|
31
|
+
kind: StandalonePrimitiveKind;
|
|
32
|
+
dir: string;
|
|
33
|
+
}): Promise<void>;
|
|
34
|
+
/**
|
|
35
|
+
* Run a standalone init (`argv` is everything after `init`), then declare its
|
|
36
|
+
* scaffold. `defaultDir` is where the init scaffolds without a positional.
|
|
37
|
+
*/
|
|
38
|
+
export declare function runStandaloneInit({ kind, argv, defaultDir, run }: {
|
|
39
|
+
kind: StandalonePrimitiveKind;
|
|
40
|
+
argv: readonly string[];
|
|
41
|
+
defaultDir?: string;
|
|
42
|
+
run: () => Promise<number>;
|
|
43
|
+
}): Promise<number>;
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Declare a primitive scaffolded on its own (`orm init`, `functions init`,
|
|
3
|
+
* `artifact init`) in its git-service repository's `.seq/repository.yml`, as a
|
|
4
|
+
* `resources` entry, so repository CI checks and deploys it. Without one, CI
|
|
5
|
+
* fails `undeclared-manifest` on the scaffold's manifest.
|
|
6
|
+
*
|
|
7
|
+
* Only git-service checkouts are touched (an origin under
|
|
8
|
+
* `/api/git-service/repos/`, or an existing index): other repositories have no
|
|
9
|
+
* repository CI to satisfy. A primitive inside a declared application belongs
|
|
10
|
+
* in that application's manifest (`seq-studio add`), never in `resources`.
|
|
11
|
+
*/
|
|
12
|
+
import { execFile } from 'node:child_process';
|
|
13
|
+
import { existsSync } from 'node:fs';
|
|
14
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
15
|
+
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
|
|
16
|
+
import { promisify } from 'node:util';
|
|
17
|
+
import { Document, isSeq, parseDocument } from 'yaml';
|
|
18
|
+
import { z } from 'zod';
|
|
19
|
+
import { parseArgs } from '../argv.js';
|
|
20
|
+
import { APP_MANIFEST_FILENAME } from '../app/manifest.js';
|
|
21
|
+
import { primitiveIdFor } from '../app/primitive-ids.js';
|
|
22
|
+
import { findGitRoot, REPOSITORY_INDEX_PATH, under } from '../app/repository-index.js';
|
|
23
|
+
import { LOG } from '../functions/commands.js';
|
|
24
|
+
const exec = promisify(execFile);
|
|
25
|
+
const indexSchema = z.looseObject({
|
|
26
|
+
schema_version: z.literal(1),
|
|
27
|
+
applications: z.array(z.looseObject({ path: z.string().min(1) })).nullish(),
|
|
28
|
+
resources: z.array(z.looseObject({
|
|
29
|
+
id: z.string().min(1),
|
|
30
|
+
path: z.string().min(1),
|
|
31
|
+
kind: z.string().optional(),
|
|
32
|
+
namespace: z.string().optional(),
|
|
33
|
+
slug: z.string().optional(),
|
|
34
|
+
project_id: z.string().optional(),
|
|
35
|
+
name: z.string().optional(),
|
|
36
|
+
})).nullish(),
|
|
37
|
+
ignore: z.array(z.string().min(1)).nullish(),
|
|
38
|
+
});
|
|
39
|
+
const IDENTITY_FIELD = {
|
|
40
|
+
orm: 'the namespace in sequence.config.ts',
|
|
41
|
+
function: 'function.id in managed-function.yml',
|
|
42
|
+
artifact: 'artifact.project_id in artifact.bundle.yml',
|
|
43
|
+
};
|
|
44
|
+
const NEW_INDEX_HEADER = '# Repository CI checks every application and resource listed here and deploys it when changes merge to main.\n';
|
|
45
|
+
const GIT_SERVICE_ORIGIN = /\/api\/git-service\/repos\/[^/]+(?:\/git|\.git)?\/?$/;
|
|
46
|
+
async function hasGitServiceOrigin(gitRoot) {
|
|
47
|
+
try {
|
|
48
|
+
const { stdout } = await exec('git', ['-C', gitRoot, 'remote', 'get-url', 'origin'], { encoding: 'utf8', timeout: 10_000 });
|
|
49
|
+
return GIT_SERVICE_ORIGIN.test(stdout.trim());
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
async function readYaml(path) {
|
|
56
|
+
if (!existsSync(path))
|
|
57
|
+
return undefined;
|
|
58
|
+
try {
|
|
59
|
+
return parseDocument(await readFile(path, 'utf8')).toJS();
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function stringAt(value, ...keys) {
|
|
66
|
+
let current = value;
|
|
67
|
+
for (const key of keys)
|
|
68
|
+
current = current && typeof current === 'object' ? Reflect.get(current, key) : undefined;
|
|
69
|
+
return typeof current === 'string' && current.length > 0 ? current : undefined;
|
|
70
|
+
}
|
|
71
|
+
/** The deployed identity the scaffold wrote, read as data (never imported). */
|
|
72
|
+
async function readIdentity({ kind, dir }) {
|
|
73
|
+
switch (kind) {
|
|
74
|
+
case 'function': {
|
|
75
|
+
const slug = stringAt(await readYaml(join(dir, 'managed-function.yml')), 'function', 'id');
|
|
76
|
+
return slug ? { id: slug, slug } : null;
|
|
77
|
+
}
|
|
78
|
+
case 'artifact': {
|
|
79
|
+
const projectId = stringAt(await readYaml(join(dir, 'artifact.bundle.yml')), 'artifact', 'project_id');
|
|
80
|
+
return projectId ? { id: primitiveIdFor({ kind: 'artifact', name: projectId }), project_id: projectId } : null;
|
|
81
|
+
}
|
|
82
|
+
case 'orm': {
|
|
83
|
+
const config = join(dir, 'sequence.config.ts');
|
|
84
|
+
const namespace = existsSync(config)
|
|
85
|
+
? /\bnamespace:\s*['"]([a-z][a-z0-9_]*)['"]/.exec(await readFile(config, 'utf8'))?.[1]
|
|
86
|
+
: undefined;
|
|
87
|
+
return namespace ? { id: primitiveIdFor({ kind: 'orm', name: namespace }), namespace } : null;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
/** The deployed identity repository CI compares (its `resourceIdentity`), per kind. */
|
|
92
|
+
function deployedIdentity(resource) {
|
|
93
|
+
return resource.namespace ?? resource.slug ?? resource.project_id ?? resource.name ?? resource.id;
|
|
94
|
+
}
|
|
95
|
+
function uniqueId(id, taken) {
|
|
96
|
+
if (!taken.has(id))
|
|
97
|
+
return id;
|
|
98
|
+
for (let n = 2;; n++)
|
|
99
|
+
if (!taken.has(`${id}-${n}`))
|
|
100
|
+
return `${id}-${n}`;
|
|
101
|
+
}
|
|
102
|
+
/** The existing index (with its document, to edit in place), none, or why it cannot be edited. */
|
|
103
|
+
async function readIndex({ indexPath, path }) {
|
|
104
|
+
if (!existsSync(indexPath))
|
|
105
|
+
return null;
|
|
106
|
+
const document = parseDocument(await readFile(indexPath, 'utf8'));
|
|
107
|
+
if (document.errors.length > 0)
|
|
108
|
+
return { reason: `${REPOSITORY_INDEX_PATH} is not valid YAML; declare ${path} under resources by hand` };
|
|
109
|
+
const parsed = indexSchema.safeParse(document.toJS());
|
|
110
|
+
if (!parsed.success) {
|
|
111
|
+
return { reason: `${REPOSITORY_INDEX_PATH} is not a schema_version 1 repository index; declare ${path} under resources by hand` };
|
|
112
|
+
}
|
|
113
|
+
return { document, index: parsed.data };
|
|
114
|
+
}
|
|
115
|
+
/** Why `path` must not become a resource, or null when it can. */
|
|
116
|
+
function conflict({ path, gitRoot, index }) {
|
|
117
|
+
const applications = index
|
|
118
|
+
? (index.applications ?? []).map((application) => application.path)
|
|
119
|
+
: existsSync(join(gitRoot, APP_MANIFEST_FILENAME)) ? ['.'] : [];
|
|
120
|
+
const application = applications.find((root) => under({ path, root }));
|
|
121
|
+
if (application !== undefined) {
|
|
122
|
+
return `${path} is inside the application at ${application}; add it to that application's ${APP_MANIFEST_FILENAME} (seq-studio add) so repository CI checks it`;
|
|
123
|
+
}
|
|
124
|
+
const overlap = (index?.resources ?? []).find((resource) => resource.path !== path &&
|
|
125
|
+
(under({ path, root: resource.path }) || under({ path: resource.path, root: path })));
|
|
126
|
+
if (overlap !== undefined)
|
|
127
|
+
return `${path} overlaps the declared resource ${overlap.id} at ${overlap.path}; move one so their roots are separate`;
|
|
128
|
+
const ignored = (index?.ignore ?? []).find((root) => under({ path, root }) || under({ path: root, root: path }));
|
|
129
|
+
if (ignored !== undefined)
|
|
130
|
+
return `${REPOSITORY_INDEX_PATH} ignores ${ignored}, so repository CI leaves ${path} unmanaged`;
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
/** Plan the index change for a primitive just scaffolded at `dir`. */
|
|
134
|
+
export async function planResourceDeclaration({ kind, dir }) {
|
|
135
|
+
const gitRoot = findGitRoot(dir);
|
|
136
|
+
if (gitRoot === null)
|
|
137
|
+
return { action: 'skip' };
|
|
138
|
+
const path = relative(gitRoot, resolve(dir)).split(sep).join('/') || '.';
|
|
139
|
+
if (path.startsWith('..'))
|
|
140
|
+
return { action: 'skip' };
|
|
141
|
+
const indexPath = join(gitRoot, REPOSITORY_INDEX_PATH);
|
|
142
|
+
const existing = await readIndex({ indexPath, path });
|
|
143
|
+
if (existing && 'reason' in existing)
|
|
144
|
+
return { action: 'skip', reason: existing.reason };
|
|
145
|
+
if (!existing && !(await hasGitServiceOrigin(gitRoot)))
|
|
146
|
+
return { action: 'skip' };
|
|
147
|
+
const resources = existing?.index.resources ?? [];
|
|
148
|
+
if (resources.some((resource) => resource.path === path))
|
|
149
|
+
return { action: 'skip' };
|
|
150
|
+
const reason = conflict({ path, gitRoot, index: existing?.index });
|
|
151
|
+
if (reason !== null)
|
|
152
|
+
return { action: 'skip', reason };
|
|
153
|
+
const identity = await readIdentity({ kind, dir });
|
|
154
|
+
if (!identity?.id)
|
|
155
|
+
return { action: 'skip', reason: `could not read the ${kind} identity in ${path}; declare it under resources in ${REPOSITORY_INDEX_PATH} by hand` };
|
|
156
|
+
const { id, ...fields } = identity;
|
|
157
|
+
const entry = { id: uniqueId(id, new Set(resources.map((resource) => resource.id))), kind, path, ...fields };
|
|
158
|
+
const twin = resources.find((resource) => resource.kind === kind && deployedIdentity(resource) === deployedIdentity(entry));
|
|
159
|
+
if (twin !== undefined) {
|
|
160
|
+
return {
|
|
161
|
+
action: 'skip',
|
|
162
|
+
reason: `${path} deploys the same ${kind} "${deployedIdentity(entry)}" as the declared resource ${twin.id} at ${twin.path}; ` +
|
|
163
|
+
`rename one (${IDENTITY_FIELD[kind]}) and declare it under resources in ${REPOSITORY_INDEX_PATH}`,
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
if (!existing) {
|
|
167
|
+
const fresh = new Document({ schema_version: 1, resources: [entry] });
|
|
168
|
+
return { action: 'write', indexPath, content: `${NEW_INDEX_HEADER}${fresh.toString()}`, entry, created: true };
|
|
169
|
+
}
|
|
170
|
+
const { document } = existing;
|
|
171
|
+
const list = document.get('resources');
|
|
172
|
+
if (isSeq(list))
|
|
173
|
+
list.add(document.createNode(entry));
|
|
174
|
+
else
|
|
175
|
+
document.set('resources', [entry]);
|
|
176
|
+
return { action: 'write', indexPath, content: document.toString(), entry, created: false };
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* After a successful standalone init, declare the scaffold for repository CI.
|
|
180
|
+
* Never changes the init's exit code: a declaration problem is a warning with
|
|
181
|
+
* the manual fix.
|
|
182
|
+
*/
|
|
183
|
+
export async function declareScaffoldedPrimitive({ kind, dir }) {
|
|
184
|
+
try {
|
|
185
|
+
const plan = await planResourceDeclaration({ kind, dir });
|
|
186
|
+
if (plan.action === 'skip') {
|
|
187
|
+
if (plan.reason)
|
|
188
|
+
console.error(`${LOG} not declared for repository CI: ${plan.reason}`);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
await mkdir(dirname(plan.indexPath), { recursive: true });
|
|
192
|
+
await writeFile(plan.indexPath, plan.content, 'utf8');
|
|
193
|
+
console.log(`${LOG} ${plan.created ? 'created' : 'updated'} ${REPOSITORY_INDEX_PATH}: declared ${kind} "${plan.entry.id}" at ${plan.entry.path} ` +
|
|
194
|
+
'so repository CI checks and deploys it; commit it with the scaffold');
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
console.error(`${LOG} could not update ${REPOSITORY_INDEX_PATH} for ${basename(dir)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
/**
|
|
201
|
+
* Run a standalone init (`argv` is everything after `init`), then declare its
|
|
202
|
+
* scaffold. `defaultDir` is where the init scaffolds without a positional.
|
|
203
|
+
*/
|
|
204
|
+
export async function runStandaloneInit({ kind, argv, defaultDir, run }) {
|
|
205
|
+
const code = await run();
|
|
206
|
+
if (code !== 0 || argv.includes('--help') || argv.includes('-h'))
|
|
207
|
+
return code;
|
|
208
|
+
const target = parseArgs([...argv]).positional[0] ?? defaultDir;
|
|
209
|
+
if (target !== undefined)
|
|
210
|
+
await declareScaffoldedPrimitive({ kind, dir: resolve(target) });
|
|
211
|
+
return code;
|
|
212
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Runs `git <args>` in `cwd` and resolves its stdout; rejects on any failure. */
|
|
2
|
+
export type GitRunner = (args: {
|
|
3
|
+
cwd: string;
|
|
4
|
+
args: string[];
|
|
5
|
+
}) => Promise<string>;
|
|
6
|
+
export declare const runGitQuietly: GitRunner;
|
|
7
|
+
interface CheckoutState {
|
|
8
|
+
dirty: boolean;
|
|
9
|
+
ahead: number;
|
|
10
|
+
hasUpstream: boolean;
|
|
11
|
+
hasCommits: boolean;
|
|
12
|
+
}
|
|
13
|
+
/** Parse `git status --porcelain=v2 --branch`. */
|
|
14
|
+
export declare function parseStatus(output: string): CheckoutState;
|
|
15
|
+
/** The warning for `cwd`, or null when there is nothing to warn about (or anything fails). */
|
|
16
|
+
export declare function unpushedWorkWarning({ cwd, env, git, }?: {
|
|
17
|
+
cwd?: string;
|
|
18
|
+
env?: NodeJS.ProcessEnv;
|
|
19
|
+
git?: GitRunner;
|
|
20
|
+
}): Promise<string | null>;
|
|
21
|
+
/** Print the warning to stderr, if any. Never throws. */
|
|
22
|
+
export declare function warnUnpushedSandboxWork(): Promise<void>;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent sandboxes are temporary: a reset after inactivity can take every file
|
|
3
|
+
* with it. After each command in sandbox token mode, warn on stderr when the
|
|
4
|
+
* working directory is a Git checkout with work that exists only here:
|
|
5
|
+
* uncommitted changes (untracked files included), commits ahead of the
|
|
6
|
+
* upstream, or, without an upstream, commits on no remote-tracking ref.
|
|
7
|
+
*
|
|
8
|
+
* Best effort by design: it never throws, never touches stdout (JSON output
|
|
9
|
+
* stays clean), never changes an exit code, gives up on any Git error or after
|
|
10
|
+
* a short timeout, and does nothing outside sandbox token mode.
|
|
11
|
+
*/
|
|
12
|
+
import { execFile } from 'node:child_process';
|
|
13
|
+
import { isSandboxTokenMode } from './sandbox-auth.js';
|
|
14
|
+
const GIT_TIMEOUT_MS = 1_000;
|
|
15
|
+
export const runGitQuietly = ({ cwd, args }) => new Promise((resolve, reject) => {
|
|
16
|
+
execFile('git', ['-C', cwd, ...args], {
|
|
17
|
+
encoding: 'utf8',
|
|
18
|
+
timeout: GIT_TIMEOUT_MS,
|
|
19
|
+
maxBuffer: 1024 * 1024,
|
|
20
|
+
// Read-only: never take the index lock or prompt for credentials.
|
|
21
|
+
env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' },
|
|
22
|
+
}, (error, stdout) => (error ? reject(error) : resolve(stdout)));
|
|
23
|
+
});
|
|
24
|
+
/** Parse `git status --porcelain=v2 --branch`. */
|
|
25
|
+
export function parseStatus(output) {
|
|
26
|
+
const state = { dirty: false, ahead: 0, hasUpstream: false, hasCommits: true };
|
|
27
|
+
for (const line of output.split('\n')) {
|
|
28
|
+
if (!line)
|
|
29
|
+
continue;
|
|
30
|
+
if (!line.startsWith('# ')) {
|
|
31
|
+
state.dirty = true;
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if (line === '# branch.oid (initial)')
|
|
35
|
+
state.hasCommits = false;
|
|
36
|
+
else if (line.startsWith('# branch.upstream '))
|
|
37
|
+
state.hasUpstream = true;
|
|
38
|
+
else if (line.startsWith('# branch.ab '))
|
|
39
|
+
state.ahead = Number(/\+(\d+)/.exec(line)?.[1] ?? 0);
|
|
40
|
+
}
|
|
41
|
+
return state;
|
|
42
|
+
}
|
|
43
|
+
function describe({ dirty, unpushed }) {
|
|
44
|
+
if (dirty && unpushed)
|
|
45
|
+
return `uncommitted changes and ${unpushed}`;
|
|
46
|
+
return dirty ? 'uncommitted changes' : unpushed ?? '';
|
|
47
|
+
}
|
|
48
|
+
/** The warning for `cwd`, or null when there is nothing to warn about (or anything fails). */
|
|
49
|
+
export async function unpushedWorkWarning({ cwd = process.cwd(), env = process.env, git = runGitQuietly, } = {}) {
|
|
50
|
+
try {
|
|
51
|
+
if (!isSandboxTokenMode(env))
|
|
52
|
+
return null;
|
|
53
|
+
const root = (await git({ cwd, args: ['rev-parse', '--show-toplevel'] })).trim();
|
|
54
|
+
if (!root)
|
|
55
|
+
return null;
|
|
56
|
+
const state = parseStatus(await git({ cwd: root, args: ['status', '--porcelain=v2', '--branch'] }));
|
|
57
|
+
let unpushed = null;
|
|
58
|
+
if (state.hasUpstream && state.ahead > 0) {
|
|
59
|
+
unpushed = `${state.ahead} unpushed commit${state.ahead === 1 ? '' : 's'}`;
|
|
60
|
+
}
|
|
61
|
+
else if (!state.hasUpstream && state.hasCommits) {
|
|
62
|
+
// No upstream: is HEAD on any remote-tracking branch at all?
|
|
63
|
+
const local = (await git({ cwd: root, args: ['rev-list', '--count', '--max-count=1', 'HEAD', '--not', '--remotes'] })).trim();
|
|
64
|
+
if (local !== '0')
|
|
65
|
+
unpushed = 'commits that are not pushed anywhere';
|
|
66
|
+
}
|
|
67
|
+
if (!state.dirty && !unpushed)
|
|
68
|
+
return null;
|
|
69
|
+
return (`[seq-studio] This sandbox is temporary and ${root} has ${describe({ dirty: state.dirty, unpushed })}. ` +
|
|
70
|
+
`Commit and push them (git -C ${root} status).`);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/** Print the warning to stderr, if any. Never throws. */
|
|
77
|
+
export async function warnUnpushedSandboxWork() {
|
|
78
|
+
try {
|
|
79
|
+
const warning = await unpushedWorkWarning();
|
|
80
|
+
if (warning)
|
|
81
|
+
console.error(warning);
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
// Never let a warning affect the command.
|
|
85
|
+
}
|
|
86
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { operatorPlatformClient } from '../atlas-client.js';
|
|
2
2
|
import { printCliError } from '../cli-errors.js';
|
|
3
3
|
import { requiredStringFlag, validateCommandInput, wantsHelp } from '../command-input.js';
|
|
4
4
|
import { buildContext, clientOptions } from '../functions/commands.js';
|
|
@@ -38,8 +38,20 @@ export async function runServiceAccountsCommand(sub, args) {
|
|
|
38
38
|
if (target !== undefined && !target.trim())
|
|
39
39
|
throw new Error('An account ID or slug is required.');
|
|
40
40
|
const ctx = await buildContext(args);
|
|
41
|
-
const
|
|
42
|
-
|
|
41
|
+
const accounts = operatorPlatformClient(clientOptions(ctx)).controlPlane.serviceAccounts;
|
|
42
|
+
let result;
|
|
43
|
+
if (sub === 'create') {
|
|
44
|
+
if (!body || !body.slug)
|
|
45
|
+
throw new Error('A service account slug is required.');
|
|
46
|
+
result = await accounts.create({ ...body, slug: body.slug });
|
|
47
|
+
}
|
|
48
|
+
else if (sub === 'show') {
|
|
49
|
+
if (!target)
|
|
50
|
+
throw new Error('An account ID is required.');
|
|
51
|
+
result = await accounts.get({ accountId: target });
|
|
52
|
+
}
|
|
53
|
+
else
|
|
54
|
+
result = await accounts.list();
|
|
43
55
|
console.log(JSON.stringify(result, null, 2));
|
|
44
56
|
return 0;
|
|
45
57
|
}
|