@ftrdotdev/pi-tracker 0.6.0 → 0.8.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 (36) hide show
  1. package/README.md +183 -60
  2. package/package.json +23 -11
  3. package/src/compaction/candidate.test.ts +9 -6
  4. package/src/compaction/candidate.ts +32 -2
  5. package/src/compaction/classifier.test.ts +67 -60
  6. package/src/compaction/classifier.ts +24 -22
  7. package/src/compaction/completion.test.ts +127 -49
  8. package/src/compaction/completion.ts +1 -3
  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 +104 -9
  12. package/src/compaction/digest.ts +96 -9
  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/rules.test.ts +253 -0
  18. package/src/compaction/rules.ts +188 -0
  19. package/src/compaction/settings.test.ts +105 -49
  20. package/src/compaction/settings.ts +53 -31
  21. package/src/compaction/settle.test.ts +370 -0
  22. package/src/compaction/settle.ts +109 -53
  23. package/src/core/deps.test.ts +1 -1
  24. package/src/core/domain.test.ts +42 -9
  25. package/src/core/domain.ts +73 -8
  26. package/src/core/persistence.test.ts +7 -7
  27. package/src/core/store.test.ts +116 -50
  28. package/src/core/store.ts +92 -31
  29. package/src/index.test.ts +209 -68
  30. package/src/index.ts +170 -48
  31. package/src/presentation/tool-metadata.test.ts +263 -48
  32. package/src/presentation/tool-metadata.ts +325 -102
  33. package/src/presentation/ui.test.ts +122 -7
  34. package/src/presentation/ui.ts +81 -18
  35. package/src/presentation/vim-settings.test.ts +98 -0
  36. package/src/presentation/vim-settings.ts +59 -0
package/src/index.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
3
3
  import { Text } from "@earendil-works/pi-tui";
4
- import { makeBorderedBox } from "@ftrdotdev/pi-tui";
4
+ import { makeBorderedBox, VimRouter } from "@ftrdotdev/pi-tui";
5
5
  import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
6
6
  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,
@@ -35,6 +42,7 @@ import {
35
42
  readinessSuffix,
36
43
  type TrackerUiAction,
37
44
  } from "./presentation/ui.ts";
45
+ import { VimSettingsService } from "./presentation/vim-settings.ts";
38
46
 
39
47
  /** Custom-entry type used to persist the tracker state in the session. */
40
48
  const CUSTOM_TYPE = "tracker/state";
@@ -63,24 +71,49 @@ const withSettleDecider = <A, E>(
63
71
  f: (decider: SettleDecider["Service"]) => Effect.Effect<A, E>,
64
72
  ): Effect.Effect<A, E, SettleDecider> => Effect.flatMap(SettleDecider, f);
65
73
 
74
+ const withFootprintRecorder = <A, E>(
75
+ f: (recorder: FootprintRecorder["Service"]) => Effect.Effect<A, E>,
76
+ ): Effect.Effect<A, E, FootprintRecorder> => Effect.flatMap(FootprintRecorder, f);
77
+
78
+ const withVimSettings = <A, E>(
79
+ f: (settings: VimSettingsService["Service"]) => Effect.Effect<A, E>,
80
+ ): Effect.Effect<A, E, VimSettingsService> => Effect.flatMap(VimSettingsService, f);
81
+
82
+ /** The bounded `path`/`command` projection of a tool call's arguments. */
83
+ const boundedArgsOf = (value: unknown): ToolEvent["args"] => {
84
+ if (typeof value !== "object" || value === null) return undefined;
85
+ const record = value as { readonly path?: unknown; readonly command?: unknown };
86
+ const path = typeof record.path === "string" && record.path.length > 0 ? record.path : undefined;
87
+ const command =
88
+ typeof record.command === "string" && record.command.length > 0 ? record.command : undefined;
89
+ if (path === undefined && command === undefined) return undefined;
90
+ return {
91
+ ...(path === undefined ? {} : { path }),
92
+ ...(command === undefined ? {} : { command }),
93
+ };
94
+ };
95
+
96
+ /** The tool result's `details`, which carries a write's or edit's unified patch. */
97
+ const detailsOf = (result: unknown): unknown =>
98
+ typeof result === "object" && result !== null
99
+ ? (result as { readonly details?: unknown }).details
100
+ : undefined;
101
+
66
102
  /** Throw for a missing required tool parameter; caught in `execute`. */
67
103
  const requireParam = <T>(value: T | undefined, name: string): T => {
68
104
  if (value === undefined) throw new Error(`${name} is required for this tracker action`);
69
105
  return value;
70
106
  };
71
107
 
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
- };
108
+ /** Project the tool's item objects onto the store's item specs. */
109
+ const toItemSpecs = (items: readonly TrackerItemSpec[]): ItemSpec[] =>
110
+ items.map((item) => ({
111
+ title: item.title,
112
+ ...(item.description === undefined ? {} : { description: item.description }),
113
+ ...(item.refs === undefined ? {} : { refs: item.refs }),
114
+ ...(item.produces === undefined ? {} : { produces: item.produces }),
115
+ ...(item.deps === undefined ? {} : { deps: item.deps }),
116
+ }));
84
117
 
85
118
  // --------------------------------------------------------------------------
86
119
  // Extension
@@ -89,14 +122,20 @@ const toItemSpecs = (raw: NonNullable<TrackerToolParams["text"]>): ItemSpec[] =>
89
122
  export default function (pi: ExtensionAPI): void {
90
123
  // The settings path is resolved inside the factory, so a test can point
91
124
  // ENV_AGENT_DIR at a temp directory before `tracker(api)` runs.
125
+ const probe = productionProbe();
126
+ // One shared config path: the smart-compaction reader and the vim reader both
127
+ // read `tui.json`, owned by the TUI package.
128
+ const configPath = join(getAgentDir(), SMART_COMPACTION_CONFIG_FILE);
92
129
  const decisionServices = Layer.mergeAll(
93
130
  CompletionObserver.layer,
94
131
  ClassifierGateway.layer,
95
- SmartCompactionSettingsService.make(join(getAgentDir(), SMART_COMPACTION_CONFIG_FILE)),
132
+ FootprintRecorder.layer(probe),
133
+ SmartCompactionSettingsService.make(configPath),
134
+ VimSettingsService.make(configPath),
96
135
  );
97
136
 
98
137
  const runtime = ManagedRuntime.make(
99
- SettleDecider.layer.pipe(
138
+ SettleDecider.layer(probe).pipe(
100
139
  Layer.provideMerge(Layer.mergeAll(TrackerStore.layer, decisionServices)),
101
140
  Layer.provideMerge(
102
141
  TrackerPersistence.layer((encoded) => pi.appendEntry(CUSTOM_TYPE, encoded)),
@@ -127,31 +166,42 @@ export default function (pi: ExtensionAPI): void {
127
166
  return withStore((store) => store.deleteList(requireParam(params.list_id, "list_id")));
128
167
  case "set_active":
129
168
  return withStore((store) => store.setActiveList(params.list_id ?? null));
130
- case "add_item": {
131
- const specs = toItemSpecs(requireParam(params.text, "text"));
169
+ case "add_items": {
170
+ // Validation guarantees every entry is an item object; the shared
171
+ // `items` field also carries update_items patches, which are rejected
172
+ // for this action.
173
+ const specs = toItemSpecs(
174
+ requireParam(params.items, "items") as readonly TrackerItemSpec[],
175
+ );
132
176
  return withStore((store) => store.addItems(requireParam(params.list_id, "list_id"), specs));
133
177
  }
134
- case "update_item": {
178
+ case "update_items": {
135
179
  if (params.items !== undefined) {
136
180
  // Batch form: list_id + item-id patches within one list (mirrors
137
- // add_item's list_id + text[]). The store resolves each id against
181
+ // add_items' list_id + items). The store resolves each id against
138
182
  // that single list, so the reference's list name must match it.
139
183
  const listId = requireParam(params.list_id, "list_id");
140
- const batch = params.items.map((patch) => ({
184
+ const batch = (params.items as readonly TrackerUpdatePatch[]).map((patch) => ({
141
185
  itemId: patch.item_id,
142
- ...(patch.text !== undefined ? { text: patch.text } : {}),
186
+ ...(patch.title !== undefined ? { title: patch.title } : {}),
187
+ ...(patch.description !== undefined ? { description: patch.description } : {}),
188
+ ...(patch.refs !== undefined ? { refs: patch.refs } : {}),
189
+ ...(patch.produces !== undefined ? { produces: patch.produces } : {}),
143
190
  ...(patch.done !== undefined ? { done: patch.done } : {}),
144
191
  ...(patch.deps !== undefined ? { deps: patch.deps } : {}),
145
192
  }));
146
193
  return withStore((store) => store.updateItems(listId, batch));
147
194
  }
148
195
  const patch: UpdateItemPatch = {
149
- ...(typeof params.text === "string" ? { text: params.text } : {}),
196
+ ...(typeof params.title === "string" ? { title: params.title } : {}),
197
+ ...(params.description !== undefined ? { description: params.description } : {}),
198
+ ...(params.refs !== undefined ? { refs: params.refs } : {}),
199
+ ...(params.produces !== undefined ? { produces: params.produces } : {}),
150
200
  ...(params.done !== undefined ? { done: params.done } : {}),
151
201
  ...(params.deps !== undefined ? { deps: params.deps } : {}),
152
202
  };
153
- // Both update_item forms return an affected-items array, so the
154
- // result contract matches add_item and the renderer/reminder can
203
+ // Both update_items forms return an affected-items array, so the
204
+ // result contract matches add_items and the renderer/reminder can
155
205
  // treat every result the same way.
156
206
  return withStore((store) =>
157
207
  store.updateItem(requireParam(params.item_id, "item_id"), patch),
@@ -173,7 +223,7 @@ export default function (pi: ExtensionAPI): void {
173
223
  case "setActive":
174
224
  return withStore((store) => store.setActiveList(action.listId));
175
225
  case "addItem":
176
- return withStore((store) => store.addItem(action.listId, action.text));
226
+ return withStore((store) => store.addItem(action.listId, action.title));
177
227
  case "updateItem":
178
228
  return withStore((store) => store.updateItem(action.itemId, action.patch));
179
229
  case "removeItem":
@@ -212,9 +262,7 @@ export default function (pi: ExtensionAPI): void {
212
262
  // Record the transition before the mirror moves, so the observer sees the
213
263
  // true pre-mutation state. Every mutation runs this, so a later mutation
214
264
  // that completes nothing still refreshes the live snapshot.
215
- await runtime.runPromise(
216
- withCompletionObserver((observer) => observer.record(state, next)),
217
- );
265
+ await runtime.runPromise(withCompletionObserver((observer) => observer.record(state, next)));
218
266
  state = next;
219
267
  await runtime.runPromise(
220
268
  withPersistence((p) => p.save(next)).pipe(
@@ -309,6 +357,39 @@ export default function (pi: ExtensionAPI): void {
309
357
  compactionAborted = event.aborted;
310
358
  });
311
359
 
360
+ /**
361
+ * The args of in-flight tool calls, so a `tool_execution_end` event can name
362
+ * the path its `tool_execution_start` carried. pi's end event has no args.
363
+ */
364
+ const toolCallArgs = new Map<string, ToolEvent["args"]>();
365
+
366
+ pi.on("tool_execution_start", async (event) => {
367
+ const args = boundedArgsOf(event.args);
368
+ if (args === undefined) return;
369
+ toolCallArgs.set(event.toolCallId, args);
370
+ await runtime.runPromise(
371
+ withFootprintRecorder((recorder) =>
372
+ recorder.capture({ phase: "start", toolName: event.toolName, args }),
373
+ ),
374
+ );
375
+ });
376
+
377
+ pi.on("tool_execution_end", async (event) => {
378
+ const args = toolCallArgs.get(event.toolCallId);
379
+ toolCallArgs.delete(event.toolCallId);
380
+ const details = detailsOf(event.result);
381
+ await runtime.runPromise(
382
+ withFootprintRecorder((recorder) =>
383
+ recorder.capture({
384
+ phase: "end",
385
+ toolName: event.toolName,
386
+ ...(args === undefined ? {} : { args }),
387
+ ...(details === undefined ? {} : { details }),
388
+ }),
389
+ ),
390
+ );
391
+ });
392
+
312
393
  pi.on("agent_before_settle", async (event, ctx) => {
313
394
  const decision = await runtime.runPromise(
314
395
  withSettleDecider((decider) =>
@@ -319,6 +400,11 @@ export default function (pi: ExtensionAPI): void {
319
400
  }),
320
401
  ),
321
402
  );
403
+ // The decision record is written before the pointer delivery, so the
404
+ // harvest can see the raw row and the resolved states for every decision.
405
+ if (decision.record !== undefined) {
406
+ pi.appendEntry(DECISION_CUSTOM_TYPE, encodeDecisionRecord(decision.record));
407
+ }
322
408
  if (decision.kind !== "compact") return;
323
409
  // The run signal can fire after the verdict, while the classifier is the
324
410
  // last thing between here and compaction. An abort keeps the context.
@@ -395,7 +481,7 @@ export default function (pi: ExtensionAPI): void {
395
481
  : annotations.items
396
482
  .map(
397
483
  (item, index) =>
398
- ` [${item.done ? "x" : " "}] #${list.name}:${item.id}: ${item.text}` +
484
+ ` [${item.done ? "x" : " "}] #${list.name}:${item.id}: ${item.title}` +
399
485
  `${annotations.suffixByIndex[index]}`,
400
486
  )
401
487
  .join("\n");
@@ -468,7 +554,7 @@ export default function (pi: ExtensionAPI): void {
468
554
  }
469
555
  break;
470
556
  }
471
- case "add_item": {
557
+ case "add_items": {
472
558
  const items = value as TodoItem[];
473
559
  const list = current.lists.find((l) => l.id === params.list_id);
474
560
  details.list = list;
@@ -478,33 +564,36 @@ export default function (pi: ExtensionAPI): void {
478
564
  const ids = items.map((item) => `${listName}:${item.id}`);
479
565
  text =
480
566
  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(", ")}`;
567
+ ? `Added item #${ids[0]} to ${listName}: ${items[0]!.title}`
568
+ : `Added ${items.length} items to ${listName}: ${ids.map((id, i) => `#${id}: ${items[i]!.title}`).join(", ")}`;
483
569
  break;
484
570
  }
485
- case "update_item": {
571
+ case "update_items": {
486
572
  const items = value as TodoItem[];
487
573
  details.items = items;
488
574
  // 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;
575
+ // share: each has a display id plus optional title/description/done.
576
+ const batch = params.items as readonly TrackerUpdatePatch[] | undefined;
491
577
  const patches: Array<{
492
578
  id: string;
493
- text?: string;
579
+ title?: string;
580
+ description?: string;
494
581
  done?: boolean;
495
582
  deps?: readonly string[];
496
583
  }> =
497
584
  batch !== undefined
498
585
  ? batch.map((p) => ({
499
586
  id: p.item_id,
500
- text: p.text,
587
+ title: p.title,
588
+ description: p.description,
501
589
  done: p.done,
502
590
  deps: p.deps,
503
591
  }))
504
592
  : [
505
593
  {
506
594
  id: params.item_id ?? "?",
507
- text: typeof params.text === "string" ? params.text : undefined,
595
+ title: typeof params.title === "string" ? params.title : undefined,
596
+ description: params.description,
508
597
  done: params.done,
509
598
  deps: params.deps,
510
599
  },
@@ -513,7 +602,8 @@ export default function (pi: ExtensionAPI): void {
513
602
  const patch = patches[i]!;
514
603
  const changes: string[] = [];
515
604
  if (patch.done !== undefined) changes.push(item.done ? "completed" : "uncompleted");
516
- if (patch.text !== undefined) changes.push(`text: ${item.text}`);
605
+ if (patch.title !== undefined) changes.push(`title: ${item.title}`);
606
+ if (patch.description !== undefined) changes.push("description updated");
517
607
  if (patch.deps !== undefined) {
518
608
  changes.push(depsChange(patch.id, patch.deps, before));
519
609
  }
@@ -560,7 +650,7 @@ export default function (pi: ExtensionAPI): void {
560
650
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
561
651
  const action = params.action;
562
652
  // Error-nudging gate: reject incorrect calls (missing required fields,
563
- // unknown fields, mixed update_item forms) with a precise message that
653
+ // unknown fields, mixed update_items forms) with a precise message that
564
654
  // tells the agent exactly what to fix, before any state is touched.
565
655
  const validation = validateTrackerCall(params);
566
656
  if (!validation.ok) {
@@ -576,7 +666,7 @@ export default function (pi: ExtensionAPI): void {
576
666
  // The state as this call finds it, so a result can name what a change
577
667
  // replaced. Only the actions that report a diff read it.
578
668
  const before =
579
- action === "update_item"
669
+ action === "update_items"
580
670
  ? await runtime.runPromise(withStore((store) => store.state))
581
671
  : state;
582
672
 
@@ -600,13 +690,31 @@ export default function (pi: ExtensionAPI): void {
600
690
  let text =
601
691
  theme.style("tracker ", { fg: "toolTitle", bold: true }) + theme.fg("muted", action);
602
692
  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(" "))}`;
693
+ if (typeof raw.title === "string") {
694
+ text += ` ${theme.fg("dim", `"${raw.title}"`)}`;
695
+ } else if (Array.isArray(raw.title)) {
696
+ text += ` ${theme.fg(
697
+ "dim",
698
+ raw.title
699
+ .map((entry) =>
700
+ typeof entry === "string"
701
+ ? `"${entry}"`
702
+ : `"${String((entry as { title?: unknown }).title ?? "")}"`,
703
+ )
704
+ .join(" "),
705
+ )}`;
607
706
  }
608
707
  if (Array.isArray(raw.initial_items)) {
609
- text += ` ${theme.fg("dim", raw.initial_items.map((t) => `"${t}"`).join(" "))}`;
708
+ text += ` ${theme.fg(
709
+ "dim",
710
+ raw.initial_items
711
+ .map((entry) =>
712
+ typeof entry === "string"
713
+ ? `"${entry}"`
714
+ : `"${String((entry as { title?: unknown }).title ?? "")}"`,
715
+ )
716
+ .join(" "),
717
+ )}`;
610
718
  }
611
719
  if (Array.isArray(raw.items)) text += ` ${theme.fg("accent", `${raw.items.length} items`)}`;
612
720
  if (raw.activate === false) text += ` ${theme.fg("muted", "(no auto-switch)")}`;
@@ -641,11 +749,14 @@ export default function (pi: ExtensionAPI): void {
641
749
  const display = expanded ? annotations.items : annotations.items.slice(0, 5);
642
750
  for (const [index, item] of display.entries()) {
643
751
  const check = item.done ? theme.fg("success", "✓") : theme.fg("dim", "○");
644
- const itemText = item.done ? theme.fg("dim", item.text) : item.text;
752
+ const itemText = item.done ? theme.fg("dim", item.title) : item.title;
645
753
  const blocked = theme.fg("dim", annotations.suffixByIndex[index] ?? "");
646
754
  parts.push(
647
755
  ` ${check} ${theme.fg("accent", `#${list.name}:${item.id}`)} ${itemText}${blocked}`,
648
756
  );
757
+ if (expanded && (item.description ?? "").length > 0) {
758
+ parts.push(` ${theme.fg("dim", item.description ?? "")}`);
759
+ }
649
760
  }
650
761
  if (!expanded && annotations.items.length > 5) {
651
762
  parts.push(theme.fg("dim", ` ... ${annotations.items.length - 5} more`));
@@ -683,6 +794,16 @@ export default function (pi: ExtensionAPI): void {
683
794
  ctx.ui.notify("/tracker requires interactive mode", "error");
684
795
  return;
685
796
  }
797
+ // Read the shared `vim` toggle and build the gated router once, before
798
+ // the modal opens: h/j/k/l then work only when vim mode is on, and the
799
+ // overlay's help line reports which keys are live.
800
+ const vimEnabled = await runtime.runPromise(withVimSettings((settings) => settings.load));
801
+ const vim = {
802
+ router: Effect.runSync(
803
+ Effect.service(VimRouter).pipe(Effect.provide(VimRouter.make(() => vimEnabled))),
804
+ ),
805
+ enabled: vimEnabled,
806
+ };
686
807
  await ctx.ui.custom<void>((tui, theme, _kb, done) => {
687
808
  // The overlay content is framed by the same house rounded box as the
688
809
  // widget. makeBorderedBox's own cache is disabled so an overlay
@@ -694,6 +815,7 @@ export default function (pi: ExtensionAPI): void {
694
815
  requestRender: () => tui.requestRender(),
695
816
  onAction: (action) => runUiAction(ctx, action),
696
817
  onClose: () => done(),
818
+ vim,
697
819
  });
698
820
  const framed = makeBorderedBox(overlay, theme, {
699
821
  label: "Tracker",