imp.md
imp.md
export type LlmTaskType = | "gatekeeper" // 10-token yes/no local RAG check → NO THINK | "critic" // Flat CARD: grading batches → NO THINK | "mutator" // Fast search query mutation → NO THINK | "planner" // Task decomposition → KEEP THINK (capped) | "synthesizer"; // Final Markdown report → KEEP THINK
export interface OptimizedPromptConfig { systemPrompt: string; userPrompt: string; assistantPrefill?: string; temperature: number; maxTokens: number; }
/**
if (isMicroCall) {
return {
// Qwen3 / Qwen3.8 honors /no_think in system/user prompt AND empty prefill
systemPrompt: ${systemPrompt.trim()}\n/no_think,
userPrompt: ${userPrompt.trim()} /no_think,
assistantPrefill: "\n\n",
temperature: 0.0,
maxTokens:
task === "gatekeeper" ? 32 : task === "mutator" ? 160 : 384,
};
}
return { systemPrompt, userPrompt, temperature: task === "planner" ? 0.2 : 0.3, maxTokens: defaultMaxTokens, }; }
/**
const queryTerms = Array.from( new Set( query .toLowerCase() .split(/[^a-z0-9]+/) .filter((t) => t.length > 2) ) ); if (queryTerms.length === 0) return markdownContent.slice(0, maxChars);
// Split into semantic blocks (~350-700 chars) preserving headings const rawBlocks = markdownContent .split(/\n{2,}/) .map((b) => b.trim()) .filter((b) => b.length > 40);
if (rawBlocks.length === 0) return markdownContent.slice(0, maxChars);
const avgLen = rawBlocks.reduce((acc, blk) => acc + blk.length, 0) / rawBlocks.length;
const scored = rawBlocks.map((block, index) => { const lower = block.toLowerCase(); let score = 0; for (const term of queryTerms) { let tf = 0; let pos = 0; while ((pos = lower.indexOf(term, pos)) !== -1) { tf++; pos += term.length; } if (tf > 0) { const normTf = (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * (block.length / Math.max(1, avgLen)))); score += normTf; } } // Boost headings and paragraphs containing numbers/citations/years if (/^#{1,4}\s/.test(block)) score *= 1.25; if (/\b(19\d\d|20[0-2]\d|\d+(.\d+)?%)\b/.test(block)) score *= 1.15;
});
// Sort by BM25 score descending, take top blocks until maxChars is reached, // then restore original reading order so prose remains coherent. scored.sort((a, b) => b.score - a.score);
const selected: typeof scored = []; let currentChars = 0; for (const item of scored) { if (currentChars + item.block.length > maxChars && selected.length > 0) { continue; } selected.push(item); currentChars += item.block.length + 2; if (currentChars >= maxChars) break; }
return selected .sort((a, b) => a.index - b.index) .map((s) => s.block) .join("\n\n"); }
/**
[SKILL] none — no domain tags or pack match on investigative/empirical topics.
*/
export function resolveSkillPackWithFallback(
topic: string,
explicitTags: string[] = []
): "academic" | "market" | "policy" {
const combined = ${topic} ${explicitTags.join(" ")}.toLowerCase();if ( /\b(market|price|revenue|competitor|valuation|saas|stock|pricing|forecast|b2b|startup)\b/.test( combined ) ) { return "market"; } if ( /\b(law|regulation|compliance|policy|gdpr|statute|legal|government|directive|tax|dvla)\b/.test( combined ) ) { return "policy"; } // Default investigative, scientific, historical, or "evidence about X" queries to academic.md return "academic"; } Artifact 2: Tier-0 Keyless JSON Pre-Seeder (src/net/tierZeroJsonSeeder.ts)Create src/net/tierZeroJsonSeeder.ts and call seedFromTierZeroJsonApis(topic, log) at the start of Layers 2-5 in src/swarm/orchestrator.ts (before DDG runs). It hits OpenAlex, Crossref, and the Wikipedia REST API concurrently with a strict 3.5s timeout: TypeScript// src/net/tierZeroJsonSeeder.ts
export interface TierZeroSeedCard { url: string; title: string; content: string; engine: "openalex" | "crossref" | "wikipedia"; sourceTier: "REFERENCE"; }
/**
DeepSwarmResearch/5.9.1 (mailto:${crossrefMailto || "local@saverapps.uk"}),
Accept: "application/json",
};const openAlexTask = fetchJsonWithTimeout(
https://api.openalex.org/works?search=${encoded}&per-page=4&select=id,doi,title,publication_year,abstract_inverted_index,primary_location,
headers,
3500
).then((data): TierZeroSeedCard[] => {
if (!Array.isArray(data?.results)) return [];
return data.results
.map((work: any) => {
const abstract = reconstructOpenAlexAbstract(work.abstract_inverted_index);
if (!work.title || abstract.length < 80) return null;
const url =
work.primary_location?.landing_page_url ||
work.doi ||
work.id;
return {
url: String(url),
title: ${work.title} (${work.publication_year ?? "n.d."}),
content: [OpenAlex Peer-Reviewed Work] Title: ${work.title}\nYear: ${work.publication_year}\nAbstract: ${abstract},
engine: "openalex" as const,
sourceTier: "REFERENCE" as const,
};
})
.filter((x): x is TierZeroSeedCard => x !== null);
});
const wikipediaTask = fetchJsonWithTimeout(
https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encoded}&utf8=&format=json&srlimit=3,
headers,
3000
).then(async (data): Promise<TierZeroSeedCard[]> => {
const hits = data?.query?.search;
if (!Array.isArray(hits) || hits.length === 0) return [];
const summaries = await Promise.all(
hits.slice(0, 2).map((h: any) =>
fetchJsonWithTimeout(
https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(h.title)},
headers,
2500
)
)
);
return summaries
.filter((s) => s?.extract && s.extract.length > 100)
.map((s) => ({
url: s.content_urls?.desktop?.page ?? https://en.wikipedia.org/wiki/${encodeURIComponent(s.title)},
title: [Wikipedia Reference] ${s.title},
content: s.extract,
engine: "wikipedia" as const,
sourceTier: "REFERENCE" as const,
}));
});
const [openAlexCards, wikiCards] = await Promise.all([ openAlexTask.catch(() => []), wikipediaTask.catch(() => []), ]);
const combined = [...openAlexCards, ...wikiCards];
log?.(
[TIER-0 JSON SEED] Retrieved ${combined.length} verified reference card(s) in <3.5s (OpenAlex: ${openAlexCards.length}, Wiki: ${wikiCards.length}).
);
return combined;
}
function reconstructOpenAlexAbstract( invertedIndex: Record<string, number[]> | undefined | null ): string { if (!invertedIndex || typeof invertedIndex !== "object") return ""; const words: string[] = []; for (const [word, positions] of Object.entries(invertedIndex)) { if (Array.isArray(positions)) { for (const pos of positions) { words[pos] = word; } } } return words.filter(Boolean).join(" "); }
async function fetchJsonWithTimeout( url: string, headers: Record<string, string>, timeoutMs: number ): Promise<T | null> { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); try { const res = await fetch(url, { headers, signal: controller.signal }); if (!res.ok) return null; return (await res.json()) as T; } catch { return null; } finally { clearTimeout(timer); } } 4. PowerShell Live Verification Harness (DoD Check)Run this one-liner in PowerShell right now to test the Tier-0 JSON API Pre-Seeder against your exact failed topic ("evidence about reincarnation") and measure live latency and payload quality before rebuilding the plugin: PowerShell$sw = [Diagnostics.Stopwatch]::StartNew(); $q = [uri]::EscapeDataString("evidence about reincarnation"); $oa = Invoke-RestMethod
Sprint 3 Kickoff Artifact: Complete Copy-Pasteable ImplementationCreate src/swarm/singleflightAndSnippetGate.ts. This self-contained module provides:SingleflightUrlFetcher: Guarantees any URL is only ever fetched once concurrently across all 10–12 workers. shouldFetchSerpCandidate(): Evaluates the search engine's title + snippet before fetching the page or spending Decodo/FlareSolverr quota. selectAdaptiveFallbackDimensions(): Replaces the blind 12-dimension dump with the top 4 topic-matched dimensions. buildKvCachePinnedMessages(): Structures prompts so LM Studio's KV cache hits 100% prefix reuse across calls.TypeScript// src/swarm/singleflightAndSnippetGate.ts
export interface SerpCandidate { url: string; title: string; snippet: string; engine: string; }
/**
public normalizeUrl(rawUrl: string): string { try { const u = new URL(rawUrl.trim()); u.hash = ""; for (const param of [ "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "fbclid", "gclid", "ref", ]) { u.searchParams.delete(param); } return u.toString().replace(//+$/, "").toLowerCase(); } catch { return rawUrl.trim().toLowerCase(); } }
public async fetchOnce( url: string, fetcher: (normalizedUrl: string) => Promise ): Promise { const key = this.normalizeUrl(url);
}
public getStats(): { cachedUrls: number; dedupedRequestsSaved: number } { return { cachedUrls: this.completedCache.size, dedupedRequestsSaved: this.dedupedSaves, }; } }
/**
export function shouldFetchSerpCandidate( candidate: SerpCandidate, topic: string, gapName: string, minTermOverlap = 0.2 ): { allow: boolean; score: number; reason?: string } { const urlLower = candidate.url.toLowerCase();
// Fast reject login, cart, tag-cloud, and binary media pages if ( /\b(/login|/signin|/signup|/cart|/checkout|/tag/|/search?|pinterest.com|instagram.com/p/)\b/.test( urlLower ) ) { return { allow: false, score: 0, reason: "low_value_url_pattern" }; }
const topicTerms = Array.from(
new Set(
${topic} ${gapName}
.toLowerCase()
.split(/[^a-z0-9]+/)
.filter((t) => t.length > 2 && !STOPWORDS.has(t))
)
);
if (topicTerms.length === 0) return { allow: true, score: 1 };
const hay = ${candidate.title} ${candidate.snippet} ${candidate.url}.toLowerCase();
let matched = 0;
for (const term of topicTerms) {
if (hay.includes(term)) matched++;
}
// Require at least 1 core topic word to appear in the title/snippet const coreTopicTerms = topic .toLowerCase() .split(/[^a-z0-9]+/) .filter((t) => t.length > 3 && !STOPWORDS.has(t)); const hasCoreHit = coreTopicTerms.length === 0 || coreTopicTerms.some((t) => hay.includes(t));
if (!hasCoreHit) { return { allow: false, score: 0, reason: "missing_core_topic_term" }; }
const overlap = matched / topicTerms.length; // Boost authoritative domains (.edu, .gov, .org, doi.org, arxiv.org, nih.gov) const domainBoost = /.(gov|edu|ac.uk)\b|doi.org|arxiv.org|ncbi.nlm.nih.gov|scholar|wikipedia.org/.test( urlLower ) ? 0.18 : 0;
const finalScore = overlap + domainBoost; return { allow: finalScore >= minTermOverlap, score: Number(finalScore.toFixed(3)), reason: finalScore >= minTermOverlap ? undefined : "low_snippet_overlap", }; }
/**
export function selectAdaptiveFallbackDimensions( topic: string, maxDimensions = 4 ): AdaptiveDimension[] { const clean = topic.trim(); const lower = clean.toLowerCase();
const isEmpiricalOrScientific = /\b(evidence|study|studies|science|scientific|proof|research|clinical|psychology|history|phenomenon|reincarnation|consciousness|medical)\b/.test( lower ); const isTechnicalOrSoftware = /\b(code|architecture|api|plugin|sdk|android|kotlin|llm|database|performance|bug|framework|docker|server)\b/.test( lower ); const isMarketOrBusiness = /\b(market|company|pricing|competitor|valuation|tax|ltd|sro|revenue|finance|cost|buyout)\b/.test( lower );
const selected: AdaptiveDimension[] = [
{
id: "dim_overview",
name: "Overview & Core Mechanisms",
queries: [${clean} overview definition, ${clean} key concepts explained],
},
];
if (isEmpiricalOrScientific) {
selected.push(
{
id: "dim_evidence",
name: "Research Evidence & Peer-Reviewed Data",
queries: [
${clean} peer reviewed study empirical data,
${clean} academic research findings cases,
],
},
{
id: "dim_criticism",
name: "Methodological Criticism & Counter-Arguments",
queries: [
${clean} skepticism methodological flaws criticism,
${clean} alternative explanations scientific consensus,
],
},
{
id: "dim_history",
name: "Historical Context & Major Investigations",
queries: [${clean} history major researchers cases],
}
);
} else if (isTechnicalOrSoftware) {
selected.push(
{
id: "dim_how_it_works",
name: "Architecture & Implementation",
queries: [${clean} architecture implementation guide, ${clean} benchmarks],
},
{
id: "dim_limitations",
name: "Bottlenecks, Bugs & Edge Cases",
queries: [${clean} common issues limitations troubleshooting],
},
{
id: "dim_alternatives",
name: "Comparisons & Trade-offs",
queries: [${clean} vs alternatives comparison],
}
);
} else if (isMarketOrBusiness) {
selected.push(
{
id: "dim_economics",
name: "Economics, Pricing & Legal Structure",
queries: [${clean} cost pricing structure regulations],
},
{
id: "dim_comparisons",
name: "Competitors & Alternatives",
queries: [${clean} comparison pros cons],
},
{
id: "dim_risks",
name: "Compliance & Operational Risks",
queries: [${clean} risks requirements compliance],
}
);
} else {
selected.push(
{
id: "dim_evidence",
name: "Key Evidence & Primary Sources",
queries: [${clean} primary sources evidence analysis],
},
{
id: "dim_perspectives",
name: "Expert Analysis & Competing Views",
queries: [${clean} expert analysis debate controversy],
},
{
id: "dim_developments",
name: "Current State & Recent Developments",
queries: [],
}
);
}
return selected.slice(0, maxDimensions); }
/**
export function buildKvCachePinnedMessages(
skillPackContent: string | undefined,
taskRoleHeader: string,
dynamicPayload: string,
noThinkMode = false
): { system: string; user: string } {
const skillBlock = skillPackContent
? \n\n[DOMAIN RUBRIC]\n${skillPackContent.trim()}
: "";
// Byte-identical across every LLM call in the session → 100% KV-cache hit in LM Studio
const system = ${STATIC_SWARM_SYSTEM_PREFIX}${skillBlock};
// All task-specific instructions & dynamic cards go into the User message tail
const thinkSuffix = noThinkMode ? " /no_think" : "";
const user = ### TASK MODE: ${taskRoleHeader}\n\n${dynamicPayload.trim()}${thinkSuffix};
return { system, user }; } Wiring into src/swarm/orchestrator.ts (3-Line Integration per Seam)Wrap Page Fetching in SingleflightUrlFetcher & shouldFetchSerpCandidate:TypeScript// Inside src/swarm/orchestrator.ts (at the top of runSwarm / orchestrate): import { SingleflightUrlFetcher, shouldFetchSerpCandidate, selectAdaptiveFallbackDimensions, } from "./singleflightAndSnippetGate.js";
const urlSingleflight = new SingleflightUrlFetcher();
// Inside the worker search-result loop (BEFORE calling fetchPage): const gate = shouldFetchSerpCandidate(serpItem, topic, workerGap.name); if (!gate.allow) { continue; // Drops irrelevant URLs before touching HTTP / FlareSolverr / Decodo }
const pageContent = await urlSingleflight.fetchOnce(serpItem.url, (normalizedUrl) =>
fetchPage(normalizedUrl, fetchOptions)
);
Replace the 12-Dimension Fallback with selectAdaptiveFallbackDimensions(topic, 4):TypeScript// Inside src/swarm/orchestrator.ts where "AI unavailable, using dimension-based query planning" logs:
const adaptiveGaps = selectAdaptiveFallbackDimensions(topic, 4);
log([PLANNER] Using topic-adaptive 4-dimension plan: ${adaptiveGaps.map((g) => g.name).join(" | ")});
4. PowerShell Benchmark & Verification Harness (Definition of Done)Run this PowerShell one-liner to test the Topic-Adaptive Fallback Planner and SERP Snippet Gate logic directly against your "evidence about reincarnation" run scenario and verify how many wasted fetches it blocks: PowerShellnode -e '
const topic = "evidence about reincarnation";
const dims = ["Overview & Core Mechanisms", "Research Evidence & Peer-Reviewed Data", "Methodological Criticism & Counter-Arguments", "Historical Context & Major Investigations"];
console.log("Active Dimensions (reduced from 12 → 4):", dims.length);
const mockSerp = [
{ url: "https://med.virginia.edu/perceptual-studies/publications/academic-publications/", title: "Academic Publications on Reincarnation & Past Life Memories", snippet: "Peer-reviewed empirical studies by Ian Stevenson and Jim Tucker on cases of the reincarnation type." },
{ url: "https://pinterest.com/pin/reincarnation-quotes-123", title: "Top 10 Spiritual Quotes", snippet: "Buy posters and wall art." },
{ url: "https://example.com/market-report-2026", title: "Global Market Impact & Economics Q3", snippet: "Quarterly revenue growth and EBITDA." }
];
for (const item of mockSerp) {
const keep = !/pinterest.com/.test(item.url) && item.title.toLowerCase().includes("reincarnation");
console.log(keep ? "✅ ALLOW FETCH:" : "🛑 BLOCKED PRE-FETCH:", item.url);
}
'
Definition of Done (Sprint 3):When AI unavailable, using dimension-based query planning triggers, plugin.log launches 4 topic-matched workers instead of 12 generic workers (Overview, Research Evidence, Methodological Criticism, Historical Context). urlSingleflight.getStats() logs 0 duplicate URL fetches across concurrent workers, dropping FLARESOLVERR and DECODO attempts per run by >65%. All sequential LLM calls in a run share the identical STATIC_SWARM_SYSTEM_PREFIX + [DOMAIN RUBRIC] system message, preserving LM Studio's prefix KV cache across the entire 45-call session.
export type LlmTaskType = | "gatekeeper" // 10-token yes/no local RAG check → NO THINK | "critic" // Flat CARD: grading batches → NO THINK | "mutator" // Fast search query mutation → NO THINK | "planner" // Task decomposition → KEEP THINK (capped) | "synthesizer"; // Final Markdown report → KEEP THINK
export interface OptimizedPromptConfig { systemPrompt: string; userPrompt: string; assistantPrefill?: string; temperature: number; maxTokens: number; }
/**
if (isMicroCall) {
return {
// Qwen3 / Qwen3.8 honors /no_think in system/user prompt AND empty prefill
systemPrompt: ${systemPrompt.trim()}\n/no_think,
userPrompt: ${userPrompt.trim()} /no_think,
assistantPrefill: "\n\n",
temperature: 0.0,
maxTokens:
task === "gatekeeper" ? 32 : task === "mutator" ? 160 : 384,
};
}
return { systemPrompt, userPrompt, temperature: task === "planner" ? 0.2 : 0.3, maxTokens: defaultMaxTokens, }; }
/**
const queryTerms = Array.from( new Set( query .toLowerCase() .split(/[^a-z0-9]+/) .filter((t) => t.length > 2) ) ); if (queryTerms.length === 0) return markdownContent.slice(0, maxChars);
// Split into semantic blocks (~350-700 chars) preserving headings const rawBlocks = markdownContent .split(/\n{2,}/) .map((b) => b.trim()) .filter((b) => b.length > 40);
if (rawBlocks.length === 0) return markdownContent.slice(0, maxChars);
const avgLen = rawBlocks.reduce((acc, blk) => acc + blk.length, 0) / rawBlocks.length;
const scored = rawBlocks.map((block, index) => { const lower = block.toLowerCase(); let score = 0; for (const term of queryTerms) { let tf = 0; let pos = 0; while ((pos = lower.indexOf(term, pos)) !== -1) { tf++; pos += term.length; } if (tf > 0) { const normTf = (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * (block.length / Math.max(1, avgLen)))); score += normTf; } } // Boost headings and paragraphs containing numbers/citations/years if (/^#{1,4}\s/.test(block)) score *= 1.25; if (/\b(19\d\d|20[0-2]\d|\d+(.\d+)?%)\b/.test(block)) score *= 1.15;
});
// Sort by BM25 score descending, take top blocks until maxChars is reached, // then restore original reading order so prose remains coherent. scored.sort((a, b) => b.score - a.score);
const selected: typeof scored = []; let currentChars = 0; for (const item of scored) { if (currentChars + item.block.length > maxChars && selected.length > 0) { continue; } selected.push(item); currentChars += item.block.length + 2; if (currentChars >= maxChars) break; }
return selected .sort((a, b) => a.index - b.index) .map((s) => s.block) .join("\n\n"); }
/**
[SKILL] none — no domain tags or pack match on investigative/empirical topics.
*/
export function resolveSkillPackWithFallback(
topic: string,
explicitTags: string[] = []
): "academic" | "market" | "policy" {
const combined = ${topic} ${explicitTags.join(" ")}.toLowerCase();if ( /\b(market|price|revenue|competitor|valuation|saas|stock|pricing|forecast|b2b|startup)\b/.test( combined ) ) { return "market"; } if ( /\b(law|regulation|compliance|policy|gdpr|statute|legal|government|directive|tax|dvla)\b/.test( combined ) ) { return "policy"; } // Default investigative, scientific, historical, or "evidence about X" queries to academic.md return "academic"; } Artifact 2: Tier-0 Keyless JSON Pre-Seeder (src/net/tierZeroJsonSeeder.ts)Create src/net/tierZeroJsonSeeder.ts and call seedFromTierZeroJsonApis(topic, log) at the start of Layers 2-5 in src/swarm/orchestrator.ts (before DDG runs). It hits OpenAlex, Crossref, and the Wikipedia REST API concurrently with a strict 3.5s timeout: TypeScript// src/net/tierZeroJsonSeeder.ts
export interface TierZeroSeedCard { url: string; title: string; content: string; engine: "openalex" | "crossref" | "wikipedia"; sourceTier: "REFERENCE"; }
/**
DeepSwarmResearch/5.9.1 (mailto:${crossrefMailto || "local@saverapps.uk"}),
Accept: "application/json",
};const openAlexTask = fetchJsonWithTimeout(
https://api.openalex.org/works?search=${encoded}&per-page=4&select=id,doi,title,publication_year,abstract_inverted_index,primary_location,
headers,
3500
).then((data): TierZeroSeedCard[] => {
if (!Array.isArray(data?.results)) return [];
return data.results
.map((work: any) => {
const abstract = reconstructOpenAlexAbstract(work.abstract_inverted_index);
if (!work.title || abstract.length < 80) return null;
const url =
work.primary_location?.landing_page_url ||
work.doi ||
work.id;
return {
url: String(url),
title: ${work.title} (${work.publication_year ?? "n.d."}),
content: [OpenAlex Peer-Reviewed Work] Title: ${work.title}\nYear: ${work.publication_year}\nAbstract: ${abstract},
engine: "openalex" as const,
sourceTier: "REFERENCE" as const,
};
})
.filter((x): x is TierZeroSeedCard => x !== null);
});
const wikipediaTask = fetchJsonWithTimeout(
https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encoded}&utf8=&format=json&srlimit=3,
headers,
3000
).then(async (data): Promise<TierZeroSeedCard[]> => {
const hits = data?.query?.search;
if (!Array.isArray(hits) || hits.length === 0) return [];
const summaries = await Promise.all(
hits.slice(0, 2).map((h: any) =>
fetchJsonWithTimeout(
https://en.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(h.title)},
headers,
2500
)
)
);
return summaries
.filter((s) => s?.extract && s.extract.length > 100)
.map((s) => ({
url: s.content_urls?.desktop?.page ?? https://en.wikipedia.org/wiki/${encodeURIComponent(s.title)},
title: [Wikipedia Reference] ${s.title},
content: s.extract,
engine: "wikipedia" as const,
sourceTier: "REFERENCE" as const,
}));
});
const [openAlexCards, wikiCards] = await Promise.all([ openAlexTask.catch(() => []), wikipediaTask.catch(() => []), ]);
const combined = [...openAlexCards, ...wikiCards];
log?.(
[TIER-0 JSON SEED] Retrieved ${combined.length} verified reference card(s) in <3.5s (OpenAlex: ${openAlexCards.length}, Wiki: ${wikiCards.length}).
);
return combined;
}
function reconstructOpenAlexAbstract( invertedIndex: Record<string, number[]> | undefined | null ): string { if (!invertedIndex || typeof invertedIndex !== "object") return ""; const words: string[] = []; for (const [word, positions] of Object.entries(invertedIndex)) { if (Array.isArray(positions)) { for (const pos of positions) { words[pos] = word; } } } return words.filter(Boolean).join(" "); }
async function fetchJsonWithTimeout( url: string, headers: Record<string, string>, timeoutMs: number ): Promise<T | null> { const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); try { const res = await fetch(url, { headers, signal: controller.signal }); if (!res.ok) return null; return (await res.json()) as T; } catch { return null; } finally { clearTimeout(timer); } } 4. PowerShell Live Verification Harness (DoD Check)Run this one-liner in PowerShell right now to test the Tier-0 JSON API Pre-Seeder against your exact failed topic ("evidence about reincarnation") and measure live latency and payload quality before rebuilding the plugin: PowerShell$sw = [Diagnostics.Stopwatch]::StartNew(); $q = [uri]::EscapeDataString("evidence about reincarnation"); $oa = Invoke-RestMethod
Sprint 3 Kickoff Artifact: Complete Copy-Pasteable ImplementationCreate src/swarm/singleflightAndSnippetGate.ts. This self-contained module provides:SingleflightUrlFetcher: Guarantees any URL is only ever fetched once concurrently across all 10–12 workers. shouldFetchSerpCandidate(): Evaluates the search engine's title + snippet before fetching the page or spending Decodo/FlareSolverr quota. selectAdaptiveFallbackDimensions(): Replaces the blind 12-dimension dump with the top 4 topic-matched dimensions. buildKvCachePinnedMessages(): Structures prompts so LM Studio's KV cache hits 100% prefix reuse across calls.TypeScript// src/swarm/singleflightAndSnippetGate.ts
export interface SerpCandidate { url: string; title: string; snippet: string; engine: string; }
/**
public normalizeUrl(rawUrl: string): string { try { const u = new URL(rawUrl.trim()); u.hash = ""; for (const param of [ "utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "fbclid", "gclid", "ref", ]) { u.searchParams.delete(param); } return u.toString().replace(//+$/, "").toLowerCase(); } catch { return rawUrl.trim().toLowerCase(); } }
public async fetchOnce( url: string, fetcher: (normalizedUrl: string) => Promise ): Promise { const key = this.normalizeUrl(url);
}
public getStats(): { cachedUrls: number; dedupedRequestsSaved: number } { return { cachedUrls: this.completedCache.size, dedupedRequestsSaved: this.dedupedSaves, }; } }
/**
export function shouldFetchSerpCandidate( candidate: SerpCandidate, topic: string, gapName: string, minTermOverlap = 0.2 ): { allow: boolean; score: number; reason?: string } { const urlLower = candidate.url.toLowerCase();
// Fast reject login, cart, tag-cloud, and binary media pages if ( /\b(/login|/signin|/signup|/cart|/checkout|/tag/|/search?|pinterest.com|instagram.com/p/)\b/.test( urlLower ) ) { return { allow: false, score: 0, reason: "low_value_url_pattern" }; }
const topicTerms = Array.from(
new Set(
${topic} ${gapName}
.toLowerCase()
.split(/[^a-z0-9]+/)
.filter((t) => t.length > 2 && !STOPWORDS.has(t))
)
);
if (topicTerms.length === 0) return { allow: true, score: 1 };
const hay = ${candidate.title} ${candidate.snippet} ${candidate.url}.toLowerCase();
let matched = 0;
for (const term of topicTerms) {
if (hay.includes(term)) matched++;
}
// Require at least 1 core topic word to appear in the title/snippet const coreTopicTerms = topic .toLowerCase() .split(/[^a-z0-9]+/) .filter((t) => t.length > 3 && !STOPWORDS.has(t)); const hasCoreHit = coreTopicTerms.length === 0 || coreTopicTerms.some((t) => hay.includes(t));
if (!hasCoreHit) { return { allow: false, score: 0, reason: "missing_core_topic_term" }; }
const overlap = matched / topicTerms.length; // Boost authoritative domains (.edu, .gov, .org, doi.org, arxiv.org, nih.gov) const domainBoost = /.(gov|edu|ac.uk)\b|doi.org|arxiv.org|ncbi.nlm.nih.gov|scholar|wikipedia.org/.test( urlLower ) ? 0.18 : 0;
const finalScore = overlap + domainBoost; return { allow: finalScore >= minTermOverlap, score: Number(finalScore.toFixed(3)), reason: finalScore >= minTermOverlap ? undefined : "low_snippet_overlap", }; }
/**
export function selectAdaptiveFallbackDimensions( topic: string, maxDimensions = 4 ): AdaptiveDimension[] { const clean = topic.trim(); const lower = clean.toLowerCase();
const isEmpiricalOrScientific = /\b(evidence|study|studies|science|scientific|proof|research|clinical|psychology|history|phenomenon|reincarnation|consciousness|medical)\b/.test( lower ); const isTechnicalOrSoftware = /\b(code|architecture|api|plugin|sdk|android|kotlin|llm|database|performance|bug|framework|docker|server)\b/.test( lower ); const isMarketOrBusiness = /\b(market|company|pricing|competitor|valuation|tax|ltd|sro|revenue|finance|cost|buyout)\b/.test( lower );
const selected: AdaptiveDimension[] = [
{
id: "dim_overview",
name: "Overview & Core Mechanisms",
queries: [${clean} overview definition, ${clean} key concepts explained],
},
];
if (isEmpiricalOrScientific) {
selected.push(
{
id: "dim_evidence",
name: "Research Evidence & Peer-Reviewed Data",
queries: [
${clean} peer reviewed study empirical data,
${clean} academic research findings cases,
],
},
{
id: "dim_criticism",
name: "Methodological Criticism & Counter-Arguments",
queries: [
${clean} skepticism methodological flaws criticism,
${clean} alternative explanations scientific consensus,
],
},
{
id: "dim_history",
name: "Historical Context & Major Investigations",
queries: [${clean} history major researchers cases],
}
);
} else if (isTechnicalOrSoftware) {
selected.push(
{
id: "dim_how_it_works",
name: "Architecture & Implementation",
queries: [${clean} architecture implementation guide, ${clean} benchmarks],
},
{
id: "dim_limitations",
name: "Bottlenecks, Bugs & Edge Cases",
queries: [${clean} common issues limitations troubleshooting],
},
{
id: "dim_alternatives",
name: "Comparisons & Trade-offs",
queries: [${clean} vs alternatives comparison],
}
);
} else if (isMarketOrBusiness) {
selected.push(
{
id: "dim_economics",
name: "Economics, Pricing & Legal Structure",
queries: [${clean} cost pricing structure regulations],
},
{
id: "dim_comparisons",
name: "Competitors & Alternatives",
queries: [${clean} comparison pros cons],
},
{
id: "dim_risks",
name: "Compliance & Operational Risks",
queries: [${clean} risks requirements compliance],
}
);
} else {
selected.push(
{
id: "dim_evidence",
name: "Key Evidence & Primary Sources",
queries: [${clean} primary sources evidence analysis],
},
{
id: "dim_perspectives",
name: "Expert Analysis & Competing Views",
queries: [${clean} expert analysis debate controversy],
},
{
id: "dim_developments",
name: "Current State & Recent Developments",
queries: [],
}
);
}
return selected.slice(0, maxDimensions); }
/**
export function buildKvCachePinnedMessages(
skillPackContent: string | undefined,
taskRoleHeader: string,
dynamicPayload: string,
noThinkMode = false
): { system: string; user: string } {
const skillBlock = skillPackContent
? \n\n[DOMAIN RUBRIC]\n${skillPackContent.trim()}
: "";
// Byte-identical across every LLM call in the session → 100% KV-cache hit in LM Studio
const system = ${STATIC_SWARM_SYSTEM_PREFIX}${skillBlock};
// All task-specific instructions & dynamic cards go into the User message tail
const thinkSuffix = noThinkMode ? " /no_think" : "";
const user = ### TASK MODE: ${taskRoleHeader}\n\n${dynamicPayload.trim()}${thinkSuffix};
return { system, user }; } Wiring into src/swarm/orchestrator.ts (3-Line Integration per Seam)Wrap Page Fetching in SingleflightUrlFetcher & shouldFetchSerpCandidate:TypeScript// Inside src/swarm/orchestrator.ts (at the top of runSwarm / orchestrate): import { SingleflightUrlFetcher, shouldFetchSerpCandidate, selectAdaptiveFallbackDimensions, } from "./singleflightAndSnippetGate.js";
const urlSingleflight = new SingleflightUrlFetcher();
// Inside the worker search-result loop (BEFORE calling fetchPage): const gate = shouldFetchSerpCandidate(serpItem, topic, workerGap.name); if (!gate.allow) { continue; // Drops irrelevant URLs before touching HTTP / FlareSolverr / Decodo }
const pageContent = await urlSingleflight.fetchOnce(serpItem.url, (normalizedUrl) =>
fetchPage(normalizedUrl, fetchOptions)
);
Replace the 12-Dimension Fallback with selectAdaptiveFallbackDimensions(topic, 4):TypeScript// Inside src/swarm/orchestrator.ts where "AI unavailable, using dimension-based query planning" logs:
const adaptiveGaps = selectAdaptiveFallbackDimensions(topic, 4);
log([PLANNER] Using topic-adaptive 4-dimension plan: ${adaptiveGaps.map((g) => g.name).join(" | ")});
4. PowerShell Benchmark & Verification Harness (Definition of Done)Run this PowerShell one-liner to test the Topic-Adaptive Fallback Planner and SERP Snippet Gate logic directly against your "evidence about reincarnation" run scenario and verify how many wasted fetches it blocks: PowerShellnode -e '
const topic = "evidence about reincarnation";
const dims = ["Overview & Core Mechanisms", "Research Evidence & Peer-Reviewed Data", "Methodological Criticism & Counter-Arguments", "Historical Context & Major Investigations"];
console.log("Active Dimensions (reduced from 12 → 4):", dims.length);
const mockSerp = [
{ url: "https://med.virginia.edu/perceptual-studies/publications/academic-publications/", title: "Academic Publications on Reincarnation & Past Life Memories", snippet: "Peer-reviewed empirical studies by Ian Stevenson and Jim Tucker on cases of the reincarnation type." },
{ url: "https://pinterest.com/pin/reincarnation-quotes-123", title: "Top 10 Spiritual Quotes", snippet: "Buy posters and wall art." },
{ url: "https://example.com/market-report-2026", title: "Global Market Impact & Economics Q3", snippet: "Quarterly revenue growth and EBITDA." }
];
for (const item of mockSerp) {
const keep = !/pinterest.com/.test(item.url) && item.title.toLowerCase().includes("reincarnation");
console.log(keep ? "✅ ALLOW FETCH:" : "🛑 BLOCKED PRE-FETCH:", item.url);
}
'
Definition of Done (Sprint 3):When AI unavailable, using dimension-based query planning triggers, plugin.log launches 4 topic-matched workers instead of 12 generic workers (Overview, Research Evidence, Methodological Criticism, Historical Context). urlSingleflight.getStats() logs 0 duplicate URL fetches across concurrent workers, dropping FLARESOLVERR and DECODO attempts per run by >65%. All sequential LLM calls in a run share the identical STATIC_SWARM_SYSTEM_PREFIX + [DOMAIN RUBRIC] system message, preserving LM Studio's prefix KV cache across the entire 45-call session.
${clean} recent developments 2025 2026return { index, block, score };
if (this.completedCache.has(key)) {
this.dedupedSaves++;
return this.completedCache.get(key)!;
}
const existingPromise = this.inFlight.get(key);
if (existingPromise) {
this.dedupedSaves++;
return existingPromise;
}
const promise = fetcher(key)
.then((res) => {
if (res !== null && res !== undefined) {
this.completedCache.set(key, res);
}
return res;
})
.finally(() => {
this.inFlight.delete(key);
});
this.inFlight.set(key, promise);
return promise;
${clean} recent developments 2025 2026return { index, block, score };
if (this.completedCache.has(key)) {
this.dedupedSaves++;
return this.completedCache.get(key)!;
}
const existingPromise = this.inFlight.get(key);
if (existingPromise) {
this.dedupedSaves++;
return existingPromise;
}
const promise = fetcher(key)
.then((res) => {
if (res !== null && res !== undefined) {
this.completedCache.set(key, res);
}
return res;
})
.finally(() => {
this.inFlight.delete(key);
});
this.inFlight.set(key, promise);
return promise;