@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.
package/src/store.ts ADDED
@@ -0,0 +1,517 @@
1
+ import { Context, Effect, Layer, Ref, Result, Schema } from "effect";
2
+ import { TodoItem, TodoList, TrackerState, emptyState } from "./domain.ts";
3
+
4
+ // --------------------------------------------------------------------------
5
+ // Errors
6
+ // --------------------------------------------------------------------------
7
+
8
+ const Reason = Schema.Union([
9
+ Schema.Literal("ListNotFound"),
10
+ Schema.Literal("ItemNotFound"),
11
+ Schema.Literal("EmptyText"),
12
+ Schema.Literal("DuplicateListName"),
13
+ ]);
14
+
15
+ export type TrackerErrorReason = Schema.Schema.Type<typeof Reason>;
16
+
17
+ export class TrackerError extends Schema.TaggedError<TrackerError>()("TrackerError", {
18
+ reason: Reason,
19
+ message: Schema.String,
20
+ listId: Schema.optional(Schema.Int),
21
+ itemId: Schema.optional(Schema.String),
22
+ }) {}
23
+
24
+ /**
25
+ * Not-found messages name the available ids so the caller (the LLM) can
26
+ * retry without an extra round trip. Empty lists produce a "no lists / no
27
+ * items" hint instead.
28
+ */
29
+ const listNotFoundMessage = (s: TrackerState, listId: number): string => {
30
+ const available = s.lists.map((list) => `#${list.id}`).join(", ");
31
+ return available === ""
32
+ ? `List #${listId} not found (no lists exist)`
33
+ : `List #${listId} not found — available: ${available}`;
34
+ };
35
+
36
+ /**
37
+ * Parse a `listName:index` item id (e.g. `Work:2`). Splits on the *last*
38
+ * colon so list names may contain colons; the index must be a positive
39
+ * integer. Returns null for anything that is not a well-formed id.
40
+ */
41
+ const parseItemId = (
42
+ itemId: string,
43
+ ): { readonly listName: string; readonly index: number } | null => {
44
+ const colon = itemId.lastIndexOf(":");
45
+ if (colon <= 0 || colon === itemId.length - 1) return null;
46
+ const indexText = itemId.slice(colon + 1);
47
+ if (!/^[1-9]\d*$/.test(indexText)) return null;
48
+ return { listName: itemId.slice(0, colon), index: Number(indexText) };
49
+ };
50
+
51
+ /** Outcome of resolving an item id against a state. */
52
+ type ResolvedItem =
53
+ | { readonly kind: "malformed" }
54
+ | { readonly kind: "noList"; readonly listName: string }
55
+ | { readonly kind: "noItem"; readonly list: TodoList }
56
+ | {
57
+ readonly kind: "ok";
58
+ readonly list: TodoList;
59
+ readonly item: TodoItem;
60
+ readonly index: number;
61
+ };
62
+
63
+ /** Resolve `listName:index` against the current state (index is 1-based). */
64
+ const resolveItem = (s: TrackerState, itemId: string): ResolvedItem => {
65
+ const parsed = parseItemId(itemId);
66
+ if (!parsed) return { kind: "malformed" };
67
+ const list = s.lists.find((l) => l.name === parsed.listName);
68
+ if (!list) return { kind: "noList", listName: parsed.listName };
69
+ const item = list.items[parsed.index - 1];
70
+ if (!item) return { kind: "noItem", list };
71
+ return { kind: "ok", list, item, index: parsed.index };
72
+ };
73
+
74
+ /**
75
+ * Resolve an item id, or build the not-found error naming what the caller
76
+ * (the LLM) can use instead. Not-found messages list the available ids so a
77
+ * stale reference self-corrects on the next attempt.
78
+ */
79
+ const resolveItemOrError = (
80
+ s: TrackerState,
81
+ itemId: string,
82
+ ):
83
+ | { readonly ok: true; readonly list: TodoList; readonly item: TodoItem; readonly index: number }
84
+ | { readonly ok: false; readonly error: TrackerError } => {
85
+ const resolved = resolveItem(s, itemId);
86
+ switch (resolved.kind) {
87
+ case "malformed":
88
+ return {
89
+ ok: false,
90
+ error: new TrackerError({
91
+ reason: "ItemNotFound",
92
+ message: `Item "${itemId}" must look like "listName:index" (e.g. "Work:2")`,
93
+ itemId,
94
+ }),
95
+ };
96
+ case "noList": {
97
+ const available = s.lists.map((list) => `[${list.id}] ${list.name}`).join(", ");
98
+ return {
99
+ ok: false,
100
+ error: new TrackerError({
101
+ reason: "ItemNotFound",
102
+ message:
103
+ available === ""
104
+ ? `Item "${itemId}" not found — no lists exist`
105
+ : `Item "${itemId}" not found — no list named "${resolved.listName}" (available: ${available})`,
106
+ itemId,
107
+ }),
108
+ };
109
+ }
110
+ case "noItem": {
111
+ const available = resolved.list.items
112
+ .map((_, i) => `${resolved.list.name}:${i + 1}`)
113
+ .join(", ");
114
+ return {
115
+ ok: false,
116
+ error: new TrackerError({
117
+ reason: "ItemNotFound",
118
+ message:
119
+ available === ""
120
+ ? `Item "${itemId}" not found in list "${resolved.list.name}" (no items)`
121
+ : `Item "${itemId}" not found in list "${resolved.list.name}" — available: ${available}`,
122
+ listId: resolved.list.id,
123
+ itemId,
124
+ }),
125
+ };
126
+ }
127
+ case "ok":
128
+ return { ok: true, list: resolved.list, item: resolved.item, index: resolved.index };
129
+ }
130
+ };
131
+
132
+ // --------------------------------------------------------------------------
133
+ // Store
134
+ // --------------------------------------------------------------------------
135
+
136
+ export interface UpdateItemPatch {
137
+ readonly text?: string;
138
+ readonly done?: boolean;
139
+ }
140
+
141
+ /** An `UpdateItemPatch` that also names the item it targets (batch form). */
142
+ export interface UpdateItemPatchWithId extends UpdateItemPatch {
143
+ /** `listName:index`, as shown by the list action (e.g. `Work:2`). */
144
+ readonly itemId: string;
145
+ }
146
+
147
+ /** Options for `createList`: activation behavior and initial items. */
148
+ export interface CreateListOptions {
149
+ /** Make the new list the active list (defaults to true). */
150
+ readonly activate?: boolean;
151
+ /** Initial item texts, added when the list is created (atomic with the list). */
152
+ readonly initialItems?: readonly string[];
153
+ }
154
+
155
+ export class TrackerStore extends Context.Service<
156
+ TrackerStore,
157
+ {
158
+ readonly state: Effect.Effect<TrackerState>;
159
+ readonly reset: (state: TrackerState) => Effect.Effect<void>;
160
+ readonly createList: (
161
+ name: string,
162
+ options?: CreateListOptions,
163
+ ) => Effect.Effect<TodoList, TrackerError>;
164
+ readonly deleteList: (listId: number) => Effect.Effect<void, TrackerError>;
165
+ readonly setActiveList: (listId: number | null) => Effect.Effect<void, TrackerError>;
166
+ readonly addItem: (listId: number, text: string) => Effect.Effect<TodoItem, TrackerError>;
167
+ readonly addItems: (
168
+ listId: number,
169
+ texts: readonly string[],
170
+ ) => Effect.Effect<TodoItem[], TrackerError>;
171
+ readonly updateItem: (
172
+ itemId: string,
173
+ patch: UpdateItemPatch,
174
+ ) => Effect.Effect<TodoItem, TrackerError>;
175
+ readonly updateItems: (
176
+ patches: readonly UpdateItemPatchWithId[],
177
+ ) => Effect.Effect<TodoItem[], TrackerError>;
178
+ readonly removeItem: (itemId: string) => Effect.Effect<void, TrackerError>;
179
+ }
180
+ >()("tracker/TrackerStore") {
181
+ static readonly layer: Layer.Layer<TrackerStore> = Layer.effect(
182
+ TrackerStore,
183
+ Effect.gen(function* () {
184
+ const ref = yield* Ref.make(emptyState());
185
+
186
+ /**
187
+ * Atomic read-modify-write. The callback validates against the current
188
+ * state and either fails with `Result.fail` (state untouched) or
189
+ * succeeds with `Result.succeed(result)` plus the next state.
190
+ */
191
+ const mutate = <A>(
192
+ f: (s: TrackerState) => readonly [Result.Result<A, TrackerError>, TrackerState],
193
+ ): Effect.Effect<A, TrackerError> =>
194
+ Ref.modify(ref, f).pipe(Effect.flatMap(Effect.fromResult));
195
+
196
+ const state: Effect.Effect<TrackerState> = Ref.get(ref);
197
+
198
+ const reset = Effect.fn("TrackerStore.reset")(function* (state: TrackerState) {
199
+ yield* Ref.set(ref, state);
200
+ });
201
+
202
+ const createList = Effect.fn("TrackerStore.createList")(function* (
203
+ name: string,
204
+ options: CreateListOptions = {},
205
+ ) {
206
+ const trimmed = name.trim();
207
+ if (trimmed === "") {
208
+ return yield* new TrackerError({
209
+ reason: "EmptyText",
210
+ message: "List name must not be empty",
211
+ });
212
+ }
213
+ const initialItems = (options.initialItems ?? []).map((text) => text.trim());
214
+ if (initialItems.some((text) => text === "")) {
215
+ return yield* new TrackerError({
216
+ reason: "EmptyText",
217
+ message: "Item text must not be empty",
218
+ });
219
+ }
220
+ const activate = options.activate ?? true;
221
+ return yield* mutate(
222
+ (s): readonly [Result.Result<TodoList, TrackerError>, TrackerState] => {
223
+ if (s.lists.some((list) => list.name === trimmed)) {
224
+ return [
225
+ Result.fail(
226
+ new TrackerError({
227
+ reason: "DuplicateListName",
228
+ message: `List "${trimmed}" already exists`,
229
+ }),
230
+ ),
231
+ s,
232
+ ];
233
+ }
234
+ const items = initialItems.map((text) => new TodoItem({ text, done: false }));
235
+ const list = new TodoList({ id: s.nextListId, name: trimmed, items });
236
+ return [
237
+ Result.succeed(list),
238
+ new TrackerState({
239
+ ...s,
240
+ lists: [...s.lists, list],
241
+ // The new list becomes the active list by default (the widget
242
+ // switches to it); pass activate: false to keep the current
243
+ // active list (or stay without one).
244
+ activeListId: activate ? list.id : s.activeListId,
245
+ nextListId: s.nextListId + 1,
246
+ }),
247
+ ];
248
+ },
249
+ );
250
+ });
251
+
252
+ const deleteList = Effect.fn("TrackerStore.deleteList")(function* (listId: number) {
253
+ return yield* mutate((s): readonly [Result.Result<void, TrackerError>, TrackerState] => {
254
+ if (!s.lists.some((list) => list.id === listId)) {
255
+ return [
256
+ Result.fail(
257
+ new TrackerError({
258
+ reason: "ListNotFound",
259
+ message: listNotFoundMessage(s, listId),
260
+ listId,
261
+ }),
262
+ ),
263
+ s,
264
+ ];
265
+ }
266
+ const lists = s.lists.filter((list) => list.id !== listId);
267
+ const activeListId = s.activeListId === listId ? null : s.activeListId;
268
+ return [Result.succeed(undefined), new TrackerState({ ...s, lists, activeListId })];
269
+ });
270
+ });
271
+
272
+ const setActiveList = Effect.fn("TrackerStore.setActiveList")(function* (
273
+ listId: number | null,
274
+ ) {
275
+ return yield* mutate((s): readonly [Result.Result<void, TrackerError>, TrackerState] => {
276
+ if (listId === null) {
277
+ return [Result.succeed(undefined), new TrackerState({ ...s, activeListId: null })];
278
+ }
279
+ if (!s.lists.some((list) => list.id === listId)) {
280
+ return [
281
+ Result.fail(
282
+ new TrackerError({
283
+ reason: "ListNotFound",
284
+ message: listNotFoundMessage(s, listId),
285
+ listId,
286
+ }),
287
+ ),
288
+ s,
289
+ ];
290
+ }
291
+ return [Result.succeed(undefined), new TrackerState({ ...s, activeListId: listId })];
292
+ });
293
+ });
294
+
295
+ const addItem = Effect.fn("TrackerStore.addItem")(function* (listId: number, text: string) {
296
+ const trimmed = text.trim();
297
+ if (trimmed === "") {
298
+ return yield* new TrackerError({
299
+ reason: "EmptyText",
300
+ message: "Item text must not be empty",
301
+ });
302
+ }
303
+ return yield* mutate(
304
+ (s): readonly [Result.Result<TodoItem, TrackerError>, TrackerState] => {
305
+ const list = s.lists.find((l) => l.id === listId);
306
+ if (!list) {
307
+ return [
308
+ Result.fail(
309
+ new TrackerError({
310
+ reason: "ListNotFound",
311
+ message: listNotFoundMessage(s, listId),
312
+ listId,
313
+ }),
314
+ ),
315
+ s,
316
+ ];
317
+ }
318
+ const item = new TodoItem({ text: trimmed, done: false });
319
+ const lists = s.lists.map((l) =>
320
+ l.id === listId
321
+ ? new TodoList({ id: l.id, name: l.name, items: [...l.items, item] })
322
+ : l,
323
+ );
324
+ return [Result.succeed(item), new TrackerState({ ...s, lists })];
325
+ },
326
+ );
327
+ });
328
+
329
+ const addItems = Effect.fn("TrackerStore.addItems")(function* (
330
+ listId: number,
331
+ texts: readonly string[],
332
+ ) {
333
+ const trimmed = texts.map((text) => text.trim());
334
+ if (trimmed.some((text) => text === "")) {
335
+ return yield* new TrackerError({
336
+ reason: "EmptyText",
337
+ message: "Item text must not be empty",
338
+ });
339
+ }
340
+ return yield* mutate(
341
+ (s): readonly [Result.Result<TodoItem[], TrackerError>, TrackerState] => {
342
+ const list = s.lists.find((l) => l.id === listId);
343
+ if (!list) {
344
+ return [
345
+ Result.fail(
346
+ new TrackerError({
347
+ reason: "ListNotFound",
348
+ message: listNotFoundMessage(s, listId),
349
+ listId,
350
+ }),
351
+ ),
352
+ s,
353
+ ];
354
+ }
355
+ const items = trimmed.map((text) => new TodoItem({ text, done: false }));
356
+ const lists = s.lists.map((l) =>
357
+ l.id === listId
358
+ ? new TodoList({ id: l.id, name: l.name, items: [...l.items, ...items] })
359
+ : l,
360
+ );
361
+ return [Result.succeed(items), new TrackerState({ ...s, lists })];
362
+ },
363
+ );
364
+ });
365
+
366
+ const updateItem = Effect.fn("TrackerStore.updateItem")(function* (
367
+ itemId: string,
368
+ patch: UpdateItemPatch,
369
+ ) {
370
+ const trimmed = patch.text === undefined ? undefined : patch.text.trim();
371
+ if (patch.text !== undefined && trimmed === "") {
372
+ return yield* new TrackerError({
373
+ reason: "EmptyText",
374
+ message: "Item text must not be empty",
375
+ });
376
+ }
377
+ return yield* mutate(
378
+ (s): readonly [Result.Result<TodoItem, TrackerError>, TrackerState] => {
379
+ const resolved = resolveItemOrError(s, itemId);
380
+ if (!resolved.ok) {
381
+ return [Result.fail(resolved.error), s];
382
+ }
383
+ const { list, item } = resolved;
384
+ if (patch.text === undefined && patch.done === undefined) {
385
+ // No-op patch: return the current item, leave state untouched.
386
+ return [Result.succeed(item), s];
387
+ }
388
+ const next = new TodoItem({
389
+ text: trimmed ?? item.text,
390
+ done: patch.done ?? item.done,
391
+ });
392
+ const lists = s.lists.map((l) =>
393
+ l.id === list.id
394
+ ? new TodoList({
395
+ id: l.id,
396
+ name: l.name,
397
+ items: l.items.map((i, idx) => (idx === resolved.index - 1 ? next : i)),
398
+ })
399
+ : l,
400
+ );
401
+ return [Result.succeed(next), new TrackerState({ ...s, lists })];
402
+ },
403
+ );
404
+ });
405
+
406
+ /**
407
+ * Batched updates. Each patch's `itemId` names its own list
408
+ * (`listName:index`), so one batch may span several lists. The whole
409
+ * batch fails atomically if any target is missing.
410
+ */
411
+ const updateItems = Effect.fn("TrackerStore.updateItems")(function* (
412
+ patches: readonly UpdateItemPatchWithId[],
413
+ ) {
414
+ // Reject empty replacement texts up front so the whole batch fails
415
+ // before touching the state (atomicity).
416
+ for (const patch of patches) {
417
+ if (patch.text !== undefined && patch.text.trim() === "") {
418
+ return yield* new TrackerError({
419
+ reason: "EmptyText",
420
+ message: "Item text must not be empty",
421
+ });
422
+ }
423
+ }
424
+ return yield* mutate(
425
+ (s): readonly [Result.Result<TodoItem[], TrackerError>, TrackerState] => {
426
+ // Every target item must exist; the batch fails atomically otherwise.
427
+ const resolved: Array<{
428
+ readonly index: number;
429
+ readonly list: TodoList;
430
+ readonly item: TodoItem;
431
+ }> = [];
432
+ for (const patch of patches) {
433
+ const r = resolveItemOrError(s, patch.itemId);
434
+ if (!r.ok) {
435
+ return [Result.fail(r.error), s];
436
+ }
437
+ resolved.push({ index: r.index, list: r.list, item: r.item });
438
+ }
439
+ // All-empty batch: return the current items, leave state untouched.
440
+ if (patches.every((patch) => patch.text === undefined && patch.done === undefined)) {
441
+ return [Result.succeed(resolved.map((r) => r.item)), s];
442
+ }
443
+ // Later patches win for duplicate positions. Group by list id so
444
+ // affected lists are rebuilt exactly once each.
445
+ const byList = new Map<number, Map<number, UpdateItemPatch>>();
446
+ for (const [i, patch] of patches.entries()) {
447
+ const listId = resolved[i]!.list.id;
448
+ let patchesByIndex = byList.get(listId);
449
+ if (!patchesByIndex) {
450
+ patchesByIndex = new Map();
451
+ byList.set(listId, patchesByIndex);
452
+ }
453
+ patchesByIndex.set(resolved[i]!.index, patch);
454
+ }
455
+ const lists = s.lists.map((l) => {
456
+ const patchesByIndex = byList.get(l.id);
457
+ if (!patchesByIndex) return l;
458
+ const nextItems = l.items.map((item, idx) => {
459
+ const patch = patchesByIndex.get(idx + 1);
460
+ if (!patch) return item;
461
+ const text = patch.text === undefined ? item.text : patch.text.trim();
462
+ const done = patch.done ?? item.done;
463
+ return new TodoItem({ text, done });
464
+ });
465
+ return new TodoList({ id: l.id, name: l.name, items: nextItems });
466
+ });
467
+ return [
468
+ // Results in patch order so the caller can map them 1:1.
469
+ Result.succeed(
470
+ resolved.map((r) => lists.find((l) => l.id === r.list.id)!.items[r.index - 1]!),
471
+ ),
472
+ new TrackerState({ ...s, lists }),
473
+ ];
474
+ },
475
+ );
476
+ });
477
+
478
+ /**
479
+ * Remove an item. Positions shift implicitly: the item that followed
480
+ * the removed one takes its index, so `Work:3` becomes `Work:2`. The
481
+ * error message lists the fresh ids for a stale reference.
482
+ */
483
+ const removeItem = Effect.fn("TrackerStore.removeItem")(function* (itemId: string) {
484
+ return yield* mutate((s): readonly [Result.Result<void, TrackerError>, TrackerState] => {
485
+ const resolved = resolveItemOrError(s, itemId);
486
+ if (!resolved.ok) {
487
+ return [Result.fail(resolved.error), s];
488
+ }
489
+ const { list, index } = resolved;
490
+ const lists = s.lists.map((l) =>
491
+ l.id === list.id
492
+ ? new TodoList({
493
+ id: l.id,
494
+ name: l.name,
495
+ items: l.items.filter((_, idx) => idx !== index - 1),
496
+ })
497
+ : l,
498
+ );
499
+ return [Result.succeed(undefined), new TrackerState({ ...s, lists })];
500
+ });
501
+ });
502
+
503
+ return TrackerStore.of({
504
+ state,
505
+ reset,
506
+ createList,
507
+ deleteList,
508
+ setActiveList,
509
+ addItem,
510
+ addItems,
511
+ updateItem,
512
+ updateItems,
513
+ removeItem,
514
+ });
515
+ }),
516
+ );
517
+ }