@ftrdotdev/pi-tracker 0.6.0 → 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.
@@ -1,32 +1,45 @@
1
1
  import { Context, Effect, Layer, Option } from "effect";
2
+ import { formatItemRef } from "../core/deps.ts";
2
3
  import { ClassifierGateway, type ClassifierRegistry } from "./classifier.ts";
3
4
  import { selectCandidates } from "./candidate.ts";
4
5
  import { CompletionObserver } from "./completion.ts";
5
6
  import { buildDigests, compactQuestions } from "./digest.ts";
7
+ import { buildDecisionRecord, type DecisionRecord } from "./decision-record.ts";
8
+ import { FootprintRecorder } from "./footprint.ts";
9
+ import { productionFacts, type FileProbe } from "./observations.ts";
6
10
  import { resumePointer } from "./pointer.ts";
11
+ import { acceptedRoute, buildRuleInput, resolveCandidates, route } from "./rules.ts";
7
12
  import { SmartCompactionSettingsService } from "./settings.ts";
8
13
 
9
14
  /** How the run that just reached the settle boundary ended. */
10
15
  export type SettleOutcome = "completed" | "aborted" | "error";
11
16
 
12
17
  const SETTLE_DECISION = {
13
- keep: { kind: "keep" },
14
- compact: (pointer: string) => ({
18
+ keep: { kind: "keep" } as { readonly kind: "keep" },
19
+ compact: (pointer: string): { readonly kind: "compact"; readonly pointer: string } => ({
15
20
  kind: "compact",
16
21
  pointer,
17
22
  }),
18
- } as const;
23
+ };
19
24
 
20
25
  /** What the bridge should do with the run's context. */
21
26
  export type SettleDecision =
22
- | (typeof SETTLE_DECISION)["keep"]
23
- | ReturnType<(typeof SETTLE_DECISION)["compact"]>;
27
+ | { readonly kind: "keep"; readonly record?: DecisionRecord }
28
+ | {
29
+ readonly kind: "compact";
30
+ readonly pointer: string;
31
+ readonly record?: DecisionRecord;
32
+ };
24
33
 
25
34
  /**
26
35
  * The settle decision. It consumes the completion record first, so every
27
36
  * terminal path clears it and one completion set yields at most one decision,
28
37
  * then requires a completed run before it classifies anything. It judges the
29
38
  * whole ready frontier and never fails: every failure path keeps the context.
39
+ *
40
+ * The reliance rule table runs before the classifier. A row in `ACCEPTED_RULES`
41
+ * decides on its own. Every other row reports its name and hands the frontier
42
+ * to the classifier, so an unmeasured row can never compact alone.
30
43
  */
31
44
  export class SettleDecider extends Context.Service<
32
45
  SettleDecider,
@@ -38,57 +51,100 @@ export class SettleDecider extends Context.Service<
38
51
  }) => Effect.Effect<SettleDecision>;
39
52
  }
40
53
  >()("tracker/SettleDecider") {
41
- static readonly layer: Layer.Layer<
54
+ static readonly layer = (
55
+ probe: FileProbe,
56
+ ): Layer.Layer<
42
57
  SettleDecider,
43
58
  never,
44
- CompletionObserver | SmartCompactionSettingsService | ClassifierGateway
45
- > = Layer.effect(
46
- SettleDecider,
47
- Effect.gen(function* () {
48
- const pending = yield* CompletionObserver;
49
- const settings = yield* SmartCompactionSettingsService;
50
- const gateway = yield* ClassifierGateway;
59
+ CompletionObserver | SmartCompactionSettingsService | ClassifierGateway | FootprintRecorder
60
+ > =>
61
+ Layer.effect(
62
+ SettleDecider,
63
+ Effect.gen(function* () {
64
+ const pending = yield* CompletionObserver;
65
+ const settings = yield* SmartCompactionSettingsService;
66
+ const gateway = yield* ClassifierGateway;
67
+ const recorder = yield* FootprintRecorder;
68
+
69
+ const decide = Effect.fn("SettleDecider.decide")(
70
+ function* (input: {
71
+ readonly registry: ClassifierRegistry;
72
+ readonly outcome: SettleOutcome;
73
+ readonly signal?: AbortSignal | undefined;
74
+ }) {
75
+ // Consume first: nothing below may run twice for one completion, and
76
+ // every path from here clears both records. The footprint is
77
+ // in-memory, so it goes with the completion that consumed it.
78
+ const recorded = yield* pending.consume;
79
+ const footprint = yield* recorder.consume;
80
+ if (Option.isNone(recorded)) return SETTLE_DECISION.keep;
81
+ // An aborted or errored run compacts nothing and produces no pointer.
82
+ if (input.outcome !== "completed") return SETTLE_DECISION.keep;
83
+ const values = yield* settings.load;
84
+ // A disabled feature compacts nothing, whatever the rules say.
85
+ if (!values.enabled) return SETTLE_DECISION.keep;
86
+ // The whole ready frontier is judged, capped by the setting. The
87
+ // first entry is the pointer target; the array is empty when nothing
88
+ // is ready.
89
+ const candidates = selectCandidates(recorded.value, values.maxCandidates);
90
+ if (candidates.length === 0) return SETTLE_DECISION.keep;
91
+
92
+ // The rule table reads the pointer candidate's declarations and the
93
+ // batch's production facts. An accepted row decides the whole
94
+ // frontier; every other row reports and asks the classifier.
95
+ const head = candidates[0]!;
96
+ const facts = resolveCandidates(candidates, footprint, probe);
97
+ const batchTexts = head.completed.flatMap((item) =>
98
+ item.description === undefined ? [item.text] : [item.text, item.description],
99
+ );
100
+ const ruleInput = buildRuleInput(
101
+ facts[0]!,
102
+ productionFacts(batchTexts, footprint, head.text),
103
+ );
104
+ const raw = route(ruleInput);
105
+ const routed = acceptedRoute(ruleInput);
106
+ // The record names the raw row, so a declared row's live coverage is
107
+ // measurable without a second model call. It exists only when the
108
+ // candidate declared something.
109
+ const record = buildDecisionRecord({
110
+ rule: raw.rule,
111
+ verdict: raw.verdict,
112
+ candidateRef: formatItemRef(head.listName, head.id),
113
+ references: facts[0]!.references,
114
+ products: facts[0]!.products,
115
+ });
116
+ const withRecord = (decision: SettleDecision): SettleDecision =>
117
+ record === undefined ? decision : { ...decision, record };
118
+ if (routed.verdict === "keep") return withRecord(SETTLE_DECISION.keep);
119
+ if (routed.verdict === "compact") {
120
+ return withRecord(SETTLE_DECISION.compact(resumePointer(head)));
121
+ }
122
+ yield* Effect.logInfo(
123
+ `tracker: smart-compaction rule ${routed.rule} is observe-only for ${formatItemRef(head.listName, head.id)}; asking the classifier`,
124
+ );
51
125
 
52
- const decide = Effect.fn("SettleDecider.decide")(
53
- function* (input: {
54
- readonly registry: ClassifierRegistry;
55
- readonly outcome: SettleOutcome;
56
- readonly signal?: AbortSignal | undefined;
57
- }) {
58
- // Consume first: nothing below may run twice for one completion, and
59
- // every path from here clears the record.
60
- const recorded = yield* pending.consume;
61
- if (Option.isNone(recorded)) return SETTLE_DECISION.keep;
62
- // An aborted or errored run compacts nothing and produces no pointer.
63
- if (input.outcome !== "completed") return SETTLE_DECISION.keep;
64
- const values = yield* settings.load;
65
- // The whole ready frontier is judged, capped by the setting. The
66
- // first entry is the pointer target; the array is empty when nothing
67
- // is ready.
68
- const candidates = selectCandidates(recorded.value, values.maxCandidates);
69
- if (candidates.length === 0) return SETTLE_DECISION.keep;
70
- const verdict = yield* gateway.verdict({
71
- registry: input.registry,
72
- enabled: values.enabled,
73
- chosen: values.chosen,
74
- keepContextThreshold: values.keepContextThreshold,
75
- keepContextMinConfidence: values.keepContextMinConfidence,
76
- digest: buildDigests(candidates),
77
- questions: compactQuestions(candidates),
78
- signal: input.signal,
79
- });
80
- return verdict.kind === "compact"
81
- ? SETTLE_DECISION.compact(resumePointer(candidates[0]!))
82
- : SETTLE_DECISION.keep;
83
- },
84
- Effect.catchCause(() =>
85
- Effect.logWarning("tracker: smart-compaction decision failed, keeping context").pipe(
86
- Effect.as(SETTLE_DECISION.keep),
126
+ const verdict = yield* gateway.verdict({
127
+ registry: input.registry,
128
+ enabled: values.enabled,
129
+ chosen: values.chosen,
130
+ needsContextProbabilityThreshold: values.needsContextProbabilityThreshold,
131
+ minAnswerConfidence: values.minAnswerConfidence,
132
+ digest: buildDigests(candidates, facts),
133
+ questions: compactQuestions(candidates),
134
+ signal: input.signal,
135
+ });
136
+ return verdict.kind === "compact"
137
+ ? withRecord(SETTLE_DECISION.compact(resumePointer(head)))
138
+ : withRecord(SETTLE_DECISION.keep);
139
+ },
140
+ Effect.catchCause(() =>
141
+ Effect.logWarning("tracker: smart-compaction decision failed, keeping context").pipe(
142
+ Effect.as(SETTLE_DECISION.keep),
143
+ ),
87
144
  ),
88
- ),
89
- );
145
+ );
90
146
 
91
- return SettleDecider.of({ decide });
92
- }),
93
- );
147
+ return SettleDecider.of({ decide });
148
+ }),
149
+ );
94
150
  }
@@ -29,7 +29,7 @@ const listWith = (
29
29
  (itemDeps, index) =>
30
30
  new TodoItem({
31
31
  id: index + 1,
32
- text: `item ${index + 1}`,
32
+ title: `item ${index + 1}`,
33
33
  done: done.includes(index),
34
34
  deps: itemDeps,
35
35
  }),
@@ -4,6 +4,7 @@ import {
4
4
  decodeStateEffect,
5
5
  emptyState,
6
6
  encodeState,
7
+ migrateState,
7
8
  TodoItem,
8
9
  TodoList,
9
10
  TrackerState,
@@ -29,15 +30,15 @@ const sampleState = (): TrackerState =>
29
30
  name: "Work",
30
31
  nextItemId: 3,
31
32
  items: [
32
- new TodoItem({ id: 1, text: "write plan", done: true }),
33
- new TodoItem({ id: 2, text: "implement tracker", done: false }),
33
+ new TodoItem({ id: 1, title: "write plan", done: true }),
34
+ new TodoItem({ id: 2, title: "implement tracker", done: false }),
34
35
  ],
35
36
  }),
36
37
  new TodoList({
37
38
  id: 2,
38
39
  name: "Home",
39
40
  nextItemId: 2,
40
- items: [new TodoItem({ id: 1, text: "water plants", done: false })],
41
+ items: [new TodoItem({ id: 1, title: "water plants", done: false })],
41
42
  }),
42
43
  ],
43
44
  activeListId: 1,
@@ -73,8 +74,8 @@ it("item ids and deps round-trip", () => {
73
74
  name: "Work",
74
75
  nextItemId: 4,
75
76
  items: [
76
- new TodoItem({ id: 1, text: "a", done: true }),
77
- new TodoItem({ id: 3, text: "b", done: false, deps: ["Work:1"] }),
77
+ new TodoItem({ id: 1, title: "a", done: true }),
78
+ new TodoItem({ id: 3, title: "b", done: false, deps: ["Work:1"] }),
78
79
  ],
79
80
  }),
80
81
  ],
@@ -118,8 +119,8 @@ it("decoded values are real class instances", () => {
118
119
  it("constructors validate their input", () => {
119
120
  // Invalid types / missing fields throw at construction time. (The invalid
120
121
  // inputs are cast because the constructor signature is already typed.)
121
- assert.throws(() => new TodoItem({ text: 42, done: false } as never));
122
- assert.throws(() => new TodoItem({ text: "x" } as never));
122
+ assert.throws(() => new TodoItem({ title: 42, done: false } as never));
123
+ assert.throws(() => new TodoItem({ title: "x" } as never));
123
124
  assert.throws(() => new TrackerState({} as never));
124
125
  });
125
126
 
@@ -157,7 +158,7 @@ it("rejects a snapshot with the wrong field type", () => {
157
158
 
158
159
  it("rejects a snapshot with an invalid item field", () => {
159
160
  const bad = {
160
- lists: [{ id: 1, name: "Work", items: [{ text: "x", done: "yes" }] }],
161
+ lists: [{ id: 1, name: "Work", items: [{ title: "x", done: "yes" }] }],
161
162
  activeListId: null,
162
163
  nextListId: 2,
163
164
  };
@@ -176,7 +177,39 @@ it("drops a legacy string item id so old sessions stay loadable", () => {
176
177
  nextItemId: 9,
177
178
  };
178
179
  const decoded = decodeOrThrow(legacy);
179
- assert.deepStrictEqual(decoded.lists[0]?.items, [new TodoItem({ text: "x", done: false })]);
180
+ assert.deepStrictEqual(decoded.lists[0]?.items, [new TodoItem({ title: "x", done: false })]);
181
+ });
182
+
183
+ it("splits a legacy text item into a title and a description", () => {
184
+ const legacy = {
185
+ lists: [
186
+ {
187
+ id: 1,
188
+ name: "Work",
189
+ items: [{ id: 1, text: "Short title\nMore detail", done: false, deps: [] }],
190
+ },
191
+ ],
192
+ activeListId: null,
193
+ nextListId: 2,
194
+ };
195
+ const migrated = migrateState(decodeOrThrow(legacy));
196
+ const item = migrated.lists[0]!.items[0]!;
197
+ assert.strictEqual(item.title, "Short title");
198
+ assert.strictEqual(item.description, "More detail");
199
+ });
200
+
201
+ it("a single-line legacy text item becomes a title with an empty description", () => {
202
+ const legacy = {
203
+ lists: [
204
+ { id: 1, name: "Work", items: [{ id: 1, text: "Just a title", done: false, deps: [] }] },
205
+ ],
206
+ activeListId: null,
207
+ nextListId: 2,
208
+ };
209
+ const migrated = migrateState(decodeOrThrow(legacy));
210
+ const item = migrated.lists[0]!.items[0]!;
211
+ assert.strictEqual(item.title, "Just a title");
212
+ assert.strictEqual(item.description, "");
180
213
  });
181
214
 
182
215
  it("enforces Int list ids (fractional ids are rejected)", () => {
@@ -29,6 +29,47 @@ const itemDeps = Schema.Array(Schema.String).pipe(
29
29
  Schema.withConstructorDefault(Effect.succeed([])),
30
30
  );
31
31
 
32
+ /** The optional longer explanation of an item; defaults to empty. */
33
+ const itemDescription = Schema.String.pipe(
34
+ Schema.withDecodingDefaultType(Effect.succeed("")),
35
+ Schema.withConstructorDefault(Effect.succeed("")),
36
+ );
37
+
38
+ /**
39
+ * A declared reference: a path the item must read (optionally narrowed to a
40
+ * symbol or a line span), or a decision topic it depends on.
41
+ */
42
+ const declaredReference = Schema.Union([
43
+ Schema.Struct({
44
+ kind: Schema.Literal("path"),
45
+ path: Schema.String,
46
+ symbol: Schema.optional(Schema.String),
47
+ span: Schema.optional(Schema.String),
48
+ }),
49
+ Schema.Struct({
50
+ kind: Schema.Literal("decision"),
51
+ topic: Schema.String,
52
+ }),
53
+ ]);
54
+
55
+ /** A document the item will write. */
56
+ const declaredProduct = Schema.Struct({ path: Schema.String });
57
+
58
+ /** Declared references; defaults to empty, so an old item decodes without them. */
59
+ const itemRefs = Schema.Array(declaredReference).pipe(
60
+ Schema.withDecodingDefaultType(Effect.succeed([])),
61
+ Schema.withConstructorDefault(Effect.succeed([])),
62
+ );
63
+
64
+ /** Declared products; defaults to empty, so an old item decodes without them. */
65
+ const itemProduces = Schema.Array(declaredProduct).pipe(
66
+ Schema.withDecodingDefaultType(Effect.succeed([])),
67
+ Schema.withConstructorDefault(Effect.succeed([])),
68
+ );
69
+
70
+ export type DeclaredReference = Schema.Schema.Type<typeof declaredReference>;
71
+ export type DeclaredProduct = Schema.Schema.Type<typeof declaredProduct>;
72
+
32
73
  /**
33
74
  * Sentinel for a list that stored no item id counter, which means the snapshot
34
75
  * was written before item ids existed. `normalizeSnapshot` stamps it so
@@ -44,7 +85,10 @@ const itemCounter = Schema.Int.pipe(
44
85
 
45
86
  export class TodoItem extends Schema.Class<TodoItem>("tracker/TodoItem")({
46
87
  id: itemId,
47
- text: Schema.String,
88
+ title: Schema.String,
89
+ description: itemDescription,
90
+ refs: itemRefs,
91
+ produces: itemProduces,
48
92
  done: Schema.Boolean,
49
93
  deps: itemDeps,
50
94
  }) {}
@@ -81,7 +125,15 @@ export const emptyState = (): TrackerState =>
81
125
 
82
126
  /** A copy of `item` with a replaced id. */
83
127
  const withId = (item: TodoItem, id: number): TodoItem =>
84
- new TodoItem({ id, text: item.text, done: item.done, deps: item.deps });
128
+ new TodoItem({
129
+ id,
130
+ title: item.title,
131
+ description: item.description,
132
+ refs: item.refs,
133
+ produces: item.produces,
134
+ done: item.done,
135
+ deps: item.deps,
136
+ });
85
137
 
86
138
  /**
87
139
  * Reassign ids for one list and return it with a counter above every id.
@@ -127,16 +179,29 @@ export const migrateState = (state: TrackerState): TrackerState =>
127
179
 
128
180
  /**
129
181
  * 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.
182
+ * unassigned, and split a legacy `text` into a title and a description. An
183
+ * older format stored the id as a string and the item content as one `text`
184
+ * string; the schema now stores an integer id plus separate `title` and
185
+ * `description` fields, and rejecting the snapshot would lose the whole
186
+ * session.
132
187
  */
133
188
  const normalizeItem = (item: unknown): unknown => {
134
189
  if (typeof item !== "object" || item === null || Array.isArray(item)) return item;
135
190
  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;
191
+ const next: Record<string, unknown> = { ...record };
192
+ let changed = false;
193
+ if (typeof record.id === "string") {
194
+ delete next.id;
195
+ changed = true;
196
+ }
197
+ if (record.title === undefined && typeof record.text === "string") {
198
+ const newline = record.text.indexOf("\n");
199
+ next.title = newline === -1 ? record.text : record.text.slice(0, newline);
200
+ next.description = newline === -1 ? "" : record.text.slice(newline + 1);
201
+ delete next.text;
202
+ changed = true;
203
+ }
204
+ return changed ? next : item;
140
205
  };
141
206
 
142
207
  /**
@@ -27,15 +27,15 @@ layer(
27
27
  name: "Work",
28
28
  nextItemId: 3,
29
29
  items: [
30
- new TodoItem({ id: 1, text: "write plan", done: true }),
31
- new TodoItem({ id: 2, text: "implement tracker", done: false }),
30
+ new TodoItem({ id: 1, title: "write plan", done: true }),
31
+ new TodoItem({ id: 2, title: "implement tracker", done: false }),
32
32
  ],
33
33
  }),
34
34
  new TodoList({
35
35
  id: 2,
36
36
  name: "Home",
37
37
  nextItemId: 2,
38
- items: [new TodoItem({ id: 1, text: "water plants", done: false })],
38
+ items: [new TodoItem({ id: 1, title: "water plants", done: false })],
39
39
  }),
40
40
  ],
41
41
  activeListId: 1,
@@ -168,7 +168,7 @@ layer(
168
168
  id: 1,
169
169
  name: "Work",
170
170
  nextItemId: 2,
171
- items: [new TodoItem({ id: 1, text: "a", done: false })],
171
+ items: [new TodoItem({ id: 1, title: "a", done: false })],
172
172
  }),
173
173
  ],
174
174
  activeListId: 1,
@@ -176,7 +176,7 @@ layer(
176
176
  });
177
177
  assert.deepStrictEqual(encodeState(restored), encodeState(expected));
178
178
  assert.deepStrictEqual(restored.lists[0]?.items, [
179
- new TodoItem({ id: 1, text: "a", done: false }),
179
+ new TodoItem({ id: 1, title: "a", done: false }),
180
180
  ]);
181
181
  }),
182
182
  );
@@ -262,7 +262,7 @@ layer(
262
262
  const restored = yield* persistence.restore(legacy);
263
263
 
264
264
  assert.deepStrictEqual(
265
- restored.lists[0]?.items.map((i) => [i.id, i.text]),
265
+ restored.lists[0]?.items.map((i) => [i.id, i.title]),
266
266
  [[1, "a"]],
267
267
  );
268
268
  }),
@@ -281,7 +281,7 @@ layer(
281
281
  yield* decodeFailureOf({ lists: 42 });
282
282
  yield* decodeFailureOf({ lists: [] }); // missing counters + activeListId
283
283
  yield* decodeFailureOf({
284
- lists: [{ id: 1, name: "Work", items: [{ text: "x", done: "yes" }] }],
284
+ lists: [{ id: 1, name: "Work", items: [{ title: "x", done: "yes" }] }],
285
285
  activeListId: null,
286
286
  nextListId: 2,
287
287
  });