@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
@@ -0,0 +1,188 @@
1
+ /**
2
+ * The reliance rule table.
3
+ *
4
+ * Every row is named for the observation it tests; the verdict is separate.
5
+ * The declared rows fire only when the item carries declarations, and they come
6
+ * first. The legacy rows reproduce the pre-revert rules exactly, under honest
7
+ * names, so the corpus parity test can show the rename changed nothing.
8
+ *
9
+ * `ACCEPTED_RULES` is the product policy. A row that has not cleared the
10
+ * two-pass gate reports its raw verdict and abstains, so an unmeasured row can
11
+ * never compact on its own.
12
+ */
13
+ import type { CompactionCandidate } from "./candidate.ts";
14
+ import {
15
+ QRSPI_PLAN_DOCUMENT,
16
+ productionFacts,
17
+ resolveProducts,
18
+ resolveReferences,
19
+ type BatchFootprint,
20
+ type FileProbe,
21
+ type ResolvedProduct,
22
+ type ResolvedReference,
23
+ } from "./observations.ts";
24
+
25
+ /** What the rule layer decides for one candidate. */
26
+ export type RuleVerdict = "keep" | "compact" | "abstain";
27
+
28
+ /** Everything the rows read. Declarations may be empty; the legacy facts may not. */
29
+ export interface RuleInput {
30
+ /** Declared references, already resolved against the disk. */
31
+ readonly references: readonly ResolvedReference[];
32
+ /** Declared products, already resolved against the disk. */
33
+ readonly products: readonly ResolvedProduct[];
34
+ /** Every file path the candidate names. */
35
+ readonly candidatePaths: readonly string[];
36
+ /** The batch texts plus the work record, joined. A document named here was named. */
37
+ readonly knownText: string;
38
+ /** The `write` and `edit` call paths, joined. A path named here was produced. */
39
+ readonly producedText: string;
40
+ /** The candidate is a `dependent-successor`. */
41
+ readonly dependent: boolean;
42
+ /** The batch or the record names a plan, design, or outline document. */
43
+ readonly planDocument: boolean;
44
+ }
45
+
46
+ export interface RuleDecision {
47
+ readonly verdict: RuleVerdict;
48
+ /** The rule id, stable across the report and the product. */
49
+ readonly rule: string;
50
+ }
51
+
52
+ const hasDeclaration = (input: RuleInput): boolean =>
53
+ input.references.length > 0 || input.products.length > 0;
54
+
55
+ /** The declaration facts one candidate resolves to. */
56
+ export interface CandidateFacts {
57
+ readonly references: readonly ResolvedReference[];
58
+ readonly products: readonly ResolvedProduct[];
59
+ /** The candidate is a `dependent-successor`. */
60
+ readonly dependent: boolean;
61
+ }
62
+
63
+ /**
64
+ * Decide one candidate from the observations.
65
+ *
66
+ * The order matters. A lost reference keeps the context before anything else.
67
+ * An unwritten plan product keeps it next, because the document it will write
68
+ * needs the upstream decisions. A declared decision abstains: it is a semantic
69
+ * claim, and the classifier is the judge. A drifted or unresolved declaration
70
+ * abstains rather than compact on half a fact. Only then do the legacy rows
71
+ * run, and they run exactly as the pre-revert table did.
72
+ */
73
+ export const route = (input: RuleInput): RuleDecision => {
74
+ // --- Declared rows: they fire only when the item carries declarations. ---
75
+ if (input.references.some((entry) => entry.state === "lost")) {
76
+ return { verdict: "keep", rule: "reference-is-lost" };
77
+ }
78
+ if (
79
+ input.products.some(
80
+ (entry) => entry.state === "missing" && QRSPI_PLAN_DOCUMENT.test(entry.product.path),
81
+ )
82
+ ) {
83
+ return { verdict: "keep", rule: "product-is-unwritten-plan" };
84
+ }
85
+ if (input.references.some((entry) => entry.reference.kind === "decision")) {
86
+ return { verdict: "abstain", rule: "decision-is-declared" };
87
+ }
88
+ if (input.references.some((entry) => entry.state === "drifted")) {
89
+ return { verdict: "abstain", rule: "reference-has-drifted" };
90
+ }
91
+ if (
92
+ input.references.length > 0 &&
93
+ input.references.every((entry) => entry.state === "readable")
94
+ ) {
95
+ return { verdict: "compact", rule: "reference-is-readable" };
96
+ }
97
+ if (input.references.some((entry) => entry.state === "unresolved")) {
98
+ return { verdict: "abstain", rule: "reference-is-unresolved" };
99
+ }
100
+ if (hasDeclaration(input)) {
101
+ // A declaration exists and no row decided it. Never compact on a
102
+ // half-resolved declaration.
103
+ return { verdict: "abstain", rule: "declarations-unresolved" };
104
+ }
105
+
106
+ // --- Legacy rows: the frozen pre-revert rules, under honest names. ---
107
+ const writes = input.candidatePaths.some((path) => !input.knownText.includes(path));
108
+ const reads = input.candidatePaths.some((path) => input.producedText.includes(path));
109
+ if (writes) return { verdict: "keep", rule: "names-unknown-path" };
110
+ if (reads && !input.dependent) return { verdict: "compact", rule: "names-batch-output" };
111
+ if (!reads && !input.dependent && !input.planDocument) {
112
+ return { verdict: "compact", rule: "no-visible-link" };
113
+ }
114
+ if (input.dependent && input.planDocument) {
115
+ return { verdict: "abstain", rule: "document-and-dependency" };
116
+ }
117
+ if (input.dependent) return { verdict: "abstain", rule: "dependent-successor" };
118
+ return { verdict: "abstain", rule: "plan-document" };
119
+ };
120
+
121
+ /**
122
+ * The rows that cleared the gate and may decide without a model call. The
123
+ * measured production gate: `names-batch-output` agrees with 96.4% of pass 1
124
+ * and 100.0% of pass 2, and `no-visible-link` with 96.0% of pass 2 and 98.2%
125
+ * of pass 3. `bun run eval:promote` prints the table and rewrites this block;
126
+ * every declared row is observe-only until it clears the same gate on a corpus
127
+ * that carries declarations.
128
+ */
129
+ export const ACCEPTED_RULES: ReadonlySet<string> = new Set([
130
+ "names-batch-output",
131
+ "no-visible-link",
132
+ ]);
133
+
134
+ /**
135
+ * The product policy: a rule that cleared the gate keeps its verdict; every
136
+ * other row abstains and keeps its name for the report.
137
+ */
138
+ export const acceptedRoute = (input: RuleInput): RuleDecision => {
139
+ const decision = route(input);
140
+ return ACCEPTED_RULES.has(decision.rule) ? decision : { verdict: "abstain", rule: decision.rule };
141
+ };
142
+
143
+ /** True when the batch recorded any work at all. */
144
+ export const hasFootprint = (footprint: BatchFootprint): boolean =>
145
+ footprint.wrote.length > 0 ||
146
+ footprint.read.length > 0 ||
147
+ footprint.deleted.length > 0 ||
148
+ footprint.commands.length > 0;
149
+
150
+ /**
151
+ * Resolve each candidate's declarations against the footprint and the disk.
152
+ *
153
+ * Without a footprint there is nothing to resolve against: a session restore
154
+ * leaves the recorder empty, so every declared reference abstains and the
155
+ * classifier decides. Declared products still check disk existence, because a
156
+ * product is a claim about a file, not about the batch.
157
+ */
158
+ export const resolveCandidates = (
159
+ candidates: readonly CompactionCandidate[],
160
+ footprint: BatchFootprint,
161
+ probe: FileProbe,
162
+ ): readonly CandidateFacts[] => {
163
+ const recorded = hasFootprint(footprint);
164
+ return candidates.map((candidate) => {
165
+ const references = candidate.refs ?? [];
166
+ return {
167
+ references: recorded
168
+ ? resolveReferences(references, footprint, probe)
169
+ : references.map((reference) => ({ reference, state: "unresolved" as const })),
170
+ products: resolveProducts(candidate.produces ?? [], probe),
171
+ dependent: candidate.class === "dependent-successor",
172
+ };
173
+ });
174
+ };
175
+
176
+ /** Fold the resolved declarations and the production facts into a rule input. */
177
+ export const buildRuleInput = (
178
+ facts: CandidateFacts,
179
+ production: ReturnType<typeof productionFacts>,
180
+ ): RuleInput => ({
181
+ references: facts.references,
182
+ products: facts.products,
183
+ candidatePaths: production.candidatePaths,
184
+ knownText: production.knownText,
185
+ producedText: production.producedText,
186
+ dependent: facts.dependent,
187
+ planDocument: production.planDocument,
188
+ });
@@ -0,0 +1,315 @@
1
+ import { assert, it } from "@effect/vitest";
2
+ import { Effect, Option, PlatformError } from "effect";
3
+ import * as FileSystem from "effect/FileSystem";
4
+ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
5
+ import { fileURLToPath } from "node:url";
6
+ import {
7
+ CLASSIFIER_KEY,
8
+ DEFAULT_MAX_CANDIDATES,
9
+ ENABLED_KEY,
10
+ MIN_ANSWER_CONFIDENCE_KEY,
11
+ NEEDS_CONTEXT_PROBABILITY_THRESHOLD_KEY,
12
+ LEGACY_KEEP_CONTEXT_MIN_CONFIDENCE_KEY,
13
+ LEGACY_KEEP_CONTEXT_THRESHOLD_KEY,
14
+ MAX_CANDIDATES_KEY,
15
+ SMART_COMPACTION_KEY,
16
+ SmartCompactionSettingsService,
17
+ parseClassifierIdentity,
18
+ type SmartCompactionSettings,
19
+ } from "./settings.ts";
20
+ import {
21
+ DEFAULT_MIN_ANSWER_CONFIDENCE,
22
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
23
+ } from "./classifier.ts";
24
+
25
+ const TEST_PATH = "/tmp/tracker-settings-test/tui.json";
26
+ const FIXTURE_PATH = fileURLToPath(
27
+ new URL("../../test-fixtures/tui-config.contract.json", import.meta.url),
28
+ );
29
+
30
+ /** Read the shared contract fixture through the FileSystem service. */
31
+ const readFixture: Effect.Effect<string, PlatformError.PlatformError> = Effect.gen(function* () {
32
+ const fs = yield* FileSystem.FileSystem;
33
+ return yield* fs.readFileString(FIXTURE_PATH);
34
+ }).pipe(Effect.provide(NodeFileSystem.layer));
35
+
36
+ interface MemFs {
37
+ readonly fs: Partial<FileSystem.FileSystem>;
38
+ readonly files: Map<string, string>;
39
+ readonly writes: string[];
40
+ }
41
+
42
+ function makeMemFs(init: Record<string, string> = {}): MemFs {
43
+ const files = new Map<string, string>(Object.entries(init));
44
+ const writes: string[] = [];
45
+
46
+ const fs: Partial<FileSystem.FileSystem> = {
47
+ readFileString: (path) =>
48
+ files.has(path)
49
+ ? Effect.succeed(files.get(path)!)
50
+ : Effect.fail(
51
+ PlatformError.systemError({
52
+ _tag: "NotFound",
53
+ module: "FileSystem",
54
+ method: "readFileString",
55
+ pathOrDescriptor: path,
56
+ description: "No such file",
57
+ }),
58
+ ),
59
+ writeFileString: (path, data) =>
60
+ Effect.sync(() => {
61
+ writes.push(path);
62
+ files.set(path, data);
63
+ }),
64
+ };
65
+
66
+ return { fs, files, writes };
67
+ }
68
+
69
+ const load = (): Effect.Effect<SmartCompactionSettings, never, SmartCompactionSettingsService> =>
70
+ Effect.gen(function* () {
71
+ const service = yield* SmartCompactionSettingsService;
72
+ return yield* service.load;
73
+ });
74
+
75
+ const runWithMem = <A, E>(
76
+ mem: MemFs,
77
+ program: Effect.Effect<A, E, SmartCompactionSettingsService>,
78
+ ): Effect.Effect<A, E> =>
79
+ program.pipe(Effect.provide(SmartCompactionSettingsService.layerTest(TEST_PATH, mem.fs)));
80
+
81
+ it.effect("load returns the fail-open defaults when the file is missing", () =>
82
+ Effect.gen(function* () {
83
+ const mem = makeMemFs();
84
+ const settings = yield* runWithMem(mem, load());
85
+ assert.strictEqual(settings.enabled, true);
86
+ assert.strictEqual(Option.isNone(settings.chosen), true);
87
+ assert.strictEqual(
88
+ settings.needsContextProbabilityThreshold,
89
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
90
+ );
91
+ }),
92
+ );
93
+
94
+ it.effect("load returns the fail-open defaults when the file is not JSON", () =>
95
+ Effect.gen(function* () {
96
+ const mem = makeMemFs({ [TEST_PATH]: "not json" });
97
+ const settings = yield* runWithMem(mem, load());
98
+ assert.strictEqual(settings.enabled, true);
99
+ assert.strictEqual(Option.isNone(settings.chosen), true);
100
+ assert.strictEqual(
101
+ settings.needsContextProbabilityThreshold,
102
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
103
+ );
104
+ }),
105
+ );
106
+
107
+ it.effect("load returns the fail-open defaults when the section has the wrong shape", () =>
108
+ Effect.gen(function* () {
109
+ const mem = makeMemFs({ [TEST_PATH]: JSON.stringify({ smartCompaction: "on" }) });
110
+ const settings = yield* runWithMem(mem, load());
111
+ assert.strictEqual(settings.enabled, true);
112
+ assert.strictEqual(Option.isNone(settings.chosen), true);
113
+ assert.strictEqual(
114
+ settings.needsContextProbabilityThreshold,
115
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
116
+ );
117
+ }),
118
+ );
119
+
120
+ it.effect("load ignores an unrecognized enabled value and keeps a valid chosen classifier", () =>
121
+ Effect.gen(function* () {
122
+ const mem = makeMemFs({
123
+ [TEST_PATH]: JSON.stringify({
124
+ smartCompaction: { enabled: "yes", classifier: "typesafe/jev-latest" },
125
+ }),
126
+ });
127
+ const settings = yield* runWithMem(mem, load());
128
+ assert.strictEqual(settings.enabled, true);
129
+ assert.deepStrictEqual(Option.getOrThrow(settings.chosen), {
130
+ provider: "typesafe",
131
+ modelId: "jev-latest",
132
+ });
133
+ assert.strictEqual(
134
+ settings.needsContextProbabilityThreshold,
135
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
136
+ );
137
+ }),
138
+ );
139
+
140
+ it.effect("load reads a valid needs-context probability threshold from the section", () =>
141
+ Effect.gen(function* () {
142
+ const mem = makeMemFs({
143
+ [TEST_PATH]: JSON.stringify({ smartCompaction: { needsContextProbabilityThreshold: 0.72 } }),
144
+ });
145
+ const settings = yield* runWithMem(mem, load());
146
+ assert.strictEqual(settings.needsContextProbabilityThreshold, 0.72);
147
+ }),
148
+ );
149
+
150
+ it.effect(
151
+ "load falls back alone when the probability threshold is outside the open unit interval",
152
+ () =>
153
+ Effect.gen(function* () {
154
+ for (const invalid of [0, 1, -0.1, 1.5, "0.5"]) {
155
+ const mem = makeMemFs({
156
+ [TEST_PATH]: JSON.stringify({
157
+ smartCompaction: { enabled: false, needsContextProbabilityThreshold: invalid },
158
+ }),
159
+ });
160
+ const settings = yield* runWithMem(mem, load());
161
+ assert.strictEqual(
162
+ settings.needsContextProbabilityThreshold,
163
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
164
+ );
165
+ // The bad value must not discard the rest of the section.
166
+ assert.strictEqual(settings.enabled, false);
167
+ }
168
+ }),
169
+ );
170
+
171
+ it.effect("load reads a valid min answer confidence from the section", () =>
172
+ Effect.gen(function* () {
173
+ const mem = makeMemFs({
174
+ [TEST_PATH]: JSON.stringify({ smartCompaction: { minAnswerConfidence: 0.72 } }),
175
+ });
176
+ const settings = yield* runWithMem(mem, load());
177
+ assert.strictEqual(settings.minAnswerConfidence, 0.72);
178
+ }),
179
+ );
180
+
181
+ it.effect(
182
+ "load falls back alone when the min answer confidence is outside the open unit interval",
183
+ () =>
184
+ Effect.gen(function* () {
185
+ for (const invalid of [0, 1, -0.1, 1.5, "0.5"]) {
186
+ const mem = makeMemFs({
187
+ [TEST_PATH]: JSON.stringify({
188
+ smartCompaction: { enabled: false, minAnswerConfidence: invalid },
189
+ }),
190
+ });
191
+ const settings = yield* runWithMem(mem, load());
192
+ assert.strictEqual(settings.minAnswerConfidence, DEFAULT_MIN_ANSWER_CONFIDENCE);
193
+ // The bad value must not discard the rest of the section.
194
+ assert.strictEqual(settings.enabled, false);
195
+ }
196
+ }),
197
+ );
198
+
199
+ it.effect("load reads the legacy probability keys when the current keys are absent", () =>
200
+ Effect.gen(function* () {
201
+ const mem = makeMemFs({
202
+ [TEST_PATH]: JSON.stringify({
203
+ smartCompaction: {
204
+ [LEGACY_KEEP_CONTEXT_THRESHOLD_KEY]: 0.72,
205
+ [LEGACY_KEEP_CONTEXT_MIN_CONFIDENCE_KEY]: 0.31,
206
+ },
207
+ }),
208
+ });
209
+ const settings = yield* runWithMem(mem, load());
210
+ assert.strictEqual(settings.needsContextProbabilityThreshold, 0.72);
211
+ assert.strictEqual(settings.minAnswerConfidence, 0.31);
212
+ }),
213
+ );
214
+
215
+ it.effect("load prefers the current probability keys over their legacy aliases", () =>
216
+ Effect.gen(function* () {
217
+ const mem = makeMemFs({
218
+ [TEST_PATH]: JSON.stringify({
219
+ smartCompaction: {
220
+ [NEEDS_CONTEXT_PROBABILITY_THRESHOLD_KEY]: 0.72,
221
+ [LEGACY_KEEP_CONTEXT_THRESHOLD_KEY]: 0.31,
222
+ [MIN_ANSWER_CONFIDENCE_KEY]: 0.41,
223
+ [LEGACY_KEEP_CONTEXT_MIN_CONFIDENCE_KEY]: 0.21,
224
+ },
225
+ }),
226
+ });
227
+ const settings = yield* runWithMem(mem, load());
228
+ assert.strictEqual(settings.needsContextProbabilityThreshold, 0.72);
229
+ assert.strictEqual(settings.minAnswerConfidence, 0.41);
230
+ }),
231
+ );
232
+
233
+ it.effect("load reads a valid max-candidates cap from the section", () =>
234
+ Effect.gen(function* () {
235
+ const mem = makeMemFs({
236
+ [TEST_PATH]: JSON.stringify({ smartCompaction: { maxCandidates: 3 } }),
237
+ });
238
+ const settings = yield* runWithMem(mem, load());
239
+ assert.strictEqual(settings.maxCandidates, 3);
240
+ }),
241
+ );
242
+
243
+ it.effect("load falls back alone when the cap is not an integer in range", () =>
244
+ Effect.gen(function* () {
245
+ for (const invalid of [0, 21, 5.5, "8", null]) {
246
+ const mem = makeMemFs({
247
+ [TEST_PATH]: JSON.stringify({
248
+ smartCompaction: { enabled: false, maxCandidates: invalid },
249
+ }),
250
+ });
251
+ const settings = yield* runWithMem(mem, load());
252
+ assert.strictEqual(settings.maxCandidates, DEFAULT_MAX_CANDIDATES);
253
+ assert.strictEqual(settings.enabled, false);
254
+ }
255
+ }),
256
+ );
257
+
258
+ it.effect("load resolves every value from the shared contract fixture", () =>
259
+ Effect.gen(function* () {
260
+ const mem = makeMemFs({ [TEST_PATH]: yield* readFixture });
261
+ const settings = yield* runWithMem(mem, load());
262
+ assert.strictEqual(settings.enabled, true);
263
+ assert.deepStrictEqual(Option.getOrThrow(settings.chosen), {
264
+ provider: "typesafe",
265
+ modelId: "jev-latest",
266
+ });
267
+ assert.strictEqual(settings.needsContextProbabilityThreshold, 0.5);
268
+ assert.strictEqual(settings.minAnswerConfidence, 0.5);
269
+ assert.strictEqual(settings.maxCandidates, 8);
270
+ }),
271
+ );
272
+
273
+ it.effect("load reads the enabled, classifier, and probability keys the contract names", () =>
274
+ Effect.gen(function* () {
275
+ const parsed = JSON.parse(yield* readFixture) as {
276
+ smartCompaction: Record<string, unknown>;
277
+ };
278
+ assert.strictEqual(SMART_COMPACTION_KEY in parsed, true);
279
+ assert.strictEqual(ENABLED_KEY in parsed.smartCompaction, true);
280
+ assert.strictEqual(CLASSIFIER_KEY in parsed.smartCompaction, true);
281
+ assert.strictEqual(NEEDS_CONTEXT_PROBABILITY_THRESHOLD_KEY in parsed.smartCompaction, true);
282
+ assert.strictEqual(MIN_ANSWER_CONFIDENCE_KEY in parsed.smartCompaction, true);
283
+ assert.strictEqual(LEGACY_KEEP_CONTEXT_THRESHOLD_KEY in parsed.smartCompaction, false);
284
+ assert.strictEqual(LEGACY_KEEP_CONTEXT_MIN_CONFIDENCE_KEY in parsed.smartCompaction, false);
285
+ assert.strictEqual(MAX_CANDIDATES_KEY in parsed.smartCompaction, true);
286
+ assert.strictEqual(parsed.smartCompaction[ENABLED_KEY], true);
287
+ assert.strictEqual(parsed.smartCompaction[CLASSIFIER_KEY], "typesafe/jev-latest");
288
+ assert.strictEqual(parsed.smartCompaction[NEEDS_CONTEXT_PROBABILITY_THRESHOLD_KEY], 0.5);
289
+ assert.strictEqual(parsed.smartCompaction[MIN_ANSWER_CONFIDENCE_KEY], 0.5);
290
+ assert.strictEqual(parsed.smartCompaction[MAX_CANDIDATES_KEY], 8);
291
+ }),
292
+ );
293
+
294
+ it("parseClassifierIdentity splits provider and model id at the first slash", () => {
295
+ const identity = parseClassifierIdentity("cloudflare-workers-ai/@cf/cloudflare/clef-flash");
296
+ assert.deepStrictEqual(Option.getOrThrow(identity), {
297
+ provider: "cloudflare-workers-ai",
298
+ modelId: "@cf/cloudflare/clef-flash",
299
+ });
300
+ });
301
+
302
+ it("parseClassifierIdentity rejects a value with no provider or no model id", () => {
303
+ assert.strictEqual(Option.isNone(parseClassifierIdentity("jev-latest")), true);
304
+ assert.strictEqual(Option.isNone(parseClassifierIdentity("typesafe/")), true);
305
+ });
306
+
307
+ it.effect("load never writes to the config file", () =>
308
+ Effect.gen(function* () {
309
+ const mem = makeMemFs({ [TEST_PATH]: yield* readFixture });
310
+ const before = mem.files.get(TEST_PATH);
311
+ yield* runWithMem(mem, load());
312
+ assert.deepStrictEqual(mem.writes, []);
313
+ assert.strictEqual(mem.files.get(TEST_PATH), before);
314
+ }),
315
+ );
@@ -0,0 +1,185 @@
1
+ import { Context, Effect, Layer, Option, Predicate, Schema } from "effect";
2
+ import * as FileSystem from "effect/FileSystem";
3
+ import {
4
+ DEFAULT_MIN_ANSWER_CONFIDENCE,
5
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
6
+ type ClassifierIdentity,
7
+ } from "./classifier.ts";
8
+
9
+ /**
10
+ * The tracker's reader of the shared TUI settings file. It owns the
11
+ * interpretation of the five keys that smart compaction uses, and it fails open
12
+ * on every read, parse, or shape problem: the feature is active by default, the
13
+ * classifier preference order applies when no identity is chosen, and the
14
+ * default threshold applies when the value is missing or invalid.
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
+ *
19
+ * Co-owned with `packages/tui/src/config.ts`; the key names and value shapes
20
+ * are pinned by `test-fixtures/tui-config.contract.json`, read by both suites.
21
+ */
22
+ export const SMART_COMPACTION_CONFIG_FILE = "tui.json";
23
+ export const SMART_COMPACTION_KEY = "smartCompaction";
24
+ export const ENABLED_KEY = "enabled";
25
+ export const CLASSIFIER_KEY = "classifier";
26
+ export const NEEDS_CONTEXT_PROBABILITY_THRESHOLD_KEY = "needsContextProbabilityThreshold";
27
+ export const MIN_ANSWER_CONFIDENCE_KEY = "minAnswerConfidence";
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";
33
+
34
+ /** Default number of ready items one classification judges. */
35
+ export const DEFAULT_MAX_CANDIDATES = 8;
36
+ /** Upper bound for the configured cap; a larger value falls back to the default. */
37
+ export const MAX_CANDIDATES_LIMIT = 20;
38
+
39
+ const FileSchema = Schema.fromJsonString(Schema.Unknown);
40
+ const EnabledSchema = Schema.Boolean;
41
+ const ClassifierSchema = Schema.NullOr(Schema.String);
42
+ const UnitIntervalSchema = Schema.Finite;
43
+ const MaxCandidatesSchema = Schema.Int;
44
+
45
+ export interface SmartCompactionSettings {
46
+ readonly enabled: boolean;
47
+ readonly chosen: Option.Option<ClassifierIdentity>;
48
+ readonly needsContextProbabilityThreshold: number;
49
+ readonly minAnswerConfidence: number;
50
+ readonly maxCandidates: number;
51
+ }
52
+
53
+ export const defaultSmartCompactionSettings = (): SmartCompactionSettings => ({
54
+ enabled: true,
55
+ chosen: Option.none(),
56
+ needsContextProbabilityThreshold: DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
57
+ minAnswerConfidence: DEFAULT_MIN_ANSWER_CONFIDENCE,
58
+ maxCandidates: DEFAULT_MAX_CANDIDATES,
59
+ });
60
+
61
+ /**
62
+ * Split a `"provider/modelId"` value at the first slash, so a model id that
63
+ * itself contains slashes — the Cloudflare id `@cf/cloudflare/clef-flash` —
64
+ * stays whole. A value without both parts is not an identity.
65
+ */
66
+ export const parseClassifierIdentity = (value: string): Option.Option<ClassifierIdentity> => {
67
+ const slash = value.indexOf("/");
68
+ if (slash <= 0 || slash === value.length - 1) return Option.none();
69
+ return Option.some({ provider: value.slice(0, slash), modelId: value.slice(slash + 1) });
70
+ };
71
+
72
+ /** The `smartCompaction` object, when the parsed file has one of that shape. */
73
+ const smartSection = (parsed: unknown): Record<string, unknown> | undefined => {
74
+ if (!Predicate.isObject(parsed)) return undefined;
75
+ if (!Predicate.hasProperty(SMART_COMPACTION_KEY)(parsed)) return undefined;
76
+ const section = parsed[SMART_COMPACTION_KEY];
77
+ return Predicate.isObject(section) ? section : undefined;
78
+ };
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
+
102
+ export class SmartCompactionSettingsService extends Context.Service<
103
+ SmartCompactionSettingsService,
104
+ {
105
+ readonly path: string;
106
+ /** Never fails: every read, parse, or shape problem yields the defaults. */
107
+ readonly load: Effect.Effect<SmartCompactionSettings>;
108
+ }
109
+ >()("tracker/SmartCompactionSettings") {
110
+ static make(
111
+ path: string,
112
+ ): Layer.Layer<SmartCompactionSettingsService, never, FileSystem.FileSystem> {
113
+ return Layer.effect(
114
+ SmartCompactionSettingsService,
115
+ Effect.gen(function* () {
116
+ const fs = yield* FileSystem.FileSystem;
117
+ const load = Effect.gen(function* () {
118
+ const raw = yield* fs.readFileString(path);
119
+ // `Schema.Unknown` accepts any JSON value; the guards below narrow it.
120
+ const parsed = yield* Schema.decodeEffect(FileSchema)(raw);
121
+ const section = smartSection(parsed);
122
+ // Each key decodes independently, so an unrecognized value falls back
123
+ // alone instead of discarding the rest of the section.
124
+ const enabled = Option.getOrElse(
125
+ Schema.decodeUnknownOption(EnabledSchema)(
126
+ section === undefined ? undefined : section[ENABLED_KEY],
127
+ ),
128
+ () => true,
129
+ );
130
+ const chosen = Option.flatMap(
131
+ Schema.decodeUnknownOption(ClassifierSchema)(
132
+ section === undefined ? undefined : section[CLASSIFIER_KEY],
133
+ ),
134
+ (value) => (value === null ? Option.none() : parseClassifierIdentity(value)),
135
+ );
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,
143
+ );
144
+ const minAnswerConfidence = readUnitInterval(
145
+ section,
146
+ MIN_ANSWER_CONFIDENCE_KEY,
147
+ LEGACY_KEEP_CONTEXT_MIN_CONFIDENCE_KEY,
148
+ DEFAULT_MIN_ANSWER_CONFIDENCE,
149
+ );
150
+ // The cap must be an integer in [1, MAX_CANDIDATES_LIMIT]; anything
151
+ // else falls back alone.
152
+ const maxCandidates = Option.getOrElse(
153
+ Option.filter(
154
+ Schema.decodeUnknownOption(MaxCandidatesSchema)(
155
+ section === undefined ? undefined : section[MAX_CANDIDATES_KEY],
156
+ ),
157
+ (value) => value >= 1 && value <= MAX_CANDIDATES_LIMIT,
158
+ ),
159
+ () => DEFAULT_MAX_CANDIDATES,
160
+ );
161
+ return {
162
+ enabled,
163
+ chosen,
164
+ needsContextProbabilityThreshold,
165
+ minAnswerConfidence,
166
+ maxCandidates,
167
+ } satisfies SmartCompactionSettings;
168
+ }).pipe(
169
+ Effect.catchCause(() =>
170
+ Effect.logWarning("tracker: smart-compaction settings unreadable, using defaults").pipe(
171
+ Effect.as(defaultSmartCompactionSettings()),
172
+ ),
173
+ ),
174
+ );
175
+ return SmartCompactionSettingsService.of({ path, load });
176
+ }),
177
+ );
178
+ }
179
+
180
+ static readonly layerTest = (
181
+ path: string,
182
+ fileSystem: Partial<FileSystem.FileSystem>,
183
+ ): Layer.Layer<SmartCompactionSettingsService> =>
184
+ SmartCompactionSettingsService.make(path).pipe(Layer.provide(FileSystem.layerNoop(fileSystem)));
185
+ }