@ftrdotdev/pi-tracker 0.3.0 → 0.5.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
@@ -2,18 +2,31 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
2
2
  import { Text } from "@earendil-works/pi-tui";
3
3
  import { makeBorderedBox } from "@ftrdotdev/pi-tui";
4
4
  import { Effect, Layer, ManagedRuntime, Option, Result } from "effect";
5
+ import {
6
+ formatItemRef,
7
+ parseItemRef,
8
+ type DependencyItem,
9
+ type DependencyListView,
10
+ } from "./deps.ts";
5
11
  import { TodoItem, TodoList, TrackerState, emptyState, encodeState } from "./domain.ts";
6
12
  import { TrackerPersistence } from "./persistence.ts";
7
- import { TrackerError, TrackerStore, type UpdateItemPatch } from "./store.ts";
13
+ import { TrackerError, TrackerStore, type ItemSpec, type UpdateItemPatch } from "./store.ts";
8
14
  import {
9
15
  TRACKER_TOOL_METADATA,
16
+ blockedDoneNote,
10
17
  doneMarkReminder,
11
18
  validateTrackerCall,
12
19
  type TrackerToolAction,
13
20
  type TrackerToolDetails,
14
21
  type TrackerToolParams,
15
22
  } from "./tool-metadata.ts";
16
- import { makeTrackerOverlay, makeTrackerWidget, type TrackerUiAction } from "./ui.ts";
23
+ import {
24
+ displayList,
25
+ makeTrackerOverlay,
26
+ makeTrackerWidget,
27
+ readinessSuffix,
28
+ type TrackerUiAction,
29
+ } from "./ui.ts";
17
30
 
18
31
  /** Custom-entry type used to persist the tracker state in the session. */
19
32
  const CUSTOM_TYPE = "tracker/state";
@@ -40,6 +53,19 @@ const requireParam = <T>(value: T | undefined, name: string): T => {
40
53
  return value;
41
54
  };
42
55
 
56
+ /**
57
+ * Normalize the tool's item shapes (a text string, an item object, or an array
58
+ * of either) into the store's item specs.
59
+ */
60
+ const toItemSpecs = (raw: NonNullable<TrackerToolParams["text"]>): ItemSpec[] => {
61
+ const entries = Array.isArray(raw) ? raw : [raw];
62
+ return entries.map((entry) =>
63
+ typeof entry === "string"
64
+ ? entry
65
+ : { text: entry.text, ...(entry.deps === undefined ? {} : { deps: entry.deps }) },
66
+ );
67
+ };
68
+
43
69
  // --------------------------------------------------------------------------
44
70
  // Extension
45
71
  // --------------------------------------------------------------------------
@@ -66,7 +92,9 @@ export default function (pi: ExtensionAPI): void {
66
92
  return withStore((store) =>
67
93
  store.createList(requireParam(params.name, "name"), {
68
94
  activate: params.activate ?? true,
69
- ...(params.initial_items !== undefined ? { initialItems: params.initial_items } : {}),
95
+ ...(params.initial_items !== undefined
96
+ ? { initialItems: toItemSpecs(params.initial_items) }
97
+ : {}),
70
98
  }),
71
99
  );
72
100
  case "delete_list":
@@ -74,28 +102,34 @@ export default function (pi: ExtensionAPI): void {
74
102
  case "set_active":
75
103
  return withStore((store) => store.setActiveList(params.list_id ?? null));
76
104
  case "add_item": {
77
- const raw = requireParam(params.text, "text");
78
- const texts = Array.isArray(raw) ? raw : [raw];
79
- return withStore((store) => store.addItems(requireParam(params.list_id, "list_id"), texts));
105
+ const specs = toItemSpecs(requireParam(params.text, "text"));
106
+ return withStore((store) => store.addItems(requireParam(params.list_id, "list_id"), specs));
80
107
  }
81
108
  case "update_item": {
82
109
  if (params.items !== undefined) {
83
- // Batch form: list_id + index-based patches within one list (mirrors
84
- // add_item's list_id + text[]). The store resolves each index against
85
- // that single list.
110
+ // Batch form: list_id + item-id patches within one list (mirrors
111
+ // add_item's list_id + text[]). The store resolves each id against
112
+ // that single list, so the reference's list name must match it.
86
113
  const listId = requireParam(params.list_id, "list_id");
87
- const batch = params.items;
114
+ const batch = params.items.map((patch) => ({
115
+ itemId: patch.item_id,
116
+ ...(patch.text !== undefined ? { text: patch.text } : {}),
117
+ ...(patch.done !== undefined ? { done: patch.done } : {}),
118
+ ...(patch.deps !== undefined ? { deps: patch.deps } : {}),
119
+ }));
88
120
  return withStore((store) => store.updateItems(listId, batch));
89
121
  }
90
122
  const patch: UpdateItemPatch = {
91
- ...(params.text !== undefined && !Array.isArray(params.text)
92
- ? { text: params.text }
93
- : {}),
123
+ ...(typeof params.text === "string" ? { text: params.text } : {}),
94
124
  ...(params.done !== undefined ? { done: params.done } : {}),
125
+ ...(params.deps !== undefined ? { deps: params.deps } : {}),
95
126
  };
127
+ // Both update_item forms return an affected-items array, so the
128
+ // result contract matches add_item and the renderer/reminder can
129
+ // treat every result the same way.
96
130
  return withStore((store) =>
97
131
  store.updateItem(requireParam(params.item_id, "item_id"), patch),
98
- );
132
+ ).pipe(Effect.map((item) => [item]));
99
133
  }
100
134
  case "remove_item":
101
135
  return withStore((store) => store.removeItem(requireParam(params.item_id, "item_id")));
@@ -121,24 +155,47 @@ export default function (pi: ExtensionAPI): void {
121
155
  }
122
156
  };
123
157
 
158
+ /**
159
+ * Every state change runs through this chain, so the read and the session
160
+ * write of one change stay atomic and in order. Tool calls are sequential
161
+ * already (the tool declares `executionMode`), but a session event is not
162
+ * serialized with them: without this queue, a restore on `session_tree`
163
+ * could land between a change and its write and clobber it.
164
+ */
165
+ let mutationQueue: Promise<void> = Promise.resolve();
166
+
167
+ /** Serialize a state-changing step and keep the chain alive if it fails. */
168
+ const enqueue = <A>(step: () => Promise<A>): Promise<A> => {
169
+ const run = mutationQueue.then(step);
170
+ mutationQueue = run.then(
171
+ () => undefined,
172
+ () => undefined,
173
+ );
174
+ return run;
175
+ };
176
+
124
177
  /**
125
178
  * Persist the current store state and refresh the widget pane. Called after
126
179
  * every successful mutation, from both the tool and the /tracker UI, so the
127
- * two entry points can never diverge.
180
+ * two entry points can never diverge. Returns the state it read, which the
181
+ * tool result is built from, so no surface reads a stale mirror.
128
182
  */
129
- const applyMutation = async (ctx: ExtensionContext): Promise<void> => {
130
- state = await runtime.runPromise(withStore((store) => store.state));
131
- await runtime.runPromise(
132
- withPersistence((p) => p.save(state)).pipe(
133
- Effect.catch((err) =>
134
- Effect.logWarning(
135
- `tracker: persist failed: ${err instanceof Error ? err.message : String(err)}`,
183
+ const applyMutation = (ctx: ExtensionContext): Promise<TrackerState> =>
184
+ enqueue(async () => {
185
+ const next = await runtime.runPromise(withStore((store) => store.state));
186
+ state = next;
187
+ await runtime.runPromise(
188
+ withPersistence((p) => p.save(next)).pipe(
189
+ Effect.catch((err) =>
190
+ Effect.logWarning(
191
+ `tracker: persist failed: ${err instanceof Error ? err.message : String(err)}`,
192
+ ),
136
193
  ),
137
194
  ),
138
- ),
139
- );
140
- refreshWidget(ctx);
141
- };
195
+ );
196
+ refreshWidget(ctx);
197
+ return next;
198
+ });
142
199
 
143
200
  const refreshWidget = (ctx: ExtensionContext): void => {
144
201
  // The widget is the opt-in view of the *active* list: hidden when no list
@@ -163,31 +220,36 @@ export default function (pi: ExtensionAPI): void {
163
220
  });
164
221
  };
165
222
 
166
- /** Rebuild state from the latest tracker custom entry on the current branch. */
167
- const reconstructState = async (ctx: ExtensionContext): Promise<void> => {
168
- let snapshot: unknown = null;
169
- for (const entry of ctx.sessionManager.getBranch()) {
170
- if (entry.type === "custom" && entry.customType === CUSTOM_TYPE) {
171
- snapshot = entry.data;
223
+ /**
224
+ * Rebuild state from the latest tracker custom entry on the current branch.
225
+ * Runs through the same queue as a mutation, so a restore cannot land in the
226
+ * middle of a change and clobber it.
227
+ */
228
+ const reconstructState = (ctx: ExtensionContext): Promise<void> =>
229
+ enqueue(async () => {
230
+ let snapshot: unknown = null;
231
+ for (const entry of ctx.sessionManager.getBranch()) {
232
+ if (entry.type === "custom" && entry.customType === CUSTOM_TYPE) {
233
+ snapshot = entry.data;
234
+ }
172
235
  }
173
- }
174
236
 
175
- if (snapshot === null) {
176
- state = emptyState();
177
- } else {
178
- const result = await runtime.runPromise(
179
- Effect.result(withPersistence((p) => p.restore(snapshot))),
180
- );
181
- if (Result.isFailure(result)) {
182
- ctx.ui.notify("tracker: saved state could not be decoded — starting empty", "warning");
237
+ if (snapshot === null) {
183
238
  state = emptyState();
184
239
  } else {
185
- state = Option.getOrThrow(Result.getSuccess(result));
240
+ const result = await runtime.runPromise(
241
+ Effect.result(withPersistence((p) => p.restore(snapshot))),
242
+ );
243
+ if (Result.isFailure(result)) {
244
+ ctx.ui.notify("tracker: saved state could not be decoded — starting empty", "warning");
245
+ state = emptyState();
246
+ } else {
247
+ state = Option.getOrThrow(Result.getSuccess(result));
248
+ }
186
249
  }
187
- }
188
- await runtime.runPromise(withStore((store) => store.reset(state)));
189
- refreshWidget(ctx);
190
- };
250
+ await runtime.runPromise(withStore((store) => store.reset(state)));
251
+ refreshWidget(ctx);
252
+ });
191
253
 
192
254
  // --- Session lifecycle -------------------------------------------------
193
255
 
@@ -205,29 +267,91 @@ export default function (pi: ExtensionAPI): void {
205
267
 
206
268
  // --- Tool ---------------------------------------------------------------
207
269
 
270
+ /**
271
+ * Derived view of a list for the two `list` surfaces: the items in derived
272
+ * order, each item's blocker annotation by index, the refs that are ready
273
+ * now, and whether the list has any dependency at all. A dependency-free
274
+ * list renders exactly as before. Returning the ordered array keeps the
275
+ * annotations and the rendered rows in step.
276
+ */
277
+ const listAnnotations = <T extends DependencyItem>(
278
+ list: DependencyListView<T>,
279
+ ): {
280
+ readonly items: readonly T[];
281
+ readonly suffixByIndex: readonly string[];
282
+ readonly readyRefs: readonly string[];
283
+ readonly hasDependencies: boolean;
284
+ } => {
285
+ const view = displayList(list);
286
+ return {
287
+ items: view.list.items,
288
+ suffixByIndex: view.ready.map((entry, index) =>
289
+ readinessSuffix(view.list.items[index]!.done, entry.blockers),
290
+ ),
291
+ readyRefs: view.ready
292
+ .filter((entry) => entry.ready)
293
+ .map((entry) => formatItemRef(list.name, entry.id)),
294
+ hasDependencies: view.list.items.some((item) => (item.deps ?? []).length > 0),
295
+ };
296
+ };
297
+
298
+ const readyLine = (refs: readonly string[]): string =>
299
+ ` Ready now: ${refs.length === 0 ? "(none)" : refs.map((ref) => `#${ref}`).join(", ")}`;
300
+
208
301
  const listSummary = (current: TrackerState): string => {
209
302
  if (current.lists.length === 0) return "No lists";
210
303
  return current.lists
211
304
  .map((list) => {
212
305
  const done = list.items.filter((item) => item.done).length;
213
306
  const active = list.id === current.activeListId ? " (active)" : "";
214
- const items =
215
- list.items.length === 0
307
+ const annotations = listAnnotations(list);
308
+ const body =
309
+ annotations.items.length === 0
216
310
  ? " (no items)"
217
- : list.items
311
+ : annotations.items
218
312
  .map(
219
- (item, i) => ` [${item.done ? "x" : " "}] #${list.name}:${i + 1}: ${item.text}`,
313
+ (item, index) =>
314
+ ` [${item.done ? "x" : " "}] #${list.name}:${item.id}: ${item.text}` +
315
+ `${annotations.suffixByIndex[index]}`,
220
316
  )
221
317
  .join("\n");
222
- return `[${list.id}] ${list.name} — ${done}/${list.items.length}${active}\n${items}`;
318
+ const ready = annotations.hasDependencies ? `\n${readyLine(annotations.readyRefs)}` : "";
319
+ return `[${list.id}] ${list.name} — ${done}/${list.items.length}${active}\n${body}${ready}`;
223
320
  })
224
321
  .join("\n");
225
322
  };
226
323
 
324
+ /**
325
+ * The dependency set an item carried before the call, or null when the
326
+ * reference does not resolve there.
327
+ */
328
+ const depsOf = (current: TrackerState, ref: string): readonly string[] | null => {
329
+ const parsed = parseItemRef(ref);
330
+ if (parsed === null) return null;
331
+ const list = current.lists.find((candidate) => candidate.name === parsed.name);
332
+ const item = list?.items.find((candidate) => candidate.id === parsed.id);
333
+ return item?.deps ?? null;
334
+ };
335
+
336
+ /**
337
+ * The `deps` change for one patch. `deps` replaces the whole set, so the
338
+ * result names the set before and after whenever they differ: a dependency
339
+ * that the call dropped must not disappear from the report.
340
+ */
341
+ const depsChange = (ref: string, next: readonly string[], before: TrackerState): string => {
342
+ const previous = depsOf(before, ref);
343
+ const after = next.length === 0 ? "deps cleared" : `deps: ${next.join(", ")}`;
344
+ if (previous === null || previous.join(",") === next.join(",")) return after;
345
+ return next.length === 0
346
+ ? `deps cleared (was ${previous.join(", ")})`
347
+ : `deps: ${previous.join(", ")} → ${next.join(", ")}`;
348
+ };
349
+
227
350
  const toolSuccess = (
228
351
  params: TrackerToolParams,
229
352
  value: unknown,
230
353
  current: TrackerState,
354
+ before: TrackerState,
231
355
  ): { content: Array<{ type: "text"; text: string }>; details: TrackerToolDetails } => {
232
356
  const details: TrackerToolDetails = { action: params.action };
233
357
  let text = "";
@@ -266,10 +390,8 @@ export default function (pi: ExtensionAPI): void {
266
390
  details.list = list;
267
391
  details.items = items;
268
392
  const listName = list ? list.name : `#${params.list_id}`;
269
- // The new items are the last ones in the list, so their ids follow
270
- // directly from the position they now occupy.
271
- const firstId = list ? list.items.length - items.length + 1 : 1;
272
- const ids = items.map((_, i) => `${listName}:${firstId + i}`);
393
+ // The store assigned each new item its id; report those.
394
+ const ids = items.map((item) => `${listName}:${item.id}`);
273
395
  text =
274
396
  items.length === 1
275
397
  ? `Added item #${ids[0]} to ${listName}: ${items[0]!.text}`
@@ -282,20 +404,25 @@ export default function (pi: ExtensionAPI): void {
282
404
  // Normalize both forms into patch records the renderer and reminder
283
405
  // share: each has a display id plus optional text/done.
284
406
  const batch = params.items;
285
- const list =
286
- batch !== undefined ? current.lists.find((l) => l.id === params.list_id) : undefined;
287
- const listName = list ? list.name : `#${params.list_id}`;
288
- const patches: Array<{ id: string; text?: string; done?: boolean }> =
407
+ const patches: Array<{
408
+ id: string;
409
+ text?: string;
410
+ done?: boolean;
411
+ deps?: readonly string[];
412
+ }> =
289
413
  batch !== undefined
290
- ? batch.map((p) => ({ id: `${listName}:${p.index}`, text: p.text, done: p.done }))
414
+ ? batch.map((p) => ({
415
+ id: p.item_id,
416
+ text: p.text,
417
+ done: p.done,
418
+ deps: p.deps,
419
+ }))
291
420
  : [
292
421
  {
293
422
  id: params.item_id ?? "?",
294
- text:
295
- params.text !== undefined && !Array.isArray(params.text)
296
- ? params.text
297
- : undefined,
423
+ text: typeof params.text === "string" ? params.text : undefined,
298
424
  done: params.done,
425
+ deps: params.deps,
299
426
  },
300
427
  ];
301
428
  const parts = items.map((item, i) => {
@@ -303,6 +430,9 @@ export default function (pi: ExtensionAPI): void {
303
430
  const changes: string[] = [];
304
431
  if (patch.done !== undefined) changes.push(item.done ? "completed" : "uncompleted");
305
432
  if (patch.text !== undefined) changes.push(`text: ${item.text}`);
433
+ if (patch.deps !== undefined) {
434
+ changes.push(depsChange(patch.id, patch.deps, before));
435
+ }
306
436
  return `${patch.id}${changes.length === 0 ? " (no change)" : ` (${changes.join(", ")})`}`;
307
437
  });
308
438
  text = `Updated ${items.length} item${items.length === 1 ? "" : "s"}: ${parts.join(", ")}`;
@@ -317,11 +447,16 @@ export default function (pi: ExtensionAPI): void {
317
447
  );
318
448
  const reminder = doneMarkReminder(patches, openRemaining);
319
449
  if (reminder !== null) text += `\n${reminder}`;
450
+ // Reopening an item, or giving a done item an open dependency, can
451
+ // leave done work unsatisfied. The tracker does not cascade, so say it
452
+ // out loud instead of silently re-planning.
453
+ const blockedDone = blockedDoneNote(patches, current);
454
+ if (blockedDone !== null) text += `\n${blockedDone}`;
320
455
  break;
321
456
  }
322
457
  case "remove_item":
323
458
  details.itemId = params.item_id;
324
- text = `Removed item ${params.item_id} (items after it renumbered)`;
459
+ text = `Removed item ${params.item_id}`;
325
460
  break;
326
461
  }
327
462
  return { content: [{ type: "text", text }], details };
@@ -354,16 +489,24 @@ export default function (pi: ExtensionAPI): void {
354
489
  return toolError(action, err instanceof Error ? err.message : String(err));
355
490
  }
356
491
 
492
+ // The state as this call finds it, so a result can name what a change
493
+ // replaced. Only the actions that report a diff read it.
494
+ const before =
495
+ action === "update_item"
496
+ ? await runtime.runPromise(withStore((store) => store.state))
497
+ : state;
498
+
357
499
  const result = await runtime.runPromise(Effect.result(program));
358
500
  if (Result.isFailure(result)) {
359
501
  const failure = Option.getOrThrow(Result.getFailure(result));
360
502
  return toolError(action, failure.message);
361
503
  }
362
-
363
- if (action !== "list") {
364
- await applyMutation(ctx);
365
- }
366
- return toolSuccess(params, Option.getOrThrow(Result.getSuccess(result)), state);
504
+ const value = Option.getOrThrow(Result.getSuccess(result));
505
+ // `list` reports the store state it just read; a mutation reports the
506
+ // state it persisted. Both are authoritative, so no result depends on
507
+ // the widget mirror.
508
+ const current = action === "list" ? (value as TrackerState) : await applyMutation(ctx);
509
+ return toolSuccess(params, value, current, before);
367
510
  },
368
511
 
369
512
  renderCall(args, theme, _context) {
@@ -409,14 +552,21 @@ export default function (pi: ExtensionAPI): void {
409
552
  theme.fg("accent", `[${list.id}] ${list.name}`) +
410
553
  theme.fg("muted", ` (${done}/${list.items.length})${active}`),
411
554
  );
412
- const display = expanded ? list.items : list.items.slice(0, 5);
413
- for (const [idx, item] of display.entries()) {
555
+ const annotations = listAnnotations(list);
556
+ const display = expanded ? annotations.items : annotations.items.slice(0, 5);
557
+ for (const [index, item] of display.entries()) {
414
558
  const check = item.done ? theme.fg("success", "✓") : theme.fg("dim", "○");
415
559
  const itemText = item.done ? theme.fg("dim", item.text) : item.text;
416
- parts.push(` ${check} ${theme.fg("accent", `#${list.name}:${idx + 1}`)} ${itemText}`);
560
+ const blocked = theme.fg("dim", annotations.suffixByIndex[index] ?? "");
561
+ parts.push(
562
+ ` ${check} ${theme.fg("accent", `#${list.name}:${item.id}`)} ${itemText}${blocked}`,
563
+ );
564
+ }
565
+ if (!expanded && annotations.items.length > 5) {
566
+ parts.push(theme.fg("dim", ` ... ${annotations.items.length - 5} more`));
417
567
  }
418
- if (!expanded && list.items.length > 5) {
419
- parts.push(theme.fg("dim", ` ... ${list.items.length - 5} more`));
568
+ if (annotations.hasDependencies) {
569
+ parts.push(theme.fg("muted", readyLine(annotations.readyRefs)));
420
570
  }
421
571
  }
422
572
  return new Text(parts.join("\n"), 0, 0);
@@ -25,15 +25,17 @@ layer(
25
25
  new TodoList({
26
26
  id: 1,
27
27
  name: "Work",
28
+ nextItemId: 3,
28
29
  items: [
29
- new TodoItem({ text: "write plan", done: true }),
30
- new TodoItem({ text: "implement tracker", done: false }),
30
+ new TodoItem({ id: 1, text: "write plan", done: true }),
31
+ new TodoItem({ id: 2, text: "implement tracker", done: false }),
31
32
  ],
32
33
  }),
33
34
  new TodoList({
34
35
  id: 2,
35
36
  name: "Home",
36
- items: [new TodoItem({ text: "water plants", done: false })],
37
+ nextItemId: 2,
38
+ items: [new TodoItem({ id: 1, text: "water plants", done: false })],
37
39
  }),
38
40
  ],
39
41
  activeListId: 1,
@@ -145,10 +147,13 @@ layer(
145
147
  }),
146
148
  );
147
149
 
148
- it.effect("restore accepts legacy snapshots (stored item ids are ignored)", () =>
150
+ it.effect("restore assigns legacy item ids by position (no per-list counter stored)", () =>
149
151
  Effect.gen(function* () {
150
152
  resetCapture();
151
153
  const persistence = yield* TrackerPersistence;
154
+ // A list written before item ids existed carries no nextItemId, so its
155
+ // stored (session-wide) numeric ids are ignored and reassigned from each
156
+ // item's position.
152
157
  const legacy = {
153
158
  lists: [{ id: 1, name: "Work", items: [{ id: 7, text: "a", done: false }] }],
154
159
  activeListId: 1,
@@ -159,13 +164,107 @@ layer(
159
164
  const restored = yield* persistence.restore(legacy);
160
165
  const expected = new TrackerState({
161
166
  lists: [
162
- new TodoList({ id: 1, name: "Work", items: [new TodoItem({ text: "a", done: false })] }),
167
+ new TodoList({
168
+ id: 1,
169
+ name: "Work",
170
+ nextItemId: 2,
171
+ items: [new TodoItem({ id: 1, text: "a", done: false })],
172
+ }),
163
173
  ],
164
174
  activeListId: 1,
165
175
  nextListId: 2,
166
176
  });
167
177
  assert.deepStrictEqual(encodeState(restored), encodeState(expected));
168
- assert.deepStrictEqual(restored.lists[0]?.items, [new TodoItem({ text: "a", done: false })]);
178
+ assert.deepStrictEqual(restored.lists[0]?.items, [
179
+ new TodoItem({ id: 1, text: "a", done: false }),
180
+ ]);
181
+ }),
182
+ );
183
+
184
+ it.effect("restore gives a legacy item without an id its position as the id", () =>
185
+ Effect.gen(function* () {
186
+ resetCapture();
187
+ const persistence = yield* TrackerPersistence;
188
+ const legacy = {
189
+ lists: [
190
+ {
191
+ id: 1,
192
+ name: "Work",
193
+ items: [
194
+ { text: "a", done: false },
195
+ { text: "b", done: true },
196
+ ],
197
+ },
198
+ ],
199
+ activeListId: 1,
200
+ nextListId: 2,
201
+ };
202
+
203
+ const restored = yield* persistence.restore(legacy);
204
+
205
+ assert.deepStrictEqual(
206
+ restored.lists[0]?.items.map((i) => i.id),
207
+ [1, 2],
208
+ );
209
+ assert.deepStrictEqual(
210
+ restored.lists[0]?.items.map((i) => i.deps),
211
+ [[], []],
212
+ );
213
+ assert.strictEqual(restored.lists[0]?.nextItemId, 3);
214
+ }),
215
+ );
216
+
217
+ it.effect("restore keeps stored ids and raises a counter that lags behind them", () =>
218
+ Effect.gen(function* () {
219
+ resetCapture();
220
+ const persistence = yield* TrackerPersistence;
221
+ // The list stored a counter (so its ids are real), but the counter is
222
+ // lower than the highest id: it must not hand out an id twice.
223
+ const snapshot = {
224
+ lists: [
225
+ {
226
+ id: 1,
227
+ name: "Work",
228
+ nextItemId: 2,
229
+ items: [
230
+ { id: 1, text: "a", done: false, deps: [] },
231
+ { id: 7, text: "b", done: false, deps: ["Work:1"] },
232
+ ],
233
+ },
234
+ ],
235
+ activeListId: 1,
236
+ nextListId: 2,
237
+ };
238
+
239
+ const restored = yield* persistence.restore(snapshot);
240
+
241
+ assert.deepStrictEqual(
242
+ restored.lists[0]?.items.map((i) => i.id),
243
+ [1, 7],
244
+ );
245
+ assert.deepStrictEqual(restored.lists[0]?.items[1]?.deps, ["Work:1"]);
246
+ assert.strictEqual(restored.lists[0]?.nextItemId, 8);
247
+ }),
248
+ );
249
+
250
+ it.effect("restore tolerates a legacy string item id (the session stays loadable)", () =>
251
+ Effect.gen(function* () {
252
+ resetCapture();
253
+ const persistence = yield* TrackerPersistence;
254
+ // Deleting this session's lists would be data loss, so a string id is
255
+ // dropped at the boundary instead of failing the whole decode.
256
+ const legacy = {
257
+ lists: [{ id: 1, name: "Work", items: [{ id: "Work:1", text: "a", done: false }] }],
258
+ activeListId: 1,
259
+ nextListId: 2,
260
+ };
261
+
262
+ const restored = yield* persistence.restore(legacy);
263
+
264
+ assert.deepStrictEqual(
265
+ restored.lists[0]?.items.map((i) => [i.id, i.text]),
266
+ [[1, "a"]],
267
+ );
169
268
  }),
170
269
  );
171
270
 
@@ -1,5 +1,5 @@
1
1
  import { Context, Effect, Layer, Schema } from "effect";
2
- import { TrackerState, decodeStateEffect, encodeStateEffect } from "./domain.ts";
2
+ import { TrackerState, decodeStateEffect, encodeStateEffect, migrateState } from "./domain.ts";
3
3
 
4
4
  /** The plain JSON shape of a `TrackerState` (what goes into the session). */
5
5
  export type EncodedState = Schema.Codec.Encoded<typeof TrackerState>;
@@ -14,7 +14,9 @@ export type EncodedState = Schema.Codec.Encoded<typeof TrackerState>;
14
14
  *
15
15
  * `restore` decodes an untrusted snapshot (e.g. `data` from a session custom
16
16
  * entry) back into a validated `TrackerState`, failing with a `SchemaError`
17
- * on malformed input.
17
+ * on malformed input. A decoded snapshot is then migrated, so every state that
18
+ * reaches the store has a real id on every item and an item counter above each
19
+ * list's ids.
18
20
  *
19
21
  * The service has no Pi dependency: `append` is injected, which keeps the
20
22
  * whole persistence path testable with an in-memory capture.
@@ -39,7 +41,7 @@ export class TrackerPersistence extends Context.Service<
39
41
  });
40
42
 
41
43
  const restore = Effect.fn("TrackerPersistence.restore")(function* (snapshot: unknown) {
42
- return yield* decodeStateEffect(snapshot);
44
+ return migrateState(yield* decodeStateEffect(snapshot));
43
45
  });
44
46
 
45
47
  return TrackerPersistence.of({ save, restore });