@crewhaus/runtime-core 0.1.1 → 0.1.3

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.
@@ -0,0 +1,303 @@
1
+ /**
2
+ * Coverage tests for `attachDefaultSubscribers` and `logFlushError`
3
+ * (observability.ts). Drives the cost-tracker / cost-inline / flushAll /
4
+ * shutdownAll branches deterministically by:
5
+ * - mocking the metrics-collector + otel-exporter attach helpers so their
6
+ * `flush`/`shutdown` resolve or reject under test control (NO real
7
+ * network sinks, NO leaked handles), and
8
+ * - publishing real `cost_accrual` events through a real TraceEventBus to
9
+ * exercise the inline-cost stdout handler.
10
+ *
11
+ * The mock.module replacements are reinstalled to the REAL modules in
12
+ * afterAll — `mock.restore()` (run in afterEach for the spies) does not undo
13
+ * `mock.module`, and Bun shares one module registry across all test files in
14
+ * nondeterministic order, so without that re-mock the fakes would leak into
15
+ * the rest of the runtime-core suite.
16
+ */
17
+ import { afterAll, afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test";
18
+ // Real modules captured for the afterAll restore — as plain-object SNAPSHOTS:
19
+ // an `import * as` namespace is a live view that resolves to the fakes once
20
+ // mock.module patches the module, so restoring from it would be a no-op.
21
+ import * as realMetricsCollectorNS from "@crewhaus/metrics-collector";
22
+ import * as realOtelExporterNS from "@crewhaus/otel-exporter";
23
+ import { createRunContext } from "@crewhaus/run-context";
24
+ import { TraceEventBus } from "@crewhaus/trace-event-bus";
25
+ import type { CostAccrualEvent } from "@crewhaus/trace-event-bus";
26
+
27
+ const realMetricsCollectorSnapshot = { ...realMetricsCollectorNS };
28
+ const realOtelExporterSnapshot = { ...realOtelExporterNS };
29
+
30
+ // Controllable fakes for the two heavyweight subscribers. The booleans let
31
+ // each test decide whether flush()/shutdown() reject so the catch → logFlushError
32
+ // branches (102, 105, 113-114) are reachable without real I/O.
33
+ const metricsState = {
34
+ flushRejects: false,
35
+ shutdownRejects: false,
36
+ flushCalls: 0,
37
+ shutdownCalls: 0,
38
+ unsubscribeCalls: 0,
39
+ attached: true,
40
+ };
41
+ const otelState = {
42
+ flushRejects: false,
43
+ shutdownRejects: false,
44
+ flushCalls: 0,
45
+ shutdownCalls: 0,
46
+ unsubscribeCalls: 0,
47
+ attached: true,
48
+ };
49
+
50
+ function resetState(): void {
51
+ for (const s of [metricsState, otelState]) {
52
+ s.flushRejects = false;
53
+ s.shutdownRejects = false;
54
+ s.flushCalls = 0;
55
+ s.shutdownCalls = 0;
56
+ s.unsubscribeCalls = 0;
57
+ s.attached = true;
58
+ }
59
+ }
60
+
61
+ beforeEach(() => {
62
+ resetState();
63
+ mock.module("@crewhaus/metrics-collector", () => ({
64
+ attachIfEnvSet: async () =>
65
+ metricsState.attached
66
+ ? {
67
+ registry: {},
68
+ unsubscribe: () => {
69
+ metricsState.unsubscribeCalls += 1;
70
+ },
71
+ flush: async () => {
72
+ metricsState.flushCalls += 1;
73
+ if (metricsState.flushRejects) throw new Error("metrics flush boom");
74
+ },
75
+ shutdown: async () => {
76
+ metricsState.shutdownCalls += 1;
77
+ if (metricsState.shutdownRejects) throw new Error("metrics shutdown boom");
78
+ },
79
+ }
80
+ : undefined,
81
+ }));
82
+ mock.module("@crewhaus/otel-exporter", () => ({
83
+ attachIfEnvSet: () =>
84
+ otelState.attached
85
+ ? {
86
+ unsubscribe: () => {
87
+ otelState.unsubscribeCalls += 1;
88
+ },
89
+ flush: async () => {
90
+ otelState.flushCalls += 1;
91
+ if (otelState.flushRejects) throw new Error("otel flush boom");
92
+ },
93
+ shutdown: async () => {
94
+ otelState.shutdownCalls += 1;
95
+ if (otelState.shutdownRejects) throw new Error("otel shutdown boom");
96
+ },
97
+ }
98
+ : undefined,
99
+ }));
100
+ });
101
+
102
+ afterEach(() => {
103
+ mock.restore();
104
+ });
105
+
106
+ afterAll(() => {
107
+ // Reinstall the real modules — mock.restore() only undoes spies, not
108
+ // mock.module, so without these the fakes leak into sibling test files.
109
+ mock.module("@crewhaus/metrics-collector", () => realMetricsCollectorSnapshot);
110
+ mock.module("@crewhaus/otel-exporter", () => realOtelExporterSnapshot);
111
+ });
112
+
113
+ function makeAccrual(overrides: Partial<CostAccrualEvent> = {}): CostAccrualEvent {
114
+ return {
115
+ kind: "cost_accrual",
116
+ traceId: "trace_a",
117
+ runId: "run_a",
118
+ sessionId: "sess_0000000000000001",
119
+ timestamp: 0,
120
+ provider: "anthropic",
121
+ modelId: "claude-sonnet-4-6",
122
+ inputTokens: 2_000,
123
+ outputTokens: 500,
124
+ cachedReadTokens: 0,
125
+ costUsdMicros: 4_200,
126
+ ...overrides,
127
+ } as CostAccrualEvent;
128
+ }
129
+
130
+ describe("attachDefaultSubscribers — cost tracking + inline cost line", () => {
131
+ test("cost tracker is created with tenantId when CREWHAUS_TENANT_ID is set", async () => {
132
+ const { attachDefaultSubscribers } = await import("./observability");
133
+ const bus = new TraceEventBus({ runId: "run_a", sessionId: "sess_0000000000000001" });
134
+ const ctx = createRunContext();
135
+ const subs = await attachDefaultSubscribers(bus, ctx, {
136
+ CREWHAUS_COST_TRACKING: "1",
137
+ CREWHAUS_TENANT_ID: "tenant-xyz",
138
+ });
139
+ // The cost tracker exists (lines 67-74 — including the tenantId spread).
140
+ expect(subs.costTracker).toBeDefined();
141
+ await subs.flushAll();
142
+ await subs.shutdownAll();
143
+ });
144
+
145
+ test("cost tracker is created without tenantId when the env var is absent", async () => {
146
+ const { attachDefaultSubscribers } = await import("./observability");
147
+ const bus = new TraceEventBus({ runId: "run_a", sessionId: "sess_0000000000000001" });
148
+ const ctx = createRunContext();
149
+ const subs = await attachDefaultSubscribers(bus, ctx, {
150
+ CREWHAUS_COST_TRACKING: "true",
151
+ });
152
+ expect(subs.costTracker).toBeDefined();
153
+ await subs.shutdownAll();
154
+ });
155
+
156
+ test("inline cost handler prints one line per cost_accrual and ignores other events", async () => {
157
+ const { attachDefaultSubscribers } = await import("./observability");
158
+ const bus = new TraceEventBus({ runId: "run_a", sessionId: "sess_0000000000000001" });
159
+ const ctx = createRunContext();
160
+ const writes: string[] = [];
161
+ const writeSpy = spyOn(process.stdout, "write").mockImplementation(((chunk: unknown) => {
162
+ writes.push(String(chunk));
163
+ return true;
164
+ }) as typeof process.stdout.write);
165
+ try {
166
+ const subs = await attachDefaultSubscribers(bus, ctx, {
167
+ CREWHAUS_COST_TRACKING: "1",
168
+ CREWHAUS_COST_INLINE: "1",
169
+ });
170
+ expect(subs.costInlineUnsubscribe).toBeDefined();
171
+
172
+ // A non-cost event must hit the early `return` (line 85) → no write.
173
+ bus.publish({ ...bus.envelope(), kind: "turn_start", turn: 1, messageCount: 0 });
174
+ const beforeCost = writes.length;
175
+ // A cost_accrual event triggers the inline line (lines 86-88).
176
+ bus.publish(makeAccrual({ costUsdMicros: 4_200 }));
177
+ const costLines = writes.filter((w) => w.includes("💸"));
178
+ expect(costLines.length).toBe(1);
179
+ expect(costLines[0]).toContain("$0.0042");
180
+ expect(beforeCost).toBe(0); // turn_start wrote nothing
181
+
182
+ // Unsubscribe stops further inline lines.
183
+ subs.costInlineUnsubscribe?.();
184
+ bus.publish(makeAccrual({ costUsdMicros: 9_999 }));
185
+ expect(writes.filter((w) => w.includes("💸")).length).toBe(1);
186
+ await subs.shutdownAll();
187
+ } finally {
188
+ writeSpy.mockRestore();
189
+ }
190
+ });
191
+
192
+ test("inline cost is NOT enabled when CREWHAUS_COST_TRACKING is missing", async () => {
193
+ const { attachDefaultSubscribers } = await import("./observability");
194
+ const bus = new TraceEventBus({ runId: "run_a", sessionId: "sess_0000000000000001" });
195
+ const ctx = createRunContext();
196
+ // COST_INLINE set but no COST_TRACKING → costTracker undefined → inline off.
197
+ const subs = await attachDefaultSubscribers(bus, ctx, { CREWHAUS_COST_INLINE: "1" });
198
+ expect(subs.costTracker).toBeUndefined();
199
+ expect(subs.costInlineUnsubscribe).toBeUndefined();
200
+ await subs.shutdownAll();
201
+ });
202
+ });
203
+
204
+ describe("attachDefaultSubscribers — flushAll / shutdownAll error handling", () => {
205
+ test("flushAll flushes metrics + otel + bus and tolerates rejections (logFlushError)", async () => {
206
+ const { attachDefaultSubscribers } = await import("./observability");
207
+ const bus = new TraceEventBus({ runId: "run_a", sessionId: "sess_0000000000000001" });
208
+ const ctx = createRunContext();
209
+ const errSpy = spyOn(ctx.logger, "error");
210
+
211
+ metricsState.flushRejects = true;
212
+ otelState.flushRejects = true;
213
+ // Both subscribers attached (their attach helpers are mocked to return
214
+ // truthy objects). bus.flush is also exercised; force it to reject too so
215
+ // the bus-flush catch arm (logFlushError "bus") runs.
216
+ const busFlushSpy = spyOn(bus, "flush").mockImplementation(async () => {
217
+ throw new Error("bus flush boom");
218
+ });
219
+
220
+ const subs = await attachDefaultSubscribers(bus, ctx, {
221
+ CREWHAUS_METRICS: "stdout",
222
+ OTEL_EXPORTER_OTLP_ENDPOINT: "http://localhost:4318",
223
+ });
224
+ // Should resolve despite all three flush paths rejecting.
225
+ await subs.flushAll();
226
+
227
+ expect(metricsState.flushCalls).toBe(1);
228
+ expect(otelState.flushCalls).toBe(1);
229
+ expect(busFlushSpy).toHaveBeenCalled();
230
+ // logFlushError logged once per failing surface (metrics, otel, bus).
231
+ const flushFailedLogs = errSpy.mock.calls.filter((c) => c[0] === "observability.flush_failed");
232
+ expect(flushFailedLogs.length).toBe(3);
233
+ busFlushSpy.mockRestore();
234
+ });
235
+
236
+ test("shutdownAll awaits metrics + otel shutdown and tolerates rejections", async () => {
237
+ const { attachDefaultSubscribers } = await import("./observability");
238
+ const bus = new TraceEventBus({ runId: "run_a", sessionId: "sess_0000000000000001" });
239
+ const ctx = createRunContext();
240
+ const errSpy = spyOn(ctx.logger, "error");
241
+
242
+ metricsState.shutdownRejects = true;
243
+ otelState.shutdownRejects = true;
244
+
245
+ const subs = await attachDefaultSubscribers(bus, ctx, {
246
+ CREWHAUS_METRICS: "stdout",
247
+ OTEL_EXPORTER_OTLP_ENDPOINT: "http://localhost:4318",
248
+ CREWHAUS_COST_TRACKING: "1",
249
+ CREWHAUS_COST_INLINE: "1",
250
+ });
251
+ await subs.shutdownAll();
252
+
253
+ // Both shutdowns ran (lines 101-106), both failures logged (113-114),
254
+ // and the cost tracker + inline subscription were torn down (107-108).
255
+ expect(metricsState.shutdownCalls).toBe(1);
256
+ expect(otelState.shutdownCalls).toBe(1);
257
+ const shutdownFailedLogs = errSpy.mock.calls.filter(
258
+ (c) => c[0] === "observability.flush_failed",
259
+ );
260
+ expect(shutdownFailedLogs.length).toBe(2);
261
+ });
262
+
263
+ test("logFlushError stringifies a non-Error rejection value", async () => {
264
+ const { attachDefaultSubscribers } = await import("./observability");
265
+ const bus = new TraceEventBus({ runId: "run_a", sessionId: "sess_0000000000000001" });
266
+ const ctx = createRunContext();
267
+ const errSpy = spyOn(ctx.logger, "error");
268
+
269
+ // Reject with a plain string (not an Error) so the `String(err)` branch
270
+ // of logFlushError (line 114) is exercised. Use Promise.reject rather than
271
+ // `throw "literal"` to avoid the throw-literal lint while still rejecting
272
+ // with a non-Error value.
273
+ const busFlushSpy = spyOn(bus, "flush").mockImplementation(() =>
274
+ Promise.reject("plain-string-failure"),
275
+ );
276
+
277
+ const subs = await attachDefaultSubscribers(bus, ctx, {});
278
+ await subs.flushAll();
279
+
280
+ const log = errSpy.mock.calls.find((c) => c[0] === "observability.flush_failed");
281
+ expect(log).toBeDefined();
282
+ expect((log?.[1] as { message: string }).message).toBe("plain-string-failure");
283
+ busFlushSpy.mockRestore();
284
+ });
285
+
286
+ test("flushAll with no subscribers attached only flushes the bus", async () => {
287
+ const { attachDefaultSubscribers } = await import("./observability");
288
+ const bus = new TraceEventBus({ runId: "run_a", sessionId: "sess_0000000000000001" });
289
+ const ctx = createRunContext();
290
+ // No env → metrics/otel attach helpers (mocked) still return objects, so
291
+ // flip `attached` off to model the genuine no-subscriber case (the `if`
292
+ // guards on lines 93-95 / 101-106 skip their bodies).
293
+ metricsState.attached = false;
294
+ otelState.attached = false;
295
+ const subs = await attachDefaultSubscribers(bus, ctx, {});
296
+ expect(subs.metrics).toBeUndefined();
297
+ expect(subs.otel).toBeUndefined();
298
+ await subs.flushAll();
299
+ await subs.shutdownAll();
300
+ expect(metricsState.flushCalls).toBe(0);
301
+ expect(otelState.flushCalls).toBe(0);
302
+ });
303
+ });
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Coverage tests for the defensive / error branches of loadProjectMemory
3
+ * that the happy-path suite (project-memory.test.ts) does not reach:
4
+ * - a matched path that is a directory, not a file (`!st.isFile()`)
5
+ * - `readFile()` throwing (the `catch { continue }` during read)
6
+ * - `classifyBoundary()` rejecting (the `.catch(() => undefined)` arrow)
7
+ *
8
+ * Module mocks are installed ONCE at file scope (before loadProjectMemory is
9
+ * first imported) and gated behind mutable flags so each test toggles only
10
+ * the failure it needs — this sidesteps ESM live-binding caching, where a
11
+ * mock.module call made after the importer is already loaded would not be
12
+ * observed. Flags are reset in afterEach; afterAll reinstalls the REAL
13
+ * modules — `mock.restore()` does not undo `mock.module`, and Bun shares one
14
+ * module registry across all test files (nondeterministic order), so only
15
+ * the re-mock keeps the stubs from leaking into sibling test files.
16
+ */
17
+ import { afterAll, afterEach, describe, expect, mock, test } from "bun:test";
18
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
19
+ import * as realFsPromises from "node:fs/promises";
20
+ import { tmpdir } from "node:os";
21
+ import { join } from "node:path";
22
+ // Real module captured for the afterAll restore.
23
+ import * as realBoundaryClassifierNS from "@crewhaus/boundary-classifier";
24
+
25
+ const realStat = realFsPromises.stat;
26
+ const realReadFile = realFsPromises.readFile;
27
+ // Plain-object SNAPSHOTS for the afterAll restore: an `import * as` namespace
28
+ // is a live view that resolves to the stubs once mock.module patches the
29
+ // module, so restoring from it would be a no-op.
30
+ const realFsPromisesSnapshot = { ...realFsPromises };
31
+ const realBoundaryClassifierSnapshot = { ...realBoundaryClassifierNS };
32
+
33
+ // Per-test toggles. When a `*Fails` is set, the corresponding mocked fn
34
+ // rejects for the named file; otherwise it delegates to the real impl.
35
+ const flags = {
36
+ readFileFailsFor: undefined as string | undefined,
37
+ classifyFails: false,
38
+ classifyCalls: 0,
39
+ };
40
+
41
+ mock.module("node:fs/promises", () => ({
42
+ ...realFsPromises,
43
+ stat: realStat,
44
+ readFile: (p: string, enc: BufferEncoding) => {
45
+ if (flags.readFileFailsFor !== undefined && String(p).endsWith(flags.readFileFailsFor)) {
46
+ return Promise.reject(new Error("readFile EIO"));
47
+ }
48
+ return realReadFile(p, enc);
49
+ },
50
+ }));
51
+
52
+ mock.module("@crewhaus/boundary-classifier", () => ({
53
+ classifyBoundary: (..._args: unknown[]) => {
54
+ flags.classifyCalls += 1;
55
+ if (flags.classifyFails) return Promise.reject(new Error("classifier offline"));
56
+ return Promise.resolve({ classification: "clean", hits: [] });
57
+ },
58
+ }));
59
+
60
+ afterEach(() => {
61
+ flags.readFileFailsFor = undefined;
62
+ flags.classifyFails = false;
63
+ flags.classifyCalls = 0;
64
+ });
65
+
66
+ afterAll(() => {
67
+ // Reinstall the real modules — mock.restore() would only undo spies, not
68
+ // mock.module, so re-mocking is the only way to prevent cross-file leaks.
69
+ mock.module("node:fs/promises", () => realFsPromisesSnapshot);
70
+ mock.module("@crewhaus/boundary-classifier", () => realBoundaryClassifierSnapshot);
71
+ });
72
+
73
+ describe("loadProjectMemory — defensive branches", () => {
74
+ test("skips a canonical name that resolves to a directory (not a file)", async () => {
75
+ const { loadProjectMemory } = await import("./project-memory");
76
+ const dir = mkdtempSync(join(tmpdir(), "crewhaus-pm-dir-"));
77
+ try {
78
+ // A *directory* named CLAUDE.md: existsSync true, stat ok, isFile false.
79
+ mkdirSync(join(dir, "CLAUDE.md"));
80
+ writeFileSync(join(dir, "AGENTS.md"), "# real file");
81
+ const result = await loadProjectMemory({ cwd: dir });
82
+ expect(result.files.map((f) => f.filename)).toEqual(["AGENTS.md"]);
83
+ } finally {
84
+ rmSync(dir, { recursive: true, force: true });
85
+ }
86
+ });
87
+
88
+ test("continues past a readFile() failure during read (catch { continue })", async () => {
89
+ const dir = mkdtempSync(join(tmpdir(), "crewhaus-pm-read-"));
90
+ try {
91
+ writeFileSync(join(dir, "AGENTS.md"), "# unreadable");
92
+ writeFileSync(join(dir, "CLAUDE.md"), "# readable");
93
+ flags.readFileFailsFor = "AGENTS.md";
94
+ const { loadProjectMemory } = await import("./project-memory");
95
+ const result = await loadProjectMemory({ cwd: dir });
96
+ // AGENTS.md's read threw → `continue`; only CLAUDE.md is loaded.
97
+ expect(result.files.map((f) => f.filename)).toEqual(["CLAUDE.md"]);
98
+ expect(result.files[0]?.content).toContain("# readable");
99
+ } finally {
100
+ rmSync(dir, { recursive: true, force: true });
101
+ }
102
+ });
103
+
104
+ test("tolerates classifyBoundary rejecting (.catch arrow returns undefined)", async () => {
105
+ const dir = mkdtempSync(join(tmpdir(), "crewhaus-pm-classify-"));
106
+ try {
107
+ writeFileSync(join(dir, "AGENTS.md"), "# content to classify");
108
+ flags.classifyFails = true;
109
+ const { loadProjectMemory } = await import("./project-memory");
110
+ const result = await loadProjectMemory({ cwd: dir });
111
+ // The classifier threw but the load still succeeded (best-effort).
112
+ expect(flags.classifyCalls).toBe(1);
113
+ expect(result.files.length).toBe(1);
114
+ expect(result.files[0]?.content).toContain("# content to classify");
115
+ } finally {
116
+ rmSync(dir, { recursive: true, force: true });
117
+ }
118
+ });
119
+ });
@@ -0,0 +1,80 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2
+ import { buildTenant, withTenant } from "@crewhaus/tenancy";
3
+ import { resolveSessionRootDir, resolveToolResultRoot } from "./index";
4
+
5
+ // Regression — issue #142 (CWE-1230). The managed daemon wraps every gateway
6
+ // request in `withTenant(...)`; runtime-core must resolve its session/event-log
7
+ // root from that ambient tenant context so two tenants' transcripts never share
8
+ // a directory. These tests pin the resolution contract directly (no model loop).
9
+
10
+ const ENV_KEYS = ["CREWHAUS_SESSION_DIR"] as const;
11
+ const ORIGINAL_ENV: Record<string, string | undefined> = {};
12
+
13
+ beforeEach(() => {
14
+ for (const key of ENV_KEYS) {
15
+ ORIGINAL_ENV[key] = process.env[key];
16
+ delete process.env[key];
17
+ }
18
+ });
19
+
20
+ afterEach(() => {
21
+ for (const [key, value] of Object.entries(ORIGINAL_ENV)) {
22
+ if (value === undefined) delete process.env[key];
23
+ else process.env[key] = value;
24
+ }
25
+ });
26
+
27
+ describe("resolveSessionRootDir — tenant isolation (#142)", () => {
28
+ test("each tenant resolves to its own disjoint sessionRoot", () => {
29
+ const a = buildTenant("tenant-a", { tenantsRoot: "/tmp/ch-tenant-test" });
30
+ const b = buildTenant("tenant-b", { tenantsRoot: "/tmp/ch-tenant-test" });
31
+
32
+ const rootA = withTenant(a, () => resolveSessionRootDir(undefined)) as string;
33
+ const rootB = withTenant(b, () => resolveSessionRootDir(undefined)) as string;
34
+
35
+ expect(rootA).toBe(a.sessionRoot);
36
+ expect(rootB).toBe(b.sessionRoot);
37
+ expect(rootA).not.toBe(rootB);
38
+ // Neither tenant's transcripts can land under the other's root.
39
+ expect(rootA.startsWith(`${rootB}/`)).toBe(false);
40
+ expect(rootB.startsWith(`${rootA}/`)).toBe(false);
41
+ });
42
+
43
+ test("does NOT fall back to the global default inside a tenant scope", () => {
44
+ process.env["CREWHAUS_SESSION_DIR"] = "/tmp/GLOBAL-shared";
45
+ const a = buildTenant("tenant-a", { tenantsRoot: "/tmp/ch-tenant-test" });
46
+ const root = withTenant(a, () => resolveSessionRootDir(undefined)) as string;
47
+ expect(root).toBe(a.sessionRoot);
48
+ expect(root).not.toBe("/tmp/GLOBAL-shared");
49
+ });
50
+
51
+ test("outside any tenant scope, honours env then undefined (unchanged behaviour)", () => {
52
+ expect(resolveSessionRootDir(undefined)).toBeUndefined();
53
+ process.env["CREWHAUS_SESSION_DIR"] = "/tmp/env-root";
54
+ expect(resolveSessionRootDir(undefined)).toBe("/tmp/env-root");
55
+ });
56
+
57
+ test("an explicit per-call root still wins (trusted caller override)", () => {
58
+ const a = buildTenant("tenant-a", { tenantsRoot: "/tmp/ch-tenant-test" });
59
+ const root = withTenant(a, () => resolveSessionRootDir("/tmp/explicit")) as string;
60
+ expect(root).toBe("/tmp/explicit");
61
+ });
62
+ });
63
+
64
+ // Regression — issue #150 (CWE-1230). The tool-result spill store must be
65
+ // rebased per tenant too, not just the session store.
66
+ describe("resolveToolResultRoot — tenant isolation (#150)", () => {
67
+ test("each tenant resolves to its own toolResultRoot, disjoint", () => {
68
+ const a = buildTenant("tenant-a", { tenantsRoot: "/tmp/ch-tenant-test" });
69
+ const b = buildTenant("tenant-b", { tenantsRoot: "/tmp/ch-tenant-test" });
70
+ const rootA = withTenant(a, () => resolveToolResultRoot()) as string;
71
+ const rootB = withTenant(b, () => resolveToolResultRoot()) as string;
72
+ expect(rootA).toBe(a.toolResultRoot);
73
+ expect(rootB).toBe(b.toolResultRoot);
74
+ expect(rootA).not.toBe(rootB);
75
+ });
76
+
77
+ test("outside a tenant scope, returns undefined (tool-result-store default applies)", () => {
78
+ expect(resolveToolResultRoot()).toBeUndefined();
79
+ });
80
+ });