From 4b1ac6ac2305f69ee4a84171662e9666e6e33da1 Mon Sep 17 00:00:00 2001 From: Patty Chow <91703531+patty-chow@users.noreply.github.com> Date: Sun, 18 Oct 2026 20:12:01 -0700 Subject: [PATCH 1/5] feat: add optional local semantic search showcase --- .github/workflows/semantic-search.yml | 32 ++ README.md | 22 + compose.search.yaml | 62 +++ docs/semantic-search.md | 294 ++++++++++++ package.json | 4 +- scripts/search-index.mjs | 28 ++ scripts/search-prepare.mjs | 61 +++ src/config.js | 2 +- src/public/index.html | 334 +++++++++++++- src/search-model.js | 105 +++++ src/search-store.js | 182 ++++++++ src/search.js | 117 +++++ src/server.js | 25 +- test/search-http.test.js | 322 +++++++++++++ test/search-prepare.test.js | 83 ++++ test/search-ui.test.js | 387 ++++++++++++++++ test/search.integration.js | 100 ++++ test/search.test.js | 637 ++++++++++++++++++++++++++ 18 files changed, 2771 insertions(+), 26 deletions(-) create mode 100644 .github/workflows/semantic-search.yml create mode 100644 compose.search.yaml create mode 100644 docs/semantic-search.md create mode 100644 scripts/search-index.mjs create mode 100644 scripts/search-prepare.mjs create mode 100644 src/search-model.js create mode 100644 src/search-store.js create mode 100644 src/search.js create mode 100644 test/search-http.test.js create mode 100644 test/search-prepare.test.js create mode 100644 test/search-ui.test.js create mode 100644 test/search.integration.js create mode 100644 test/search.test.js diff --git a/.github/workflows/semantic-search.yml b/.github/workflows/semantic-search.yml new file mode 100644 index 0000000..8346057 --- /dev/null +++ b/.github/workflows/semantic-search.yml @@ -0,0 +1,32 @@ +name: Optional semantic search showcase +on: + workflow_dispatch: +permissions: + contents: read +jobs: + real-model-and-documentdb: + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + COMPOSE_PROJECT_NAME: ato-search-ci + WORKSHOP_MODE: complete + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '24' + cache: npm + - run: npm ci --ignore-scripts --no-audit --no-fund + - run: npm test + - run: npm run test:docs + - name: Start ordinary model-free workshop + run: npm run workspace:start + - name: Explicitly download the pinned embedding model and prepare both sites + run: npm run search:prepare -- --local-sites + - name: Real model, native vector queries, metadata integrity and unrelated-query checks + run: docker compose -f compose.yaml -f compose.search.yaml exec -T app npm run test:search + - name: Confirm ordinary two-site workflow is unchanged + run: docker compose -f compose.yaml -f compose.search.yaml exec -T app npm run test:database + - name: Remove only this ephemeral CI project's resources + if: always() + run: docker compose -f compose.yaml -f compose.search.yaml --profile search --profile search-download down --volumes diff --git a/README.md b/README.md index 1f4b51b..772db77 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,28 @@ Fictional practice favorites cannot automatically map to real conference session An interrupted seed of the same catalog can be retried; incompatible partial catalogs are rejected rather than silently hidden or overwritten. +## Optional built-in semantic search + +The planner also has a separate **Search by meaning** showcase: prompt chips, +ranked source cards, favorite actions and an inspectable **real DocumentDB vector +query**. It uses one local embedding model—**no answer-generation model or paid +API**—over the same public title/track metadata. The catalog has no abstracts, so +rankings are suggestions, not confidence claims. Keyword search stays separate; +missing models or indexes never trigger a hidden keyword/static fallback. + +This is **not another lab exercise** and is disabled during ordinary startup. +Outside the 105-minute lab, after both sites are seeded, explicitly enable it: + +```sh +npm run search:prepare -- --local-sites +``` + +This downloads a pinned ~274 MB embedding model, starts an internal-only CPU +service, and prepares separate search collections on both existing local sites. +It does not change catalog documents or favorites, provision Azure, or replace +your TODO code. See [optional search setup, limits, model/runtime tradeoffs and +verification](docs/semantic-search.md) before enabling it on a classroom machine. + ## Complete reference and recovery The starter and reference use the same app, catalog, configuration, and volumes: diff --git a/compose.search.yaml b/compose.search.yaml new file mode 100644 index 0000000..9099ed7 --- /dev/null +++ b/compose.search.yaml @@ -0,0 +1,62 @@ +# Optional showcase only. Normal workspace:start never loads this overlay/model. +# This bounded, multi-platform official runtime is deliberately CPU-only at runtime. +# See docs/semantic-search.md for the image-size tradeoff and model license. +x-search-runtime: &search-runtime + image: docker.io/ollama/ollama:0.1.48@sha256:4a3c5b5261f325580d7f4f6440e5094d807784f0513439dcabfda9c2bdf4191e + cpus: 2 + mem_limit: 1g + pids_limit: 128 + read_only: true + tmpfs: + - /tmp:size=128m + environment: &model-environment + OLLAMA_HOST: 0.0.0.0:11434 + OLLAMA_MODELS: /models + OLLAMA_RUNNERS_DIR: /runners + OLLAMA_NOHISTORY: "true" + OLLAMA_NOPRUNE: "true" + HOME: /tmp + OLLAMA_NUM_PARALLEL: "1" + OLLAMA_MAX_LOADED_MODELS: "1" + OLLAMA_MAX_QUEUE: "1" + OLLAMA_KEEP_ALIVE: 2m + OLLAMA_DEBUG: "false" + OLLAMA_LLM_LIBRARY: cpu + CUDA_VISIBLE_DEVICES: "-1" + volumes: + - search-model-data:/models + - search-runner-data:/runners + +services: + app: + environment: + SEARCH_ENABLED: "1" + networks: + - default + - search-internal + + search-model: + <<: *search-runtime + profiles: [search] + volumes: + - search-model-data:/models:ro + - search-runner-data:/runners:ro + networks: + - search-internal + # No host ports. The inference service has no route to the internet. + + search-download: + <<: *search-runtime + profiles: [search-download] + networks: + - default + # Runs only while the explicit preparation command downloads the model. + # No query traffic is sent here. Stopped in the preparation command's finally. + +networks: + search-internal: + internal: true + +volumes: + search-model-data: + search-runner-data: diff --git a/docs/semantic-search.md b/docs/semantic-search.md new file mode 100644 index 0000000..62f5671 --- /dev/null +++ b/docs/semantic-search.md @@ -0,0 +1,294 @@ +# Optional showcase: Search by meaning + +This is a **built-in site feature, not another required lab exercise**. Prepare it +before or after the 105-minute workshop. The required TODOs, extension activities, +copy/return flow and calendar export are unchanged. Normal `npm ci` and +`npm run workspace:start` do **not** download a model or create a vector index. + +The panel uses an embedding model to turn a query into a vector, then asks the +**selected DocumentDB instance** to retrieve similar session metadata. There is +no answer-generation model, agent, chat history, paid API key, or separate vector +database. The existing **Keyword search** remains a distinct substring browser. +If either the model or selected database is unavailable, semantic search fails +explicitly; it never silently uses keywords, static results, Site A, or another +model as a substitute. + +## Enable explicitly in Codespaces or the local workshop + +First finish ordinary startup so both canonical catalogs are seeded. Run in the +repository terminal (inside Codespaces for the Codespaces workshop): + +```sh +npm run search:prepare -- --local-sites +``` + +This uses the current Compose project and its existing credentials/volumes. It: + +1. Checks the pinned public embedding manifest and its download size. +2. Starts an **unpublished, temporary download service**, downloads only the + embedding model, then stops that service even on failure. +3. Starts the internal-only CPU embedding service and enables the app's optional + search configuration with `compose.search.yaml`. +4. Prepares and live-probes a separate search collection in **both** local sites. + A target is only marked ready after all vectors, hashes, index options and an + actual full-corpus DocumentDB cosine query pass verification. + +Refresh the planner, or click **Check search readiness**. The showcase works +independently of TODO 1, but **Save favorite** uses the same TODO 2 implementation +as the ordinary cards; it does not bypass your exercise code. Using the complete +reference is optional. To keep reference mode while preparing, set it explicitly +for this command (this does not overwrite the starter file): + +```sh +WORKSHOP_MODE=complete npm run search:prepare -- --local-sites +``` + +Prepare just one selected local site instead: + +```sh +npm run search:prepare -- --target local +# Or explicitly: npm run search:prepare -- --target site-b +``` + +There is **no default target** for preparation. A site that was not prepared is +unavailable in semantic mode; switching sites clears results and ignores late +responses. Preparing search never seeds a missing canonical catalog or copies +favorites. The helper never provisions Azure or prepares a cloud target. + +### Restart, stop, or return to the model-free workshop + +With cached assets, this restart needs no model registry access: + +```sh +docker compose -f compose.yaml -f compose.search.yaml --profile search up -d --wait --wait-timeout 240 app search-model +``` + +Add `-f compose.complete.yaml` **after** the search overlay if you want reference +mode. Keep port **3000 private**. Never forward the model port (11434), and retain +the existing database-port/TLS precautions in the [extension guide](extension.md). + +To disable the optional feature while preserving every catalog, vector and favorite: + +```sh +docker compose -f compose.yaml up -d --wait --wait-timeout 240 app +docker compose -f compose.yaml -f compose.search.yaml stop search-model search-download +``` + +`npm run workspace:start` also restores normal model-free app configuration. It +does not remove the optional cached model or stop a previously running sidecar; +use the explicit `stop` command above to release its memory. Do not use volume +pruning or `down --volumes` as a troubleshooting step. + +## What is actually searched? + +The same checked-in **216-entry official public schedule snapshot** is used. +There are **no abstracts**, private conference datasets or invented descriptions. +The text embedded for each entry is exactly: + +```text +search_document: +Track: +``` + +Queries are prefixed with `search_query: `. Source URL, room, start/end time and +conference-local day remain grounded metadata on each card; day/track are explicit +validated filters, not guesses from a language model. A query such as “Monday +only” does **not** set the day filter for you. + +Short titles are imperfect evidence. Broad topics, puns and missing terminology +can produce poor rankings or no matches. Check the published title/track and +source before saving. The raw similarity score is **not confidence, probability, +attendance relevance, or a guarantee that a talk covers a requested technique**. + +### Real DocumentDB index and query + +`session_search` contains derived vectors and metadata; `search_meta` records +ownership, catalog fingerprint, model digest, text/schema version, count and +readiness. The canonical `sessions`, `workshop_meta` and `favorites` are not +changed by preparation. Vectors are finite, 768-dimensional and unit-normalized; +source/text/vector hashes are verified during preparation and periodically on +successful reads. Requests also check ownership, count, index options and returned +metadata. Mismatched or unowned collections are rejected, not adopted or dropped. + +The pinned local DocumentDB **0.117.0** executes this index definition: + +```js +{ + createIndexes: "session_search", + indexes: [{ + name: "session_meaning_ivf", + key: { embedding: "cosmosSearch" }, + cosmosSearchOptions: { + kind: "vector-ivf", numLists: 1, similarity: "COS", dimensions: 768 + } + }] +} +``` + +For this deliberately small corpus, one IVF list and `k: 216` retrieve the entire +candidate set before explicit filters. The **actual executed** query appears in +the inspector, with only vector coordinates abbreviated: + +```js +[ + { $search: { + cosmosSearch: { vector: [/* 768 numbers */], path: "embedding", k: 216 }, + returnStoredSource: true + } }, + { $addFields: { similarity: { $meta: "searchScore" } } }, + // Present only when selected; this is POST-retrieval filtering in DocumentDB: + { $match: { day: "2026-10-19", track: "" } }, + { $project: { embedding: 0, __cosmos_meta__: 0 } } +] +``` + +This is **DocumentDB's `$search.cosmosSearch` dialect**, not a claim that Atlas +`$vectorSearch` and its score metadata are identical. The application sorts the +actual returned scores, applies the disclosed **0.60 cosine cutoff**, then keeps +at most 10 results (the UI requests 5). No lexical gate, reciprocal-rank fusion, +answer generation or hidden fallback is applied. Nearest neighbors below the +cutoff are withheld rather than dressed up as confident recommendations. The +cutoff is an educational heuristic for this metadata snapshot, not a calibrated +universal relevance threshold. An initial 0.45 trial admitted unrelated bread, +ankle and basket-weaving queries; the stricter policy rejected those sampled +queries while retaining the three prompt-chip topics. This is a small sanity +check, not a benchmark or a guarantee for arbitrary queries. + +The inspector reports target/database name (never a URI), model/digest/dimensions, +index, filters, candidate count, ranking policy and embedding/database/total +latencies. It only shows a pipeline after successful execution. Queries create no +indexes and persist no query histories. Query text is kept transiently in memory, +not in a server-side result cache. Internal errors are reported by safe codes. + +## Model, runtime and resource budget + +- Model: [`nomic-embed-text:v1.5`](https://ollama.com/library/nomic-embed-text:v1.5), + 768 dimensions. Its official [model card](https://huggingface.co/nomic-ai/nomic-embed-text-v1.5) + declares **Apache-2.0** and documents the query/document prefixes. +- Model manifest SHA-256: + `0a109f422b47e3a30ba2b10eca18548e944e8a23073ee3f3e947efcf3c45e59f`. + Assets total **274,302,450 bytes** (~262 MiB), including model/license/config. + Ollama verifies blob hashes; the app verifies the pinned manifest digest on + every embedding batch. Model assets stay in the Compose volume, never Git. +- Runtime: official [`ollama/ollama:0.1.48`](https://github.com/ollama/ollama/releases/tag/v0.1.48), + pinned multi-platform image digest + `4a3c5b5261f325580d7f4f6440e5094d807784f0513439dcabfda9c2bdf4191e`. + Both Linux amd64 and arm64 manifests were checked before selection. Compressed + image layers are approximately **455 MB amd64 / 410 MB arm64**. The older runtime + uses the single-prompt `/api/embeddings` endpoint; the app normalizes its output + and batches preparation as four sequential bounded requests. +- **Deliberate size tradeoff:** a newer GPU-bundled runtime considered for this + feature was an amd64-only digest with **3.78 GB of compressed layers**. It was + not downloaded. This small older pinned runtime avoids that download and a new + Python runtime, but it is **not a recommendation for public or production + inference hosting**. Keep it isolated; upgrading it requires re-proving the + embedding contract and resource use. Its unused bundled GPU runner is extracted + to an owned disk-backed cache (~555 MiB observed on arm64), never used for inference. +- CPU only, **2 threads**, **1 GiB service memory limit**, one loaded model and one + inference at a time. No GPU pass-through or generation model. The app permits + one search at a time and bounds queries to 500 characters, result limits to + 1–10, vector queries to the catalog count, model calls to 60 seconds and database + queries to 10 seconds. Cold model loading takes longer than warm searches. +- Inference runs on a Docker **internal-only network**, with no published ports + and read-only model/runner volumes. Only the temporary download service has an + outbound route. There are no user-configurable inference URLs, HTTP redirects, + remote embedding APIs or query-time model downloads. The host preparation + command contacts the public model registry; queries do not. + +Reserve roughly **2 GB of extra disk** beyond the normal workshop and enough RAM +for the extra 1 GiB-limited sidecar. Codespaces compute/storage usage still applies; +there is no paid inference API. Test the chosen two-core Codespace before a demo, +not during the timed lab. If preparation fails or runs out of resources, use the +normal workshop while investigating; do not resize machines or delete unrelated +images automatically. + +## Failures and ownership + +- **Disabled / unseeded / not prepared:** use the explicit target command after + ordinary startup. The search panel is separate from core workshop readiness. +- **Model missing/digest mismatch:** preparation checks the fixed manifest and + repulls the pinned public model; a different model is never substituted. +- **Interrupted matching preparation:** rerun it; validated existing vectors are + reused and only missing rows are embedded. A crashed writer's lease expires in + three minutes. Ready is published only after the final real query probe. +- **Changed catalog/model/index or unowned namespace:** preserve the database and + investigate, or select a fresh explicit database name, seed it and prepare it. + There is intentionally no “force overwrite” or automatic deletion command. + A namespace interrupted before its ownership marker was written also requires + review rather than being silently claimed. +- **No strong match:** try a more specific subject or broaden the explicit filters. + Returning nothing can be more honest than the nearest unrelated talk. +- **Timeout / busy / cancellation:** retry after the in-flight work finishes. + Cancel clears the panel; late target/query replies cannot restore old cards. + +The ideas are inspired by an “Ask the conference” search pattern: local embeddings, +native vector retrieval, grounded source cards and an inspectable query. This is +an independently authored, search-only implementation over this repository's +public catalog, not a copied conference corpus or an additional required exercise. + +## Verification + +Offline tests include model shape/digest checks, explicit input and target guards, +UI cancel/switch races and honest unavailable states. They use labeled mocks and +do **not** establish real vector-search compatibility: + +```sh +npm test +npm run test:docs +``` + +After explicit preparation, run the opt-in real model/database suite: + +```sh +docker compose -f compose.yaml -f compose.search.yaml exec -T app npm run test:search +``` + +It creates a uniquely named owned test database, embeds the actual public catalog, +executes native vector queries, checks sampled unrelated queries, validates +non-destructive re-preparation and intentional mismatch rejection, and removes +**only its owned temporary test database**. It does not change workshop favorites. +The ordinary two-site integration and reconnect tests remain separate. A manual +**Optional semantic search showcase** Actions workflow runs the real-model suite; +it is intentionally not added to every normal push/PR or attendee startup. + +### Local evidence and limits (October 18, 2026) + +On an isolated arm64 Docker Linux VM with **2 CPUs / 4 GB RAM**, shared with other +running applications: + +- Both existing sites prepared **216 real 768-dimensional vectors** each, using + the pinned model and DocumentDB image. Fresh indexing took **40.9 s / 40.4 s** + after the model was cached. A complete idempotent `search:prepare -- --local-sites` + rerun took **9.8 s**. These are not full cold Codespaces startup measurements. +- The real-model integration suite passed, including exact index options, + full-corpus query, explicit track filtering, source/vector hashes, read-only + canonical catalog/favorites, repeat preparation, unseeded status and intentional + search marker/vector/index mismatch rejection. Ordinary two-site integration + and both loopback extension authentication checks also passed. +- A changed on-disk **model manifest digest** was rejected by both readiness and + query endpoints. Restoring the original manifest restored readiness. Stopping + the actual model service returned explicit failures while ordinary catalog + browsing remained available. Restart and canceled-HTTP retry recovered without + restarting the app or changing the notebook. +- Within that same owned project, first-use and previously healthy Site B outages + recovered with the same app token and the same three-concurrent-acquisition + probe process. The original database wait process also survived its first + failed connection. There was no target fallback or notebook change. The + standalone reconnect harness was not launched because it creates another + project; its critical cases were exercised against the owned test project. +- Warm HTTP samples took **69–216 ms**. “running AI locally” ranked **Running + Agents Locally with Open Source: From Laptop to Kubernetes** first (0.747) and + **How to Run and Orchestrate LLMs Locally** second (0.724). The supply-chain chip + returned supply-chain titles (top 0.719). Accessibility returned the published + accessibility titles (top 0.682), **but also generic “Workflow Phase” / “Community + Phase” entries because of their accessibility track**—a visible metadata limit, + not evidence that those entries cover interface implementation. +- Sample bread-baking, Antarctic veterinary surgery, broken-ankle, basket-weaving, + and banana-teleportation queries produced **zero accepted matches** at 0.60. + “developer mental health” also produced no accepted match. The earlier 0.45 + trial produced unrelated suggestions and was rejected. No universal relevance + claim follows from these few probes. + +Browser rendering and a fresh two-core Codespaces run require separate proof; +DOM-unit tests and this local API evidence are not substitutes. No Azure resources, +paid inference services, private corpus, or model binaries were added to this repo. diff --git a/package.json b/package.json index 800e6f8..c31d840 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,9 @@ "test:database": "node --test test/database.integration.js", "wait:database": "node scripts/database.mjs wait", "extension:connections": "node scripts/extension-connections.mjs", - "extension:check": "node scripts/extension-check.mjs" + "extension:check": "node scripts/extension-check.mjs", + "search:prepare": "node scripts/search-prepare.mjs", + "test:search": "node --test test/search.integration.js" }, "dependencies": { "mongodb": "7.1.0" diff --git a/scripts/search-index.mjs b/scripts/search-index.mjs new file mode 100644 index 0000000..8402050 --- /dev/null +++ b/scripts/search-index.mjs @@ -0,0 +1,28 @@ +import { readConfig } from "../src/config.js"; +import { readCatalog } from "../src/catalog.js"; +import { createConnections } from "../src/connections.js"; +import { reportError } from "../src/errors.js"; +import { SearchModel } from "../src/search-model.js"; +import { SearchStore } from "../src/search-store.js"; + +// Deliberately separate from seed/migrate and from every HTTP request path. +const args = process.argv.slice(2); +if (args.length !== 2 || args[0] !== "--target" || !["local", "site-b", "cloud"].includes(args[1])) { + console.error("Usage: node scripts/search-index.mjs --target local|site-b|cloud (explicit configured target only)"); + process.exitCode = 1; +} else { + let connections; + try { + const config = readConfig(); + connections = createConnections(config); + const target = args[1]; + const started = performance.now(); + const store = new SearchStore(await connections.db(target), await readCatalog()); + const result = await store.prepare(new SearchModel()); + console.log(JSON.stringify({ target, ...result, setupMs: Math.round(performance.now() - started), status: "ready", proof: "all vector hashes, index definition and actual full-corpus cosine self-query verified" })); + } catch (error) { + const safe = reportError(error); + console.error(safe.message); + process.exitCode = 1; + } finally { await connections?.close(); } +} diff --git a/scripts/search-prepare.mjs b/scripts/search-prepare.mjs new file mode 100644 index 0000000..8cf973e --- /dev/null +++ b/scripts/search-prepare.mjs @@ -0,0 +1,61 @@ +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { setTimeout as sleep } from "node:timers/promises"; +import { pathToFileURL } from "node:url"; +import { SEARCH_MODEL, MODEL_MAX_BYTES } from "../src/search-model.js"; + +export function preparationTargets(args) { + if (args.length === 1 && args[0] === "--local-sites") return ["local", "site-b"]; + if (args.length === 2 && args[0] === "--target" && ["local", "site-b"].includes(args[1])) return [args[1]]; + throw new Error("Choose explicitly: npm run search:prepare -- --local-sites, or --target local|site-b. This helper never provisions or prepares cloud targets."); +} +export function checkManifest(text) { + if (Buffer.byteLength(text) > 64_000 || createHash("sha256").update(text).digest("hex") !== SEARCH_MODEL.digest) throw new Error("The public embedding manifest does not match the pinned digest. Nothing was downloaded or indexed."); + const manifest = JSON.parse(text); + const bytes = [manifest.config, ...manifest.layers].reduce((sum, layer) => sum + layer.size, 0); + if (!Number.isSafeInteger(bytes) || bytes < 1 || bytes > MODEL_MAX_BYTES) throw new Error("The pinned model exceeds the optional showcase download bound."); + return bytes; +} +export async function prepareSearch(args, { run = spawnSync, fetchImpl = fetch, log = console.log } = {}) { + const targets = preparationTargets(args); + const started = performance.now(); + const response = await fetchImpl("https://registry.ollama.ai/v2/library/nomic-embed-text/manifests/v1.5", { redirect: "error", signal: AbortSignal.timeout(30000) }); + if (!response.ok) throw new Error("The pinned public model manifest is unavailable. Preparation did not start; the core workshop is unchanged."); + if (!response.body) throw new Error("The public model registry returned an empty manifest."); + const chunks = []; + let manifestBytes = 0; + for await (const chunk of response.body) { + manifestBytes += chunk.length; + if (manifestBytes > 64_000) throw new Error("The public model manifest exceeded the size bound. Preparation did not start."); + chunks.push(chunk); + } + const bytes = checkManifest(Buffer.concat(chunks).toString("utf8")); + log(`Optional embedding-only showcase: pinned model assets ${bytes} bytes (Apache-2.0); no generation model or paid API. Targets: ${targets.join(", ")}.`); + const base = ["compose", "-f", "compose.yaml", "-f", "compose.search.yaml"]; + const docker = (args, options = {}) => { + const result = run("docker", [...base, ...args], { stdio: "inherit", timeout: 900000, ...options }); + if (result.error || result.status !== 0) throw new Error(`Optional search preparation stopped at Docker ${args[0]}. Check the preceding service output. Existing catalogs and favorites were not replaced.`); + return result; + }; + try { + docker(["--profile", "search-download", "up", "-d", "search-download"]); + let ready = false; + for (let attempt = 0; attempt < 20; attempt++) { + const result = run("docker", [...base, "exec", "-T", "search-download", "ollama", "list"], { stdio: "ignore", timeout: 5000 }); + if (result.status === 0) { ready = true; break; } + await sleep(1000); + } + if (!ready) throw new Error("The model download service did not become ready. Core workshop startup does not depend on it."); + docker(["exec", "-T", "search-download", "ollama", "pull", SEARCH_MODEL.name]); + } finally { + // No down -v, no pruning, no other projects. Inference uses an internal-only network. + docker(["stop", "search-download"]); + } + docker(["--profile", "search", "up", "--build", "-d", "--wait", "--wait-timeout", "240", "app", "search-model"]); + for (const target of targets) docker(["exec", "-T", "app", "node", "scripts/search-index.mjs", "--target", target]); + log(JSON.stringify({ status: "ready", targets, model: SEARCH_MODEL, modelAssetBytes: bytes, elapsedMs: Math.round(performance.now() - started) })); + log("Search by meaning is enabled. Refresh the page/readiness. This is a built-in showcase, not an extra lab exercise. Normal workspace:start remains model-free."); +} +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + prepareSearch(process.argv.slice(2)).catch((error) => { console.error(error.message); process.exitCode = 1; }); +} diff --git a/src/config.js b/src/config.js index 01593da..f804cab 100644 --- a/src/config.js +++ b/src/config.js @@ -91,7 +91,7 @@ export function readConfig(env = process.env) { } } if (!Object.hasOwn(targets, activeTarget)) throw configurationError("The requested initial database target is not configured for this scenario."); - return { mode, scenario, location, activeTarget, port, host: env.HOST || "127.0.0.1", publicHost, targets }; + return { mode, scenario, location, activeTarget, port, host: env.HOST || "127.0.0.1", publicHost, targets, searchEnabled: env.SEARCH_ENABLED === "1" }; } export function targetLabel(target, location, scenario = "attendee") { diff --git a/src/public/index.html b/src/public/index.html index 71b6ea6..24efcf1 100644 --- a/src/public/index.html +++ b/src/public/index.html @@ -121,6 +121,17 @@ .empty { padding: 24px 0; color: var(--cp-text-muted); } .footer { margin-top: 32px; border-top: 1px solid var(--cp-border); padding-top: 16px; font-size: 0.875rem; color: var(--cp-text-muted); } .results { padding-left: 20px; font-size: 0.875rem; } + .semantic { margin: 24px 0; } + .semantic-filters { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px; } + .semantic input, .semantic select { min-width: 0; width: 100%; } + .semantic-chips button { font-size: 0.875rem; text-align: left; } + .semantic-results { list-style: none; padding: 0; margin: 0; } + .semantic-results > li { display: flex; min-width: 0; } + .semantic-results .session { width: 100%; } + .semantic details { min-width: 0; } + .semantic summary { cursor: pointer; font-weight: 600; } + .semantic pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 28rem; overflow: auto; background: var(--cp-surface-soft); padding: 12px; border-radius: 8px; font-size: 0.8125rem; } + .semantic .meta, .semantic .status { overflow-wrap: anywhere; } dialog { max-width: 560px; width: calc(100% - 32px); border: 1px solid var(--cp-border-strong); border-radius: 16px; padding: 24px; background: var(--cp-surface); color: var(--cp-text); } dialog::backdrop { background: var(--cp-overlay); } [hidden] { display: none !important; } @@ -133,7 +144,7 @@ .layout { grid-template-columns: 1fr; } .itinerary { position: static; } .environment { align-items: flex-start; flex-direction: column; } - .filters { grid-template-columns: 1fr; } + .filters, .semantic-filters { grid-template-columns: 1fr; } } @@ -178,6 +189,49 @@

+
+

Optional built-in showcase / Outside the 105-minute lab

+

Search by meaning

+

Search the schedule snapshot's published title and track metadata by meaning. Cards show published rooms and times, not invented descriptions. No generated answers. This built-in feature works independently of Exercise 1; saving favorites still uses Exercise 2.

+

Checking optional search readiness...

+

+

+
+ + Optional setup: npm run search:prepare -- --local-sites. Core keyword browsing does not require a model. +
+
+ +
+ + + +
+
+ + +
+
+ + +
+
+ The query is sent to this app's configured embedding service. This page keeps no search history. Pure semantic ranking uses raw cosine similarity, not confidence or probability; there is no keyword fallback. Keyword search and its filters below are separate. +

+
    + +
    +
    0sessions
    0favorites
    @@ -187,7 +241,7 @@

    -