pi-mega-compact 0.20.6 → 0.20.7

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.
@@ -0,0 +1,142 @@
1
+ /**
2
+ * dashboard-server/routes-rag-settings-vector-cortex.ts — Vector Cortex SETTINGS.
3
+ *
4
+ * The VC0A..VC5C chain flag inventory, split out of routes-rag-settings-helpers.ts
5
+ * to keep that file under the 400-line extensions/ soft limit. Every VC flag is a
6
+ * user-visible dashboard toggle (never in EXCLUDED_SETTINGS) per the chain spec,
7
+ * and each carries the long description the Setup panel renders as help text.
8
+ *
9
+ * PREVENT-011: no `any` type.
10
+ */
11
+
12
+ import type { SettingSpec, SettingGroup } from "./routes-rag-settings-types.js";
13
+
14
+ const boolDirect = (
15
+ key: string,
16
+ label: string,
17
+ description: string,
18
+ def: boolean,
19
+ ): SettingSpec => ({
20
+ key,
21
+ label,
22
+ description,
23
+ type: "boolean",
24
+ default: def,
25
+ disabledConvention: false,
26
+ requiresLlm: false,
27
+ });
28
+
29
+ /** The Vector Cortex chain flags, as one SETTINGS category. */
30
+ export const VECTOR_CORTEX_SETTINGS: SettingGroup = {
31
+ name: "Vector Cortex",
32
+ settings: [
33
+ boolDirect(
34
+ "MEGACOMPACT_VC0A",
35
+ "VC0A Baseline Observability",
36
+ "Structured evaluation observer (MetricEventV1 + latency histogram). OFF = mode C, byte-identical to predecessor.",
37
+ true,
38
+ ),
39
+ boolDirect(
40
+ "MEGACOMPACT_VC0B",
41
+ "VC0B Replay Correctness",
42
+ "ReplayCutV2 effective-cut (min of boundary-safe/commit/capture high-water + pair retreat + anchor floor) and M3 effective-cut-v2 migration. OFF = legacy capped replay, byte-identical.",
43
+ true,
44
+ ),
45
+ boolDirect(
46
+ "MEGACOMPACT_VC1A",
47
+ "VC1A Canonical Byte Events",
48
+ "EventV2 byte-authority ledger codec (original bytes + SHA-256, strict UTF-8, derived NFC) and canonical validator (EVT_DIGEST_MISMATCH / EVT_UTF8_TAG_INVALID / EVT_DUPLICATE_ID). OFF = mode C, transcript codec unchanged, byte-identical.",
49
+ true,
50
+ ),
51
+ boolDirect(
52
+ "MEGACOMPACT_VC1B",
53
+ "VC1B Occurrence Ledger + Tool Identity",
54
+ "Neutral occurrence ledger (LedgerReader/Writer/Admin + CompatJournalV1): per-session monotonic seq, tool result references one earlier call, uniqueness by (eventId,digest) only, and the M2 copy-validate-switch downgrade journal. OFF = mode C, ledger unwritten, byte-identical.",
55
+ true,
56
+ ),
57
+ boolDirect(
58
+ "MEGACOMPACT_VC0C",
59
+ "VC0C Live Safety Envelope",
60
+ "TriadResult/Breaker live circuit breaker (60s window, 20 attempts, 30s cooldown, 3 probes, 5min healthy residence) + durable spool before provider invocation; manual reset clears cooldown but never evidence. OFF = mode C, unchanged transcript, byte-identical.",
61
+ true,
62
+ ),
63
+ boolDirect(
64
+ "MEGACOMPACT_VC1C",
65
+ "VC1C Cross-Language Conformance v2",
66
+ "FixtureManifestV2 canonical manifest validator + DowngradeReport deterministic downgrade export + MinHashV2 exact big-integer signatures and the M4 copy/validate/switch minhash-v2 migration (seed table frozen, cross-language byte-exact). OFF = mode C, v1 sync dedup scan unchanged, byte-identical.",
67
+ true,
68
+ ),
69
+ boolDirect(
70
+ "MEGACOMPACT_VC2A",
71
+ "VC2A Offline Model Runtime",
72
+ "ModelManifestV1 digest-before-load ONNX runtime (opset17/batch1/max512) + asset-free trigram demotion. Asset path assets/vector-cortex/encoder-v1 is immutable/digest-pinned. OFF = mode C, byte-identical to predecessor.",
73
+ true,
74
+ ),
75
+ boolDirect(
76
+ "MEGACOMPACT_VC2B",
77
+ "VC2B Multi-Head Encoder",
78
+ "VectorSetV1 five L2-normalized heads (384/128/128/64/32) with head-calibration draft + asset-free trigram B (512d) and lexical C fallbacks, plus the per-head emit seam. OFF = mode C, no per-head vectors emitted, byte-identical predecessor.",
79
+ true,
80
+ ),
81
+ boolDirect(
82
+ "MEGACOMPACT_VC2C",
83
+ "VC2C Encoder Qualification + Calibration",
84
+ "QualifiedEncoderV1/CalibrationV1: calibration fit on the calibration split only (held-out labels prohibited) + atomic selection across MODEL_ASSET and per-head EVALUATION thresholds (any field failure demotes all of A). OFF = mode C, no qualification/calibration selection, byte-identical predecessor.",
85
+ true,
86
+ ),
87
+ boolDirect(
88
+ "MEGACOMPACT_VC3A",
89
+ "VC3A Cortex Store",
90
+ "Capability-gated derived cortex store (CortexReader/Writer/Admin + CortexRecordV1): additive, keyed (sourceHighWater, algorithmVersion, id), immutable records, deterministic generation rebuild + one root digest. OFF = mode C, no cortex records written, byte-identical predecessor.",
91
+ true,
92
+ ),
93
+ boolDirect(
94
+ "MEGACOMPACT_VC3B",
95
+ "VC3B Deterministic Topology",
96
+ "Deterministic cortical topology (TopologyV1/EdgeV1): per-(source,head) top-k=16/head calibrated-threshold edges, stable score-desc/then-target-ID sort, dependency directed + contradiction symmetric paired records, one stable generation digest. OFF = mode C, no topology graph built/emitted, predecessor-precise topology view, byte-identical predecessor.",
97
+ true,
98
+ ),
99
+ boolDirect(
100
+ "MEGACOMPACT_VC3C",
101
+ "VC3C Topology Query + Router Invalidation",
102
+ "TopologyQueryV1/RouterKeyV2 structured keys (length-delimited, unsigned-byte order, no prefix ambiguity), exact (session,generation) invalidation, stale-generation rejection (TOP_GENERATION_STALE), and the M6 router-generation-v2 copy/validate/switch migration. OFF = mode C, no structured router key / generation invalidation, byte-identical predecessor.",
103
+ true,
104
+ ),
105
+ boolDirect(
106
+ "MEGACOMPACT_VC4A",
107
+ "VC4A Dual-Tier Shards",
108
+ "SemanticShardV1/ExactShardV1/ShardManifestV1: partition a session ONLY at complete EventV2 boundaries; exact shards preserve every tool call/result pair, anchor and invalid UTF-8 event as original bytes (pairs never split across exact shards); manifest enforces disjoint sorted ranges + complete protected-span coverage. OFF = mode C, exact anchors/current transcript only, byte-identical predecessor.",
109
+ true,
110
+ ),
111
+ boolDirect(
112
+ "MEGACOMPACT_VC4B",
113
+ "VC4B Residual Basis Parity",
114
+ "Residual codec: orthonormal DCT-II basis + int16 block quantization + block-scoped exact correction stream + (9,6) Reed-Solomon parity shards with SHA-256 corruption detection; admission gates on encodedSize <= 95% of exact-compressed size. OFF = mode C, no residual artifact produced, byte-identical predecessor.",
115
+ true,
116
+ ),
117
+ boolDirect(
118
+ "MEGACOMPACT_VC4C",
119
+ "VC4C Reconstruction Fidelity",
120
+ "Conservative closure + source-order assembly + reconstruction validator: recursively closes dependencies and whole tool pairs to a fixed point, resolves contradictions by retaining the later exact source resolution, assembles spans solely by source range, and rejects missing anchors / split pairs / digest mismatch / unresolved contradiction. Mandatory token estimate is content-only and handed unchanged to VC5A. OFF = mode C, no closure/validator, byte-identical predecessor (VC4B).",
121
+ true,
122
+ ),
123
+ boolDirect(
124
+ "MEGACOMPACT_VC5A",
125
+ "VC5A PromptDagV1 + Budgeted Planner",
126
+ "Single-session DAG (PromptDagV1) + budgeted 0/1 portfolio planner: builds a stable Kahn-ordered DAG, computes the mandatory dependency/tool/anchor closure before optional selection, returns MANDATORY_CLOSURE_OVER_BUDGET with evidence preserved on overflow, and runs a utility-per-token portfolio that never exceeds the remaining budget. Framing is owned here, not in VC4C. OFF = byte-identical predecessor (VC4C).",
127
+ true,
128
+ ),
129
+ boolDirect(
130
+ "MEGACOMPACT_VC5B",
131
+ "VC5B Validated Renderer + Provider Profiles",
132
+ "Validated prompt renderer: replays VC5A's stable Kahn order verbatim, preserves exact tool bytes (PREVENT-PI-002), places compacted context via the host before_agent_start prepend seam — never role:system (PREVENT-PI-003) — and SHA-256 hashes the entire canonical outbound request before provider invocation. Unknown provider/model cleanly bypasses to the predecessor prompt path. OFF = byte-identical predecessor (VC5A).",
133
+ true,
134
+ ),
135
+ boolDirect(
136
+ "MEGACOMPACT_VC5C",
137
+ "VC5C Live Graduated Rollout",
138
+ "Live graduated rollout: deterministically hashes each session into a stable 10,000-bucket cohort and advances the exposure gate (1/5/25/50/100%) only after a 72h monotonic residency, a powered sample, >=10,000 events, and >=200 sessions — advancing ONE gate at a time. A hard causal/tool/anchor/exact failure freezes promotion and selects the pre-VC path. OFF = byte-identical predecessor (VC5B).",
139
+ true,
140
+ ),
141
+ ],
142
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mega-compact",
3
- "version": "0.20.6",
3
+ "version": "0.20.7",
4
4
  "description": "Layered, local, vector-backed context compressor for pi — supersede/collapse/cluster compaction with deduped inline recall.",
5
5
  "type": "module",
6
6
  "license": "BSD-3-Clause",
@@ -75,6 +75,14 @@ export interface DedupConfigShape {
75
75
  * topical structure before detailed checkpoint hits. */
76
76
  RAPTOR_INJECT_SUMMARIES: boolean;
77
77
  // Monitoring / alerting.
78
+ /**
79
+ * Durable dedup audit trail (external-audit item #2). ON appends one
80
+ * structured JSON line per tier DECISION to events.log so an operator can see
81
+ * which layer collapsed a region, onto what, and at what similarity — the
82
+ * inputs needed to tune the thresholds above. OFF writes nothing at all;
83
+ * dedup behavior is identical either way (pure instrumentation).
84
+ */
85
+ DEDUP_AUDIT: boolean;
78
86
  FP_RATE_L0: number; // FP alert threshold for exact tier
79
87
  FP_RATE_L1L2: number; // FP alert threshold for fuzzy tiers
80
88
  ALERT_WINDOW_MS: number;
@@ -115,6 +123,7 @@ export function loadDedupConfig(): DedupConfigShape {
115
123
  RAPTOR_MAX_LEAF_EXPANSION: envNum("MEGACOMPACT_RAPTOR_MAX_LEAF_EXP", 10),
116
124
  RAPTOR_FRESHNESS_HOURS: envNum("MEGACOMPACT_RAPTOR_FRESHNESS_HOURS", 4),
117
125
  RAPTOR_INJECT_SUMMARIES: envBool("MEGACOMPACT_RAPTOR_INJECT_SUMMARIES", true),
126
+ DEDUP_AUDIT: envBool("MEGACOMPACT_DEDUP_AUDIT", true),
118
127
  FP_RATE_L0: envNum("MEGACOMPACT_FP_RATE_L0", 0.01),
119
128
  FP_RATE_L1L2: envNum("MEGACOMPACT_FP_RATE_L1L2", 0.05),
120
129
  ALERT_WINDOW_MS: envNum("MEGACOMPACT_ALERT_WINDOW_MS", 600_000),
@@ -0,0 +1,49 @@
1
+ /**
2
+ * dedup-audit.test-helpers.ts — shared harness for the dedup audit trail tests.
3
+ *
4
+ * Extracted so dedup-audit.test.ts and dedup-audit-gating.test.ts share one
5
+ * temp-dir lifecycle and one events.log reader instead of duplicating them, and
6
+ * so each test file stays under the 300-line src/ soft limit.
7
+ *
8
+ * Hermetic: every store gets its own temp state dir, so no test can observe
9
+ * another's audit lines. No network (PREVENT-PI-004).
10
+ */
11
+
12
+ import { mkdtempSync, readFileSync, writeFileSync, existsSync } from "node:fs";
13
+ import { tmpdir } from "node:os";
14
+ import { join } from "node:path";
15
+ import { loadDedupConfig, type DedupConfigShape } from "./config/dedup.js";
16
+ import { defaultEventsPath, type DedupAuditEvent } from "./monitoring.js";
17
+
18
+ /** Root temp dir shared by both audit test files (each run gets a subdir). */
19
+ export const baseTmp = mkdtempSync(join(tmpdir(), "mc-dedup-audit-"));
20
+
21
+ /** The live config with per-test overrides applied. */
22
+ export function cfg(over: Partial<DedupConfigShape> = {}): DedupConfigShape {
23
+ return { ...loadDedupConfig(), ...over };
24
+ }
25
+
26
+ let seq = 0;
27
+
28
+ /** A never-before-used state dir under `baseTmp`. */
29
+ export function freshDir(): string {
30
+ return join(baseTmp, `run-${seq++}-${Math.floor(performance.now() * 1000)}`);
31
+ }
32
+
33
+ /** Read every dedup_audit line from a store's default events.log. */
34
+ export function auditLines(stateDir: string): DedupAuditEvent[] {
35
+ const path = defaultEventsPath(stateDir);
36
+ if (!existsSync(path)) return [];
37
+ return readFileSync(path, "utf-8")
38
+ .split("\n")
39
+ .filter((l) => l.trim())
40
+ .map((l) => JSON.parse(l) as DedupAuditEvent)
41
+ .filter((e) => e.type === "dedup_audit");
42
+ }
43
+
44
+ /** A path whose parent directory can never be created: it sits under a FILE. */
45
+ export function unwritablePath(): string {
46
+ const blocker = join(baseTmp, `blocker-${seq++}`);
47
+ writeFileSync(blocker, "not a directory");
48
+ return join(blocker, "sub", "events.log");
49
+ }
package/src/monitoring.ts CHANGED
@@ -204,3 +204,13 @@ export function logRecallQuality(path: string, ev: RecallQualityEvent): void {
204
204
  /* best-effort — never break the extension */
205
205
  }
206
206
  }
207
+
208
+ // ---------------------------------------------------------------------------
209
+ // Dedup audit trail (external-audit item #2)
210
+ // ---------------------------------------------------------------------------
211
+ // The event shape and its append helper are DEFINED in vectorStore/dedup-audit.ts,
212
+ // co-located with the only recorder that emits them (this file already carries
213
+ // decision events + the metrics snapshot + FP alerting and must stay under its
214
+ // 300-line soft limit). Re-exported here so callers that treat monitoring.ts as
215
+ // the events.log barrel — including the dashboard SSE tail — keep one import.
216
+ export { logDedupAudit, type DedupAuditEvent } from "./vectorStore/dedup-audit.js";
@@ -0,0 +1,152 @@
1
+ /**
2
+ * add-l0.ts — the L0 exact-match tier of the dedup cascade.
3
+ *
4
+ * L0 is three exact-hash probes sharing one enable flag and one MARK_ONLY flag:
5
+ * 1. contentHash — normalized dual-hash, bloom-accelerated (Sprint 9/10)
6
+ * 2. regionHash — the legacy pre-normalization hash (backward-compat)
7
+ * 3. summaryHash — same-topic incremental compactions
8
+ *
9
+ * Split out of add.ts so both files stay under the 300-line src/ soft limit.
10
+ * The tier is a pure decision: it either produces a collapse (returning the
11
+ * matched result) or reports the fall-through, and it never writes a new
12
+ * checkpoint — that stays in add.ts.
13
+ *
14
+ * All three probes are hash comparisons, so none of them computes a similarity
15
+ * score and none is invented for the audit trail.
16
+ */
17
+ import { createHash } from "node:crypto";
18
+ import type { StoredCheckpoint } from "../store.js";
19
+ import type { ContentDigest } from "../dedup/digest.js";
20
+ import { upsertCheckpoint, addTokensSaved, bumpDedupStats } from "../store/sqlite.js";
21
+ import type { BloomFilter } from "../store/bloom.js";
22
+ import type { DedupAuditRecorder } from "./dedup-audit.js";
23
+ import type { AddInput, AddResult } from "./types.js";
24
+ import type { VectorStore } from "./class.js";
25
+
26
+ /** Everything the L0 tier needs from the enclosing add() cascade. */
27
+ export interface L0Context {
28
+ store: VectorStore;
29
+ input: AddInput;
30
+ /** Checkpoints already stored for this session. */
31
+ all: StoredCheckpoint[];
32
+ /** Normalized content digest of the incoming region. */
33
+ digest: ContentDigest;
34
+ /** Legacy region hash of the incoming region. */
35
+ regionHash: string;
36
+ /** SHA-256 of the topic summary, when one was supplied. */
37
+ summaryHash?: string;
38
+ /** Tokens the original region occupied (the dedup "saved" base). */
39
+ origTokens: number;
40
+ /** Warm bloom accelerator for the content-hash probe. */
41
+ bloom: BloomFilter;
42
+ /** Cascade start time, for the monitoring latency figure. */
43
+ t0: number;
44
+ audit: DedupAuditRecorder;
45
+ }
46
+
47
+ /**
48
+ * Outcome of the L0 tier.
49
+ *
50
+ * `result` set → the tier collapsed the region and add() returns immediately.
51
+ * `markOnly` set → a probe matched but MARK_ONLY policy said store anyway, so
52
+ * the cascade continues and records the mark at the end.
53
+ */
54
+ export interface L0Outcome {
55
+ result?: AddResult;
56
+ markOnly: "L0" | null;
57
+ }
58
+
59
+ /** Run the L0 exact-match tier. */
60
+ export function runL0Tier(ctx: L0Context): L0Outcome {
61
+ const { store, input, all, digest, regionHash, origTokens, bloom, t0, audit } = ctx;
62
+ const cfg = store.cfg;
63
+ const onTier = input.onTier;
64
+ let markOnly: "L0" | null = null;
65
+
66
+ // 0. Content-hash dedup (Sprint 9) — catches identical content arriving under
67
+ // different regionText. Normalization handles case/whitespace/ANSI so
68
+ // variants collapse to one row. Dual-hash guards a single-hash collision.
69
+ // Sprint 10: bloom is the accelerator — a miss means "definitely new" and
70
+ // skips the scan; a hit is only a candidate, confirmed against `all` here.
71
+ // MARK_ONLY_L0 records the decision but does not collapse.
72
+ onTier?.({ tier: "L0", status: "scanning" });
73
+ if (cfg.L0_ENABLED && bloom.maybeHas(digest.contentHash)) {
74
+ const contentMatch = all.find(
75
+ (cp) =>
76
+ cp.contentHash === digest.contentHash &&
77
+ cp.contentHash2 === digest.contentHash2,
78
+ );
79
+ if (contentMatch) {
80
+ if (cfg.MARK_ONLY_L0) {
81
+ markOnly = "L0"; // Record-but-don't-collapse: fall through.
82
+ } else {
83
+ contentMatch.timestamp = input.timestamp;
84
+ upsertCheckpoint(contentMatch, store.stateDir);
85
+ bumpDedupStats(true, store.stateDir);
86
+ // Deduped: whole original region discarded, nothing new stored.
87
+ addTokensSaved(origTokens, store.stateDir);
88
+ store.record("L0", "deduped", "contentHash", Date.now() - t0, 1, contentMatch.checkpointId);
89
+ audit.deduped("L0", contentMatch.checkpointId, "contentHash");
90
+ onTier?.({ tier: "L0", status: "deduped", detail: "contentHash" });
91
+ return {
92
+ result: { checkpoint: contentMatch, deduped: true, reason: "contentHash" },
93
+ markOnly,
94
+ };
95
+ }
96
+ }
97
+ }
98
+
99
+ // 1. Legacy regionHash dedup (backward-compat) — part of L0 tier gating.
100
+ if (cfg.L0_ENABLED) {
101
+ const regionMatch = all.find((cp) => cp.regionHash === regionHash);
102
+ if (regionMatch) {
103
+ if (cfg.MARK_ONLY_L0) {
104
+ markOnly = "L0"; // fall through
105
+ } else {
106
+ bumpDedupStats(true, store.stateDir);
107
+ // Deduped: whole original region discarded, nothing new stored.
108
+ addTokensSaved(origTokens, store.stateDir);
109
+ store.record("L0", "deduped", "regionHash", Date.now() - t0, 1, regionMatch.checkpointId);
110
+ audit.deduped("L0", regionMatch.checkpointId, "regionHash");
111
+ onTier?.({ tier: "L0", status: "deduped", detail: "regionHash" });
112
+ return {
113
+ result: { checkpoint: regionMatch, deduped: true, reason: "regionHash" },
114
+ markOnly,
115
+ };
116
+ }
117
+ }
118
+ }
119
+
120
+ // 2. SummaryHash dedup — catches same-topic incremental compactions.
121
+ if (ctx.summaryHash && cfg.L0_ENABLED) {
122
+ const summaryMatch = all.find((cp) => cp.summaryHash === ctx.summaryHash);
123
+ if (summaryMatch) {
124
+ if (cfg.MARK_ONLY_L0) {
125
+ markOnly = "L0"; // fall through
126
+ } else {
127
+ summaryMatch.timestamp = input.timestamp;
128
+ upsertCheckpoint(summaryMatch, store.stateDir);
129
+ bumpDedupStats(true, store.stateDir);
130
+ // Deduped: whole original region discarded, nothing new stored.
131
+ addTokensSaved(origTokens, store.stateDir);
132
+ store.record("L0", "deduped", "summaryHash", Date.now() - t0, 1, summaryMatch.checkpointId);
133
+ audit.deduped("L0", summaryMatch.checkpointId, "summaryHash");
134
+ onTier?.({ tier: "L0", status: "deduped", detail: "summaryHash" });
135
+ return {
136
+ result: { checkpoint: summaryMatch, deduped: true, reason: "summaryHash" },
137
+ markOnly,
138
+ };
139
+ }
140
+ }
141
+ }
142
+ // L0 did not collapse this region.
143
+ onTier?.({ tier: "L0", status: "passed" });
144
+ return { markOnly };
145
+ }
146
+
147
+ /** SHA-256 of the topic summary (full 64-hex; 16-hex was collision-prone). */
148
+ export function computeSummaryHash(topicSummary?: string): string | undefined {
149
+ return topicSummary
150
+ ? createHash("sha256").update(topicSummary).digest("hex")
151
+ : undefined;
152
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * add-l1.ts — the L1 MinHash/LSH near-duplicate lookup.
3
+ *
4
+ * Split out of add.ts to keep both files under the 300-line src/ soft limit.
5
+ * L1 catches the one-word edits and rewordings L0's exact hashes miss: a cheap
6
+ * LSH bucket retrieval narrows the field, then a trigram verification
7
+ * (pg_trgm-equivalent) is the final gate. The verify is boolean, so the tier
8
+ * produces no similarity score.
9
+ */
10
+ import type { StoredCheckpoint } from "../store.js";
11
+ import {
12
+ minhashSignature,
13
+ SIGNATURE_VERSION,
14
+ NUM_HASHES,
15
+ } from "../dedup/l1-minhash.js";
16
+ import { lshBands } from "../dedup/l1-lsh.js";
17
+ import { isNearDuplicate } from "../dedup/l1-verify.js";
18
+ import { lshCandidateChunks } from "../store/sqlite.js";
19
+ import type { VectorStore } from "./class.js";
20
+
21
+ export /**
22
+ * L1 near-duplicate lookup: MinHash → LSH candidate retrieval → trigram verify.
23
+ * Returns the matching checkpoint or undefined. Bounded by a 100-candidate cap
24
+ * and a 20ms verify budget (QA #7/#15) so it never hangs a large session.
25
+ */
26
+ function findL1Duplicate(
27
+ store: VectorStore,
28
+ sessionId: string,
29
+ regionText: string,
30
+ all: StoredCheckpoint[],
31
+ ): StoredCheckpoint | undefined {
32
+ if (all.length === 0) return undefined;
33
+ const sig = minhashSignature(regionText);
34
+ if (sig.length !== NUM_HASHES) return undefined;
35
+ const bands = lshBands(sig, sessionId, SIGNATURE_VERSION);
36
+ // Cheap candidate retrieval (single query, capped). Exclude nothing yet —
37
+ // the new checkpoint has no id, so pass a sentinel that never matches.
38
+ const candidateIds = lshCandidateChunks(
39
+ bands,
40
+ sessionId,
41
+ "__new__",
42
+ store.stateDir,
43
+ 100,
44
+ );
45
+ if (candidateIds.length === 0) return undefined;
46
+ const byId = new Map(all.map((cp) => [cp.checkpointId, cp]));
47
+ const VERIFY_BUDGET_MS = 20;
48
+ const start = Date.now();
49
+ for (const id of candidateIds) {
50
+ if (Date.now() - start > VERIFY_BUDGET_MS) break; // QA #15: abort → "not dup"
51
+ const cand = byId.get(id);
52
+ if (!cand) continue;
53
+ const candText = cand.normalizedText ?? cand.summary ?? "";
54
+ if (isNearDuplicate(regionText, candText)) return cand;
55
+ }
56
+ return undefined;
57
+ }