- Find a session
+ Keyword search
Day
@@ -243,6 +297,10 @@ Confirm selected favorites
let state;
let busy = false;
const selected = new Set();
+ const semantic = {
+ status: undefined, results: [], confirmedFavorites: new Set(), searching: false, checking: false,
+ request: 0, statusRequest: 0, controller: undefined, statusController: undefined,
+ };
const labels = {
copied: "Copied",
already_present: "Already present",
@@ -261,12 +319,12 @@ Confirm selected favorites
const dayKey = (session) => new Intl.DateTimeFormat("en-CA", {
timeZone: state.catalog.timeZone, year: "numeric", month: "2-digit", day: "2-digit",
}).format(new Date(session.startsAt));
- const dateText = (session) => new Intl.DateTimeFormat("en-US", {
- timeZone: state.catalog.timeZone, weekday: "short", month: "short", day: "numeric",
+ const dateText = (session, catalog = state?.catalog) => new Intl.DateTimeFormat("en-US", {
+ timeZone: catalog?.timeZone || "UTC", weekday: "short", month: "short", day: "numeric",
}).format(new Date(session.startsAt));
- const timeText = (session) => {
+ const timeText = (session, catalog = state?.catalog) => {
const format = new Intl.DateTimeFormat("en-US", {
- timeZone: state.catalog.timeZone, hour: "numeric", minute: "2-digit", timeZoneName: "short",
+ timeZone: catalog?.timeZone || "UTC", hour: "numeric", minute: "2-digit", timeZoneName: "short",
});
return `${format.format(new Date(session.startsAt))} - ${format.format(new Date(session.endsAt))}`;
};
@@ -304,7 +362,7 @@ Confirm selected favorites
? "Exercise 1 — Read the catalog" : "Exercise 2 — Save your first favorite";
$("exercise-help").textContent = step === 1
? "Your database is reachable. Implement listSessions to make its catalog appear; this is an expected exercise checkpoint, not a system failure."
- : "The catalog is working. Implement saveFavorite, then try Save favorite again. Your existing favorites have not been reset.";
+ : "Saving favorites uses the core lab’s saveFavorite. Implement it, then try Save favorite again. Your existing favorites have not been reset.";
$("exercise-guide").href = `https://github.com/documentdb/ato-2026-workshop/blob/main/docs/lab.md#${step === 1 ? "2-read-the-catalog" : "3-save-favorites-and-prove-persistence"}`;
} else {
$("exercise").hidden = true;
@@ -347,6 +405,7 @@ Confirm selected favorites
$("copy").disabled = busy || !state || !selected.size || !config.targets.some((target) => target.id === destination());
document.querySelectorAll(".save-favorite, .favorite-choice input").forEach((element) => { element.disabled = busy; });
$("confirm-copy").disabled = busy;
+ semanticControls();
}
function renderConfiguration() {
@@ -394,21 +453,7 @@ Confirm selected favorites
if (conflicts.has(session.id)) card.append(node("p", state.catalog.kind === "official" ? "Overlapping published time block" : "Overlaps another favorite", "conflict"));
const actions = node("div", undefined, "actions");
const saved = favorites.has(session.id);
- const button = node("button", saved ? "Remove favorite" : "Save favorite", `save-favorite${saved ? "" : " primary"}`);
- button.type = "button";
- button.setAttribute("aria-label", `${saved ? "Remove" : "Save"} favorite: ${session.title}`);
- button.addEventListener("click", () => {
- if (saved && !window.confirm(`Remove "${session.title}" from this database's favorites? Copies in the other database will remain.`)) return;
- perform(async () => {
- await api("/api/favorites", {
- method: saved ? "DELETE" : "POST",
- body: JSON.stringify({ target: config.target, sessionId: session.id }),
- });
- await loadState();
- $("exercise").hidden = true;
- notice("message", saved ? "Removed from the active database only." : "Favorite saved in the active database.");
- });
- });
+ const button = favoriteButton(session, saved, config.target);
const link = node("a", "Source");
link.href = session.url;
link.target = "_blank";
@@ -441,9 +486,228 @@ Confirm selected favorites
if (state.orphanedFavorites.length) {
notice("error", `${state.orphanedFavorites.length} favorite(s) have no matching session. Review catalog drift before exporting or copying.`);
}
+ renderSemanticResults();
controls();
}
+ // Both result surfaces use the core favorite endpoint (and its TODO 2).
+ // Capture the card's target: a stale card must never write to a new target.
+ function favoriteButton(session, saved, target) {
+ const button = node("button", saved ? "Remove favorite" : "Save favorite", `save-favorite${saved ? "" : " primary"}`);
+ button.type = "button";
+ button.disabled = busy;
+ button.setAttribute("aria-label", `${saved ? "Remove" : "Save"} favorite: ${session.title}`);
+ button.addEventListener("click", () => {
+ if (target !== config.target) return;
+ if (saved && !window.confirm(`Remove "${session.title}" from this database's favorites? Copies in the other database will remain.`)) return;
+ return perform(async () => {
+ await api("/api/favorites", {
+ method: saved ? "DELETE" : "POST",
+ body: JSON.stringify({ target, sessionId: session.id }),
+ });
+ saved ? semantic.confirmedFavorites.delete(session.id) : semantic.confirmedFavorites.add(session.id);
+ renderSemanticResults();
+ notice("message", saved ? "Removed from the active database only." : "Favorite saved in the active database.");
+ await loadState();
+ $("exercise").hidden = true;
+ });
+ });
+ return button;
+ }
+
+ function semanticControls() {
+ const ready = semantic.status?.ready && semantic.status?.enabled && semantic.status.target === config?.target;
+ const query = $("semantic-query").value.trim();
+ $("semantic-submit").disabled = busy || semantic.checking || semantic.searching || !ready || !query || query.length > 500;
+ $("semantic-cancel").disabled = !semantic.searching;
+ $("semantic-retry").disabled = busy || semantic.checking || !config;
+ $("semantic-day").disabled = !ready;
+ $("semantic-track").disabled = !ready;
+ $("semantic-results").setAttribute("aria-busy", String(semantic.searching));
+ }
+
+ function clearSemanticResults() {
+ semantic.results = [];
+ $("semantic-results").replaceChildren();
+ $("semantic-inspector-json").textContent = "";
+ $("semantic-inspector").hidden = true;
+ $("semantic-inspector").open = false;
+ }
+
+ function cancelSemanticSearch(message = "") {
+ semantic.request++;
+ semantic.controller?.abort();
+ semantic.controller = undefined;
+ semantic.searching = false;
+ clearSemanticResults();
+ $("semantic-message").textContent = message;
+ semanticControls();
+ }
+
+ function semanticOptions(id, values, allText) {
+ const select = $(id);
+ const previous = select.value;
+ const all = node("option", allText);
+ all.value = "";
+ select.replaceChildren(all);
+ for (const value of values) {
+ const option = node("option", value);
+ option.value = value;
+ select.append(option);
+ }
+ select.value = values.includes(previous) ? previous : "";
+ }
+
+ function resetSemanticTarget() {
+ cancelSemanticSearch();
+ semantic.statusRequest++;
+ semantic.statusController?.abort();
+ semantic.statusController = undefined;
+ semantic.status = undefined;
+ semantic.confirmedFavorites.clear();
+ semantic.checking = false;
+ $("semantic-query").value = "";
+ $("semantic-status").textContent = "Check optional search readiness for the selected database.";
+ $("semantic-model").textContent = "";
+ $("semantic-catalog").textContent = "";
+ semanticOptions("semantic-day", [], "All days");
+ semanticOptions("semantic-track", [], "All tracks");
+ semanticControls();
+ }
+
+ async function loadSemanticStatus() {
+ if (!config) return;
+ cancelSemanticSearch();
+ const target = config.target;
+ const request = ++semantic.statusRequest;
+ semantic.statusController?.abort();
+ const controller = new AbortController();
+ semantic.statusController = controller;
+ semantic.checking = true;
+ semantic.status = undefined;
+ $("semantic-model").textContent = "";
+ $("semantic-catalog").textContent = "";
+ $("semantic-status").textContent = "Checking optional search readiness...";
+ semanticControls();
+ try {
+ const next = await api("/api/search/status", { signal: controller.signal });
+ if (request !== semantic.statusRequest || config.target !== target) return;
+ if (next.target !== target) throw new Error("The target changed in another tab. Refresh the planner before searching.");
+ semantic.status = next;
+ const ready = next.enabled && next.ready;
+ $("semantic-status").textContent = ready
+ ? `Built-in meaning search ready on ${label(target)}. ${next.message || ""}`.trim()
+ : `Meaning search ${next.enabled ? "not ready" : "disabled"} on ${label(target)}. ${next.code ? next.code + ": " : ""}${next.message || "Run the optional preparation, then check readiness again."} Keyword browsing remains separate.`;
+ if (next.model) {
+ $("semantic-model").textContent = `Embedding model: ${next.model.name || "not configured"} / Digest: ${next.model.digest || "unavailable"} / Dimensions: ${next.model.dimensions ?? "unavailable"}`;
+ }
+ if (next.catalog) {
+ $("semantic-catalog").textContent = `${next.catalog.title} / Snapshot: ${next.catalog.snapshotDate} / Times: ${next.catalog.timeZone}. ${next.catalog.source}`;
+ }
+ semanticOptions("semantic-day", next.filters?.days || [], "All days");
+ semanticOptions("semantic-track", next.filters?.tracks || [], "All tracks");
+ } catch (error) {
+ if (request !== semantic.statusRequest || config.target !== target) return;
+ $("semantic-status").textContent = `Meaning search unavailable: ${error.message} No keyword fallback was used. Retry readiness or use the separate keyword browser.`;
+ } finally {
+ if (request === semantic.statusRequest) {
+ semantic.checking = false;
+ semantic.statusController = undefined;
+ semanticControls();
+ }
+ }
+ }
+
+ function renderSemanticResults() {
+ $("semantic-results").replaceChildren();
+ if (semantic.status?.target !== config?.target) return;
+ const favorites = new Set(state?.target === config.target ? state.favorites : semantic.confirmedFavorites);
+ const conflicts = new Set(state?.target === config.target ? state.conflicts.flat() : []);
+ const catalog = semantic.status.catalog || state?.catalog;
+ for (const result of semantic.results) {
+ const { session } = result;
+ const saved = favorites.has(session.id);
+ const item = node("li");
+ const card = node("article", undefined, `session${saved ? " saved" : ""}`);
+ card.append(node("p", `Rank ${result.rank} / Cosine similarity: ${Number(result.similarity).toFixed(3)}`, "meta"));
+ card.append(node("span", session.track, "tag"), node("h3", session.title));
+ card.append(node("p", `${dateText(session, catalog)} / ${timeText(session, catalog)}`, "meta"));
+ card.append(node("p", session.room, "meta"));
+ if (conflicts.has(session.id)) card.append(node("p", catalog?.kind === "official" ? "Overlapping published time block" : "Overlaps another favorite", "conflict"));
+ const evidence = node("details");
+ evidence.append(node("summary", "Matching metadata (not a generated explanation)"));
+ evidence.append(node("p", `Title: ${result.evidence.title}`, "meta"), node("p", `Track: ${result.evidence.track}`, "meta"));
+ card.append(evidence);
+ const actions = node("div", undefined, "actions");
+ actions.append(favoriteButton(session, saved, semantic.status.target));
+ // Server-provided catalog links are text-safe and restricted to web URLs.
+ try {
+ const url = new URL(session.url);
+ if (["https:", "http:"].includes(url.protocol)) {
+ const link = node("a", "Source (opens new tab)");
+ link.href = url.href;
+ link.target = "_blank";
+ link.rel = "noopener noreferrer";
+ actions.append(link);
+ }
+ } catch { /* Missing source metadata is not a navigable link. */ }
+ card.append(actions);
+ item.append(card);
+ $("semantic-results").append(item);
+ }
+ }
+
+ async function searchByMeaning(event) {
+ event?.preventDefault();
+ if (busy || semantic.searching || semantic.checking) return;
+ const query = $("semantic-query").value.trim();
+ if (!query || query.length > 500) {
+ cancelSemanticSearch("Enter a query of 1 to 500 characters.");
+ return;
+ }
+ if (!semantic.status?.ready || !semantic.status.enabled || semantic.status.target !== config?.target) {
+ cancelSemanticSearch("Meaning search is not ready. Check search readiness first; keyword browsing is separate.");
+ return;
+ }
+ const day = $("semantic-day").value;
+ const track = $("semantic-track").value;
+ if ((day && !semantic.status.filters?.days?.includes(day)) || (track && !semantic.status.filters?.tracks?.includes(track))) {
+ cancelSemanticSearch("Choose a day and track from this target's available search filters.");
+ return;
+ }
+ cancelSemanticSearch();
+ const request = semantic.request;
+ const target = config.target;
+ const controller = new AbortController();
+ semantic.controller = controller;
+ semantic.searching = true;
+ $("semantic-message").textContent = "Searching by meaning... A cold model can take 30 seconds. You can cancel or keep using the keyword browser.";
+ semanticControls();
+ try {
+ const response = await api("/api/search", {
+ method: "POST", signal: controller.signal,
+ body: JSON.stringify({ target, query, limit: 5, ...(day ? { day } : {}), ...(track ? { track } : {}) }),
+ });
+ if (request !== semantic.request || config.target !== target) return;
+ if (response.target !== target) throw new Error("The target changed in another tab. Refresh the planner before searching.");
+ semantic.results = response.results;
+ renderSemanticResults();
+ $("semantic-inspector-json").textContent = JSON.stringify(response.inspector, null, 2);
+ $("semantic-inspector").hidden = false;
+ $("semantic-message").textContent = `${response.results.length ? `${response.results.length} ranked match(es).` : "No sessions met the semantic cutoff with these filters. Try a different question or broaden the filters."}${response.message ? " " + response.message : ""} Similarity is not confidence or probability.`;
+ } catch (error) {
+ if (request !== semantic.request || config.target !== target) return;
+ clearSemanticResults();
+ $("semantic-message").textContent = `Meaning search failed: ${error.message} No keyword fallback was used. Check readiness and retry, or use the separate keyword browser.`;
+ } finally {
+ if (request === semantic.request) {
+ semantic.searching = false;
+ semantic.controller = undefined;
+ controls();
+ }
+ }
+ }
+
async function loadState() {
const next = await api("/api/state");
if (next.target !== config.target) throw new Error("The target changed in another tab. Refresh before continuing.");
@@ -464,6 +728,7 @@ Confirm selected favorites
}
async function refresh() {
+ resetSemanticTarget();
state = undefined;
selected.clear();
$("exercise").hidden = true;
@@ -480,19 +745,42 @@ Confirm selected favorites
notice("catalog-notice", "");
notice("message", "");
$("status").textContent = "Checking the selected database...";
- config = await api("/api/config");
+ try {
+ config = await api("/api/config");
+ } catch (error) {
+ $("semantic-status").textContent = "Search readiness could not be checked because app configuration is unavailable. Refresh the planner to retry.";
+ throw error;
+ }
renderConfiguration();
+ // Readiness handles its own errors. Neither a slow optional status probe
+ // nor the starter's TODO 1 should block the other, independent surface.
+ void loadSemanticStatus();
await api("/api/health");
$("status").textContent = "Database reachable. No other environment was used.";
await loadState();
}
+ $("semantic-form").addEventListener("submit", searchByMeaning);
+ $("semantic-cancel").addEventListener("click", () => cancelSemanticSearch("Search canceled. No results from that request will be shown."));
+ $("semantic-retry").addEventListener("click", loadSemanticStatus);
+ $("semantic-query").addEventListener("input", () => cancelSemanticSearch());
+ for (const id of ["semantic-day", "semantic-track"]) {
+ $(id).addEventListener("change", () => cancelSemanticSearch());
+ }
+ for (const id of ["semantic-chip-local", "semantic-chip-security", "semantic-chip-accessibility"]) {
+ $(id).addEventListener("click", () => {
+ $("semantic-query").value = $(id).textContent;
+ cancelSemanticSearch();
+ $("semantic-query").focus();
+ });
+ }
$("refresh").addEventListener("click", () => perform(refresh));
$("search").addEventListener("input", render);
$("day").addEventListener("change", render);
$("target-select").addEventListener("change", controls);
$("switch-target").addEventListener("click", () => perform(async () => {
const nextTarget = $("target-select").value;
+ resetSemanticTarget();
await api("/api/target", {
method: "POST",
body: JSON.stringify({ target: config.target, nextTarget }),
diff --git a/src/search-bundle-pin.js b/src/search-bundle-pin.js
new file mode 100644
index 0000000..2872ca8
--- /dev/null
+++ b/src/search-bundle-pin.js
@@ -0,0 +1,10 @@
+// Generated by the explicit maintainer workflow. Review with both data/search assets.
+// A manifest cannot authorize itself: production also requires these source pins.
+export const SEARCH_BUNDLE_PIN = Object.freeze({
+ "version": "ato-session-embeddings-v1",
+ "count": 216,
+ "manifestBytes": 69657,
+ "manifestSha256": "4b0c03a82b77eee871ef3d2a29b8176f2a994e31a5a9e94ee058532247929da0",
+ "dataBytes": 663552,
+ "dataSha256": "f1f6ae30c6550fdd14cb80fa0ad9d2876b86b2e8faf8784308a6bf669c19b582"
+});
diff --git a/src/search-bundle.js b/src/search-bundle.js
new file mode 100644
index 0000000..4797e15
--- /dev/null
+++ b/src/search-bundle.js
@@ -0,0 +1,73 @@
+import { createHash } from "node:crypto";
+import { open } from "node:fs/promises";
+import { constants } from "node:fs";
+import { WorkshopError } from "./errors.js";
+import { SEARCH_MODEL, checkedVector } from "./search-model.js";
+import { hash, documentText, TEXT_VERSION } from "./search-contract.js";
+import { SEARCH_BUNDLE_PIN } from "./search-bundle-pin.js";
+
+export const BUNDLE_VERSION = "ato-session-embeddings-v1";
+export const BUNDLE_ENCODING = "float32-le-row-major";
+export const BUNDLE_NORMALIZATION = "l2-float64-then-float32-v1";
+export const BUNDLE_FILES = Object.freeze({ manifest: "session-embeddings.manifest.json", data: "session-embeddings.f32" });
+export const byteHash = (bytes) => createHash("sha256").update(bytes).digest("hex");
+const MAX_MANIFEST_BYTES = 150000;
+const MAX_DATA_BYTES = 2000 * 768 * 4;
+const invalid = () => new WorkshopError(409, "SEARCH_BUNDLE_INVALID", "The checked-in session embedding bundle is missing, corrupt or incompatible with this catalog/model. Restore the reviewed bundle and pin, or use the explicit maintainer regeneration workflow. No document embeddings were generated or database rows changed as a fallback.");
+
+async function boundedFile(name, maximum) {
+ // Only these fixed repository assets, never an input-selected path or URL.
+ const file = await open(new URL(`../data/search/${name}`, import.meta.url), constants.O_RDONLY | constants.O_NOFOLLOW);
+ try {
+ const info = await file.stat();
+ if (!info.isFile() || info.size < 1 || info.size > maximum) throw invalid();
+ const bytes = Buffer.alloc(info.size);
+ let offset = 0;
+ while (offset < bytes.length) {
+ const { bytesRead } = await file.read(bytes, offset, bytes.length - offset, offset);
+ if (!bytesRead) throw invalid();
+ offset += bytesRead;
+ }
+ if ((await file.stat()).size !== bytes.length) throw invalid();
+ return bytes;
+ } finally { await file.close(); }
+}
+
+// Pure decoder exported for offline corruption tests and maintainer validation.
+// Production never supplies a caller-controlled pin; readSearchBundle uses the
+// separately reviewed source pin, so changing only the manifest is insufficient.
+export function decodeSearchBundle(manifestBytes, dataBytes, catalog, pin = SEARCH_BUNDLE_PIN) {
+ try {
+ if (!Buffer.isBuffer(manifestBytes) || !Buffer.isBuffer(dataBytes) || manifestBytes.length > MAX_MANIFEST_BYTES || dataBytes.length > MAX_DATA_BYTES ||
+ manifestBytes.length !== pin.manifestBytes || dataBytes.length !== pin.dataBytes ||
+ byteHash(manifestBytes) !== pin.manifestSha256 || byteHash(dataBytes) !== pin.dataSha256) throw invalid();
+ const manifest = JSON.parse(manifestBytes.toString("utf8"));
+ if (manifest.version !== BUNDLE_VERSION || pin.version !== BUNDLE_VERSION || manifest.catalogFingerprint !== catalog.fingerprint ||
+ manifest.model?.name !== SEARCH_MODEL.name || manifest.model?.digest !== SEARCH_MODEL.digest || manifest.model?.dimensions !== SEARCH_MODEL.dimensions ||
+ manifest.textVersion !== TEXT_VERSION || manifest.normalization !== BUNDLE_NORMALIZATION || manifest.encoding !== BUNDLE_ENCODING ||
+ manifest.count !== catalog.sessions.length || manifest.count !== pin.count || dataBytes.length !== manifest.count * SEARCH_MODEL.dimensions * 4 ||
+ manifest.data?.file !== BUNDLE_FILES.data || manifest.data?.sha256 !== pin.dataSha256 || manifest.data?.bytes !== dataBytes.length ||
+ !Array.isArray(manifest.sessions) || manifest.sessions.length !== manifest.count) throw invalid();
+ const ordered = [...catalog.sessions].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
+ const rows = new Map();
+ for (let index = 0; index < ordered.length; index++) {
+ const session = ordered[index];
+ const entry = manifest.sessions[index];
+ if (!entry || entry.id !== session.id || rows.has(entry.id) || entry.sourceHash !== hash(session) || entry.textHash !== hash(documentText(session))) throw invalid();
+ const embedding = Array.from({ length: SEARCH_MODEL.dimensions }, (_, axis) => dataBytes.readFloatLE((index * SEARCH_MODEL.dimensions + axis) * 4));
+ checkedVector(embedding);
+ if (entry.vectorHash !== hash(embedding)) throw invalid();
+ rows.set(entry.id, Object.freeze({ ...entry, embedding: Object.freeze(embedding) }));
+ }
+ return { version: manifest.version, digest: pin.manifestSha256, dataDigest: pin.dataSha256, manifest, rows };
+ } catch { throw invalid(); }
+}
+
+export async function readSearchBundle(catalog) {
+ try {
+ const [manifest, data] = await Promise.all([
+ boundedFile(BUNDLE_FILES.manifest, MAX_MANIFEST_BYTES), boundedFile(BUNDLE_FILES.data, MAX_DATA_BYTES),
+ ]);
+ return decodeSearchBundle(manifest, data, catalog);
+ } catch { throw invalid(); }
+}
diff --git a/src/search-contract.js b/src/search-contract.js
new file mode 100644
index 0000000..dd3ebdc
--- /dev/null
+++ b/src/search-contract.js
@@ -0,0 +1,19 @@
+import { createHash } from "node:crypto";
+import { SEARCH_MODEL } from "./search-model.js";
+
+export const SEARCH_COLLECTION = "session_search";
+export const SEARCH_META = "search_meta";
+export const SEARCH_OWNER = "ato-workshop-semantic-search-v1";
+export const TEXT_VERSION = 1;
+export const SEARCH_INDEX = Object.freeze({
+ name: "session_meaning_ivf", key: { embedding: "cosmosSearch" },
+ cosmosSearchOptions: { kind: "vector-ivf", numLists: 1, similarity: "COS", dimensions: 768 },
+});
+export const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
+export const documentText = (session) => `search_document: ${session.title}\nTrack: ${session.track}`;
+export function sessionDay(session, catalog) {
+ return new Intl.DateTimeFormat("en-CA", { timeZone: catalog.timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(new Date(session.startsAt));
+}
+export function searchFields(session, catalog) {
+ return { ...session, day: sessionDay(session, catalog), sourceHash: hash(session), textHash: hash(documentText(session)), modelDigest: SEARCH_MODEL.digest, textVersion: TEXT_VERSION, schemaVersion: 1 };
+}
diff --git a/src/search-model.js b/src/search-model.js
new file mode 100644
index 0000000..7816d17
--- /dev/null
+++ b/src/search-model.js
@@ -0,0 +1,105 @@
+import { WorkshopError } from "./errors.js";
+
+// Fixed internal Compose service only: never accept a request-supplied model URL.
+export const MODEL_URL = "http://search-model:11434";
+export const SEARCH_MODEL = Object.freeze({
+ name: "nomic-embed-text:v1.5",
+ digest: "0a109f422b47e3a30ba2b10eca18548e944e8a23073ee3f3e947efcf3c45e59f",
+ dimensions: 768,
+});
+export const MODEL_MAX_BYTES = 400_000_000;
+export const MODEL_BATCH = 4;
+
+export function checkedVector(vector) {
+ if (!Array.isArray(vector) || vector.length !== SEARCH_MODEL.dimensions ||
+ Array.from(vector).some((n) => typeof n !== "number" || !Number.isFinite(n))) {
+ throw new WorkshopError(503, "SEARCH_VECTOR_INVALID", "Search requires finite 768-dimensional embeddings. No keyword fallback was used.");
+ }
+ const norm = Math.sqrt(vector.reduce((sum, n) => sum + n * n, 0));
+ if (Math.abs(norm - 1) > 0.01) {
+ throw new WorkshopError(503, "SEARCH_VECTOR_INVALID", "The embedding is not unit normalized. Search was not executed.");
+ }
+ return vector;
+}
+
+export class SearchModel {
+ constructor({ fetchImpl = fetch, url = MODEL_URL } = {}) {
+ if (url !== MODEL_URL) throw new WorkshopError(503, "SEARCH_CONFIGURATION", "Only the fixed internal search-model service is supported.");
+ this.fetchImpl = fetchImpl;
+ this.busy = false;
+ }
+
+ async call(path, body, { signal, timeoutMs = 5000 } = {}) {
+ if (!["/api/tags", "/api/embeddings"].includes(path)) throw new Error("Unsupported search model operation.");
+ const timeout = AbortSignal.timeout(timeoutMs);
+ try {
+ const response = await this.fetchImpl(`${MODEL_URL}${path}`, {
+ method: body ? "POST" : "GET",
+ headers: body ? { "Content-Type": "application/json" } : {},
+ body: body ? JSON.stringify(body) : undefined,
+ redirect: "error",
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
+ });
+ if (!response.ok || !response.body) {
+ await response.body?.cancel();
+ throw new WorkshopError(503, "SEARCH_MODEL_UNAVAILABLE", "The local embedding service rejected the request. Retry after checking search readiness; no fallback was used.");
+ }
+ const chunks = [];
+ let bytes = 0;
+ for await (const chunk of response.body) {
+ bytes += chunk.length;
+ if (bytes > 256_000) throw new WorkshopError(503, "SEARCH_MODEL_INVALID", "The embedding service returned an oversized response.");
+ chunks.push(chunk);
+ }
+ const result = JSON.parse(Buffer.concat(chunks).toString("utf8"));
+ if (!result || typeof result !== "object" || result.error) throw new Error("Invalid model response");
+ return result;
+ } catch (error) {
+ if (signal?.aborted) throw new WorkshopError(499, "SEARCH_CANCELLED", "Search was cancelled.");
+ if (timeout.aborted) throw new WorkshopError(504, "SEARCH_MODEL_TIMEOUT", "Local embedding timed out. Try again after the model finishes loading; no fallback was used.");
+ if (error instanceof WorkshopError) throw error;
+ throw new WorkshopError(503, "SEARCH_MODEL_UNAVAILABLE", "The optional local embedding service is unavailable. Run the explicit search preparation command; keyword browsing is separate.");
+ }
+ }
+
+ async verify(signal) {
+ const data = await this.call("/api/tags", undefined, { signal });
+ const model = data.models?.find((item) => item.name === SEARCH_MODEL.name);
+ if (!model || model.digest?.replace(/^sha256:/, "") !== SEARCH_MODEL.digest ||
+ !Number.isFinite(model.size) || model.size <= 0 || model.size > MODEL_MAX_BYTES) {
+ throw new WorkshopError(503, "SEARCH_MODEL_MISMATCH", "The pinned embedding model is missing or has changed. Run search:prepare; no other model or keyword fallback was used.");
+ }
+ return SEARCH_MODEL;
+ }
+
+ async embed(texts, signal) {
+ if (!Array.isArray(texts) || !texts.length || texts.length > MODEL_BATCH ||
+ Array.from(texts).some((text) => typeof text !== "string" || text.length > 3000 || !/^(search_query|search_document): /.test(text))) {
+ throw new WorkshopError(400, "SEARCH_EMBED_INPUT", "Embedding input is outside the bounded search contract.");
+ }
+ if (this.busy) throw new WorkshopError(429, "SEARCH_BUSY", "One search is already running. Wait or cancel it before retrying.");
+ this.busy = true;
+ try {
+ await this.verify(signal);
+ const vectors = [];
+ // The bounded pinned runtime exposes the single-prompt embeddings API.
+ // Sequential calls avoid an unbounded runtime queue. No generation API exists here.
+ for (const prompt of texts) {
+ const data = await this.call("/api/embeddings", {
+ model: SEARCH_MODEL.name, prompt, keep_alive: "2m",
+ options: { num_thread: 2, num_ctx: 2048, num_gpu: 0 },
+ }, { signal, timeoutMs: 60000 });
+ const raw = data.embedding;
+ if (!Array.isArray(raw) || raw.length !== SEARCH_MODEL.dimensions || Array.from(raw).some((n) => typeof n !== "number" || !Number.isFinite(n))) {
+ throw new WorkshopError(503, "SEARCH_VECTOR_INVALID", "The model returned an unexpected embedding shape.");
+ }
+ const norm = Math.sqrt(raw.reduce((sum, n) => sum + n * n, 0));
+ if (!Number.isFinite(norm) || norm <= 0) throw new WorkshopError(503, "SEARCH_VECTOR_INVALID", "The model returned a zero or invalid embedding.");
+ vectors.push(checkedVector(raw.map((n) => n / norm)));
+ }
+ return vectors;
+ } finally {
+ this.busy = false;
+ }
+ }
+}
diff --git a/src/search-store.js b/src/search-store.js
new file mode 100644
index 0000000..548066b
--- /dev/null
+++ b/src/search-store.js
@@ -0,0 +1,187 @@
+import { randomUUID } from "node:crypto";
+import { requireCatalog, sessionView } from "./catalog.js";
+import { WorkshopError } from "./errors.js";
+import { checkedVector, SEARCH_MODEL } from "./search-model.js";
+
+export { SEARCH_COLLECTION, SEARCH_META, SEARCH_OWNER, TEXT_VERSION, SEARCH_INDEX, hash, documentText, sessionDay, searchFields } from "./search-contract.js";
+import { SEARCH_COLLECTION, SEARCH_META, SEARCH_OWNER, TEXT_VERSION, SEARCH_INDEX, hash, searchFields, sessionDay } from "./search-contract.js";
+import { readSearchBundle } from "./search-bundle.js";
+
+function incompatible(message = "The search snapshot or embedding model does not match. Preserve this database and prepare a fresh database, or review an explicit search-only migration.") {
+ throw new WorkshopError(409, "SEARCH_SNAPSHOT_MISMATCH", message);
+}
+export function validateMarker(marker, catalog, bundle) {
+ if (!marker) throw new WorkshopError(409, "SEARCH_NOT_PREPARED", "This target has no prepared semantic search. Run search:prepare explicitly for this target; no other target was searched.");
+ if (marker.owner !== SEARCH_OWNER || marker.fingerprint !== catalog.fingerprint || marker.modelDigest !== SEARCH_MODEL.digest ||
+ marker.dimensions !== SEARCH_MODEL.dimensions || marker.textVersion !== TEXT_VERSION || marker.schemaVersion !== 1 || marker.count !== catalog.sessions.length) incompatible();
+ if (bundle && (marker.bundleVersion !== bundle.version || marker.bundleDigest !== bundle.digest)) incompatible("This search target is not bound to the reviewed embedding bundle. Legacy/generated vectors were preserved; use a fresh explicit database or review a search-only migration.");
+ return marker;
+}
+export function validateRow(row, expected, catalog, withVector = false) {
+ if (!expected || hash(sessionView(row)) !== hash(expected)) incompatible("Search session metadata has drifted from the public catalog. No stale results were returned.");
+ const fields = searchFields(expected, catalog);
+ for (const key of ["sourceHash", "textHash", "modelDigest", "textVersion", "schemaVersion", "day"]) if (row[key] !== fields[key]) incompatible();
+ if (withVector && hash(checkedVector(row.embedding)) !== row.vectorHash) incompatible("Stored search vectors failed their integrity check. No stale results were returned.");
+}
+export function validateIndex(index) {
+ if (!index || hash(index.key) !== hash(SEARCH_INDEX.key) ||
+ Object.entries(SEARCH_INDEX.cosmosSearchOptions).some(([key, value]) => index.cosmosSearchOptions?.[key] !== value)) {
+ throw new WorkshopError(409, "SEARCH_INDEX_MISMATCH", "The required DocumentDB IVF/COS/768 index is missing or incompatible. Run explicit preparation; no index is created by a query.");
+ }
+}
+export function vectorPipeline(vector, count, filters = {}) {
+ checkedVector(vector);
+ return [
+ { $search: { cosmosSearch: { vector, path: "embedding", k: count }, returnStoredSource: true } },
+ { $addFields: { similarity: { $meta: "searchScore" } } },
+ ...(Object.keys(filters).length ? [{ $match: filters }] : []),
+ { $project: { embedding: 0, __cosmos_meta__: 0 } },
+ ];
+}
+
+export class SearchStore {
+ constructor(db, catalog, { bundleLoader = readSearchBundle } = {}) {
+ this.db = db;
+ this.bundleLoader = bundleLoader;
+ this.loadedBundle = undefined;
+ this.catalog = catalog;
+ this.expected = new Map(catalog.sessions.map((session) => [session.id, session]));
+ this.rows = db.collection(SEARCH_COLLECTION);
+ this.meta = db.collection(SEARCH_META);
+ }
+ async bundle() {
+ return this.loadedBundle ||= this.bundleLoader(this.catalog).catch((error) => { this.loadedBundle = undefined; throw error; });
+ }
+ validateBundledRow(row, bundle, withVector = false) {
+ validateRow(row, this.expected.get(row?._id), this.catalog, withVector);
+ if (row.bundleVersion !== bundle.version || row.bundleDigest !== bundle.digest || row.vectorHash !== bundle.rows.get(row._id)?.vectorHash) incompatible("Stored vectors are not the reviewed bundle for this snapshot. No existing search rows or favorites were replaced.");
+ }
+ async canonical() {
+ const metadata = await requireCatalog(this.db);
+ if (metadata.fingerprint !== this.catalog.fingerprint) incompatible("The active target has a different canonical catalog. Search is unavailable for this snapshot.");
+ }
+ async marker() { return this.meta.findOne({ _id: SEARCH_OWNER }); }
+ async index() {
+ const indexes = await this.rows.listIndexes().toArray();
+ if (indexes.some((index) => index.key?.embedding === "cosmosSearch" && index.name !== SEARCH_INDEX.name)) {
+ throw new WorkshopError(409, "SEARCH_INDEX_MISMATCH", "Multiple vector indexes could serve this embedding path. Review the search-only indexes explicitly; no ambiguous index was used.");
+ }
+ validateIndex(indexes.find((index) => index.name === SEARCH_INDEX.name));
+ }
+ async verifyAll() {
+ const bundle = await this.bundle();
+ const rows = await this.rows.find({}).limit(this.expected.size + 1).toArray();
+ if (rows.length !== this.expected.size || new Set(rows.map((row) => row._id)).size !== this.expected.size) incompatible("The search snapshot is incomplete or contains unexpected rows. Retry explicit preparation; browsing is unchanged.");
+ for (const row of rows) this.validateBundledRow(row, bundle, true);
+ return rows;
+ }
+ async ready({ full = false } = {}) {
+ await this.canonical();
+ const marker = validateMarker(await this.marker(), this.catalog, await this.bundle());
+ if (!marker.ready) throw new WorkshopError(409, "SEARCH_NOT_PREPARED", "Search preparation for this target is incomplete. Retry search:prepare; keyword browsing is separate.");
+ if (await this.rows.countDocuments({}) !== this.expected.size) incompatible("The search row count changed. Search is unavailable until reviewed.");
+ await this.index();
+ if (full) await this.verifyAll();
+ return marker;
+ }
+ async query(vector, filters, signal) {
+ const bundle = await this.bundle();
+ const pipeline = vectorPipeline(vector, this.expected.size, filters);
+ const rows = await this.rows.aggregate(pipeline, { maxTimeMS: 10000, signal }).toArray();
+ const count = this.catalog.sessions.filter((session) => (!filters.day || sessionDay(session, this.catalog) === filters.day) && (!filters.track || session.track === filters.track)).length;
+ if (rows.length !== count || new Set(rows.map((row) => row._id)).size !== count) incompatible("The vector query did not return the complete bounded candidate set. No partial or keyword fallback results were returned.");
+ for (const row of rows) {
+ this.validateBundledRow(row, bundle);
+ if (!Number.isFinite(row.similarity) || row.similarity < -1.000001 || row.similarity > 1.000001) throw new WorkshopError(503, "SEARCH_SCORE_INVALID", "DocumentDB did not return valid cosine searchScore metadata.");
+ }
+ return { rows, pipeline };
+ }
+
+ async prepare(model, log = console.log) {
+ // Decode/check every bundled vector before any collection claim or write.
+ // Missing/stale assets never trigger document embedding generation.
+ const bundle = await this.bundle();
+ const receipt = (reused) => ({ count: this.expected.size, reused, model: SEARCH_MODEL, bundle: { version: bundle.version, digest: bundle.digest, dataDigest: bundle.dataDigest }, documentEmbeddingCalls: 0 });
+ await this.canonical();
+ // Confirm canonical documents themselves, not just their ready marker.
+ const canonical = await this.db.collection("sessions").find({}).limit(this.expected.size + 1).toArray();
+ if (canonical.length !== this.expected.size || canonical.some((row) => hash(sessionView(row)) !== hash(this.expected.get(row._id)))) incompatible("Canonical session documents have changed. Search preparation did not alter them.");
+ await model.verify();
+ let marker = await this.marker();
+ if (!marker) {
+ const existing = await this.db.listCollections({}, { nameOnly: true }).toArray();
+ if (existing.some((collection) => [SEARCH_META, SEARCH_COLLECTION].includes(collection.name))) {
+ throw new WorkshopError(409, "SEARCH_UNOWNED", "An existing search collection has no ownership marker. It was not adopted or modified. Use a fresh database or review it explicitly.");
+ }
+ // Create (not upsert) the control collection: only its creator can claim it.
+ try { await this.db.createCollection(SEARCH_META); }
+ catch (error) {
+ if (error.code === 48 || error.codeName === "NamespaceExists") {
+ throw new WorkshopError(409, "SEARCH_PREPARING", "Another preparation claimed the search namespace. Retry after it finishes.");
+ }
+ throw error;
+ }
+ await this.meta.insertOne({
+ _id: SEARCH_OWNER, owner: SEARCH_OWNER, fingerprint: this.catalog.fingerprint,
+ modelDigest: SEARCH_MODEL.digest, dimensions: SEARCH_MODEL.dimensions,
+ schemaVersion: 1, textVersion: TEXT_VERSION, count: this.expected.size, ready: false,
+ bundleVersion: bundle.version, bundleDigest: bundle.digest,
+ leaseUntil: new Date(0),
+ });
+ marker = await this.marker();
+ }
+ validateMarker(marker, this.catalog, bundle);
+ if (marker.ready) {
+ await this.ready({ full: true });
+ await this.probe();
+ return receipt(true);
+ }
+ const leaseId = randomUUID();
+ const lease = await this.meta.updateOne({ _id: SEARCH_OWNER, ready: false, leaseUntil: { $lt: new Date() } }, { $set: { leaseId, leaseUntil: new Date(Date.now() + 180000) } });
+ if (lease.matchedCount !== 1) throw new WorkshopError(409, "SEARCH_PREPARING", "Another preparation holds the search lease. After an interruption, wait three minutes before retrying.");
+ const renew = async () => {
+ const result = await this.meta.updateOne({ _id: SEARCH_OWNER, leaseId, ready: false }, { $set: { leaseUntil: new Date(Date.now() + 180000) } });
+ if (result.matchedCount !== 1) throw new WorkshopError(409, "SEARCH_PREPARING", "Search preparation ownership changed. No ready marker was written.");
+ };
+ try {
+ const present = await this.rows.find({}).limit(this.expected.size + 1).toArray();
+ if (present.length > this.expected.size) incompatible();
+ for (const row of present) this.validateBundledRow(row, bundle, true);
+ const ids = new Set(present.map((row) => row._id));
+ const missing = this.catalog.sessions.filter((session) => !ids.has(session.id));
+ const batchSize = 32;
+ for (let i = 0; i < missing.length; i += batchSize) {
+ await renew();
+ const batch = missing.slice(i, i + batchSize);
+ await this.rows.bulkWrite(batch.map((session) => {
+ const { id, ...fields } = searchFields(session, this.catalog);
+ const prepared = bundle.rows.get(id);
+ return { updateOne: { filter: { _id: id }, update: { $setOnInsert: { ...fields, embedding: checkedVector(prepared.embedding), vectorHash: prepared.vectorHash, bundleVersion: bundle.version, bundleDigest: bundle.digest } }, upsert: true } };
+ }), { ordered: true });
+ log(`Imported ${Math.min(i + batchSize, missing.length)}/${missing.length} missing catalog embeddings from the checked-in bundle; no document inference.`);
+ }
+ await renew();
+ const indexes = await this.rows.listIndexes().toArray();
+ const index = indexes.find((item) => item.name === SEARCH_INDEX.name);
+ if (index) validateIndex(index);
+ else await this.db.command({ createIndexes: SEARCH_COLLECTION, indexes: [SEARCH_INDEX] });
+ await this.index();
+ await this.verifyAll();
+ await this.probe();
+ await renew();
+ const result = await this.meta.updateOne({ _id: SEARCH_OWNER, leaseId, ready: false }, { $set: { ready: true, readyAt: new Date().toISOString() }, $unset: { leaseId: "", leaseUntil: "" } });
+ if (result.matchedCount !== 1) throw new WorkshopError(409, "SEARCH_PREPARING", "Search ownership changed before publication.");
+ return receipt(false);
+ } finally {
+ await this.meta.updateOne({ _id: SEARCH_OWNER, leaseId, ready: false }, { $set: { leaseUntil: new Date(0) }, $unset: { leaseId: "" } });
+ }
+ }
+ async probe() {
+ const first = await this.rows.findOne({ _id: this.catalog.sessions[0].id });
+ this.validateBundledRow(first, await this.bundle(), true);
+ const { rows } = await this.query(first.embedding, {});
+ if (!rows.some((row) => row._id === first._id && row.similarity > 0.99)) {
+ throw new WorkshopError(503, "SEARCH_PROBE_FAILED", "The real DocumentDB vector self-query failed. Search was not marked ready.");
+ }
+ }
+}
diff --git a/src/search.js b/src/search.js
new file mode 100644
index 0000000..59468f3
--- /dev/null
+++ b/src/search.js
@@ -0,0 +1,121 @@
+import { readCatalog, sessionView } from "./catalog.js";
+import { WorkshopError, publicError } from "./errors.js";
+import { SearchModel, SEARCH_MODEL } from "./search-model.js";
+import { SearchStore, SEARCH_COLLECTION, SEARCH_INDEX, sessionDay } from "./search-store.js";
+
+// A conservative demo policy for sparse title/track metadata, NOT calibrated confidence.
+export const SIMILARITY_CUTOFF = 0.60;
+export const RANKING_POLICY = `DocumentDB cosine similarity descending; only scores >= ${SIMILARITY_CUTOFF.toFixed(2)}; at most the requested limit. No lexical reranking or fallback. Scores are not probabilities.`;
+export const FILTER_STRATEGY = "IVF with one list retrieves the full bounded catalog (k = catalog count), then DocumentDB applies explicit day/track $match. Filters are not pre-retrieval filters.";
+export function availableFilters(catalog) {
+ return {
+ days: [...new Set(catalog.sessions.map((session) => sessionDay(session, catalog)))].sort(),
+ tracks: [...new Set(catalog.sessions.map((session) => session.track))].sort(),
+ };
+}
+export function validateSearchInput(data, catalog) {
+ if (!data || typeof data !== "object" || Array.isArray(data) ||
+ Object.keys(data).some((key) => !["target", "query", "day", "track", "limit"].includes(key)) ||
+ typeof data.query !== "string" || !data.query.trim() || data.query.length > 500 || /[\u0000-\u001f\u007f]/u.test(data.query)) {
+ throw new WorkshopError(400, "SEARCH_INPUT_INVALID", "Use a plain search query of 1–500 characters and the explicit day/track filters only.");
+ }
+ const limit = data.limit ?? 5;
+ if (!Number.isInteger(limit) || limit < 1 || limit > 10) throw new WorkshopError(400, "SEARCH_LIMIT_INVALID", "Choose between 1 and 10 search results.");
+ const options = availableFilters(catalog);
+ const filters = {};
+ for (const [key, values] of [["day", options.days], ["track", options.tracks]]) {
+ if (data[key] !== undefined && data[key] !== "") {
+ if (typeof data[key] !== "string" || !values.includes(data[key])) throw new WorkshopError(400, "SEARCH_FILTER_INVALID", "Choose a day or track from this catalog. Search does not infer filters from your prompt.");
+ filters[key] = data[key];
+ }
+ }
+ return { query: data.query.trim(), limit, filters };
+}
+
+export function createSearch({ config, connections, model = new SearchModel(), catalogLoader = readCatalog, bundleLoader }) {
+ let busy = false;
+ let catalogPromise;
+ let bundlePromise;
+ const loadBundle = (source) => bundlePromise ||= (bundleLoader ? bundleLoader(source) : import("./search-bundle.js").then(({ readSearchBundle }) => readSearchBundle(source)))
+ .catch((error) => { bundlePromise = undefined; throw error; });
+ const verified = new Map(); // Bounded by the configured targets; never contains queries/results.
+ const catalog = () => catalogPromise ||= catalogLoader().catch((error) => { catalogPromise = undefined; throw error; });
+ const assertEnabled = () => {
+ if (!config.searchEnabled) throw new WorkshopError(503, "SEARCH_DISABLED", "Optional showcase not enabled. Outside the timed lab, run npm run search:prepare -- --local-sites. Keyword browsing and the required exercises do not need a model.");
+ };
+ async function storeFor(target) {
+ if (!Object.hasOwn(config.targets, target)) throw new WorkshopError(409, "TARGET_NOT_CONFIGURED", "This search target is not configured.");
+ return new SearchStore(await connections.db(target), await catalog(), { bundleLoader: loadBundle });
+ }
+ async function verify(store, target) {
+ const last = verified.get(target);
+ const marker = await store.ready();
+ if (!last || last.readyAt !== marker.readyAt || Date.now() - last.at > 300000) {
+ await store.verifyAll();
+ verified.set(target, { readyAt: marker.readyAt, at: Date.now() });
+ }
+ }
+ return {
+ async status(target) {
+ const base = { target, enabled: Boolean(config.searchEnabled), model: SEARCH_MODEL };
+ try {
+ assertEnabled();
+ const source = await catalog();
+ const { sessions, ...metadata } = source;
+ base.catalog = metadata;
+ base.filters = availableFilters(source);
+ const store = await storeFor(target);
+ await verify(store, target);
+ await model.verify();
+ return { ...base, ready: true, message: `Ready: ${sessions.length} public catalog entries. Titles and tracks only; there are no abstracts or generated answers.` };
+ } catch (error) {
+ verified.delete(target);
+ const safe = publicError(error);
+ return { ...base, ready: false, code: safe.code, message: safe.message };
+ }
+ },
+ async query(target, data, signal) {
+ assertEnabled();
+ const started = performance.now();
+ const source = await catalog();
+ const { query, limit, filters } = validateSearchInput(data, source);
+ if (busy) throw new WorkshopError(429, "SEARCH_BUSY", "One semantic search is already running. Wait or cancel it before retrying.");
+ busy = true;
+ try {
+ signal?.throwIfAborted();
+ const store = await storeFor(target);
+ await verify(store, target);
+ const embeddingStart = performance.now();
+ const [vector] = await model.embed([`search_query: ${query}`], signal);
+ const embeddingMs = Math.round(performance.now() - embeddingStart);
+ const databaseStart = performance.now();
+ const { rows, pipeline } = await store.query(vector, filters, signal);
+ const databaseMs = Math.round(performance.now() - databaseStart);
+ signal?.throwIfAborted();
+ const results = rows.filter((row) => row.similarity >= SIMILARITY_CUTOFF)
+ .sort((a, b) => b.similarity - a.similarity || a._id.localeCompare(b._id)).slice(0, limit)
+ .map((row, index) => ({ session: sessionView(row), rank: index + 1, similarity: row.similarity, evidence: { title: row.title, track: row.track } }));
+ const displayPipeline = structuredClone(pipeline);
+ displayPipeline[0].$search.cosmosSearch.vector = `[${vector.length} numeric values omitted]`;
+ return {
+ target, results,
+ message: results.length ? "Ranked by meaning, using title and track metadata only. Inspect the source before saving." : "No strong metadata matches passed the demo cutoff. Try a more specific topic or remove filters; the nearest unrelated talks are not shown.",
+ inspector: {
+ status: "executed", target, database: config.targets[target].database,
+ collection: SEARCH_COLLECTION, index: SEARCH_INDEX, model: SEARCH_MODEL,
+ bundle: { version: (await store.bundle()).version, digest: (await store.bundle()).digest },
+ dialect: "DocumentDB $search.cosmosSearch / $meta: searchScore (not Atlas syntax)",
+ filters, filterStrategy: FILTER_STRATEGY, pipeline: displayPipeline,
+ embeddingMs, databaseMs, totalMs: Math.round(performance.now() - started),
+ rankingPolicy: RANKING_POLICY, cutoff: SIMILARITY_CUTOFF, candidates: rows.length,
+ metadataOnly: true,
+ },
+ };
+ } catch (error) {
+ verified.delete(target);
+ if (signal?.aborted) throw new WorkshopError(499, "SEARCH_CANCELLED", "Search was cancelled. No results were substituted.");
+ throw error;
+ } finally { busy = false; }
+ },
+ };
+}
diff --git a/src/server.js b/src/server.js
index 99f9d14..40700b2 100644
--- a/src/server.js
+++ b/src/server.js
@@ -8,6 +8,7 @@ import { WorkshopError, reportError } from "./errors.js";
import { readPlanner, requireSession } from "./planner.js";
import { copyFavorites } from "./transfer.js";
import { createCalendar } from "./calendar.js";
+import { createSearch } from "./search.js";
async function readJson(request) {
if (request.headers["content-type"]?.split(";")[0] !== "application/json") {
@@ -31,10 +32,11 @@ async function readJson(request) {
}
}
-export async function createApp({ config, connections, repository, logger = console }) {
+export async function createApp({ config, connections, repository, logger = console, search = createSearch({ config, connections }) }) {
const html = await readFile(new URL("./public/index.html", import.meta.url), "utf8");
const csrfToken = randomBytes(32).toString("hex");
let activeTarget = config.activeTarget;
+ let targetEpoch = 0;
const details = () => ({
target: activeTarget,
initialTarget: config.activeTarget,
@@ -87,6 +89,13 @@ export async function createApp({ config, connections, repository, logger = cons
return;
}
const target = activeTarget;
+ const epoch = targetEpoch;
+ if (request.method === "GET" && url.pathname === "/api/search/status") {
+ const status = await search.status(target);
+ if (epoch !== targetEpoch) throw new WorkshopError(409, "TARGET_CHANGED", "The active database changed. Refresh search readiness.");
+ json(200, status);
+ return;
+ }
if (request.method === "GET" && url.pathname === "/api/health") {
await (await connections.db(target)).command({ ping: 1 });
json(200, { ready: true, target, mode: config.mode, location: config.location });
@@ -116,6 +125,19 @@ export async function createApp({ config, connections, repository, logger = cons
assertToken(request);
const data = await readJson(request);
assertTarget(data.target);
+ if (epoch !== targetEpoch) throw new WorkshopError(409, "TARGET_CHANGED", "The active database changed while receiving this request. Refresh before retrying.");
+ if (request.method === "POST" && url.pathname === "/api/search") {
+ const controller = new AbortController();
+ const disconnected = () => { if (!response.writableEnded) controller.abort(); };
+ response.once("close", disconnected);
+ try {
+ const result = await search.query(target, data, controller.signal);
+ if (epoch !== targetEpoch) throw new WorkshopError(409, "TARGET_CHANGED", "The active database changed during search. No stale results were returned.");
+ assertTarget(data.target);
+ json(200, result);
+ } finally { response.off("close", disconnected); }
+ return;
+ }
if (request.method === "POST" && url.pathname === "/api/target") {
if (!["local", "site-b", "cloud"].includes(data.nextTarget)) {
throw new WorkshopError(400, "INVALID_TARGET", "Choose one of the configured database targets.");
@@ -123,6 +145,7 @@ export async function createApp({ config, connections, repository, logger = cons
await (await connections.db(data.nextTarget)).command({ ping: 1 });
assertTarget(data.target);
activeTarget = data.nextTarget;
+ targetEpoch += 1;
json(200, details());
return;
}
diff --git a/test/search-bundle.test.js b/test/search-bundle.test.js
new file mode 100644
index 0000000..4692652
--- /dev/null
+++ b/test/search-bundle.test.js
@@ -0,0 +1,196 @@
+// Reads the genuine checked-in model output. Corruption tests modify copies in
+// memory; no model service, synthetic retrieval, or database writes occur here.
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { readCatalog } from "../src/catalog.js";
+import { readSearchBundle, decodeSearchBundle, byteHash, BUNDLE_FILES, BUNDLE_VERSION } from "../src/search-bundle.js";
+import { SEARCH_BUNDLE_PIN } from "../src/search-bundle-pin.js";
+import { SEARCH_MODEL } from "../src/search-model.js";
+import { hash, documentText, TEXT_VERSION } from "../src/search-contract.js";
+import { generateVectors, publishBundle } from "../scripts/search-bundle-generate.mjs";
+import { SearchStore } from "../src/search-store.js";
+
+const catalog = await readCatalog();
+const manifestBytes = await readFile(new URL(`../data/search/${BUNDLE_FILES.manifest}`, import.meta.url));
+const data = await readFile(new URL(`../data/search/${BUNDLE_FILES.data}`, import.meta.url));
+const manifest = JSON.parse(manifestBytes);
+const repin = (m, d = data) => ({ ...SEARCH_BUNDLE_PIN, manifestBytes: m.length, manifestSha256: byteHash(m), dataBytes: d.length, dataSha256: byteHash(d) });
+const rejectsBundle = (operation) => assert.throws(operation, { code: "SEARCH_BUNDLE_INVALID" });
+
+test("reviewed real bundle matches all 216 canonical IDs, public source/text hashes, dense normalized vectors and separate pins", async () => {
+ const bundle = await readSearchBundle(catalog);
+ assert.equal(bundle.version, BUNDLE_VERSION);
+ assert.equal(bundle.rows.size, 216);
+ assert.equal(data.length, 216 * 768 * 4);
+ assert.ok(manifestBytes.length < 150000);
+ assert.equal(bundle.digest, byteHash(manifestBytes));
+ assert.equal(bundle.dataDigest, byteHash(data));
+ assert.deepEqual(manifest.model, SEARCH_MODEL);
+ assert.equal(manifest.textVersion, TEXT_VERSION);
+ assert.equal(manifest.provenance.documentEmbeddingCalls, 216);
+ assert.equal(manifest.provenance.method, "fresh-local-model-inference");
+ assert.equal(manifest.provenance.license, "Apache-2.0");
+ assert.ok(["cpu", "cpu_avx", "cpu_avx2"].includes(manifest.provenance.backend));
+ for (const session of catalog.sessions) {
+ const row = bundle.rows.get(session.id);
+ assert.equal(row.sourceHash, hash(session));
+ assert.equal(row.textHash, hash(documentText(session)));
+ assert.equal(row.vectorHash, hash(row.embedding));
+ assert.equal(row.embedding.length, 768);
+ assert.ok(row.embedding.every(Number.isFinite));
+ assert.ok(Math.abs(Math.hypot(...row.embedding) - 1) < 1e-6);
+ }
+ assert.ok(new Set([...bundle.rows.values()].map((row) => row.vectorHash)).size > 150, "artifact contains varied actual session vectors, not repeated dummy embeddings");
+});
+
+test("a changed manifest cannot authorize itself and any one-coordinate mutation fails the data pin", () => {
+ const altered = Buffer.from(data);
+ altered.writeFloatLE(altered.readFloatLE(0) + 0.0001, 0);
+ rejectsBundle(() => decodeSearchBundle(manifestBytes, altered, catalog));
+ const replaced = structuredClone(manifest);
+ replaced.data.sha256 = byteHash(altered);
+ const bytes = Buffer.from(JSON.stringify(replaced));
+ rejectsBundle(() => decodeSearchBundle(bytes, altered, catalog));
+ // Even a test-only updated outer pin must still match the per-session hash.
+ rejectsBundle(() => decodeSearchBundle(bytes, altered, catalog, repin(bytes, altered)));
+ rejectsBundle(() => decodeSearchBundle(Buffer.concat([manifestBytes, Buffer.from(" ")]), data, catalog));
+});
+
+test("malformed shape, duplicate/missing/extra/reordered IDs and stale source metadata fail closed", () => {
+ for (const change of [
+ (m) => { m.sessions.pop(); },
+ (m) => { m.sessions.push(m.sessions[0]); },
+ (m) => { m.sessions[1] = m.sessions[0]; },
+ (m) => { [m.sessions[0], m.sessions[1]] = [m.sessions[1], m.sessions[0]]; },
+ (m) => { m.sessions[0].id = "unexpected-id"; },
+ (m) => { m.sessions[0].sourceHash = "0".repeat(64); },
+ (m) => { m.sessions[0].textHash = "0".repeat(64); },
+ (m) => { m.sessions[0].vectorHash = "0".repeat(64); },
+ (m) => { m.count--; },
+ (m) => { m.encoding = "arbitrary-json"; },
+ (m) => { m.normalization = "other-v1"; },
+ (m) => { m.data.file = "https://evil.invalid/model"; },
+ ]) {
+ const changed = structuredClone(manifest); change(changed);
+ const bytes = Buffer.from(JSON.stringify(changed));
+ rejectsBundle(() => decodeSearchBundle(bytes, data, catalog, repin(bytes)));
+ }
+});
+
+test("wrong model, dimensions, catalog and text schema reject even when test pins are deliberately recomputed", () => {
+ for (const change of [
+ (m) => { m.model.name = "different-model"; }, (m) => { m.model.digest = "0".repeat(64); },
+ (m) => { m.model.dimensions = 384; }, (m) => { m.catalogFingerprint = "0".repeat(64); },
+ (m) => { m.textVersion++; }, (m) => { m.version = "unknown-version"; },
+ ]) {
+ const changed = structuredClone(manifest); change(changed);
+ const bytes = Buffer.from(JSON.stringify(changed));
+ rejectsBundle(() => decodeSearchBundle(bytes, data, catalog, repin(bytes)));
+ }
+ rejectsBundle(() => decodeSearchBundle(manifestBytes, data, { ...catalog, fingerprint: "changed" }));
+});
+
+test("nonfinite, zero, out-of-norm and truncated binary vectors are rejected", () => {
+ for (const bad of [NaN, Infinity, -Infinity, 10]) {
+ const changed = Buffer.from(data); changed.writeFloatLE(bad, 0);
+ const m = structuredClone(manifest); m.data.sha256 = byteHash(changed);
+ const bytes = Buffer.from(JSON.stringify(m));
+ rejectsBundle(() => decodeSearchBundle(bytes, changed, catalog, repin(bytes, changed)));
+ }
+ const zero = Buffer.from(data); zero.fill(0, 0, 768 * 4);
+ const m = structuredClone(manifest); m.data.sha256 = byteHash(zero);
+ const bytes = Buffer.from(JSON.stringify(m));
+ rejectsBundle(() => decodeSearchBundle(bytes, zero, catalog, repin(bytes, zero)));
+ rejectsBundle(() => decodeSearchBundle(manifestBytes, data.subarray(0, -4), catalog));
+ rejectsBundle(() => decodeSearchBundle(Buffer.alloc(150001), data, catalog));
+});
+
+test("missing/corrupt bundle errors occur before any database operation or model inference and can retry", async () => {
+ let loads = 0;
+ const db = { collection() { return {}; }, command() { assert.fail("no DB operation"); } };
+ const model = { verify() { assert.fail("no model verification before bundle validity"); }, embed() { assert.fail("no fallback inference"); } };
+ const store = new SearchStore(db, catalog, { bundleLoader: async () => { loads++; decodeSearchBundle(manifestBytes, data.subarray(4), catalog); } });
+ await assert.rejects(store.prepare(model), { code: "SEARCH_BUNDLE_INVALID" });
+ await assert.rejects(store.prepare(model), { code: "SEARCH_BUNDLE_INVALID" });
+ assert.equal(loads, 2);
+});
+
+test("maintainer encoder alone computes bounded prefixed vectors in stable ID order (mock model, not live provenance)", async () => {
+ const source = { ...catalog, sessions: catalog.sessions.slice(0, 6).reverse() };
+ let verifies = 0;
+ const prompts = [];
+ const mock = {
+ async verify() { verifies++; },
+ async embed(texts) { prompts.push(...texts); return texts.map(() => Array.from({ length: 768 }, (_, i) => i === 0 ? 1 : 0)); },
+ };
+ const result = await generateVectors(source, mock);
+ assert.equal(verifies, 1);
+ assert.equal(result.documentEmbeddingCalls, 6);
+ assert.equal(result.data.length, 6 * 768 * 4);
+ const ordered = [...source.sessions].sort((a, b) => a.id < b.id ? -1 : 1);
+ assert.deepEqual(result.entries.map((row) => row.id), ordered.map((row) => row.id));
+ assert.deepEqual(prompts, ordered.map(documentText));
+ const preparation = await readFile(new URL("../scripts/search-prepare.mjs", import.meta.url), "utf8");
+ const store = await readFile(new URL("../src/search-store.js", import.meta.url), "utf8");
+ assert.doesNotMatch(preparation, /search-bundle-generate|generateVectors/);
+ assert.doesNotMatch(store, /model\.embed\(/);
+});
+
+test("overlapping maintainers cannot interleave any final asset/pin writes (in-memory I/O race)", async () => {
+ const files = new Map();
+ let locked = false;
+ let reached;
+ const firstWrite = new Promise((resolve) => { reached = resolve; });
+ let proceed;
+ const paused = new Promise((resolve) => { proceed = resolve; });
+ let writes = 0;
+ const io = {
+ async mkdir() {},
+ async open(_url, flags) {
+ assert.equal(flags, "wx");
+ if (locked) throw Object.assign(new Error("exists"), { code: "EEXIST" });
+ locked = true;
+ return { async writeFile() {}, async close() {} };
+ },
+ async writeFile(url, bytes) {
+ writes++;
+ files.set(url.href, typeof bytes === "string" ? Buffer.from(bytes) : Buffer.from(bytes));
+ if (writes === 1) { reached(); await paused; }
+ },
+ async rename(from, to) { assert.ok(files.has(from.href)); files.set(to.href, files.get(from.href)); files.delete(from.href); },
+ async readFile(url) { return files.get(url.href); },
+ async unlink() { locked = false; },
+ };
+ const first = publishBundle(manifestBytes, data, catalog, SEARCH_BUNDLE_PIN, io);
+ await firstWrite;
+ const changed = structuredClone(manifest);
+ changed.provenance.generatedAt = "2099-01-01T00:00:00.000Z";
+ const changedBytes = Buffer.from(JSON.stringify(changed));
+ await assert.rejects(publishBundle(changedBytes, data, catalog, repin(changedBytes), io), { code: "BUNDLE_PUBLICATION_BUSY" });
+ assert.equal(writes, 1, "losing publisher writes no temp file, final asset or pin");
+ assert.equal(locked, true, "loser cannot release another publisher's guard");
+ proceed();
+ await first;
+ assert.equal(locked, false);
+ const directory = new URL("../data/search/", import.meta.url);
+ assert.equal(decodeSearchBundle(files.get(new URL(BUNDLE_FILES.manifest, directory).href), files.get(new URL(BUNDLE_FILES.data, directory).href), catalog).digest, SEARCH_BUNDLE_PIN.manifestSha256);
+ const pinText = files.get(new URL("../src/search-bundle-pin.js", import.meta.url).href).toString();
+ assert.ok(pinText.includes(SEARCH_BUNDLE_PIN.manifestSha256));
+});
+
+test("failed publication releases its own guard and never reports successful completion", async () => {
+ let locked = false;
+ let closed = false;
+ const io = {
+ async mkdir() {},
+ async open() { locked = true; return { async writeFile() {}, async close() { closed = true; } }; },
+ async writeFile() { throw new Error("synthetic write failure"); },
+ async rename() { assert.fail("no publication after a failed write"); },
+ async readFile() { assert.fail("no success verification after a failed write"); },
+ async unlink() { locked = false; },
+ };
+ await assert.rejects(publishBundle(manifestBytes, data, catalog, SEARCH_BUNDLE_PIN, io), /synthetic write failure/);
+ assert.equal(locked, false);
+ assert.equal(closed, true);
+});
diff --git a/test/search-http.test.js b/test/search-http.test.js
new file mode 100644
index 0000000..dd823c8
--- /dev/null
+++ b/test/search-http.test.js
@@ -0,0 +1,322 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import http from "node:http";
+import { createApp } from "../src/server.js";
+import { createSearch, validateSearchInput } from "../src/search.js";
+import { validateCatalog } from "../src/catalog.js";
+import { WorkshopError } from "../src/errors.js";
+
+// Local HTTP + explicit injected fakes only. No DocumentDB or model service is
+// contacted; target/race/security assertions are not live vector-quality evidence.
+const deferred = () => {
+ let resolve;
+ const promise = new Promise((done) => { resolve = done; });
+ return { promise, resolve };
+};
+const catalog = validateCatalog({
+ kind: "practice", title: "Offline HTTP search fixture", timeZone: "America/New_York",
+ version: "http-search-test-v1", source: "Fictional unit-test data", snapshotDate: "2026-10-18",
+ sessions: [{ id: "synthetic-session", title: "Synthetic database topic", track: "Databases", room: "Test room",
+ startsAt: "2026-10-19T13:00:00Z", endsAt: "2026-10-19T14:00:00Z", url: "https://example.invalid/synthetic-session" }],
+});
+const configFor = (searchEnabled = true) => ({
+ activeTarget: "local", mode: "complete", scenario: "attendee", location: "laptop", searchEnabled,
+ targets: { local: { database: "offline_a" }, "site-b": { database: "offline_b" } },
+});
+
+async function serve(t, { config = configFor(), search, connections } = {}) {
+ const dbCalls = [];
+ const logs = [];
+ const app = await createApp({ config, search, repository: {}, logger: { error: (message) => logs.push(message) },
+ connections: connections || {
+ async db(target) { dbCalls.push(target); return { command: async () => ({ ok: 1 }) }; },
+ async close() {},
+ },
+ });
+ await new Promise((resolve, reject) => {
+ app.server.once("error", reject);
+ app.server.listen(0, "127.0.0.1", resolve);
+ });
+ t.after(() => { app.server.closeAllConnections(); return app.close(); });
+ const origin = `http://127.0.0.1:${app.server.address().port}`;
+ const get = (path) => fetch(`${origin}${path}`);
+ const details = await (await get("/api/config")).json();
+ const post = (path, body, token = details.csrfToken) => fetch(`${origin}${path}`, {
+ method: "POST", headers: { "Content-Type": "application/json", ...(token === undefined ? {} : { "X-Workshop-Token": token }) },
+ body: JSON.stringify(body),
+ });
+ return {
+ app, origin, get, post, details, dbCalls, logs,
+ switchTarget: (target, nextTarget) => post("/api/target", { target, nextTarget }),
+ };
+}
+
+async function expectError(response, status, code) {
+ assert.equal(response.status, status);
+ assert.equal(response.headers.get("cache-control"), "no-store");
+ const body = await response.json();
+ assert.equal(body.error.code, code);
+ assert.equal(body.results, undefined);
+ return body;
+}
+
+test("core startup, page/config, and health work with search disabled and without a model dependency", { timeout: 5000 }, async (t) => {
+ const realFetch = globalThis.fetch;
+ const modelFetches = [];
+ t.mock.method(globalThis, "fetch", async (url, ...args) => {
+ if (new URL(url).hostname !== "127.0.0.1") modelFetches.push(url);
+ assert.equal(new URL(url).hostname, "127.0.0.1", "offline startup must not fetch model/remote endpoints");
+ return realFetch(url, ...args);
+ });
+ // Exercise createApp's actual default createSearch, not an injected search fake.
+ const fixture = await serve(t, { config: configFor(false) });
+ assert.deepEqual(fixture.dbCalls, []);
+ assert.equal(fixture.details.target, "local");
+ const page = await fixture.get("/");
+ assert.equal(page.status, 200);
+ assert.match(await page.text(), //i);
+ const status = await fixture.get("/api/search/status");
+ assert.equal(status.status, 200);
+ assert.equal(status.headers.get("cache-control"), "no-store");
+ const payload = await status.json();
+ assert.equal(payload.target, "local");
+ assert.equal(payload.enabled, false);
+ assert.equal(payload.ready, false);
+ assert.equal(payload.code, "SEARCH_DISABLED");
+ await expectError(await fixture.post("/api/search", { target: "local", query: "topic" }), 503, "SEARCH_DISABLED");
+ assert.deepEqual(fixture.dbCalls, [], "disabled status and POST must not open a database");
+ assert.deepEqual(modelFetches, []);
+ const health = await fixture.get("/api/health");
+ assert.equal(health.status, 200);
+ assert.deepEqual(fixture.dbCalls, ["local"], "core health still uses its ordinary database ping");
+});
+
+test("POST /api/search requires the request token before invoking any search work", { timeout: 5000 }, async (t) => {
+ const queries = [];
+ const fixture = await serve(t, { search: {
+ status: async (target) => ({ target, enabled: true, ready: true }),
+ async query(target, data, signal) { queries.push({ target, data, signal }); return { target, results: [] }; },
+ } });
+ for (const token of ["", "wrong", "x".repeat(64)]) {
+ await expectError(await fixture.post("/api/search", { target: "local", query: "topic" }, token), 403, "REQUEST_TOKEN_REQUIRED");
+ }
+ const missing = await fetch(`${fixture.origin}/api/search`, {
+ method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ target: "local", query: "topic" }),
+ });
+ await expectError(missing, 403, "REQUEST_TOKEN_REQUIRED");
+ assert.equal(queries.length, 0);
+ assert.deepEqual(fixture.dbCalls, []);
+ const result = await fixture.post("/api/search", { target: "local", query: "topic" });
+ assert.equal(result.status, 200);
+ assert.equal(result.headers.get("cache-control"), "no-store");
+ assert.deepEqual(await result.json(), { target: "local", results: [] });
+ assert.equal(queries.length, 1);
+ assert.equal(queries[0].target, "local");
+ assert.deepEqual(queries[0].data, { target: "local", query: "topic" });
+ assert.ok(queries[0].signal instanceof AbortSignal);
+ assert.equal(queries[0].signal.aborted, false);
+ assert.equal((await fixture.get("/api/search/status")).status, 200, "status is a read-only GET");
+});
+
+test("search HTTP rejects malformed/oversized bodies, unknown URL/model inputs, and nonwhitelisted filters before DB/model access", { timeout: 5000 }, async (t) => {
+ const config = configFor();
+ const touches = [];
+ const connections = { async db() { touches.push("db"); throw new Error("unexpected DB access"); }, async close() {} };
+ const model = { async verify() { touches.push("verify"); }, async embed() { touches.push("embed"); } };
+ const search = createSearch({ config, connections, model, catalogLoader: async () => catalog });
+ const fixture = await serve(t, { config, connections, search });
+ for (const [data, expected] of [
+ [{ query: "x".repeat(501) }, "SEARCH_INPUT_INVALID"], [{ query: "" }, "SEARCH_INPUT_INVALID"],
+ [{ query: "x\ny" }, "SEARCH_INPUT_INVALID"], [{ query: "x", limit: 11 }, "SEARCH_LIMIT_INVALID"],
+ [{ query: "x", limit: 0 }, "SEARCH_LIMIT_INVALID"], [{ query: "x", limit: "5" }, "SEARCH_LIMIT_INVALID"],
+ [{ query: "x", day: "2026-10-20" }, "SEARCH_FILTER_INVALID"], [{ query: "x", track: { $ne: "" } }, "SEARCH_FILTER_INVALID"],
+ ...["url", "modelUrl", "baseURL", "model", "pipeline", "history", "filters"].map((key) => [{ query: "x", [key]: "http://169.254.169.254/latest/meta-data" }, "SEARCH_INPUT_INVALID"]),
+ ]) {
+ await expectError(await fixture.post("/api/search", { target: "local", ...data }), 400, expected);
+ }
+ await expectError(await fixture.post("/api/search", { target: "local", query: "x".repeat(17_000) }), 413, "REQUEST_TOO_LARGE");
+ for (const body of ["[]", "null", "{invalid"]) {
+ await expectError(await fetch(`${fixture.origin}/api/search`, {
+ method: "POST", headers: { "Content-Type": "application/json", "X-Workshop-Token": fixture.details.csrfToken }, body,
+ }), 400, "INVALID_JSON");
+ }
+ await expectError(await fetch(`${fixture.origin}/api/search`, {
+ method: "POST", headers: { "Content-Type": "text/plain", "X-Workshop-Token": fixture.details.csrfToken },
+ body: JSON.stringify({ target: "local", query: "x" }),
+ }), 415, "JSON_REQUIRED");
+ assert.deepEqual(touches, []);
+});
+
+test("valid boundary queries use POST bodies, never GET/history, and do not echo private query text in responses or logs", { timeout: 5000 }, async (t) => {
+ const calls = [];
+ const fixture = await serve(t, { search: {
+ async query(target, data) {
+ calls.push(validateSearchInput(data, catalog));
+ return { target, results: [], inspector: { metadataOnly: true } };
+ },
+ } });
+ const query = "q".repeat(500);
+ for (const limit of [1, 10]) {
+ const response = await fixture.post("/api/search", { target: "local", query, limit, day: "2026-10-19", track: "Databases" });
+ assert.equal(response.status, 200);
+ assert.equal(response.headers.get("cache-control"), "no-store");
+ assert.doesNotMatch(await response.text(), new RegExp(query));
+ }
+ assert.deepEqual(calls.map(({ limit }) => limit), [1, 10]);
+ const notSearch = await fixture.get(`/api/search?target=local&query=${query}`);
+ await expectError(notSearch, 404, "NOT_FOUND");
+ assert.equal(calls.length, 2);
+ assert.doesNotMatch(JSON.stringify(fixture.logs), new RegExp(query));
+});
+
+test("stale request targets are rejected before search; selected targets are not silently substituted", { timeout: 5000 }, async (t) => {
+ const queries = [];
+ const fixture = await serve(t, { search: {
+ async query(target) { queries.push(target); return { target, results: [] }; },
+ async status(target) { return { target, enabled: true, ready: true }; },
+ } });
+ await expectError(await fixture.post("/api/search", { target: "site-b", query: "x" }), 409, "TARGET_CHANGED");
+ await expectError(await fixture.post("/api/search", { query: "x" }), 409, "TARGET_CHANGED");
+ assert.deepEqual(queries, []);
+ assert.equal((await fixture.switchTarget("local", "site-b")).status, 200);
+ await expectError(await fixture.post("/api/search", { target: "local", query: "x" }), 409, "TARGET_CHANGED");
+ assert.equal((await fixture.get("/api/search/status")).status, 200);
+ const status = await (await fixture.get("/api/search/status")).json();
+ assert.equal(status.target, "site-b");
+ const current = await fixture.post("/api/search", { target: "site-b", query: "x" });
+ assert.equal(current.status, 200);
+ assert.equal((await current.json()).target, "site-b");
+ assert.deepEqual(queries, ["site-b"]);
+ assert.deepEqual(fixture.dbCalls, ["site-b"], "only explicit target switching performs the injected ping");
+});
+
+for (const roundTrip of [false, true]) {
+ test(`in-flight search results are discarded after ${roundTrip ? "A→B→A" : "A→B"} target switching`, { timeout: 5000 }, async (t) => {
+ const entered = deferred();
+ const release = deferred();
+ const calls = [];
+ const fixture = await serve(t, { search: {
+ async query(target) {
+ calls.push(target);
+ if (calls.length === 1) { entered.resolve(); await release.promise; }
+ return { target, results: [{ session: { id: calls.length === 1 ? "stale-result-must-not-escape" : "fresh-result" } }] };
+ },
+ } });
+ const pending = fixture.post("/api/search", { target: "local", query: "topic" });
+ try {
+ await entered.promise;
+ assert.equal((await fixture.switchTarget("local", "site-b")).status, 200);
+ if (roundTrip) assert.equal((await fixture.switchTarget("site-b", "local")).status, 200);
+ } finally { release.resolve(); }
+ const response = await pending;
+ const payload = await expectError(response, 409, "TARGET_CHANGED");
+ assert.doesNotMatch(JSON.stringify(payload), /stale-result-must-not-escape/);
+ assert.deepEqual(calls, ["local"], "stale requests are not replayed on another target");
+ const active = roundTrip ? "local" : "site-b";
+ assert.equal((await (await fixture.get("/api/config")).json()).target, active);
+ const retry = await fixture.post("/api/search", { target: active, query: "topic" });
+ assert.equal(retry.status, 200);
+ assert.equal((await retry.json()).results[0].session.id, "fresh-result");
+ assert.deepEqual(calls, ["local", active]);
+ });
+}
+
+for (const roundTrip of [false, true]) {
+ test(`in-flight readiness is also discarded after ${roundTrip ? "A→B→A" : "A→B"} target switching`, { timeout: 5000 }, async (t) => {
+ const entered = deferred();
+ const release = deferred();
+ const fixture = await serve(t, { search: {
+ async status(target) { entered.resolve(); await release.promise; return { target, ready: true, message: "stale-readiness" }; },
+ } });
+ const pending = fixture.get("/api/search/status");
+ try {
+ await entered.promise;
+ assert.equal((await fixture.switchTarget("local", "site-b")).status, 200);
+ if (roundTrip) assert.equal((await fixture.switchTarget("site-b", "local")).status, 200);
+ } finally { release.resolve(); }
+ const response = await pending;
+ const payload = await expectError(response, 409, "TARGET_CHANGED");
+ assert.doesNotMatch(JSON.stringify(payload), /stale-readiness/);
+ });
+}
+
+test("HTTP disconnect aborts search and the subsequent request can retry", { timeout: 5000 }, async (t) => {
+ const entered = deferred();
+ const cancelled = deferred();
+ let calls = 0;
+ let seenSignal;
+ const fixture = await serve(t, { search: {
+ async query(target, _data, signal) {
+ calls += 1;
+ if (calls > 1) return { target, results: [] };
+ seenSignal = signal;
+ entered.resolve();
+ return new Promise((_resolve, reject) => signal.addEventListener("abort", () => {
+ cancelled.resolve(); reject(new WorkshopError(499, "SEARCH_CANCELLED", "Search was cancelled."));
+ }, { once: true }));
+ },
+ } });
+ const controller = new AbortController();
+ const pending = fetch(`${fixture.origin}/api/search`, {
+ method: "POST", headers: { "Content-Type": "application/json", "X-Workshop-Token": fixture.details.csrfToken },
+ body: JSON.stringify({ target: "local", query: "cancel me" }), signal: controller.signal,
+ });
+ await entered.promise;
+ const rejected = assert.rejects(pending, { name: "AbortError" });
+ controller.abort();
+ await rejected;
+ await cancelled.promise;
+ assert.equal(seenSignal.aborted, true);
+ assert.equal((await fixture.post("/api/search", { target: "local", query: "retry" })).status, 200);
+ assert.equal(calls, 2);
+});
+
+test("search/status HTTP failures and logs exclude database URI, credentials, private endpoints, and query text", { timeout: 5000 }, async (t) => {
+ const secret = "mongodb://secret-user:secret-password@private-db.example.invalid/db?tls=true";
+ const privateQuery = "private query not for logs";
+ let mode = "mongo";
+ const fail = async () => {
+ if (mode === "model") throw new WorkshopError(503, "SEARCH_MODEL_UNAVAILABLE", "Optional embedding is unavailable; no fallback was used.");
+ const error = new Error(`${secret}; ${privateQuery}`);
+ if (mode === "mongo") error.name = "MongoServerSelectionError";
+ throw error;
+ };
+ const fixture = await serve(t, { search: { query: fail, status: fail } });
+ for (const [nextMode, status, expected] of [["mongo", 503, "DATABASE_UNAVAILABLE"], ["raw", 500, "INTERNAL_ERROR"], ["model", 503, "SEARCH_MODEL_UNAVAILABLE"]]) {
+ mode = nextMode;
+ const queryFailure = await expectError(await fixture.post("/api/search", { target: "local", query: privateQuery }), status, expected);
+ const statusFailure = await expectError(await fixture.get("/api/search/status"), status, expected);
+ assert.doesNotMatch(JSON.stringify({ queryFailure, statusFailure, logs: fixture.logs }), /mongodb:\/\/|secret-user|secret-password|private-db|private query not for logs/);
+ }
+ assert.deepEqual(fixture.dbCalls, [], "HTTP never falls back to a different connection after search errors");
+ assert.ok(fixture.logs.every((line) => Object.keys(JSON.parse(line)).sort().join(",") === "code,event"));
+});
+
+test("a target switch while a POST body is arriving cannot query the originally captured database", { timeout: 5000 }, async (t) => {
+ let queries = 0;
+ const fixture = await serve(t, { search: {
+ status: async (target) => ({ target, enabled: true, ready: true }),
+ async query(target) { queries++; return { target, results: [] }; },
+ } });
+ const started = deferred();
+ fixture.app.server.on("request", (request) => { if (request.url === "/api/search") started.resolve(); });
+ let request;
+ const completed = new Promise((resolve, reject) => {
+ request = http.request(`${fixture.origin}/api/search`, {
+ method: "POST", headers: { "Content-Type": "application/json", "X-Workshop-Token": fixture.details.csrfToken },
+ }, (response) => {
+ let body = "";
+ response.on("data", (chunk) => { body += chunk; });
+ response.on("end", () => resolve({ status: response.statusCode, body: JSON.parse(body) }));
+ });
+ request.on("error", reject);
+ });
+ request.write('{"target":"site-b",');
+ await started.promise;
+ assert.equal((await fixture.switchTarget("local", "site-b")).status, 200);
+ request.end('"query":"topic"}');
+ const response = await completed;
+ assert.equal(response.status, 409);
+ assert.equal(response.body.error.code, "TARGET_CHANGED");
+ assert.equal(queries, 0, "no query is allowed against stale captured Site A or newly selected Site B");
+});
diff --git a/test/search-prepare-interruption.test.js b/test/search-prepare-interruption.test.js
new file mode 100644
index 0000000..9ce654b
--- /dev/null
+++ b/test/search-prepare-interruption.test.js
@@ -0,0 +1,183 @@
+// Offline subprocess tests: real OS signals and child processes, fake Docker and
+// model registry. These prove lifecycle handling, not live Docker/model behavior.
+import test from "node:test";
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { mkdtemp, writeFile, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { setTimeout as sleep } from "node:timers/promises";
+import { runCommand } from "../scripts/search-prepare.mjs";
+
+const root = fileURLToPath(new URL("../", import.meta.url));
+const manifest = '{"schemaVersion":2,"mediaType":"application/vnd.docker.distribution.manifest.v2+json","config":{"mediaType":"application/vnd.docker.container.image.v1+json","digest":"sha256:31df23ea7daa448f9ccdbbcecce6c14689c8552222b80defd3830707c0139d4f","size":420},"layers":[{"mediaType":"application/vnd.ollama.image.model","digest":"sha256:970aa74c0a90ef7482477cf803618e776e173c007bf957f635f1015bfcfef0e6","size":274290656},{"mediaType":"application/vnd.ollama.image.license","digest":"sha256:c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","size":11357},{"mediaType":"application/vnd.ollama.image.params","digest":"sha256:ce4a164fc04605703b485251fe9f1a181688ba0eb6badb80cc6335c0de17ca0d","size":17}]}';
+
+async function fixture(t, mode) {
+ const directory = await mkdtemp(join(tmpdir(), "search-interruption-"));
+ const commands = join(directory, "commands.jsonl");
+ const stateFile = join(directory, "running");
+ const reached = join(directory, "reached");
+ const cleaned = join(directory, "cleaning");
+ await writeFile(stateFile, "false");
+ const bootstrap = join(directory, "registry.mjs");
+ await writeFile(bootstrap, `import { writeFileSync } from 'node:fs';
+const mode=process.env.TEST_MODE;
+globalThis.fetch=async (_url, {signal})=>{
+ if(mode==='manifest') {
+ writeFileSync(process.env.TEST_REACHED,'manifest');
+ return new Promise((_,reject)=>{const timer=setInterval(()=>{},1000); signal.addEventListener('abort',()=>{clearInterval(timer);reject(signal.reason)},{once:true})});
+ }
+ if(mode==='manifest-body') return new Response(new ReadableStream({start(controller){
+ writeFileSync(process.env.TEST_REACHED,'manifest-body');
+ const timer=setInterval(()=>{},1000);
+ signal.addEventListener('abort',()=>{clearInterval(timer);controller.error(signal.reason)},{once:true});
+ }}));
+ return new Response(${JSON.stringify(manifest)});
+};
+`);
+ await writeFile(join(directory, "docker"), `#!${process.execPath}
+const fs=require('node:fs');const args=process.argv.slice(2);const mode=process.env.TEST_MODE;
+fs.appendFileSync(process.env.TEST_COMMANDS,JSON.stringify(args)+'\\n');
+const has=x=>args.includes(x), output=x=>console.log(x), write=x=>fs.writeFileSync(process.env.TEST_STATE,String(x));
+if(args[0]==='context') output('offline-context');
+else if(has('config')) output(JSON.stringify({name:'offline-project',private:'PRIVATE-CONFIG-CREDENTIAL-DO-NOT-LOG'}));
+else if(has('up')&&has('search-download')) {write(true);if(mode==='startup'){fs.writeFileSync(process.env.TEST_REACHED,'startup');setInterval(()=>{},1000);}}
+else if(has('list')) {if(mode==='readiness'){fs.writeFileSync(process.env.TEST_REACHED,'readiness');setInterval(()=>{},1000);}}
+else if(has('pull')) {
+ if(mode==='pull'||mode==='signal-cleanup-failure'){fs.writeFileSync(process.env.TEST_REACHED,'pull');setInterval(()=>{},1000);}
+ else if(mode==='pull-failure') process.exitCode=7;
+}
+else if(has('stop')) {
+ fs.writeFileSync(process.env.TEST_CLEANING,'yes');
+ // Keep cleanup alive long enough to deliver a second signal to the parent.
+ setTimeout(()=>{
+ if(mode==='cleanup-failure'||mode==='signal-cleanup-failure') {console.error('PRIVATE-DAEMON-DETAIL-DO-NOT-LOG');process.exitCode=7;}
+ else if(mode!=='still-running') write(false);
+ },300);
+}
+else if(has('ps')) output('aaaaaaaaaaaa');
+else if(has('inspect')) {const running=fs.readFileSync(process.env.TEST_STATE,'utf8')==='true';output(JSON.stringify({Running:running,Status:running?'running':'exited'}));}
+`, { mode: 0o700 });
+ const child = spawn(process.execPath, ["--import", bootstrap, "scripts/search-prepare.mjs", "--local-sites"], {
+ cwd: root, detached: process.platform !== "win32", stdio: ["ignore", "pipe", "pipe"],
+ env: { ...process.env, DOCKER_HOST: mode === "host-override" ? "tcp://PRIVATE-DOCKER-HOST:2375" : "", DOCKER_CONTEXT: "", PATH: `${directory}:${process.env.PATH}`, TEST_MODE: mode, TEST_COMMANDS: commands, TEST_STATE: stateFile, TEST_REACHED: reached, TEST_CLEANING: cleaned },
+ });
+ let output = "";
+ child.stdout.on("data", (chunk) => { output += chunk; });
+ child.stderr.on("data", (chunk) => { output += chunk; });
+ let exited = false;
+ const done = new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", (code, signal) => { exited = true; resolve({ code, signal }); });
+ });
+ const timeout = setTimeout(() => child.kill("SIGKILL"), 15000);
+ t.after(async () => {
+ clearTimeout(timeout);
+ if (!exited) { child.kill("SIGKILL"); await done; }
+ await rm(directory, { recursive: true, force: true });
+ });
+ const waitFile = async (path) => {
+ for (let i = 0; i < 200; i++) {
+ try { await readFile(path); return; } catch (error) { if (error.code !== "ENOENT") throw error; }
+ if (exited) assert.fail(`subprocess exited before lifecycle checkpoint: ${output}`);
+ await sleep(20);
+ }
+ assert.fail("subprocess did not reach lifecycle checkpoint");
+ };
+ const commandList = async () => {
+ try { return (await readFile(commands, "utf8")).trim().split("\n").filter(Boolean).map(JSON.parse); }
+ catch (error) { if (error.code === "ENOENT") return []; throw error; }
+ };
+ const sendGroupSignal = (signal) => {
+ if (process.platform === "win32") return child.kill(signal);
+ process.kill(-child.pid, signal);
+ return true;
+ };
+ return { child, done, waitFile, reached, cleaned, commandList, sendGroupSignal,
+ output: () => output, running: () => readFile(stateFile, "utf8") };
+}
+
+for (const signal of ["SIGINT", "SIGTERM"]) {
+ for (const phase of ["manifest", "manifest-body", "startup", "readiness", "pull"]) {
+ test(`${signal} during ${phase}: cancel, reconcile downloader, never index; repeated signal cannot interrupt cleanup`, { timeout: 20000 }, async (t) => {
+ const run = await fixture(t, phase);
+ await run.waitFile(run.reached);
+ assert.equal(run.sendGroupSignal(signal), true);
+ if (!["manifest", "manifest-body"].includes(phase)) {
+ await run.waitFile(run.cleaned);
+ assert.equal(run.sendGroupSignal(signal === "SIGINT" ? "SIGTERM" : "SIGINT"), true);
+ }
+ assert.deepEqual(await run.done, { code: signal === "SIGINT" ? 130 : 143, signal: null });
+ const commands = await run.commandList();
+ assert.ok(commands.every((args) => !args.includes("scripts/search-index.mjs")));
+ assert.ok(commands.every((args) => !(args.includes("up") && args.includes("app"))));
+ assert.equal(await run.running(), "false");
+ if (["manifest", "manifest-body"].includes(phase)) assert.deepEqual(commands, []);
+ else {
+ assert.match(run.output(), /"event":"search-download-stopped".*"verified":true/);
+ assert.ok(commands.some((args) => args.includes("inspect")));
+ for (const args of commands.filter((args) => args.includes("stop") || args.includes("ps") || args.includes("inspect"))) {
+ assert.deepEqual(args.slice(0, 2), ["--context", "offline-context"]);
+ if (args.includes("stop")) assert.ok(args.includes("offline-project") && args.at(-1) === "search-download");
+ assert.ok(!args.includes("down") && !args.includes("--volumes") && !args.includes("rm"));
+ }
+ }
+ assert.doesNotMatch(run.output(), /PRIVATE-CONFIG|PRIVATE-DAEMON|"status":"ready"/);
+ });
+ }
+}
+
+for (const [mode, expected] of [["success", 0], ["pull-failure", 1], ["cleanup-failure", 1], ["still-running", 1]]) {
+ test(`subprocess ${mode}: explicit outcome and no indexing before verified cleanup`, { timeout: 20000 }, async (t) => {
+ const run = await fixture(t, mode);
+ assert.deepEqual(await run.done, { code: expected, signal: null });
+ const commands = await run.commandList();
+ const indexes = commands.filter((args) => args.includes("scripts/search-index.mjs"));
+ if (mode === "success") {
+ assert.deepEqual(indexes.map((args) => args.at(-1)), ["local", "site-b"]);
+ assert.match(run.output(), /"status":"ready"/);
+ } else assert.deepEqual(indexes, []);
+ if (["cleanup-failure", "still-running"].includes(mode)) {
+ assert.match(run.output(), /SEARCH_DOWNLOAD_CLEANUP_FAILED.*offline-project.*offline-context/);
+ assert.doesNotMatch(run.output(), /"event":"search-download-stopped"/);
+ assert.equal(await run.running(), "true"); // Fake resource intentionally persists to verify the honest failure path.
+ } else {
+ assert.match(run.output(), /"event":"search-download-stopped"/);
+ assert.equal(await run.running(), "false");
+ }
+ assert.doesNotMatch(run.output(), /PRIVATE-CONFIG|PRIVATE-DAEMON/);
+ });
+}
+
+test("signal followed by cleanup failure exits nonzero with recovery context, not a successful cleanup receipt", { timeout: 20000 }, async (t) => {
+ const run = await fixture(t, "signal-cleanup-failure");
+ await run.waitFile(run.reached);
+ run.child.kill("SIGINT");
+ await run.waitFile(run.cleaned);
+ run.child.kill("SIGTERM");
+ assert.deepEqual(await run.done, { code: 1, signal: null });
+ assert.match(run.output(), /SEARCH_DOWNLOAD_CLEANUP_FAILED.*offline-project.*offline-context/);
+ assert.doesNotMatch(run.output(), /"event":"search-download-stopped"|"status":"ready"|PRIVATE-DAEMON/);
+ assert.ok((await run.commandList()).every((args) => !args.includes("scripts/search-index.mjs")));
+});
+
+test("async runner deadline cancels and waits for child closure", { timeout: 5000 }, async () => {
+ const result = await runCommand(process.execPath, ["-e", "setInterval(()=>{},1000)"], { timeout: 50, capture: true });
+ assert.equal(result.cancelled, true);
+ assert.notEqual(result.status, 0);
+});
+
+test("async runner escalates a timed-out child that ignores SIGTERM, then settles after closure", { timeout: 6000 }, async () => {
+ const result = await runCommand(process.execPath, ["-e", "process.on('SIGTERM',()=>{});setInterval(()=>{},1000)"], { timeout: 150, capture: true });
+ assert.equal(result.cancelled, true);
+ assert.equal(result.status, null);
+});
+
+test("ambiguous DOCKER_HOST override is rejected before selecting or modifying a daemon", { timeout: 5000 }, async (t) => {
+ const run = await fixture(t, "host-override");
+ assert.deepEqual(await run.done, { code: 1, signal: null });
+ assert.deepEqual(await run.commandList(), []);
+ assert.match(run.output(), /requires an explicit Docker context/);
+ assert.doesNotMatch(run.output(), /PRIVATE-DOCKER-HOST/);
+});
diff --git a/test/search-prepare.test.js b/test/search-prepare.test.js
new file mode 100644
index 0000000..ff7d649
--- /dev/null
+++ b/test/search-prepare.test.js
@@ -0,0 +1,97 @@
+// Offline orchestration tests. Docker and registry responses below are mocks,
+// not evidence that a model was downloaded or that vectors were executed.
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import { checkManifest, preparationTargets, prepareSearch } from "../scripts/search-prepare.mjs";
+import { SEARCH_MODEL } from "../src/search-model.js";
+
+// Public registry manifest, no model weights or private source material.
+const manifest = '{"schemaVersion":2,"mediaType":"application/vnd.docker.distribution.manifest.v2+json","config":{"mediaType":"application/vnd.docker.container.image.v1+json","digest":"sha256:31df23ea7daa448f9ccdbbcecce6c14689c8552222b80defd3830707c0139d4f","size":420},"layers":[{"mediaType":"application/vnd.ollama.image.model","digest":"sha256:970aa74c0a90ef7482477cf803618e776e173c007bf957f635f1015bfcfef0e6","size":274290656},{"mediaType":"application/vnd.ollama.image.license","digest":"sha256:c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","size":11357},{"mediaType":"application/vnd.ollama.image.params","digest":"sha256:ce4a164fc04605703b485251fe9f1a181688ba0eb6badb80cc6335c0de17ca0d","size":17}]}';
+
+function mockRun(commands, failPull = false) {
+ return async (command, args, options) => {
+ assert.equal(command, "docker");
+ assert.ok(options.timeout <= 900000);
+ commands.push(args);
+ return { status: failPull && args.includes("pull") ? 1 : 0,
+ stdout: args[0] === "context" ? "test-context\n" : args.includes("config") ? '{"name":"test-project"}' : "" };
+ };
+}
+
+test("preparation requires explicit local targets; missing, cloud and extra arguments do nothing", async () => {
+ assert.deepEqual(preparationTargets(["--local-sites"]), ["local", "site-b"]);
+ assert.deepEqual(preparationTargets(["--target", "local"]), ["local"]);
+ assert.deepEqual(preparationTargets(["--target", "site-b"]), ["site-b"]);
+ for (const args of [[], ["--target", "cloud"], ["--target", "https://evil.invalid"], ["--local-sites", "--force"], ["--target"]]) {
+ let calls = 0;
+ await assert.rejects(prepareSearch(args, { run() { calls++; }, fetchImpl() { calls++; } }));
+ assert.equal(calls, 0);
+ }
+});
+
+test("the public manifest must match the exact pin and the bounded asset size", () => {
+ assert.equal(checkManifest(manifest), 274302450);
+ for (const invalid of [manifest + "\n", manifest.replace("274290656", "274290657"), "{}", "x".repeat(64001)]) {
+ assert.throws(() => checkManifest(invalid), /pinned digest/);
+ }
+});
+
+test("explicit helper downloads only the embedding pin, stops downloader, then indexes exactly requested targets", async () => {
+ const commands = [];
+ const requests = [];
+ await prepareSearch(["--local-sites"], {
+ run: mockRun(commands),
+ fetchImpl: async (url, options) => { requests.push({ url, options }); return new Response(manifest); },
+ log() {},
+ });
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].url, "https://registry.ollama.ai/v2/library/nomic-embed-text/manifests/v1.5");
+ assert.equal(requests[0].options.redirect, "error");
+ const text = commands.map((args) => args.join(" ")).join("\n");
+ assert.match(text, new RegExp(`ollama pull ${SEARCH_MODEL.name}`));
+ assert.doesNotMatch(text, /qwen|generate|chat|cloud|prune|\bdown\b|--volumes|seed|migrate/);
+ const stop = commands.findIndex((args) => args.includes("stop"));
+ const upApp = commands.findIndex((args) => args.includes("app") && args.includes("up"));
+ assert.ok(stop >= 0 && stop < upApp);
+ assert.deepEqual(commands.filter((args) => args.includes("scripts/search-index.mjs")).map((args) => args.at(-1)), ["local", "site-b"]);
+});
+
+test("a failed download still stops its service and never enables/indexes the app", async () => {
+ const commands = [];
+ await assert.rejects(prepareSearch(["--target", "local"], {
+ run: mockRun(commands, true),
+ fetchImpl: async () => new Response(manifest), log() {},
+ }), /bounded Docker operation failed/);
+ assert.ok(commands.some((args) => args.includes("stop")));
+ assert.ok(commands.at(-1).includes("ps"));
+ assert.ok(commands.every((args) => !args.includes("scripts/search-index.mjs")));
+});
+
+test("failed, changed or oversized registry responses do not invoke Docker", async () => {
+ for (const response of [new Response("unavailable", { status: 503 }), new Response("{}"), new Response("x".repeat(64001))]) {
+ let calls = 0;
+ await assert.rejects(prepareSearch(["--local-sites"], { run() { calls++; }, fetchImpl: async () => response, log() {} }));
+ assert.equal(calls, 0);
+ }
+});
+
+test("model is optional, private, bounded and absent from core startup; optional CI is manual", async () => {
+ const compose = await readFile(new URL("../compose.search.yaml", import.meta.url), "utf8");
+ assert.match(compose, /profiles: \[search\]/);
+ assert.match(compose, /internal: true/);
+ assert.match(compose, /mem_limit: 1g/);
+ assert.match(compose, /cpus: 2/);
+ assert.doesNotMatch(compose, /OLLAMA_LLM_LIBRARY:/, "do not force generic CPU over detected AVX2/AVX");
+ const adapter = await readFile(new URL("../src/search-model.js", import.meta.url), "utf8");
+ assert.match(adapter, /num_gpu: 0/, "CPU backend autodetection must not enable GPU inference");
+ assert.match(compose, /search-model-data:\/models:ro/);
+ assert.doesNotMatch(compose, /^\s+ports:/m);
+ for (const path of ["../compose.yaml", "../scripts/workspace-start.mjs", "../Dockerfile"]) {
+ const core = await readFile(new URL(path, import.meta.url), "utf8");
+ assert.doesNotMatch(core, /ollama|search:prepare|search-index|SEARCH_ENABLED/);
+ }
+ const workflow = await readFile(new URL("../.github/workflows/semantic-search.yml", import.meta.url), "utf8");
+ assert.match(workflow, /workflow_dispatch:/);
+ assert.doesNotMatch(workflow, /pull_request:|push:/);
+});
diff --git a/test/search-ui.test.js b/test/search-ui.test.js
new file mode 100644
index 0000000..dd74ab9
--- /dev/null
+++ b/test/search-ui.test.js
@@ -0,0 +1,387 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import vm from "node:vm";
+
+const html = await readFile(new URL("../src/public/index.html", import.meta.url), "utf8");
+const script = [...html.matchAll(/