@sequenceholdings/studio-cli 0.1.26 → 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 (62) hide show
  1. package/README.md +265 -81
  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 +107 -229
  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 +9 -4
  41. package/dist/orm/delegate.js +30 -23
  42. package/dist/pat-hints.js +1 -0
  43. package/dist/pipeline/commands.js +27 -9
  44. package/dist/pipeline/lifecycle.d.ts +2 -0
  45. package/dist/pipeline/lifecycle.js +91 -11
  46. package/dist/process/build.js +59 -43
  47. package/dist/process/codegen.d.ts +3 -2
  48. package/dist/process/codegen.js +143 -27
  49. package/dist/process/commands.d.ts +2 -0
  50. package/dist/process/commands.js +63 -18
  51. package/dist/process/discover.d.ts +6 -3
  52. package/dist/process/discover.js +11 -3
  53. package/dist/process/lint.d.ts +14 -0
  54. package/dist/process/lint.js +143 -5
  55. package/dist/process/plan-diff.d.ts +8 -0
  56. package/dist/process/plan-diff.js +61 -4
  57. package/dist/process/safety-baseline.d.ts +154 -0
  58. package/dist/process/safety-baseline.js +387 -0
  59. package/dist/process/simulate.js +64 -22
  60. package/dist/repos/commands.d.ts +1 -1
  61. package/dist/repos/commands.js +29 -3
  62. package/package.json +8 -7
@@ -0,0 +1,154 @@
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 type { LatticeSafetyProfile } from '@sequenceholdings/lattice';
33
+ /** Repo-relative path of the committed, generated baseline report. */
34
+ export declare const SAFETY_PROFILE_BASELINE_RELATIVE_PATH = "atlas/lattice/SAFETY_PROFILE_BASELINE.md";
35
+ /** Statically measurable observations for one committed process definition. */
36
+ export interface ProcessSafetyObservation {
37
+ /** Repo-relative apply root the process was discovered under. */
38
+ readonly root: string;
39
+ readonly processId: string;
40
+ /** Repo-relative path of the process.ts file. */
41
+ readonly file: string;
42
+ /** Node definitions, including nested parallel sub-nodes. */
43
+ readonly nodeCount: number;
44
+ /** Total outgoing edges across all nodes and sub-nodes. */
45
+ readonly edgeCount: number;
46
+ /** Deepest parallel-in-parallel nesting (0 = no parallel blocks). */
47
+ readonly parallelNestingDepth: number;
48
+ /** Unique subprocess target process ids (sorted). */
49
+ readonly subprocessTargets: readonly string[];
50
+ /**
51
+ * Longest known subprocess chain STARTING at this process, resolved across
52
+ * the full committed graph (co-located and cross-root ids): 0 = no
53
+ * subprocess nodes, chain A→B→C gives A depth 2, and an unknown external
54
+ * child contributes exactly one edge. Same unit as
55
+ * MAX_SUBPROCESS_NESTING_DEPTH ("a top-level subprocess is depth 1").
56
+ */
57
+ readonly subprocessChainDepth: number;
58
+ /**
59
+ * Unique linked protected resources — (kind, ref) pairs across agents (or
60
+ * their backing workflows when `workflowId` is set, matching the
61
+ * linked-resource authz target semantics), managed functions, and
62
+ * subprocess children, nested parallel branches included.
63
+ */
64
+ readonly linkedResourceRefs: number;
65
+ /** Max multiplicative fan-out width along any parallel nesting path. */
66
+ readonly fanoutProduct: number;
67
+ /** Declared per-run caps (undefined = orchestrator default). */
68
+ readonly maxIterations: number | undefined;
69
+ readonly maxRevisits: number | undefined;
70
+ readonly maxConcurrentRuns: number | undefined;
71
+ /**
72
+ * Largest explicit retry attempts / delay across node `withRetry`
73
+ * middleware and every supervisor_retry lane (process orchestrator,
74
+ * parallel runner, subprocess runner).
75
+ */
76
+ readonly maxRetryAttempts: number;
77
+ readonly maxRetryDelayMs: number;
78
+ /** Byte size of the raw process.ts source file (informational only). */
79
+ readonly sourceBytes: number;
80
+ /**
81
+ * Total bytes of SERIALIZED inline source across this process's bundle form:
82
+ * every `*_source` (Function.toString) and `*_expr` (JSONata) mapper slot,
83
+ * nested parallel branches included. Measured from the built bundle, not the
84
+ * TS file.
85
+ */
86
+ readonly inlineSourceBytes: number;
87
+ }
88
+ /** Corpus maxima keyed by the safety-profile fields they gate. */
89
+ export interface ObservedCorpusMaxima {
90
+ readonly staticGraph: {
91
+ readonly maxProcessesPerBundle: number;
92
+ readonly maxNodesPerProcess: number;
93
+ readonly maxEdgesPerProcess: number;
94
+ readonly maxLinkedResourceRefs: number;
95
+ readonly maxParallelNestingDepth: number;
96
+ readonly maxSubprocessNestingDepth: number;
97
+ /** Largest per-process serialized inline source, bytes. */
98
+ readonly maxInlineSourceBytes: number;
99
+ /** Largest canonical built bundle across apply roots, bytes. */
100
+ readonly maxBundleBytes: number;
101
+ };
102
+ readonly runtime: {
103
+ readonly maxIterationsPerRun: number;
104
+ readonly maxRevisitsPerNode: number;
105
+ readonly maxFanoutProductPerRun: number;
106
+ readonly maxRetryAttempts: number;
107
+ readonly maxRetryDelayMs: number;
108
+ readonly maxConcurrentRunsPerProcess: number;
109
+ };
110
+ }
111
+ export interface LatticeSafetyBaseline {
112
+ readonly roots: ReadonlyArray<{
113
+ readonly root: string;
114
+ readonly processCount: number;
115
+ /** Canonical built-bundle size for this apply root, bytes. */
116
+ readonly bundleBytes: number;
117
+ }>;
118
+ readonly processes: readonly ProcessSafetyObservation[];
119
+ /**
120
+ * Subprocess reference cycles detected across the committed graph, as
121
+ * canonical `a -> b -> a` strings (sorted). Always empty for a healthy
122
+ * corpus; a cycle makes chain depth unbounded and fails the fit assertion.
123
+ */
124
+ readonly subprocessCycles: readonly string[];
125
+ readonly observed: ObservedCorpusMaxima;
126
+ }
127
+ /** Derive the observed baseline for the committed first-party process corpus. */
128
+ export declare function deriveLatticeSafetyBaseline({ repoRoot, }: {
129
+ repoRoot: string;
130
+ }): Promise<LatticeSafetyBaseline>;
131
+ /**
132
+ * Assert every committed process fits the profile. Throws with the full
133
+ * violation list — the test gate that keeps the committed defaults ≥ what the
134
+ * committed corpus needs (LAT-140's backwards-compatibility requirement).
135
+ * A subprocess reference cycle also fails: chain depth is unbounded there.
136
+ */
137
+ export declare function assertBaselineFitsProfile({ baseline, profile, }: {
138
+ baseline: LatticeSafetyBaseline;
139
+ profile: LatticeSafetyProfile;
140
+ }): void;
141
+ /** Render the human-readable baseline report (markdown, deterministic). */
142
+ export declare function formatSafetyBaselineReport({ baseline, profile, }: {
143
+ baseline: LatticeSafetyBaseline;
144
+ profile: LatticeSafetyProfile;
145
+ }): string;
146
+ /**
147
+ * `seq-studio process safety-baseline [--repo-root <dir>] [--write]` — derive
148
+ * the baseline from the committed corpus, assert it fits the committed default
149
+ * profile, and print the markdown report. `--write` also refreshes the
150
+ * committed copy at {@link SAFETY_PROFILE_BASELINE_RELATIVE_PATH}.
151
+ */
152
+ export declare function safetyBaselineCommand({ flags, }: {
153
+ flags: Record<string, string | true>;
154
+ }): Promise<number>;
@@ -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
+ }