@ftrdotdev/pi-tracker 0.8.0 → 0.9.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.
package/src/core/store.ts CHANGED
@@ -25,9 +25,12 @@ const Reason = Schema.Union([
25
25
  Schema.Literal("ItemDependedOn"),
26
26
  ]);
27
27
 
28
- export type TrackerErrorReason = Schema.Schema.Type<typeof Reason>;
28
+ export type TrackerErrorReason = typeof Reason.Type;
29
29
 
30
- export class TrackerError extends Schema.TaggedError<TrackerError>()("TrackerError", {
30
+ export class TrackerError extends Schema.TaggedError<
31
+ TrackerError,
32
+ { readonly brand: unique symbol }
33
+ >()("TrackerError", {
31
34
  reason: Reason,
32
35
  message: Schema.String,
33
36
  listId: Schema.optional(Schema.Int),
@@ -65,12 +68,12 @@ type ResolvedItem =
65
68
  */
66
69
  const resolveItem = (s: TrackerState, itemId: string): ResolvedItem => {
67
70
  const parsed = parseItemRef(itemId);
68
- if (!parsed) return { kind: "malformed" };
71
+ if (parsed === null) return { kind: "malformed" };
69
72
  const list = s.lists.find((l) => l.name === parsed.name);
70
- if (!list) return { kind: "noList", listName: parsed.name };
73
+ if (list === undefined) return { kind: "noList", listName: parsed.name };
71
74
  const index = list.items.findIndex((item) => item.id === parsed.id);
72
75
  const item = index === -1 ? undefined : list.items[index];
73
- if (!item) return { kind: "noItem", list };
76
+ if (item === undefined) return { kind: "noItem", list };
74
77
  return { kind: "ok", list, item, index };
75
78
  };
76
79
 
@@ -90,7 +93,7 @@ const resolveItemOrError = (
90
93
  case "malformed":
91
94
  return {
92
95
  ok: false,
93
- error: new TrackerError({
96
+ error: TrackerError.make({
94
97
  reason: "ItemNotFound",
95
98
  message: `Item "${itemId}" must look like "listName:id" (e.g. "Work:2")`,
96
99
  itemId,
@@ -100,7 +103,7 @@ const resolveItemOrError = (
100
103
  const available = s.lists.map((list) => `[${list.id}] ${list.name}`).join(", ");
101
104
  return {
102
105
  ok: false,
103
- error: new TrackerError({
106
+ error: TrackerError.make({
104
107
  reason: "ItemNotFound",
105
108
  message:
106
109
  available === ""
@@ -113,7 +116,7 @@ const resolveItemOrError = (
113
116
  case "noItem":
114
117
  return {
115
118
  ok: false,
116
- error: new TrackerError({
119
+ error: TrackerError.make({
117
120
  reason: "ItemNotFound",
118
121
  message: itemNotFoundMessage(resolved.list, itemId),
119
122
  listId: resolved.list.id,
@@ -153,13 +156,32 @@ const nextItemIdFor = (items: readonly TodoItem[], counter: number): number =>
153
156
 
154
157
  /** A copy of `list` with a replaced item array and a counter above its ids. */
155
158
  const withItems = (list: TodoList, items: readonly TodoItem[]): TodoList =>
156
- new TodoList({
159
+ TodoList.make({
157
160
  id: list.id,
158
161
  name: list.name,
159
162
  items: [...items],
160
163
  nextItemId: nextItemIdFor(items, list.nextItemId),
161
164
  });
162
165
 
166
+ /**
167
+ * A copy of the state with the given fields replaced. Every field is named
168
+ * explicitly: spreading a `Schema.Class` instance would drop its prototype, so
169
+ * a later `encode` or `instanceof` check would fail on the copy.
170
+ */
171
+ const withState = (
172
+ s: TrackerState,
173
+ change: {
174
+ readonly lists?: readonly TodoList[];
175
+ readonly activeListId?: number | null;
176
+ readonly nextListId?: number;
177
+ },
178
+ ): TrackerState =>
179
+ TrackerState.make({
180
+ lists: change.lists ?? s.lists,
181
+ activeListId: change.activeListId === undefined ? s.activeListId : change.activeListId,
182
+ nextListId: change.nextListId ?? s.nextListId,
183
+ });
184
+
163
185
  // --------------------------------------------------------------------------
164
186
  // Store
165
187
  // --------------------------------------------------------------------------
@@ -218,13 +240,13 @@ const firstDependencyError = (
218
240
  for (const ref of deps) {
219
241
  const parsed = parseItemRef(ref);
220
242
  if (parsed === null) {
221
- return new TrackerError({
243
+ return TrackerError.make({
222
244
  reason: "DependencyNotFound",
223
245
  message: `Dependency "${ref}" must look like "listName:id" (e.g. "Work:2")`,
224
246
  });
225
247
  }
226
248
  if (parsed.name !== list.name) {
227
- return new TrackerError({
249
+ return TrackerError.make({
228
250
  reason: "CrossListDependency",
229
251
  message:
230
252
  `Dependency "${ref}" is in another list. Dependencies must be in "${list.name}" ` +
@@ -232,13 +254,13 @@ const firstDependencyError = (
232
254
  });
233
255
  }
234
256
  if (!list.items.some((item) => item.id === parsed.id)) {
235
- return new TrackerError({
257
+ return TrackerError.make({
236
258
  reason: "DependencyNotFound",
237
259
  message: notFoundMessage(ref, "Dependency", list),
238
260
  });
239
261
  }
240
262
  if (target !== undefined && target.id === parsed.id) {
241
- return new TrackerError({
263
+ return TrackerError.make({
242
264
  reason: "DependencyCycle",
243
265
  message: `Item "${ref}" cannot depend on itself`,
244
266
  });
@@ -250,7 +272,7 @@ const firstDependencyError = (
250
272
  cycle.length === 0
251
273
  ? `involving "${list.name}:${target?.id ?? targetIndex + 1}"`
252
274
  : `: ${cycle.join(" → ")}`;
253
- return new TrackerError({
275
+ return TrackerError.make({
254
276
  reason: "DependencyCycle",
255
277
  message: `Dependency cycle${where}. Change or clear one of these dependencies`,
256
278
  });
@@ -265,7 +287,7 @@ const blockedError = (list: TodoList, index: number): TrackerError | null => {
265
287
  const blockers = blockersOf(list, index);
266
288
  if (blockers.length === 0) return null;
267
289
  const subject = formatItemRef(list.name, list.items[index]!.id);
268
- return new TrackerError({
290
+ return TrackerError.make({
269
291
  reason: "ItemBlocked",
270
292
  message:
271
293
  `Item "${subject}" is blocked by ${blockers.join(", ")}. ` +
@@ -281,7 +303,7 @@ const dependedOnError = (list: TodoList, index: number, itemId: string): Tracker
281
303
  const names = dependents
282
304
  .map((dependent) => formatItemRef(list.name, list.items[dependent]!.id))
283
305
  .join(", ");
284
- return new TrackerError({
306
+ return TrackerError.make({
285
307
  reason: "ItemDependedOn",
286
308
  message:
287
309
  `Item "${itemId}" has dependents: ${names}. ` + "Remove or change those dependencies first",
@@ -349,7 +371,7 @@ export class TrackerStore extends Context.Service<
349
371
  ) => Effect.Effect<TodoItem[], TrackerError>;
350
372
  readonly removeItem: (itemId: string) => Effect.Effect<void, TrackerError>;
351
373
  }
352
- >()("tracker/TrackerStore") {
374
+ >()("@ftrdotdev/pi-tracker/core/store/TrackerStore") {
353
375
  static readonly layer: Layer.Layer<TrackerStore> = Layer.effect(
354
376
  TrackerStore,
355
377
  Effect.gen(function* () {
@@ -377,14 +399,14 @@ export class TrackerStore extends Context.Service<
377
399
  ) {
378
400
  const trimmed = name.trim();
379
401
  if (trimmed === "") {
380
- return yield* new TrackerError({
402
+ return yield* TrackerError.make({
381
403
  reason: "EmptyText",
382
404
  message: "List name must not be empty",
383
405
  });
384
406
  }
385
407
  const initialSpecs = (options.initialItems ?? []).map(normalizeSpec);
386
408
  if (initialSpecs.some((spec) => spec.title === "")) {
387
- return yield* new TrackerError({
409
+ return yield* TrackerError.make({
388
410
  reason: "EmptyText",
389
411
  message: "Item title must not be empty",
390
412
  });
@@ -395,7 +417,7 @@ export class TrackerStore extends Context.Service<
395
417
  if (s.lists.some((list) => list.name === trimmed)) {
396
418
  return [
397
419
  Result.fail(
398
- new TrackerError({
420
+ TrackerError.make({
399
421
  reason: "DuplicateListName",
400
422
  message: `List "${trimmed}" already exists`,
401
423
  }),
@@ -403,19 +425,18 @@ export class TrackerStore extends Context.Service<
403
425
  s,
404
426
  ];
405
427
  }
406
- const items = initialSpecs.map(
407
- (spec, index) =>
408
- new TodoItem({
409
- id: index + 1,
410
- title: spec.title,
411
- description: spec.description,
412
- refs: [...spec.refs],
413
- produces: [...spec.produces],
414
- done: false,
415
- deps: [...spec.deps],
416
- }),
428
+ const items = initialSpecs.map((spec, index) =>
429
+ TodoItem.make({
430
+ id: index + 1,
431
+ title: spec.title,
432
+ description: spec.description,
433
+ refs: [...spec.refs],
434
+ produces: [...spec.produces],
435
+ done: false,
436
+ deps: [...spec.deps],
437
+ }),
417
438
  );
418
- const list = new TodoList({
439
+ const list = TodoList.make({
419
440
  id: s.nextListId,
420
441
  name: trimmed,
421
442
  items,
@@ -429,8 +450,7 @@ export class TrackerStore extends Context.Service<
429
450
  }
430
451
  return [
431
452
  Result.succeed(list),
432
- new TrackerState({
433
- ...s,
453
+ withState(s, {
434
454
  lists: [...s.lists, list],
435
455
  // The new list becomes the active list by default (the widget
436
456
  // switches to it); pass activate: false to keep the current
@@ -448,7 +468,7 @@ export class TrackerStore extends Context.Service<
448
468
  if (!s.lists.some((list) => list.id === listId)) {
449
469
  return [
450
470
  Result.fail(
451
- new TrackerError({
471
+ TrackerError.make({
452
472
  reason: "ListNotFound",
453
473
  message: listNotFoundMessage(s, listId),
454
474
  listId,
@@ -459,7 +479,7 @@ export class TrackerStore extends Context.Service<
459
479
  }
460
480
  const lists = s.lists.filter((list) => list.id !== listId);
461
481
  const activeListId = s.activeListId === listId ? null : s.activeListId;
462
- return [Result.succeed(undefined), new TrackerState({ ...s, lists, activeListId })];
482
+ return [Result.succeed(undefined), withState(s, { lists, activeListId })];
463
483
  });
464
484
  });
465
485
 
@@ -468,12 +488,12 @@ export class TrackerStore extends Context.Service<
468
488
  ) {
469
489
  return yield* mutate((s): readonly [Result.Result<void, TrackerError>, TrackerState] => {
470
490
  if (listId === null) {
471
- return [Result.succeed(undefined), new TrackerState({ ...s, activeListId: null })];
491
+ return [Result.succeed(undefined), withState(s, { activeListId: null })];
472
492
  }
473
493
  if (!s.lists.some((list) => list.id === listId)) {
474
494
  return [
475
495
  Result.fail(
476
- new TrackerError({
496
+ TrackerError.make({
477
497
  reason: "ListNotFound",
478
498
  message: listNotFoundMessage(s, listId),
479
499
  listId,
@@ -482,7 +502,7 @@ export class TrackerStore extends Context.Service<
482
502
  s,
483
503
  ];
484
504
  }
485
- return [Result.succeed(undefined), new TrackerState({ ...s, activeListId: listId })];
505
+ return [Result.succeed(undefined), withState(s, { activeListId: listId })];
486
506
  });
487
507
  });
488
508
 
@@ -497,7 +517,7 @@ export class TrackerStore extends Context.Service<
497
517
  ) {
498
518
  const specs = items.map(normalizeSpec);
499
519
  if (specs.some((spec) => spec.title === "")) {
500
- return yield* new TrackerError({
520
+ return yield* TrackerError.make({
501
521
  reason: "EmptyText",
502
522
  message: "Item title must not be empty",
503
523
  });
@@ -505,10 +525,10 @@ export class TrackerStore extends Context.Service<
505
525
  return yield* mutate(
506
526
  (s): readonly [Result.Result<TodoItem[], TrackerError>, TrackerState] => {
507
527
  const list = s.lists.find((l) => l.id === listId);
508
- if (!list) {
528
+ if (list === undefined) {
509
529
  return [
510
530
  Result.fail(
511
- new TrackerError({
531
+ TrackerError.make({
512
532
  reason: "ListNotFound",
513
533
  message: listNotFoundMessage(s, listId),
514
534
  listId,
@@ -519,7 +539,7 @@ export class TrackerStore extends Context.Service<
519
539
  }
520
540
  let nextId = nextItemIdFor(list.items, list.nextItemId);
521
541
  const added = specs.map((spec) => {
522
- const item = new TodoItem({
542
+ const item = TodoItem.make({
523
543
  id: nextId,
524
544
  title: spec.title,
525
545
  description: spec.description,
@@ -539,7 +559,7 @@ export class TrackerStore extends Context.Service<
539
559
  if (error !== null) return [Result.fail(error), s];
540
560
  }
541
561
  const lists = s.lists.map((l) => (l.id === listId ? nextList : l));
542
- return [Result.succeed(added), new TrackerState({ ...s, lists })];
562
+ return [Result.succeed(added), withState(s, { lists })];
543
563
  },
544
564
  );
545
565
  });
@@ -560,7 +580,7 @@ export class TrackerStore extends Context.Service<
560
580
  ) {
561
581
  const trimmed = patch.title === undefined ? undefined : patch.title.trim();
562
582
  if (patch.title !== undefined && trimmed === "") {
563
- return yield* new TrackerError({
583
+ return yield* TrackerError.make({
564
584
  reason: "EmptyText",
565
585
  message: "Item title must not be empty",
566
586
  });
@@ -575,7 +595,7 @@ export class TrackerStore extends Context.Service<
575
595
  // Completion is gated on the list as it stands: an item may only be
576
596
  // completed once its dependencies are done. Reopening and text or
577
597
  // dependency edits stay open, so a blocked item can be repaired.
578
- if (patch.done === true) {
598
+ if (patch.done ?? false) {
579
599
  const blocked = blockedError(list, resolved.index);
580
600
  if (blocked !== null) return [Result.fail(blocked), s];
581
601
  }
@@ -590,7 +610,7 @@ export class TrackerStore extends Context.Service<
590
610
  // No-op patch: return the current item, leave state untouched.
591
611
  return [Result.succeed(item), s];
592
612
  }
593
- const next = new TodoItem({
613
+ const next = TodoItem.make({
594
614
  id: item.id,
595
615
  title: trimmed ?? item.title,
596
616
  description: patch.description ?? item.description,
@@ -609,7 +629,7 @@ export class TrackerStore extends Context.Service<
609
629
  const error = firstDependencyError(nextList, resolved.index, next.deps);
610
630
  if (error !== null) return [Result.fail(error), s];
611
631
  const lists = s.lists.map((l) => (l.id === list.id ? nextList : l));
612
- return [Result.succeed(next), new TrackerState({ ...s, lists })];
632
+ return [Result.succeed(next), withState(s, { lists })];
613
633
  },
614
634
  );
615
635
  });
@@ -628,7 +648,7 @@ export class TrackerStore extends Context.Service<
628
648
  // before touching the state (atomicity).
629
649
  for (const patch of patches) {
630
650
  if (patch.title !== undefined && patch.title.trim() === "") {
631
- return yield* new TrackerError({
651
+ return yield* TrackerError.make({
632
652
  reason: "EmptyText",
633
653
  message: "Item title must not be empty",
634
654
  });
@@ -637,10 +657,10 @@ export class TrackerStore extends Context.Service<
637
657
  return yield* mutate(
638
658
  (s): readonly [Result.Result<TodoItem[], TrackerError>, TrackerState] => {
639
659
  const list = s.lists.find((l) => l.id === listId);
640
- if (!list) {
660
+ if (list === undefined) {
641
661
  return [
642
662
  Result.fail(
643
- new TrackerError({
663
+ TrackerError.make({
644
664
  reason: "ListNotFound",
645
665
  message: listNotFoundMessage(s, listId),
646
666
  listId,
@@ -658,7 +678,7 @@ export class TrackerStore extends Context.Service<
658
678
  if (parsed === null) {
659
679
  return [
660
680
  Result.fail(
661
- new TrackerError({
681
+ TrackerError.make({
662
682
  reason: "ItemNotFound",
663
683
  message: `Item "${patch.itemId}" must look like "listName:id" (e.g. "Work:2")`,
664
684
  listId,
@@ -675,7 +695,7 @@ export class TrackerStore extends Context.Service<
675
695
  if (index === -1) {
676
696
  return [
677
697
  Result.fail(
678
- new TrackerError({
698
+ TrackerError.make({
679
699
  reason: "ItemNotFound",
680
700
  message: itemNotFoundMessage(list, patch.itemId),
681
701
  listId,
@@ -697,14 +717,14 @@ export class TrackerStore extends Context.Service<
697
717
  let items = [...list.items];
698
718
  for (const [index, patch] of patches.entries()) {
699
719
  const target = targets[index]!;
700
- if (patch.done === true) {
720
+ if (patch.done ?? false) {
701
721
  const blocked = blockedError(withItems(list, items), target);
702
722
  if (blocked !== null) return [Result.fail(blocked), s];
703
723
  }
704
724
  const current = items[target]!;
705
725
  items = items.map((item, at) =>
706
726
  at === target
707
- ? new TodoItem({
727
+ ? TodoItem.make({
708
728
  id: current.id,
709
729
  title: patch.title === undefined ? current.title : patch.title.trim(),
710
730
  description: patch.description ?? current.description,
@@ -730,7 +750,7 @@ export class TrackerStore extends Context.Service<
730
750
  // Results in patch order so the caller can map them 1:1. A patch
731
751
  // that a later one overwrote reports the later state.
732
752
  Result.succeed(targets.map((index) => items[index]!)),
733
- new TrackerState({ ...s, lists }),
753
+ withState(s, { lists }),
734
754
  ];
735
755
  },
736
756
  );
@@ -760,7 +780,7 @@ export class TrackerStore extends Context.Service<
760
780
  )
761
781
  : l,
762
782
  );
763
- return [Result.succeed(undefined), new TrackerState({ ...s, lists })];
783
+ return [Result.succeed(undefined), withState(s, { lists })];
764
784
  });
765
785
  });
766
786
 
@@ -0,0 +1,75 @@
1
+ import { expect, it } from "@effect/vitest";
2
+ import { readdirSync } from "node:fs";
3
+ import { join, relative } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { createVitest } from "vitest/node";
6
+
7
+ const PACKAGE_ROOT = fileURLToPath(new URL("..", import.meta.url));
8
+
9
+ /** Every `*.test.ts` under `dir`, as paths relative to `PACKAGE_ROOT`. */
10
+ const walkTests = (dir: string, found: string[] = []): string[] => {
11
+ for (const entry of readdirSync(join(PACKAGE_ROOT, dir), { withFileTypes: true })) {
12
+ const path = join(dir, entry.name);
13
+ if (entry.isDirectory()) walkTests(path, found);
14
+ else if (entry.name.endsWith(".test.ts")) found.push(path);
15
+ }
16
+ return found;
17
+ };
18
+
19
+ /** The eval project's config, resolved from this file so the cwd cannot move it. */
20
+ const EVAL_CONFIG = fileURLToPath(new URL("../evals/vitest.config.ts", import.meta.url));
21
+
22
+ /** The unit project's collected file ids. */
23
+ const unitSpecs = async (): Promise<readonly string[]> => {
24
+ const vitest = await createVitest({ root: PACKAGE_ROOT, watch: false });
25
+ try {
26
+ return (await vitest.globTestSpecifications()).map((spec) => spec.moduleId);
27
+ } finally {
28
+ await vitest.close();
29
+ }
30
+ };
31
+
32
+ /** The eval project's collected file ids and its resolved project config. */
33
+ const evalSpecs = async () => {
34
+ const vitest = await createVitest({
35
+ config: EVAL_CONFIG,
36
+ watch: false,
37
+ });
38
+ try {
39
+ const specs = await vitest.globTestSpecifications();
40
+ return { ids: specs.map((spec) => spec.moduleId), config: vitest.projects.at(0)?.config };
41
+ } finally {
42
+ await vitest.close();
43
+ }
44
+ };
45
+
46
+ it("the unit project's file set is the source tree, and nothing else", async () => {
47
+ const vitest = await createVitest({ root: PACKAGE_ROOT, watch: false });
48
+ try {
49
+ const specs = await vitest.globTestSpecifications();
50
+ const collected = specs.map((spec) => relative(PACKAGE_ROOT, spec.moduleId)).sort();
51
+
52
+ expect(collected).toEqual(walkTests("src").sort());
53
+ expect(specs.some((spec) => spec.moduleId.includes("/evals/"))).toBe(false);
54
+ expect(vitest.projects.at(0)?.config.name).toBe("tracker");
55
+ } finally {
56
+ await vitest.close();
57
+ }
58
+ });
59
+
60
+ it("the eval project collects exactly the eval tree and keeps isolation", async () => {
61
+ const { ids, config } = await evalSpecs();
62
+
63
+ expect(ids).toHaveLength(22);
64
+ expect(ids.every((id) => id.includes("/evals/"))).toBe(true);
65
+ expect(config?.name).toBe("tracker-evals");
66
+ expect(config?.isolate).toBe(true);
67
+ expect(config?.include).toEqual(["**/*.test.ts"]);
68
+ });
69
+
70
+ it("the two projects are disjoint", async () => {
71
+ const unit = new Set(await unitSpecs());
72
+ const { ids } = await evalSpecs();
73
+
74
+ expect(ids.filter((id) => unit.has(id))).toEqual([]);
75
+ });
package/src/index.test.ts CHANGED
@@ -9,9 +9,7 @@ import {
9
9
  type AgentBeforeSettleEvent,
10
10
  type AgentToolResult,
11
11
  type CompactOptions,
12
- type ExtensionAPI,
13
12
  type ExtensionToolContext,
14
- type Theme,
15
13
  type ToolDefinition,
16
14
  } from "@earendil-works/pi-coding-agent";
17
15
  import type {
@@ -24,8 +22,10 @@ import type {
24
22
  import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
25
23
  import { Effect } from "effect";
26
24
  import * as FileSystem from "effect/FileSystem";
25
+ import { themeDouble } from "@ftrdotdev/pi-test-kit";
26
+ import { trackerApiDouble, trackerCtxDouble } from "../test-support/doubles.ts";
27
27
  import { join } from "node:path";
28
- import { describe, expect, it } from "vitest";
28
+ import { describe, expect, it, vi } from "vitest";
29
29
  import {
30
30
  NEEDS_CONTEXT_LABEL,
31
31
  NEEDS_NONE_LABEL,
@@ -40,6 +40,12 @@ import type { TrackerToolDetails, TrackerToolParams } from "./presentation/tool-
40
40
  */
41
41
  const AGENT_DIR_ENV = "PI_CODING_AGENT_DIR";
42
42
 
43
+ /** The agent directory the runner started with; a stub must not outlive its test. */
44
+ const AGENT_DIR_AT_MODULE_LOAD = process.env[AGENT_DIR_ENV];
45
+
46
+ /** The console functions the runner started with; a capture must not outlive its test. */
47
+ const REAL_LOG = console.log;
48
+
43
49
  interface Harness {
44
50
  readonly tool: ToolDefinition<any, unknown, any>;
45
51
  readonly ctx: ExtensionToolContext;
@@ -127,7 +133,7 @@ const prepareAgentDir = (config: unknown): Promise<string> =>
127
133
  */
128
134
  const makeHarness = async (options: HarnessOptions = {}): Promise<Harness> => {
129
135
  const agentDir = await prepareAgentDir(options.config);
130
- process.env[AGENT_DIR_ENV] = agentDir;
136
+ vi.stubEnv(AGENT_DIR_ENV, agentDir);
131
137
 
132
138
  let registered: ToolDefinition<any, unknown, any> | undefined;
133
139
  const handlers = new Map<string, (event: any, ctx: any) => unknown>();
@@ -142,7 +148,7 @@ const makeHarness = async (options: HarnessOptions = {}): Promise<Harness> => {
142
148
  classify: async (_model, context) => choiceResult(1, context),
143
149
  };
144
150
 
145
- const api = {
151
+ const api = trackerApiDouble({
146
152
  registerTool: (tool: ToolDefinition<any, unknown, any>) => {
147
153
  registered = tool;
148
154
  },
@@ -159,12 +165,12 @@ const makeHarness = async (options: HarnessOptions = {}): Promise<Harness> => {
159
165
  sendUserMessage: (content: unknown) => {
160
166
  userSends.push(content);
161
167
  },
162
- } as unknown as ExtensionAPI;
168
+ });
163
169
 
164
170
  tracker(api);
165
- if (!registered) throw new Error("tracker did not register a tool");
171
+ if (registered === undefined) throw new Error("tracker did not register a tool");
166
172
 
167
- const ctx = {
173
+ const ctx = trackerCtxDouble({
168
174
  ui: {
169
175
  setWidget: () => {},
170
176
  notify: (message: string, severity?: string) => {
@@ -176,17 +182,19 @@ const makeHarness = async (options: HarnessOptions = {}): Promise<Harness> => {
176
182
  compact: (opts?: CompactOptions) => {
177
183
  compacts.push(opts ?? {});
178
184
  },
179
- } as unknown as ExtensionToolContext;
185
+ });
180
186
 
181
187
  const settle = async (event: Partial<AgentBeforeSettleEvent> = {}): Promise<void> => {
182
188
  const handler = handlers.get("agent_before_settle");
183
- if (!handler) throw new Error("tracker did not register an agent_before_settle handler");
189
+ if (handler === undefined)
190
+ throw new Error("tracker did not register an agent_before_settle handler");
184
191
  await handler({ type: "agent_before_settle", outcome: "completed", ...event }, ctx);
185
192
  };
186
193
 
187
194
  const compactFailed = async (aborted: boolean): Promise<void> => {
188
195
  const handler = handlers.get("session_compact_failed");
189
- if (!handler) throw new Error("tracker did not register a session_compact_failed handler");
196
+ if (handler === undefined)
197
+ throw new Error("tracker did not register a session_compact_failed handler");
190
198
  await handler({ type: "session_compact_failed", aborted }, ctx);
191
199
  };
192
200
 
@@ -217,12 +225,7 @@ const textOf = (result: AgentToolResult<TrackerToolDetails>): string => {
217
225
  };
218
226
 
219
227
  /** Identity theme: styles pass text through, so assertions search plain text. */
220
- const identityTheme = {
221
- fg: (_color: string, text: string): string => text,
222
- bold: (text: string): string => text,
223
- strikethrough: (text: string): string => text,
224
- style: (text: string): string => text,
225
- } as unknown as Theme;
228
+ const identityTheme = themeDouble();
226
229
 
227
230
  /** Render a tool result through the registered `renderResult`. */
228
231
  const renderList = (
@@ -242,24 +245,17 @@ const renderList = (
242
245
 
243
246
  /**
244
247
  * Capture everything the tracker's Effect logger writes while `body` runs.
245
- * Vitest's console proxy defeats `vi.spyOn`, so replace the methods directly.
248
+ * The spies are reset by the harness's restore policy, so the helper leaves the
249
+ * console as it found it without a `finally`.
246
250
  */
247
251
  const captureConsole = async (body: () => Promise<void>): Promise<string[]> => {
248
252
  const lines: string[] = [];
249
- const originalLog = console.log;
250
- const originalError = console.error;
251
- console.log = (...args: unknown[]) => {
252
- lines.push(args.map(String).join(" "));
253
- };
254
- console.error = (...args: unknown[]) => {
253
+ const record = (...args: unknown[]) => {
255
254
  lines.push(args.map(String).join(" "));
256
255
  };
257
- try {
258
- await body();
259
- } finally {
260
- console.log = originalLog;
261
- console.error = originalError;
262
- }
256
+ vi.spyOn(console, "log").mockImplementation(record);
257
+ vi.spyOn(console, "error").mockImplementation(record);
258
+ await body();
263
259
  return lines;
264
260
  };
265
261
 
@@ -280,6 +276,10 @@ describe("tracker tool bridge", () => {
280
276
  expect(textOf(result)).toContain("Work:1 (completed)");
281
277
  });
282
278
 
279
+ it("the agent-directory override does not leak into the next test", () => {
280
+ expect(process.env[AGENT_DIR_ENV]).toBe(AGENT_DIR_AT_MODULE_LOAD);
281
+ });
282
+
283
283
  it("keeps the title patch for the scalar update_items form", async () => {
284
284
  const harness = await makeHarness();
285
285
  await run(harness, { action: "create_list", name: "Work", initial_items: [{ title: "old" }] });
@@ -692,6 +692,11 @@ describe("tracker smart-compaction bridge", () => {
692
692
  expect(lines).toEqual([]);
693
693
  });
694
694
 
695
+ it("the captured console is not a mock after the capture block", () => {
696
+ expect(vi.isMockFunction(console.log)).toBe(false);
697
+ expect(console.log).toBe(REAL_LOG);
698
+ });
699
+
695
700
  it("a raised needsContextProbabilityThreshold compacts an answer the default would keep", async () => {
696
701
  const harness = await makeHarness({
697
702
  registry: compactRegistry(0.6),