diff --git a/.dockerignore b/.dockerignore index 6883715..52daecc 100644 --- a/.dockerignore +++ b/.dockerignore @@ -10,3 +10,8 @@ test-results # Secret-bearing local extension handoff; never build, commit, or share. .workshop-private/ + +# Incomplete maintainer-only embedding bundle publication. +data/search/*.pending +src/search-bundle-pin.js.pending +data/search/.publication.lock diff --git a/.github/workflows/semantic-search.yml b/.github/workflows/semantic-search.yml new file mode 100644 index 0000000..09b3ee4 --- /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: Cache pinned query model and import the reviewed document vectors into both sites + run: npm run search:prepare -- --local-sites + - name: Zero document inference, live query embeddings, native vector queries and integrity 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/.gitignore b/.gitignore index 349d33f..ac6750c 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,8 @@ Thumbs.db # Secret-bearing local extension handoff; never build, commit, or share. .workshop-private/ + +# Incomplete maintainer-only embedding bundle publication; never commit partial assets. +data/search/*.pending +src/search-bundle-pin.js.pending +data/search/.publication.lock diff --git a/README.md b/README.md index 1f4b51b..e820125 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,35 @@ 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 once for arbitrary live queries, +starts an internal-only CPU service, and **imports the same checked-in ~716 KiB +session-vector bundle** into both existing local sites before building each real +DocumentDB vector index. Attendee preparation makes **zero document-embedding +calls**; these are precomputed embeddings, not canned search results. +In the tested two-core Codespace, full optional preparation with the model/image +already cached took **17 seconds**, including about **1.8 seconds per site** for +import/index/verification. First-time model downloads add time; see the +[measured acceptance and limits](docs/semantic-search.md#codespace-and-browser-acceptance-october-18-2026). +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..e86d644 --- /dev/null +++ b/compose.search.yaml @@ -0,0 +1,63 @@ +# 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" + # Let Ollama select the available CPU backend (AVX2/AVX on amd64). + # Every embedding request sets num_gpu: 0; no GPU is passed through. + 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/data/search/MODEL-LICENSE.txt b/data/search/MODEL-LICENSE.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/data/search/MODEL-LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/data/search/README.md b/data/search/README.md new file mode 100644 index 0000000..9ce2fd4 --- /dev/null +++ b/data/search/README.md @@ -0,0 +1,69 @@ +# Reviewed session embedding bundle + +This directory contains **derived vectors, not model weights, query results, or a +physical database index**. The default optional preparation imports this same +bundle into either explicitly selected DocumentDB site. Every new user query is +still embedded locally and executed against the selected database. + +## Assets and provenance + +- `session-embeddings.f32`: **663,552 bytes**; 216 rows × 768 float32 little-endian + coordinates, row-major in ascending session-ID order. + SHA-256: `f1f6ae30c6550fdd14cb80fa0ad9d2876b86b2e8faf8784308a6bf669c19b582`. +- `session-embeddings.manifest.json`: **69,657 bytes**. Contains the exact model, + catalog fingerprint, text/normalization version, vector-file digest, source/text + and decoded-vector hashes for every session, and generation provenance. + SHA-256: `4b0c03a82b77eee871ef3d2a29b8176f2a994e31a5a9e94ee058532247929da0`. +- Combined vector/manifest payload: **733,209 bytes** (~716 KiB). A separately + reviewed source pin in `src/search-bundle-pin.js` authenticates both assets; + editing only a manifest cannot authorize changed vectors. + +Generated afresh on **2026-10-19 03:48:30 UTC** using the pinned +`nomic-embed-text:v1.5` manifest +`0a109f422b47e3a30ba2b10eca18548e944e8a23073ee3f3e947efcf3c45e59f`. +The official Ollama 0.1.48 image index is +`4a3c5b5261f325580d7f4f6440e5094d807784f0513439dcabfda9c2bdf4191e`. +Runtime: Linux **arm64**, observed **cpu** runner, two threads, `num_gpu: 0`, +`num_ctx: 2048`, `/api/embeddings`. Generation performed **216 real document +embedding calls**, not an export of unverified old rows or synthetic embeddings. + +Only this repository's checked-in public ATO schedule **titles and tracks** were +embedded, using `search_document: \nTrack: <track>`. There are no abstracts +or private conference materials. Catalog fingerprint: +`867c0473e9366654f222ad585515d4028289f192b6f39bd3123d9f704ddde106`. + +The model output was normalized in float64 by the shared adapter, then encoded as +float32 without further normalization. Import validates every finite coordinate, +unit norm tolerance, hash, source text and ID. CPU/backend floating-point results +may differ: regeneration is deterministic in ordering/format, **not guaranteed +bit-identical across machines**. New checksums are deliberate reviewable changes. + +## Attribution and license + +Model: Nomic AI, [nomic-embed-text-v1.5 model card](https://huggingface.co/nomic-ai/nomic-embed-text-v1.5), +licensed **Apache-2.0**. `MODEL-LICENSE.txt` is the exact license layer distributed +with the pinned Ollama model, SHA-256 +`c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4`. +No model weights are redistributed here. The generator and workshop code retain +the repository's MIT license; the public schedule's original source and caveats +remain in `data/catalog.json` and the schedule import report. Derived vectors do +not add a new license claim over the original published conference material. + +## Maintainer regeneration (never an attendee startup step) + +See [the complete optional-search guide](../../docs/semantic-search.md) for service +startup, runtime caveats and ownership. With the correct local Compose project +and pinned model already running, run from the repository host terminal: + +```sh +npm run search:bundle:generate -- --write +``` + +This explicitly computes all 216 document embeddings in the app container, checks +the actual model runtime/backend, writes the two fixed assets and updates the +source pin **last**. It modifies no database. Review all three files together, +run offline tests, rebuild/restart the app to reload its pin and decoded bundle, +run actual search tests, and deliberately commit the updated assets. +Restore all three files together if generation/publication is interrupted. +Regenerated assets are not silently adopted by existing database search rows; +use a fresh explicit database or a reviewed search-only migration. diff --git a/data/search/session-embeddings.f32 b/data/search/session-embeddings.f32 new file mode 100644 index 0000000..a5c6833 Binary files /dev/null and b/data/search/session-embeddings.f32 differ diff --git a/data/search/session-embeddings.manifest.json b/data/search/session-embeddings.manifest.json new file mode 100644 index 0000000..ba704c4 --- /dev/null +++ b/data/search/session-embeddings.manifest.json @@ -0,0 +1,1337 @@ +{ + "version": "ato-session-embeddings-v1", + "catalogFingerprint": "867c0473e9366654f222ad585515d4028289f192b6f39bd3123d9f704ddde106", + "model": { + "name": "nomic-embed-text:v1.5", + "digest": "0a109f422b47e3a30ba2b10eca18548e944e8a23073ee3f3e947efcf3c45e59f", + "dimensions": 768 + }, + "textVersion": 1, + "normalization": "l2-float64-then-float32-v1", + "encoding": "float32-le-row-major", + "count": 216, + "data": { + "file": "session-embeddings.f32", + "bytes": 663552, + "sha256": "f1f6ae30c6550fdd14cb80fa0ad9d2876b86b2e8faf8784308a6bf669c19b582" + }, + "provenance": { + "generatedAt": "2026-10-19T03:48:30.848Z", + "method": "fresh-local-model-inference", + "runtime": "ollama/ollama:0.1.48", + "runtimeImageDigest": "sha256:4a3c5b5261f325580d7f4f6440e5094d807784f0513439dcabfda9c2bdf4191e", + "platform": "linux", + "architecture": "arm64", + "endpoint": "/api/embeddings", + "options": { + "num_thread": 2, + "num_ctx": 2048, + "num_gpu": 0 + }, + "documentEmbeddingCalls": 216, + "license": "Apache-2.0", + "modelSource": "https://huggingface.co/nomic-ai/nomic-embed-text-v1.5", + "corpus": "Only this repository's public ATO schedule titles and tracks; no abstracts or private corpus.", + "reproducibility": "Stable session order and float32 encoding; CPU/backend floating-point results may differ. Regeneration changes checksums and requires review.", + "backend": "cpu", + "backendEvidence": "Observed /runners/<backend>/ollama_llama_server in the model container process command line immediately after generation." + }, + "sessions": [ + { + "id": "ato-2026-26664-20261020-1", + "sourceHash": "2973a2bb6a43d322f5c5fffd8ba9d7f4013342f63664f4e6d359b6d674217a70", + "textHash": "7a1850a76228210e74a97eed556a4054e7bb85a62d68aef9ebfe4978a21e1be1", + "vectorHash": "93a7681f226e0c6e43e3a668ba3586cfc4f71ce692169916fd308b50e590c5c8" + }, + { + "id": "ato-2026-26673-20261020-1", + "sourceHash": "a5674c5d4391f634bde5ea9d33261fbdeac3e1772397fb86d5fa6deeb404362c", + "textHash": "d5f7d98c8a80952cfeaf2cfde6b0cff476c46c51744c8740ab3e6deebb09e086", + "vectorHash": "b9120941b50b6c5b508285b828c408f3aa5967feef261ac3e5b22df236680180" + }, + { + "id": "ato-2026-26686-20261020-1", + "sourceHash": "f5a78365ff15df616e46d6f1101d80f1c75d14cd1946c002abf2d13f4d6e3e42", + "textHash": "05f90d59d061b2dd04ef4d29ac461c4711d11709cd84ab0a559d9872d3a5d779", + "vectorHash": "2f384ea52104b508f2375564f5e69ea5725fa57b7b478bc9e0d0bdb0a09b3065" + }, + { + "id": "ato-2026-26705-20261019-1", + "sourceHash": "551f205de769b800434b912ab0eb1b4e2ae097f75fc96f3856d36e47ea8612bf", + "textHash": "ede332d6571802de3e39e699c26516d804f7650cb9f316ccc3a49649cc0a7f3f", + "vectorHash": "22ac00cfeb11354d7da2a05b25b49b0f0fb28d950d332edf096492ea72247e6b" + }, + { + "id": "ato-2026-26711-20261020-1", + "sourceHash": "95540144dce18e3b6e603d44b32e07b4823eda9a67267834938645caa143400e", + "textHash": "a82c51124351e3895d39534098a66331f313e593b6a60be12dfb27e0684d65ae", + "vectorHash": "a0468dba2303dcdf73b052dd411a0cc23c4192e963bd7310bc1d174f58d07fd6" + }, + { + "id": "ato-2026-26732-20261020-1", + "sourceHash": "62c36a7fad3b6ee153d4d5958764dc2802cbf8765fb49f234e5a96542133fc56", + "textHash": "d004639b71cbdc94c2d42d4943231dd3d0285a7b1758f3ac79d7214e9ab4c6f5", + "vectorHash": "fac5e9a8ca888685fba179f966b995ab33ebd6816848273dd0a5aa38595d8865" + }, + { + "id": "ato-2026-26738-20261020-1", + "sourceHash": "90cc77d39144412e2d9e1e22a4536b6496ccd3d6a376288964ced02369265fe5", + "textHash": "313b098f81774f67a12a8f04bb5e9f3a1b7abf05a4dd721bbae7f65f33f2de8a", + "vectorHash": "b64bb681a5154eeac32171b3c63d4cd777c8d90b15a3c048da7d3c5c88ccc31a" + }, + { + "id": "ato-2026-26752-20261020-1", + "sourceHash": "b1196008aa0723ea41011a2fa600058b977caf94fd1a2f2ed6de130e382611dc", + "textHash": "83bf91155f6ee9bf46b426d5d2a391fdfdba31e247bd5ab24a604ae9324790dd", + "vectorHash": "25858b120ea1cec7a091bb441e9678baea25d37278cc8ce3ab8a3eec98b3f012" + }, + { + "id": "ato-2026-26755-20261020-1", + "sourceHash": "af63decd9b57933078455e4a84c792647bad5041d4ec3f8ea4139fd03e54171f", + "textHash": "29e1617951cc94d609432deafcfdd98feeb1580e2727395282ebba43056b28e7", + "vectorHash": "5394563a867128b8929956ac0468c6d6733237a82c0034b27c010066b38bb468" + }, + { + "id": "ato-2026-26761-20261020-1", + "sourceHash": "a4e41d4eb9f7ed6f2b747ee64f7101134ed12b4f90d34438ab00fd08973ef8ef", + "textHash": "dfce739ef56de4e989ca653c6f9b5580a95dc7152e8a43e5871578d3d02f023b", + "vectorHash": "1e1decddbd03605f82c03eb0d2362afa5b3e4e3a6504c1dbaaf2c2e11c41d8c4" + }, + { + "id": "ato-2026-26764-20261020-1", + "sourceHash": "91f7f22253471f3a844506066954e46aa5d575a18c1be59baadddfb674945188", + "textHash": "1a44bde9d0c628f0f1ea8e76ca9685a693f28812c6cae9e4144feb8f420047c0", + "vectorHash": "6e6ed2d19761fa6ff5a11b8dc09fac0cd458fc34ce3073594df2e8257127e8d9" + }, + { + "id": "ato-2026-26770-20261020-1", + "sourceHash": "cb80bbc06fac6f7a898ada355c61fbb5d7df00f35aad948f0e4742a87f466b7d", + "textHash": "6c8d7d40edac25acce6d9e7f63a4bbaf2a4868320b5da93e15bbdcf8d94cf5d8", + "vectorHash": "5b4fa1a03ed29efeb24b909356d4fb923a6ba2fc7ab9f94dc9eb0656882b1076" + }, + { + "id": "ato-2026-26773-20261020-1", + "sourceHash": "51cbe0d9a2817533614e474820421136e22ade29c9de296d9344db273ba07cbc", + "textHash": "e8515192c1f305f23b676a0fea3e3289fba725da0031bad69de141ea787b0f4a", + "vectorHash": "ee424542ad95998805f2b92649326c6cb0b0fc110b4bf23facb18df49e00009f" + }, + { + "id": "ato-2026-26776-20261020-1", + "sourceHash": "b990d40a44ca8c79a848cc61695bcd4f42d049fed3d4b4082549443cdbd8978c", + "textHash": "9104da8572e48a1ad8c85b31f4fc458f20f5fd689dd089c52fe2251414025897", + "vectorHash": "82884fcaf6cbd489b8b68e19eb720f33f5040138ae95d164cf52d1bc5d75ba5a" + }, + { + "id": "ato-2026-26782-20261020-1", + "sourceHash": "0d2dff7f43420d3d7f796b23c7c1d46354cccb03d6ea3239935443daeb046317", + "textHash": "ca3c32e2d36053b9b9533add77ec027b83ccc6995cbd10ad039ef739d5fb0f3c", + "vectorHash": "cbd02ab25648ed8aa3dc89114cca318756b67581b4619547ac9d05d7f1ec96e3" + }, + { + "id": "ato-2026-26785-20261020-1", + "sourceHash": "e339a281121f2d9ce543f8d6ee826e53a643bdc18c71b1a3aa3b85466560fc15", + "textHash": "2c20fc1ac0853c5239108a89cf8190d6e097dc5f796abebdb9af1b13ea13141c", + "vectorHash": "fa1d9a088e72bc77824ff1352361ac53da2808435ca34f77d782ad1957e8676f" + }, + { + "id": "ato-2026-26788-20261020-1", + "sourceHash": "c0031e0d2df55dfa5c28088858e1d589cd99af2c0bf790b6ffa574a3a73b76aa", + "textHash": "ceedfa20ccc1c73f992c5815772502b8ae161932a164930dff05e2487eeb3d55", + "vectorHash": "34f38dd78f08dc1851f64a0f18c1708dc517319335f6de4db1b60dc21f7204ca" + }, + { + "id": "ato-2026-26791-20261020-1", + "sourceHash": "ffc69da57e7f18a00eb3c2fa2687052259d5b686bb9309589822db1cda3faf80", + "textHash": "ebd788aa5c3f6a775261d7a61e423b590e9def52bc3ef472b604bf3d2ef4dffa", + "vectorHash": "88caacbbc349e210ded7aafca4649a91405c2b62c7fdff7b44467273bfda723d" + }, + { + "id": "ato-2026-26794-20261020-1", + "sourceHash": "c5b0293c50c42004654b5b3b8a1fd5ed231e99a235bf4498a8eac959a52cdfa8", + "textHash": "ba1a9f466a5f741212aefa1112a76e7ce3d46b54a09ac8953e0f4f4ead30390c", + "vectorHash": "d45e5b35b8871b91fe80cb25cd1b139e0e016af380b15078733ea36d03268d0f" + }, + { + "id": "ato-2026-26799-20261020-1", + "sourceHash": "923ca8de1976d9e7ea45613c72110a7c5e65c3e16f931b9023c84e37945d6f35", + "textHash": "bc38c61836be8760e88f534afa1bf3209b1845d5d3fdbb771d4a90dab23553e8", + "vectorHash": "355eeb4967ea8fe7dc45036a99f739fca4b0a6a9798d3e50b6fd97000325583c" + }, + { + "id": "ato-2026-26802-20261020-1", + "sourceHash": "47401d2908ce83776a06ab7df11fcd267499700824000ad6ca4731a933f98c56", + "textHash": "1b401ebdf86b2c33ece2117e4110308e685198e5adaaeb18dcdbcdfeb5ee351f", + "vectorHash": "0e17b9a91d0969cc7447ef77cd7913ce1b500c7f00f299286ecdc5c28809048e" + }, + { + "id": "ato-2026-26805-20261020-1", + "sourceHash": "75797df1b83eb017d954e5414596ff36c5549032900c370e2f30ac4732054cb5", + "textHash": "dd1cd0bdcb875080ade1e99fe37e176b02e1845bd1b34dca2f2bf0a5d728705f", + "vectorHash": "8fc98b12373fe6acf3bbb714a583bcec03e32efcb126285c52179feb55f83d19" + }, + { + "id": "ato-2026-26808-20261020-1", + "sourceHash": "9870704bbe287612f5e0cea0487ba15d273fa6a11d527fb791ae6f07a2cb3c6e", + "textHash": "f7af2ca177bdf480c148d0043c1e423f7d8444ca66917f608018127283594287", + "vectorHash": "ef6f345962ca395678c9ff24f7f9efbe3b42d50a52a52e170df83da6d65a0b08" + }, + { + "id": "ato-2026-26809-20261020-1", + "sourceHash": "05f6e9a6534de0ffc1ca3db7c047b5132bdb047373c4bcc879e9d1459a3114ca", + "textHash": "717c8b504b0590645a51893987eb91873a66f51038749ede2b4fc68b4888c632", + "vectorHash": "dd8c17fcc3e21fedbee31703ad12d1f6f68595c5dd450ef2a696b8b70f13cb40" + }, + { + "id": "ato-2026-26811-20261020-1", + "sourceHash": "607a2ada48fa2443718766808651415acf4f421a0207a72a700b1fe4cec67454", + "textHash": "9a9865cf9c6f40f11b56c14aeffc15f657e97c0bb9fccb4d9f53b049418ad0e3", + "vectorHash": "1f3ba855e4e2463e8276d7729b8146d1b16a6d0b5d52363e3c5d36f50672694b" + }, + { + "id": "ato-2026-26822-20261019-1", + "sourceHash": "2e9adb3a9d1b0f7236c55c76261acdadefc987ab344530fd07ab97464afa429a", + "textHash": "f5dd8f1df60d14418f81cba504437872c90c0df663c3f4bc265827b64398600d", + "vectorHash": "fd143727064d280e916b118df8c57d4d76d87a6f05babba5ad776e08811c4515" + }, + { + "id": "ato-2026-26825-20261019-1", + "sourceHash": "2dcd36727e6be702f76b97e6ec2913cbf67c0d9c9f8aafff43ddb76492ddc85a", + "textHash": "4f8db52d044f6af24f82266732f21cc13c355919fb1b8f808a8b54327905a1b7", + "vectorHash": "ca7df14031e486ff9193e480ac365d050be62af08b1f09420213da3c5b5f7bd3" + }, + { + "id": "ato-2026-26828-20261019-1", + "sourceHash": "4de2713babfebb297bfd7aef95b01c528debc8b0a3a785bec55ce826873317aa", + "textHash": "2e5535eed36e2e4ac1b4db35ae9f85eb9565451da2964d3cec9323670df76371", + "vectorHash": "e8c6710ebd8e9001f96301d2b328767d071ea1443486b37d91acb7a258b66941" + }, + { + "id": "ato-2026-26831-20261019-1", + "sourceHash": "cd06199e5b147f684828a8b79d72e7cecba92def6d10d832ea81d3dbd39e6d2c", + "textHash": "4b9f5e68f66c03e87284a809bbc8d377ec220df6b76e2e374c160f91b3662dbf", + "vectorHash": "e1269ee2952c0bc034ccd44e72b961045dbf786089109775593b1aeb557f5321" + }, + { + "id": "ato-2026-26834-20261020-1", + "sourceHash": "688800e8be76e2926a952f7d446c6a418670ca45aaff4d3d4ac7d568bd9837d2", + "textHash": "bdc8df98ae40f147421c447ff5d7f078d03e489ad60062cbb1fc4dcd2b96d9ea", + "vectorHash": "dcb5e031fde3a9bb6513d3920a774829e9da1e1a6fb53373caf2828a8f2d14c1" + }, + { + "id": "ato-2026-26837-20261020-1", + "sourceHash": "f4f1034fee2bbc2eca29fe4d25611c9944e2db5c9d3973d11ce963ab25146605", + "textHash": "688f29afe8cafef05e7de86e908ad7bf45045a469cfe2fbc3b23d3ed311a298c", + "vectorHash": "8ecbf1132207c93bf194ff91b2a921679338652db77fee4059b7288fa18d789f" + }, + { + "id": "ato-2026-26971-20261020-1", + "sourceHash": "4514bbca3ec730ccd2cd4798e50aa908875d103a0697f0fae8f4bfdb6c7ca8bc", + "textHash": "e5d569f7b227ef0240328157f7c06c01fa7f1ea3acdc5c0faed474271dad18dd", + "vectorHash": "a532c1172fde18649c2e84cfa678e1c6203e29df1bd7eee0c82151a431d88f46" + }, + { + "id": "ato-2026-26974-20261020-1", + "sourceHash": "96badb37f3d579a14bee0f32f0311b84968db0b868eab3bc947f6ddfabafc2d8", + "textHash": "b96943f2058f39ca912a63a5f047af57ea1634d54973e8ce4053afefa191073c", + "vectorHash": "19d3ab9f53856ac45df5a2ef9d017a9e0191e5900c3ba70fcb4dbae72b6fd65e" + }, + { + "id": "ato-2026-26989-20261020-1", + "sourceHash": "d953a9fa43eff2acad0556d54019ec1a146750d724ba94ddeb31d6326e5dca54", + "textHash": "2c95425a7892c20fe9e4fe40076a4d0fb2d9b85ffb2a82eb72338f79158ccce8", + "vectorHash": "efcb47d8c7c0d0161367bdb6382ccd3a0df4253d60ce3b878c2accc472fe2a19" + }, + { + "id": "ato-2026-26990-20261020-1", + "sourceHash": "5430eb06e0d1ba9a6f5d92b801dec3cf3a91ad6b7bb117b27986abf19c05804e", + "textHash": "3f119aa4d52c71deb2187206539ec9d372480ce3c4e76f4dbdd99ebe29f032c6", + "vectorHash": "0f7313a5d024af8cf41d00d9d29c9fa80b90c9eeff2902eb3d5dda3f93057368" + }, + { + "id": "ato-2026-27047-20261020-1", + "sourceHash": "fed16d368f48da05eab00e38f03fd8ac760c8a204ed39bd088dccf7e9850f761", + "textHash": "b996623450f8ee562d8eb0b1f8098212ac408797bf13c92a4676ef75674a770c", + "vectorHash": "43903b8d6c18b5084747a1bec37feec498bff275e9f57791fd72c75373f1f760" + }, + { + "id": "ato-2026-27060-20261020-1", + "sourceHash": "a0a4a7d6f1ec259bacc4c6e124048c7b8b103af3a0421a6dc0a3b2a0a5b4b2bb", + "textHash": "5c649fd78a55bdb31089f5452c4e4f6b835cefd91f02110f672996d743d27782", + "vectorHash": "b075039336bc015719cc93e12b35ec8ab7c5e7213882210d2d411f18f67b6dab" + }, + { + "id": "ato-2026-27066-20261019-1", + "sourceHash": "f3d7a8b40b3a40135126ef3d5b657700d393f2cd5057cea567fc9414678dea9f", + "textHash": "0acba13c271e545ce8d8c9a85ef6697ccf110206450b0d867877d17c7f13ffff", + "vectorHash": "04720d7a0d624439c21e22d71925366f6369f7315a51c0b55cb8ebb0bf9885cb" + }, + { + "id": "ato-2026-27069-20261020-1", + "sourceHash": "894c9dc9f265c2c5fd206d8b04f66d6e8fab550ed5e0fee2bf34abb372801ac1", + "textHash": "1dd75c0b4d4a6814295ee41ae4622ab1b097e95ddbe358206e3b1e0e03bb1262", + "vectorHash": "de88b591e8bcf05db5370d8b882fb773d49da2ac694ee47ac3e52b0104aba58d" + }, + { + "id": "ato-2026-27073-20261020-1", + "sourceHash": "4397c3bfb86e3e3787d7dd5beee87bda23ccd48c943580278b02b8bb8d70b7c9", + "textHash": "0d558840f91facb63e8d4b922289288d1bd791501110f1d4db7754be551e870d", + "vectorHash": "96104ee02566276c58d935e92711276b86b71ccb56d18b2c68c787c26d7993c3" + }, + { + "id": "ato-2026-27078-20261020-1", + "sourceHash": "06b13722f675ead7617efa5509cf7515e9fa76b5b9aa3cba15daf52261ce239b", + "textHash": "5996b56013e83084ee57b474e62df976fe7678a2b939a843b1493acb99171f7e", + "vectorHash": "7b92074d833403654182ddc62c06066e59784330d6858698b7459828f867b7f4" + }, + { + "id": "ato-2026-27081-20261020-1", + "sourceHash": "380ff2872eebfc7224ea67544b8aa8e5d006dc73b6441e7f170fa10f2dcf4e59", + "textHash": "a67f1275db0650816e5c0af5b2370ed93155baaa89cb1f36cb6fb882f8f2f508", + "vectorHash": "6f99b34fd40a231212fc5bec790ab8022f9520de4ae41a0c636c7cedef58dc88" + }, + { + "id": "ato-2026-27094-20261020-1", + "sourceHash": "e742930c45b605d20eadf18614b8e94d3a179da0a7ca92dc671e0f0fb32f1390", + "textHash": "83da282cf7bb7117bb9f74c1627f1b73154ea51a8a1ef3b4970fd659650d61a5", + "vectorHash": "eec8051d357cf06b7d4b44158c4754a623360e556c8d8fd1ad186fc0a7871401" + }, + { + "id": "ato-2026-27098-20261020-1", + "sourceHash": "aedfb30e170b16b01ada99bb80a3d4d41d3907b83465568d63a12f0f2cd48a30", + "textHash": "fcc0041823c774f8afa637025eb91fee13f312fc961133391cb4ed413f768da1", + "vectorHash": "fd7c6620505cdc574d3b483ee090a988784b1f5fa16529326dafd6bf1dde848b" + }, + { + "id": "ato-2026-27099-20261019-1", + "sourceHash": "5182313fad3f9364a0361e7d3d67cc8b7653e7679f18fcf7d6c2f78ee00760a9", + "textHash": "a80e95cc9c5941a27e2b208e560c7ca6cc90389fb56606be2c44730449231fbb", + "vectorHash": "4c729d5e95289fc4ef013ecd8b6d9eefce2308a9529a75b2279f625567c3c8e5" + }, + { + "id": "ato-2026-27102-20261020-1", + "sourceHash": "b5e8fe6636003a650605772ca541e2cfe875add88e0f275e46792f3156ac7c0b", + "textHash": "7f72b3bcd0a0d4acea0c928cfc2195d1c1ca4256cdf47fde5403f5b6815d7486", + "vectorHash": "d7b9f8b08f60eecf3c02e71f3c787590c48c4b1c456683c9d79aa320d0715450" + }, + { + "id": "ato-2026-27105-20261020-1", + "sourceHash": "bc42c5f04d2b0673b4668982ed304db5b85b6003d7950a3bf3f7b298cf05ce65", + "textHash": "0452c745e193477745c5f7b26f5feb3fabf2e51d86fc6fd950c546b1a87c0ee5", + "vectorHash": "330ec7df2aeee544584a76bfab3b03b1188fe94f2f1502c447fc879a272bee28" + }, + { + "id": "ato-2026-27106-20261019-1", + "sourceHash": "5d9d2bd4645ee38e465b99c0a24ae6fa4704ec377520507f74ca5bad65f33db8", + "textHash": "dff8eff436c04638f0b930d085dfcc46954aacb130442c6cb87352200e6c6441", + "vectorHash": "9fb745ed88566a144e199e4d18f100535a0e7d66db25e99c203ba51d1a27a784" + }, + { + "id": "ato-2026-27106-20261019-2", + "sourceHash": "d07fc8b1ffa456177b29af793095d22b57b397be45033ebaaf93dd52315f2084", + "textHash": "dff8eff436c04638f0b930d085dfcc46954aacb130442c6cb87352200e6c6441", + "vectorHash": "9fb745ed88566a144e199e4d18f100535a0e7d66db25e99c203ba51d1a27a784" + }, + { + "id": "ato-2026-27109-20261019-1", + "sourceHash": "56b6a18dbf5adbe2bc412f5cb1c8a22f1eb9e45ac01d7b34d6ed40a52bbf5830", + "textHash": "ba4b93e63e4abfab6afd96b596f6fdb7ff53ed558f7fdcfff3ada7ce8bb5586f", + "vectorHash": "272b03b3ac479e52e8041d292d711887ec68e89ffbf98cf43817f4d41c4b0075" + }, + { + "id": "ato-2026-27109-20261019-2", + "sourceHash": "8aafc3c7a57047de696053a7a1c3f874df26936b3f04c7baded898ae9205058e", + "textHash": "ba4b93e63e4abfab6afd96b596f6fdb7ff53ed558f7fdcfff3ada7ce8bb5586f", + "vectorHash": "272b03b3ac479e52e8041d292d711887ec68e89ffbf98cf43817f4d41c4b0075" + }, + { + "id": "ato-2026-27112-20261019-1", + "sourceHash": "ee12809420a6a502dfbefe54d5c2efd2aeed3f6afac2417c1bc87db08ff88c97", + "textHash": "2347cc509b5c3c9758c005d4cd5147bd415df1b12f197393844c7c587bb1cbc4", + "vectorHash": "888bb063c8b76890188a59aaedae92d61b0b95c2fbc54252d3c30ad3abc23baa" + }, + { + "id": "ato-2026-27112-20261019-2", + "sourceHash": "b5ea910b4c04b55d2e6bb77514ba2229e43638d3b110d6c61499eb7a84e5c735", + "textHash": "2347cc509b5c3c9758c005d4cd5147bd415df1b12f197393844c7c587bb1cbc4", + "vectorHash": "888bb063c8b76890188a59aaedae92d61b0b95c2fbc54252d3c30ad3abc23baa" + }, + { + "id": "ato-2026-27239-20261020-1", + "sourceHash": "6986db479222f8d91500e8656b3e091bf33c3a06a395b9e91df1a8e9517cbb64", + "textHash": "f4ae16235cad458b5b7782f0a18676570ad74840a0c4e0e97abad20374fddf73", + "vectorHash": "a3fae2c496b7d5cfed42c9a5bbe33b4e3f926f89b2eda1093220f22419733078" + }, + { + "id": "ato-2026-27272-20261020-1", + "sourceHash": "77a712b81f1419c43c76642303f2d2b5dadbd8d4520c7892f58e7dccfca42d9c", + "textHash": "28186026363e203580e6dc4fbc248abfb50b57a554e820415419577a327ceb1e", + "vectorHash": "5caf1849ad93d46ace985423ea8abd4287d1aa677e192876bac58b0b09ad04d0" + }, + { + "id": "ato-2026-27275-20261019-1", + "sourceHash": "1214321c29191ff3ba526061842ef2a9dfdd7bdd888f74f19436cc93a69bffca", + "textHash": "a8ee3fcf764f0a8e5d8f314d1f3097c45066e0fd8fcb43a5a7038e0891dbae4a", + "vectorHash": "78ded14caea356c340f7b0c14ce01114b53b0374002fc31009cfb1f0d40eb20b" + }, + { + "id": "ato-2026-27358-20261020-1", + "sourceHash": "e7fbfea0d8df5e1529955ea20b2e63d1bad1bc6d71f5bc617c12e51cc5f17dc9", + "textHash": "eabfaa5a04fbde8b37b3e103212bd260d43615f8cdd1c13578be7bc08ea52a68", + "vectorHash": "610769dd8e4a22d90b86820961010bae1ce492053634ee8fb92f1dc186a16b74" + }, + { + "id": "ato-2026-27361-20261020-1", + "sourceHash": "a871af62f889fe5a29b82fa96227b4c8d9f348f5f58032e2ea8f960898092b2f", + "textHash": "35891ac62a47f9d44d5daa88dc55c5e7b7c4d3026c22a03393d4beba7960ce12", + "vectorHash": "30886024b54d3bcbc43bdd125c4c467869ba211a0c5fd9b5469aeb61d9c20f67" + }, + { + "id": "ato-2026-27364-20261020-1", + "sourceHash": "aaca23afbb749a9d675f67445c713620457f9c7932c315ba08a5960e99a497c7", + "textHash": "ec71f921c342ac3199106f2885548278d2ad4240228556c0e06f0fd8e4c2da99", + "vectorHash": "8d2afe7bcb860225ebba58479d047f64c5d3a435e1b061d2969acbd93ca38b5c" + }, + { + "id": "ato-2026-27371-20261020-1", + "sourceHash": "b07383386aee25bc79e8da8121904ab57599c2b65aa470844063546cc85966a6", + "textHash": "e6713781c476ef6f72ec1a61ab8d38b5dac5d10e3fbf57f4457769f978829cab", + "vectorHash": "854f53b5480a491aaf0fafb8c769385d9047c4fb7403ac266a07f6a548bc3285" + }, + { + "id": "ato-2026-27419-20261020-1", + "sourceHash": "8056c26425c5e881ba9f8c00ca47dc01d0530e01ce17ffea1c68f08d82c3b7eb", + "textHash": "a5dd5c22f64c8b6ce998e03065e224c017b07db7fba989d7ac1d2ae3064c672c", + "vectorHash": "4e3c66c01930a100d19d77b5fa52e68ac9e43e5c19c0bb29d2d548cb1c7aa5f7" + }, + { + "id": "ato-2026-27423-20261020-1", + "sourceHash": "9bf4fc38b02a2b8035184c0e8f736870588dad8c07dfb40831f29711a40e1cd6", + "textHash": "577955c0ad96156a7f654810ef2439a5ef13864ab3ccadc2b53c06ff0e8341fa", + "vectorHash": "53ee0ee4faa510a9b5fabe35bf3ae4d1944db9a1738278f2754fae90f54c2fe2" + }, + { + "id": "ato-2026-27426-20261020-1", + "sourceHash": "8f22a1d28efcc624b02a58531dbdbf32d1f23eef1c1fec0e54788d60e471834f", + "textHash": "fd456910e9cf4b199de688a823159a0146f00e5a8e2b2b0ef5639d186b6166e4", + "vectorHash": "8a54c6b31f6eaebd0e56c6cfa43cba9cc79cd0e4c8377f1ece34edd200410883" + }, + { + "id": "ato-2026-27429-20261020-1", + "sourceHash": "fefae06f731294cbe7f2f8e9c65b85a7564bdaa2e9e118aa7ea5cc6437d73ad6", + "textHash": "4e76eb7ec7c731ffeab27dc104d5e73aeec5ff06e1831549e853fde967b36f4b", + "vectorHash": "365fa5476c9128b8be7518816fc68a778357bed3154ede62d686adad65035de5" + }, + { + "id": "ato-2026-27464-20261020-1", + "sourceHash": "e834dd343be2764071448155cf53a048c23b1566fe9da376becdb4894744dc1f", + "textHash": "8ed6a26100c58b44e05e8cd649f681dd5a0e470478b6291ffe166e1b60143ad6", + "vectorHash": "5b104b39b33b03269be2601a6c10abd0be5876bb0cc105ac9b19ce8550d388bd" + }, + { + "id": "ato-2026-27483-20261020-1", + "sourceHash": "97a194bffc6e409df08449c91e7a6fa8c8c22f562fef893df6fbfcaf7f1a2b64", + "textHash": "b63f9416bd70ab37d706e588c3b3084d43a072637764c721ee18befe58d7262d", + "vectorHash": "0e719e4f70c737fee30f520fc2d1070c9af8b8cbd97bb4e9d845ce4e4d6ed2d1" + }, + { + "id": "ato-2026-27577-20261020-1", + "sourceHash": "a4ceefdbc77eae883daf7602eca826e3cf0aa017f52b64fadeecd0db7cd97268", + "textHash": "2aa1e7714120285ca5ff17c9d2e58d047c553fca9051cbb8a2936c869711cd69", + "vectorHash": "59c82ce73a2b46400be482ee6ef259133ed46e09c6c967a5ca71aecd0064a563" + }, + { + "id": "ato-2026-27580-20261019-1", + "sourceHash": "f6cc47e343e6b31e99d85c448799fb6ff99e00260bfc4db83989fad6cd81e75e", + "textHash": "a2dfe0abebdb832a714b35c5135de3b876a1ad0ab91625634a584f24b23b7c85", + "vectorHash": "41cd6a51deebd5887cc90aff33667de226ca4a674307ffb35414689a3ddf2d56" + }, + { + "id": "ato-2026-27656-20261020-1", + "sourceHash": "336510a887c700dc794b5fe0415c3532ee6da291d5a307c26607f739bc84dc2f", + "textHash": "dc8e633f7a5170b34f77c74caae309e9d91b8f0695f71c1e49ee0f165e95ea56", + "vectorHash": "14a279eebe253f9fa04fb43bef68d7bcf02a5d2a98f12216b27c4cf524d55a72" + }, + { + "id": "ato-2026-27757-20261020-1", + "sourceHash": "16fcf038d480ab125debc7a136accb11565c8bc407fa4bba73da2e4209f562dd", + "textHash": "62cc62bc23a8c4043c9d88945743ab946304fe6197b348ba93f6bcdbbf0878a9", + "vectorHash": "e702c87b3d13e3ed80f57f820d1f93152b352e846f3535482cbf1b2608289fd6" + }, + { + "id": "ato-2026-27760-20261019-1", + "sourceHash": "3b5a228da0a2f7cca01145370065ceb84c596295746d14862fd654b506f02d30", + "textHash": "1ef2432bb2c44feb55765998676aa0dfb6016e6e431be388c0ac5a9b98e92e36", + "vectorHash": "d74399800c926ce5d0c24530356776f15c335f4c0250e12dad7de5cce6781e27" + }, + { + "id": "ato-2026-27768-20261020-1", + "sourceHash": "4521479beb539b0f6d62c175b7b8a70e5b0f1657747480297f180cbb1f5d8090", + "textHash": "40c58cd5dd8431131b608542a78da43f0f0de6a08e7269aaae1c858a0953f016", + "vectorHash": "288b71be0f882d855618caebdb1e7d21e28724d9c0d28479e20d0607fde898bb" + }, + { + "id": "ato-2026-27777-20261019-1", + "sourceHash": "5d2b3fafcd545da63c767b9e235195d28427105bfb6903e9ed00e8e24aee8147", + "textHash": "d787c63ab164cd505b0ac46dd80052f9ebc741393d968d4e594cfcca8a86a01a", + "vectorHash": "369663332819f29b0f98229199187fa79aade84f3c9b8bc3baf488587b419e56" + }, + { + "id": "ato-2026-27777-20261019-2", + "sourceHash": "b7d7490f71ae08c597a60cc2fe6cfc267eb0be10e3af9891ed2b437b3c6663b0", + "textHash": "d787c63ab164cd505b0ac46dd80052f9ebc741393d968d4e594cfcca8a86a01a", + "vectorHash": "369663332819f29b0f98229199187fa79aade84f3c9b8bc3baf488587b419e56" + }, + { + "id": "ato-2026-27777-20261020-1", + "sourceHash": "9309ac68bcde16e4e0715716ca3a769d0ea54d31ff5b09f0812142a6efdbaca1", + "textHash": "d787c63ab164cd505b0ac46dd80052f9ebc741393d968d4e594cfcca8a86a01a", + "vectorHash": "369663332819f29b0f98229199187fa79aade84f3c9b8bc3baf488587b419e56" + }, + { + "id": "ato-2026-27784-20261019-1", + "sourceHash": "4bf3c8fb73dd2f6f27640017e8a11aa990ce8a3df380a76a2f5d4e91194e03e1", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261019-2", + "sourceHash": "3a78ae94146290a039ac428bad8f4e4b53168f9cbc66d4868092540776c02279", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261019-3", + "sourceHash": "aa8b4bcd6ac95bf3a6b2be483c878f1748bf52af2c9071422d0d9c2f6fcf2fb1", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261019-4", + "sourceHash": "1e46f6c6875092d8ec81a2b3aaabbb64766904a86ef1cdb646bdd6db540d34ea", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261019-5", + "sourceHash": "f7df53a7f0b6c4b41b2f31a4e39ae68cedc27a6a4890d76d7f0bbd5dbb7068e9", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261019-6", + "sourceHash": "bfd3d1ecc9980c09285b2a5120b61e5b58ab35e27a093f54d6c6745c5e68048a", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261019-7", + "sourceHash": "ddd071ea8e140412995acec5a26eb2bca2d8b552c3d060108d8f84051822d457", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261019-8", + "sourceHash": "db53640e896f0013afea38157a6cea89725e8101a4cd9b90374306a0cf23d756", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261020-1", + "sourceHash": "fcf4935db44d39088d49b8579b75a5a0734907fe750310450ccd833b04f040bd", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261020-2", + "sourceHash": "5151cdc0627d4acd0644c119d259e9842295c9c3426f77f0c3aa3ccfd50a9fb4", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261020-3", + "sourceHash": "9f2b35f7a7910d1c21fde079686c6f7e6ee7931ad92335defb142638e8f307ce", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261020-4", + "sourceHash": "79daf512bfbc7d16d649f192b75d71a44849848c77e4bf94d2c71f69cf379a0f", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261020-5", + "sourceHash": "72bc3c4c74da67f4d0fbacddcc92421ecbb4c7ec503b3fd0988e944fcbd0c9a1", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261020-6", + "sourceHash": "4ce39d7f34b689dda080f55f0f2cf8a26f85b530970aea0cf60f43d0a34440e9", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27784-20261020-7", + "sourceHash": "9b7ee8a98a59aab4234c7c24e614385a42d4ee846cea9b5a3f9b772f929f6401", + "textHash": "9e4287be1668447cde974e9a0437483e991b1683cc4d9ea69a0515e9b1394ca7", + "vectorHash": "228b49c28790d7a66cd5172f1aa300cb806bb01b9af313721a0af83c21ac3211" + }, + { + "id": "ato-2026-27785-20261019-1", + "sourceHash": "4026e89f8c28f4d301fe1c6bc1230e01d9ab2cb0a2f3a842cba9d369a6bea2b1", + "textHash": "33e77d388b40c2754048698cf980f562fd53b9b5f809f5eafa6c26ab6f0de1ca", + "vectorHash": "6996f0dcc8b6b06780aa631f1130412e396e5fe6ee70e2bd0315044529277a6f" + }, + { + "id": "ato-2026-27786-20261019-1", + "sourceHash": "a3983fa280c091b01e86344224dcc4e5900cb6ee1147721fad10d60fefc25ae1", + "textHash": "f51235b47e7f6f147d9ac92d19114d62f578654df8f44f8f740f0f933783a7af", + "vectorHash": "90e7f479528ad5dd182f52c7254a952f24a179604a0e579a74c454ba831618f7" + }, + { + "id": "ato-2026-27788-20261019-1", + "sourceHash": "b4ce170a8e9dfb888353559b7aca66ad79e90dfa456ea9227ca188ad4788d1b8", + "textHash": "7632a11e628a2975ed804bf29f03d59bd57891b7e34015b59f44e9c5f3b6f0db", + "vectorHash": "d22bde01a0539400d65b1cd7f2ff219564abf333ada10e862975024f82f8c897" + }, + { + "id": "ato-2026-27794-20261019-1", + "sourceHash": "e93bf6a004ae7f0f9a1801628b455c966018b53afa20bfc0232147dc44acc748", + "textHash": "8957409b38f8168f6a83b6d289bd2e18a4fdab33a61fcdadbb021a9cbe17b06b", + "vectorHash": "893a38c401d7cc75702a8711041b626c2f2cfae060993578d4e468b75542394b" + }, + { + "id": "ato-2026-27798-20261019-1", + "sourceHash": "ba8de5ac312e95942023d0f3876dba6a1706fac6da6635329390cce8e134187e", + "textHash": "66f21e697daa0310cbf6929facc4b18f24c94935b2149b0f9d75f79b3ea8e0c9", + "vectorHash": "8a1630dca6e29440925e0ba3e765a12f063d6c26e548ddfeae08e4e74b353fb7" + }, + { + "id": "ato-2026-27799-20261019-1", + "sourceHash": "ac70908fe3965d159b7b9ed825bc1dacd40d5183c1a5895fe441a85419bbcf49", + "textHash": "56b7a8b00fff0b009c68721f9aedd1c6ddac1f640908f11389ec1d81a8b46e7b", + "vectorHash": "951f19e74d316c46ba3652d6dc9cf0bf398345b781fc63a4e0cc48103b52b1fc" + }, + { + "id": "ato-2026-27800-20261019-1", + "sourceHash": "323b58d077275168c972b978910cea7235d1d9a863f384fbd199c073e4ee67c7", + "textHash": "4c0c3e29a809229e98efd028fe7d4cbc39416a6829130f7326dda23101b8f8ac", + "vectorHash": "3a1c6dfe12533cb1eb57444193c6b4e9cb101c296a5216ca2bf093a7d4b109a5" + }, + { + "id": "ato-2026-27801-20261019-1", + "sourceHash": "f04106ff24d8d3f89281495d060c01b1f990e168590d94168c5b93bfdb739c8a", + "textHash": "af5bc440d20cc5a066a59f4aff993343c094f1d1d4a947181a4ab18aa4d32618", + "vectorHash": "4e8fe80176e9d20d043cf5a072218595fe1bc96f2fc3c071460c8044a90eb472" + }, + { + "id": "ato-2026-27802-20261019-1", + "sourceHash": "0035c70d4af450e25f68fda3907a5e0c585deb1429298a7200f86f85cc8b853f", + "textHash": "caee503250ccc0a1a2e7d51076d6b17f7be677c9b6a227ae96f239788173786d", + "vectorHash": "fe625b5fb85fde8daac95dcde4a4cde80bf6cc2e507c7d723ac1701a6bc2858f" + }, + { + "id": "ato-2026-27803-20261019-1", + "sourceHash": "73fd4df7acab319a1e269ab62b02f9fd09133a6cf94da160bda9cbb471c98001", + "textHash": "3c5d2b683de24141af555ff9b9b2f1dcdff56d299e694865988a1ab6d9291a0e", + "vectorHash": "cf0c9a73cf519434b4aa3d528c2ae7e8741629a530ae6eb0179119e5bdb3c5a7" + }, + { + "id": "ato-2026-27804-20261019-1", + "sourceHash": "ce591f65d1c0f8bfe0e27c54ea126f4dea08c3c27c027e261b0d3a7997b8e400", + "textHash": "0482fd761f4cc02a206cf412c6b490cc2a832a3ffaffb0a6942278d32c276754", + "vectorHash": "c6bc10c1141609eb65afe104d58f0a193f87fd0fa7baee805aeb557b55970c95" + }, + { + "id": "ato-2026-27804-20261019-2", + "sourceHash": "f5cbd2264adad55af9ee9fe209f35b49eb0baba65f7b94bc495f109de964e931", + "textHash": "0482fd761f4cc02a206cf412c6b490cc2a832a3ffaffb0a6942278d32c276754", + "vectorHash": "c6bc10c1141609eb65afe104d58f0a193f87fd0fa7baee805aeb557b55970c95" + }, + { + "id": "ato-2026-27804-20261019-3", + "sourceHash": "4ec05f21cefb2f2ac291c0821d55dc0864d7cc2048fa63ed0a0d614bba2eb59e", + "textHash": "0482fd761f4cc02a206cf412c6b490cc2a832a3ffaffb0a6942278d32c276754", + "vectorHash": "c6bc10c1141609eb65afe104d58f0a193f87fd0fa7baee805aeb557b55970c95" + }, + { + "id": "ato-2026-27804-20261019-4", + "sourceHash": "87676f5e0c621bf513277826e2e1cece7273366d651b8d901c7529755e17133a", + "textHash": "0482fd761f4cc02a206cf412c6b490cc2a832a3ffaffb0a6942278d32c276754", + "vectorHash": "c6bc10c1141609eb65afe104d58f0a193f87fd0fa7baee805aeb557b55970c95" + }, + { + "id": "ato-2026-27804-20261019-5", + "sourceHash": "b2fead120e2351c56546211ba351c9a201cf91e90fbd75d2e66dc48a19005714", + "textHash": "0482fd761f4cc02a206cf412c6b490cc2a832a3ffaffb0a6942278d32c276754", + "vectorHash": "c6bc10c1141609eb65afe104d58f0a193f87fd0fa7baee805aeb557b55970c95" + }, + { + "id": "ato-2026-27805-20261019-1", + "sourceHash": "3c26506eaa8e72e808c5cf31bc93c52f639e606ed86d363d33568ed3cfe5e21f", + "textHash": "7b02ff5a70017c273a972ef79854a8eb806ef76eb56450caac4b2997559fa2fe", + "vectorHash": "644869ae21d1820f94d69c6bb4bf21cd62993620acf259f78abc1341a02d4d23" + }, + { + "id": "ato-2026-27818-20261020-1", + "sourceHash": "94b61fa4070785d173186a5151abe3affd932885f07a22b25870f22363732fe9", + "textHash": "97eba5e0e55d697190450854ccc5082f680fda6f10d9f09cf4f86725d6bd291e", + "vectorHash": "c8a52a2270bfb1ed1773bad8ed00935f56079c61ebc877bafed5e8f97f5b79bb" + }, + { + "id": "ato-2026-27819-20261020-1", + "sourceHash": "9b5dfc981f5041d8b62d0855aceeae4903db4d5f4e6517f9a21ab1b407b49a4b", + "textHash": "c95689277fa160297845fbd2bc631ccabe41ce4b5aae1d5fe9ce438cbcb2d33b", + "vectorHash": "7f961b998191874b503d9f705c2995548b21fb277d56db249cf29293d0460fb0" + }, + { + "id": "ato-2026-27822-20261020-1", + "sourceHash": "474dbdeeee27658dfe7c5ea5e3495c7ed4d636ccf8b2deec27aa98c2f6edab72", + "textHash": "e89635c470ac7a7cad5e72f00d6de027823f82e7af5736a891fa618b45f4be7f", + "vectorHash": "bd9257457f44c0015938f5b91a7345600684c175e9e943d35190df6f66777f6b" + }, + { + "id": "ato-2026-27822-20261020-2", + "sourceHash": "0c9e121eff0d8f4b81be1b91ea0f3c1c1f8787b59a2c76ac93dac7714b608fca", + "textHash": "e89635c470ac7a7cad5e72f00d6de027823f82e7af5736a891fa618b45f4be7f", + "vectorHash": "bd9257457f44c0015938f5b91a7345600684c175e9e943d35190df6f66777f6b" + }, + { + "id": "ato-2026-27824-20261020-1", + "sourceHash": "101d44583728d998d7b0dacbfab43e97e169d083a816eb2462bc20c861948c94", + "textHash": "085fe5e173e438f2fcd821c27220385e0e1f9a760e4baafaf5327cac1b3ec3be", + "vectorHash": "c97f8cc10b80b262ae796233b50a60a0cfae4a751c6a8a67ca420315e5cc144a" + }, + { + "id": "ato-2026-27824-20261020-2", + "sourceHash": "0f7ad8a426e6dcc05eb3221352a4a3adaf8678876232b63137af9781b8fe5c49", + "textHash": "085fe5e173e438f2fcd821c27220385e0e1f9a760e4baafaf5327cac1b3ec3be", + "vectorHash": "c97f8cc10b80b262ae796233b50a60a0cfae4a751c6a8a67ca420315e5cc144a" + }, + { + "id": "ato-2026-27825-20261020-1", + "sourceHash": "873e9f3e42aeabe229a0bc2be6eb2bee99ea886488175c442109135206a13dcf", + "textHash": "b6a4e43f8d6bc3620ad8d95e522209370e43ec0ae1a4af14821e0289d78a540e", + "vectorHash": "e9af1dfa03926ff6862dcfd33fe5ecf8b248f14adc8895d496ee64b436d19de8" + }, + { + "id": "ato-2026-27827-20261020-1", + "sourceHash": "1150c6f846e8b81a0a056fb393f515ee8f3a7bd3875755b530d2c27e7157ab9a", + "textHash": "be6596e1c6819cd728a65d14892e2e3c8df4f70ac7b72371821ffad48b16b91b", + "vectorHash": "11f3d83efef371f5446baa289b7e4762762fab6ebd7624a7df5d664fcf50a3f9" + }, + { + "id": "ato-2026-27828-20261020-1", + "sourceHash": "3c853d14c5851853014b15983158a765b9958dd478b933d14d89293abd332302", + "textHash": "aeb0d7e65a8a49414c301f4f529deb567a73c65e8594863c74ac208a039f048e", + "vectorHash": "ee22c29670d3cb2e585052b92437294f062b9a775c82b7303438140f80c26847" + }, + { + "id": "ato-2026-27829-20261020-1", + "sourceHash": "64ca1fde42f4f5b2353c7b7e4a58c1ea5be351669cd31e03321b934509416ca1", + "textHash": "1d062f29a979a93ce05fb22ce67305fd1e5e843fce7e58acd396e0b1ede54cef", + "vectorHash": "c5e047f546660ad2f543d3a4b59f237b7172a27039e593c53f3de4b3e9f57b22" + }, + { + "id": "ato-2026-27830-20261020-1", + "sourceHash": "bea2e6450c078a63ce649cc2522e2ebec23512c163d57a1a464f58bd1f26d477", + "textHash": "d61f54686f07a23551fed902c6b5033342e97cc97ead4591f43502371068cfef", + "vectorHash": "ef082693807d9476e156a17adb4254f3e8197eb8aa0c8639fbfd5c32dbfe792e" + }, + { + "id": "ato-2026-27831-20261020-1", + "sourceHash": "6a1535b562807fb9ea1f5b4dbc96211b6a6bf084e9b2f627cb744df478a37a9d", + "textHash": "855b637ea6e572a8b5eeb31d40e65de4166295a1579fbc61144854dd54b854da", + "vectorHash": "bb6576bb545887fb392b9bb717d4d23ca240f080e44231ee9e742ed155c0a093" + }, + { + "id": "ato-2026-27834-20261020-1", + "sourceHash": "c9d51e9c57fef9a4c761ed27258764441533d79e97d5976b1bb74d26cb94b934", + "textHash": "acfcec1d13141723814e687a49fb2f30eb36cf83f3850023d6eac32c47c344b0", + "vectorHash": "3d86990f3a850bc71a804fce44a055b18bc519b44726680214db623bba1ff674" + }, + { + "id": "ato-2026-27834-20261020-2", + "sourceHash": "e0ce3f0b7dd25b725b16400dbbe6a72883f56f12ef41f0afac3c248d29f03fa9", + "textHash": "acfcec1d13141723814e687a49fb2f30eb36cf83f3850023d6eac32c47c344b0", + "vectorHash": "3d86990f3a850bc71a804fce44a055b18bc519b44726680214db623bba1ff674" + }, + { + "id": "ato-2026-27836-20261020-1", + "sourceHash": "504cd30e99c39d25197dc8a7df539e921d64ca8aebff9897b8feb1d524573a92", + "textHash": "bcce6506f3f8a79f9cdee07b52a5bee2e61f6851dcd4650ee5657b04090804ac", + "vectorHash": "a9adb2dc11c128777c33e08717d18bc0294b7d4a07d3451984ab98b47297e7b9" + }, + { + "id": "ato-2026-27837-20261020-1", + "sourceHash": "c45c6a48b18711057e2405fe63f14fafd64d0be5de099ae8ec057f0f4adec73d", + "textHash": "398350dce47a313a9ce3ab20c5cdebbb7ace1a47f6c9280c5056f4333188dd84", + "vectorHash": "8f4a903103b0fb32a695fcefef31e877587ad24848c44bc89e6a3553c357fa33" + }, + { + "id": "ato-2026-27840-20261019-1", + "sourceHash": "e604b2a839a88be7b1d189e2c8fcc7b1347d5bb42ed2d17a008cf74f26df97d6", + "textHash": "527f67aff68d813355719ab02554d98d9fae124071934a850e6d5f4baea854a5", + "vectorHash": "1c352666b5fcb250bcf0d48c6e18044ad37f0cd62052fdbfeb0f5441595c0369" + }, + { + "id": "ato-2026-27841-20261019-1", + "sourceHash": "4090771514e95c20aeac37f71dc2b52c790d8d1eb91acadd9b1386b160263f51", + "textHash": "e65274deed374859dd77b5299821a4511ec1301448b0ebe15eadb6c0a5d72603", + "vectorHash": "0833de27cbba0f8a9b30259f37b645f623d98ef4513a865da4d8adf83a897169" + }, + { + "id": "ato-2026-27846-20261020-1", + "sourceHash": "52251994d4a335306ea789124b6adb8977d18871501399c4f9f4f7c9e7221680", + "textHash": "1a63f3bf9eae4c35abc1d54b229fa161744e1b7c3118ee6c53dfa70eac2ec103", + "vectorHash": "2639f9311bf8f7c07b79ceafb721be97b0909618052a2449e5201bdf2ff5a810" + }, + { + "id": "ato-2026-27894-20261019-1", + "sourceHash": "5044a8ab837cd632cc8e22171ade1b718d21684eb09b5c2b5e7c98d21e8ddf05", + "textHash": "00e7562a874d3b5046d19176cfcd4fc7a1190436ba48a8f8bd71c7536bb3a769", + "vectorHash": "7c7a0010a1e75bd4af0175446a0ad35194798c6de572665702645c66da4ab706" + }, + { + "id": "ato-2026-27895-20261019-1", + "sourceHash": "948e03b6a6e2d21d4c7b230e5293bcc8fcab627ddd1c769beb7b7b5e134db8a9", + "textHash": "d1e10dbc317d4772e72b29ee5f86dc7281eff8b9b53027339fbbb7e1f4f21a55", + "vectorHash": "c4401e254ade2e71e39d00f8fa2863b8f50a5d5fce41d988853026d133a4fe96" + }, + { + "id": "ato-2026-27898-20261020-1", + "sourceHash": "c3b465b915aa7938190d2aaf92d05f11b9d42c415921571c4630ab5e48bc8c84", + "textHash": "f303c3aa10bcaab7822c0e8ba8de37d1e757cd19ff71be1975c83c1661a616ee", + "vectorHash": "4b176272d7cbc448903bafc97abe19cc4a241e3f46b5541514fd22edc0c18c99" + }, + { + "id": "ato-2026-27901-20261019-1", + "sourceHash": "69f5dfeb9046fd04e4a602b46707ff53319f619464c8d1c5d8cc4bdc6547e88f", + "textHash": "a0d52395521e689a5e5674eb00920904437b40def09772607101e7cbc6bb3cb1", + "vectorHash": "84ad10d2406eef4d809eaf20474ce1b8f459c5cd40606863690eb2cc1f727246" + }, + { + "id": "ato-2026-27906-20261019-1", + "sourceHash": "80be35c24708ef095a07487c175a0dc2d61e8a0111bc4c1d91eb15ac1fbe87fe", + "textHash": "d8709b980e285ffa34cd626623081dd3b7fdf5dec9d8199ca05811c196912431", + "vectorHash": "1b1d594f3e64bad76a99913a44dcf41a87027743e49ce2d0da3adddbf1fa2e74" + }, + { + "id": "ato-2026-27909-20261020-1", + "sourceHash": "d85c7a881d7be95196ff8a6b033069cfd2b305e38af574699aa99f2b7c0796e3", + "textHash": "878f47885b52ef89cede30dbd360616679b381b9b3f863fd36410c236b5662e4", + "vectorHash": "c2ef0b45a34ef8465ce936d1b86d6c951867adf857a5b6cf6a83be87562be0e0" + }, + { + "id": "ato-2026-27912-20261020-1", + "sourceHash": "49d31bf32255b5200d560137f165a500094b3d14d06eb6238c9805fb5b43417a", + "textHash": "fb58398471f5dba8443e2aee9b1568c846083ea713785d079bba8734884840fc", + "vectorHash": "68fc10d0a579bbf47a04ba06cf0330f15e435a677b17325c07c08c0caed06a69" + }, + { + "id": "ato-2026-27915-20261020-1", + "sourceHash": "7a0c62c9babecc126dc23ebf18c62fd2da09bccc0d4e4eb96d38f7565bfa26bf", + "textHash": "6773963ade8ac5fabb6e7213d1af79f5db5b50dbc502bed921ddcafe65ab9055", + "vectorHash": "0768f0b25baede1f97e197cd1509b80ec43dc11511623589a3095cf6ae8c5d09" + }, + { + "id": "ato-2026-27918-20261020-1", + "sourceHash": "3586442109b19d8b12a277f9815f217c923669760b1db2f05424799edb52cff1", + "textHash": "138103d215a01ecfd8abc0c90afd53a74d8068f652852ae7c00755d7b5a2a180", + "vectorHash": "8d6af342dd94b4d8f913284a471b19b318b65860b817c67ec87ed1dc0a4705b7" + }, + { + "id": "ato-2026-27921-20261020-1", + "sourceHash": "b198a41c3e9c81116c02e97399a56e3b055623a81b8c01c41cc9cba13ae59583", + "textHash": "73709d91b3f1ac15778f6b20877929d86a108edd63fdfb9a0f44e50cbd2ef8d2", + "vectorHash": "c06016ab3452576585f99650e0b9eb8c99d2a4f3a4449216caaf515573d10104" + }, + { + "id": "ato-2026-27922-20261020-1", + "sourceHash": "8278c6eb55d0a61e71df23fe4a012eebc23f1922f79fd0baa4e65bd5c19e394a", + "textHash": "98820b01e90fb8c8f2071ba07270be7b4a3a46e1406507ae9f5845b0db5c1230", + "vectorHash": "d328cfc957504ed0c85c88fdc18b9c4800e03623052e7c56851ac4a122878b71" + }, + { + "id": "ato-2026-27923-20261020-1", + "sourceHash": "a418a4ea8902ff7c7c66ca3d87e5891d2a9ff2cd56c6d4feda325953aace56d6", + "textHash": "fd9ed90650eb3c9e62b4411cc1b831ea857d7d84f50fe5e031c03a61fc50eedb", + "vectorHash": "3c649b70d5b48f53d0192decac9c260961651a711e01613c3e0c051e680d3447" + }, + { + "id": "ato-2026-27925-20261019-1", + "sourceHash": "4679a666219a6718a596621bc4911d3eef909fa6be02ab2e56f4a810975829b2", + "textHash": "b52742cbe68ea0563dd58a2a7c5a3313ec1304a5a2afba87a173a6ac4a5045b5", + "vectorHash": "9eff5a54d7df069f84ac3235567549cf1ed5df171d9dc62e6e691d8fdbf4d689" + }, + { + "id": "ato-2026-27926-20261019-1", + "sourceHash": "376f81279a9a6a4552ce635e0db85854316bb0f2da770dceeda8c0e167ffb898", + "textHash": "06b3603f0a9286ce310dfa1c4146b680c8cc32184b3b0eac70f2aba5a7079bf4", + "vectorHash": "90f05eeef27bf1a40a2b789ea1c8fc6f83cfef5d86701c4af8b037a6891cca9d" + }, + { + "id": "ato-2026-27927-20261019-1", + "sourceHash": "79f2ba0f617e244fd27ab87aecf243625309c671542b9a76fcc64253fdd13d2d", + "textHash": "73012d0ceac7da9bfbe67b33783618a81199ea7841c8cfce8f7e9a251ff2c8c6", + "vectorHash": "7dfc7fc4acd575a01b844bb33c5fad47cda14087e08224b7a4ae5fcb49d9afc7" + }, + { + "id": "ato-2026-27928-20261019-1", + "sourceHash": "5799db90c0f02826dcd52fc6f1b5d4cf9c6e3806c9ed73c3f511de68c0d51ec3", + "textHash": "b1ef72ff9c0e7ea2a1e2d082dc9114549b70ad4bd608561fc31a3d30d1a0e72c", + "vectorHash": "2e07940ceb86914390155d3783f1b53aca8327e7e54a32d51420b901096db51e" + }, + { + "id": "ato-2026-27929-20261019-1", + "sourceHash": "3d9932f124de83749fe6b19a955519f934440554b130e9a3ab7bc9db0334401a", + "textHash": "ccef2965e66dc1e9667c4dce99a65be9e6c6fd53d1d7fa7fdae524a59d519d0b", + "vectorHash": "7aac10f9def9bfd21a9208608ddc7919c2c34bbc25843801e9afbf4fd336a0b7" + }, + { + "id": "ato-2026-27930-20261019-1", + "sourceHash": "eab4f64edb05e197caed3c16f773ede166a624edc21333232ddc68fa6324b55d", + "textHash": "3d39d2ee6f8f5c3a999ff56a4ddcd6f1e4827fbc5988b88ded46a0529ebebf4c", + "vectorHash": "c4c7a925070aaadaf11011a96aa84ec324a1cfb1a686c1ef1b32a0e0b8081e76" + }, + { + "id": "ato-2026-27931-20261019-1", + "sourceHash": "34c380b1d08d5fc7936d12cf1fd7f0bbb1e96372448ecb724002c805c192c57a", + "textHash": "c1de4b42cd844fb627bc630f19b2f63a387c9a7894800b81fb3cfe9450815c30", + "vectorHash": "bf246a084091a61356e0346a73cb44d74fc40cce1bb9c2036ea52d06fd7697ad" + }, + { + "id": "ato-2026-27933-20261020-1", + "sourceHash": "d896179c11305f275961ff8cac02d6652047c614532ddeaf5da7e2f36b20d26d", + "textHash": "fa1fac8a9d5e8a506330d9337bffbb16e51a4d3da8eee1f2a30d8ce1d8ce737e", + "vectorHash": "d419e2312e9876e5564e942e82ef52e6bca26e6947cd5e2d34e1dbe83f65b62d" + }, + { + "id": "ato-2026-27936-20261020-1", + "sourceHash": "b19549dc00b53f195f86e0d1b57dc977d368685dc7021122f5081b3c4ecef996", + "textHash": "e13a85f63f66b89311c233f5e1e63296800bc2d06055d9c377daeaf84d28cb24", + "vectorHash": "65578b553ba238e871aa1de023f3ddcdf2b007021d354339cc1d5afb075eaa2f" + }, + { + "id": "ato-2026-27937-20261020-1", + "sourceHash": "0ec11ee9e520ec96f26de74417eaf0c24fc16f26a47aefaf47dbb712b17e67bb", + "textHash": "00d53dceb07bb9b9b29d6a83bb07f0f68a19300cee7cd539cfc677a0667a5f9a", + "vectorHash": "29699ac0fe22314e22c920a72b447bebe2fb876953f67cd3382abda8a619d0f1" + }, + { + "id": "ato-2026-27940-20261020-1", + "sourceHash": "7e2ba3f16b12fa65ff9d2d802139c710e783393b6ee04b5164c5a6903694c51c", + "textHash": "c348b4a118031b2f3989c49cd3b3b2707e02f5a5f9e5bec9010f77b7abc3b88f", + "vectorHash": "1c063827b741fda1bad5d420eb119d8c50686fe411876b116fb03ac790d0346c" + }, + { + "id": "ato-2026-27941-20261020-1", + "sourceHash": "b658c3267b77f9652ee4da3216996e242bfb68fa6f00fcbaa5ac3fc8cbeaa235", + "textHash": "f1eb50067b46f945236ba773f4feb1d70c7be38a9ad677b9b5e8c2acc21d2022", + "vectorHash": "40c4bb514c983497f830bfda923a74b74557d233796d5ce03caa1e003380bcc5" + }, + { + "id": "ato-2026-27942-20261020-1", + "sourceHash": "0d529a8d34bc38da885ab6616573cbaff7db0513aa2d21dd9dc47111612bc320", + "textHash": "cc7b19d7191c0fc269363a23d0166cc6061c2463302d1132e36d082fd07f73ce", + "vectorHash": "16bcfa66eea8fac17247f295d61ce2c98918c241c991f2160ebf3649158e990e" + }, + { + "id": "ato-2026-27943-20261020-1", + "sourceHash": "f039f23d102fdb87b6b000ccc95aa7823d49ef217cfa99cb699e46b7ae1e6f86", + "textHash": "0b6029fdf8c4f815aea5e1d070b79431f69884064a9cc27aab5e85aac554636c", + "vectorHash": "36ee5ab6aeafae07f7afcf3ffd209bd0fc17a84e473c2bff4c80b903173c345e" + }, + { + "id": "ato-2026-27944-20261020-1", + "sourceHash": "24c16f74443abc026dec733a7d33bde0d15d5f321518b0574b4b4821e36243b6", + "textHash": "c7484c3e8ce050dc0dd5320d605015477aae0ae506e20f0b81b954e44ecfa196", + "vectorHash": "f5ab348f354cfd980457156da1bd6a38d86d69b0ecdf1ab32cf233143dd7fc71" + }, + { + "id": "ato-2026-27945-20261020-1", + "sourceHash": "4a62aab32d37f95de11a8ebcb9e7911fcff99524ad10607ffa1067f33f43dfd6", + "textHash": "db855db10242038c0330ab987b4ee809f2295875436e1ecbe9983f2122f0f626", + "vectorHash": "38f980d7d0d8b9c97daa9e85609a0899258a4b5f541b1dff3cba017a4dbae2b8" + }, + { + "id": "ato-2026-27955-20261019-1", + "sourceHash": "807ff7eb5b3e1b71b1d8798b7c96ac8cf26eff986901258afc92a70b1d9ffdb6", + "textHash": "8a5131f728727e45985fb00b79e10c7df46a43990bbdb09650e26163659ebedb", + "vectorHash": "6f86aa5e7f3e978e9dd605f64e8528b3288eb04bdc55040a25dd66ad37245687" + }, + { + "id": "ato-2026-27958-20261020-1", + "sourceHash": "b3ebfc563516dedbacd43a2025773bd857cd38613349009dd815587a1c916d49", + "textHash": "63e42c5e011c47e100f48702b0aef4045e68c4dc1c1a37306b900e1211231c2e", + "vectorHash": "0e233e15604bdfb413a8935d460a69daa3fe73860e21bea1f05aba528fd14cb1" + }, + { + "id": "ato-2026-28051-20261020-1", + "sourceHash": "ac22b4d61c326a27e1a3a3ea7b185d93fa8f6d912c94e86ffcfae345669aafc4", + "textHash": "0949c61410e6b9f0766406386725fad191846c504b3e9466d2cb96b48b2e30eb", + "vectorHash": "1bbf29fdf1ec16847d12af76da6e333dd38d31beedefe577ba3f3ee38c677437" + }, + { + "id": "ato-2026-28054-20261020-1", + "sourceHash": "2b3fcb9379b8d7d9c4031d1dfdb20f04ca948147584ccf157a835ef6faf659dd", + "textHash": "5ea349424a44e3773e0ebbec64f72aa305ec3df23b11053f6b259bfeeef38a44", + "vectorHash": "03bc4a70d9774e900481c887b3a6baa40e073a19109a283706a0228131bf028d" + }, + { + "id": "ato-2026-28057-20261019-1", + "sourceHash": "94c41c87807bf0c8d6a00af3a4a7906bb0c6984b18f7b117a680e4359c4d3abe", + "textHash": "1f6f9d64dd662e7a05df45fc278b2054248c944a9f73f8e1bdc667bee8bd3b93", + "vectorHash": "0664ebd9fc79f0e7431c3e093db84deaa70ee465ce77cddd875b51e8b1528b08" + }, + { + "id": "ato-2026-28071-20261020-1", + "sourceHash": "0233627eb57575ef442e668541ff6c7d15498b6e8318c251c551bd13c54c7d89", + "textHash": "b084d5bea9aa4bba42489304ef85a7e5725cdb7f618d2ccba285a9d12b469371", + "vectorHash": "0b52218e2a60b4fcaa2e7bfbe2bf7a00ce70d90d5323c99b98ef62ee7e19510f" + }, + { + "id": "ato-2026-28089-20261020-1", + "sourceHash": "ef02e39e5b23d8f1db6706d6da9b6a8ee8a09d041ef54a277cbb81a4e5bc22d5", + "textHash": "d80e9a7831a9584084a7360b939d7ad43dcb9b6d72966848172f53a704dc202c", + "vectorHash": "f1339e886c3d48a99cdeeefc9dafaf440fc88c930b215cb6121eb0442017ffc7" + }, + { + "id": "ato-2026-28096-20261020-1", + "sourceHash": "6b2d557d62ddb3c9bbff85de34533bcd70061b5b93990e92b7437817efb67e17", + "textHash": "30517534aaee6d098ab86b34912d181ead2e87f84d2412399212d4b03f3eb1c6", + "vectorHash": "7b2af74b6ab58c7223cca1994c51cfaede133b5c1598b045ab707b1b57dba96f" + }, + { + "id": "ato-2026-28106-20261020-1", + "sourceHash": "0e2cc98629159a357e15958496c2c48714293525e9476be636be9d4a3e02687b", + "textHash": "e7fe39d35db30f3bc032eeea1d4e0fca23deb89435359a46555f26c4540215cd", + "vectorHash": "97fefba5100c29505d2de597ba71115584524ee0a67418a42084ff566ac85dbd" + }, + { + "id": "ato-2026-28111-20261020-1", + "sourceHash": "daf7bd30ec1cfb0b8def0c2f7fa116855f67713e707ba3072a6030d78dfcd2c5", + "textHash": "23df3686b4ee7503585202cefcdcfa5cb31de57933942a6e19710cba36ebd79f", + "vectorHash": "ecfd0b790e03d7e37b49f764c747126e8411445128645da1010e24a87f363d0c" + }, + { + "id": "ato-2026-28116-20261020-1", + "sourceHash": "3a87823a3cd224f7793efc1080eaa6cf4a57388dd8a205fcd129e18c65d91e01", + "textHash": "90bf9e032ba7ac70aea0b9757f2ea1316058115bf3ab35d3aa8630a84f037b48", + "vectorHash": "4d08165a83fa2897f486ce09a27abefa839b355dded0f45a3a2bc95fdcfbf1ad" + }, + { + "id": "ato-2026-28117-20261020-1", + "sourceHash": "cb7e5f97391f70f66b3da739ba294f04c41c8318e71ce17779a603757559b3de", + "textHash": "4061764739b0dfc16a22e5aa78a5cb26751c60a51d56945ccf6102e0b61528e1", + "vectorHash": "435d1df1ea22f51e2f55a63699be43736b7b85bdbaecd18916897efa73be8690" + }, + { + "id": "ato-2026-28120-20261020-1", + "sourceHash": "38b796ca8e9569f6f8f7f497515cda5f0af436986b8e4464a4b46a24277e9dd7", + "textHash": "562ce1059cc71385a8d30ed4a2c0e042164ccc396fc39c7a874c51fb80fd7b05", + "vectorHash": "6d03c24d6d55e196b11431b4cb8cee5e928fa5763efce947f48d1ccce344a091" + }, + { + "id": "ato-2026-28121-20261020-1", + "sourceHash": "43da6cbcc1b289b6e5bebf7c41a4206ca0253326aa1917d13a57b158373e925e", + "textHash": "d0b0abe7a7d7af29c7465a2545a9084e21e3414a4dfa7a5a760742c8f9c195f3", + "vectorHash": "4b5643ff9af7f91b4427e216021e1b1075e7cad78e635694ccec9c1e5e7f81f0" + }, + { + "id": "ato-2026-28164-20261020-1", + "sourceHash": "eef0b591c3de64939479343235ac5f352395760fee7c230834f256fb421774a8", + "textHash": "92691e2fea70314feb6204844109918ba9508190447b9a41d286ac1abe5293e4", + "vectorHash": "320fac0eb71db982098c5da815b3ef4c369f6fac6bb636f60b453e0eed3c4046" + }, + { + "id": "ato-2026-28173-20261020-1", + "sourceHash": "3077d1a10a89bdc24d58826e6b303cdb59ab81cb3eb313016bce8c02b470d615", + "textHash": "f0998af23d43aa7c9678bd862ad599869c86c244661a42ad213b93feec721f1d", + "vectorHash": "05ef68d1ec50614695e0ec3ed86e26113410c5d2ea6d9fb2f61c7373ece74914" + }, + { + "id": "ato-2026-28179-20261020-1", + "sourceHash": "fc0ac107eec71a2a3f4ce00ca6d748c23a0b79e221d8fc6c14e3bdde3ca9324f", + "textHash": "08c9edd3b9edd91b0d2598d07a5fefe9ad5722731e079298cc3007e82649484e", + "vectorHash": "394900a10079098d2b947ac7f603a92bb3382d394bb7737ba45c18cd6921d012" + }, + { + "id": "ato-2026-28182-20261019-1", + "sourceHash": "d3166c216af4efafbc6b5326a30bad93aace4e2826e0a9f0c30cc8e011e88057", + "textHash": "35bf131eea284c71982dcc9088ca9da6781213bc86289e1e35d8858bf0920706", + "vectorHash": "f3ea916214f0a8e28bffa7723a07db0fbe5a5e66ec8ae159b12aad5ee0568b1b" + }, + { + "id": "ato-2026-28183-20261020-1", + "sourceHash": "43a1629626d257f5959f64ad5c0cd2192b33d6a05ee00e6aa8e96bd6b629842c", + "textHash": "f1c240f1ccd720c766e66187c2e5abfb5485a773d63ee1e5ce80ebf463a2a637", + "vectorHash": "0edb3780111a6cfddfc8428aba9efa8cea7f24533c3e58b2e74b9f1ab11f5413" + }, + { + "id": "ato-2026-28189-20261020-1", + "sourceHash": "5e2251a297ef7f4c037d8194ac05839d092c35f521f64b475780ea6782892aa2", + "textHash": "d974043cfb4925786efd6292e8881248d21a7b7159ebfb313b206760bf562b69", + "vectorHash": "bb20b92bc3e5ee2f7d96280f473f145d0054296358376398efb4b0af49405001" + }, + { + "id": "ato-2026-28190-20261020-1", + "sourceHash": "7b6980f3fa1e0908fadf0b8f0c92b4e9a8161846d6ce1e5506c37afaa0c96f38", + "textHash": "58f3d87ccc6abb0f64e9ffca88502a1632671f1c12e2b71432e3c027e9f6fe6b", + "vectorHash": "344140e9de0c7323aaf5f59de127be1cbace286738c5b8690db15e6e7b346d6d" + }, + { + "id": "ato-2026-28257-20261020-1", + "sourceHash": "f2656009f5ff0956fdbd969f31619e0f04fc3448c05311069b014943e5f2a44d", + "textHash": "f0a7a7dcf49c447abf58b2a5416d9bf70c493c8c965891cb5d6af663cc0e0270", + "vectorHash": "5835f92c603cb2c2ab5474e0f66563ad07552227a58f656275efcb2bea06a92b" + }, + { + "id": "ato-2026-28294-20261019-1", + "sourceHash": "bd6edf36d9375af259dcae7301440328ca4c6c87ab0f7c2cdfc565dd22f93019", + "textHash": "7014909d14db6df3e8989b375c6c64429bb76c62152fe5645a9206c3d140a086", + "vectorHash": "2aec31876e2e4954f99f5f93109d8eae406cb6359c56c7c733317a07887fba3b" + }, + { + "id": "ato-2026-28297-20261020-1", + "sourceHash": "6d96a256de56cdf2e00ec9f970cc19027540b52fcaf096c72cc0dad95cebdc97", + "textHash": "2610445c03dc87ffa61322f0d65422de7862f282c37dbd120851dcca0686cfca", + "vectorHash": "229144478c155885d745bcc715f8cef506565cd15bbe55c73890a150097fc54f" + }, + { + "id": "ato-2026-28298-20261020-1", + "sourceHash": "237406dda6582d501531448960b440bce367d29e219c6e4233fd0ff6a6eba0a0", + "textHash": "a8c39544860fd3e4d8031c6245fed4af6b2e1c5f3f35ccf1aa71e6bb666563c1", + "vectorHash": "3de6a77b4ee36d5ed6893e4fd7dfb02d0d7bef44ea001d75b0a877445bf6fc5b" + }, + { + "id": "ato-2026-28363-20261020-1", + "sourceHash": "969ae8fe64977fb50d28ad7963d328523c386f43344fad746c4aef6ef555fdbd", + "textHash": "0724d1c3cd66f586a6aca14fe8e2a02f94ca143c367b79f5b9abb92a21f5a0d1", + "vectorHash": "ba35ffde782a25fdf97b6921d62be339efbf7cbcadbbb25dad84dc5dce6e2cd1" + }, + { + "id": "ato-2026-28451-20261020-1", + "sourceHash": "1b73fe56c36587768ddc6fe05b3d9358c0bbe4804bea1f37bc85e7eaece59a91", + "textHash": "53a5685615ebe9aa04d0bf6d25afe191936fddf81f481b754e3c735c214cab3e", + "vectorHash": "99d171461ce89767c3b4a6e200963cb0d3c737de353f8402be33d22d286b0103" + }, + { + "id": "ato-2026-28456-20261019-1", + "sourceHash": "1411cf12e297ac47ca1fed3df3cc05f8eec9daf37d6dd772c717d0eba0ec1ac5", + "textHash": "f2e637fba1da300ab0e4b87c5d9ce491b330199ce0af6e12059d18ecfa10680e", + "vectorHash": "e0385e206b30ef301a57f6491de374eee4a9c79586074c49970349c9a2daecc6" + }, + { + "id": "ato-2026-28465-20261018-1", + "sourceHash": "5765e7ec649354512f83b02e457743831a1efe6d7046393d831f0e406093de4f", + "textHash": "ef5c0a442f649dc7455c5acbbe84f4d6906a346cfb817bef5c30e15147138934", + "vectorHash": "7a39fae0227992998199e8518856153f9d144890b4c23a25ca55dad68ad3e13c" + }, + { + "id": "ato-2026-28469-20261020-1", + "sourceHash": "42c0305ae7991eeb6c520154bdf94d0898f6752dbe8e60847b1412297de11609", + "textHash": "8609f858246c30c75b5bdc49f35079f7d2a359d6819f74e97d30701e5ac2a6c0", + "vectorHash": "6053579a7b0a1e9a6b46f1f1d9649ca37c912144dae74449529b55d840cabea7" + }, + { + "id": "ato-2026-28478-20261020-1", + "sourceHash": "450c94ed2f0059760b78612be195ef3dda147e5cc8307cd4b747ecd24b25e144", + "textHash": "c680752d80f454e0648ba3e62514af52e6f390fde943e85aa849eb8a0d667752", + "vectorHash": "692390fe1b03b40bc355b0c213cb93b96637115b7c3dffbbf3d65019fc7ce1c3" + }, + { + "id": "ato-2026-28624-20261019-1", + "sourceHash": "760510501b6bf86687f5ebd3f311f508c206fa2cdf3112cacbff275096bb1200", + "textHash": "1d962acfb3055a8500fe2365d80c1529d432a1344248736aa557015e806753f6", + "vectorHash": "68983a6437486bb0f503a580761a33d3d9476cb1f1108e0eeaf62aacc4780d37" + }, + { + "id": "ato-2026-28627-20261019-1", + "sourceHash": "0c8475db6368e7018780b17839c09c3f7755c545799201f36b2b33e936be5291", + "textHash": "b5ad8127a9696946b0ef241b09d5b23046ebcd44f6b5656c029fac041661f297", + "vectorHash": "9d3f5bea3a3a54c757ef7263deb4c4c2f11445591174611f2a7c8cd91243c826" + }, + { + "id": "ato-2026-28639-20261020-1", + "sourceHash": "11848445845170cf6284a54e94792a44270182facd784bec5c57346f448010c9", + "textHash": "f44a44e52063b12fcc6b13802470debbe66420c55303221393b9bba6ab2c2b4c", + "vectorHash": "a7f3ed592882e452cbfbd9bb5217e3e8808ae685d6d75630c082df1b3e23d5e9" + }, + { + "id": "ato-2026-28640-20261020-1", + "sourceHash": "b5dd4962dbac525c2fad23a24d3ef12b74dacc22713c126b42ce52c9ea92a342", + "textHash": "87d73c2da1ac496b7dfb0809e747635555bb973de1b667fb05344f9e128880bb", + "vectorHash": "8108989d1adf1109c11e2a5d57fd1b01416653af836214ff6ff606ee6fc7f5fc" + }, + { + "id": "ato-2026-28705-20261020-1", + "sourceHash": "afb9da26d4988c62774f8eeb06fc02dbd03dc5d8d1da8ba6e9adb8f1575d9647", + "textHash": "5ddd9ca95fcfc8149c1cc1f01baa41ae242db05dbfc757d308007cdfc76ebf63", + "vectorHash": "185ac88a44b106003f00e3a88e91a53d82ec15666fecd41dd5c98d267a8de53a" + }, + { + "id": "ato-2026-28706-20261020-1", + "sourceHash": "72db2092f37432832b554b63821c0b9afff370c03cdecf29e23837ea3ba49c5d", + "textHash": "a78365531932ed57b76162dd6d0d322082c6f4ba0acc8d12124fac702733b47b", + "vectorHash": "6d6a1d0dbdfa7fd8cfa44bfc748dbd9741e8dc2afe9f99ef1fbb682827579b55" + }, + { + "id": "ato-2026-28709-20261020-1", + "sourceHash": "724766f9a54549000fc69ed2079af910efc5c5f18737a9a3bb620205e629d761", + "textHash": "62a41ecdf350f77e7cfec933e309113cc143ddc78b7e54e6c33d6fca9fe8017b", + "vectorHash": "892d5338fb072f7e3d0726664faa8bcbd4b6e57ac5720f73887e04f8eae479e4" + }, + { + "id": "ato-2026-28718-20261020-1", + "sourceHash": "7735aebb077d5475e80142a6cb70cf01ccaad40251521a2415d994a83907e32b", + "textHash": "093f97f0ce3ca4ed31cef7d5f13628b72785db5a8c3e63e3fb4876892ae4d70d", + "vectorHash": "01c07dad1979d65a4fab667461a45999421f0a2a75bbf9126a8efac9154d69bd" + }, + { + "id": "ato-2026-28755-20261020-1", + "sourceHash": "513b18f7e251eb535a4728e462b177b0e150ad959ef662a5ae4e0394907fb237", + "textHash": "4d9a338bc8d242dc7fbac5b9fc155e1be7647d3eff5ff4b03b349aa5810e2a73", + "vectorHash": "79a406cdd19ed1a71e812840e22d32109b1a0c1d4ede9975a8d36944f171aeec" + }, + { + "id": "ato-2026-28756-20261020-1", + "sourceHash": "52ceaf43c325ec3324ce4062e667d7d0378d1f543ffcd781260f8477fcd5519d", + "textHash": "b92fdb32d57d95d0c84d70fd71dbda9542c47251eeeab5dc02d6a034346e66b4", + "vectorHash": "ec1e79fcef6dfb2693e141cb1645c182618629e8493e90fea389cc7457b02efa" + }, + { + "id": "ato-2026-28757-20261020-1", + "sourceHash": "47613a833849d9c0dd76149570a544ecd735005995d072209f0531923f62fc99", + "textHash": "e7a8c228a898fc7f196136bbe57affbe3467ba0918c05e41730628d05d391e6a", + "vectorHash": "f751c102b0c5713d46e6c01bd54e7bc6fc855285e7291da14cb82670b90d4746" + }, + { + "id": "ato-2026-28762-20261020-1", + "sourceHash": "349038f180b89215c114f4323e0c0144bd91a178eea2524aaf75f6448ccb6915", + "textHash": "3338fc2c69e5395c05347d4ffa7a53925654d9c378f081c91a9c7910010214e0", + "vectorHash": "78b2b0b1ad3153f3268a8c3728e4f9dfdf87cd82bcdc8e7c0b32b3706439089c" + }, + { + "id": "ato-2026-28763-20261020-1", + "sourceHash": "91b25c1c534b73ebba2eb4ebec1cc1b01a7590b7643950eee0219db0ea10ec3b", + "textHash": "20e0cb58ac29e1cd0e27ab67f4c466268247b5a5457a12051cb790b3150ff786", + "vectorHash": "8d64f54ec8e7782faade818166ea303030101a786d25e9a68c70d3777ecc2671" + }, + { + "id": "ato-2026-28764-20261020-1", + "sourceHash": "7496561e8d7db136ebaf09ac573c1daeba5b23a2733bd825baa1e711d0b58086", + "textHash": "75e01a7ea8d7498d33a0cd84b5b864c246d4305e43f6cc6245938372473c4cd2", + "vectorHash": "840786ca1e8d147c15d5e1cd04ae084b3bcc19f3861c3b88d0f3101ee21fae58" + }, + { + "id": "ato-2026-28765-20261019-1", + "sourceHash": "9926d0bcdaba50738316d382af6331562bed201f5f5b3791b4b40aa65ed6b349", + "textHash": "61c96fa6df98acb683a604e0b5bec9d6f60d5545613e1636bce2f594393ab8b6", + "vectorHash": "10d1d2a18d5001433191fa6c1d4d3fcda8ff35cb87bdae9a85bf9b99ede0572c" + }, + { + "id": "ato-2026-28772-20261020-1", + "sourceHash": "9d323a5d0e7649c93f48703204686b3c461b8e111e3ef891c32bdf5db3dd04a3", + "textHash": "60d9db44fc975d4e723039ffd9ec031038bb700c56e3fc066793289f1c42563b", + "vectorHash": "c60e4fe3519b4adf037b192dff7b8d04975546db140383e6b576b192189b1cbd" + }, + { + "id": "ato-2026-28846-20261019-1", + "sourceHash": "b107e9b165f322c773692c93d57cb6a68083108bd3d83cd1de449935d0602a98", + "textHash": "fcd4d231325c4d4c1bda8ad3fe036d061db1af0815d38aabd77be46fbc231a6c", + "vectorHash": "fa2f97c9a8ccecaef49fcf1d957bfee3aaa69b45d721383503e34ac86db5631a" + }, + { + "id": "ato-2026-28853-20261019-1", + "sourceHash": "de6b126629137c22e46b30bf2569372b7ce355106d841920f55ea4eabf950161", + "textHash": "859d2465b737175bf3db442297138c515b9d111afde2404ee95def36ab32d0d8", + "vectorHash": "b118d072bc2ef27d9c1d7cd4d09ee716c02204b429d6862f4a2271623ec0e13a" + }, + { + "id": "ato-2026-28854-20261019-1", + "sourceHash": "e7c7586685e4483b2be65c105e1be0c6e2a2dec7b22cfb88918b4fe9e4edf21c", + "textHash": "60a03856161c931dae10174ac2134ef123bc5a265708e6d8d883f4f70f5efe41", + "vectorHash": "52afed96b9fc9c3d9bc8c84712a9deca229a6e78c145ce71fb97e722472c9e7c" + }, + { + "id": "ato-2026-28855-20261019-1", + "sourceHash": "fa6c31088fe12c6ba9ce4b9dd937fc6218e3e9b288f24ac5efe6ac27fc9c81c3", + "textHash": "9517b5142f3a91531ff9574fa8c9c2c43ad22836558aa6db2ee5332b996b18db", + "vectorHash": "96d63366dd1206f0ac1688f4a4ceeb313bf9e36192c7ddb847e62907d7817b50" + }, + { + "id": "ato-2026-28856-20261019-1", + "sourceHash": "6dd3466cd99de66705e327e20d363d2db58e8af25c1d43b4a2d7241950d3911a", + "textHash": "a70de12f5d3dbd295b1a4990b1a69e74fb8232c5507bdb6b6951c7f658723da8", + "vectorHash": "f7a10a6a857ac0d35e5225a4071b5dfef78bdb314570003976be4eda75d0281e" + }, + { + "id": "ato-2026-28861-20261019-1", + "sourceHash": "8aed704301043e5a56f0ec270e2ad1e41012f3d2b7380c7439d4388a76273850", + "textHash": "ae0949bcad55c64d09c653683f1f4da4b3796107d49079bed4e3c7baa69992a7", + "vectorHash": "44df7c9b1a1cc2a8ddcad9e19208ef6de0d12a767f3f37ddbc375c03ea1bc429" + }, + { + "id": "ato-2026-28863-20261019-1", + "sourceHash": "a4c4e4d58f28cce78f204b04fd563ced45ae97ab6bc6758112969b311028d6c3", + "textHash": "770cc1520f10ec7ef648cbc076e78f42d5bae16fef4a8f857816468bb35194c0", + "vectorHash": "390b293b8767a82ee135014473dd97075c00e0c3050cb9efcbd9ce473965f3d0" + }, + { + "id": "ato-2026-28864-20261019-1", + "sourceHash": "6cdd3baf3ad3c2317585fdb3fbc5440d026d452f3e5e775e7a513f3b92119e1b", + "textHash": "1029120b79ea31be48487efc3c7d7fa87b6ab6e7fe3968eba1baacd4bc4e93f9", + "vectorHash": "7bb31c0753abdb34f13699371ebd2e098898d38dc4b03237d90f88b70035c3b1" + }, + { + "id": "ato-2026-28866-20261019-1", + "sourceHash": "720ab8651a292168fffdf659fcc746b94abf7644ed8a170a8b8b16eee7cf8f49", + "textHash": "6c18d816e665823739b26f1f5ed4e6eecf10776aa09b6c83c0e05bbd37c76c9c", + "vectorHash": "dbba78356549aff04d556a0df413f5c1e048d06be227f1fadbe5d927c70a9f6d" + }, + { + "id": "ato-2026-28869-20261020-1", + "sourceHash": "b1fbe2fac44483be29e7134b54a613a92b09051504eeb80bccbcb224b4e0f139", + "textHash": "9436f631055366b691e040516cb29d36193b528a170918e021a9d548eed6d244", + "vectorHash": "fd37346cefa728df86c320b1803d716bd58c0c93b24378902ed9f21e667be3be" + }, + { + "id": "ato-2026-28875-20261020-1", + "sourceHash": "f3c37a71f664693a0af83f981341592b083e10c0c2e7645d00f8c423afde6cd7", + "textHash": "33b1fa29ef7bb97370c86f8cf7ab54c44b7016ad39658ea9580852c82af9e248", + "vectorHash": "319160a4ea84245da159727d0da541f497e6d18784af5b2595702b750bb140e4" + }, + { + "id": "ato-2026-28877-20261020-1", + "sourceHash": "7d1095f0dd4cf4c7729924de707b611e0f7e3290428591384ead910c4eb4f5ea", + "textHash": "f2ad163da99d96e3807acd8bbe7a2d0bb6678a37c5bdcfb24a29ad09507fc6d4", + "vectorHash": "417101ec518def54e5e10d22248d01769cd37bcb5f68c90012df027972bab84d" + }, + { + "id": "ato-2026-28882-20261020-1", + "sourceHash": "19a3f34dc67c99ae20da3d0d94c15a5ade75772f131c3e2d3ec96b1f78d8c57c", + "textHash": "4bfcedd8d703df68044183f9f789f7287e354de1974c2eef04118c7cca136516", + "vectorHash": "2a6a1a91789c4e2cd49d869ba62c08a4d74387ddc82c97f245b7b3bb21da9c4d" + }, + { + "id": "ato-2026-28885-20261020-1", + "sourceHash": "0cf98f90928b6d1072b08a6795e97bab5c5d4e827d0b7c35db6753ea6d7d3546", + "textHash": "ed1e85279f778e24e3d1a275635e6147d3688c9811659f280ec360aa0791a0e0", + "vectorHash": "ba73ec1f83fb10ba8c7746ef988718426bcee2f328c75b057a9417b98a4ddafe" + }, + { + "id": "ato-2026-28921-20261019-1", + "sourceHash": "33e798f5f8408c27b078ffc6735e457eb146fa48663a83bda4b1b7a200fb5397", + "textHash": "9328e4e399c509dcf7dd407054f37d180fd02a1f2680c1290b7fa53547127dd6", + "vectorHash": "a45fef2c2f4c15f452af73830a97220307621212b2efb7bfd0af8cfe2354b286" + }, + { + "id": "ato-2026-28922-20261019-1", + "sourceHash": "6b4d96b148df83c29a4ad6809f64963ea58dcbfa229b7863a3d0c21bc3d2a147", + "textHash": "69f6f6f65e09e1d79d8cf889fdeaf3dd894dfc9480d47004dd9c1d5a9174c6f0", + "vectorHash": "a611caa95f4cb59ce017622607d7be2c91a4600c2b73d7cd9346f4e65884275b" + } + ] +} diff --git a/docs/semantic-search.md b/docs/semantic-search.md new file mode 100644 index 0000000..78d2295 --- /dev/null +++ b/docs/semantic-search.md @@ -0,0 +1,492 @@ +# 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 on success, failure, **SIGINT or + SIGTERM**. It waits for cancelled subprocesses to close, stops only this + project's downloader, and verifies the container state before continuing. +3. Starts the internal-only CPU embedding service and enables the app's optional + search configuration with `compose.search.yaml`. +4. Imports the **same checked-in 216-session embedding bundle** into a separate + search collection in **both** local sites, builds each native vector index, + and live-probes it. There are **zero document-embedding calls during ordinary + preparation**. A target is only marked ready after the reviewed bundle, stored + vectors/hashes, index options and actual full-corpus cosine query pass checks. + +The ~716 KiB bundle is **precomputed document embeddings, not precomputed search +results**. Arbitrary user queries still need the pinned ~274 MB local model; +each query is embedded at runtime and retrieved from the selected DocumentDB. +The first preparation downloads/caches that model once for both sites, not once +per session or site. It does not generate the 216 document vectors on an attendee +machine. Missing, corrupted or stale bundle files fail closed, never fall back +to generating them. + +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. + +### Interruptions and emergency downloader recovery + +Use Ctrl+C once to cancel preparation and **wait for the +`search-download-stopped` / `verified: true` receipt**. The helper handles SIGINT +and SIGTERM during the manifest fetch, readiness and model pull. Cleanup is +independent of the cancelled operation; a second SIGINT/SIGTERM does not interrupt +it. No later app-start or indexing step begins after cancellation. The helper +freezes the resolved Docker context/project before starting the downloader and +uses only those selectors during bounded cleanup. A failed stop or unverifiable +container state produces **`SEARCH_DOWNLOAD_CLEANUP_FAILED`**, a nonzero exit, +and the safe context/project names—not a success claim. Catalogs, favorites, +model caches and volumes are never deleted by cleanup. + +**SIGKILL, a killed terminal/container, a host crash or an unavailable Docker +daemon cannot be reliably cleaned up by process signal handlers.** If the receipt +is missing, or cleanup reports failure, inspect and stop the downloader manually. +Use the context/project reported by the helper, in the same workshop checkout: + +```sh +# Replace these two placeholders with the exact names from the receipt/error. +docker --context YOUR_CONTEXT compose --project-name YOUR_PROJECT -f compose.yaml -f compose.search.yaml stop --timeout 10 search-download +docker --context YOUR_CONTEXT compose --project-name YOUR_PROJECT -f compose.yaml -f compose.search.yaml ps --all search-download +``` + +The downloader must show **Exited**, or no container. If it is still running, +restore Docker access and repeat the scoped stop before retrying preparation. +Never substitute a different project, delete volumes, or run a system-wide prune. +If termination happened before the helper printed project/context names, use +`docker context show` and `docker compose -f compose.yaml -f compose.search.yaml +config --format json` locally to establish the original selection; the latter +contains private credentials and must **not** be pasted into chat or a public log. +Do not run concurrent preparation commands for the same Compose project. If your +terminal overrides `DOCKER_HOST` without selecting `DOCKER_CONTEXT`, preparation +refuses to guess a daemon: select the matching explicit Docker context first. +It must be the same daemon that already owns your workshop volumes. + +## 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: <published title> +Track: <published 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, plus the **bundle version and manifest digest**. 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: "<selected published 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. + +## Checked-in bundle and maintainer regeneration + +The [bundle manifest and provenance](../data/search/README.md) describe these +fixed artifacts: + +- `data/search/session-embeddings.f32`: **663,552 bytes**, 216 × 768 float32 + little-endian coordinates in ascending session-ID order. +- `data/search/session-embeddings.manifest.json`: **69,657 bytes**. Catalog + fingerprint, model/digest, text and normalization version, encoding, per-session + ID/source/text/vector hashes, data SHA-256 and actual generation provenance. +- `src/search-bundle-pin.js`: separately reviewed manifest/data SHA-256 and size + pins. A changed manifest cannot authorize its own changed coordinates. + +Combined embedding/manifest payload: **733,209 bytes**. These are freshly generated +vectors over the public snapshot, not model weights, canned query results or a +portable physical database index. DocumentDB still builds its index on each target. +The bundle was generated once with Nomic v1.5, Linux arm64 and the observed CPU +backend; its full provenance and model's Apache-2.0 attribution/license are included. +The shared adapter normalizes model output in float64 and the bundle encodes it as +float32. Import validates finite coordinates, unit norm tolerance and every hash. + +**Maintainers only, outside the lab:** after starting the pinned search service and +app in your own local Compose project, deliberately regenerate with: + +```sh +# Only needed to build/start the current app and cached embedding service: +docker compose -f compose.yaml -f compose.search.yaml --profile search up --build -d --wait --wait-timeout 240 app search-model +npm run search:bundle:generate -- --write +npm test +``` + +The generator computes all 216 embeddings with the fixed model, verifies the actual +CPU runner, writes the two fixed assets, and updates the source pin last. It writes +**no database**, does not scrape a new catalog or download a different model, and is +never invoked by ordinary startup/preparation. A missing cached model requires the +explicit model preparation workflow first. Review and commit all three generated +files together; restore them together if publication is interrupted. Ordering and +encoding are reproducible, but different CPU backends can produce slightly different +floating-point coordinates. New checksums must be reviewed, not described as +bit-identical cross-platform output. Update the artifact byte/hash documentation +when approving a regenerated bundle. Rebuild/restart the app after approving a +changed bundle so its source pin and cached decoded bundle are reloaded, then run +the real `test:search` suite against its separately owned fresh test database. +Publication holds an exclusive `data/search/.publication.lock` guard through all +three final-file writes and read-back verification. A concurrent publisher fails +without touching the winning publisher's files. If a maintainer process is killed +while publishing, confirm that no generator is running, review/restore the three +artifacts together, then remove **only the stale** `.publication.lock` file before +retrying. Never remove a live publisher's guard. A stale guard is not used as +permission to overwrite data or silently regenerate on attendee startup. + +**Existing pre-bundle or differently bundled search targets are intentionally not +adopted or overwritten.** They return `SEARCH_SNAPSHOT_MISMATCH`; their catalog, +favorites and old vectors remain intact. For branch-testing recovery, select fresh +explicit `LOCAL_DATABASE_NAME` / `SITE_B_DATABASE_NAME` values in the existing private +`.env`, preserving credentials and all other settings; recreate the app, explicitly +seed those new databases, and prepare search. The [older-catalog recovery instructions](../README.md#existing-notebook-or-older-practice-version) +show that same non-destructive workflow. Changing a name selects another notebook; +it does not migrate favorites. Otherwise arrange a separately reviewed search-only +migration—there is no automatic deletion/force-overwrite command. + +## 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 weights stay in the Compose volume, never Git; + only derived session vectors and model-license attribution are checked in. +- 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 + for each live query. Only the explicit maintainer regeneration tool makes + four-at-a-time batches of sequential document calls; attendee preparation imports + the already-reviewed vectors without calling document inference. +- **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**. This choice is not a vulnerability audit or security + certification. Keep it isolated; upgrading it requires re-proving the + embedding contract and resource use. The large bundled image does **not** prove + that every current CPU-only build is unsuitable: evaluating a supported current + CPU-only distribution/custom image is future maintenance, not a completed + comparison. A smaller final image may still require large build-time downloads. + Its unused bundled GPU runner is extracted + to an owned disk-backed cache (~555 MiB observed on arm64), never used for inference. +- CPU backend is automatically selected (AVX2/AVX when available, otherwise the + portable backend); `OLLAMA_LLM_LIBRARY=cpu` is deliberately not forced because + it prevents those optimized CPU choices. Every embedding request retains + `num_gpu: 0`, and no GPU is passed through. Runtime/backend changes require + measured vector/ranking compatibility checks, not an assumption of identical + floating-point coordinates. +- 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 app adapter invokes + only model-tag verification and embeddings; Ollama itself still has a broader + model-management/generation API.** Network isolation and read-only inference + volumes reduce exposure; they do not remove that API or patch runtime defects. + The temporary downloader is writable and internet-connected, which is why its + verified shutdown matters. 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 bundle-bound existing + vectors are reused and only missing rows are imported from the checked-in bundle. + 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. Separate subprocess tests +send real SIGINT/SIGTERM during mocked manifest reads, startup, readiness and pull; +verify second-signal-resistant cleanup; and check normal failure, stop failure +and a still-running container are never reported as safe completion. 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, imports the genuine checked-in +catalog embeddings with an inference-throwing preparation adapter, then executes +real model query embeddings and native vector queries. It checks sampled unrelated +queries and 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: + +- **Current bundled preparation:** importing the reviewed 216 vectors, building the + IVF index and performing full integrity/query probes on fresh canonical databases + took **1.302 s on Site A / 1.281 s on Site B**. The entire one-command preparation + with cached model/image took **10.775 s** (including model-manifest check, downloader + shutdown verification and app readiness). These are local—not Codespaces—timings. +- An actual model adapter that throws if document inference is requested observed + **zero document embedding calls** for both initial and repeat preparation. Real + user queries still performed one model embedding each. All 216 stored vectors + matched the reviewed bundle; canonical catalog/favorite byte hashes were unchanged. +- Comparing all bundled vectors with the previously validated same-runtime vectors + gave minimum cosine **0.9999999999999979**, maximum coordinate change + **7.45e-9** (float32 encoding). This is not a cross-CPU bit-identity claim. Old + unbound search markers were rejected without changing rows or favorites. +- **Historical per-document preparation, before the checked-in bundle:** both + sites generated 216 real vectors each, taking **40.9 s / 40.4 s** locally after + model caching. A cached reuse run took 9.8 s. These arm64 timings did not predict + a two-core amd64 Codespace running a generic CPU backend: that earlier path took + several minutes per site. The default path now imports precomputed vectors; + those old generation timings are **not current preparation claims**. +- 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. +- The preparation cleanup fix was separately live-tested with **SIGINT and + SIGTERM delivered to the whole CLI process group**, followed by a second, + different signal during cleanup. Both runs started only the owned cached + downloader, verified it **Exited**, and returned **130 / 143** respectively. + The app and both databases stayed stopped; pre-existing unrelated services were + unchanged. No indexing started. Offline subprocess tests also cover blocked + manifest/readiness/pull calls, ordinary success/failure and cleanup failure. +- 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. + +### Codespace and browser acceptance (October 18, 2026) + +The bundled source `d4c10d6c7b2f2722e9f672045cd80841d520885c` was tested in an +existing owned **two-core / 8 GiB Codespace**, using fresh canonical database +names on both sites. Earlier notebooks, solved files, credentials and model cache +were preserved. This final evidence update changes documentation only. + +- Complete `search:prepare -- --local-sites` with cached image/model assets took + **17.07 seconds**, including service readiness and verified downloader shutdown. + Site A import/index/integrity/probes took **1.756 seconds**; Site B also took + **1.756 seconds**. Both imported all 216 vectors. This is **not a first model + download or cold Codespace creation measurement**. +- **Zero document embedding calls** were independently observed: the real model + request count stayed unchanged during the complete preparation. An adapter + that throws on preparation inference also passed initial/repeat import. Every + stored coordinate and ID/source/text/vector-hash tuple matched the bundle. +- Each browser search still made **one genuine query-embedding request**. The + first query after model restart, “running AI locally,” returned the expected + 0.747 / 0.724 top scores in **1.732 seconds** total. A later Site B query returned + the same five ranked results in **248 ms**. These are individual observations, + not a latency guarantee. +- Actual private browser controls passed unfiltered search, unrelated bread + query with zero accepted results, combined day/track filtering, target switching, + native pipeline/model/bundle inspector, and saving a search result through the + existing favorite route. The favorite remained in ordinary browsing after refresh. +- Codespace root tests: **152/152 passed**, no skips; **67 documentation links** + checked. Real bundle/model/DocumentDB integration: **1/1 passed in 8.55 seconds**. +- Earlier browser acceptance of the same query/UI implementation at `75547c2` + also exercised all three chips, cancellation/retry, query-edit and target races, + model outage with explicit errors while keyword browsing/copy remained usable, + model-only recovery, and the required TODO 2 gate. Those simulations were not + repeated for the bundle-only preparation change. +- The CPU backend comparison sampled three prompts on generic CPU versus detected + AVX2: roughly **10–11× faster warm query embeddings**, vector cosine agreement + above **0.9999994**, and identical accepted result IDs/order. This does not promise + bit-identical coordinates across architectures or universal search quality. +- Legacy collection hashes, including previous search vectors/markers and favorite + timestamps, were unchanged. Only fresh selected notebook names received imports. + Only app port 3000 was privately forwarded; database/model ports were not forwarded. +- The owned test Codespace was stopped and authoritative **Shutdown** verified; + notebooks/cache were retained under its existing 24-hour retention setting. + +Code/setup operations used CLI assistance; searches, filters, result actions and +inspector checks used the real browser. This was not a timed novice classroom +study, a new Azure test, or proof of full cold model-download timing. No Azure +resources, paid inference services, private corpus, or model binaries were added +to this repository. diff --git a/package.json b/package.json index 800e6f8..6a9b4eb 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,10 @@ "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", + "search:bundle:generate": "node scripts/search-bundle-generate.mjs", + "test:search": "node --test test/search.integration.js" }, "dependencies": { "mongodb": "7.1.0" diff --git a/scripts/search-bundle-generate.mjs b/scripts/search-bundle-generate.mjs new file mode 100644 index 0000000..dccf4ad --- /dev/null +++ b/scripts/search-bundle-generate.mjs @@ -0,0 +1,133 @@ +// Maintainer-only: genuine local model inference, never called by search:prepare. +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { mkdir, writeFile, rename, open, unlink, readFile } from "node:fs/promises"; +import { pathToFileURL } from "node:url"; +import { readCatalog } from "../src/catalog.js"; +import { SearchModel, SEARCH_MODEL, MODEL_BATCH } from "../src/search-model.js"; +import { documentText, hash, TEXT_VERSION } from "../src/search-contract.js"; +import { BUNDLE_VERSION, BUNDLE_ENCODING, BUNDLE_NORMALIZATION, BUNDLE_FILES, byteHash, decodeSearchBundle } from "../src/search-bundle.js"; + +export async function generateVectors(catalog, model = new SearchModel()) { + const sessions = [...catalog.sessions].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0); + await model.verify(); + const data = Buffer.alloc(sessions.length * SEARCH_MODEL.dimensions * 4); + const entries = []; + let calls = 0; + for (let start = 0; start < sessions.length; start += MODEL_BATCH) { + const batch = sessions.slice(start, start + MODEL_BATCH); + const vectors = await model.embed(batch.map(documentText)); + calls += batch.length; + for (const [offset, session] of batch.entries()) { + const index = start + offset; + // Binary float32 is explicit, compact and round-trip exact. Do not round + // decimal JSON coordinates or renormalize differently at import time. + for (let axis = 0; axis < SEARCH_MODEL.dimensions; axis++) data.writeFloatLE(vectors[offset][axis], (index * SEARCH_MODEL.dimensions + axis) * 4); + const vector = Array.from({ length: SEARCH_MODEL.dimensions }, (_, axis) => data.readFloatLE((index * SEARCH_MODEL.dimensions + axis) * 4)); + entries.push({ id: session.id, sourceHash: hash(session), textHash: hash(documentText(session)), vectorHash: hash(vector) }); + } + } + return { entries, data, documentEmbeddingCalls: calls }; +} + +async function emit() { + const version = await fetch("http://search-model:11434/api/version", { redirect: "error", signal: AbortSignal.timeout(5000) }).then((response) => response.json()); + if (version.version !== "0.1.48") throw new Error("Maintainer generation requires the reviewed runtime version."); + const catalog = await readCatalog(); + const generated = await generateVectors(catalog); + process.stdout.write(JSON.stringify({ + entries: generated.entries, base64: generated.data.toString("base64"), + provenance: { + generatedAt: new Date().toISOString(), method: "fresh-local-model-inference", + runtime: "ollama/ollama:0.1.48", runtimeImageDigest: "sha256:4a3c5b5261f325580d7f4f6440e5094d807784f0513439dcabfda9c2bdf4191e", + platform: process.platform, architecture: process.arch, + endpoint: "/api/embeddings", options: { num_thread: 2, num_ctx: 2048, num_gpu: 0 }, + documentEmbeddingCalls: generated.documentEmbeddingCalls, + license: "Apache-2.0", modelSource: "https://huggingface.co/nomic-ai/nomic-embed-text-v1.5", + corpus: "Only this repository's public ATO schedule titles and tracks; no abstracts or private corpus.", + reproducibility: "Stable session order and float32 encoding; CPU/backend floating-point results may differ. Regeneration changes checksums and requires review.", + }, + })); +} + +// Exclusive guard spans the entire three-file publication; unique temp files +// alone cannot prevent two publishers from interleaving final-file renames. +// Injectable I/O is only for offline race tests; production paths are fixed. +export async function publishBundle(manifestBytes, data, catalog, pin, io = { mkdir, writeFile, rename, open, unlink, readFile }) { + decodeSearchBundle(manifestBytes, data, catalog, pin); + const directory = new URL("../data/search/", import.meta.url); + await io.mkdir(directory, { recursive: true }); + const lockFile = new URL(".publication.lock", directory); + let lock; + try { lock = await io.open(lockFile, "wx", 0o600); } + catch (error) { + if (error.code === "EEXIST") { + const busy = new Error("Another bundle publication owns data/search/.publication.lock. After an interrupted maintainer publication, review/restore all three artifacts and recover the stale guard explicitly; never remove a live publisher's guard."); + busy.code = "BUNDLE_PUBLICATION_BUSY"; + throw busy; + } + throw error; + } + try { + await lock.writeFile(JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }) + "\n"); + for (const [name, bytes] of [[BUNDLE_FILES.data, data], [BUNDLE_FILES.manifest, manifestBytes]]) { + await io.writeFile(new URL(`${name}.pending`, directory), bytes, { mode: 0o644 }); + await io.rename(new URL(`${name}.pending`, directory), new URL(name, directory)); + } + // Pin last: interrupted publication is rejected, not silently accepted. + const pinFile = new URL("../src/search-bundle-pin.js", import.meta.url); + const temporary = new URL("../src/search-bundle-pin.js.pending", import.meta.url); + await io.writeFile(temporary, `// Generated by the explicit maintainer workflow. Review with both data/search assets.\n// A manifest cannot authorize itself: production also requires these source pins.\nexport const SEARCH_BUNDLE_PIN = Object.freeze(${JSON.stringify(pin, null, 2)});\n`, { mode: 0o644 }); + await io.rename(temporary, pinFile); + // Read final assets back while still owning the guard, before success. + decodeSearchBundle(await io.readFile(new URL(BUNDLE_FILES.manifest, directory)), await io.readFile(new URL(BUNDLE_FILES.data, directory)), catalog, pin); + } finally { + await lock.close(); + await io.unlink(lockFile); + } +} + +async function writeBundle() { + const started = performance.now(); + const execute = promisify(execFile); + const base = ["compose", "-f", "compose.yaml", "-f", "compose.search.yaml"]; + const container = (await execute("docker", [...base, "ps", "-q", "search-model"], { timeout: 10000, maxBuffer: 10000 })).stdout.trim(); + if (!/^[a-f0-9]{12,64}$/.test(container)) throw new Error("Exactly one prepared model service must be running."); + const image = (await execute("docker", ["inspect", "--format", "{{.Config.Image}}", container], { timeout: 10000, maxBuffer: 10000 })).stdout.trim(); + if (!image.endsWith("@sha256:4a3c5b5261f325580d7f4f6440e5094d807784f0513439dcabfda9c2bdf4191e")) throw new Error("Generation requires the exact reviewed model-service image."); + const { stdout } = await execute("docker", [...base, "exec", "-T", "app", "node", "scripts/search-bundle-generate.mjs", "--emit"], { timeout: 1800000, maxBuffer: 3_000_000 }); + const generated = JSON.parse(stdout); + const catalog = await readCatalog(); + if (generated.provenance.documentEmbeddingCalls !== catalog.sessions.length) throw new Error("Every catalog entry must have fresh model provenance."); + // Inspect the actual running backend, not the requested override or host CPU. + const { stdout: runners } = await execute("docker", [...base, "exec", "-T", "search-model", "sh", "-c", "for f in /proc/[0-9]*/cmdline; do tr '\\000' ' ' < \"$f\" 2>/dev/null; printf '\\n'; done"], { timeout: 10000, maxBuffer: 256000 }); + const backends = [...new Set([...runners.matchAll(/(?:^|\n)\/runners\/(cpu(?:_avx2|_avx)?)\/ollama_llama_server(?: |$)/g)].map((match) => match[1]))]; + if (backends.length !== 1) throw new Error("Could not establish exactly one running CPU backend for generation provenance."); + generated.provenance.backend = backends[0]; + generated.provenance.backendEvidence = "Observed /runners/<backend>/ollama_llama_server in the model container process command line immediately after generation."; + const data = Buffer.from(generated.base64, "base64"); + const manifest = { + version: BUNDLE_VERSION, catalogFingerprint: catalog.fingerprint, + model: SEARCH_MODEL, textVersion: TEXT_VERSION, normalization: BUNDLE_NORMALIZATION, + encoding: BUNDLE_ENCODING, count: catalog.sessions.length, + data: { file: BUNDLE_FILES.data, bytes: data.length, sha256: byteHash(data) }, + provenance: generated.provenance, sessions: generated.entries, + }; + const manifestBytes = Buffer.from(JSON.stringify(manifest, null, 2) + "\n"); + const pin = { version: BUNDLE_VERSION, count: catalog.sessions.length, manifestBytes: manifestBytes.length, manifestSha256: byteHash(manifestBytes), dataBytes: data.length, dataSha256: byteHash(data) }; + decodeSearchBundle(manifestBytes, data, catalog, pin); + await publishBundle(manifestBytes, data, catalog, pin); + console.log(JSON.stringify({ status: "generated-for-review", ...pin, provenance: generated.provenance, elapsedMs: Math.round(performance.now() - started) })); +} +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + try { + const args = process.argv.slice(2); + if (args.length === 1 && args[0] === "--emit") await emit(); + else if (args.length === 1 && args[0] === "--write") await writeBundle(); + else throw new Error("Maintainers only: npm run search:bundle:generate -- --write. Start the pinned local service first; this deliberately replaces the derived bundle and pin for review, not any database."); + } catch (error) { + if (error.code === "BUNDLE_PUBLICATION_BUSY") console.error(error.message); + console.error("Maintainer bundle generation failed. Check the pinned local model/runtime, writable repository and reviewed generator invocation. No database was modified; if publication was interrupted, restore/review all three bundle files together."); + process.exitCode = 1; + } +} 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..c281051 --- /dev/null +++ b/scripts/search-prepare.mjs @@ -0,0 +1,193 @@ +import { spawn } 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; +} + +// Wait for close, not just exit/abort: a cancelled Compose process must finish +// before cleanup reconciles any detached container it may have created. +export function runCommand(command, args, { signal, timeout = 900000, capture = false, quiet = false } = {}) { + signal?.throwIfAborted(); + return new Promise((resolve) => { + // Own the subprocess group on POSIX: terminal-wide Ctrl+C must not kill a + // cleanup command directly, bypassing the parent's second-signal handler. + const detached = process.platform !== "win32"; + const child = spawn(command, args, { detached, stdio: ["ignore", "pipe", "pipe"] }); + const kill = (signal) => { + try { + if (detached && child.pid) process.kill(-child.pid, signal); + else child.kill(signal); + } catch { /* Already closed; the close handler is authoritative. */ } + }; + let stdout = ""; + let cancelled = false; + let force; + let spawnError; + const cancel = () => { + if (cancelled) return; + cancelled = true; + kill("SIGTERM"); + force = setTimeout(() => kill("SIGKILL"), 3000); + }; + const timer = setTimeout(cancel, timeout); + signal?.addEventListener("abort", cancel, { once: true }); + if (signal?.aborted) cancel(); + child.stdout.on("data", (chunk) => { + if (capture) { + stdout += chunk; + if (Buffer.byteLength(stdout) > 2_000_000) cancel(); + } else if (!quiet) process.stdout.write(chunk); + }); + // Configuration/inspection output is private in memory and never relayed. + child.stderr.on("data", (chunk) => { if (!capture && !quiet) process.stderr.write(chunk); }); + child.once("error", (error) => { spawnError = error; }); + child.once("close", (status) => { + clearTimeout(timer); clearTimeout(force); + signal?.removeEventListener("abort", cancel); + resolve({ status, stdout, cancelled, error: Boolean(spawnError) }); + }); + }); +} + +export async function prepareSearch(args, { run = runCommand, fetchImpl = fetch, log = console.log, signal } = {}) { + const targets = preparationTargets(args); + if (process.env.DOCKER_HOST && !process.env.DOCKER_CONTEXT) { + throw new Error("Search preparation requires an explicit Docker context when DOCKER_HOST is overridden. Select a context for the intended daemon before retrying; no search service was started."); + } + const started = performance.now(); + const checkCancelled = () => signal?.throwIfAborted(); + checkCancelled(); + const response = await fetchImpl("https://registry.ollama.ai/v2/library/nomic-embed-text/manifests/v1.5", { + redirect: "error", signal: AbortSignal.any([...(signal ? [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) { + checkCancelled(); + 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); + } + checkCancelled(); + const bytes = checkManifest(Buffer.concat(chunks).toString("utf8")); + log(`Optional embedding-only showcase: pinned query-model assets ${bytes} bytes (Apache-2.0); document vectors are imported from the checked-in bundle, not generated here. No answer model or paid API. Targets: ${targets.join(", ")}.`); + const execute = async (args, options = {}) => { + if (!options.cleanup) checkCancelled(); + const result = await run("docker", args, { signal: options.cleanup ? undefined : signal, timeout: 900000, ...options }); + if (!options.cleanup) checkCancelled(); + if (result.error || result.cancelled || result.status !== 0) throw new Error("A bounded Docker operation failed. Existing catalogs and favorites were not replaced."); + return result.stdout || ""; + }; + // Resolve once, then freeze both selectors for every startup/cleanup command. + // Compose configuration can contain credentials: capture it, keep only name, + // and never include raw CLI output or error objects in a diagnostic. + const context = (await execute(["context", "show"], { capture: true, timeout: 10000 })).trim(); + if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(context)) throw new Error("Cannot safely identify the active Docker context; no search service was started."); + const files = ["-f", "compose.yaml", "-f", "compose.search.yaml"]; + let project; + try { project = JSON.parse(await execute(["--context", context, "compose", ...files, "config", "--format", "json"], { capture: true, timeout: 10000 })).name; } + catch { checkCancelled(); throw new Error("Cannot resolve the Compose project safely; no search service was started."); } + if (typeof project !== "string" || !/^[a-z0-9][a-z0-9_-]{0,127}$/.test(project)) throw new Error("Cannot safely identify this Compose project; no search service was started."); + const base = ["--context", context, "compose", "--project-name", project, ...files]; + const docker = (args, options) => execute([...base, ...args], options); + let attemptedDownload = false; + let cleanupPromise; + const cleanup = () => cleanupPromise ||= (async () => { + if (!attemptedDownload) return; + log(JSON.stringify({ event: "search-download-cleanup-started", project, context })); + // No caller AbortSignal: repeated SIGINT/SIGTERM cannot kill this cleanup. + // Every command remains independently time-bounded; no deletion or pruning. + try { + await docker(["stop", "--timeout", "10", "search-download"], { cleanup: true, timeout: 45000, capture: true }); + const inventory = async () => { + const output = await execute(["--context", context, "ps", "-aq", "--filter", `label=com.docker.compose.project=${project}`, "--filter", "label=com.docker.compose.service=search-download"], { cleanup: true, timeout: 10000, capture: true }); + const ids = output.trim() ? output.trim().split(/\s+/) : []; + if (ids.length > 4 || ids.some((id) => !/^[a-f0-9]{12,64}$/.test(id))) throw new Error("Invalid owned container inventory"); + for (const id of ids) { + const text = await execute(["--context", context, "inspect", "--format", "{{json .State}}", id], { cleanup: true, timeout: 5000, capture: true }); + const state = JSON.parse(text); + if (state.Running !== false || !["exited", "created", "dead"].includes(state.Status)) throw new Error("Owned downloader is still running"); + } + return ids; + }; + const ids = await inventory(); + // Recheck after the cancelled startup client has closed and Docker settled. + await sleep(250); + const finalIds = await inventory(); + if (JSON.stringify(ids.sort()) !== JSON.stringify(finalIds.sort())) throw new Error("Owned downloader inventory changed during cleanup"); + log(JSON.stringify({ event: "search-download-stopped", project, context, verified: true, containers: finalIds.length })); + } catch { + const error = new Error(`SEARCH_DOWNLOAD_CLEANUP_FAILED: could not verify search-download stopped in project ${project}, Docker context ${context}. Run the scoped recovery command in docs/semantic-search.md before retrying. No data or volumes were deleted.`); + error.code = "SEARCH_DOWNLOAD_CLEANUP_FAILED"; + throw error; + } + })(); + try { + checkCancelled(); + attemptedDownload = true; + await docker(["--profile", "search-download", "up", "-d", "search-download"]); + log(JSON.stringify({ event: "search-download-started", project, context })); + let ready = false; + for (let attempt = 0; attempt < 20; attempt++) { + checkCancelled(); + const result = await run("docker", [...base, "exec", "-T", "search-download", "ollama", "list"], { signal, quiet: true, timeout: 5000 }); + checkCancelled(); + if (!result.error && !result.cancelled && result.status === 0) { ready = true; break; } + await sleep(1000, undefined, { signal }); + } + if (!ready) throw new Error("The model download service did not become ready. Core workshop startup does not depend on it."); + await docker(["exec", "-T", "search-download", "ollama", "pull", SEARCH_MODEL.name]); + } finally { await cleanup(); } + checkCancelled(); + await docker(["--profile", "search", "up", "--build", "-d", "--wait", "--wait-timeout", "240", "app", "search-model"]); + for (const target of targets) { + checkCancelled(); + await docker(["exec", "-T", "app", "node", "scripts/search-index.mjs", "--target", target]); + } + checkCancelled(); + 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."); +} + +export async function searchPrepareMain(args, options = {}) { + const interrupted = new AbortController(); + let receivedSignal; + const onSignal = (signal) => { + receivedSignal ||= signal; + interrupted.abort(); // idempotent; never exit before cleanup completes + }; + process.on("SIGINT", onSignal); + process.on("SIGTERM", onSignal); + try { + await prepareSearch(args, { ...options, signal: interrupted.signal }); + return receivedSignal === "SIGINT" ? 130 : receivedSignal ? 143 : 0; + } catch (error) { + const message = error?.code === "SEARCH_DOWNLOAD_CLEANUP_FAILED" ? error.message + : receivedSignal ? "Search preparation interrupted. No later preparation steps were started; inspect the scoped downloader cleanup receipt." + : error?.name === "AbortError" || error?.name === "TimeoutError" ? "Search preparation timed out or was cancelled before completion." + : error?.message || "Search preparation failed."; + (options.errorLog || console.error)(message); + return error?.code === "SEARCH_DOWNLOAD_CLEANUP_FAILED" ? 1 : receivedSignal === "SIGINT" ? 130 : receivedSignal ? 143 : 1; + } finally { + process.removeListener("SIGINT", onSignal); + process.removeListener("SIGTERM", onSignal); + } +} +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + process.exitCode = await searchPrepareMain(process.argv.slice(2)); +} 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; } } </style> </head> @@ -178,6 +189,49 @@ <h2 id="exercise-title"></h2> <div class="notice error" id="error" role="alert" hidden></div> <div class="notice success" id="message" role="status" hidden></div> + <section class="panel stack semantic" aria-labelledby="semantic-title"> + <p class="eyebrow">Optional built-in showcase / Outside the 105-minute lab</p> + <h2 id="semantic-title">Search by meaning</h2> + <p class="muted" id="semantic-help">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.</p> + <p class="status" id="semantic-status" role="status" aria-live="polite">Checking optional search readiness...</p> + <p class="status" id="semantic-model"></p> + <p class="status" id="semantic-catalog"></p> + <div class="row"> + <button id="semantic-retry" type="button">Check search readiness</button> + <small>Optional setup: <code>npm run search:prepare -- --local-sites</code>. Core keyword browsing does not require a model.</small> + </div> + <form id="semantic-form" class="stack" aria-describedby="semantic-help semantic-privacy"> + <label class="field" for="semantic-query">What would you like to learn? + <input id="semantic-query" type="search" maxlength="500" required autocomplete="off" placeholder="For example, running AI locally"> + </label> + <div class="row semantic-chips" aria-label="Example meaning searches"> + <button type="button" id="semantic-chip-local">running AI locally</button> + <button type="button" id="semantic-chip-security">securing software supply chains</button> + <button type="button" id="semantic-chip-accessibility">building accessible interfaces</button> + </div> + <div class="semantic-filters"> + <label class="field" for="semantic-day">Meaning search day + <select id="semantic-day"><option value="">All days</option></select> + </label> + <label class="field" for="semantic-track">Meaning search track + <select id="semantic-track"><option value="">All tracks</option></select> + </label> + </div> + <div class="row"> + <button id="semantic-submit" class="primary" type="submit" disabled>Search by meaning</button> + <button id="semantic-cancel" type="button" disabled>Cancel search</button> + </div> + </form> + <small id="semantic-privacy">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.</small> + <p class="status" id="semantic-message" role="status" aria-live="polite"></p> + <ol class="sessions semantic-results" id="semantic-results" aria-label="Ranked meaning search results" aria-busy="false"></ol> + <details id="semantic-inspector" hidden> + <summary>Query inspector — model, database pipeline, filters and timings</summary> + <p class="status">Actual server-reported query details; the vector is abbreviated. Timings are milliseconds. Only the current response is shown.</p> + <pre id="semantic-inspector-json" tabindex="0" aria-label="Query inspector JSON"></pre> + </details> + </section> + <div class="metrics" aria-label="Planner totals"> <div class="metric"><strong id="session-count">0</strong><span>sessions</span></div> <div class="metric"><strong id="favorite-count">0</strong><span>favorites</span></div> @@ -187,7 +241,7 @@ <h2 id="exercise-title"></h2> <div class="layout"> <section aria-label="Session catalog"> <div class="filters"> - <label class="field">Find a session + <label class="field">Keyword search <input id="search" type="search" placeholder="Search titles, tracks, or rooms"> </label> <label class="field">Day @@ -243,6 +297,10 @@ <h2 id="copy-title">Confirm selected favorites</h2> 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 @@ <h2 id="copy-title">Confirm selected favorites</h2> 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 @@ <h2 id="copy-title">Confirm selected favorites</h2> ? "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 @@ <h2 id="copy-title">Confirm selected favorites</h2> $("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 @@ <h2 id="copy-title">Confirm selected favorites</h2> 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 @@ <h2 id="copy-title">Confirm selected favorites</h2> 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 @@ <h2 id="copy-title">Confirm selected favorites</h2> } async function refresh() { + resetSemanticTarget(); state = undefined; selected.clear(); $("exercise").hidden = true; @@ -480,19 +745,42 @@ <h2 id="copy-title">Confirm selected favorites</h2> 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(), /<!doctype html>/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(/<script[^>]*>([\s\S]*?)<\/script>/g)].at(-1)[1]; +const catalog = { kind: "official", title: "All Things Open 2026", snapshotDate: "2026-10-12", timeZone: "America/New_York", source: "216 published schedule entries" }; +const config = { target: "local", mode: "starter", csrfToken: "test-token", targets: [{ id: "local", label: "Site A" }, { id: "cloud", label: "Site B" }] }; +const status = { target: "local", enabled: true, ready: true, model: { name: "local-embed", digest: "sha256:test", dimensions: 768 }, catalog, filters: { days: ["2026-10-20"], tracks: ["AI", "Security"] } }; +const session = { id: "session-1", title: "Running models locally", track: "AI", room: "Room 1", startsAt: "2026-10-20T14:00:00.000Z", endsAt: "2026-10-20T15:00:00.000Z", url: "https://example.org/session" }; +const planner = { target: "local", catalog, sessions: [session], favorites: [], conflicts: [], orphanedFavorites: [] }; +const response = { + target: "local", results: [{ session, similarity: 0.7234, evidence: { title: session.title, track: session.track }, rank: 1 }], + inspector: { status: "ok", target: "local", model: status.model, database: "workshop", collection: "session_vectors", index: "semantic_cosine", filterStrategy: "prefilter", pipeline: [{ $search: { vector: "[0.12, ... 768 dimensions]" } }], filters: {}, embeddingMs: 30000, databaseMs: 6, totalMs: 30006, rankingPolicy: "pure semantic", cutoff: 0.45, candidates: 5, metadataOnly: true }, +}; +const json = (body, ok = true) => ({ ok, json: async () => structuredClone(body) }); +const deferred = () => { + let resolve; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +}; + +// Runs the actual page script with a minimal DOM, not a rendered-browser proof. +// innerHTML throws so metadata/inspector XSS regressions cannot silently pass. +function browser(fetcher = async (path) => { + if (path === "/api/search/status") return json(status); + if (path === "/api/search") return json(response); + throw new Error(`Unexpected request: ${path}`); +}) { + const elements = new Map(); + class Element { + constructor(tag = "div") { + Object.assign(this, { tagName: tag, hidden: false, disabled: false, textContent: "", value: "", children: [], attributes: {}, listeners: {}, className: "" }); + } + set innerHTML(_) { throw new Error("Do not interpret server-provided HTML"); } + addEventListener(name, listener) { this.listeners[name] = listener; } + setAttribute(name, value) { this.attributes[name] = value; } + append(...children) { this.children.push(...children); } + replaceChildren(...children) { this.children = children; } + focus() { this.focused = true; } + showModal() { this.open = true; } + close() { this.open = false; } + async emit(name) { await this.listeners[name]?.({ preventDefault() {} }); } + } + const get = (id) => { + if (!elements.has(id)) elements.set(id, new Element()); + return elements.get(id); + }; + const descendants = (element) => [element, ...element.children.flatMap(descendants)]; + const calls = []; + const context = vm.createContext({ + Intl, Date, URL, URLSearchParams, AbortController, Set, Map, Error, console, + window: { confirm: () => true }, + fetch: async (path, options) => { calls.push({ path, options }); return fetcher(path, options); }, + document: { + getElementById: get, createElement: (tag) => new Element(tag), + querySelectorAll: () => [...elements.values()].flatMap(descendants).filter((element) => element.className.includes("save-favorite")), + }, + }); + const run = (source) => vm.runInContext(source, context); + run(script.replace(/ perform\(refresh\);\s*$/, "")); + run(`config = ${JSON.stringify(config)}`); + for (const [id, text] of [["local", "running AI locally"], ["security", "securing software supply chains"], ["accessibility", "building accessible interfaces"]]) get(`semantic-chip-${id}`).textContent = text; + return { get, run, calls, descendants, text: (id) => descendants(get(id)).map((element) => element.textContent).join(" ") }; +} + +test("optional panel is always present, accurately labeled and accessible without TODO 1", () => { + assert.match(html, /<section class="panel stack semantic" aria-labelledby="semantic-title">/); + assert.match(html, /Optional built-in showcase \/ Outside the 105-minute lab/); + assert.match(html, /Keyword search\s*<input id="search"/); + assert.match(html, /maxlength="500" required autocomplete="off"/); + assert.match(html, /npm run search:prepare -- --local-sites/); + assert.match(html, /id="semantic-status" role="status" aria-live="polite"/); + assert.match(html, /id="semantic-message" role="status" aria-live="polite"/); + assert.match(html, /raw cosine similarity, not confidence or probability/); + assert.doesNotMatch(script, /localStorage|sessionStorage|indexedDB|innerHTML/); +}); + +test("search status loads even when starter state fails with TODO 1", async () => { + const ui = browser(async (path) => { + if (path === "/api/config") return json(config); + if (path === "/api/health") return json({ ready: true }); + if (path === "/api/state") return json({ error: { code: "TODO_LIST_SESSIONS", message: "Implement listSessions" } }, false); + if (path === "/api/search/status") return json(status); + throw new Error(path); + }); + await ui.run("perform(refresh)"); + assert.match(ui.get("exercise-title").textContent, /Exercise 1/); + assert.match(ui.get("semantic-status").textContent, /Built-in meaning search ready on Site A/); + assert.match(ui.get("semantic-model").textContent, /local-embed.*sha256:test.*768/); + assert.match(ui.get("semantic-catalog").textContent, /216 published schedule entries/); + ui.get("semantic-query").value = "running AI locally"; + await ui.get("semantic-query").emit("input"); + assert.equal(ui.get("semantic-submit").disabled, false); + assert.equal(ui.get("semantic-day").children[1].value, "2026-10-20"); +}); + +test("core health failure does not prevent built-in readiness; failed readiness is scoped to search", async () => { + const ui = browser(async (path) => { + if (path === "/api/config") return json(config); + if (path === "/api/health") return json({ error: { code: "DATABASE_UNAVAILABLE", message: "Database down" } }, false); + if (path === "/api/search/status") return json(status); + throw new Error(path); + }); + await ui.run("perform(refresh)"); + assert.match(ui.get("error").textContent, /DATABASE_UNAVAILABLE/); + assert.match(ui.get("semantic-status").textContent, /ready on Site A/); +}); + +test("a slow optional readiness probe does not hold core refresh or favorite controls busy", async () => { + const pending = deferred(); + const ui = browser(async (path) => { + if (path === "/api/config") return json(config); + if (path === "/api/health") return json({ ready: true }); + if (path === "/api/state") return json(planner); + if (path === "/api/search/status") return pending.promise; + throw new Error(path); + }); + await ui.run("perform(refresh)"); + assert.equal(ui.run("busy"), false); + assert.equal(ui.get("refresh").disabled, false); + assert.equal(ui.get("sessions").children.length, 1); + assert.equal(ui.descendants(ui.get("sessions")).find((element) => element.tagName === "button").disabled, false); + assert.equal(ui.run("semantic.checking"), true); + pending.resolve(json(status)); + await new Promise((resolve) => setImmediate(resolve)); + assert.match(ui.get("semantic-status").textContent, /ready on Site A/); +}); + +test("disabled, unseeded and missing-model statuses stay visible and can retry safely", async () => { + for (const unavailable of [ + { enabled: false, code: "SEARCH_DISABLED", message: "Optional showcase disabled." }, + { enabled: true, code: "SEARCH_NOT_PREPARED", message: "No seeded vectors for this target." }, + { enabled: true, code: "MODEL_UNAVAILABLE", message: "Embedding model not installed." }, + ]) { + let attempt = 0; + const ui = browser(async () => json(attempt++ ? status : { ...status, ...unavailable, ready: false })); + await ui.run("loadSemanticStatus()"); + assert.equal(ui.get("semantic-submit").disabled, true); + assert.match(ui.get("semantic-status").textContent, new RegExp(unavailable.code)); + assert.equal(ui.get("semantic-retry").disabled, false); + ui.get("semantic-query").value = "local AI"; + await ui.get("semantic-retry").emit("click"); + assert.equal(ui.get("semantic-submit").disabled, false); + } + const ui = browser(async () => json({ error: { code: "EMBEDDING_UNAVAILABLE", message: "Service down" } }, false)); + await ui.run("loadSemanticStatus()"); + assert.match(ui.get("semantic-status").textContent, /EMBEDDING_UNAVAILABLE.*No keyword fallback/); + assert.equal(ui.get("semantic-retry").disabled, false); +}); + +test("semantic query is a token-protected POST with bounded limit and independent validated filters", async () => { + const ui = browser(); + await ui.run("loadSemanticStatus()"); + ui.get("search").value = "keyword stays here"; + ui.get("day").value = "2026-10-19"; + ui.get("semantic-query").value = " running AI locally "; + ui.get("semantic-day").value = "2026-10-20"; + ui.get("semantic-track").value = "AI"; + await ui.get("semantic-form").emit("submit"); + const request = ui.calls.find(({ path }) => path === "/api/search"); + assert.equal(request.options.method, "POST"); + assert.equal(request.options.headers["X-Workshop-Token"], "test-token"); + assert.equal(request.options.headers["Content-Type"], "application/json"); + assert.deepEqual(JSON.parse(request.options.body), { target: "local", query: "running AI locally", limit: 5, day: "2026-10-20", track: "AI" }); + assert.equal(ui.get("search").value, "keyword stays here"); + assert.equal(ui.get("day").value, "2026-10-19"); + assert.match(ui.text("semantic-results"), /Rank 1 \/ Cosine similarity: 0.723/); + assert.doesNotMatch(ui.text("semantic-results"), /72.3%|confidence/); + assert.match(ui.text("semantic-results"), /Room 1/); + assert.deepEqual(JSON.parse(ui.get("semantic-inspector-json").textContent), response.inspector); + assert.equal(ui.get("semantic-inspector").hidden, false); + assert.equal(ui.get("semantic-results").attributes["aria-busy"], "false"); +}); + +test("blank, overlong and forged filters never dispatch a search; prompt chips only fill the query", async () => { + const ui = browser(); + await ui.run("loadSemanticStatus()"); + for (const query of [" ", "x".repeat(501)]) { + ui.get("semantic-query").value = query; + await ui.run("searchByMeaning()"); + assert.match(ui.get("semantic-message").textContent, /1 to 500/); + } + await ui.get("semantic-chip-security").emit("click"); + assert.equal(ui.get("semantic-query").value, "securing software supply chains"); + assert.equal(ui.get("semantic-query").focused, true); + ui.get("semantic-track").value = "not a catalog track"; + await ui.run("searchByMeaning()"); + assert.match(ui.get("semantic-message").textContent, /available search filters/); + assert.equal(ui.calls.filter(({ path }) => path === "/api/search").length, 0); +}); + +test("cancel aborts cold searches and ignores late replies even when fetch ignores abort", async () => { + const pending = deferred(); + const ui = browser(async (path) => path === "/api/search/status" ? json(status) : pending.promise); + await ui.run("loadSemanticStatus()"); + ui.get("semantic-query").value = "local AI"; + const search = ui.run("searchByMeaning()"); + assert.match(ui.get("semantic-message").textContent, /30 seconds/); + assert.equal(ui.get("semantic-cancel").disabled, false); + assert.equal(ui.get("semantic-submit").disabled, true); + assert.equal(ui.run("busy"), false, "semantic latency must not hold the core action lock"); + const request = ui.calls.at(-1); + await ui.get("semantic-cancel").emit("click"); + assert.equal(request.options.signal.aborted, true); + pending.resolve(json(response)); + await search; + assert.equal(ui.get("semantic-results").children.length, 0); + assert.equal(ui.get("semantic-inspector-json").textContent, ""); + assert.match(ui.get("semantic-message").textContent, /canceled/); +}); + +test("editing query or filters clears old results and ignores old errors after a newer search", async () => { + const old = deferred(); + let searches = 0; + const ui = browser(async (path) => path === "/api/search/status" ? json(status) : (++searches === 1 ? old.promise : json(response))); + await ui.run("loadSemanticStatus()"); + ui.get("semantic-query").value = "old query"; + const first = ui.run("searchByMeaning()"); + ui.get("semantic-query").value = "new query"; + await ui.get("semantic-query").emit("input"); + await ui.run("searchByMeaning()"); + old.resolve(json({ error: { code: "OLD_FAILURE", message: "Ignore me" } }, false)); + await first; + assert.match(ui.get("semantic-message").textContent, /1 ranked match/); + assert.equal(ui.get("semantic-results").children.length, 1); + await ui.get("semantic-day").emit("change"); + assert.equal(ui.get("semantic-results").children.length, 0); + assert.equal(ui.get("semantic-inspector").hidden, true); +}); + +test("switching targets aborts search and pending status and clears old results immediately", async () => { + const pendingSearch = deferred(); + const ui = browser(async (path) => { + if (path === "/api/search/status") return json(status); + if (path === "/api/search") return pendingSearch.promise; + if (path === "/api/target") return json({ error: { code: "TARGET_UNAVAILABLE", message: "Cannot switch" } }, false); + throw new Error(path); + }); + await ui.run("loadSemanticStatus()"); + ui.get("semantic-query").value = "local AI"; + const running = ui.run("searchByMeaning()"); + const signal = ui.calls.at(-1).options.signal; + ui.get("target-select").value = "cloud"; + await ui.get("switch-target").emit("click"); + assert.equal(signal.aborted, true); + pendingSearch.resolve(json(response)); + await running; + assert.equal(ui.get("semantic-results").children.length, 0); + assert.equal(ui.get("semantic-submit").disabled, true); + assert.equal(ui.get("semantic-retry").disabled, false); + assert.equal(ui.get("semantic-query").value, ""); + + const pendingStatus = deferred(); + const statusUi = browser(async () => pendingStatus.promise); + const checking = statusUi.run("loadSemanticStatus()"); + const statusSignal = statusUi.calls.at(-1).options.signal; + statusUi.run('resetSemanticTarget(); config.target = "cloud"'); + pendingStatus.resolve(json(status)); + await checking; + assert.equal(statusSignal.aborted, true); + assert.equal(statusUi.run("semantic.status"), undefined); + assert.doesNotMatch(statusUi.get("semantic-status").textContent, /ready on Site A/); +}); + +test("cross-tab target mismatch never renders results, and unavailable searches never fall back", async () => { + for (const reply of [ + json({ ...response, target: "cloud" }), + json({ error: { code: "EMBEDDING_UNAVAILABLE", message: "No model connection" } }, false), + ]) { + const ui = browser(async (path) => path === "/api/search/status" ? json(status) : reply); + await ui.run("loadSemanticStatus()"); + ui.get("semantic-query").value = "local AI"; + await ui.run("searchByMeaning()"); + assert.match(ui.get("semantic-message").textContent, /No keyword fallback was used/); + assert.equal(ui.get("semantic-results").children.length, 0); + assert.equal(ui.get("semantic-inspector").hidden, true); + assert.deepEqual(ui.calls.map(({ path }) => path), ["/api/search/status", "/api/search"]); + } +}); + +test("empty semantic results explain the cutoff rather than inventing a recommendation", async () => { + const ui = browser(async (path) => json(path === "/api/search/status" ? status : { ...response, results: [] })); + await ui.run("loadSemanticStatus()"); + ui.get("semantic-query").value = "something unrelated"; + await ui.run("searchByMeaning()"); + assert.match(ui.get("semantic-message").textContent, /No sessions met the semantic cutoff/); + assert.equal(ui.get("semantic-results").children.length, 0); + assert.equal(ui.get("semantic-inspector").hidden, false); +}); + +test("untrusted metadata and inspector JSON are text-only and unsafe source URLs are omitted", async () => { + const attack = '<img src=x onerror="alert(1)">'; + const unsafe = structuredClone(response); + unsafe.results[0].session.title = attack; + unsafe.results[0].session.url = "javascript:alert(1)"; + unsafe.results[0].evidence.title = attack; + unsafe.inspector.pipeline = [{ $match: { title: attack } }]; + const ui = browser(async (path) => json(path === "/api/search/status" ? status : unsafe)); + await ui.run("loadSemanticStatus()"); + ui.get("semantic-query").value = "metadata"; + await ui.run("searchByMeaning()"); + assert.ok(ui.text("semantic-results").includes(attack)); + assert.equal(JSON.parse(ui.get("semantic-inspector-json").textContent).pipeline[0].$match.title, attack); + assert.equal(ui.descendants(ui.get("semantic-results")).some((element) => element.tagName === "a"), false); +}); + +test("semantic favorite action uses core TODO 2 endpoint; never writes a database directly", async () => { + const ui = browser(async (path) => { + if (path === "/api/search/status") return json(status); + if (path === "/api/search") return json(response); + if (path === "/api/favorites") return json({ error: { code: "TODO_SAVE_FAVORITE", message: "Implement saveFavorite" } }, false); + throw new Error(path); + }); + await ui.run("loadSemanticStatus()"); + ui.get("semantic-query").value = "local AI"; + await ui.run("searchByMeaning()"); + const button = ui.descendants(ui.get("semantic-results")).find((element) => element.tagName === "button"); + await button.emit("click"); + const favorite = ui.calls.at(-1); + assert.equal(favorite.path, "/api/favorites"); + assert.equal(favorite.options.method, "POST"); + assert.deepEqual(JSON.parse(favorite.options.body), { target: "local", sessionId: "session-1" }); + assert.match(ui.get("exercise-title").textContent, /Exercise 2/); + assert.match(ui.get("exercise-help").textContent, /saveFavorite/); + assert.equal(ui.get("semantic-results").children.length, 1); + ui.run('config.target = "cloud"'); + const count = ui.calls.length; + await button.emit("click"); + assert.equal(ui.calls.length, count, "a detached stale-target card cannot save"); +}); + +test("confirmed saves remain usable in built-in cards when TODO 1 still blocks core state", async () => { + const ui = browser(async (path) => { + if (path === "/api/search/status") return json(status); + if (path === "/api/search") return json(response); + if (path === "/api/favorites") return json({ ok: true }); + if (path === "/api/state") return json({ error: { code: "TODO_LIST_SESSIONS", message: "Implement listSessions" } }, false); + throw new Error(path); + }); + await ui.run("loadSemanticStatus()"); + ui.get("semantic-query").value = "local AI"; + await ui.run("searchByMeaning()"); + const button = () => ui.descendants(ui.get("semantic-results")).find((element) => element.tagName === "button"); + await button().emit("click"); + assert.match(ui.get("message").textContent, /Favorite saved/); + assert.equal(button().textContent, "Remove favorite"); + assert.match(ui.get("exercise-title").textContent, /Exercise 1/); + await button().emit("click"); + assert.equal(button().textContent, "Save favorite"); + assert.match(ui.get("message").textContent, /Removed from the active database only/); + ui.run("resetSemanticTarget()"); + assert.equal(ui.run("semantic.confirmedFavorites.size"), 0); +}); + +test("successful core favorites rerender both surfaces, preserving remove, keyword and copy selection behavior", async () => { + let saved = false; + const ui = browser(async (path, options) => { + if (path === "/api/search/status") return json(status); + if (path === "/api/search") return json(response); + if (path === "/api/favorites") { saved = options.method === "POST"; return json({ ok: true }); } + if (path === "/api/state") return json({ ...planner, favorites: saved ? [session.id] : [] }); + throw new Error(path); + }); + ui.run(`state = ${JSON.stringify(planner)}; render()`); + await ui.run("loadSemanticStatus()"); + ui.get("semantic-query").value = "local AI"; + await ui.run("searchByMeaning()"); + const favoriteButton = (id) => ui.descendants(ui.get(id)).find((element) => element.tagName === "button"); + await favoriteButton("semantic-results").emit("click"); + assert.equal(favoriteButton("semantic-results").textContent, "Remove favorite"); + assert.equal(favoriteButton("sessions").textContent, "Remove favorite"); + assert.equal(ui.get("favorites").children.length, 1); + assert.equal(ui.get("export").disabled, false); + ui.run('selected.add("session-1"); controls()'); + assert.equal(ui.get("copy").disabled, false); + ui.get("search").value = "not in title, track, or room"; + await ui.get("search").emit("input"); + assert.equal(ui.get("sessions").children.length, 0); + assert.equal(ui.get("semantic-results").children.length, 1); + await favoriteButton("semantic-results").emit("click"); + assert.equal(favoriteButton("semantic-results").textContent, "Save favorite"); + assert.equal(ui.get("favorites").children.length, 0); + assert.equal(ui.get("copy").disabled, true); + assert.equal(ui.get("export").disabled, true); +}); diff --git a/test/search.integration.js b/test/search.integration.js new file mode 100644 index 0000000..8b3ffb6 --- /dev/null +++ b/test/search.integration.js @@ -0,0 +1,174 @@ +// Opt-in integration: real shipped document embeddings, pinned local QUERY embeddings, +// and actual DocumentDB vector queries. Preparation must never embed documents. +// Run inside the explicitly prepared Compose app. Never part of npm test. +import test from "node:test"; +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import { readConfig } from "../src/config.js"; +import { createConnections } from "../src/connections.js"; +import { readCatalog, seedCatalog } from "../src/catalog.js"; +import { SearchModel, SEARCH_MODEL } from "../src/search-model.js"; +import { readSearchBundle } from "../src/search-bundle.js"; +import { SearchStore, SEARCH_COLLECTION, SEARCH_META, SEARCH_OWNER, SEARCH_INDEX, hash } from "../src/search-store.js"; +import { createSearch } from "../src/search.js"; +import { createApp } from "../src/server.js"; +import * as repository from "../examples/complete/repository.js"; + +test("real precomputed bundle + query model + DocumentDB: owned import, zero document embeds, index, query, filters and safe rejection", { timeout: 600000 }, async (t) => { + const name = `search_verify_${randomUUID().replaceAll("-", "")}`; + const config = readConfig({ ...process.env, SEARCH_ENABLED: "1", ACTIVE_TARGET: "local", LOCAL_DATABASE_NAME: name }); + const connections = createConnections(config); + let db; + let owned = false; + let app; + t.after(async () => { + try { if (owned) await db.dropDatabase(); } + finally { if (app) await app.close(); else await connections.close(); } + }); + db = await connections.db("local"); + assert.equal(await db.listCollections({}, { nameOnly: true }).hasNext(), false, "never adopt an existing test database"); + await db.createCollection("integration_ownership"); + owned = true; + const catalog = await readCatalog(); + const bundle = await readSearchBundle(catalog); + assert.equal(bundle.version, "ato-session-embeddings-v1"); + assert.equal(bundle.rows.size, 216); + const bundleInfo = { version: bundle.version, digest: bundle.digest, dataDigest: bundle.dataDigest }; + const realModel = new SearchModel(); + const calls = { verify: 0, documents: 0, queries: [] }; + const preparationModel = { + async verify() { calls.verify += 1; return realModel.verify(); }, + async embed() { calls.documents += 1; assert.fail("bundle preparation and self-probes must never invoke model.embed"); }, + }; + const queryModel = { + verify: () => realModel.verify(), + async embed(texts, signal) { + assert.equal(texts.length, 1, "each semantic query embeds exactly one query string"); + assert.match(texts[0], /^search_query: /); + calls.queries.push([...texts]); + return realModel.embed(texts, signal); + }, + }; + assert.equal((await realModel.verify()).digest, SEARCH_MODEL.digest); + const service = createSearch({ config, connections, model: queryModel }); + assert.equal((await service.status("local")).code, "CATALOG_NOT_SEEDED"); + await seedCatalog(db, catalog); + await repository.saveFavorite(db, catalog.sessions[0].id); + const snapshot = async () => hash({ + sessions: await db.collection("sessions").find({}).sort({ _id: 1 }).toArray(), + favorites: await db.collection("favorites").find({}).sort({ _id: 1 }).toArray(), + catalog: await db.collection("workshop_meta").find({}).sort({ _id: 1 }).toArray(), + }); + const before = await snapshot(); + assert.equal((await service.status("local")).code, "SEARCH_NOT_PREPARED"); + const store = new SearchStore(db, catalog); + assert.deepEqual(await store.prepare(preparationModel, () => {}), { + count: 216, reused: false, model: SEARCH_MODEL, bundle: bundleInfo, documentEmbeddingCalls: 0, + }); + assert.deepEqual(await store.prepare(preparationModel, () => {}), { + count: 216, reused: true, model: SEARCH_MODEL, bundle: bundleInfo, documentEmbeddingCalls: 0, + }); + assert.equal(calls.verify, 2); + assert.equal(calls.documents, 0); + assert.deepEqual(calls.queries, []); + const imported = await db.collection(SEARCH_COLLECTION).find({}).toArray(); + assert.equal(imported.length, bundle.rows.size); + for (const row of imported) { + const authoritative = bundle.rows.get(row._id); + assert.ok(authoritative, "every imported row belongs to the real bundle"); + for (const key of ["sourceHash", "textHash", "vectorHash"]) assert.equal(row[key], authoritative[key]); + assert.deepEqual(row.embedding, authoritative.embedding); + assert.equal(hash(row.embedding), authoritative.vectorHash); + assert.equal(row.bundleVersion, bundle.version); + assert.equal(row.bundleDigest, bundle.digest); + } + assert.equal(await snapshot(), before, "search preparation must not change canonical catalog, metadata or favorites"); + assert.equal((await service.status("local")).ready, true); + const marker = await store.marker(); + assert.equal(marker.ready, true); + assert.equal(marker.bundleVersion, bundle.version); + assert.equal(marker.bundleDigest, bundle.digest); + await store.ready({ full: true }); + const query = await service.query("local", { query: "running AI locally", limit: 5 }); + assert.deepEqual(calls.queries, [["search_query: running AI locally"]], "the actual query invokes model.embed exactly once; import invoked it zero times"); + assert.equal(calls.documents, 0); + assert.ok(query.results.length > 0); + assert.equal(query.inspector.candidates, 216); + assert.equal(query.inspector.pipeline[0].$search.cosmosSearch.k, 216); + assert.equal(query.inspector.pipeline[0].$search.cosmosSearch.vector, "[768 numeric values omitted]"); + assert.equal(query.inspector.model.digest, SEARCH_MODEL.digest); + assert.ok(query.results.every((result) => catalog.sessions.some((session) => session.id === result.session.id))); + const session = query.results[0].session; + const filtered = await service.query("local", { query: "running AI locally", track: session.track, limit: 10 }); + assert.equal(calls.queries.length, 2, "a repeated filtered query gets its own single query embedding"); + assert.ok(filtered.results.length); + assert.ok(filtered.results.every((result) => result.session.track === session.track)); + assert.deepEqual(filtered.inspector.pipeline[2], { $match: { track: session.track } }); + await assert.rejects(service.query("local", { query: "AI", track: { $ne: "" } }), { code: "SEARCH_FILTER_INVALID" }); + for (const text of ["sourdough bread baking recipes", "penguin veterinary surgery in Antarctica"]) { + const unrelated = await service.query("local", { query: text }); + console.log(JSON.stringify({ probe: text, results: unrelated.results.map((result) => ({ title: result.session.title, similarity: result.similarity })) })); + assert.equal(unrelated.results.length, 0, "these sampled unrelated queries should have no accepted matches; not a universal guarantee"); + } + // Owned test-only marker corruption is restored before any later assertion. + await db.collection(SEARCH_META).updateOne({ _id: SEARCH_OWNER }, { $set: { modelDigest: "0".repeat(64) } }); + try { + await assert.rejects(store.prepare(preparationModel, () => {}), { code: "SEARCH_SNAPSHOT_MISMATCH" }); + assert.equal((await service.status("local")).ready, false); + } finally { await db.collection(SEARCH_META).replaceOne({ _id: SEARCH_OWNER }, marker); } + for (const mutation of [ + { $unset: { bundleVersion: "", bundleDigest: "" } }, + { $set: { bundleVersion: "legacy-generated-vectors" } }, + { $set: { bundleDigest: "0".repeat(64) } }, + ]) { + await db.collection(SEARCH_META).updateOne({ _id: SEARCH_OWNER }, mutation); + try { + const incompatible = await store.marker(); + await assert.rejects(store.ready({ full: true }), { code: "SEARCH_SNAPSHOT_MISMATCH" }); + await assert.rejects(store.prepare(preparationModel, () => {}), { code: "SEARCH_SNAPSHOT_MISMATCH" }); + assert.deepEqual(await store.marker(), incompatible, "legacy/mismatched markers are never silently adopted or replaced"); + assert.equal(await db.collection(SEARCH_COLLECTION).countDocuments({}), 216); + assert.equal(await snapshot(), before); + } finally { await db.collection(SEARCH_META).replaceOne({ _id: SEARCH_OWNER }, marker); } + } + const row = await db.collection(SEARCH_COLLECTION).findOne({ _id: catalog.sessions[0].id }); + // A different REAL bundle vector has a valid norm and matching self-hash, but + // it is not authoritative for this ID. Never synthesize integration vectors. + const other = [...bundle.rows.values()].find((candidate) => candidate.vectorHash !== row.vectorHash); + assert.ok(other, "the real catalog contains distinct embeddings"); + for (const mutation of [ + { $set: { vectorHash: "invalid" } }, + { $set: { embedding: other.embedding, vectorHash: other.vectorHash } }, + { $unset: { bundleVersion: "", bundleDigest: "" } }, + ]) { + await db.collection(SEARCH_COLLECTION).updateOne({ _id: row._id }, mutation); + try { + const incompatible = await db.collection(SEARCH_COLLECTION).findOne({ _id: row._id }); + await assert.rejects(store.ready({ full: true }), { code: "SEARCH_SNAPSHOT_MISMATCH" }); + await assert.rejects(store.prepare(preparationModel, () => {}), { code: "SEARCH_SNAPSHOT_MISMATCH" }); + assert.deepEqual(await db.collection(SEARCH_COLLECTION).findOne({ _id: row._id }), incompatible, "drift is not repaired by overwriting stored vectors"); + } finally { await db.collection(SEARCH_COLLECTION).replaceOne({ _id: row._id }, row); } + } + await db.collection(SEARCH_COLLECTION).dropIndex(SEARCH_INDEX.name); + try { await assert.rejects(service.query("local", { query: "local AI" }), { code: "SEARCH_INDEX_MISMATCH" }); } + finally { await db.command({ createIndexes: SEARCH_COLLECTION, indexes: [SEARCH_INDEX] }); } + const cancelled = new AbortController(); + cancelled.abort(); + await assert.rejects(service.query("local", { query: "local AI" }, cancelled.signal), { code: "SEARCH_CANCELLED" }); + assert.ok((await service.query("local", { query: "local AI" })).results.length, "cancel does not permanently poison readiness"); + assert.equal(await snapshot(), before); + + app = await createApp({ config, connections, repository, logger: { error() {} } }); + await new Promise((resolve) => app.server.listen(0, "127.0.0.1", resolve)); + const origin = `http://127.0.0.1:${app.server.address().port}`; + const details = await fetch(`${origin}/api/config`).then((response) => response.json()); + const response = await fetch(`${origin}/api/search`, { method: "POST", headers: { "Content-Type": "application/json", "X-Workshop-Token": details.csrfToken }, body: JSON.stringify({ target: "local", query: "securing software supply chains", limit: 5 }) }); + assert.equal(response.status, 200); + const result = await response.json(); + assert.ok(result.results.length); + assert.equal(result.inspector.status, "executed"); + assert.equal(result.target, "local"); + assert.equal(calls.documents, 0); + assert.equal(await snapshot(), before); + console.log(JSON.stringify({ liveHttp: true, top: result.results.map((row) => ({ title: row.session.title, similarity: row.similarity })), model: SEARCH_MODEL.name, count: result.inspector.candidates, bundle: bundleInfo, documentEmbeddingCalls: calls.documents, observedDirectQueryEmbeddingCalls: calls.queries.length })); +}); diff --git a/test/search.test.js b/test/search.test.js new file mode 100644 index 0000000..54c0131 --- /dev/null +++ b/test/search.test.js @@ -0,0 +1,804 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { validateCatalog } from "../src/catalog.js"; +import { WorkshopError } from "../src/errors.js"; +import { checkedVector, MODEL_BATCH, MODEL_MAX_BYTES, MODEL_URL, SEARCH_MODEL, SearchModel } from "../src/search-model.js"; +import { + documentText, hash, SEARCH_COLLECTION, SEARCH_INDEX, SEARCH_META, SEARCH_OWNER, + SearchStore, searchFields, TEXT_VERSION, validateIndex, validateMarker, validateRow, vectorPipeline, +} from "../src/search-store.js"; +import { availableFilters, createSearch, SIMILARITY_CUTOFF, validateSearchInput } from "../src/search.js"; + +// Entirely offline contract tests. The in-memory adapter below is NOT a vector engine: +// it returns explicit synthetic scores and only models the collection operations used +// by SearchStore. These tests are not live DocumentDB/model or retrieval-quality proof. +const catalog = validateCatalog({ + kind: "practice", title: "Synthetic semantic-search fixture", timeZone: "America/New_York", + version: "search-test-v1", source: "Fictional offline unit-test data", snapshotDate: "2026-10-18", + sessions: Array.from({ length: 6 }, (_, n) => ({ + id: `session-${n + 1}`, title: `Synthetic topic ${n + 1}`, room: `Room ${n + 1}`, + track: n % 2 ? "Databases" : "Community", + startsAt: `2026-10-${19 + Math.floor(n / 3)}T13:00:00Z`, + endsAt: `2026-10-${19 + Math.floor(n / 3)}T14:00:00Z`, + url: `https://example.invalid/sessions/${n + 1}`, + })), +}); +const clone = (value) => structuredClone(value); +const unitVector = (axis = 0) => Array.from({ length: 768 }, (_, n) => Number(n === axis)); +const code = (expected) => (error) => { + assert.ok(error instanceof WorkshopError); + assert.equal(error.code, expected); + return true; +}; +const deferred = () => { + let resolve; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +}; +const pinnedTags = (changes = {}) => ({ models: [{ name: SEARCH_MODEL.name, digest: SEARCH_MODEL.digest, size: 274_000_000, ...changes }] }); +const jsonResponse = (body, status = 200) => new Response(JSON.stringify(body), { status, headers: { "Content-Type": "application/json" } }); +const bundleInfo = Object.freeze({ + version: "ato-session-embeddings-v1", digest: "b".repeat(64), dataDigest: "c".repeat(64), +}); +// This loader is deliberately synthetic and used only by offline contract tests. +// Integration tests use readSearchBundle and the shipped real catalog vectors. +const bundleFor = (source = catalog) => ({ + ...bundleInfo, + rows: new Map(source.sessions.map((session) => { + const { sourceHash, textHash } = searchFields(session, source); + const embedding = unitVector(); + return [session.id, { id: session.id, sourceHash, textHash, embedding, vectorHash: hash(embedding) }]; + })), + manifest: { version: bundleInfo.version, catalogFingerprint: source.fingerprint, count: source.sessions.length, dataDigest: bundleInfo.dataDigest }, +}); +const fakeBundleLoader = async (source) => bundleFor(source); +const storeFor = (db, source = catalog, bundleLoader = fakeBundleLoader) => new SearchStore(db, source, { bundleLoader }); +const markerFor = (changes = {}, source = catalog) => ({ + _id: SEARCH_OWNER, owner: SEARCH_OWNER, fingerprint: source.fingerprint, + modelDigest: SEARCH_MODEL.digest, dimensions: 768, schemaVersion: 1, + textVersion: TEXT_VERSION, count: source.sessions.length, ready: true, + bundleVersion: bundleInfo.version, bundleDigest: bundleInfo.digest, + readyAt: "2026-10-18T00:00:00.000Z", ...changes, +}); +const rowFor = (session, source = catalog) => { + const { id, ...fields } = searchFields(session, source); + const embedding = unitVector(); + return { _id: id, ...fields, embedding, vectorHash: hash(embedding), bundleVersion: bundleInfo.version, bundleDigest: bundleInfo.digest }; +}; + +function fakeDatabase({ prepared = true, source = catalog } = {}) { + const { sessions, ...metadata } = source; + const state = { + collections: new Map([ + ["workshop_meta", [{ _id: "catalog", ...metadata, ready: true }]], + ["sessions", sessions.map(({ id, ...fields }) => ({ _id: id, ...fields, catalogVersion: source.fingerprint, schemaVersion: 1 }))], + ["favorites", [{ _id: sessions[0].id, savedAt: "2026-10-18T00:00:00.000Z" }]], + ]), + indexes: prepared ? [clone(SEARCH_INDEX)] : [], writes: [], aggregates: [], reads: [], + scores: new Map(sessions.map((session, n) => [session.id, [0.95, 0.7, SIMILARITY_CUTOFF, SIMILARITY_CUTOFF - 0.001, -0.2, 0.7][n]])), + aggregateHook: undefined, bulkWriteHook: undefined, readError: undefined, + }; + if (prepared) { + state.collections.set(SEARCH_META, [markerFor({}, source)]); + state.collections.set(SEARCH_COLLECTION, sessions.map((session) => rowFor(session, source))); + } + const matches = (row, filter) => Object.entries(filter).every(([key, value]) => { + if (value && typeof value === "object" && "$lt" in value) return row[key] < value.$lt; + return row[key] === value; + }); + const recordWrite = (name, operation, value) => { + assert.ok([SEARCH_COLLECTION, SEARCH_META].includes(name), `Canonical collection ${name} must never be mutated by search`); + state.writes.push({ name, operation, value: clone(value) }); + }; + const docs = (name) => state.collections.get(name) || []; + const writable = (name) => { + if (!state.collections.has(name)) state.collections.set(name, []); + return docs(name); + }; + const db = { + collection(name) { + return { + async findOne(filter) { + state.reads.push({ name, operation: "findOne" }); + return clone(docs(name).find((row) => matches(row, filter)) || null); + }, + find(filter) { + let limit = Infinity; + const cursor = { + limit(value) { limit = value; return cursor; }, + async toArray() { + state.reads.push({ name, operation: "find" }); + return clone(docs(name).filter((row) => matches(row, filter)).slice(0, limit)); + }, + }; + return cursor; + }, + async countDocuments(filter) { + if (state.readError) throw state.readError; + return docs(name).filter((row) => matches(row, filter)).length; + }, + listIndexes() { return { toArray: async () => clone(state.indexes) }; }, + aggregate(pipeline, options) { + state.aggregates.push({ pipeline: clone(pipeline), options }); + return { async toArray() { + if (state.aggregateHook) return state.aggregateHook(pipeline, options); + const filter = pipeline.find((stage) => stage.$match)?.$match || {}; + return docs(name).filter((row) => matches(row, filter)).map((row) => { + const { embedding, ...projected } = clone(row); + return { ...projected, similarity: state.scores.get(row._id) }; + }); + } }; + }, + async insertOne(document) { + recordWrite(name, "insertOne", document); + assert.ok(!docs(name).some((row) => row._id === document._id)); + writable(name).push(clone(document)); + return { insertedId: document._id }; + }, + async updateOne(filter, update) { + recordWrite(name, "updateOne", { filter, update }); + const row = docs(name).find((candidate) => matches(candidate, filter)); + if (!row) return { matchedCount: 0 }; + Object.assign(row, clone(update.$set || {})); + for (const key of Object.keys(update.$unset || {})) delete row[key]; + return { matchedCount: 1 }; + }, + async bulkWrite(operations, options) { + recordWrite(name, "bulkWrite", { operations, options }); + if (state.bulkWriteHook) await state.bulkWriteHook(operations, options); + for (const { updateOne: operation } of operations) { + assert.deepEqual(Object.keys(operation.update), ["$setOnInsert"]); + assert.equal(operation.upsert, true); + if (!docs(name).some((row) => matches(row, operation.filter))) { + writable(name).push({ ...clone(operation.filter), ...clone(operation.update.$setOnInsert) }); + } + } + return { ok: 1 }; + }, + }; + }, + listCollections() { return { toArray: async () => [...state.collections.keys()].map((name) => ({ name })) }; }, + async createCollection(name) { + recordWrite(name, "createCollection", {}); + if (state.collections.has(name)) throw new Error("NamespaceExists"); + state.collections.set(name, []); + }, + async command(command) { + recordWrite(command.createIndexes, "command", command); + assert.deepEqual(command, { createIndexes: SEARCH_COLLECTION, indexes: [SEARCH_INDEX] }); + state.indexes.push(...clone(command.indexes)); + return { ok: 1 }; + }, + }; + return { db, state }; +} + +function searchFixture({ enabled = true, model, database = fakeDatabase(), catalogLoader = async () => catalog, bundleLoader = fakeBundleLoader } = {}) { + const targets = []; + const calls = { verify: 0, embed: [] }; + const defaultModel = { + async verify() { calls.verify += 1; return SEARCH_MODEL; }, + async embed(texts) { calls.embed.push(clone(texts)); return texts.map(() => unitVector()); }, + }; + const search = createSearch({ + config: { searchEnabled: enabled, targets: { local: { database: "offline_a" }, "site-b": { database: "offline_b" } } }, + connections: { async db(target) { targets.push(target); return database.db; } }, + model: model || defaultModel, catalogLoader, bundleLoader, + }); + return { search, targets, calls, ...database }; +} + +function canonicalSnapshot(state) { + return ["sessions", "favorites", "workshop_meta"].map((name) => [name, clone(state.collections.get(name))]); +} + +test("embeddings must be finite, unit-normalized, dense 768-element numeric arrays", () => { + const valid = unitVector(); + assert.equal(checkedVector(valid), valid); + assert.doesNotThrow(() => checkedVector(Array(768).fill(1 / Math.sqrt(768)))); + const sparse = Array(768); sparse[0] = 1; + for (const vector of [ + null, new Float32Array(768), [], valid.slice(1), [...valid, 0], Array(768).fill(0), + [2, ...valid.slice(1)], [NaN, ...valid.slice(1)], [Infinity, ...valid.slice(1)], + [-Infinity, ...valid.slice(1)], ["1", ...valid.slice(1)], [null, ...valid.slice(1)], sparse, + ]) assert.throws(() => checkedVector(vector), code("SEARCH_VECTOR_INVALID"), `reject ${Array.isArray(vector) && Object.keys(vector).length !== vector.length ? "sparse embedding" : "invalid embedding"}`); +}); + +test("model pin verification rejects changed digest/name/size and permits the exact sha256 pin", async () => { + for (const data of [ + { models: [] }, pinnedTags({ digest: "f".repeat(64) }), pinnedTags({ name: "other-model:latest" }), + pinnedTags({ size: MODEL_MAX_BYTES + 1 }), pinnedTags({ size: 0 }), pinnedTags({ size: -1 }), pinnedTags({ size: null }), pinnedTags({ size: "274000000" }), + ]) { + const calls = []; + const model = new SearchModel({ fetchImpl: async (url) => { calls.push(url); return jsonResponse(data); } }); + await assert.rejects(model.embed(["search_query: vector databases"]), code("SEARCH_MODEL_MISMATCH")); + assert.deepEqual(calls, [`${MODEL_URL}/api/tags`]); + assert.equal(model.busy, false); + } + const model = new SearchModel({ fetchImpl: async () => jsonResponse(pinnedTags({ digest: `sha256:${SEARCH_MODEL.digest}` })) }); + assert.equal(await model.verify(), SEARCH_MODEL); +}); + +test("the model service address and API operations cannot be redirected to URLs or generation", async () => { + let calls = 0; + for (const url of ["http://169.254.169.254/latest/meta-data", "http://localhost:11434", "https://evil.invalid", `${MODEL_URL}/`, `${MODEL_URL}@evil.invalid`]) { + assert.throws(() => new SearchModel({ url, fetchImpl: async () => { calls += 1; } }), code("SEARCH_CONFIGURATION")); + } + const model = new SearchModel({ fetchImpl: async () => { calls += 1; } }); + for (const path of ["/api/generate", "/api/chat", "/api/pull", "http://evil.invalid/api/embeddings", "/api/embeddings?url=http://evil.invalid"]) { + await assert.rejects(model.call(path, {}), /Unsupported search model operation/); + } + assert.equal(calls, 0); +}); + +test("embedding uses only fixed tags/embeddings endpoints, explicit prefixes, bounded CPU settings, and no generation", async () => { + const calls = []; + let axis = 0; + const model = new SearchModel({ fetchImpl: async (url, options) => { + calls.push({ url, options }); + // The pinned runtime's single-prompt API returns raw vectors; the adapter + // normalizes each one before it can reach the store/query pipeline. + return jsonResponse(url.endsWith("/api/tags") ? pinnedTags() : { embedding: unitVector(axis++).map((n) => n * 3) }); + } }); + const texts = [documentText(catalog.sessions[0]), "search_query: a topic"]; + assert.deepEqual(await model.embed(texts), [unitVector(), unitVector(1)]); + assert.deepEqual(calls.map(({ url }) => url), [`${MODEL_URL}/api/tags`, `${MODEL_URL}/api/embeddings`, `${MODEL_URL}/api/embeddings`]); + assert.equal(calls[0].options.method, "GET"); + assert.equal(calls[0].options.body, undefined); + for (const [n, { options: request }] of calls.slice(1).entries()) { + assert.equal(request.method, "POST"); + assert.equal(request.redirect, "error"); + assert.ok(request.signal instanceof AbortSignal); + assert.deepEqual(JSON.parse(request.body), { + model: SEARCH_MODEL.name, prompt: texts[n], keep_alive: "2m", + options: { num_thread: 2, num_ctx: 2048, num_gpu: 0 }, + }); + } + assert.ok(calls.every(({ url, options }) => new URL(url).origin === MODEL_URL && options.redirect === "error")); +}); + +test("unprefixed, unbounded, or malformed embedding requests never reach fetch", async () => { + let calls = 0; + const model = new SearchModel({ fetchImpl: async () => { calls += 1; } }); + for (const texts of [undefined, [], "search_query: x", [null], ["x"], ["search_query:x"], ["search_document: " + "x".repeat(3000)], Array(MODEL_BATCH + 1).fill("search_query: x")]) { + await assert.rejects(model.embed(texts), code("SEARCH_EMBED_INPUT")); + } + assert.equal(calls, 0); +}); + +test("malformed model responses and outage details are rejected without exposing upstream secrets", async () => { + const secret = "mongodb://private-user:private-password@private-host.invalid/db"; + for (const response of [ + () => jsonResponse({ embedding: [] }), () => jsonResponse({ embedding: Array(768).fill(0) }), + () => jsonResponse({ embeddings: [unitVector(), unitVector()] }), + () => jsonResponse({ embedding: [null, ...unitVector().slice(1)] }), + () => jsonResponse({ embedding: ["1", ...unitVector().slice(1)] }), + () => jsonResponse({ error: secret }), () => new Response(secret, { status: 500 }), + () => new Response("not JSON"), () => new Response("x".repeat(256_001)), + () => { throw new Error(secret); }, + ]) { + const model = new SearchModel({ fetchImpl: async (url) => url.endsWith("/api/tags") ? jsonResponse(pinnedTags()) : response() }); + await assert.rejects(model.embed(["search_query: x"]), (error) => { + assert.ok(error instanceof WorkshopError); + assert.doesNotMatch(error.message, /private-user|private-password|private-host|mongodb:\/\//); + return true; + }); + assert.equal(model.busy, false); + } +}); + +test("model cancellation releases its one-request lock and permits a fresh retry", { timeout: 5000 }, async () => { + const entered = deferred(); + let block = true; + let embeddings = 0; + const model = new SearchModel({ fetchImpl: async (url, options) => { + if (url.endsWith("/api/tags")) return jsonResponse(pinnedTags()); + embeddings += 1; + if (!block) return jsonResponse({ embedding: unitVector() }); + entered.resolve(); + return new Promise((_resolve, reject) => options.signal.addEventListener("abort", () => reject(options.signal.reason), { once: true })); + } }); + const controller = new AbortController(); + const pending = model.embed(["search_query: first"], controller.signal); + await entered.promise; + await assert.rejects(model.embed(["search_query: second"]), code("SEARCH_BUSY")); + assert.equal(embeddings, 1); + const cancelled = assert.rejects(pending, code("SEARCH_CANCELLED")); + controller.abort(); + await cancelled; + assert.equal(model.busy, false); + block = false; + assert.deepEqual(await model.embed(["search_query: retry"]), [unitVector()]); + assert.equal(embeddings, 2); +}); + +test("search input has a 500-character bound, a 1–10 limit, and catalog-only explicit filters", () => { + assert.deepEqual(validateSearchInput({ target: "local", query: ` ${"x".repeat(498)} `, limit: 10 }, catalog), { query: "x".repeat(498), limit: 10, filters: {} }); + assert.equal(validateSearchInput({ query: "x".repeat(500), limit: 1 }, catalog).query.length, 500); + assert.equal(validateSearchInput({ query: "x" }, catalog).limit, 5); + for (const data of [null, [], "x", {}, { query: "" }, { query: " " }, { query: 1 }, { query: "x".repeat(501) }, ...["\n", "\r", "\t", "\0", "\u007f"].map((control) => ({ query: `x${control}y` }))]) { + assert.throws(() => validateSearchInput(data, catalog), code("SEARCH_INPUT_INVALID")); + } + for (const limit of [0, -1, 11, 1.5, "5", Infinity, NaN, {}, true]) { + assert.throws(() => validateSearchInput({ query: "x", limit }, catalog), code("SEARCH_LIMIT_INVALID")); + } + const options = availableFilters(catalog); + assert.deepEqual(options, { days: ["2026-10-19", "2026-10-20"], tracks: ["Community", "Databases"] }); + assert.deepEqual(validateSearchInput({ query: "x", day: options.days[0], track: options.tracks[0] }, catalog).filters, { day: options.days[0], track: options.tracks[0] }); + assert.deepEqual(validateSearchInput({ query: "Tuesday database talks", day: "", track: "" }, catalog).filters, {}, "prompt words must not silently become filters"); + for (const data of [{ day: "2026-10-21" }, { track: "databases" }, { day: { $ne: null } }, { track: ["Community"] }, { day: null }]) { + assert.throws(() => validateSearchInput({ query: "x", ...data }, catalog), code("SEARCH_FILTER_INVALID")); + } +}); + +test("unknown fields and request-selected URL/model/pipeline options are rejected rather than used", () => { + for (const key of ["url", "modelUrl", "baseURL", "model", "digest", "dimensions", "filters", "pipeline", "embedding", "$where", "messages", "history", "temperature"]) { + assert.throws(() => validateSearchInput({ query: "x", [key]: "http://169.254.169.254/latest/meta-data" }, catalog), code("SEARCH_INPUT_INVALID")); + } +}); + +test("document text is title/track metadata only and the real pipeline encodes full-catalog post-filtering", () => { + assert.equal(documentText(catalog.sessions[0]), "search_document: Synthetic topic 1\nTrack: Community"); + assert.doesNotMatch(documentText(catalog.sessions[0]), /Room|https:|2026/); + const vector = unitVector(); + const filters = { day: "2026-10-19", track: "Community" }; + const pipeline = vectorPipeline(vector, catalog.sessions.length, filters); + assert.deepEqual(pipeline, [ + { $search: { cosmosSearch: { vector, path: "embedding", k: 6 }, returnStoredSource: true } }, + { $addFields: { similarity: { $meta: "searchScore" } } }, + { $match: filters }, + { $project: { embedding: 0, __cosmos_meta__: 0 } }, + ]); + assert.equal(pipeline[0].$search.cosmosSearch.vector.length, SEARCH_INDEX.cosmosSearchOptions.dimensions); + assert.deepEqual(SEARCH_INDEX.cosmosSearchOptions, { kind: "vector-ivf", numLists: 1, similarity: "COS", dimensions: 768 }); + assert.equal(vectorPipeline(vector, 6).some((stage) => stage.$match), false); + assert.doesNotMatch(JSON.stringify(pipeline), /\$vectorSearch|knnBeta|compound/); +}); + +test("ownership markers reject foreign owners, snapshots, model pins, dimensions, counts, and schemas", () => { + assert.equal(validateMarker(markerFor(), catalog, bundleFor()).owner, SEARCH_OWNER); + assert.throws(() => validateMarker(null, catalog, bundleFor()), code("SEARCH_NOT_PREPARED")); + for (const changes of [ + { owner: "another-owner" }, { fingerprint: "different" }, { modelDigest: "different" }, + { dimensions: 1536 }, { textVersion: TEXT_VERSION + 1 }, { schemaVersion: 2 }, { count: 5 }, + { bundleVersion: undefined }, { bundleDigest: undefined }, { bundleVersion: "different" }, { bundleDigest: "d".repeat(64) }, + ]) assert.throws(() => validateMarker(markerFor(changes), catalog, bundleFor()), code("SEARCH_SNAPSHOT_MISMATCH")); +}); + +test("stored metadata, source/text/vector hashes, model identity, and index definition must agree", () => { + const session = catalog.sessions[0]; + const row = rowFor(session); + const store = storeFor(fakeDatabase().db); + const bundle = bundleFor(); + assert.doesNotThrow(() => validateRow(row, session, catalog, true)); + assert.doesNotThrow(() => store.validateBundledRow(row, bundle, true)); + for (const changes of [ + { title: "Changed" }, { room: "Changed" }, { url: "https://example.invalid/changed" }, { sourceHash: "wrong" }, + { textHash: "wrong" }, { modelDigest: "wrong" }, { textVersion: 2 }, { schemaVersion: 2 }, + { day: "2026-10-21" }, { vectorHash: "wrong" }, { embedding: unitVector(1) }, + { bundleVersion: undefined }, { bundleDigest: undefined }, { bundleVersion: "different" }, { bundleDigest: "d".repeat(64) }, + { embedding: unitVector(1), vectorHash: hash(unitVector(1)) }, + ]) assert.throws(() => store.validateBundledRow({ ...row, ...changes }, bundle, true), code("SEARCH_SNAPSHOT_MISMATCH")); + assert.throws(() => validateRow(row, undefined, catalog, true), code("SEARCH_SNAPSHOT_MISMATCH")); + assert.throws(() => store.validateBundledRow({ ...row, embedding: Array(768).fill(0) }, bundle, true), code("SEARCH_VECTOR_INVALID")); + assert.doesNotThrow(() => validateIndex(clone(SEARCH_INDEX))); + for (const index of [ + null, { ...SEARCH_INDEX, key: { other: "cosmosSearch" } }, { ...SEARCH_INDEX, key: { embedding: 1 } }, + ...[{ kind: "vector-hnsw" }, { numLists: 2 }, { similarity: "IP" }, { dimensions: 767 }].map((change) => ({ ...SEARCH_INDEX, cosmosSearchOptions: { ...SEARCH_INDEX.cosmosSearchOptions, ...change } })), + ]) assert.throws(() => validateIndex(index), code("SEARCH_INDEX_MISMATCH")); +}); + +test("readiness rejects missing, duplicate, extra, corrupted, or wrong-catalog rows without creating an index", async () => { + const cases = [ + (state) => state.collections.get(SEARCH_COLLECTION).pop(), + (state) => state.collections.get(SEARCH_COLLECTION).push(rowFor(catalog.sessions[0])), + (state) => { state.collections.get(SEARCH_COLLECTION)[1] = rowFor(catalog.sessions[0]); }, + (state) => { state.collections.get(SEARCH_COLLECTION)[0].sourceHash = "changed"; }, + (state) => { state.collections.get(SEARCH_COLLECTION)[0].vectorHash = "changed"; }, + (state) => { delete state.collections.get(SEARCH_COLLECTION)[0].bundleVersion; }, + (state) => { state.collections.get(SEARCH_COLLECTION)[0].bundleDigest = "d".repeat(64); }, + (state) => { state.collections.get("workshop_meta")[0].fingerprint = "different-canonical-catalog"; }, + ]; + for (const mutate of cases) { + const { db, state } = fakeDatabase(); mutate(state); + await assert.rejects(storeFor(db).ready({ full: true }), code("SEARCH_SNAPSHOT_MISMATCH")); + assert.equal(state.writes.length, 0); + } + const { db, state } = fakeDatabase(); state.indexes = []; + await assert.rejects(storeFor(db).ready(), code("SEARCH_INDEX_MISMATCH")); + assert.equal(state.writes.length, 0); + state.indexes = [clone(SEARCH_INDEX), { ...clone(SEARCH_INDEX), name: "ambiguous_second_vector_index" }]; + await assert.rejects(storeFor(db).ready(), code("SEARCH_INDEX_MISMATCH")); + assert.equal(state.writes.length, 0); +}); + +test("preparation refuses unowned search namespaces and incompatible ownership without mutation", async () => { + const model = { verify: async () => SEARCH_MODEL, embed: async () => assert.fail("must not embed") }; + for (const existing of [SEARCH_COLLECTION, SEARCH_META]) { + const { db, state } = fakeDatabase({ prepared: false }); + state.collections.set(existing, []); + const before = clone([...state.collections]); + await assert.rejects(storeFor(db).prepare(model, () => {}), code("SEARCH_UNOWNED")); + assert.deepEqual([...state.collections], before); + assert.equal(state.writes.length, 0); + } + for (const changes of [{ owner: "foreign" }, { fingerprint: "foreign" }, { modelDigest: "foreign" }, { count: 99 }]) { + const { db, state } = fakeDatabase(); + Object.assign(state.collections.get(SEARCH_META)[0], changes); + const before = clone([...state.collections]); + await assert.rejects(storeFor(db).prepare(model, () => {}), code("SEARCH_SNAPSHOT_MISMATCH")); + assert.deepEqual([...state.collections], before); + assert.equal(state.writes.length, 0); + } +}); + +test("explicit preparation imports the authoritative bundle, checks stored vectors/index/probe, and never embeds documents", async () => { + const { db, state } = fakeDatabase({ prepared: false }); + const before = canonicalSnapshot(state); + const calls = { verify: 0, embed: 0, bundle: 0 }; + const bundle = bundleFor(); + state.scores.set(catalog.sessions[0].id, 1); // Synthetic self-score; no engine calculation. + const model = { + async verify() { calls.verify += 1; return SEARCH_MODEL; }, + async embed() { calls.embed += 1; assert.fail("preparation must import vectors, never embed documents or the self-probe"); }, + }; + const store = storeFor(db, catalog, async (source) => { calls.bundle += 1; assert.equal(source, catalog); return bundle; }); + const result = await store.prepare(model, () => {}); + assert.deepEqual(result, { count: 6, reused: false, model: SEARCH_MODEL, bundle: bundleInfo, documentEmbeddingCalls: 0 }); + assert.ok(calls.bundle > 0); + assert.equal(calls.verify, 1); + assert.equal(calls.embed, 0); + assert.deepEqual(state.writes.filter(({ operation }) => operation === "bulkWrite").map(({ value }) => value.operations.length), [6]); + assert.deepEqual(canonicalSnapshot(state), before); + assert.ok(state.writes.every(({ name }) => [SEARCH_META, SEARCH_COLLECTION].includes(name))); + assert.deepEqual(state.indexes, [SEARCH_INDEX]); + const marker = state.collections.get(SEARCH_META)[0]; + assert.equal(marker.ready, true); + assert.equal(marker.leaseId, undefined); + assert.equal(marker.bundleVersion, bundleInfo.version); + assert.equal(marker.bundleDigest, bundleInfo.digest); + for (const row of state.collections.get(SEARCH_COLLECTION)) { + store.validateBundledRow(row, bundle, true); + assert.deepEqual(row.embedding, bundle.rows.get(row._id).embedding); + assert.equal(row.vectorHash, bundle.rows.get(row._id).vectorHash); + assert.equal(row.bundleVersion, bundleInfo.version); + assert.equal(row.bundleDigest, bundleInfo.digest); + } + const writes = state.writes.length; + assert.deepEqual(await store.prepare(model, () => {}), { count: 6, reused: true, model: SEARCH_MODEL, bundle: bundleInfo, documentEmbeddingCalls: 0 }); + assert.equal(calls.verify, 2); + assert.equal(calls.embed, 0, "ready snapshots and self-probes must not invoke document embedding"); + assert.equal(state.writes.length, writes); + assert.equal(state.aggregates.length, 2); + assert.ok(state.aggregates.every(({ pipeline }) => pipeline[0].$search.cosmosSearch.k === catalog.sessions.length)); + assert.ok(state.aggregates.every(({ pipeline }) => hash(pipeline[0].$search.cosmosSearch.vector) === bundle.rows.get(catalog.sessions[0].id).vectorHash)); +}); + +test("bundle import uses batches of at most 32 and resumes an interrupted partial import without overwriting rows", async () => { + const source = validateCatalog({ ...catalog, sessions: Array.from({ length: 70 }, (_, n) => ({ + ...catalog.sessions[n % catalog.sessions.length], id: `batch-${String(n + 1).padStart(3, "0")}`, title: `Synthetic batch entry ${n + 1}`, + })) }); + const { db, state } = fakeDatabase({ prepared: false, source }); + const before = canonicalSnapshot(state); + state.scores = new Map(source.sessions.map((session) => [session.id, 1])); + let embeddings = 0; + const model = { verify: async () => SEARCH_MODEL, async embed() { embeddings += 1; assert.fail("import must not embed documents"); } }; + const interrupted = new Error("simulated interrupted bundle import"); + let batches = 0; + state.bulkWriteHook = async () => { if (++batches === 2) throw interrupted; }; + await assert.rejects(storeFor(db, source).prepare(model, () => {}), (error) => error === interrupted); + const present = clone(state.collections.get(SEARCH_COLLECTION)); + assert.equal(present.length, 32); + assert.equal(state.collections.get(SEARCH_META)[0].ready, false); + assert.equal(state.collections.get(SEARCH_META)[0].leaseId, undefined, "failed import releases its lease for explicit retry"); + assert.equal(state.indexes.length, 0); + assert.deepEqual(canonicalSnapshot(state), before); + state.bulkWriteHook = undefined; + const writes = state.writes.length; + const result = await storeFor(db, source).prepare(model, () => {}); + assert.deepEqual(result, { count: 70, reused: false, model: SEARCH_MODEL, bundle: bundleInfo, documentEmbeddingCalls: 0 }); + const resumed = state.writes.slice(writes).filter(({ operation }) => operation === "bulkWrite"); + assert.deepEqual(resumed.map(({ value }) => value.operations.length), [32, 6]); + const preservedIds = new Set(present.map((row) => row._id)); + assert.ok(resumed.every(({ value }) => value.operations.every(({ updateOne }) => !preservedIds.has(updateOne.filter._id)))); + assert.deepEqual(state.collections.get(SEARCH_COLLECTION).filter((row) => preservedIds.has(row._id)), present); + assert.equal(state.collections.get(SEARCH_COLLECTION).length, 70); + assert.equal(state.collections.get(SEARCH_META)[0].ready, true); + assert.equal(embeddings, 0); + assert.deepEqual(canonicalSnapshot(state), before); +}); + +test("a failed bundle validation prevents preparation writes and model calls, then permits an explicit retry", async () => { + const { db, state } = fakeDatabase({ prepared: false }); + state.scores.set(catalog.sessions[0].id, 1); + const before = clone([...state.collections]); + let valid = false; + let loads = 0; + let verifies = 0; + const invalid = new WorkshopError(409, "SEARCH_BUNDLE_INVALID", "The checked-in bundle is invalid."); + const store = storeFor(db, catalog, async (source) => { + loads += 1; + if (!valid) throw invalid; + return bundleFor(source); + }); + const model = { + async verify() { verifies += 1; return SEARCH_MODEL; }, + embed: async () => assert.fail("a missing or invalid bundle must not fall back to generating documents"), + }; + await assert.rejects(store.prepare(model, () => {}), code("SEARCH_BUNDLE_INVALID")); + assert.deepEqual([...state.collections], before); + assert.equal(state.writes.length, 0); + assert.equal(verifies, 0); + valid = true; + assert.equal((await store.prepare(model, () => {})).documentEmbeddingCalls, 0); + assert.equal(loads, 2, "failed bundle validation is not cached"); + assert.equal(verifies, 1); +}); + +test("legacy or different-bundle snapshots are rejected, never adopted, regenerated, or deleted", async () => { + for (const mutate of [ + (marker) => { delete marker.bundleVersion; delete marker.bundleDigest; }, + (marker) => { marker.bundleVersion = "legacy-generated-vectors"; }, + (marker) => { marker.bundleDigest = "d".repeat(64); }, + ]) { + for (const ready of [true, false]) { + const { db, state } = fakeDatabase(); + const marker = state.collections.get(SEARCH_META)[0]; + marker.ready = ready; + marker.leaseUntil = new Date(0); + mutate(marker); + const before = clone([...state.collections]); + const model = { verify: async () => SEARCH_MODEL, embed: async () => assert.fail("mismatches must not regenerate embeddings") }; + await assert.rejects(storeFor(db).ready({ full: true }), code("SEARCH_SNAPSHOT_MISMATCH")); + await assert.rejects(storeFor(db).prepare(model, () => {}), code("SEARCH_SNAPSHOT_MISMATCH")); + assert.deepEqual([...state.collections], before); + assert.equal(state.writes.length, 0); + } + } +}); + +test("readiness and partial-import resume reject self-consistent vectors not present in the authoritative bundle", async () => { + for (const ready of [true, false]) { + const { db, state } = fakeDatabase(); + const marker = state.collections.get(SEARCH_META)[0]; + marker.ready = ready; + marker.leaseUntil = new Date(0); + if (!ready) state.collections.get(SEARCH_COLLECTION).splice(2); + const row = state.collections.get(SEARCH_COLLECTION)[0]; + row.embedding = unitVector(1); + row.vectorHash = hash(row.embedding); // Internally valid, but not the shipped vector. + const before = clone(state.collections.get(SEARCH_COLLECTION)); + const canonical = canonicalSnapshot(state); + if (ready) { + await assert.rejects(storeFor(db).ready({ full: true }), code("SEARCH_SNAPSHOT_MISMATCH")); + assert.equal(state.writes.length, 0); + } + const model = { verify: async () => SEARCH_MODEL, embed: async () => assert.fail("bundle mismatch must not be re-embedded") }; + await assert.rejects(storeFor(db).prepare(model, () => {}), code("SEARCH_SNAPSHOT_MISMATCH")); + assert.deepEqual(state.collections.get(SEARCH_COLLECTION), before); + assert.deepEqual(canonicalSnapshot(state), canonical); + assert.equal(state.writes.filter(({ name }) => name === SEARCH_COLLECTION).length, 0); + } +}); + +test("preparation never repairs drift by overwriting canonical content, vectors, or a conflicting index", async () => { + for (const [mutate, expected] of [ + [(state) => { state.collections.get("sessions")[0].title = "canonical drift"; }, "SEARCH_SNAPSHOT_MISMATCH"], + [(state) => { state.collections.get(SEARCH_COLLECTION)[0].vectorHash = "vector drift"; }, "SEARCH_SNAPSHOT_MISMATCH"], + [(state) => { state.indexes[0].cosmosSearchOptions.dimensions = 12; }, "SEARCH_INDEX_MISMATCH"], + ]) { + const { db, state } = fakeDatabase(); mutate(state); + const before = clone([...state.collections]); const indexes = clone(state.indexes); + const model = { verify: async () => SEARCH_MODEL, embed: async () => assert.fail("must not re-embed drift") }; + await assert.rejects(storeFor(db).prepare(model, () => {}), code(expected)); + assert.deepEqual([...state.collections], before); + assert.deepEqual(state.indexes, indexes); + assert.equal(state.writes.length, 0); + } +}); + +test("disabled status/query need no catalog, database, or model and report explicit unavailability", async () => { + const never = async () => assert.fail("disabled semantic search must not touch dependencies"); + const search = createSearch({ config: { searchEnabled: false, targets: {} }, connections: { db: never }, model: { verify: never, embed: never }, catalogLoader: never, bundleLoader: never }); + const status = await search.status("local"); + assert.equal(status.enabled, false); + assert.equal(status.ready, false); + assert.equal(status.code, "SEARCH_DISABLED"); + await assert.rejects(search.query("local", { query: "topic" }), code("SEARCH_DISABLED")); +}); + +test("status catches and sanitizes database/model errors, and does not cache failed readiness", async () => { + const fixture = searchFixture(); + assert.equal((await fixture.search.status("local")).ready, true); + const error = new Error("mongodb://private-user:private-password@private-host.invalid/db"); + error.name = "MongoServerSelectionError"; + fixture.state.readError = error; + const failed = await fixture.search.status("local"); + assert.equal(failed.ready, false); + assert.equal(failed.code, "DATABASE_UNAVAILABLE"); + assert.doesNotMatch(JSON.stringify(failed), /private-user|private-password|private-host|mongodb:\/\//); + fixture.state.readError = undefined; + fixture.state.collections.get(SEARCH_COLLECTION)[0].vectorHash = "changed after failure"; + assert.equal((await fixture.search.status("local")).code, "SEARCH_SNAPSHOT_MISMATCH", "failed status must invalidate prior full verification"); + const unavailable = searchFixture({ model: { async verify() { throw error; } } }); + assert.equal((await unavailable.search.status("local")).code, "DATABASE_UNAVAILABLE"); + const unknown = searchFixture(); + assert.equal((await unknown.search.status("arbitrary")).code, "TARGET_NOT_CONFIGURED"); + assert.deepEqual(unknown.targets, []); +}); + +test("a failed catalog load is retried rather than retained as a rejected promise", async () => { + let loads = 0; + const fixture = searchFixture({ catalogLoader: async () => { loads += 1; if (loads === 1) throw new Error("private catalog path"); return catalog; } }); + const failure = await fixture.search.status("local"); + assert.equal(failure.code, "INTERNAL_ERROR"); + assert.doesNotMatch(JSON.stringify(failure), /private catalog path/); + assert.equal((await fixture.search.status("local")).ready, true); + assert.equal(loads, 2); +}); + +test("query service retries bundle load failure without embedding, querying, or falling back", async () => { + let loads = 0; + const fixture = searchFixture({ bundleLoader: async (source) => { + loads += 1; + if (loads === 1) throw new WorkshopError(409, "SEARCH_BUNDLE_INVALID", "The checked-in bundle is invalid."); + return bundleFor(source); + } }); + const before = canonicalSnapshot(fixture.state); + await assert.rejects(fixture.search.query("local", { query: "topic" }), code("SEARCH_BUNDLE_INVALID")); + assert.deepEqual(fixture.calls.embed, []); + assert.equal(fixture.state.aggregates.length, 0); + assert.equal(fixture.state.writes.length, 0); + assert.ok((await fixture.search.query("local", { query: "topic" })).results.length); + assert.equal(loads, 2); + assert.deepEqual(fixture.calls.embed, [["search_query: topic"]]); + assert.deepEqual(canonicalSnapshot(fixture.state), before); +}); + +test("search ranks numeric scores with a cutoff/limit, returns source evidence, and shows the executed DocumentDB contract", async () => { + const fixture = searchFixture(); + const result = await fixture.search.query("local", { target: "local", query: " distributed systems ", limit: 3 }); + assert.deepEqual(fixture.calls.embed, [["search_query: distributed systems"]]); + assert.deepEqual(result.results.map(({ session, rank, similarity }) => [session.id, rank, similarity]), [["session-1", 1, 0.95], ["session-2", 2, 0.7], ["session-6", 3, 0.7]]); + for (const item of result.results) { + assert.deepEqual(item.session, catalog.sessions.find((session) => session.id === item.session.id)); + assert.deepEqual(item.evidence, { title: item.session.title, track: item.session.track }); + assert.ok(item.similarity >= SIMILARITY_CUTOFF); + assert.equal(item.session.embedding, undefined); + } + assert.equal(result.inspector.target, "local"); + assert.equal(result.inspector.database, "offline_a"); + assert.equal(result.inspector.collection, SEARCH_COLLECTION); + assert.equal(result.inspector.metadataOnly, true); + assert.equal(result.inspector.candidates, 6); + assert.equal(result.inspector.cutoff, SIMILARITY_CUTOFF); + assert.deepEqual(result.inspector.model, SEARCH_MODEL); + assert.deepEqual(result.inspector.index, SEARCH_INDEX); + assert.equal(result.inspector.pipeline[0].$search.cosmosSearch.vector, "[768 numeric values omitted]"); + assert.equal(fixture.state.aggregates[0].pipeline[0].$search.cosmosSearch.vector.length, 768); + assert.equal(fixture.state.aggregates[0].pipeline[0].$search.cosmosSearch.k, 6, "request limit is not retrieval k"); + assert.equal(fixture.state.aggregates[0].options.maxTimeMS, 10000); + for (const key of ["embeddingMs", "databaseMs", "totalMs"]) assert.ok(Number.isFinite(result.inspector[key]) && result.inspector[key] >= 0); + assert.match(result.inspector.filterStrategy, /not pre-retrieval/); + assert.match(result.inspector.rankingPolicy, /not probabilities/); + assert.equal(fixture.state.writes.length, 0); +}); + +test("explicit day/track post-filters preserve full catalog k and include the exact configured cutoff", async () => { + const fixture = searchFixture(); + const result = await fixture.search.query("local", { query: "topic", limit: 10, day: "2026-10-19", track: "Community" }); + assert.deepEqual(result.results.map(({ session }) => session.id), ["session-1", "session-3"]); + assert.equal(result.results[1].similarity, SIMILARITY_CUTOFF); + assert.equal(result.inspector.candidates, 2); + const pipeline = fixture.state.aggregates[0].pipeline; + assert.equal(pipeline[0].$search.cosmosSearch.k, 6); + assert.deepEqual(pipeline[2], { $match: { day: "2026-10-19", track: "Community" } }); + const empty = await fixture.search.query("local", { query: "topic", day: "2026-10-20", track: "Community" }); + assert.deepEqual(empty.results, []); + assert.match(empty.message, /No strong metadata matches/); +}); + +test("model outage never runs the vector query or substitutes keyword browsing, and retry is not cached", async () => { + let failing = true; + const embeds = []; + const fixture = searchFixture({ model: { + async embed(texts) { + embeds.push(clone(texts)); + if (failing) throw new WorkshopError(503, "SEARCH_MODEL_UNAVAILABLE", "Optional embedding is unavailable."); + return [unitVector()]; + }, + } }); + const before = canonicalSnapshot(fixture.state); + await assert.rejects(fixture.search.query("local", { query: "topic" }), code("SEARCH_MODEL_UNAVAILABLE")); + assert.equal(fixture.state.aggregates.length, 0); + assert.equal(fixture.state.reads.some(({ name }) => ["sessions", "favorites"].includes(name)), false, "no keyword/favorite fallback was read"); + failing = false; + assert.ok((await fixture.search.query("local", { query: "topic" })).results.length > 0); + assert.deepEqual(embeds, [["search_query: topic"], ["search_query: topic"]]); + assert.equal(fixture.state.aggregates.length, 1); + assert.deepEqual(canonicalSnapshot(fixture.state), before); + assert.equal(fixture.state.writes.length, 0); +}); + +test("identical and subsequent queries are independently embedded/queried with no history or result persistence", async () => { + const fixture = searchFixture(); + for (const query of ["first private query", "second private query", "first private query"]) await fixture.search.query("local", { query }); + assert.deepEqual(fixture.calls.embed, [["search_query: first private query"], ["search_query: second private query"], ["search_query: first private query"]]); + assert.equal(fixture.state.aggregates.length, 3); + assert.equal(fixture.state.writes.length, 0); + assert.doesNotMatch(JSON.stringify([...fixture.state.collections]), /private query/); +}); + +test("only one query is allowed across targets; model cancellation releases busy and allows retry", { timeout: 5000 }, async () => { + const entered = deferred(); + let block = true; + let calls = 0; + const fixture = searchFixture({ model: { + async embed(_texts, signal) { + calls += 1; + if (!block) return [unitVector()]; + entered.resolve(); + return new Promise((_resolve, reject) => signal.addEventListener("abort", () => reject(signal.reason), { once: true })); + }, + } }); + const controller = new AbortController(); + const pending = fixture.search.query("local", { query: "first" }, controller.signal); + await entered.promise; + await assert.rejects(fixture.search.query("site-b", { query: "second" }), code("SEARCH_BUSY")); + assert.deepEqual(fixture.targets, ["local"]); + const cancelled = assert.rejects(pending, code("SEARCH_CANCELLED")); + controller.abort(); + await cancelled; + assert.equal(fixture.state.aggregates.length, 0); + block = false; + assert.equal((await fixture.search.query("site-b", { query: "retry" })).target, "site-b"); + assert.equal(calls, 2); +}); + +test("database cancellation propagates its signal, discards results, and releases busy for a new request", { timeout: 5000 }, async () => { + const fixture = searchFixture(); + const entered = deferred(); + const controller = new AbortController(); + fixture.state.aggregateHook = async (_pipeline, options) => { + assert.equal(options.signal, controller.signal); + entered.resolve(); + return new Promise((_resolve, reject) => options.signal.addEventListener("abort", () => reject(options.signal.reason), { once: true })); + }; + const pending = fixture.search.query("local", { query: "cancel in database" }, controller.signal); + await entered.promise; + const cancelled = assert.rejects(pending, code("SEARCH_CANCELLED")); + controller.abort(); await cancelled; + fixture.state.aggregateHook = undefined; + assert.ok((await fixture.search.query("local", { query: "retry" })).results.length > 0); + assert.equal(fixture.state.aggregates.length, 2); +}); + +test("an already cancelled query never obtains a database or calls the model", async () => { + const fixture = searchFixture(); + const controller = new AbortController(); controller.abort(); + await assert.rejects(fixture.search.query("local", { query: "cancelled" }, controller.signal), code("SEARCH_CANCELLED")); + assert.deepEqual(fixture.targets, []); + assert.deepEqual(fixture.calls.embed, []); + assert.equal(fixture.state.aggregates.length, 0); + assert.ok((await fixture.search.query("local", { query: "retry" })).results.length > 0); +}); + +test("partial, duplicated, drifted, or nonnumeric engine results are rejected instead of becoming fallback results", async () => { + for (const [transform, expected] of [ + [(rows) => rows.slice(1), "SEARCH_SNAPSHOT_MISMATCH"], + [(rows) => rows.map((row, n) => n === 1 ? rows[0] : row), "SEARCH_SNAPSHOT_MISMATCH"], + [(rows) => rows.map((row, n) => n ? row : { ...row, sourceHash: "drift" }), "SEARCH_SNAPSHOT_MISMATCH"], + [(rows) => rows.map((row, n) => n ? row : { ...row, vectorHash: hash(unitVector(1)) }), "SEARCH_SNAPSHOT_MISMATCH"], + [(rows) => rows.map((row, n) => n ? row : { ...row, bundleDigest: "d".repeat(64) }), "SEARCH_SNAPSHOT_MISMATCH"], + ...[undefined, null, "0.9", NaN, Infinity, 2, -2].map((similarity) => [(rows) => rows.map((row, n) => n ? row : { ...row, similarity }), "SEARCH_SCORE_INVALID"]), + ]) { + const fixture = searchFixture(); + const rows = fixture.state.collections.get(SEARCH_COLLECTION).map((row) => ({ ...clone(row), similarity: 0.8 })); + fixture.state.aggregateHook = async () => transform(rows); + await assert.rejects(fixture.search.query("local", { query: "topic" }), code(expected)); + assert.equal(fixture.state.aggregates.length, 1); + assert.equal(fixture.state.writes.length, 0); + fixture.state.aggregateHook = undefined; + assert.ok((await fixture.search.query("local", { query: "topic" })).results.length > 0, "engine failure is not cached"); + } +});