Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: semantic near-duplicate dedup for Layered Intelligence proposals (#2262)

Adam Eivy79eceef90000
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 879683214c..80c681326d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -30,6 +30,7 @@
## Layered Intelligence
- **[issue-2262] A dedicated Layered Intelligence page now surfaces the self-improvement loop's status across every app.** The perpetual per-app loop was previously visible only inside each app's Edit-App → Intelligence drawer tab, so there was no single place to see which apps had it enabled, when each last ran / is next due, or whether the global sweep job is even on. The new `/layered-intelligence` route (Chief of Staff → Layered Intelligence, `⌘K`/voice-navigable) reads a deterministic cross-app overview — each active app's effective config plus scheduler bookkeeping (`lastRunAt`/`nextDueAt`/due) and the global job's on/off state — with no LLM or forge I/O. It warns when the global job is disabled (per-app configs are inert until it's on), lists enabled apps with their interval, telemetry sources, allowed scopes, and provider, and deep-links each app's "Configure" action straight into its Intelligence tab (`/apps/:id?edit=1&appTab=intelligence`, via a new auto-open trigger on the app-detail drawer). (`server/routes/apps.js`, `server/services/layeredIntelligence.js` `summarizeLoopStatus`, `client/src/pages/LayeredIntelligence.jsx`, `client/src/components/apps/AppDetailView.jsx`, `server/lib/navManifest.js`)
+- **[issue-2262] The loop now catches near-duplicate proposals worded differently, not just exact-slug repeats.** The DECIDE layer's dedup was purely the reasoner-chosen slug (plus label) — so if the model proposed the same work under a fresh slug ("introduce-widget" vs an open "add-widget"), it slipped past and filed a second tracker issue. A semantic guard now runs *after* the slug guard passes: it embeds the proposal's title+body and each open (or recently-closed, within the same 30-day window) tracker issue via the local embeddings provider, and suppresses the proposal when a candidate's cosine similarity meets a conservative floor (`SEMANTIC_DEDUP_THRESHOLD = 0.9`). It's strictly best-effort and self-gating: when no embeddings provider is configured (or the proposal embed is skipped/fails) the check reports `available:false` and filing proceeds — slug dedup already guarded the exact case, so an unavailable semantic layer only restores prior behavior, never files a slug-duplicate. No cold-bootstrap risk (embeddings degrade to a no-op with no provider, and this only runs inside the user-enabled scheduled sweep), no new config field, and plan-tracked slug-only issues are simply not embeddable so they're skipped. Candidate embedding is capped per run (`SEMANTIC_DEDUP_MAX_CANDIDATES = 50`) so a large backlog can't fan out unboundedly, and the shared `isIssueWithinDedupWindow` helper keeps the semantic and slug guards agreeing on which issues still count. (`server/services/layeredIntelligence.js` `checkSemanticDuplicate`/`findSemanticDuplicate`/`cosineSimilarity`, `server/services/autonomousJobs/layeredIntelligenceHandler.js`)
## Creative Writing Quality Engine
diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.js b/server/services/autonomousJobs/layeredIntelligenceHandler.js
index 4c2e2f510b..f763a366c3 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHandler.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.js
@@ -24,6 +24,7 @@ import {
validateReasonerResponse,
isScopeAllowed,
isProposalDuplicate,
+ checkSemanticDuplicate,
filerForTracker,
trackerSupportsPause,
resolveBlockOnIssue,
@@ -172,6 +173,8 @@ export async function processApp(app, deps = {}) {
} else if (isProposalDuplicate({ slug: proposal.slug, existingIssues, now })) {
console.log(`♻️ Layered Intelligence: ${app.name} proposal "${proposal.slug}" is a duplicate — suppressed`)
filedAction = 'duplicate'
+ } else if (await isSemanticDuplicate(app, proposal, existingIssues, now)) {
+ filedAction = 'semantic-duplicate'
} else {
// ---- Layer 4: ACT (file exactly one) ----
const filed = await fileProposal({ filer, forgeCli, cwd, app, proposal, jira })
@@ -209,6 +212,23 @@ export async function processApp(app, deps = {}) {
return { app: app.id, action: filedAction, filedNumber, filedKey, paused }
}
+/**
+ * Semantic (embedding-similarity) near-duplicate check — the extra dedup layer
+ * that runs AFTER the exact slug dedup passes. Suppresses a proposal that restates
+ * an existing dedup-window issue in different words (different slug). Best-effort:
+ * when embeddings aren't configured it's `available:false` and we DON'T suppress
+ * (slug dedup already covered the exact case). Returns a boolean "should suppress".
+ */
+async function isSemanticDuplicate(app, proposal, existingIssues, now) {
+ const semantic = await checkSemanticDuplicate({ proposal, existingIssues, now })
+ if (!semantic.available || !semantic.duplicate) return false
+ const m = semantic.match
+ const ref = m?.number ? `#${m.number}` : (m?.slug || 'an existing issue')
+ const score = typeof m?.score === 'number' ? m.score.toFixed(2) : '?'
+ console.log(`♻️ Layered Intelligence: ${app.name} proposal "${proposal.slug}" is a near-duplicate of ${ref} (score ${score}) — suppressed`)
+ return true
+}
+
/** File the proposal via the resolved tracker's filer. */
async function fileProposal({ filer, forgeCli, cwd, app, proposal, jira }) {
if (filer === 'forge' && forgeCli) {
diff --git a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
index c9dae4f9fe..8fc5a50ee8 100644
--- a/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
+++ b/server/services/autonomousJobs/layeredIntelligenceHandler.test.js
@@ -34,7 +34,11 @@ const forgeState = {
jiraBlockingOk: true,
jiraFileResult: { success: true, key: 'PROJ-100' },
jiraFiled: [],
- jiraBlockingApplied: []
+ jiraBlockingApplied: [],
+ // Semantic dedup default: unavailable (embeddings off) → never suppresses.
+ // The real checkSemanticDuplicate lazy-imports embeddings.js; mock it so
+ // processApp orchestration is isolated from the embedding provider.
+ semanticResult: { available: false, duplicate: false, match: null }
};
vi.mock('../layeredIntelligence.js', async (importOriginal) => {
const actual = await importOriginal();
@@ -44,6 +48,7 @@ vi.mock('../layeredIntelligence.js', async (importOriginal) => {
// Listers now return { ok, issues }; forgeState.existingOk toggles a failed read.
listForgeIssues: vi.fn(async () => ({ ok: forgeState.existingOk, issues: forgeState.existing })),
listBlockingIssues: vi.fn(async () => ({ ok: forgeState.blockingOk, issues: forgeState.blocking })),
+ checkSemanticDuplicate: vi.fn(async () => forgeState.semanticResult),
fileProposalToForge: vi.fn(async (opts) => { forgeState.filed.push(opts); return forgeState.fileResult; }),
applyBlockingLabel: vi.fn(async (opts) => { forgeState.blockingApplied.push(opts); return { success: true }; }),
appendProposalToPlan: vi.fn(async () => ({ success: true, duplicate: false })),
@@ -80,6 +85,7 @@ beforeEach(() => {
forgeState.jiraFileResult = { success: true, key: 'PROJ-100' };
forgeState.jiraFiled = [];
forgeState.jiraBlockingApplied = [];
+ forgeState.semanticResult = { available: false, duplicate: false, match: null };
resolveTrackerMock.mockResolvedValue({ resolved: 'github', forge: 'gh' });
});
@@ -158,6 +164,26 @@ describe('processApp', () => {
expect(forgeState.filed).toHaveLength(0);
});
+ it('suppresses a semantic near-duplicate (different slug) when embeddings flag it', async () => {
+ // Slug does NOT match an existing issue, so slug dedup passes; the semantic
+ // layer reports a near-duplicate and suppresses before filing.
+ forgeState.existing = [{ number: 7, slug: 'add-widget', title: 'Add widget', body: 'do it', state: 'open' }];
+ forgeState.semanticResult = { available: true, duplicate: true, match: { number: 7, slug: 'add-widget', score: 0.95 } };
+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'introduce-widget', title: 'Introduce a widget', body: 'do it' } });
+ const out = await processApp(enabledApp(), { callLLM });
+ expect(out.action).toBe('semantic-duplicate');
+ expect(forgeState.filed).toHaveLength(0);
+ });
+
+ it('files when the semantic layer is unavailable (embeddings off) — best-effort only', async () => {
+ forgeState.existing = [{ number: 7, slug: 'add-widget', title: 'Add widget', body: 'do it', state: 'open' }];
+ forgeState.semanticResult = { available: false, duplicate: false, match: null };
+ const callLLM = reasoner({ proposal: { scope: 'app-improvement', slug: 'introduce-widget', title: 'Introduce a widget', body: 'do it' } });
+ const out = await processApp(enabledApp(), { callLLM });
+ expect(out.action).toBe('filed');
+ expect(forgeState.filed).toHaveLength(1);
+ });
+
it('files AND pauses when the response carries both, blocking on "this"', async () => {
const callLLM = reasoner({
proposal: { scope: 'app-improvement', slug: 'add-x', title: 'Add X' },
diff --git a/server/services/layeredIntelligence.js b/server/services/layeredIntelligence.js
index 8d59ca96fa..6253976937 100644
--- a/server/services/layeredIntelligence.js
+++ b/server/services/layeredIntelligence.js
@@ -42,6 +42,18 @@ export const LI_JIRA_BLOCKING_LABEL = 'layered-intelligence-blocking';
// so the loop doesn't immediately re-file something the user just resolved.
export const CLOSED_SUPPRESSION_MS = 30 * DAY;
+// Cosine-similarity floor for the semantic (embedding) near-duplicate guard that
+// layers atop the exact slug/label dedup. A proposal whose embedding is at least
+// this close to an existing dedup-window issue is treated as the same work worded
+// differently and suppressed. Deliberately conservative — only near-identical
+// intent should trip it (768-dim local embeddings put genuine near-dups ≳0.9).
+export const SEMANTIC_DEDUP_THRESHOLD = 0.9;
+
+// Cap the number of existing issues embedded per run so a repo with a large LI
+// backlog can't fan out into an unbounded embedding sweep. Open dedup-window
+// issues should be few (the loop files ≤1/run), so this is a generous ceiling.
+export const SEMANTIC_DEDUP_MAX_CANDIDATES = 50;
+
// The autonomous-job id that drives the whole loop (the global sweep). Single
// source of truth — the DEFAULT_JOBS catalog entry and the cross-app overview
// route both key on this so per-app enablement and the global on/off stay in
@@ -187,6 +199,19 @@ export function normalizeSlug(slug) {
return norm || null;
}
+/**
+ * Whether an existing tracker issue is still within the dedup suppression window:
+ * OPEN, or CLOSED within CLOSED_SUPPRESSION_MS. A closed-long-ago (or unknown
+ * close time, treated as long ago) issue falls out of the window so its work can
+ * be re-proposed. Shared by both the slug dedup and the semantic dedup so the two
+ * guards agree on which issues still count.
+ */
+export function isIssueWithinDedupWindow(issue, now = Date.now()) {
+ if ((issue?.state || '').toLowerCase() === 'open') return true;
+ const closedAt = issue?.closedAt ? Date.parse(issue.closedAt) : NaN;
+ return Number.isFinite(closedAt) && now - closedAt <= CLOSED_SUPPRESSION_MS;
+}
+
/**
* Deterministic dedup guard. Given the slug of the proposed item and the live
* tracker's existing issues (each `{ slug, state, closedAt }`), suppress the
@@ -203,16 +228,57 @@ export function isProposalDuplicate({ slug, existingIssues = [], now = Date.now(
? normalizeSlug(issue.slug)
: extractSlugFromBody(issue.body) || extractSlugFromBody(issue.title);
if (issueSlug !== target) continue;
- const state = (issue.state || '').toLowerCase();
- if (state === 'open') return true;
- // Closed within the suppression window still suppresses.
- const closedAt = issue.closedAt ? Date.parse(issue.closedAt) : NaN;
- if (Number.isFinite(closedAt) && now - closedAt <= CLOSED_SUPPRESSION_MS) return true;
- // Closed long ago (or unknown close time treated as long ago) → allow re-file.
+ if (isIssueWithinDedupWindow(issue, now)) return true;
}
return false;
}
+/**
+ * Build the text to embed for a proposal OR an existing issue — title + body,
+ * trimmed and length-capped so a single huge body can't blow the embedding
+ * model's context. Both sides go through THIS helper so the proposal and the
+ * candidates are embedded from the same seed shape (a fair comparison).
+ */
+export function issueEmbedSeed({ title = '', body = '' } = {}) {
+ const parts = [title, body].map(s => (typeof s === 'string' ? s.trim() : '')).filter(Boolean);
+ return parts.join('\n\n').slice(0, 2000);
+}
+
+/** Cosine similarity of two equal-length numeric vectors. Returns 0 for a shape
+ * mismatch, empty vector, or a zero-magnitude vector (nothing meaningful to
+ * compare) rather than NaN, so a bad embedding can never trip the dedup guard. */
+export function cosineSimilarity(a, b) {
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length === 0 || a.length !== b.length) return 0;
+ let dot = 0, na = 0, nb = 0;
+ for (let i = 0; i < a.length; i++) {
+ dot += a[i] * b[i];
+ na += a[i] * a[i];
+ nb += b[i] * b[i];
+ }
+ if (na === 0 || nb === 0) return 0;
+ return dot / (Math.sqrt(na) * Math.sqrt(nb));
+}
+
+/**
+ * Pure near-duplicate finder. Given the proposal's embedding and an array of
+ * candidates (each `{ slug?, number?, title?, embedding }`), return the single
+ * best candidate whose cosine similarity meets `threshold` (highest score wins),
+ * or null when none qualify / the proposal embedding is unusable. Side-effect-free
+ * and unit-tested; the I/O layer feeds it real embeddings.
+ */
+export function findSemanticDuplicate({ proposalEmbedding, candidates = [], threshold = SEMANTIC_DEDUP_THRESHOLD } = {}) {
+ if (!Array.isArray(proposalEmbedding) || proposalEmbedding.length === 0) return null;
+ let best = null;
+ for (const c of candidates) {
+ if (!Array.isArray(c?.embedding) || c.embedding.length === 0) continue;
+ const score = cosineSimilarity(proposalEmbedding, c.embedding);
+ if (score >= threshold && (!best || score > best.score)) {
+ best = { slug: c.slug || null, number: c.number ?? null, title: c.title || '', score };
+ }
+ }
+ return best;
+}
+
/**
* Whether the app is currently PARKED — i.e. has at least one OPEN blocking
* issue. When parked, the sweep skips the app entirely (no gather, no reason),
@@ -475,6 +541,60 @@ export async function confineToRepo(repo, ref) {
return realAbs;
}
+/** Lazily resolve the default embedder so the pure module doesn't statically pull
+ * in the embeddings/settings/provider graph (matches the handler's dynamic-import
+ * pattern for heavy deps). Only reached in production — tests inject `embed`. */
+async function defaultEmbed(text) {
+ const { embedText } = await import('./embeddings.js');
+ return embedText(text);
+}
+
+/**
+ * SEMANTIC dedup guard — the embedding-similarity layer ON TOP OF the exact
+ * slug/label dedup (`isProposalDuplicate`). Catches a proposal that describes the
+ * same work as an existing issue but was worded differently (so its slug differs).
+ * Runs only AFTER slug dedup passes, so it's a best-effort extra catch.
+ *
+ * Returns `{ available, duplicate, match }`:
+ * - `available:false` when semantic dedup couldn't run (no embeddable candidates,
+ * or the embeddings provider is off / the proposal embed failed). This is a
+ * SENTINEL, distinct from `available:true, duplicate:false` ("checked, no
+ * near-dup"): the handler treats unavailable as "proceed to file" because slug
+ * dedup already guarded the exact case — losing the semantic catch just
+ * restores pre-feature behavior, it never files a slug-duplicate.
+ * - `duplicate:true` with `match` = the highest-scoring near-duplicate issue.
+ *
+ * No cold-bootstrap risk: `embed` degrades to `{ skipped:true }` when no
+ * embeddings provider is configured, and this only runs inside the user-enabled
+ * scheduled sweep. `embed` is injectable for tests.
+ */
+export async function checkSemanticDuplicate({ proposal, existingIssues = [], now = Date.now(), embed = defaultEmbed, threshold = SEMANTIC_DEDUP_THRESHOLD } = {}) {
+ const unavailable = { available: false, duplicate: false, match: null };
+ if (!proposal || typeof proposal !== 'object') return unavailable;
+
+ // Only issues still within the dedup window with SOMETHING to embed are worth
+ // comparing; a plan-tracked slug-only issue (no title/body) can't be embedded.
+ const candidates = existingIssues
+ .filter(i => isIssueWithinDedupWindow(i, now) && (i.body || i.title))
+ .slice(0, SEMANTIC_DEDUP_MAX_CANDIDATES);
+ if (candidates.length === 0) return unavailable;
+
+ const proposalRes = await embed(issueEmbedSeed({ title: proposal.title, body: proposal.body }));
+ if (!proposalRes?.success || !Array.isArray(proposalRes.embedding)) return unavailable;
+
+ const embedded = [];
+ for (const c of candidates) {
+ const res = await embed(issueEmbedSeed({ title: c.title, body: c.body }));
+ if (res?.success && Array.isArray(res.embedding)) {
+ embedded.push({ slug: c.slug || null, number: c.number ?? null, title: c.title || '', embedding: res.embedding });
+ }
+ }
+ if (embedded.length === 0) return unavailable;
+
+ const match = findSemanticDuplicate({ proposalEmbedding: proposalRes.embedding, candidates: embedded, threshold });
+ return { available: true, duplicate: !!match, match };
+}
+
/**
* Normalize a forge issue state to `open` / `closed`. GitLab reports `opened`
* (and `closed`/`locked`); GitHub reports `open`/`closed`. Anything that isn't a
diff --git a/server/services/layeredIntelligence.test.js b/server/services/layeredIntelligence.test.js
index b4bcaa68d1..6146ee62aa 100644
--- a/server/services/layeredIntelligence.test.js
+++ b/server/services/layeredIntelligence.test.js
@@ -12,6 +12,13 @@ import {
extractSlugFromBody,
normalizeSlug,
isProposalDuplicate,
+ isIssueWithinDedupWindow,
+ cosineSimilarity,
+ findSemanticDuplicate,
+ issueEmbedSeed,
+ checkSemanticDuplicate,
+ SEMANTIC_DEDUP_THRESHOLD,
+ SEMANTIC_DEDUP_MAX_CANDIDATES,
isAppParked,
validateReasonerResponse,
resolveBlockOnIssue,
@@ -786,3 +793,133 @@ describe('Jira filer', () => {
expect(res.error).toContain('nope');
});
});
+
+describe('semantic dedup — pure helpers', () => {
+ const NOW = Date.parse('2026-07-07T00:00:00Z');
+
+ describe('isIssueWithinDedupWindow', () => {
+ it('open issues are always in-window', () => {
+ expect(isIssueWithinDedupWindow({ state: 'open' }, NOW)).toBe(true);
+ });
+ it('recently-closed issues are in-window; long-closed are not', () => {
+ const recent = new Date(NOW - 5 * 24 * 60 * 60 * 1000).toISOString();
+ const old = new Date(NOW - (CLOSED_SUPPRESSION_MS + 1000)).toISOString();
+ expect(isIssueWithinDedupWindow({ state: 'closed', closedAt: recent }, NOW)).toBe(true);
+ expect(isIssueWithinDedupWindow({ state: 'closed', closedAt: old }, NOW)).toBe(false);
+ });
+ it('closed with unknown close time falls out of window', () => {
+ expect(isIssueWithinDedupWindow({ state: 'closed' }, NOW)).toBe(false);
+ });
+ it('agrees with isProposalDuplicate on the window boundary', () => {
+ const old = new Date(NOW - (CLOSED_SUPPRESSION_MS + 1000)).toISOString();
+ const existing = [{ slug: 'add-x', state: 'closed', closedAt: old }];
+ expect(isProposalDuplicate({ slug: 'add-x', existingIssues: existing, now: NOW })).toBe(false);
+ const recent = new Date(NOW - 1000).toISOString();
+ const existing2 = [{ slug: 'add-x', state: 'closed', closedAt: recent }];
+ expect(isProposalDuplicate({ slug: 'add-x', existingIssues: existing2, now: NOW })).toBe(true);
+ });
+ });
+
+ describe('cosineSimilarity', () => {
+ it('is 1 for identical vectors and 0 for orthogonal', () => {
+ expect(cosineSimilarity([1, 2, 3], [1, 2, 3])).toBeCloseTo(1, 6);
+ expect(cosineSimilarity([1, 0], [0, 1])).toBeCloseTo(0, 6);
+ });
+ it('returns 0 (not NaN) for shape mismatch, empty, or zero-magnitude vectors', () => {
+ expect(cosineSimilarity([1, 2], [1, 2, 3])).toBe(0);
+ expect(cosineSimilarity([], [])).toBe(0);
+ expect(cosineSimilarity([0, 0], [1, 1])).toBe(0);
+ expect(cosineSimilarity('x', [1])).toBe(0);
+ });
+ });
+
+ describe('issueEmbedSeed', () => {
+ it('joins trimmed title + body and caps length', () => {
+ expect(issueEmbedSeed({ title: ' T ', body: ' B ' })).toBe('T\n\nB');
+ expect(issueEmbedSeed({ title: '', body: 'only body' })).toBe('only body');
+ expect(issueEmbedSeed({}).length).toBe(0);
+ expect(issueEmbedSeed({ title: 'x'.repeat(5000) }).length).toBe(2000);
+ });
+ });
+
+ describe('findSemanticDuplicate', () => {
+ it('returns the highest-scoring candidate above threshold', () => {
+ const p = [1, 0, 0];
+ const candidates = [
+ { slug: 'low', embedding: [0, 1, 0] }, // orthogonal → 0
+ { slug: 'high', number: 9, embedding: [1, 0, 0] }, // identical → 1
+ ];
+ const match = findSemanticDuplicate({ proposalEmbedding: p, candidates, threshold: 0.9 });
+ expect(match.slug).toBe('high');
+ expect(match.number).toBe(9);
+ expect(match.score).toBeCloseTo(1, 6);
+ });
+ it('returns null when nothing meets threshold, or the proposal embedding is unusable', () => {
+ expect(findSemanticDuplicate({ proposalEmbedding: [1, 0], candidates: [{ embedding: [0, 1] }], threshold: 0.9 })).toBe(null);
+ expect(findSemanticDuplicate({ proposalEmbedding: [], candidates: [{ embedding: [1] }] })).toBe(null);
+ expect(findSemanticDuplicate({ proposalEmbedding: [1], candidates: [{ embedding: [] }, {}] })).toBe(null);
+ });
+ });
+});
+
+describe('checkSemanticDuplicate — I/O wrapper', () => {
+ const NOW = Date.parse('2026-07-07T00:00:00Z');
+ const ok = (embedding) => ({ success: true, embedding });
+ const proposal = { title: 'Introduce widget', body: 'add it' };
+
+ it('is unavailable (never suppresses) when there are no embeddable candidates', async () => {
+ const embed = vi.fn(async () => ok([1, 0, 0]));
+ // plan-style slug-only issue has no title/body to embed
+ const res = await checkSemanticDuplicate({ proposal, existingIssues: [{ slug: 's', state: 'open' }], now: NOW, embed });
+ expect(res).toEqual({ available: false, duplicate: false, match: null });
+ expect(embed).not.toHaveBeenCalled();
+ });
+
+ it('is unavailable when the embeddings provider is off (skipped proposal embed)', async () => {
+ const embed = vi.fn(async () => ({ skipped: true, reason: 'provider-disabled' }));
+ const existing = [{ number: 3, title: 'Add widget', body: 'x', state: 'open' }];
+ const res = await checkSemanticDuplicate({ proposal, existingIssues: existing, now: NOW, embed });
+ expect(res.available).toBe(false);
+ expect(res.duplicate).toBe(false);
+ });
+
+ it('flags a near-duplicate when a candidate embedding is close enough', async () => {
+ const embed = vi.fn(async () => ok([1, 0, 0])); // proposal + candidate both identical → score 1
+ const existing = [{ number: 3, slug: 'add-widget', title: 'Add widget', body: 'x', state: 'open' }];
+ const res = await checkSemanticDuplicate({ proposal, existingIssues: existing, now: NOW, embed });
+ expect(res.available).toBe(true);
+ expect(res.duplicate).toBe(true);
+ expect(res.match.number).toBe(3);
+ });
+
+ it('checks but finds no duplicate when candidates are dissimilar', async () => {
+ const embed = vi.fn(async (text) => ok(text === issueEmbedSeed({ title: proposal.title, body: proposal.body }) ? [1, 0, 0] : [0, 1, 0]));
+ const existing = [{ number: 3, title: 'Unrelated', body: 'y', state: 'open' }];
+ const res = await checkSemanticDuplicate({ proposal, existingIssues: existing, now: NOW, embed });
+ expect(res.available).toBe(true);
+ expect(res.duplicate).toBe(false);
+ expect(res.match).toBe(null);
+ });
+
+ it('ignores long-closed candidates (out of the dedup window)', async () => {
+ const embed = vi.fn(async () => ok([1, 0, 0]));
+ const old = new Date(NOW - (CLOSED_SUPPRESSION_MS + 1000)).toISOString();
+ const existing = [{ number: 3, title: 'Add widget', body: 'x', state: 'closed', closedAt: old }];
+ const res = await checkSemanticDuplicate({ proposal, existingIssues: existing, now: NOW, embed });
+ expect(res.available).toBe(false);
+ expect(embed).not.toHaveBeenCalled();
+ });
+
+ it('caps the number of candidates embedded per run', async () => {
+ const embed = vi.fn(async () => ok([0, 1, 0])); // dissimilar so nothing matches
+ const existing = Array.from({ length: SEMANTIC_DEDUP_MAX_CANDIDATES + 20 }, (_, i) => ({ number: i, title: `t${i}`, body: 'b', state: 'open' }));
+ await checkSemanticDuplicate({ proposal, existingIssues: existing, now: NOW, embed });
+ // 1 proposal embed + at most SEMANTIC_DEDUP_MAX_CANDIDATES candidate embeds
+ expect(embed.mock.calls.length).toBe(SEMANTIC_DEDUP_MAX_CANDIDATES + 1);
+ });
+
+ it('respects the threshold constant default', () => {
+ expect(SEMANTIC_DEDUP_THRESHOLD).toBeGreaterThan(0);
+ expect(SEMANTIC_DEDUP_THRESHOLD).toBeLessThanOrEqual(1);
+ });
+});