opencode-self-improvement 0.24.2 → 0.26.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.
@@ -6,6 +6,7 @@ import { session, setCurrent } from "../core/state.ts";
6
6
  import {
7
7
  AUTO_CAPTURE_TAG,
8
8
  CODE_CHECKED_TAG,
9
+ RESTATABLE_TAG,
9
10
  USER_GUIDED_TAG,
10
11
  } from "../core/tags.ts";
11
12
  import { record, recordCaptureLag } from "../evidence/record.ts";
@@ -22,6 +23,7 @@ import {
22
23
  import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
23
24
  import { flattenMemoryText } from "../store/sanitize.ts";
24
25
  import { redactSecrets } from "../store/secrets.ts";
26
+ import { type AvailabilityIndex, availabilityIndex } from "./available.ts";
25
27
  import { parseCandidates, parseModelRef } from "./candidates.ts";
26
28
  import { claimVerdictFromContent } from "./checked.ts";
27
29
  import {
@@ -235,30 +237,102 @@ export function configureAutoCapture(
235
237
  // gate receipts, promoted rows, supersession. The contract is bounded
236
238
  // and explicit:
237
239
  // 1. cleanup aborts the subscription, so no NEW pass starts;
238
- // 2. every pass checks the signal after the model call and between
239
- // candidates, and stops BEFORE the next gate run — a gate already
240
- // mutating is never cut in half, because a half-applied gate is
240
+ // 2. every pass checks its own abandonment flag after the model call and
241
+ // between candidates, and stops BEFORE the next gate run — a gate
242
+ // already mutating is never cut in half, because a half-applied gate is
241
243
  // worse than a late one;
242
244
  // 3. cleanup then drains the tracked passes up to DRAIN_LIMIT_MS, so
243
245
  // a caller that removes the store right after cleanup sees nothing
244
- // straggling. A generate that outlives the bound is covered by (2),
245
- // not by the drain: teardown never waits on the model.
246
+ // straggling. A pass still working when the bound expires is abandoned
247
+ // there and then, so it stops at its next candidate boundary; a
248
+ // generate that outlives the bound is covered by (2), not by the
249
+ // drain: teardown never waits on the model.
250
+ //
251
+ // #404 changed (2) from one signal into two phases, because one signal
252
+ // conflated two different situations and the conflation killed the feature
253
+ // on the CLI. A pass PARKED in `generate.text` when the host disposes must
254
+ // never write — that is #211, and the caller may remove the store the
255
+ // moment cleanup resolves. A pass that already HOLDS its model answer is
256
+ // different work: the answer exists, the gate is milliseconds of local
257
+ // work, and on `opencode run` nothing is being removed at all — the process
258
+ // simply exits. Aborting that pass is why most real CLI passes recorded
259
+ // `capture_cost` and no row — 9 of 12 in one sample, 6 of 12 in a
260
+ // controlled A/B (#404): the abort fired on the healthy path, in the only
261
+ // window capture is allowed to run. Past-model passes are bounded by the
262
+ // drain instead, which is what the drain is for.
246
263
  const DRAIN_LIMIT_MS = 1000;
264
+ type PassPhase = {
265
+ /** Set the instant `generate.text` resolves. */
266
+ pastModel: boolean;
267
+ /** Set by cleanup, and only for a pass that has not answered yet. */
268
+ abandoned: boolean;
269
+ };
247
270
  const inFlight = new Set<Promise<unknown>>();
248
- function track<T>(pass: Promise<T>): Promise<T> {
249
- const wrapped = pass.finally(() => inFlight.delete(wrapped));
271
+ const passPhases = new Set<PassPhase>();
272
+ function newPhase(): PassPhase {
273
+ return { pastModel: false, abandoned: false };
274
+ }
275
+ function track<T>(pass: Promise<T>, phase?: PassPhase): Promise<T> {
276
+ const wrapped = pass.finally(() => {
277
+ inFlight.delete(wrapped);
278
+ if (phase) passPhases.delete(phase);
279
+ });
280
+ if (phase) passPhases.add(phase);
250
281
  inFlight.add(wrapped);
251
282
  return wrapped;
252
283
  }
284
+ /**
285
+ * Teardown, in two phases (#404).
286
+ *
287
+ * 1. Abandon every pass that has not answered yet, then drain what is
288
+ * left, bounded. A parked `generate.text` can outlive any bound, so
289
+ * abandoning it is what makes the bound mean something: #211's caller
290
+ * may remove the store the moment cleanup resolves.
291
+ * 2. A pass that already holds its answer is never abandoned. It is
292
+ * drained instead, because its remaining work is the gate — local,
293
+ * milliseconds — and killing it is what lost most real CLI captures
294
+ * (#404: 9 of 12 in one sample, 6 of 12 in a controlled A/B).
295
+ *
296
+ * The residual risk is a stated constant, not an accident. If the bound
297
+ * expires while a past-model pass is still working, cleanup returns and at
298
+ * most the gate run already in progress can land afterwards — the drain
299
+ * abandons the pass so its remaining candidates stop at the next boundary.
300
+ * Before #404 that residual was unbounded in a different way: a generate
301
+ * that outlived the bound woke up and ran the whole gate, which is what
302
+ * #211 was filed about. Neither version ever cuts a gate in half.
303
+ *
304
+ * Nothing here writes. #211's tested contract is that a disposed instance
305
+ * leaves no trace at all after cleanup, and an abandonment receipt would
306
+ * break it in all four of that issue's cases — `appendLog` calls
307
+ * `ensureDir`, so the receipt resurrects a directory the caller deleted.
308
+ * An abandoned pass is instead identified by the gap it leaves: a
309
+ * `capture_cost` line with no later `capture_lag` for the same session is
310
+ * a pass that was cut, and both lines are already written.
311
+ */
253
312
  async function drainInFlight(): Promise<void> {
313
+ for (const phase of passPhases) {
314
+ if (!phase.pastModel) phase.abandoned = true;
315
+ }
254
316
  if (!inFlight.size) return;
317
+ let timedOut = false;
255
318
  let timer: ReturnType<typeof setTimeout> | undefined;
256
319
  const bound = new Promise<void>((resolve) => {
257
- timer = setTimeout(resolve, DRAIN_LIMIT_MS);
320
+ timer = setTimeout(() => {
321
+ timedOut = true;
322
+ resolve();
323
+ }, DRAIN_LIMIT_MS);
258
324
  });
259
325
  await Promise.race([Promise.allSettled([...inFlight]), bound]).finally(
260
326
  () => clearTimeout(timer),
261
327
  );
328
+ // The bound expired, so cleanup is returning while a pass still works.
329
+ // Abandon it now: it is past the model, so it may not be stopped inside a
330
+ // gate run, but it stops at the next candidate boundary instead of
331
+ // running an unbounded list against a process that is on its way out.
332
+ // That makes the residual risk a stated constant — at most the one gate
333
+ // run already in progress can land after cleanup returns — rather than a
334
+ // function of how many candidates the model returned.
335
+ if (timedOut) for (const phase of passPhases) phase.abandoned = true;
262
336
  }
263
337
  const eventApi = ctx.event;
264
338
  const generateApi = ctx.generate;
@@ -328,6 +402,14 @@ export function configureAutoCapture(
328
402
  // cannot re-stamp this operation's receipts. Optional for direct
329
403
  // callers, which bind here instead.
330
404
  gate?: GateContext,
405
+ // Teardown phase, owned by the caller that `track()`s this pass. Both
406
+ // production triggers pass one. The default is for direct callers —
407
+ // tests, and any future seam that runs a pass outside the subscription —
408
+ // and reads "not drainable, so not abandonable": an untracked pass is
409
+ // not in `inFlight`, so cleanup could neither wait for it nor stop it
410
+ // safely, and killing work the drain cannot bound is the failure mode
411
+ // this parameter exists to avoid.
412
+ phase: PassPhase = { pastModel: true, abandoned: false },
331
413
  ): Promise<void> {
332
414
  const captureGate = gate ?? bindCapture(sid);
333
415
  const captureReader = captureGate.reader ?? readerFromSid(sid);
@@ -539,13 +621,17 @@ export function configureAutoCapture(
539
621
  model,
540
622
  prompt: capturePrompt,
541
623
  });
624
+ // The phase boundary. From here the answer exists, so cleanup stops
625
+ // abandoning this pass and drains it instead (#404). Set before the next
626
+ // await, so a disposal during anything below cannot be missed.
627
+ phase.pastModel = true;
542
628
  const text = typeof out === "string" ? out : (out?.text ?? "");
543
- // #211: disposed while the model call was in flight. Stop here — the
629
+ // #211: abandoned while the model call was in flight. Stop here — the
544
630
  // gate, the rows and the receipts below all write to a store the
545
631
  // caller may already have removed. Silent on purpose: a receipt here
546
632
  // is the ENOENT teardown noise this check exists to eliminate, and
547
633
  // the drain in cleanup means the pass is finished, not lost mid-air.
548
- if (controller.signal.aborted) return;
634
+ if (phase.abandoned) return;
549
635
  // #387: bill our own call. `generate.text` resolves to `{ text }` and
550
636
  // nothing else — no `usage`, no `tokens` (probed against the running
551
637
  // host) — and capture is not part of any session's event stream, so a
@@ -656,6 +742,31 @@ export function configureAutoCapture(
656
742
  c.original = undefined;
657
743
  }
658
744
  }
745
+ // #389: availability before authority. A candidate that restates a
746
+ // tracked file, or names a command the project already declares, is
747
+ // readable by the next session without a row — and capture costs about a
748
+ // third of a session's own generation.
749
+ //
750
+ // #402 P0: built on FIRST USE, not on every pass. The build is a
751
+ // synchronous `git ls-files` plus a read of every tracked text file —
752
+ // measured here at 108 ms for 218 files and 2.11 MB — and the pass that
753
+ // needs it least is the one that used to pay for it: a model answer of
754
+ // `[]` still scanned the tree. One build per pass is kept, so the cost is
755
+ // now bounded by the candidates that exist.
756
+ let availableIndex: AvailabilityIndex | undefined;
757
+ let availableMs = 0;
758
+ const availability = (): AvailabilityIndex => {
759
+ if (!availableIndex) {
760
+ const t0 = Date.now();
761
+ availableIndex = availabilityIndex(
762
+ captureReader.kind === "repo"
763
+ ? captureReader.scope.path
764
+ : undefined,
765
+ );
766
+ availableMs = Date.now() - t0;
767
+ }
768
+ return availableIndex;
769
+ };
659
770
  // S1 (learn-from-failure): a row that CITES a failing command is
660
771
  // claiming to be a lesson, and the claim is checked against the ledger,
661
772
  // not against the model's retelling. ReMe (Findings ACL 2026) found
@@ -672,6 +783,15 @@ export function configureAutoCapture(
672
783
  // recall loss here.
673
784
  let lessonsKept = 0;
674
785
  let lessonsRefused = 0;
786
+ // #402: rows tagged `restatable` this pass. Counted, never dropped.
787
+ // Two numbers, because they are two different facts and one field that
788
+ // silently means "verdicts" reads as "rows" (#403 review round 1). A
789
+ // verdict lands on candidates the write gate then refuses — a dup, a
790
+ // credential-shaped scope — and a refused row carries no tag, so the
791
+ // verdict count is an upper bound on the tagged count, never equal by
792
+ // construction.
793
+ let availVerdicts = 0;
794
+ let restatements = 0;
675
795
  candidates = candidates.filter((c) => {
676
796
  if (c.failure === undefined) return true;
677
797
  const cite = normWs(c.failure).toLowerCase();
@@ -699,8 +819,67 @@ export function configureAutoCapture(
699
819
  );
700
820
  for (const c of candidates) {
701
821
  // Between candidates, never inside a gate run: a supersession that
702
- // half-applied is a store the next session cannot trust.
703
- if (controller.signal.aborted) return;
822
+ // half-applied is a store the next session cannot trust. The phase
823
+ // flag, not the signal: this loop only runs once the answer exists,
824
+ // and cleanup stops abandoning such a pass (#404).
825
+ if (phase.abandoned) return;
826
+ // #402: the availability verdict TAGS the row. It used to `continue`
827
+ // past the write, and that is the defect #402 exists for. A lexical
828
+ // match was never strong enough to delete a fact — 29 of the 30 rows
829
+ // the first version refused were new facts, and a silently dropped
830
+ // candidate leaves no trace to recover from.
831
+ //
832
+ // The row now goes through the same write gate as every other row, and
833
+ // the tag is what retrieval acts on: `restatable` rows sort last, so a
834
+ // full injection block gives them up first and a spare one keeps them.
835
+ // A wrong verdict costs one row. A right one saves a slot. That is the
836
+ // first version of this where the two error directions are both
837
+ // survivable, which is why four rounds of patches could not produce it.
838
+ const avail = availability().check(c.content);
839
+ if (avail) {
840
+ availVerdicts++;
841
+ await record(
842
+ "auto_capture_restatable",
843
+ {
844
+ session: sid,
845
+ trigger,
846
+ type: c.type,
847
+ scope: redactSecrets(c.scope),
848
+ reason: avail.reason,
849
+ where: avail.where,
850
+ // `matched` is a slice of the CANDIDATE, not of the tree, so it
851
+ // carries model prose too: measured, `Ship with \`npm run deploy\`.<NUL>`
852
+ // yields `matched` ending in the NUL. Flattened for the reason
853
+ // below.
854
+ matched: flattenMemoryText(avail.matched),
855
+ // The whole candidate, so the audit line alone can rebuild a row
856
+ // a later consolidation drops. It records the VERDICT, not proof
857
+ // of storage: this line is written before the gate, so a
858
+ // candidate the gate then refuses has one and no row. The row's
859
+ // fate is the adjacent `auto_capture_<action>` line, same pass,
860
+ // same type and scope; `restatements` on the scan line counts
861
+ // only rows that were really tagged.
862
+ //
863
+ // Both free-text fields here are flattened, which nothing else on
864
+ // this path does: `candidates.ts` checks type and scope for control
865
+ // characters but not content, `scrubFields` only redacts
866
+ // credentials, and the logfmt writer escapes `\ " \n \r \t` and
867
+ // nothing else. Without this, a NUL or U+2028 from model prose
868
+ // lands raw in the day log and `memory_evidence` hands it straight
869
+ // back to a model. Redact FIRST: flattening a PEM body would break
870
+ // the pattern that recognises it. The systemic version — flattening
871
+ // every string field in `scrubFields` — is deliberately NOT done
872
+ // here, because it would change the meaning of existing audit
873
+ // lines that carry multi-line values.
874
+ content: flattenMemoryText(redactSecrets(c.content)),
875
+ ...(c.guided ? { guided: true } : {}),
876
+ ...(modelTag ? { model: modelTag } : {}),
877
+ },
878
+ false,
879
+ sid,
880
+ captureGate.evidenceContext,
881
+ );
882
+ }
704
883
  // #393 AC 2: a numeric claim capture INFERRED (the user did not state
705
884
  // it) that names a constant the tree also names is checked before it
706
885
  // is stored. Only a contradiction refuses; "undecidable" is the
@@ -753,6 +932,8 @@ export function configureAutoCapture(
753
932
  ...(original ? { original } : {}),
754
933
  tags: [
755
934
  AUTO_CAPTURE_TAG,
935
+ // #402: the tree states this too. Stored anyway, sorted last.
936
+ ...(avail ? [RESTATABLE_TAG] : []),
756
937
  // #393: the ONE case that earns `[code-checked]` — an inferred
757
938
  // numeric claim that agreed with the tree. Absent everywhere
758
939
  // else, which is what makes `[unverified]` mean something
@@ -784,6 +965,10 @@ export function configureAutoCapture(
784
965
  );
785
966
  continue;
786
967
  }
968
+ // The tag exists only on a row the gate really wrote. `blocked` writes
969
+ // nothing and `collapsed` folds into an existing row whose tags are not
970
+ // these, so only `promoted` can carry `restatable` into the store.
971
+ if (avail && outcome.action === "promoted") restatements++;
787
972
  await record(
788
973
  trigger === "compaction"
789
974
  ? `auto_capture_compaction_${outcome.action}`
@@ -837,6 +1022,35 @@ export function configureAutoCapture(
837
1022
  }
838
1023
  }
839
1024
  }
1025
+ // #402 P0: the scan is now visible in the trail. `scanned()` shipped
1026
+ // "for evidence" and was never called, so a synchronous tree read ran
1027
+ // every pass with no record that it happened. One line per pass that
1028
+ // actually built the index, naming files, bytes and milliseconds.
1029
+ if (availableIndex) {
1030
+ const scan = availableIndex.scanned();
1031
+ await record(
1032
+ "auto_capture_scan",
1033
+ {
1034
+ session: sid,
1035
+ trigger,
1036
+ files: scan.files,
1037
+ bytes: scan.bytes,
1038
+ ms: availableMs,
1039
+ tracked: scan.tracked,
1040
+ capped: scan.capped,
1041
+ // Two numbers on purpose: `verdicts` is how many candidates the
1042
+ // check matched, `restatements` how many rows carry the tag. They
1043
+ // differ exactly by the verdicts the write gate refused, and a
1044
+ // reader who sees one number will assume it is the other.
1045
+ verdicts: availVerdicts,
1046
+ restatements,
1047
+ ...(modelTag ? { model: modelTag } : {}),
1048
+ },
1049
+ false,
1050
+ sid,
1051
+ captureGate.evidenceContext,
1052
+ );
1053
+ }
840
1054
  await recordCaptureLag(
841
1055
  sid,
842
1056
  lagMs,
@@ -884,9 +1098,15 @@ export function configureAutoCapture(
884
1098
  // another repository; resolving it there would stamp the failure
885
1099
  // receipt of repo A's capture as repo B's evidence.
886
1100
  let opGate: GateContext | undefined;
1101
+ // Created before the first await so cleanup can see this pass in the
1102
+ // window before the model call, where #211 still applies in full.
1103
+ const phase = newPhase();
887
1104
  try {
888
1105
  opGate = bindCapture(sid);
889
- await track(captureSession(sid, "", "idle", undefined, opGate));
1106
+ await track(
1107
+ captureSession(sid, "", "idle", undefined, opGate, phase),
1108
+ phase,
1109
+ );
890
1110
  } catch (err) {
891
1111
  // Teardown is not a capture failure: after cleanup the store may
892
1112
  // be gone, and a receipt here would be the ENOENT noise #211
@@ -916,6 +1136,10 @@ export function configureAutoCapture(
916
1136
  }
917
1137
  })();
918
1138
  captureCleanup = async () => {
1139
+ // The signal stops NEW passes (the subscription checks it before
1140
+ // dispatch, and the compaction seam checks it before starting). Passes
1141
+ // already started are handled by drainInFlight in two phases: abandon
1142
+ // the unanswered ones, drain the answered ones (#404).
919
1143
  controller.abort();
920
1144
  await drainInFlight();
921
1145
  };
@@ -936,6 +1160,7 @@ export function configureAutoCapture(
936
1160
  const opGate = bindCapture(sid);
937
1161
  // Tracked, not just fired: cleanup must be able to drain this pass
938
1162
  // (#211), which is the only reason the seam keeps the promise.
1163
+ const phase = newPhase();
939
1164
  void track(
940
1165
  // The predicate, not just the checks inside the pass: a rejection
941
1166
  // from the awaited model call skips every abort check that follows
@@ -950,9 +1175,11 @@ export function configureAutoCapture(
950
1175
  "compaction",
951
1176
  messages,
952
1177
  opGate,
1178
+ phase,
953
1179
  ),
954
1180
  () => !controller.signal.aborted,
955
1181
  ),
1182
+ phase,
956
1183
  );
957
1184
  };
958
1185
  }
@@ -1,3 +1,5 @@
1
+ import { RESTATABLE_TAG } from "./tags.ts";
2
+
1
3
  /** Capture-only provenance: grants always-ride priority in the hint channel. */
2
4
  export const USER_GUIDED_TAG = "user-guided";
3
5
 
@@ -5,9 +7,29 @@ export const USER_GUIDED_TAG = "user-guided";
5
7
  * Tool/import input cannot grant capture provenance. Split the storage
6
8
  * delimiter first: ["ordinary,user-guided"] reads back as two tags too.
7
9
  * Silently drop the reserved tag; ordinary prose still faces the write gate.
10
+ *
11
+ * `restatable` is dropped for the same reason it cannot be granted: it is a
12
+ * verdict about a SPECIFIC prose against a SPECIFIC working tree, and neither
13
+ * survives these paths.
14
+ *
15
+ * - `tools/update.ts` carries the target's tags onto the replacement row. A
16
+ * user correcting a restatable row would otherwise leave the corrected prose
17
+ * demoted in injection forever, on a verdict that described the superseded
18
+ * text — the one case where the demotion is guaranteed wrong rather than
19
+ * merely possible.
20
+ * - `portable/import.ts` moves a row between machines. The tag asserts "THIS
21
+ * tree states it"; an imported row keeps another machine's verdict and is
22
+ * demoted against a tree that was never scanned.
23
+ *
24
+ * A row that is genuinely restatable gets the tag again from the next capture
25
+ * pass, so dropping it costs a demotion and never a fact.
26
+ *
27
+ * The viewer's edit path deliberately does NOT go through here: #129 keeps tag
28
+ * provenance across a typo fix, where the verdict still describes the prose, and
29
+ * a human can clear the tag by hand.
8
30
  */
9
31
  export function nonCaptureTags(tags?: string[]): string[] | undefined {
10
32
  return tags
11
33
  ?.flatMap((tag) => tag.split(","))
12
- .filter((tag) => tag !== USER_GUIDED_TAG);
34
+ .filter((tag) => tag !== USER_GUIDED_TAG && tag !== RESTATABLE_TAG);
13
35
  }
package/src/core/tags.ts CHANGED
@@ -1,6 +1,20 @@
1
1
  /** Auto-capture provenance, shared by capture and retrieval. */
2
2
  export const AUTO_CAPTURE_TAG = "auto-capture";
3
3
 
4
+ /**
5
+ * #402: the working tree already states this fact, so the next session can read
6
+ * it there. Captured from #389's availability check, which used to DROP these
7
+ * candidates. Measured on this repo's store, that check refused 0 of 1166 real
8
+ * rows after four review rounds, and the version before it refused 30 of which
9
+ * 29 were wrong — so the verdict is a tag now, and a wrong match costs a tag
10
+ * instead of a fact.
11
+ *
12
+ * Retrieval sorts these rows last within their score band: a restatement is the
13
+ * first thing to give up budget when the block is full, and the last thing worth
14
+ * a slot when it is not.
15
+ */
16
+ export const RESTATABLE_TAG = "restatable";
17
+
4
18
  /**
5
19
  * #393: a capture candidate whose numeric claim was CHECKED against the working
6
20
  * tree and agreed. Absent on every other row, which is what makes the injected
@@ -0,0 +1,182 @@
1
+ // Near-duplicate suppression inside a returned window (#409, RESULTS §17).
2
+ //
3
+ // The live store carries repeated rows — superseded snapshots, cursor rows that
4
+ // differ only by a timestamp, the same decision restated after a compaction —
5
+ // and the matcher scores them all the same. With a fixed window they crowd out
6
+ // distinct facts, which is what breaks composition: two memories a later task
7
+ // needs together rarely fit side by side because the first one's copies take
8
+ // the slots.
9
+ //
10
+ // The fix is one deterministic pass AFTER ranking: skip any candidate whose
11
+ // content-token Jaccard against an already-kept row of the same scope reaches
12
+ // the threshold, keeping the NEWEST copy of a clash (§17's adoption rule: the
13
+ // live duplicates are stale cursors and superseded snapshots, so the row that
14
+ // survives is the one written last, not the one that ranked highest). No model,
15
+ // no new index, and nothing changes unless the flag is set:
16
+ //
17
+ // OPENCODE_MEMORY_DEDUP=0.8 (unset or 0 = shipped behavior, byte-identical)
18
+ //
19
+ // Threshold guidance from the live replay (§17): 0.5-0.7 suppresses rows that
20
+ // are merely related (92% of them at 0.5) and forces the window deep into the
21
+ // ranking; 0.8 suppresses only near-identical copies. Values below 0.5 are a
22
+ // misconfiguration, not an aggressive setting: at Jaccard 1e-9 a single shared
23
+ // fragment suppressed rows, so anything under 0.5 turns the pass off.
24
+ //
25
+ // WHAT COUNTS AS A NEAR-COPY — the first version's three mistakes, each pinned
26
+ // by a test:
27
+ //
28
+ // 1. It scored `type` and `scope` as tokens. Same-scope rows then shared two
29
+ // free tokens, so short rows looked like copies of each other. Comparison is
30
+ // content-only.
31
+ // 2. It compared whole token sets, so a prohibition read as a copy of the
32
+ // permission it denies: "force push main" inside "never force push main"
33
+ // reaches Jaccard 0.833, and at threshold 0.8 the WRONG copy survived. If
34
+ // exactly one row of a pair carries a negation word, it is not a copy.
35
+ // 3. It had no floor. Non-Latin prose tokenises to nothing under `words()`
36
+ // (which splits on [^a-z0-9_]+), so two unrelated Chinese rows in one scope
37
+ // both reduced to the empty content set — Jaccard over empty sets is
38
+ // defined here as 0, but the pre-floor version scored them on type and
39
+ // scope alone at 1.0 and deleted the second row. A row with fewer than
40
+ // MIN_CONTENT content tokens is never suppressed: there is nothing to
41
+ // compare.
42
+ // 4. It treated differing numeric facts as duplicates. `words()` drops tokens
43
+ // of length <= 2, so "Rate limiter reads Redis DB 3." and "...DB 4." have
44
+ // identical token sets (Jaccard 1) and the older row was suppressed even at
45
+ // threshold 1 (review #415, reproduced through the handler). Numbers are
46
+ // compared as a sorted multiset of literals and a pair that disagrees on
47
+ // them is never a copy.
48
+ import type { Memory } from "../store/model/memory.ts";
49
+ import { haystack, words } from "./score.ts";
50
+
51
+ export const DEDUPE_ENV = "OPENCODE_MEMORY_DEDUP";
52
+
53
+ /** Below this, the value is a misconfiguration and the pass stays off. */
54
+ export const MIN_THRESHOLD = 0.5;
55
+
56
+ /** A row with fewer content tokens than this is never compared (§17 floor). */
57
+ export const MIN_CONTENT = 4;
58
+
59
+ /**
60
+ * Tokens that reverse a row's meaning. If exactly one row of a candidate pair
61
+ * carries any of them, the rows disagree, and disagreement is not duplication.
62
+ * Only words that survive `words()` (lower-case, length > 2) are listed;
63
+ * contractions split ("don't" yields "don"), which is why "don" appears.
64
+ */
65
+ export const POLARITY_WORDS = new Set([
66
+ "never",
67
+ "not",
68
+ "cannot",
69
+ "cant",
70
+ "dont",
71
+ "don",
72
+ "avoid",
73
+ "forbidden",
74
+ "prohibited",
75
+ "banned",
76
+ ]);
77
+
78
+ /** Threshold from the environment. Unset, empty, unparsable, < MIN_THRESHOLD or > 1 means off. */
79
+ export function dedupeThreshold(
80
+ env: Record<string, string | undefined> = process.env,
81
+ ): number {
82
+ const raw = env[DEDUPE_ENV];
83
+ if (!raw) return 0;
84
+ const n = Number(raw);
85
+ return Number.isFinite(n) && n >= MIN_THRESHOLD && n <= 1 ? n : 0;
86
+ }
87
+
88
+ export function jaccard(a: Set<string>, b: Set<string>): number {
89
+ let inter = 0;
90
+ const small = a.size <= b.size ? a : b;
91
+ const large = small === a ? b : a;
92
+ for (const t of small) if (large.has(t)) inter++;
93
+ const union = a.size + b.size - inter;
94
+ return union ? inter / union : 0;
95
+ }
96
+
97
+ /**
98
+ * The short tokens `words()` drops (chunks of length <= 2). They are where
99
+ * single-digit facts hide: "Rate limiter reads Redis DB 3." and "...DB 4."
100
+ * have identical token sets and reach Jaccard 1 (review #415). Timestamped
101
+ * cursor rows — the rows this pass exists to suppress — keep their digit
102
+ * groups inside longer tokens ("15z"), so comparing the dropped chunks only
103
+ * guards real fact changes without touching the cursor case. A pair whose
104
+ * dropped chunks differ is never a copy.
105
+ */
106
+ export function droppedChunks(content: string): string[] {
107
+ return content
108
+ .toLowerCase()
109
+ .split(/[^a-z0-9_]+/)
110
+ .filter((t) => t.length > 0 && t.length <= 2)
111
+ .sort();
112
+ }
113
+
114
+ /** True when two rows carry the same short chunks (same multiset). */
115
+ function sameDroppedChunks(a: Memory, b: Memory): boolean {
116
+ const na = droppedChunks(a.content);
117
+ const nb = droppedChunks(b.content);
118
+ if (na.length !== nb.length) return false;
119
+ for (let i = 0; i < na.length; i++) if (na[i] !== nb[i]) return false;
120
+ return true;
121
+ }
122
+
123
+ /**
124
+ * A row's own tokens: everything except the `type` and `scope` values, which
125
+ * the same-scope requirement already guarantees are shared and which made short
126
+ * unrelated rows look like copies.
127
+ */
128
+ export function contentTokens(m: Memory): Set<string> {
129
+ const out = new Set(words(haystack(m)));
130
+ out.delete(m.type.toLowerCase());
131
+ out.delete(m.scope.toLowerCase());
132
+ return out;
133
+ }
134
+
135
+ function hasPolarity(tokens: Set<string>): boolean {
136
+ for (const w of tokens) if (POLARITY_WORDS.has(w)) return true;
137
+ return false;
138
+ }
139
+
140
+ /**
141
+ * Keep at most `limit` rows from `ranked`, in ranking order, skipping a row
142
+ * when it is a near-copy (same scope, content-token Jaccard >= `threshold`) of
143
+ * a row already kept. When a clash happens the NEWER row takes the slot —
144
+ * §17: the duplicates are stale snapshots, so recency decides, not rank. Rows
145
+ * under `MIN_CONTENT` content tokens, pairs that disagree on a negation word,
146
+ * and pairs whose numeric literals differ are never suppressed. `threshold <= 0`
147
+ * returns the plain top-`limit` slice, so the flag-off path costs nothing and
148
+ * cannot reorder.
149
+ */
150
+ export function dedupeWindow(
151
+ ranked: Memory[],
152
+ limit: number,
153
+ threshold: number,
154
+ ): Memory[] {
155
+ if (threshold <= 0 || ranked.length <= 1) return ranked.slice(0, limit);
156
+ const tokenSets = ranked.map(contentTokens);
157
+ const polarity = tokenSets.map(hasPolarity);
158
+ const kept: number[] = [];
159
+ for (let i = 0; i < ranked.length && kept.length < limit; i++) {
160
+ if (tokenSets[i]!.size < MIN_CONTENT) {
161
+ kept.push(i);
162
+ continue;
163
+ }
164
+ let clash = -1; // position within `kept`, not the row index
165
+ for (const pos of kept.keys()) {
166
+ const k = kept[pos]!;
167
+ if (
168
+ ranked[k]!.scope === ranked[i]!.scope &&
169
+ tokenSets[k]!.size >= MIN_CONTENT &&
170
+ polarity[k] === polarity[i] &&
171
+ sameDroppedChunks(ranked[k]!, ranked[i]!) &&
172
+ jaccard(tokenSets[i]!, tokenSets[k]!) >= threshold
173
+ ) {
174
+ clash = pos;
175
+ break;
176
+ }
177
+ }
178
+ if (clash === -1) kept.push(i);
179
+ else if (ranked[i]!.ts > ranked[kept[clash]!]!.ts) kept[clash] = i;
180
+ }
181
+ return kept.map((i) => ranked[i]!);
182
+ }