@stigmer/runner 3.14.0-dev.20260910084630 → 3.14.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 (56) hide show
  1. package/dist/.build-fingerprint +1 -1
  2. package/dist/__test-utils__/hermetic-activity.d.ts +245 -0
  3. package/dist/__test-utils__/hermetic-activity.js +369 -0
  4. package/dist/__test-utils__/hermetic-activity.js.map +1 -0
  5. package/dist/__test-utils__/mock-client.d.ts +13 -0
  6. package/dist/__test-utils__/mock-client.js +45 -0
  7. package/dist/__test-utils__/mock-client.js.map +1 -0
  8. package/dist/activities/execute-cursor/__test-utils__/hermetic-cursor.d.ts +172 -0
  9. package/dist/activities/execute-cursor/__test-utils__/hermetic-cursor.js +331 -0
  10. package/dist/activities/execute-cursor/__test-utils__/hermetic-cursor.js.map +1 -0
  11. package/dist/activities/execute-cursor/__test-utils__/scripted-agent.d.ts +167 -0
  12. package/dist/activities/execute-cursor/__test-utils__/scripted-agent.js +239 -0
  13. package/dist/activities/execute-cursor/__test-utils__/scripted-agent.js.map +1 -0
  14. package/dist/activities/execute-cursor/__test-utils__/scripted-sdk.d.ts +97 -0
  15. package/dist/activities/execute-cursor/__test-utils__/scripted-sdk.js +132 -0
  16. package/dist/activities/execute-cursor/__test-utils__/scripted-sdk.js.map +1 -0
  17. package/dist/harness/capabilities.d.ts +71 -0
  18. package/dist/harness/capabilities.js +36 -0
  19. package/dist/harness/capabilities.js.map +1 -0
  20. package/dist/harness/registry.d.ts +67 -0
  21. package/dist/harness/registry.js +112 -0
  22. package/dist/harness/registry.js.map +1 -0
  23. package/dist/harness/types.d.ts +268 -0
  24. package/dist/harness/types.js +55 -0
  25. package/dist/harness/types.js.map +1 -0
  26. package/package.json +4 -4
  27. package/src/__test-utils__/__tests__/harness-contract-self-check.test.ts +229 -0
  28. package/src/__test-utils__/config-fixture.ts +63 -0
  29. package/src/__test-utils__/harness-contract/contract.ts +536 -0
  30. package/src/__test-utils__/harness-contract/recording-sink.ts +96 -0
  31. package/src/__test-utils__/harness-contract/scripted-adapter.ts +289 -0
  32. package/src/__test-utils__/harness-contract/types.ts +100 -0
  33. package/src/__test-utils__/hermetic-activity.ts +477 -0
  34. package/src/__test-utils__/proto-helpers.ts +25 -0
  35. package/src/__tests__/harness-contract.test.ts +25 -0
  36. package/src/activities/execute-cursor/__test-utils__/hermetic-cursor.ts +422 -0
  37. package/src/activities/execute-cursor/__test-utils__/scripted-agent.ts +342 -0
  38. package/src/activities/execute-cursor/__test-utils__/scripted-sdk.ts +166 -0
  39. package/src/activities/execute-cursor/__tests__/hermetic/deny-and-retry.test.ts +228 -0
  40. package/src/activities/execute-cursor/__tests__/hermetic/file-review-capture.test.ts +180 -0
  41. package/src/activities/execute-cursor/__tests__/hermetic/goldens/deny-and-retry.turn1.status.json +55 -0
  42. package/src/activities/execute-cursor/__tests__/hermetic/goldens/deny-and-retry.turn2.status.json +77 -0
  43. package/src/activities/execute-cursor/__tests__/hermetic/goldens/file-review-capture.status.json +126 -0
  44. package/src/activities/execute-cursor/__tests__/hermetic/goldens/pause.status.json +45 -0
  45. package/src/activities/execute-cursor/__tests__/hermetic/goldens/plain-turn.status.json +48 -0
  46. package/src/activities/execute-cursor/__tests__/hermetic/goldens/recovery-fresh-agent.status.json +53 -0
  47. package/src/activities/execute-cursor/__tests__/hermetic/goldens/tool-call.status.json +68 -0
  48. package/src/activities/execute-cursor/__tests__/hermetic/goldens/worker-shutdown.status.json +47 -0
  49. package/src/activities/execute-cursor/__tests__/hermetic/pause-vs-shutdown.test.ts +201 -0
  50. package/src/activities/execute-cursor/__tests__/hermetic/plain-turn.test.ts +171 -0
  51. package/src/activities/execute-cursor/__tests__/hermetic/recovery-fresh-agent.test.ts +156 -0
  52. package/src/activities/execute-cursor/__tests__/hermetic/tool-call.test.ts +137 -0
  53. package/src/harness/__tests__/registry.test.ts +167 -0
  54. package/src/harness/capabilities.ts +75 -0
  55. package/src/harness/registry.ts +123 -0
  56. package/src/harness/types.ts +278 -0
@@ -0,0 +1,477 @@
1
+ /**
2
+ * Hermetic activity driver — run a REAL runner activity end to end with no
3
+ * network, no credentials, and no live Temporal worker, and read back every
4
+ * status it persisted.
5
+ *
6
+ * Why this exists: the runner's activities (`ExecuteCursor`, `ExecuteDeepAgent`)
7
+ * are the wire contract the control plane's workflow keys on — the phases they
8
+ * persist, the copy they write, whether they RETURN a slim status or THROW
9
+ * `CancelledFailure`. Refactoring them safely needs goldens recorded through the
10
+ * activity whole, not through its modules one at a time. The native harness
11
+ * tests already run their activity hermetically by mocking three modules at the
12
+ * boundary (`execute-deep-agent/__tests__/{index,hitl-*,sequential-gate-resume}.test.ts`);
13
+ * this module is that convention made reusable, harness-agnostic, and driven by
14
+ * the framework's own activity environment instead of a hand-written stand-in.
15
+ *
16
+ * What is generic here and what is not: everything an activity touches that is
17
+ * NOT the vendor SDK — the Temporal `Context`, the control-plane client, the
18
+ * runner-owned `~/.stigmer` tree, artifact storage, the model registry, the
19
+ * clock, the worker-shutdown signal — is set up here. The vendor SDK double
20
+ * belongs to the harness (`activities/execute-cursor/__test-utils__/scripted-*.ts`),
21
+ * the same split as `approval-contract/` (runner-wide kit) + each harness's
22
+ * `gateway-substrate.ts`.
23
+ *
24
+ * Three substitutions, and why each is shaped the way it is:
25
+ *
26
+ * 1. `Context.current()` — `MockActivityEnvironment` from `@temporalio/testing`,
27
+ * ONE PER INVOCATION. It gives the activity a real `Context` (real
28
+ * `cancellationSignal`, real `heartbeat()` surfaced as events, real
29
+ * `CancelledFailure` on throw). The native tests' stand-in mints a fresh
30
+ * `AbortController` on every `Context.current()` call and so cannot drive a
31
+ * pause; production hands each attempt one `Context`, and so does this. The
32
+ * environment's documented caveat — once cancelled it stays cancelled — is
33
+ * why it is per invocation and never shared.
34
+ *
35
+ * 2. `StigmerClient` — the test file mocks the module (`vi.mock` is hoisted and
36
+ * must live in the test file; see {@link hermeticStigmerClientModule}) and
37
+ * the constructor hands back whatever client {@link bindHermeticClient} bound
38
+ * for the current run. The client is `mockStigmerClient` over an
39
+ * {@link ExecutionRecord}: `updateStatus` writes back into the record the way
40
+ * the server would, so a REINVOCATION (`threadId` set) reads the transcript
41
+ * the first invocation persisted — the resume path runs on real data, not on
42
+ * a hand-built status.
43
+ *
44
+ * 3. The environment — a temp `HOME` (the runner-owned `~/.stigmer` tree,
45
+ * `platform-dir.ts` reads `process.env.HOME`), a temp workspace root, local
46
+ * artifact storage in a temp dir, and the HITL fingerprint secret pinned by
47
+ * env var (`fingerprint-secret.ts` falls back to `randomBytes` — the ONE
48
+ * source of randomness on the activity path — and memoizes on first call, so
49
+ * the pin must precede the first invocation in the process).
50
+ *
51
+ * Determinism: the clock is faked for `Date` ONLY (`vi.useFakeTimers({ toFake:
52
+ * ["Date"] })`) and TICKS — the harness double advances it a fixed quantum per
53
+ * script step through {@link ScriptedClock}. Frozen time would make
54
+ * `delta-enricher.ts`'s persist debounce (`Date.now() - lastPersistTime`) never
55
+ * elapse and silently skip the mid-stream persist path production always runs;
56
+ * a ticking clock runs the same path and lands on the same instants every run.
57
+ * Timers stay real so the periodic heartbeat and the stall watchdog behave.
58
+ *
59
+ * Not in scope: this module never edits a production module and never
60
+ * normalizes output. If a golden is not byte-stable, the volatile source is
61
+ * controlled at its origin or the surprise is escalated — never redacted here.
62
+ */
63
+
64
+ import { mkdtempSync, rmSync } from "node:fs";
65
+ import { tmpdir } from "node:os";
66
+ import { join } from "node:path";
67
+ import { vi } from "vitest";
68
+ import { MockActivityEnvironment } from "@temporalio/testing";
69
+ import { CancelledFailure } from "@temporalio/activity";
70
+ import { Code, ConnectError } from "@connectrpc/connect";
71
+ import { clone, create } from "@bufbuild/protobuf";
72
+ import {
73
+ AgentExecutionSchema,
74
+ AgentExecutionStatusSchema,
75
+ type AgentExecution,
76
+ type AgentExecutionStatus,
77
+ } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/api_pb";
78
+ import {
79
+ ApprovalAction,
80
+ ExecutionPhase,
81
+ ToolCallStatus,
82
+ } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/enum_pb";
83
+ import { UpdateStatusResponseSchema } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/io_pb";
84
+ import type { ToolCall } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/message_pb";
85
+ import type { Session } from "@stigmer/protos/ai/stigmer/agentic/session/v1/api_pb";
86
+ import type { Agent } from "@stigmer/protos/ai/stigmer/agentic/agent/v1/api_pb";
87
+ import type { AgentInstance } from "@stigmer/protos/ai/stigmer/agentic/agentinstance/v1/api_pb";
88
+ import type { StigmerClient } from "../client/stigmer-client.js";
89
+ import {
90
+ registerWorkerShutdownSignal,
91
+ signalWorkerShutdown,
92
+ unregisterWorkerShutdownSignal,
93
+ } from "../shared/worker-shutdown.js";
94
+ import { mockStigmerClient } from "./mock-client.js";
95
+
96
+ // ---------------------------------------------------------------------------
97
+ // The execution record: what the control plane would hold for one execution
98
+ // ---------------------------------------------------------------------------
99
+
100
+ /**
101
+ * The four resources the activity's blueprint chain reads
102
+ * (`execution.spec.sessionId -> session.spec.agentInstanceId ->
103
+ * agentInstance.spec.agentId -> agent`) plus the status the server would hold.
104
+ */
105
+ export interface ExecutionRecordInput {
106
+ readonly execution: AgentExecution;
107
+ readonly session: Session;
108
+ readonly agentInstance: AgentInstance;
109
+ readonly agent: Agent;
110
+ }
111
+
112
+ /**
113
+ * An in-memory stand-in for the server's execution row, with the TWO merge
114
+ * rules the activity depends on and no others:
115
+ *
116
+ * - A status whose phase is UNSPECIFIED is a setup-progress report
117
+ * (`reportSetupProgress`): the server keeps `setup_progress` and leaves the
118
+ * phase and transcript alone. Modelled as: record the label, change nothing else.
119
+ * - Any other status replaces the held status wholesale (the runner is the
120
+ * writer of the transcript; the server's own field-ownership merge — approval
121
+ * fields it owns — is exercised by the test SETTING `approvalAction` on the
122
+ * record between invocations, exactly as `SubmitApproval` would).
123
+ *
124
+ * Every persisted status is also kept in order (`persisted`) so a test can
125
+ * assert the phase sequence the activity wrote, independent of the final state.
126
+ */
127
+ export class ExecutionRecord {
128
+ readonly execution: AgentExecution;
129
+ readonly session: Session;
130
+ readonly agentInstance: AgentInstance;
131
+ readonly agent: Agent;
132
+ /** Every `updateStatus` payload, in order, snapshotted at write time. */
133
+ readonly persisted: AgentExecutionStatus[] = [];
134
+ /** Setup-progress labels reported before the stream started, in order. */
135
+ readonly setupProgress: string[] = [];
136
+ /** Every `updateSession` payload, in order (the `harness_state_id` write-back). */
137
+ readonly sessionUpdates: Session[] = [];
138
+
139
+ constructor(input: ExecutionRecordInput) {
140
+ this.execution = clone(AgentExecutionSchema, input.execution);
141
+ this.session = input.session;
142
+ this.agentInstance = input.agentInstance;
143
+ this.agent = input.agent;
144
+ }
145
+
146
+ get executionId(): string {
147
+ return this.execution.metadata?.id ?? "";
148
+ }
149
+
150
+ /** The status the server would currently hold (what `getExecution` returns). */
151
+ get status(): AgentExecutionStatus | undefined {
152
+ return this.execution.status;
153
+ }
154
+
155
+ /** The last FULL status written (phase set), or undefined if none yet. */
156
+ get lastFullStatus(): AgentExecutionStatus | undefined {
157
+ for (let i = this.persisted.length - 1; i >= 0; i--) {
158
+ const s = this.persisted[i];
159
+ if (s.phase !== ExecutionPhase.EXECUTION_PHASE_UNSPECIFIED) return s;
160
+ }
161
+ return undefined;
162
+ }
163
+
164
+ /**
165
+ * The ORDERED, DISTINCT phases the activity persisted — the deterministic
166
+ * shape of the persist cadence. The COUNT of persists depends on the
167
+ * debounce timer and is deliberately not exposed as an assertion surface.
168
+ */
169
+ get persistedPhases(): ExecutionPhase[] {
170
+ const out: ExecutionPhase[] = [];
171
+ for (const s of this.persisted) {
172
+ if (s.phase === ExecutionPhase.EXECUTION_PHASE_UNSPECIFIED) continue;
173
+ if (out[out.length - 1] !== s.phase) out.push(s.phase);
174
+ }
175
+ return out;
176
+ }
177
+
178
+ /** Every tool call on the held transcript (top-level messages), in order. */
179
+ toolCalls(): ToolCall[] {
180
+ return this.execution.status?.messages.flatMap((m) => m.toolCalls) ?? [];
181
+ }
182
+
183
+ /** The tool calls currently paused for a decision. */
184
+ waitingToolCalls(): ToolCall[] {
185
+ return this.toolCalls().filter((tc) => tc.status === ToolCallStatus.TOOL_CALL_WAITING_APPROVAL);
186
+ }
187
+
188
+ /**
189
+ * What the server's `SubmitApproval` does to the row: record the decision on
190
+ * the tool call the runner wrote. The runner owns `status`; the server owns
191
+ * `approval_action` (field ownership, 005 mandate 2) — so this is the ONE
192
+ * place a test writes it, and the status stays WAITING_APPROVAL until the
193
+ * resumed turn runs the tool, exactly as in production.
194
+ */
195
+ decideWaitingToolCalls(action: ApprovalAction, decidedAt: string): number {
196
+ const waiting = this.waitingToolCalls();
197
+ for (const tc of waiting) {
198
+ tc.approvalAction = action;
199
+ tc.approvalDecidedAt = decidedAt;
200
+ }
201
+ return waiting.length;
202
+ }
203
+
204
+ applyStatusUpdate(status: AgentExecutionStatus): void {
205
+ const snapshot = clone(AgentExecutionStatusSchema, status);
206
+ this.persisted.push(snapshot);
207
+ if (snapshot.phase === ExecutionPhase.EXECUTION_PHASE_UNSPECIFIED) {
208
+ if (snapshot.setupProgress?.currentPhase) {
209
+ this.setupProgress.push(snapshot.setupProgress.currentPhase);
210
+ }
211
+ return;
212
+ }
213
+ this.execution.status = clone(AgentExecutionStatusSchema, snapshot);
214
+ }
215
+
216
+ /**
217
+ * The control-plane client the activity sees: every read answers from this
218
+ * record; every write lands in it. Reads the activity makes for optional
219
+ * facets (execution context, channels, skills) answer the everyday shape —
220
+ * NOT_FOUND for the execution context (an execution with no env vars), no
221
+ * channels, no scoped token (the OSS/local posture) — so a scenario opts INTO
222
+ * a facet by overriding.
223
+ */
224
+ client(overrides: Partial<StigmerClient> = {}): StigmerClient {
225
+ return mockStigmerClient({
226
+ getExecution: vi.fn(async () => clone(AgentExecutionSchema, this.execution)),
227
+ getSession: vi.fn(async () => this.session),
228
+ getAgentInstance: vi.fn(async () => this.agentInstance),
229
+ getAgent: vi.fn(async () => this.agent),
230
+ updateStatus: vi.fn(async (_id: string, status: AgentExecutionStatus) => {
231
+ this.applyStatusUpdate(status);
232
+ // The activity reads only `.signal`; UNSPECIFIED means "keep going".
233
+ return create(UpdateStatusResponseSchema, {});
234
+ }),
235
+ updateSession: vi.fn(async (session: Session) => {
236
+ this.sessionUpdates.push(session);
237
+ return session;
238
+ }),
239
+ getExecutionContextByExecutionId: vi.fn(async () => {
240
+ throw new ConnectError("execution context not found", Code.NotFound);
241
+ }),
242
+ ...overrides,
243
+ } as Partial<StigmerClient>);
244
+ }
245
+ }
246
+
247
+ // ---------------------------------------------------------------------------
248
+ // The module-boundary seam for StigmerClient
249
+ // ---------------------------------------------------------------------------
250
+
251
+ let boundClient: StigmerClient | undefined;
252
+
253
+ /**
254
+ * Bind the client the mocked `StigmerClient` constructor hands out for the
255
+ * current run. Called by the harness driver immediately before invoking the
256
+ * activity factory (`createCursorActivities(config)` constructs its client
257
+ * inside the factory, so the bind must precede the factory call).
258
+ */
259
+ export function bindHermeticClient(client: StigmerClient): void {
260
+ boundClient = client;
261
+ }
262
+
263
+ /**
264
+ * The factory a test passes to `vi.mock(".../client/stigmer-client.js", ...)`.
265
+ * `vi.mock` is hoisted and must appear in the test file itself; the factory can
266
+ * `await import()` this module. Usage:
267
+ *
268
+ * ```ts
269
+ * vi.mock("../../../../client/stigmer-client.js", async () =>
270
+ * (await import("../../../../__test-utils__/hermetic-activity.js")).hermeticStigmerClientModule(),
271
+ * );
272
+ * ```
273
+ */
274
+ export function hermeticStigmerClientModule(): { StigmerClient: new () => StigmerClient } {
275
+ return {
276
+ StigmerClient: class {
277
+ constructor() {
278
+ if (!boundClient) {
279
+ throw new Error(
280
+ "hermetic-activity: no StigmerClient bound — call bindHermeticClient(record.client()) " +
281
+ "before constructing the activities",
282
+ );
283
+ }
284
+ return boundClient;
285
+ }
286
+ } as unknown as new () => StigmerClient,
287
+ };
288
+ }
289
+
290
+ // ---------------------------------------------------------------------------
291
+ // The environment: temp HOME, temp workspace root, local artifact storage
292
+ // ---------------------------------------------------------------------------
293
+
294
+ /**
295
+ * The env-var pins a hermetic run needs, and the reason for each:
296
+ * - `HOME`: `platform-dir.ts` roots the runner-owned `~/.stigmer` tree (HITL
297
+ * gate dir, session dirs, denial ledger) on it.
298
+ * - `ARTIFACT_STORAGE_TYPE=local` + `LOCAL_ARTIFACT_PATH`: a writable local
299
+ * store so capture mode and tool-output offload run the production path
300
+ * (an absent store flips capture off — a different code path).
301
+ * - `STIGMER_RUNNER_HITL_SECRET`: the one randomness source on the activity
302
+ * path, pinned so grant tokens and fingerprints are byte-stable.
303
+ * - `CURSOR_EVENT_RECORD_DIR` cleared: never write recordings from a test.
304
+ */
305
+ const PINNED_ENV = {
306
+ ARTIFACT_STORAGE_TYPE: "local",
307
+ STIGMER_RUNNER_HITL_SECRET: "hermetic-fixture-secret-do-not-use-in-production",
308
+ } as const;
309
+
310
+ const CLEARED_ENV = ["CURSOR_EVENT_RECORD_DIR", "STIGMER_PROXY_ENDPOINT", "STIGMER_CLOUD_API_URL"] as const;
311
+
312
+ export interface HermeticEnvironment {
313
+ /** The temp `HOME` (the runner's `~/.stigmer` lands under it). */
314
+ readonly home: string;
315
+ /** The temp workspace root (`config.workspaceRootDir`). */
316
+ readonly workspaceRootDir: string;
317
+ /** The temp local artifact store (`LOCAL_ARTIFACT_PATH`). */
318
+ readonly artifactPath: string;
319
+ /** Restore every env var and remove the temp tree. Idempotent. */
320
+ dispose(): void;
321
+ }
322
+
323
+ /**
324
+ * Create the temp tree and pin the env vars. Call once per test FILE (in
325
+ * `beforeAll`) — the fingerprint secret is memoized per process on first use,
326
+ * and vitest isolates files in forks, so per-file is the natural unit.
327
+ */
328
+ export function createHermeticEnvironment(): HermeticEnvironment {
329
+ const root = mkdtempSync(join(tmpdir(), "stigmer-hermetic-"));
330
+ const home = join(root, "home");
331
+ const workspaceRootDir = join(root, "workspaces");
332
+ const artifactPath = join(root, "artifacts");
333
+
334
+ const saved = new Map<string, string | undefined>();
335
+ const set = (key: string, value: string | undefined): void => {
336
+ if (!saved.has(key)) saved.set(key, process.env[key]);
337
+ if (value === undefined) delete process.env[key];
338
+ else process.env[key] = value;
339
+ };
340
+ set("HOME", home);
341
+ set("LOCAL_ARTIFACT_PATH", artifactPath);
342
+ for (const [k, v] of Object.entries(PINNED_ENV)) set(k, v);
343
+ for (const k of CLEARED_ENV) set(k, undefined);
344
+
345
+ let disposed = false;
346
+ return {
347
+ home,
348
+ workspaceRootDir,
349
+ artifactPath,
350
+ dispose() {
351
+ if (disposed) return;
352
+ disposed = true;
353
+ for (const [k, v] of saved) {
354
+ if (v === undefined) delete process.env[k];
355
+ else process.env[k] = v;
356
+ }
357
+ rmSync(root, { recursive: true, force: true });
358
+ },
359
+ };
360
+ }
361
+
362
+ // ---------------------------------------------------------------------------
363
+ // The clock
364
+ // ---------------------------------------------------------------------------
365
+
366
+ /**
367
+ * A deterministic, TICKING `Date`. Only `Date` is faked; timers stay real (the
368
+ * periodic heartbeat, the stall watchdog, `withTimeout` all need them). The
369
+ * harness double calls {@link ScriptedClock.tick} once per script step, so
370
+ * every `Date.now()`-based decision on the activity path (status timestamps,
371
+ * the enricher's persist debounce, cache TTLs) sees the same instants run after
372
+ * run and runs the same branches production runs.
373
+ */
374
+ export class ScriptedClock {
375
+ /** A fixed epoch: 2026-01-01T00:00:00.000Z. Chosen for readability in goldens. */
376
+ static readonly EPOCH_MS = Date.UTC(2026, 0, 1, 0, 0, 0, 0);
377
+ /** One second per step — well under any stall or cache horizon. */
378
+ static readonly STEP_MS = 1_000;
379
+
380
+ private nowMs = ScriptedClock.EPOCH_MS;
381
+
382
+ install(): void {
383
+ vi.useFakeTimers({ toFake: ["Date"], now: this.nowMs });
384
+ }
385
+
386
+ tick(ms: number = ScriptedClock.STEP_MS): void {
387
+ this.nowMs += ms;
388
+ vi.setSystemTime(this.nowMs);
389
+ }
390
+
391
+ /** Back to the epoch — for a second scenario in the same file. */
392
+ reset(): void {
393
+ this.nowMs = ScriptedClock.EPOCH_MS;
394
+ vi.setSystemTime(this.nowMs);
395
+ }
396
+
397
+ uninstall(): void {
398
+ vi.useRealTimers();
399
+ }
400
+ }
401
+
402
+ // ---------------------------------------------------------------------------
403
+ // Running one activity invocation
404
+ // ---------------------------------------------------------------------------
405
+
406
+ /** How an activity invocation ended: the return value or the error it threw. */
407
+ export type ActivityOutcome =
408
+ | { readonly kind: "returned"; readonly value: unknown }
409
+ | { readonly kind: "threw"; readonly error: unknown };
410
+
411
+ export interface ActivityInvocation {
412
+ readonly outcome: ActivityOutcome;
413
+ /** Heartbeat details the activity reported, in order. */
414
+ readonly heartbeats: unknown[];
415
+ /** The `taskQueue` the invocation ran on (the shutdown signal is keyed by it). */
416
+ readonly taskQueue: string;
417
+ }
418
+
419
+ /**
420
+ * Handles a scenario uses to interrupt the invocation FROM A SCRIPT STEP —
421
+ * never from a timer. `cancel()` aborts the activity's `cancellationSignal`
422
+ * (a user pause, as the workflow delivers it). `signalWorkerShutdown()` aborts
423
+ * the queue's shutdown signal first, which the activity reads to tell a worker
424
+ * drain from a user pause (`classifyTurnInterruption`).
425
+ */
426
+ export interface InvocationControls {
427
+ cancel(): void;
428
+ signalWorkerShutdown(): void;
429
+ }
430
+
431
+ export interface RunActivityOptions {
432
+ readonly taskQueue?: string;
433
+ /**
434
+ * Receives the invocation's controls before the activity starts, so a
435
+ * scenario can hand them to the harness double's `effect` steps.
436
+ */
437
+ readonly onControls?: (controls: InvocationControls) => void;
438
+ }
439
+
440
+ /**
441
+ * Run one activity function under a fresh `MockActivityEnvironment` and
442
+ * capture how it ended. `CancelledFailure` is caught like any other throw and
443
+ * reported as `{ kind: "threw" }` — the throw-vs-return table is the thing
444
+ * under test, so the driver never interprets it.
445
+ */
446
+ export async function runActivityHermetically<A extends unknown[]>(
447
+ activity: (...args: A) => Promise<unknown>,
448
+ args: A,
449
+ options: RunActivityOptions = {},
450
+ ): Promise<ActivityInvocation> {
451
+ const taskQueue = options.taskQueue ?? "hermetic-test-queue";
452
+ const env = new MockActivityEnvironment({ taskQueue });
453
+ const heartbeats: unknown[] = [];
454
+ env.on("heartbeat", (details: unknown) => heartbeats.push(details));
455
+
456
+ // The worker-shutdown signal is process-global per queue; register for this
457
+ // invocation and always unregister so no state leaks into the next one.
458
+ registerWorkerShutdownSignal(taskQueue);
459
+ options.onControls?.({
460
+ cancel: () => env.cancel(),
461
+ signalWorkerShutdown: () => signalWorkerShutdown(taskQueue),
462
+ });
463
+
464
+ try {
465
+ const value = await env.run(activity, ...args);
466
+ return { outcome: { kind: "returned", value }, heartbeats, taskQueue };
467
+ } catch (error) {
468
+ return { outcome: { kind: "threw", error }, heartbeats, taskQueue };
469
+ } finally {
470
+ unregisterWorkerShutdownSignal(taskQueue);
471
+ }
472
+ }
473
+
474
+ /** True when the outcome is a thrown Temporal `CancelledFailure`. */
475
+ export function threwCancelledFailure(outcome: ActivityOutcome): outcome is { kind: "threw"; error: CancelledFailure } {
476
+ return outcome.kind === "threw" && outcome.error instanceof CancelledFailure;
477
+ }
@@ -39,3 +39,28 @@ export function toolCall(
39
39
  ): ToolCall {
40
40
  return create(ToolCallSchema, { id, name, status });
41
41
  }
42
+
43
+ /** The tool-call row with this id, wherever it sits in the transcript. */
44
+ export function findToolCallRow(status: AgentExecutionStatus, toolCallId: string): ToolCall | undefined {
45
+ for (const message of status.messages) {
46
+ const row = message.toolCalls.find((tc) => tc.id === toolCallId);
47
+ if (row) return row;
48
+ }
49
+ return undefined;
50
+ }
51
+
52
+ /**
53
+ * A tool call withheld for approval — the row a harness writes when it
54
+ * proposes a gated side effect: WAITING_APPROVAL, `requiresApproval` set, and
55
+ * the approval fields the server owns (`approvalAction`, `approvalDecidedAt`)
56
+ * left at their defaults for the decision to fill in.
57
+ */
58
+ export function waitingToolCall(id: string, name: string, approvalMessage: string): ToolCall {
59
+ return create(ToolCallSchema, {
60
+ id,
61
+ name,
62
+ status: ToolCallStatus.TOOL_CALL_WAITING_APPROVAL,
63
+ requiresApproval: true,
64
+ approvalMessage,
65
+ });
66
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The runnable harness adapter contract.
3
+ *
4
+ * Runs the single, authoritative invariant catalog (see
5
+ * `__test-utils__/harness-contract/contract.ts`) against the scripted
6
+ * reference adapter under BOTH real pause primitives and BOTH state-id
7
+ * sources: `interrupt` with an engine-minted id and `deny-and-retry` with a
8
+ * deterministic id. Neither the kit nor the fake branches on the pause
9
+ * primitive — running both is what proves it.
10
+ *
11
+ * This is the consolidation home for what every harness owes the turn
12
+ * runtime. A real adapter joins the net by implementing
13
+ * `HarnessContractSubject` for its own SDK double and adding one line below;
14
+ * the runtime extraction (S2 of the program) adds the Cursor adapter here
15
+ * and runs the runtime-side half through the hermetic activity driver.
16
+ */
17
+
18
+ import { describeHarnessContract } from "../__test-utils__/harness-contract/contract.js";
19
+ import { scriptedSubject } from "../__test-utils__/harness-contract/scripted-adapter.js";
20
+
21
+ const interruptEngineMinted = scriptedSubject({ pausePrimitive: "interrupt", stateIdSource: "engine-minted" });
22
+ const denyAndRetryDeterministic = scriptedSubject({ pausePrimitive: "deny-and-retry", stateIdSource: "deterministic" });
23
+
24
+ describeHarnessContract(interruptEngineMinted);
25
+ describeHarnessContract(denyAndRetryDeterministic);