omkit 0.0.15 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +110 -97
  2. package/dist/actions/chrome-page.d.ts +12 -29
  3. package/dist/actions/chrome-page.js +19 -32
  4. package/dist/actions/command.d.ts +18 -39
  5. package/dist/actions/command.js +28 -80
  6. package/dist/actions/healthcheck.d.ts +3 -11
  7. package/dist/actions/healthcheck.js +8 -22
  8. package/dist/actions/index.d.ts +6 -8
  9. package/dist/actions/index.js +4 -6
  10. package/dist/actions/prompt.d.ts +5 -19
  11. package/dist/actions/prompt.js +10 -31
  12. package/dist/actions/tail-log.d.ts +7 -21
  13. package/dist/actions/tail-log.js +13 -34
  14. package/dist/actions/until-log.d.ts +4 -7
  15. package/dist/actions/until-log.js +3 -3
  16. package/dist/actions/watch-dir.d.ts +5 -19
  17. package/dist/actions/watch-dir.js +13 -28
  18. package/dist/actions/watch.d.ts +4 -12
  19. package/dist/actions/watch.js +9 -16
  20. package/dist/core/ActionRun.d.ts +97 -0
  21. package/dist/core/ActionRun.js +266 -0
  22. package/dist/core/ExecutionTree.d.ts +88 -0
  23. package/dist/core/ExecutionTree.js +320 -0
  24. package/dist/core/action.d.ts +6 -0
  25. package/dist/core/action.js +72 -0
  26. package/dist/core/context.d.ts +9 -0
  27. package/dist/core/context.js +8 -0
  28. package/dist/core/om.d.ts +9 -0
  29. package/dist/core/om.js +25 -0
  30. package/dist/core/step.d.ts +9 -0
  31. package/dist/core/step.js +18 -0
  32. package/dist/core/types.d.ts +128 -0
  33. package/dist/foundation/ActionRef.d.ts +18 -0
  34. package/dist/foundation/ActionRef.js +5 -0
  35. package/dist/{utils → foundation}/AsyncQueue.d.ts +2 -4
  36. package/dist/{utils → foundation}/AsyncQueue.js +6 -19
  37. package/dist/foundation/CancelledError.d.ts +10 -0
  38. package/dist/foundation/CancelledError.js +13 -0
  39. package/dist/foundation/Deferred.d.ts +8 -0
  40. package/dist/foundation/Deferred.js +10 -0
  41. package/dist/foundation/LogEntry.d.ts +29 -0
  42. package/dist/{orchestration/events → foundation}/events.d.ts +2 -11
  43. package/dist/{orchestration/events → foundation}/events.js +1 -7
  44. package/dist/{utils → foundation}/format.d.ts +3 -4
  45. package/dist/{utils → foundation}/format.js +12 -4
  46. package/dist/foundation/fsSafe.d.ts +7 -0
  47. package/dist/foundation/fsSafe.js +7 -0
  48. package/dist/foundation/ids.d.ts +9 -0
  49. package/dist/foundation/ids.js +10 -0
  50. package/dist/index.d.ts +11 -22
  51. package/dist/index.js +10 -30
  52. package/dist/output/LiveRenderer.d.ts +13 -0
  53. package/dist/output/LiveRenderer.js +56 -0
  54. package/dist/output/console/ConsoleCapture.d.ts +20 -0
  55. package/dist/output/console/ConsoleCapture.js +47 -0
  56. package/dist/output/folder/RunFolder.d.ts +11 -22
  57. package/dist/output/folder/RunFolder.js +18 -36
  58. package/dist/output/log/LogStore.d.ts +22 -0
  59. package/dist/output/log/LogStore.js +56 -0
  60. package/dist/output/log/RawStream.d.ts +11 -0
  61. package/dist/output/log/RawStream.js +18 -0
  62. package/dist/output/snapshot/SnapshotStore.d.ts +6 -43
  63. package/dist/output/snapshot/SnapshotStore.js +12 -52
  64. package/dist/output/writers/NodeLogWriter.d.ts +8 -0
  65. package/dist/output/writers/NodeLogWriter.js +36 -0
  66. package/dist/output/writers/ResultWriter.d.ts +3 -0
  67. package/dist/output/writers/ResultWriter.js +5 -0
  68. package/dist/output/writers/RollupWriter.d.ts +9 -0
  69. package/dist/output/writers/RollupWriter.js +29 -0
  70. package/dist/output/writers/entryLine.d.ts +10 -0
  71. package/dist/output/writers/entryLine.js +39 -0
  72. package/dist/output/writers/views.d.ts +38 -0
  73. package/dist/output/writers/views.js +6 -0
  74. package/dist/system/fs/FolderCache.d.ts +6 -34
  75. package/dist/system/fs/FolderCache.js +7 -38
  76. package/dist/system/proc.d.ts +51 -0
  77. package/dist/system/proc.js +148 -0
  78. package/dist/system/procRegistry.d.ts +52 -0
  79. package/dist/system/procRegistry.js +117 -0
  80. package/package.json +3 -1
  81. package/dist/orchestration/action/action.d.ts +0 -23
  82. package/dist/orchestration/action/action.js +0 -256
  83. package/dist/orchestration/action/types.d.ts +0 -182
  84. package/dist/orchestration/assert.d.ts +0 -24
  85. package/dist/orchestration/assert.js +0 -26
  86. package/dist/orchestration/spin/SpinHost.d.ts +0 -111
  87. package/dist/orchestration/spin/SpinHost.js +0 -345
  88. package/dist/orchestration/spin/spin.d.ts +0 -24
  89. package/dist/orchestration/spin/spin.js +0 -57
  90. package/dist/orchestration/spin/types.d.ts +0 -63
  91. package/dist/output/Output.d.ts +0 -24
  92. package/dist/output/Output.js +0 -27
  93. package/dist/output/index.d.ts +0 -11
  94. package/dist/output/index.js +0 -11
  95. package/dist/output/log/LogRenderer.d.ts +0 -73
  96. package/dist/output/log/LogRenderer.js +0 -133
  97. package/dist/output/log/LogsCollector.d.ts +0 -79
  98. package/dist/output/log/LogsCollector.js +0 -141
  99. package/dist/output/log/RunLog.d.ts +0 -54
  100. package/dist/output/log/RunLog.js +0 -152
  101. package/dist/output/log/console-capture.d.ts +0 -24
  102. package/dist/output/log/console-capture.js +0 -53
  103. package/dist/system/fs/streams.d.ts +0 -11
  104. package/dist/system/fs/streams.js +0 -14
  105. package/dist/system/process/process.d.ts +0 -35
  106. package/dist/system/process/process.js +0 -104
  107. package/dist/utils/serialize.d.ts +0 -2
  108. package/dist/utils/serialize.js +0 -12
  109. /package/dist/{orchestration/action → core}/types.js +0 -0
  110. /package/dist/{orchestration/spin/types.js → foundation/LogEntry.js} +0 -0
@@ -1,345 +0,0 @@
1
- import { relative } from "node:path";
2
- import { producerOfRef } from "../action/action.js";
3
- import { LogsCollector, ScopedLogger } from "../../output/log/LogsCollector.js";
4
- import { LogRenderer } from "../../output/log/LogRenderer.js";
5
- import { actionScope, captureConsole } from "../../output/log/console-capture.js";
6
- import { Output } from "../../output/Output.js";
7
- import { createAssert } from "../assert.js";
8
- /** The entry script, relative to where node was invoked (so the log says what produced it). */
9
- const scriptPath = () => {
10
- const entry = process.argv[1];
11
- return entry ? relative(process.cwd(), entry) : "(unknown)";
12
- };
13
- /** A constructed instance is an object carrying a `start` function. */
14
- const isActionInstance = (value) => typeof value === "object" &&
15
- value !== null &&
16
- typeof value.start === "function";
17
- /** An *uncalled* action: the callable `action(name).run(…)` returns before it's invoked. */
18
- const isUncalledAction = (value) => typeof value === "function" && typeof value.actionName === "string";
19
- /**
20
- * Guard each launch argument: an action *instance* is required, not the action
21
- * itself. Forgetting the trailing `()` is an easy slip (the callable has no
22
- * `.start`), and silently treating it as something else would report a false
23
- * green — so fail loudly with the fix.
24
- */
25
- function assertInstance(value) {
26
- if (isActionInstance(value))
27
- return;
28
- const hint = isUncalledAction(value)
29
- ? ` — that looks like an action that wasn't invoked; construct an instance by calling it: action("…").run(…)()`
30
- : "";
31
- throw new Error(`run() expects action instances; received ${typeof value}${hint}`);
32
- }
33
- /**
34
- * A live spin over its own append-only log: constructing one launches the given
35
- * actions in parallel under a single abort controller and drives them to a terminal
36
- * {@link SpinResult}. Stop it with `.cancel()`, `await` its `.done` for the verdict.
37
- *
38
- * **A spin owns its world.** Each construction creates its *own* {@link LogsCollector}
39
- * and {@link Output} — the run's log, folder, and snapshots — rather than sharing a
40
- * process global, so runs don't bleed into each other and a fresh run can be created
41
- * in a living process (sequential re-runs, in-process tests). Attach further actions
42
- * to a running spin — including event-driven ones — via its `.run(…)` method.
43
- *
44
- * Each action runs against its own child logger (which headers and indents its
45
- * lines into this run's log) and the spin's shared abort signal — both injected
46
- * into its context, where the framework also binds a `proc` and the run's `output`
47
- * so child processes stream into the right log and die on teardown. A **failing
48
- * action never tears the spin down** — its `{ ok: false }` outcome is recorded in
49
- * the verdict (and sets exit code 1) and the spin keeps running. Teardown to
50
- * `closed` happens only on Ctrl-C, `.cancel()`, natural completion, or an uncaught
51
- * fatal. The process-level hooks (SIGINT/uncaught handlers, `exitCode`) are owned by
52
- * the run and cleaned at finalize, so they don't outlive it.
53
- */
54
- export class SpinHost {
55
- /** This run's append-only log — its own store, not a process global. */
56
- logs = new LogsCollector();
57
- /** This run's output subsystem (folder + snapshots + run-log writer), wired to {@link logs}. */
58
- output = new Output(this.logs);
59
- /** The spin's abort signal — for consumers that want to observe teardown. */
60
- signal;
61
- /** Settles once the spin reaches `closed`, carrying the terminal verdict. Never rejects. */
62
- done;
63
- /** The original `console.log`, captured before patching — the run's terminal writer. */
64
- term;
65
- /** Reinstalls the pre-run console methods; called once at finalize. */
66
- restoreConsole;
67
- controller = new AbortController();
68
- // ── Lifecycle state ──────────────────────────────────────────────────────
69
- // The single source of truth for "where in its life is this run". Only
70
- // `beginClosing` and the finalize step below mutate it, and only forward.
71
- // The log stays open through teardown and is closed once at finalize (after the
72
- // last entry), so `streamLog` captures the whole run — including lines logged
73
- // *during* teardown — and its run.jsonl is complete before `writeLog` reads it.
74
- phase = "open";
75
- /** The current lifecycle state — see {@link SpinState}. */
76
- get state() {
77
- return this.phase;
78
- }
79
- // Genuine failures (not teardown cascade). Frozen into the verdict at close.
80
- failures = [];
81
- // Running tally of every assertion this run made, for the run.log summary footer.
82
- assertionsPassed = 0;
83
- assertionsFailed = 0;
84
- // Every launched action's promise lives here until it settles; the drive loop
85
- // empties this set. Daemons keep it non-empty until the controller aborts.
86
- inFlight = new Set();
87
- // Instances launched so far — used to verify a `.ref` dependency was launched
88
- // before the action that consumes its handle.
89
- launched = new WeakSet();
90
- // The incremental crash-insurance stream; awaited at finalize before writeLog.
91
- streaming;
92
- // Ctrl-C tears the spin down gracefully through the lifecycle, like cancel().
93
- onSigint = () => this.beginClosing("interrupted (SIGINT)");
94
- onUncaught = this.onFatal("uncaughtException");
95
- onUnhandled = this.onFatal("unhandledRejection");
96
- constructor(...actions) {
97
- // Validate eagerly so a bad argument throws cleanly before any work begins.
98
- for (const instance of actions)
99
- assertInstance(instance);
100
- this.signal = this.controller.signal;
101
- // Capture the ORIGINAL console.log as this run's terminal writer BEFORE patching,
102
- // or `drain`/finalize would re-enter the patched method and feedback-loop. Then
103
- // patch console so every console.* during the run folds into this run's log,
104
- // attributed via `actionScope` (see `launch`).
105
- this.term = console.log.bind(console);
106
- this.restoreConsole = captureConsole(this.logs);
107
- process.once("SIGINT", this.onSigint);
108
- process.on("uncaughtException", this.onUncaught);
109
- process.on("unhandledRejection", this.onUnhandled);
110
- this.narrate(`run started · ${scriptPath()}`);
111
- // Start streaming log entries to disk immediately — incremental writes survive
112
- // hard kills where the final writeLog never runs. Kept so finalize can await it
113
- // *before* writeLog rewrites the same files: otherwise a late flush from this
114
- // stream lands past writeLog's truncation and the OS zero-fills the gap (a
115
- // multi-MB NUL run in run.log).
116
- this.streaming = this.output.runLog.stream(this.logs).catch(() => { });
117
- // Live-render the log to the console for the whole run (replay + live). Always
118
- // on — the run's terminal output, no flag or call required.
119
- this.drain();
120
- for (const instance of actions)
121
- this.launch(instance, undefined);
122
- // Launch before driving: the drive loop breaks on an empty `inFlight`, so it
123
- // must not start until the initial actions have populated it.
124
- this.done = this.drive();
125
- // `done` resolves with the verdict and never rejects; guard anyway so a stray
126
- // finalize error can't surface as an unhandled rejection.
127
- this.done.catch(() => { });
128
- }
129
- /**
130
- * Launch more actions into this same spin — same controller, same log. Chainable.
131
- *
132
- * Throws if the spin is no longer `open`.
133
- */
134
- run(...more) {
135
- for (const instance of more)
136
- this.nodInto(instance, undefined);
137
- return this;
138
- }
139
- /**
140
- * Launch `instance` into the spin under an optional `parentPath` (the nodding
141
- * action's path, or `undefined` for a top-level nod). The single guarded entry to
142
- * launching — `run` (top-level) and an action's own scoped `nod` both route here,
143
- * so the "spin is open" check lives in one place.
144
- */
145
- nodInto(instance, parentPath) {
146
- if (this.phase !== "open") {
147
- throw new Error(`spin.run(…) rejected: the spin is "${this.phase}", not "open". Launch actions before ` +
148
- `teardown, or from a lifecycle event of an action that is still running.`);
149
- }
150
- this.launch(instance, parentPath);
151
- }
152
- /** Begin teardown: abort the signal (killing procs, unblocking waits, stopping daemons). */
153
- cancel() {
154
- this.beginClosing("cancelled");
155
- }
156
- /**
157
- * Live-render the log to the console. Started automatically from the constructor
158
- * — every spin drains, with no flag to disable and nothing for the caller to
159
- * invoke (for now). A single {@link LogRenderer} applies grouping/indentation as
160
- * entries stream by; its state spans the replayed history and live entries as one
161
- * continuous stream. The subscription ends itself when the run tears down (the
162
- * collector closes it), so this loop simply runs to completion.
163
- */
164
- drain() {
165
- void (async () => {
166
- const renderer = new LogRenderer();
167
- for await (const entry of this.logs.subscribe({ replay: true }))
168
- this.term(renderer.render(entry));
169
- })().catch(() => { });
170
- }
171
- /** Narrate a run-lifecycle milestone into this run's log (renders as a `[run]` line). */
172
- narrate(message) {
173
- this.logs.append({ source: "run", level: "run", message });
174
- }
175
- /**
176
- * Move `open → closing`: abort the signal (unwinding procs, waits, and
177
- * daemons), narrate the cause once, and stop accepting new actions. Idempotent
178
- * — only the first caller transitions; later triggers (a second failure, a
179
- * `cancel()` during teardown) are no-ops. This is the *only* path to abort, so
180
- * every teardown reason flows through one place.
181
- */
182
- beginClosing(reason) {
183
- if (this.phase !== "open")
184
- return;
185
- this.phase = "closing";
186
- this.narrate(`tearing down · ${reason}`);
187
- this.controller.abort();
188
- }
189
- /**
190
- * Record a genuine fault in the verdict. It does **not** tear the spin down — a
191
- * failing action is data, and the spin keeps running (only Ctrl-C / cancel /
192
- * completion / an uncaught fatal close it).
193
- */
194
- recordFailure(action, error) {
195
- this.failures.push({ action, error });
196
- }
197
- /**
198
- * A throw or rejection that escaped every action's own handling. Without a
199
- * handler Node prints it and exits *immediately* — before the run can flush its
200
- * log, which leaves a silent, empty log directory and no verdict. So catch it,
201
- * log it, fold it into the verdict, and drive teardown so the log still flushes
202
- * and the exit code reflects the fault — degrading a stray throw to a recorded
203
- * failure instead of a hard crash. Removed at finalize, so it only governs
204
- * while this run owns the process.
205
- */
206
- onFatal(kind) {
207
- return (error) => {
208
- this.logs.append({
209
- source: kind,
210
- level: "error",
211
- message: error instanceof Error ? (error.stack ?? error.message) : String(error),
212
- });
213
- // Genuine fault vs. teardown fallout: only one that surfaces *before* the
214
- // signal aborts is the spin's own (mirrors `launch`'s cascade rule); a throw
215
- // during unwind is logged but doesn't pollute the verdict. Either way tear
216
- // down — unlike an action's own failure, an *uncaught* fatal leaves the
217
- // process state undefined, so we always finish and flush.
218
- if (!this.controller.signal.aborted)
219
- this.failures.push({ action: kind, error });
220
- this.beginClosing(kind);
221
- };
222
- }
223
- launch(instance, parentPath) {
224
- // A consumer built with another action's `.ref` (e.g. `chromePage("Explorer", driver.ref)`)
225
- // must be launched *after* that producer — otherwise it awaits a handle that
226
- // never arrives and the spin hangs silently. Catch it and say how to fix it.
227
- for (const arg of instance.args) {
228
- const producer = producerOfRef(arg);
229
- if (producer && !this.launched.has(producer)) {
230
- throw new Error(`${instance.name} was launched before its dependency ${producer.name}: it ` +
231
- `consumes ${producer.name}'s .ref, so nod ${producer.name} first.`);
232
- }
233
- }
234
- this.launched.add(instance);
235
- // The action's path: its name for a top-level nod, or `<parent> › <name>` when a
236
- // parent action nodded it. Top-level actions keep this run's logger (output
237
- // unchanged); a child gets a ScopedLogger so its every line — and its `proc`'s,
238
- // and any grandchildren's — is prefixed with this path. Its own `nod` carries
239
- // this path down, so scoping composes automatically.
240
- const path = parentPath ? `${parentPath} › ${instance.name}` : instance.name;
241
- const scoped = parentPath === undefined ? this.logs : new ScopedLogger(this.logs, path);
242
- const nod = (child) => {
243
- this.nodInto(child, path);
244
- return child;
245
- };
246
- // A boolean check bound to this action's path: it logs a `⊨` milestone, tallies
247
- // the result for the run.log summary, and on failure records a verdict failure
248
- // the same way an action's own failure does — skipped during teardown (cascade,
249
- // not a fault). Uses `this.logs` (not `scoped`) the same way `record` below does:
250
- // the path is already embedded in the message via `name`, so routing through
251
- // `scoped` would double-prefix the `source` field for a nodded child.
252
- const assert = createAssert(path, this.logs, (pass, error) => {
253
- if (pass)
254
- this.assertionsPassed++;
255
- else {
256
- this.assertionsFailed++;
257
- if (!this.controller.signal.aborted && error)
258
- this.recordFailure(path, error);
259
- }
260
- });
261
- this.narrate(`launch ${path}`);
262
- // The action logs into this run's shared store (entries carry their `source`;
263
- // grouping is applied at render time) and gets the spin's signal directly; the
264
- // framework injects a `proc` and the run's `output` bound to both, so there's no
265
- // ambient context. `start()` resolves with the action's Outcome — it never
266
- // rejects for the action's own failure — so a failure is handled here as data.
267
- const record = (error) => {
268
- // Always record the fault in the action's own log, under its path.
269
- this.logs.append({
270
- source: path,
271
- level: "error",
272
- message: error instanceof Error ? (error.stack ?? error.message) : String(error),
273
- });
274
- // Genuine failure vs. teardown fallout: if the signal was already aborted
275
- // when this surfaced, the failure is almost certainly the abort killing the
276
- // action (a cascade), not its own fault — so it must not pollute the verdict.
277
- if (!this.controller.signal.aborted)
278
- this.recordFailure(path, error);
279
- };
280
- const promise = actionScope
281
- .run(path, () => instance.start({
282
- logs: scoped,
283
- signal: this.controller.signal,
284
- nod,
285
- output: this.output,
286
- assert,
287
- }))
288
- .then((outcome) => {
289
- if (!outcome.ok)
290
- record(outcome.error);
291
- })
292
- // Defensive: `start()` shouldn't reject, but if the framework itself throws,
293
- // treat it as a fault rather than losing it to an unhandled rejection.
294
- .catch(record);
295
- this.inFlight.add(promise);
296
- void promise.finally(() => this.inFlight.delete(promise));
297
- }
298
- /**
299
- * Drives the run to `closed`. The loop re-checks `inFlight` because actions can
300
- * be added (or daemons can settle on abort) while we await. A synchronous
301
- * `.run(…)` from a settling action's lifecycle event lands before that action's
302
- * `finally` removes it, so `inFlight` never spuriously hits 0 mid-handoff.
303
- */
304
- async drive() {
305
- for (;;) {
306
- if (this.inFlight.size === 0) {
307
- // Nothing left to run. If still open, every action finished on its own —
308
- // natural completion; tear down so daemons/listeners unwind uniformly.
309
- // If already closing, teardown is simply complete.
310
- if (this.phase === "open")
311
- this.beginClosing("completed");
312
- break;
313
- }
314
- await Promise.allSettled([...this.inFlight]);
315
- }
316
- // ── Finalize (reached exactly once) ──────────────────────────────────────
317
- this.phase = "closed";
318
- process.off("SIGINT", this.onSigint);
319
- process.off("uncaughtException", this.onUncaught);
320
- process.off("unhandledRejection", this.onUnhandled);
321
- this.restoreConsole();
322
- this.narrate("finished");
323
- // Close the log now (after the last entry) so `streamLog` drains and finishes
324
- // writing the complete run.jsonl, then wait for it to fully close its files —
325
- // both so its last flush can't corrupt run.log later, and so run.jsonl is done
326
- // before `writeLog` streams it into the final collapsed run.log.
327
- this.logs.close();
328
- await this.streaming;
329
- // Hand the assertion tally to `write`, which bubbles a summary + the
330
- // `assertions.log` link into the run.log footer (only when there were any).
331
- const file = await this.output.runLog.write({
332
- passed: this.assertionsPassed,
333
- failed: this.assertionsFailed,
334
- });
335
- // Direct to the terminal — the file's already written, so this line isn't in it.
336
- this.term(LogRenderer.marker("run", `log → ${file}`));
337
- const result = { ok: this.failures.length === 0, failures: this.failures };
338
- // One process = one run = one verdict; reflect pass/fail in the exit code so
339
- // shells and CI see it without parsing the log. Only set it on failure, so a
340
- // code a failing action's own handler may have set isn't clobbered to 0.
341
- if (!result.ok)
342
- process.exitCode = 1;
343
- return result;
344
- }
345
- }
@@ -1,24 +0,0 @@
1
- import type { SpinBody } from "./types.ts";
2
- /**
3
- * Runs a linear orchestration. You pass a plain (async) function; omkit hosts it
4
- * in a single in-flight action and hands it a {@link Nod}. Because that host
5
- * stays in-flight while your body `await`s, the spin never idles shut between
6
- * steps — so you write `await` / `if` control flow instead of nested callbacks.
7
- * When the body returns, the daemons it nodded in keep the spin alive until
8
- * teardown.
9
- *
10
- * A failing action **never throws into the body** — `await nod(x).done` yields an
11
- * {@link import("./action.ts").Outcome} you inspect, and the spin keeps going
12
- * (the failure is recorded in the verdict and sets exit code 1):
13
- *
14
- * spin({ drain: false }, async ({ nod }) => {
15
- * const ans = await nod(prompt({ … })).done; // Outcome — never throws
16
- * if (ans.ok && ans.value === "yes") await nod(test).done;
17
- * nod(devServer); // fire-and-forget daemon
18
- * const chrome = nod(chromedriver({ … }));
19
- * nod(chromePage("Explorer", chrome.ref)); // data deps via .ref
20
- * });
21
- *
22
- * Auto-drains by default;
23
- */
24
- export declare function spin(body: SpinBody): void;
@@ -1,57 +0,0 @@
1
- import { action } from "../action/action.js";
2
- import { SpinHost } from "./SpinHost.js";
3
- /**
4
- * Runs a linear orchestration. You pass a plain (async) function; omkit hosts it
5
- * in a single in-flight action and hands it a {@link Nod}. Because that host
6
- * stays in-flight while your body `await`s, the spin never idles shut between
7
- * steps — so you write `await` / `if` control flow instead of nested callbacks.
8
- * When the body returns, the daemons it nodded in keep the spin alive until
9
- * teardown.
10
- *
11
- * A failing action **never throws into the body** — `await nod(x).done` yields an
12
- * {@link import("./action.ts").Outcome} you inspect, and the spin keeps going
13
- * (the failure is recorded in the verdict and sets exit code 1):
14
- *
15
- * spin({ drain: false }, async ({ nod }) => {
16
- * const ans = await nod(prompt({ … })).done; // Outcome — never throws
17
- * if (ans.ok && ans.value === "yes") await nod(test).done;
18
- * nod(devServer); // fire-and-forget daemon
19
- * const chrome = nod(chromedriver({ … }));
20
- * nod(chromePage("Explorer", chrome.ref)); // data deps via .ref
21
- * });
22
- *
23
- * Auto-drains by default;
24
- */
25
- export function spin(body) {
26
- // `run(...)` below assigns `host` synchronously, before the action's async body
27
- // ever runs — so the closures here capture the spin safely.
28
- let hostRun;
29
- const hostAction = action("omkit:Spin").run(async (ctx) => {
30
- const nod = (instance) => {
31
- hostRun.run(instance);
32
- return instance;
33
- };
34
- await body({
35
- nod,
36
- // TODO: maybe add a reason for cancel ???
37
- cancel: () => hostRun.cancel(),
38
- signal: ctx.signal,
39
- // The host action runs inside the SpinHost, so its ctx already carries the
40
- // run's output subsystem — surface the folder and a snapshot convenience to
41
- // the body from there rather than reaching for a module singleton.
42
- artifactsFolder: ctx.artifactsFolder,
43
- snapshot: (name, value) => ctx.output.snapshots.snapshot(name, value),
44
- assert: ctx.assert,
45
- });
46
- });
47
- const mainSpinAction = hostAction();
48
- hostRun = new SpinHost(mainSpinAction);
49
- // The body is the orchestrator, not a peer action: if it throws, tear the whole
50
- // spin down. Regular action failures only get recorded (they don't stop the
51
- // spin), but the orchestrator crashing must end the run — otherwise any daemon
52
- // it already nodded keeps the process alive forever on a pipeline bug.
53
- void mainSpinAction.done.then((outcome) => {
54
- if (!outcome.ok)
55
- hostRun.cancel();
56
- });
57
- }
@@ -1,63 +0,0 @@
1
- export type { Nod } from "../action/types.ts";
2
- import type { Nod } from "../action/types.ts";
3
- import type { Assert } from "../assert.ts";
4
- /** What a {@link spin} body receives. */
5
- export interface SpinContext {
6
- /** Launch an action into the spin; returns the instance for awaiting/chaining. */
7
- readonly nod: Nod;
8
- /**
9
- * Tear the spin down (abort the signal, stopping daemons). Use it to end a spin
10
- * whose work is finished but which is held open by a daemon — e.g. once a
11
- * one-shot build completes while a watcher is still running.
12
- */
13
- readonly cancel: () => void;
14
- /** The spin's abort signal — honor it to stop early. */
15
- readonly signal: AbortSignal;
16
- /**
17
- * Absolute path to this spin's output folder (`logs/<name>/<date>/<time>/`),
18
- * created up front. Hand it to actions (or use `ctx.artifactsFolder` inside
19
- * one) to write artifacts beside `run.log`.
20
- */
21
- readonly artifactsFolder: string;
22
- /**
23
- * Capture a JSON snapshot into this run's output folder and drop a `[snapshot]`
24
- * line on the timeline — for run-level inputs the log should narrate (a build
25
- * config, resolved options). Resolves with the snapshot's relative path. The
26
- * run-scoped counterpart to the action `ctx.output.snapshots`.
27
- */
28
- readonly snapshot: (name: string, value: unknown) => Promise<string>;
29
- /**
30
- * Assert a boolean invariant from the spin body. Same semantics as the action
31
- * `ctx.assert`; body assertions are attributed to the host action path
32
- * (`omkit:Spin`).
33
- */
34
- readonly assert: Assert;
35
- }
36
- /** The body of a {@link spin}: any (async) function — it isn't named or wrapped by you. */
37
- export type SpinBody = (ctx: SpinContext) => void | Promise<void>;
38
- /**
39
- * A single action's failure, captured for the spin's verdict. Cascade failures —
40
- * actions that settled `{ ok: false }` only because teardown aborted them — are
41
- * deliberately excluded (see `launch`'s outcome handling), so this records
42
- * genuine faults, not fallout.
43
- */
44
- export interface ActionFailure {
45
- /** The failing action's name. */
46
- readonly action: string;
47
- /** Whatever it failed with (the Outcome's `error`). */
48
- readonly error: unknown;
49
- }
50
- /**
51
- * The terminal verdict of a spin: did everything that mattered succeed, and if
52
- * not, what failed. {@link SpinHost.done} resolves (never rejects) with this, so a
53
- * single `await` yields the outcome instead of forcing a try/catch on awaiters.
54
- * A failing action is *recorded* here (so `ok` is false and the exit code is 1)
55
- * but does **not** tear the spin down — see {@link SpinHost}.
56
- */
57
- export interface SpinResult {
58
- /** True when no genuine failure was recorded. */
59
- readonly ok: boolean;
60
- /** The genuine failures, in the order they surfaced. Empty when `ok`. */
61
- readonly failures: readonly ActionFailure[];
62
- }
63
- export type SpinState = "open" | "closing" | "closed";
@@ -1,24 +0,0 @@
1
- import type { Logger } from "./log/LogsCollector.ts";
2
- import { RunFolder } from "./folder/RunFolder.ts";
3
- import { SnapshotStore } from "./snapshot/SnapshotStore.ts";
4
- import { RunLog } from "./log/RunLog.ts";
5
- /**
6
- * The run's output subsystem — the composition root that owns the per-run folder and
7
- * the writers layered on it, and hands them to the rest of the process.
8
- *
9
- * Each run owns one of these: its {@link SpinHost} constructs an `Output` over the
10
- * run's log and threads it to actions as `ctx.output`. Everything that was
11
- * module-global in the old `output.ts` (the folder path, the mkdir latch, the
12
- * snapshot sequence) now lives inside these three members, reachable as
13
- * `output.folder`, `output.snapshots`, `output.runLog` — so callers reach for a named
14
- * layer instead of a free function, and the shared state has one owner per run.
15
- */
16
- export declare class Output {
17
- /** The per-run directory and artifact drop. */
18
- readonly folder: RunFolder;
19
- /** Sequenced JSON/text snapshot files + `[snapshot]` timeline lines. */
20
- readonly snapshots: SnapshotStore;
21
- /** The `run.jsonl` / `run.log` writer. */
22
- readonly runLog: RunLog;
23
- constructor(logger: Logger);
24
- }
@@ -1,27 +0,0 @@
1
- import { RunFolder } from "./folder/RunFolder.js";
2
- import { SnapshotStore } from "./snapshot/SnapshotStore.js";
3
- import { RunLog } from "./log/RunLog.js";
4
- /**
5
- * The run's output subsystem — the composition root that owns the per-run folder and
6
- * the writers layered on it, and hands them to the rest of the process.
7
- *
8
- * Each run owns one of these: its {@link SpinHost} constructs an `Output` over the
9
- * run's log and threads it to actions as `ctx.output`. Everything that was
10
- * module-global in the old `output.ts` (the folder path, the mkdir latch, the
11
- * snapshot sequence) now lives inside these three members, reachable as
12
- * `output.folder`, `output.snapshots`, `output.runLog` — so callers reach for a named
13
- * layer instead of a free function, and the shared state has one owner per run.
14
- */
15
- export class Output {
16
- /** The per-run directory and artifact drop. */
17
- folder;
18
- /** Sequenced JSON/text snapshot files + `[snapshot]` timeline lines. */
19
- snapshots;
20
- /** The `run.jsonl` / `run.log` writer. */
21
- runLog;
22
- constructor(logger) {
23
- this.folder = new RunFolder();
24
- this.snapshots = new SnapshotStore(this.folder, logger);
25
- this.runLog = new RunLog(this.folder, this.snapshots);
26
- }
27
- }
@@ -1,11 +0,0 @@
1
- /**
2
- * The output layer's barrel — the composition root ({@link Output}) and its member
3
- * classes. There is **no module singleton** here: each run's {@link SpinHost} owns
4
- * its own `Output`, and threads it to actions as `ctx.output` (and to the spin body
5
- * as `ctx.snapshot` / `ctx.artifactsFolder`), so nothing binds to process-global
6
- * state and runs stay isolated.
7
- */
8
- export { Output } from "./Output.ts";
9
- export { RunFolder } from "./folder/RunFolder.ts";
10
- export { type SnapshotRef, SnapshotStore } from "./snapshot/SnapshotStore.ts";
11
- export { RunLog } from "./log/RunLog.ts";
@@ -1,11 +0,0 @@
1
- /**
2
- * The output layer's barrel — the composition root ({@link Output}) and its member
3
- * classes. There is **no module singleton** here: each run's {@link SpinHost} owns
4
- * its own `Output`, and threads it to actions as `ctx.output` (and to the spin body
5
- * as `ctx.snapshot` / `ctx.artifactsFolder`), so nothing binds to process-global
6
- * state and runs stay isolated.
7
- */
8
- export { Output } from "./Output.js";
9
- export { RunFolder } from "./folder/RunFolder.js";
10
- export { SnapshotStore } from "./snapshot/SnapshotStore.js";
11
- export { RunLog } from "./log/RunLog.js";
@@ -1,73 +0,0 @@
1
- import type { LogEntry } from "./LogsCollector.ts";
2
- /** The special "title" log lines that get a distinguishing prefix. */
3
- export type MarkerKind = "event" | "action" | "run" | "snapshot" | "assert";
4
- /** A run set aside for collapsing: its source and every output line, in order. */
5
- export interface CollapsedRun {
6
- readonly source: string;
7
- readonly lines: readonly string[];
8
- }
9
- /**
10
- * One unit of batch-rendered output: either a ready-to-write text `line`
11
- * (identical to {@link LogRenderer.render}'s output for that entry) or a
12
- * `collapsed` run the caller must off-load and render via {@link LogRenderer.renderCollapsed}.
13
- */
14
- export type DisplayItem = {
15
- kind: "line";
16
- text: string;
17
- } | {
18
- kind: "collapsed";
19
- run: CollapsedRun;
20
- };
21
- /**
22
- * Turns raw {@link LogEntry} records into the pretty, grouped text form.
23
- * Presentation lives here and nowhere else: the collector stores raw entries; the
24
- * live drain and `run.log` writer each construct a renderer and feed it entries in
25
- * order. Two modes over the same grouping rules — pick per instance, don't mix:
26
- *
27
- * - **streaming** — {@link render} returns one entry's line as it arrives (live
28
- * drain, incremental `run.log`).
29
- * - **batch** — {@link push}/{@link end} accumulate a same-source run and collapse
30
- * it when it grows past the threshold, so one proc's burst can't drown the
31
- * durable `run.log` (the caller off-loads the full run to a snapshot).
32
- *
33
- * Grouping is decided against the *single merged stream* (`lastSource`), not
34
- * per-producer — so interleaved concurrent sources re-header correctly. A
35
- * milestone line breaks the current group, so the next action line re-headers.
36
- */
37
- export declare class LogRenderer {
38
- /** Lines of a collapsed run shown inline before the pointer. */
39
- static readonly COLLAPSE_HEAD = 5;
40
- /** Prefix a milestone/header line with its marker (`● run`, `▸ action`, …). */
41
- static marker(kind: MarkerKind, text: string): string;
42
- /**
43
- * Renders a {@link CollapsedRun} as its `head` lines under the `▸ <source>`
44
- * header, then a single indented `📎` pointer line to the off-loaded snapshot at
45
- * `rel` reporting how many lines were hidden. Pure — `rel` is supplied by the
46
- * caller after it writes the file.
47
- */
48
- static renderCollapsed(run: CollapsedRun, { rel, head }: {
49
- rel: string;
50
- head?: number;
51
- }): string;
52
- private lastSource;
53
- private run;
54
- private readonly threshold;
55
- constructor(threshold?: number);
56
- /**
57
- * Streaming: render one entry to its pretty line. A milestone renders as its own
58
- * marker line and breaks the group; other entries are grouped under an
59
- * `▸ <source>` header (first line of a group) and indented (the rest).
60
- */
61
- render(entry: LogEntry): string;
62
- /**
63
- * Batch: push an entry in order and get back the {@link DisplayItem}s that just
64
- * became final (0, 1, or a whole flushed run). Only the current same-source run
65
- * is held in memory, so segmenting a huge log stays bounded — the `run.log`
66
- * writer feeds this straight from `run.jsonl` on disk. Output is byte-identical
67
- * to {@link render} for non-collapsed runs. Pure — no filesystem.
68
- */
69
- push(entry: LogEntry): DisplayItem[];
70
- /** Batch: flush the last pending run (call once after the final {@link push}). */
71
- end(): DisplayItem[];
72
- private flush;
73
- }