@ftrdotdev/pi-tracker 0.2.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.
@@ -0,0 +1,213 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { Value } from "typebox/value";
3
+ import {
4
+ TOOL_ACTIONS,
5
+ TRACKER_TOOL_METADATA,
6
+ TRACKER_TOOL_NAME,
7
+ TrackerToolParams,
8
+ doneMarkReminder,
9
+ validateTrackerCall,
10
+ } from "./tool-metadata.ts";
11
+
12
+ describe("tracker tool parameter schema", () => {
13
+ it("accepts valid parameters for every action", () => {
14
+ const valid: Array<Record<string, unknown>> = [
15
+ { action: "list" },
16
+ { action: "create_list", name: "Work" },
17
+ { action: "create_list", name: "Work", activate: true },
18
+ { action: "create_list", name: "Work", activate: false },
19
+ { action: "create_list", name: "Work", initial_items: ["Fix bug", "Write test"] },
20
+ { action: "create_list", name: "Work", initial_items: ["Fix bug"], activate: false },
21
+ { action: "delete_list", list_id: 1 },
22
+ { action: "set_active", list_id: 1 },
23
+ { action: "set_active" },
24
+ { action: "add_item", list_id: 1, text: "Fix bug" },
25
+ { action: "add_item", list_id: 1, text: ["Fix bug", "Write test"] },
26
+ { action: "update_item", item_id: "Work:2", text: "New text", done: true },
27
+ { action: "update_item", item_id: "Work:2" },
28
+ {
29
+ action: "update_item",
30
+ items: [
31
+ { item_id: "Work:1", done: true },
32
+ { item_id: "Work:2", text: "New text" },
33
+ ],
34
+ },
35
+ { action: "remove_item", item_id: "Work:2" },
36
+ ];
37
+ for (const params of valid) {
38
+ expect(Value.Check(TrackerToolParams, params), JSON.stringify(params)).toBe(true);
39
+ }
40
+ });
41
+
42
+ it("rejects unknown actions", () => {
43
+ expect(Value.Check(TrackerToolParams, { action: "bogus" })).toBe(false);
44
+ expect(Value.Check(TrackerToolParams, {})).toBe(false);
45
+ });
46
+
47
+ it("rejects wrong parameter types", () => {
48
+ expect(Value.Check(TrackerToolParams, { action: "add_item", list_id: "one", text: "x" })).toBe(
49
+ false,
50
+ );
51
+ expect(Value.Check(TrackerToolParams, { action: "create_list", name: 42 })).toBe(false);
52
+ expect(Value.Check(TrackerToolParams, { action: "create_list", activate: "yes" })).toBe(false);
53
+ expect(Value.Check(TrackerToolParams, { action: "update_item", done: "yes" })).toBe(false);
54
+ expect(Value.Check(TrackerToolParams, { action: "add_item", list_id: 1, text: [1, "x"] })).toBe(
55
+ false,
56
+ );
57
+ expect(
58
+ Value.Check(TrackerToolParams, {
59
+ action: "update_item",
60
+ items: [{ item_id: "Work:1", done: "yes" }],
61
+ }),
62
+ ).toBe(false);
63
+ expect(Value.Check(TrackerToolParams, { action: "update_item", item_id: 2 })).toBe(false); // ids are strings
64
+ });
65
+
66
+ it("rejects empty batch arrays", () => {
67
+ expect(Value.Check(TrackerToolParams, { action: "add_item", list_id: 1, text: [] })).toBe(
68
+ false,
69
+ );
70
+ expect(Value.Check(TrackerToolParams, { action: "update_item", items: [] })).toBe(false);
71
+ expect(
72
+ Value.Check(TrackerToolParams, { action: "create_list", name: "Work", initial_items: [] }),
73
+ ).toBe(false);
74
+ expect(
75
+ Value.Check(TrackerToolParams, { action: "create_list", name: "Work", initial_items: [1] }),
76
+ ).toBe(false);
77
+ expect(Value.Check(TrackerToolParams, { action: "set_active", list_id: "one" })).toBe(false);
78
+ });
79
+ });
80
+
81
+ describe("validateTrackerCall (error-nudging layer)", () => {
82
+ it("accepts every valid call shape", () => {
83
+ const valid: Array<Record<string, unknown>> = [
84
+ { action: "list" },
85
+ { action: "create_list", name: "Work" },
86
+ { action: "create_list", name: "Work", initial_items: ["a", "b"], activate: false },
87
+ { action: "delete_list", list_id: 1 },
88
+ { action: "set_active" },
89
+ { action: "set_active", list_id: 1 },
90
+ { action: "add_item", list_id: 1, text: "x" },
91
+ { action: "add_item", list_id: 1, text: ["a", "b"] },
92
+ { action: "update_item", item_id: "Work:2" },
93
+ { action: "update_item", item_id: "Work:2", text: "x", done: true },
94
+ { action: "update_item", items: [{ item_id: "Work:2", done: true }] },
95
+ { action: "remove_item", item_id: "Work:2" },
96
+ ];
97
+ for (const call of valid) {
98
+ const result = validateTrackerCall(call);
99
+ expect(result.ok, JSON.stringify(call)).toBe(true);
100
+ }
101
+ });
102
+
103
+ it("nudges on unknown fields with the accepted parameter list", () => {
104
+ const result = validateTrackerCall({ action: "create_list", name: "Work", list_id: 1 });
105
+ expect(result.ok).toBe(false);
106
+ if (!result.ok) {
107
+ expect(result.message).toContain("list_id");
108
+ expect(result.message).toContain("name");
109
+ expect(result.message).toContain("initial_items");
110
+ expect(result.message).toContain("activate");
111
+ }
112
+
113
+ const bare = validateTrackerCall({ action: "list", name: "x" });
114
+ expect(bare.ok).toBe(false);
115
+ if (!bare.ok) expect(bare.message).toContain("accepts no parameters");
116
+
117
+ // The old numeric contract (list_id + numeric item_id) is rejected with
118
+ // the new parameter list, so a stale agent call self-corrects.
119
+ const stale = validateTrackerCall({ action: "update_item", list_id: 1, item_id: 2 });
120
+ expect(stale.ok).toBe(false);
121
+ if (!stale.ok) {
122
+ expect(stale.message).toContain("list_id");
123
+ expect(stale.message).toContain("item_id");
124
+ }
125
+ });
126
+
127
+ it("nudges on missing required fields", () => {
128
+ const cases: Array<[Record<string, unknown>, string]> = [
129
+ [{ action: "create_list" }, "'name'"],
130
+ [{ action: "delete_list" }, "'list_id'"],
131
+ [{ action: "add_item", list_id: 1 }, "'text'"],
132
+ [{ action: "add_item", text: "x" }, "'list_id'"],
133
+ [{ action: "update_item" }, "'item_id'"],
134
+ [{ action: "remove_item" }, "'item_id'"],
135
+ ];
136
+ for (const [call, expected] of cases) {
137
+ const result = validateTrackerCall(call);
138
+ expect(result.ok, JSON.stringify(call)).toBe(false);
139
+ if (!result.ok) expect(result.message, JSON.stringify(call)).toContain(expected);
140
+ }
141
+ });
142
+
143
+ it("nudges on mixed update_item forms and array text", () => {
144
+ const mixed = validateTrackerCall({
145
+ action: "update_item",
146
+ item_id: "Work:2",
147
+ items: [{ item_id: "Work:3" }],
148
+ });
149
+ expect(mixed.ok).toBe(false);
150
+ if (!mixed.ok) expect(mixed.message).toContain("not both");
151
+
152
+ const arrayText = validateTrackerCall({
153
+ action: "update_item",
154
+ item_id: "Work:2",
155
+ text: ["a"],
156
+ });
157
+ expect(arrayText.ok).toBe(false);
158
+ if (!arrayText.ok) expect(arrayText.message).toContain("single string");
159
+ });
160
+
161
+ it("nudges on unknown actions and non-object args", () => {
162
+ const unknown = validateTrackerCall({ action: "bogus" });
163
+ expect(unknown.ok).toBe(false);
164
+ if (!unknown.ok) {
165
+ expect(unknown.message).toContain("bogus");
166
+ expect(unknown.message).toContain(TOOL_ACTIONS.join(", "));
167
+ }
168
+ expect(validateTrackerCall("nope").ok).toBe(false);
169
+ expect(validateTrackerCall(undefined).ok).toBe(false);
170
+ expect(validateTrackerCall([1]).ok).toBe(false);
171
+ });
172
+ });
173
+
174
+ describe("doneMarkReminder (batch done-mark guard)", () => {
175
+ it("reminds when one call marks two or more items done", () => {
176
+ const reminder = doneMarkReminder([{ done: true }, { done: true }]);
177
+ expect(reminder).not.toBeNull();
178
+ expect(reminder).toContain("same turn");
179
+ expect(reminder).toContain("2 items");
180
+ });
181
+
182
+ it("is silent for single done marks and text-only batches", () => {
183
+ expect(doneMarkReminder([{ done: true }])).toBeNull();
184
+ expect(doneMarkReminder([{}, {}])).toBeNull(); // text-only/no-op patches
185
+ expect(doneMarkReminder([])).toBeNull();
186
+ });
187
+
188
+ it("does not count reopening (done: false) as marking done", () => {
189
+ expect(doneMarkReminder([{ done: true }, { done: false }])).toBeNull();
190
+ });
191
+ });
192
+
193
+ describe("tracker tool prompt metadata", () => {
194
+ it("every guideline names the tracker tool", () => {
195
+ for (const guideline of TRACKER_TOOL_METADATA.promptGuidelines) {
196
+ expect(guideline, guideline).toContain(TRACKER_TOOL_NAME);
197
+ }
198
+ });
199
+
200
+ it("description and snippet are non-empty and cover every action", () => {
201
+ expect(TRACKER_TOOL_METADATA.description.length).toBeGreaterThan(0);
202
+ expect(TRACKER_TOOL_METADATA.promptSnippet.length).toBeGreaterThan(0);
203
+ for (const action of TOOL_ACTIONS) {
204
+ expect(TRACKER_TOOL_METADATA.description, `description should mention ${action}`).toContain(
205
+ action,
206
+ );
207
+ }
208
+ });
209
+
210
+ it("runs tool calls sequentially to avoid mutation races", () => {
211
+ expect(TRACKER_TOOL_METADATA.executionMode).toBe("sequential");
212
+ });
213
+ });
@@ -0,0 +1,302 @@
1
+ /**
2
+ * Static metadata for the tracker tool: action enum, parameter schema, result
3
+ * contract, and the prompt-facing strings. Everything here is free of runtime
4
+ * state; behavior (execute and rendering) lives in index.ts.
5
+ */
6
+ import { StringEnum } from "@earendil-works/pi-ai";
7
+ import { Type } from "typebox";
8
+ import type { Static } from "typebox";
9
+ import type { TodoItem, TodoList } from "./domain.ts";
10
+ import type { EncodedState } from "./persistence.ts";
11
+
12
+ /** Tracker tool actions, in the same order as the store operations. */
13
+ export const TOOL_ACTIONS = [
14
+ "list",
15
+ "create_list",
16
+ "delete_list",
17
+ "set_active",
18
+ "add_item",
19
+ "update_item",
20
+ "remove_item",
21
+ ] as const;
22
+
23
+ export type TrackerToolAction = (typeof TOOL_ACTIONS)[number];
24
+
25
+ export const TRACKER_TOOL_NAME = "tracker";
26
+ export const TRACKER_TOOL_LABEL = "Tracker";
27
+
28
+ /**
29
+ * Parameter schema for the tracker tool.
30
+ *
31
+ * The schema enforces *types* (strings, numbers, array shapes, the action
32
+ * enum) but stays permissive about field presence and unknown fields: those
33
+ * are validated at runtime by `validateTrackerCall`, so every incorrect call
34
+ * receives a precise, actionable error message instead of a generic schema
35
+ * rejection.
36
+ */
37
+ export const TrackerToolParams = Type.Object({
38
+ action: StringEnum(TOOL_ACTIONS, { description: "Tracker operation to perform" }),
39
+ list_id: Type.Optional(
40
+ Type.Number({
41
+ description:
42
+ "List id, as shown by the list action. Required for delete_list, add_item; optional for set_active (omit to deselect).",
43
+ }),
44
+ ),
45
+ item_id: Type.Optional(
46
+ Type.String({
47
+ description:
48
+ 'Item id, as shown by the list action: listName:index (1-based position in the list, e.g. "Work:2"). Required for update_item (scalar form) and remove_item.',
49
+ }),
50
+ ),
51
+ name: Type.Optional(
52
+ Type.String({ description: "Name for the new list. Required for create_list." }),
53
+ ),
54
+ initial_items: Type.Optional(
55
+ Type.Array(Type.String({ description: "Item text." }), {
56
+ description: "For create_list: initial items, added when the list is created.",
57
+ minItems: 1,
58
+ }),
59
+ ),
60
+ activate: Type.Optional(
61
+ Type.Boolean({
62
+ description:
63
+ "For create_list: switch the active list to the new list (defaults to true; pass false to keep the current active list).",
64
+ }),
65
+ ),
66
+ text: Type.Optional(
67
+ Type.Union(
68
+ [
69
+ Type.String({
70
+ description:
71
+ "Item text. For add_item: the text of a new item. For update_item: the replacement text.",
72
+ }),
73
+ Type.Array(Type.String({ description: "Item text." }), {
74
+ description: "For add_item: several item texts to add in one call.",
75
+ minItems: 1,
76
+ }),
77
+ ],
78
+ { description: "Item text: a single string, or (add_item only) an array of strings." },
79
+ ),
80
+ ),
81
+ done: Type.Optional(
82
+ Type.Boolean({ description: "For update_item: true marks the item done, false reopens it." }),
83
+ ),
84
+ items: Type.Optional(
85
+ Type.Array(
86
+ Type.Object(
87
+ {
88
+ item_id: Type.String({
89
+ description: 'Item id, as shown by the list action (listName:index, e.g. "Work:2").',
90
+ }),
91
+ text: Type.Optional(Type.String({ description: "Replacement text for the item." })),
92
+ done: Type.Optional(
93
+ Type.Boolean({ description: "true marks the item done, false reopens it." }),
94
+ ),
95
+ },
96
+ // Patch objects are strict: a typo inside an item update fails here.
97
+ { additionalProperties: false },
98
+ ),
99
+ {
100
+ description:
101
+ "For update_item: one or more item updates in a single call (all in the same list). Alternative to item_id/text/done.",
102
+ minItems: 1,
103
+ },
104
+ ),
105
+ ),
106
+ });
107
+
108
+ export type TrackerToolParams = Static<typeof TrackerToolParams>;
109
+
110
+ /** Parameters each action accepts (besides `action` itself). */
111
+ const ACTION_PARAMS: Readonly<Record<TrackerToolAction, readonly string[]>> = {
112
+ list: [],
113
+ create_list: ["name", "initial_items", "activate"],
114
+ delete_list: ["list_id"],
115
+ set_active: ["list_id"],
116
+ add_item: ["list_id", "text"],
117
+ update_item: ["item_id", "text", "done", "items"],
118
+ remove_item: ["item_id"],
119
+ };
120
+
121
+ /** Outcome of `validateTrackerCall`; on success the params are safe to use. */
122
+ export type TrackerCallValidation =
123
+ | { ok: true; params: TrackerToolParams }
124
+ | { ok: false; message: string };
125
+
126
+ /**
127
+ * Runtime validation for a tracker call — the error-nudging layer.
128
+ *
129
+ * The parameter schema only enforces types; this checks what the schema
130
+ * cannot express (presence of required fields per action, unknown fields,
131
+ * the mutually exclusive update_item forms) and returns an actionable error
132
+ * message naming exactly what to fix. `execute` surfaces that message to the
133
+ * agent, so an incorrect call self-corrects on the next attempt.
134
+ */
135
+ export function validateTrackerCall(args: unknown): TrackerCallValidation {
136
+ if (typeof args !== "object" || args === null || Array.isArray(args)) {
137
+ return { ok: false, message: "tracker arguments must be an object with an 'action' field" };
138
+ }
139
+ const record = args as Record<string, unknown>;
140
+ const action = record.action;
141
+ if (typeof action !== "string" || !(TOOL_ACTIONS as readonly string[]).includes(action)) {
142
+ return {
143
+ ok: false,
144
+ message: `Unknown tracker action ${JSON.stringify(action)} — expected one of: ${TOOL_ACTIONS.join(", ")}`,
145
+ };
146
+ }
147
+ const typed = action as TrackerToolAction;
148
+ const allowed = ACTION_PARAMS[typed];
149
+ const unexpected = Object.keys(record).filter(
150
+ (key) => key !== "action" && !allowed.includes(key),
151
+ );
152
+ if (unexpected.length > 0) {
153
+ return {
154
+ ok: false,
155
+ message:
156
+ allowed.length === 0
157
+ ? `tracker ${typed} accepts no parameters — unexpected: ${unexpected.join(", ")}`
158
+ : `tracker ${typed} does not accept ${unexpected.join(", ")} — it accepts: ${allowed.join(", ")}`,
159
+ };
160
+ }
161
+ switch (typed) {
162
+ case "create_list":
163
+ if (record.name === undefined) {
164
+ return {
165
+ ok: false,
166
+ message: "create_list requires the 'name' parameter (the new list's name).",
167
+ };
168
+ }
169
+ break;
170
+ case "delete_list":
171
+ if (record.list_id === undefined) {
172
+ return { ok: false, message: "delete_list requires the 'list_id' parameter." };
173
+ }
174
+ break;
175
+ case "add_item":
176
+ if (record.list_id === undefined) {
177
+ return { ok: false, message: "add_item requires the 'list_id' parameter." };
178
+ }
179
+ if (record.text === undefined) {
180
+ return {
181
+ ok: false,
182
+ message:
183
+ "add_item requires the 'text' parameter (a string, or an array of strings for several items).",
184
+ };
185
+ }
186
+ break;
187
+ case "update_item":
188
+ if (record.items !== undefined) {
189
+ if (
190
+ record.item_id !== undefined ||
191
+ record.text !== undefined ||
192
+ record.done !== undefined
193
+ ) {
194
+ return {
195
+ ok: false,
196
+ message:
197
+ "update_item: pass either item_id/text/done (one item) or items (several items in one call), not both.",
198
+ };
199
+ }
200
+ } else if (record.item_id === undefined) {
201
+ return {
202
+ ok: false,
203
+ message: "update_item requires 'item_id' (or 'items' for batched updates).",
204
+ };
205
+ } else if (Array.isArray(record.text)) {
206
+ return {
207
+ ok: false,
208
+ message:
209
+ "update_item: 'text' must be a single string — use 'items' to update several items in one call.",
210
+ };
211
+ }
212
+ break;
213
+ case "remove_item":
214
+ if (record.item_id === undefined) {
215
+ return { ok: false, message: "remove_item requires the 'item_id' parameter." };
216
+ }
217
+ break;
218
+
219
+ default:
220
+ // list and set_active need nothing beyond `action` (set_active may omit list_id to deselect).
221
+ break;
222
+ }
223
+ return { ok: true, params: args as TrackerToolParams };
224
+ }
225
+
226
+ /** Structured result payload attached to tool calls, consumed by the renderers. */
227
+ export interface TrackerToolDetails {
228
+ action: TrackerToolAction;
229
+ error?: string;
230
+ listId?: number;
231
+ /** `listName:index`, as shown by the list action. */
232
+ itemId?: string;
233
+ list?: TodoList;
234
+ /** Items affected by an add_item/update_item call, in creation/patch order. */
235
+ items?: TodoItem[];
236
+ /** Full state snapshot, only for the `list` action (for rendering). */
237
+ snapshot?: EncodedState;
238
+ }
239
+
240
+ /**
241
+ * Anti-pattern guard: the tracker guideline says to mark each item done in
242
+ * the same turn it completes and never batch the marking at the end. A call
243
+ * that marks two or more items done at once is the terminal-batch signature.
244
+ * Returns a reminder (or null when the call is fine); it is advisory text,
245
+ * never a rejection, so legitimate same-turn multi-completions still work.
246
+ */
247
+ export const doneMarkReminder = (
248
+ patches: readonly { readonly done?: boolean }[],
249
+ ): string | null => {
250
+ const doneCount = patches.filter((patch) => patch.done === true).length;
251
+ if (doneCount < 2) return null;
252
+ return (
253
+ `Note: this call completed ${doneCount} items at once — the tracker guideline is to mark ` +
254
+ "each item done in the same turn it completes, not batch the marking at the end."
255
+ );
256
+ };
257
+
258
+ const TRACKER_TOOL_DESCRIPTION =
259
+ "Manage todolists and track progress. Use for task lists, checklists, milestones, and step-by-step " +
260
+ "work; keep track of tasks with tracker instead of in chat or files. Work through items one at a " +
261
+ "time, marking each done as it completes, so the list is the live working state.\n" +
262
+ 'Item ids are listName:index — the 1-based position of the item in its list, e.g. "Work:2" (copy ' +
263
+ "them from the list action output). Removing an item renumbers the items after it, so list again " +
264
+ "before referencing items after a removal.\n" +
265
+ "The tracker tool is strict: each action accepts only its own parameters — any other argument is " +
266
+ "rejected. Parameter contract per action:\n" +
267
+ "- list: no parameters\n" +
268
+ "- create_list: name (required), initial_items (optional array of item texts, added when the " +
269
+ "list is created), activate (optional, defaults to true: the new list becomes active; pass false " +
270
+ "to keep the current active list)\n" +
271
+ "- delete_list: list_id (required)\n" +
272
+ "- set_active: list_id (omit the field to deselect)\n" +
273
+ "- add_item: list_id (required), text (required: a string, or an array of strings to add several " +
274
+ "items in one call)\n" +
275
+ "- update_item: item_id (required, listName:index) with optional text/done, or items=" +
276
+ "[{item_id, text?, done?}, ...] for several updates in one call (items may span lists; never " +
277
+ "mix the two forms)\n" +
278
+ "- remove_item: item_id (required, listName:index)";
279
+
280
+ const TRACKER_TOOL_PROMPT_SNIPPET =
281
+ "Manage todolists and track progress: create lists with initial items, add/update/remove items, " +
282
+ "batch adds and updates in one call";
283
+
284
+ const TRACKER_TOOL_PROMPT_GUIDELINES = [
285
+ "Use tracker for todo lists, checklists, and multi-step work. Put progress in tracker, not in prose.",
286
+ "Break work into tracker items up front. One item per deliverable. Mark an item done in the same turn it completes. Never batch the marking at the end. Batch related adds and updates in one call.",
287
+ "Before starting work, call tracker with action list. Work from the list, not from memory. Re-check it when the task drifts.",
288
+ "Copy tracker item ids (listName:index, e.g. Work:2) from the list action output; removing an item renumbers the items after it.",
289
+ "When a tracker call fails, read the error. It tells you what to fix. Not-found errors name the available ids. Retry with corrected parameters in the same turn. Never repeat the same failing call.",
290
+ "The tracker widget shows the active list. create_list makes the new list active by default; pass activate: false to keep the current one. Use set_active to show or hide a list.",
291
+ ];
292
+
293
+ /** Metadata block spread into `pi.registerTool` in index.ts. */
294
+ export const TRACKER_TOOL_METADATA = {
295
+ name: TRACKER_TOOL_NAME,
296
+ label: TRACKER_TOOL_LABEL,
297
+ description: TRACKER_TOOL_DESCRIPTION,
298
+ promptSnippet: TRACKER_TOOL_PROMPT_SNIPPET,
299
+ promptGuidelines: TRACKER_TOOL_PROMPT_GUIDELINES,
300
+ parameters: TrackerToolParams,
301
+ executionMode: "sequential",
302
+ } as const;