@ftrdotdev/pi-tracker 0.4.0 → 0.5.1

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 CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Context, Effect, Layer, Ref, Result, Schema } from "effect";
2
+ import { blockersOf, cyclePath, dependentsOf, formatItemRef, parseItemRef } from "./deps.ts";
2
3
  import { TodoItem, TodoList, TrackerState, emptyState } from "./domain.ts";
3
4
 
4
5
  // --------------------------------------------------------------------------
@@ -10,6 +11,11 @@ const Reason = Schema.Union([
10
11
  Schema.Literal("ItemNotFound"),
11
12
  Schema.Literal("EmptyText"),
12
13
  Schema.Literal("DuplicateListName"),
14
+ Schema.Literal("DependencyNotFound"),
15
+ Schema.Literal("CrossListDependency"),
16
+ Schema.Literal("DependencyCycle"),
17
+ Schema.Literal("ItemBlocked"),
18
+ Schema.Literal("ItemDependedOn"),
13
19
  ]);
14
20
 
15
21
  export type TrackerErrorReason = Schema.Schema.Type<typeof Reason>;
@@ -33,21 +39,6 @@ const listNotFoundMessage = (s: TrackerState, listId: number): string => {
33
39
  : `List #${listId} not found — available: ${available}`;
34
40
  };
35
41
 
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
42
  /** Outcome of resolving an item id against a state. */
52
43
  type ResolvedItem =
53
44
  | { readonly kind: "malformed" }
@@ -57,18 +48,23 @@ type ResolvedItem =
57
48
  readonly kind: "ok";
58
49
  readonly list: TodoList;
59
50
  readonly item: TodoItem;
51
+ /** 0-based position of the item within its list. */
60
52
  readonly index: number;
61
53
  };
62
54
 
63
- /** Resolve `listName:index` against the current state (index is 1-based). */
55
+ /**
56
+ * Resolve `listName:id` against the current state. The id is permanent, so a
57
+ * reference keeps pointing at the same item after other items are removed.
58
+ */
64
59
  const resolveItem = (s: TrackerState, itemId: string): ResolvedItem => {
65
- const parsed = parseItemId(itemId);
60
+ const parsed = parseItemRef(itemId);
66
61
  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];
62
+ const list = s.lists.find((l) => l.name === parsed.name);
63
+ if (!list) return { kind: "noList", listName: parsed.name };
64
+ const index = list.items.findIndex((item) => item.id === parsed.id);
65
+ const item = index === -1 ? undefined : list.items[index];
70
66
  if (!item) return { kind: "noItem", list };
71
- return { kind: "ok", list, item, index: parsed.index };
67
+ return { kind: "ok", list, item, index };
72
68
  };
73
69
 
74
70
  /**
@@ -89,7 +85,7 @@ const resolveItemOrError = (
89
85
  ok: false,
90
86
  error: new TrackerError({
91
87
  reason: "ItemNotFound",
92
- message: `Item "${itemId}" must look like "listName:index" (e.g. "Work:2")`,
88
+ message: `Item "${itemId}" must look like "listName:id" (e.g. "Work:2")`,
93
89
  itemId,
94
90
  }),
95
91
  };
@@ -107,53 +103,185 @@ const resolveItemOrError = (
107
103
  }),
108
104
  };
109
105
  }
110
- case "noItem": {
111
- const available = resolved.list.items
112
- .map((_, i) => `${resolved.list.name}:${i + 1}`)
113
- .join(", ");
106
+ case "noItem":
114
107
  return {
115
108
  ok: false,
116
109
  error: new TrackerError({
117
110
  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}`,
111
+ message: itemNotFoundMessage(resolved.list, itemId),
122
112
  listId: resolved.list.id,
123
113
  itemId,
124
114
  }),
125
115
  };
126
- }
127
116
  case "ok":
128
117
  return { ok: true, list: resolved.list, item: resolved.item, index: resolved.index };
129
118
  }
130
119
  };
131
120
 
121
+ /** Ids the caller can use instead, formatted as `listName:id`. */
122
+ const availableItemIds = (list: TodoList): string =>
123
+ list.items.map((item) => `${list.name}:${item.id}`).join(", ");
124
+
125
+ /**
126
+ * `Item "Work:9" not found in list "Work" — available: Work:1, Work:3`.
127
+ * Shared by the item, batch, and dependency paths so each names usable ids.
128
+ */
129
+ const notFoundMessage = (subject: string, label: string, list: TodoList): string => {
130
+ const available = availableItemIds(list);
131
+ return available === ""
132
+ ? `${label} "${subject}" not found in list "${list.name}" (no items)`
133
+ : `${label} "${subject}" not found in list "${list.name}" — available: ${available}`;
134
+ };
135
+
136
+ const itemNotFoundMessage = (list: TodoList, itemId: string): string =>
137
+ notFoundMessage(itemId, "Item", list);
138
+
139
+ /**
140
+ * The next item id to hand out: the stored counter, raised past the highest id
141
+ * in the list. Never below 1, so a list with an unset counter still hands out
142
+ * a usable id, and a removed id is never reused.
143
+ */
144
+ const nextItemIdFor = (items: readonly TodoItem[], counter: number): number =>
145
+ items.reduce((max, item) => Math.max(max, item.id + 1), Math.max(counter, 1));
146
+
147
+ /** A copy of `list` with a replaced item array and a counter above its ids. */
148
+ const withItems = (list: TodoList, items: readonly TodoItem[]): TodoList =>
149
+ new TodoList({
150
+ id: list.id,
151
+ name: list.name,
152
+ items: [...items],
153
+ nextItemId: nextItemIdFor(items, list.nextItemId),
154
+ });
155
+
132
156
  // --------------------------------------------------------------------------
133
157
  // Store
134
158
  // --------------------------------------------------------------------------
135
159
 
160
+ /**
161
+ * How a caller declares an item to create: the bare text, or an object that
162
+ * also carries the ids of the same-list items this one waits for.
163
+ */
164
+ export type ItemSpec = string | { readonly text: string; readonly deps?: readonly string[] };
165
+
166
+ /** Trim a spec's text and settle its dependency refs. */
167
+ const normalizeSpec = (
168
+ spec: ItemSpec,
169
+ ): { readonly text: string; readonly deps: readonly string[] } => {
170
+ if (typeof spec === "string") return { text: spec.trim(), deps: [] };
171
+ return { text: spec.text.trim(), deps: spec.deps ?? [] };
172
+ };
173
+
174
+ /**
175
+ * The first problem with `deps` for the item at `targetIndex`, or null when
176
+ * every dependency is valid. `list` must already contain the item and its
177
+ * siblings, so a reference to an item created by the same call resolves.
178
+ *
179
+ * Checks run in order: reference shape, same-list rule, existence, a self
180
+ * reference, then whether the resulting graph stays acyclic.
181
+ */
182
+ const firstDependencyError = (
183
+ list: TodoList,
184
+ targetIndex: number,
185
+ deps: readonly string[],
186
+ ): TrackerError | null => {
187
+ const target = list.items[targetIndex];
188
+ for (const ref of deps) {
189
+ const parsed = parseItemRef(ref);
190
+ if (parsed === null) {
191
+ return new TrackerError({
192
+ reason: "DependencyNotFound",
193
+ message: `Dependency "${ref}" must look like "listName:id" (e.g. "Work:2")`,
194
+ });
195
+ }
196
+ if (parsed.name !== list.name) {
197
+ return new TrackerError({
198
+ reason: "CrossListDependency",
199
+ message:
200
+ `Dependency "${ref}" is in another list. Dependencies must be in "${list.name}" ` +
201
+ `(e.g. "${list.name}:${parsed.id}")`,
202
+ });
203
+ }
204
+ if (!list.items.some((item) => item.id === parsed.id)) {
205
+ return new TrackerError({
206
+ reason: "DependencyNotFound",
207
+ message: notFoundMessage(ref, "Dependency", list),
208
+ });
209
+ }
210
+ if (target !== undefined && target.id === parsed.id) {
211
+ return new TrackerError({
212
+ reason: "DependencyCycle",
213
+ message: `Item "${ref}" cannot depend on itself`,
214
+ });
215
+ }
216
+ }
217
+ const cycle = cyclePath(list, targetIndex, deps);
218
+ if (cycle === null) return null;
219
+ const where =
220
+ cycle.length === 0
221
+ ? `involving "${list.name}:${target?.id ?? targetIndex + 1}"`
222
+ : `: ${cycle.join(" → ")}`;
223
+ return new TrackerError({
224
+ reason: "DependencyCycle",
225
+ message: `Dependency cycle${where}. Change or clear one of these dependencies`,
226
+ });
227
+ };
228
+
229
+ /**
230
+ * The refusal for completing a blocked item, or null when the item is already
231
+ * done or every dependency is done. Completion is gated; reopening is not, so
232
+ * a dependency that is reopened can always be re-closed or dropped.
233
+ */
234
+ const blockedError = (list: TodoList, index: number): TrackerError | null => {
235
+ const blockers = blockersOf(list, index);
236
+ if (blockers.length === 0) return null;
237
+ const subject = formatItemRef(list.name, list.items[index]!.id);
238
+ return new TrackerError({
239
+ reason: "ItemBlocked",
240
+ message:
241
+ `Item "${subject}" is blocked by ${blockers.join(", ")}. ` +
242
+ "Complete those items first, or clear this item's dependencies",
243
+ itemId: subject,
244
+ });
245
+ };
246
+
247
+ /** The refusal for removing an item that other items depend on, or null. */
248
+ const dependedOnError = (list: TodoList, index: number, itemId: string): TrackerError | null => {
249
+ const dependents = dependentsOf(list, index);
250
+ if (dependents.length === 0) return null;
251
+ const names = dependents
252
+ .map((dependent) => formatItemRef(list.name, list.items[dependent]!.id))
253
+ .join(", ");
254
+ return new TrackerError({
255
+ reason: "ItemDependedOn",
256
+ message:
257
+ `Item "${itemId}" has dependents: ${names}. ` + "Remove or change those dependencies first",
258
+ itemId,
259
+ });
260
+ };
261
+
136
262
  export interface UpdateItemPatch {
137
263
  readonly text?: string;
138
264
  readonly done?: boolean;
265
+ /** Replacement dependency set (same-list `listName:id` refs); `[]` clears it. */
266
+ readonly deps?: readonly string[];
139
267
  }
140
268
 
141
269
  /**
142
- * An `UpdateItemPatch` that targets an item by its 1-based position within a
143
- * single list (mirrors `add_item`'s `list_id + text[]` shape: the list is
144
- * factored out, the patches are positional).
270
+ * An `UpdateItemPatch` that targets an item by id within a single list
271
+ * (mirrors `add_item`'s `list_id + text[]` shape: the list is factored out,
272
+ * the patches name their item).
145
273
  */
146
274
  export interface UpdateItemInListPatch extends UpdateItemPatch {
147
- /** 1-based position of the item within its list (e.g. 2 for the second item). */
148
- readonly index: number;
275
+ /** The item's `listName:id` reference, e.g. "Work:2". */
276
+ readonly itemId: string;
149
277
  }
150
278
 
151
279
  /** Options for `createList`: activation behavior and initial items. */
152
280
  export interface CreateListOptions {
153
281
  /** Make the new list the active list (defaults to true). */
154
282
  readonly activate?: boolean;
155
- /** Initial item texts, added when the list is created (atomic with the list). */
156
- readonly initialItems?: readonly string[];
283
+ /** Initial items, added when the list is created (atomic with the list). */
284
+ readonly initialItems?: readonly ItemSpec[];
157
285
  }
158
286
 
159
287
  export class TrackerStore extends Context.Service<
@@ -167,10 +295,14 @@ export class TrackerStore extends Context.Service<
167
295
  ) => Effect.Effect<TodoList, TrackerError>;
168
296
  readonly deleteList: (listId: number) => Effect.Effect<void, TrackerError>;
169
297
  readonly setActiveList: (listId: number | null) => Effect.Effect<void, TrackerError>;
170
- readonly addItem: (listId: number, text: string) => Effect.Effect<TodoItem, TrackerError>;
298
+ readonly addItem: (
299
+ listId: number,
300
+ text: string,
301
+ deps?: readonly string[],
302
+ ) => Effect.Effect<TodoItem, TrackerError>;
171
303
  readonly addItems: (
172
304
  listId: number,
173
- texts: readonly string[],
305
+ specs: readonly ItemSpec[],
174
306
  ) => Effect.Effect<TodoItem[], TrackerError>;
175
307
  readonly updateItem: (
176
308
  itemId: string,
@@ -215,8 +347,8 @@ export class TrackerStore extends Context.Service<
215
347
  message: "List name must not be empty",
216
348
  });
217
349
  }
218
- const initialItems = (options.initialItems ?? []).map((text) => text.trim());
219
- if (initialItems.some((text) => text === "")) {
350
+ const initialSpecs = (options.initialItems ?? []).map(normalizeSpec);
351
+ if (initialSpecs.some((spec) => spec.text === "")) {
220
352
  return yield* new TrackerError({
221
353
  reason: "EmptyText",
222
354
  message: "Item text must not be empty",
@@ -236,8 +368,22 @@ export class TrackerStore extends Context.Service<
236
368
  s,
237
369
  ];
238
370
  }
239
- const items = initialItems.map((text) => new TodoItem({ text, done: false }));
240
- const list = new TodoList({ id: s.nextListId, name: trimmed, items });
371
+ const items = initialSpecs.map(
372
+ (spec, index) =>
373
+ new TodoItem({ id: index + 1, text: spec.text, done: false, deps: [...spec.deps] }),
374
+ );
375
+ const list = new TodoList({
376
+ id: s.nextListId,
377
+ name: trimmed,
378
+ items,
379
+ nextItemId: items.length + 1,
380
+ });
381
+ // Dependencies are checked against the new list itself, so an
382
+ // initial item may depend on a sibling from the same call.
383
+ for (const [index, item] of items.entries()) {
384
+ const error = firstDependencyError(list, index, item.deps);
385
+ if (error !== null) return [Result.fail(error), s];
386
+ }
241
387
  return [
242
388
  Result.succeed(list),
243
389
  new TrackerState({
@@ -297,46 +443,17 @@ export class TrackerStore extends Context.Service<
297
443
  });
298
444
  });
299
445
 
300
- const addItem = Effect.fn("TrackerStore.addItem")(function* (listId: number, text: string) {
301
- const trimmed = text.trim();
302
- if (trimmed === "") {
303
- return yield* new TrackerError({
304
- reason: "EmptyText",
305
- message: "Item text must not be empty",
306
- });
307
- }
308
- return yield* mutate(
309
- (s): readonly [Result.Result<TodoItem, TrackerError>, TrackerState] => {
310
- const list = s.lists.find((l) => l.id === listId);
311
- if (!list) {
312
- return [
313
- Result.fail(
314
- new TrackerError({
315
- reason: "ListNotFound",
316
- message: listNotFoundMessage(s, listId),
317
- listId,
318
- }),
319
- ),
320
- s,
321
- ];
322
- }
323
- const item = new TodoItem({ text: trimmed, done: false });
324
- const lists = s.lists.map((l) =>
325
- l.id === listId
326
- ? new TodoList({ id: l.id, name: l.name, items: [...l.items, item] })
327
- : l,
328
- );
329
- return [Result.succeed(item), new TrackerState({ ...s, lists })];
330
- },
331
- );
332
- });
333
-
446
+ /**
447
+ * Append items to a list, assigning ids from the list counter. Accepts
448
+ * bare text or `{ text, deps }` objects; a dependency may name an item
449
+ * created by this same call.
450
+ */
334
451
  const addItems = Effect.fn("TrackerStore.addItems")(function* (
335
452
  listId: number,
336
- texts: readonly string[],
453
+ items: readonly ItemSpec[],
337
454
  ) {
338
- const trimmed = texts.map((text) => text.trim());
339
- if (trimmed.some((text) => text === "")) {
455
+ const specs = items.map(normalizeSpec);
456
+ if (specs.some((spec) => spec.text === "")) {
340
457
  return yield* new TrackerError({
341
458
  reason: "EmptyText",
342
459
  message: "Item text must not be empty",
@@ -357,17 +474,39 @@ export class TrackerStore extends Context.Service<
357
474
  s,
358
475
  ];
359
476
  }
360
- const items = trimmed.map((text) => new TodoItem({ text, done: false }));
361
- const lists = s.lists.map((l) =>
362
- l.id === listId
363
- ? new TodoList({ id: l.id, name: l.name, items: [...l.items, ...items] })
364
- : l,
365
- );
366
- return [Result.succeed(items), new TrackerState({ ...s, lists })];
477
+ let nextId = nextItemIdFor(list.items, list.nextItemId);
478
+ const added = specs.map((spec) => {
479
+ const item = new TodoItem({
480
+ id: nextId,
481
+ text: spec.text,
482
+ done: false,
483
+ deps: [...spec.deps],
484
+ });
485
+ nextId += 1;
486
+ return item;
487
+ });
488
+ const nextList = withItems(list, [...list.items, ...added]);
489
+ // Validate against the post-insertion list, so a dependency may
490
+ // name a sibling created by this same call.
491
+ for (const [offset, item] of added.entries()) {
492
+ const error = firstDependencyError(nextList, list.items.length + offset, item.deps);
493
+ if (error !== null) return [Result.fail(error), s];
494
+ }
495
+ const lists = s.lists.map((l) => (l.id === listId ? nextList : l));
496
+ return [Result.succeed(added), new TrackerState({ ...s, lists })];
367
497
  },
368
498
  );
369
499
  });
370
500
 
501
+ const addItem = Effect.fn("TrackerStore.addItem")(function* (
502
+ listId: number,
503
+ text: string,
504
+ deps: readonly string[] = [],
505
+ ) {
506
+ const [item] = yield* addItems(listId, [{ text, deps }]);
507
+ return item!;
508
+ });
509
+
371
510
  const updateItem = Effect.fn("TrackerStore.updateItem")(function* (
372
511
  itemId: string,
373
512
  patch: UpdateItemPatch,
@@ -386,23 +525,33 @@ export class TrackerStore extends Context.Service<
386
525
  return [Result.fail(resolved.error), s];
387
526
  }
388
527
  const { list, item } = resolved;
389
- if (patch.text === undefined && patch.done === undefined) {
528
+ // Completion is gated on the list as it stands: an item may only be
529
+ // completed once its dependencies are done. Reopening and text or
530
+ // dependency edits stay open, so a blocked item can be repaired.
531
+ if (patch.done === true) {
532
+ const blocked = blockedError(list, resolved.index);
533
+ if (blocked !== null) return [Result.fail(blocked), s];
534
+ }
535
+ if (patch.text === undefined && patch.done === undefined && patch.deps === undefined) {
390
536
  // No-op patch: return the current item, leave state untouched.
391
537
  return [Result.succeed(item), s];
392
538
  }
393
539
  const next = new TodoItem({
540
+ id: item.id,
394
541
  text: trimmed ?? item.text,
395
542
  done: patch.done ?? item.done,
543
+ deps: patch.deps === undefined ? item.deps : [...patch.deps],
396
544
  });
397
- const lists = s.lists.map((l) =>
398
- l.id === list.id
399
- ? new TodoList({
400
- id: l.id,
401
- name: l.name,
402
- items: l.items.map((i, idx) => (idx === resolved.index - 1 ? next : i)),
403
- })
404
- : l,
545
+ const nextList = withItems(
546
+ list,
547
+ list.items.map((i) => (i.id === item.id ? next : i)),
405
548
  );
549
+ // The replacement set is validated against the list the change
550
+ // produces, so dependencies are checked exactly as they will be
551
+ // stored. The item keeps its position, so the index still holds.
552
+ const error = firstDependencyError(nextList, resolved.index, next.deps);
553
+ if (error !== null) return [Result.fail(error), s];
554
+ const lists = s.lists.map((l) => (l.id === list.id ? nextList : l));
406
555
  return [Result.succeed(next), new TrackerState({ ...s, lists })];
407
556
  },
408
557
  );
@@ -410,9 +559,9 @@ export class TrackerStore extends Context.Service<
410
559
 
411
560
  /**
412
561
  * Per-list batched updates, mirroring `addItems(listId, texts)`: the
413
- * list is named once and each patch targets an item by its 1-based
414
- * position (`index`) within that list. The whole batch fails atomically
415
- * if the list is missing or any index is out of range.
562
+ * list is named once and each patch targets an item by id within that
563
+ * list. The whole batch fails atomically if the list is missing or any
564
+ * id does not resolve.
416
565
  */
417
566
  const updateItems = Effect.fn("TrackerStore.updateItems")(function* (
418
567
  listId: number,
@@ -443,41 +592,83 @@ export class TrackerStore extends Context.Service<
443
592
  s,
444
593
  ];
445
594
  }
446
- // Resolve every target position; the batch fails atomically if any
447
- // index is out of range.
448
- const positions: number[] = [];
595
+ // Resolve every target id within this single list; the batch fails
596
+ // atomically if any of them does not resolve. A reference naming
597
+ // another list does not resolve here either.
598
+ const targets: number[] = [];
449
599
  for (const patch of patches) {
450
- if (patch.index < 1 || patch.index > list.items.length) {
600
+ const parsed = parseItemRef(patch.itemId);
601
+ if (parsed === null) {
451
602
  return [
452
603
  Result.fail(
453
604
  new TrackerError({
454
605
  reason: "ItemNotFound",
455
- message:
456
- `Item ${list.name}:${patch.index} not found — list "${list.name}" has ` +
457
- `${list.items.length} item${list.items.length === 1 ? "" : "s"}`,
606
+ message: `Item "${patch.itemId}" must look like "listName:id" (e.g. "Work:2")`,
607
+ listId,
608
+ itemId: patch.itemId,
458
609
  }),
459
610
  ),
460
611
  s,
461
612
  ];
462
613
  }
463
- positions.push(patch.index);
614
+ const index =
615
+ parsed.name === list.name
616
+ ? list.items.findIndex((item) => item.id === parsed.id)
617
+ : -1;
618
+ if (index === -1) {
619
+ return [
620
+ Result.fail(
621
+ new TrackerError({
622
+ reason: "ItemNotFound",
623
+ message: itemNotFoundMessage(list, patch.itemId),
624
+ listId,
625
+ itemId: patch.itemId,
626
+ }),
627
+ ),
628
+ s,
629
+ ];
630
+ }
631
+ targets.push(index);
464
632
  }
465
- // Later patches win for duplicate positions.
466
- const byIndex = new Map<number, UpdateItemPatch>();
467
- patches.forEach((patch, i) => byIndex.set(positions[i]!, patch));
468
- const nextItems = list.items.map((item, idx) => {
469
- const patch = byIndex.get(idx + 1);
470
- if (!patch) return item;
471
- const text = patch.text === undefined ? item.text : patch.text.trim();
472
- const done = patch.done ?? item.done;
473
- return new TodoItem({ text, done });
474
- });
475
- const lists = s.lists.map((l) =>
476
- l.id === listId ? new TodoList({ id: l.id, name: l.name, items: nextItems }) : l,
477
- );
633
+ // Later patches win for duplicate ids, which falls out of
634
+ // applying them in order below.
635
+ //
636
+ // The patches are applied in order, each validated against the list
637
+ // the earlier patches produced. A batch therefore behaves like the
638
+ // same calls in sequence: one call can complete a chain, and a
639
+ // completion that is out of order is still refused.
640
+ let items = [...list.items];
641
+ for (const [index, patch] of patches.entries()) {
642
+ const target = targets[index]!;
643
+ if (patch.done === true) {
644
+ const blocked = blockedError(withItems(list, items), target);
645
+ if (blocked !== null) return [Result.fail(blocked), s];
646
+ }
647
+ const current = items[target]!;
648
+ items = items.map((item, at) =>
649
+ at === target
650
+ ? new TodoItem({
651
+ id: current.id,
652
+ text: patch.text === undefined ? current.text : patch.text.trim(),
653
+ done: patch.done ?? current.done,
654
+ deps: patch.deps === undefined ? current.deps : [...patch.deps],
655
+ })
656
+ : item,
657
+ );
658
+ // Validate this patch's dependency set against the list it
659
+ // produces, so a cycle is refused at the patch that closes it.
660
+ if (patch.deps !== undefined) {
661
+ const worked = withItems(list, items);
662
+ const error = firstDependencyError(worked, target, items[target]!.deps);
663
+ if (error !== null) return [Result.fail(error), s];
664
+ }
665
+ }
666
+ const nextList = withItems(list, items);
667
+ const lists = s.lists.map((l) => (l.id === listId ? nextList : l));
478
668
  return [
479
- // Results in patch order so the caller can map them 1:1.
480
- Result.succeed(positions.map((index) => nextItems[index - 1]!)),
669
+ // Results in patch order so the caller can map them 1:1. A patch
670
+ // that a later one overwrote reports the later state.
671
+ Result.succeed(targets.map((index) => items[index]!)),
481
672
  new TrackerState({ ...s, lists }),
482
673
  ];
483
674
  },
@@ -485,9 +676,11 @@ export class TrackerStore extends Context.Service<
485
676
  });
486
677
 
487
678
  /**
488
- * Remove an item. Positions shift implicitly: the item that followed
489
- * the removed one takes its index, so `Work:3` becomes `Work:2`. The
490
- * error message lists the fresh ids for a stale reference.
679
+ * Remove an item. Its id is never reused and the ids of the items after it
680
+ * do not change, so a reference the caller already holds keeps pointing at
681
+ * the same item. A stale reference still lists every id that does resolve.
682
+ * An item that other items depend on cannot be removed: the dependents
683
+ * would be left dangling.
491
684
  */
492
685
  const removeItem = Effect.fn("TrackerStore.removeItem")(function* (itemId: string) {
493
686
  return yield* mutate((s): readonly [Result.Result<void, TrackerError>, TrackerState] => {
@@ -495,14 +688,15 @@ export class TrackerStore extends Context.Service<
495
688
  if (!resolved.ok) {
496
689
  return [Result.fail(resolved.error), s];
497
690
  }
498
- const { list, index } = resolved;
691
+ const { list, item } = resolved;
692
+ const dependedOn = dependedOnError(list, resolved.index, itemId);
693
+ if (dependedOn !== null) return [Result.fail(dependedOn), s];
499
694
  const lists = s.lists.map((l) =>
500
695
  l.id === list.id
501
- ? new TodoList({
502
- id: l.id,
503
- name: l.name,
504
- items: l.items.filter((_, idx) => idx !== index - 1),
505
- })
696
+ ? withItems(
697
+ l,
698
+ l.items.filter((i) => i.id !== item.id),
699
+ )
506
700
  : l,
507
701
  );
508
702
  return [Result.succeed(undefined), new TrackerState({ ...s, lists })];