@causyne/agent 1.20.26 → 1.20.29

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 (41) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +52 -4
  3. package/src/agentLoop.ts +48 -4
  4. package/src/browser/causyneBrowser.js +1 -1
  5. package/src/browser/causyneBrowser.ts +1 -1
  6. package/src/browser/searchProviders.js +1 -1
  7. package/src/browser/searchProviders.ts +1 -1
  8. package/src/decideTools.js +9 -1
  9. package/src/decideTools.ts +7 -1
  10. package/src/dynamicCatalogue.js +3 -1
  11. package/src/dynamicCatalogue.ts +3 -1
  12. package/src/launchIntent.js +1 -1
  13. package/src/launchIntent.ts +1 -1
  14. package/src/mcp/mcpRegistry.js +6 -2
  15. package/src/mcp/mcpRegistry.ts +5 -2
  16. package/src/memory/actrRanker.js +78 -0
  17. package/src/memory/actrRanker.ts +111 -0
  18. package/src/memory/contextBudget.js +131 -0
  19. package/src/memory/contextBudget.ts +155 -0
  20. package/src/memory/episodicStore.js +652 -0
  21. package/src/memory/episodicStore.ts +788 -0
  22. package/src/memory/episodicTypes.js +8 -0
  23. package/src/memory/episodicTypes.ts +124 -0
  24. package/src/memory/nearDuplicate.js +179 -0
  25. package/src/memory/nearDuplicate.ts +232 -0
  26. package/src/memory/symbolFolder.js +301 -0
  27. package/src/memory/symbolFolder.ts +327 -0
  28. package/src/toolPacks.js +1 -0
  29. package/src/toolPacks.ts +1 -0
  30. package/src/tools/desktopOpen.js +9 -2
  31. package/src/tools/desktopOpen.ts +8 -2
  32. package/src/tools/memoryRecall.js +211 -0
  33. package/src/tools/memoryRecall.ts +251 -0
  34. package/src/tools/nativeEngine.js +16 -2
  35. package/src/tools/nativeEngine.ts +16 -2
  36. package/src/tools/registry.js +2 -1
  37. package/src/tools/subagentOrchestrator.js +3 -2
  38. package/src/tools/toolSelfRepair.js +4 -1
  39. package/src/tools/toolSelfRepair.ts +4 -1
  40. package/src/toolsList.js +1 -0
  41. package/src/toolsList.ts +1 -0
@@ -0,0 +1,8 @@
1
+ /**
2
+ * @file src/memory/episodicTypes.ts
3
+ * Core types for Causyne Episodic Memory, ACT-R Ranking, 2-Tier IDF-Veto Deduplication,
4
+ * 3-Layer Progressive Disclosure, Measured Context Budgeting, and Symbol Folding.
5
+ *
6
+ * Authorship: Strict TypeScript (Causyne Agent).
7
+ */
8
+ export {};
@@ -0,0 +1,124 @@
1
+ /**
2
+ * @file src/memory/episodicTypes.ts
3
+ * Core types for Causyne Episodic Memory, ACT-R Ranking, 2-Tier IDF-Veto Deduplication,
4
+ * 3-Layer Progressive Disclosure, Measured Context Budgeting, and Symbol Folding.
5
+ *
6
+ * Authorship: Strict TypeScript (Causyne Agent).
7
+ */
8
+
9
+ export type ObservationType =
10
+ | 'decision'
11
+ | 'bugfix'
12
+ | 'feature'
13
+ | 'refactor'
14
+ | 'discovery'
15
+ | 'verification';
16
+
17
+ export interface EpisodicObservation {
18
+ readonly id: number;
19
+ readonly taskId: string;
20
+ readonly workspace: string;
21
+ readonly project: string;
22
+ readonly type: ObservationType;
23
+ readonly title: string;
24
+ readonly subtitle: string;
25
+ readonly narrative: string;
26
+ readonly facts: readonly string[];
27
+ readonly concepts: readonly string[];
28
+ readonly filesRead: readonly string[];
29
+ readonly filesModified: readonly string[];
30
+ readonly toolName: string;
31
+ readonly createdAtEpochMs: number;
32
+ readonly reinforcedAtEpochsMs: readonly number[];
33
+ readonly reinforcementCount: number;
34
+ readonly source?: 'native' | 'external_bridge' | undefined;
35
+ }
36
+
37
+ export interface EpisodicSessionSummary {
38
+ readonly id: number;
39
+ readonly taskId: string;
40
+ readonly workspace: string;
41
+ readonly project: string;
42
+ readonly request: string;
43
+ readonly investigated: string;
44
+ readonly learned: string;
45
+ readonly completed: string;
46
+ readonly nextSteps: string;
47
+ readonly createdAtEpochMs: number;
48
+ }
49
+
50
+ export interface ProgressiveSearchRow {
51
+ readonly id: string;
52
+ readonly numericId: number;
53
+ readonly kind: 'observation' | 'summary';
54
+ readonly type: ObservationType | 'summary';
55
+ readonly project: string;
56
+ readonly title: string;
57
+ readonly subtitle: string;
58
+ readonly createdAtEpochMs: number;
59
+ readonly reinforcementCount: number;
60
+ readonly score: number;
61
+ }
62
+
63
+ export interface ProgressiveSearchResult {
64
+ readonly query: string;
65
+ readonly totalMatches: number;
66
+ readonly results: readonly ProgressiveSearchRow[];
67
+ }
68
+
69
+ export interface TimelineWindowItem {
70
+ readonly id: string;
71
+ readonly numericId: number;
72
+ readonly isAnchor: boolean;
73
+ readonly type: ObservationType;
74
+ readonly title: string;
75
+ readonly subtitle: string;
76
+ readonly toolName: string;
77
+ readonly filesModified: readonly string[];
78
+ readonly createdAtEpochMs: number;
79
+ }
80
+
81
+ export interface TimelineWindowResult {
82
+ readonly anchorId: string;
83
+ readonly project: string;
84
+ readonly before: readonly TimelineWindowItem[];
85
+ readonly anchor: TimelineWindowItem | null;
86
+ readonly after: readonly TimelineWindowItem[];
87
+ }
88
+
89
+ export interface ObservationBatchResult {
90
+ readonly requestedIds: readonly string[];
91
+ readonly observations: readonly EpisodicObservation[];
92
+ readonly omittedIds: readonly string[];
93
+ readonly truncatedByByteLimit: boolean;
94
+ readonly totalBytes: number;
95
+ }
96
+
97
+ export type FoldedSymbolKind =
98
+ | 'function'
99
+ | 'class'
100
+ | 'interface'
101
+ | 'type'
102
+ | 'enum'
103
+ | 'method'
104
+ | 'const';
105
+
106
+ export interface FoldedSymbolEntry {
107
+ readonly name: string;
108
+ readonly kind: FoldedSymbolKind;
109
+ readonly signature: string;
110
+ readonly lineStart: number;
111
+ readonly lineEnd: number;
112
+ readonly exported: boolean;
113
+ readonly docComment?: string | undefined;
114
+ }
115
+
116
+ export interface FoldedFileOutline {
117
+ readonly filePath: string;
118
+ readonly language: string;
119
+ readonly totalLines: number;
120
+ readonly importCount: number;
121
+ readonly symbols: readonly FoldedSymbolEntry[];
122
+ readonly renderedOutline: string;
123
+ }
124
+
@@ -0,0 +1,179 @@
1
+ /**
2
+ * @file src/memory/nearDuplicate.ts
3
+ * 2-Tier Deterministic Near-Duplicate Observation Detector with Rare-Token IDF Veto.
4
+ *
5
+ * Tier-0 (`exact`): Normalized non-empty title equality triggers silent reinforcement.
6
+ * Tier-1 (`candidate`): IDF-weighted cosine similarity >= threshold with a minimum
7
+ * shared-token guard (`minSharedTokens: 2`) AND a rare-token IDF Veto (if the
8
+ * symmetric difference contains a rare high-IDF token such as a distinct filename,
9
+ * symbol, or error code, the merge is vetoed).
10
+ *
11
+ * Authorship: Strict TypeScript (Causyne Agent).
12
+ */
13
+ const DEFAULT_SIMILARITY_THRESHOLD = 0.72;
14
+ const DEFAULT_MIN_SHARED_TOKENS = 2;
15
+ const DEFAULT_IDF_VETO_RATIO = 0.85;
16
+ const STOPWORDS = new Set([
17
+ 'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of',
18
+ 'with', 'by', 'from', 'up', 'about', 'into', 'over', 'after', 'is', 'are',
19
+ 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does',
20
+ 'did', 'will', 'would', 'shall', 'should', 'may', 'might', 'must', 'can',
21
+ 'could', 'this', 'that', 'these', 'those', 'it', 'its', 'as', 'if', 'when',
22
+ 'than', 'then', 'so', 'no', 'not', 'only', 'own', 'same', 'too', 'very',
23
+ 'via', 'using', 'used', 'file', 'files', 'tool', 'ran', 'run', 'executed'
24
+ ]);
25
+ /**
26
+ * Normalize an observation title for Tier-0 exact match comparison.
27
+ */
28
+ export function normalizeTitleForExactMatch(title) {
29
+ return String(title || '')
30
+ .toLowerCase()
31
+ .replace(/[\r\n\t]+/g, ' ')
32
+ .replace(/[^\p{L}\p{N}\s._/-]/gu, '')
33
+ .replace(/\s+/g, ' ')
34
+ .trim();
35
+ }
36
+ /**
37
+ * Tokenize text into lowercase alphanumeric/identifier tokens, filtering stopwords.
38
+ */
39
+ export function tokenizeForDedup(text) {
40
+ const raw = String(text || '')
41
+ .toLowerCase()
42
+ .split(/[^a-z0-9_./-]+/g);
43
+ const tokens = [];
44
+ for (const part of raw) {
45
+ const cleaned = part.replace(/^[._/-]+|[._/-]+$/g, '');
46
+ if (cleaned.length < 2)
47
+ continue;
48
+ if (STOPWORDS.has(cleaned))
49
+ continue;
50
+ tokens.push(cleaned);
51
+ }
52
+ return tokens;
53
+ }
54
+ /**
55
+ * Build a corpus-wide Inverse Document Frequency (IDF) map from existing observations:
56
+ * idf(t) = ln((N + 1) / (df(t) + 1)) + 1
57
+ */
58
+ export function buildCorpusIdfMap(documents) {
59
+ const docCount = Math.max(1, documents.length);
60
+ const df = new Map();
61
+ for (const doc of documents) {
62
+ const uniqueTokens = new Set(tokenizeForDedup(`${doc.title} ${doc.narrative}`));
63
+ for (const token of uniqueTokens) {
64
+ df.set(token, (df.get(token) ?? 0) + 1);
65
+ }
66
+ }
67
+ const idf = new Map();
68
+ for (const [token, count] of df.entries()) {
69
+ idf.set(token, Math.log((docCount + 1) / (count + 1)) + 1);
70
+ }
71
+ return idf;
72
+ }
73
+ function defaultIdfWeight(corpusSize, idfMap, token) {
74
+ const known = idfMap.get(token);
75
+ if (known !== undefined)
76
+ return known;
77
+ // Unseen token has df = 0 -> maximum rarity in the corpus
78
+ return Math.log(Math.max(1, corpusSize) + 1) + 1;
79
+ }
80
+ /**
81
+ * Compute IDF-weighted cosine similarity and shared unique token count between two token lists.
82
+ */
83
+ export function tfidfCosineSimilarity(tokensA, tokensB, idfMap, corpusSize = 10) {
84
+ if (tokensA.length === 0 || tokensB.length === 0) {
85
+ return { similarity: 0, sharedTokens: 0 };
86
+ }
87
+ const tfA = new Map();
88
+ const tfB = new Map();
89
+ for (const t of tokensA)
90
+ tfA.set(t, (tfA.get(t) ?? 0) + 1);
91
+ for (const t of tokensB)
92
+ tfB.set(t, (tfB.get(t) ?? 0) + 1);
93
+ let dot = 0;
94
+ let normA = 0;
95
+ let normB = 0;
96
+ let sharedTokens = 0;
97
+ for (const [token, countA] of tfA.entries()) {
98
+ const tfWeightA = 1 + Math.log(countA);
99
+ const wA = tfWeightA * defaultIdfWeight(corpusSize, idfMap, token);
100
+ normA += wA * wA;
101
+ const countB = tfB.get(token);
102
+ if (countB !== undefined) {
103
+ sharedTokens += 1;
104
+ const tfWeightB = 1 + Math.log(countB);
105
+ const wB = tfWeightB * defaultIdfWeight(corpusSize, idfMap, token);
106
+ dot += wA * wB;
107
+ }
108
+ }
109
+ for (const [token, countB] of tfB.entries()) {
110
+ const tfWeightB = 1 + Math.log(countB);
111
+ const wB = tfWeightB * defaultIdfWeight(corpusSize, idfMap, token);
112
+ normB += wB * wB;
113
+ }
114
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
115
+ if (denom <= 0)
116
+ return { similarity: 0, sharedTokens };
117
+ return { similarity: dot / denom, sharedTokens };
118
+ }
119
+ /**
120
+ * Rare-token IDF Veto:
121
+ * If the symmetric difference between A and B contains a high-IDF discriminating token
122
+ * (such as a specific file path, identifier, or distinct error code whose IDF is >=
123
+ * `idfVetoRatio * maxPossibleIdf`, or a structural path/identifier difference),
124
+ * veto the merge so two distinct fixes are not collapsed into one.
125
+ */
126
+ export function shouldIdfVeto(tokensA, tokensB, idfMap, corpusSize = 10, idfVetoRatio = DEFAULT_IDF_VETO_RATIO) {
127
+ const setA = new Set(tokensA);
128
+ const setB = new Set(tokensB);
129
+ const maxIdf = Math.log(Math.max(2, corpusSize) + 1) + 1;
130
+ const threshold = maxIdf * idfVetoRatio;
131
+ const symmetricDiff = [];
132
+ for (const t of setA) {
133
+ if (!setB.has(t))
134
+ symmetricDiff.push(t);
135
+ }
136
+ for (const t of setB) {
137
+ if (!setA.has(t))
138
+ symmetricDiff.push(t);
139
+ }
140
+ for (const diffToken of symmetricDiff) {
141
+ // Structural file path or dotted/slashed symbol in symmetric difference is a strong discriminator
142
+ if ((diffToken.includes('/') || diffToken.includes('.')) && diffToken.length >= 4) {
143
+ return true;
144
+ }
145
+ if (corpusSize >= 3) {
146
+ const tokenIdf = defaultIdfWeight(corpusSize, idfMap, diffToken);
147
+ if (tokenIdf >= threshold && diffToken.length >= 4) {
148
+ return true;
149
+ }
150
+ }
151
+ }
152
+ return false;
153
+ }
154
+ /**
155
+ * Decide whether observation `a` and `b` are exact duplicates, near-duplicate candidates, or distinct.
156
+ */
157
+ export function decideNearDuplicate(a, b, idfMap, corpusSize = 10, config = {}) {
158
+ const similarityThreshold = config.similarityThreshold ?? DEFAULT_SIMILARITY_THRESHOLD;
159
+ const minSharedTokens = config.minSharedTokens ?? DEFAULT_MIN_SHARED_TOKENS;
160
+ const idfVetoRatio = config.idfVetoRatio ?? DEFAULT_IDF_VETO_RATIO;
161
+ const normA = normalizeTitleForExactMatch(a.title);
162
+ const normB = normalizeTitleForExactMatch(b.title);
163
+ if (normA.length > 0 && normA === normB) {
164
+ return { tier: 'exact', similarity: 1 };
165
+ }
166
+ const tokensA = tokenizeForDedup(`${a.title} ${a.narrative}`);
167
+ const tokensB = tokenizeForDedup(`${b.title} ${b.narrative}`);
168
+ const { similarity, sharedTokens } = tfidfCosineSimilarity(tokensA, tokensB, idfMap, corpusSize);
169
+ if (sharedTokens < minSharedTokens) {
170
+ return { tier: 'distinct', similarity };
171
+ }
172
+ if (shouldIdfVeto(tokensA, tokensB, idfMap, corpusSize, idfVetoRatio)) {
173
+ return { tier: 'distinct', similarity, vetoed: true };
174
+ }
175
+ if (similarity < similarityThreshold) {
176
+ return { tier: 'distinct', similarity };
177
+ }
178
+ return { tier: 'candidate', similarity };
179
+ }
@@ -0,0 +1,232 @@
1
+ /**
2
+ * @file src/memory/nearDuplicate.ts
3
+ * 2-Tier Deterministic Near-Duplicate Observation Detector with Rare-Token IDF Veto.
4
+ *
5
+ * Tier-0 (`exact`): Normalized non-empty title equality triggers silent reinforcement.
6
+ * Tier-1 (`candidate`): IDF-weighted cosine similarity >= threshold with a minimum
7
+ * shared-token guard (`minSharedTokens: 2`) AND a rare-token IDF Veto (if the
8
+ * symmetric difference contains a rare high-IDF token such as a distinct filename,
9
+ * symbol, or error code, the merge is vetoed).
10
+ *
11
+ * Authorship: Strict TypeScript (Causyne Agent).
12
+ */
13
+
14
+ export type DedupTier = 'exact' | 'candidate' | 'distinct';
15
+
16
+ export interface DedupDecision {
17
+ readonly tier: DedupTier;
18
+ readonly similarity: number;
19
+ readonly vetoed?: boolean | undefined;
20
+ }
21
+
22
+ export interface DedupObservationInput {
23
+ readonly title: string;
24
+ readonly narrative: string;
25
+ }
26
+
27
+ export interface DedupConfig {
28
+ readonly similarityThreshold?: number | undefined;
29
+ readonly minSharedTokens?: number | undefined;
30
+ readonly idfVetoRatio?: number | undefined;
31
+ }
32
+
33
+ const DEFAULT_SIMILARITY_THRESHOLD = 0.72;
34
+ const DEFAULT_MIN_SHARED_TOKENS = 2;
35
+ const DEFAULT_IDF_VETO_RATIO = 0.85;
36
+
37
+ const STOPWORDS: ReadonlySet<string> = new Set([
38
+ 'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of',
39
+ 'with', 'by', 'from', 'up', 'about', 'into', 'over', 'after', 'is', 'are',
40
+ 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does',
41
+ 'did', 'will', 'would', 'shall', 'should', 'may', 'might', 'must', 'can',
42
+ 'could', 'this', 'that', 'these', 'those', 'it', 'its', 'as', 'if', 'when',
43
+ 'than', 'then', 'so', 'no', 'not', 'only', 'own', 'same', 'too', 'very',
44
+ 'via', 'using', 'used', 'file', 'files', 'tool', 'ran', 'run', 'executed'
45
+ ]);
46
+
47
+ /**
48
+ * Normalize an observation title for Tier-0 exact match comparison.
49
+ */
50
+ export function normalizeTitleForExactMatch(title: string): string {
51
+ return String(title || '')
52
+ .toLowerCase()
53
+ .replace(/[\r\n\t]+/g, ' ')
54
+ .replace(/[^\p{L}\p{N}\s._/-]/gu, '')
55
+ .replace(/\s+/g, ' ')
56
+ .trim();
57
+ }
58
+
59
+ /**
60
+ * Tokenize text into lowercase alphanumeric/identifier tokens, filtering stopwords.
61
+ */
62
+ export function tokenizeForDedup(text: string): string[] {
63
+ const raw = String(text || '')
64
+ .toLowerCase()
65
+ .split(/[^a-z0-9_./-]+/g);
66
+ const tokens: string[] = [];
67
+ for (const part of raw) {
68
+ const cleaned = part.replace(/^[._/-]+|[._/-]+$/g, '');
69
+ if (cleaned.length < 2) continue;
70
+ if (STOPWORDS.has(cleaned)) continue;
71
+ tokens.push(cleaned);
72
+ }
73
+ return tokens;
74
+ }
75
+
76
+ /**
77
+ * Build a corpus-wide Inverse Document Frequency (IDF) map from existing observations:
78
+ * idf(t) = ln((N + 1) / (df(t) + 1)) + 1
79
+ */
80
+ export function buildCorpusIdfMap(documents: readonly DedupObservationInput[]): Map<string, number> {
81
+ const docCount = Math.max(1, documents.length);
82
+ const df = new Map<string, number>();
83
+
84
+ for (const doc of documents) {
85
+ const uniqueTokens = new Set(tokenizeForDedup(`${doc.title} ${doc.narrative}`));
86
+ for (const token of uniqueTokens) {
87
+ df.set(token, (df.get(token) ?? 0) + 1);
88
+ }
89
+ }
90
+
91
+ const idf = new Map<string, number>();
92
+ for (const [token, count] of df.entries()) {
93
+ idf.set(token, Math.log((docCount + 1) / (count + 1)) + 1);
94
+ }
95
+ return idf;
96
+ }
97
+
98
+ function defaultIdfWeight(corpusSize: number, idfMap: ReadonlyMap<string, number>, token: string): number {
99
+ const known = idfMap.get(token);
100
+ if (known !== undefined) return known;
101
+ // Unseen token has df = 0 -> maximum rarity in the corpus
102
+ return Math.log(Math.max(1, corpusSize) + 1) + 1;
103
+ }
104
+
105
+ /**
106
+ * Compute IDF-weighted cosine similarity and shared unique token count between two token lists.
107
+ */
108
+ export function tfidfCosineSimilarity(
109
+ tokensA: readonly string[],
110
+ tokensB: readonly string[],
111
+ idfMap: ReadonlyMap<string, number>,
112
+ corpusSize: number = 10
113
+ ): { similarity: number; sharedTokens: number } {
114
+ if (tokensA.length === 0 || tokensB.length === 0) {
115
+ return { similarity: 0, sharedTokens: 0 };
116
+ }
117
+
118
+ const tfA = new Map<string, number>();
119
+ const tfB = new Map<string, number>();
120
+ for (const t of tokensA) tfA.set(t, (tfA.get(t) ?? 0) + 1);
121
+ for (const t of tokensB) tfB.set(t, (tfB.get(t) ?? 0) + 1);
122
+
123
+ let dot = 0;
124
+ let normA = 0;
125
+ let normB = 0;
126
+ let sharedTokens = 0;
127
+
128
+ for (const [token, countA] of tfA.entries()) {
129
+ const tfWeightA = 1 + Math.log(countA);
130
+ const wA = tfWeightA * defaultIdfWeight(corpusSize, idfMap, token);
131
+ normA += wA * wA;
132
+ const countB = tfB.get(token);
133
+ if (countB !== undefined) {
134
+ sharedTokens += 1;
135
+ const tfWeightB = 1 + Math.log(countB);
136
+ const wB = tfWeightB * defaultIdfWeight(corpusSize, idfMap, token);
137
+ dot += wA * wB;
138
+ }
139
+ }
140
+
141
+ for (const [token, countB] of tfB.entries()) {
142
+ const tfWeightB = 1 + Math.log(countB);
143
+ const wB = tfWeightB * defaultIdfWeight(corpusSize, idfMap, token);
144
+ normB += wB * wB;
145
+ }
146
+
147
+ const denom = Math.sqrt(normA) * Math.sqrt(normB);
148
+ if (denom <= 0) return { similarity: 0, sharedTokens };
149
+ return { similarity: dot / denom, sharedTokens };
150
+ }
151
+
152
+ /**
153
+ * Rare-token IDF Veto:
154
+ * If the symmetric difference between A and B contains a high-IDF discriminating token
155
+ * (such as a specific file path, identifier, or distinct error code whose IDF is >=
156
+ * `idfVetoRatio * maxPossibleIdf`, or a structural path/identifier difference),
157
+ * veto the merge so two distinct fixes are not collapsed into one.
158
+ */
159
+ export function shouldIdfVeto(
160
+ tokensA: readonly string[],
161
+ tokensB: readonly string[],
162
+ idfMap: ReadonlyMap<string, number>,
163
+ corpusSize: number = 10,
164
+ idfVetoRatio: number = DEFAULT_IDF_VETO_RATIO
165
+ ): boolean {
166
+ const setA = new Set(tokensA);
167
+ const setB = new Set(tokensB);
168
+ const maxIdf = Math.log(Math.max(2, corpusSize) + 1) + 1;
169
+ const threshold = maxIdf * idfVetoRatio;
170
+
171
+ const symmetricDiff: string[] = [];
172
+ for (const t of setA) {
173
+ if (!setB.has(t)) symmetricDiff.push(t);
174
+ }
175
+ for (const t of setB) {
176
+ if (!setA.has(t)) symmetricDiff.push(t);
177
+ }
178
+
179
+ for (const diffToken of symmetricDiff) {
180
+ // Structural file path or dotted/slashed symbol in symmetric difference is a strong discriminator
181
+ if ((diffToken.includes('/') || diffToken.includes('.')) && diffToken.length >= 4) {
182
+ return true;
183
+ }
184
+ if (corpusSize >= 3) {
185
+ const tokenIdf = defaultIdfWeight(corpusSize, idfMap, diffToken);
186
+ if (tokenIdf >= threshold && diffToken.length >= 4) {
187
+ return true;
188
+ }
189
+ }
190
+ }
191
+
192
+ return false;
193
+ }
194
+
195
+ /**
196
+ * Decide whether observation `a` and `b` are exact duplicates, near-duplicate candidates, or distinct.
197
+ */
198
+ export function decideNearDuplicate(
199
+ a: DedupObservationInput,
200
+ b: DedupObservationInput,
201
+ idfMap: ReadonlyMap<string, number>,
202
+ corpusSize: number = 10,
203
+ config: DedupConfig = {}
204
+ ): DedupDecision {
205
+ const similarityThreshold = config.similarityThreshold ?? DEFAULT_SIMILARITY_THRESHOLD;
206
+ const minSharedTokens = config.minSharedTokens ?? DEFAULT_MIN_SHARED_TOKENS;
207
+ const idfVetoRatio = config.idfVetoRatio ?? DEFAULT_IDF_VETO_RATIO;
208
+
209
+ const normA = normalizeTitleForExactMatch(a.title);
210
+ const normB = normalizeTitleForExactMatch(b.title);
211
+ if (normA.length > 0 && normA === normB) {
212
+ return { tier: 'exact', similarity: 1 };
213
+ }
214
+
215
+ const tokensA = tokenizeForDedup(`${a.title} ${a.narrative}`);
216
+ const tokensB = tokenizeForDedup(`${b.title} ${b.narrative}`);
217
+
218
+ const { similarity, sharedTokens } = tfidfCosineSimilarity(tokensA, tokensB, idfMap, corpusSize);
219
+ if (sharedTokens < minSharedTokens) {
220
+ return { tier: 'distinct', similarity };
221
+ }
222
+
223
+ if (shouldIdfVeto(tokensA, tokensB, idfMap, corpusSize, idfVetoRatio)) {
224
+ return { tier: 'distinct', similarity, vetoed: true };
225
+ }
226
+
227
+ if (similarity < similarityThreshold) {
228
+ return { tier: 'distinct', similarity };
229
+ }
230
+
231
+ return { tier: 'candidate', similarity };
232
+ }