@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,18 +1,21 @@
1
1
  import { Context, Effect, Layer, Option, Predicate, Schema } from "effect";
2
2
  import * as FileSystem from "effect/FileSystem";
3
3
  import {
4
- DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE,
5
- DEFAULT_KEEP_CONTEXT_THRESHOLD,
4
+ DEFAULT_MIN_ANSWER_CONFIDENCE,
5
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
6
6
  type ClassifierIdentity,
7
7
  } from "./classifier.ts";
8
8
 
9
9
  /**
10
10
  * The tracker's reader of the shared TUI settings file. It owns the
11
- * interpretation of the three keys that smart compaction uses, and it fails open
11
+ * interpretation of the five keys that smart compaction uses, and it fails open
12
12
  * on every read, parse, or shape problem: the feature is active by default, the
13
13
  * classifier preference order applies when no identity is chosen, and the
14
14
  * default threshold applies when the value is missing or invalid.
15
15
  *
16
+ * The two probability knobs also accept their pre-rename key as an alias; the
17
+ * current key wins when both are present.
18
+ *
16
19
  * Co-owned with `packages/tui/src/config.ts`; the key names and value shapes
17
20
  * are pinned by `test-fixtures/tui-config.contract.json`, read by both suites.
18
21
  */
@@ -20,9 +23,13 @@ export const SMART_COMPACTION_CONFIG_FILE = "tui.json";
20
23
  export const SMART_COMPACTION_KEY = "smartCompaction";
21
24
  export const ENABLED_KEY = "enabled";
22
25
  export const CLASSIFIER_KEY = "classifier";
23
- export const KEEP_CONTEXT_THRESHOLD_KEY = "keepContextThreshold";
24
- export const KEEP_CONTEXT_MIN_CONFIDENCE_KEY = "keepContextMinConfidence";
26
+ export const NEEDS_CONTEXT_PROBABILITY_THRESHOLD_KEY = "needsContextProbabilityThreshold";
27
+ export const MIN_ANSWER_CONFIDENCE_KEY = "minAnswerConfidence";
25
28
  export const MAX_CANDIDATES_KEY = "maxCandidates";
29
+ /** Pre-rename name of `NEEDS_CONTEXT_PROBABILITY_THRESHOLD_KEY`. */
30
+ export const LEGACY_KEEP_CONTEXT_THRESHOLD_KEY = "keepContextThreshold";
31
+ /** Pre-rename name of `MIN_ANSWER_CONFIDENCE_KEY`. */
32
+ export const LEGACY_KEEP_CONTEXT_MIN_CONFIDENCE_KEY = "keepContextMinConfidence";
26
33
 
27
34
  /** Default number of ready items one classification judges. */
28
35
  export const DEFAULT_MAX_CANDIDATES = 8;
@@ -32,23 +39,22 @@ export const MAX_CANDIDATES_LIMIT = 20;
32
39
  const FileSchema = Schema.fromJsonString(Schema.Unknown);
33
40
  const EnabledSchema = Schema.Boolean;
34
41
  const ClassifierSchema = Schema.NullOr(Schema.String);
35
- const KeepContextThresholdSchema = Schema.Finite;
36
- const KeepContextMinConfidenceSchema = Schema.Finite;
42
+ const UnitIntervalSchema = Schema.Finite;
37
43
  const MaxCandidatesSchema = Schema.Int;
38
44
 
39
45
  export interface SmartCompactionSettings {
40
46
  readonly enabled: boolean;
41
47
  readonly chosen: Option.Option<ClassifierIdentity>;
42
- readonly keepContextThreshold: number;
43
- readonly keepContextMinConfidence: number;
48
+ readonly needsContextProbabilityThreshold: number;
49
+ readonly minAnswerConfidence: number;
44
50
  readonly maxCandidates: number;
45
51
  }
46
52
 
47
53
  export const defaultSmartCompactionSettings = (): SmartCompactionSettings => ({
48
54
  enabled: true,
49
55
  chosen: Option.none(),
50
- keepContextThreshold: DEFAULT_KEEP_CONTEXT_THRESHOLD,
51
- keepContextMinConfidence: DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE,
56
+ needsContextProbabilityThreshold: DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
57
+ minAnswerConfidence: DEFAULT_MIN_ANSWER_CONFIDENCE,
52
58
  maxCandidates: DEFAULT_MAX_CANDIDATES,
53
59
  });
54
60
 
@@ -71,6 +77,28 @@ const smartSection = (parsed: unknown): Record<string, unknown> | undefined => {
71
77
  return Predicate.isObject(section) ? section : undefined;
72
78
  };
73
79
 
80
+ /**
81
+ * Read one of the two probability knobs. The current key wins; a config that
82
+ * still carries only the legacy alias resolves the same way. The value must
83
+ * stay strictly inside (0, 1), and anything else falls back to the default
84
+ * alone, so a bad value cannot disable the whole feature.
85
+ */
86
+ const readUnitInterval = (
87
+ section: Record<string, unknown> | undefined,
88
+ key: string,
89
+ legacyKey: string,
90
+ fallback: number,
91
+ ): number => {
92
+ const raw = section === undefined ? undefined : (section[key] ?? section[legacyKey]);
93
+ return Option.getOrElse(
94
+ Option.filter(
95
+ Schema.decodeUnknownOption(UnitIntervalSchema)(raw),
96
+ (value) => value > 0 && value < 1,
97
+ ),
98
+ () => fallback,
99
+ );
100
+ };
101
+
74
102
  export class SmartCompactionSettingsService extends Context.Service<
75
103
  SmartCompactionSettingsService,
76
104
  {
@@ -105,25 +133,19 @@ export class SmartCompactionSettingsService extends Context.Service<
105
133
  ),
106
134
  (value) => (value === null ? Option.none() : parseClassifierIdentity(value)),
107
135
  );
108
- // A threshold must stay strictly inside (0, 1); anything else falls
109
- // back alone, so a bad value cannot disable the whole feature.
110
- const keepContextThreshold = Option.getOrElse(
111
- Option.filter(
112
- Schema.decodeUnknownOption(KeepContextThresholdSchema)(
113
- section === undefined ? undefined : section[KEEP_CONTEXT_THRESHOLD_KEY],
114
- ),
115
- (value) => value > 0 && value < 1,
116
- ),
117
- () => DEFAULT_KEEP_CONTEXT_THRESHOLD,
136
+ // Each probability knob resolves independently: the current key, then
137
+ // the legacy alias, then the default.
138
+ const needsContextProbabilityThreshold = readUnitInterval(
139
+ section,
140
+ NEEDS_CONTEXT_PROBABILITY_THRESHOLD_KEY,
141
+ LEGACY_KEEP_CONTEXT_THRESHOLD_KEY,
142
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
118
143
  );
119
- const keepContextMinConfidence = Option.getOrElse(
120
- Option.filter(
121
- Schema.decodeUnknownOption(KeepContextMinConfidenceSchema)(
122
- section === undefined ? undefined : section[KEEP_CONTEXT_MIN_CONFIDENCE_KEY],
123
- ),
124
- (value) => value > 0 && value < 1,
125
- ),
126
- () => DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE,
144
+ const minAnswerConfidence = readUnitInterval(
145
+ section,
146
+ MIN_ANSWER_CONFIDENCE_KEY,
147
+ LEGACY_KEEP_CONTEXT_MIN_CONFIDENCE_KEY,
148
+ DEFAULT_MIN_ANSWER_CONFIDENCE,
127
149
  );
128
150
  // The cap must be an integer in [1, MAX_CANDIDATES_LIMIT]; anything
129
151
  // else falls back alone.
@@ -139,8 +161,8 @@ export class SmartCompactionSettingsService extends Context.Service<
139
161
  return {
140
162
  enabled,
141
163
  chosen,
142
- keepContextThreshold,
143
- keepContextMinConfidence,
164
+ needsContextProbabilityThreshold,
165
+ minAnswerConfidence,
144
166
  maxCandidates,
145
167
  } satisfies SmartCompactionSettings;
146
168
  }).pipe(
@@ -0,0 +1,370 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { Effect, Layer } from "effect";
3
+ import type { ClassifierApi, ClassifierModel, ClassifierResult } from "@earendil-works/pi-ai";
4
+ import { NEEDS_CONTEXT_LABEL, NEEDS_NONE_LABEL } from "./classifier.ts";
5
+ import { ClassifierGateway, type ClassifierRegistry } from "./classifier.ts";
6
+ import type { CompactionCandidate } from "./candidate.ts";
7
+ import { CompletionObserver } from "./completion.ts";
8
+ import { FootprintRecorder } from "./footprint.ts";
9
+ import {
10
+ containsSymbol,
11
+ emptyFootprint,
12
+ productionFacts,
13
+ type BatchFootprint,
14
+ type FileProbe,
15
+ } from "./observations.ts";
16
+ import { acceptedRoute, buildRuleInput, resolveCandidates } from "./rules.ts";
17
+ import { SettleDecider, type SettleDecision } from "./settle.ts";
18
+ import { SmartCompactionSettingsService, defaultSmartCompactionSettings } from "./settings.ts";
19
+ import { TodoItem, TodoList, TrackerState } from "../core/domain.ts";
20
+
21
+ const model: ClassifierModel<ClassifierApi> = {
22
+ id: "@cf/cloudflare/clef-flash",
23
+ name: "clef-flash",
24
+ api: "typesafe-system-one",
25
+ provider: "cloudflare-workers-ai",
26
+ baseUrl: "https://example.invalid",
27
+ input: ["text"],
28
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
29
+ type: "classifier",
30
+ contextWindow: 8192,
31
+ };
32
+
33
+ /** A probe over a path-to-text map. `findSymbol` scans the same map. */
34
+ const probeOf = (files: Readonly<Record<string, string>>): FileProbe => ({
35
+ read: (path) => files[path],
36
+ findSymbol: (symbol) =>
37
+ Object.entries(files)
38
+ .filter(([, text]) => containsSymbol(text, symbol))
39
+ .map(([path]) => path),
40
+ });
41
+
42
+ interface RegistrySpy {
43
+ readonly registry: ClassifierRegistry;
44
+ readonly calls: () => number;
45
+ }
46
+
47
+ /** A registry that answers every question with the given `needs-context` mass. */
48
+ const registrySpy = (needsMass: number): RegistrySpy => {
49
+ let calls = 0;
50
+ return {
51
+ calls: () => calls,
52
+ registry: {
53
+ getAvailableOfType: async () => [model],
54
+ classify: async (_model, context) => {
55
+ calls += 1;
56
+ const answers: ClassifierResult["answers"] = {};
57
+ for (const key of Object.keys(context.questions)) {
58
+ answers[key] = {
59
+ type: "choice",
60
+ choice: needsMass >= 0.5 ? NEEDS_CONTEXT_LABEL : NEEDS_NONE_LABEL,
61
+ probabilities: { [NEEDS_CONTEXT_LABEL]: needsMass, [NEEDS_NONE_LABEL]: 1 - needsMass },
62
+ confidence: 1,
63
+ };
64
+ }
65
+ return {
66
+ api: "typesafe-system-one",
67
+ provider: "typesafe",
68
+ model: "jev-latest",
69
+ answers,
70
+ stopReason: "stop",
71
+ timestamp: 0,
72
+ };
73
+ },
74
+ },
75
+ };
76
+ };
77
+
78
+ const settingsLayer = (
79
+ overrides: Partial<ReturnType<typeof defaultSmartCompactionSettings>> = {},
80
+ ): Layer.Layer<SmartCompactionSettingsService> =>
81
+ Layer.succeed(
82
+ SmartCompactionSettingsService,
83
+ SmartCompactionSettingsService.of({
84
+ path: "/tmp/smart-compaction.json",
85
+ load: Effect.succeed({ ...defaultSmartCompactionSettings(), ...overrides }),
86
+ }),
87
+ );
88
+
89
+ const footprintLayer = (footprint: BatchFootprint): Layer.Layer<FootprintRecorder> =>
90
+ Layer.succeed(
91
+ FootprintRecorder,
92
+ FootprintRecorder.of({
93
+ capture: () => Effect.void,
94
+ snapshot: Effect.succeed(footprint),
95
+ consume: Effect.succeed(footprint),
96
+ }),
97
+ );
98
+
99
+ const item = (spec: {
100
+ readonly id: number;
101
+ readonly title: string;
102
+ readonly description?: string;
103
+ readonly done: boolean;
104
+ readonly refs?: TodoItem["refs"];
105
+ readonly produces?: TodoItem["produces"];
106
+ }): TodoItem =>
107
+ new TodoItem({
108
+ id: spec.id,
109
+ title: spec.title,
110
+ description: spec.description ?? "",
111
+ done: spec.done,
112
+ deps: [],
113
+ refs: [...(spec.refs ?? [])],
114
+ produces: [...(spec.produces ?? [])],
115
+ });
116
+
117
+ const stateOf = (first: TodoItem, candidate: TodoItem, firstDone: boolean): TrackerState =>
118
+ new TrackerState({
119
+ lists: [
120
+ new TodoList({
121
+ id: 1,
122
+ name: "Work",
123
+ items: [
124
+ new TodoItem({ ...first, done: firstDone }),
125
+ new TodoItem({ ...candidate, done: false }),
126
+ ],
127
+ nextItemId: 3,
128
+ }),
129
+ ],
130
+ activeListId: 1,
131
+ nextListId: 2,
132
+ });
133
+
134
+ /**
135
+ * Record one completion (item 1) and decide. `candidate` is the ready item the
136
+ * rule table and the classifier judge.
137
+ */
138
+ const decide = (input: {
139
+ readonly footprint: BatchFootprint;
140
+ readonly probe: FileProbe;
141
+ readonly spy: RegistrySpy;
142
+ readonly candidate: TodoItem;
143
+ }): Effect.Effect<SettleDecision> => {
144
+ const first = item({
145
+ id: 1,
146
+ title: "first slice",
147
+ description: "the completed work",
148
+ done: true,
149
+ });
150
+ const before = stateOf(first, input.candidate, false);
151
+ const after = stateOf(first, input.candidate, true);
152
+ return Effect.gen(function* () {
153
+ const observer = yield* CompletionObserver;
154
+ yield* observer.record(before, after);
155
+ const decider = yield* SettleDecider;
156
+ return yield* decider.decide({ registry: input.spy.registry, outcome: "completed" });
157
+ }).pipe(
158
+ Effect.provide(
159
+ SettleDecider.layer(input.probe).pipe(
160
+ Layer.provideMerge(
161
+ Layer.mergeAll(
162
+ CompletionObserver.layer,
163
+ ClassifierGateway.layer,
164
+ footprintLayer(input.footprint),
165
+ settingsLayer(),
166
+ ),
167
+ ),
168
+ ),
169
+ ),
170
+ );
171
+ };
172
+
173
+ const candidate = (overrides: Partial<TodoItem> = {}): TodoItem =>
174
+ item({ id: 2, title: "second step", done: false, ...overrides });
175
+
176
+ const wrote = (path: string): BatchFootprint => ({
177
+ ...emptyFootprint(),
178
+ wrote: [{ path, spans: [] }],
179
+ });
180
+
181
+ /** The decision compacts the head candidate; the pointer is a long resume text. */
182
+ const assertCompacts = (decision: SettleDecision): void => {
183
+ if (decision.kind !== "compact") assert.fail(`expected compact, got ${decision.kind}`);
184
+ assert.include(decision.pointer, "Work:2");
185
+ };
186
+
187
+ // ---------------------------------------------------------------------------
188
+ // The accepted rows decide without the classifier
189
+ // ---------------------------------------------------------------------------
190
+
191
+ it.effect("no declarations and no named batch output compact without a classifier call", () =>
192
+ Effect.gen(function* () {
193
+ const spy = registrySpy(0.1);
194
+ const decision = yield* decide({
195
+ footprint: emptyFootprint(),
196
+ probe: probeOf({}),
197
+ spy,
198
+ candidate: candidate(),
199
+ });
200
+ assertCompacts(decision);
201
+ assert.strictEqual(spy.calls(), 0);
202
+ // No declarations: no decision record is written.
203
+ assert.isUndefined(decision.record);
204
+ }),
205
+ );
206
+
207
+ it.effect("a candidate that names a batch output compacts", () =>
208
+ Effect.gen(function* () {
209
+ const spy = registrySpy(0.1);
210
+ const decision = yield* decide({
211
+ footprint: wrote("src/router.ts"),
212
+ probe: probeOf({}),
213
+ spy,
214
+ candidate: candidate({ title: "wire src/router.ts into the app" }),
215
+ });
216
+ assertCompacts(decision);
217
+ assert.strictEqual(spy.calls(), 0);
218
+ }),
219
+ );
220
+
221
+ // ---------------------------------------------------------------------------
222
+ // Observe-only rows keep the classifier in the loop
223
+ // ---------------------------------------------------------------------------
224
+
225
+ it.effect("a readable declared reference reports but does not compact", () =>
226
+ Effect.gen(function* () {
227
+ const spy = registrySpy(0.9);
228
+ const decision = yield* decide({
229
+ footprint: { ...emptyFootprint(), read: ["src/a.ts"] },
230
+ probe: probeOf({ "src/a.ts": "export {};" }),
231
+ spy,
232
+ candidate: candidate({ refs: [{ kind: "path", path: "src/a.ts" }] }),
233
+ });
234
+ assert.strictEqual(spy.calls(), 1);
235
+ assert.strictEqual(decision.kind, "keep");
236
+ // The declared decision carries the raw row and the resolved state.
237
+ assert.strictEqual(decision.record?.rule, "reference-is-readable");
238
+ assert.deepStrictEqual(decision.record?.references, [
239
+ { kind: "path", path: "src/a.ts", state: "readable" },
240
+ ]);
241
+ }),
242
+ );
243
+
244
+ it.effect("a lost declared reference is reported and the classifier decides", () =>
245
+ Effect.gen(function* () {
246
+ const spy = registrySpy(0.9);
247
+ const decision = yield* decide({
248
+ footprint: { ...emptyFootprint(), deleted: [{ path: "src/a.ts" }] },
249
+ probe: probeOf({}),
250
+ spy,
251
+ candidate: candidate({ refs: [{ kind: "path", path: "src/a.ts" }] }),
252
+ });
253
+ assert.strictEqual(spy.calls(), 1);
254
+ assert.strictEqual(decision.kind, "keep");
255
+ }),
256
+ );
257
+
258
+ it.effect("after a restore, a declared reference abstains and the classifier decides", () =>
259
+ Effect.gen(function* () {
260
+ const spy = registrySpy(0.9);
261
+ const decision = yield* decide({
262
+ footprint: emptyFootprint(),
263
+ probe: probeOf({ "src/a.ts": "export {};" }),
264
+ spy,
265
+ candidate: candidate({ refs: [{ kind: "path", path: "src/a.ts" }] }),
266
+ });
267
+ assert.strictEqual(spy.calls(), 1);
268
+ assert.strictEqual(decision.kind, "keep");
269
+ }),
270
+ );
271
+
272
+ it.effect("after a restore, a declared product resolves by disk existence", () =>
273
+ Effect.gen(function* () {
274
+ const spy = registrySpy(0.9);
275
+ const decision = yield* decide({
276
+ footprint: emptyFootprint(),
277
+ probe: probeOf({ "docs/plan.md": "# Plan" }),
278
+ spy,
279
+ candidate: candidate({ produces: [{ path: "docs/plan.md" }] }),
280
+ });
281
+ assert.strictEqual(spy.calls(), 1);
282
+ assert.strictEqual(decision.kind, "keep");
283
+ }),
284
+ );
285
+
286
+ it.effect("a declared symbol found in two workspace files abstains", () =>
287
+ Effect.gen(function* () {
288
+ const spy = registrySpy(0.9);
289
+ const decision = yield* decide({
290
+ footprint: { ...emptyFootprint(), read: ["src/a.ts"] },
291
+ probe: probeOf({ "src/a.ts": "nothing", "src/b.ts": "route()", "src/c.ts": "route()" }),
292
+ spy,
293
+ candidate: candidate({ refs: [{ kind: "path", path: "src/a.ts", symbol: "route" }] }),
294
+ });
295
+ assert.strictEqual(spy.calls(), 1);
296
+ assert.strictEqual(decision.kind, "keep");
297
+ }),
298
+ );
299
+
300
+ it.effect("a row outside the accepted set keeps the classifier in the loop", () =>
301
+ Effect.gen(function* () {
302
+ const spy = registrySpy(0.1);
303
+ const decision = yield* decide({
304
+ footprint: { ...emptyFootprint(), read: ["src/a.ts"] },
305
+ probe: probeOf({ "src/a.ts": "export {};" }),
306
+ spy,
307
+ candidate: candidate({ refs: [{ kind: "path", path: "src/a.ts" }] }),
308
+ });
309
+ assert.strictEqual(spy.calls(), 1);
310
+ assertCompacts(decision);
311
+ }),
312
+ );
313
+
314
+ it.effect("a disabled setting keeps the context without a classifier call", () =>
315
+ Effect.gen(function* () {
316
+ const spy = registrySpy(0.1);
317
+ const first = item({
318
+ id: 1,
319
+ title: "first slice",
320
+ description: "the completed work",
321
+ done: true,
322
+ });
323
+ const before = stateOf(first, candidate(), false);
324
+ const after = stateOf(first, candidate(), true);
325
+ const decision = yield* Effect.gen(function* () {
326
+ const observer = yield* CompletionObserver;
327
+ yield* observer.record(before, after);
328
+ const decider = yield* SettleDecider;
329
+ return yield* decider.decide({ registry: spy.registry, outcome: "completed" });
330
+ }).pipe(
331
+ Effect.provide(
332
+ SettleDecider.layer(probeOf({})).pipe(
333
+ Layer.provideMerge(
334
+ Layer.mergeAll(
335
+ CompletionObserver.layer,
336
+ ClassifierGateway.layer,
337
+ footprintLayer(emptyFootprint()),
338
+ settingsLayer({ enabled: false }),
339
+ ),
340
+ ),
341
+ ),
342
+ ),
343
+ );
344
+ assert.strictEqual(spy.calls(), 0);
345
+ assert.strictEqual(decision.kind, "keep");
346
+ }),
347
+ );
348
+
349
+ // The product state must really be `exists`, so the restore test cannot pass
350
+ // by accident; `resolveCandidates` reads the disk for it.
351
+ it("a product that exists on disk resolves to exists and grants no compact row", () => {
352
+ const candidate: CompactionCandidate = {
353
+ class: "ready-queue",
354
+ listName: "Work",
355
+ id: 2,
356
+ text: "second step",
357
+ completed: [],
358
+ produces: [{ path: "docs/plan.md" }],
359
+ };
360
+ const facts = resolveCandidates(
361
+ [candidate],
362
+ emptyFootprint(),
363
+ probeOf({ "docs/plan.md": "# Plan" }),
364
+ )[0]!;
365
+ assert.deepStrictEqual(facts.products, [{ product: { path: "docs/plan.md" }, state: "exists" }]);
366
+ assert.deepStrictEqual(
367
+ acceptedRoute(buildRuleInput(facts, productionFacts([], emptyFootprint(), candidate.text))),
368
+ { verdict: "abstain", rule: "declarations-unresolved" },
369
+ );
370
+ });