@ftrdotdev/pi-tracker 0.5.2 → 0.6.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.
@@ -0,0 +1,179 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { Effect, Option } from "effect";
3
+ import { CompletionObserver, completedInActiveList } from "./completion.ts";
4
+ import { TodoItem, TodoList, TrackerState } from "../core/domain.ts";
5
+
6
+ interface ItemSpec {
7
+ readonly id: number;
8
+ readonly done: boolean;
9
+ readonly deps?: readonly string[];
10
+ }
11
+
12
+ const list = (id: number, name: string, items: readonly ItemSpec[]): TodoList =>
13
+ new TodoList({
14
+ id,
15
+ name,
16
+ items: items.map(
17
+ (item) => new TodoItem({ id: item.id, text: `item ${item.id}`, done: item.done, deps: [...(item.deps ?? [])] }),
18
+ ),
19
+ nextItemId: items.reduce((max, item) => Math.max(max, item.id), 0) + 1,
20
+ });
21
+
22
+ const state = (
23
+ lists: readonly TodoList[],
24
+ activeListId: number | null,
25
+ nextListId = lists.length + 1,
26
+ ): TrackerState => new TrackerState({ lists: [...lists], activeListId, nextListId });
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // completedInActiveList
30
+ // ---------------------------------------------------------------------------
31
+
32
+ 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);
35
+ assert.deepStrictEqual(completedInActiveList(before, after), [1, 3]);
36
+ });
37
+
38
+ it("completedInActiveList returns a single id for a single completion", () => {
39
+ const before = state([list(1, "Work", [{ id: 1, done: false }])], 1);
40
+ const after = state([list(1, "Work", [{ id: 1, done: true }])], 1);
41
+ assert.deepStrictEqual(completedInActiveList(before, after), [1]);
42
+ });
43
+
44
+ it("completedInActiveList ignores an item that was already done", () => {
45
+ const before = state([list(1, "Work", [{ id: 1, done: true }])], 1);
46
+ const after = state([list(1, "Work", [{ id: 1, done: true }])], 1);
47
+ assert.deepStrictEqual(completedInActiveList(before, after), []);
48
+ });
49
+
50
+ it("completedInActiveList ignores a completion in a list that is not active", () => {
51
+ const before = state(
52
+ [list(1, "Work", [{ id: 1, done: false }]), list(2, "Other", [{ id: 1, done: false }])],
53
+ 1,
54
+ );
55
+ const after = state(
56
+ [list(1, "Work", [{ id: 1, done: false }]), list(2, "Other", [{ id: 1, done: true }])],
57
+ 1,
58
+ );
59
+ assert.deepStrictEqual(completedInActiveList(before, after), []);
60
+ });
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // CompletionObserver
64
+ // ---------------------------------------------------------------------------
65
+
66
+ const withObserver = <A, E>(
67
+ program: Effect.Effect<A, E, CompletionObserver>,
68
+ ): Effect.Effect<A, E> => program.pipe(Effect.provide(CompletionObserver.layer));
69
+
70
+ it.effect("CompletionObserver record folds successive mutations into one batch", () =>
71
+ withObserver(
72
+ Effect.gen(function* () {
73
+ 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);
77
+ yield* observer.record(s0, s1);
78
+ yield* observer.record(s1, s2);
79
+ const batch = Option.getOrThrow(yield* observer.consume);
80
+ assert.deepStrictEqual(batch.completedItemIds, [1, 3]);
81
+ assert.deepStrictEqual(
82
+ batch.list.items.map((item) => item.done),
83
+ [true, true],
84
+ );
85
+ }),
86
+ ),
87
+ );
88
+
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
+ ),
106
+ );
107
+
108
+ it.effect("CompletionObserver record drops a completed item that was reopened before settle", () =>
109
+ withObserver(
110
+ Effect.gen(function* () {
111
+ const observer = yield* CompletionObserver;
112
+ const s0 = state([list(1, "Work", [{ id: 1, done: false }])], 1);
113
+ const s1 = state([list(1, "Work", [{ id: 1, done: true }])], 1);
114
+ const s2 = state([list(1, "Work", [{ id: 1, done: false }])], 1);
115
+ yield* observer.record(s0, s1);
116
+ yield* observer.record(s1, s2);
117
+ assert.strictEqual(Option.isNone(yield* observer.consume), true);
118
+ }),
119
+ ),
120
+ );
121
+
122
+ it.effect("CompletionObserver record drops a completed item that was removed before settle", () =>
123
+ withObserver(
124
+ Effect.gen(function* () {
125
+ const observer = yield* CompletionObserver;
126
+ const s0 = state([list(1, "Work", [{ id: 1, done: false }])], 1);
127
+ const s1 = state([list(1, "Work", [{ id: 1, done: true }])], 1);
128
+ const s2 = state([list(1, "Work", [])], 1);
129
+ yield* observer.record(s0, s1);
130
+ yield* observer.record(s1, s2);
131
+ assert.strictEqual(Option.isNone(yield* observer.consume), true);
132
+ }),
133
+ ),
134
+ );
135
+
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
+ ),
148
+ );
149
+
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
+ ),
164
+ );
165
+
166
+ it.effect("CompletionObserver consume clears the record", () =>
167
+ withObserver(
168
+ Effect.gen(function* () {
169
+ const observer = yield* CompletionObserver;
170
+ const s0 = state([list(1, "Work", [{ id: 1, done: false }])], 1);
171
+ const s1 = state([list(1, "Work", [{ id: 1, done: true }])], 1);
172
+ yield* observer.record(s0, s1);
173
+ const first = yield* observer.consume;
174
+ const second = yield* observer.consume;
175
+ assert.strictEqual(Option.isSome(first), true);
176
+ assert.strictEqual(Option.isNone(second), true);
177
+ }),
178
+ ),
179
+ );
@@ -0,0 +1,96 @@
1
+ import { Context, Effect, Layer, Option, Ref } from "effect";
2
+ import type { TodoList, TrackerState } from "../core/domain.ts";
3
+
4
+ /**
5
+ * Completion detection and the pending-completion record.
6
+ *
7
+ * The record is in-memory only and never persisted. It carries the active list
8
+ * as it stands and every item that transitioned open → done since the last
9
+ * decision, as a batch. The batch is referenced prior work; the decision's
10
+ * subject is always the next unfinished candidate.
11
+ */
12
+
13
+ /** The completions a settle decision may act on. In memory only, never persisted. */
14
+ export interface PendingCompletion {
15
+ /** The active list as it stands now; refreshed on every same-list mutation. */
16
+ readonly list: TodoList;
17
+ /** Every item that transitioned open → done since the last decision, in list order. */
18
+ readonly completedItemIds: readonly number[];
19
+ }
20
+
21
+ /**
22
+ * Ids of active-list items that transitioned open → done, in list order. Empty
23
+ * when none. Only the active list is consulted, and a completion in another
24
+ * list contributes nothing.
25
+ */
26
+ export const completedInActiveList = (
27
+ before: TrackerState,
28
+ after: TrackerState,
29
+ ): readonly number[] => {
30
+ if (after.activeListId === null) return [];
31
+ const activeAfter = after.lists.find((list) => list.id === after.activeListId);
32
+ if (activeAfter === undefined) return [];
33
+ const activeBefore = before.lists.find((list) => list.id === after.activeListId);
34
+ const doneBefore = new Set(
35
+ (activeBefore?.items ?? []).filter((item) => item.done).map((item) => item.id),
36
+ );
37
+ return activeAfter.items
38
+ .filter((item) => item.done && !doneBefore.has(item.id))
39
+ .map((item) => item.id);
40
+ };
41
+
42
+ /**
43
+ * Live-record fold: refresh the snapshot from `after`; keep the previously
44
+ * completed ids that are still done and present; add the new ones. A different
45
+ * active list (or none) clears the record. An empty result clears it too, so a
46
+ * reopen or removal between the completion and the settle cannot leave a
47
+ * stale batch behind.
48
+ */
49
+ const mergeLiveBatch = (
50
+ current: Option.Option<PendingCompletion>,
51
+ after: TrackerState,
52
+ newlyCompleted: readonly number[],
53
+ ): Option.Option<PendingCompletion> => {
54
+ if (after.activeListId === null) return Option.none();
55
+ const list = after.lists.find((candidate) => candidate.id === after.activeListId);
56
+ if (list === undefined) return Option.none();
57
+
58
+ const previousIds =
59
+ Option.isSome(current) && current.value.list.id === list.id
60
+ ? current.value.completedItemIds
61
+ : [];
62
+ const tracked = new Set<number>([...previousIds, ...newlyCompleted]);
63
+ const completedItemIds = list.items
64
+ .filter((item) => item.done && tracked.has(item.id))
65
+ .map((item) => item.id);
66
+ return completedItemIds.length === 0
67
+ ? Option.none()
68
+ : Option.some({ list, completedItemIds });
69
+ };
70
+
71
+ export class CompletionObserver extends Context.Service<
72
+ CompletionObserver,
73
+ {
74
+ readonly record: (before: TrackerState, after: TrackerState) => Effect.Effect<void>;
75
+ /** Read and clear in one step, so one completion set yields one decision. */
76
+ readonly consume: Effect.Effect<Option.Option<PendingCompletion>>;
77
+ }
78
+ >()("tracker/CompletionObserver") {
79
+ static readonly layer: Layer.Layer<CompletionObserver> = Layer.effect(
80
+ CompletionObserver,
81
+ Effect.gen(function* () {
82
+ const pending = yield* Ref.make(Option.none<PendingCompletion>());
83
+ const record = Effect.fnUntraced(function* (before: TrackerState, after: TrackerState) {
84
+ const newlyCompleted = completedInActiveList(before, after);
85
+ // A mutation in a different active list (or a deselect/delete) clears
86
+ // the record. Otherwise the snapshot follows the current list, and ids
87
+ // that were reopened or removed drop out; an empty result clears it.
88
+ yield* Ref.update(pending, (current) => mergeLiveBatch(current, after, newlyCompleted));
89
+ });
90
+ return CompletionObserver.of({
91
+ record,
92
+ consume: Ref.modify(pending, (current) => [current, Option.none<PendingCompletion>()]),
93
+ });
94
+ }),
95
+ );
96
+ }
@@ -0,0 +1,90 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { NEEDS_CONTEXT_LABEL, NEEDS_NONE_LABEL } from "./classifier.ts";
3
+ import type { CompactionCandidate } from "./candidate.ts";
4
+ import {
5
+ QUESTION_KEY_PREFIX,
6
+ buildDigests,
7
+ compactQuestions,
8
+ questionKey,
9
+ } from "./digest.ts";
10
+
11
+ interface DigestShape {
12
+ candidates: Array<{ ref: string; text: string; class: string; relationship: string }>;
13
+ completed: Array<{ ref: string; text: string }>;
14
+ }
15
+
16
+ const dependent: CompactionCandidate = {
17
+ class: "dependent-successor",
18
+ listName: "Work",
19
+ id: 2,
20
+ text: "second",
21
+ completed: [{ ref: "Work:1", text: "first" }],
22
+ };
23
+
24
+ const readyQueue: CompactionCandidate = {
25
+ class: "ready-queue",
26
+ listName: "Work",
27
+ id: 3,
28
+ text: "third",
29
+ completed: [{ ref: "Work:1", text: "first" }],
30
+ };
31
+
32
+ it("buildDigests carries only the candidates and the completed batch", () => {
33
+ const digest = buildDigests([dependent]);
34
+ assert.deepStrictEqual(Object.keys(digest).sort(), ["candidates", "completed"]);
35
+ });
36
+
37
+ it("buildDigests lists one entry per candidate with its class and relationship", () => {
38
+ const digest = buildDigests([dependent, readyQueue]) as unknown as DigestShape;
39
+ assert.deepStrictEqual(digest.candidates, [
40
+ { ref: "Work:2", text: "second", class: "dependent-successor", relationship: "depends on Work:1" },
41
+ { ref: "Work:3", text: "third", class: "ready-queue", relationship: "independent of Work:1" },
42
+ ]);
43
+ });
44
+
45
+ it("buildDigests carries the completed batch once as prior work", () => {
46
+ const digest = buildDigests([dependent, readyQueue]) as unknown as DigestShape;
47
+ assert.deepStrictEqual(digest.completed, [{ ref: "Work:1", text: "first" }]);
48
+ });
49
+
50
+ it("compactQuestions keys each question by its candidate reference and index", () => {
51
+ const questions = compactQuestions([dependent, readyQueue]);
52
+ assert.deepStrictEqual(
53
+ questions.map((entry) => entry.key),
54
+ [questionKey("Work:2", 0), questionKey("Work:3", 1)],
55
+ );
56
+ assert.strictEqual(questions[0]!.key, `${QUESTION_KEY_PREFIX}.Work_2.0`);
57
+ });
58
+
59
+ it("compactQuestions produces ids that satisfy the provider pattern", () => {
60
+ const questions = compactQuestions([dependent, readyQueue]);
61
+ for (const { key } of questions) {
62
+ assert.match(key, /^[A-Za-z0-9_.-]{1,100}$/);
63
+ }
64
+ });
65
+
66
+ it("compactQuestions asks one two-label choice question per candidate", () => {
67
+ const questions = compactQuestions([dependent, readyQueue]);
68
+ assert.strictEqual(questions.length, 2);
69
+ for (const { question } of questions) {
70
+ assert.strictEqual(question.type, "choice");
71
+ if (question.type !== "choice") continue;
72
+ assert.isAtLeast(question.instructions.length, 1);
73
+ assert.deepStrictEqual(
74
+ Object.keys(question.criteria).sort(),
75
+ [NEEDS_CONTEXT_LABEL, NEEDS_NONE_LABEL].sort(),
76
+ );
77
+ assert.isAtLeast(question.criteria[NEEDS_CONTEXT_LABEL]!.length, 1);
78
+ assert.isAtLeast(question.criteria[NEEDS_NONE_LABEL]!.length, 1);
79
+ }
80
+ });
81
+
82
+ it("compactQuestions uses the class-specific wording", () => {
83
+ const [dependentQuestion, queueQuestion] = compactQuestions([dependent, readyQueue]);
84
+ assert.include(dependentQuestion!.question.instructions, "depends on");
85
+ assert.include(queueQuestion!.question.instructions, "completed work");
86
+ assert.notStrictEqual(
87
+ dependentQuestion!.question.instructions,
88
+ queueQuestion!.question.instructions,
89
+ );
90
+ });
@@ -0,0 +1,71 @@
1
+ import type { JsonObject } from "@earendil-works/pi-ai";
2
+ import { formatItemRef } from "../core/deps.ts";
3
+ import { NEEDS_CONTEXT_LABEL, NEEDS_NONE_LABEL, type CompactionQuestion } from "./classifier.ts";
4
+ import type { CompactionCandidate } from "./candidate.ts";
5
+
6
+ /**
7
+ * The bounded classifier input: every ready candidate, each with its class and
8
+ * its relationship to the completed batch, plus the batch itself as referenced
9
+ * prior work. The transcript is never read.
10
+ */
11
+
12
+ /** Shared prefix of the per-candidate classifier question key. */
13
+ export const QUESTION_KEY_PREFIX = "needsCompletedContext";
14
+
15
+ /**
16
+ * A safe, unique question id for one candidate. Cloudflare Workers AI rejects
17
+ * any id that does not match `^[A-Za-z0-9_.-]{1,100}$`, so the item reference
18
+ * (`Work:2`) is sanitized and a positional index is appended for uniqueness.
19
+ */
20
+ export const questionKey = (ref: string, index: number): string =>
21
+ `${QUESTION_KEY_PREFIX}.${ref.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 60)}.${index}`;
22
+
23
+ const relationshipOf = (candidate: CompactionCandidate): string =>
24
+ candidate.class === "dependent-successor"
25
+ ? `depends on ${candidate.completed[0]?.ref ?? "the completed work"}`
26
+ : `independent of ${candidate.completed.map((item) => item.ref).join(", ")}`;
27
+
28
+ /**
29
+ * One entry per candidate plus the completed batch once. Exactly two keys.
30
+ */
31
+ export const buildDigests = (candidates: readonly CompactionCandidate[]): JsonObject => ({
32
+ candidates: candidates.map((candidate) => ({
33
+ ref: formatItemRef(candidate.listName, candidate.id),
34
+ text: candidate.text,
35
+ class: candidate.class,
36
+ relationship: relationshipOf(candidate),
37
+ })),
38
+ completed: (candidates[0]?.completed ?? []).map((item) => ({ ref: item.ref, text: item.text })),
39
+ });
40
+
41
+ /**
42
+ * One two-label choice question per candidate, keyed by the candidate's
43
+ * reference, so a single classifier call judges the whole ready frontier. The
44
+ * candidate class chooses the wording, so a dependent successor and independent
45
+ * work are asked different questions in the same call. The two labels stay
46
+ * binary either way; `confidence` rides along on the answer.
47
+ */
48
+ export const compactQuestions = (
49
+ candidates: readonly CompactionCandidate[],
50
+ ): readonly CompactionQuestion[] =>
51
+ candidates.map((candidate, index) => {
52
+ const ref = formatItemRef(candidate.listName, candidate.id);
53
+ const dependent = candidate.class === "dependent-successor";
54
+ return {
55
+ key: questionKey(ref, index),
56
+ question: {
57
+ type: "choice",
58
+ instructions: dependent
59
+ ? `The completed work is about to leave the context. Does this ready item #${ref} ("${candidate.text}") need the detail of the completed item it depends on?`
60
+ : `The completed work is about to leave the context. Does this ready item #${ref} ("${candidate.text}") need the detail of the completed work?`,
61
+ criteria: {
62
+ [NEEDS_CONTEXT_LABEL]: dependent
63
+ ? "The item needs specifics of the completed work — an interface, decision, or value — that its own text does not carry."
64
+ : "The item refers to the completed work or needs its details to proceed.",
65
+ [NEEDS_NONE_LABEL]: dependent
66
+ ? "The item's own text is self-contained and its dependency is only ordering."
67
+ : "The item stands alone and does not need the completed detail.",
68
+ },
69
+ },
70
+ };
71
+ });
@@ -0,0 +1,26 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import type { CompactionCandidate } from "./candidate.ts";
3
+ import { resumePointer } from "./pointer.ts";
4
+
5
+ const candidate: CompactionCandidate = {
6
+ class: "dependent-successor",
7
+ listName: "Work",
8
+ id: 4,
9
+ text: "third slice",
10
+ completed: [{ ref: "Work:1", text: "first slice" }],
11
+ };
12
+
13
+ it("resumePointer names the next ready item", () => {
14
+ const pointer = resumePointer(candidate);
15
+ assert.isTrue(pointer.includes("Work:4"));
16
+ assert.isTrue(pointer.includes("third slice"));
17
+ });
18
+
19
+ it("resumePointer reads as a continuation of the current work", () => {
20
+ const pointer = resumePointer(candidate);
21
+ assert.isTrue(pointer.includes("Work"));
22
+ assert.isTrue(pointer.includes("compacted"));
23
+ // A continuation, not a new request: it must not open by soliciting new work.
24
+ assert.isFalse(pointer.toLowerCase().includes("please"));
25
+ assert.isFalse(pointer.toLowerCase().includes("new task"));
26
+ });
@@ -0,0 +1,15 @@
1
+ import { formatItemRef } from "../core/deps.ts";
2
+ import type { CompactionCandidate } from "./candidate.ts";
3
+
4
+ /** The custom-message type the resume turn carries. */
5
+ export const SMART_COMPACTION_CUSTOM_TYPE = "tracker/smart-compaction";
6
+
7
+ /**
8
+ * A continuation note naming the next ready item after compaction. It reads as
9
+ * a continuation of the current work, never as a new request, and it is never
10
+ * written to a plan file.
11
+ */
12
+ export const resumePointer = (candidate: CompactionCandidate): string =>
13
+ `Continue the ${candidate.listName} tracker list. ` +
14
+ `The earlier context was compacted after the completed work. ` +
15
+ `The next ready item is #${formatItemRef(candidate.listName, candidate.id)}: ${candidate.text}.`;