@ftrdotdev/pi-tracker 0.6.0 → 0.8.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.
Files changed (36) hide show
  1. package/README.md +183 -60
  2. package/package.json +23 -11
  3. package/src/compaction/candidate.test.ts +9 -6
  4. package/src/compaction/candidate.ts +32 -2
  5. package/src/compaction/classifier.test.ts +67 -60
  6. package/src/compaction/classifier.ts +24 -22
  7. package/src/compaction/completion.test.ts +127 -49
  8. package/src/compaction/completion.ts +1 -3
  9. package/src/compaction/decision-record.test.ts +91 -0
  10. package/src/compaction/decision-record.ts +101 -0
  11. package/src/compaction/digest.test.ts +104 -9
  12. package/src/compaction/digest.ts +96 -9
  13. package/src/compaction/footprint.test.ts +135 -0
  14. package/src/compaction/footprint.ts +387 -0
  15. package/src/compaction/observations.test.ts +199 -0
  16. package/src/compaction/observations.ts +348 -0
  17. package/src/compaction/rules.test.ts +253 -0
  18. package/src/compaction/rules.ts +188 -0
  19. package/src/compaction/settings.test.ts +105 -49
  20. package/src/compaction/settings.ts +53 -31
  21. package/src/compaction/settle.test.ts +370 -0
  22. package/src/compaction/settle.ts +109 -53
  23. package/src/core/deps.test.ts +1 -1
  24. package/src/core/domain.test.ts +42 -9
  25. package/src/core/domain.ts +73 -8
  26. package/src/core/persistence.test.ts +7 -7
  27. package/src/core/store.test.ts +116 -50
  28. package/src/core/store.ts +92 -31
  29. package/src/index.test.ts +209 -68
  30. package/src/index.ts +170 -48
  31. package/src/presentation/tool-metadata.test.ts +263 -48
  32. package/src/presentation/tool-metadata.ts +325 -102
  33. package/src/presentation/ui.test.ts +122 -7
  34. package/src/presentation/ui.ts +81 -18
  35. package/src/presentation/vim-settings.test.ts +98 -0
  36. package/src/presentation/vim-settings.ts +59 -0
@@ -11,8 +11,8 @@ import type {
11
11
  } from "@earendil-works/pi-ai";
12
12
  import {
13
13
  CLASSIFY_TIMEOUT_MILLIS,
14
- DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE,
15
- DEFAULT_KEEP_CONTEXT_THRESHOLD,
14
+ DEFAULT_MIN_ANSWER_CONFIDENCE,
15
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
16
16
  NEEDS_CONTEXT_LABEL,
17
17
  NEEDS_NONE_LABEL,
18
18
  ClassifierGateway,
@@ -74,17 +74,17 @@ const choiceResult = (needsMass: number, confidence = 1, key = QUESTION_KEY): Cl
74
74
  const verdict = (
75
75
  result: ClassifierResult,
76
76
  questionKeys: readonly string[],
77
- keepContextThreshold = DEFAULT_KEEP_CONTEXT_THRESHOLD,
78
- keepContextMinConfidence = DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE,
79
- ) => classifyVerdict(result, questionKeys, keepContextThreshold, keepContextMinConfidence);
77
+ needsContextProbabilityThreshold = DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
78
+ minAnswerConfidence = DEFAULT_MIN_ANSWER_CONFIDENCE,
79
+ ) => classifyVerdict(result, questionKeys, needsContextProbabilityThreshold, minAnswerConfidence);
80
80
 
81
81
  const input = (
82
82
  registry: ClassifierRegistry,
83
83
  overrides: {
84
84
  enabled?: boolean;
85
85
  chosen?: Option.Option<ClassifierIdentity>;
86
- keepContextThreshold?: number;
87
- keepContextMinConfidence?: number;
86
+ needsContextProbabilityThreshold?: number;
87
+ minAnswerConfidence?: number;
88
88
  digest?: JsonObject;
89
89
  questions?: readonly CompactionQuestion[];
90
90
  signal?: AbortSignal;
@@ -93,17 +93,16 @@ const input = (
93
93
  registry,
94
94
  enabled: overrides.enabled ?? true,
95
95
  chosen: overrides.chosen ?? Option.none(),
96
- keepContextThreshold: overrides.keepContextThreshold ?? DEFAULT_KEEP_CONTEXT_THRESHOLD,
97
- keepContextMinConfidence:
98
- overrides.keepContextMinConfidence ?? DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE,
96
+ needsContextProbabilityThreshold:
97
+ overrides.needsContextProbabilityThreshold ?? DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
98
+ minAnswerConfidence: overrides.minAnswerConfidence ?? DEFAULT_MIN_ANSWER_CONFIDENCE,
99
99
  digest: overrides.digest ?? DIGEST,
100
100
  questions: overrides.questions ?? [question],
101
101
  signal: overrides.signal,
102
102
  });
103
103
 
104
- const withGateway = <A, E>(
105
- program: Effect.Effect<A, E, ClassifierGateway>,
106
- ): Effect.Effect<A, E> => program.pipe(Effect.provide(ClassifierGateway.layer));
104
+ const withGateway = <A, E>(program: Effect.Effect<A, E, ClassifierGateway>): Effect.Effect<A, E> =>
105
+ program.pipe(Effect.provide(ClassifierGateway.layer));
107
106
 
108
107
  // ---------------------------------------------------------------------------
109
108
  // resolveClassifier
@@ -179,9 +178,12 @@ it("resolveClassifier returns none when no classifier is credential-available",
179
178
  // ---------------------------------------------------------------------------
180
179
 
181
180
  it("classifyVerdict keeps context at the threshold", () => {
182
- assert.deepStrictEqual(verdict(choiceResult(DEFAULT_KEEP_CONTEXT_THRESHOLD), [QUESTION_KEY]), {
183
- kind: "keep",
184
- });
181
+ assert.deepStrictEqual(
182
+ verdict(choiceResult(DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD), [QUESTION_KEY]),
183
+ {
184
+ kind: "keep",
185
+ },
186
+ );
185
187
  });
186
188
 
187
189
  it("classifyVerdict compacts below the threshold", () => {
@@ -210,7 +212,7 @@ it("classifyVerdict keeps context when an answer is below the confidence floor",
210
212
 
211
213
  it("classifyVerdict compacts when the answer reaches the confidence floor", () => {
212
214
  assert.deepStrictEqual(
213
- verdict(choiceResult(0.1, DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE), [QUESTION_KEY]),
215
+ verdict(choiceResult(0.1, DEFAULT_MIN_ANSWER_CONFIDENCE), [QUESTION_KEY]),
214
216
  { kind: "compact" },
215
217
  );
216
218
  });
@@ -334,51 +336,56 @@ it.effect("gateway returns disabled when the classifier call exceeds the deadlin
334
336
  ),
335
337
  );
336
338
 
337
- it.effect("gateway returns a compact verdict for an available classifier and a low probability", () =>
338
- withGateway(
339
- Effect.gen(function* () {
340
- const gateway = yield* ClassifierGateway;
341
- const registry: ClassifierRegistry = {
342
- getAvailableOfType: async () => [clefFlash, jev],
343
- classify: async () => choiceResult(0.1, 0.9),
344
- };
345
- const result = yield* gateway.verdict(input(registry));
346
- assert.deepStrictEqual(result, { kind: "compact" });
347
- }),
348
- ),
339
+ it.effect(
340
+ "gateway returns a compact verdict for an available classifier and a low probability",
341
+ () =>
342
+ withGateway(
343
+ Effect.gen(function* () {
344
+ const gateway = yield* ClassifierGateway;
345
+ const registry: ClassifierRegistry = {
346
+ getAvailableOfType: async () => [clefFlash, jev],
347
+ classify: async () => choiceResult(0.1, 0.9),
348
+ };
349
+ const result = yield* gateway.verdict(input(registry));
350
+ assert.deepStrictEqual(result, { kind: "compact" });
351
+ }),
352
+ ),
349
353
  );
350
354
 
351
- it.effect("gateway forwards the run signal to the classifier call and returns disabled on abort", () => {
352
- // Constructed outside the Effect program so the run signal is a plain value.
353
- const controller = new AbortController();
354
- return withGateway(
355
- Effect.gen(function* () {
356
- const gateway = yield* ClassifierGateway;
357
- const captured: { signal?: AbortSignal } = {};
358
- const registry: ClassifierRegistry = {
359
- getAvailableOfType: async () => [jev],
360
- classify: (_model, _context, options) => {
361
- captured.signal = options?.signal;
362
- return new Promise((_resolve, reject) => {
363
- options?.signal?.addEventListener("abort", () => reject(new Error("run abort")));
364
- });
365
- },
366
- };
367
- const fiber = yield* Effect.forkChild(
368
- gateway.verdict(input(registry, { signal: controller.signal })),
369
- );
370
- let attempts = 0;
371
- while (captured.signal === undefined && attempts < 1000) {
372
- yield* Effect.yieldNow;
373
- attempts += 1;
374
- }
375
- controller.abort();
376
- const result = yield* Fiber.join(fiber);
377
- assert.deepStrictEqual(result, { kind: "disabled" });
378
- assert.strictEqual(captured.signal?.aborted, true);
379
- }),
380
- );
381
- });
355
+ it.effect(
356
+ "gateway forwards the run signal to the classifier call and returns disabled on abort",
357
+ () => {
358
+ // Constructed outside the Effect program so the run signal is a plain value.
359
+ const controller = new AbortController();
360
+ return withGateway(
361
+ Effect.gen(function* () {
362
+ const gateway = yield* ClassifierGateway;
363
+ const captured: { signal?: AbortSignal } = {};
364
+ const registry: ClassifierRegistry = {
365
+ getAvailableOfType: async () => [jev],
366
+ classify: (_model, _context, options) => {
367
+ captured.signal = options?.signal;
368
+ return new Promise((_resolve, reject) => {
369
+ options?.signal?.addEventListener("abort", () => reject(new Error("run abort")));
370
+ });
371
+ },
372
+ };
373
+ const fiber = yield* Effect.forkChild(
374
+ gateway.verdict(input(registry, { signal: controller.signal })),
375
+ );
376
+ let attempts = 0;
377
+ while (captured.signal === undefined && attempts < 1000) {
378
+ yield* Effect.yieldNow;
379
+ attempts += 1;
380
+ }
381
+ controller.abort();
382
+ const result = yield* Fiber.join(fiber);
383
+ assert.deepStrictEqual(result, { kind: "disabled" });
384
+ assert.strictEqual(captured.signal?.aborted, true);
385
+ }),
386
+ );
387
+ },
388
+ );
382
389
 
383
390
  it.effect("gateway sends exactly one choice question with the digest as the classifier state", () =>
384
391
  withGateway(
@@ -63,18 +63,19 @@ export const PREFERRED_CLASSIFIERS: readonly ClassifierIdentity[] = [
63
63
  ];
64
64
 
65
65
  /**
66
- * The default probability at or above which the candidate is judged to need
67
- * the prior context. A user overrides it with
68
- * `smartCompaction.keepContextThreshold`; the default keeps context on an
69
- * uncertain answer.
66
+ * The default `P(needs-context)` at or above which the candidate is judged to
67
+ * need the prior context. A user overrides it with
68
+ * `smartCompaction.needsContextProbabilityThreshold`. Raise it to compact more
69
+ * often.
70
70
  */
71
- export const DEFAULT_KEEP_CONTEXT_THRESHOLD = 0.5;
71
+ export const DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD = 0.5;
72
72
 
73
73
  /**
74
- * The default `confidence` below which the answer is distrusted and the context
75
- * is kept. A user overrides it with `smartCompaction.keepContextMinConfidence`.
74
+ * The default floor on the answer's self-reported `confidence`. A lower answer
75
+ * is distrusted and the context is kept. A user overrides it with
76
+ * `smartCompaction.minAnswerConfidence`. Raise it to keep context more often.
76
77
  */
77
- export const DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE = 0.5;
78
+ export const DEFAULT_MIN_ANSWER_CONFIDENCE = 0.5;
78
79
 
79
80
  /** The `choice` label that means the candidate needs the completed context. */
80
81
  export const NEEDS_CONTEXT_LABEL = "needs-context";
@@ -104,28 +105,29 @@ export const resolveClassifier = (
104
105
  };
105
106
 
106
107
  /**
107
- * The verdict over every judged candidate. Keep context when any candidate
108
- * needs the completed detail, or when an answer is below the confidence floor.
109
- * Compact only when every answer is above the floor and self-contained. A
110
- * non-stop or malformed answer, or an empty question set, keeps the context.
108
+ * The verdict over every judged candidate. Keep context when any candidate's
109
+ * `P(needs-context)` reaches `needsContextProbabilityThreshold`, or when an
110
+ * answer is below the `minAnswerConfidence` floor. Compact only when every
111
+ * answer is above the floor and self-contained. A non-stop or malformed answer,
112
+ * or an empty question set, keeps the context.
111
113
  */
112
114
  export const classifyVerdict = (
113
115
  result: ClassifierResult,
114
116
  questionKeys: readonly string[],
115
- keepContextThreshold: number,
116
- keepContextMinConfidence: number,
117
+ needsContextProbabilityThreshold: number,
118
+ minAnswerConfidence: number,
117
119
  ): ClassificationVerdict => {
118
120
  if (result.stopReason !== "stop") return CLASSIFICATION_VERDICT.disabled;
119
121
  if (questionKeys.length === 0) return CLASSIFICATION_VERDICT.disabled;
120
122
  for (const questionKey of questionKeys) {
121
123
  const answer = result.answers[questionKey];
122
124
  if (answer === undefined || answer.type !== "choice") return CLASSIFICATION_VERDICT.disabled;
123
- if ((answer.probabilities[NEEDS_CONTEXT_LABEL] ?? 0) >= keepContextThreshold) {
125
+ if ((answer.probabilities[NEEDS_CONTEXT_LABEL] ?? 0) >= needsContextProbabilityThreshold) {
124
126
  return CLASSIFICATION_VERDICT.keep;
125
127
  }
126
128
  // A provider that omits or mangles confidence keeps the context.
127
129
  const confidence = Number.isFinite(answer.confidence) ? answer.confidence : 0;
128
- if (confidence < keepContextMinConfidence) return CLASSIFICATION_VERDICT.keep;
130
+ if (confidence < minAnswerConfidence) return CLASSIFICATION_VERDICT.keep;
129
131
  }
130
132
  return CLASSIFICATION_VERDICT.compact;
131
133
  };
@@ -138,8 +140,8 @@ export class ClassifierGateway extends Context.Service<
138
140
  readonly registry: ClassifierRegistry;
139
141
  readonly enabled: boolean;
140
142
  readonly chosen: Option.Option<ClassifierIdentity>;
141
- readonly keepContextThreshold: number;
142
- readonly keepContextMinConfidence: number;
143
+ readonly needsContextProbabilityThreshold: number;
144
+ readonly minAnswerConfidence: number;
143
145
  readonly digest: JsonObject;
144
146
  readonly questions: readonly CompactionQuestion[];
145
147
  readonly signal?: AbortSignal | undefined;
@@ -151,8 +153,8 @@ export class ClassifierGateway extends Context.Service<
151
153
  readonly registry: ClassifierRegistry;
152
154
  readonly enabled: boolean;
153
155
  readonly chosen: Option.Option<ClassifierIdentity>;
154
- readonly keepContextThreshold: number;
155
- readonly keepContextMinConfidence: number;
156
+ readonly needsContextProbabilityThreshold: number;
157
+ readonly minAnswerConfidence: number;
156
158
  readonly digest: JsonObject;
157
159
  readonly questions: readonly CompactionQuestion[];
158
160
  readonly signal?: AbortSignal | undefined;
@@ -187,8 +189,8 @@ export class ClassifierGateway extends Context.Service<
187
189
  : classifyVerdict(
188
190
  result.value,
189
191
  input.questions.map((question) => question.key),
190
- input.keepContextThreshold,
191
- input.keepContextMinConfidence,
192
+ input.needsContextProbabilityThreshold,
193
+ input.minAnswerConfidence,
192
194
  );
193
195
  });
194
196
  return ClassifierGateway.of({ verdict });
@@ -14,7 +14,13 @@ const list = (id: number, name: string, items: readonly ItemSpec[]): TodoList =>
14
14
  id,
15
15
  name,
16
16
  items: items.map(
17
- (item) => new TodoItem({ id: item.id, text: `item ${item.id}`, done: item.done, deps: [...(item.deps ?? [])] }),
17
+ (item) =>
18
+ new TodoItem({
19
+ id: item.id,
20
+ title: `item ${item.id}`,
21
+ done: item.done,
22
+ deps: [...(item.deps ?? [])],
23
+ }),
18
24
  ),
19
25
  nextItemId: items.reduce((max, item) => Math.max(max, item.id), 0) + 1,
20
26
  });
@@ -30,8 +36,24 @@ const state = (
30
36
  // ---------------------------------------------------------------------------
31
37
 
32
38
  it("completedInActiveList returns every item that transitioned from open to done, in list order", () => {
33
- const before = state([list(1, "Work", [{ id: 1, done: false }, { id: 3, done: false }])], 1);
34
- const after = state([list(1, "Work", [{ id: 1, done: true }, { id: 3, done: true }])], 1);
39
+ const before = state(
40
+ [
41
+ list(1, "Work", [
42
+ { id: 1, done: false },
43
+ { id: 3, done: false },
44
+ ]),
45
+ ],
46
+ 1,
47
+ );
48
+ const after = state(
49
+ [
50
+ list(1, "Work", [
51
+ { id: 1, done: true },
52
+ { id: 3, done: true },
53
+ ]),
54
+ ],
55
+ 1,
56
+ );
35
57
  assert.deepStrictEqual(completedInActiveList(before, after), [1, 3]);
36
58
  });
37
59
 
@@ -71,9 +93,33 @@ it.effect("CompletionObserver record folds successive mutations into one batch",
71
93
  withObserver(
72
94
  Effect.gen(function* () {
73
95
  const observer = yield* CompletionObserver;
74
- const s0 = state([list(1, "Work", [{ id: 1, done: false }, { id: 3, done: false }])], 1);
75
- const s1 = state([list(1, "Work", [{ id: 1, done: true }, { id: 3, done: false }])], 1);
76
- const s2 = state([list(1, "Work", [{ id: 1, done: true }, { id: 3, done: true }])], 1);
96
+ const s0 = state(
97
+ [
98
+ list(1, "Work", [
99
+ { id: 1, done: false },
100
+ { id: 3, done: false },
101
+ ]),
102
+ ],
103
+ 1,
104
+ );
105
+ const s1 = state(
106
+ [
107
+ list(1, "Work", [
108
+ { id: 1, done: true },
109
+ { id: 3, done: false },
110
+ ]),
111
+ ],
112
+ 1,
113
+ );
114
+ const s2 = state(
115
+ [
116
+ list(1, "Work", [
117
+ { id: 1, done: true },
118
+ { id: 3, done: true },
119
+ ]),
120
+ ],
121
+ 1,
122
+ );
77
123
  yield* observer.record(s0, s1);
78
124
  yield* observer.record(s1, s2);
79
125
  const batch = Option.getOrThrow(yield* observer.consume);
@@ -86,23 +132,33 @@ it.effect("CompletionObserver record folds successive mutations into one batch",
86
132
  ),
87
133
  );
88
134
 
89
- it.effect("CompletionObserver record refreshes the snapshot when a later mutation completes nothing", () =>
90
- withObserver(
91
- Effect.gen(function* () {
92
- const observer = yield* CompletionObserver;
93
- const s0 = state([list(1, "Work", [{ id: 1, done: false }])], 1);
94
- const s1 = state([list(1, "Work", [{ id: 1, done: true }])], 1);
95
- const s2 = state([list(1, "Work", [{ id: 1, done: true }, { id: 2, done: false }])], 1);
96
- yield* observer.record(s0, s1);
97
- yield* observer.record(s1, s2);
98
- const batch = Option.getOrThrow(yield* observer.consume);
99
- assert.deepStrictEqual(batch.completedItemIds, [1]);
100
- assert.deepStrictEqual(
101
- batch.list.items.map((item) => item.id),
102
- [1, 2],
103
- );
104
- }),
105
- ),
135
+ it.effect(
136
+ "CompletionObserver record refreshes the snapshot when a later mutation completes nothing",
137
+ () =>
138
+ withObserver(
139
+ Effect.gen(function* () {
140
+ const observer = yield* CompletionObserver;
141
+ const s0 = state([list(1, "Work", [{ id: 1, done: false }])], 1);
142
+ const s1 = state([list(1, "Work", [{ id: 1, done: true }])], 1);
143
+ const s2 = state(
144
+ [
145
+ list(1, "Work", [
146
+ { id: 1, done: true },
147
+ { id: 2, done: false },
148
+ ]),
149
+ ],
150
+ 1,
151
+ );
152
+ yield* observer.record(s0, s1);
153
+ yield* observer.record(s1, s2);
154
+ const batch = Option.getOrThrow(yield* observer.consume);
155
+ assert.deepStrictEqual(batch.completedItemIds, [1]);
156
+ assert.deepStrictEqual(
157
+ batch.list.items.map((item) => item.id),
158
+ [1, 2],
159
+ );
160
+ }),
161
+ ),
106
162
  );
107
163
 
108
164
  it.effect("CompletionObserver record drops a completed item that was reopened before settle", () =>
@@ -133,34 +189,56 @@ it.effect("CompletionObserver record drops a completed item that was removed bef
133
189
  ),
134
190
  );
135
191
 
136
- it.effect("CompletionObserver record clears the batch when the active list changes without a completion", () =>
137
- withObserver(
138
- Effect.gen(function* () {
139
- const observer = yield* CompletionObserver;
140
- const s0 = state([list(1, "Work", [{ id: 1, done: false }]), list(2, "Other", [{ id: 1, done: false }])], 1);
141
- const s1 = state([list(1, "Work", [{ id: 1, done: true }]), list(2, "Other", [{ id: 1, done: false }])], 1);
142
- const s2 = state([list(1, "Work", [{ id: 1, done: true }]), list(2, "Other", [{ id: 1, done: false }])], 2);
143
- yield* observer.record(s0, s1);
144
- yield* observer.record(s1, s2);
145
- assert.strictEqual(Option.isNone(yield* observer.consume), true);
146
- }),
147
- ),
192
+ it.effect(
193
+ "CompletionObserver record clears the batch when the active list changes without a completion",
194
+ () =>
195
+ withObserver(
196
+ Effect.gen(function* () {
197
+ const observer = yield* CompletionObserver;
198
+ const s0 = state(
199
+ [list(1, "Work", [{ id: 1, done: false }]), list(2, "Other", [{ id: 1, done: false }])],
200
+ 1,
201
+ );
202
+ const s1 = state(
203
+ [list(1, "Work", [{ id: 1, done: true }]), list(2, "Other", [{ id: 1, done: false }])],
204
+ 1,
205
+ );
206
+ const s2 = state(
207
+ [list(1, "Work", [{ id: 1, done: true }]), list(2, "Other", [{ id: 1, done: false }])],
208
+ 2,
209
+ );
210
+ yield* observer.record(s0, s1);
211
+ yield* observer.record(s1, s2);
212
+ assert.strictEqual(Option.isNone(yield* observer.consume), true);
213
+ }),
214
+ ),
148
215
  );
149
216
 
150
- it.effect("CompletionObserver record starts a fresh batch when a completion arrives in a different active list", () =>
151
- withObserver(
152
- Effect.gen(function* () {
153
- const observer = yield* CompletionObserver;
154
- const s0 = state([list(1, "Work", [{ id: 1, done: false }]), list(2, "Other", [{ id: 1, done: false }])], 1);
155
- const s1 = state([list(1, "Work", [{ id: 1, done: true }]), list(2, "Other", [{ id: 1, done: false }])], 1);
156
- const s2 = state([list(1, "Work", [{ id: 1, done: true }]), list(2, "Other", [{ id: 1, done: true }])], 2);
157
- yield* observer.record(s0, s1);
158
- yield* observer.record(s1, s2);
159
- const batch = Option.getOrThrow(yield* observer.consume);
160
- assert.deepStrictEqual(batch.completedItemIds, [1]);
161
- assert.strictEqual(batch.list.name, "Other");
162
- }),
163
- ),
217
+ it.effect(
218
+ "CompletionObserver record starts a fresh batch when a completion arrives in a different active list",
219
+ () =>
220
+ withObserver(
221
+ Effect.gen(function* () {
222
+ const observer = yield* CompletionObserver;
223
+ const s0 = state(
224
+ [list(1, "Work", [{ id: 1, done: false }]), list(2, "Other", [{ id: 1, done: false }])],
225
+ 1,
226
+ );
227
+ const s1 = state(
228
+ [list(1, "Work", [{ id: 1, done: true }]), list(2, "Other", [{ id: 1, done: false }])],
229
+ 1,
230
+ );
231
+ const s2 = state(
232
+ [list(1, "Work", [{ id: 1, done: true }]), list(2, "Other", [{ id: 1, done: true }])],
233
+ 2,
234
+ );
235
+ yield* observer.record(s0, s1);
236
+ yield* observer.record(s1, s2);
237
+ const batch = Option.getOrThrow(yield* observer.consume);
238
+ assert.deepStrictEqual(batch.completedItemIds, [1]);
239
+ assert.strictEqual(batch.list.name, "Other");
240
+ }),
241
+ ),
164
242
  );
165
243
 
166
244
  it.effect("CompletionObserver consume clears the record", () =>
@@ -63,9 +63,7 @@ const mergeLiveBatch = (
63
63
  const completedItemIds = list.items
64
64
  .filter((item) => item.done && tracked.has(item.id))
65
65
  .map((item) => item.id);
66
- return completedItemIds.length === 0
67
- ? Option.none()
68
- : Option.some({ list, completedItemIds });
66
+ return completedItemIds.length === 0 ? Option.none() : Option.some({ list, completedItemIds });
69
67
  };
70
68
 
71
69
  export class CompletionObserver extends Context.Service<
@@ -0,0 +1,91 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { Effect } from "effect";
3
+ import {
4
+ DECISION_CUSTOM_TYPE,
5
+ buildDecisionRecord,
6
+ decodeDecisionRecord,
7
+ encodeDecisionRecord,
8
+ type DecisionRecord,
9
+ } from "./decision-record.ts";
10
+ import type { ResolvedProduct, ResolvedReference } from "./observations.ts";
11
+
12
+ const reference = (
13
+ value: ResolvedReference["reference"],
14
+ state: ResolvedReference["state"],
15
+ ): ResolvedReference => ({ reference: value, state });
16
+
17
+ const product = (path: string, state: ResolvedProduct["state"]): ResolvedProduct => ({
18
+ product: { path },
19
+ state,
20
+ });
21
+
22
+ const input = (overrides: {
23
+ readonly references?: readonly ResolvedReference[];
24
+ readonly products?: readonly ResolvedProduct[];
25
+ }): Parameters<typeof buildDecisionRecord>[0] => ({
26
+ rule: "reference-is-readable",
27
+ verdict: "compact",
28
+ candidateRef: "Work:2",
29
+ references: overrides.references ?? [],
30
+ products: overrides.products ?? [],
31
+ });
32
+
33
+ it("the custom-entry type is the reliance-decision carrier", () => {
34
+ assert.strictEqual(DECISION_CUSTOM_TYPE, "tracker/reliance-decision");
35
+ });
36
+
37
+ it("a decision records the fired row and the resolved states", () => {
38
+ const record = buildDecisionRecord(
39
+ input({
40
+ references: [reference({ kind: "path", path: "src/a.ts", symbol: "route" }, "readable")],
41
+ products: [product("docs/plan.md", "missing")],
42
+ }),
43
+ )!;
44
+ assert.deepStrictEqual(record, {
45
+ rule: "reference-is-readable",
46
+ verdict: "compact",
47
+ candidateRef: "Work:2",
48
+ references: [{ kind: "path", path: "src/a.ts", symbol: "route", state: "readable" }],
49
+ products: [{ path: "docs/plan.md", state: "missing" }],
50
+ });
51
+ assert.notInclude(JSON.stringify(record), "transcript");
52
+ });
53
+
54
+ it("a decision with no declarations records no decision entry", () => {
55
+ assert.isUndefined(buildDecisionRecord(input({})));
56
+ });
57
+
58
+ it("a decision reference rides as a topic, not as an archived claim", () => {
59
+ const record = buildDecisionRecord(
60
+ input({ references: [reference({ kind: "decision", topic: "storage shape" }, "unresolved")] }),
61
+ )!;
62
+ assert.deepStrictEqual(record.references, [
63
+ { kind: "decision", topic: "storage shape", state: "unresolved" },
64
+ ]);
65
+ assert.notInclude(JSON.stringify(record), "archived");
66
+ });
67
+
68
+ it("a record round-trips through the codec", () => {
69
+ const record = buildDecisionRecord(
70
+ input({ references: [reference({ kind: "path", path: "src/a.ts" }, "drifted")] }),
71
+ )!;
72
+ const decoded = Effect.runSync(decodeDecisionRecord(encodeDecisionRecord(record)));
73
+ assert.deepStrictEqual(decoded as DecisionRecord, record);
74
+ });
75
+
76
+ it("a record caps references at eight and products at four", () => {
77
+ const references = Array.from({ length: 10 }, (_value, index) =>
78
+ reference({ kind: "path", path: `src/f${index}.ts` }, "readable"),
79
+ );
80
+ const products = Array.from({ length: 6 }, (_value, index) =>
81
+ product(`src/p${index}.ts`, "exists"),
82
+ );
83
+ const record = buildDecisionRecord(input({ references, products }))!;
84
+ assert.strictEqual(record.references.length, 8);
85
+ assert.strictEqual(record.products.length, 4);
86
+ });
87
+
88
+ it("a malformed record fails to decode", () => {
89
+ const exit = Effect.runSync(Effect.exit(decodeDecisionRecord({ rule: 42 })));
90
+ assert.strictEqual(exit._tag, "Failure");
91
+ });