@cnc-tools/storm 0.6.0 → 0.8.0

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 (174) hide show
  1. package/dist/build-info.js +1 -1
  2. package/dist/commands/exec/cleanup.d.ts +3 -3
  3. package/dist/commands/exec/cleanup.js +1 -1
  4. package/dist/commands/exec/command.d.ts +797 -1
  5. package/dist/commands/exec/command.js +1 -1
  6. package/dist/commands/exec/live-view.js +32 -15
  7. package/dist/commands/exec/metadata.d.ts +5 -2
  8. package/dist/commands/exec/metadata.js +4 -0
  9. package/dist/commands/exec/mint-failed.d.ts +28 -0
  10. package/dist/commands/exec/outcomes.d.ts +526 -0
  11. package/dist/commands/exec/outcomes.js +9 -0
  12. package/dist/commands/exec/progress.d.ts +14 -2
  13. package/dist/commands/exec/progress.js +57 -14
  14. package/dist/commands/exec/run-command.d.ts +10 -4
  15. package/dist/commands/exec/run-command.js +41 -8
  16. package/dist/commands/exec/run-metadata.d.ts +6 -3
  17. package/dist/commands/exec/run-metadata.js +6 -3
  18. package/dist/commands/exec/run-record.d.ts +83 -4
  19. package/dist/commands/exec/run-record.js +49 -1
  20. package/dist/commands/exec/tests-summary.d.ts +1 -1
  21. package/dist/commands/exec/tests-summary.js +1 -1
  22. package/dist/commands/exec/view.js +36 -4
  23. package/dist/commands/runs/facts.d.ts +25 -0
  24. package/dist/commands/runs/facts.js +36 -3
  25. package/dist/commands/runs/list/command.d.ts +154 -1
  26. package/dist/commands/runs/list/command.js +1 -1
  27. package/dist/commands/runs/list/outcomes.d.ts +41 -0
  28. package/dist/commands/runs/logs/command.d.ts +263 -1
  29. package/dist/commands/runs/logs/command.js +1 -1
  30. package/dist/commands/runs/logs/outcomes.d.ts +105 -0
  31. package/dist/commands/runs/show/command.d.ts +354 -1
  32. package/dist/commands/runs/show/command.js +1 -1
  33. package/dist/commands/runs/show/metadata.js +1 -1
  34. package/dist/commands/runs/show/outcomes.d.ts +96 -0
  35. package/dist/commands/runs/show/outcomes.js +30 -1
  36. package/dist/commands/vitest/command.d.ts +912 -1
  37. package/dist/commands/vitest/command.js +1 -1
  38. package/dist/commands/vitest/metadata.d.ts +5 -2
  39. package/dist/commands/vitest/metadata.js +4 -0
  40. package/dist/commands/vitest/outcomes.d.ts +320 -0
  41. package/dist/config/errors.d.ts +73 -0
  42. package/dist/config/schema.d.ts +1 -1
  43. package/dist/config-file/define.d.ts +4 -3
  44. package/dist/config-file/define.js +1 -1
  45. package/dist/config-file/toolchain.js +1 -1
  46. package/dist/core/command-slots.d.ts +8 -2
  47. package/dist/core/command-slots.js +6 -2
  48. package/dist/core/events.d.ts +9 -7
  49. package/dist/core/index.d.ts +1 -1
  50. package/dist/core/run-state.d.ts +30 -6
  51. package/dist/core/run-state.js +19 -4
  52. package/dist/core/run.d.ts +17 -4
  53. package/dist/core/run.js +61 -25
  54. package/dist/credential/index.d.ts +1 -0
  55. package/dist/credential/index.js +1 -0
  56. package/dist/credential/settle.d.ts +20 -0
  57. package/dist/credential/target.d.ts +6 -0
  58. package/dist/credential/target.js +7 -0
  59. package/dist/resources/github/command.d.ts +54 -2
  60. package/dist/resources/github/config.js +1 -1
  61. package/dist/resources/github/index.js +1 -1
  62. package/dist/resources/github/resource.js +2 -2
  63. package/dist/resources/testserver/command.d.ts +208 -10
  64. package/dist/resources/testserver/command.js +7 -0
  65. package/dist/resources/testserver/commands/create/command.d.ts +808 -1
  66. package/dist/resources/testserver/commands/create/command.js +64 -23
  67. package/dist/resources/testserver/commands/create/metadata.js +6 -2
  68. package/dist/resources/testserver/commands/create/outcomes.d.ts +347 -0
  69. package/dist/resources/testserver/commands/create/outcomes.js +14 -1
  70. package/dist/resources/testserver/commands/list/command.d.ts +84 -1
  71. package/dist/resources/testserver/commands/list/command.js +1 -1
  72. package/dist/resources/testserver/commands/list/outcomes.d.ts +16 -0
  73. package/dist/resources/testserver/config.js +14 -4
  74. package/dist/resources/testserver/events.d.ts +9 -0
  75. package/dist/resources/testserver/index.js +8 -7
  76. package/dist/resources/testserver/lane.js +1 -0
  77. package/dist/resources/testserver/live/gateways.d.ts +2 -0
  78. package/dist/resources/testserver/live/gateways.js +16 -3
  79. package/dist/resources/testserver/pool/channels.d.ts +5 -2
  80. package/dist/resources/testserver/pool/channels.js +1 -1
  81. package/dist/resources/testserver/pool/create.d.ts +6 -2
  82. package/dist/resources/testserver/pool/create.js +6 -5
  83. package/dist/resources/testserver/pool/index.d.ts +1 -0
  84. package/dist/resources/testserver/pool/index.js +1 -0
  85. package/dist/resources/testserver/pool/pull-request.d.ts +89 -0
  86. package/dist/resources/testserver/pool/pull-request.js +85 -0
  87. package/dist/resources/testserver/pr-build-facts.d.ts +130 -0
  88. package/dist/resources/testserver/pr-build-facts.js +261 -0
  89. package/dist/resources/testserver/presentation.d.ts +2 -2
  90. package/dist/resources/testserver/presentation.js +12 -3
  91. package/dist/resources/testserver/provider.d.ts +16 -6
  92. package/dist/resources/testserver/provider.js +46 -15
  93. package/dist/resources/testserver/pull-request/gateways.d.ts +117 -0
  94. package/dist/resources/testserver/pull-request/gateways.js +5 -0
  95. package/dist/resources/testserver/pull-request/index.d.ts +5 -0
  96. package/dist/resources/testserver/pull-request/index.js +6 -0
  97. package/dist/resources/testserver/pull-request/live/github-rest.d.ts +28 -0
  98. package/dist/resources/testserver/pull-request/live/github-rest.js +114 -0
  99. package/dist/resources/testserver/pull-request/live/github-token-gateway.d.ts +12 -0
  100. package/dist/resources/testserver/pull-request/live/github-token-gateway.js +39 -0
  101. package/dist/resources/testserver/pull-request/live/pull-request-gateway.d.ts +10 -0
  102. package/dist/resources/testserver/pull-request/live/pull-request-gateway.js +27 -0
  103. package/dist/resources/testserver/pull-request/live/testserver-workflow-gateway.d.ts +21 -0
  104. package/dist/resources/testserver/pull-request/live/testserver-workflow-gateway.js +64 -0
  105. package/dist/resources/testserver/ran.d.ts +5 -0
  106. package/dist/resources/testserver/ran.js +19 -3
  107. package/dist/resources/testserver/resource.d.ts +5 -1
  108. package/dist/resources/testserver/resource.js +2 -2
  109. package/dist/resources/testserver/sandbox/build-reference.d.ts +38 -0
  110. package/dist/resources/testserver/sandbox/build-reference.js +79 -0
  111. package/dist/resources/testserver/sandbox/index.d.ts +1 -0
  112. package/dist/resources/testserver/sandbox/index.js +1 -0
  113. package/dist/resources.d.ts +265 -15
  114. package/dist/runner/events.d.ts +64 -1
  115. package/dist/runner/gateways.d.ts +17 -6
  116. package/dist/runner/index.d.ts +5 -4
  117. package/dist/runner/index.js +4 -3
  118. package/dist/runner/live/snapshot-records.js +18 -4
  119. package/dist/runner/prepare.d.ts +23 -4
  120. package/dist/runner/prepare.js +13 -3
  121. package/dist/runner/ready.d.ts +7 -3
  122. package/dist/runner/ready.js +11 -5
  123. package/dist/runner/scope.d.ts +17 -1
  124. package/dist/runner/scope.js +4 -0
  125. package/dist/runner/snapshot-build.d.ts +3 -1
  126. package/dist/runner/snapshot-build.js +12 -2
  127. package/dist/runner/snapshot-cache.d.ts +46 -8
  128. package/dist/runner/snapshot-cache.js +60 -11
  129. package/dist/runner/snapshot-key.d.ts +12 -1
  130. package/dist/runner/snapshot-key.js +17 -1
  131. package/dist/runner/snapshot-save.d.ts +53 -0
  132. package/dist/runner/snapshot-save.js +148 -0
  133. package/dist/sdk/index.js +2 -2
  134. package/dist/story/align.d.ts +1 -1
  135. package/dist/story/align.js +1 -1
  136. package/dist/story/command-line.d.ts +34 -0
  137. package/dist/story/command-line.js +100 -0
  138. package/dist/story/definition.d.ts +22 -15
  139. package/dist/story/definition.js +2 -2
  140. package/dist/story/errors.js +1 -1
  141. package/dist/story/gateways.d.ts +45 -25
  142. package/dist/story/gateways.js +2 -2
  143. package/dist/story/host.d.ts +11 -8
  144. package/dist/story/host.js +37 -37
  145. package/dist/story/index.d.ts +2 -1
  146. package/dist/story/index.js +6 -5
  147. package/dist/story/json.d.ts +1 -1
  148. package/dist/story/json.js +2 -2
  149. package/dist/story/live/recording-gateway.d.ts +2 -0
  150. package/dist/story/live/{artifact-gateway.js → recording-gateway.js} +33 -12
  151. package/dist/story/mode.d.ts +2 -2
  152. package/dist/story/mode.js +1 -1
  153. package/dist/story/orphans.d.ts +23 -5
  154. package/dist/story/orphans.js +44 -8
  155. package/dist/story/recording.d.ts +62 -0
  156. package/dist/story/{artifact.js → recording.js} +31 -27
  157. package/dist/story/report.d.ts +21 -9
  158. package/dist/story/report.js +37 -25
  159. package/dist/story/settle.d.ts +23 -21
  160. package/dist/story/settle.js +17 -16
  161. package/dist/story/{run.d.ts → start.d.ts} +18 -17
  162. package/dist/story/{run.js → start.js} +66 -43
  163. package/dist/vercel-cli/context.js +1 -1
  164. package/dist/vercel-cli/index.js +1 -1
  165. package/dist/vitest/config.js +2 -2
  166. package/dist/vitest/fixtures.d.ts +1 -1
  167. package/dist/vitest/fixtures.js +1 -1
  168. package/dist/vitest/index.js +3 -3
  169. package/dist/vitest/plan.js +1 -1
  170. package/package.json +3 -3
  171. package/skills/overview.md +2 -0
  172. package/skills/testserver-builds.md +80 -0
  173. package/dist/story/artifact.d.ts +0 -60
  174. package/dist/story/live/artifact-gateway.d.ts +0 -2
@@ -0,0 +1,53 @@
1
+ import type { RunnerContext } from "./context.ts";
2
+ import type { RunnerProgress, RunnerSave } from "./events.ts";
3
+ import type { ReadyRunner } from "./ready.ts";
4
+ import type { RunnerSandboxScope } from "./scope.ts";
5
+ /** The directories the temp scrub empties: `/tmp`, `/var/tmp`, and `$TMPDIR` when it is set. */
6
+ export declare const TEMP_DIRECTORIES: readonly string[];
7
+ /**
8
+ * Resets the working tree in `root` to its root commit, the base's tracked files (`baseIndexScript`), and removes
9
+ * untracked files and nested Git repositories that `.gitignore` doesn't match: the same reset the next run's apply
10
+ * starts with (`RESET_TO_BASE`). Ignored files, such as `node_modules`, build outputs and the turbo cache, stay.
11
+ *
12
+ * It leaves `.git` alone, so the run's commit and anything else the command put in Git stay in the snapshot. Cleaning
13
+ * history adds no correctness: the next run resets before it applies. Nor does it hide the run's changes: the ignored
14
+ * files the snapshot keeps hold their build outputs. And `git prune` can't promise it either, since it removes only
15
+ * loose objects, not packed ones.
16
+ */
17
+ export declare function scrubGitScript(root?: string): string;
18
+ /**
19
+ * Empties each of `directories`, shell words that may expand to nothing: deletes what it holds, then, for anything
20
+ * left, tries again with `sudo -n`. Fails, naming the directory and what is left, when one still holds something.
21
+ */
22
+ export declare function scrubTempScript(directories?: readonly string[]): string;
23
+ /** What saving a branch snapshot is asked to save: the ready runner sandbox, and the branch and commit it is for. */
24
+ export interface SaveBranchSnapshotRequest {
25
+ /** The runner sandbox the command ran in, and the runner snapshot it started from. */
26
+ readonly ready: ReadyRunner;
27
+ /** HEAD's branch as the run started, which the snapshot is for. */
28
+ readonly branch: string;
29
+ /** HEAD's commit as the run started, a full SHA. */
30
+ readonly head: string;
31
+ }
32
+ /** How a save that ran ended: a detached HEAD's `skipped` is decided before the run (`prepareRunner`). */
33
+ type BranchSnapshotSave = Exclude<RunnerSave, {
34
+ readonly kind: "skipped";
35
+ }>;
36
+ /**
37
+ * Saves the runner sandbox, once the command ended, as a branch snapshot of the run's branch. The run's plan gave the
38
+ * scope no keep time (`RunnerSandboxPlan`), so however the save ends, closing stops and deletes the sandbox. It resets
39
+ * the working tree to the base the sandbox started from, leaving `.git` alone, empties the temp directories, saves the
40
+ * sandbox as a runner snapshot, which the scope then deletes, and records the entry: the started-from entry's owner,
41
+ * recipe, snapshot key and base, with the branch, the HEAD commit and the checkout's root. Its entry replaces the
42
+ * branch's entry in that checkout at that base; the snapshot it replaces is left to expire, since a run on this
43
+ * machine may be starting from it. Nothing here changes the run's outcome: each way it ends is a note.
44
+ *
45
+ * It searches nothing for the run's secrets: the snapshot keeps what the command wrote to `$HOME` and the ignored
46
+ * files, such as a resource's token, as a kept runner sandbox does. The token is limited to one test resource, and
47
+ * only a later run on the branch from this checkout, which gets the same token, starts from the snapshot.
48
+ */
49
+ export declare function saveBranchSnapshot(context: Pick<RunnerContext, "runnerSandboxes" | "runnerSnapshots" | "clock">, request: SaveBranchSnapshotRequest, control: {
50
+ readonly scope: RunnerSandboxScope;
51
+ readonly signal: AbortSignal;
52
+ }, progress: RunnerProgress): Promise<BranchSnapshotSave>;
53
+ export {};
@@ -0,0 +1,148 @@
1
+ // Saving a runner run's runner sandbox as a branch snapshot once its command ended (`--save-snapshot`): reset the
2
+ // working tree to its base and empty the temp directories, save the sandbox as a runner snapshot, and record it in the
3
+ // cache for the run's branch in its checkout. The snapshot keeps the rest of what the command left, a run secret it
4
+ // wrote included.
5
+ import { lineSplitter, outputTail, splitLines } from "./output.js";
6
+ import { SNAPSHOT_EXPIRATION_MS } from "./snapshot-cache.js";
7
+ import { REMOTE_ROOT, RESET_TO_BASE } from "./snapshot-key.js";
8
+ import { STEP_ENV } from "./steps.js";
9
+ /** How many of a failed script's last output lines its note keeps. */
10
+ const FAILURE_TAIL_LINES = 3;
11
+ /** The directories the temp scrub empties: `/tmp`, `/var/tmp`, and `$TMPDIR` when it is set. */
12
+ export const TEMP_DIRECTORIES = ["/tmp", "/var/tmp", '"${TMPDIR:-}"'];
13
+ /**
14
+ * Resets the working tree in `root` to its root commit, the base's tracked files (`baseIndexScript`), and removes
15
+ * untracked files and nested Git repositories that `.gitignore` doesn't match: the same reset the next run's apply
16
+ * starts with (`RESET_TO_BASE`). Ignored files, such as `node_modules`, build outputs and the turbo cache, stay.
17
+ *
18
+ * It leaves `.git` alone, so the run's commit and anything else the command put in Git stay in the snapshot. Cleaning
19
+ * history adds no correctness: the next run resets before it applies. Nor does it hide the run's changes: the ignored
20
+ * files the snapshot keeps hold their build outputs. And `git prune` can't promise it either, since it removes only
21
+ * loose objects, not packed ones.
22
+ */
23
+ export function scrubGitScript(root = REMOTE_ROOT) {
24
+ return ["set -euo pipefail", `cd ${root}`, ...RESET_TO_BASE].join("\n");
25
+ }
26
+ /**
27
+ * Empties each of `directories`, shell words that may expand to nothing: deletes what it holds, then, for anything
28
+ * left, tries again with `sudo -n`. Fails, naming the directory and what is left, when one still holds something.
29
+ */
30
+ export function scrubTempScript(directories = TEMP_DIRECTORIES) {
31
+ return [
32
+ "set -euo pipefail",
33
+ `for dir in ${directories.join(" ")}; do`,
34
+ ' [ -n "$dir" ] && [ -d "$dir" ] || continue',
35
+ ' find "$dir" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true',
36
+ ' if [ -n "$(find "$dir" -mindepth 1 -maxdepth 1 -print -quit)" ]; then',
37
+ ' sudo -n find "$dir" -mindepth 1 -maxdepth 1 -exec rm -rf -- {} + 2>/dev/null || true',
38
+ " fi",
39
+ ' left=$(find "$dir" -mindepth 1 -maxdepth 1 -print -quit)',
40
+ ' if [ -n "$left" ]; then echo "couldn\'t empty $dir: $left is left" >&2; exit 1; fi',
41
+ "done",
42
+ ].join("\n");
43
+ }
44
+ /**
45
+ * Saves the runner sandbox, once the command ended, as a branch snapshot of the run's branch. The run's plan gave the
46
+ * scope no keep time (`RunnerSandboxPlan`), so however the save ends, closing stops and deletes the sandbox. It resets
47
+ * the working tree to the base the sandbox started from, leaving `.git` alone, empties the temp directories, saves the
48
+ * sandbox as a runner snapshot, which the scope then deletes, and records the entry: the started-from entry's owner,
49
+ * recipe, snapshot key and base, with the branch, the HEAD commit and the checkout's root. Its entry replaces the
50
+ * branch's entry in that checkout at that base; the snapshot it replaces is left to expire, since a run on this
51
+ * machine may be starting from it. Nothing here changes the run's outcome: each way it ends is a note.
52
+ *
53
+ * It searches nothing for the run's secrets: the snapshot keeps what the command wrote to `$HOME` and the ignored
54
+ * files, such as a resource's token, as a kept runner sandbox does. The token is limited to one test resource, and
55
+ * only a later run on the branch from this checkout, which gets the same token, starts from the snapshot.
56
+ */
57
+ export async function saveBranchSnapshot(context, request, control, progress) {
58
+ const save = await saveOnce(context, request, control, progress);
59
+ if (save.kind !== "saved")
60
+ await progress.emit({ kind: "branch-snapshot-not-saved", save });
61
+ return save;
62
+ }
63
+ async function saveOnce(context, request, control, progress) {
64
+ const { ready, branch, head } = request;
65
+ const { scope, signal } = control;
66
+ const stopped = () => signal.aborted || scope.closed;
67
+ if (stopped())
68
+ return { kind: "stopped" };
69
+ const { sandbox, startedFrom } = ready;
70
+ const startedAt = context.clock.now().getTime();
71
+ await progress.emit({ kind: "branch-snapshot-saving", branch });
72
+ for (const script of [scrubGitScript(), scrubTempScript()]) {
73
+ if (stopped())
74
+ return { kind: "stopped" };
75
+ const ran = await runSaveScript(context, sandbox, script, signal);
76
+ if (ran.kind === "stopped")
77
+ return ran;
78
+ if (ran.kind === "failed")
79
+ return { kind: "failed", step: "scrub", message: ran.message };
80
+ }
81
+ if (stopped())
82
+ return { kind: "stopped" };
83
+ const saved = await scope.saveSnapshot(sandbox, { expirationMs: SNAPSHOT_EXPIRATION_MS });
84
+ if (!saved.ok)
85
+ return saved.failure.kind === "aborted"
86
+ ? { kind: "stopped" }
87
+ : { kind: "failed", step: "save-snapshot", message: saved.failure.message };
88
+ // A signal while the snapshot saved: the snapshot exists, but the run records nothing more.
89
+ if (signal.aborted)
90
+ return { kind: "stopped" };
91
+ const savedAt = context.clock.now();
92
+ const entry = {
93
+ teamId: startedFrom.teamId,
94
+ projectId: startedFrom.projectId,
95
+ region: startedFrom.region,
96
+ runtime: startedFrom.runtime,
97
+ recipeName: startedFrom.recipeName,
98
+ snapshotKey: startedFrom.snapshotKey,
99
+ base: startedFrom.base,
100
+ branch,
101
+ head,
102
+ repoRoot: ready.repoRoot,
103
+ snapshotId: saved.value.snapshotId,
104
+ createdAt: savedAt.toISOString(),
105
+ expiresAt: saved.value.expiresAt ?? new Date(savedAt.getTime() + SNAPSHOT_EXPIRATION_MS).toISOString(),
106
+ };
107
+ const written = await context.runnerSnapshots.writeEntry(entry);
108
+ if (!written.ok)
109
+ await progress.emit({ kind: "snapshot-entry-not-written", failure: written.failure });
110
+ const ms = savedAt.getTime() - startedAt;
111
+ await progress.emit({
112
+ kind: "branch-snapshot-saved",
113
+ snapshotId: entry.snapshotId,
114
+ branch,
115
+ head,
116
+ ms,
117
+ sizeBytes: saved.value.sizeBytes,
118
+ });
119
+ return {
120
+ kind: "saved",
121
+ snapshotId: entry.snapshotId,
122
+ base: entry.base,
123
+ branch,
124
+ head,
125
+ ms,
126
+ sizeBytes: saved.value.sizeBytes,
127
+ entryWritten: written.ok,
128
+ };
129
+ }
130
+ async function runSaveScript(context, sandbox, script, signal) {
131
+ const splitters = { stdout: lineSplitter(), stderr: lineSplitter() };
132
+ const tail = outputTail(FAILURE_TAIL_LINES);
133
+ const keep = (text) => {
134
+ for (const line of splitLines(text))
135
+ tail.add(line);
136
+ };
137
+ const ran = await context.runnerSandboxes.runScript(sandbox, { script, env: STEP_ENV }, ({ stream, data }) => keep(splitters[stream].push(data)), signal);
138
+ keep(splitters.stdout.flush());
139
+ keep(splitters.stderr.flush());
140
+ if (!ran.ok)
141
+ return ran.failure.kind === "aborted" ? { kind: "stopped" } : { kind: "failed", message: ran.failure.message };
142
+ const { exitCode } = ran.value;
143
+ if (exitCode === 0)
144
+ return { kind: "ok" };
145
+ const lines = tail.lines();
146
+ const ended = exitCode === null ? "ended without an exit code" : `exited ${exitCode}`;
147
+ return { kind: "failed", message: lines.length === 0 ? ended : `${ended}: ${lines.join(" / ")}` };
148
+ }
package/dist/sdk/index.js CHANGED
@@ -1,8 +1,8 @@
1
- // The storm SDK's published surface, exported as `@cnc-tools/storm/sdk`: only what a command uses. A command
1
+ // The storm SDK's published surface, exported as `@vercel/storm/sdk`: only what a command uses. A command
2
2
  // running under a storm run uses it to read the run payload, start containers, seed them through factories or
3
3
  // the seeder's entity-level calls, send them API requests, warm their services, read their logs, and proxy clients
4
4
  // that can't send a test id. The gateway seams the SDK's own tests and fakes need live on each SDK module's
5
- // `index.ts`, not here. The Vitest adapter (`src/vitest/`, `@cnc-tools/storm/vitest`) builds on this surface;
5
+ // `index.ts`, not here. The Vitest adapter (`src/vitest/`, `@vercel/storm/vitest`) builds on this surface;
6
6
  // nothing here imports it. Everything
7
7
  // under `src/sdk/` depends only on Node builtins and `zod`, and on nothing outside this directory, so the tree can
8
8
  // move into its own package; `tsconfig.sdk.json` and `.oxlintrc.json` check it.
@@ -1,4 +1,4 @@
1
- import type { StoryCall } from "./artifact.ts";
1
+ import type { StoryCall } from "./recording.ts";
2
2
  /**
3
3
  * One place in the alignment of recorded and live calls:
4
4
  *
@@ -1,4 +1,4 @@
1
- // Aligning the calls a story made with the calls its artifact recorded. Pure.
1
+ // Aligning the calls a story made with the calls in its recording. Pure.
2
2
  import { canonicalJson, sameJson } from "./json.js";
3
3
  import { diffSequences, MAX_SEQUENCE_CELLS } from "./sequence.js";
4
4
  /** A call's key, (agent, tool, input), as one string: two calls have the same key when these are equal. */
@@ -0,0 +1,34 @@
1
+ /** A command line the harness can't split into words: the story or the variable wrote it. */
2
+ export declare class InvalidCommandLine extends Error {
3
+ readonly name = "InvalidCommandLine";
4
+ }
5
+ /**
6
+ * `command` split into words as a POSIX shell splits them: whitespace separates words; single quotes keep everything
7
+ * up to the next single quote; double quotes keep everything up to the next unescaped double quote, where a backslash
8
+ * escapes `"`, `\`, `$` and a backtick; a backslash outside quotes escapes the next character. A shell operator or
9
+ * expansion outside quotes (`|`, `&`, `;`, `<`, `>`, `(`, `)`, `$`, a backtick, `*`, `?`, `[`, `~`, `#`) and an
10
+ * unclosed quote throw `InvalidCommandLine`, since the harness runs no shell.
11
+ */
12
+ export declare function splitCommandLine(command: string): readonly string[];
13
+ /** A program and the words it gets before a story's own arguments. */
14
+ export interface StoryExecutable {
15
+ readonly file: string;
16
+ readonly args: readonly string[];
17
+ }
18
+ /** Where `storyExecutable` reads the executable a harness invokes. */
19
+ export interface StoryExecutableOptions {
20
+ /** The environment variable that names another executable, such as `SLOT_STORY_BIN`. */
21
+ readonly variable: string;
22
+ readonly env: Readonly<Record<string, string | undefined>>;
23
+ /** The executable when the variable is unset or empty: the package's own. */
24
+ readonly fallback: StoryExecutable;
25
+ /** The directory a relative program word resolves against: the one the tests run from, never a story's cwd. */
26
+ readonly base: string;
27
+ }
28
+ /**
29
+ * The executable `variable`'s value in `env` names, or `fallback` when it is unset or empty. The value is split as
30
+ * `splitCommandLine` splits a story's command: its first word is the program, and the rest come before the story's
31
+ * arguments. A program word with a `/` that isn't absolute resolves against `base`; a word without one is looked up on
32
+ * `PATH`. A value that doesn't split, or holds only whitespace, throws an error that names the variable.
33
+ */
34
+ export declare function storyExecutable({ variable, env, fallback, base }: StoryExecutableOptions): StoryExecutable;
@@ -0,0 +1,100 @@
1
+ // Command lines a harness splits without a shell: a story's command, and the executable a `*_BIN` variable names in
2
+ // place of the package's own, such as a port of the tool to another language. Pure.
3
+ import { isAbsolute, resolve } from "node:path";
4
+ /** A command line the harness can't split into words: the story or the variable wrote it. */
5
+ export class InvalidCommandLine extends Error {
6
+ name = "InvalidCommandLine";
7
+ }
8
+ /**
9
+ * `command` split into words as a POSIX shell splits them: whitespace separates words; single quotes keep everything
10
+ * up to the next single quote; double quotes keep everything up to the next unescaped double quote, where a backslash
11
+ * escapes `"`, `\`, `$` and a backtick; a backslash outside quotes escapes the next character. A shell operator or
12
+ * expansion outside quotes (`|`, `&`, `;`, `<`, `>`, `(`, `)`, `$`, a backtick, `*`, `?`, `[`, `~`, `#`) and an
13
+ * unclosed quote throw `InvalidCommandLine`, since the harness runs no shell.
14
+ */
15
+ export function splitCommandLine(command) {
16
+ const words = [];
17
+ let word;
18
+ let index = 0;
19
+ const add = (text) => {
20
+ word = (word ?? "") + text;
21
+ };
22
+ while (index < command.length) {
23
+ const char = command[index] ?? "";
24
+ if (/\s/u.test(char)) {
25
+ if (word !== undefined)
26
+ words.push(word);
27
+ word = undefined;
28
+ index += 1;
29
+ }
30
+ else if (char === "'") {
31
+ const end = command.indexOf("'", index + 1);
32
+ if (end === -1)
33
+ throw new InvalidCommandLine(`${JSON.stringify(command)} has an unclosed single quote`);
34
+ add(command.slice(index + 1, end));
35
+ index = end + 1;
36
+ }
37
+ else if (char === '"') {
38
+ let text = "";
39
+ index += 1;
40
+ while (command[index] !== '"') {
41
+ if (index >= command.length) {
42
+ throw new InvalidCommandLine(`${JSON.stringify(command)} has an unclosed double quote`);
43
+ }
44
+ const next = command[index + 1] ?? "";
45
+ if (command[index] === "\\" && ['"', "\\", "$", "`"].includes(next)) {
46
+ text += next;
47
+ index += 2;
48
+ }
49
+ else {
50
+ text += command[index] ?? "";
51
+ index += 1;
52
+ }
53
+ }
54
+ add(text);
55
+ index += 1;
56
+ }
57
+ else if (char === "\\") {
58
+ if (index + 1 >= command.length)
59
+ throw new InvalidCommandLine(`${JSON.stringify(command)} ends in a backslash`);
60
+ add(command[index + 1] ?? "");
61
+ index += 2;
62
+ }
63
+ else if ("|&;<>()$`*?[~#".includes(char)) {
64
+ throw new InvalidCommandLine(`${JSON.stringify(command)} has ${JSON.stringify(char)} outside quotes, and the harness runs no shell`);
65
+ }
66
+ else {
67
+ add(char);
68
+ index += 1;
69
+ }
70
+ }
71
+ if (word !== undefined)
72
+ words.push(word);
73
+ return words;
74
+ }
75
+ /**
76
+ * The executable `variable`'s value in `env` names, or `fallback` when it is unset or empty. The value is split as
77
+ * `splitCommandLine` splits a story's command: its first word is the program, and the rest come before the story's
78
+ * arguments. A program word with a `/` that isn't absolute resolves against `base`; a word without one is looked up on
79
+ * `PATH`. A value that doesn't split, or holds only whitespace, throws an error that names the variable.
80
+ */
81
+ export function storyExecutable({ variable, env, fallback, base }) {
82
+ const commandLine = env[variable];
83
+ if (commandLine === undefined || commandLine === "")
84
+ return fallback;
85
+ let words;
86
+ try {
87
+ words = splitCommandLine(commandLine);
88
+ }
89
+ catch (error) {
90
+ throw new Error(`${variable} ${errorText(error)}`, { cause: error });
91
+ }
92
+ const [program, ...args] = words;
93
+ if (program === undefined)
94
+ throw new Error(`${variable} ${JSON.stringify(commandLine)} names no program`);
95
+ const file = program.includes("/") && !isAbsolute(program) ? resolve(base, program) : program;
96
+ return { file, args };
97
+ }
98
+ function errorText(error) {
99
+ return error instanceof Error ? error.message : String(error);
100
+ }
@@ -1,23 +1,27 @@
1
1
  import type { z } from "zod";
2
2
  import type { StoryJson } from "./json.ts";
3
- /** One story's session: what the tools run against. Story calls `close()` once the story ends, pass or fail. */
3
+ /** One story's session: what the tools run against. Story core closes it once the story ends, pass or fail. */
4
4
  export interface StorySession {
5
5
  close(): void | Promise<void>;
6
6
  }
7
7
  /**
8
8
  * A tool an agent calls: `input`, the schema its input must match; `run`, which does the work against the story's
9
- * session with the parsed input and returns a result; and `observe`, the JSON story records and compares for that
10
- * result. The story gets the result itself; only the observation reaches the artifact. `run` and `observe` are
11
- * methods, so a tool of any input and result fits an agent's `tools` map (`AnyStoryTool`).
9
+ * session with the parsed input and returns a value; and `observe`, which turns that return value into the
10
+ * observation, the JSON story core records and compares. The story gets the return value itself; only the observation
11
+ * reaches the recording. `run` and `observe` are methods, so a tool of any input and return value fits an agent's
12
+ * `tools` map (`AnyStoryTool`).
12
13
  */
13
- export interface StoryTool<Session, Schema extends z.ZodType, Result> {
14
+ export interface StoryTool<Session, Schema extends z.ZodType, Returned> {
14
15
  readonly input: Schema;
15
- run(session: Session, input: z.output<Schema>): Result | Promise<Result>;
16
- observe(result: Result): StoryJson;
16
+ run(session: Session, input: z.output<Schema>): Returned | Promise<Returned>;
17
+ observe(returned: Returned): StoryJson;
17
18
  }
18
- /** A tool with any input and result, as an agent's `tools` map holds it. */
19
+ /** A tool with any input and return value, as an agent's `tools` map holds it. */
19
20
  export type AnyStoryTool<Session> = StoryTool<Session, z.ZodType, unknown>;
20
- /** An agent: a name in the harness's `agents`, and the tools it may call. */
21
+ /**
22
+ * An agent: a name in the harness's `agents`, such as `tester` or `user`, with the tools a story calls through it. The
23
+ * name is part of each tool call's key; story core gives it no meaning.
24
+ */
21
25
  export interface StoryAgent<Session> {
22
26
  readonly tools: {
23
27
  readonly [tool: string]: AnyStoryTool<Session>;
@@ -27,14 +31,17 @@ export interface StoryAgent<Session> {
27
31
  export type StoryAgents<Session> = {
28
32
  readonly [agent: string]: StoryAgent<Session>;
29
33
  };
30
- /** What `createStory` takes. */
34
+ /**
35
+ * What a set of stories declares once and passes to `createStory`: `start()`, which makes each story's session, and
36
+ * its agents with their tools.
37
+ */
31
38
  export interface StoryHarness<Session extends StorySession, Agents extends StoryAgents<Session>> {
32
39
  /** Starts the story's session, at its first tool call. A story that calls no tool starts none. */
33
40
  readonly start: () => Session | Promise<Session>;
34
41
  readonly agents: Agents;
35
42
  }
36
- /** How a story calls one tool: with the tool's input, resolving with its result. */
37
- export type StoryToolCall<Tool> = Tool extends StoryTool<infer _Session, infer Schema, infer Result> ? (input: z.input<Schema>) => Promise<Result> : never;
43
+ /** How a story calls one tool: with the tool's input, resolving with its return value. */
44
+ export type StoryToolCall<Tool> = Tool extends StoryTool<infer _Session, infer Schema, infer Returned> ? (input: z.input<Schema>) => Promise<Returned> : never;
38
45
  /** What a story's body gets: one handle per agent, each with a function per tool. */
39
46
  export type StoryHandles<Agents> = {
40
47
  readonly [Agent in keyof Agents]: {
@@ -46,7 +53,7 @@ export type StoryHandles<Agents> = {
46
53
  };
47
54
  };
48
55
  /**
49
- * `tool`, typed: TypeScript infers its input from `input`, its session from `run`'s first parameter, and its result
50
- * from what `run` returns, so `run` and `observe` need no other annotation. Annotate `run`'s session parameter.
56
+ * `tool`, typed: TypeScript infers its input from `input`, its session from `run`'s first parameter, and its return
57
+ * value from what `run` returns, so `run` and `observe` need no other annotation. Annotate `run`'s session parameter.
51
58
  */
52
- export declare function storyTool<Session, Schema extends z.ZodType, Result>(tool: StoryTool<Session, Schema, Result>): StoryTool<Session, Schema, Result>;
59
+ export declare function storyTool<Session, Schema extends z.ZodType, Returned>(tool: StoryTool<Session, Schema, Returned>): StoryTool<Session, Schema, Returned>;
@@ -1,8 +1,8 @@
1
1
  // What a story harness declares: how to start a session, and the agents with their tools. Types only, but for
2
2
  // `storyTool`, which returns its argument.
3
3
  /**
4
- * `tool`, typed: TypeScript infers its input from `input`, its session from `run`'s first parameter, and its result
5
- * from what `run` returns, so `run` and `observe` need no other annotation. Annotate `run`'s session parameter.
4
+ * `tool`, typed: TypeScript infers its input from `input`, its session from `run`'s first parameter, and its return
5
+ * value from what `run` returns, so `run` and `observe` need no other annotation. Annotate `run`'s session parameter.
6
6
  */
7
7
  export function storyTool(tool) {
8
8
  return tool;
@@ -1,4 +1,4 @@
1
- // The errors a story fails with when its body passed but its calls don't fit its artifact.
1
+ // The errors a story fails with when its body passed but its calls don't fit its recording.
2
2
  /** A story made a call whose observation differs from the recorded one: the tool behaved differently. */
3
3
  export class StoryDivergenceError extends Error {
4
4
  name = "StoryDivergenceError";
@@ -1,8 +1,8 @@
1
- import type { StoryArtifact } from "./artifact.ts";
2
- /** An artifact, read: found, missing, unreadable (not an artifact, with why), or a read that failed. */
3
- export type StoryArtifactRead = {
1
+ import type { StoryRecording } from "./recording.ts";
2
+ /** A recording, read: found, missing, unreadable (not a recording, with why), or a read that failed. */
3
+ export type StoryRecordingRead = {
4
4
  readonly kind: "found";
5
- readonly artifact: StoryArtifact;
5
+ readonly recording: StoryRecording;
6
6
  } | {
7
7
  readonly kind: "missing";
8
8
  } | {
@@ -13,10 +13,10 @@ export type StoryArtifactRead = {
13
13
  readonly message: string;
14
14
  };
15
15
  /**
16
- * An artifact, written: written, unchanged (its bytes were already there, so nothing was written), canceled (the
16
+ * A recording, written: written, unchanged (its bytes were already there, so nothing was written), canceled (the
17
17
  * signal aborted first, so nothing was written), or failed.
18
18
  */
19
- export type StoryArtifactWrite = {
19
+ export type StoryRecordingWrite = {
20
20
  readonly kind: "written";
21
21
  } | {
22
22
  readonly kind: "unchanged";
@@ -26,8 +26,8 @@ export type StoryArtifactWrite = {
26
26
  readonly kind: "failed";
27
27
  readonly message: string;
28
28
  };
29
- /** An artifact, removed: removed, missing (nothing was there), canceled (the signal aborted first), or failed. */
30
- export type StoryArtifactRemove = {
29
+ /** A recording, removed: removed, missing (nothing was there), canceled (the signal aborted first), or failed. */
30
+ export type StoryRecordingRemove = {
31
31
  readonly kind: "removed";
32
32
  } | {
33
33
  readonly kind: "missing";
@@ -37,38 +37,58 @@ export type StoryArtifactRemove = {
37
37
  readonly kind: "failed";
38
38
  readonly message: string;
39
39
  };
40
- /** The artifacts in one story file's artifact directory, by absolute path, sorted; none when it doesn't exist. */
41
- export type StoryArtifactList = {
40
+ /**
41
+ * Paths listed: the recordings in one story file's recording directory, or the recording directories in one
42
+ * `__story__/` directory, by absolute path, sorted; none when the directory doesn't exist.
43
+ */
44
+ export type StoryRecordingList = {
42
45
  readonly kind: "listed";
43
46
  readonly paths: readonly string[];
44
47
  } | {
45
48
  readonly kind: "failed";
46
49
  readonly message: string;
47
50
  };
51
+ /** A story file, looked for: found, missing (no file is there), or a look that failed. */
52
+ export type StoryFileFind = {
53
+ readonly kind: "found";
54
+ } | {
55
+ readonly kind: "missing";
56
+ } | {
57
+ readonly kind: "failed";
58
+ readonly message: string;
59
+ };
48
60
  /**
49
- * Where story artifacts live: one per story, by absolute path. A write or a removal given an aborted `signal` changes
50
- * nothing and returns `canceled`; the signal is checked again just before the change is made, so one that aborts
51
- * while the method waits still stops it.
61
+ * Where story recordings live: one per story, by absolute path, in its story file's recording directory. A write or a
62
+ * removal given an aborted `signal` changes nothing and returns `canceled`; the signal is checked again just before
63
+ * the change is made, so one that aborts while the method waits still stops it.
52
64
  */
53
- export interface StoryArtifactGateway {
54
- readArtifact(request: {
65
+ export interface StoryRecordingGateway {
66
+ readRecording(request: {
55
67
  readonly path: string;
56
- }): Promise<StoryArtifactRead>;
68
+ }): Promise<StoryRecordingRead>;
57
69
  /**
58
- * Writes `artifact` at `path` as `serializeArtifact` gives it, making missing directories, unless those bytes are
59
- * already there. A reader never sees half an artifact.
70
+ * Writes `recording` at `path` as `serializeRecording` gives it, making missing directories, unless those bytes are
71
+ * already there. A reader never sees half a recording.
60
72
  */
61
- writeArtifact(request: {
73
+ writeRecording(request: {
62
74
  readonly path: string;
63
- readonly artifact: StoryArtifact;
75
+ readonly recording: StoryRecording;
64
76
  readonly signal?: AbortSignal;
65
- }): Promise<StoryArtifactWrite>;
66
- removeArtifact(request: {
77
+ }): Promise<StoryRecordingWrite>;
78
+ removeRecording(request: {
67
79
  readonly path: string;
68
80
  readonly signal?: AbortSignal;
69
- }): Promise<StoryArtifactRemove>;
81
+ }): Promise<StoryRecordingRemove>;
70
82
  /** The `.json` files directly in `directory`. */
71
- listArtifacts(request: {
83
+ listRecordings(request: {
72
84
  readonly directory: string;
73
- }): Promise<StoryArtifactList>;
85
+ }): Promise<StoryRecordingList>;
86
+ /** The directories directly in `root`, a `__story__/` directory: each a story file's recording directory. */
87
+ listRecordingDirectories(request: {
88
+ readonly root: string;
89
+ }): Promise<StoryRecordingList>;
90
+ /** Whether a story file is at `path`. */
91
+ findStoryFile(request: {
92
+ readonly path: string;
93
+ }): Promise<StoryFileFind>;
74
94
  }
@@ -1,3 +1,3 @@
1
- // story's gateway: where story artifacts live. The live gateway is `live/artifact-gateway.ts`; the fake is
2
- // `test/fakes/story/artifact-gateway.ts`.
1
+ // Story core's gateway: where story recordings live. The live gateway is `live/recording-gateway.ts`; the fake is
2
+ // `test/fakes/story/recording-gateway.ts`.
3
3
  export {};
@@ -15,13 +15,16 @@ export interface StoryHostOptions {
15
15
  /** Declares one story, a Vitest test named `name`, whose body gets one handle per agent. */
16
16
  export type StoryFunction<Agents> = (name: string, body: (agents: StoryHandles<Agents>) => Promise<void>) => void;
17
17
  /**
18
- * The `story` function for `harness`. A story's name is its full test name, its `describe` names first; its artifact
19
- * is `artifactPath(<story file>, <name>)`. When the story ends, each call becomes a Vitest annotation of type `story`
20
- * (`storyEventLines`), and a line saying what it changed goes to stderr too. A story whose body threw prints its
21
- * report on stderr, when there is one, and fails with its body's error; one that diverged or went stale fails with
22
- * the report as the error. A story Vitest stops (a timeout, or a canceled run) ends then, without waiting for its body,
23
- * and counts as one whose body threw: its session closes, and it writes nothing and removes no orphans, even when its
24
- * body returns later or the stop comes while its end is changing the artifact. When every story in the file runs (no
25
- * test name filter, `.only` or `.skip` left one out), the last to end also finds the file's orphans.
18
+ * The `story` function for `harness`. A story's name is its full test name, its `describe` names first; its recording
19
+ * is `recordingPath(<story file>, <name>)`. When the story ends, each call becomes a Vitest annotation of type `story`
20
+ * (`storyEventLines`), and what a passing story changed, naming each call it rewrote (`storyChangeReport`), goes to
21
+ * stderr and becomes an annotation too. A story whose body threw prints its report on stderr, when there is one, and
22
+ * fails with its body's error; one that diverged or went stale fails with the report as the error. A story Vitest
23
+ * stops (a timeout, or a canceled Vitest run) ends then, without waiting for its body, and counts as one whose body
24
+ * threw: its session closes, and it writes nothing and removes no orphan recording, even when its body returns later
25
+ * or the stop comes while its end is changing the recording. When every story in the file runs (no test name filter,
26
+ * `.only` or `.skip` left one out), the last story the file declares also finds the orphan recordings when it ends
27
+ * (`looksForOrphans`, `findOrphans`): the file's own, and those in the recording directory of each story file that is
28
+ * gone.
26
29
  */
27
30
  export declare function createStory<Session extends StorySession, Agents extends StoryAgents<Session>>(harness: StoryHarness<Session, Agents>, options?: StoryHostOptions): StoryFunction<Agents>;