@ftrdotdev/pi-tracker 0.6.0 → 0.8.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 (36) hide show
  1. package/README.md +183 -60
  2. package/package.json +23 -11
  3. package/src/compaction/candidate.test.ts +9 -6
  4. package/src/compaction/candidate.ts +32 -2
  5. package/src/compaction/classifier.test.ts +67 -60
  6. package/src/compaction/classifier.ts +24 -22
  7. package/src/compaction/completion.test.ts +127 -49
  8. package/src/compaction/completion.ts +1 -3
  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 +104 -9
  12. package/src/compaction/digest.ts +96 -9
  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/rules.test.ts +253 -0
  18. package/src/compaction/rules.ts +188 -0
  19. package/src/compaction/settings.test.ts +105 -49
  20. package/src/compaction/settings.ts +53 -31
  21. package/src/compaction/settle.test.ts +370 -0
  22. package/src/compaction/settle.ts +109 -53
  23. package/src/core/deps.test.ts +1 -1
  24. package/src/core/domain.test.ts +42 -9
  25. package/src/core/domain.ts +73 -8
  26. package/src/core/persistence.test.ts +7 -7
  27. package/src/core/store.test.ts +116 -50
  28. package/src/core/store.ts +92 -31
  29. package/src/index.test.ts +209 -68
  30. package/src/index.ts +170 -48
  31. package/src/presentation/tool-metadata.test.ts +263 -48
  32. package/src/presentation/tool-metadata.ts +325 -102
  33. package/src/presentation/ui.test.ts +122 -7
  34. package/src/presentation/ui.ts +81 -18
  35. package/src/presentation/vim-settings.test.ts +98 -0
  36. package/src/presentation/vim-settings.ts +59 -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
+ });
@@ -7,15 +7,20 @@ import {
7
7
  CLASSIFIER_KEY,
8
8
  DEFAULT_MAX_CANDIDATES,
9
9
  ENABLED_KEY,
10
- KEEP_CONTEXT_MIN_CONFIDENCE_KEY,
11
- KEEP_CONTEXT_THRESHOLD_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,
12
14
  MAX_CANDIDATES_KEY,
13
15
  SMART_COMPACTION_KEY,
14
16
  SmartCompactionSettingsService,
15
17
  parseClassifierIdentity,
16
18
  type SmartCompactionSettings,
17
19
  } from "./settings.ts";
18
- import { DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE, DEFAULT_KEEP_CONTEXT_THRESHOLD } from "./classifier.ts";
20
+ import {
21
+ DEFAULT_MIN_ANSWER_CONFIDENCE,
22
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
23
+ } from "./classifier.ts";
19
24
 
20
25
  const TEST_PATH = "/tmp/tracker-settings-test/tui.json";
21
26
  const FIXTURE_PATH = fileURLToPath(
@@ -61,11 +66,7 @@ function makeMemFs(init: Record<string, string> = {}): MemFs {
61
66
  return { fs, files, writes };
62
67
  }
63
68
 
64
- const load = (): Effect.Effect<
65
- SmartCompactionSettings,
66
- never,
67
- SmartCompactionSettingsService
68
- > =>
69
+ const load = (): Effect.Effect<SmartCompactionSettings, never, SmartCompactionSettingsService> =>
69
70
  Effect.gen(function* () {
70
71
  const service = yield* SmartCompactionSettingsService;
71
72
  return yield* service.load;
@@ -83,7 +84,10 @@ it.effect("load returns the fail-open defaults when the file is missing", () =>
83
84
  const settings = yield* runWithMem(mem, load());
84
85
  assert.strictEqual(settings.enabled, true);
85
86
  assert.strictEqual(Option.isNone(settings.chosen), true);
86
- assert.strictEqual(settings.keepContextThreshold, DEFAULT_KEEP_CONTEXT_THRESHOLD);
87
+ assert.strictEqual(
88
+ settings.needsContextProbabilityThreshold,
89
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
90
+ );
87
91
  }),
88
92
  );
89
93
 
@@ -93,7 +97,10 @@ it.effect("load returns the fail-open defaults when the file is not JSON", () =>
93
97
  const settings = yield* runWithMem(mem, load());
94
98
  assert.strictEqual(settings.enabled, true);
95
99
  assert.strictEqual(Option.isNone(settings.chosen), true);
96
- assert.strictEqual(settings.keepContextThreshold, DEFAULT_KEEP_CONTEXT_THRESHOLD);
100
+ assert.strictEqual(
101
+ settings.needsContextProbabilityThreshold,
102
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
103
+ );
97
104
  }),
98
105
  );
99
106
 
@@ -103,7 +110,10 @@ it.effect("load returns the fail-open defaults when the section has the wrong sh
103
110
  const settings = yield* runWithMem(mem, load());
104
111
  assert.strictEqual(settings.enabled, true);
105
112
  assert.strictEqual(Option.isNone(settings.chosen), true);
106
- assert.strictEqual(settings.keepContextThreshold, DEFAULT_KEEP_CONTEXT_THRESHOLD);
113
+ assert.strictEqual(
114
+ settings.needsContextProbabilityThreshold,
115
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
116
+ );
107
117
  }),
108
118
  );
109
119
 
@@ -120,59 +130,103 @@ it.effect("load ignores an unrecognized enabled value and keeps a valid chosen c
120
130
  provider: "typesafe",
121
131
  modelId: "jev-latest",
122
132
  });
123
- assert.strictEqual(settings.keepContextThreshold, DEFAULT_KEEP_CONTEXT_THRESHOLD);
133
+ assert.strictEqual(
134
+ settings.needsContextProbabilityThreshold,
135
+ DEFAULT_NEEDS_CONTEXT_PROBABILITY_THRESHOLD,
136
+ );
124
137
  }),
125
138
  );
126
139
 
127
- it.effect("load reads a valid keep-context threshold from the section", () =>
140
+ it.effect("load reads a valid needs-context probability threshold from the section", () =>
128
141
  Effect.gen(function* () {
129
142
  const mem = makeMemFs({
130
- [TEST_PATH]: JSON.stringify({ smartCompaction: { keepContextThreshold: 0.72 } }),
143
+ [TEST_PATH]: JSON.stringify({ smartCompaction: { needsContextProbabilityThreshold: 0.72 } }),
131
144
  });
132
145
  const settings = yield* runWithMem(mem, load());
133
- assert.strictEqual(settings.keepContextThreshold, 0.72);
146
+ assert.strictEqual(settings.needsContextProbabilityThreshold, 0.72);
134
147
  }),
135
148
  );
136
149
 
137
- it.effect("load falls back alone when a threshold is outside the open unit interval", () =>
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", () =>
138
172
  Effect.gen(function* () {
139
- for (const invalid of [0, 1, -0.1, 1.5, "0.5"]) {
140
- const mem = makeMemFs({
141
- [TEST_PATH]: JSON.stringify({
142
- smartCompaction: { enabled: false, keepContextThreshold: invalid },
143
- }),
144
- });
145
- const settings = yield* runWithMem(mem, load());
146
- assert.strictEqual(settings.keepContextThreshold, DEFAULT_KEEP_CONTEXT_THRESHOLD);
147
- // The bad value must not discard the rest of the section.
148
- assert.strictEqual(settings.enabled, false);
149
- }
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);
150
178
  }),
151
179
  );
152
180
 
153
- it.effect("load reads a valid keep-context min confidence from the section", () =>
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", () =>
154
200
  Effect.gen(function* () {
155
201
  const mem = makeMemFs({
156
- [TEST_PATH]: JSON.stringify({ smartCompaction: { keepContextMinConfidence: 0.72 } }),
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
+ }),
157
208
  });
158
209
  const settings = yield* runWithMem(mem, load());
159
- assert.strictEqual(settings.keepContextMinConfidence, 0.72);
210
+ assert.strictEqual(settings.needsContextProbabilityThreshold, 0.72);
211
+ assert.strictEqual(settings.minAnswerConfidence, 0.31);
160
212
  }),
161
213
  );
162
214
 
163
- it.effect("load falls back alone when the min confidence is outside the open unit interval", () =>
215
+ it.effect("load prefers the current probability keys over their legacy aliases", () =>
164
216
  Effect.gen(function* () {
165
- for (const invalid of [0, 1, -0.1, 1.5, "0.5"]) {
166
- const mem = makeMemFs({
167
- [TEST_PATH]: JSON.stringify({
168
- smartCompaction: { enabled: false, keepContextMinConfidence: invalid },
169
- }),
170
- });
171
- const settings = yield* runWithMem(mem, load());
172
- assert.strictEqual(settings.keepContextMinConfidence, DEFAULT_KEEP_CONTEXT_MIN_CONFIDENCE);
173
- // The bad value must not discard the rest of the section.
174
- assert.strictEqual(settings.enabled, false);
175
- }
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);
176
230
  }),
177
231
  );
178
232
 
@@ -210,13 +264,13 @@ it.effect("load resolves every value from the shared contract fixture", () =>
210
264
  provider: "typesafe",
211
265
  modelId: "jev-latest",
212
266
  });
213
- assert.strictEqual(settings.keepContextThreshold, 0.5);
214
- assert.strictEqual(settings.keepContextMinConfidence, 0.5);
267
+ assert.strictEqual(settings.needsContextProbabilityThreshold, 0.5);
268
+ assert.strictEqual(settings.minAnswerConfidence, 0.5);
215
269
  assert.strictEqual(settings.maxCandidates, 8);
216
270
  }),
217
271
  );
218
272
 
219
- it.effect("load reads the enabled, classifier, and threshold keys the contract names", () =>
273
+ it.effect("load reads the enabled, classifier, and probability keys the contract names", () =>
220
274
  Effect.gen(function* () {
221
275
  const parsed = JSON.parse(yield* readFixture) as {
222
276
  smartCompaction: Record<string, unknown>;
@@ -224,13 +278,15 @@ it.effect("load reads the enabled, classifier, and threshold keys the contract n
224
278
  assert.strictEqual(SMART_COMPACTION_KEY in parsed, true);
225
279
  assert.strictEqual(ENABLED_KEY in parsed.smartCompaction, true);
226
280
  assert.strictEqual(CLASSIFIER_KEY in parsed.smartCompaction, true);
227
- assert.strictEqual(KEEP_CONTEXT_THRESHOLD_KEY in parsed.smartCompaction, true);
228
- assert.strictEqual(KEEP_CONTEXT_MIN_CONFIDENCE_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);
229
285
  assert.strictEqual(MAX_CANDIDATES_KEY in parsed.smartCompaction, true);
230
286
  assert.strictEqual(parsed.smartCompaction[ENABLED_KEY], true);
231
287
  assert.strictEqual(parsed.smartCompaction[CLASSIFIER_KEY], "typesafe/jev-latest");
232
- assert.strictEqual(parsed.smartCompaction[KEEP_CONTEXT_THRESHOLD_KEY], 0.5);
233
- assert.strictEqual(parsed.smartCompaction[KEEP_CONTEXT_MIN_CONFIDENCE_KEY], 0.5);
288
+ assert.strictEqual(parsed.smartCompaction[NEEDS_CONTEXT_PROBABILITY_THRESHOLD_KEY], 0.5);
289
+ assert.strictEqual(parsed.smartCompaction[MIN_ANSWER_CONFIDENCE_KEY], 0.5);
234
290
  assert.strictEqual(parsed.smartCompaction[MAX_CANDIDATES_KEY], 8);
235
291
  }),
236
292
  );
@@ -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(