@ftrdotdev/pi-delegates 0.0.0-stage → 0.2.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 (138) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/LICENSE +21 -0
  3. package/OPERATIONS.md +130 -0
  4. package/README.md +456 -2
  5. package/ROADMAP.md +179 -0
  6. package/TESTING.md +896 -0
  7. package/agents.ts +8 -0
  8. package/examples/README.md +114 -0
  9. package/examples/gated.ts +28 -0
  10. package/index.ts +9 -0
  11. package/package.json +94 -4
  12. package/skills/pi-delegates/SKILL.md +176 -0
  13. package/skills/pi-delegates/references/control.md +159 -0
  14. package/skills/pi-delegates/references/definitions.md +163 -0
  15. package/skills/pi-delegates/references/gates.md +175 -0
  16. package/skills/pi-delegates/references/launch.md +184 -0
  17. package/src/docs-contract.test.ts +106 -0
  18. package/src/domain/definitions.test.ts +41 -0
  19. package/src/domain/definitions.ts +163 -0
  20. package/src/domain/failure.ts +33 -0
  21. package/src/domain/ids.ts +13 -0
  22. package/src/domain/model-source.ts +30 -0
  23. package/src/domain/names.ts +35 -0
  24. package/src/domain/orchestration/admission.ts +78 -0
  25. package/src/domain/orchestration/control.test.ts +1332 -0
  26. package/src/domain/orchestration/control.ts +457 -0
  27. package/src/domain/orchestration/fanout.test.ts +524 -0
  28. package/src/domain/orchestration/fanout.ts +372 -0
  29. package/src/domain/orchestration/gates.test.ts +685 -0
  30. package/src/domain/orchestration/gates.ts +360 -0
  31. package/src/domain/orchestration/launch.test.ts +372 -0
  32. package/src/domain/orchestration/launch.ts +691 -0
  33. package/src/domain/orchestration/requests.test.ts +695 -0
  34. package/src/domain/orchestration/requests.ts +782 -0
  35. package/src/domain/orchestration/review.test.ts +292 -0
  36. package/src/domain/orchestration/review.ts +168 -0
  37. package/src/domain/orchestration/run-wait.test.ts +265 -0
  38. package/src/domain/orchestration/run-wait.ts +256 -0
  39. package/src/domain/orchestration/workflow-section.test.ts +62 -0
  40. package/src/domain/orchestration/workflow-section.ts +99 -0
  41. package/src/domain/orchestration/workflow.test.ts +1566 -0
  42. package/src/domain/orchestration/workflow.ts +778 -0
  43. package/src/domain/run-records.test.ts +27 -0
  44. package/src/domain/run-records.ts +689 -0
  45. package/src/domain/settlement.test.ts +186 -0
  46. package/src/domain/settlement.ts +137 -0
  47. package/src/domain/shapes.test.ts +185 -0
  48. package/src/domain/skills.test.ts +477 -0
  49. package/src/domain/skills.ts +114 -0
  50. package/src/domain/tool-schema.test.ts +46 -0
  51. package/src/domain/tool-schema.ts +20 -0
  52. package/src/domain/toolkit.test.ts +215 -0
  53. package/src/domain/toolkit.ts +374 -0
  54. package/src/domain/turn-budget.test.ts +37 -0
  55. package/src/domain/turn-budget.ts +23 -0
  56. package/src/domain/view.test.ts +803 -0
  57. package/src/domain/view.ts +491 -0
  58. package/src/example.test.ts +15 -0
  59. package/src/extension/commands.test.ts +485 -0
  60. package/src/extension/commands.ts +230 -0
  61. package/src/extension/entry.test.ts +1276 -0
  62. package/src/extension/entry.ts +380 -0
  63. package/src/extension/gate-alerts.test.ts +237 -0
  64. package/src/extension/gate-alerts.ts +143 -0
  65. package/src/extension/guard.test.ts +48 -0
  66. package/src/extension/guard.ts +31 -0
  67. package/src/extension/host-signals.test.ts +20 -0
  68. package/src/extension/host-signals.ts +13 -0
  69. package/src/extension/inspector-command.test.ts +1343 -0
  70. package/src/extension/inspector-command.ts +685 -0
  71. package/src/extension/prompt.test.ts +108 -0
  72. package/src/extension/prompt.ts +50 -0
  73. package/src/extension/request-alerts.test.ts +183 -0
  74. package/src/extension/request-alerts.ts +181 -0
  75. package/src/extension/retry-observer.test.ts +292 -0
  76. package/src/extension/retry-observer.ts +150 -0
  77. package/src/extension/revocation.test.ts +81 -0
  78. package/src/extension/revocation.ts +84 -0
  79. package/src/extension/settle-alerts.test.ts +579 -0
  80. package/src/extension/settle-alerts.ts +175 -0
  81. package/src/extension/shortcut.test.ts +62 -0
  82. package/src/extension/shortcut.ts +105 -0
  83. package/src/extension/tools.test.ts +1294 -0
  84. package/src/extension/tools.ts +553 -0
  85. package/src/extension/version.test.ts +115 -0
  86. package/src/extension/version.ts +97 -0
  87. package/src/goldens.test.ts +294 -0
  88. package/src/harness-policy.test.ts +76 -0
  89. package/src/layers.test.ts +309 -0
  90. package/src/layers.ts +405 -0
  91. package/src/package-manifest.test.ts +170 -0
  92. package/src/presentation/actions.test.ts +221 -0
  93. package/src/presentation/actions.ts +85 -0
  94. package/src/presentation/activity.test.ts +386 -0
  95. package/src/presentation/activity.ts +66 -0
  96. package/src/presentation/close.test.ts +359 -0
  97. package/src/presentation/inspector.test.ts +682 -0
  98. package/src/presentation/inspector.ts +442 -0
  99. package/src/presentation/overlay.test.ts +553 -0
  100. package/src/presentation/overlay.ts +229 -0
  101. package/src/presentation/repaint.test.ts +365 -0
  102. package/src/presentation/shortcut.ts +2 -0
  103. package/src/presentation/snapshot.test.ts +535 -0
  104. package/src/presentation/snapshot.ts +306 -0
  105. package/src/presentation/status.test.ts +43 -0
  106. package/src/presentation/status.ts +30 -0
  107. package/src/presentation/strip.test.ts +203 -0
  108. package/src/presentation/strip.ts +67 -0
  109. package/src/presentation/wording.test.ts +388 -0
  110. package/src/presentation/wording.ts +294 -0
  111. package/src/runtime/bridge.test.ts +131 -0
  112. package/src/runtime/bridge.ts +128 -0
  113. package/src/runtime/clock.test.ts +31 -0
  114. package/src/runtime/clock.ts +31 -0
  115. package/src/runtime/config.test.ts +63 -0
  116. package/src/runtime/config.ts +92 -0
  117. package/src/runtime/context.test.ts +19 -0
  118. package/src/runtime/context.ts +9 -0
  119. package/src/runtime/execution-env.test.ts +33 -0
  120. package/src/runtime/execution-env.ts +15 -0
  121. package/src/runtime/extensions.test.ts +86 -0
  122. package/src/runtime/extensions.ts +152 -0
  123. package/src/runtime/handle.ts +54 -0
  124. package/src/runtime/log.test.ts +140 -0
  125. package/src/runtime/log.ts +91 -0
  126. package/src/runtime/mcp.test.ts +1450 -0
  127. package/src/runtime/mcp.ts +1005 -0
  128. package/src/runtime/models.test.ts +145 -0
  129. package/src/runtime/models.ts +259 -0
  130. package/src/runtime/observe.test.ts +50 -0
  131. package/src/runtime/observe.ts +150 -0
  132. package/src/runtime/runtime-state.test.ts +25 -0
  133. package/src/runtime/runtime-state.ts +36 -0
  134. package/src/runtime/session-tag.ts +11 -0
  135. package/src/runtime/session.test.ts +352 -0
  136. package/src/runtime/session.ts +263 -0
  137. package/src/runtime/storage.ts +29 -0
  138. package/src/test-hygiene.test.ts +97 -0
@@ -0,0 +1,97 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath, pathToFileURL } from "node:url";
4
+ import { Option, Schema } from "effect";
5
+
6
+ export type VersionSignals = {
7
+ readonly durablePin: string | undefined;
8
+ readonly hostResolved: string | undefined;
9
+ };
10
+
11
+ export type VersionVerdict =
12
+ | { readonly kind: "clear"; readonly note?: "unverified" }
13
+ | { readonly kind: "refused"; readonly message: string };
14
+
15
+ /** The manifest fields the version check reads; a malformed field reads as absent. */
16
+ const ManifestSchema = Schema.Struct({
17
+ version: Schema.optional(Schema.String),
18
+ dependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
19
+ peerDependencies: Schema.optional(Schema.Record(Schema.String, Schema.String)),
20
+ });
21
+ type Manifest = typeof ManifestSchema.Type;
22
+
23
+ /** The nearest `package.json` above a resolved entry. Node blocks most `./package.json` subpaths. */
24
+ const manifestPathFor = (entry: string): string | undefined => {
25
+ let directory = dirname(entry);
26
+ for (;;) {
27
+ const candidate = join(directory, "package.json");
28
+ if (existsSync(candidate)) return candidate;
29
+ const parent = dirname(directory);
30
+ if (parent === directory) return undefined;
31
+ directory = parent;
32
+ }
33
+ };
34
+
35
+ /** Reads durable's pinned `@earendil-works/pi-ai` and the host-resolved version. */
36
+ export const readVersionSignals = (
37
+ resolve: (specifier: string, parent?: string) => string | undefined,
38
+ ): VersionSignals => {
39
+ const manifestOf = (entry: string): Manifest | undefined => {
40
+ const path = manifestPathFor(entry);
41
+ if (path === undefined) return undefined;
42
+ try {
43
+ return Option.getOrUndefined(
44
+ Schema.decodeUnknownOption(ManifestSchema)(JSON.parse(readFileSync(path, "utf8"))),
45
+ );
46
+ } catch {
47
+ return undefined;
48
+ }
49
+ };
50
+ const readManifest = (specifier: string, parent?: string): Manifest | undefined => {
51
+ const entry = resolve(specifier, parent);
52
+ return entry === undefined ? undefined : manifestOf(entry);
53
+ };
54
+ const piAiPin = (manifest: Manifest | undefined): string | undefined =>
55
+ manifest?.dependencies?.["@earendil-works/pi-ai"] ??
56
+ manifest?.peerDependencies?.["@earendil-works/pi-ai"];
57
+
58
+ const hostEntry = resolve("@earendil-works/pi-coding-agent");
59
+ const host = hostEntry === undefined ? undefined : manifestOf(hostEntry);
60
+ const durable = readManifest("@earendil-works/pi-durable");
61
+ const installedPiAi = readManifest("@earendil-works/pi-ai", hostEntry);
62
+ return {
63
+ durablePin: piAiPin(durable) ?? durable?.version,
64
+ hostResolved: installedPiAi?.version ?? piAiPin(host),
65
+ };
66
+ };
67
+
68
+ /** The identity constraint, checked before anything registers. */
69
+ export const versionVerdict = (signals: VersionSignals): VersionVerdict => {
70
+ if (signals.durablePin === undefined) {
71
+ return { kind: "clear", note: "unverified" };
72
+ }
73
+ if (signals.hostResolved === undefined) {
74
+ return { kind: "clear", note: "unverified" };
75
+ }
76
+ if (signals.durablePin === signals.hostResolved) return { kind: "clear" };
77
+ return {
78
+ kind: "refused",
79
+ message:
80
+ `@ftrdotdev/pi-delegates needs @earendil-works/pi-ai ${signals.durablePin}, the version pi-durable ` +
81
+ `pins, but the host resolved ${signals.hostResolved}. Run pi update, then reinstall ` +
82
+ `@ftrdotdev/pi-delegates so both packages share one copy.`,
83
+ };
84
+ };
85
+
86
+ /** Resolves a package entry through the installed package graph; ESM, so `import` conditions apply. */
87
+ export const resolveFromPackage = (specifier: string, parent?: string): string | undefined => {
88
+ try {
89
+ const resolved =
90
+ parent === undefined
91
+ ? import.meta.resolve(specifier)
92
+ : import.meta.resolve(specifier, pathToFileURL(parent).href);
93
+ return fileURLToPath(resolved);
94
+ } catch {
95
+ return undefined;
96
+ }
97
+ };
@@ -0,0 +1,294 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
3
+ import * as NodePath from "@effect/platform-node/NodePath";
4
+ import { MemoryStorage } from "@earendil-works/pi-durable";
5
+ import {
6
+ Context,
7
+ Deferred,
8
+ Effect,
9
+ Exit,
10
+ Fiber,
11
+ Layer,
12
+ PlatformError,
13
+ Scope,
14
+ Stream,
15
+ } from "effect";
16
+ import * as FileSystem from "effect/FileSystem";
17
+ import * as Path from "effect/Path";
18
+ import { fakeObservations } from "../test-support/fake-observations.ts";
19
+ import { inspectorClock } from "../test-support/inspector-clock.ts";
20
+ import { stubHostSource } from "../test-support/stub-model-source.ts";
21
+ import { makeStubPi } from "../test-support/stub-pi.ts";
22
+ import { createCatalogue, defineAgent } from "./domain/definitions.ts";
23
+ import { CODING_EXTENSION } from "./domain/names.ts";
24
+ import type { HostDefaults } from "./domain/orchestration/launch.ts";
25
+ import type { RunView } from "./domain/view.ts";
26
+ import { registerDelegateTools } from "./extension/tools.ts";
27
+ import { Inspector, liveAddress, type InspectorReadFailed } from "./presentation/inspector.ts";
28
+ import { nullLogSink } from "./runtime/log.ts";
29
+ import { HostModelAdapter } from "./runtime/models.ts";
30
+ import { type SessionRuntime } from "./runtime/session.ts";
31
+ import { openTestSession, type TestSession } from "../test-support/seams.ts";
32
+ import type { SessionHandle } from "./runtime/handle.ts";
33
+ import { handleFor } from "../test-support/session-handle.ts";
34
+ import { Ref } from "effect";
35
+
36
+ /**
37
+ * Four behaviour goldens, recorded once from the tree before the composition
38
+ * rework and diffed by every later slice. A plain run is verify-only: the files
39
+ * change only under an explicit `GOLDENS=record`.
40
+ */
41
+ const suite = it.layer(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer));
42
+
43
+ const host: HostDefaults = {
44
+ model: { provider: "stub", modelId: "stub-1" },
45
+ thinkingLevel: "low",
46
+ };
47
+
48
+ const deployer = defineAgent({
49
+ name: "deployer",
50
+ role: "Deploy agent",
51
+ prompt: { role: "You deploy things." },
52
+ tools: ["bash"],
53
+ extensions: [CODING_EXTENSION],
54
+ approval: { gates: [{ name: "deploy", tools: ["bash"], match: "deploy" }] },
55
+ });
56
+
57
+ const catalogue = (): ReturnType<typeof createCatalogue> => createCatalogue([deployer]);
58
+
59
+ const golden = <E>(
60
+ name: string,
61
+ produce: Effect.Effect<unknown, E, FileSystem.FileSystem | Path.Path>,
62
+ ): Effect.Effect<void, E | PlatformError.PlatformError, FileSystem.FileSystem | Path.Path> =>
63
+ Effect.gen(function* () {
64
+ const fs = yield* FileSystem.FileSystem;
65
+ const path = yield* Path.Path;
66
+ // Module-relative: a bare relative path would resolve against the vitest cwd.
67
+ const file = path.join(import.meta.dirname, "..", "test-support", "goldens", `${name}.json`);
68
+ const value = yield* produce;
69
+ const actual = `${JSON.stringify(value, null, 2)}\n`;
70
+ if (process.env.GOLDENS === "record") {
71
+ yield* fs.makeDirectory(path.dirname(file), { recursive: true });
72
+ yield* fs.writeFileString(file, actual);
73
+ return;
74
+ }
75
+ const recorded = yield* fs.readFileString(file);
76
+ assert.strictEqual(recorded, actual);
77
+ });
78
+
79
+ interface ToolResult {
80
+ readonly content: readonly { readonly type: string; readonly text: string }[];
81
+ readonly details?: unknown;
82
+ }
83
+
84
+ interface RegisteredTool {
85
+ readonly execute: (
86
+ id: string,
87
+ params: unknown,
88
+ signal: undefined,
89
+ onUpdate: undefined,
90
+ ctx: unknown,
91
+ ) => Promise<ToolResult>;
92
+ }
93
+
94
+ interface Opened {
95
+ readonly runtime: TestSession;
96
+ readonly tool: (name: string) => RegisteredTool;
97
+ readonly context: unknown;
98
+ }
99
+
100
+ /** One opened session with the launch and control tools registered against it. */
101
+ const withSession = <A, E, R>(
102
+ use: (opened: Opened) => Effect.Effect<A, E, R>,
103
+ ): Effect.Effect<A, E | PlatformError.PlatformError, R | FileSystem.FileSystem | Scope.Scope> =>
104
+ Effect.acquireUseRelease(
105
+ Effect.gen(function* () {
106
+ const fs = yield* FileSystem.FileSystem;
107
+ // Scoped: the directory is removed when the test's scope closes.
108
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "delegates-golden-" });
109
+ const runtime = yield* Effect.promise(() =>
110
+ openTestSession({
111
+ identity: {
112
+ sessionId: "s-1",
113
+ sessionDir: directory,
114
+ cwd: directory,
115
+ agentDir: directory,
116
+ },
117
+ models: new HostModelAdapter(
118
+ stubHostSource({
119
+ text: "deployed",
120
+ toolCall: { name: "bash", arguments: { command: "echo deploy" } },
121
+ }),
122
+ ),
123
+ storage: new MemoryStorage(),
124
+ catalogue: catalogue(),
125
+ }),
126
+ );
127
+ const stub = makeStubPi({ settings: { packages: [] } });
128
+ registerDelegateTools(stub.api, {
129
+ session: Ref.makeUnsafe<SessionHandle | undefined>(handleFor(runtime)),
130
+ catalogue: catalogue(),
131
+ host,
132
+ launchWaitMs: () => 10_000,
133
+ log: () => nullLogSink,
134
+ });
135
+ const definitions = stub.registrations.toolDefinitions;
136
+ return {
137
+ runtime,
138
+ context: stub.context,
139
+ tool: (name: string) => definitions.get(name) as unknown as RegisteredTool,
140
+ };
141
+ }),
142
+ use,
143
+ (opened) => Effect.promise(() => opened.runtime.close()),
144
+ );
145
+
146
+ /** One parked single run, so every later payload carries no terminal duration. */
147
+ const parkedLaunch = (opened: Opened): Effect.Effect<ToolResult> =>
148
+ Effect.promise(() =>
149
+ opened
150
+ .tool("delegate_launch")
151
+ .execute(
152
+ "",
153
+ { request: { kind: "single", agent: "deployer", task: "deploy it" } },
154
+ undefined,
155
+ undefined,
156
+ opened.context,
157
+ ),
158
+ );
159
+
160
+ const runIdOf = (result: ToolResult): string =>
161
+ (result.details as { readonly run: RunView }).run.runId;
162
+
163
+ /** One instance from the real layer, built in a scope this test owns and closes. */
164
+ const withInspector = <A>(
165
+ runtime: SessionRuntime,
166
+ observe: ReturnType<typeof fakeObservations>,
167
+ use: (inspector: Inspector["Service"]) => Effect.Effect<A>,
168
+ ): Effect.Effect<A, InspectorReadFailed> =>
169
+ Effect.acquireUseRelease(
170
+ Effect.gen(function* () {
171
+ const scope = yield* Scope.make("sequential");
172
+ const built = yield* Effect.provideService(
173
+ Layer.build(
174
+ Inspector.layer({
175
+ runtime,
176
+ observe,
177
+ view: async () => ({
178
+ runs: [
179
+ {
180
+ runId: "run:golden",
181
+ definition: "deployer",
182
+ mode: "single",
183
+ lane: "default",
184
+ conversationId: 10,
185
+ taskId: 8,
186
+ status: "running",
187
+ answer: null,
188
+ durationMs: null,
189
+ children: [],
190
+ missing: [],
191
+ gates: [],
192
+ requests: [],
193
+ diagnostic: null,
194
+ execution: "wait",
195
+ maxTurns: null,
196
+ failure: null,
197
+ },
198
+ ],
199
+ lanes: [],
200
+ gates: [],
201
+ reviews: [],
202
+ requests: [],
203
+ }),
204
+ now: () => 4_000,
205
+ timers: inspectorClock(),
206
+ }),
207
+ ),
208
+ Scope.Scope,
209
+ scope,
210
+ ).pipe(Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))));
211
+ return { inspector: Context.get(built, Inspector), scope };
212
+ }),
213
+ (built) => use(built.inspector),
214
+ (built) => Scope.close(built.scope, Exit.void),
215
+ );
216
+
217
+ suite((it) => {
218
+ it.effect("the launch golden matches when a gated run parks", () =>
219
+ withSession((opened) =>
220
+ golden(
221
+ "delegate-launch",
222
+ Effect.map(parkedLaunch(opened), (result) => result),
223
+ ),
224
+ ),
225
+ );
226
+
227
+ it.effect("the control golden matches when a parked run is steered", () =>
228
+ withSession((opened) =>
229
+ golden(
230
+ "delegate-control",
231
+ Effect.gen(function* () {
232
+ const launched = yield* parkedLaunch(opened);
233
+ return yield* Effect.promise(() =>
234
+ opened
235
+ .tool("delegate_control")
236
+ .execute(
237
+ "",
238
+ { action: "steer", run: runIdOf(launched), message: "keep going" },
239
+ undefined,
240
+ undefined,
241
+ opened.context,
242
+ ),
243
+ );
244
+ }),
245
+ ),
246
+ ),
247
+ );
248
+
249
+ it.effect("the invalid-control golden matches when the action misses its field", () =>
250
+ withSession((opened) =>
251
+ golden(
252
+ "invalid-control",
253
+ Effect.orDie(
254
+ Effect.promise(() =>
255
+ opened
256
+ .tool("delegate_control")
257
+ .execute("", { action: "answer" }, undefined, undefined, opened.context),
258
+ ),
259
+ ),
260
+ ),
261
+ ),
262
+ );
263
+
264
+ it.effect("the inspector golden matches when one publication is projected", () =>
265
+ withSession((opened) =>
266
+ golden(
267
+ "inspector-publication",
268
+ Effect.gen(function* () {
269
+ const observe = fakeObservations();
270
+ return yield* withInspector(opened.runtime, observe, (inspector) =>
271
+ Effect.gen(function* () {
272
+ const subscribed = Deferred.makeUnsafe<void>();
273
+ const changes = yield* Stream.map(inspector.changes, (snapshot) => {
274
+ Deferred.doneUnsafe(subscribed, Exit.void);
275
+ return snapshot;
276
+ }).pipe(Stream.take(2), Stream.runCollect, Effect.forkChild);
277
+ yield* Deferred.await(subscribed);
278
+ yield* Effect.sync(() => {
279
+ observe.pushActivity(liveAddress(10), {
280
+ tool: "bash",
281
+ slot: "running",
282
+ turns: 1,
283
+ at: 1_000,
284
+ });
285
+ });
286
+ const collected = yield* Fiber.join(changes);
287
+ return [...collected].at(-1);
288
+ }),
289
+ );
290
+ }),
291
+ ),
292
+ ),
293
+ );
294
+ });
@@ -0,0 +1,76 @@
1
+ import { expect, it, vi } from "@effect/vitest";
2
+ import { createVitest } from "vitest/node";
3
+ import { dirEntries, join, readText, relativePath } from "../test-support/platform.ts";
4
+
5
+ const PACKAGE_ROOT = join(import.meta.dirname, "..");
6
+ const PROBE = "PI_HARNESS_PROBE";
7
+ const REAL_LOG = console.log;
8
+
9
+ /** Every `*.test.ts` under `dir`, as paths relative to `PACKAGE_ROOT`. */
10
+ const walkTests = async (dir: string, found: string[] = []): Promise<string[]> => {
11
+ for (const entry of await dirEntries(join(PACKAGE_ROOT, dir))) {
12
+ const path = join(dir, entry.name);
13
+ if (entry.directory) await walkTests(path, found);
14
+ else if (entry.name.endsWith(".test.ts")) found.push(path);
15
+ }
16
+ return found;
17
+ };
18
+
19
+ /** The project's resolved config, read from the config this package ships. */
20
+ const project = async () => {
21
+ const vitest = await createVitest({ root: PACKAGE_ROOT, watch: false });
22
+ try {
23
+ return { config: vitest.projects.at(0)?.config, specs: await vitest.globTestSpecifications() };
24
+ } finally {
25
+ await vitest.close();
26
+ }
27
+ };
28
+
29
+ it("this package resolves the shared policy without stating it", async () => {
30
+ const { config } = await project();
31
+
32
+ expect(config?.name).toBe("delegates");
33
+ expect(config?.restoreMocks).toBe(true);
34
+ expect(config?.unstubEnvs).toBe(true);
35
+ expect(config?.unstubGlobals).toBe(true);
36
+ expect(config?.isolate).toBe(false);
37
+ });
38
+
39
+ it("the package config states no shared key", async () => {
40
+ const source = await readText(join(import.meta.dirname, "../vitest.config.ts"));
41
+
42
+ expect(source).toContain("baseTestConfig");
43
+ for (const key of ["restoreMocks", "unstubEnvs", "unstubGlobals", "fakeTimers", "isolate"]) {
44
+ expect(source).not.toContain(key);
45
+ }
46
+ });
47
+
48
+ it("the project collects the source tree, the scripts and the test support", async () => {
49
+ const { specs } = await project();
50
+ const collected = specs.map((spec) => relativePath(PACKAGE_ROOT, spec.moduleId)).sort();
51
+
52
+ expect(collected).toEqual(
53
+ [
54
+ ...(await walkTests("src")),
55
+ ...(await walkTests("scripts")),
56
+ ...(await walkTests("test-support")),
57
+ ].sort(),
58
+ );
59
+ });
60
+
61
+ it("a stubbed environment variable is set for the test that stubs it", () => {
62
+ vi.stubEnv(PROBE, "1");
63
+ });
64
+
65
+ it("a stubbed environment variable is absent in the next test", () => {
66
+ expect(process.env[PROBE]).toBeUndefined();
67
+ });
68
+
69
+ it("a spy made in one test replaces the function for that test", () => {
70
+ vi.spyOn(console, "log").mockImplementation(() => {});
71
+ });
72
+
73
+ it("a spy made in one test is not a mock in the next", () => {
74
+ expect(vi.isMockFunction(console.log)).toBe(false);
75
+ expect(console.log).toBe(REAL_LOG);
76
+ });