@ftrdotdev/pi-tracker 0.6.0 → 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.
package/src/index.ts CHANGED
@@ -7,6 +7,8 @@ import { Effect, Layer, ManagedRuntime, Option, Result } from "effect";
7
7
  import { join } from "node:path";
8
8
  import { ClassifierGateway } from "./compaction/classifier.ts";
9
9
  import { CompletionObserver } from "./compaction/completion.ts";
10
+ import { DECISION_CUSTOM_TYPE, encodeDecisionRecord } from "./compaction/decision-record.ts";
11
+ import { FootprintRecorder, productionProbe, type ToolEvent } from "./compaction/footprint.ts";
10
12
  import {
11
13
  formatItemRef,
12
14
  parseItemRef,
@@ -16,7 +18,10 @@ import {
16
18
  import { TodoItem, TodoList, TrackerState, emptyState, encodeState } from "./core/domain.ts";
17
19
  import { TrackerPersistence } from "./core/persistence.ts";
18
20
  import { SMART_COMPACTION_CUSTOM_TYPE } from "./compaction/pointer.ts";
19
- import { SMART_COMPACTION_CONFIG_FILE, SmartCompactionSettingsService } from "./compaction/settings.ts";
21
+ import {
22
+ SMART_COMPACTION_CONFIG_FILE,
23
+ SmartCompactionSettingsService,
24
+ } from "./compaction/settings.ts";
20
25
  import { SettleDecider } from "./compaction/settle.ts";
21
26
  import { TrackerError, TrackerStore, type ItemSpec, type UpdateItemPatch } from "./core/store.ts";
22
27
  import {
@@ -24,9 +29,11 @@ import {
24
29
  blockedDoneNote,
25
30
  doneMarkReminder,
26
31
  validateTrackerCall,
32
+ type TrackerItemSpec,
27
33
  type TrackerToolAction,
28
34
  type TrackerToolDetails,
29
35
  type TrackerToolParams,
36
+ type TrackerUpdatePatch,
30
37
  } from "./presentation/tool-metadata.ts";
31
38
  import {
32
39
  displayList,
@@ -63,24 +70,45 @@ const withSettleDecider = <A, E>(
63
70
  f: (decider: SettleDecider["Service"]) => Effect.Effect<A, E>,
64
71
  ): Effect.Effect<A, E, SettleDecider> => Effect.flatMap(SettleDecider, f);
65
72
 
73
+ const withFootprintRecorder = <A, E>(
74
+ f: (recorder: FootprintRecorder["Service"]) => Effect.Effect<A, E>,
75
+ ): Effect.Effect<A, E, FootprintRecorder> => Effect.flatMap(FootprintRecorder, f);
76
+
77
+ /** The bounded `path`/`command` projection of a tool call's arguments. */
78
+ const boundedArgsOf = (value: unknown): ToolEvent["args"] => {
79
+ if (typeof value !== "object" || value === null) return undefined;
80
+ const record = value as { readonly path?: unknown; readonly command?: unknown };
81
+ const path = typeof record.path === "string" && record.path.length > 0 ? record.path : undefined;
82
+ const command =
83
+ typeof record.command === "string" && record.command.length > 0 ? record.command : undefined;
84
+ if (path === undefined && command === undefined) return undefined;
85
+ return {
86
+ ...(path === undefined ? {} : { path }),
87
+ ...(command === undefined ? {} : { command }),
88
+ };
89
+ };
90
+
91
+ /** The tool result's `details`, which carries a write's or edit's unified patch. */
92
+ const detailsOf = (result: unknown): unknown =>
93
+ typeof result === "object" && result !== null
94
+ ? (result as { readonly details?: unknown }).details
95
+ : undefined;
96
+
66
97
  /** Throw for a missing required tool parameter; caught in `execute`. */
67
98
  const requireParam = <T>(value: T | undefined, name: string): T => {
68
99
  if (value === undefined) throw new Error(`${name} is required for this tracker action`);
69
100
  return value;
70
101
  };
71
102
 
72
- /**
73
- * Normalize the tool's item shapes (a text string, an item object, or an array
74
- * of either) into the store's item specs.
75
- */
76
- const toItemSpecs = (raw: NonNullable<TrackerToolParams["text"]>): ItemSpec[] => {
77
- const entries = Array.isArray(raw) ? raw : [raw];
78
- return entries.map((entry) =>
79
- typeof entry === "string"
80
- ? entry
81
- : { text: entry.text, ...(entry.deps === undefined ? {} : { deps: entry.deps }) },
82
- );
83
- };
103
+ /** Project the tool's item objects onto the store's item specs. */
104
+ const toItemSpecs = (items: readonly TrackerItemSpec[]): ItemSpec[] =>
105
+ items.map((item) => ({
106
+ title: item.title,
107
+ ...(item.description === undefined ? {} : { description: item.description }),
108
+ ...(item.refs === undefined ? {} : { refs: item.refs }),
109
+ ...(item.produces === undefined ? {} : { produces: item.produces }),
110
+ ...(item.deps === undefined ? {} : { deps: item.deps }),
111
+ }));
84
112
 
85
113
  // --------------------------------------------------------------------------
86
114
  // Extension
@@ -89,14 +117,16 @@ const toItemSpecs = (raw: NonNullable<TrackerToolParams["text"]>): ItemSpec[] =>
89
117
  export default function (pi: ExtensionAPI): void {
90
118
  // The settings path is resolved inside the factory, so a test can point
91
119
  // ENV_AGENT_DIR at a temp directory before `tracker(api)` runs.
120
+ const probe = productionProbe();
92
121
  const decisionServices = Layer.mergeAll(
93
122
  CompletionObserver.layer,
94
123
  ClassifierGateway.layer,
124
+ FootprintRecorder.layer(probe),
95
125
  SmartCompactionSettingsService.make(join(getAgentDir(), SMART_COMPACTION_CONFIG_FILE)),
96
126
  );
97
127
 
98
128
  const runtime = ManagedRuntime.make(
99
- SettleDecider.layer.pipe(
129
+ SettleDecider.layer(probe).pipe(
100
130
  Layer.provideMerge(Layer.mergeAll(TrackerStore.layer, decisionServices)),
101
131
  Layer.provideMerge(
102
132
  TrackerPersistence.layer((encoded) => pi.appendEntry(CUSTOM_TYPE, encoded)),
@@ -127,31 +157,42 @@ export default function (pi: ExtensionAPI): void {
127
157
  return withStore((store) => store.deleteList(requireParam(params.list_id, "list_id")));
128
158
  case "set_active":
129
159
  return withStore((store) => store.setActiveList(params.list_id ?? null));
130
- case "add_item": {
131
- const specs = toItemSpecs(requireParam(params.text, "text"));
160
+ case "add_items": {
161
+ // Validation guarantees every entry is an item object; the shared
162
+ // `items` field also carries update_items patches, which are rejected
163
+ // for this action.
164
+ const specs = toItemSpecs(
165
+ requireParam(params.items, "items") as readonly TrackerItemSpec[],
166
+ );
132
167
  return withStore((store) => store.addItems(requireParam(params.list_id, "list_id"), specs));
133
168
  }
134
- case "update_item": {
169
+ case "update_items": {
135
170
  if (params.items !== undefined) {
136
171
  // Batch form: list_id + item-id patches within one list (mirrors
137
- // add_item's list_id + text[]). The store resolves each id against
172
+ // add_items' list_id + items). The store resolves each id against
138
173
  // that single list, so the reference's list name must match it.
139
174
  const listId = requireParam(params.list_id, "list_id");
140
- const batch = params.items.map((patch) => ({
175
+ const batch = (params.items as readonly TrackerUpdatePatch[]).map((patch) => ({
141
176
  itemId: patch.item_id,
142
- ...(patch.text !== undefined ? { text: patch.text } : {}),
177
+ ...(patch.title !== undefined ? { title: patch.title } : {}),
178
+ ...(patch.description !== undefined ? { description: patch.description } : {}),
179
+ ...(patch.refs !== undefined ? { refs: patch.refs } : {}),
180
+ ...(patch.produces !== undefined ? { produces: patch.produces } : {}),
143
181
  ...(patch.done !== undefined ? { done: patch.done } : {}),
144
182
  ...(patch.deps !== undefined ? { deps: patch.deps } : {}),
145
183
  }));
146
184
  return withStore((store) => store.updateItems(listId, batch));
147
185
  }
148
186
  const patch: UpdateItemPatch = {
149
- ...(typeof params.text === "string" ? { text: params.text } : {}),
187
+ ...(typeof params.title === "string" ? { title: params.title } : {}),
188
+ ...(params.description !== undefined ? { description: params.description } : {}),
189
+ ...(params.refs !== undefined ? { refs: params.refs } : {}),
190
+ ...(params.produces !== undefined ? { produces: params.produces } : {}),
150
191
  ...(params.done !== undefined ? { done: params.done } : {}),
151
192
  ...(params.deps !== undefined ? { deps: params.deps } : {}),
152
193
  };
153
- // Both update_item forms return an affected-items array, so the
154
- // result contract matches add_item and the renderer/reminder can
194
+ // Both update_items forms return an affected-items array, so the
195
+ // result contract matches add_items and the renderer/reminder can
155
196
  // treat every result the same way.
156
197
  return withStore((store) =>
157
198
  store.updateItem(requireParam(params.item_id, "item_id"), patch),
@@ -173,7 +214,7 @@ export default function (pi: ExtensionAPI): void {
173
214
  case "setActive":
174
215
  return withStore((store) => store.setActiveList(action.listId));
175
216
  case "addItem":
176
- return withStore((store) => store.addItem(action.listId, action.text));
217
+ return withStore((store) => store.addItem(action.listId, action.title));
177
218
  case "updateItem":
178
219
  return withStore((store) => store.updateItem(action.itemId, action.patch));
179
220
  case "removeItem":
@@ -212,9 +253,7 @@ export default function (pi: ExtensionAPI): void {
212
253
  // Record the transition before the mirror moves, so the observer sees the
213
254
  // true pre-mutation state. Every mutation runs this, so a later mutation
214
255
  // that completes nothing still refreshes the live snapshot.
215
- await runtime.runPromise(
216
- withCompletionObserver((observer) => observer.record(state, next)),
217
- );
256
+ await runtime.runPromise(withCompletionObserver((observer) => observer.record(state, next)));
218
257
  state = next;
219
258
  await runtime.runPromise(
220
259
  withPersistence((p) => p.save(next)).pipe(
@@ -309,6 +348,39 @@ export default function (pi: ExtensionAPI): void {
309
348
  compactionAborted = event.aborted;
310
349
  });
311
350
 
351
+ /**
352
+ * The args of in-flight tool calls, so a `tool_execution_end` event can name
353
+ * the path its `tool_execution_start` carried. pi's end event has no args.
354
+ */
355
+ const toolCallArgs = new Map<string, ToolEvent["args"]>();
356
+
357
+ pi.on("tool_execution_start", async (event) => {
358
+ const args = boundedArgsOf(event.args);
359
+ if (args === undefined) return;
360
+ toolCallArgs.set(event.toolCallId, args);
361
+ await runtime.runPromise(
362
+ withFootprintRecorder((recorder) =>
363
+ recorder.capture({ phase: "start", toolName: event.toolName, args }),
364
+ ),
365
+ );
366
+ });
367
+
368
+ pi.on("tool_execution_end", async (event) => {
369
+ const args = toolCallArgs.get(event.toolCallId);
370
+ toolCallArgs.delete(event.toolCallId);
371
+ const details = detailsOf(event.result);
372
+ await runtime.runPromise(
373
+ withFootprintRecorder((recorder) =>
374
+ recorder.capture({
375
+ phase: "end",
376
+ toolName: event.toolName,
377
+ ...(args === undefined ? {} : { args }),
378
+ ...(details === undefined ? {} : { details }),
379
+ }),
380
+ ),
381
+ );
382
+ });
383
+
312
384
  pi.on("agent_before_settle", async (event, ctx) => {
313
385
  const decision = await runtime.runPromise(
314
386
  withSettleDecider((decider) =>
@@ -319,6 +391,11 @@ export default function (pi: ExtensionAPI): void {
319
391
  }),
320
392
  ),
321
393
  );
394
+ // The decision record is written before the pointer delivery, so the
395
+ // harvest can see the raw row and the resolved states for every decision.
396
+ if (decision.record !== undefined) {
397
+ pi.appendEntry(DECISION_CUSTOM_TYPE, encodeDecisionRecord(decision.record));
398
+ }
322
399
  if (decision.kind !== "compact") return;
323
400
  // The run signal can fire after the verdict, while the classifier is the
324
401
  // last thing between here and compaction. An abort keeps the context.
@@ -395,7 +472,7 @@ export default function (pi: ExtensionAPI): void {
395
472
  : annotations.items
396
473
  .map(
397
474
  (item, index) =>
398
- ` [${item.done ? "x" : " "}] #${list.name}:${item.id}: ${item.text}` +
475
+ ` [${item.done ? "x" : " "}] #${list.name}:${item.id}: ${item.title}` +
399
476
  `${annotations.suffixByIndex[index]}`,
400
477
  )
401
478
  .join("\n");
@@ -468,7 +545,7 @@ export default function (pi: ExtensionAPI): void {
468
545
  }
469
546
  break;
470
547
  }
471
- case "add_item": {
548
+ case "add_items": {
472
549
  const items = value as TodoItem[];
473
550
  const list = current.lists.find((l) => l.id === params.list_id);
474
551
  details.list = list;
@@ -478,33 +555,36 @@ export default function (pi: ExtensionAPI): void {
478
555
  const ids = items.map((item) => `${listName}:${item.id}`);
479
556
  text =
480
557
  items.length === 1
481
- ? `Added item #${ids[0]} to ${listName}: ${items[0]!.text}`
482
- : `Added ${items.length} items to ${listName}: ${ids.map((id, i) => `#${id}: ${items[i]!.text}`).join(", ")}`;
558
+ ? `Added item #${ids[0]} to ${listName}: ${items[0]!.title}`
559
+ : `Added ${items.length} items to ${listName}: ${ids.map((id, i) => `#${id}: ${items[i]!.title}`).join(", ")}`;
483
560
  break;
484
561
  }
485
- case "update_item": {
562
+ case "update_items": {
486
563
  const items = value as TodoItem[];
487
564
  details.items = items;
488
565
  // Normalize both forms into patch records the renderer and reminder
489
- // share: each has a display id plus optional text/done.
490
- const batch = params.items;
566
+ // share: each has a display id plus optional title/description/done.
567
+ const batch = params.items as readonly TrackerUpdatePatch[] | undefined;
491
568
  const patches: Array<{
492
569
  id: string;
493
- text?: string;
570
+ title?: string;
571
+ description?: string;
494
572
  done?: boolean;
495
573
  deps?: readonly string[];
496
574
  }> =
497
575
  batch !== undefined
498
576
  ? batch.map((p) => ({
499
577
  id: p.item_id,
500
- text: p.text,
578
+ title: p.title,
579
+ description: p.description,
501
580
  done: p.done,
502
581
  deps: p.deps,
503
582
  }))
504
583
  : [
505
584
  {
506
585
  id: params.item_id ?? "?",
507
- text: typeof params.text === "string" ? params.text : undefined,
586
+ title: typeof params.title === "string" ? params.title : undefined,
587
+ description: params.description,
508
588
  done: params.done,
509
589
  deps: params.deps,
510
590
  },
@@ -513,7 +593,8 @@ export default function (pi: ExtensionAPI): void {
513
593
  const patch = patches[i]!;
514
594
  const changes: string[] = [];
515
595
  if (patch.done !== undefined) changes.push(item.done ? "completed" : "uncompleted");
516
- if (patch.text !== undefined) changes.push(`text: ${item.text}`);
596
+ if (patch.title !== undefined) changes.push(`title: ${item.title}`);
597
+ if (patch.description !== undefined) changes.push("description updated");
517
598
  if (patch.deps !== undefined) {
518
599
  changes.push(depsChange(patch.id, patch.deps, before));
519
600
  }
@@ -560,7 +641,7 @@ export default function (pi: ExtensionAPI): void {
560
641
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
561
642
  const action = params.action;
562
643
  // Error-nudging gate: reject incorrect calls (missing required fields,
563
- // unknown fields, mixed update_item forms) with a precise message that
644
+ // unknown fields, mixed update_items forms) with a precise message that
564
645
  // tells the agent exactly what to fix, before any state is touched.
565
646
  const validation = validateTrackerCall(params);
566
647
  if (!validation.ok) {
@@ -576,7 +657,7 @@ export default function (pi: ExtensionAPI): void {
576
657
  // The state as this call finds it, so a result can name what a change
577
658
  // replaced. Only the actions that report a diff read it.
578
659
  const before =
579
- action === "update_item"
660
+ action === "update_items"
580
661
  ? await runtime.runPromise(withStore((store) => store.state))
581
662
  : state;
582
663
 
@@ -600,13 +681,31 @@ export default function (pi: ExtensionAPI): void {
600
681
  let text =
601
682
  theme.style("tracker ", { fg: "toolTitle", bold: true }) + theme.fg("muted", action);
602
683
  if (typeof raw.name === "string") text += ` ${theme.fg("dim", `"${raw.name}"`)}`;
603
- if (typeof raw.text === "string") {
604
- text += ` ${theme.fg("dim", `"${raw.text}"`)}`;
605
- } else if (Array.isArray(raw.text)) {
606
- text += ` ${theme.fg("dim", raw.text.map((t) => `"${t}"`).join(" "))}`;
684
+ if (typeof raw.title === "string") {
685
+ text += ` ${theme.fg("dim", `"${raw.title}"`)}`;
686
+ } else if (Array.isArray(raw.title)) {
687
+ text += ` ${theme.fg(
688
+ "dim",
689
+ raw.title
690
+ .map((entry) =>
691
+ typeof entry === "string"
692
+ ? `"${entry}"`
693
+ : `"${String((entry as { title?: unknown }).title ?? "")}"`,
694
+ )
695
+ .join(" "),
696
+ )}`;
607
697
  }
608
698
  if (Array.isArray(raw.initial_items)) {
609
- text += ` ${theme.fg("dim", raw.initial_items.map((t) => `"${t}"`).join(" "))}`;
699
+ text += ` ${theme.fg(
700
+ "dim",
701
+ raw.initial_items
702
+ .map((entry) =>
703
+ typeof entry === "string"
704
+ ? `"${entry}"`
705
+ : `"${String((entry as { title?: unknown }).title ?? "")}"`,
706
+ )
707
+ .join(" "),
708
+ )}`;
610
709
  }
611
710
  if (Array.isArray(raw.items)) text += ` ${theme.fg("accent", `${raw.items.length} items`)}`;
612
711
  if (raw.activate === false) text += ` ${theme.fg("muted", "(no auto-switch)")}`;
@@ -641,11 +740,14 @@ export default function (pi: ExtensionAPI): void {
641
740
  const display = expanded ? annotations.items : annotations.items.slice(0, 5);
642
741
  for (const [index, item] of display.entries()) {
643
742
  const check = item.done ? theme.fg("success", "✓") : theme.fg("dim", "○");
644
- const itemText = item.done ? theme.fg("dim", item.text) : item.text;
743
+ const itemText = item.done ? theme.fg("dim", item.title) : item.title;
645
744
  const blocked = theme.fg("dim", annotations.suffixByIndex[index] ?? "");
646
745
  parts.push(
647
746
  ` ${check} ${theme.fg("accent", `#${list.name}:${item.id}`)} ${itemText}${blocked}`,
648
747
  );
748
+ if (expanded && (item.description ?? "").length > 0) {
749
+ parts.push(` ${theme.fg("dim", item.description ?? "")}`);
750
+ }
649
751
  }
650
752
  if (!expanded && annotations.items.length > 5) {
651
753
  parts.push(theme.fg("dim", ` ... ${annotations.items.length - 5} more`));