@sequenceholdings/studio-cli 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +465 -28
  2. package/dist/agents/commands.d.ts +1 -1
  3. package/dist/agents/commands.js +5 -0
  4. package/dist/agents/scaffold.js +5 -7
  5. package/dist/agents/voice-authoring.d.ts +5 -0
  6. package/dist/agents/voice-authoring.js +75 -0
  7. package/dist/agents/voice-publication.d.ts +5 -0
  8. package/dist/agents/voice-publication.js +63 -0
  9. package/dist/agents/voice-shared.d.ts +20 -0
  10. package/dist/agents/voice-shared.js +112 -0
  11. package/dist/agents/voice.d.ts +3 -0
  12. package/dist/agents/voice.js +57 -0
  13. package/dist/app/adapters.d.ts +6 -0
  14. package/dist/app/adapters.js +17 -2
  15. package/dist/app/agent-refs.d.ts +16 -0
  16. package/dist/app/agent-refs.js +36 -0
  17. package/dist/app/application-registration.d.ts +31 -5
  18. package/dist/app/application-registration.js +58 -14
  19. package/dist/app/commands.js +19 -2
  20. package/dist/app/deploy.d.ts +3 -0
  21. package/dist/app/deploy.js +18 -4
  22. package/dist/app/env-bindings.d.ts +21 -0
  23. package/dist/app/env-bindings.js +184 -0
  24. package/dist/app/manifest-validation.js +8 -0
  25. package/dist/app/manifest.d.ts +13 -9
  26. package/dist/app/manifest.js +1 -1
  27. package/dist/app/primitive-scaffold.d.ts +4 -1
  28. package/dist/app/primitive-scaffold.js +4 -4
  29. package/dist/app/readme.js +1 -0
  30. package/dist/app/scaffold-files.js +1 -1
  31. package/dist/app/scaffold.d.ts +6 -4
  32. package/dist/app/scaffold.js +7 -4
  33. package/dist/app/workspace-scaffold.js +12 -7
  34. package/dist/argv.d.ts +7 -0
  35. package/dist/argv.js +56 -0
  36. package/dist/artifact/delegate.js +8 -4
  37. package/dist/atlas-client.d.ts +6 -0
  38. package/dist/atlas-client.js +39 -2
  39. package/dist/auth.d.ts +32 -0
  40. package/dist/auth.js +170 -33
  41. package/dist/bin.js +23 -4
  42. package/dist/command-contract.d.ts +137 -0
  43. package/dist/command-contract.js +43 -0
  44. package/dist/command-help.d.ts +8 -0
  45. package/dist/command-help.js +71 -0
  46. package/dist/functions/commands.d.ts +1 -1
  47. package/dist/functions/commands.js +19 -3
  48. package/dist/functions/deploy-preflight.d.ts +21 -0
  49. package/dist/functions/deploy-preflight.js +58 -0
  50. package/dist/functions/egress-postgres.d.ts +7 -0
  51. package/dist/functions/egress-postgres.js +36 -0
  52. package/dist/functions/manifest.d.ts +8 -0
  53. package/dist/functions/manifest.js +9 -0
  54. package/dist/functions/source-selection.js +4 -1
  55. package/dist/main.js +58 -20
  56. package/dist/orm/delegate.d.ts +16 -0
  57. package/dist/orm/delegate.js +140 -7
  58. package/dist/pipeline/clone-deploy.d.ts +37 -0
  59. package/dist/pipeline/clone-deploy.js +125 -0
  60. package/dist/pipeline/codegen.js +6 -2
  61. package/dist/pipeline/commands.js +21 -5
  62. package/dist/pipeline/lifecycle.d.ts +1 -0
  63. package/dist/pipeline/lifecycle.js +95 -44
  64. package/dist/pipeline/repin-orm.js +6 -2
  65. package/dist/pipeline/stage-secrets.js +1 -1
  66. package/dist/process/build.js +17 -0
  67. package/dist/process/codegen.js +16 -0
  68. package/dist/process/commands.d.ts +15 -7
  69. package/dist/process/commands.js +291 -99
  70. package/dist/process/lint.js +35 -0
  71. package/dist/process/plan-diff.js +9 -0
  72. package/dist/process/simulate.js +8 -0
  73. package/dist/release-age.d.ts +12 -0
  74. package/dist/release-age.js +24 -0
  75. package/dist/repos/commands.d.ts +1 -1
  76. package/dist/repos/commands.js +36 -7
  77. package/dist/scaffold-guidance.d.ts +4 -0
  78. package/dist/scaffold-guidance.js +15 -0
  79. package/dist/storage/commands.js +23 -1
  80. package/dist/storage/gcs-download.d.ts +13 -0
  81. package/dist/storage/gcs-download.js +41 -0
  82. package/dist/storage/import-cycle.d.ts +41 -0
  83. package/dist/storage/import-cycle.js +123 -0
  84. package/dist/storage/import-files.d.ts +30 -0
  85. package/dist/storage/import-files.js +133 -0
  86. package/dist/storage/import-gcloud.d.ts +12 -0
  87. package/dist/storage/import-gcloud.js +54 -0
  88. package/dist/storage/import-identity.d.ts +12 -0
  89. package/dist/storage/import-identity.js +15 -0
  90. package/dist/storage/import-plan.d.ts +120 -0
  91. package/dist/storage/import-plan.js +189 -0
  92. package/dist/storage/import-preflight.d.ts +36 -0
  93. package/dist/storage/import-preflight.js +62 -0
  94. package/dist/storage/import-progress-map.d.ts +5 -0
  95. package/dist/storage/import-progress-map.js +22 -0
  96. package/dist/storage/import-recover.d.ts +97 -0
  97. package/dist/storage/import-recover.js +186 -0
  98. package/dist/storage/import-run.d.ts +14 -0
  99. package/dist/storage/import-run.js +140 -0
  100. package/dist/templates/guidance/AGENTS.md +10 -0
  101. package/dist/templates/guidance/CLAUDE.md +1 -0
  102. package/dist/templates/process/package.json +2 -2
  103. package/dist/templates/process/pnpm-workspace.yaml +7 -4
  104. package/dist/validation-detail.d.ts +2 -0
  105. package/dist/validation-detail.js +20 -0
  106. package/package.json +9 -9
  107. package/templates/guidance/AGENTS.md +10 -0
  108. package/templates/guidance/CLAUDE.md +1 -0
  109. package/templates/process/package.json +2 -2
  110. package/templates/process/pnpm-workspace.yaml +7 -4
@@ -366,6 +366,11 @@ export async function reposCloneCommand(args, deps = {}) {
366
366
  }
367
367
  const output = outputFlag ?? outFlag;
368
368
  const pat = resolveGitPatFromEnv();
369
+ const transportFlag = stringFlag(args.flags, 'transport') ?? 'auto';
370
+ if (!['auto', 'git', 'json'].includes(transportFlag)) {
371
+ throw new Error('--transport must be one of: auto, git, json.');
372
+ }
373
+ const transport = transportFlag;
369
374
  const urlFlag = stringFlag(args.flags, 'url');
370
375
  const idFlag = stringFlag(args.flags, 'id');
371
376
  const positional = args.positional[0];
@@ -376,14 +381,21 @@ export async function reposCloneCommand(args, deps = {}) {
376
381
  throw new Error('Pass either <ns>/<name> or --url/--id, not both.');
377
382
  }
378
383
  // --url/--id are PAT-only (no JSON materialize for a bare UUID/URL).
379
- if ((urlFlag || idFlag) && !pat) {
384
+ if ((urlFlag || idFlag) && (!pat || transport === 'json')) {
380
385
  const env = await resolveEnvOnly(args);
381
386
  const lines = [
382
- `${LOG} --url/--id requires ATLAS_GIT_PAT (JSON materialize needs <ns>/<name>).`,
387
+ `${LOG} --url/--id requires ATLAS_GIT_PAT and Git transport (JSON materialize needs <ns>/<name>).`,
383
388
  ...formatPatSetupHint({ envUrl: env.url, envName: env.name }),
384
389
  ];
385
390
  throw new Error(lines.join('\n'));
386
391
  }
392
+ if (transport === 'git' && !pat) {
393
+ const env = await resolveEnvOnly(args);
394
+ throw new Error([
395
+ `${LOG} --transport git requires ATLAS_GIT_PAT with repo:read access for ${env.name}.`,
396
+ ...formatPatSetupHint({ envUrl: env.url, envName: env.name }),
397
+ ].join('\n'));
398
+ }
387
399
  // PAT-only path: clone by URL or repo UUID without seqapi/Auth0.
388
400
  if (pat && (urlFlag || idFlag)) {
389
401
  const env = await resolveEnvOnly(args);
@@ -399,6 +411,8 @@ export async function reposCloneCommand(args, deps = {}) {
399
411
  pat,
400
412
  ...(ref ? { ref } : {}),
401
413
  ...(depth != null ? { depth } : {}),
414
+ }).catch((error) => {
415
+ throw withGitAuthHint({ error, envName: env.name });
402
416
  });
403
417
  console.log(`${LOG} cloned ${targetUrl} → ${destDir}` +
404
418
  (ref ? ` (ref ${ref})` : '') +
@@ -431,7 +445,7 @@ export async function reposCloneCommand(args, deps = {}) {
431
445
  }
432
446
  const ctx = await reposContext(args);
433
447
  const destDir = resolve(output ?? name);
434
- if (pat) {
448
+ if (pat && transport !== 'json') {
435
449
  prepareCloneDest({ destDir, force });
436
450
  const resolved = await resolveRepo({ ...clientOptions(ctx), namespace, name });
437
451
  const targetUrl = cloneUrl(ctx, resolved.id);
@@ -442,6 +456,8 @@ export async function reposCloneCommand(args, deps = {}) {
442
456
  pat,
443
457
  ...(ref ? { ref } : {}),
444
458
  ...(depth != null ? { depth } : {}),
459
+ }).catch((error) => {
460
+ throw withGitAuthHint({ error, envName: ctx.env.name });
445
461
  });
446
462
  console.log(`${LOG} cloned ${namespace}/${name} → ${destDir}` +
447
463
  (ref ? ` (ref ${ref})` : '') +
@@ -449,7 +465,9 @@ export async function reposCloneCommand(args, deps = {}) {
449
465
  return 0;
450
466
  }
451
467
  assertDestWritable({ destDir, force });
452
- console.log(`${LOG} no ATLAS_GIT_PAT — materializing via JSON API (no .git dir).`);
468
+ console.log(transport === 'json'
469
+ ? `${LOG} materializing via JSON API as the signed-in Atlas identity (no .git dir; ignoring ATLAS_GIT_PAT).`
470
+ : `${LOG} no ATLAS_GIT_PAT — materializing via JSON API (no .git dir).`);
453
471
  for (const line of formatPatSetupHint({ envUrl: ctx.env.url, envName: ctx.env.name })) {
454
472
  console.log(line);
455
473
  }
@@ -462,6 +480,14 @@ export async function reposCloneCommand(args, deps = {}) {
462
480
  verb: 'cloned',
463
481
  });
464
482
  }
483
+ function withGitAuthHint({ error, envName }) {
484
+ const message = error instanceof Error ? error.message : String(error);
485
+ if (!/(authentication failed|could not read username|http\s*(401|403)|returned error:\s*(401|403))/i.test(message)) {
486
+ return error instanceof Error ? error : new Error(message);
487
+ }
488
+ return new Error(`${message}\n${LOG} Git-service rejected ATLAS_GIT_PAT for ${envName}. Check that it is current and has repo:read access for this environment. ` +
489
+ `If your signed-in Atlas account can read the repo, retry with --transport json to materialize without using the ambient PAT (this creates no .git directory).`, { cause: error });
490
+ }
465
491
  /** Resolve -e/--env without requiring Auth0 (for PAT-only --url/--id clones). */
466
492
  async function resolveEnvOnly(args) {
467
493
  if (args.flags.env === true || args.flags.e === true) {
@@ -801,7 +827,7 @@ export const REPOS_USAGE = `usage:
801
827
  create a repo seeded with a README; --git-backend
802
828
  walgit creates it empty (for pushing existing
803
829
  history); needs namespace write
804
- seq-studio repos clone <ns>/<name> -e <env> [--ref r] [--output dir] [--force] [--full]
830
+ seq-studio repos clone <ns>/<name> -e <env> [--ref r] [--output dir] [--force] [--full] [--transport auto|git|json]
805
831
  seq-studio repos clone --url <https://…/repos/<id>/git> -e <env> [--ref r] [--output dir] [--full]
806
832
  seq-studio repos clone --id <uuid> -e <env> [--ref r] [--output dir] [--full]
807
833
  smart-HTTP when ATLAS_GIT_PAT is set;
@@ -817,8 +843,11 @@ export const REPOS_USAGE = `usage:
817
843
  Flags: -e/--env <env> (required; see: seq-studio envs list)
818
844
 
819
845
  clone prefers real git clone (PAT via askpass — never written into the remote
820
- URL). Without ATLAS_GIT_PAT, <ns>/<name> falls back to the JSON API and prints
821
- how to get a PAT (seq-studio or Atlas UI /settings/tokens).
846
+ URL). --transport auto (default) uses Git when ATLAS_GIT_PAT is set and JSON
847
+ materialization otherwise; --transport git requires a repo:read PAT; --transport
848
+ json ignores ATLAS_GIT_PAT and uses the signed-in Atlas identity (<ns>/<name>
849
+ only; no .git directory). Authentication failures explain this retry path.
850
+ JSON materialization requires repo read access and prints how to create a PAT.
822
851
  PAT without Auth0 login: use --id from Repositories → Clone
823
852
  (or --url with the environment's canonical HTTPS origin).
824
853
  --ref accepts a branch, tag, or commit SHA (SHA → full clone, then checkout).
@@ -0,0 +1,4 @@
1
+ /** Add documentation pointers without replacing project-specific instructions. */
2
+ export declare function writeScaffoldGuidance({ directory }: {
3
+ directory: string;
4
+ }): Promise<void>;
@@ -0,0 +1,15 @@
1
+ import { readFile, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ /** Add documentation pointers without replacing project-specific instructions. */
4
+ export async function writeScaffoldGuidance({ directory }) {
5
+ for (const name of ['AGENTS.md', 'CLAUDE.md']) {
6
+ const body = await readFile(new URL(`../templates/guidance/${name}`, import.meta.url), 'utf8');
7
+ try {
8
+ await writeFile(join(directory, name), body, { flag: 'wx' });
9
+ }
10
+ catch (error) {
11
+ if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST'))
12
+ throw error;
13
+ }
14
+ }
15
+ }
@@ -1,6 +1,6 @@
1
1
  import { createReadStream, createWriteStream } from 'node:fs';
2
2
  import { readFile, stat, writeFile } from 'node:fs/promises';
3
- import { basename, resolve } from 'node:path';
3
+ import { basename, dirname, resolve } from 'node:path';
4
4
  import { Readable } from 'node:stream';
5
5
  import { pipeline } from 'node:stream/promises';
6
6
  import { randomUUID } from 'node:crypto';
@@ -10,7 +10,9 @@ import { getAccessTokenWithMode } from '../auth.js';
10
10
  import { resolveEnvWithDiscovery } from '../config.js';
11
11
  import { getJson, postJson, putJson, patchJson, deleteJson, } from '../atlas-client.js';
12
12
  import { printCliError } from '../cli-errors.js';
13
+ import { runStorageImport } from './import-run.js';
13
14
  import { REQUIRE_EXPLICIT_ENV_MESSAGE } from '../env-flags.js';
15
+ import { writeScaffoldGuidance } from '../scaffold-guidance.js';
14
16
  const usage = `usage:
15
17
  seq-studio storage init <workspace-name> [--out workspace.yml]
16
18
  seq-studio storage validate [workspace.yml]
@@ -19,6 +21,9 @@ const usage = `usage:
19
21
  seq-studio storage show --workspace <id> [--node <id>] -e <env>
20
22
  seq-studio storage mkdir <name> --workspace <id> [--parent <id>] -e <env>
21
23
  seq-studio storage upload <file> --workspace <id> [--path <path>] [--parent <id>] [--replace <file-id> --revision <n>] [--resume <upload-id>] -e <env>
24
+ seq-studio storage import <directory|gs://bucket/prefix> --workspace <id> [--path <prefix>] [--parent <id>] [--concurrency <n>] [--progress <file>] [--yes] -e <env>
25
+ seq-studio storage uploads --workspace <id> -e <env>
26
+ seq-studio storage reconcile --workspace <id> [--abort-incomplete] -e <env>
22
27
  seq-studio storage download --workspace <id> --node <id> --out <file> [--version <id>] -e <env>
23
28
  seq-studio storage trash|restore|purge --workspace <id> --node <id> --revision <n> [-e <env>] [--yes]
24
29
  seq-studio storage access --workspace <id> [--node <id>] [--file <access.json>] -e <env>
@@ -48,6 +53,7 @@ export async function runStorageCommand(sub, args) {
48
53
  const manifest = workspaceManifestSchema.parse({ workspace: { name } });
49
54
  const output = resolve(flag('out') ?? 'workspace.yml');
50
55
  await writeFile(output, `workspace:\n name: ${manifest.workspace.name}\n description: ""\n`, { flag: 'wx' });
56
+ await writeScaffoldGuidance({ directory: dirname(output) });
51
57
  console.log(output);
52
58
  return 0;
53
59
  }
@@ -156,6 +162,22 @@ export async function runStorageCommand(sub, args) {
156
162
  }
157
163
  break;
158
164
  }
165
+ case 'import':
166
+ return runStorageImport({
167
+ args,
168
+ env,
169
+ token,
170
+ workspace,
171
+ flag,
172
+ });
173
+ case 'uploads':
174
+ print(await workspace.uploads.list());
175
+ break;
176
+ case 'reconcile':
177
+ print(await workspace.uploads.reconcile({
178
+ abortIncomplete: args.flags['abort-incomplete'] === true,
179
+ }));
180
+ break;
159
181
  case 'download': {
160
182
  const output = resolve(required('out'));
161
183
  const signed = await workspace.download(required('node'), {
@@ -0,0 +1,13 @@
1
+ /** Read a GCS object with the operator's token. Redirects stay on Google storage and drop the bearer token. */
2
+ export declare function gcsMediaUrl({ bucket, name }: {
3
+ bucket: string;
4
+ name: string;
5
+ }): string;
6
+ export declare function allowedDownloadRedirect(location: string): URL;
7
+ export declare function openGcsObject({ fetch: fetcher, token, bucket, name, signal, }: {
8
+ fetch: typeof fetch;
9
+ token: string;
10
+ bucket: string;
11
+ name: string;
12
+ signal?: AbortSignal;
13
+ }): Promise<ReadableStream<Uint8Array>>;
@@ -0,0 +1,41 @@
1
+ /** Read a GCS object with the operator's token. Redirects stay on Google storage and drop the bearer token. */
2
+ const STORAGE_HOST = 'storage.googleapis.com';
3
+ export function gcsMediaUrl({ bucket, name }) {
4
+ if (!bucket || bucket.includes('/') || !name || name.startsWith('/') || name.includes('\\'))
5
+ throw new Error('Invalid GCS object name');
6
+ const url = new URL(`https://${STORAGE_HOST}/storage/v1/b/${encodeURIComponent(bucket)}/o/${encodeURIComponent(name)}`);
7
+ url.searchParams.set('alt', 'media');
8
+ return url.toString();
9
+ }
10
+ export function allowedDownloadRedirect(location) {
11
+ let url;
12
+ try {
13
+ url = new URL(location);
14
+ }
15
+ catch {
16
+ throw new Error('GCS download redirect was not a URL');
17
+ }
18
+ const hostOk = url.hostname === STORAGE_HOST || url.hostname.endsWith(`.${STORAGE_HOST}`);
19
+ if (url.protocol !== 'https:' || url.username || url.password || url.port || !hostOk)
20
+ throw new Error('GCS download redirect left Google storage');
21
+ return url;
22
+ }
23
+ export async function openGcsObject({ fetch: fetcher, token, bucket, name, signal, }) {
24
+ const first = await fetcher(gcsMediaUrl({ bucket, name }), {
25
+ headers: { Authorization: `Bearer ${token}` },
26
+ redirect: 'manual',
27
+ signal,
28
+ });
29
+ const response = await followStorageRedirect({ response: first, fetch: fetcher, signal });
30
+ if (!response.ok || !response.body)
31
+ throw new Error(`GCS object read failed (${response.status})`);
32
+ return response.body;
33
+ }
34
+ async function followStorageRedirect({ response, fetch: fetcher, signal, }) {
35
+ if (response.status < 300 || response.status >= 400)
36
+ return response;
37
+ const location = response.headers.get('location');
38
+ if (!location)
39
+ throw new Error('GCS download redirect was missing a location');
40
+ return fetcher(allowedDownloadRedirect(location), { redirect: 'error', signal });
41
+ }
@@ -0,0 +1,41 @@
1
+ import { type StorageClient } from '@sequenceholdings/storage';
2
+ import type { ClassifiedImport, ImportProgress } from './import-plan.js';
3
+ type Workspace = ReturnType<StorageClient['workspace']>;
4
+ /**
5
+ * Replays go out even when the pending cap is full, because those reservations
6
+ * already exist. Fresh reservations share whatever slots the cap still allows,
7
+ * and the combined start never exceeds one batch.
8
+ */
9
+ export declare function selectImportBatch<TPending, TStart extends {
10
+ replay: boolean;
11
+ }>({ starts, pending, slots, batchLimit, }: {
12
+ starts: TStart[];
13
+ pending: TPending[];
14
+ slots: number;
15
+ batchLimit?: number;
16
+ }): {
17
+ replayNow: TStart[];
18
+ freshNow: TStart[];
19
+ wave: TPending[];
20
+ laterStarts: TStart[];
21
+ rest: TPending[];
22
+ };
23
+ export declare function transferImport({ workspace, progress, progressPath, classified, perPrincipal, concurrency, parentId, bucket, token, }: {
24
+ workspace: Workspace;
25
+ progress: ImportProgress;
26
+ progressPath: string;
27
+ classified: ClassifiedImport;
28
+ perPrincipal: number;
29
+ concurrency: number;
30
+ parentId: string | null;
31
+ bucket?: string;
32
+ token: string | null;
33
+ }): Promise<string[]>;
34
+ /** A wave with nothing left to reserve or transfer is finished, not out of slots. */
35
+ export declare function importCycleOutcome({ live, starting, wave, deferred, }: {
36
+ live: number;
37
+ starting: number;
38
+ wave: number;
39
+ deferred: number;
40
+ }): 'transfer' | 'done' | 'blocked';
41
+ export {};
@@ -0,0 +1,123 @@
1
+ import { STORAGE_UPLOAD_BATCH_LIMIT } from '@sequenceholdings/storage';
2
+ import { eachLimited, openImportSource, saveProgress } from './import-files.js';
3
+ import { prepareWave, recoverResume, } from './import-recover.js';
4
+ /**
5
+ * Replays go out even when the pending cap is full, because those reservations
6
+ * already exist. Fresh reservations share whatever slots the cap still allows,
7
+ * and the combined start never exceeds one batch.
8
+ */
9
+ export function selectImportBatch({ starts, pending, slots, batchLimit = STORAGE_UPLOAD_BATCH_LIMIT, }) {
10
+ const limit = Math.max(0, batchLimit);
11
+ const replays = starts.filter((start) => start.replay);
12
+ const fresh = starts.filter((start) => !start.replay);
13
+ const replayNow = replays.slice(0, limit);
14
+ const room = limit - replayNow.length;
15
+ const slotRoom = Math.max(0, Math.min(room, slots));
16
+ const replaySlotCost = slots > 0 ? replayNow.length : 0;
17
+ const admissionRoom = Math.max(0, slotRoom - replaySlotCost);
18
+ const freshNow = fresh.slice(0, admissionRoom);
19
+ return {
20
+ replayNow,
21
+ freshNow,
22
+ wave: pending.slice(0, admissionRoom - freshNow.length),
23
+ laterStarts: [...replays.slice(limit), ...fresh.slice(admissionRoom)],
24
+ rest: pending.slice(admissionRoom - freshNow.length),
25
+ };
26
+ }
27
+ export async function transferImport({ workspace, progress, progressPath, classified, perPrincipal, concurrency, parentId, bucket, token, }) {
28
+ const controller = new AbortController();
29
+ const cancel = () => controller.abort();
30
+ process.once('SIGINT', cancel);
31
+ const failures = [];
32
+ try {
33
+ let queue = classified.pending;
34
+ let resume = classified.resume;
35
+ while (resume.length || queue.length) {
36
+ const listed = await workspace.uploads.list();
37
+ const slots = listed.limits.perPrincipal - listed.items.length;
38
+ const recovered = await recoverResume({ workspace, resume, parentId });
39
+ for (const conflict of recovered.conflicts)
40
+ failures.push(`${conflict.relativePath}: ${conflict.reason}`);
41
+ noteRecovered(progress, recovered.done);
42
+ const selected = selectImportBatch({ starts: recovered.starts, pending: queue, slots });
43
+ const starting = [...selected.replayNow, ...selected.freshNow];
44
+ const outcome = importCycleOutcome({
45
+ live: recovered.resume.length,
46
+ starting: starting.length,
47
+ wave: selected.wave.length,
48
+ deferred: selected.laterStarts.length + selected.rest.length,
49
+ });
50
+ if (outcome !== 'transfer') {
51
+ if (recovered.done.length)
52
+ await saveProgress(progressPath, progress);
53
+ if (outcome === 'blocked')
54
+ failures.push(`No pending-upload slots left (${perPrincipal} per person). Run storage uploads and storage reconcile.`);
55
+ break;
56
+ }
57
+ failures.push(...(await transferWave({
58
+ workspace,
59
+ progress,
60
+ progressPath,
61
+ resume: recovered.resume,
62
+ starts: starting,
63
+ wave: selected.wave,
64
+ concurrency,
65
+ parentId,
66
+ bucket,
67
+ token,
68
+ signal: controller.signal,
69
+ })));
70
+ resume = selected.laterStarts.map((start) => start.resumeItem);
71
+ queue = selected.rest;
72
+ }
73
+ }
74
+ finally {
75
+ process.removeListener('SIGINT', cancel);
76
+ }
77
+ return failures;
78
+ }
79
+ /** A wave with nothing left to reserve or transfer is finished, not out of slots. */
80
+ export function importCycleOutcome({ live, starting, wave, deferred, }) {
81
+ if (live > 0 || starting > 0 || wave > 0)
82
+ return 'transfer';
83
+ return deferred > 0 ? 'blocked' : 'done';
84
+ }
85
+ function noteRecovered(progress, done) {
86
+ for (const item of done) {
87
+ const previous = progress.inflight[item.relativePath];
88
+ progress.completed[item.relativePath] = {
89
+ fileId: item.fileId,
90
+ uploadId: item.uploadId,
91
+ size: previous?.size ?? 0,
92
+ checksum: previous?.checksum,
93
+ idempotencyKey: item.idempotencyKey,
94
+ };
95
+ delete progress.inflight[item.relativePath];
96
+ }
97
+ }
98
+ async function transferWave({ workspace, progress, progressPath, resume, starts, wave, concurrency, parentId, bucket, token, signal, }) {
99
+ const transfers = await prepareWave({
100
+ workspace,
101
+ progress,
102
+ progressPath,
103
+ resume,
104
+ starts,
105
+ wave,
106
+ parentId,
107
+ });
108
+ return eachLimited(transfers, concurrency, async (item) => {
109
+ if (!item.sessionId)
110
+ throw new Error(`${item.object.relativePath}: batch did not return a session`);
111
+ const session = await workspace.uploads.resume(item.sessionId, await openImportSource({ object: item.object, bucket, token, signal }), { size: item.object.size, signal });
112
+ progress.completed[item.object.relativePath] = {
113
+ fileId: session.fileId,
114
+ uploadId: session.id,
115
+ size: item.object.size,
116
+ checksum: item.object.checksum,
117
+ idempotencyKey: item.idempotencyKey,
118
+ };
119
+ delete progress.inflight[item.object.relativePath];
120
+ await saveProgress(progressPath, progress);
121
+ console.error(`imported ${item.object.relativePath}`);
122
+ });
123
+ }
@@ -0,0 +1,30 @@
1
+ import { type StartStorageUpload } from '@sequenceholdings/storage';
2
+ import { type ImportProgress, type ImportSourceObject } from './import-plan.js';
3
+ /** The progress file and its `*.tmp` siblings are not source objects. */
4
+ export declare function isImportProgressFile({ relativePath, progressRelative, }: {
5
+ relativePath: string;
6
+ progressRelative: string | null;
7
+ }): boolean;
8
+ export declare function walkDirectory(root: string, options?: {
9
+ progressRelative?: string | null;
10
+ }): Promise<ImportSourceObject[]>;
11
+ export declare function loadProgress(path: string, expected: {
12
+ source: string;
13
+ workspaceId: string;
14
+ destPrefix: string;
15
+ parentId: string | null;
16
+ }): Promise<ImportProgress>;
17
+ /** One writer at a time. Concurrent completions share this file, and a shared temp path loses a rename. */
18
+ export declare function saveProgress(path: string, progress: ImportProgress): Promise<void>;
19
+ export declare function eachLimited<T>(items: T[], limit: number, run: (item: T) => Promise<void>): Promise<string[]>;
20
+ export declare function batchItem(item: {
21
+ destination: string;
22
+ idempotencyKey: string;
23
+ object: ImportSourceObject;
24
+ }, parentId: string | null): StartStorageUpload;
25
+ export declare function openImportSource({ object, bucket, token, signal, }: {
26
+ object: ImportSourceObject;
27
+ bucket?: string;
28
+ token: string | null;
29
+ signal: AbortSignal;
30
+ }): Promise<ReadableStream<Uint8Array<ArrayBufferLike>> | import("fs").ReadStream>;
@@ -0,0 +1,133 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createReadStream } from 'node:fs';
3
+ import { readdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
4
+ import { join, relative, sep } from 'node:path';
5
+ import { Crc32c } from '@sequenceholdings/storage';
6
+ import { openGcsObject } from './gcs-download.js';
7
+ import { emptyImportProgress, parseImportProgress, } from './import-plan.js';
8
+ /** The progress file and its `*.tmp` siblings are not source objects. */
9
+ export function isImportProgressFile({ relativePath, progressRelative, }) {
10
+ if (!progressRelative || progressRelative.startsWith('..') || progressRelative.startsWith('/'))
11
+ return false;
12
+ if (relativePath === progressRelative)
13
+ return true;
14
+ const slash = progressRelative.lastIndexOf('/');
15
+ const directory = slash === -1 ? '' : progressRelative.slice(0, slash + 1);
16
+ const base = progressRelative.slice(directory.length);
17
+ if (!relativePath.startsWith(directory))
18
+ return false;
19
+ const name = relativePath.slice(directory.length);
20
+ return name.startsWith(`${base}.`) && name.endsWith('.tmp') && !name.includes('/');
21
+ }
22
+ export async function walkDirectory(root, options) {
23
+ const progressRelative = options?.progressRelative ?? null;
24
+ const objects = [];
25
+ async function visit(current) {
26
+ for (const entry of await readdir(current, { withFileTypes: true })) {
27
+ if (entry.isSymbolicLink())
28
+ continue;
29
+ const path = join(current, entry.name);
30
+ if (entry.isDirectory())
31
+ await visit(path);
32
+ else if (entry.isFile()) {
33
+ const relativePath = relative(root, path).split(sep).join('/');
34
+ if (isImportProgressFile({ relativePath, progressRelative }))
35
+ continue;
36
+ const info = await stat(path);
37
+ objects.push({
38
+ relativePath,
39
+ size: info.size,
40
+ checksum: await checksumFile(path),
41
+ contentType: 'application/octet-stream',
42
+ sourceName: path,
43
+ });
44
+ }
45
+ }
46
+ }
47
+ await visit(root);
48
+ return objects;
49
+ }
50
+ async function checksumFile(path) {
51
+ const checksum = new Crc32c();
52
+ for await (const chunk of createReadStream(path))
53
+ checksum.update(chunk);
54
+ return checksum.digest();
55
+ }
56
+ export async function loadProgress(path, expected) {
57
+ try {
58
+ return parseImportProgress(JSON.parse(await readFile(path, 'utf8')), expected);
59
+ }
60
+ catch (error) {
61
+ if (error && typeof error === 'object' && 'code' in error && error.code === 'ENOENT')
62
+ return emptyImportProgress(expected);
63
+ throw error;
64
+ }
65
+ }
66
+ const progressWrites = new Map();
67
+ /** One writer at a time. Concurrent completions share this file, and a shared temp path loses a rename. */
68
+ export function saveProgress(path, progress) {
69
+ const previous = progressWrites.get(path) ?? Promise.resolve();
70
+ const write = previous
71
+ .catch(() => undefined)
72
+ .then(() => writeProgress(path, progress));
73
+ const tracked = write.finally(() => {
74
+ if (progressWrites.get(path) === tracked)
75
+ progressWrites.delete(path);
76
+ });
77
+ progressWrites.set(path, tracked);
78
+ return tracked;
79
+ }
80
+ async function writeProgress(path, progress) {
81
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
82
+ await writeFile(temporary, `${JSON.stringify(progress, null, 2)}\n`, { mode: 0o600 });
83
+ await rename(temporary, path);
84
+ }
85
+ export async function eachLimited(items, limit, run) {
86
+ const failures = [];
87
+ let cursor = 0;
88
+ async function worker() {
89
+ for (;;) {
90
+ const index = cursor;
91
+ cursor += 1;
92
+ const item = items[index];
93
+ if (!item)
94
+ return;
95
+ try {
96
+ await run(item);
97
+ }
98
+ catch (error) {
99
+ failures.push(error instanceof Error ? error.message : 'Import item failed');
100
+ }
101
+ }
102
+ }
103
+ const workers = Math.min(limit, items.length);
104
+ if (workers > 0)
105
+ await Promise.all(Array.from({ length: workers }, () => worker()));
106
+ return failures;
107
+ }
108
+ export function batchItem(item, parentId) {
109
+ return {
110
+ path: item.destination,
111
+ parentId,
112
+ size: item.object.size,
113
+ contentType: item.object.contentType,
114
+ idempotencyKey: item.idempotencyKey,
115
+ ...(item.object.checksum ? { checksum: item.object.checksum } : {}),
116
+ };
117
+ }
118
+ export async function openImportSource({ object, bucket, token, signal, }) {
119
+ if (!bucket) {
120
+ if (!object.sourceName)
121
+ throw new Error('Local import source is missing a path');
122
+ return createReadStream(object.sourceName);
123
+ }
124
+ if (!token || !object.sourceName)
125
+ throw new Error('GCS import is missing a credential or object name');
126
+ return openGcsObject({
127
+ fetch: globalThis.fetch,
128
+ token,
129
+ bucket,
130
+ name: object.sourceName,
131
+ signal,
132
+ });
133
+ }
@@ -0,0 +1,12 @@
1
+ export interface GcloudIdentity {
2
+ project: string | null;
3
+ account: string | null;
4
+ tokenExpiry: string | null;
5
+ accessToken: string | null;
6
+ error: string | null;
7
+ }
8
+ export declare function readGcloudIdentity(): Promise<GcloudIdentity>;
9
+ export declare function listGcsObjects({ bucket, prefix, }: {
10
+ bucket: string;
11
+ prefix: string;
12
+ }): Promise<unknown>;
@@ -0,0 +1,54 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { z } from 'zod';
4
+ const exec = promisify(execFile);
5
+ const gcloudConfigSchema = z.object({
6
+ configuration: z
7
+ .object({
8
+ properties: z
9
+ .object({
10
+ core: z
11
+ .object({ project: z.string().optional(), account: z.string().optional() })
12
+ .optional(),
13
+ })
14
+ .optional(),
15
+ })
16
+ .optional(),
17
+ credential: z
18
+ .object({ access_token: z.string().optional(), token_expiry: z.string().optional() })
19
+ .optional(),
20
+ });
21
+ export async function readGcloudIdentity() {
22
+ const empty = { project: null, account: null, tokenExpiry: null, accessToken: null };
23
+ try {
24
+ const { stdout } = await exec('gcloud', ['config', 'config-helper', '--format=json'], {
25
+ timeout: 15_000,
26
+ maxBuffer: 1024 * 1024,
27
+ });
28
+ let parsed;
29
+ try {
30
+ parsed = gcloudConfigSchema.parse(JSON.parse(stdout));
31
+ }
32
+ catch {
33
+ return { ...empty, error: 'gcloud config-helper returned an unexpected payload' };
34
+ }
35
+ return {
36
+ project: parsed.configuration?.properties?.core?.project ?? null,
37
+ account: parsed.configuration?.properties?.core?.account ?? null,
38
+ tokenExpiry: parsed.credential?.token_expiry ?? null,
39
+ accessToken: parsed.credential?.access_token ?? null,
40
+ error: null,
41
+ };
42
+ }
43
+ catch {
44
+ // The failure can include config-helper stdout, which carries the access token.
45
+ return { ...empty, error: 'gcloud config-helper failed' };
46
+ }
47
+ }
48
+ export async function listGcsObjects({ bucket, prefix, }) {
49
+ const uri = prefix ? `gs://${bucket}/${prefix}` : `gs://${bucket}`;
50
+ const { stdout } = await exec('gcloud', ['storage', 'objects', 'list', uri, '--format=json'], { timeout: 120_000, maxBuffer: 32 * 1024 * 1024 });
51
+ if (!stdout.trim())
52
+ return [];
53
+ return JSON.parse(stdout);
54
+ }
@@ -0,0 +1,12 @@
1
+ /** Whether a published version is the source bytes, not merely the same size. */
2
+ export declare function publishedIdentity({ versions, fileId, versionId, checksum, }: {
3
+ versions?: (fileId: string) => Promise<{
4
+ items: Array<{
5
+ id: string;
6
+ checksum: string;
7
+ }>;
8
+ }>;
9
+ fileId: string;
10
+ versionId: string;
11
+ checksum?: string;
12
+ }): Promise<'match' | 'mismatch' | 'unknown'>;