@sequenceholdings/studio-cli 0.9.0 → 0.9.2

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/dist/orm/read.js CHANGED
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * Both run the namespace's built-in read-only SQL operation through the
6
6
  * published ORM client (`createOperationExecutorWithTransport(...).sql()`),
7
- * which owns the `{ op, variables }` wire format. Requests go through the CLI's
7
+ * which owns the `{ op, variables, expectedKind? }` wire format. Requests go through the CLI's
8
8
  * Atlas client so environment resolution, sandbox tokens, and edge headers
9
9
  * behave like every other command. The server compiles the SQL in its closed
10
10
  * read-only grammar and enforces grants, row-level security, and its row,
@@ -191,9 +191,9 @@ export function buildReadSql({ plan, columnTypes }) {
191
191
  }
192
192
  /** The ORM client's operation transport, served by the CLI's Atlas client. */
193
193
  function atlasTransport({ baseUrl, token }) {
194
- return async ({ namespace, op, variables }) => {
194
+ return async ({ namespace, op, variables, expectedKind }) => {
195
195
  // The data endpoint `orm execute` uses; it shares the deployment gate of the /api/orm discovery routes.
196
- const response = await postJsonResponse({ baseUrl, token, path: `/api/data/v2/${namespace}`, body: { op, variables } });
196
+ const response = await postJsonResponse({ baseUrl, token, path: `/api/data/v2/${namespace}`, body: { op, variables, expectedKind } });
197
197
  let body = null;
198
198
  try {
199
199
  body = JSON.parse(response.body);
@@ -262,13 +262,19 @@ async function buildBundleForPublish(args, compiled) {
262
262
  export async function planCommand(args) {
263
263
  const compiled = await compileLocalProcessSource(args);
264
264
  const bundle = await buildBundleForPublish(args, compiled);
265
- // Static graph limits (LAT-148): run limits lint so `process plan` matches registration.
265
+ // Static graph limits (LAT-148) and the definition lint `apply` enforces,
266
+ // so a plan that passes does not fail at apply or at run time (for example a
267
+ // human `input` projection without upstream).
266
268
  const limitLint = lintBundleStaticGraphLimits({ bundle });
267
- const formattedLint = formatLintResult(limitLint);
269
+ const planLint = {
270
+ errors: [...compiled.lint.errors, ...limitLint.errors],
271
+ warnings: [...compiled.lint.warnings, ...limitLint.warnings],
272
+ };
273
+ const formattedLint = formatLintResult(planLint);
268
274
  if (formattedLint.text)
269
275
  console.log(formattedLint.text);
270
276
  if (formattedLint.hasErrors) {
271
- console.error(`\nplan FAILED — ${limitLint.errors.length} static graph limit error(s), ${limitLint.warnings.length} warning(s)`);
277
+ console.error(`\nplan FAILED — ${planLint.errors.length} lint error(s), ${planLint.warnings.length} warning(s)`);
272
278
  return 1;
273
279
  }
274
280
  const summary = summarizeBundle(bundle);
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Pre-deploy check for a human node's `input` projection. Atlas persists the
3
+ * projection as the step's ctx snapshot and fails the run at that node when it
4
+ * is not `{ entity, run, upstream }`. Lint reports a projection only when the
5
+ * problem cannot depend on the run's real data:
6
+ *
7
+ * - a JSONata projection whose root is an object constructor without one of
8
+ * the required literal keys (read from the parsed expression, not evaluated);
9
+ * - a JS projection that, run against a probe ctx, returns an object without a
10
+ * required key. Values read from upstream outputs are stand-ins that count as
11
+ * present, and a mapper that spreads or enumerates upstream data is
12
+ * inconclusive, because the real data could supply the keys.
13
+ *
14
+ * Anything else (a mapper that throws on probe data, returns a promise or a
15
+ * stand-in, or a JSONata root that is not an object constructor) passes.
16
+ */
17
+ /**
18
+ * The problem with a human node's `input` projection, or `undefined` when it
19
+ * is valid, absent, or the check was inconclusive.
20
+ */
21
+ export declare function probeHumanInputProjection({ input }: {
22
+ input: unknown;
23
+ }): string | undefined;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Pre-deploy check for a human node's `input` projection. Atlas persists the
3
+ * projection as the step's ctx snapshot and fails the run at that node when it
4
+ * is not `{ entity, run, upstream }`. Lint reports a projection only when the
5
+ * problem cannot depend on the run's real data:
6
+ *
7
+ * - a JSONata projection whose root is an object constructor without one of
8
+ * the required literal keys (read from the parsed expression, not evaluated);
9
+ * - a JS projection that, run against a probe ctx, returns an object without a
10
+ * required key. Values read from upstream outputs are stand-ins that count as
11
+ * present, and a mapper that spreads or enumerates upstream data is
12
+ * inconclusive, because the real data could supply the keys.
13
+ *
14
+ * Anything else (a mapper that throws on probe data, returns a promise or a
15
+ * stand-in, or a JSONata root that is not an object constructor) passes.
16
+ */
17
+ import { describeHumanCtxProjectionProblem, isJsonataExpr } from '@sequenceholdings/lattice/define';
18
+ import { jsonataObjectConstructorKeys } from '@sequenceholdings/lattice/jsonata-runtime';
19
+ const PROBE_RUN = {
20
+ id: 'lint-probe-run',
21
+ process_id: 'lint-probe-process',
22
+ version: 'lint-probe-version',
23
+ started_at: '2026-01-01T00:00:00.000Z',
24
+ started_by: null,
25
+ trigger_reason: null,
26
+ metadata: {},
27
+ };
28
+ /** Tracks the probe stand-ins one mapper call produced and touched. */
29
+ class ProbeSession {
30
+ standIns = new WeakSet();
31
+ /** Set when the mapper enumerated stand-in keys, e.g. `{ ...upstream.x }`. */
32
+ enumerated = false;
33
+ /**
34
+ * A stand-in for upstream data: every property read, call and coercion
35
+ * returns another stand-in, so a mapper that walks deep into
36
+ * `ctx.upstream.<node>` completes and its result shape can be checked.
37
+ */
38
+ standIn() {
39
+ const session = this;
40
+ const value = new Proxy(function probeValue() { }, {
41
+ get(_target, key) {
42
+ if (key === Symbol.toPrimitive)
43
+ return () => '';
44
+ if (key === Symbol.iterator)
45
+ return function* empty() { };
46
+ if (key === 'then' || typeof key === 'symbol')
47
+ return undefined;
48
+ if (key === 'toJSON')
49
+ return () => null;
50
+ return value;
51
+ },
52
+ apply: () => value,
53
+ has: () => true,
54
+ ownKeys(target) {
55
+ session.enumerated = true;
56
+ return Reflect.ownKeys(target);
57
+ },
58
+ });
59
+ this.standIns.add(value);
60
+ return value;
61
+ }
62
+ ctx() {
63
+ const nodeOutput = this.standIn();
64
+ const session = this;
65
+ return {
66
+ entity: { type: 'lint-probe', id: 'lint-probe' },
67
+ upstream: new Proxy({}, {
68
+ get: (target, key) => (typeof key === 'symbol' ? Reflect.get(target, key) : nodeOutput),
69
+ has: () => true,
70
+ ownKeys(target) {
71
+ session.enumerated = true;
72
+ return Reflect.ownKeys(target);
73
+ },
74
+ }),
75
+ state: {},
76
+ run: { ...PROBE_RUN },
77
+ };
78
+ }
79
+ /** The result with stand-in values replaced by `{}`, so they count as present objects. */
80
+ settle(result) {
81
+ if (typeof result !== 'object' || result === null || Array.isArray(result))
82
+ return result;
83
+ return Object.fromEntries(Object.entries(result).map(([key, value]) => [key, typeof value === 'function' && this.standIns.has(value) ? {} : value]));
84
+ }
85
+ }
86
+ function probeJsFunction(mapper) {
87
+ const session = new ProbeSession();
88
+ let projected;
89
+ try {
90
+ projected = mapper(session.ctx());
91
+ }
92
+ catch {
93
+ // Probe data the mapper did not expect: inconclusive, not a finding.
94
+ return undefined;
95
+ }
96
+ if (projected instanceof Promise || session.enumerated)
97
+ return undefined;
98
+ if (typeof projected === 'function' && session.standIns.has(projected))
99
+ return undefined;
100
+ return describeHumanCtxProjectionProblem(session.settle(projected));
101
+ }
102
+ function probeJsonata(expr) {
103
+ const keys = jsonataObjectConstructorKeys(expr);
104
+ if (keys === undefined)
105
+ return undefined;
106
+ return describeHumanCtxProjectionProblem(Object.fromEntries(keys.map((key) => [key, {}])));
107
+ }
108
+ /**
109
+ * The problem with a human node's `input` projection, or `undefined` when it
110
+ * is valid, absent, or the check was inconclusive.
111
+ */
112
+ export function probeHumanInputProjection({ input }) {
113
+ if (typeof input === 'function')
114
+ return probeJsFunction(input);
115
+ if (isJsonataExpr(input))
116
+ return probeJsonata(input.expr);
117
+ return undefined;
118
+ }
@@ -8,6 +8,8 @@
8
8
  * JSON Schema, confirm edge_id enum matches outgoing_edges
9
9
  * - Human timeout edge — if timeout is set and outgoing_edges.length > 0
10
10
  * but on_timeout_edge_id is unset, warn
11
+ * - Human input projection — probe the `input` mapper and fail when it
12
+ * does not return { entity, run, upstream }
11
13
  */
12
14
  import { type LatticeBundle } from '@sequenceholdings/lattice/bundle';
13
15
  import type { ProcessDefinition } from '@sequenceholdings/lattice/define';
@@ -8,12 +8,15 @@
8
8
  * JSON Schema, confirm edge_id enum matches outgoing_edges
9
9
  * - Human timeout edge — if timeout is set and outgoing_edges.length > 0
10
10
  * but on_timeout_edge_id is unset, warn
11
+ * - Human input projection — probe the `input` mapper and fail when it
12
+ * does not return { entity, run, upstream }
11
13
  */
12
14
  import { readFileSync } from 'node:fs';
13
15
  import { checkBundleStaticGraphLimits, forEachSerializedNode, measureBundleStaticGraph, } from '@sequenceholdings/lattice/bundle';
14
16
  import { DEFAULT_LATTICE_SAFETY_PROFILE, LATTICE_SAFETY_CEILINGS, } from '@sequenceholdings/lattice';
15
17
  import { isJsonataExpr, parallelSubNodes, validateEmailReminders } from '@sequenceholdings/lattice/define';
16
18
  import { assertJsonataExpr } from '@sequenceholdings/lattice/jsonata-runtime';
19
+ import { probeHumanInputProjection } from './human-input-probe.js';
17
20
  export async function lintProcesses(input) {
18
21
  const errors = [];
19
22
  const warnings = [];
@@ -745,6 +748,13 @@ function lintParallelJoin(processId, node, errors, warnings) {
745
748
  }
746
749
  }
747
750
  function lintHuman(processId, node, errors, warnings) {
751
+ // Atlas persists an `input` projection as the step's ctx snapshot and fails
752
+ // the run at this node when it is not { entity, run, upstream }. Only
753
+ // problems that cannot depend on the run's data are reported.
754
+ const projectionProblem = probeHumanInputProjection({ input: node.input });
755
+ if (projectionProblem !== undefined) {
756
+ errors.push({ process_id: processId, node_id: node.id, message: `input: ${projectionProblem}` });
757
+ }
748
758
  // Email reminders that can never fire (offset before the task is ready, or
749
759
  // after it times out / past the cap) are author bugs the runner silently
750
760
  // skips — catch them here. Only the object form carries reminders.
@@ -0,0 +1,112 @@
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 declare const STEP_FIELD_PREVIEW_CHARS = 2000;
9
+ /** A step row as the run-detail route returns it (redacted, camelCase). */
10
+ export interface RunStepRow {
11
+ id?: string;
12
+ nodeId: string;
13
+ kind: string | null;
14
+ attempt: number | null;
15
+ status: string;
16
+ branchId?: string | null;
17
+ nextEdgeId?: string | null;
18
+ startedAt: string | null;
19
+ completedAt: string | null;
20
+ error?: unknown;
21
+ input?: unknown;
22
+ output?: unknown;
23
+ }
24
+ /**
25
+ * Which fields were cut, and the full serialized length of each. Kept apart
26
+ * from the values so a payload that happens to contain `truncated: true` is
27
+ * never mistaken for a cut one.
28
+ */
29
+ export type TruncatedFields<TField extends string> = Partial<Record<TField, {
30
+ chars: number;
31
+ }>>;
32
+ type StepField = 'error' | 'input' | 'output';
33
+ export interface StepDetail {
34
+ id: string | null;
35
+ nodeId: string;
36
+ kind: string | null;
37
+ attempt: number | null;
38
+ status: string;
39
+ branchId: string | null;
40
+ nextEdgeId: string | null;
41
+ startedAt: string | null;
42
+ completedAt: string | null;
43
+ error: unknown;
44
+ input: unknown;
45
+ output: unknown;
46
+ /** Fields replaced by their first {@link STEP_FIELD_PREVIEW_CHARS} characters. */
47
+ truncated: TruncatedFields<StepField>;
48
+ }
49
+ /**
50
+ * Bound each named field of `record`: a value whose serialized form is longer
51
+ * than {@link STEP_FIELD_PREVIEW_CHARS} becomes its preview string and is
52
+ * listed in `truncated` with its full length. `full` keeps every value whole.
53
+ */
54
+ export declare function boundFields<TField extends string>({ record, fields, full, }: {
55
+ record: Partial<Record<TField, unknown>>;
56
+ fields: readonly TField[];
57
+ full: boolean;
58
+ }): {
59
+ values: Record<TField, unknown>;
60
+ truncated: TruncatedFields<TField>;
61
+ };
62
+ /**
63
+ * The steps to show, in the route's order, optionally narrowed to one node,
64
+ * with their inputs, outputs and errors bounded unless `full`.
65
+ */
66
+ export declare function stepDetails({ steps, node, full, }: {
67
+ steps: readonly RunStepRow[];
68
+ node?: string;
69
+ full: boolean;
70
+ }): StepDetail[];
71
+ /** Human-readable blocks, one per step. */
72
+ export declare function formatStepDetails(steps: readonly StepDetail[]): string[];
73
+ export declare function errorText(error: unknown): string | undefined;
74
+ export interface StepOptions {
75
+ node?: string;
76
+ full: boolean;
77
+ }
78
+ /** `--steps` options, or `undefined` without `--steps`; `--node`/`--full` need it. */
79
+ export declare function stepOptions({ steps, node, full }: {
80
+ steps: boolean;
81
+ node?: string;
82
+ full: boolean;
83
+ }): StepOptions | undefined;
84
+ interface RunWithSteps<TRun> {
85
+ run: TRun;
86
+ steps: readonly RunStepRow[];
87
+ }
88
+ /** `--steps --json`: the run plus bounded step detail, never the raw rows. */
89
+ export declare function runWithSteps<TRun extends {
90
+ state?: unknown;
91
+ output?: unknown;
92
+ }>({ detail, options, }: {
93
+ detail: RunWithSteps<TRun>;
94
+ options: StepOptions;
95
+ }): {
96
+ run: TRun & {
97
+ truncated: Partial<Record<"state" | "output", {
98
+ chars: number;
99
+ }>>;
100
+ state: unknown;
101
+ output: unknown;
102
+ };
103
+ steps: StepDetail[];
104
+ };
105
+ export declare function printRunSteps<TRun extends {
106
+ error?: unknown;
107
+ }>({ detail, options, printHeader, }: {
108
+ detail: RunWithSteps<TRun>;
109
+ options: StepOptions;
110
+ printHeader: (run: TRun) => void;
111
+ }): void;
112
+ export {};
@@ -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,8 +1,8 @@
1
1
  /**
2
2
  * `seq-studio process runs <start|retry|list|show|cancel>` — start, retry and
3
3
  * observe Lattice runs through the programmatic run API, as the caller.
4
- * Starting or retrying needs `invoker` on the process; reading a run needs
5
- * `viewer` on it.
4
+ * Starting or retrying needs `invoker` on the process; reading a run, and
5
+ * `show --steps` step detail, needs `viewer` on it.
6
6
  */
7
7
  import type { ParsedArgs } from './commands.js';
8
8
  type Sleep = (ms: number) => Promise<void>;
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * `seq-studio process runs <start|retry|list|show|cancel>` — start, retry and
3
3
  * observe Lattice runs through the programmatic run API, as the caller.
4
- * Starting or retrying needs `invoker` on the process; reading a run needs
5
- * `viewer` on it.
4
+ * Starting or retrying needs `invoker` on the process; reading a run, and
5
+ * `show --steps` step detail, needs `viewer` on it.
6
6
  */
7
7
  import { randomUUID } from 'node:crypto';
8
8
  import { readFile } from 'node:fs/promises';
@@ -12,6 +12,7 @@ import { PROCESS_RUNS_USAGE } from '../command-help.js';
12
12
  import { validateCommandInput } from '../command-input.js';
13
13
  import { buildContext, clientOptions } from '../functions/commands.js';
14
14
  import { table } from '../text-table.js';
15
+ import { errorText, printRunSteps, runWithSteps, stepOptions } from './run-steps.js';
15
16
  const RUN_STATUSES = ['pending', 'running', 'completed', 'failed', 'cancelled', 'timed_out'];
16
17
  const TERMINAL_STATUSES = new Set(['completed', 'failed', 'cancelled', 'timed_out']);
17
18
  const RETRYABLE_STATUSES = new Set(['failed', 'cancelled', 'timed_out']);
@@ -45,15 +46,6 @@ function newRunId(args) {
45
46
  }
46
47
  return runId ?? randomUUID();
47
48
  }
48
- function errorText(error) {
49
- if (error === null || error === undefined)
50
- return undefined;
51
- if (typeof error === 'string')
52
- return error;
53
- if (typeof error === 'object' && typeof Reflect.get(error, 'message') === 'string')
54
- return String(Reflect.get(error, 'message'));
55
- return JSON.stringify(error);
56
- }
57
49
  async function metadataFromFile(path) {
58
50
  let parsed;
59
51
  try {
@@ -133,16 +125,21 @@ function printRunsTable(runs) {
133
125
  rows: runs.map((run) => [run.id, run.processId, run.processVersion, run.status, run.startedAt, run.completedAt, run.title]),
134
126
  });
135
127
  }
136
- function printRunDetail({ run, steps }) {
128
+ function printRunHeader(run) {
137
129
  console.log(`Run: ${run.id} | Process: ${run.processId}@${run.processVersion ?? '—'} | Status: ${run.status}`);
138
130
  console.log(`Started: ${run.startedAt ?? '—'} | Completed: ${run.completedAt ?? '—'}`);
139
131
  const runError = errorText(run.error);
140
132
  if (runError)
141
133
  console.log(`Error: ${runError}`);
134
+ }
135
+ function printRunDetail({ run, steps }) {
136
+ printRunHeader(run);
142
137
  table({
143
138
  headers: ['NODE', 'KIND', 'ATTEMPT', 'STATUS', 'STARTED', 'COMPLETED', 'ERROR'],
144
139
  rows: steps.map((step) => [step.nodeId, step.kind, step.attempt, step.status, step.startedAt, step.completedAt, errorText(step.error)]),
145
140
  });
141
+ if (steps.length > 0)
142
+ console.error(`Step inputs, outputs and errors: seq-studio process runs show ${run.id} --steps`);
146
143
  }
147
144
  async function waitForTerminal({ load, timeoutSeconds, sleep, }) {
148
145
  const deadline = Date.now() + timeoutSeconds * 1000;
@@ -221,13 +218,22 @@ function waitTimeoutSeconds(args) {
221
218
  return seconds;
222
219
  }
223
220
  async function showRun({ args, json, sleep }) {
224
- 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
+ });
225
226
  const runId = runIdArg({ args, label: 'run id' });
226
227
  const timeoutSeconds = waitTimeoutSeconds(args);
228
+ const steps = stepOptions({ node: stringFlag({ args, key: 'node' }), steps: args.flags.steps === true, full: args.flags.full === true });
227
229
  const ctx = await buildContext(args);
228
230
  const load = () => getJson({ ...clientOptions(ctx), path: `/api/lattice/runs/${encodeURIComponent(runId)}` });
229
231
  const detail = args.flags.wait === true ? await waitForTerminal({ load, timeoutSeconds, sleep }) : await load();
230
- 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)
231
237
  console.log(JSON.stringify(detail, null, 2));
232
238
  else
233
239
  printRunDetail(detail);
@@ -75,6 +75,19 @@ export declare function createRepo({ ctx, namespace, name, defaultBranch, gitBac
75
75
  defaultBranch?: string;
76
76
  gitBackend?: 'walgit';
77
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>;
78
91
  export declare function reposCreateCommand(args: ParsedArgs): Promise<number>;
79
92
  export declare function reposPullCommand(args: ParsedArgs): Promise<number>;
80
93
  /** A real Git checkout needs a user login or a sandbox credential, never an M2M identity. */
@@ -314,6 +314,30 @@ export async function createRepo({ ctx, namespace, name, defaultBranch, gitBacke
314
314
  },
315
315
  });
316
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
+ }
317
341
  export async function reposCreateCommand(args) {
318
342
  const { namespace, name } = parseRepoPath(args.positional[0]);
319
343
  const ctx = await reposContext(args);
@@ -331,6 +355,10 @@ export async function reposCreateCommand(args) {
331
355
  });
332
356
  const backend = repo.gitBackend ?? gitBackend;
333
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
+ }
334
362
  return 0;
335
363
  }
336
364
  async function materializeTree({ ctx, namespace, name, destDir, ref, verb, }) {
@@ -0,0 +1,43 @@
1
+ export type StandalonePrimitiveKind = 'orm' | 'function' | 'artifact';
2
+ export interface ResourceEntry {
3
+ id: string;
4
+ kind: StandalonePrimitiveKind;
5
+ path: string;
6
+ namespace?: string;
7
+ slug?: string;
8
+ project_id?: string;
9
+ }
10
+ export type ResourceDeclarationPlan = {
11
+ action: 'write';
12
+ indexPath: string;
13
+ content: string;
14
+ entry: ResourceEntry;
15
+ created: boolean;
16
+ } | {
17
+ action: 'skip';
18
+ reason?: string;
19
+ };
20
+ /** Plan the index change for a primitive just scaffolded at `dir`. */
21
+ export declare function planResourceDeclaration({ kind, dir }: {
22
+ kind: StandalonePrimitiveKind;
23
+ dir: string;
24
+ }): Promise<ResourceDeclarationPlan>;
25
+ /**
26
+ * After a successful standalone init, declare the scaffold for repository CI.
27
+ * Never changes the init's exit code: a declaration problem is a warning with
28
+ * the manual fix.
29
+ */
30
+ export declare function declareScaffoldedPrimitive({ kind, dir }: {
31
+ kind: StandalonePrimitiveKind;
32
+ dir: string;
33
+ }): Promise<void>;
34
+ /**
35
+ * Run a standalone init (`argv` is everything after `init`), then declare its
36
+ * scaffold. `defaultDir` is where the init scaffolds without a positional.
37
+ */
38
+ export declare function runStandaloneInit({ kind, argv, defaultDir, run }: {
39
+ kind: StandalonePrimitiveKind;
40
+ argv: readonly string[];
41
+ defaultDir?: string;
42
+ run: () => Promise<number>;
43
+ }): Promise<number>;