@sequenceholdings/studio-cli 0.4.7 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +78 -50
- package/dist/app/commands.d.ts +1 -1
- package/dist/app/commands.js +28 -3
- package/dist/app/readme.js +6 -2
- package/dist/app/scaffold.js +1 -1
- package/dist/artifact/delegate.js +4 -4
- package/dist/auth-cmds/commands.d.ts +1 -13
- package/dist/auth-cmds/commands.js +11 -246
- package/dist/bin.js +1 -1
- package/dist/command-contract.d.ts +11 -5
- package/dist/command-contract.js +4 -3
- package/dist/command-help.d.ts +2 -2
- package/dist/command-help.js +14 -16
- package/dist/main.d.ts +3 -2
- package/dist/main.js +11 -5
- package/dist/pipeline/clone-deploy.d.ts +1 -2
- package/dist/pipeline/clone-deploy.js +6 -8
- package/dist/pipeline/commands.js +1 -1
- package/dist/pipeline/lifecycle.d.ts +3 -1
- package/dist/pipeline/lifecycle.js +12 -4
- package/dist/repos/commands.d.ts +2 -11
- package/dist/repos/commands.js +70 -156
- package/dist/repos/git-clone.d.ts +1 -10
- package/dist/repos/git-clone.js +1 -49
- package/dist/repos/git-credential.d.ts +15 -0
- package/dist/repos/git-credential.js +91 -0
- package/dist/templates/catalog.d.ts +69 -0
- package/dist/templates/catalog.js +68 -0
- package/dist/templates/commands.d.ts +29 -0
- package/dist/templates/commands.js +443 -0
- package/package.json +12 -11
- package/dist/pat-hints.d.ts +0 -15
- package/dist/pat-hints.js +0 -28
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
export const TEMPLATE_NAMESPACE = 'templates';
|
|
4
|
+
export const TEMPLATE_CATALOG_REPO = 'catalog';
|
|
5
|
+
export const TEMPLATE_METADATA_PATH = '.seq/template.json';
|
|
6
|
+
export const TEMPLATE_RELEASE_PATH = '.seq/template-release.json';
|
|
7
|
+
const slug = z.string().regex(/^[a-z][a-z0-9-]{0,63}$/);
|
|
8
|
+
const version = z.string().regex(/^[0-9]+\.[0-9]+\.[0-9]+(?:-[a-z0-9][a-z0-9.-]*)?$/);
|
|
9
|
+
export const templateMetadataSchema = z.object({
|
|
10
|
+
schemaVersion: z.literal(1),
|
|
11
|
+
name: slug,
|
|
12
|
+
description: z.string().trim().min(1).max(2000),
|
|
13
|
+
includes: z.array(z.enum(['orm', 'workspace', 'function', 'agent', 'process', 'pipeline', 'artifact'])).min(1),
|
|
14
|
+
}).strict();
|
|
15
|
+
export const templateReleaseSchema = z.object({
|
|
16
|
+
schemaVersion: z.literal(1),
|
|
17
|
+
name: slug,
|
|
18
|
+
version,
|
|
19
|
+
description: z.string().min(1),
|
|
20
|
+
includes: templateMetadataSchema.shape.includes,
|
|
21
|
+
source: z.object({ environment: z.enum(['banksouth', 'staging']), repo: z.string(), commit: z.string().regex(/^[0-9a-f]{40}$/) }),
|
|
22
|
+
digest: z.string().regex(/^[0-9a-f]{64}$/),
|
|
23
|
+
scope: z.union([z.object({ kind: z.literal('all') }), z.object({ kind: z.literal('one'), deployment: z.string().min(1) })]),
|
|
24
|
+
publishedAt: z.string().datetime(),
|
|
25
|
+
}).strict();
|
|
26
|
+
/** Staging rehearsal stays in staging; cross-deployment releases use BankSouth. */
|
|
27
|
+
export function validateTemplatePublishRoute(from, to) {
|
|
28
|
+
if (from !== 'banksouth' && from !== 'staging') {
|
|
29
|
+
throw new Error('publish requires --from banksouth or --from staging.');
|
|
30
|
+
}
|
|
31
|
+
if (to === 'local' || to.startsWith('local:') || to.startsWith('preview:')) {
|
|
32
|
+
throw new Error('--to must be a deployed environment or all.');
|
|
33
|
+
}
|
|
34
|
+
if (from === 'staging' && to !== 'staging') {
|
|
35
|
+
throw new Error('Staging-authored templates can only publish to staging; use BankSouth as the source for cross-deployment promotion.');
|
|
36
|
+
}
|
|
37
|
+
return from;
|
|
38
|
+
}
|
|
39
|
+
export function parseTemplateSelection(input) {
|
|
40
|
+
const match = /^([^@]+)@([^@]+)$/.exec(input);
|
|
41
|
+
if (!match)
|
|
42
|
+
throw new Error('Template must be <name>@<version>, for example full-stack@1.0.0.');
|
|
43
|
+
return { name: slug.parse(match[1]), version: version.parse(match[2]) };
|
|
44
|
+
}
|
|
45
|
+
export function releaseBranch(value) {
|
|
46
|
+
return `releases/${version.parse(value)}`;
|
|
47
|
+
}
|
|
48
|
+
export function ledgerPath(name, releaseVersion) {
|
|
49
|
+
return `releases/${slug.parse(name)}/${version.parse(releaseVersion)}.json`;
|
|
50
|
+
}
|
|
51
|
+
/** Hash the actual source bytes and executable bits, independent of Git commit IDs. */
|
|
52
|
+
export function templateDigest(files) {
|
|
53
|
+
const hash = createHash('sha256');
|
|
54
|
+
hash.update('seq-template-v2\0');
|
|
55
|
+
for (const file of [...files].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0)) {
|
|
56
|
+
if (file.path === TEMPLATE_RELEASE_PATH)
|
|
57
|
+
continue;
|
|
58
|
+
for (const field of [Buffer.from(file.path), Buffer.from(file.mode), Buffer.from(file.content, 'base64')]) {
|
|
59
|
+
const length = Buffer.alloc(4);
|
|
60
|
+
length.writeUInt32BE(field.length);
|
|
61
|
+
hash.update(length).update(field);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return hash.digest('hex');
|
|
65
|
+
}
|
|
66
|
+
export function targetIncludesRelease(release, deployment) {
|
|
67
|
+
return release.scope.kind === 'all' || release.scope.deployment === deployment;
|
|
68
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ParsedArgs } from '../process/commands.js';
|
|
2
|
+
import { type TemplateFile, type TemplateRelease } from './catalog.js';
|
|
3
|
+
type RemoteFile = TemplateFile;
|
|
4
|
+
type TreeEntry = {
|
|
5
|
+
path: string;
|
|
6
|
+
type: string;
|
|
7
|
+
mode: string;
|
|
8
|
+
size?: number;
|
|
9
|
+
};
|
|
10
|
+
/** Resolve the platform's explicit deploy registry without teaching the public CLI deployment URLs. */
|
|
11
|
+
export declare function promotionTargetsFromRegistry(path: string, configuredUrls: Record<string, {
|
|
12
|
+
url: string;
|
|
13
|
+
}>, registeredUrls: Record<string, {
|
|
14
|
+
url: string;
|
|
15
|
+
}>): Promise<string[]>;
|
|
16
|
+
export declare function validateTemplateTree(entries: readonly TreeEntry[]): TreeEntry[];
|
|
17
|
+
export declare function verifyReleaseFiles(files: readonly RemoteFile[], release: TemplateRelease): void;
|
|
18
|
+
export declare function initFromTemplate({ selection, target, environment }: {
|
|
19
|
+
selection: string;
|
|
20
|
+
target: string;
|
|
21
|
+
environment: string;
|
|
22
|
+
}): Promise<void>;
|
|
23
|
+
export declare function writeTemplateToDirectory({ files, release, target }: {
|
|
24
|
+
files: RemoteFile[];
|
|
25
|
+
release: TemplateRelease;
|
|
26
|
+
target: string;
|
|
27
|
+
}): Promise<void>;
|
|
28
|
+
export declare function runTemplatesCommand(sub: string | undefined, args: ParsedArgs): Promise<number>;
|
|
29
|
+
export {};
|
|
@@ -0,0 +1,443 @@
|
|
|
1
|
+
import { lstat, mkdir, mkdtemp, readFile, readdir, rename, rmdir, rm, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { basename, dirname, join, resolve, sep } from 'node:path';
|
|
4
|
+
import { resolveCommitSha, resolveRepo } from '@sequenceholdings/artifact-studio/git-service-client';
|
|
5
|
+
import { AtlasApiError, getJson, getJsonOr404, postJson } from '../atlas-client.js';
|
|
6
|
+
import { readConfig } from '../config.js';
|
|
7
|
+
import { readRegisteredEnvironmentUrls } from '../env-registry.js';
|
|
8
|
+
import { buildContext, clientOptions } from '../functions/commands.js';
|
|
9
|
+
import { stringFlag } from '../repos/commands.js';
|
|
10
|
+
import { TEMPLATE_CATALOG_REPO, TEMPLATE_METADATA_PATH, TEMPLATE_NAMESPACE, TEMPLATE_RELEASE_PATH, ledgerPath, parseTemplateSelection, releaseBranch, targetIncludesRelease, templateDigest, templateMetadataSchema, templateReleaseSchema, validateTemplatePublishRoute, } from './catalog.js';
|
|
11
|
+
const LOG = '[seq-studio]';
|
|
12
|
+
const AUTHOR = { name: 'Sequence Template Promotion', email: 'templates@seqholdings.com' };
|
|
13
|
+
const MAX_FILES = 2000;
|
|
14
|
+
const MAX_BYTES = 50 * 1024 * 1024;
|
|
15
|
+
const MAX_MARKER_BYTES = 16 * 1024;
|
|
16
|
+
const BATCH_SIZE = 100;
|
|
17
|
+
const USAGE = `usage:
|
|
18
|
+
seq-studio templates publish <name>@<version> --from <banksouth|staging> --ref <source-ref> --to <deployment|all> [--targets-file <deploy-targets.json>]
|
|
19
|
+
seq-studio templates sync -e <deployment>
|
|
20
|
+
seq-studio templates list -e <deployment>
|
|
21
|
+
seq-studio init <dir> --template <name>@<version> -e <deployment>
|
|
22
|
+
|
|
23
|
+
Author a skeleton in the source deployment's templates/<name> repo with
|
|
24
|
+
.seq/template.json. --from staging --to staging is a staging-only rehearsal.
|
|
25
|
+
BankSouth sources can promote to other deployments; --to all requires the
|
|
26
|
+
current platform deploy-target registry and configured target URLs. It records
|
|
27
|
+
an ongoing policy; sync applies releases to newly provisioned deployments. A template
|
|
28
|
+
only needs valid metadata and Git files; it need not build or deploy.
|
|
29
|
+
`;
|
|
30
|
+
function contextFor(environment) {
|
|
31
|
+
return buildContext({ positional: [], flags: { env: environment } });
|
|
32
|
+
}
|
|
33
|
+
/** Resolve the platform's explicit deploy registry without teaching the public CLI deployment URLs. */
|
|
34
|
+
export async function promotionTargetsFromRegistry(path, configuredUrls, registeredUrls) {
|
|
35
|
+
const raw = JSON.parse(await readFile(path, 'utf8'));
|
|
36
|
+
if (!raw || typeof raw !== 'object' || !('targets' in raw) || !raw.targets || typeof raw.targets !== 'object' || Array.isArray(raw.targets)) {
|
|
37
|
+
throw new Error('Promotion target file must contain a targets object.');
|
|
38
|
+
}
|
|
39
|
+
const names = Object.keys(raw.targets);
|
|
40
|
+
if (!names.includes('banksouth'))
|
|
41
|
+
throw new Error('Promotion target file is missing the BankSouth source deployment.');
|
|
42
|
+
const deployTargets = names.filter((name) => name !== 'banksouth');
|
|
43
|
+
if (deployTargets.length === 0 || deployTargets.some((name) => !/^[a-z][a-z0-9_-]*$/.test(name) || name === 'local')) {
|
|
44
|
+
throw new Error('Promotion target file has no valid deployed targets.');
|
|
45
|
+
}
|
|
46
|
+
// OpCo deploy identities use underscores; public CLI registration names use hyphens.
|
|
47
|
+
// The Sequence production deployment needs an alias because "sequence" is the auth realm name.
|
|
48
|
+
const targets = deployTargets.map((name) => name === 'sequence' ? 'sequence-prod' : name.replaceAll('_', '-'));
|
|
49
|
+
if (new Set(targets).size !== targets.length)
|
|
50
|
+
throw new Error('Promotion target names collide after CLI name normalization.');
|
|
51
|
+
const missing = targets.filter((name) => !((name === 'staging' || name === 'production') ? configuredUrls[name] : registeredUrls[name]));
|
|
52
|
+
if (missing.length)
|
|
53
|
+
throw new Error(`Configure staging/production and register each OpCo promotion target before publishing: ${missing.join(', ')}.`);
|
|
54
|
+
return targets.sort();
|
|
55
|
+
}
|
|
56
|
+
function encodePath(path) {
|
|
57
|
+
return path.split('/').map(encodeURIComponent).join('/');
|
|
58
|
+
}
|
|
59
|
+
function assertSafePath(path) {
|
|
60
|
+
if (!path || path.startsWith('/') || path.includes('\\') || path.split('/').some((part) => !part || part === '.' || part === '..')) {
|
|
61
|
+
throw new Error(`Unsafe template file path: ${path}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
async function readFileAt(ctx, repo, path, ref) {
|
|
65
|
+
const file = await getJsonOr404({
|
|
66
|
+
...clientOptions(ctx),
|
|
67
|
+
path: `/api/git-service/repos/${repo.id}/contents/${encodePath(path)}?ref=${encodeURIComponent(ref)}`,
|
|
68
|
+
});
|
|
69
|
+
if (!file)
|
|
70
|
+
return null;
|
|
71
|
+
if (file.encoding !== 'base64' || (file.mode !== '100644' && file.mode !== '100755')) {
|
|
72
|
+
throw new Error(`Unsupported Git file encoding or mode: ${path}`);
|
|
73
|
+
}
|
|
74
|
+
return { path, content: file.content, mode: file.mode };
|
|
75
|
+
}
|
|
76
|
+
async function readFiles(ctx, repo, ref) {
|
|
77
|
+
const tree = await getJson({
|
|
78
|
+
...clientOptions(ctx),
|
|
79
|
+
path: `/api/git-service/repos/${repo.id}/tree?recursive=true&ref=${encodeURIComponent(ref)}`,
|
|
80
|
+
});
|
|
81
|
+
const blobs = validateTemplateTree(tree.entries);
|
|
82
|
+
const files = [];
|
|
83
|
+
let decodedBytes = 0;
|
|
84
|
+
for (const blob of blobs) {
|
|
85
|
+
assertSafePath(blob.path);
|
|
86
|
+
const file = await readFileAt(ctx, repo, blob.path, ref);
|
|
87
|
+
if (!file)
|
|
88
|
+
throw new Error(`Template changed while reading ${blob.path}; retry from a pinned commit.`);
|
|
89
|
+
const fileBytes = Buffer.byteLength(file.content, 'base64');
|
|
90
|
+
if (blob.path === TEMPLATE_RELEASE_PATH) {
|
|
91
|
+
if (fileBytes > MAX_MARKER_BYTES)
|
|
92
|
+
throw new Error('Template release marker exceeds 16 KiB.');
|
|
93
|
+
}
|
|
94
|
+
else {
|
|
95
|
+
decodedBytes += fileBytes;
|
|
96
|
+
if (decodedBytes > MAX_BYTES)
|
|
97
|
+
throw new Error('Template exceeds the 50 MiB promotion limit.');
|
|
98
|
+
}
|
|
99
|
+
files.push(file);
|
|
100
|
+
}
|
|
101
|
+
return files;
|
|
102
|
+
}
|
|
103
|
+
export function validateTemplateTree(entries) {
|
|
104
|
+
const unsupported = entries.find((entry) => entry.type !== 'blob' && entry.type !== 'tree');
|
|
105
|
+
if (unsupported)
|
|
106
|
+
throw new Error(`Unsupported Git tree entry ${unsupported.path} (${unsupported.type}, ${unsupported.mode}); templates cannot contain submodules.`);
|
|
107
|
+
const blobs = entries.filter((entry) => entry.type === 'blob');
|
|
108
|
+
const sourceBlobs = blobs.filter((entry) => entry.path !== TEMPLATE_RELEASE_PATH);
|
|
109
|
+
if (sourceBlobs.length > MAX_FILES || sourceBlobs.reduce((n, entry) => n + (entry.size ?? 0), 0) > MAX_BYTES) {
|
|
110
|
+
throw new Error(`Template exceeds the ${MAX_FILES}-file or 50 MiB promotion limit.`);
|
|
111
|
+
}
|
|
112
|
+
const marker = blobs.find((entry) => entry.path === TEMPLATE_RELEASE_PATH);
|
|
113
|
+
if (marker && (marker.size ?? 0) > MAX_MARKER_BYTES)
|
|
114
|
+
throw new Error('Template release marker exceeds 16 KiB.');
|
|
115
|
+
return blobs;
|
|
116
|
+
}
|
|
117
|
+
async function findRepo(ctx, name) {
|
|
118
|
+
try {
|
|
119
|
+
return await resolveRepo({ ...clientOptions(ctx), namespace: TEMPLATE_NAMESPACE, name });
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (error instanceof Error && /not found/.test(error.message))
|
|
123
|
+
return null;
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async function ensureRepo(ctx, name) {
|
|
128
|
+
const existing = await findRepo(ctx, name);
|
|
129
|
+
if (existing)
|
|
130
|
+
return existing;
|
|
131
|
+
const ns = await getJsonOr404({ ...clientOptions(ctx), path: `/api/git-service/namespaces/${TEMPLATE_NAMESPACE}` });
|
|
132
|
+
if (!ns)
|
|
133
|
+
throw new Error(`${TEMPLATE_NAMESPACE} namespace is not provisioned on ${ctx.env.name}; a platform admin must create it and grant the promoter writer access.`);
|
|
134
|
+
const created = await postJson({ ...clientOptions(ctx), path: '/api/git-service/repos', body: { namespaceSlug: TEMPLATE_NAMESPACE, name } });
|
|
135
|
+
return created;
|
|
136
|
+
}
|
|
137
|
+
async function refSha(ctx, repo, ref) {
|
|
138
|
+
try {
|
|
139
|
+
return await resolveCommitSha({ ...clientOptions(ctx), repoId: repo.id, ref });
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
if (error instanceof Error && /not found/.test(error.message))
|
|
143
|
+
return null;
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async function commitFiles(ctx, repo, branch, message, files) {
|
|
148
|
+
for (let i = 0; i < files.length; i += BATCH_SIZE) {
|
|
149
|
+
await postJson({
|
|
150
|
+
...clientOptions(ctx),
|
|
151
|
+
path: `/api/git-service/repos/${repo.id}/commits-tree`,
|
|
152
|
+
body: { branch, message, author: AUTHOR, files: files.slice(i, i + BATCH_SIZE) },
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
async function createBranch(ctx, repo, name, fromRef) {
|
|
157
|
+
await postJson({ ...clientOptions(ctx), path: `/api/git-service/repos/${repo.id}/refs`, body: { name, fromRef } });
|
|
158
|
+
}
|
|
159
|
+
function jsonFile(path, value) {
|
|
160
|
+
return { path, content: Buffer.from(`${JSON.stringify(value, null, 2)}\n`).toString('base64'), mode: '100644' };
|
|
161
|
+
}
|
|
162
|
+
function parseRelease(file) {
|
|
163
|
+
return templateReleaseSchema.parse(JSON.parse(Buffer.from(file.content, 'base64').toString('utf8')));
|
|
164
|
+
}
|
|
165
|
+
async function readLedger(ctx, repo, name, version) {
|
|
166
|
+
const file = await readFileAt(ctx, repo, ledgerPath(name, version), repo.defaultBranch);
|
|
167
|
+
return file ? parseRelease(file) : null;
|
|
168
|
+
}
|
|
169
|
+
async function listLedger(ctx, repo) {
|
|
170
|
+
let tree;
|
|
171
|
+
try {
|
|
172
|
+
tree = await getJson({
|
|
173
|
+
...clientOptions(ctx),
|
|
174
|
+
path: `/api/git-service/repos/${repo.id}/tree?path=releases&recursive=true&ref=${encodeURIComponent(repo.defaultBranch)}`,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
if (error instanceof AtlasApiError && error.status === 404)
|
|
179
|
+
return [];
|
|
180
|
+
throw error;
|
|
181
|
+
}
|
|
182
|
+
const releases = [];
|
|
183
|
+
for (const entry of tree.entries.filter((item) => item.type === 'blob' && /^releases\/[a-z][a-z0-9-]*\/[0-9].*\.json$/.test(item.path))) {
|
|
184
|
+
const file = await readFileAt(ctx, repo, entry.path, repo.defaultBranch);
|
|
185
|
+
if (file)
|
|
186
|
+
releases.push(parseRelease(file));
|
|
187
|
+
}
|
|
188
|
+
return releases;
|
|
189
|
+
}
|
|
190
|
+
function sameRelease(a, b) {
|
|
191
|
+
return JSON.stringify(a) === JSON.stringify(b);
|
|
192
|
+
}
|
|
193
|
+
export function verifyReleaseFiles(files, release) {
|
|
194
|
+
const marker = files.find((file) => file.path === TEMPLATE_RELEASE_PATH);
|
|
195
|
+
if (!marker || !sameRelease(parseRelease(marker), release) || templateDigest(files) !== release.digest) {
|
|
196
|
+
throw new Error(`${release.name}@${release.version} failed release provenance or content verification.`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
async function writeLedger(ctx, repo, release) {
|
|
200
|
+
const existing = await readLedger(ctx, repo, release.name, release.version);
|
|
201
|
+
if (existing) {
|
|
202
|
+
if (!sameRelease(existing, release))
|
|
203
|
+
throw new Error(`${release.name}@${release.version} already exists with different provenance or scope on ${ctx.env.name}.`);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
206
|
+
await commitFiles(ctx, repo, repo.defaultBranch, `Publish template ${release.name}@${release.version}`, [jsonFile(ledgerPath(release.name, release.version), release)]);
|
|
207
|
+
}
|
|
208
|
+
/** A version becomes visible only after its complete branch and ledger are written. */
|
|
209
|
+
async function promoteTo(ctx, release, sourceFiles) {
|
|
210
|
+
const repo = await ensureRepo(ctx, release.name);
|
|
211
|
+
const catalog = await ensureRepo(ctx, TEMPLATE_CATALOG_REPO);
|
|
212
|
+
const existing = await readLedger(ctx, catalog, release.name, release.version);
|
|
213
|
+
if (existing) {
|
|
214
|
+
if (!sameRelease(existing, release))
|
|
215
|
+
throw new Error(`${release.name}@${release.version} already differs on ${ctx.env.name}.`);
|
|
216
|
+
const files = await readFiles(ctx, repo, releaseBranch(release.version));
|
|
217
|
+
verifyReleaseFiles(files, release);
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
const branch = releaseBranch(release.version);
|
|
221
|
+
if (!await refSha(ctx, repo, branch)) {
|
|
222
|
+
await createBranch(ctx, repo, branch, repo.defaultBranch);
|
|
223
|
+
}
|
|
224
|
+
const currentFiles = await readFiles(ctx, repo, branch);
|
|
225
|
+
const currentMarker = currentFiles.find((file) => file.path === TEMPLATE_RELEASE_PATH);
|
|
226
|
+
if (currentMarker) {
|
|
227
|
+
try {
|
|
228
|
+
verifyReleaseFiles(currentFiles, release);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
throw new Error(`Incomplete or conflicting branch ${branch} exists on ${ctx.env.name}; inspect it before retrying.`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
else {
|
|
235
|
+
const sourcePaths = new Set(sourceFiles.map((file) => file.path));
|
|
236
|
+
const deletes = currentFiles.filter((file) => !sourcePaths.has(file.path)).map((file) => ({ path: file.path, delete: true }));
|
|
237
|
+
// Git Service rejects file/directory collisions even if the conflicting
|
|
238
|
+
// path is deleted in the same commit as its replacement.
|
|
239
|
+
if (deletes.length)
|
|
240
|
+
await commitFiles(ctx, repo, branch, `Remove replaced paths for ${release.name}@${release.version}`, deletes);
|
|
241
|
+
await commitFiles(ctx, repo, branch, `Mirror ${release.name}@${release.version} from BankSouth`, sourceFiles);
|
|
242
|
+
await commitFiles(ctx, repo, branch, `Record ${release.name}@${release.version} provenance`, [jsonFile(TEMPLATE_RELEASE_PATH, release)]);
|
|
243
|
+
}
|
|
244
|
+
const mirrored = await readFiles(ctx, repo, branch);
|
|
245
|
+
verifyReleaseFiles(mirrored, release);
|
|
246
|
+
await writeLedger(ctx, catalog, release);
|
|
247
|
+
}
|
|
248
|
+
async function sourceForRelease(release) {
|
|
249
|
+
if (release.source.environment !== 'banksouth') {
|
|
250
|
+
throw new Error(`BankSouth catalog contains a release from ${release.source.environment}; refusing cross-deployment sync.`);
|
|
251
|
+
}
|
|
252
|
+
const source = await contextFor('banksouth');
|
|
253
|
+
const repo = await findRepo(source, release.name);
|
|
254
|
+
if (!repo)
|
|
255
|
+
throw new Error(`BankSouth source ${TEMPLATE_NAMESPACE}/${release.name} is missing.`);
|
|
256
|
+
const files = await readFiles(source, repo, release.source.commit);
|
|
257
|
+
if (templateDigest(files) !== release.digest)
|
|
258
|
+
throw new Error(`BankSouth source digest mismatch for ${release.name}@${release.version}.`);
|
|
259
|
+
return files;
|
|
260
|
+
}
|
|
261
|
+
async function publish(args) {
|
|
262
|
+
const { name, version } = parseTemplateSelection(args.positional[0] ?? '');
|
|
263
|
+
const sourceRef = stringFlag(args.flags, 'ref');
|
|
264
|
+
const to = stringFlag(args.flags, 'to');
|
|
265
|
+
const targetsFile = stringFlag(args.flags, 'targets-file');
|
|
266
|
+
if (!sourceRef || !to)
|
|
267
|
+
throw new Error('publish requires --ref <source-ref> and --to <deployment|all>.');
|
|
268
|
+
if (to === 'all' && !targetsFile)
|
|
269
|
+
throw new Error('--to all requires --targets-file <current deploy-targets.json>.');
|
|
270
|
+
if (to !== 'all' && targetsFile)
|
|
271
|
+
throw new Error('--targets-file is only valid with --to all.');
|
|
272
|
+
const sourceEnvironment = validateTemplatePublishRoute(stringFlag(args.flags, 'from'), to);
|
|
273
|
+
const source = await contextFor(sourceEnvironment);
|
|
274
|
+
const sourceRepo = await findRepo(source, name);
|
|
275
|
+
if (!sourceRepo)
|
|
276
|
+
throw new Error(`Create ${TEMPLATE_NAMESPACE}/${name} on ${sourceEnvironment} first.`);
|
|
277
|
+
const sourceSha = await refSha(source, sourceRepo, sourceRef);
|
|
278
|
+
if (!sourceSha)
|
|
279
|
+
throw new Error(`Source ref ${sourceRef} was not found on ${sourceEnvironment}.`);
|
|
280
|
+
const files = await readFiles(source, sourceRepo, sourceSha);
|
|
281
|
+
if (files.some((file) => file.path === TEMPLATE_RELEASE_PATH))
|
|
282
|
+
throw new Error(`${TEMPLATE_RELEASE_PATH} is reserved for promotion.`);
|
|
283
|
+
const metadataFile = files.find((file) => file.path === TEMPLATE_METADATA_PATH);
|
|
284
|
+
if (!metadataFile)
|
|
285
|
+
throw new Error(`Source repo needs ${TEMPLATE_METADATA_PATH}.`);
|
|
286
|
+
const metadata = templateMetadataSchema.parse(JSON.parse(Buffer.from(metadataFile.content, 'base64').toString('utf8')));
|
|
287
|
+
if (metadata.name !== name)
|
|
288
|
+
throw new Error(`Metadata name ${metadata.name} does not match repo name ${name}.`);
|
|
289
|
+
let targets;
|
|
290
|
+
if (to === 'all') {
|
|
291
|
+
if (!targetsFile)
|
|
292
|
+
throw new Error('--to all requires --targets-file <current deploy-targets.json>.');
|
|
293
|
+
const [config, registered] = await Promise.all([readConfig(), readRegisteredEnvironmentUrls()]);
|
|
294
|
+
targets = await promotionTargetsFromRegistry(targetsFile, config.envs, registered);
|
|
295
|
+
}
|
|
296
|
+
else {
|
|
297
|
+
const config = await readConfig();
|
|
298
|
+
if (!config.envs[to])
|
|
299
|
+
throw new Error(`Unknown deployment ${to}; register it with seq-studio envs add first.`);
|
|
300
|
+
targets = to === sourceEnvironment ? [] : [to];
|
|
301
|
+
}
|
|
302
|
+
const release = {
|
|
303
|
+
schemaVersion: 1, name, version, description: metadata.description, includes: metadata.includes,
|
|
304
|
+
source: { environment: sourceEnvironment, repo: `${TEMPLATE_NAMESPACE}/${name}`, commit: sourceSha },
|
|
305
|
+
digest: templateDigest(files),
|
|
306
|
+
scope: to === 'all' ? { kind: 'all' } : { kind: 'one', deployment: to },
|
|
307
|
+
publishedAt: new Date().toISOString(),
|
|
308
|
+
};
|
|
309
|
+
const catalogRepo = await ensureRepo(source, TEMPLATE_CATALOG_REPO);
|
|
310
|
+
const prior = await readLedger(source, catalogRepo, name, version);
|
|
311
|
+
const sourceBranch = releaseBranch(version);
|
|
312
|
+
const sourceBranchSha = await refSha(source, sourceRepo, sourceBranch);
|
|
313
|
+
const sourceMarkerFile = sourceBranchSha ? await readFileAt(source, sourceRepo, TEMPLATE_RELEASE_PATH, sourceBranch) : null;
|
|
314
|
+
const sourceMarker = sourceMarkerFile ? parseRelease(sourceMarkerFile) : null;
|
|
315
|
+
const pinned = prior ?? sourceMarker ?? release;
|
|
316
|
+
if (pinned.source.commit !== sourceSha || pinned.digest !== release.digest || JSON.stringify(pinned.scope) !== JSON.stringify(release.scope)) {
|
|
317
|
+
throw new Error(`${name}@${version} is already published with different source or scope; publish a new version.`);
|
|
318
|
+
}
|
|
319
|
+
if (prior && sourceMarker && !sameRelease(prior, sourceMarker)) {
|
|
320
|
+
throw new Error(`${sourceEnvironment} branch ${sourceBranch} differs from its release ledger.`);
|
|
321
|
+
}
|
|
322
|
+
if (!sourceBranchSha) {
|
|
323
|
+
await createBranch(source, sourceRepo, sourceBranch, sourceSha);
|
|
324
|
+
await commitFiles(source, sourceRepo, sourceBranch, `Record ${name}@${version} provenance`, [jsonFile(TEMPLATE_RELEASE_PATH, pinned)]);
|
|
325
|
+
}
|
|
326
|
+
else {
|
|
327
|
+
const branchFiles = await readFiles(source, sourceRepo, sourceBranch);
|
|
328
|
+
if (templateDigest(branchFiles) !== release.digest)
|
|
329
|
+
throw new Error(`${sourceEnvironment} branch ${sourceBranch} has drifted from the pinned source.`);
|
|
330
|
+
if (!sourceMarker)
|
|
331
|
+
await commitFiles(source, sourceRepo, sourceBranch, `Record ${name}@${version} provenance`, [jsonFile(TEMPLATE_RELEASE_PATH, pinned)]);
|
|
332
|
+
}
|
|
333
|
+
await writeLedger(source, catalogRepo, pinned);
|
|
334
|
+
console.log(`${LOG} ${name}@${version} published on ${sourceEnvironment} (${pinned.digest.slice(0, 12)})`);
|
|
335
|
+
const failures = [];
|
|
336
|
+
for (const target of targets) {
|
|
337
|
+
try {
|
|
338
|
+
const targetContext = await contextFor(target);
|
|
339
|
+
await promoteTo(targetContext, pinned, files);
|
|
340
|
+
console.log(`${LOG} ${name}@${version} available on ${target} (${pinned.digest.slice(0, 12)})`);
|
|
341
|
+
}
|
|
342
|
+
catch (error) {
|
|
343
|
+
failures.push(`${target}: ${error instanceof Error ? error.message : String(error)}`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (failures.length)
|
|
347
|
+
throw new Error(`${sourceEnvironment} release is recorded, but promotion failed on:\n${failures.join('\n')}\nRun templates sync -e <deployment> after resolving access or availability.`);
|
|
348
|
+
return 0;
|
|
349
|
+
}
|
|
350
|
+
async function sync(args) {
|
|
351
|
+
const target = stringFlag(args.flags, 'e') ?? stringFlag(args.flags, 'env');
|
|
352
|
+
if (!target || ['local', 'banksouth'].includes(target) || target.startsWith('local:'))
|
|
353
|
+
throw new Error('sync requires -e <deployed target>.');
|
|
354
|
+
const source = await contextFor('banksouth');
|
|
355
|
+
const catalog = await findRepo(source, TEMPLATE_CATALOG_REPO);
|
|
356
|
+
if (!catalog)
|
|
357
|
+
throw new Error('BankSouth templates/catalog is missing.');
|
|
358
|
+
const releases = (await listLedger(source, catalog)).filter((release) => targetIncludesRelease(release, target));
|
|
359
|
+
const destination = await contextFor(target);
|
|
360
|
+
for (const release of releases) {
|
|
361
|
+
await promoteTo(destination, release, await sourceForRelease(release));
|
|
362
|
+
console.log(`${LOG} ${release.name}@${release.version} available on ${target}`);
|
|
363
|
+
}
|
|
364
|
+
console.log(`${LOG} synchronized ${releases.length} template release(s) to ${target}`);
|
|
365
|
+
return 0;
|
|
366
|
+
}
|
|
367
|
+
async function list(args) {
|
|
368
|
+
const ctx = await buildContext(args);
|
|
369
|
+
const catalog = await findRepo(ctx, TEMPLATE_CATALOG_REPO);
|
|
370
|
+
if (!catalog) {
|
|
371
|
+
console.log(`${LOG} no template releases on ${ctx.env.name}`);
|
|
372
|
+
return 0;
|
|
373
|
+
}
|
|
374
|
+
for (const release of await listLedger(ctx, catalog)) {
|
|
375
|
+
console.log(`${release.name}@${release.version} ${release.includes.join(', ')} ${release.description}`);
|
|
376
|
+
}
|
|
377
|
+
return 0;
|
|
378
|
+
}
|
|
379
|
+
export async function initFromTemplate({ selection, target, environment }) {
|
|
380
|
+
const { name, version } = parseTemplateSelection(selection);
|
|
381
|
+
const ctx = await contextFor(environment);
|
|
382
|
+
const catalog = await findRepo(ctx, TEMPLATE_CATALOG_REPO);
|
|
383
|
+
if (!catalog)
|
|
384
|
+
throw new Error(`No template catalog on ${environment}.`);
|
|
385
|
+
const release = await readLedger(ctx, catalog, name, version);
|
|
386
|
+
if (!release)
|
|
387
|
+
throw new Error(`${selection} is not published on ${environment}.`);
|
|
388
|
+
const repo = await findRepo(ctx, name);
|
|
389
|
+
if (!repo)
|
|
390
|
+
throw new Error(`${TEMPLATE_NAMESPACE}/${name} is missing on ${environment}.`);
|
|
391
|
+
const files = await readFiles(ctx, repo, releaseBranch(version));
|
|
392
|
+
await writeTemplateToDirectory({ files, release, target });
|
|
393
|
+
console.log(`${LOG} initialized ${resolve(target)} from ${selection} on ${environment}`);
|
|
394
|
+
console.log(`${LOG} source: ${release.source.repo}@${release.source.commit} sha256:${release.digest}`);
|
|
395
|
+
}
|
|
396
|
+
export async function writeTemplateToDirectory({ files, release, target }) {
|
|
397
|
+
verifyReleaseFiles(files, release);
|
|
398
|
+
const dest = resolve(target);
|
|
399
|
+
if ((await lstat(dest).catch(() => null))?.isSymbolicLink())
|
|
400
|
+
throw new Error(`${dest} is a symlink.`);
|
|
401
|
+
if (existsSync(dest) && (await readdir(dest)).length > 0)
|
|
402
|
+
throw new Error(`${dest} is not empty.`);
|
|
403
|
+
await mkdir(dirname(dest), { recursive: true });
|
|
404
|
+
const temp = await mkdtemp(join(dirname(dest), `.${basename(dest)}-template-`));
|
|
405
|
+
try {
|
|
406
|
+
for (const file of files) {
|
|
407
|
+
if (file.path === TEMPLATE_RELEASE_PATH)
|
|
408
|
+
continue;
|
|
409
|
+
assertSafePath(file.path);
|
|
410
|
+
const output = resolve(temp, file.path);
|
|
411
|
+
if (!output.startsWith(temp + sep))
|
|
412
|
+
throw new Error(`Unsafe template file path: ${file.path}`);
|
|
413
|
+
await mkdir(dirname(output), { recursive: true });
|
|
414
|
+
await writeFile(output, Buffer.from(file.content, 'base64'), { mode: file.mode === '100755' ? 0o755 : 0o644 });
|
|
415
|
+
}
|
|
416
|
+
if (existsSync(dest))
|
|
417
|
+
await rmdir(dest);
|
|
418
|
+
await rename(temp, dest);
|
|
419
|
+
}
|
|
420
|
+
catch (error) {
|
|
421
|
+
await rm(temp, { recursive: true, force: true });
|
|
422
|
+
throw error;
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
export async function runTemplatesCommand(sub, args) {
|
|
426
|
+
if (!sub || sub === 'help' || args.flags.help === true) {
|
|
427
|
+
console.log(USAGE);
|
|
428
|
+
return sub ? 0 : 1;
|
|
429
|
+
}
|
|
430
|
+
try {
|
|
431
|
+
switch (sub) {
|
|
432
|
+
case 'publish': return await publish(args);
|
|
433
|
+
case 'sync': return await sync(args);
|
|
434
|
+
case 'list': return await list(args);
|
|
435
|
+
default: throw new Error(`Unknown templates command ${sub}.\n${USAGE}`);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
catch (error) {
|
|
439
|
+
const detail = error instanceof AtlasApiError ? `${error.message} (HTTP ${error.status}, ${error.path})` : error instanceof Error ? error.message : String(error);
|
|
440
|
+
console.error(`${LOG} ${detail}`);
|
|
441
|
+
return 1;
|
|
442
|
+
}
|
|
443
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sequenceholdings/studio-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Unified Sequence Studio CLI — `seq-studio init` / `add` / `deploy` (app monorepos), `seq-studio agents`, `seq-studio process` (Lattice), `seq-studio artifact`, `seq-studio functions` / `secrets`, `seq-studio repos`, and `seq-studio auth
|
|
3
|
+
"version": "0.5.1",
|
|
4
|
+
"description": "Unified Sequence Studio CLI — `seq-studio init` / `add` / `deploy` (app monorepos), `seq-studio agents`, `seq-studio process` (Lattice), `seq-studio artifact`, `seq-studio functions` / `secrets`, `seq-studio repos`, and `seq-studio auth whoami`. Includes Auth0 browser login shared with seqapi.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
@@ -41,15 +41,15 @@
|
|
|
41
41
|
"smol-toml": "^1.9.0",
|
|
42
42
|
"tsx": "^4.20.3",
|
|
43
43
|
"zod": "^4.1.13",
|
|
44
|
+
"@sequenceholdings/artifact-studio": "0.7.0",
|
|
44
45
|
"@sequenceholdings/agent-spec": "0.1.3",
|
|
45
|
-
"@sequenceholdings/
|
|
46
|
-
"@sequenceholdings/managed-functions": "0.
|
|
47
|
-
"@sequenceholdings/storage": "0.1.1"
|
|
48
|
-
"@sequenceholdings/lattice": "0.1.5"
|
|
46
|
+
"@sequenceholdings/lattice": "0.1.5",
|
|
47
|
+
"@sequenceholdings/managed-functions": "0.4.0",
|
|
48
|
+
"@sequenceholdings/storage": "0.1.1"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
|
-
"@sequenceholdings/
|
|
52
|
-
"@sequenceholdings/
|
|
51
|
+
"@sequenceholdings/pipeline-spec": "0.2.4",
|
|
52
|
+
"@sequenceholdings/orm": "2.6.0"
|
|
53
53
|
},
|
|
54
54
|
"peerDependenciesMeta": {
|
|
55
55
|
"@sequenceholdings/orm": {
|
|
@@ -64,8 +64,8 @@
|
|
|
64
64
|
"@types/node": "^22.0.0",
|
|
65
65
|
"typescript": "^5.6.0",
|
|
66
66
|
"vitest": "^4.1.11",
|
|
67
|
-
"@sequenceholdings/orm": "2.
|
|
68
|
-
"@sequenceholdings/pipeline-spec": "0.2.
|
|
67
|
+
"@sequenceholdings/orm": "2.6.0",
|
|
68
|
+
"@sequenceholdings/pipeline-spec": "0.2.4"
|
|
69
69
|
},
|
|
70
70
|
"engines": {
|
|
71
71
|
"node": ">=20"
|
|
@@ -83,6 +83,7 @@
|
|
|
83
83
|
"build": "rm -rf dist && tsc && node scripts/copy-templates.mjs",
|
|
84
84
|
"type-check": "tsc --noEmit",
|
|
85
85
|
"test": "vitest run",
|
|
86
|
-
"test:watch": "vitest"
|
|
86
|
+
"test:watch": "vitest",
|
|
87
|
+
"test:git-login": "pnpm run build && node scripts/test-git-login.mjs"
|
|
87
88
|
}
|
|
88
89
|
}
|
package/dist/pat-hints.d.ts
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* User-facing hints for minting a git-service PAT.
|
|
3
|
-
*
|
|
4
|
-
* Users can mint a PAT with seq-studio after interactive login, or through
|
|
5
|
-
* the Atlas UI at `/settings/tokens`.
|
|
6
|
-
*/
|
|
7
|
-
export declare function settingsTokensUrl(envUrl: string): string;
|
|
8
|
-
/**
|
|
9
|
-
* Multi-line setup instructions covering both the CLI and Atlas UI paths.
|
|
10
|
-
*/
|
|
11
|
-
export declare function formatPatSetupHint({ envUrl, envName, indent, }: {
|
|
12
|
-
envUrl: string;
|
|
13
|
-
envName: string;
|
|
14
|
-
indent?: string;
|
|
15
|
-
}): string[];
|
package/dist/pat-hints.js
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* User-facing hints for minting a git-service PAT.
|
|
3
|
-
*
|
|
4
|
-
* Users can mint a PAT with seq-studio after interactive login, or through
|
|
5
|
-
* the Atlas UI at `/settings/tokens`.
|
|
6
|
-
*/
|
|
7
|
-
export function settingsTokensUrl(envUrl) {
|
|
8
|
-
return `${envUrl.replace(/\/$/, '')}/settings/tokens`;
|
|
9
|
-
}
|
|
10
|
-
/**
|
|
11
|
-
* Multi-line setup instructions covering both the CLI and Atlas UI paths.
|
|
12
|
-
*/
|
|
13
|
-
export function formatPatSetupHint({ envUrl, envName, indent = ' ', }) {
|
|
14
|
-
const tokensUrl = settingsTokensUrl(envUrl);
|
|
15
|
-
return [
|
|
16
|
-
`${indent}Get a PAT with seq-studio:`,
|
|
17
|
-
`${indent} seq-studio login`,
|
|
18
|
-
`${indent} seq-studio auth pat create --name laptop --scopes repo:read,repo:write -e ${envName}`,
|
|
19
|
-
`${indent}Or create one in Atlas:`,
|
|
20
|
-
`${indent} 1. Open ${tokensUrl} and sign in`,
|
|
21
|
-
`${indent} 2. New token → scopes repo:read (add repo:write for push) → copy once`,
|
|
22
|
-
`${indent} Merge is a repository grant (Merge / Admin), not a PAT scope.`,
|
|
23
|
-
`${indent} 3. export ATLAS_GIT_PAT=<token>`,
|
|
24
|
-
`${indent} 4. Copy the clone URL from Repositories → Clone, then:`,
|
|
25
|
-
`${indent} ATLAS_GIT_PAT=<token> seq-studio repos clone --url <https://…/repos/<id>/git> -e ${envName}`,
|
|
26
|
-
`${indent} (or: seq-studio repos clone <ns>/<name> -e ${envName})`,
|
|
27
|
-
];
|
|
28
|
-
}
|