@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.
Files changed (89) hide show
  1. package/README.md +414 -55
  2. package/dist/access/commands.d.ts +1 -1
  3. package/dist/access/commands.js +102 -55
  4. package/dist/access/custom-role-hosts.d.ts +3 -0
  5. package/dist/access/custom-role-hosts.js +88 -0
  6. package/dist/access/group-rosters.d.ts +6 -0
  7. package/dist/access/group-rosters.js +33 -0
  8. package/dist/access/host-contract.d.ts +55 -0
  9. package/dist/access/host-contract.js +33 -0
  10. package/dist/access/hosts.d.ts +4 -0
  11. package/dist/access/hosts.js +60 -0
  12. package/dist/access/principal.d.ts +16 -0
  13. package/dist/access/principal.js +36 -0
  14. package/dist/access/roles.d.ts +18 -0
  15. package/dist/access/roles.js +89 -0
  16. package/dist/access/tier-hosts.d.ts +12 -0
  17. package/dist/access/tier-hosts.js +206 -0
  18. package/dist/agents/commands.d.ts +1 -1
  19. package/dist/agents/commands.js +76 -16
  20. package/dist/agents/scaffold.js +8 -3
  21. package/dist/app/commands.js +37 -12
  22. package/dist/app/manifest.d.ts +2 -2
  23. package/dist/app/official-source.d.ts +4 -2
  24. package/dist/app/official-source.js +6 -4
  25. package/dist/app/readme.js +2 -2
  26. package/dist/app/repository-index.d.ts +6 -0
  27. package/dist/app/repository-index.js +2 -2
  28. package/dist/app/workspace-model.js +4 -0
  29. package/dist/app/workspace-scaffold.js +5 -3
  30. package/dist/app/workspace.d.ts +2 -0
  31. package/dist/app/workspace.js +1 -1
  32. package/dist/artifact/delegate.js +26 -3
  33. package/dist/artifact/sandbox.js +2 -1
  34. package/dist/atlas-client.d.ts +15 -8
  35. package/dist/atlas-client.js +140 -64
  36. package/dist/bin.js +9 -1
  37. package/dist/cli-errors.js +4 -0
  38. package/dist/command-contract.d.ts +8 -2
  39. package/dist/command-contract.js +3 -2
  40. package/dist/command-help.d.ts +8 -6
  41. package/dist/command-help.js +65 -14
  42. package/dist/env-flags.d.ts +7 -0
  43. package/dist/env-flags.js +23 -0
  44. package/dist/functions/commands.js +66 -11
  45. package/dist/functions/manifest.d.ts +5 -0
  46. package/dist/functions/manifest.js +44 -23
  47. package/dist/functions/service-account-guidance.d.ts +21 -0
  48. package/dist/functions/service-account-guidance.js +62 -0
  49. package/dist/functions/workspace.d.ts +11 -0
  50. package/dist/functions/workspace.js +52 -0
  51. package/dist/machine-output.d.ts +7 -0
  52. package/dist/machine-output.js +56 -0
  53. package/dist/main.d.ts +2 -1
  54. package/dist/main.js +32 -4
  55. package/dist/orm/delegate.js +49 -6
  56. package/dist/orm/execute.js +11 -5
  57. package/dist/orm/failures.d.ts +32 -0
  58. package/dist/orm/failures.js +75 -0
  59. package/dist/orm/read.js +3 -3
  60. package/dist/orm/version-guard.d.ts +3 -0
  61. package/dist/orm/version-guard.js +63 -0
  62. package/dist/pipeline/commands.js +4 -1
  63. package/dist/principals/commands.d.ts +3 -0
  64. package/dist/principals/commands.js +124 -0
  65. package/dist/process/commands.js +9 -3
  66. package/dist/process/human-input-probe.d.ts +23 -0
  67. package/dist/process/human-input-probe.js +118 -0
  68. package/dist/process/lint.d.ts +2 -0
  69. package/dist/process/lint.js +10 -0
  70. package/dist/process/run-steps.d.ts +112 -0
  71. package/dist/process/run-steps.js +123 -0
  72. package/dist/process/runs.d.ts +4 -3
  73. package/dist/process/runs.js +69 -21
  74. package/dist/release-age.d.ts +1 -1
  75. package/dist/release-age.js +1 -0
  76. package/dist/repos/commands.d.ts +57 -0
  77. package/dist/repos/commands.js +83 -15
  78. package/dist/repos/init-repo.d.ts +45 -0
  79. package/dist/repos/init-repo.js +257 -0
  80. package/dist/repos/primitive-declaration.d.ts +43 -0
  81. package/dist/repos/primitive-declaration.js +212 -0
  82. package/dist/sandbox-unpushed-warning.d.ts +23 -0
  83. package/dist/sandbox-unpushed-warning.js +86 -0
  84. package/dist/service-accounts/commands.js +15 -3
  85. package/dist/templates/commands.d.ts +14 -2
  86. package/dist/templates/commands.js +70 -16
  87. package/dist/templates/process/pnpm-workspace.yaml +1 -0
  88. package/package.json +15 -12
  89. package/templates/process/pnpm-workspace.yaml +1 -0
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Step-level detail for `seq-studio process runs show <run-id> --steps`: each
3
+ * step's status, edge, error, input and output, read from the same run-detail
4
+ * response `runs show` already fetches (run `viewer`). Large inputs and
5
+ * outputs are cut to a preview unless the caller asks for `--full`.
6
+ */
7
+ /** Characters kept from one serialized input, output or error. */
8
+ export const STEP_FIELD_PREVIEW_CHARS = 2_000;
9
+ function serialized(value) {
10
+ return typeof value === 'string' ? value : (JSON.stringify(value) ?? String(value));
11
+ }
12
+ /**
13
+ * Bound each named field of `record`: a value whose serialized form is longer
14
+ * than {@link STEP_FIELD_PREVIEW_CHARS} becomes its preview string and is
15
+ * listed in `truncated` with its full length. `full` keeps every value whole.
16
+ */
17
+ export function boundFields({ record, fields, full, }) {
18
+ const values = {};
19
+ const truncated = {};
20
+ for (const field of fields) {
21
+ const value = record[field] ?? null;
22
+ const text = full || value === null ? '' : serialized(value);
23
+ if (text.length > STEP_FIELD_PREVIEW_CHARS) {
24
+ values[field] = text.slice(0, STEP_FIELD_PREVIEW_CHARS);
25
+ truncated[field] = { chars: text.length };
26
+ }
27
+ else {
28
+ values[field] = value;
29
+ }
30
+ }
31
+ return { values, truncated };
32
+ }
33
+ const STEP_FIELDS = ['error', 'input', 'output'];
34
+ /**
35
+ * The steps to show, in the route's order, optionally narrowed to one node,
36
+ * with their inputs, outputs and errors bounded unless `full`.
37
+ */
38
+ export function stepDetails({ steps, node, full, }) {
39
+ return steps
40
+ .filter((step) => node === undefined || step.nodeId === node)
41
+ .map((step) => {
42
+ const { values, truncated } = boundFields({ record: step, fields: STEP_FIELDS, full });
43
+ return {
44
+ id: step.id ?? null,
45
+ nodeId: step.nodeId,
46
+ kind: step.kind,
47
+ attempt: step.attempt,
48
+ status: step.status,
49
+ branchId: step.branchId ?? null,
50
+ nextEdgeId: step.nextEdgeId ?? null,
51
+ startedAt: step.startedAt,
52
+ completedAt: step.completedAt,
53
+ error: values.error,
54
+ input: values.input,
55
+ output: values.output,
56
+ truncated,
57
+ };
58
+ });
59
+ }
60
+ function fieldLine({ label, value, cut }) {
61
+ if (value === null || value === undefined)
62
+ return undefined;
63
+ if (cut)
64
+ return ` ${label}: ${serialized(value)}… (${cut.chars} chars; --full prints all)`;
65
+ return ` ${label}: ${serialized(value)}`;
66
+ }
67
+ /** Human-readable blocks, one per step. */
68
+ export function formatStepDetails(steps) {
69
+ const lines = [];
70
+ for (const step of steps) {
71
+ const branch = step.branchId ? ` branch ${step.branchId}` : '';
72
+ lines.push('', `${step.nodeId}${branch} (${step.kind ?? '?'}) attempt ${step.attempt ?? '?'} | ${step.status} | ${step.startedAt ?? '—'} → ${step.completedAt ?? '—'}`);
73
+ if (step.nextEdgeId)
74
+ lines.push(` edge: ${step.nextEdgeId}`);
75
+ for (const label of STEP_FIELDS) {
76
+ const line = fieldLine({ label, value: step[label], cut: step.truncated[label] });
77
+ if (line)
78
+ lines.push(line);
79
+ }
80
+ }
81
+ return lines;
82
+ }
83
+ export function errorText(error) {
84
+ if (error === null || error === undefined)
85
+ return undefined;
86
+ if (typeof error === 'string')
87
+ return error;
88
+ if (typeof error === 'object' && typeof Reflect.get(error, 'message') === 'string')
89
+ return String(Reflect.get(error, 'message'));
90
+ return JSON.stringify(error);
91
+ }
92
+ /** `--steps` options, or `undefined` without `--steps`; `--node`/`--full` need it. */
93
+ export function stepOptions({ steps, node, full }) {
94
+ if (!steps) {
95
+ if (node !== undefined || full)
96
+ throw new Error('--node and --full apply only with --steps.');
97
+ return undefined;
98
+ }
99
+ return { ...(node !== undefined ? { node } : {}), full };
100
+ }
101
+ /** `--steps --json`: the run plus bounded step detail, never the raw rows. */
102
+ export function runWithSteps({ detail, options, }) {
103
+ const { run } = detail;
104
+ const { values, truncated } = boundFields({ record: run, fields: ['state', 'output'], full: options.full });
105
+ return {
106
+ run: { ...run, ...values, truncated },
107
+ steps: stepDetails({ steps: detail.steps, ...options }),
108
+ };
109
+ }
110
+ export function printRunSteps({ detail, options, printHeader, }) {
111
+ const steps = stepDetails({ steps: detail.steps, ...options });
112
+ printHeader(detail.run);
113
+ for (const line of formatStepDetails(steps))
114
+ console.log(line);
115
+ if (steps.length === 0) {
116
+ console.error(options.node === undefined ? 'No steps recorded yet.' : `No steps recorded for node '${options.node}'.`);
117
+ }
118
+ // A node whose input mapper fails never gets a step row, so the run error
119
+ // printed in the header is the only place that failure shows.
120
+ if (errorText(detail.run.error) && !detail.steps.some((step) => errorText(step.error))) {
121
+ console.error('No step recorded the run error: it happened before a step started (for example, in its input mapper) or between steps.');
122
+ }
123
+ }
@@ -1,7 +1,8 @@
1
1
  /**
2
- * `seq-studio process runs <start|list|show|cancel>` — start and observe
3
- * Lattice runs through the programmatic run API, as the caller. Starting needs
4
- * `invoker` on the process; reading a run needs `viewer` on it.
2
+ * `seq-studio process runs <start|retry|list|show|cancel>` — start, retry and
3
+ * observe Lattice runs through the programmatic run API, as the caller.
4
+ * Starting or retrying needs `invoker` on the process; reading a run, and
5
+ * `show --steps` step detail, needs `viewer` on it.
5
6
  */
6
7
  import type { ParsedArgs } from './commands.js';
7
8
  type Sleep = (ms: number) => Promise<void>;
@@ -1,8 +1,10 @@
1
1
  /**
2
- * `seq-studio process runs <start|list|show|cancel>` — start and observe
3
- * Lattice runs through the programmatic run API, as the caller. Starting needs
4
- * `invoker` on the process; reading a run needs `viewer` on it.
2
+ * `seq-studio process runs <start|retry|list|show|cancel>` — start, retry and
3
+ * observe Lattice runs through the programmatic run API, as the caller.
4
+ * Starting or retrying needs `invoker` on the process; reading a run, and
5
+ * `show --steps` step detail, needs `viewer` on it.
5
6
  */
7
+ import { randomUUID } from 'node:crypto';
6
8
  import { readFile } from 'node:fs/promises';
7
9
  import { getJson, postJson } from '../atlas-client.js';
8
10
  import { printCliError } from '../cli-errors.js';
@@ -10,12 +12,18 @@ import { PROCESS_RUNS_USAGE } from '../command-help.js';
10
12
  import { validateCommandInput } from '../command-input.js';
11
13
  import { buildContext, clientOptions } from '../functions/commands.js';
12
14
  import { table } from '../text-table.js';
15
+ import { errorText, printRunSteps, runWithSteps, stepOptions } from './run-steps.js';
13
16
  const RUN_STATUSES = ['pending', 'running', 'completed', 'failed', 'cancelled', 'timed_out'];
14
17
  const TERMINAL_STATUSES = new Set(['completed', 'failed', 'cancelled', 'timed_out']);
18
+ const RETRYABLE_STATUSES = new Set(['failed', 'cancelled', 'timed_out']);
15
19
  const RUN_ID = /^[A-Za-z0-9._-]{2,128}$/;
16
20
  const MAX_LIST_LIMIT = 500;
17
21
  const DEFAULT_WAIT_SECONDS = 600;
18
22
  const WAIT_POLL_MS = 2_000;
23
+ /** Atlas holds a new run `pending` when its process is at `max_concurrent_runs`. */
24
+ function queuedNote(outcome) {
25
+ return outcome === 'queued' ? ' (queued: the process is at its concurrent-run limit; it starts when a slot frees)' : '';
26
+ }
19
27
  function stringFlag({ args, key }) {
20
28
  const value = args.flags[key];
21
29
  return typeof value === 'string' ? value : undefined;
@@ -26,14 +34,17 @@ function runIdArg({ args, label }) {
26
34
  throw new Error(`Invalid ${label} '${value}': 2-128 letters, digits, '.', '_' or '-'.`);
27
35
  return value;
28
36
  }
29
- function errorText(error) {
30
- if (error === null || error === undefined)
31
- return undefined;
32
- if (typeof error === 'string')
33
- return error;
34
- if (typeof error === 'object' && typeof Reflect.get(error, 'message') === 'string')
35
- return String(Reflect.get(error, 'message'));
36
- return JSON.stringify(error);
37
+ /**
38
+ * The new run's id: `--run-id` when given, else a fresh UUID. Minting it here
39
+ * rather than leaving it to Atlas keeps the client's own 503 retries of the
40
+ * POST from ever starting a second run.
41
+ */
42
+ function newRunId(args) {
43
+ const runId = stringFlag({ args, key: 'run-id' });
44
+ if (runId !== undefined && !RUN_ID.test(runId)) {
45
+ throw new Error(`Invalid --run-id '${runId}': 2-128 letters, digits, '.', '_' or '-'.`);
46
+ }
47
+ return runId ?? randomUUID();
37
48
  }
38
49
  async function metadataFromFile(path) {
39
50
  let parsed;
@@ -55,10 +66,7 @@ export async function startRunBody(args) {
55
66
  flags: { version: 'string', 'run-id': 'string', 'metadata-file': 'string', title: 'string', entity: 'string' },
56
67
  positional: 2,
57
68
  });
58
- const runId = stringFlag({ args, key: 'run-id' });
59
- if (runId !== undefined && !RUN_ID.test(runId)) {
60
- throw new Error(`Invalid --run-id '${runId}': 2-128 letters, digits, '.', '_' or '-'.`);
61
- }
69
+ const runId = newRunId(args);
62
70
  const entity = stringFlag({ args, key: 'entity' });
63
71
  const separator = entity?.indexOf(':') ?? -1;
64
72
  if (entity !== undefined && (separator < 1 || separator === entity.length - 1)) {
@@ -70,7 +78,7 @@ export async function startRunBody(args) {
70
78
  return {
71
79
  process_id: args.positional[1],
72
80
  ...(version !== undefined ? { version } : {}),
73
- ...(runId !== undefined ? { run_id: runId } : {}),
81
+ run_id: runId,
74
82
  ...(title !== undefined ? { title } : {}),
75
83
  ...(entity !== undefined ? { entity: { type: entity.slice(0, separator), id: entity.slice(separator + 1) } } : {}),
76
84
  ...(metadataFile !== undefined ? { metadata: await metadataFromFile(metadataFile) } : {}),
@@ -117,16 +125,21 @@ function printRunsTable(runs) {
117
125
  rows: runs.map((run) => [run.id, run.processId, run.processVersion, run.status, run.startedAt, run.completedAt, run.title]),
118
126
  });
119
127
  }
120
- function printRunDetail({ run, steps }) {
128
+ function printRunHeader(run) {
121
129
  console.log(`Run: ${run.id} | Process: ${run.processId}@${run.processVersion ?? '—'} | Status: ${run.status}`);
122
130
  console.log(`Started: ${run.startedAt ?? '—'} | Completed: ${run.completedAt ?? '—'}`);
123
131
  const runError = errorText(run.error);
124
132
  if (runError)
125
133
  console.log(`Error: ${runError}`);
134
+ }
135
+ function printRunDetail({ run, steps }) {
136
+ printRunHeader(run);
126
137
  table({
127
138
  headers: ['NODE', 'KIND', 'ATTEMPT', 'STATUS', 'STARTED', 'COMPLETED', 'ERROR'],
128
139
  rows: steps.map((step) => [step.nodeId, step.kind, step.attempt, step.status, step.startedAt, step.completedAt, errorText(step.error)]),
129
140
  });
141
+ if (steps.length > 0)
142
+ console.error(`Step inputs, outputs and errors: seq-studio process runs show ${run.id} --steps`);
130
143
  }
131
144
  async function waitForTerminal({ load, timeoutSeconds, sleep, }) {
132
145
  const deadline = Date.now() + timeoutSeconds * 1000;
@@ -148,8 +161,33 @@ async function startRun({ args, json }) {
148
161
  console.log(JSON.stringify(result, null, 2));
149
162
  return 0;
150
163
  }
151
- const replay = result.idempotent_replay ? ' (existing run; --run-id already used)' : '';
152
- console.log(`Run: ${result.run_id} | Process: ${result.process_id}@${result.process_version ?? '—'} | Status: ${result.status}${replay}`);
164
+ const status = result.existing_status ?? result.status;
165
+ const replay = result.idempotent_replay ? ' (existing run; a run id names one run and never starts another)' : '';
166
+ console.log(`Run: ${result.run_id} | Process: ${result.process_id}@${result.process_version ?? '—'} | Status: ${status}${replay}${queuedNote(result.outcome)}`);
167
+ if (result.idempotent_replay && RETRYABLE_STATUSES.has(status)) {
168
+ console.log(`Retry it with: seq-studio process runs retry ${result.run_id}`);
169
+ }
170
+ else {
171
+ console.log(`Follow it with: seq-studio process runs show ${result.run_id} --wait`);
172
+ }
173
+ return 0;
174
+ }
175
+ async function retryRun({ args, json }) {
176
+ validateCommandInput({ args, flags: { 'run-id': 'string' }, positional: 2 });
177
+ const sourceRunId = runIdArg({ args, label: 'run id' });
178
+ const runId = newRunId(args);
179
+ const ctx = await buildContext(args);
180
+ const result = await postJson({
181
+ ...clientOptions(ctx),
182
+ path: `/api/lattice/runs/${encodeURIComponent(sourceRunId)}/retry`,
183
+ body: { run_id: runId },
184
+ });
185
+ if (json) {
186
+ console.log(JSON.stringify(result, null, 2));
187
+ return 0;
188
+ }
189
+ const replay = result.idempotent_replay ? ' (existing retry; this run id was already used)' : '';
190
+ console.log(`Run: ${result.run_id} | Retry of: ${result.retry_of} | Process: ${result.process_id}@${result.process_version ?? '—'} | Status: ${result.status}${replay}${queuedNote(result.outcome)}`);
153
191
  console.log(`Follow it with: seq-studio process runs show ${result.run_id} --wait`);
154
192
  return 0;
155
193
  }
@@ -180,13 +218,22 @@ function waitTimeoutSeconds(args) {
180
218
  return seconds;
181
219
  }
182
220
  async function showRun({ args, json, sleep }) {
183
- validateCommandInput({ args, flags: { wait: 'boolean', timeout: 'string' }, positional: 2 });
221
+ validateCommandInput({
222
+ args,
223
+ flags: { wait: 'boolean', timeout: 'string', steps: 'boolean', node: 'string', full: 'boolean' },
224
+ positional: 2,
225
+ });
184
226
  const runId = runIdArg({ args, label: 'run id' });
185
227
  const timeoutSeconds = waitTimeoutSeconds(args);
228
+ const steps = stepOptions({ node: stringFlag({ args, key: 'node' }), steps: args.flags.steps === true, full: args.flags.full === true });
186
229
  const ctx = await buildContext(args);
187
230
  const load = () => getJson({ ...clientOptions(ctx), path: `/api/lattice/runs/${encodeURIComponent(runId)}` });
188
231
  const detail = args.flags.wait === true ? await waitForTerminal({ load, timeoutSeconds, sleep }) : await load();
189
- if (json)
232
+ if (steps && json)
233
+ console.log(JSON.stringify(runWithSteps({ detail, options: steps }), null, 2));
234
+ else if (steps)
235
+ printRunSteps({ detail, options: steps, printHeader: printRunHeader });
236
+ else if (json)
190
237
  console.log(JSON.stringify(detail, null, 2));
191
238
  else
192
239
  printRunDetail(detail);
@@ -208,6 +255,7 @@ async function cancelRun({ args, json }) {
208
255
  }
209
256
  const RUN_ACTIONS = {
210
257
  start: startRun,
258
+ retry: retryRun,
211
259
  list: listRuns,
212
260
  show: showRun,
213
261
  cancel: cancelRun,
@@ -9,4 +9,4 @@
9
9
  * The YAML templates under templates/ carry the same list; a test keeps them
10
10
  * in sync with this one.
11
11
  */
12
- export declare const FIRST_PARTY_RELEASE_AGE_EXCLUDE: readonly ["@sequenceholdings/agent-spec", "@sequenceholdings/artifact-studio", "@sequenceholdings/atlas-ui", "@sequenceholdings/custom-roles-manifest", "@sequenceholdings/lattice", "@sequenceholdings/lattice-form-renderer", "@sequenceholdings/managed-functions", "@sequenceholdings/orm", "@sequenceholdings/pipeline-spec", "@sequenceholdings/storage", "@sequenceholdings/studio-cli"];
12
+ export declare const FIRST_PARTY_RELEASE_AGE_EXCLUDE: readonly ["@sequenceholdings/agent-spec", "@sequenceholdings/artifact-studio", "@sequenceholdings/atlas-ui", "@sequenceholdings/custom-roles-manifest", "@sequenceholdings/lattice", "@sequenceholdings/lattice-form-renderer", "@sequenceholdings/managed-functions", "@sequenceholdings/orm", "@sequenceholdings/pipeline-spec", "@sequenceholdings/platform", "@sequenceholdings/storage", "@sequenceholdings/studio-cli"];
@@ -19,6 +19,7 @@ export const FIRST_PARTY_RELEASE_AGE_EXCLUDE = [
19
19
  '@sequenceholdings/managed-functions',
20
20
  '@sequenceholdings/orm',
21
21
  '@sequenceholdings/pipeline-spec',
22
+ '@sequenceholdings/platform',
22
23
  '@sequenceholdings/storage',
23
24
  '@sequenceholdings/studio-cli',
24
25
  ];
@@ -1,7 +1,27 @@
1
1
  import type { ParsedArgs } from '../process/commands.js';
2
2
  import { type CommandContext } from '../functions/commands.js';
3
3
  import { type RunGitClone } from './git-clone.js';
4
+ import type { RepositoryIdentity } from '@sequenceholdings/artifact-studio/repository-identity';
4
5
  import { type ResolvedEnv } from '../config.js';
6
+ interface ReviewPolicyDTO {
7
+ codexReview?: boolean;
8
+ claudeReview?: boolean;
9
+ requiredReviews?: boolean;
10
+ requiredReviewMode?: string;
11
+ requiredChecks?: string[];
12
+ }
13
+ export interface RepoDTO {
14
+ id: string;
15
+ namespaceId: string;
16
+ name: string;
17
+ defaultBranch: string;
18
+ reviewPolicy?: ReviewPolicyDTO | null;
19
+ gitBackend?: string;
20
+ repositoryIdentity?: RepositoryIdentity | null;
21
+ createdBy: string;
22
+ createdAt: string;
23
+ updatedAt: string;
24
+ }
5
25
  export declare function parseRepoPath(input: string | undefined): {
6
26
  namespace: string;
7
27
  name: string;
@@ -43,8 +63,45 @@ export declare function assertSafeForceDest(destDir: string): void;
43
63
  export declare function reposNamespacesCommand(args: ParsedArgs): Promise<number>;
44
64
  export declare function reposListCommand(args: ParsedArgs): Promise<number>;
45
65
  export declare function reposShowCommand(args: ParsedArgs): Promise<number>;
66
+ /**
67
+ * Create a git-service repo. Without `gitBackend` Atlas seeds it with a README
68
+ * and the `.seq/identity.json` receipt; `gitBackend: 'walgit'` creates it empty
69
+ * for pushing existing history. 409 when the name is taken.
70
+ */
71
+ export declare function createRepo({ ctx, namespace, name, defaultBranch, gitBackend, }: {
72
+ ctx: CommandContext;
73
+ namespace: string;
74
+ name: string;
75
+ defaultBranch?: string;
76
+ gitBackend?: 'walgit';
77
+ }): Promise<RepoDTO>;
78
+ /**
79
+ * Wait until `namespace/name` resolves for the caller, the lookup every later
80
+ * command (clone, show, pull) uses. An Atlas that authorizes that lookup only
81
+ * through OpenFGA's cached object list can omit a new repo for up to 10s.
82
+ * Returns false when it is still not readable after about 12s, or the lookup fails.
83
+ */
84
+ export declare function waitUntilRepoReadable({ ctx, namespace, name, repoId, sleep, }: {
85
+ ctx: CommandContext;
86
+ namespace: string;
87
+ name: string;
88
+ repoId: string;
89
+ sleep?: (ms: number) => Promise<void>;
90
+ }): Promise<boolean>;
46
91
  export declare function reposCreateCommand(args: ParsedArgs): Promise<number>;
47
92
  export declare function reposPullCommand(args: ParsedArgs): Promise<number>;
93
+ /** A real Git checkout needs a user login or a sandbox credential, never an M2M identity. */
94
+ export declare function assertGitCheckoutAuth(ctx: CommandContext): void;
95
+ /**
96
+ * Clone a resolved repository's default branch (shallow, like `repos clone`)
97
+ * into an absent or empty `destDir`. Returns the origin URL it configured.
98
+ */
99
+ export declare function cloneRepoById({ ctx, repoId, destDir, gitClone, }: {
100
+ ctx: CommandContext;
101
+ repoId: string;
102
+ destDir: string;
103
+ gitClone?: RunGitClone;
104
+ }): Promise<string>;
48
105
  /** Git clone always uses the selected human login, never an ambient PAT. */
49
106
  export declare function reposCloneCommand(args: ParsedArgs, deps?: {
50
107
  gitClone?: RunGitClone;
@@ -297,15 +297,13 @@ function parseGitBackendFlag(args) {
297
297
  }
298
298
  return gitBackend;
299
299
  }
300
- export async function reposCreateCommand(args) {
301
- const { namespace, name } = parseRepoPath(args.positional[0]);
302
- const ctx = await reposContext(args);
303
- const defaultBranch = stringFlag(args.flags, 'default-branch');
304
- const gitBackend = parseGitBackendFlag(args);
305
- if (gitBackend === 'walgit' && defaultBranch !== undefined && defaultBranch !== 'main') {
306
- throw new Error('walgit create does not set HEAD from --default-branch; omit it or use main.');
307
- }
308
- const repo = await postJson({
300
+ /**
301
+ * Create a git-service repo. Without `gitBackend` Atlas seeds it with a README
302
+ * and the `.seq/identity.json` receipt; `gitBackend: 'walgit'` creates it empty
303
+ * for pushing existing history. 409 when the name is taken.
304
+ */
305
+ export async function createRepo({ ctx, namespace, name, defaultBranch, gitBackend, }) {
306
+ return postJson({
309
307
  ...clientOptions(ctx),
310
308
  path: '/api/git-service/repos',
311
309
  body: {
@@ -315,8 +313,52 @@ export async function reposCreateCommand(args) {
315
313
  ...(gitBackend ? { gitBackend } : {}),
316
314
  },
317
315
  });
316
+ }
317
+ const READABLE_WAIT_DELAYS_MS = [250, 500, 1000, 2000, 4000, 4000];
318
+ /**
319
+ * Wait until `namespace/name` resolves for the caller, the lookup every later
320
+ * command (clone, show, pull) uses. An Atlas that authorizes that lookup only
321
+ * through OpenFGA's cached object list can omit a new repo for up to 10s.
322
+ * Returns false when it is still not readable after about 12s, or the lookup fails.
323
+ */
324
+ export async function waitUntilRepoReadable({ ctx, namespace, name, repoId, sleep = (ms) => new Promise((done) => setTimeout(done, ms)), }) {
325
+ for (const delay of [0, ...READABLE_WAIT_DELAYS_MS]) {
326
+ if (delay > 0)
327
+ await sleep(delay);
328
+ try {
329
+ if ((await resolveRepo({ ...clientOptions(ctx), namespace, name })).id === repoId)
330
+ return true;
331
+ }
332
+ catch (error) {
333
+ // Only "not found (or not readable)" is worth waiting out; the repo
334
+ // exists either way, so an HTTP failure here never fails the create.
335
+ if (typeof Reflect.get(Object(error), 'status') === 'number')
336
+ return false;
337
+ }
338
+ }
339
+ return false;
340
+ }
341
+ export async function reposCreateCommand(args) {
342
+ const { namespace, name } = parseRepoPath(args.positional[0]);
343
+ const ctx = await reposContext(args);
344
+ const defaultBranch = stringFlag(args.flags, 'default-branch');
345
+ const gitBackend = parseGitBackendFlag(args);
346
+ if (gitBackend === 'walgit' && defaultBranch !== undefined && defaultBranch !== 'main') {
347
+ throw new Error('walgit create does not set HEAD from --default-branch; omit it or use main.');
348
+ }
349
+ const repo = await createRepo({
350
+ ctx,
351
+ namespace,
352
+ name,
353
+ ...(defaultBranch ? { defaultBranch } : {}),
354
+ ...(gitBackend ? { gitBackend } : {}),
355
+ });
318
356
  const backend = repo.gitBackend ?? gitBackend;
319
357
  console.log(`${LOG} created ${namespace}/${name} (id=${repo.id}, default branch ${repo.defaultBranch}${backend ? `, gitBackend=${backend}` : ''}) on ${ctx.env.name}`);
358
+ if (!(await waitUntilRepoReadable({ ctx, namespace, name, repoId: repo.id }))) {
359
+ console.error(`${LOG} ${namespace}/${name} is not readable by name yet; if repos clone reports it missing, retry in a few seconds ` +
360
+ `or clone by id: seq-studio repos clone --id ${repo.id}${isSandboxTokenMode() ? '' : ` -e ${ctx.env.name}`}`);
361
+ }
320
362
  return 0;
321
363
  }
322
364
  async function materializeTree({ ctx, namespace, name, destDir, ref, verb, }) {
@@ -373,13 +415,40 @@ function parseCloneOptions(args) {
373
415
  throw new Error('--transport json requires <namespace>/<name>.');
374
416
  return { force, ref, depth, output, urlFlag, idFlag, positional, transport };
375
417
  }
376
- async function gitCloneContext(args) {
377
- const ctx = await reposContext(args);
418
+ /** A real Git checkout needs a user login or a sandbox credential, never an M2M identity. */
419
+ export function assertGitCheckoutAuth(ctx) {
378
420
  if (ctx.authMode === 'm2m') {
379
421
  throw new Error(`Git clone requires a user login: seq-studio login --env ${ctx.env.name}. Use repos pull for M2M JSON materialization.`);
380
422
  }
423
+ }
424
+ async function gitCloneContext(args) {
425
+ const ctx = await reposContext(args);
426
+ assertGitCheckoutAuth(ctx);
381
427
  return ctx;
382
428
  }
429
+ /**
430
+ * Clone over smart-HTTP into `destDir` (absent or empty unless `force`) and
431
+ * bind the checkout's credential helper to this environment and repository.
432
+ */
433
+ async function cloneCheckout({ ctx, targetUrl, destDir, force, ref, depth, gitClone, }) {
434
+ prepareCloneDest({ destDir, force });
435
+ await (gitClone ?? runGitClone)({
436
+ cloneUrl: targetUrl, destDir, pat: ctx.token,
437
+ ...(ref ? { ref } : {}),
438
+ ...(depth != null ? { depth } : {}),
439
+ });
440
+ await configureGitLogin({ destDir, envName: ctx.env.name, cloneUrl: targetUrl });
441
+ }
442
+ /**
443
+ * Clone a resolved repository's default branch (shallow, like `repos clone`)
444
+ * into an absent or empty `destDir`. Returns the origin URL it configured.
445
+ */
446
+ export async function cloneRepoById({ ctx, repoId, destDir, gitClone, }) {
447
+ assertGitCheckoutAuth(ctx);
448
+ const targetUrl = normalizeCloneUrl(cloneUrl(ctx, repoId), ctx.env);
449
+ await cloneCheckout({ ctx, targetUrl, destDir, force: false, depth: smartHttpCloneDepth({ full: false }), ...(gitClone ? { gitClone } : {}) });
450
+ return targetUrl;
451
+ }
383
452
  /** Git clone always uses the selected human login, never an ambient PAT. */
384
453
  export async function reposCloneCommand(args, deps = {}) {
385
454
  const { force, ref, depth, output, urlFlag, idFlag, positional, transport } = parseCloneOptions(args);
@@ -411,13 +480,12 @@ export async function reposCloneCommand(args, deps = {}) {
411
480
  }
412
481
  targetUrl = normalizeCloneUrl(targetUrl, env);
413
482
  const destDir = resolve(output ?? defaultOut);
414
- prepareCloneDest({ destDir, force });
415
- await (deps.gitClone ?? runGitClone)({
416
- cloneUrl: targetUrl, destDir, pat: ctx.token,
483
+ await cloneCheckout({
484
+ ctx, targetUrl, destDir, force,
417
485
  ...(ref ? { ref } : {}),
418
486
  ...(depth != null ? { depth } : {}),
487
+ ...(deps.gitClone ? { gitClone: deps.gitClone } : {}),
419
488
  });
420
- await configureGitLogin({ destDir, envName: env.name, cloneUrl: targetUrl });
421
489
  console.log(`${LOG} cloned ${positional ?? targetUrl} → ${destDir}` +
422
490
  (ref ? ` (ref ${ref})` : '') +
423
491
  ` via smart-HTTP${depth != null ? ` (depth ${depth})` : ''}`);
@@ -0,0 +1,45 @@
1
+ import type { ParsedArgs } from '../process/commands.js';
2
+ import type { RunGitClone } from './git-clone.js';
3
+ type LocalCheckout = {
4
+ mode: 'clone';
5
+ targetDir: string;
6
+ } | {
7
+ mode: 'origin';
8
+ root: string;
9
+ origin: string | null;
10
+ };
11
+ export declare function inspectLocalCheckout(targetDir: string): Promise<LocalCheckout>;
12
+ /** How the checkout came to point at the repository; it decides the push steps. */
13
+ export type RepoSetup = 'cloned' | 'origin-created' | 'origin-added' | 'origin-kept';
14
+ export declare function persistNextSteps({ root, repoPath, envName, defaultBranch, setup }: {
15
+ root: string;
16
+ repoPath: string;
17
+ envName: string;
18
+ defaultBranch: string;
19
+ setup: RepoSetup;
20
+ }): string[];
21
+ /**
22
+ * Prepare the repository checkout for `target`, run `scaffold` in it, then
23
+ * print how to commit and push. Returns the scaffold's exit code (1 when the
24
+ * repository could not be prepared).
25
+ */
26
+ export declare function runInitWithRepo({ args, target, scaffold, deps }: {
27
+ args: ParsedArgs;
28
+ target: string;
29
+ scaffold: () => Promise<number>;
30
+ deps?: {
31
+ gitClone?: RunGitClone;
32
+ };
33
+ }): Promise<number>;
34
+ /** The same parsed arguments with `--repo` removed, for the scaffold itself. */
35
+ export declare function withoutRepoFlag(args: ParsedArgs): ParsedArgs;
36
+ /**
37
+ * For delegated init commands that forward raw argv: split `--repo <v>` /
38
+ * `--repo=<v>` off. `repo` is undefined when absent and `true` when given
39
+ * without a value (so the caller can report it like any other flag).
40
+ */
41
+ export declare function extractRepoFlag(argv: readonly string[]): {
42
+ repo: string | true | undefined;
43
+ rest: string[];
44
+ };
45
+ export {};