@ftrdotdev/pi-tracker 0.5.2 → 0.7.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 (39) hide show
  1. package/README.md +136 -46
  2. package/package.json +8 -2
  3. package/src/compaction/candidate.test.ts +191 -0
  4. package/src/compaction/candidate.ts +105 -0
  5. package/src/compaction/classifier.test.ts +422 -0
  6. package/src/compaction/classifier.ts +198 -0
  7. package/src/compaction/completion.test.ts +257 -0
  8. package/src/compaction/completion.ts +94 -0
  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 +185 -0
  12. package/src/compaction/digest.ts +158 -0
  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/pointer.test.ts +26 -0
  18. package/src/compaction/pointer.ts +15 -0
  19. package/src/compaction/rules.test.ts +253 -0
  20. package/src/compaction/rules.ts +188 -0
  21. package/src/compaction/settings.test.ts +315 -0
  22. package/src/compaction/settings.ts +185 -0
  23. package/src/compaction/settle.test.ts +370 -0
  24. package/src/compaction/settle.ts +150 -0
  25. package/src/{deps.test.ts → core/deps.test.ts} +1 -1
  26. package/src/{domain.test.ts → core/domain.test.ts} +42 -9
  27. package/src/{domain.ts → core/domain.ts} +73 -8
  28. package/src/{persistence.test.ts → core/persistence.test.ts} +7 -7
  29. package/src/{store.test.ts → core/store.test.ts} +116 -50
  30. package/src/{store.ts → core/store.ts} +92 -31
  31. package/src/index.test.ts +728 -84
  32. package/src/index.ts +237 -49
  33. package/src/{tool-metadata.test.ts → presentation/tool-metadata.test.ts} +264 -49
  34. package/src/presentation/tool-metadata.ts +675 -0
  35. package/src/{ui.test.ts → presentation/ui.test.ts} +128 -9
  36. package/src/{ui.ts → presentation/ui.ts} +123 -30
  37. package/src/tool-metadata.ts +0 -452
  38. /package/src/{deps.ts → core/deps.ts} +0 -0
  39. /package/src/{persistence.ts → core/persistence.ts} +0 -0
package/README.md CHANGED
@@ -6,11 +6,13 @@ pi-tracker is an extension for Pi. It manages todolists in your session.
6
6
 
7
7
  - Create and delete todolists.
8
8
  - Add, update, and remove items in a todolist.
9
+ - Give an item a short title, a longer description, and optional declarations.
9
10
  - Mark an item as complete or incomplete.
10
- - Change the task text of an item.
11
11
  - Declare dependencies between items, so work happens in order.
12
+ - Declare the references and products an item needs, so the next step survives compaction.
12
13
  - Persist todolists with the session.
13
14
  - Show the active todolist in a widget above the editor.
15
+ - Start Pi's compaction when a completed item's detail is no longer needed.
14
16
 
15
17
  ## How it works
16
18
 
@@ -26,38 +28,40 @@ The snapshot does not enter the LLM context.
26
28
  Ask Pi to manage your todolists. Pi calls the `tracker` tool. The tool
27
29
  supports these actions:
28
30
 
29
- | Action | Purpose | Parameters |
30
- | ------------- | ----------------------------------------- | ----------------------------------------------------------- |
31
- | `list` | Show all lists and items | — |
32
- | `create_list` | Create a list (becomes active by default) | `name`, `initial_items?`, `activate?` |
33
- | `delete_list` | Delete a list | `list_id` |
34
- | `set_active` | Set or clear the active list | `list_id` (optional) |
35
- | `add_item` | Add one or more items | `list_id`, `text` (string, item object, or array) |
36
- | `update_item` | Update one or more items | `item_id` + `text?`/`done?`/`deps?`, or `list_id` + `items` |
37
- | `remove_item` | Remove an item | `item_id` |
31
+ | Action | Purpose | Parameters |
32
+ | -------------- | ----------------------------------------- | ------------------------------------------ |
33
+ | `list` | Show all lists and items | None |
34
+ | `create_list` | Create a list (becomes active by default) | `name`, `initial_items?`, `activate?` |
35
+ | `delete_list` | Delete a list | `list_id` |
36
+ | `set_active` | Set or clear the active list | `list_id` (optional) |
37
+ | `add_items` | Add one or more items | `list_id`, `items` (array of item objects) |
38
+ | `update_items` | Update one or more items | `item_id` + fields, or `list_id` + `items` |
39
+ | `remove_item` | Remove an item | `item_id` |
38
40
 
39
41
  `create_list` accepts `initial_items` to create the list with its first
40
- items in one call, so the list and its items are created atomically. Each
41
- item is either a text string or an object `{text, deps?}`. `add_item`
42
- accepts the same shapes, plus an array of them, to add several items in one
43
- call.
42
+ items in one call, so the list and its items are created atomically. Every
43
+ item is an object `{title, description?, refs?, produces?, deps?}`, and
44
+ `add_items` takes the same objects in its `items` array, so an item is
45
+ always declared the same way. A title is one short action line, at most 200
46
+ characters; put the longer detail in `description`.
44
47
 
45
48
  Item ids are `listName:id`, as the `list` action shows them (e.g. `Work:2`).
46
49
  An id is permanent: it is stored on the item, it is unique within its list,
47
50
  and it is never reused. Removing an item leaves a gap in the numbering
48
51
  instead of shifting the items after it, so a reference you already hold stays
49
- valid. `update_item` accepts the scalar form (`item_id` with optional
50
- `text`/`done`/`deps`) or a per-list batched form: `list_id` plus an `items`
51
- array (`[{item_id, text?, done?, deps?}, ...]`), mirroring `add_item`'s
52
- `list_id + text[]` shape, so one batch stays within a single list. Creating a
53
- list makes it the active list (the widget switches to it); pass
54
- `activate: false` to keep the current active list.
52
+ valid. `update_items` accepts the scalar form (`item_id` with optional
53
+ `title`/`description`/`refs`/`produces`/`done`/`deps`) or a per-list batched
54
+ form: `list_id` plus an `items`
55
+ array (`[{item_id, title?, description?, refs?, produces?, done?, deps?}, ...]`),
56
+ mirroring `add_items`' `list_id + items` shape, so one batch stays within a
57
+ single list. Creating a list makes it the active list (the widget switches to
58
+ it); pass `activate: false` to keep the current active list.
55
59
 
56
60
  The tool validates every call and returns an error that names exactly what to
57
61
  fix: each action accepts only its own parameters, required fields are
58
- enforced, and the two `update_item` forms never mix. Read the error and retry
59
- with corrected parameters — not-found errors also list the available ids.
60
- `update_item` also appends a reminder when one call marks two or more items
62
+ enforced, and the two `update_items` forms never mix. Read the error and retry
63
+ with corrected parameters. Not-found errors also list the available ids.
64
+ `update_items` also appends a reminder when one call marks two or more items
61
65
  done and leaves no open items behind (the terminal batch): the working
62
66
  rhythm is to mark each item done in the same turn it completes, never batch
63
67
  the marking at the end.
@@ -69,10 +73,29 @@ Example prompt:
69
73
  Call `set_active` without `list_id` to deselect. The widget hides when no
70
74
  list is active.
71
75
 
76
+ ### Titles, descriptions, and declarations
77
+
78
+ Every item has a required `title`: one short action line, at most 200
79
+ characters. An item may also carry a `description` with the longer detail. The
80
+ widget shows the title, with the description dimmed on the line below; the
81
+ `/tracker` items pane shows the full description.
82
+
83
+ An item may declare two optional lists:
84
+
85
+ - `refs`: what the item must read after the completed work. Each entry is
86
+ `{kind: "path", path, symbol?, span?}` or `{kind: "decision", topic}`.
87
+ - `produces`: every document the item will write. Each entry is `{path}`.
88
+
89
+ Declarations tell the tracker what the next step needs. At the settle boundary
90
+ the tracker resolves a declared path against disk. If the detail is readable
91
+ there, the rule table can compact the completed work and keep the next step
92
+ moving without a classifier call. After a session restore there is no tool
93
+ footprint, so references resolve as unresolved and only products check disk.
94
+
72
95
  ### Dependencies and readiness
73
96
 
74
97
  An item can wait for other items. Pass `deps` on the item object when you
75
- create it, or through `update_item`, as a list of `listName:id` references to
98
+ create it, or through `update_items`, as a list of `listName:id` references to
76
99
  items in the same list. `deps` replaces the whole dependency set, so pass `[]`
77
100
  to clear it. The result names the set before and after whenever the two
78
101
  differ, so a dependency the call dropped does not disappear silently.
@@ -104,7 +127,7 @@ keeps the output it had before dependencies existed. A dependency reference
104
127
  that does not resolve counts as a blocker, so a hand-edited snapshot cannot
105
128
  silently unblock work.
106
129
 
107
- An `update_item` batch applies its patches in order, so it behaves like the
130
+ An `update_items` batch applies its patches in order, so it behaves like the
108
131
  same calls in sequence: one call can complete a chain, and a completion that
109
132
  comes before its blocker in the array is refused.
110
133
 
@@ -117,9 +140,9 @@ action, the widget, and the `/tracker` items pane all use that order.
117
140
 
118
141
  The intended rhythm: break multi-step work into items up front (one item per
119
142
  deliverable), work through them one at a time, and mark each done as it
120
- completes. The list — shown in the widget — always shows current progress; the
121
- agent should read it with `list` before starting and after finishing, and
122
- update item text with `update_item` when scope changes.
143
+ completes. The list in the widget always shows current progress. The agent
144
+ reads it with `list` before starting and after finishing, and updates an item's
145
+ title or description with `update_items` when scope changes.
123
146
 
124
147
  Failed calls are recoverable: the tool's errors say what to fix, and
125
148
  not-found errors name the available ids. The agent corrects the call and
@@ -143,7 +166,7 @@ pane for editing.
143
166
  | `d` | Delete a list |
144
167
  | `a` | Add an item |
145
168
  | `x` | Toggle an item complete or incomplete |
146
- | `e` | Edit the item text |
169
+ | `e` | Edit the item title |
147
170
  | `r` | Remove an item |
148
171
  | `esc` | Close the view |
149
172
 
@@ -177,6 +200,58 @@ whole report of an item's state, so a done item whose dependency was reopened
177
200
  keeps the `✓` there; the `(waiting on ...)` annotation appears in the `list`
178
201
  output and the `/tracker` items pane, which have room for it.
179
202
 
203
+ ### Smart compaction
204
+
205
+ When you complete an item in the active list, pi-tracker decides whether the
206
+ **ready items** need the completed work. A measured rule row runs first. When
207
+ an accepted row fires, it decides the whole ready frontier on its own. Every
208
+ other row reports its name and hands the frontier to the classifier, which
209
+ judges up to `maxCandidates` entries, dependents first. Each candidate gets one
210
+ two-label choice question: `needs-context` or `stands-alone`. The answer carries
211
+ a probability and a `confidence`. When no ready item needs the detail,
212
+ pi-tracker starts Pi's compaction at the settle boundary and then resumes the
213
+ session with a pointer to the next ready item.
214
+
215
+ The feature reads five keys from `tui.json`, under `smartCompaction`:
216
+
217
+ | Key | Type | Default | Meaning |
218
+ | ---------------------------------- | ---------------- | ------- | -------------------------------------------------------------------------------------------------------------------- |
219
+ | `enabled` | boolean | `true` | Turn smart compaction on or off. |
220
+ | `classifier` | string or null | `null` | A `provider/modelId` classifier. `null` uses the preference order: Clef Flash, then TypeSafe Jev, then OpenCode Jev. |
221
+ | `needsContextProbabilityThreshold` | number in (0, 1) | `0.5` | The `needs-context` probability at or above which the context is kept. |
222
+ | `minAnswerConfidence` | number in (0, 1) | `0.5` | The answer's self-reported confidence below which the context is kept. |
223
+ | `maxCandidates` | integer 1..20 | `8` | How many ready items one classification judges. |
224
+
225
+ `needsContextProbabilityThreshold` is the probability knob: raise it to compact
226
+ more often, lower it to keep context more often. It cuts on the probability the
227
+ classifier assigns to `needs-context`, not on its confidence. `minAnswerConfidence`
228
+ is a separate guard on the answer's self-reported confidence: when the model is
229
+ less confident than the floor, pi-tracker keeps the context. This guard only
230
+ adds keeping, so it can never cause a premature compaction. Both keys still
231
+ accept their pre-rename names (`keepContextThreshold`, `keepContextMinConfidence`)
232
+ as aliases; the current key wins when both are present. `maxCandidates` bounds the
233
+ classifier input; when more items are ready than the cap, the first
234
+ `maxCandidates` are judged, dependents first.
235
+
236
+ A value outside the range in the table falls back to the default. The feature
237
+ fails open. A disabled feature, no credential-available classifier, a classifier
238
+ error or timeout, an aborted run, or a list with no ready item keeps the full
239
+ context. The classifier input is the item list only. The transcript never leaves
240
+ the session. An unaccepted rule row abstains, so it never compacts on its own.
241
+
242
+ The rule table lives in `src/compaction/rules.ts`. Only rows in
243
+ `ACCEPTED_RULES` compact on their own. A row enters that set only when the eval
244
+ gate accepts it on labeled decisions: at least 10 labeled firings, at least 95%
245
+ agreement, above the pass base rate, in at least two passes. Every decision on
246
+ an item with declarations records the fired row and the resolved states as a
247
+ `tracker/reliance-decision` session entry, which the eval reads back.
248
+ `bun run eval:rules` prints the tables and the gate.
249
+
250
+ The `/tui` command edits all five on a **Compaction** tab: `Smart compaction`
251
+ (toggle), `Compaction classifier` (picker), `Needs-context probability`, `Answer
252
+ confidence floor`, and `Max candidates` (`+` and `-` adjust the numeric rows).
253
+ The Compaction tab appears only while the tracker extension is loaded.
254
+
180
255
  ## Persistence
181
256
 
182
257
  The state lives in the session file. Pi writes a snapshot after every change.
@@ -185,7 +260,9 @@ and written in order, and each result reports the state its own call produced
185
260
  instead of a value another surface cached.
186
261
 
187
262
  A snapshot saved before item ids existed loads with each item id equal to its
188
- position, so references in that format still resolve.
263
+ position, so references in that format still resolve. A snapshot written before
264
+ the title/description split loads with the first line as the title and the rest
265
+ as the description.
189
266
 
190
267
  ## Installation
191
268
 
@@ -213,27 +290,40 @@ Registration lives in `package.json` under the `pi` field:
213
290
 
214
291
  ```json
215
292
  "pi": {
216
- "extensions": ["./src/index.ts"]
293
+ "extensions": ["./index.ts"]
217
294
  }
218
295
  ```
219
296
 
220
297
  ## Development
221
298
 
222
- | Command | Purpose |
223
- | ------------------- | -------------------------------------------- |
224
- | `bun test` | Run the test suite (vitest + @effect/vitest) |
225
- | `bun test:watch` | Run the test suite in watch mode |
226
- | `bunx tsc --noEmit` | Type check |
227
- | `bun lint` | Lint with oxlint |
299
+ | Command | Purpose |
300
+ | ---------------------- | -------------------------------------------- |
301
+ | `bun run test` | Run the test suite (vitest + @effect/vitest) |
302
+ | `bun run test:watch` | Run the test suite in watch mode |
303
+ | `bun run typecheck` | Type check with `tsc --noEmit` |
304
+ | `bun run lint` | Lint with oxlint |
305
+ | `bun run eval:harvest` | Harvest the eval corpus from local sessions |
306
+ | `bun run eval:rules` | Print the rule tables and the promotion gate |
307
+ | `bun run eval:promote` | Align `ACCEPTED_RULES` with the measured set |
228
308
 
229
309
  ## Project structure
230
310
 
231
- | File | Purpose |
232
- | -------------------- | ---------------------------------------------------------------- |
233
- | `src/domain.ts` | Schema domain model (`TodoItem`, `TodoList`, `TrackerState`) |
234
- | `src/deps.ts` | Dependency references, cycle detection, readiness, derived order |
235
- | `src/store.ts` | `TrackerStore` service with `Effect.Ref` state |
236
- | `src/persistence.ts` | `TrackerPersistence` service (save and restore snapshots) |
237
- | `src/ui.ts` | Widget pane and interactive `/tracker` component |
238
- | `src/index.ts` | Pi bridge: tool, command, session hooks, widget refresh |
239
- | `src/*.test.ts` | Test suites |
311
+ | File | Purpose |
312
+ | ----------------------------------- | ---------------------------------------------------------------- |
313
+ | `src/core/domain.ts` | Schema domain model (`TodoItem`, `TodoList`, `TrackerState`) |
314
+ | `src/core/deps.ts` | Dependency references, cycle detection, readiness, derived order |
315
+ | `src/core/store.ts` | `TrackerStore` service with `Effect.Ref` state |
316
+ | `src/core/persistence.ts` | `TrackerPersistence` service (save and restore snapshots) |
317
+ | `src/compaction/observations.ts` | Resolves declared references and products against disk |
318
+ | `src/compaction/rules.ts` | The rule table, `ACCEPTED_RULES`, and the gate constants |
319
+ | `src/compaction/footprint.ts` | Records what each batch wrote, read, and ran |
320
+ | `src/compaction/settle.ts` | The settle decision: rules first, then the classifier |
321
+ | `src/compaction/digest.ts` | The bounded classifier input |
322
+ | `src/compaction/decision-record.ts` | The `tracker/reliance-decision` session entry |
323
+ | `src/compaction/classifier.ts` | The classifier gateway |
324
+ | `src/compaction/pointer.ts` | The resume pointer and its custom entry |
325
+ | `src/compaction/settings.ts` | The `tui.json` reader |
326
+ | `src/presentation/ui.ts` | Widget pane and interactive `/tracker` component |
327
+ | `src/presentation/tool-metadata.ts` | Tool parameters, result details, and display labels |
328
+ | `src/index.ts` | Pi bridge: tool, command, session hooks, widget refresh |
329
+ | `src/**/*.test.ts` | Test suites, colocated with each module |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ftrdotdev/pi-tracker",
3
- "version": "0.5.2",
3
+ "version": "0.7.0",
4
4
  "description": "Session-persistent todolist extension for Pi",
5
5
  "keywords": [
6
6
  "effect",
@@ -37,6 +37,11 @@
37
37
  "scripts": {
38
38
  "test": "vitest run",
39
39
  "test:watch": "vitest",
40
+ "eval:harvest": "bun evals/harvest.ts",
41
+ "eval:review": "bun evals/review.ts",
42
+ "eval:label": "bun evals/label.ts",
43
+ "eval:rules": "bun evals/rules.ts",
44
+ "eval:promote": "bun evals/promote.ts",
40
45
  "lint": "oxlint && oxlint --type-aware -A all -D typescript/unbound-method",
41
46
  "lint:fix": "oxlint --fix",
42
47
  "fmt": "oxfmt",
@@ -45,10 +50,11 @@
45
50
  "dependencies": {
46
51
  "@effect/platform-node": "4.0.0",
47
52
  "@effect/platform-node-shared": "4.0.0",
48
- "@ftrdotdev/pi-tui": "^0.5.2",
53
+ "@ftrdotdev/pi-tui": "^0.7.0",
49
54
  "effect": "4.0.0"
50
55
  },
51
56
  "devDependencies": {
57
+ "@earendil-works/pi-tui": "1.1.0",
52
58
  "@effect/tsgo": "0.47.2",
53
59
  "@effect/vitest": "4.0.0",
54
60
  "@types/bun": "latest",
@@ -0,0 +1,191 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { selectCandidates, type CompactionCandidate } from "./candidate.ts";
3
+ import type { PendingCompletion } from "./completion.ts";
4
+ import { TodoItem, TodoList } from "../core/domain.ts";
5
+
6
+ interface ItemSpec {
7
+ readonly id: number;
8
+ readonly done: boolean;
9
+ readonly title?: string;
10
+ readonly deps?: readonly string[];
11
+ }
12
+
13
+ const completion = (
14
+ items: readonly ItemSpec[],
15
+ completedItemIds: readonly number[],
16
+ ): PendingCompletion => {
17
+ const list = new TodoList({
18
+ id: 1,
19
+ name: "Work",
20
+ items: items.map(
21
+ (item) =>
22
+ new TodoItem({
23
+ id: item.id,
24
+ title: item.title ?? `item ${item.id}`,
25
+ done: item.done,
26
+ deps: [...(item.deps ?? [])],
27
+ }),
28
+ ),
29
+ nextItemId: items.reduce((max, item) => Math.max(max, item.id), 0) + 1,
30
+ });
31
+ return { list, completedItemIds };
32
+ };
33
+
34
+ /** The primary candidate: the first entry, which the pointer names. */
35
+ const first = (pending: PendingCompletion, limit = 8): CompactionCandidate => {
36
+ const candidates = selectCandidates(pending, limit);
37
+ assert.isAtLeast(candidates.length, 1);
38
+ return candidates[0]!;
39
+ };
40
+
41
+ it("selectCandidates prefers the first ready dependent successor", () => {
42
+ const candidate = first(
43
+ completion(
44
+ [
45
+ { id: 1, done: true },
46
+ { id: 2, done: false, deps: ["Work:1"] },
47
+ { id: 3, done: false },
48
+ ],
49
+ [1],
50
+ ),
51
+ );
52
+ assert.strictEqual(candidate.id, 2);
53
+ assert.strictEqual(candidate.class, "dependent-successor");
54
+ });
55
+
56
+ it("selectCandidates skips a dependent successor that is still blocked", () => {
57
+ const candidate = first(
58
+ completion(
59
+ [
60
+ { id: 1, done: true },
61
+ { id: 2, done: false, deps: ["Work:1", "Work:4"] },
62
+ { id: 3, done: false },
63
+ { id: 4, done: false },
64
+ ],
65
+ [1],
66
+ ),
67
+ );
68
+ assert.strictEqual(candidate.id, 3);
69
+ assert.strictEqual(candidate.class, "ready-queue");
70
+ });
71
+
72
+ it("selectCandidates considers every item in the completed batch", () => {
73
+ const candidate = first(
74
+ completion(
75
+ [
76
+ { id: 1, done: true },
77
+ { id: 2, done: false },
78
+ { id: 3, done: true },
79
+ { id: 4, done: false, deps: ["Work:3"] },
80
+ ],
81
+ [1, 3],
82
+ ),
83
+ );
84
+ assert.strictEqual(candidate.id, 4);
85
+ assert.strictEqual(candidate.class, "dependent-successor");
86
+ });
87
+
88
+ it("selectCandidates falls back to the first remaining ready item in list order", () => {
89
+ const candidate = first(
90
+ completion(
91
+ [
92
+ { id: 1, done: true },
93
+ { id: 3, done: false },
94
+ { id: 4, done: false },
95
+ ],
96
+ [1],
97
+ ),
98
+ );
99
+ assert.strictEqual(candidate.id, 3);
100
+ assert.strictEqual(candidate.class, "ready-queue");
101
+ });
102
+
103
+ it("selectCandidates excludes every completed item from the fallback", () => {
104
+ const candidate = first(
105
+ completion(
106
+ [
107
+ { id: 1, done: false },
108
+ { id: 2, done: false },
109
+ { id: 3, done: false },
110
+ ],
111
+ [1, 2],
112
+ ),
113
+ );
114
+ assert.strictEqual(candidate.id, 3);
115
+ assert.notStrictEqual(candidate.id, 1);
116
+ assert.notStrictEqual(candidate.id, 2);
117
+ });
118
+
119
+ it("selectCandidates returns an empty array when nothing is ready", () => {
120
+ const candidates = selectCandidates(
121
+ completion(
122
+ [
123
+ { id: 1, done: true },
124
+ { id: 2, done: false, deps: ["Work:9"] },
125
+ ],
126
+ [1],
127
+ ),
128
+ 8,
129
+ );
130
+ assert.deepStrictEqual(candidates, []);
131
+ });
132
+
133
+ it("selectCandidates carries the completed batch as prior work", () => {
134
+ const candidate = first(
135
+ completion(
136
+ [
137
+ { id: 1, done: true, title: "first" },
138
+ { id: 3, done: true, title: "third" },
139
+ { id: 4, done: false, title: "fourth", deps: ["Work:3"] },
140
+ ],
141
+ [1, 3],
142
+ ),
143
+ );
144
+ assert.deepStrictEqual(candidate.completed, [
145
+ { ref: "Work:1", text: "first" },
146
+ { ref: "Work:3", text: "third" },
147
+ ]);
148
+ assert.strictEqual(candidate.id, 4);
149
+ });
150
+
151
+ it("selectCandidates orders dependent successors before the ready queue", () => {
152
+ const candidates = selectCandidates(
153
+ completion(
154
+ [
155
+ { id: 1, done: true },
156
+ { id: 2, done: false, deps: ["Work:1"] },
157
+ { id: 3, done: false },
158
+ { id: 4, done: false, deps: ["Work:1"] },
159
+ ],
160
+ [1],
161
+ ),
162
+ 8,
163
+ );
164
+ assert.deepStrictEqual(
165
+ candidates.map((candidate) => candidate.id),
166
+ [2, 4, 3],
167
+ );
168
+ assert.deepStrictEqual(
169
+ candidates.map((candidate) => candidate.class),
170
+ ["dependent-successor", "dependent-successor", "ready-queue"],
171
+ );
172
+ });
173
+
174
+ it("selectCandidates caps the judged set at the limit, dependents first", () => {
175
+ const candidates = selectCandidates(
176
+ completion(
177
+ [
178
+ { id: 1, done: true },
179
+ { id: 2, done: false },
180
+ { id: 3, done: false, deps: ["Work:1"] },
181
+ { id: 4, done: false },
182
+ ],
183
+ [1],
184
+ ),
185
+ 2,
186
+ );
187
+ assert.deepStrictEqual(
188
+ candidates.map((candidate) => candidate.id),
189
+ [3, 2],
190
+ );
191
+ });
@@ -0,0 +1,105 @@
1
+ import { dependentsOf, formatItemRef, readiness } from "../core/deps.ts";
2
+ import type { DeclaredProduct, DeclaredReference } from "../core/domain.ts";
3
+ import type { PendingCompletion } from "./completion.ts";
4
+
5
+ /** Why the candidate was chosen; the classifier question is keyed by this. */
6
+ export type CandidateClass = "dependent-successor" | "ready-queue";
7
+
8
+ /** One item from the completed batch, as referenced prior work. */
9
+ export interface CompletedItem {
10
+ readonly ref: string;
11
+ readonly text: string;
12
+ /** The item's description, when it carries one. Part of the batch text. */
13
+ readonly description?: string;
14
+ }
15
+
16
+ /** The single next unfinished item, with the batch as referenced prior work. */
17
+ export interface CompactionCandidate {
18
+ readonly class: CandidateClass;
19
+ readonly listName: string;
20
+ readonly id: number;
21
+ /** The item's title. */
22
+ readonly text: string;
23
+ /** The item's description, when it carries one. */
24
+ readonly description?: string;
25
+ /** Every item completed since the last decision. Never the subject. */
26
+ readonly completed: readonly CompletedItem[];
27
+ /** The item's declared references, when it carries any. */
28
+ readonly refs?: readonly DeclaredReference[];
29
+ /** The item's declared products, when it carries any. */
30
+ readonly produces?: readonly DeclaredProduct[];
31
+ }
32
+
33
+ /**
34
+ * The single next unfinished item: the first open ready item in list order that
35
+ * depends on any item in the completed batch, else the first remaining ready
36
+ * item in list order, excluding every completed item. Reuses the readiness and
37
+ * dependent-set derivations (`deps.ts`); adds no graph behavior.
38
+ *
39
+ * The candidates to judge, in decision order: the ready dependent successors
40
+ * first (in list order), then the remaining ready items (in list order),
41
+ * excluding every completed item, capped at `limit`. The first entry is the
42
+ * pointer target, so it matches the old single candidate; the array is empty
43
+ * when nothing is ready.
44
+ */
45
+ export const selectCandidates = (
46
+ completion: PendingCompletion,
47
+ limit: number,
48
+ ): readonly CompactionCandidate[] => {
49
+ const { list } = completion;
50
+ const completedIds = new Set(completion.completedItemIds);
51
+ const completed: CompletedItem[] = completion.completedItemIds.flatMap((id) => {
52
+ const item = list.items.find((candidate) => candidate.id === id);
53
+ if (item === undefined) return [];
54
+ return [
55
+ {
56
+ ref: formatItemRef(list.name, id),
57
+ text: item.title,
58
+ ...(item.description === undefined || item.description.length === 0
59
+ ? {}
60
+ : { description: item.description }),
61
+ },
62
+ ];
63
+ });
64
+
65
+ // The completed items were selected because the candidate depends on one of
66
+ // them; a blocked dependent is skipped and the ready queue takes over.
67
+ const completedIndexes = list.items
68
+ .map((item, index) => (completedIds.has(item.id) ? index : -1))
69
+ .filter((index) => index >= 0);
70
+ const dependentIndexes = new Set(
71
+ completedIndexes.flatMap((index) => [...dependentsOf(list, index)]),
72
+ );
73
+ const view = readiness(list);
74
+
75
+ const make = (index: number, cls: CandidateClass): CompactionCandidate => {
76
+ const item = list.items[index]!;
77
+ return {
78
+ class: cls,
79
+ listName: list.name,
80
+ id: item.id,
81
+ text: item.title,
82
+ ...(item.description === undefined || item.description.length === 0
83
+ ? {}
84
+ : { description: item.description }),
85
+ completed,
86
+ ...(item.refs.length === 0 ? {} : { refs: item.refs }),
87
+ ...(item.produces.length === 0 ? {} : { produces: item.produces }),
88
+ };
89
+ };
90
+
91
+ const ordered: CompactionCandidate[] = [];
92
+ const take = (index: number, cls: CandidateClass): void => {
93
+ if (ordered.length < limit) ordered.push(make(index, cls));
94
+ };
95
+ for (let index = 0; index < list.items.length && ordered.length < limit; index += 1) {
96
+ if (view[index]!.ready && dependentIndexes.has(index)) take(index, "dependent-successor");
97
+ }
98
+ for (let index = 0; index < list.items.length && ordered.length < limit; index += 1) {
99
+ const item = list.items[index]!;
100
+ if (view[index]!.ready && !completedIds.has(item.id) && !dependentIndexes.has(index)) {
101
+ take(index, "ready-queue");
102
+ }
103
+ }
104
+ return ordered;
105
+ };