@ftrdotdev/pi-tracker 0.5.2 → 0.7.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 (39) hide show
  1. package/README.md +136 -46
  2. package/package.json +8 -2
  3. package/src/compaction/candidate.test.ts +191 -0
  4. package/src/compaction/candidate.ts +105 -0
  5. package/src/compaction/classifier.test.ts +422 -0
  6. package/src/compaction/classifier.ts +198 -0
  7. package/src/compaction/completion.test.ts +257 -0
  8. package/src/compaction/completion.ts +94 -0
  9. package/src/compaction/decision-record.test.ts +91 -0
  10. package/src/compaction/decision-record.ts +101 -0
  11. package/src/compaction/digest.test.ts +185 -0
  12. package/src/compaction/digest.ts +158 -0
  13. package/src/compaction/footprint.test.ts +135 -0
  14. package/src/compaction/footprint.ts +387 -0
  15. package/src/compaction/observations.test.ts +199 -0
  16. package/src/compaction/observations.ts +348 -0
  17. package/src/compaction/pointer.test.ts +26 -0
  18. package/src/compaction/pointer.ts +15 -0
  19. package/src/compaction/rules.test.ts +253 -0
  20. package/src/compaction/rules.ts +188 -0
  21. package/src/compaction/settings.test.ts +315 -0
  22. package/src/compaction/settings.ts +185 -0
  23. package/src/compaction/settle.test.ts +370 -0
  24. package/src/compaction/settle.ts +150 -0
  25. package/src/{deps.test.ts → core/deps.test.ts} +1 -1
  26. package/src/{domain.test.ts → core/domain.test.ts} +42 -9
  27. package/src/{domain.ts → core/domain.ts} +73 -8
  28. package/src/{persistence.test.ts → core/persistence.test.ts} +7 -7
  29. package/src/{store.test.ts → core/store.test.ts} +116 -50
  30. package/src/{store.ts → core/store.ts} +92 -31
  31. package/src/index.test.ts +728 -84
  32. package/src/index.ts +237 -49
  33. package/src/{tool-metadata.test.ts → presentation/tool-metadata.test.ts} +264 -49
  34. package/src/presentation/tool-metadata.ts +675 -0
  35. package/src/{ui.test.ts → presentation/ui.test.ts} +128 -9
  36. package/src/{ui.ts → presentation/ui.ts} +123 -30
  37. package/src/tool-metadata.ts +0 -452
  38. /package/src/{deps.ts → core/deps.ts} +0 -0
  39. /package/src/{persistence.ts → core/persistence.ts} +0 -0
package/src/index.test.ts CHANGED
@@ -1,51 +1,206 @@
1
1
  /**
2
2
  * Bridge tests for `src/index.ts`. The store and the planner have their own
3
3
  * suites; these tests pin the thin wiring between them, including the result
4
- * contract that both `update_item` forms report an affected-items array. That
4
+ * contract that both `update_items` forms report an affected-items array. That
5
5
  * contract broke once: the scalar form returned one `TodoItem`, the renderer
6
6
  * called `.map` on it, and the tool failed with `items.map is not a function`.
7
7
  */
8
- import type {
9
- AgentToolResult,
10
- ExtensionAPI,
11
- ExtensionToolContext,
12
- ToolDefinition,
8
+ import {
9
+ type AgentBeforeSettleEvent,
10
+ type AgentToolResult,
11
+ type CompactOptions,
12
+ type ExtensionAPI,
13
+ type ExtensionToolContext,
14
+ type Theme,
15
+ type ToolDefinition,
13
16
  } from "@earendil-works/pi-coding-agent";
17
+ import type {
18
+ ClassifierApi,
19
+ ClassifierChoiceAnswer,
20
+ ClassifierModel,
21
+ ClassifierResult,
22
+ JsonObject,
23
+ } from "@earendil-works/pi-ai";
24
+ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
25
+ import { Effect } from "effect";
26
+ import * as FileSystem from "effect/FileSystem";
27
+ import { join } from "node:path";
14
28
  import { describe, expect, it } from "vitest";
29
+ import {
30
+ NEEDS_CONTEXT_LABEL,
31
+ NEEDS_NONE_LABEL,
32
+ type ClassifierRegistry,
33
+ } from "./compaction/classifier.ts";
15
34
  import tracker from "./index.ts";
16
- import type { TrackerToolDetails, TrackerToolParams } from "./tool-metadata.ts";
35
+ import type { TrackerToolDetails, TrackerToolParams } from "./presentation/tool-metadata.ts";
36
+
37
+ /**
38
+ * The variable `getAgentDir()` reads. Pi 1.0.2 does not re-export the
39
+ * `ENV_AGENT_DIR` constant from its package root, so its value is inlined here.
40
+ */
41
+ const AGENT_DIR_ENV = "PI_CODING_AGENT_DIR";
17
42
 
18
43
  interface Harness {
19
44
  readonly tool: ToolDefinition<any, unknown, any>;
20
45
  readonly ctx: ExtensionToolContext;
21
46
  /** Every persisted snapshot, in the order the session received it. */
22
47
  readonly appends: unknown[];
48
+ /** Every `ctx.compact` call's options, in order. */
49
+ readonly compacts: CompactOptions[];
50
+ /** Every `ctx.ui.notify` call. */
51
+ readonly notifications: Array<{ readonly message: string; readonly severity?: string }>;
52
+ /** Every `pi.sendMessage` call. */
53
+ readonly sends: Array<{ readonly message: any; readonly options?: any }>;
54
+ /** Every `pi.sendUserMessage` call. */
55
+ readonly userSends: unknown[];
56
+ /** Invoke the captured `agent_before_settle` handler. */
57
+ readonly settle: (event?: Partial<AgentBeforeSettleEvent>) => Promise<void>;
58
+ /** Invoke the captured `session_compact_failed` handler. */
59
+ readonly compactFailed: (aborted: boolean) => Promise<void>;
60
+ }
61
+
62
+ interface HarnessOptions {
63
+ /** Classifier registry double; defaults to one with no available classifier. */
64
+ readonly registry?: ClassifierRegistry;
65
+ /** Parsed contents for the temp `tui.json`; omitted means no config file. */
66
+ readonly config?: unknown;
23
67
  }
24
68
 
69
+ const classifierModel = (provider: string, id: string): ClassifierModel<ClassifierApi> => ({
70
+ id,
71
+ name: id,
72
+ api: "typesafe-system-one",
73
+ provider,
74
+ baseUrl: "https://example.invalid",
75
+ input: ["text"],
76
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
77
+ type: "classifier",
78
+ contextWindow: 8192,
79
+ });
80
+
81
+ /** Answer every question in the classifier context with the same needs mass. */
82
+ const choiceResult = (
83
+ needsMass: number,
84
+ context: { readonly questions: Record<string, unknown> },
85
+ confidence = 1,
86
+ ): ClassifierResult => {
87
+ const answers: Record<string, ClassifierChoiceAnswer> = {};
88
+ for (const key of Object.keys(context.questions)) {
89
+ answers[key] = {
90
+ type: "choice",
91
+ choice: needsMass >= 0.5 ? NEEDS_CONTEXT_LABEL : NEEDS_NONE_LABEL,
92
+ probabilities: { [NEEDS_CONTEXT_LABEL]: needsMass, [NEEDS_NONE_LABEL]: 1 - needsMass },
93
+ confidence,
94
+ };
95
+ }
96
+ return {
97
+ api: "typesafe-system-one",
98
+ provider: "typesafe",
99
+ model: "jev-latest",
100
+ answers,
101
+ stopReason: "stop",
102
+ timestamp: 0,
103
+ };
104
+ };
105
+
106
+ /** Create a temp agent directory (and optional `tui.json`) via the FileSystem service. */
107
+ const prepareAgentDir = (config: unknown): Promise<string> =>
108
+ Effect.runPromise(
109
+ Effect.gen(function* () {
110
+ const fs = yield* FileSystem.FileSystem;
111
+ const directory = yield* fs.makeTempDirectory({ prefix: "tracker-smart-compaction-" });
112
+ if (config !== undefined) {
113
+ yield* fs.writeFileString(join(directory, "tui.json"), JSON.stringify(config));
114
+ }
115
+ return directory;
116
+ }).pipe(Effect.provide(NodeFileSystem.layer)),
117
+ );
118
+
25
119
  /**
26
120
  * Register the extension against a minimal fake API and return the captured
27
- * tool plus a context that satisfies the paths `execute` touches (widget
28
- * refresh and persistence).
121
+ * tool plus a context that satisfies the paths `execute`, the widget refresh,
122
+ * persistence, and the settle handler touch.
123
+ *
124
+ * Sets the agent-dir environment variable to a fresh temp directory before the
125
+ * factory runs, so the settings reader never touches the developer's real
126
+ * `~/.pi/agent/tui.json`.
29
127
  */
30
- const makeHarness = (): Harness => {
128
+ const makeHarness = async (options: HarnessOptions = {}): Promise<Harness> => {
129
+ const agentDir = await prepareAgentDir(options.config);
130
+ process.env[AGENT_DIR_ENV] = agentDir;
131
+
31
132
  let registered: ToolDefinition<any, unknown, any> | undefined;
133
+ const handlers = new Map<string, (event: any, ctx: any) => unknown>();
32
134
  const appends: unknown[] = [];
135
+ const compacts: CompactOptions[] = [];
136
+ const notifications: Array<{ message: string; severity?: string }> = [];
137
+ const sends: Array<{ message: any; options?: any }> = [];
138
+ const userSends: unknown[] = [];
139
+
140
+ const registry: ClassifierRegistry = options.registry ?? {
141
+ getAvailableOfType: async () => [],
142
+ classify: async (_model, context) => choiceResult(1, context),
143
+ };
144
+
33
145
  const api = {
34
146
  registerTool: (tool: ToolDefinition<any, unknown, any>) => {
35
147
  registered = tool;
36
148
  },
37
149
  registerCommand: () => {},
38
- on: () => {},
150
+ on: (event: string, handler: (event: any, ctx: any) => unknown) => {
151
+ handlers.set(event, handler);
152
+ },
39
153
  appendEntry: (_type: string, data: unknown) => {
40
154
  appends.push(data);
41
155
  },
156
+ sendMessage: (message: any, options?: any) => {
157
+ sends.push({ message, options });
158
+ },
159
+ sendUserMessage: (content: unknown) => {
160
+ userSends.push(content);
161
+ },
42
162
  } as unknown as ExtensionAPI;
163
+
43
164
  tracker(api);
44
165
  if (!registered) throw new Error("tracker did not register a tool");
166
+
45
167
  const ctx = {
46
- ui: { setWidget: () => {}, notify: () => {} },
168
+ ui: {
169
+ setWidget: () => {},
170
+ notify: (message: string, severity?: string) => {
171
+ notifications.push({ message, ...(severity === undefined ? {} : { severity }) });
172
+ },
173
+ },
174
+ modelRegistry: registry,
175
+ signal: undefined,
176
+ compact: (opts?: CompactOptions) => {
177
+ compacts.push(opts ?? {});
178
+ },
47
179
  } as unknown as ExtensionToolContext;
48
- return { tool: registered, ctx, appends };
180
+
181
+ const settle = async (event: Partial<AgentBeforeSettleEvent> = {}): Promise<void> => {
182
+ const handler = handlers.get("agent_before_settle");
183
+ if (!handler) throw new Error("tracker did not register an agent_before_settle handler");
184
+ await handler({ type: "agent_before_settle", outcome: "completed", ...event }, ctx);
185
+ };
186
+
187
+ const compactFailed = async (aborted: boolean): Promise<void> => {
188
+ const handler = handlers.get("session_compact_failed");
189
+ if (!handler) throw new Error("tracker did not register a session_compact_failed handler");
190
+ await handler({ type: "session_compact_failed", aborted }, ctx);
191
+ };
192
+
193
+ return {
194
+ tool: registered,
195
+ ctx,
196
+ appends,
197
+ compacts,
198
+ notifications,
199
+ sends,
200
+ userSends,
201
+ settle,
202
+ compactFailed,
203
+ };
49
204
  };
50
205
 
51
206
  const run = (
@@ -61,16 +216,40 @@ const textOf = (result: AgentToolResult<TrackerToolDetails>): string => {
61
216
  return block?.type === "text" ? block.text : "";
62
217
  };
63
218
 
219
+ /** 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;
226
+
227
+ /** Render a tool result through the registered `renderResult`. */
228
+ const renderList = (
229
+ harness: Harness,
230
+ result: AgentToolResult<TrackerToolDetails>,
231
+ expanded: boolean,
232
+ ): string =>
233
+ harness.tool.renderResult!(
234
+ result,
235
+ { expanded, isPartial: false },
236
+ identityTheme,
237
+ harness.ctx as never,
238
+ )
239
+ .render(400)
240
+ .join("\n")
241
+ .replace(/\s+/g, " ");
242
+
64
243
  describe("tracker tool bridge", () => {
65
- it("returns an affected-items array for the scalar update_item form", async () => {
66
- const harness = makeHarness();
244
+ it("returns an affected-items array for the scalar update_items form", async () => {
245
+ const harness = await makeHarness();
67
246
  await run(harness, {
68
247
  action: "create_list",
69
248
  name: "Work",
70
- initial_items: ["write plan", "ship it"],
249
+ initial_items: [{ title: "write plan" }, { title: "ship it" }],
71
250
  });
72
251
 
73
- const result = await run(harness, { action: "update_item", item_id: "Work:1", done: true });
252
+ const result = await run(harness, { action: "update_items", item_id: "Work:1", done: true });
74
253
 
75
254
  expect(result.details?.items).toHaveLength(1);
76
255
  expect(result.details?.items?.[0]?.done).toBe(true);
@@ -78,52 +257,60 @@ describe("tracker tool bridge", () => {
78
257
  expect(textOf(result)).toContain("Work:1 (completed)");
79
258
  });
80
259
 
81
- it("keeps the text patch for the scalar update_item form", async () => {
82
- const harness = makeHarness();
83
- await run(harness, { action: "create_list", name: "Work", initial_items: ["old"] });
260
+ it("keeps the title patch for the scalar update_items form", async () => {
261
+ const harness = await makeHarness();
262
+ await run(harness, { action: "create_list", name: "Work", initial_items: [{ title: "old" }] });
84
263
 
85
- const result = await run(harness, { action: "update_item", item_id: "Work:1", text: "new" });
264
+ const result = await run(harness, { action: "update_items", item_id: "Work:1", title: "new" });
86
265
 
87
266
  expect(result.details?.items).toHaveLength(1);
88
- expect(result.details?.items?.[0]?.text).toBe("new");
89
- expect(textOf(result)).toContain("Work:1 (text: new)");
267
+ expect(result.details?.items?.[0]?.title).toBe("new");
268
+ expect(textOf(result)).toContain("Work:1 (title: new)");
90
269
  });
91
270
 
92
- it("returns one entry per patch for the batch update_item form", async () => {
93
- const harness = makeHarness();
94
- await run(harness, { action: "create_list", name: "Work", initial_items: ["a", "b", "c"] });
271
+ it("returns one entry per patch for the batch update_items form", async () => {
272
+ const harness = await makeHarness();
273
+ await run(harness, {
274
+ action: "create_list",
275
+ name: "Work",
276
+ initial_items: [{ title: "a" }, { title: "b" }, { title: "c" }],
277
+ });
95
278
 
96
279
  const result = await run(harness, {
97
- action: "update_item",
280
+ action: "update_items",
98
281
  list_id: 1,
99
282
  items: [
100
283
  { item_id: "Work:1", done: true },
101
- { item_id: "Work:3", text: "cee" },
284
+ { item_id: "Work:3", title: "cee" },
102
285
  ],
103
286
  });
104
287
 
105
288
  expect(result.details?.items).toHaveLength(2);
106
289
  expect(textOf(result)).toContain("Updated 2 items");
107
- expect(textOf(result)).toContain("Work:3 (text: cee)");
290
+ expect(textOf(result)).toContain("Work:3 (title: cee)");
108
291
  });
109
292
 
110
293
  it("shows id-based references in the list output", async () => {
111
- const harness = makeHarness();
294
+ const harness = await makeHarness();
112
295
  await run(harness, {
113
296
  action: "create_list",
114
297
  name: "Work",
115
- initial_items: ["write plan", "ship it"],
298
+ initial_items: [{ title: "write plan" }, { title: "ship it" }],
116
299
  });
117
300
 
118
- await run(harness, { action: "update_item", item_id: "Work:2", done: true });
301
+ await run(harness, { action: "update_items", item_id: "Work:2", done: true });
119
302
  const result = await run(harness, { action: "list" });
120
303
 
121
304
  expect(textOf(result)).toContain("[x] #Work:2: ship it");
122
305
  });
123
306
 
124
307
  it("shows stable ids after a removal", async () => {
125
- const harness = makeHarness();
126
- await run(harness, { action: "create_list", name: "Work", initial_items: ["a", "b", "c"] });
308
+ const harness = await makeHarness();
309
+ await run(harness, {
310
+ action: "create_list",
311
+ name: "Work",
312
+ initial_items: [{ title: "a" }, { title: "b" }, { title: "c" }],
313
+ });
127
314
 
128
315
  await run(harness, { action: "remove_item", item_id: "Work:1" });
129
316
  const result = await run(harness, { action: "list" });
@@ -134,28 +321,43 @@ describe("tracker tool bridge", () => {
134
321
  expect(textOf(result)).not.toContain("#Work:1");
135
322
  });
136
323
 
324
+ it("shows the full description in the expanded list view", async () => {
325
+ const harness = await makeHarness();
326
+ const description = "detail ".repeat(30).trim();
327
+ await run(harness, { action: "create_list", name: "Work" });
328
+ await run(harness, {
329
+ action: "add_items",
330
+ list_id: 1,
331
+ items: [{ title: "big", description }],
332
+ });
333
+ const result = await run(harness, { action: "list" });
334
+
335
+ expect(renderList(harness, result, true)).toContain(description);
336
+ expect(renderList(harness, result, false)).not.toContain(description);
337
+ });
338
+
137
339
  it("reports an error result for a missing item instead of throwing", async () => {
138
- const harness = makeHarness();
139
- await run(harness, { action: "create_list", name: "Work", initial_items: ["only"] });
340
+ const harness = await makeHarness();
341
+ await run(harness, { action: "create_list", name: "Work", initial_items: [{ title: "only" }] });
140
342
 
141
- const result = await run(harness, { action: "update_item", item_id: "Work:9", done: true });
343
+ const result = await run(harness, { action: "update_items", item_id: "Work:9", done: true });
142
344
 
143
345
  expect(result.details?.error).toContain("Work:9");
144
346
  expect(result.content[0]).toMatchObject({ type: "text" });
145
347
  });
146
348
 
147
349
  it("accepts dependencies in the object item form", async () => {
148
- const harness = makeHarness();
350
+ const harness = await makeHarness();
149
351
  await run(harness, {
150
352
  action: "create_list",
151
353
  name: "Work",
152
- initial_items: ["a", { text: "b", deps: ["Work:1"] }],
354
+ initial_items: [{ title: "a" }, { title: "b", deps: ["Work:1"] }],
153
355
  });
154
356
 
155
357
  const added = await run(harness, {
156
- action: "add_item",
358
+ action: "add_items",
157
359
  list_id: 1,
158
- text: { text: "c", deps: ["Work:2"] },
360
+ items: [{ title: "c", deps: ["Work:2"] }],
159
361
  });
160
362
 
161
363
  expect(added.details?.error).toBeUndefined();
@@ -163,29 +365,61 @@ describe("tracker tool bridge", () => {
163
365
  expect(textOf(added)).toContain("Work:3");
164
366
  });
165
367
 
368
+ it("carries every nested object field on add_items", async () => {
369
+ const harness = await makeHarness();
370
+ await run(harness, {
371
+ action: "create_list",
372
+ name: "Work",
373
+ initial_items: [{ title: "a" }, { title: "b" }],
374
+ });
375
+
376
+ const added = await run(harness, {
377
+ action: "add_items",
378
+ list_id: 1,
379
+ items: [
380
+ {
381
+ title: "Wire the promotion script",
382
+ description: "Add evals/promote.ts.",
383
+ refs: [{ kind: "path", path: "evals/rules.ts" }],
384
+ produces: [{ path: "evals/promote.ts" }],
385
+ deps: ["Work:1"],
386
+ },
387
+ ],
388
+ });
389
+
390
+ expect(added.details?.error).toBeUndefined();
391
+ expect(added.details?.items?.[0]).toMatchObject({
392
+ title: "Wire the promotion script",
393
+ description: "Add evals/promote.ts.",
394
+ refs: [{ kind: "path", path: "evals/rules.ts" }],
395
+ produces: [{ path: "evals/promote.ts" }],
396
+ deps: ["Work:1"],
397
+ });
398
+ });
399
+
166
400
  it("rejects a malformed dependency reference with an actionable message", async () => {
167
- const harness = makeHarness();
168
- await run(harness, { action: "create_list", name: "Work", initial_items: ["a"] });
401
+ const harness = await makeHarness();
402
+ await run(harness, { action: "create_list", name: "Work", initial_items: [{ title: "a" }] });
169
403
 
170
404
  const result = await run(harness, {
171
- action: "add_item",
405
+ action: "add_items",
172
406
  list_id: 1,
173
- text: { text: "b", deps: ["nonsense"] },
407
+ items: [{ title: "b", deps: ["nonsense"] }],
174
408
  });
175
409
 
176
410
  expect(result.details?.error).toContain("listName:id");
177
411
  });
178
412
 
179
413
  it("names the cycle when a dependency would close one", async () => {
180
- const harness = makeHarness();
414
+ const harness = await makeHarness();
181
415
  await run(harness, {
182
416
  action: "create_list",
183
417
  name: "Work",
184
- initial_items: ["a", { text: "b", deps: ["Work:1"] }],
418
+ initial_items: [{ title: "a" }, { title: "b", deps: ["Work:1"] }],
185
419
  });
186
420
 
187
421
  const result = await run(harness, {
188
- action: "update_item",
422
+ action: "update_items",
189
423
  item_id: "Work:1",
190
424
  deps: ["Work:2"],
191
425
  });
@@ -195,11 +429,15 @@ describe("tracker tool bridge", () => {
195
429
  });
196
430
 
197
431
  it("annotates blocked items and names what is ready", async () => {
198
- const harness = makeHarness();
432
+ const harness = await makeHarness();
199
433
  await run(harness, {
200
434
  action: "create_list",
201
435
  name: "Work",
202
- initial_items: ["a", { text: "b", deps: ["Work:1"] }, { text: "c", deps: ["Work:2"] }],
436
+ initial_items: [
437
+ { title: "a" },
438
+ { title: "b", deps: ["Work:1"] },
439
+ { title: "c", deps: ["Work:2"] },
440
+ ],
203
441
  });
204
442
 
205
443
  const text = textOf(await run(harness, { action: "list" }));
@@ -210,8 +448,12 @@ describe("tracker tool bridge", () => {
210
448
  });
211
449
 
212
450
  it("leaves the list output untouched for a dependency-free list", async () => {
213
- const harness = makeHarness();
214
- await run(harness, { action: "create_list", name: "Work", initial_items: ["a", "b"] });
451
+ const harness = await makeHarness();
452
+ await run(harness, {
453
+ action: "create_list",
454
+ name: "Work",
455
+ initial_items: [{ title: "a" }, { title: "b" }],
456
+ });
215
457
 
216
458
  const text = textOf(await run(harness, { action: "list" }));
217
459
 
@@ -221,31 +463,31 @@ describe("tracker tool bridge", () => {
221
463
  });
222
464
 
223
465
  it("names the blockers when a completion is refused", async () => {
224
- const harness = makeHarness();
466
+ const harness = await makeHarness();
225
467
  await run(harness, {
226
468
  action: "create_list",
227
469
  name: "Work",
228
- initial_items: ["a", { text: "b", deps: ["Work:1"] }],
470
+ initial_items: [{ title: "a" }, { title: "b", deps: ["Work:1"] }],
229
471
  });
230
472
 
231
- const result = await run(harness, { action: "update_item", item_id: "Work:2", done: true });
473
+ const result = await run(harness, { action: "update_items", item_id: "Work:2", done: true });
232
474
 
233
475
  expect(result.details?.error).toContain("Work:1");
234
476
  expect(result.details?.error).toContain("blocked");
235
477
  });
236
478
 
237
479
  it("notes the done dependents when a dependency is reopened", async () => {
238
- const harness = makeHarness();
480
+ const harness = await makeHarness();
239
481
  await run(harness, {
240
482
  action: "create_list",
241
483
  name: "Work",
242
- initial_items: ["a", { text: "b", deps: ["Work:1"] }],
484
+ initial_items: [{ title: "a" }, { title: "b", deps: ["Work:1"] }],
243
485
  });
244
- await run(harness, { action: "update_item", item_id: "Work:1", done: true });
245
- await run(harness, { action: "update_item", item_id: "Work:2", done: true });
486
+ await run(harness, { action: "update_items", item_id: "Work:1", done: true });
487
+ await run(harness, { action: "update_items", item_id: "Work:2", done: true });
246
488
 
247
489
  const text = textOf(
248
- await run(harness, { action: "update_item", item_id: "Work:1", done: false }),
490
+ await run(harness, { action: "update_items", item_id: "Work:1", done: false }),
249
491
  );
250
492
 
251
493
  expect(text).toContain("Note:");
@@ -253,31 +495,31 @@ describe("tracker tool bridge", () => {
253
495
  });
254
496
 
255
497
  it("adds no reopen note when no dependent is done", async () => {
256
- const harness = makeHarness();
498
+ const harness = await makeHarness();
257
499
  await run(harness, {
258
500
  action: "create_list",
259
501
  name: "Work",
260
- initial_items: ["a", { text: "b", deps: ["Work:1"] }],
502
+ initial_items: [{ title: "a" }, { title: "b", deps: ["Work:1"] }],
261
503
  });
262
- await run(harness, { action: "update_item", item_id: "Work:1", done: true });
504
+ await run(harness, { action: "update_items", item_id: "Work:1", done: true });
263
505
 
264
506
  const text = textOf(
265
- await run(harness, { action: "update_item", item_id: "Work:1", done: false }),
507
+ await run(harness, { action: "update_items", item_id: "Work:1", done: false }),
266
508
  );
267
509
 
268
510
  expect(text).not.toContain("Note:");
269
511
  });
270
512
 
271
513
  it("marks a done item whose dependency is open again", async () => {
272
- const harness = makeHarness();
514
+ const harness = await makeHarness();
273
515
  await run(harness, {
274
516
  action: "create_list",
275
517
  name: "Work",
276
- initial_items: ["a", { text: "b", deps: ["Work:1"] }],
518
+ initial_items: [{ title: "a" }, { title: "b", deps: ["Work:1"] }],
277
519
  });
278
- await run(harness, { action: "update_item", item_id: "Work:1", done: true });
279
- await run(harness, { action: "update_item", item_id: "Work:2", done: true });
280
- await run(harness, { action: "update_item", item_id: "Work:1", done: false });
520
+ await run(harness, { action: "update_items", item_id: "Work:1", done: true });
521
+ await run(harness, { action: "update_items", item_id: "Work:2", done: true });
522
+ await run(harness, { action: "update_items", item_id: "Work:1", done: false });
281
523
 
282
524
  const text = textOf(await run(harness, { action: "list" }));
283
525
 
@@ -288,31 +530,35 @@ describe("tracker tool bridge", () => {
288
530
  });
289
531
 
290
532
  it("notes a done item that a dependency edit left waiting", async () => {
291
- const harness = makeHarness();
292
- await run(harness, { action: "create_list", name: "Work", initial_items: ["a", "b"] });
293
- await run(harness, { action: "update_item", item_id: "Work:2", done: true });
533
+ const harness = await makeHarness();
534
+ await run(harness, {
535
+ action: "create_list",
536
+ name: "Work",
537
+ initial_items: [{ title: "a" }, { title: "b" }],
538
+ });
539
+ await run(harness, { action: "update_items", item_id: "Work:2", done: true });
294
540
 
295
541
  const text = textOf(
296
- await run(harness, { action: "update_item", item_id: "Work:2", deps: ["Work:1"] }),
542
+ await run(harness, { action: "update_items", item_id: "Work:2", deps: ["Work:1"] }),
297
543
  );
298
544
 
299
545
  expect(text).toContain("Note: Work:2 is done but now waits on Work:1");
300
546
  });
301
547
 
302
548
  it("names the dependencies a deps edit removed", async () => {
303
- const harness = makeHarness();
549
+ const harness = await makeHarness();
304
550
  await run(harness, {
305
551
  action: "create_list",
306
552
  name: "Work",
307
- initial_items: ["a", { text: "b", deps: ["Work:1"] }, "c"],
553
+ initial_items: [{ title: "a" }, { title: "b", deps: ["Work:1"] }, { title: "c" }],
308
554
  });
309
555
 
310
- const cleared = await run(harness, { action: "update_item", item_id: "Work:2", deps: [] });
556
+ const cleared = await run(harness, { action: "update_items", item_id: "Work:2", deps: [] });
311
557
  expect(textOf(cleared)).toContain("deps cleared (was Work:1)");
312
558
 
313
- await run(harness, { action: "update_item", item_id: "Work:2", deps: ["Work:1"] });
559
+ await run(harness, { action: "update_items", item_id: "Work:2", deps: ["Work:1"] });
314
560
  const replaced = await run(harness, {
315
- action: "update_item",
561
+ action: "update_items",
316
562
  item_id: "Work:2",
317
563
  deps: ["Work:3"],
318
564
  });
@@ -320,14 +566,18 @@ describe("tracker tool bridge", () => {
320
566
  });
321
567
 
322
568
  it("persists overlapping mutations in order", async () => {
323
- const harness = makeHarness();
324
- await run(harness, { action: "create_list", name: "Work", initial_items: ["a", "b"] });
569
+ const harness = await makeHarness();
570
+ await run(harness, {
571
+ action: "create_list",
572
+ name: "Work",
573
+ initial_items: [{ title: "a" }, { title: "b" }],
574
+ });
325
575
 
326
576
  // Two calls in flight at once. The last snapshot the session receives must
327
577
  // be the state after both, or a later restore resurrects an older one.
328
578
  await Promise.all([
329
- run(harness, { action: "update_item", item_id: "Work:1", done: true }),
330
- run(harness, { action: "update_item", item_id: "Work:2", done: true }),
579
+ run(harness, { action: "update_items", item_id: "Work:1", done: true }),
580
+ run(harness, { action: "update_items", item_id: "Work:2", done: true }),
331
581
  ]);
332
582
 
333
583
  const last = harness.appends.at(-1) as {
@@ -341,11 +591,11 @@ describe("tracker tool bridge", () => {
341
591
  });
342
592
 
343
593
  it("shows items in dependency order, not stored order", async () => {
344
- const harness = makeHarness();
594
+ const harness = await makeHarness();
345
595
  await run(harness, {
346
596
  action: "create_list",
347
597
  name: "Work",
348
- initial_items: [{ text: "ship", deps: ["Work:2"] }, "write plan"],
598
+ initial_items: [{ title: "ship", deps: ["Work:2"] }, { title: "write plan" }],
349
599
  });
350
600
 
351
601
  const text = textOf(await run(harness, { action: "list" }));
@@ -356,3 +606,397 @@ describe("tracker tool bridge", () => {
356
606
  expect(text).toContain("#Work:2: write plan");
357
607
  });
358
608
  });
609
+
610
+ describe("tracker smart-compaction bridge", () => {
611
+ const available: readonly ClassifierModel<ClassifierApi>[] = [
612
+ classifierModel("typesafe", "jev-latest"),
613
+ ];
614
+
615
+ const compactRegistry = (
616
+ needsMass: number,
617
+ onDescribe?: (state: JsonObject) => void,
618
+ confidence = 1,
619
+ ): ClassifierRegistry => ({
620
+ getAvailableOfType: async () => available,
621
+ classify: async (_model, context) => {
622
+ onDescribe?.(context.state);
623
+ return choiceResult(needsMass, context, confidence);
624
+ },
625
+ });
626
+
627
+ /** Create a two-item dependency list and complete the first item. */
628
+ const completeFirst = async (harness: Harness): Promise<void> => {
629
+ await run(harness, {
630
+ action: "create_list",
631
+ name: "Work",
632
+ initial_items: [{ title: "first" }, { title: "second", deps: ["Work:1"] }],
633
+ });
634
+ await run(harness, { action: "update_items", item_id: "Work:1", done: true });
635
+ };
636
+
637
+ it("a completed item with a compact verdict starts pi's compaction at the settle boundary", async () => {
638
+ const harness = await makeHarness({ registry: compactRegistry(0.1) });
639
+ await completeFirst(harness);
640
+
641
+ await harness.settle({ outcome: "completed" });
642
+
643
+ expect(harness.compacts).toHaveLength(1);
644
+ expect(harness.compacts[0]?.customInstructions).toBeUndefined();
645
+ expect(typeof harness.compacts[0]?.onComplete).toBe("function");
646
+ expect(typeof harness.compacts[0]?.onError).toBe("function");
647
+ });
648
+
649
+ it("a keep verdict leaves the run untouched", async () => {
650
+ const harness = await makeHarness({ registry: compactRegistry(0.9) });
651
+ await completeFirst(harness);
652
+
653
+ await harness.settle();
654
+
655
+ expect(harness.compacts).toHaveLength(0);
656
+ });
657
+
658
+ it("a raised needsContextProbabilityThreshold compacts an answer the default would keep", async () => {
659
+ const harness = await makeHarness({
660
+ registry: compactRegistry(0.6),
661
+ config: { smartCompaction: { needsContextProbabilityThreshold: 0.9 } },
662
+ });
663
+ await completeFirst(harness);
664
+
665
+ await harness.settle();
666
+
667
+ expect(harness.compacts).toHaveLength(1);
668
+ });
669
+
670
+ it("a lowered needsContextProbabilityThreshold keeps an answer the default would compact", async () => {
671
+ const harness = await makeHarness({
672
+ registry: compactRegistry(0.45),
673
+ config: { smartCompaction: { needsContextProbabilityThreshold: 0.2 } },
674
+ });
675
+ await completeFirst(harness);
676
+
677
+ await harness.settle();
678
+
679
+ expect(harness.compacts).toHaveLength(0);
680
+ });
681
+
682
+ it("keeps context when the classifier answer is below the confidence floor", async () => {
683
+ const harness = await makeHarness({
684
+ registry: compactRegistry(0.1, undefined, 0.2),
685
+ config: { smartCompaction: { minAnswerConfidence: 0.9 } },
686
+ });
687
+ await completeFirst(harness);
688
+
689
+ await harness.settle();
690
+
691
+ expect(harness.compacts).toHaveLength(0);
692
+ });
693
+
694
+ it("compacts when the classifier answer reaches the confidence floor", async () => {
695
+ const harness = await makeHarness({
696
+ registry: compactRegistry(0.1, undefined, 0.9),
697
+ config: { smartCompaction: { minAnswerConfidence: 0.5 } },
698
+ });
699
+ await completeFirst(harness);
700
+
701
+ await harness.settle();
702
+
703
+ expect(harness.compacts).toHaveLength(1);
704
+ });
705
+
706
+ it("judges the whole ready frontier and keeps context when any candidate needs it", async () => {
707
+ let questions: Record<string, unknown> = {};
708
+ const harness = await makeHarness({
709
+ registry: {
710
+ getAvailableOfType: async () => available,
711
+ classify: async (_model, context) => {
712
+ questions = context.questions;
713
+ const answers: Record<string, ClassifierChoiceAnswer> = {};
714
+ // Work:2 (dependent) says no; Work:3 (independent) says yes.
715
+ for (const key of Object.keys(context.questions)) {
716
+ const needsMass = key.includes("Work_3") ? 0.9 : 0.1;
717
+ answers[key] = {
718
+ type: "choice",
719
+ choice: needsMass >= 0.5 ? NEEDS_CONTEXT_LABEL : NEEDS_NONE_LABEL,
720
+ probabilities: {
721
+ [NEEDS_CONTEXT_LABEL]: needsMass,
722
+ [NEEDS_NONE_LABEL]: 1 - needsMass,
723
+ },
724
+ confidence: 1,
725
+ };
726
+ }
727
+ return {
728
+ api: "typesafe-system-one",
729
+ provider: "typesafe",
730
+ model: "jev-latest",
731
+ answers,
732
+ stopReason: "stop",
733
+ timestamp: 0,
734
+ };
735
+ },
736
+ },
737
+ });
738
+ await run(harness, {
739
+ action: "create_list",
740
+ name: "Work",
741
+ initial_items: [
742
+ { title: "first" },
743
+ { title: "second", deps: ["Work:1"] },
744
+ { title: "third" },
745
+ ],
746
+ });
747
+ await run(harness, { action: "update_items", item_id: "Work:1", done: true });
748
+
749
+ await harness.settle();
750
+
751
+ expect(Object.keys(questions).length).toBe(2);
752
+ expect(harness.compacts).toHaveLength(0);
753
+ });
754
+
755
+ it("compacts when every judged candidate is self-contained", async () => {
756
+ const harness = await makeHarness({ registry: compactRegistry(0.1) });
757
+ await run(harness, {
758
+ action: "create_list",
759
+ name: "Work",
760
+ initial_items: [
761
+ { title: "first" },
762
+ { title: "second", deps: ["Work:1"] },
763
+ { title: "third" },
764
+ ],
765
+ });
766
+ await run(harness, { action: "update_items", item_id: "Work:1", done: true });
767
+
768
+ await harness.settle();
769
+
770
+ expect(harness.compacts).toHaveLength(1);
771
+ });
772
+
773
+ it("no credential-available classifier leaves the run untouched", async () => {
774
+ let classifyCalls = 0;
775
+ const harness = await makeHarness({
776
+ registry: {
777
+ getAvailableOfType: async () => [],
778
+ classify: async (_model, context) => {
779
+ classifyCalls += 1;
780
+ return choiceResult(0.1, context);
781
+ },
782
+ },
783
+ });
784
+ await completeFirst(harness);
785
+
786
+ await harness.settle();
787
+
788
+ expect(harness.compacts).toHaveLength(0);
789
+ expect(classifyCalls).toBe(0);
790
+ });
791
+
792
+ it("an enabled: false setting leaves the run untouched even when a classifier is available", async () => {
793
+ const harness = await makeHarness({
794
+ registry: compactRegistry(0.1),
795
+ config: { smartCompaction: { enabled: false } },
796
+ });
797
+ await completeFirst(harness);
798
+
799
+ await harness.settle();
800
+
801
+ expect(harness.compacts).toHaveLength(0);
802
+ });
803
+
804
+ it("a settle with no pending completion calls no classifier", async () => {
805
+ let classifyCalls = 0;
806
+ const harness = await makeHarness({
807
+ registry: {
808
+ getAvailableOfType: async () => available,
809
+ classify: async (_model, context) => {
810
+ classifyCalls += 1;
811
+ return choiceResult(0.1, context);
812
+ },
813
+ },
814
+ });
815
+ await run(harness, {
816
+ action: "create_list",
817
+ name: "Work",
818
+ initial_items: [{ title: "first" }, { title: "second", deps: ["Work:1"] }],
819
+ });
820
+
821
+ await harness.settle();
822
+
823
+ expect(classifyCalls).toBe(0);
824
+ expect(harness.compacts).toHaveLength(0);
825
+ });
826
+
827
+ it("one completion yields at most one compaction across settles", async () => {
828
+ const harness = await makeHarness({ registry: compactRegistry(0.1) });
829
+ await completeFirst(harness);
830
+
831
+ await harness.settle();
832
+ await harness.settle();
833
+
834
+ expect(harness.compacts).toHaveLength(1);
835
+ });
836
+
837
+ it("an aborted settle clears the record without compacting", async () => {
838
+ const harness = await makeHarness({ registry: compactRegistry(0.1) });
839
+ await completeFirst(harness);
840
+
841
+ await harness.settle({ outcome: "aborted" });
842
+ await harness.settle({ outcome: "completed" });
843
+
844
+ expect(harness.compacts).toHaveLength(0);
845
+ });
846
+
847
+ it("an errored settle clears the record without compacting", async () => {
848
+ const harness = await makeHarness({ registry: compactRegistry(0.1) });
849
+ await completeFirst(harness);
850
+
851
+ await harness.settle({ outcome: "error" });
852
+ await harness.settle({ outcome: "completed" });
853
+
854
+ expect(harness.compacts).toHaveLength(0);
855
+ });
856
+
857
+ it("the digest centres on the candidate and carries the completed batch as prior work", async () => {
858
+ let captured: JsonObject | undefined;
859
+ const harness = await makeHarness({
860
+ registry: compactRegistry(0.1, (state) => {
861
+ captured = state;
862
+ }),
863
+ });
864
+ await completeFirst(harness);
865
+
866
+ await harness.settle();
867
+
868
+ const digest = captured as unknown as {
869
+ candidates: Array<{ ref: string; class: string }>;
870
+ completed: Array<{ ref: string }>;
871
+ };
872
+ expect(digest.candidates[0]?.ref).toBe("Work:2");
873
+ expect(digest.candidates[0]?.class).toBe("dependent-successor");
874
+ expect(digest.completed).toEqual([{ ref: "Work:1", text: "first" }]);
875
+ });
876
+
877
+ it("a classifier error leaves the run untouched", async () => {
878
+ const harness = await makeHarness({
879
+ registry: {
880
+ getAvailableOfType: async () => available,
881
+ classify: async () => {
882
+ throw new Error("provider unreachable");
883
+ },
884
+ },
885
+ });
886
+ await completeFirst(harness);
887
+
888
+ await harness.settle();
889
+
890
+ expect(harness.compacts).toHaveLength(0);
891
+ });
892
+
893
+ it("an abort signal during classification leaves the run untouched", async () => {
894
+ const controller = new AbortController();
895
+ const harness = await makeHarness({
896
+ registry: {
897
+ getAvailableOfType: async () => available,
898
+ classify: (_model, _context, options) => {
899
+ const signal = options?.signal;
900
+ return new Promise((_resolve, reject) => {
901
+ signal?.addEventListener("abort", () => reject(new Error("aborted")));
902
+ controller.abort();
903
+ });
904
+ },
905
+ },
906
+ });
907
+ harness.ctx.signal = controller.signal;
908
+ await completeFirst(harness);
909
+
910
+ await harness.settle();
911
+
912
+ expect(harness.compacts).toHaveLength(0);
913
+ });
914
+
915
+ it("the hook adds no tracker custom entry and does not change the tool result", async () => {
916
+ const harness = await makeHarness({ registry: compactRegistry(0.1) });
917
+ await run(harness, {
918
+ action: "create_list",
919
+ name: "Work",
920
+ initial_items: [{ title: "first" }, { title: "second", deps: ["Work:1"] }],
921
+ });
922
+
923
+ const result = await run(harness, { action: "update_items", item_id: "Work:1", done: true });
924
+ const appendsBefore = harness.appends.length;
925
+
926
+ await harness.settle();
927
+
928
+ expect(harness.appends).toHaveLength(appendsBefore);
929
+ expect(textOf(result)).toBe("Updated 1 item: Work:1 (completed)");
930
+ });
931
+
932
+ it("compaction completion sends one resume turn naming the next ready item", async () => {
933
+ const harness = await makeHarness({ registry: compactRegistry(0.1) });
934
+ await completeFirst(harness);
935
+ await harness.settle();
936
+
937
+ harness.compacts[0]?.onComplete?.({
938
+ summary: "summary",
939
+ firstKeptEntryId: "entry-1",
940
+ tokensBefore: 100,
941
+ });
942
+
943
+ expect(harness.sends).toHaveLength(1);
944
+ const message = harness.sends[0]?.message as { content: string };
945
+ expect(message.content).toContain("Work:2");
946
+ });
947
+
948
+ it("the resume turn is a continuation message that triggers a turn", async () => {
949
+ const harness = await makeHarness({ registry: compactRegistry(0.1) });
950
+ await completeFirst(harness);
951
+ await harness.settle();
952
+ harness.compacts[0]?.onComplete?.({
953
+ summary: "summary",
954
+ firstKeptEntryId: "entry-1",
955
+ tokensBefore: 100,
956
+ });
957
+
958
+ const message = harness.sends[0]?.message as { customType: string };
959
+ const options = harness.sends[0]?.options as { triggerTurn?: boolean };
960
+ expect(options.triggerTurn).toBe(true);
961
+ expect(message.customType).toBe("tracker/smart-compaction");
962
+ expect(harness.userSends).toHaveLength(0);
963
+ });
964
+
965
+ it("a compaction failure resumes with a warning", async () => {
966
+ const harness = await makeHarness({ registry: compactRegistry(0.1) });
967
+ await completeFirst(harness);
968
+ await harness.settle();
969
+
970
+ await harness.compactFailed(false);
971
+ harness.compacts[0]?.onError?.(new Error("boom"));
972
+
973
+ expect(harness.notifications).toHaveLength(1);
974
+ expect(harness.notifications[0]?.severity).toBe("warning");
975
+ expect(harness.sends).toHaveLength(1);
976
+ });
977
+
978
+ it("a cancelled compaction sends no resume turn", async () => {
979
+ const harness = await makeHarness({ registry: compactRegistry(0.1) });
980
+ await completeFirst(harness);
981
+ await harness.settle();
982
+
983
+ await harness.compactFailed(true);
984
+ harness.compacts[0]?.onError?.(new Error("cancelled"));
985
+
986
+ expect(harness.sends).toHaveLength(0);
987
+ expect(harness.notifications).toHaveLength(1);
988
+ expect(harness.notifications[0]?.severity).toBe("warning");
989
+ });
990
+
991
+ it("the resume turn is delivered once even if the completion callback fires twice", async () => {
992
+ const harness = await makeHarness({ registry: compactRegistry(0.1) });
993
+ await completeFirst(harness);
994
+ await harness.settle();
995
+
996
+ const onComplete = harness.compacts[0]?.onComplete;
997
+ onComplete?.({ summary: "summary", firstKeptEntryId: "entry-1", tokensBefore: 100 });
998
+ onComplete?.({ summary: "summary", firstKeptEntryId: "entry-1", tokensBefore: 100 });
999
+
1000
+ expect(harness.sends).toHaveLength(1);
1001
+ });
1002
+ });