@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/deps.ts ADDED
@@ -0,0 +1,250 @@
1
+ import { Graph } from "effect";
2
+
3
+ /**
4
+ * Dependency logic for tracker items: reference parsing, cycle detection, and
5
+ * readiness.
6
+ *
7
+ * Pure and free of the store and of any Effect runtime, so both the mutation
8
+ * path (the store) and the read path (rendering) can share it.
9
+ */
10
+
11
+ /** One item as the dependency helpers see it. */
12
+ export interface DependencyItem {
13
+ /**
14
+ * Absent in an encoded snapshot whose `id` default has not been applied yet;
15
+ * the live store always sets it, and `restore` migrates older snapshots.
16
+ */
17
+ readonly id?: number | undefined;
18
+ readonly done: boolean;
19
+ readonly deps?: readonly string[] | undefined;
20
+ }
21
+
22
+ /**
23
+ * A list and its items, as the read path sees it. Declared structurally so both
24
+ * the live `TodoList` and the encoded snapshot in tool details fit, and so this
25
+ * module stays free of the domain classes. Generic in the item type so callers
26
+ * keep their own item shape (the domain class, an encoded item, a test stub).
27
+ */
28
+ export interface DependencyListView<T extends DependencyItem> {
29
+ readonly name: string;
30
+ readonly items: readonly T[];
31
+ }
32
+
33
+ /** A list of plain items, as the dependency helpers need it. */
34
+ export type DependencyList = DependencyListView<DependencyItem>;
35
+
36
+ /** A parsed `listName:id` reference. */
37
+ export interface ItemRef {
38
+ readonly name: string;
39
+ readonly id: number;
40
+ }
41
+
42
+ /**
43
+ * Parse a `listName:id` reference. Splits on the last colon so list names may
44
+ * contain colons; the id must be a positive integer. Returns null for anything
45
+ * that is not a well-formed reference.
46
+ */
47
+ export const parseItemRef = (ref: string): ItemRef | null => {
48
+ const colon = ref.lastIndexOf(":");
49
+ if (colon <= 0 || colon === ref.length - 1) return null;
50
+ const idText = ref.slice(colon + 1);
51
+ if (!/^[1-9]\d*$/.test(idText)) return null;
52
+ return { name: ref.slice(0, colon), id: Number(idText) };
53
+ };
54
+
55
+ /** Format a reference the way the list action shows it. */
56
+ export const formatItemRef = (listName: string, id: number): string => `${listName}:${id}`;
57
+
58
+ /** Resolve a same-list reference to its 0-based index, or undefined. */
59
+ export const resolveRef = (list: DependencyList, ref: string): number | undefined => {
60
+ const parsed = parseItemRef(ref);
61
+ if (parsed === null || parsed.name !== list.name) return undefined;
62
+ const index = list.items.findIndex((item) => item.id === parsed.id);
63
+ return index === -1 ? undefined : index;
64
+ };
65
+
66
+ /**
67
+ * Candidate edges as `[dependencyIndex, dependentIndex]`, with `deps` standing
68
+ * in for the item at `targetIndex` and every other item keeping its stored
69
+ * deps. References that do not resolve to a same-list item are skipped: they
70
+ * cannot close a cycle, and the store rejects them separately.
71
+ */
72
+ const candidateEdges = (
73
+ list: DependencyList,
74
+ targetIndex: number,
75
+ deps: readonly string[],
76
+ ): Array<readonly [number, number]> => {
77
+ const edges: Array<readonly [number, number]> = [];
78
+ list.items.forEach((item, dependent) => {
79
+ for (const ref of dependent === targetIndex ? deps : (item.deps ?? [])) {
80
+ const dependency = resolveRef(list, ref);
81
+ if (dependency !== undefined) edges.push([dependency, dependent]);
82
+ }
83
+ });
84
+ return edges;
85
+ };
86
+
87
+ /**
88
+ * Follow the candidate edges depth-first from `targetIndex` and return the
89
+ * first path that comes back to it, as item indexes. Empty when no cycle
90
+ * passes through the target.
91
+ */
92
+ const findCyclePath = (
93
+ edges: ReadonlyArray<readonly [number, number]>,
94
+ targetIndex: number,
95
+ ): readonly number[] => {
96
+ // dependency → its dependents, so a walk follows what each item unblocks.
97
+ const dependents = new Map<number, number[]>();
98
+ for (const [dependency, dependent] of edges) {
99
+ const existing = dependents.get(dependency);
100
+ if (existing === undefined) dependents.set(dependency, [dependent]);
101
+ else existing.push(dependent);
102
+ }
103
+
104
+ const path: number[] = [];
105
+ const onPath = new Set<number>();
106
+ const walk = (node: number): boolean => {
107
+ path.push(node);
108
+ onPath.add(node);
109
+ for (const next of dependents.get(node) ?? []) {
110
+ if (next === targetIndex) {
111
+ // The loop is closed; name the target again at the end of the path.
112
+ path.push(next);
113
+ return true;
114
+ }
115
+ if (onPath.has(next)) continue;
116
+ if (walk(next)) return true;
117
+ }
118
+ path.pop();
119
+ onPath.delete(node);
120
+ return false;
121
+ };
122
+
123
+ return walk(targetIndex) ? path : [];
124
+ };
125
+
126
+ /**
127
+ * The cycle that giving `deps` to the item at `targetIndex` would close, as
128
+ * display refs that start and end at that item. Null when the candidate set
129
+ * stays acyclic, which is the common case.
130
+ *
131
+ * The decision comes from `Graph.isAcyclic`; the path is then walked so the
132
+ * error can name the items involved. An empty array means a cycle exists in
133
+ * the list but not through the target, which only a hand-edited snapshot can
134
+ * produce.
135
+ */
136
+ export const cyclePath = (
137
+ list: DependencyList,
138
+ targetIndex: number,
139
+ deps: readonly string[],
140
+ ): readonly string[] | null => {
141
+ const edges = candidateEdges(list, targetIndex, deps);
142
+ const graph = Graph.directed<number, string>((mutable) => {
143
+ const nodes = list.items.map((_, index) => Graph.addNode(mutable, index));
144
+ for (const [dependency, dependent] of edges) {
145
+ Graph.addEdge(mutable, nodes[dependency]!, nodes[dependent]!, "dep");
146
+ }
147
+ });
148
+ if (Graph.isAcyclic(graph)) return null;
149
+ return findCyclePath(edges, targetIndex).map((index) =>
150
+ formatItemRef(list.name, list.items[index]!.id ?? 0),
151
+ );
152
+ };
153
+
154
+ /**
155
+ * Display refs of the dependencies of the item at `index` that are not done.
156
+ * Independent of the item's own state, so a done item whose prerequisite was
157
+ * reopened still reports it.
158
+ *
159
+ * An unresolvable dependency counts as unsatisfied and is reported as `?`, so a
160
+ * hand-edited snapshot cannot silently unblock work.
161
+ */
162
+ export const unsatisfiedDeps = (list: DependencyList, index: number): readonly string[] => {
163
+ const item = list.items[index];
164
+ if (item === undefined) return [];
165
+ const unsatisfied: string[] = [];
166
+ for (const ref of item.deps ?? []) {
167
+ const dependency = resolveRef(list, ref);
168
+ if (dependency === undefined) unsatisfied.push("?");
169
+ else if (!list.items[dependency]!.done) unsatisfied.push(ref);
170
+ }
171
+ return unsatisfied;
172
+ };
173
+
174
+ /**
175
+ * What stops the item at `index` from being completed. Empty for a done item:
176
+ * completion is gated only on open work, so re-marking a done item done is
177
+ * never refused. The reading surfaces use `unsatisfiedDeps` when they need the
178
+ * fact for a done row.
179
+ */
180
+ export const blockersOf = (list: DependencyList, index: number): readonly string[] =>
181
+ list.items[index]?.done === true ? [] : unsatisfiedDeps(list, index);
182
+
183
+ /** Derived readiness of one item. `ready` means "open and unblocked". */
184
+ export interface ItemReadiness {
185
+ readonly index: number;
186
+ readonly id: number;
187
+ readonly ready: boolean;
188
+ /**
189
+ * The not-done dependencies, as display refs, or `?` when unresolvable.
190
+ * Reported for a done item too, so a row whose prerequisite reopened can be
191
+ * marked; `ready` is false whenever the item is done.
192
+ */
193
+ readonly blockers: readonly string[];
194
+ }
195
+
196
+ /**
197
+ * Readiness for every item in list order. Derived on read and never stored, so
198
+ * it cannot go stale next to the items it describes.
199
+ */
200
+ export const readiness = (list: DependencyList): readonly ItemReadiness[] =>
201
+ list.items.map((item, index) => {
202
+ const blockers = unsatisfiedDeps(list, index);
203
+ return { index, id: item.id ?? 0, ready: !item.done && blockers.length === 0, blockers };
204
+ });
205
+
206
+ /**
207
+ * Index of the first ready item in list order, or undefined when nothing is
208
+ * ready (every item is done, or every open item is blocked).
209
+ */
210
+ export const firstReadyIndex = (list: DependencyList): number | undefined => {
211
+ const index = list.items.findIndex(
212
+ (item, candidate) => !item.done && blockersOf(list, candidate).length === 0,
213
+ );
214
+ return index === -1 ? undefined : index;
215
+ };
216
+
217
+ /** Indexes of the items that depend on the item at `index`. */
218
+ export const dependentsOf = (list: DependencyList, index: number): readonly number[] =>
219
+ list.items.flatMap((item, dependent) =>
220
+ (item.deps ?? []).some((ref) => resolveRef(list, ref) === index) ? [dependent] : [],
221
+ );
222
+
223
+ /**
224
+ * The items in derived display order: every dependency before the items that
225
+ * wait for it, in a stable order otherwise.
226
+ *
227
+ * A list without dependencies returns its stored order unchanged, so nothing
228
+ * moves until dependencies exist. A list whose graph is cyclic (only a
229
+ * hand-edited snapshot can produce one) also falls back to the stored order,
230
+ * so rendering never throws and never drops an item.
231
+ */
232
+ export const orderedItems = <T extends DependencyItem>(
233
+ list: DependencyListView<T>,
234
+ ): readonly T[] => {
235
+ if (!list.items.some((item) => (item.deps ?? []).length > 0)) return list.items;
236
+ const graph = Graph.directed<number, string>((mutable) => {
237
+ const nodes = list.items.map((_, index) => Graph.addNode(mutable, index));
238
+ list.items.forEach((item, dependent) => {
239
+ for (const ref of item.deps ?? []) {
240
+ const dependency = resolveRef(list, ref);
241
+ // A self-reference orders nothing; the store rejects it separately.
242
+ if (dependency !== undefined && dependency !== dependent) {
243
+ Graph.addEdge(mutable, nodes[dependency]!, nodes[dependent]!, "dep");
244
+ }
245
+ }
246
+ });
247
+ });
248
+ if (!Graph.isAcyclic(graph)) return list.items;
249
+ return [...Graph.indices(Graph.topo(graph))].map((index) => list.items[index]!);
250
+ };
@@ -27,15 +27,17 @@ const sampleState = (): TrackerState =>
27
27
  new TodoList({
28
28
  id: 1,
29
29
  name: "Work",
30
+ nextItemId: 3,
30
31
  items: [
31
- new TodoItem({ text: "write plan", done: true }),
32
- new TodoItem({ text: "implement tracker", done: false }),
32
+ new TodoItem({ id: 1, text: "write plan", done: true }),
33
+ new TodoItem({ id: 2, text: "implement tracker", done: false }),
33
34
  ],
34
35
  }),
35
36
  new TodoList({
36
37
  id: 2,
37
38
  name: "Home",
38
- items: [new TodoItem({ text: "water plants", done: false })],
39
+ nextItemId: 2,
40
+ items: [new TodoItem({ id: 1, text: "water plants", done: false })],
39
41
  }),
40
42
  ],
41
43
  activeListId: 1,
@@ -63,6 +65,48 @@ it("a realistic state round-trips, preserving order", () => {
63
65
  assert.strictEqual(decoded.nextListId, 3);
64
66
  });
65
67
 
68
+ it("item ids and deps round-trip", () => {
69
+ const state = new TrackerState({
70
+ lists: [
71
+ new TodoList({
72
+ id: 1,
73
+ name: "Work",
74
+ nextItemId: 4,
75
+ items: [
76
+ new TodoItem({ id: 1, text: "a", done: true }),
77
+ new TodoItem({ id: 3, text: "b", done: false, deps: ["Work:1"] }),
78
+ ],
79
+ }),
80
+ ],
81
+ activeListId: 1,
82
+ nextListId: 2,
83
+ });
84
+
85
+ roundTripsTo(state, encodeState(state));
86
+
87
+ const decoded = decodeOrThrow(encodeState(state));
88
+ assert.deepStrictEqual(
89
+ decoded.lists[0]?.items.map((i) => [i.id, i.deps]),
90
+ [
91
+ [1, []],
92
+ [3, ["Work:1"]],
93
+ ],
94
+ );
95
+ assert.strictEqual(decoded.lists[0]?.nextItemId, 4);
96
+ });
97
+
98
+ it("encoded snapshots carry item ids, deps, and the list counter", () => {
99
+ const encoded = encodeState(sampleState());
100
+ assert.deepStrictEqual(
101
+ encoded.lists[0]?.items.map((i) => [i.id, i.deps]),
102
+ [
103
+ [1, []],
104
+ [2, []],
105
+ ],
106
+ );
107
+ assert.strictEqual(encoded.lists[0]?.nextItemId, 3);
108
+ });
109
+
66
110
  it("decoded values are real class instances", () => {
67
111
  const decoded = decodeOrThrow(encodeState(sampleState()));
68
112
  const firstItem = decoded.lists[0]?.items[0];
@@ -121,9 +165,10 @@ it("rejects a snapshot with an invalid item field", () => {
121
165
  assert(Result.isFailure(result));
122
166
  });
123
167
 
124
- it("ignores legacy item id fields (ids are positions, not stored)", () => {
125
- // Snapshots from both previous formats (numeric ids and listName:index
126
- // strings) decode cleanly; the stored id is ignored.
168
+ it("drops a legacy string item id so old sessions stay loadable", () => {
169
+ // An older format stored the item id as a "listName:index" string. The
170
+ // schema now stores an integer id, so a string id is dropped before decode:
171
+ // the item decodes as unassigned and migrateState gives it its position.
127
172
  const legacy = {
128
173
  lists: [{ id: 1, name: "Work", items: [{ id: "Work:1", text: "x", done: false }] }],
129
174
  activeListId: null,
package/src/domain.ts CHANGED
@@ -1,22 +1,59 @@
1
- import { Schema } from "effect";
1
+ import { Effect, Schema } from "effect";
2
2
 
3
3
  /**
4
4
  * Domain model for the tracker extension.
5
5
  *
6
6
  * Schema classes double as their own TypeScript types (no separate
7
- * interfaces). The on-disk / session snapshot is the full `TrackerState`,
8
- * so decode does not need to apply defaults: a snapshot is either complete
9
- * and valid, or rejected with a `SchemaError`.
7
+ * interfaces). The on-disk / session snapshot is the full `TrackerState`.
8
+ *
9
+ * Items carry a per-list integer `id` and a same-list `deps` list. Both were
10
+ * added after the first release, so decode applies defaults for them and
11
+ * `normalizeSnapshot` tolerates the older item shapes. `migrateState` then
12
+ * turns a decoded snapshot into a state the store can rely on: every item has
13
+ * a real id and every list has a counter above its ids.
14
+ */
15
+
16
+ /**
17
+ * An item id of 0 means "not assigned yet": a snapshot written before ids
18
+ * existed, or an item whose legacy string id was dropped. `migrateState`
19
+ * assigns the real id (the item's position for a legacy list).
20
+ */
21
+ const itemId = Schema.Int.pipe(
22
+ Schema.withDecodingDefaultType(Effect.succeed(0)),
23
+ Schema.withConstructorDefault(Effect.succeed(0)),
24
+ );
25
+
26
+ /** Same-list dependencies, as `listName:id` references. */
27
+ const itemDeps = Schema.Array(Schema.String).pipe(
28
+ Schema.withDecodingDefaultType(Effect.succeed([])),
29
+ Schema.withConstructorDefault(Effect.succeed([])),
30
+ );
31
+
32
+ /**
33
+ * Sentinel for a list that stored no item id counter, which means the snapshot
34
+ * was written before item ids existed. `normalizeSnapshot` stamps it so
35
+ * `migrateState` can tell such a list apart and reassign its ids by position.
10
36
  */
37
+ const LEGACY_ITEM_COUNTER = 0;
38
+
39
+ /** Per-list counter for the next item id. Strictly increasing, never reused. */
40
+ const itemCounter = Schema.Int.pipe(
41
+ Schema.withDecodingDefaultType(Effect.succeed(1)),
42
+ Schema.withConstructorDefault(Effect.succeed(1)),
43
+ );
11
44
 
12
45
  export class TodoItem extends Schema.Class<TodoItem>("tracker/TodoItem")({
46
+ id: itemId,
13
47
  text: Schema.String,
14
48
  done: Schema.Boolean,
49
+ deps: itemDeps,
15
50
  }) {}
16
51
 
17
52
  export class TodoList extends Schema.Class<TodoList>("tracker/TodoList")({
18
53
  id: Schema.Int,
19
54
  name: Schema.String,
55
+ // Strictly-increasing counter ⇒ stable item ids, never reused after deletes.
56
+ nextItemId: itemCounter,
20
57
  items: Schema.Array(TodoItem),
21
58
  }) {}
22
59
 
@@ -31,15 +68,119 @@ export class TrackerState extends Schema.Class<TrackerState>("tracker/TrackerSta
31
68
  /**
32
69
  * Fresh state: no lists, list counter starting at 1.
33
70
  *
34
- * Item ids are not stored: `listName:index` is a reference syntax where
35
- * `index` is the 1-based position in the list's `items` array. State is
36
- * always carried as real class instances: `Schema.Class` encode requires
37
- * instances (its Declaration checks the class marker), and the constructors
38
- * validate their input (`new TodoItem({ text: 42, ... })` throws).
71
+ * State is always carried as real class instances: `Schema.Class` encode
72
+ * requires instances (its Declaration checks the class marker), and the
73
+ * constructors validate their input (`new TodoItem({ text: 42, ... })` throws).
39
74
  */
40
75
  export const emptyState = (): TrackerState =>
41
76
  new TrackerState({ lists: [], activeListId: null, nextListId: 1 });
42
77
 
78
+ // --------------------------------------------------------------------------
79
+ // Legacy snapshot tolerance
80
+ // --------------------------------------------------------------------------
81
+
82
+ /** A copy of `item` with a replaced id. */
83
+ const withId = (item: TodoItem, id: number): TodoItem =>
84
+ new TodoItem({ id, text: item.text, done: item.done, deps: item.deps });
85
+
86
+ /**
87
+ * Reassign ids for one list and return it with a counter above every id.
88
+ *
89
+ * A list carrying the legacy sentinel was written before item ids existed, so
90
+ * its stored ids (if any) mean nothing now: ids are assigned from each item's
91
+ * position, which is what the old `listName:index` references resolved to.
92
+ * Otherwise stored ids are kept and the counter is raised past the highest
93
+ * one, so it never hands out an id twice.
94
+ */
95
+ const migrateList = (list: TodoList): TodoList => {
96
+ if (list.nextItemId === LEGACY_ITEM_COUNTER) {
97
+ return new TodoList({
98
+ id: list.id,
99
+ name: list.name,
100
+ items: list.items.map((item, index) => withId(item, index + 1)),
101
+ nextItemId: list.items.length + 1,
102
+ });
103
+ }
104
+ const highest = list.items.reduce((max, item) => Math.max(max, item.id), 0);
105
+ let counter = Math.max(list.nextItemId, highest + 1);
106
+ const items = list.items.map((item) => {
107
+ if (item.id !== LEGACY_ITEM_COUNTER) return item;
108
+ // A stray unassigned id (hand-edited snapshot): hand out a fresh one
109
+ // rather than leave an item no reference can reach.
110
+ const assigned = withId(item, counter);
111
+ counter += 1;
112
+ return assigned;
113
+ });
114
+ return new TodoList({ id: list.id, name: list.name, items, nextItemId: counter });
115
+ };
116
+
117
+ /**
118
+ * Make a decoded snapshot safe for the store: every item has a real id and
119
+ * every list has a counter above its ids. Pure; called once per restore.
120
+ */
121
+ export const migrateState = (state: TrackerState): TrackerState =>
122
+ new TrackerState({
123
+ lists: state.lists.map(migrateList),
124
+ activeListId: state.activeListId,
125
+ nextListId: state.nextListId,
126
+ });
127
+
128
+ /**
129
+ * Drop a legacy `listName:index` string item id so the item decodes as
130
+ * unassigned. An older format stored the id as a string; the schema now
131
+ * stores an integer, and rejecting the snapshot would lose the whole session.
132
+ */
133
+ const normalizeItem = (item: unknown): unknown => {
134
+ if (typeof item !== "object" || item === null || Array.isArray(item)) return item;
135
+ const record = item as Record<string, unknown>;
136
+ if (typeof record.id !== "string") return item;
137
+ const next = { ...record };
138
+ delete next.id;
139
+ return next;
140
+ };
141
+
142
+ /**
143
+ * Tolerate item shapes written by older versions before the schema sees them.
144
+ *
145
+ * Two older shapes exist, described on `normalizeItem` and on
146
+ * `LEGACY_ITEM_COUNTER`. Anything unrecognizable passes through untouched, so
147
+ * the schema still reports the real error for malformed input.
148
+ */
149
+ const normalizeSnapshot = (snapshot: unknown): unknown => {
150
+ if (typeof snapshot !== "object" || snapshot === null || Array.isArray(snapshot)) {
151
+ return snapshot;
152
+ }
153
+ const state = snapshot as Record<string, unknown>;
154
+ if (!Array.isArray(state.lists)) return snapshot;
155
+ let changed = false;
156
+ const lists = state.lists.map((list) => {
157
+ if (typeof list !== "object" || list === null || Array.isArray(list)) return list;
158
+ const record = list as Record<string, unknown>;
159
+ const next: Record<string, unknown> = { ...record };
160
+ let listChanged = false;
161
+ const rawItems = record.items;
162
+ if (Array.isArray(rawItems)) {
163
+ const items = rawItems.map(normalizeItem);
164
+ if (items.some((item, index) => item !== rawItems[index])) {
165
+ next.items = items;
166
+ listChanged = true;
167
+ }
168
+ }
169
+ if (typeof record.nextItemId !== "number") {
170
+ next.nextItemId = LEGACY_ITEM_COUNTER;
171
+ listChanged = true;
172
+ }
173
+ if (!listChanged) return list;
174
+ changed = true;
175
+ return next;
176
+ });
177
+ return changed ? { ...state, lists } : snapshot;
178
+ };
179
+
180
+ // --------------------------------------------------------------------------
181
+ // Codecs
182
+ // --------------------------------------------------------------------------
183
+
43
184
  /**
44
185
  * Encode a `TrackerState` into its plain JSON shape (the session snapshot).
45
186
  * Guarantees the snapshot is JSON-serializable and schema-valid.
@@ -55,8 +196,13 @@ export const encodeStateEffect = Schema.encodeEffect(TrackerState);
55
196
  /**
56
197
  * Decode an untrusted snapshot (e.g. `data` from a session custom entry)
57
198
  * into a validated `TrackerState`. Fails with `SchemaError` on malformed
58
- * input; unknown extra keys are ignored for forward compatibility.
199
+ * input; unknown extra keys are ignored for forward compatibility, and the
200
+ * legacy item shapes accepted by `normalizeSnapshot` are tolerated.
201
+ *
202
+ * The result is not yet migrated: call `migrateState` (as
203
+ * `TrackerPersistence.restore` does) before handing it to the store.
59
204
  */
60
- export const decodeStateEffect = Schema.decodeUnknownEffect(TrackerState, {
61
- onExcessProperty: "ignore",
62
- });
205
+ export const decodeStateEffect = (snapshot: unknown) =>
206
+ Schema.decodeUnknownEffect(TrackerState, { onExcessProperty: "ignore" })(
207
+ normalizeSnapshot(snapshot),
208
+ );