@sequenceholdings/studio-cli 0.1.27 → 0.1.28

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 (61) hide show
  1. package/README.md +255 -72
  2. package/dist/app/adapters.d.ts +9 -0
  3. package/dist/app/adapters.js +176 -0
  4. package/dist/app/commands.d.ts +2 -2
  5. package/dist/app/commands.js +98 -22
  6. package/dist/app/deploy.d.ts +9 -10
  7. package/dist/app/deploy.js +83 -141
  8. package/dist/app/graph.d.ts +15 -0
  9. package/dist/app/graph.js +36 -0
  10. package/dist/app/manifest-validation.d.ts +16 -0
  11. package/dist/app/manifest-validation.js +99 -0
  12. package/dist/app/manifest.d.ts +27 -9
  13. package/dist/app/manifest.js +23 -107
  14. package/dist/app/paths.d.ts +14 -0
  15. package/dist/app/paths.js +77 -0
  16. package/dist/app/primitive-scaffold.d.ts +18 -0
  17. package/dist/app/primitive-scaffold.js +136 -0
  18. package/dist/app/readme.d.ts +4 -18
  19. package/dist/app/readme.js +105 -233
  20. package/dist/app/run-deployment.d.ts +8 -0
  21. package/dist/app/run-deployment.js +50 -0
  22. package/dist/app/scaffold-files.d.ts +13 -0
  23. package/dist/app/scaffold-files.js +68 -0
  24. package/dist/app/scaffold.d.ts +11 -3
  25. package/dist/app/scaffold.js +77 -245
  26. package/dist/app/workspace-compile.d.ts +18 -0
  27. package/dist/app/workspace-compile.js +143 -0
  28. package/dist/app/workspace-model.d.ts +70 -0
  29. package/dist/app/workspace-model.js +159 -0
  30. package/dist/app/workspace-scaffold.d.ts +27 -0
  31. package/dist/app/workspace-scaffold.js +126 -0
  32. package/dist/app/workspace.d.ts +14 -0
  33. package/dist/app/workspace.js +147 -0
  34. package/dist/atlas-client.js +28 -6
  35. package/dist/auth-cmds/commands.d.ts +1 -1
  36. package/dist/auth-cmds/commands.js +5 -2
  37. package/dist/functions/commands.js +7 -1
  38. package/dist/functions/manifest.d.ts +18 -0
  39. package/dist/functions/manifest.js +29 -4
  40. package/dist/main.js +8 -3
  41. package/dist/pat-hints.js +1 -0
  42. package/dist/pipeline/commands.js +27 -9
  43. package/dist/pipeline/lifecycle.d.ts +2 -0
  44. package/dist/pipeline/lifecycle.js +91 -11
  45. package/dist/process/build.js +59 -43
  46. package/dist/process/codegen.d.ts +3 -2
  47. package/dist/process/codegen.js +143 -27
  48. package/dist/process/commands.d.ts +2 -0
  49. package/dist/process/commands.js +63 -18
  50. package/dist/process/discover.d.ts +6 -3
  51. package/dist/process/discover.js +11 -3
  52. package/dist/process/lint.d.ts +14 -0
  53. package/dist/process/lint.js +143 -5
  54. package/dist/process/plan-diff.d.ts +8 -0
  55. package/dist/process/plan-diff.js +61 -4
  56. package/dist/process/safety-baseline.d.ts +154 -0
  57. package/dist/process/safety-baseline.js +387 -0
  58. package/dist/process/simulate.js +64 -22
  59. package/dist/repos/commands.d.ts +1 -1
  60. package/dist/repos/commands.js +29 -3
  61. package/package.json +6 -5
@@ -0,0 +1,387 @@
1
+ /**
2
+ * Lattice safety-profile baseline (LAT-140): scan every committed first-party
3
+ * process definition and derive the observed corpus maxima for each statically
4
+ * measurable safety-profile dimension. `seq-studio process safety-baseline`
5
+ * prints the report (`--write` refreshes the committed copy at
6
+ * atlas/lattice/SAFETY_PROFILE_BASELINE.md); safety-baseline.test.ts asserts
7
+ * the committed DEFAULT_LATTICE_SAFETY_PROFILE fits the whole corpus, which is
8
+ * the backwards-compatibility gate for the profile's defaults.
9
+ *
10
+ * Scanned corpus: every committed first-party apply root, discovered by
11
+ * RECURSIVELY finding each `process.ts` under both bases (`atlas/processes`
12
+ * and repo-root `processes/`, skipping node_modules/hidden dirs) and taking
13
+ * `dirname(dirname(file))` as its apply root — so arbitrarily nested layouts
14
+ * (`banksouth-mortgage/loan-handoff/loan-handoff/process.ts`) are covered.
15
+ * Repo-root packages' `@sequenceholdings/lattice` import resolves through the
16
+ * repo-root node_modules (the workspace SDK is a root devDependency), so they
17
+ * load through the same tsx lane.
18
+ *
19
+ * Every static-graph observation is taken from the CANONICAL BUILT BUNDLE per
20
+ * apply root (`buildBundleFromProcesses` with fixed provenance and normalized
21
+ * metadata) using the SDK's shared measurer (`measureBundleStaticGraph`,
22
+ * LAT-148) — the same walker registration enforces with — so the baseline
23
+ * measures exactly what the server will check. Raw TS source bytes are
24
+ * reported for information only.
25
+ *
26
+ * Determinism: roots and processes are iterated in sorted order, provenance
27
+ * and metadata are pinned to fixed values, and every observation is a pure
28
+ * function of the committed sources, so two derivations over the same tree
29
+ * are deep-equal (asserted by the test) and the committed report is
30
+ * byte-identical across machines.
31
+ */
32
+ import { readdir, readFile, stat, writeFile } from 'node:fs/promises';
33
+ import { join, relative } from 'node:path';
34
+ import { computeSubprocessChainDepths, forEachSerializedNode, isRecord, measureBundleStaticGraph, } from '@sequenceholdings/lattice/bundle';
35
+ import { buildBundleFromProcesses } from './build.js';
36
+ import { loadProcessDefinitions } from './discover.js';
37
+ /** Repo-relative path of the committed, generated baseline report. */
38
+ export const SAFETY_PROFILE_BASELINE_RELATIVE_PATH = 'atlas/lattice/SAFETY_PROFILE_BASELINE.md';
39
+ /**
40
+ * Fixed provenance + metadata for canonical bundle-byte measurement: the
41
+ * builder stamps wall-clock `created_at` and `$USER` into bundle metadata,
42
+ * which must not leak into a deterministic, machine-independent measurement.
43
+ * Hashes/version derive from the processes alone (finalizeBundleIdentity), so
44
+ * pinning metadata changes nothing else.
45
+ */
46
+ const CANONICAL_PROVENANCE = { gitCommit: null, gitBranch: null, gitDirty: false };
47
+ const CANONICAL_METADATA = {
48
+ created_at: '1970-01-01T00:00:00.000Z',
49
+ created_by: null,
50
+ git_commit: null,
51
+ git_branch: null,
52
+ git_dirty: false,
53
+ };
54
+ /**
55
+ * Neutralize the one transform-context-dependent artifact in serialized
56
+ * function sources: esbuild's keepNames helper is referenced as `__name` when
57
+ * process.ts goes through a single tsx transform (vitest) but `__name2` when
58
+ * the CLI itself already runs under the tsx loader (chained transforms pick a
59
+ * collision-free suffix). The suffix carries no information — canonical byte
60
+ * measurements strip it so the committed report is identical across lanes.
61
+ * The byte-identical report test catches any new helper drifting the same way.
62
+ */
63
+ const normalizeTransformArtifacts = (serialized) => serialized.replace(/\b__name\d+\b/g, '__name');
64
+ async function isDir(path) {
65
+ try {
66
+ return (await stat(path)).isDirectory();
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ }
72
+ async function fileExists(path) {
73
+ try {
74
+ await stat(path);
75
+ return true;
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ }
81
+ /**
82
+ * The committed first-party apply roots: recursively find every `process.ts`
83
+ * below each base dir (`atlas/processes`, repo-root `processes`), skipping
84
+ * node_modules and hidden dirs, and derive each file's apply root as the
85
+ * directory whose IMMEDIATE child owns it (`dirname(dirname(file))` — the
86
+ * `<root>/<id>/process.ts` registration unit loadProcessDefinitions loads one
87
+ * level deep). Unique + sorted. Arbitrarily nested layouts (e.g.
88
+ * `atlas/processes/banksouth-mortgage/loan-handoff/loan-handoff/process.ts`)
89
+ * resolve to their own root, and a dir can be an id dir under one root while
90
+ * parenting deeper roots without overlapping loads, because each root loads
91
+ * only its immediate children.
92
+ */
93
+ async function discoverApplyRoots({ repoRoot }) {
94
+ const roots = new Set();
95
+ const walk = async (dir) => {
96
+ const entries = (await readdir(dir)).sort((a, b) => a.localeCompare(b));
97
+ for (const entry of entries) {
98
+ if (entry === 'node_modules' || entry.startsWith('.'))
99
+ continue;
100
+ const child = join(dir, entry);
101
+ if (!(await isDir(child)))
102
+ continue;
103
+ if (await fileExists(join(child, 'process.ts')))
104
+ roots.add(dir);
105
+ await walk(child);
106
+ }
107
+ };
108
+ for (const baseRel of ['atlas/processes', 'processes']) {
109
+ const base = join(repoRoot, baseRel);
110
+ if (!(await isDir(base)))
111
+ continue;
112
+ await walk(base);
113
+ }
114
+ return [...roots].sort((a, b) => a.localeCompare(b));
115
+ }
116
+ function retryBoundsFromConfig(config) {
117
+ if (!isRecord(config))
118
+ return { attempts: 0, delayMs: 0 };
119
+ const attempts = typeof config['maxAttempts'] === 'number' ? config['maxAttempts'] : 0;
120
+ const maxTimeout = typeof config['maxTimeoutInMs'] === 'number' ? config['maxTimeoutInMs'] : 0;
121
+ const minTimeout = typeof config['minTimeoutInMs'] === 'number' ? config['minTimeoutInMs'] : 0;
122
+ return { attempts, delayMs: Math.max(maxTimeout, minTimeout) };
123
+ }
124
+ /**
125
+ * Largest explicit retry attempts / delay declared anywhere on a serialized
126
+ * process: node `metadata.middleware[]` configs (withRetry), the process's
127
+ * orchestrator `supervisor_retry`, and the parallel / subprocess runner
128
+ * `supervisor_retry` lanes. Runtime dimensions, so they sit beside (not
129
+ * inside) the SDK's static-graph measurement.
130
+ */
131
+ function observeRetryBounds(process) {
132
+ let attempts = 0;
133
+ let delayMs = 0;
134
+ const take = (config) => {
135
+ const bounds = retryBoundsFromConfig(config);
136
+ attempts = Math.max(attempts, bounds.attempts);
137
+ delayMs = Math.max(delayMs, bounds.delayMs);
138
+ };
139
+ take(process.supervisor_retry);
140
+ forEachSerializedNode(process.nodes, (node) => {
141
+ const middleware = node.metadata['middleware'];
142
+ if (Array.isArray(middleware)) {
143
+ for (const ref of middleware)
144
+ if (isRecord(ref))
145
+ take(ref['config']);
146
+ }
147
+ const parallel = node.metadata['parallel'];
148
+ if (isRecord(parallel))
149
+ take(parallel['supervisor_retry']);
150
+ const subprocess = node.metadata['subprocess'];
151
+ if (isRecord(subprocess))
152
+ take(subprocess['supervisor_retry']);
153
+ });
154
+ return { maxRetryAttempts: attempts, maxRetryDelayMs: delayMs };
155
+ }
156
+ const maxOf = (values) => values.length === 0 ? 0 : Math.max(...values);
157
+ /** Derive the observed baseline for the committed first-party process corpus. */
158
+ export async function deriveLatticeSafetyBaseline({ repoRoot, }) {
159
+ const rootDirs = await discoverApplyRoots({ repoRoot });
160
+ const roots = [];
161
+ const facts = [];
162
+ for (const rootDir of rootDirs) {
163
+ const rootRel = relative(repoRoot, rootDir);
164
+ const loaded = [...(await loadProcessDefinitions(rootDir))].sort((a, b) => a.process.id.localeCompare(b.process.id));
165
+ // The apply root is the registration unit: measure the CANONICAL built
166
+ // bundle (fixed provenance, normalized metadata, transform artifacts
167
+ // stripped) — the bytes and shape the registration-time limits see.
168
+ const built = await buildBundleFromProcesses(loaded, { provenance: CANONICAL_PROVENANCE });
169
+ const canonicalJson = normalizeTransformArtifacts(JSON.stringify({ ...built, metadata: CANONICAL_METADATA }));
170
+ // Round-trips a bundle we built one line above, so the shape is known;
171
+ // the cast only recovers the type JSON.parse discards.
172
+ const canonicalBundle = JSON.parse(canonicalJson);
173
+ const measured = measureBundleStaticGraph({
174
+ bundle: canonicalBundle,
175
+ bundleBytes: Buffer.byteLength(canonicalJson, 'utf8'),
176
+ });
177
+ const graphById = new Map(measured.processes.map((m) => [m.processId, m]));
178
+ const serializedById = new Map(canonicalBundle.processes.map((p) => [p.id, p]));
179
+ for (const { file, process: def } of loaded) {
180
+ const serialized = serializedById.get(def.id);
181
+ const graph = graphById.get(def.id);
182
+ if (serialized === undefined || graph === undefined) {
183
+ throw new Error(`bundle for ${rootRel} is missing serialized process "${def.id}"`);
184
+ }
185
+ facts.push({
186
+ root: rootRel,
187
+ file: relative(repoRoot, file),
188
+ serialized,
189
+ graph,
190
+ sourceBytes: Buffer.byteLength(await readFile(file, 'utf8')),
191
+ });
192
+ }
193
+ roots.push({ root: rootRel, processCount: loaded.length, bundleBytes: measured.bundleBytes });
194
+ }
195
+ // Cross-root subprocess graph (the SDK resolves chains within ONE bundle;
196
+ // the corpus spans many): union target sets when an id repeats.
197
+ const targetsById = new Map();
198
+ for (const fact of facts) {
199
+ const merged = new Set(targetsById.get(fact.serialized.id) ?? []);
200
+ for (const target of fact.graph.subprocessTargets)
201
+ merged.add(target);
202
+ targetsById.set(fact.serialized.id, [...merged].sort((a, b) => a.localeCompare(b)));
203
+ }
204
+ const { depths, cycles } = computeSubprocessChainDepths({ targetsById });
205
+ const processes = facts
206
+ .map(({ root, file, serialized, graph, sourceBytes }) => ({
207
+ root,
208
+ processId: serialized.id,
209
+ file,
210
+ nodeCount: graph.nodeCount,
211
+ edgeCount: graph.edgeCount,
212
+ parallelNestingDepth: graph.parallelNestingDepth,
213
+ subprocessTargets: graph.subprocessTargets,
214
+ subprocessChainDepth: depths.get(serialized.id) ?? 0,
215
+ linkedResourceRefs: graph.linkedResourceRefs,
216
+ fanoutProduct: graph.fanoutProduct,
217
+ maxIterations: serialized.max_iterations,
218
+ maxRevisits: serialized.max_revisits,
219
+ maxConcurrentRuns: serialized.max_concurrent_runs,
220
+ ...observeRetryBounds(serialized),
221
+ sourceBytes,
222
+ inlineSourceBytes: graph.inlineSourceBytes,
223
+ }))
224
+ .sort((a, b) => a.file.localeCompare(b.file));
225
+ const observed = {
226
+ staticGraph: {
227
+ maxProcessesPerBundle: maxOf(roots.map((r) => r.processCount)),
228
+ maxNodesPerProcess: maxOf(processes.map((p) => p.nodeCount)),
229
+ maxEdgesPerProcess: maxOf(processes.map((p) => p.edgeCount)),
230
+ maxLinkedResourceRefs: maxOf(processes.map((p) => p.linkedResourceRefs)),
231
+ maxParallelNestingDepth: maxOf(processes.map((p) => p.parallelNestingDepth)),
232
+ maxSubprocessNestingDepth: maxOf(processes.map((p) => p.subprocessChainDepth)),
233
+ maxInlineSourceBytes: maxOf(processes.map((p) => p.inlineSourceBytes)),
234
+ maxBundleBytes: maxOf(roots.map((r) => r.bundleBytes)),
235
+ },
236
+ runtime: {
237
+ maxIterationsPerRun: maxOf(processes.map((p) => p.maxIterations ?? 0)),
238
+ maxRevisitsPerNode: maxOf(processes.map((p) => p.maxRevisits ?? 0)),
239
+ maxFanoutProductPerRun: maxOf(processes.map((p) => p.fanoutProduct)),
240
+ maxRetryAttempts: maxOf(processes.map((p) => p.maxRetryAttempts)),
241
+ maxRetryDelayMs: maxOf(processes.map((p) => p.maxRetryDelayMs)),
242
+ maxConcurrentRunsPerProcess: maxOf(processes.map((p) => p.maxConcurrentRuns ?? 0)),
243
+ },
244
+ };
245
+ return { roots, processes, subprocessCycles: cycles, observed };
246
+ }
247
+ function fitChecks({ baseline, profile, }) {
248
+ const { observed } = baseline;
249
+ return [
250
+ { field: 'staticGraph.maxProcessesPerBundle', observed: observed.staticGraph.maxProcessesPerBundle, allowed: profile.staticGraph.maxProcessesPerBundle },
251
+ { field: 'staticGraph.maxNodesPerProcess', observed: observed.staticGraph.maxNodesPerProcess, allowed: profile.staticGraph.maxNodesPerProcess },
252
+ { field: 'staticGraph.maxEdgesPerProcess', observed: observed.staticGraph.maxEdgesPerProcess, allowed: profile.staticGraph.maxEdgesPerProcess },
253
+ { field: 'staticGraph.maxLinkedResourceRefs', observed: observed.staticGraph.maxLinkedResourceRefs, allowed: profile.staticGraph.maxLinkedResourceRefs },
254
+ { field: 'staticGraph.maxParallelNestingDepth', observed: observed.staticGraph.maxParallelNestingDepth, allowed: profile.staticGraph.maxParallelNestingDepth },
255
+ { field: 'staticGraph.maxSubprocessNestingDepth', observed: observed.staticGraph.maxSubprocessNestingDepth, allowed: profile.staticGraph.maxSubprocessNestingDepth },
256
+ { field: 'staticGraph.maxInlineSourceBytes (serialized inline source)', observed: observed.staticGraph.maxInlineSourceBytes, allowed: profile.staticGraph.maxInlineSourceBytes },
257
+ { field: 'staticGraph.maxBundleBytes (built bundle)', observed: observed.staticGraph.maxBundleBytes, allowed: profile.staticGraph.maxBundleBytes },
258
+ { field: 'runtime.maxIterationsPerRun', observed: observed.runtime.maxIterationsPerRun, allowed: profile.runtime.maxIterationsPerRun },
259
+ { field: 'runtime.maxRevisitsPerNode', observed: observed.runtime.maxRevisitsPerNode, allowed: profile.runtime.maxRevisitsPerNode },
260
+ { field: 'runtime.maxFanoutProductPerRun', observed: observed.runtime.maxFanoutProductPerRun, allowed: profile.runtime.maxFanoutProductPerRun },
261
+ { field: 'runtime.maxRetryAttempts', observed: observed.runtime.maxRetryAttempts, allowed: profile.runtime.maxRetryAttempts },
262
+ { field: 'runtime.maxRetryDelayMs', observed: observed.runtime.maxRetryDelayMs, allowed: profile.runtime.maxRetryDelayMs },
263
+ { field: 'runtime.maxConcurrentRunsPerProcess', observed: observed.runtime.maxConcurrentRunsPerProcess, allowed: profile.runtime.maxConcurrentRunsPerProcess },
264
+ ];
265
+ }
266
+ /**
267
+ * Assert every committed process fits the profile. Throws with the full
268
+ * violation list — the test gate that keeps the committed defaults ≥ what the
269
+ * committed corpus needs (LAT-140's backwards-compatibility requirement).
270
+ * A subprocess reference cycle also fails: chain depth is unbounded there.
271
+ */
272
+ export function assertBaselineFitsProfile({ baseline, profile, }) {
273
+ if (baseline.subprocessCycles.length > 0) {
274
+ throw new Error(`subprocess reference cycle(s) detected in the committed corpus — chain depth is ` +
275
+ `unbounded:\n${baseline.subprocessCycles.map((c) => ` ${c}`).join('\n')}\n` +
276
+ `Break the cycle before registering these processes.`);
277
+ }
278
+ const violations = fitChecks({ baseline, profile }).filter((check) => check.observed > check.allowed);
279
+ if (violations.length > 0) {
280
+ const lines = violations.map((v) => ` ${v.field}: observed ${v.observed} > allowed ${v.allowed}`);
281
+ throw new Error(`committed process corpus does not fit the safety profile:\n${lines.join('\n')}\n` +
282
+ `Raise the profile default (never shrink the process) and regenerate the ` +
283
+ `baseline report with \`seq-studio process safety-baseline --write\`.`);
284
+ }
285
+ }
286
+ function headroom({ observed, allowed }) {
287
+ if (observed === 0)
288
+ return 'unused';
289
+ return `${(allowed / observed).toFixed(1)}x`;
290
+ }
291
+ /** Render the human-readable baseline report (markdown, deterministic). */
292
+ export function formatSafetyBaselineReport({ baseline, profile, }) {
293
+ const lines = [];
294
+ lines.push('<!-- Generated by `seq-studio process safety-baseline --write` (LAT-140). Do not edit by hand. -->');
295
+ lines.push('');
296
+ lines.push('# Lattice safety-profile baseline');
297
+ lines.push('');
298
+ lines.push(`Scanned ${baseline.processes.length} committed process definitions across ` +
299
+ `${baseline.roots.length} apply roots under \`atlas/processes\` and the ` +
300
+ `repo-root \`processes/\` packages. Bundle bytes are the canonical BUILT ` +
301
+ `bundle per apply root (fixed provenance, normalized metadata); inline-source ` +
302
+ `bytes are the serialized \`*_source\`/\`*_expr\` mapper slots.`);
303
+ lines.push('');
304
+ lines.push('| dimension | observed max | default | headroom |');
305
+ lines.push('| --- | ---: | ---: | ---: |');
306
+ for (const check of fitChecks({ baseline, profile })) {
307
+ lines.push(`| ${check.field} | ${check.observed} | ${check.allowed} | ${headroom({
308
+ observed: check.observed,
309
+ allowed: check.allowed,
310
+ })} |`);
311
+ }
312
+ lines.push('');
313
+ lines.push('`schedules` and `invocationBudgets` are not statically derivable from committed ' +
314
+ 'bundles (schedules and spend live in the runtime database). Per-run invocation ' +
315
+ 'defaults align with the execution envelope so they cannot become hidden lower ' +
316
+ 'caps; a deployment can still tighten them.');
317
+ lines.push('');
318
+ lines.push('## Subprocess cycles');
319
+ lines.push('');
320
+ if (baseline.subprocessCycles.length === 0) {
321
+ lines.push('None detected across the committed subprocess graph.');
322
+ }
323
+ else {
324
+ for (const cycle of baseline.subprocessCycles) {
325
+ lines.push(`- ${cycle}`);
326
+ }
327
+ }
328
+ lines.push('');
329
+ lines.push('## Per-root process counts and built bundle bytes');
330
+ lines.push('');
331
+ for (const root of baseline.roots) {
332
+ lines.push(`- ${root.root}: ${root.processCount} process(es), ${root.bundleBytes} bundle bytes`);
333
+ }
334
+ return lines.join('\n');
335
+ }
336
+ async function findRepoRoot({ from }) {
337
+ let dir = from;
338
+ for (;;) {
339
+ try {
340
+ const stats = await stat(join(dir, 'atlas', 'processes'));
341
+ if (stats.isDirectory())
342
+ return dir;
343
+ }
344
+ catch {
345
+ // keep walking up
346
+ }
347
+ const parent = join(dir, '..');
348
+ if (parent === dir) {
349
+ throw new Error('could not locate the studio repo root (no atlas/processes above cwd); ' +
350
+ 'pass --repo-root <dir>');
351
+ }
352
+ dir = parent;
353
+ }
354
+ }
355
+ /**
356
+ * `seq-studio process safety-baseline [--repo-root <dir>] [--write]` — derive
357
+ * the baseline from the committed corpus, assert it fits the committed default
358
+ * profile, and print the markdown report. `--write` also refreshes the
359
+ * committed copy at {@link SAFETY_PROFILE_BASELINE_RELATIVE_PATH}.
360
+ */
361
+ export async function safetyBaselineCommand({ flags, }) {
362
+ const repoRootFlag = flags['repo-root'];
363
+ const repoRoot = typeof repoRootFlag === 'string'
364
+ ? repoRootFlag
365
+ : await findRepoRoot({ from: process.cwd() });
366
+ const baseline = await deriveLatticeSafetyBaseline({ repoRoot });
367
+ const { DEFAULT_LATTICE_SAFETY_PROFILE } = await import('@sequenceholdings/lattice');
368
+ const report = formatSafetyBaselineReport({
369
+ baseline,
370
+ profile: DEFAULT_LATTICE_SAFETY_PROFILE,
371
+ });
372
+ console.log(report);
373
+ if (flags['write'] === true) {
374
+ const reportPath = join(repoRoot, SAFETY_PROFILE_BASELINE_RELATIVE_PATH);
375
+ await writeFile(reportPath, `${report}\n`, 'utf8');
376
+ console.log(`\nWrote ${SAFETY_PROFILE_BASELINE_RELATIVE_PATH}`);
377
+ }
378
+ try {
379
+ assertBaselineFitsProfile({ baseline, profile: DEFAULT_LATTICE_SAFETY_PROFILE });
380
+ }
381
+ catch (error) {
382
+ console.error(`\n${error instanceof Error ? error.message : String(error)}`);
383
+ return 1;
384
+ }
385
+ console.log('\nAll committed processes fit the default safety profile.');
386
+ return 0;
387
+ }
@@ -10,10 +10,21 @@
10
10
  * - Stubs automation runner identically — native handlers live in the
11
11
  * Atlas image and can't execute here
12
12
  */
13
- import { DEFAULT_MAX_FANOUT_WIDTH, isJoinUndecided, } from '@sequenceholdings/lattice/define';
13
+ import { DEFAULT_MAX_FANOUT_WIDTH, isJoinUndecided, isJsonataExpr, MAX_PROCESS_ITERATIONS_CEILING, MAX_PROCESS_REVISITS_CEILING, } from '@sequenceholdings/lattice/define';
14
14
  import { extractOutputState, mergeRunState } from '@sequenceholdings/lattice';
15
- const DEFAULT_MAX_ITERATIONS = 1000;
16
- const DEFAULT_MAX_REVISITS = 100;
15
+ import { evaluateJsonata } from '@sequenceholdings/lattice/jsonata-runtime';
16
+ function recordDispatch({ budget, nodeId, }) {
17
+ budget.iterations += 1;
18
+ if (budget.iterations > budget.maxIterations) {
19
+ throw new Error(`iteration cap (${budget.maxIterations}) exceeded`);
20
+ }
21
+ const visitsForNode = (budget.visitsByNodeId.get(nodeId) ?? 0) + 1;
22
+ budget.visitsByNodeId.set(nodeId, visitsForNode);
23
+ if (visitsForNode > budget.maxRevisits) {
24
+ throw new Error(`revisit cap (${budget.maxRevisits}) exceeded for node "${nodeId}"`);
25
+ }
26
+ return budget.iterations;
27
+ }
17
28
  export async function simulateProcess(opts) {
18
29
  const proc = opts.process;
19
30
  const startId = opts.startNodeId ?? proc.start_node_id;
@@ -25,27 +36,23 @@ export async function simulateProcess(opts) {
25
36
  error: `start_node_id "${startId}" not found in process "${proc.id}"`,
26
37
  };
27
38
  }
28
- const maxIterations = opts.maxIterations ?? DEFAULT_MAX_ITERATIONS;
29
- const maxRevisits = opts.maxRevisits ?? DEFAULT_MAX_REVISITS;
30
- const visits = new Map();
39
+ const maxIterations = opts.maxIterations ?? proc.max_iterations ?? MAX_PROCESS_ITERATIONS_CEILING;
40
+ const maxRevisits = opts.maxRevisits ?? proc.max_revisits ?? MAX_PROCESS_REVISITS_CEILING;
41
+ const budget = {
42
+ iterations: 0,
43
+ visitsByNodeId: new Map(),
44
+ maxIterations,
45
+ maxRevisits,
46
+ };
31
47
  const steps = [];
32
48
  const upstream = {};
33
49
  let runState = opts.state ?? {};
34
50
  const processesById = opts.processesById ??
35
51
  new Map([[proc.id, proc]]);
36
52
  let current = startNode;
37
- let iteration = 0;
38
53
  try {
39
54
  for (;;) {
40
- iteration += 1;
41
- if (iteration > maxIterations) {
42
- throw new Error(`iteration cap (${maxIterations}) exceeded`);
43
- }
44
- const visitsForNode = (visits.get(current.id) ?? 0) + 1;
45
- visits.set(current.id, visitsForNode);
46
- if (visitsForNode > maxRevisits) {
47
- throw new Error(`revisit cap (${maxRevisits}) exceeded for node "${current.id}"`);
48
- }
55
+ const iteration = recordDispatch({ budget, nodeId: current.id });
49
56
  const ctx = {
50
57
  entity: opts.entity ? { type: opts.entity.type, id: opts.entity.id } : null,
51
58
  upstream: upstream,
@@ -67,6 +74,7 @@ export async function simulateProcess(opts) {
67
74
  humanDecisions: opts.humanDecisions ?? {},
68
75
  iteration,
69
76
  processesById,
77
+ budget,
70
78
  record: (step) => steps.push(step),
71
79
  });
72
80
  const statePatch = extractOutputState(output);
@@ -131,6 +139,13 @@ export async function simulateProcess(opts) {
131
139
  }
132
140
  async function runInputMapperIfAny(node, ctx) {
133
141
  const mapper = node.input;
142
+ if (isJsonataExpr(mapper)) {
143
+ return evaluateJsonata({
144
+ label: `node:${node.id} input`,
145
+ expr: mapper.expr,
146
+ input: ctx,
147
+ });
148
+ }
134
149
  if (typeof mapper !== 'function')
135
150
  return ctx;
136
151
  return Promise.resolve(mapper(ctx));
@@ -204,7 +219,16 @@ async function simulateParallel(args, node) {
204
219
  node.branches.forEach((b, i) => branches.push({ branchId: b.branch_id, index: i, item: null, sub: b.node }));
205
220
  }
206
221
  else {
207
- const items = node.fan_out(args.ctx) ?? [];
222
+ const items = isJsonataExpr(node.fan_out)
223
+ ? await evaluateJsonata({
224
+ label: `node:${node.id} fan_out`,
225
+ expr: node.fan_out.expr,
226
+ input: args.ctx,
227
+ })
228
+ : node.fan_out(args.ctx);
229
+ if (!Array.isArray(items)) {
230
+ throw new Error(`parallel node "${node.id}" fan_out must return an array; got ${typeof items}`);
231
+ }
208
232
  const cap = node.max_fanout ?? DEFAULT_MAX_FANOUT_WIDTH;
209
233
  if (items.length > cap) {
210
234
  throw new Error(`parallel node "${node.id}" fan_out produced ${items.length} items; ` +
@@ -214,6 +238,7 @@ async function simulateParallel(args, node) {
214
238
  }
215
239
  const results = [];
216
240
  for (const br of branches) {
241
+ const iteration = recordDispatch({ budget: args.budget, nodeId: br.sub.id });
217
242
  const branchCtx = {
218
243
  ...args.ctx,
219
244
  branch: { id: br.branchId, index: br.index, item: br.item },
@@ -224,12 +249,13 @@ async function simulateParallel(args, node) {
224
249
  input: subInput,
225
250
  ctx: branchCtx,
226
251
  humanDecisions: args.humanDecisions,
227
- iteration: args.iteration,
252
+ iteration,
228
253
  processesById: args.processesById,
254
+ budget: args.budget,
229
255
  record: args.record,
230
256
  });
231
257
  args.record({
232
- iteration: args.iteration,
258
+ iteration,
233
259
  node_id: br.sub.id,
234
260
  kind: br.sub.kind,
235
261
  input: subInput,
@@ -251,7 +277,14 @@ async function simulateParallel(args, node) {
251
277
  // simulate verifies topology/routing, not settlement timing). In that case
252
278
  // the eager contract requires a decision; surface a sentinel return as the
253
279
  // same clear error the runtime raises instead of a confusing edge failure.
254
- const joinOutput = node.join(results, args.ctx);
280
+ const joinOutput = isJsonataExpr(node.join)
281
+ ? (await evaluateJsonata({
282
+ label: `node:${node.id} join`,
283
+ expr: node.join.expr,
284
+ input: args.ctx,
285
+ bindings: { branches: results },
286
+ }))
287
+ : node.join(results, args.ctx);
255
288
  if (isJoinUndecided(joinOutput)) {
256
289
  throw new Error(node.join_mode === 'eager'
257
290
  ? `parallel node "${node.id}": eager join returned {undecided: true} with ` +
@@ -313,14 +346,23 @@ async function simulateSubprocess(args, node) {
313
346
  throw new Error(childResult.error ?? `child process "${node.process}" simulation failed`);
314
347
  }
315
348
  const childOutput = childResult.steps.at(-1)?.output;
316
- return node.output({
349
+ const childRun = {
317
350
  run_id: 'sim-child',
318
351
  process_id: node.process,
319
352
  version: node.version ?? 'simulate',
320
353
  status: childFailed ? 'failed' : 'completed',
321
354
  output: childOutput,
322
355
  ...(childResult.error ? { error: childResult.error } : {}),
323
- }, args.ctx);
356
+ };
357
+ if (isJsonataExpr(node.output)) {
358
+ return evaluateJsonata({
359
+ label: `node:${node.id} output`,
360
+ expr: node.output.expr,
361
+ input: args.ctx,
362
+ bindings: { child: childRun },
363
+ });
364
+ }
365
+ return node.output(childRun, args.ctx);
324
366
  }
325
367
  export function formatSimulateResult(result) {
326
368
  const lines = [];
@@ -96,6 +96,6 @@ export declare function reposCiRequireCommand(args: ParsedArgs): Promise<number>
96
96
  export declare function reposCiImportCommand(args: ParsedArgs): Promise<number>;
97
97
  export declare function reposCiCommand(args: ParsedArgs): Promise<number>;
98
98
  export declare function reposDeleteCommand(args: ParsedArgs): Promise<number>;
99
- export declare const REPOS_USAGE = "usage:\n seq-studio repos list -e <env> [--namespace <slug>] [--mine] repos visible on the environment\n seq-studio repos namespaces [create <slug>] -e <env> list or create namespaces\n seq-studio repos show <ns>/<name> -e <env> repo detail (branches, clone URL)\n seq-studio repos create <ns>/<name> -e <env> [--default-branch b] create a repo seeded with a Sequence app README\n seq-studio repos clone <ns>/<name> -e <env> [--ref r] [--out dir] [--force]\n seq-studio repos clone --url <https://\u2026/repos/<id>/git> -e <env> [--ref r] [--out dir]\n seq-studio repos clone --id <uuid> -e <env> [--ref r] [--out dir]\n smart-HTTP when ATLAS_GIT_PAT is set;\n otherwise JSON materialize (<ns>/<name>)\n seq-studio repos pull <ns>/<name> -e <env> [--ref r] [--out dir] [--force]\n materialize the tree at a ref (JSON API)\n seq-studio repos delete <ns>/<name> -e <env> [--yes] delete a repo (confirm prompt)\n seq-studio repos ci show <ns>/<name> -e <env> [--ref r] preview discovered CI checks\n seq-studio repos ci require <ns>/<name> --check <name> -e <env> reserved (refuses write until sandboxed runner)\n seq-studio repos ci import <ns>/<name> -e <env> [--ref r] reserved (refuses write until sandboxed runner)\n\n Flags: -e/--env <env> (required; see: seq-studio envs list)\n\n clone prefers real git clone (PAT via askpass \u2014 never written into the remote\n URL). Without ATLAS_GIT_PAT, <ns>/<name> falls back to the JSON API and prints\n how to get a PAT (seq-studio or Atlas UI /settings/tokens).\n PAT without Auth0 login: use --url from Repositories \u2192 Clone (or --id <uuid>).\n --ref accepts a branch, tag, or commit SHA (SHA \u2192 clone then checkout).\n\n Authenticate JSON API calls with: seq-studio login\n Authenticate git clone/push with: ATLAS_GIT_PAT (from Atlas Settings \u2192 Tokens)\n";
99
+ export declare const REPOS_USAGE = "usage:\n seq-studio repos list -e <env> [--namespace <slug>] [--mine] repos visible on the environment\n seq-studio repos namespaces [create <slug>] -e <env> list or create namespaces\n seq-studio repos show <ns>/<name> -e <env> repo detail (branches, clone URL)\n seq-studio repos create <ns>/<name> -e <env> [--default-branch b] [--git-backend gcs_isomorphic|walgit]\n create a repo (GCS default, seed README;\n walgit starts empty on main; needs namespace write)\n seq-studio repos clone <ns>/<name> -e <env> [--ref r] [--out dir] [--force]\n seq-studio repos clone --url <https://\u2026/repos/<id>/git> -e <env> [--ref r] [--out dir]\n seq-studio repos clone --id <uuid> -e <env> [--ref r] [--out dir]\n smart-HTTP when ATLAS_GIT_PAT is set;\n otherwise JSON materialize (<ns>/<name>)\n seq-studio repos pull <ns>/<name> -e <env> [--ref r] [--out dir] [--force]\n materialize the tree at a ref (JSON API)\n seq-studio repos delete <ns>/<name> -e <env> [--yes] delete a repo (confirm prompt)\n seq-studio repos ci show <ns>/<name> -e <env> [--ref r] preview discovered CI checks\n seq-studio repos ci require <ns>/<name> --check <name> -e <env> reserved (refuses write until sandboxed runner)\n seq-studio repos ci import <ns>/<name> -e <env> [--ref r] reserved (refuses write until sandboxed runner)\n\n Flags: -e/--env <env> (required; see: seq-studio envs list)\n\n clone prefers real git clone (PAT via askpass \u2014 never written into the remote\n URL). Without ATLAS_GIT_PAT, <ns>/<name> falls back to the JSON API and prints\n how to get a PAT (seq-studio or Atlas UI /settings/tokens).\n PAT without Auth0 login: use --url from Repositories \u2192 Clone (or --id <uuid>).\n --ref accepts a branch, tag, or commit SHA (SHA \u2192 clone then checkout).\n\n Authenticate JSON API calls with: seq-studio login\n Authenticate git clone/push with: ATLAS_GIT_PAT (from Atlas Settings \u2192 Tokens)\n";
100
100
  export declare function runReposCommand(sub: string | undefined, args: ParsedArgs): Promise<number>;
101
101
  export {};
@@ -234,6 +234,9 @@ export async function reposShowCommand(args) {
234
234
  console.log(` path: ${namespace}/${name}`);
235
235
  console.log(` id: ${repo.id}`);
236
236
  console.log(` default branch: ${repo.defaultBranch}`);
237
+ if (repo.gitBackend) {
238
+ console.log(` git backend: ${repo.gitBackend}`);
239
+ }
237
240
  console.log(` created: ${shortDate(repo.createdAt)} by ${repo.createdBy}`);
238
241
  console.log(` updated: ${shortDate(repo.updatedAt)}`);
239
242
  console.log(` clone (PAT as basic-auth password): ${cloneUrl(ctx, repo.id)}`);
@@ -262,16 +265,37 @@ export async function reposShowCommand(args) {
262
265
  }
263
266
  return 0;
264
267
  }
268
+ const GIT_BACKEND_KINDS = ['gcs_isomorphic', 'walgit'];
269
+ const GIT_BACKEND_KIND_SET = new Set(GIT_BACKEND_KINDS);
270
+ function parseGitBackendFlag(args) {
271
+ const gitBackend = stringFlag(args.flags, 'git-backend');
272
+ if (gitBackend === undefined)
273
+ return undefined;
274
+ if (!GIT_BACKEND_KIND_SET.has(gitBackend)) {
275
+ throw new Error(`--git-backend must be ${GIT_BACKEND_KINDS.join(' or ')} (got "${gitBackend}").`);
276
+ }
277
+ return gitBackend;
278
+ }
265
279
  export async function reposCreateCommand(args) {
266
280
  const { namespace, name } = parseRepoPath(args.positional[0]);
267
281
  const ctx = await reposContext(args);
268
282
  const defaultBranch = stringFlag(args.flags, 'default-branch');
283
+ const gitBackend = parseGitBackendFlag(args);
284
+ if (gitBackend === 'walgit' && defaultBranch !== undefined && defaultBranch !== 'main') {
285
+ throw new Error('walgit create does not set HEAD from --default-branch; omit it or use main.');
286
+ }
269
287
  const repo = await postJson({
270
288
  ...clientOptions(ctx),
271
289
  path: '/api/git-service/repos',
272
- body: { namespaceSlug: namespace, name, ...(defaultBranch ? { defaultBranch } : {}) },
290
+ body: {
291
+ namespaceSlug: namespace,
292
+ name,
293
+ ...(defaultBranch ? { defaultBranch } : {}),
294
+ ...(gitBackend ? { gitBackend } : {}),
295
+ },
273
296
  });
274
- console.log(`${LOG} created ${namespace}/${name} (id=${repo.id}, default branch ${repo.defaultBranch}) on ${ctx.env.name}`);
297
+ const backend = repo.gitBackend ?? gitBackend;
298
+ console.log(`${LOG} created ${namespace}/${name} (id=${repo.id}, default branch ${repo.defaultBranch}${backend ? `, gitBackend=${backend}` : ''}) on ${ctx.env.name}`);
275
299
  return 0;
276
300
  }
277
301
  async function materializeTree({ ctx, namespace, name, destDir, ref, verb, }) {
@@ -748,7 +772,9 @@ export const REPOS_USAGE = `usage:
748
772
  seq-studio repos list -e <env> [--namespace <slug>] [--mine] repos visible on the environment
749
773
  seq-studio repos namespaces [create <slug>] -e <env> list or create namespaces
750
774
  seq-studio repos show <ns>/<name> -e <env> repo detail (branches, clone URL)
751
- seq-studio repos create <ns>/<name> -e <env> [--default-branch b] create a repo seeded with a Sequence app README
775
+ seq-studio repos create <ns>/<name> -e <env> [--default-branch b] [--git-backend gcs_isomorphic|walgit]
776
+ create a repo (GCS default, seed README;
777
+ walgit starts empty on main; needs namespace write)
752
778
  seq-studio repos clone <ns>/<name> -e <env> [--ref r] [--out dir] [--force]
753
779
  seq-studio repos clone --url <https://…/repos/<id>/git> -e <env> [--ref r] [--out dir]
754
780
  seq-studio repos clone --id <uuid> -e <env> [--ref r] [--out dir]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sequenceholdings/studio-cli",
3
- "version": "0.1.27",
3
+ "version": "0.1.28",
4
4
  "description": "Unified Sequence Studio CLI — `seq-studio init` / `add` / `deploy` (app monorepos), `seq-studio agents`, `seq-studio process` (Lattice), `seq-studio artifact`, `seq-studio functions` / `secrets`, `seq-studio repos`, and `seq-studio auth pat`. Includes Auth0 browser login shared with seqapi.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -36,12 +36,13 @@
36
36
  "README.md"
37
37
  ],
38
38
  "dependencies": {
39
- "js-yaml": "^4.3.1",
40
- "smol-toml": "^1.4.2",
39
+ "esbuild": "^0.25.0",
40
+ "js-yaml": "^4.3.2",
41
+ "smol-toml": "^1.7.1",
41
42
  "tsx": "^4.20.3",
42
43
  "zod": "^4.1.13",
43
44
  "@sequenceholdings/agent-spec": "0.1.2",
44
- "@sequenceholdings/artifact-studio": "0.2.2",
45
+ "@sequenceholdings/artifact-studio": "0.2.3",
45
46
  "@sequenceholdings/lattice": "0.1.2"
46
47
  },
47
48
  "peerDependencies": {
@@ -60,7 +61,7 @@
60
61
  "@types/js-yaml": "^4.0.9",
61
62
  "@types/node": "^22.0.0",
62
63
  "typescript": "^5.6.0",
63
- "vitest": "^4.1.5",
64
+ "vitest": "^4.1.11",
64
65
  "@sequenceholdings/orm": "2.0.0",
65
66
  "@sequenceholdings/pipeline-spec": "0.1.0"
66
67
  },