@fangorn-network/westmarch 0.0.6-dev → 0.0.8-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/consume/embed.js CHANGED
@@ -24,7 +24,11 @@ export const EMBED_DIM = DIM;
24
24
  let _extractor = null;
25
25
  const extractor = () => (_extractor ??= (async () => {
26
26
  const { pipeline } = await import("@huggingface/transformers");
27
- return pipeline("feature-extraction", MODEL, { dtype: "q8" });
27
+ // WESTMARCH_EMBED_DEVICE=cuda puts the publisher's document side on a GPU (Node only; needs
28
+ // onnxruntime-node's CUDA binaries). Still q8 at batch 1, so still the same encoder: its
29
+ // vectors agree with CPU q8 to ~0.99, closer than the browser's WASM q8 queries (~0.98).
30
+ const device = globalThis.process?.env?.WESTMARCH_EMBED_DEVICE;
31
+ return pipeline("feature-extraction", MODEL, { dtype: "q8", ...(device && { device }) });
28
32
  })());
29
33
 
30
34
  /** Standardize over the full vector, slice to `dim`, L2-normalize the slice. */
@@ -495,13 +495,16 @@ writeFileSync("site/.well-known/agent-card.json", JSON.stringify(card, null, 1))
495
495
 
496
496
  // The card is read from other origins, so it needs CORS, and so does the view, for
497
497
  // agents and pages elsewhere. Bundles and shards are named by their digest, so they
498
- // never change: tell caches so. (Pages allows one * per rule, hence a rule per domain.)
498
+ // never change: tell caches so. Shards only in the reader's own browser (`private`): a
499
+ // retracted record's bytes must stop being served by shared caches once the deploy drops
500
+ // its shard. (Pages allows one * per rule, hence a rule per domain.)
499
501
  const immutable = " Cache-Control: public, max-age=31536000, immutable\n";
502
+ const mine = " Cache-Control: private, max-age=31536000, immutable\n";
500
503
  writeFileSync("site/_headers",
501
504
  "/.well-known/agent-card.json\n Access-Control-Allow-Origin: *\n"
502
505
  + "/view/*\n Access-Control-Allow-Origin: *\n"
503
506
  + `/assets/*\n${immutable}`
504
- + readdirSync("site/view/cdn/domains").map((d) => `/view/cdn/domains/${d}/shards/*\n${immutable}`).join(""));
507
+ + readdirSync("site/view/cdn/domains").map((d) => `/view/cdn/domains/${d}/shards/*\n${mine}`).join(""));
505
508
  ```
506
509
 
507
510
  ```sh
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fangorn-network/westmarch",
3
- "version": "0.0.6-dev",
3
+ "version": "0.0.8-dev",
4
4
  "description": "Publisher and consumer surfaces for a Fangorn app: shape a graph, publish it, read it back as a searchable, agent-drivable catalog",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/publish/ship.js CHANGED
@@ -3,6 +3,7 @@
3
3
  //
4
4
  // westmarch-ship app.json [--no-crawl] [--no-deploy] [--dry-run]
5
5
  // westmarch-ship app.json --local <out> [--crawl] a view from staged records, no chain (see buildLocal)
6
+ // westmarch-ship app.json --register the app alone: claim, join, empty site, card bound
6
7
  //
7
8
  // Every step checks the chain (or Cloudflare) first and only acts on a difference, so
8
9
  // re-running is how you update: new data, a changed schema, a new source, a moved site.
@@ -16,6 +17,11 @@
16
17
  // 7. deploy to Cloudflare Pages
17
18
  // 8. register the ERC-8004 agent and bind the card, if the chain points elsewhere
18
19
  //
20
+ // --register is the fast path, run before there is any data: 1, 2, 6 with an empty view, 7,
21
+ // and 8 binding the card without minting. The mint copies the card's skills into its IPFS
22
+ // registration file and is never redone, so it waits for the first full ship, when the card
23
+ // lists what the app really does.
24
+ //
19
25
  // Chain writes go through the `fangorn` CLI (its configured wallet signs, and
20
26
  // `fangorn wallet` shows which). Reads go through the SDK. State lives in `.ship/` next
21
27
  // to app.json: the site, the view (its own state, see view.js) and a small state.json.
@@ -84,12 +90,12 @@ export function expandSources(sources, base) {
84
90
  export function loadConfig(path) {
85
91
  const c = JSON.parse(readFileSync(path, "utf8"));
86
92
  c.sources = expandSources(c.sources ?? [], dirname(resolve(path)));
87
- for (const k of ["app", "name", "description", "types", "sources", "site"])
93
+ for (const k of ["app", "name", "description", "site"]) // types and sources can come after --register
88
94
  if (!c[k]) throw new Error(`${path}: missing "${k}"`);
89
95
  if (!c.site.project) throw new Error(`${path}: site.project names the Cloudflare Pages project`);
90
96
  for (const s of c.sources) if (!s.namespace || !Array.isArray(s.command))
91
97
  throw new Error(`${path}: each source needs a namespace and a command (an argv array)`);
92
- return { relations: [], tags: [], ...c };
98
+ return { relations: [], tags: [], types: {}, ...c };
93
99
  }
94
100
 
95
101
  /** The schema commit for `types` + `relations`: one fangorn.type.v1 vertex per type,
@@ -155,8 +161,10 @@ function assertSameDeployment(cli) {
155
161
 
156
162
  // ── the steps ─────────────────────────────────────────────────────────────────
157
163
 
158
- export async function ship(configPath, { crawl = true, deploy = true, dry = false, replace = false, only = null } = {}) {
164
+ export async function ship(configPath, { crawl = true, deploy = true, dry = false, replace = false, only = null, register = false } = {}) {
159
165
  const cfg = loadConfig(configPath);
166
+ if (!register && (!Object.keys(cfg.types).length || !cfg.sources.length))
167
+ throw new Error(`${configPath}: no types or sources yet, so nothing to build; --register sets up the app alone`);
160
168
  CLI = cliArgv(cfg);
161
169
  assertSameDeployment(CLI);
162
170
  const base = dirname(resolve(configPath));
@@ -201,22 +209,24 @@ export async function ship(configPath, { crawl = true, deploy = true, dry = fals
201
209
 
202
210
  // 3. schema
203
211
  let onChain = null;
204
- try { onChain = view.parseSchema((await fangorn.readNamespace(owner, view.SCHEMA_NAMESPACE)).contents); } catch { /* none yet */ }
205
- if (!onChain || canonical(onChain.types, onChain.relations) !== canonical(cfg.types, cfg.relations)) {
206
- const sdir = join(dir, "schema");
207
- mkdirSync(sdir, { recursive: true });
208
- writeFileSync(join(sdir, "graph.json"), JSON.stringify(schemaGraph(cfg.types, cfg.relations), null, 1));
209
- log(`schema ${onChain ? "changed" : "is new"}: committing ${Object.keys(cfg.types).join(", ")}`);
210
- fangornCli(cfg.app, ["repo", "init", view.SCHEMA_NAMESPACE], { cwd: sdir, dry });
211
- fangornCli(cfg.app, ["commit", "graph.json", "-m", "schema", "--replace"], { cwd: sdir, dry });
212
- fangornCli(cfg.app, ["push"], { cwd: sdir, dry });
213
- } else log("schema unchanged");
212
+ if (!register) {
213
+ try { onChain = view.parseSchema((await fangorn.readNamespace(owner, view.SCHEMA_NAMESPACE)).contents); } catch { /* none yet */ }
214
+ if (!onChain || canonical(onChain.types, onChain.relations) !== canonical(cfg.types, cfg.relations)) {
215
+ const sdir = join(dir, "schema");
216
+ mkdirSync(sdir, { recursive: true });
217
+ writeFileSync(join(sdir, "graph.json"), JSON.stringify(schemaGraph(cfg.types, cfg.relations), null, 1));
218
+ log(`schema ${onChain ? "changed" : "is new"}: committing ${Object.keys(cfg.types).join(", ")}`);
219
+ fangornCli(cfg.app, ["repo", "init", view.SCHEMA_NAMESPACE], { cwd: sdir, dry });
220
+ fangornCli(cfg.app, ["commit", "graph.json", "-m", "schema", "--replace"], { cwd: sdir, dry });
221
+ fangornCli(cfg.app, ["push"], { cwd: sdir, dry });
222
+ } else log("schema unchanged");
223
+ }
214
224
 
215
225
  // 4. sources: crawl + publish straight into the app. One source failing (a site that
216
226
  // blocks us, a feed that is down) keeps its last published data and does not stop the
217
227
  // others; the ship still exits non-zero at the end, naming it.
218
228
  const failed = [];
219
- if (crawl) for (const s of cfg.sources.filter((s) => !only || only.includes(s.namespace))) {
229
+ if (crawl && !register) for (const s of cfg.sources.filter((s) => !only || only.includes(s.namespace))) {
220
230
  const cwd = s.cwd ? resolve(base, s.cwd.replace(/^~/, homedir())) : base;
221
231
  const paidArgs = cfg.paid && s.paid_dir ? ["--paid-dir", resolve(cwd, s.paid_dir)] : [];
222
232
  try {
@@ -234,7 +244,8 @@ export async function ship(configPath, { crawl = true, deploy = true, dry = fals
234
244
  const site = join(dir, "site");
235
245
  if (!existsSync(join(site, "view/cdn/catalog")) && state.url && !dry) await mirrorView(`${state.url}/view`, join(site, "view"));
236
246
  const namespaces = [...new Set(cfg.sources.map((s) => s.namespace))];
237
- const report = dry ? {} : await view.publishView({ fangorn, app: cfg.app, namespaces, out: join(site, "view"),
247
+ if (register && !dry) view.writeCatalog(join(site, "view")); // empty, or what an earlier build left
248
+ const report = dry || register ? {} : await view.publishView({ fangorn, app: cfg.app, namespaces, out: join(site, "view"),
238
249
  fromBlock: BigInt(state.fromBlock), embed: view.cachedEmbed(join(dir, "vectors.ndjson")), log });
239
250
 
240
251
  // 6. the page, the card, the headers
@@ -297,8 +308,12 @@ export async function ship(configPath, { crawl = true, deploy = true, dry = fals
297
308
  "/.well-known/agent-card.json\n Access-Control-Allow-Origin: *\n"
298
309
  + "/view/*\n Access-Control-Allow-Origin: *\n"
299
310
  + `/assets/*\n${immutable}`
300
- // An hour, not immutable: a shard is deleted when a record is retracted (see view.js).
301
- + domains.map((d) => `/view/cdn/domains/${d}/shards/*\n Cache-Control: public, max-age=3600\n`).join(""));
311
+ // A shard's name is its content hash, so a browser may keep it for good: a change or a
312
+ // retraction writes new names and the manifest stops pointing at the old ones. `private`
313
+ // keeps it out of shared caches, so a retracted record's bytes stop being served the
314
+ // moment the deploy drops the file (see view.js). An hour made readers on a phone fetch
315
+ // the whole catalog again after every hour away.
316
+ + domains.map((d) => `/view/cdn/domains/${d}/shards/*\n Cache-Control: private, max-age=31536000, immutable\n`).join(""));
302
317
 
303
318
  // 7. deploy
304
319
  if (deploy) {
@@ -311,13 +326,29 @@ export async function ship(configPath, { crawl = true, deploy = true, dry = fals
311
326
  // 8. ERC-8004 + the binding
312
327
  const cardUrl = `${url}/.well-known/agent-card.json`;
313
328
  const bound = await registry.appAgentUri(appId).catch(() => "");
314
- if (deploy && bound !== cardUrl) {
315
- log(`binding ${cardUrl} (on chain: ${bound || "nothing"})`);
329
+ const mint = () => {
316
330
  const out = dry ? "" : fangornCli(cfg.app, ["app", "agent", cardUrl]);
317
331
  state.agentId = (out.match(/Agent ID:\s+(\S+)/) ?? [])[1] ?? state.agentId;
332
+ delete state.agentPending;
318
333
  save();
334
+ };
335
+ if (deploy && bound !== cardUrl && register) {
336
+ log(`binding ${cardUrl} (on chain: ${bound || "nothing"}); the agent is minted on the first full ship`);
337
+ fangornCli(cfg.app, ["app", "agent", cardUrl, "--skip-register"], { dry });
338
+ state.agentPending = true;
339
+ save();
340
+ } else if (deploy && bound !== cardUrl) {
341
+ log(`binding ${cardUrl} (on chain: ${bound || "nothing"})`);
342
+ mint();
343
+ } else if (deploy && state.agentPending && !register) {
344
+ log(`minting the ERC-8004 agent from the card as built`);
345
+ mint();
319
346
  } else if (deploy) log("card already bound");
320
347
 
348
+ if (register) {
349
+ log(`registered: ${url} · card ${cardUrl} · ${cfg.app} is yours; build it with westmarch-ship ${configPath} --local <out>`);
350
+ return { url, cardUrl, report };
351
+ }
321
352
  const added = Object.values(report).reduce((n, r) => n + r.added, 0);
322
353
  log(`done: ${url} · card ${cardUrl} · agent ${state.agentId ?? "(unchanged)"} · +${added} records embedded`);
323
354
  if (failed.length) throw new Error(`deployed, but these sources failed and kept their old records: ${failed.join(", ")}`);
@@ -450,6 +481,7 @@ if (process.argv[1]?.endsWith("ship.js") || process.argv[1]?.endsWith("westmarch
450
481
  const [path, ...flags] = process.argv.slice(2);
451
482
  if (!path || flags.includes("--help")) {
452
483
  console.error("usage: westmarch-ship app.json [--no-crawl] [--no-deploy] [--dry-run] [--replace] [--only ns1,ns2]\n" +
484
+ " westmarch-ship app.json --register [--dry-run] (claim, join, empty site, card bound: no data)\n" +
453
485
  " westmarch-ship app.json --local <out> [--crawl] [--only ns1,ns2] (no chain, no deploy)");
454
486
  process.exit(path ? 0 : 2);
455
487
  }
@@ -460,7 +492,8 @@ if (process.argv[1]?.endsWith("ship.js") || process.argv[1]?.endsWith("westmarch
460
492
  process.exit(0);
461
493
  }
462
494
  await ship(path, { crawl: !flags.includes("--no-crawl"), deploy: !flags.includes("--no-deploy"), dry: flags.includes("--dry-run"),
463
- replace: flags.includes("--replace"),
495
+ replace: flags.includes("--replace"), register: flags.includes("--register"),
464
496
  only })
465
497
  .catch((e) => { console.error(`[ship] ✗ ${e.message}`); process.exit(1); });
498
+ process.exit(0); // a CUDA embedder keeps the process alive (and can abort in its teardown)
466
499
  }
package/publish/view.js CHANGED
@@ -238,7 +238,9 @@ async function publishDomain({ fangorn, schema, publisher, ns, domain, dir, reba
238
238
  if (rebake) rmSync(dir, { recursive: true, force: true }); // old shards would stay reachable
239
239
  const had = loadDomain(dir);
240
240
  const made = had.manifest?.embedder ?? (had.manifest ? { runtime: "fastembed", dtype: "fp32" } : null);
241
- if (made && JSON.stringify(made) !== JSON.stringify(EMBEDDER))
241
+ // Same model and dtype is the same encoder, whatever ran it: q8 on CPU, CUDA and WASM agree to
242
+ // ~0.98-0.99 cosine, fp32 against q8 only to ~0.95.
243
+ if (made && (made.model ?? EMBED_MODEL) + made.dtype !== EMBEDDER.model + EMBEDDER.dtype)
242
244
  throw new Error(`${domain} was embedded by ${made.runtime} ${made.dtype}, not ${EMBEDDER.runtime} ${EMBEDDER.dtype}; ` +
243
245
  "vectors from two encoders are not comparable. Rebake it with --rebake, or keep publishing it with the tool that made it.");
244
246
 
@@ -337,7 +339,7 @@ function applySpec(dir, manifest, schema, rows, dead, guessed = new Map()) {
337
339
  }
338
340
  }
339
341
 
340
- function writeCatalog(out) {
342
+ export function writeCatalog(out) {
341
343
  const root = `${out}/cdn/domains`;
342
344
  mkdirSync(`${out}/cdn`, { recursive: true });
343
345
  const domains = existsSync(root) ? readdirSync(root).sort().map((d) => readJson(`${root}/${d}/manifest`, null)).filter(Boolean) : [];
@@ -434,6 +436,8 @@ if (typeof process !== "undefined" && import.meta.url === `file://${process.argv
434
436
  const { rolesFrom } = await import("../consume/roles.js");
435
437
  eq(getRow(got, "b2", rolesFrom([m]))?.id, "c2b", "get by the publisher's own id, not the CID");
436
438
 
439
+ m.embedder = { ...EMBEDDER, runtime: "transformers.js cuda" }; writeJson(`${out}/cdn/domains/${d}/manifest`, m);
440
+ await run(); // throws if another runtime of the same q8 model is refused
437
441
  m.embedder = { runtime: "fastembed", dtype: "fp32" }; writeJson(`${out}/cdn/domains/${d}/manifest`, m);
438
442
  await throws(run, /not comparable/, "appending to another encoder's view");
439
443
  eq((await publishView({ fangorn, app: APP, namespaces: ["shop"], out, embed, rebake: true, log: () => {} }))[d],
@@ -0,0 +1 @@
1
+ let e=null;const t=()=>e??=(async()=>{let{pipeline:e}=await import(`./transformers.web-BgUm7F_-.js`),t={}.WESTMARCH_EMBED_DEVICE;return e(`feature-extraction`,`nomic-ai/nomic-embed-text-v1.5`,{dtype:`q8`,...t&&{device:t}})})();function n(e,t=256){let n=e.length,r=0;for(let t=0;t<n;t++)r+=e[t];r/=n;let i=0;for(let t=0;t<n;t++)i+=(e[t]-r)**2;let a=Math.sqrt(i/n+1e-5),o=Array(Math.min(t,n));for(let t=0;t<o.length;t++)o[t]=(e[t]-r)/a;let s=0;for(let e of o)s+=e*e;if(s=Math.sqrt(s),s)for(let e=0;e<o.length;e++)o[e]/=s;return o}async function r(e){return n((await(await t())(`search_query: ${e}`,{pooling:`mean`,normalize:!1})).data)}async function i(e){return n((await(await t())(`search_document: ${e}`,{pooling:`mean`,normalize:!1})).data)}const a=()=>t().then(()=>{});function o(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=Math.round(Math.max(-1,Math.min(1,e[n]))*127);t[n]=r<0?r+256:r}let n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function s(e){try{let t=atob(e),n=new Float32Array(t.length);for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);n[e]=(r>127?r-256:r)/127}return n.length?n:null}catch{return null}}function c(e){let t=new Uint8Array(Math.ceil(e.length/8));for(let n=0;n<e.length;n++)e[n]>=0&&(t[n>>3]|=128>>(n&7));let n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function l(e){try{let t=atob(e.padEnd(Math.ceil(e.length/4)*4,`=`)),n=new Float32Array(t.length*8);for(let e=0;e<n.length;e++)n[e]=t.charCodeAt(e>>3)>>7-(e&7)&1?1:-1;return n.length?n:null}catch{return null}}if(typeof process<`u`&&import.meta.url===`file://${process.argv[1]}`&&process.argv[1].endsWith(`/embed.js`)){let e=n(Array.from({length:768},(e,t)=>Math.sin(t))),t=0;for(let n of e)t+=n*n;if(Math.abs(Math.sqrt(t)-1)>1e-6)throw Error(`matryoshka must L2-normalize`);if(e.length!==256)throw Error(`matryoshka must truncate to 256`);let r=s(o(e));if(r.length!==e.length)throw Error(`pack/unpack changed the dimension`);let i=0,a=0;for(let t=0;t<e.length;t++)i+=e[t]*r[t],a+=r[t]*r[t];let u=i/Math.sqrt(a);if(u<.999)throw Error(`int8 round-trip cosine ${u} — too lossy to rank with`);let d=s(o([-1,-.5,0,.5,1]));if(d[0]>-.99||d[1]>-.49||d[1]<-.51)throw Error(`negative components corrupted: ${[...d]}`);if(s(`!!!not base64!!!`)!==null)throw Error(`malformed vector must return null, not throw`);let f=c(e);if(f.length>48)throw Error(`sign bits must stay link-sized, got ${f.length} chars`);let p=l(f);if(p.length!==e.length)throw Error(`sign round-trip changed the dimension`);for(let t=0;t<e.length;t++)if(Math.sign(p[t])!==(e[t]<0?-1:1))throw Error(`sign flipped at ${t}`);if(c(p)!==f)throw Error(`sign packing must be idempotent`);if(l(`!!!not base64!!!`)!==null)throw Error(`malformed bits must return null, not throw`);console.log(`embed.js self-check ok — matryoshka norm, int8 round-trip, negatives, malformed input, sign bits`)}const u={query:r,document:i};self.onmessage=async({data:{id:e,kind:t,text:n}})=>{try{if(t===`warm`)return await a(),self.postMessage({id:e,vec:null});self.postMessage({id:e,vec:await u[t](n)})}catch(t){self.postMessage({id:e,error:t?.message??String(t)})}};
@@ -1,8 +1,8 @@
1
1
  const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./transformers.web-u9uSoh5E.js","./rolldown-runtime-Dd_uD5pT.js","./preload-helper-uBIymjUX.js","./__vite-browser-external-CKnVkMRn.js","./roles-YDRjv_PY.js","./roles-C9V_uDr_.js"])))=>i.map(i=>d[i]);
2
- import{i as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./preload-helper-uBIymjUX.js";import{c as n,d as r,f as i,g as a,h as o,m as s,n as c,p as l,r as u,s as d}from"./roles-C9V_uDr_.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var f=`nomic-ai/nomic-embed-text-v1.5`,p=256,m=null,h=()=>m??=(async()=>{let{pipeline:e}=await t(async()=>{let{pipeline:e}=await import(`./transformers.web-u9uSoh5E.js`);return{pipeline:e}},__vite__mapDeps([0,1,2]),import.meta.url);return e(`feature-extraction`,f,{dtype:`q8`})})();function g(e,t=p){let n=e.length,r=0;for(let t=0;t<n;t++)r+=e[t];r/=n;let i=0;for(let t=0;t<n;t++)i+=(e[t]-r)**2;let a=Math.sqrt(i/n+1e-5),o=Array(Math.min(t,n));for(let t=0;t<o.length;t++)o[t]=(e[t]-r)/a;let s=0;for(let e of o)s+=e*e;if(s=Math.sqrt(s),s)for(let e=0;e<o.length;e++)o[e]/=s;return o}async function _(e){return g((await(await h())(`search_query: ${e}`,{pooling:`mean`,normalize:!1})).data)}var v=()=>typeof window<`u`&&typeof Worker<`u`,y=null,ee=0,b=new Map;function x(){return y||(y=new Worker(new URL(new URL(`embed.worker-CQqmvS52.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),y.onmessage=({data:e})=>{let t=b.get(e.id);t&&(b.delete(e.id),e.error?t.reject(Error(e.error)):t.resolve(e.vec))},y.onerror=e=>{for(let t of b.values())t.reject(Error(`embed worker: ${e?.message??`failed to start`}`));b.clear(),y=null},y)}var te=(e,t)=>new Promise((n,r)=>{let i=++ee;b.set(i,{resolve:n,reject:r}),x().postMessage({id:i,kind:e,text:t})}),ne=e=>v()?te(`query`,e):_(e);function S(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=Math.round(Math.max(-1,Math.min(1,e[n]))*127);t[n]=r<0?r+256:r}let n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function C(e){try{let t=atob(e),n=new Float32Array(t.length);for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);n[e]=(r>127?r-256:r)/127}return n.length?n:null}catch{return null}}function re(e){let t=new Uint8Array(Math.ceil(e.length/8));for(let n=0;n<e.length;n++)e[n]>=0&&(t[n>>3]|=128>>(n&7));let n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function ie(e){try{let t=atob(e.padEnd(Math.ceil(e.length/4)*4,`=`)),n=new Float32Array(t.length*8);for(let e=0;e<n.length;e++)n[e]=t.charCodeAt(e>>3)>>7-(e&7)&1?1:-1;return n.length?n:null}catch{return null}}if(typeof process<`u`&&import.meta.url===`file://${process.argv[1]}`&&process.argv[1].endsWith(`/embed.js`)){let e=g(Array.from({length:768},(e,t)=>Math.sin(t))),t=0;for(let n of e)t+=n*n;if(Math.abs(Math.sqrt(t)-1)>1e-6)throw Error(`matryoshka must L2-normalize`);if(e.length!==p)throw Error(`matryoshka must truncate to ${p}`);let n=C(S(e));if(n.length!==e.length)throw Error(`pack/unpack changed the dimension`);let r=0,i=0;for(let t=0;t<e.length;t++)r+=e[t]*n[t],i+=n[t]*n[t];let a=r/Math.sqrt(i);if(a<.999)throw Error(`int8 round-trip cosine ${a} — too lossy to rank with`);let o=C(S([-1,-.5,0,.5,1]));if(o[0]>-.99||o[1]>-.49||o[1]<-.51)throw Error(`negative components corrupted: ${[...o]}`);if(C(`!!!not base64!!!`)!==null)throw Error(`malformed vector must return null, not throw`);let s=re(e);if(s.length>48)throw Error(`sign bits must stay link-sized, got ${s.length} chars`);let c=ie(s);if(c.length!==e.length)throw Error(`sign round-trip changed the dimension`);for(let t=0;t<e.length;t++)if(Math.sign(c[t])!==(e[t]<0?-1:1))throw Error(`sign flipped at ${t}`);if(re(c)!==s)throw Error(`sign packing must be idempotent`);if(ie(`!!!not base64!!!`)!==null)throw Error(`malformed bits must return null, not throw`);console.log(`embed.js self-check ok — matryoshka norm, int8 round-trip, negatives, malformed input, sign bits`)}var w=(e,t,n)=>{let r=0;for(let n=0;n<t.length&&n<e.vector.length;n++)r+=e.vector[n]*t[n];return r/(e.norm*n)},T=e=>{let t=0;for(let n of e)t+=n*n;return Math.sqrt(t)||1};function ae(e,t=1){if(e.length<3)return-1/0;let n=e.reduce((e,t)=>e+t,0)/e.length,r=Math.sqrt(e.reduce((e,t)=>e+(t-n)**2,0)/e.length);return r>1e-6?n+t*r:-1/0}function oe(e,{limit:t=10,lambda:n=.7,key:r=`s`}={}){if(n>=1||e.length<=1)return e.slice(0,t);let i=e.slice(0,Math.max(t*6,30)),a=[];for(;a.length<t&&i.length;){let e=0,t=-1/0;for(let o=0;o<i.length;o++){let s=0;for(let e of a){if(!i[o].row?.vector||!e.row?.vector)continue;let t=w(i[o].row,e.row.vector,e.row.norm);t>s&&(s=t)}let c=n*i[o][r]-(1-n)*s;c>t&&(t=c,e=o)}a.push(i.splice(e,1)[0])}return a}var se=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),ce=e=>RegExp(`\\b${se(e)}\\b`);function E(e,t){let n=String(e.text??``).toLowerCase();if(!n)return 0;let r=t.split(/\s+/).filter(Boolean);if(!r.length)return 0;let i=0;for(let e of r)ce(e).test(n)&&i++;if(!i)return 0;let a=n.indexOf(t);return Math.min(1,.5*(i/r.length)+(ce(t).test(n)?.35:0)+(a>=0?.15*(1-a/n.length):0))}function le(e,t){let n=e[0],r=0;for(let i of e){let e=E({text:i.text},t);e>r&&(r=e,n=i)}return n}function ue(e=[],t){let n=T(t);return e.map(e=>{let r=e.coverage;if(!r?.vectors?.length)return{...e,affinity:null};let i=-1;for(let e of r.vectors){let r=0,a=0;for(let n=0;n<e.length&&n<t.length;n++)r+=e[n]*t[n],a+=e[n]*e[n];let o=r/((Math.sqrt(a)||1)*n);o>i&&(i=o)}return{...e,affinity:i}}).sort((e,t)=>(t.affinity??-1/0)-(e.affinity??-1/0))}if(typeof process<`u`&&import.meta.url===`file://${process.argv[1]}`&&process.argv[1].endsWith(`/rank.js`)){if(E({text:`intoxicated education`},`cat`)!==0)throw Error(`substring matched — word boundaries lost`);if(E({text:`a cat sat`},`cat`)<=0)throw Error(`whole word must match`);let e=E({text:`cold war submarines`},`cold war`),t=E({text:`cold nights, the war ended`},`cold war`);if(!(e>t))throw Error(`phrase bonus lost: ${e} vs ${t}`);if(E({text:`what is c++`},`c++`)===void 0)throw Error(`must not throw on regex metachars`);if(Math.abs(w({vector:[1,0,0,0],norm:1},[1,0],1)-1)>1e-9)throw Error(`cosine must truncate to the query`);if(ae([.5,.5,.5,.5])!==-1/0)throw Error(`no spread must admit everything, not nothing`);if(ae([.4,.4])!==-1/0)throw Error(`too few rows to have a distribution`);let n=ae([.4,.41,.42,.9]);if(!(.9>=n&&.42<n))throw Error(`floor did not separate the outlier: ${n}`);let r=[{text:`opening titles`},{text:`the submarine dives`}];if(le(r,`submarine`).text!==`the submarine dives`)throw Error(`wrong passage quoted`);if(le(r,`nothing here`).text!==`opening titles`)throw Error(`must fall back to the first passage`);{let e=(e,t)=>({vector:[e,t],norm:Math.sqrt(e*e+t*t)||1}),t=[{row:{id:`ep1`,...e(1,0)},s:.9},{row:{id:`ep2`,...e(1,.01)},s:.89},{row:{id:`ep3`,...e(1,.02)},s:.88},{row:{id:`other`,...e(0,1)},s:.7}],n=oe(t,{limit:2,lambda:1}).map(e=>e.row.id);if(n.join()!==`ep1,ep2`)throw Error(`lambda 1 must be the old behaviour: ${n}`);let r=oe(t,{limit:2,lambda:.7}).map(e=>e.row.id);if(r.join()!==`ep1,other`)throw Error(`MMR must not return the same episode twice: ${r}`);if(oe(t,{limit:4,lambda:.5})[0].row.id!==`ep1`)throw Error(`the top hit must survive`);if(oe([{row:{id:`a`},s:1}],{limit:3}).length!==1)throw Error(`vectorless rows must pass through`)}let i=ue([{name:`old`,coverage:null},{name:`far`,coverage:{vectors:[[0,1]]}},{name:`near`,coverage:{vectors:[[1,0]]}}],[1,0]);if(i.map(e=>e.name).join(`,`)!==`near,far,old`)throw Error(`domains misranked: ${i.map(e=>e.name)}`);if(i[2].affinity!==null)throw Error(`an unmeasured domain must be null, not 0`);console.log(`rank.js self-check ok — word boundaries, matryoshka cosine, z-floor, MMR drops near-duplicates without moving the top hit, passage pick, domain affinity`)}var de=null,fe=null,D=null,pe=new Map,me=new Map,he=new Map,ge=e=>[e.name,e.path,e.desc].filter(Boolean).join(` `),_e=null,ve=null;function O({resolveView:e,rowText:t,onManifests:n}={}){e&&(_e=e),t&&(ge=t),n&&(ve=n)}var k=()=>{pe.clear(),me.clear(),he.clear(),de=null,fe=null,D=null};function ye(e){fe=e?xe(e):null}var be=()=>fe,xe=e=>String(e).replace(/\/+$/,``).replace(/\/(stream|cdn)$/,``);function Se(){return _e?de??=Promise.resolve().then(()=>_e()).then(e=>e?xe(e):null).catch(e=>{throw de=null,e}):Promise.resolve(null)}function Ce(e){let t=(Array.isArray(e)?e:String(e??``).split(`,`)).map(e=>String(e).trim()).filter(Boolean);D=t.length?t:null}var we=e=>!D||D.some(t=>e===t||e.split(`/`).pop()===t||e.startsWith(t)),Te=`no quickbeam view configured — pass a view base, or wire one with configure({ resolveView })`;async function A(e,t){let n=e??fe??await Se();if(!n)throw Error(Te);let r=me.get(n);r||me.set(n,r=new Set),t&&r.add(t);let i=pe.get(n);if(i)return i;let a=Ne(n,e=>{for(let t of r)try{t(e)}catch{}}).finally(()=>me.delete(n)).catch(e=>{throw pe.delete(n),e});return pe.set(n,a),a}async function Ee(e){let t=await fetch(e);if(!t.ok)throw Error(`shard: HTTP ${t.status} for ${e}`);return De(new Uint8Array(await t.arrayBuffer()))}var De=async e=>e[0]===31&&e[1]===139?await new Response(new Blob([e]).stream().pipeThrough(new DecompressionStream(`gzip`))).text():new TextDecoder().decode(e);function Oe(e,t){let n=e.fields??{},r=typeof e.v==`string`?C(e.v):Array.isArray(e.embedding)?e.embedding:typeof n.embed?.vec==`string`?C(n.embed.vec):null,i=0;if(r)for(let e of r)i+=e*e;return{id:e.track_id,owner:e.owner,...n,text:ge(n,t),vector:r,norm:Math.sqrt(i)||1}}async function ke(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,n))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function Ae(e,t,n,r){if(!t)return;if(!r){console.warn(`shard: cannot verify ${e} — the transport decoded it (Content-Encoding), and the manifest digest is over the gzipped bytes`);return}let i=await ke(n);if(i!==t)throw Error(`shard: ${e} does not match the digest in its manifest (expected ${t.slice(0,12)}…, got ${i.slice(0,12)}…)`)}async function je(e,t,n){let r=await fetch(e);if(!r.ok)throw Error(`shard: HTTP ${r.status} for ${e}`);if(!r.body){let i=new Uint8Array(await r.arrayBuffer());await Ae(e,n,[i],i[0]===31&&i[1]===139);for(let e of(await De(i)).split(`
2
+ import{i as e}from"./rolldown-runtime-Dd_uD5pT.js";import{t}from"./preload-helper-uBIymjUX.js";import{c as n,d as r,f as i,g as a,h as o,m as s,n as c,p as l,r as u,s as d}from"./roles-C9V_uDr_.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var f=`nomic-ai/nomic-embed-text-v1.5`,p=256,m=null,h=()=>m??=(async()=>{let{pipeline:e}=await t(async()=>{let{pipeline:e}=await import(`./transformers.web-u9uSoh5E.js`);return{pipeline:e}},__vite__mapDeps([0,1,2]),import.meta.url),n={}.WESTMARCH_EMBED_DEVICE;return e(`feature-extraction`,f,{dtype:`q8`,...n&&{device:n}})})();function g(e,t=p){let n=e.length,r=0;for(let t=0;t<n;t++)r+=e[t];r/=n;let i=0;for(let t=0;t<n;t++)i+=(e[t]-r)**2;let a=Math.sqrt(i/n+1e-5),o=Array(Math.min(t,n));for(let t=0;t<o.length;t++)o[t]=(e[t]-r)/a;let s=0;for(let e of o)s+=e*e;if(s=Math.sqrt(s),s)for(let e=0;e<o.length;e++)o[e]/=s;return o}async function _(e){return g((await(await h())(`search_query: ${e}`,{pooling:`mean`,normalize:!1})).data)}var v=()=>typeof window<`u`&&typeof Worker<`u`,y=null,ee=0,b=new Map;function x(){return y||(y=new Worker(new URL(new URL(`embed.worker-Dn3fKctb.js`,import.meta.url).href,``+import.meta.url),{type:`module`}),y.onmessage=({data:e})=>{let t=b.get(e.id);t&&(b.delete(e.id),e.error?t.reject(Error(e.error)):t.resolve(e.vec))},y.onerror=e=>{for(let t of b.values())t.reject(Error(`embed worker: ${e?.message??`failed to start`}`));b.clear(),y=null},y)}var te=(e,t)=>new Promise((n,r)=>{let i=++ee;b.set(i,{resolve:n,reject:r}),x().postMessage({id:i,kind:e,text:t})}),ne=e=>v()?te(`query`,e):_(e);function S(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=Math.round(Math.max(-1,Math.min(1,e[n]))*127);t[n]=r<0?r+256:r}let n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function C(e){try{let t=atob(e),n=new Float32Array(t.length);for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);n[e]=(r>127?r-256:r)/127}return n.length?n:null}catch{return null}}function re(e){let t=new Uint8Array(Math.ceil(e.length/8));for(let n=0;n<e.length;n++)e[n]>=0&&(t[n>>3]|=128>>(n&7));let n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function ie(e){try{let t=atob(e.padEnd(Math.ceil(e.length/4)*4,`=`)),n=new Float32Array(t.length*8);for(let e=0;e<n.length;e++)n[e]=t.charCodeAt(e>>3)>>7-(e&7)&1?1:-1;return n.length?n:null}catch{return null}}if(typeof process<`u`&&import.meta.url===`file://${process.argv[1]}`&&process.argv[1].endsWith(`/embed.js`)){let e=g(Array.from({length:768},(e,t)=>Math.sin(t))),t=0;for(let n of e)t+=n*n;if(Math.abs(Math.sqrt(t)-1)>1e-6)throw Error(`matryoshka must L2-normalize`);if(e.length!==p)throw Error(`matryoshka must truncate to ${p}`);let n=C(S(e));if(n.length!==e.length)throw Error(`pack/unpack changed the dimension`);let r=0,i=0;for(let t=0;t<e.length;t++)r+=e[t]*n[t],i+=n[t]*n[t];let a=r/Math.sqrt(i);if(a<.999)throw Error(`int8 round-trip cosine ${a} — too lossy to rank with`);let o=C(S([-1,-.5,0,.5,1]));if(o[0]>-.99||o[1]>-.49||o[1]<-.51)throw Error(`negative components corrupted: ${[...o]}`);if(C(`!!!not base64!!!`)!==null)throw Error(`malformed vector must return null, not throw`);let s=re(e);if(s.length>48)throw Error(`sign bits must stay link-sized, got ${s.length} chars`);let c=ie(s);if(c.length!==e.length)throw Error(`sign round-trip changed the dimension`);for(let t=0;t<e.length;t++)if(Math.sign(c[t])!==(e[t]<0?-1:1))throw Error(`sign flipped at ${t}`);if(re(c)!==s)throw Error(`sign packing must be idempotent`);if(ie(`!!!not base64!!!`)!==null)throw Error(`malformed bits must return null, not throw`);console.log(`embed.js self-check ok — matryoshka norm, int8 round-trip, negatives, malformed input, sign bits`)}var w=(e,t,n)=>{let r=0;for(let n=0;n<t.length&&n<e.vector.length;n++)r+=e.vector[n]*t[n];return r/(e.norm*n)},T=e=>{let t=0;for(let n of e)t+=n*n;return Math.sqrt(t)||1};function ae(e,t=1){if(e.length<3)return-1/0;let n=e.reduce((e,t)=>e+t,0)/e.length,r=Math.sqrt(e.reduce((e,t)=>e+(t-n)**2,0)/e.length);return r>1e-6?n+t*r:-1/0}function oe(e,{limit:t=10,lambda:n=.7,key:r=`s`}={}){if(n>=1||e.length<=1)return e.slice(0,t);let i=e.slice(0,Math.max(t*6,30)),a=[];for(;a.length<t&&i.length;){let e=0,t=-1/0;for(let o=0;o<i.length;o++){let s=0;for(let e of a){if(!i[o].row?.vector||!e.row?.vector)continue;let t=w(i[o].row,e.row.vector,e.row.norm);t>s&&(s=t)}let c=n*i[o][r]-(1-n)*s;c>t&&(t=c,e=o)}a.push(i.splice(e,1)[0])}return a}var se=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),ce=e=>RegExp(`\\b${se(e)}\\b`);function E(e,t){let n=String(e.text??``).toLowerCase();if(!n)return 0;let r=t.split(/\s+/).filter(Boolean);if(!r.length)return 0;let i=0;for(let e of r)ce(e).test(n)&&i++;if(!i)return 0;let a=n.indexOf(t);return Math.min(1,.5*(i/r.length)+(ce(t).test(n)?.35:0)+(a>=0?.15*(1-a/n.length):0))}function le(e,t){let n=e[0],r=0;for(let i of e){let e=E({text:i.text},t);e>r&&(r=e,n=i)}return n}function ue(e=[],t){let n=T(t);return e.map(e=>{let r=e.coverage;if(!r?.vectors?.length)return{...e,affinity:null};let i=-1;for(let e of r.vectors){let r=0,a=0;for(let n=0;n<e.length&&n<t.length;n++)r+=e[n]*t[n],a+=e[n]*e[n];let o=r/((Math.sqrt(a)||1)*n);o>i&&(i=o)}return{...e,affinity:i}}).sort((e,t)=>(t.affinity??-1/0)-(e.affinity??-1/0))}if(typeof process<`u`&&import.meta.url===`file://${process.argv[1]}`&&process.argv[1].endsWith(`/rank.js`)){if(E({text:`intoxicated education`},`cat`)!==0)throw Error(`substring matched — word boundaries lost`);if(E({text:`a cat sat`},`cat`)<=0)throw Error(`whole word must match`);let e=E({text:`cold war submarines`},`cold war`),t=E({text:`cold nights, the war ended`},`cold war`);if(!(e>t))throw Error(`phrase bonus lost: ${e} vs ${t}`);if(E({text:`what is c++`},`c++`)===void 0)throw Error(`must not throw on regex metachars`);if(Math.abs(w({vector:[1,0,0,0],norm:1},[1,0],1)-1)>1e-9)throw Error(`cosine must truncate to the query`);if(ae([.5,.5,.5,.5])!==-1/0)throw Error(`no spread must admit everything, not nothing`);if(ae([.4,.4])!==-1/0)throw Error(`too few rows to have a distribution`);let n=ae([.4,.41,.42,.9]);if(!(.9>=n&&.42<n))throw Error(`floor did not separate the outlier: ${n}`);let r=[{text:`opening titles`},{text:`the submarine dives`}];if(le(r,`submarine`).text!==`the submarine dives`)throw Error(`wrong passage quoted`);if(le(r,`nothing here`).text!==`opening titles`)throw Error(`must fall back to the first passage`);{let e=(e,t)=>({vector:[e,t],norm:Math.sqrt(e*e+t*t)||1}),t=[{row:{id:`ep1`,...e(1,0)},s:.9},{row:{id:`ep2`,...e(1,.01)},s:.89},{row:{id:`ep3`,...e(1,.02)},s:.88},{row:{id:`other`,...e(0,1)},s:.7}],n=oe(t,{limit:2,lambda:1}).map(e=>e.row.id);if(n.join()!==`ep1,ep2`)throw Error(`lambda 1 must be the old behaviour: ${n}`);let r=oe(t,{limit:2,lambda:.7}).map(e=>e.row.id);if(r.join()!==`ep1,other`)throw Error(`MMR must not return the same episode twice: ${r}`);if(oe(t,{limit:4,lambda:.5})[0].row.id!==`ep1`)throw Error(`the top hit must survive`);if(oe([{row:{id:`a`},s:1}],{limit:3}).length!==1)throw Error(`vectorless rows must pass through`)}let i=ue([{name:`old`,coverage:null},{name:`far`,coverage:{vectors:[[0,1]]}},{name:`near`,coverage:{vectors:[[1,0]]}}],[1,0]);if(i.map(e=>e.name).join(`,`)!==`near,far,old`)throw Error(`domains misranked: ${i.map(e=>e.name)}`);if(i[2].affinity!==null)throw Error(`an unmeasured domain must be null, not 0`);console.log(`rank.js self-check ok — word boundaries, matryoshka cosine, z-floor, MMR drops near-duplicates without moving the top hit, passage pick, domain affinity`)}var de=null,fe=null,D=null,pe=new Map,me=new Map,he=new Map,ge=e=>[e.name,e.path,e.desc].filter(Boolean).join(` `),_e=null,ve=null;function O({resolveView:e,rowText:t,onManifests:n}={}){e&&(_e=e),t&&(ge=t),n&&(ve=n)}var k=()=>{pe.clear(),me.clear(),he.clear(),de=null,fe=null,D=null};function ye(e){fe=e?xe(e):null}var be=()=>fe,xe=e=>String(e).replace(/\/+$/,``).replace(/\/(stream|cdn)$/,``);function Se(){return _e?de??=Promise.resolve().then(()=>_e()).then(e=>e?xe(e):null).catch(e=>{throw de=null,e}):Promise.resolve(null)}function Ce(e){let t=(Array.isArray(e)?e:String(e??``).split(`,`)).map(e=>String(e).trim()).filter(Boolean);D=t.length?t:null}var we=e=>!D||D.some(t=>e===t||e.split(`/`).pop()===t||e.startsWith(t)),Te=`no quickbeam view configured — pass a view base, or wire one with configure({ resolveView })`;async function A(e,t){let n=e??fe??await Se();if(!n)throw Error(Te);let r=me.get(n);r||me.set(n,r=new Set),t&&r.add(t);let i=pe.get(n);if(i)return i;let a=Ne(n,e=>{for(let t of r)try{t(e)}catch{}}).finally(()=>me.delete(n)).catch(e=>{throw pe.delete(n),e});return pe.set(n,a),a}async function Ee(e){let t=await fetch(e);if(!t.ok)throw Error(`shard: HTTP ${t.status} for ${e}`);return De(new Uint8Array(await t.arrayBuffer()))}var De=async e=>e[0]===31&&e[1]===139?await new Response(new Blob([e]).stream().pipeThrough(new DecompressionStream(`gzip`))).text():new TextDecoder().decode(e);function Oe(e,t){let n=e.fields??{},r=typeof e.v==`string`?C(e.v):Array.isArray(e.embedding)?e.embedding:typeof n.embed?.vec==`string`?C(n.embed.vec):null,i=0;if(r)for(let e of r)i+=e*e;return{id:e.track_id,owner:e.owner,...n,text:ge(n,t),vector:r,norm:Math.sqrt(i)||1}}async function ke(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,n))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}async function Ae(e,t,n,r){if(!t)return;if(!r){console.warn(`shard: cannot verify ${e} — the transport decoded it (Content-Encoding), and the manifest digest is over the gzipped bytes`);return}let i=await ke(n);if(i!==t)throw Error(`shard: ${e} does not match the digest in its manifest (expected ${t.slice(0,12)}…, got ${i.slice(0,12)}…)`)}async function je(e,t,n){let r=await fetch(e);if(!r.ok)throw Error(`shard: HTTP ${r.status} for ${e}`);if(!r.body){let i=new Uint8Array(await r.arrayBuffer());await Ae(e,n,[i],i[0]===31&&i[1]===139);for(let e of(await De(i)).split(`
3
3
  `))t(e);return}let i=r.body.getReader(),a=await i.read(),o=a.value??new Uint8Array,s=n?[]:null,c=new ReadableStream({start(e){o.length&&(s?.push(o),e.enqueue(o)),a.done&&e.close()},async pull(e){let{done:t,value:n}=await i.read();t?e.close():(s?.push(n),e.enqueue(n))},cancel(e){return i.cancel(e)}}),l=o[0]===31&&o[1]===139,u=l?c.pipeThrough(new DecompressionStream(`gzip`)):c,d=new TextDecoder,f=``;for(let r=u.getReader();;){let{done:i,value:a}=await r.read();f+=i?d.decode():d.decode(a,{stream:!0});let o=f.split(`
4
4
  `);f=i?``:o.pop();for(let e of o)t(e);if(i){f&&t(f),await Ae(e,n,s,l);return}}}var Me=250;async function Ne(e,t){let n=`${e}/cdn`,{domains:r=[]}=JSON.parse(await Ee(`${n}/catalog`)),i=r.filter(e=>we(e.name));D&&i.length!==r.length&&console.info(`shard: pulling ${i.length} of ${r.length} domains (allowlist: ${D.join(`,`)})`),D&&!i.length&&console.warn(`shard: allowlist ${D.join(`,`)} matched none of ${r.map(e=>e.name).join(`, `)} — nothing will load`),i.length||console.warn(`shard: quickbeam view ${n} has no baked domains yet — nothing to read until the watcher bakes one.`);let a=new Map,o=new Set,s=await Promise.all(i.map(async e=>{let t=`${n}/domains/${encodeURIComponent(e.name)}`,r=JSON.parse(await Ee(`${t}/manifest`));for(let e of r.tombstones??[])o.add(e);return{at:t,manifest:r,shards:r.shards??[]}})),c=s.map(e=>e.manifest);he.set(e,c);try{ve?.(c,e)}catch(e){console.warn(`shard: onManifests threw, continuing with the default rowText —`,e)}let l=Date.now(),u=e=>{!t||!e&&Date.now()-l<Me||(t([...a.values()]),l=Date.now())};return await Promise.all(s.map(async({at:t,shards:n})=>{for(let r of n)await je(`${t}/shards/${r.file}`,t=>{if(!t.trim())return;let n=Oe(JSON.parse(t),e);o.has(n.id)||a.set(n.id,n),u()},r.sha256),u(!0)})),[...a.values()]}function Pe(e,t){let n=null,r=!1;return(async()=>{let i=t??fe??await Se();if(!i||r)return;n=new EventSource(`${i}/stream`);let a=()=>{k(),e()};n.addEventListener(`added`,a),n.addEventListener(`change`,a)})().catch(()=>{}),()=>{r=!0,n?.close()}}async function Fe(e,{url:t}={}){let n=t??fe??await Se();if(!n)throw Error(Te);let{domains:r=[]}=JSON.parse(await Ee(`${n}/cdn/catalog`));return ue(r,e)}if(typeof process<`u`&&import.meta.url===`file://${process.argv[1]}`&&process.argv[1].endsWith(`/shard.js`)){let{gzipSync:n}=await t(async()=>{let{gzipSync:t}=await import(`./__vite-browser-external-CKnVkMRn.js`).then(t=>e(t.default,1));return{gzipSync:t}},__vite__mapDeps([3,1]),import.meta.url),r=console.warn,i=console.info;console.warn=console.info=()=>{};let a=(e,t,n={},r)=>({track_id:`${e}:${t}`,owner:e,...r?{embedding:r}:{},fields:{entityType:`file`,name:t.split(`/`).pop(),path:t,...n}}),o=e=>e.map(e=>JSON.stringify(e)).join(`
5
5
  `),s=`https://registry.test/q/qb_test`,c=e=>{let t=Buffer.from(e),n=Math.max(1,Math.floor(t.length/2));return{ok:!0,headers:new Headers,arrayBuffer:async()=>t,body:new ReadableStream({start(e){e.enqueue(new Uint8Array(t.subarray(0,n))),e.enqueue(new Uint8Array(t.subarray(n))),e.close()}})}},l=async e=>[...new Uint8Array(await crypto.subtle.digest(`SHA-256`,e))].map(e=>e.toString(16).padStart(2,`0`)).join(``),u=async(e,{tombstones:t={},gzipped:r=!0,keep:i=!1,coverage:a={},digest:u=!1,corrupt:d=!1}={})=>{let f=new Map;for(let[r,i]of Object.entries(e)){let e=i.map((e,t)=>`shard-000${t}-${r}.ndjson.gz`),a=new Map(e.map((e,t)=>[e,o(i[t])])),s=u?await Promise.all(e.map(async e=>l(n(Buffer.from(d?a.get(e)+`
6
6
  `:a.get(e)))))):e.map(()=>void 0);f.set(r,{manifest:JSON.stringify({name:r,shards:e.map((e,t)=>({file:e,...s[t]?{sha256:s[t]}:{}})),tombstones:t[r]??[]}),bodies:a})}globalThis.fetch=async e=>{let{pathname:t}=new URL(String(e),`https://app.test`);if(t.includes(`/stream/`))return{ok:!1,status:404};if(t.endsWith(`/cdn/catalog`))return c(JSON.stringify({domains:[...f.keys()].map(e=>({name:e,...a[e]?{coverage:a[e]}:{}}))}));let i=t.match(/\/cdn\/domains\/([^/]+)\/manifest$/);if(i)return f.has(i[1])?c(f.get(i[1]).manifest):{ok:!1,status:404};if(i=t.match(/\/cdn\/domains\/([^/]+)\/shards\/([^/]+)$/),i){let e=f.get(i[1])?.bodies.get(i[2]);return e===void 0?{ok:!1,status:404}:c(r?n(Buffer.from(e)):Buffer.from(e))}return{ok:!1,status:404}},i||k(),O({resolveView:()=>`${s}/stream`})},d=async(e,t={})=>u({d0:e},{...t,tombstones:{d0:t.tombstones??[]}}),f=e=>e.map(e=>e.path).sort().join(`,`);if(await d([[a(`0xa`,`a.md`)]]),f(await A())!==`a.md`)throw Error(`resolveView never reached the loader`);if(await d([[a(`0xa`,`plain.md`)]],{gzipped:!1}),f(await A())!==`plain.md`)throw Error(`an already-decoded body must still parse`);if(await d([[a(`0xa`,`signed.md`)]],{digest:!0}),f(await A())!==`signed.md`)throw Error(`a shard matching its digest must load`);await d([[a(`0xa`,`tampered.md`)]],{digest:!0,corrupt:!0});let p=null;try{await A()}catch(e){p=e}if(!p)throw Error(`a shard that does not match its digest must fail the load`);if(!/does not match the digest/.test(p.message))throw Error(`wrong error: ${p.message}`);p=null;try{await A()}catch(e){p=e}if(!p)throw Error(`a failed verification must not leave the rows in the cache`);let m=``;if(console.warn=e=>{m+=e},await d([[a(`0xa`,`unverifiable.md`)]],{digest:!0,gzipped:!1}),f(await A())!==`unverifiable.md`)throw Error(`an unverifiable body must still load`);if(!/cannot verify/.test(m))throw Error(`an unverifiable shard must say so, not pass silently`);if(console.warn=()=>{},await u({aaa:[[a(`0xa`,`a.md`,{desc:`alpha`}),a(`0xa`,`gone.md`,{desc:`retracted`})]],bbb:[[a(`0xb`,`b.md`,{desc:`beta`})]]},{tombstones:{aaa:[`0xa:gone.md`]}}),f(await A())!==`a.md,b.md`)throw Error(`domains must merge and tombstones retract`);for(let e of[`bbb`,[`bbb`],`bb`])if(await u({aaa:[[a(`0xa`,`a.md`)]],bbb:[[a(`0xb`,`b.md`)]]}),Ce(e),f(await A())!==`b.md`)throw Error(`allowlist ${JSON.stringify(e)} did not narrow the load`);if(await u({aaa:[[a(`0xa`,`a.md`)]]}),Ce(null),f(await A())!==`a.md`)throw Error(`a null allowlist must pull everything`);await d([[a(`0xa`,`a.md`),a(`0xa`,`gone.md`)],[a(`0xa`,`b.md`)]],{tombstones:[`0xa:gone.md`]});{let e=[],t=await A(void 0,t=>e.push(t.length));if(e.length!==2||e[0]!==1||e[1]!==2)throw Error(`must emit per shard, got ${e}`);if(t.length!==2)throw Error(`the final rows must still be whole`);if(e.some(e=>e>2))throw Error(`a tombstoned row must never surface in a partial emit`)}await d([[a(`0xa`,`a.md`)],[a(`0xa`,`b.md`)]]);{let e=[],t=[],n=A(void 0,t=>e.push(t.length)),r=A(void 0,e=>t.push(e.length));if(await Promise.all([n,r]),!e.length)throw Error(`the starting caller must still receive partials`);if(!t.length)throw Error(`a caller that joins an in-flight load must receive partials too`)}if(k(),O({resolveView:()=>`${s}/stream`}),globalThis.fetch=async()=>({ok:!1,status:500}),await A().then(()=>{throw Error(`a 500 must reject`)},()=>{}),await d([[a(`0xa`,`a.md`)]],{keep:!0}),f(await A())!==`a.md`)throw Error(`a failed load poisoned the cache — the next read must retry`);{let e=[];await u({d0:[[a(`0xa`,`a.md`,{blurb:`declared prose`})]]}),O({onManifests:t=>e.push(`manifests:${t[0]?.name}`),rowText:t=>(e.push(`rowText`),t.blurb??``)});let t=await A();if(e[0]!==`manifests:d0`)throw Error(`onManifests must fire first, got ${e}`);if(!e.includes(`rowText`))throw Error(`rowText never ran`);if(t[0].text!==`declared prose`)throw Error(`the manifest-derived rowText did not reach toRow`);if(k(),O({resolveView:()=>`${s}/stream`,onManifests:()=>{throw Error(`boom`)}}),(await A()).length!==1)throw Error(`a throwing onManifests must not fail the load`);O({onManifests:()=>{}})}if(await d([[a(`0xa`,`ep1.md`,{cues:[{text:`the submarine dives`}]})]]),(await A())[0].text.includes(`submarine`))throw Error(`the default rowText must not know about cues`);if(O({rowText:e=>e.cues?.length?e.cues.map(e=>e.text).join(` `):[e.name,e.path,e.desc].filter(Boolean).join(` `)}),k(),O({resolveView:()=>`${s}/stream`}),!(await A())[0].text.includes(`submarine`))throw Error(`a configured rowText must reach toRow`);{let e=new Set;if(O({rowText:(t,n)=>(e.add(n),t.name??``),onManifests:(t,n)=>{e.add(`m:${n}`)}}),k(),O({resolveView:()=>`${s}/stream`}),await A(),!e.has(s))throw Error(`rowText must receive its trimmed view base, saw ${[...e]}`);if(!e.has(`m:${s}`))throw Error(`onManifests must receive its view`);O({rowText:e=>[e.name,e.path,e.desc].filter(Boolean).join(` `),onManifests:()=>{}})}await d([[a(`0xa`,`v.md`,{},[3,4]),a(`0xa`,`packed.md`,{embed:{vec:`fwA=`}}),a(`0xa`,`none.md`)]]);{let e=new Map((await A()).map(e=>[e.path,e]));if(Math.abs(e.get(`v.md`).norm-5)>1e-9)throw Error(`norm must be precomputed from the plain float array`);if(!e.get(`packed.md`).vector)throw Error(`the base64 int8 form a publisher commits must unpack`);if(e.get(`none.md`).vector!==null)throw Error(`a row with no vector must be null, and rank lexically`);if(e.get(`none.md`).norm!==1)throw Error(`a zero norm would divide search by zero`)}{await u({d0:[[{track_id:`p1`,owner:`0xa`,v:`AH+B`,fields:{entityType:`file`,name:`packed.md`,path:`packed.md`}},{track_id:`p2`,owner:`0xa`,embedding:[0,1,-1],fields:{entityType:`file`,name:`old.md`,path:`old.md`}}]]});let e=new Map((await A()).map(e=>[e.path,e])),t=e.get(`packed.md`).vector,n=e.get(`old.md`).vector;if(!t)throw Error("the bake's `v` key must unpack");for(let e=0;e<3;e++)if(Math.abs(t[e]-n[e])>1/127)throw Error(`packed and float forms disagree at ${e}: ${t[e]} vs ${n[e]}`);if(Math.abs(e.get(`packed.md`).norm-e.get(`old.md`).norm)>.02)throw Error(`norm must match across wire forms`)}await u({near:[[a(`0xa`,`a.md`)]],far:[[a(`0xb`,`b.md`)]],old:[[a(`0xc`,`c.md`)]]},{coverage:{near:{vectors:[[1,0]]},far:{vectors:[[0,1]]}}});{let e=await Fe([1,0]);if(e.map(e=>e.name).join(`,`)!==`near,far,old`)throw Error(`suggestDomains misranked: ${e.map(e=>e.name)}`)}await d([[a(`0xa`,`before.md`)]]);{let e=new Map,t=``,n=!1;globalThis.EventSource=class{constructor(e){t=e}addEventListener(t,n){e.set(t,n)}close(){n=!0}};let r=0,i=Pe(()=>{r++});if(await new Promise(e=>setTimeout(e,0)),t!==`${s}/stream`)throw Error(`watchShard must open the view's SSE stream, got ${t}`);if(e.has(`snapshot`))throw Error(`snapshot is the connect-time census, not a change`);if(f(await A())!==`before.md`)throw Error(`watchShard fixture never loaded`);if(await d([[a(`0xa`,`after.md`)]],{keep:!0}),e.get(`change`)(),r!==1)throw Error("a `change` event must reach the caller");if(f(await A())!==`after.md`)throw Error("a `change` must drop the cache so the next read re-pulls");if(i(),!n)throw Error(`the unsubscribe must close the stream`)}if(await u({d0:[[a(`0xa`,`home.md`)]],other:[[a(`0xb`,`guest.md`)]]}),await A(),ye(`${s}/cdn`),be()!==s)throw Error(`setView must trim to the base every route hangs off`);if(ye(null),be()!==null)throw Error(`setView(null) must go back to the app default`);console.warn=r,console.info=i,console.log(`shard.js self-check ok — resolveView, gzip sniff, shard digests, domain merge + tombstones + allowlist, streaming, late subscriber, cache poisoning, rowText, vectors, suggestDomains, watchShard`)}var Ie=new Set([`text`,`vector`,`norm`,`id`,`owner`,`embed`]),Le=(e,t,n=[])=>{let r=c(e,t,n),i=d(e,t);return i?{...r,url:i}:r};function Re(e){let t=new Map,n=0,r=0;for(let i of e){i.vector&&(n++,r||=i.vector.length);for(let e of Object.keys(i))Ie.has(e)||i[e]!=null&&i[e]!==``&&t.set(e,(t.get(e)??0)+1)}return{rows:e.length,withVectors:n,vectorDim:r,owners:[...new Set(e.map(e=>e.owner).filter(Boolean))],fields:[...t].sort((e,t)=>t[1]-e[1]).map(([t,n])=>({name:t,on:n,pct:Math.round(100*n/(e.length||1))}))}}var ze=.15,Be=new WeakMap,Ve=(e,t)=>{let n=Be.get(e);return n===void 0&&(n=[s(e,t),i(e,t)??``,...(t.tags??[]).flatMap(t=>a(e[t]??``)),e.text??``].join(` `),Be.set(e,n)),n};function j(e,t,n,{qv:r=null,limit:i=10,fields:a,where:o,lexBoost:s=ze}={}){let c=t.trim().toLowerCase();if(!c)return[];let l=r?T(r):1;o&&(e=e.filter(e=>He(e,o)));let u=e.map(e=>r&&e.vector?{r:e,score:w(e,r,l)+(s?s*E({text:Ve(e,n)},c):0),mode:`semantic`}:{r:e,score:E({text:Ve(e,n)},c),mode:`lexical`}),d=u.filter(e=>e.mode===`semantic`).map(e=>e.score),f=Math.min(ae(d),d.length?Math.max(...d):1/0);return u.filter(e=>e.mode===`semantic`?e.score>=f:e.score>0).sort((e,t)=>t.score-e.score).slice(0,i).map(({r:e,score:t,mode:r})=>({...Le(e,n,a),score:Number(t.toFixed(4)),mode:r}))}var He=(e,t)=>!t||Object.entries(t).every(([t,n])=>a(e[t]??``).some(e=>e.toLowerCase()===String(n).toLowerCase()));function Ue(e,t,{limit:n=20,where:r}={}){let i=new Map,o=0;for(let n of e){if(!He(n,r))continue;let e=n[t];if(e==null||e===``){o++;continue}for(let t of a(e))i.set(t,(i.get(t)??0)+1)}let s=[...i].sort((e,t)=>t[1]-e[1]);return{field:t,distinct:i.size,missing:o,top:s.slice(0,n).map(([e,t])=>({value:e,count:t}))}}function M(e,t,{type:n,where:r,sort:i,desc:a=!0,limit:s=20,offset:c=0,fields:l}={}){let d=e.filter(e=>(!n||o(e)?.toLowerCase()===String(n).toLowerCase())&&He(e,r)),f=d.length;if(i){let e=e=>e==null||e===``?null:Number(e);d=[...d].sort((t,n)=>{let[r,o]=[t[i],n[i]];if((r==null||r===``)!=(o==null||o===``))return r==null||r===``?1:-1;let[s,c]=[e(r),e(o)],l=Number.isFinite(s)&&Number.isFinite(c)?s-c:String(r??``).localeCompare(String(o??``));return a?-l:l})}return{total:f,offset:c,returned:Math.min(s,Math.max(0,f-c)),collections:n?void 0:u(t,e).map(e=>({type:e.type,plural:e.plural,count:e.count})),rows:d.slice(c,c+s).map(e=>Le(e,t,l))}}function We(e,t,n,{limit:r=10,fields:i}={}){let a=e.find(e=>e.id===t);if(!a?.vector)return{seed:a?Le(a,n,i):null,near:[]};let o=a.norm;return{seed:Le(a,n,i),near:e.filter(e=>e.id!==t&&e.vector).map(e=>({r:e,score:w(e,a.vector,o)})).sort((e,t)=>t.score-e.score).slice(0,r).map(({r:e,score:t})=>({...Le(e,n,i),score:Number(t.toFixed(4))}))}}function N(e,t,n){if(!t)return null;let r=e.find(e=>e.id===t)??(n?.identity?e.find(e=>String(e[n.identity])===String(t)):null)??e.find(e=>e.path===t||e.name===t||s(e,n)===t);if(!r)return null;let{vector:i,norm:a,...o}=r;return{...o,hasVector:!!i,vectorDim:i?.length??0}}if(typeof process<`u`&&import.meta.url===`file://${process.argv[1]}`&&process.argv[1].endsWith(`/tools.js`)){let{rolesFrom:e}=await t(async()=>{let{rolesFrom:e}=await import(`./roles-YDRjv_PY.js`);return{rolesFrom:e}},__vite__mapDeps([4,5]),import.meta.url),n=(e,t,n)=>({id:e,owner:`0xa`,...t,text:[t.name,t.desc].filter(Boolean).join(` `),vector:n??null,norm:n?T(n):1}),r=[n(`1`,{name:`Duet S01E02`,series:`Duet`,year:`1987`,subject:`['Sitcom', 'Comedy']`,desc:`a forgotten fox sitcom`},[1,0,0]),n(`2`,{name:`Duet S01E03`,series:`Duet`,year:`1987`,subject:`['Sitcom']`,desc:`more of the same sitcom`},[.99,.1,0]),n(`3`,{name:`Atomic Cafe`,series:``,year:`1982`,subject:`['Documentary', 'Cold War']`,desc:`nuclear test footage`},[0,1,0]),n(`4`,{name:`untitled reel`,year:`1954`})],i=e([],r);if(i.title[0]!==`name`)throw Error(`fixture roles wrong: ${i.title}`);let o=Re(r);if(o.rows!==4||o.withVectors!==3||o.vectorDim!==3)throw Error(`describe lost the corpus shape`);let s=o.fields.find(e=>e.name===`series`);if(s.on!==2||s.pct!==50)throw Error(`empty strings must not count as coverage: ${JSON.stringify(s)}`);if(o.fields.some(e=>Ie.has(e.name)))throw Error(`plumbing fields must not be offered as content`);if(o.owners.join()!==`0xa`)throw Error(`owners lost`);let c=j(r,`sitcom`,i,{qv:[1,0,0],limit:10});if(c[0].id!==`1`||c[0].title!==`Duet S01E02`)throw Error(`semantic: wrong top hit ${c[0]?.id}`);if(c[0].mode!==`semantic`)throw Error(`mode must be reported, not inferred`);if(c.some(e=>e.id===`3`))throw Error(`the z-floor must drop the unrelated row: ${JSON.stringify(c)}`);if(!j([r[0],r[1],r[2]],`sitcom`,i,{qv:[1,0,0]}).length)throw Error(`an exact match must never be filtered out by its own floor`);if(c=j(r,`nuclear`,i,{limit:10}),c[0]?.id!==`3`||c[0].mode!==`lexical`)throw Error(`must degrade to lexical, and say so`);if(j(r,` `,i).length)throw Error(`an empty query must return nothing, not everything`);if(j(r,`untitled reel`,i)[0]?.id!==`4`)throw Error(`a vectorless row must still be searchable lexically`);let l=Ue(r,`subject`);if(l.top[0].value!==`Sitcom`||l.top[0].count!==2)throw Error(`list-ish values must split: ${JSON.stringify(l.top)}`);if(l.missing!==1)throw Error(`a field absent from a row must be counted missing, not skipped silently`);if(Ue(r,`year`).distinct!==3)throw Error(`plain values must not be split`);if(a(`Sitcom,Comedy,Fox`).length!==3)throw Error(`a machine-joined list must split`);if(a(`Wilson, Michael G.`).length!==1)throw Error(`a comma followed by a space is prose, not a list`);if(a(`1987`).length!==1)throw Error(`a plain value must stay whole`);let u=Ue(r,`year`,{where:{subject:`Sitcom`}});if(u.distinct!==1||u.top[0].value!==`1987`)throw Error(`where must narrow the facet: ${JSON.stringify(u.top)}`);if(Ue(r,`year`,{where:{subject:`sitcom`}}).distinct!==1)throw Error(`where must match case-insensitively`);if(Ue(r,`year`,{where:{subject:`Sit`}}).distinct!==0)throw Error(`where must match whole values, not substrings`);let d=M(r,i,{limit:2});if(d.total!==4||d.rows.length!==2)throw Error(`browse must page: ${JSON.stringify(d)}`);if(d.collections.length!==0)throw Error(`a typeless corpus must report zero collections, not invent one`);if(M(r,i,{offset:3}).rows.length!==1)throw Error(`offset must page to the tail`);if(M(r,i,{offset:99}).rows.length!==0)throw Error(`an offset past the end must be empty, not wrapped`);let f=r.map(e=>({...e,entityType:e.id===`3`?`Film`:`Episode`})),p=M(f,i,{limit:1}).collections;if(p.map(e=>`${e.type}:${e.count}`).join()!==`Episode:3,Film:1`)throw Error(`collections must count and sort: ${JSON.stringify(p)}`);if(M(f,i,{type:`film`}).total!==1)throw Error(`type must match case-insensitively`);if(M(f,i,{type:`film`}).collections!==void 0)throw Error(`a typed browse is already inside a collection`);if(M(f,i,{type:`Episode`,where:{year:`1987`}}).total!==2)throw Error(`browse must honour where`);let m=[{id:`a`,rating:`9`},{id:`b`,rating:`10`},{id:`c`}],h=M(m,i,{sort:`rating`}).rows.map(e=>e.id);if(h.join()!==`b,a,c`)throw Error(`numeric sort + missing-last wrong: ${h}`);if(M(m,i,{sort:`rating`,desc:!1}).rows[0].id!==`a`)throw Error(`ascending sort ignored`);let g=We(r,`1`,i);if(g.near[0].id!==`2`)throw Error(`nearest neighbour missed the near-identical row`);if(g.near.some(e=>e.id===`1`))throw Error(`a row must not be its own neighbour`);if(g.near.some(e=>e.id===`4`))throw Error(`a vectorless row cannot be a neighbour`);if(We(r,`4`,i).near.length)throw Error(`a vectorless seed must return nothing, not throw`);if(We(r,`nope`,i).seed!==null)throw Error(`an unknown seed must be null, not undefined`);let _=N(r,`3`,i);if(_.name!==`Atomic Cafe`||!_.hasVector||_.vectorDim!==3)throw Error(`getRow lost the record`);if(`vector`in _||`norm`in _)throw Error(`the raw vector must never reach a tool result`);if(N(r,`nope`,i)!==null)throw Error(`an unknown id must be null`);let v=Le(n(`x`,{name:`n`,categories:`d`.repeat(500)}),e([{role_map:{title:`name`,tags:[`categories`]}}]));if(v.categories.length>200)throw Error(`brief must truncate a long field`);if(v.title!==`n`)throw Error(`brief must title from the declared field`);{let e=[{id:`a`,name:`cold war thriller`,year:1965,vector:[1,0],norm:1},{id:`b`,name:`cold war comedy`,year:1999,vector:[1,0],norm:1},{id:`c`,name:`beach party`,year:1964,vector:[0,1],norm:1},{id:`d`,name:`surf movie`,year:1966,vector:[0,1],norm:1}],t={title:[`name`],subtitle:[],tags:[],text:[`name`],measures:[],fields:[`year`]};if(!j(e,`cold war`,t,{qv:[1,0],limit:10}).some(e=>e.title===`cold war comedy`))throw Error(`unfiltered search must see every era`);let n=j(e,`cold war`,t,{qv:[1,0],limit:10,where:{year:1965}});if(n.length!==1||n[0].title!==`cold war thriller`)throw Error(`where must narrow a semantic search: ${JSON.stringify(n)}`);if(j(e,`cold war`,t,{qv:[0,1],limit:10,where:{year:1964}})[0]?.title!==`beach party`)throw Error(`the floor must be measured over the filtered rows`)}{let e=[{id:`a`,name:`cold war thriller`,vector:[1,0],norm:1}],t={title:[`name`],subtitle:[],tags:[],text:[`name`],measures:[],fields:[]},n=j(e,`cold war`,t,{qv:[1,0],limit:5});if(!Array.isArray(n))throw Error(`search must return a flat array, not {hits}`);if(n[0].score===void 0||n[0].mode===void 0)throw Error(`search rows carry score+mode`);for(let n of[void 0,null,``])if(N(e,n,t)!==null)throw Error(`getRow(${JSON.stringify(n)}) must be null`)}console.log(`tools.js self-check ok — coverage not schema, semantic/lexical modes + z-floor, list-ish facets + where, neighbours, whole-row fetch, previews truncate`)}var Ge=e=>e.reduce((e,t)=>Math.max(e,t.length),0);function Ke(e,t){let n=Ge(e);if(!n)return null;let r=new Float32Array(n),i=0;if(e.forEach((e,n)=>{let a=t[n];i+=a;for(let t=0;t<e.length;t++)r[t]+=e[t]*a}),!i)return null;for(let e=0;e<n;e++)r[e]/=i;return r}var qe=e=>{if(!e)return null;let t=T(e),n=new Float32Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]/t;return n};function P(e=[],t=[],{drift:n=.35}={}){let r=e.filter(e=>e?.vector?.length);if(!r.length)return null;let i=r.map((e,t)=>.5**((r.length-1-t)/8)),a=qe(Ke(r.map(e=>e.vector),i)),o=null;if(r.length>=4){let e=Math.floor(r.length/2),t=Ke(r.slice(e).map(e=>e.vector),i.slice(e)),n=Ke(r.slice(0,e).map(e=>e.vector),i.slice(0,e));if(t&&n){let e=new Float32Array(t.length);for(let r=0;r<e.length;r++)e[r]=t[r]-n[r];T(e)>1e-6&&(o=qe(e))}}let s=new Float32Array(a.length);for(let e=0;e<s.length;e++)s[e]=a[e]+(o?n*o[e]:0);let c=t.filter(e=>e?.vector?.length),l=c.length?qe(Ke(c.map(e=>e.vector),c.map(()=>1))):null;return{mu:a,v:o,q:qe(s),no:l,drift:n,from:r.map(e=>e.title??e.id).slice(-12),rejected:c.map(e=>e.title??e.id).slice(-12),n:r.length}}var Je=.6,Ye=(e,t)=>{if(!e?.vector||!t)return null;let n={vector:e.vector,norm:e.norm??T(e.vector)},r=w(n,t.q,T(t.q));return t.no?r-Je*Math.max(0,w(n,t.no,T(t.no))):r};function F(e,t,{limit:n=10,exclude:r=new Set,lambda:i=.7}={}){return t?oe(e.filter(e=>e.vector&&!r.has(e.id)).map(e=>({row:e,s:Ye(e,t)})).sort((e,t)=>t.s-e.s),{limit:n,lambda:i}).map(({row:e,s:t})=>({row:e,score:Number(t.toFixed(4))})):[]}var Xe={lookahead:[.35,`how far past what you like, toward where your recent likes are heading (the kernel's drift)`],variety:[.3,`how different the picks are from each other`],surprise:[0,`how much chance reorders the list; 0 is strict best-first`],reach:[0,`how far out from the closest matches to start: 0 is nearest, 1 skips the nearest ~400`]},Ze=(e,t)=>Math.min(1,Math.max(0,Number.isFinite(Number(e))?Number(e):t));function I(e,t=[],n=[],{limit:r=20,seed:i=1,exclude:a=new Set,...o}={}){let s=Object.fromEntries(Object.entries(Xe).map(([e,[t]])=>[e,Ze(o[e],t)])),c=P(t,n,{drift:s.lookahead});if(!c)return{taste:null,knobs:{...s,seed:i},picks:[]};let l=new Set([...a,...t.map(e=>e.id),...n.map(e=>e.id)]),u=e.filter(e=>e.vector&&!l.has(e.id)).map(e=>({row:e,s:Ye(e,c)})).sort((e,t)=>t.s-e.s),d=Math.round(s.reach*Math.min(400,u.length/4));if(u=u.slice(d,d+300),s.surprise){let e=Number(i)>>>0||1,t=()=>{e=e+1831565813>>>0;let t=Math.imul(e^e>>>15,1|e);return t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296};u=u.map(e=>({...e,s:e.s+.04*s.surprise*-Math.log(-Math.log(t()*.999998+1e-6))})).sort((e,t)=>t.s-e.s)}return{taste:{from:c.from,rejected:c.rejected,heading:!!c.v,n:c.n},knobs:{...s,seed:i},picks:oe(u,{limit:r,lambda:1-.6*s.variety}).map(({row:e,s:t})=>({row:e,score:Number(t.toFixed(4))}))}}var L=e=>e&&{v:1,model:`nomic-256`,drift:e.drift,n:e.n,q:S(Array.from(e.q)),mu:S(Array.from(e.mu)),...e.v?{d:S(Array.from(e.v))}:{},...e.no?{no:S(Array.from(e.no))}:{},from:e.from,rejected:e.rejected};function Qe(e){if(!e?.q)return null;let t=C(e.q),n=C(e.mu??e.q);return t?{q:t,mu:n??t,v:e.d?C(e.d):null,no:e.no?C(e.no):null,drift:e.drift??.35,from:e.from??[],rejected:e.rejected??[],n:e.n??0}:null}var $e=`(remembered`;function et(e,{carried:t=null,likes:n=[],dislikes:r=[]}={}){if(!e)return e;let i=t??{from:[],rejected:[],n:0},a=e=>e.filter(e=>!String(e?.id??``).startsWith($e)).map(e=>e.title??e.id),o=a(n);return{...e,v:e.v??i.v??null,from:[...i.from??[],...o].slice(-12),rejected:[...i.rejected??[],...a(r)].slice(-12),n:(i.n??0)+o.length}}if(typeof process<`u`&&import.meta.url===`file://${process.argv[1]}`&&process.argv[1].endsWith(`/taste.js`)){{let e=F([{id:`a`,vector:[1,0],norm:1},{id:`b`,vector:[0,1],norm:1}],{q:[1,0]});if(!e.length)throw Error(`recommend must rank rows with vectors`);if(e[0].row===void 0)throw Error(`recommend rows carry .row`);if(typeof e[0].score!=`number`)throw Error(`recommend rows carry .score (not .s)`)}let e=(e,t,n=e)=>({id:e,title:n,vector:Float32Array.from(t),norm:T(t)}),t=[1,0,0],n=[0,1,0],r=[0,0,1],i=(e,t,n)=>e.map((e,r)=>e*(1-n)+t[r]*n),a=P([e(`a`,t),e(`b`,i(t,r,.2)),e(`c`,i(t,r,.1))]);if(!a)throw Error(`three likes must make a taste`);if(a.v!==null)throw Error(`under four picks there is no older half — direction must not be invented`);if(w({vector:a.q,norm:T(a.q)},Float32Array.from(t),1)<.9)throw Error(`q must sit near what was liked`);let o=[e(`x`,n,`a comedy`),e(`y`,i(t,r,.15),`a bleak documentary`),e(`z`,r,`a documentary`)];if(F(o,a)[0].row.title!==`a bleak documentary`)throw Error(`taste must rank an unseen pool`);let s=[e(`1`,t),e(`2`,i(t,n,.2)),e(`3`,i(t,n,.4)),e(`4`,i(t,n,.6))];if(a=P(s),a.v===null)throw Error(`four picks must yield a direction`);let c=w({vector:a.q,norm:T(a.q)},Float32Array.from(n),1),l=w({vector:a.mu,norm:T(a.mu)},Float32Array.from(n),1);if(!(c>l))throw Error(`q must lean further toward where it is heading than mu: ${c} vs ${l}`);let u=P(s,[],{drift:0});if(w({vector:u.q,norm:T(u.q)},u.mu,T(u.mu))<.999)throw Error(`drift 0 must be mu`);let d=[e(`p`,i(t,n,.7))],f=[e(`m`,t,`bleak`),e(`n`,n,`comic`)];if(F(f,P(d))[0].row.title!==`comic`)throw Error(`sanity: the taste leans comic`);if(F(f,P(d,[e(`q`,n)]))[0].row.title!==`bleak`)throw Error(`rejecting comic must flip the ranking to bleak`);let p=e(`a`,t,`the one they liked`);if(F([p,e(`other`,i(t,r,.1),`similar`)],P([p]),{exclude:new Set([`a`])}).some(e=>e.row.id===`a`))throw Error(`must not recommend what the taste was built from`);a=P(s);let m=L(a),h=JSON.stringify(m).length,g=Qe(m);if(!g)throw Error(`a taste must survive the round trip`);let _=F(o,a).map(e=>e.row.id).join(),v=F(o,g).map(e=>e.row.id).join();if(_!==v)throw Error(`ranking changed across the wire: ${_} vs ${v}`);if(!m.from.length)throw Error(`a taste must say what it was built from, or it cannot be corrected`);if(!a.v)throw Error(`this fixture is meant to have a heading`);if(!g.v)throw Error(`a heading must survive the wire — q leans on it, so an export without it lies`);if(w({vector:g.v,norm:T(g.v)},a.v,T(a.v))<.98)throw Error(`…and must survive it intact`);if(Qe({})!==null||Qe(null)!==null)throw Error(`a malformed taste must be null, not a crash`);if(P([])!==null)throw Error(`no likes is no taste, not an empty one`);if(F(o,null).length)throw Error(`no taste recommends nothing`);if(Ye({vector:null},a)!==null)throw Error(`a vectorless row scores null, not NaN`);{let e=(e,t)=>{let n=t*Math.PI/180;return{id:e,vector:[Math.cos(n),Math.sin(n)],norm:1}},t=[e(`run1`,0),e(`run2`,.8),e(`run3`,1.6),e(`run4`,2.4),e(`other`,60)],n=P([{id:`seed`,...e(`seed`,30)}]),r=F(t,n,{limit:3,lambda:1}).map(e=>e.row.id);if(r.some(e=>e===`other`))throw Error(`relevance alone must fill up with the run: ${r}`);let i=F(t,n,{limit:3}).map(e=>e.row.id);if(!i.includes(`other`))throw Error(`MMR must spend a slot on something else: ${i}`);if(i[0]!==r[0])throw Error(`the best match must still come first: ${i[0]} vs ${r[0]}`)}{let a=L(P([e(`a`,t,`The Golem`),e(`b`,n,`Nosferatu`),e(`c`,r,`Metropolis`)],[e(`z`,r,`Wrestling`)]));if(a.n!==3||a.from.length!==3)throw Error(`a fresh export carries what it was built from`);let o=Qe(a),s=[{id:`(remembered)`,title:`what you liked before · ${o.n} picks`,vector:o.q}],c=o.no?[{id:`(remembered-no)`,title:`what you passed on before`,vector:o.no}]:[];if(L(P(s,c)).n!==1)throw Error(`this is the loss the next assertion is about`);let l=L(et(P(s,c),{carried:o,likes:s,dislikes:c}));if(l.n!==3)throw Error(`a restored taste must not report itself as one pick: ${l.n}`);if(!l.from.includes(`Nosferatu`))throw Error(`…and must still name what it was built from`);if(l.from.some(e=>e.startsWith(`(remembered`)))throw Error(`the synthetic placeholder is not a title`);if(!l.rejected.includes(`Wrestling`))throw Error(`rejections are provenance too`);let u=[...s,e(`d`,n,`Sunrise`)],d=L(et(P(u,c),{carried:o,likes:u,dislikes:c}));if(d.n!==4)throw Error(`a new pick must count once: ${d.n}`);if(d.from.filter(e=>e===`Nosferatu`).length!==1)throw Error(`…and must not duplicate the carried ones`);{let r=Qe(L(P([e(`p`,t,`1`),e(`q`,i(t,n,.3),`2`),e(`r`,i(t,n,.6),`3`),e(`s`,n,`4`)]))),a=[{id:`(remembered)`,title:`before`,vector:r.q}];if(!et(P(a),{carried:r,likes:a}).v)throw Error(`a restored session must keep the heading its own q was built with`);if(P(a).v)throw Error(`…which the kernel alone cannot supply from one entry`)}let f=L(et(P(s,c),{carried:Qe(l),likes:s,dislikes:c}));if(f.n!==3||f.from.join()!==l.from.join())throw Error(`a second reload must change nothing`)}{let e=Array.from({length:40},(e,t)=>{let n=t*Math.PI/80;return{id:`g${t}`,title:`g${t}`,vector:[Math.cos(n),Math.sin(n)],norm:1}}),t=[e[0]],n=[e[39]],r=e=>e.picks.map(e=>e.row.id).join(),i=I(e,t,n,{limit:5});if(i.picks[0].row.id!==`g1`)throw Error(`nearest first by default: ${r(i)}`);if(i.picks.some(e=>e.row.id===`g0`||e.row.id===`g39`))throw Error(`discover must not return what was voted on`);if(I(e,t,[],{limit:5,reach:1}).picks[0].row.id===`g1`)throw Error(`reach must skip the nearest`);if(r(I(e,t,[],{limit:5,surprise:1,seed:7}))!==r(I(e,t,[],{limit:5,surprise:1,seed:7})))throw Error(`the same seed must give the same list`);if(I(e,[],[],{}).picks.length)throw Error(`no likes, no picks`)}console.log(`taste.js self-check ok — discover's knobs, mu/v/q, drift leans forward, rejection steers, portable in ${h}B, ranks a pool it never saw, MMR keeps a run of near-duplicates from filling the list, provenance and heading survive the restore collapse and do not drift on reload`)}var R=e=>({content:[{type:`text`,text:JSON.stringify(e)}]}),z=(e,t=[])=>({type:`object`,properties:e,required:t});function tt(e){let t=document.modelContext;t?.registerTool&&(t.registerTool({name:`describe`,description:`What this app holds: its fields and how often each is present. Call it first.`,inputSchema:z({}),execute:async()=>R(Re(e.rows))}),t.registerTool({name:`search`,description:"Search by meaning: a question in plain words. Optional equality filters in `where`.",inputSchema:z({query:{type:`string`},limit:{type:`number`},where:{type:`object`}},[`query`]),execute:async({query:t,limit:n=10,where:r})=>R(j(e.rows,t,e.roles,{qv:await e.queryVector(t),limit:n,where:r}))}),t.registerTool({name:`get`,description:`One record in full, by the id search returns.`,inputSchema:z({id:{type:`string`}},[`id`]),execute:async({id:t})=>R(N(e.rows,t,e.roles)??{error:`no record ${t}`})}),t.registerTool({name:`count`,description:`Count the distinct values of a field: the shape of the data before reading it.`,inputSchema:z({field:{type:`string`},where:{type:`object`},limit:{type:`number`}},[`field`]),execute:async({field:t,where:n,limit:r=20})=>R(Ue(e.rows,t,{where:n,limit:r}))}),t.registerTool({name:`session`,description:`What the person on this page saved and searched this session, and the taste (a vector over this app's records) their choices make.`,inputSchema:z({}),execute:async()=>R(e.session?.()??{saved:[],searches:[],taste:null})}),t.registerTool({name:`rate`,description:`Record that the person liked or disliked a record (or clear it), by the id search returns. Builds the taste discover ranks with.`,inputSchema:z({id:{type:`string`},verdict:{type:`string`,enum:[`like`,`dislike`,`clear`]}},[`id`,`verdict`]),execute:async({id:t,verdict:n})=>R(e.rate?.(t,n)??{error:`this page keeps no taste`})}),t.registerTool({name:`discover`,description:`Records for a taste: a kernel over what was liked (newest last) and disliked, not a text search. Pass likes and dislikes (ids from search), or omit them to use the taste on this page. Knobs are 0–1.`,inputSchema:z({likes:{type:`array`,items:{type:`string`}},dislikes:{type:`array`,items:{type:`string`}},...Object.fromEntries(Object.entries(Xe).map(([e,[t,n]])=>[e,{type:`number`,minimum:0,maximum:1,default:t,description:n}])),seed:{type:`integer`,description:`Same seed, same shuffle`},limit:{type:`integer`,minimum:1,maximum:50,default:10}}),execute:async({likes:t,dislikes:n,limit:r=10,...i})=>{let a=t=>t.map(t=>e.rows.find(n=>n.id===N(e.rows,t,e.roles)?.id)).filter(e=>e?.vector),o=t?{likes:a(t),dislikes:a(n??[])}:e.votes?.()??{likes:[],dislikes:[]};if(!o.likes.length)return R({error:`like at least one record first (ids from search, or rate)`});let s=I(e.rows,o.likes,o.dislikes,{...i,limit:Math.min(50,r)});return R({...s,picks:s.picks.map(({row:t,score:n})=>({...N(e.rows,t.id,e.roles),score:n}))})}}))}function nt(e,t){let n=t=>new Set(e.slice(0,5e3).flatMap(e=>a(e[t]??``))).size;return t.facets?.[0]??t.tags.find(e=>{let t=n(e);return t>=2&&t<=12})??null}function rt(e,t,{facet:r=null,only:a=null,today:o=new Date().toISOString().slice(0,10)}={}){let c=new Map;for(let o of e){let e=String(n(o,t.temporal)??``).slice(0,10);if(!e)continue;let l=r?String(o[r]??``):``;if(a&&l!==a)continue;let u=i(o,t)??``,d=`${l}|${u}|${e}`,f=c.get(d);f||c.set(d,f={key:d,date:e,place:l,label:u,byTitle:new Map});let p=s(o,t).toLowerCase(),m=f.byTitle.get(p);(!m||B(m,t).length<B(o,t).length)&&f.byTitle.set(p,o)}let l=[...c.values()].map(({byTitle:e,...t})=>({...t,items:[...e.values()]}));return{upcoming:l.filter(e=>e.date>o).sort((e,t)=>e.date.localeCompare(t.date)||e.place.localeCompare(t.place)),past:l.filter(e=>e.date<=o).sort((e,t)=>t.date.localeCompare(e.date)||e.place.localeCompare(t.place))}}function B(e,t){let n=s(e,t),r=String(e.text??``),i=r.startsWith(n.replace(/\.$/,``))?r.slice(n.replace(/\.$/,``).length).replace(/^[.\s]+/,``):r;return i===n?``:i.trim()}if(typeof process<`u`&&process.argv[1]?.endsWith(`/feed.js`)){let{rolesFrom:e}=await t(async()=>{let{rolesFrom:e}=await import(`./roles-YDRjv_PY.js`);return{rolesFrom:e}},__vite__mapDeps([4,5]),import.meta.url),n=e([{role_map:{title:`heading`,subtitle:`meeting`,temporal:`date`,tags:[`city`,`body`],text:[`text`]},presentation:{facets:[`city`]}}]),r=(e,t,n,r=n)=>({city:e,date:t,heading:n,meeting:`Board · ${t}`,body:`Board`,text:r}),i=[r(`A`,`2026-01-01`,`Budget`),r(`A`,`2026-01-01`,`Budget`,`Budget. Approved 5-0.`),r(`A`,`2026-01-01`,`Roads`),r(`B`,`2026-02-01`,`Parks`),r(`A`,`2026-03-01`,`Zoning`),{heading:`undated`}],a=(e,t,n)=>{if(JSON.stringify(e)!==JSON.stringify(t))throw Error(`${n}: ${JSON.stringify(e)}`)};a(nt(i,n),`city`,`the declared facet wins`);let{upcoming:o,past:s}=rt(i,n,{facet:`city`,today:`2026-02-15`});a(o.map(e=>e.key),[`A|Board · 2026-03-01|2026-03-01`],`a future date is coming up`),a(s.map(e=>`${e.place}${e.date}`),[`B2026-02-01`,`A2026-01-01`],`past, latest first`),a(s[1].items.map(e=>B(e,n)),[`Approved 5-0.`,``],`one item per title, the one that says what happened`),a(rt(i,n,{facet:`city`,only:`B`,today:`2026-02-15`}).past.length,1,`narrowed to one place`),console.log(`feed.js self-check ok — declared facet, upcoming vs past, one item per title keeping the decision, narrowed by place`)}var it=(e,t,n)=>{try{return JSON.parse(e?.getItem(t)??`null`)??n}catch{return n}},V=(e,t,n)=>{try{e?.setItem(t,JSON.stringify(n))}catch{}};function at({local:e,session:t,app:n=`app`}={}){let r={saved:`${n}:saved`,passed:`${n}:passed`,history:`${n}:history`};return{saved:()=>it(e,r.saved,[]),passed:()=>it(e,r.passed,[]),history:()=>it(t,r.history,[]),isSaved(e){return this.saved().some(t=>t.key===e)},toggleSave(t){let n=this.saved(),i=n.findIndex(e=>e.key===t.key);return i>=0?n.splice(i,1):n.push({...t,savedAt:new Date().toISOString()}),V(e,r.saved,n),V(e,r.passed,this.passed().filter(e=>e.key!==t.key)),i<0},pass(t){V(e,r.passed,[...this.passed().filter(e=>e.key!==t.key),t].slice(-50)),V(e,r.saved,this.saved().filter(e=>e.key!==t.key))},unvote(t){V(e,r.saved,this.saved().filter(e=>e.key!==t)),V(e,r.passed,this.passed().filter(e=>e.key!==t))},remember(e){let n=e.trim();n&&V(t,r.history,[{q:n,at:new Date().toISOString()},...this.history().filter(e=>e.q!==n)].slice(0,50))},clear(n){V(n===`history`?t:e,r[n],[])},votes(){let e=e=>({id:e.key,title:e.title,vector:e.v?C(e.v):null});return{likes:this.saved().map(e),dislikes:this.passed().map(e)}},taste(){let{likes:e,dislikes:t}=this.votes();return P(e,t)},bundle({name:e=n,url:t=``}={}){return{app:e,url:t,exported:new Date().toISOString(),saved:this.saved().map(({v:e,...t})=>t),searches:this.history(),taste:L(this.taste())}}}}var ot=(e,{key:t,title:n,subtitle:r,place:i,date:a,link:o,detail:s})=>({key:t,title:n,subtitle:r,place:i,date:a,url:o??null,detail:s??``,...e.vector?{v:S(Array.from(e.vector))}:{}}),st=e=>`"${String(e??``).replace(/"/g,`""`)}"`,ct=e=>[`title,place,subtitle,date,url,detail`,...e.map(e=>[e.title,e.place,e.subtitle,e.date,e.url,e.detail].map(st).join(`,`))].join(`
7
7
  `),lt=(e,t=`Saved`)=>[`# ${t}`,``,...e.map(e=>`- **${e.url?`[${e.title}](${e.url})`:e.title}** — ${[e.place,e.subtitle].filter(Boolean).join(` · `)}${e.detail?`\n ${e.detail}`:``}`)].join(`
8
- `);if(typeof process<`u`&&process.argv[1]?.endsWith(`/store.js`)){let e=()=>{let e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>e.set(t,n)}},t=at({local:e(),session:e(),app:`t`}),n=e=>({vector:Array.from({length:8},(t,n)=>n===e?1:.1)}),r=ot(n(0),{key:`a`,title:`Budget`,place:`X`,date:`2026-01-01`}),i=ot(n(1),{key:`b`,title:`Roads, "east"`,place:`Y`}),a=(e,t,n)=>{if(JSON.stringify(e)!==JSON.stringify(t))throw Error(`${n}: ${JSON.stringify(e)}`)};if(a(t.taste(),null,`no taste before a save`),t.toggleSave(r),t.toggleSave(i),a(t.saved().map(e=>e.key),[`a`,`b`],`saved in order`),!t.taste()?.q)throw Error(`saves make a taste`);t.pass(i),a([t.saved().map(e=>e.key),t.passed().map(e=>e.key)],[[`a`],[`b`]],`passing on an item unsaves it`),a(t.taste().rejected,[`Roads, "east"`],`and it steers the taste away`),t.remember(`snow`),t.remember(`budget`),t.remember(`snow`),a(t.history().map(e=>e.q),[`snow`,`budget`],`history: newest first, no repeats`);let o=t.bundle({name:`T`});if(o.saved[0].v||!o.taste?.q||o.searches.length!==2)throw Error(`the bundle carries choices and taste, not raw vectors`);if(!ct([i]).includes(`"Roads, ""east"""`))throw Error(`CSV quoting`);if(at({local:{getItem(){throw Error(`blocked`)},setItem(){throw Error(`blocked`)}}}).saved().length!==0)throw Error(`blocked storage reads as empty`);console.log(`store.js self-check ok — saves and passes steer a taste, history dedupes, the bundle carries no raw vectors, CSV quotes, blocked storage is empty not fatal`)}var ut=`http://www.w3.org/2000/svg`,dt=(e,t={})=>{let n=document.createElementNS(ut,e);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);return n},ft=e=>e.toLocaleString(),pt=new Set([`state`]);function mt(e,{el:t,show:n,row:r,placeOf:i,ctx:s}){let c=s.roles,l=Object.keys(e.paths),u=null,d=null,f=null,p={q:``,hits:null};function m(){if(u?.n===s.rows.length)return u;let t=s.rows.map(t=>{let n=a(t[e.field]??``).filter(t=>e.paths[t]);return n.length?n:[e.places?.[i(t)]].filter(Boolean)}),n=new Map;for(let e of s.rows){let t=o(e);n.set(t,(n.get(t)??0)+1)}let r=[...n].sort((e,t)=>t[1]-e[1])[0]?.[0],c=new Map(l.map(e=>[e,[]]));s.rows.forEach((e,n)=>{for(let e of t[n])c.get(e)?.push(n)});let d=0,f=null,p=0,m=new Map;s.rows.forEach((e,n)=>{if(!e.vector||o(e)!==r||!t[n].length)return;d||=e.vector.length,f??=new Float64Array(d);let i=1/(e.norm||Math.hypot(...e.vector)||1);for(let r of t[n]){let t=m.get(r)??{v:new Float64Array(d),n:0};for(let n=0;n<d;n++)t.v[n]+=e.vector[n]*i;t.n++,m.set(r,t)}for(let t=0;t<d;t++)f[t]+=e.vector[t]*i;p++});let h=new Map;for(let[e,t]of m){if(t.n<20)continue;let n=t.v.map((e,n)=>e/t.n-f[n]/p),r=Math.hypot(...n)||1;h.set(e,n.map(e=>e/r))}return u={n:s.rows.length,regionsOf:t,by:c,main:r,types:n,centroid:h},u}function h(e){let{centroid:t}=m(),n=t.get(e);return n?[...t].filter(([t])=>t!==e).map(([e,t])=>({region:e,score:t.reduce((e,t,r)=>e+t*n[r],0)})).sort((e,t)=>t.score-e.score).slice(0,5):[]}let g=(e,t=2)=>{let n=c.types?.[e];return(t===1?n?.singular:n?.plural)??e??`Records`},_=e=>c.types?.[e]?.icon??``;function v(e){let{regionsOf:t}=m(),n=new Map,r=e??s.rows.map((e,t)=>t);for(let e of r)if(!(f&&o(s.rows[e])!==f))for(let r of t[e])n.set(r,(n.get(r)??0)+1);return n}async function y(e){if(!e)return null;if(p.q===e&&p.hits)return p.hits;let t=s.queryVector(e),n=await Promise.race([t,new Promise(e=>setTimeout(()=>e(void 0),400))]);return n===void 0&&t.then(t=>{t&&p.q===e&&!p.meaning&&(p={q:e,hits:ee(e,t),meaning:!0},x(e,d))}),p={q:e,hits:ee(e,n??null),meaning:n!==void 0},p.hits}function ee(e,t){let n=new Map(s.rows.map((e,t)=>[e.id,t]));return j(s.rows,e,c,{qv:t,limit:600}).map(e=>n.get(e.id)).filter(e=>e!=null)}let b=(e,t=d)=>{location.hash=`#/map/${encodeURIComponent(e)}${t?`/${encodeURIComponent(t)}`:``}`};async function x(r=``,i=null){d=i&&e.paths[i]?i:null;let a=await y(r),c=v(a),u=Math.max(1,...c.values()),ee=e=>e?Math.min(5,1+Math.floor((a?e/u:Math.log10(e)/Math.log10(u))*4.999)):0,ne=d?new Set(h(d).map(e=>e.region)):new Set,S=dt(`svg`,{viewBox:`0 0 ${e.width} ${e.height}`,role:`img`,"aria-label":a?`Map: where “${r}” comes up`:`Map: where records are`,class:`map`});for(let t of l){let n=dt(`path`,{d:e.paths[t],class:`h${ee(c.get(t)??0)}${t===d?` on`:``}${ne.has(t)?` near`:``}`,tabindex:0,"aria-label":`${t}: ${ft(c.get(t)??0)}`});n.append(dt(`title`)),n.firstChild.textContent=`${t} · ${ft(c.get(t)??0)} ${a?`matching`:(f?g(f):`records`).toLowerCase()}`;let i=()=>b(r,d===t?null:t);n.addEventListener(`click`,i),n.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i())}),S.append(n)}let C=t(`input`,{type:`search`,value:r,placeholder:`Search the map: data center, PFAS, solar rezoning…`,"aria-label":`Search the map`});C.addEventListener(`keydown`,e=>{e.key===`Enter`&&b(C.value.trim())});let re=a?new Map:m().types;for(let e of a??[]){let t=o(s.rows[e]);re.set(t,(re.get(t)??0)+1)}let ie=re.size>1||a?t(`div`,{className:`chips`},[[null,a?.length??s.rows.length],...re].map(([e,n])=>t(`button`,{type:`button`,className:e===f?`chip on`:`chip`,onclick:()=>{f=e,x(r,d)}},`${e?`${_(e)} ${g(e,n)}`:`All`} (${ft(n)})`))):null,w=l.filter(e=>c.get(e)).length,T=a?`“${r}”: ${ft([...c.values()].reduce((e,t)=>e+t,0))} matches in ${w} of ${l.length} regions. Darker is more.${p.meaning?``:` (Matching words; search by meaning is loading.)`}`:`${f?g(f):`Records`} in ${w} of ${l.length} regions. Select a region, or search.`;n(t(`div`,{className:`mapbar`},C),ie,t(`p`,{className:`hint`},T),t(`div`,{className:`mapwrap`},S,t(`aside`,{className:`panel`},te(d,r,a))),t(`p`,{className:`hint`},`Legend: `,[0,1,2,3,4,5].map(e=>t(`span`,{className:`sw h${e}`})),a?` none → most matches`:` none → most records`))}function te(n,i,l){if(!n)return[t(`h3`,{},`Select a region`),t(`p`,{className:`hint`},`Its records by kind and tag, the ones that match, and the regions most like it.`)];let{by:u}=m(),d=new Set(u.get(n)),p=(l?l.filter(e=>d.has(e)):[...d]).filter(e=>!f||o(s.rows[e])===f).map(e=>s.rows[e]),v=new Map;for(let e of p){let t=o(e);v.set(t,(v.get(t)??0)+1)}let y=(c.tags??[]).filter(t=>t!==e.field&&!pt.has(t)).map(e=>{let t=new Map;for(let n of p)for(let r of a(n[e]??``))t.set(r,(t.get(r)??0)+1);return[e,[...t].sort((e,t)=>t[1]-e[1]).slice(0,6)]}).filter(([,e])=>e.length>1),ee=e=>String(e[c.temporal?.[0]]??``),x=(l?p:p.slice().sort((e,t)=>ee(t).localeCompare(ee(e)))).slice(0,25),te=h(n);return[t(`h3`,{},n,` `,t(`button`,{type:`button`,className:`linkish`,"aria-label":`Close`,onclick:()=>b(i,null)},`✕`)),t(`p`,{className:`hint`},[...v].map(([e,t])=>`${_(e)} ${ft(t)} ${g(e,t).toLowerCase()}`).join(` · `)||`Nothing here`+(l?` matches.`:` yet.`)),te.length?t(`div`,{className:`chips`},t(`small`,{title:`Regions whose records are closest in meaning; outlined on the map`},`Reads most like: `),te.map(({region:e})=>t(`button`,{type:`button`,className:`chip`,onclick:()=>b(i,e)},e))):null,y.map(([e,n])=>t(`div`,{className:`chips`},t(`small`,{},`${e.replace(/_/g,` `)}: `),n.map(([e,n])=>t(`button`,{type:`button`,className:`chip`,title:`Search the map for “${e}”`,onclick:()=>b(e)},`${e} (${n})`)))),x.length?t(`ul`,{className:`list`},x.map(e=>r(e))):null,p.length>x.length?t(`p`,{className:`hint`},`${ft(p.length-x.length)} more. `,t(`a`,{href:`#/search/${encodeURIComponent(i||n)}`},`Open in search`)):null]}return{render:x}}var H=e=>document.querySelector(e),U=(e,t={},...n)=>{let r=Object.assign(document.createElement(e),t);return r.append(...n.flat(1/0).filter(e=>e!=null&&e!==!1)),r},ht=(e,t=220)=>e.length>t?`${e.slice(0,e.lastIndexOf(` `,t))} …`:e,gt=e=>e?new Date(`${String(e).slice(0,10)}T12:00:00`).toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`,year:`numeric`}):``,W={rows:[],roles:r([]),queryVector:e=>ne(e).catch(()=>null)},_t,vt=new Promise(e=>{_t=e});O({onManifests:e=>{W.roles=r(e),_t()},rowText:e=>l(e,W.roles)});var yt=await fetch(`./.well-known/agent-card.json`).then(e=>e.json()).catch(()=>({})),bt=(yt.capabilities?.extensions??[]).map(e=>e.params?.paid).find(Boolean)??null,G=yt.name??`Fangorn app`;document.title=G,H(`#name`).textContent=G,fetch(`./nav.json`).then(e=>e.json()).then(e=>H(`nav`).append(...e.map(e=>U(`a`,{href:e.href},e.label)))).catch(()=>{});var xt=await fetch(`./map.json`).then(e=>(e.headers.get(`content-type`)??``).includes(`json`)?e.json():null).catch(()=>null);xt&&H(`nav`).prepend(U(`a`,{href:`#/map`},`Map`));var St=H(`#q input`);St.disabled=!1;var Ct=G.toLowerCase().replace(/\W+/g,`-`),K=at({local:globalThis.localStorage,session:globalThis.sessionStorage,app:Ct});W.session=()=>K.bundle({name:G,url:location.origin});var wt=new URL(`view`,location.href).href,Tt=await fetch(`${wt}/cdn/catalog`).then(e=>e.json()).then(e=>e.domains.reduce((e,t)=>e+(t.count??0),0)).catch(()=>0),Et=!1,Dt=0,Ot=A(wt,e=>{W.rows=e,Nt(),Date.now()-Dt>1500&&/^(#\/?)?$/.test(location.hash)&&(Dt=Date.now(),un())});await vt;var q=W.roles,kt=e=>String((q.identity&&e[q.identity])??e.id),At=new Map,jt=new Map,J=null,Mt=[];function Nt(){At=new Map(W.rows.map(e=>[kt(e),e])),jt=new Map(W.rows.map(e=>[e.id,e])),J??=nt(W.rows,q),Mt=J?[...W.rows.reduce((e,t)=>{let n=Y(t);return n&&e.set(n,(e.get(n)??0)+1),e},new Map)].sort((e,t)=>e[0].localeCompare(t[0])):[];let e=W.rows.length.toLocaleString();St.placeholder=Et?`Search ${e} records${Mt.length>1?` in ${Mt.length} places`:``}…`:`Loading ${e}${Tt?` of ${Tt.toLocaleString()}`:``} records… (search what is here)`}var Y=e=>J?a(e[J]??``)[0]??``:``,Pt=e=>String(e[q.temporal?.[0]]??``).slice(0,10),Ft=e=>d(e,q),It=e=>ot(e,{key:kt(e),title:s(e,q),subtitle:i(e,q),place:Y(e),date:Pt(e),link:Ft(e),detail:B(e,q)}),Lt=e=>/[a-z]/.test(e)||!/[A-Z]{5}/.test(e)?e:e.toLowerCase().replace(/\b[a-z]{1,3}\b/g,(e,t)=>/^(and|or|of|the|to|for|in|on|at|by|a|an|as|is|be|no|from)$/.test(e)?e:e.toUpperCase()).replace(/^\W*\w/,e=>e.toUpperCase()).replace(/([.:;!?]\s+|\u2013\s+|-\s+)(\w)/g,(e,t,n)=>t+n.toUpperCase()),Rt=e=>Lt(s(e,q)),zt=e=>`#/item/${encodeURIComponent(kt(e))}`,Bt=(e,t)=>{if(!t.length)return[e];let n=RegExp(`(${t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})`,`ig`);return String(e).split(n).map((e,t)=>t%2?U(`mark`,{},e):e)},Vt=e=>K.isSaved(e)?`like`:K.passed().some(t=>t.key===e)?`dislike`:null;W.rate=(e,t)=>{if(![`like`,`dislike`,`clear`].includes(t))return{error:`verdict is like, dislike or clear`};let n=jt.get(e)??At.get(String(e))??jt.get(N(W.rows,e,q)?.id);if(!n)return{error:`no record ${e}`};let r=kt(n);return K.unvote(r),t===`like`&&K.toggleSave(It(n)),t===`dislike`&&K.pass(It(n)),Ut(),ln(),/^#\/for-you/.test(location.hash)&&on(),{likes:K.saved().map(e=>e.title),dislikes:K.passed().map(e=>e.title)}},W.votes=()=>{let e=e=>{let t=At.get(e.id);return t?{id:t.id,title:e.title,vector:t.vector}:e},{likes:t,dislikes:n}=K.votes();return{likes:t.map(e).filter(e=>e.vector),dislikes:n.map(e).filter(e=>e.vector)}};var Ht=e=>U(`span`,{className:`votes`},[[`like`,`👍`,`I like this`],[`dislike`,`👎`,`Not for me`]].map(([t,n,r])=>{let i=U(`button`,{type:`button`,className:`vote`,title:r,ariaLabel:`${r}: ${s(e,q)}`,onclick:n=>{n.preventDefault(),W.rate(e.id,Vt(kt(e))===t?`clear`:t)}},n);return Object.assign(i.dataset,{key:kt(e),vote:t}),i}));function Ut(){for(let e of document.querySelectorAll(`button.vote`))e.setAttribute(`aria-pressed`,String(Vt(e.dataset.key)===e.dataset.vote))}var X=(e,{terms:t=[],also:n=0,meta:r=!0}={})=>{let a=B(e,q);return U(`li`,{className:`row`},U(`div`,{className:`main`},U(`a`,{href:zt(e),className:`title`},Bt(Rt(e),t)),r?U(`small`,{},[Y(e),i(e,q)].filter(Boolean).join(` · `)):null,a?U(`p`,{className:`detail`},Bt(ht(a),t)):null,n?U(`small`,{className:`also`},`and ${n} more record${n>1?`s`:``} of the same item`):null),Ht(e))},Z=null,Wt=()=>Mt.length>1?U(`div`,{className:`chips`},[[null,W.rows.length],...Mt].map(([e,t])=>U(`button`,{type:`button`,className:e===Z?`chip on`:`chip`,title:`${t.toLocaleString()} records`,onclick:()=>{Z=e,un()}},e??`All`))):null,Gt=e=>!Z||Y(e)===Z,Kt=H(`#view`),Q=(...e)=>{Kt.replaceChildren(...e.flat().filter(Boolean)),Ut(),window.scrollTo(0,0)};function qt(e){let t=U(`ul`,{},e.items.slice(0,5).map(e=>X(e,{meta:!1}))),n=e.items.length>5?U(`button`,{type:`button`,className:`more`,onclick:n=>{t.append(...e.items.slice(5).map(e=>X(e,{meta:!1}))),n.target.remove()}},`${e.items.length-5} more`):null;return U(`article`,{},U(`header`,{},U(`time`,{dateTime:e.date},gt(e.date)),U(`h3`,{},[e.place,e.label.replace(/\s*·\s*\d{4}-\d\d-\d\d$/,``)].filter(Boolean).join(` — `))),t,n)}var Jt=12;function Yt(){let{upcoming:e,past:t}=rt(W.rows,q,{facet:J,only:Z}),{likes:n,dislikes:r}=W.votes(),i=I(W.rows.filter(Gt),n,r,{...$,limit:6});Q(yt.description?U(`p`,{className:`about`},yt.description):null,Wt(),i.picks.length?U(`section`,{},U(`h2`,{},`For you`),U(`p`,{className:`hint`},`From the ${i.taste.n} item${i.taste.n>1?`s`:``} you liked. `,U(`a`,{href:`#/for-you`},`Tune`)),U(`ul`,{className:`list`},i.picks.map(({row:e})=>X(e)))):null,e.length?U(`section`,{},U(`h2`,{},`Coming up`),e.slice(0,8).map(qt)):null,t.length?U(`section`,{},U(`h2`,{},`Recently`),t.slice(0,Jt).map(qt),t.length>Jt?U(`button`,{type:`button`,className:`more`,onclick:()=>{Jt+=12,Yt()}},`Show more`):null):null,!e.length&&!t.length?U(`p`,{className:`empty`},Et?`Nothing dated here yet. Search above.`:`Loading the records…`):null)}var Xt=`relevance`,Zt=0,Qt=null;async function $t(e){document.activeElement!==H(`#q input`)&&(H(`#q input`).value=e);let t=++Zt,n=W.queryVector(e),r=await Promise.race([n,new Promise(e=>setTimeout(()=>e(void 0),400))]);t===Zt&&(r===void 0&&n.then(n=>{n&&t===Zt&&en(e,n)}),en(e,r??null,r===void 0))}function en(e,t,n=!1){let r=j(W.rows,e,q,{qv:t,limit:80,...Z&&J?{where:{[J]:Z}}:{}}),i=new Map;for(let e of r){let t=jt.get(e.id);if(!t)continue;let n=`${Y(t)}|${s(t,q).toLowerCase()}`,r=i.get(n);r?(r.also++,B(t,q).length>B(r.r,q).length&&(r.r=t)):i.set(n,{r:t,also:0})}let a=[...i.values()];Xt===`newest`&&(a=a.sort((e,t)=>Pt(t.r).localeCompare(Pt(e.r))));let o=e.toLowerCase().split(/\W+/).filter(e=>e.length>2),c=U(`div`,{className:`sort`},`Sort: `,[`relevance`,`newest`].map(r=>U(`button`,{type:`button`,className:r===Xt?`chip on`:`chip`,onclick:()=>{Xt=r,en(e,t,n)}},r)));Q(Wt(),U(`div`,{className:`resultsbar`},U(`span`,{},`${a.length} result${a.length===1?``:`s`} for “${e}”${Z?` in ${Z}`:``}`,n?U(`small`,{},` · matching words; search by meaning is loading`):null),c),a.length?U(`ul`,{className:`list`},a.slice(0,40).map(({r:e,also:t})=>X(e,{terms:o,also:t}))):U(`p`,{className:`empty`},`No matches. Try other words, or All places.`))}function tn(e){let t=At.get(e);if(!t)return Q(U(`p`,{className:`empty`},`That record is not in this app any more. `,U(`a`,{href:`#/`},`Home`)));let n=Ft(t),r=B(t,q),a=new Set([`id`,`owner`,`text`,`vector`,`norm`,`embed`,`entityType`,q.identity,...q.title,...q.subtitle,...q.media,...q.temporal??[]]),o=Object.entries(t).filter(([e,t])=>!a.has(e)&&!/(_id|_sha256)$/.test(e)&&(typeof t==`string`||typeof t==`number`)&&String(t).length<120),c=U(`div`,{className:`doc`}),l=n?U(`button`,{type:`button`,className:`act`,onclick:()=>{if(c.firstChild){c.replaceChildren(),l.textContent=`View document`;return}c.append(U(`iframe`,{src:`./doc?u=${encodeURIComponent(n)}${Number(t.page)>1?`#page=${t.page}`:``}`,title:`Source document`,loading:`lazy`})),l.textContent=`Hide document`}},`View document`):null,u=rt(W.rows.filter(e=>Y(e)===Y(t)&&Pt(e)===Pt(t)&&i(e,q)===i(t,q)),q,{facet:J}),d=[...u.upcoming,...u.past].flatMap(e=>e.items).filter(e=>s(e,q)!==s(t,q)),f=We(W.rows,t.id,q,{limit:12}).near.map(e=>jt.get(e.id)).filter(e=>e&&s(e,q)!==s(t,q)).slice(0,6);Q(U(`p`,{},U(`a`,{href:`#/`,onclick:e=>{history.length>1&&(e.preventDefault(),history.back())}},`← Back`)),U(`article`,{className:`record`},U(`small`,{},[Y(t),i(t,q)].filter(Boolean).join(` · `)),U(`h2`,{},Rt(t)),r?U(`p`,{},r):U(`p`,{className:`hint`},`No decision is recorded under this item (it may be on an agenda, before the meeting).`),o.length?U(`dl`,{},o.map(([e,t])=>[U(`dt`,{},e.replace(/_/g,` `)),U(`dd`,{},String(t))])):null,U(`div`,{className:`acts`},Ht(t),l,n?U(`a`,{href:n,target:`_blank`,rel:`noopener`,className:`act`},`Source ↗`):null),bt&&t.paid_sha256?U(`p`,{className:`hint`},`Agents can buy this item's structured record for ${Number(bt.price)/10**(bt.decimals??6)} ${bt.symbol??`USDC`} (x402).`):null,c),d.length?U(`section`,{},U(`h2`,{},`Same meeting`),U(`ul`,{className:`list`},d.slice(0,12).map(e=>X(e,{meta:!1})))):null,f.length?U(`section`,{},U(`h2`,{},`Similar`),U(`ul`,{className:`list`},f.map(e=>X(e)))):null)}function nn(e,t,n){let r=U(`a`,{href:URL.createObjectURL(new Blob([t],{type:n})),download:e});document.body.append(r),r.click(),r.remove()}var rn={get(){try{return JSON.parse(localStorage.getItem(`${Ct}:knobs`))??{}}catch{return{}}},set(e){try{localStorage.setItem(`${Ct}:knobs`,JSON.stringify(e))}catch{}}},$={...Object.fromEntries(Object.entries(Xe).map(([e,[t]])=>[e,t])),...rn.get(),seed:1},an={lookahead:[`Lookahead`,`what you like now`,`where you're heading`],variety:[`Variety`,`close to each other`,`all different`],surprise:[`Surprise`,`best first`,`shuffled`],reach:[`Reach`,`nearest`,`further out`]};function on(){let{likes:e,dislikes:t}=W.votes(),n=I(W.rows.filter(Gt),e,t,{...$,limit:30}),r=e=>{let[t,n,r]=an[e],i=U(`output`,{},`${Math.round($[e]*100)}%`),a=U(`input`,{type:`range`,min:0,max:1,step:.05,value:$[e],id:`k-${e}`,title:Xe[e][1]});return a.oninput=()=>{i.textContent=`${Math.round(a.value*100)}%`},a.onchange=()=>{$[e]=Number(a.value),rn.set({...$,seed:void 0}),on(),document.getElementById(`k-${e}`)?.focus()},U(`label`,{className:`knob`,htmlFor:`k-${e}`},U(`span`,{},t,i),a,U(`small`,{},`${n} ↔ ${r}`))},i=(e,t)=>U(`li`,{className:t?`no`:``},e.title,U(`button`,{type:`button`,ariaLabel:`Forget ${e.title}`,onclick:()=>W.rate(e.id,`clear`)},`×`));Q(U(`h2`,{className:`page`},`For you`),Wt(),U(`section`,{className:`taste`},e.length||t.length?U(`ul`,{className:`pills`},e.slice(-30).map(e=>i(e)),t.slice(-10).map(e=>i(e,!0))):U(`p`,{className:`hint`},`Tap 👍 on records you like and 👎 on ones you don't. Newer likes count more; it all stays in this browser.`),n.taste?U(`p`,{className:`hint`},n.taste.heading?`Your recent likes point somewhere new; Lookahead follows them.`:`Like 4 or more and Lookahead can follow where your taste is heading.`):null,U(`div`,{className:`knobs`},Object.keys(Xe).map(r)),U(`button`,{type:`button`,className:`act`,disabled:!$.surprise,title:$.surprise?``:`Turn up Surprise to reroll`,onclick:()=>{$.seed++,on()}},`Reroll`)),n.picks.length?U(`ul`,{className:`list`},n.picks.map(({row:e})=>X(e))):null)}function sn(){let e=K.saved(),t=K.taste(),n=G.toLowerCase().replace(/\W+/g,`-`),r=()=>JSON.stringify(K.bundle({name:G,url:location.origin}),null,1),i=U(`button`,{type:`button`,className:`act`,onclick:async()=>{try{await navigator.clipboard.writeText(r()),i.textContent=`Copied`}catch{nn(`${n}-session.json`,r(),`application/json`)}}},`Copy for an agent`);Q(U(`h2`,{className:`page`},`Liked (${e.length})`),e.length?U(`div`,{className:`acts`},U(`button`,{type:`button`,className:`act`,onclick:()=>nn(`${n}-saved.json`,r(),`application/json`)},`Export JSON`),U(`button`,{type:`button`,className:`act`,onclick:()=>nn(`${n}-saved.csv`,ct(e),`text/csv`)},`CSV`),U(`button`,{type:`button`,className:`act`,onclick:()=>nn(`${n}-saved.md`,lt(e,`${G}: saved`),`text/markdown`)},`Markdown`),i):U(`p`,{className:`empty`},`Nothing liked yet. Tap 👍 on a record; likes stay on this device.`),t?U(`p`,{className:`hint`},`"For you" is built from these ${t.n}${t.rejected.length?`, and away from ${t.rejected.length} you passed on`:``}. It lives in this browser; the export carries it, so an agent can use it too. `,U(`button`,{type:`button`,className:`linkish`,onclick:()=>{K.clear(`passed`),sn(),ln()}},`Forget what I passed on`)):null,U(`ul`,{className:`list`},e.slice().reverse().map(e=>{let t=At.get(e.key);return U(`li`,{className:`row`},U(`div`,{className:`main`},U(`a`,{href:t?zt(t):e.url??`#/`,className:`title`},e.title),U(`small`,{},[e.place,e.subtitle].filter(Boolean).join(` · `)),e.detail?U(`p`,{className:`detail`},ht(e.detail)):null),U(`button`,{type:`button`,className:`vote`,ariaLabel:`Forget ${e.title}`,title:`Forget`,onclick:()=>{K.unvote(e.key),sn(),ln()}},`×`))})))}function cn(){let e=K.history();Q(U(`h2`,{className:`page`},`Searches this session`),e.length?U(`ul`,{className:`list`},e.map(({q:e,at:t})=>U(`li`,{className:`row`},U(`div`,{className:`main`},U(`a`,{href:`#/search/${encodeURIComponent(e)}`,className:`title`},e),U(`small`,{},new Date(t).toLocaleTimeString()))))):U(`p`,{className:`empty`},`No searches yet.`),e.length?U(`button`,{type:`button`,className:`act`,onclick:()=>{K.clear(`history`),cn()}},`Clear`):null)}function ln(){let e=K.saved().length;H(`#nsaved`).textContent=e?` (${e})`:``}function un(){let[,e=``,t=``]=location.hash.match(/^#\/([^/]*)\/?(.*)$/)??[],n=decodeURIComponent(t);for(let t of document.querySelectorAll(`nav a`))t.classList.toggle(`on`,t.getAttribute(`href`)===`#/${e}`);return document.body.classList.toggle(`wide`,e===`map`),e===`search`&&n?$t(n):e===`item`&&n?tn(n):e===`saved`?sn():e===`for-you`?on():e===`history`?cn():e===`map`&&xt?(Qt??=mt(xt,{el:U,show:Q,row:X,placeOf:Y,ctx:W})).render(...t.split(`/`).map(decodeURIComponent)):(H(`#q input`).value=``,Yt())}var dn;St.oninput=()=>{clearTimeout(dn);let e=St.value.trim();dn=setTimeout(()=>{if(!e){location.hash.startsWith(`#/search`)&&(location.hash=`#/`);return}history.replaceState(null,``,`#/search/${encodeURIComponent(e)}`),$t(e)},250)},H(`#q`).onsubmit=e=>{e.preventDefault();let t=St.value.trim();t&&(K.remember(t),location.hash=`#/search/${encodeURIComponent(t)}`)},Kt.addEventListener(`click`,e=>{e.target.closest(`a.title`)&&location.hash.startsWith(`#/search/`)&&K.remember(St.value)}),window.onhashchange=un,ln(),un(),W.rows=await Ot,Et=!0,Nt(),tt(W),un();
8
+ `);if(typeof process<`u`&&process.argv[1]?.endsWith(`/store.js`)){let e=()=>{let e=new Map;return{getItem:t=>e.get(t)??null,setItem:(t,n)=>e.set(t,n)}},t=at({local:e(),session:e(),app:`t`}),n=e=>({vector:Array.from({length:8},(t,n)=>n===e?1:.1)}),r=ot(n(0),{key:`a`,title:`Budget`,place:`X`,date:`2026-01-01`}),i=ot(n(1),{key:`b`,title:`Roads, "east"`,place:`Y`}),a=(e,t,n)=>{if(JSON.stringify(e)!==JSON.stringify(t))throw Error(`${n}: ${JSON.stringify(e)}`)};if(a(t.taste(),null,`no taste before a save`),t.toggleSave(r),t.toggleSave(i),a(t.saved().map(e=>e.key),[`a`,`b`],`saved in order`),!t.taste()?.q)throw Error(`saves make a taste`);t.pass(i),a([t.saved().map(e=>e.key),t.passed().map(e=>e.key)],[[`a`],[`b`]],`passing on an item unsaves it`),a(t.taste().rejected,[`Roads, "east"`],`and it steers the taste away`),t.remember(`snow`),t.remember(`budget`),t.remember(`snow`),a(t.history().map(e=>e.q),[`snow`,`budget`],`history: newest first, no repeats`);let o=t.bundle({name:`T`});if(o.saved[0].v||!o.taste?.q||o.searches.length!==2)throw Error(`the bundle carries choices and taste, not raw vectors`);if(!ct([i]).includes(`"Roads, ""east"""`))throw Error(`CSV quoting`);if(at({local:{getItem(){throw Error(`blocked`)},setItem(){throw Error(`blocked`)}}}).saved().length!==0)throw Error(`blocked storage reads as empty`);console.log(`store.js self-check ok — saves and passes steer a taste, history dedupes, the bundle carries no raw vectors, CSV quotes, blocked storage is empty not fatal`)}var ut=`http://www.w3.org/2000/svg`,dt=(e,t={})=>{let n=document.createElementNS(ut,e);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);return n},ft=e=>e.toLocaleString(),pt=new Set([`state`]);function mt(e,{el:t,show:n,row:r,placeOf:i,ctx:s}){let c=s.roles,l=Object.keys(e.paths),u=null,d=null,f=null,p={q:``,hits:null};function m(){if(u?.n===s.rows.length)return u;let t=s.rows.map(t=>{let n=a(t[e.field]??``).filter(t=>e.paths[t]);return n.length?n:[e.places?.[i(t)]].filter(Boolean)}),n=new Map;for(let e of s.rows){let t=o(e);n.set(t,(n.get(t)??0)+1)}let r=[...n].sort((e,t)=>t[1]-e[1])[0]?.[0],c=new Map(l.map(e=>[e,[]]));s.rows.forEach((e,n)=>{for(let e of t[n])c.get(e)?.push(n)});let d=0,f=null,p=0,m=new Map;s.rows.forEach((e,n)=>{if(!e.vector||o(e)!==r||!t[n].length)return;d||=e.vector.length,f??=new Float64Array(d);let i=1/(e.norm||Math.hypot(...e.vector)||1);for(let r of t[n]){let t=m.get(r)??{v:new Float64Array(d),n:0};for(let n=0;n<d;n++)t.v[n]+=e.vector[n]*i;t.n++,m.set(r,t)}for(let t=0;t<d;t++)f[t]+=e.vector[t]*i;p++});let h=new Map;for(let[e,t]of m){if(t.n<20)continue;let n=t.v.map((e,n)=>e/t.n-f[n]/p),r=Math.hypot(...n)||1;h.set(e,n.map(e=>e/r))}return u={n:s.rows.length,regionsOf:t,by:c,main:r,types:n,centroid:h},u}function h(e){let{centroid:t}=m(),n=t.get(e);return n?[...t].filter(([t])=>t!==e).map(([e,t])=>({region:e,score:t.reduce((e,t,r)=>e+t*n[r],0)})).sort((e,t)=>t.score-e.score).slice(0,5):[]}let g=(e,t=2)=>{let n=c.types?.[e];return(t===1?n?.singular:n?.plural)??e??`Records`},_=e=>c.types?.[e]?.icon??``;function v(e){let{regionsOf:t}=m(),n=new Map,r=e??s.rows.map((e,t)=>t);for(let e of r)if(!(f&&o(s.rows[e])!==f))for(let r of t[e])n.set(r,(n.get(r)??0)+1);return n}async function y(e){if(!e)return null;if(p.q===e&&p.hits)return p.hits;let t=s.queryVector(e),n=await Promise.race([t,new Promise(e=>setTimeout(()=>e(void 0),400))]);return n===void 0&&t.then(t=>{t&&p.q===e&&!p.meaning&&(p={q:e,hits:ee(e,t),meaning:!0},x(e,d))}),p={q:e,hits:ee(e,n??null),meaning:n!==void 0},p.hits}function ee(e,t){let n=new Map(s.rows.map((e,t)=>[e.id,t]));return j(s.rows,e,c,{qv:t,limit:600}).map(e=>n.get(e.id)).filter(e=>e!=null)}let b=(e,t=d)=>{location.hash=`#/map/${encodeURIComponent(e)}${t?`/${encodeURIComponent(t)}`:``}`};async function x(r=``,i=null){d=i&&e.paths[i]?i:null;let a=await y(r),c=v(a),u=Math.max(1,...c.values()),ee=e=>e?Math.min(5,1+Math.floor((a?e/u:Math.log10(e)/Math.log10(u))*4.999)):0,ne=d?new Set(h(d).map(e=>e.region)):new Set,S=dt(`svg`,{viewBox:`0 0 ${e.width} ${e.height}`,role:`img`,"aria-label":a?`Map: where “${r}” comes up`:`Map: where records are`,class:`map`});for(let t of l){let n=dt(`path`,{d:e.paths[t],class:`h${ee(c.get(t)??0)}${t===d?` on`:``}${ne.has(t)?` near`:``}`,tabindex:0,"aria-label":`${t}: ${ft(c.get(t)??0)}`});n.append(dt(`title`)),n.firstChild.textContent=`${t} · ${ft(c.get(t)??0)} ${a?`matching`:(f?g(f):`records`).toLowerCase()}`;let i=()=>b(r,d===t?null:t);n.addEventListener(`click`,i),n.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i())}),S.append(n)}let C=t(`input`,{type:`search`,value:r,placeholder:`Search the map: data center, PFAS, solar rezoning…`,"aria-label":`Search the map`});C.addEventListener(`keydown`,e=>{e.key===`Enter`&&b(C.value.trim())});let re=a?new Map:m().types;for(let e of a??[]){let t=o(s.rows[e]);re.set(t,(re.get(t)??0)+1)}let ie=re.size>1||a?t(`div`,{className:`chips`},[[null,a?.length??s.rows.length],...re].map(([e,n])=>t(`button`,{type:`button`,className:e===f?`chip on`:`chip`,onclick:()=>{f=e,x(r,d)}},`${e?`${_(e)} ${g(e,n)}`:`All`} (${ft(n)})`))):null,w=l.filter(e=>c.get(e)).length,T=a?`“${r}”: ${ft([...c.values()].reduce((e,t)=>e+t,0))} matches in ${w} of ${l.length} regions. Darker is more.${p.meaning?``:` (Matching words; search by meaning is loading.)`}`:`${f?g(f):`Records`} in ${w} of ${l.length} regions. Select a region, or search.`;n(t(`div`,{className:`mapbar`},C),ie,t(`p`,{className:`hint`},T),t(`div`,{className:`mapwrap`},S,t(`aside`,{className:`panel`},te(d,r,a))),t(`p`,{className:`hint`},`Legend: `,[0,1,2,3,4,5].map(e=>t(`span`,{className:`sw h${e}`})),a?` none → most matches`:` none → most records`))}function te(n,i,l){if(!n)return[t(`h3`,{},`Select a region`),t(`p`,{className:`hint`},`Its records by kind and tag, the ones that match, and the regions most like it.`)];let{by:u}=m(),d=new Set(u.get(n)),p=(l?l.filter(e=>d.has(e)):[...d]).filter(e=>!f||o(s.rows[e])===f).map(e=>s.rows[e]),v=new Map;for(let e of p){let t=o(e);v.set(t,(v.get(t)??0)+1)}let y=(c.tags??[]).filter(t=>t!==e.field&&!pt.has(t)).map(e=>{let t=new Map;for(let n of p)for(let r of a(n[e]??``))t.set(r,(t.get(r)??0)+1);return[e,[...t].sort((e,t)=>t[1]-e[1]).slice(0,6)]}).filter(([,e])=>e.length>1),ee=e=>String(e[c.temporal?.[0]]??``),x=(l?p:p.slice().sort((e,t)=>ee(t).localeCompare(ee(e)))).slice(0,25),te=h(n);return[t(`h3`,{},n,` `,t(`button`,{type:`button`,className:`linkish`,"aria-label":`Close`,onclick:()=>b(i,null)},`✕`)),t(`p`,{className:`hint`},[...v].map(([e,t])=>`${_(e)} ${ft(t)} ${g(e,t).toLowerCase()}`).join(` · `)||`Nothing here`+(l?` matches.`:` yet.`)),te.length?t(`div`,{className:`chips`},t(`small`,{title:`Regions whose records are closest in meaning; outlined on the map`},`Reads most like: `),te.map(({region:e})=>t(`button`,{type:`button`,className:`chip`,onclick:()=>b(i,e)},e))):null,y.map(([e,n])=>t(`div`,{className:`chips`},t(`small`,{},`${e.replace(/_/g,` `)}: `),n.map(([e,n])=>t(`button`,{type:`button`,className:`chip`,title:`Search the map for “${e}”`,onclick:()=>b(e)},`${e} (${n})`)))),x.length?t(`ul`,{className:`list`},x.map(e=>r(e))):null,p.length>x.length?t(`p`,{className:`hint`},`${ft(p.length-x.length)} more. `,t(`a`,{href:`#/search/${encodeURIComponent(i||n)}`},`Open in search`)):null]}return{render:x}}var H=e=>document.querySelector(e),U=(e,t={},...n)=>{let r=Object.assign(document.createElement(e),t);return r.append(...n.flat(1/0).filter(e=>e!=null&&e!==!1)),r},ht=(e,t=220)=>e.length>t?`${e.slice(0,e.lastIndexOf(` `,t))} …`:e,gt=e=>e?new Date(`${String(e).slice(0,10)}T12:00:00`).toLocaleDateString(void 0,{weekday:`short`,month:`short`,day:`numeric`,year:`numeric`}):``,W={rows:[],roles:r([]),queryVector:e=>ne(e).catch(()=>null)},_t,vt=new Promise(e=>{_t=e});O({onManifests:e=>{W.roles=r(e),_t()},rowText:e=>l(e,W.roles)});var yt=await fetch(`./.well-known/agent-card.json`).then(e=>e.json()).catch(()=>({})),bt=(yt.capabilities?.extensions??[]).map(e=>e.params?.paid).find(Boolean)??null,G=yt.name??`Fangorn app`;document.title=G,H(`#name`).textContent=G,fetch(`./nav.json`).then(e=>e.json()).then(e=>H(`nav`).append(...e.map(e=>U(`a`,{href:e.href},e.label)))).catch(()=>{});var xt=await fetch(`./map.json`).then(e=>(e.headers.get(`content-type`)??``).includes(`json`)?e.json():null).catch(()=>null);xt&&H(`nav`).prepend(U(`a`,{href:`#/map`},`Map`));var St=H(`#q input`);St.disabled=!1;var Ct=G.toLowerCase().replace(/\W+/g,`-`),K=at({local:globalThis.localStorage,session:globalThis.sessionStorage,app:Ct});W.session=()=>K.bundle({name:G,url:location.origin});var wt=new URL(`view`,location.href).href,Tt=await fetch(`${wt}/cdn/catalog`).then(e=>e.json()).then(e=>e.domains.reduce((e,t)=>e+(t.count??0),0)).catch(()=>0),Et=!1,Dt=0,Ot=A(wt,e=>{W.rows=e,Nt(),Date.now()-Dt>1500&&/^(#\/?)?$/.test(location.hash)&&(Dt=Date.now(),un())});await vt;var q=W.roles,kt=e=>String((q.identity&&e[q.identity])??e.id),At=new Map,jt=new Map,J=null,Mt=[];function Nt(){At=new Map(W.rows.map(e=>[kt(e),e])),jt=new Map(W.rows.map(e=>[e.id,e])),J??=nt(W.rows,q),Mt=J?[...W.rows.reduce((e,t)=>{let n=Y(t);return n&&e.set(n,(e.get(n)??0)+1),e},new Map)].sort((e,t)=>e[0].localeCompare(t[0])):[];let e=W.rows.length.toLocaleString();St.placeholder=Et&&!W.rows.length?`No records yet`:Et?`Search ${e} records${Mt.length>1?` in ${Mt.length} places`:``}…`:`Loading ${e}${Tt?` of ${Tt.toLocaleString()}`:``} records… (search what is here)`}var Y=e=>J?a(e[J]??``)[0]??``:``,Pt=e=>String(e[q.temporal?.[0]]??``).slice(0,10),Ft=e=>d(e,q),It=e=>ot(e,{key:kt(e),title:s(e,q),subtitle:i(e,q),place:Y(e),date:Pt(e),link:Ft(e),detail:B(e,q)}),Lt=e=>/[a-z]/.test(e)||!/[A-Z]{5}/.test(e)?e:e.toLowerCase().replace(/\b[a-z]{1,3}\b/g,(e,t)=>/^(and|or|of|the|to|for|in|on|at|by|a|an|as|is|be|no|from)$/.test(e)?e:e.toUpperCase()).replace(/^\W*\w/,e=>e.toUpperCase()).replace(/([.:;!?]\s+|\u2013\s+|-\s+)(\w)/g,(e,t,n)=>t+n.toUpperCase()),Rt=e=>Lt(s(e,q)),zt=e=>`#/item/${encodeURIComponent(kt(e))}`,Bt=(e,t)=>{if(!t.length)return[e];let n=RegExp(`(${t.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`)})`,`ig`);return String(e).split(n).map((e,t)=>t%2?U(`mark`,{},e):e)},Vt=e=>K.isSaved(e)?`like`:K.passed().some(t=>t.key===e)?`dislike`:null;W.rate=(e,t)=>{if(![`like`,`dislike`,`clear`].includes(t))return{error:`verdict is like, dislike or clear`};let n=jt.get(e)??At.get(String(e))??jt.get(N(W.rows,e,q)?.id);if(!n)return{error:`no record ${e}`};let r=kt(n);return K.unvote(r),t===`like`&&K.toggleSave(It(n)),t===`dislike`&&K.pass(It(n)),Ut(),ln(),/^#\/for-you/.test(location.hash)&&on(),{likes:K.saved().map(e=>e.title),dislikes:K.passed().map(e=>e.title)}},W.votes=()=>{let e=e=>{let t=At.get(e.id);return t?{id:t.id,title:e.title,vector:t.vector}:e},{likes:t,dislikes:n}=K.votes();return{likes:t.map(e).filter(e=>e.vector),dislikes:n.map(e).filter(e=>e.vector)}};var Ht=e=>U(`span`,{className:`votes`},[[`like`,`👍`,`I like this`],[`dislike`,`👎`,`Not for me`]].map(([t,n,r])=>{let i=U(`button`,{type:`button`,className:`vote`,title:r,ariaLabel:`${r}: ${s(e,q)}`,onclick:n=>{n.preventDefault(),W.rate(e.id,Vt(kt(e))===t?`clear`:t)}},n);return Object.assign(i.dataset,{key:kt(e),vote:t}),i}));function Ut(){for(let e of document.querySelectorAll(`button.vote`))e.setAttribute(`aria-pressed`,String(Vt(e.dataset.key)===e.dataset.vote))}var X=(e,{terms:t=[],also:n=0,meta:r=!0}={})=>{let a=B(e,q);return U(`li`,{className:`row`},U(`div`,{className:`main`},U(`a`,{href:zt(e),className:`title`},Bt(Rt(e),t)),r?U(`small`,{},[Y(e),i(e,q)].filter(Boolean).join(` · `)):null,a?U(`p`,{className:`detail`},Bt(ht(a),t)):null,n?U(`small`,{className:`also`},`and ${n} more record${n>1?`s`:``} of the same item`):null),Ht(e))},Z=null,Wt=()=>Mt.length>1?U(`div`,{className:`chips`},[[null,W.rows.length],...Mt].map(([e,t])=>U(`button`,{type:`button`,className:e===Z?`chip on`:`chip`,title:`${t.toLocaleString()} records`,onclick:()=>{Z=e,un()}},e??`All`))):null,Gt=e=>!Z||Y(e)===Z,Kt=H(`#view`),Q=(...e)=>{Kt.replaceChildren(...e.flat().filter(Boolean)),Ut(),window.scrollTo(0,0)};function qt(e){let t=U(`ul`,{},e.items.slice(0,5).map(e=>X(e,{meta:!1}))),n=e.items.length>5?U(`button`,{type:`button`,className:`more`,onclick:n=>{t.append(...e.items.slice(5).map(e=>X(e,{meta:!1}))),n.target.remove()}},`${e.items.length-5} more`):null;return U(`article`,{},U(`header`,{},U(`time`,{dateTime:e.date},gt(e.date)),U(`h3`,{},[e.place,e.label.replace(/\s*·\s*\d{4}-\d\d-\d\d$/,``)].filter(Boolean).join(` — `))),t,n)}var Jt=12;function Yt(){let{upcoming:e,past:t}=rt(W.rows,q,{facet:J,only:Z}),{likes:n,dislikes:r}=W.votes(),i=I(W.rows.filter(Gt),n,r,{...$,limit:6});Q(yt.description?U(`p`,{className:`about`},yt.description):null,Wt(),i.picks.length?U(`section`,{},U(`h2`,{},`For you`),U(`p`,{className:`hint`},`From the ${i.taste.n} item${i.taste.n>1?`s`:``} you liked. `,U(`a`,{href:`#/for-you`},`Tune`)),U(`ul`,{className:`list`},i.picks.map(({row:e})=>X(e)))):null,e.length?U(`section`,{},U(`h2`,{},`Coming up`),e.slice(0,8).map(qt)):null,t.length?U(`section`,{},U(`h2`,{},`Recently`),t.slice(0,Jt).map(qt),t.length>Jt?U(`button`,{type:`button`,className:`more`,onclick:()=>{Jt+=12,Yt()}},`Show more`):null):null,!e.length&&!t.length?U(`p`,{className:`empty`},Et?W.rows.length?`Nothing dated here yet. Search above.`:`This app is registered and being built. Its records will appear here once they are published.`:`Loading the records…`):null)}var Xt=`relevance`,Zt=0,Qt=null;async function $t(e){document.activeElement!==H(`#q input`)&&(H(`#q input`).value=e);let t=++Zt,n=W.queryVector(e),r=await Promise.race([n,new Promise(e=>setTimeout(()=>e(void 0),400))]);t===Zt&&(r===void 0&&n.then(n=>{n&&t===Zt&&en(e,n)}),en(e,r??null,r===void 0))}function en(e,t,n=!1){let r=j(W.rows,e,q,{qv:t,limit:80,...Z&&J?{where:{[J]:Z}}:{}}),i=new Map;for(let e of r){let t=jt.get(e.id);if(!t)continue;let n=`${Y(t)}|${s(t,q).toLowerCase()}`,r=i.get(n);r?(r.also++,B(t,q).length>B(r.r,q).length&&(r.r=t)):i.set(n,{r:t,also:0})}let a=[...i.values()];Xt===`newest`&&(a=a.sort((e,t)=>Pt(t.r).localeCompare(Pt(e.r))));let o=e.toLowerCase().split(/\W+/).filter(e=>e.length>2),c=U(`div`,{className:`sort`},`Sort: `,[`relevance`,`newest`].map(r=>U(`button`,{type:`button`,className:r===Xt?`chip on`:`chip`,onclick:()=>{Xt=r,en(e,t,n)}},r)));Q(Wt(),U(`div`,{className:`resultsbar`},U(`span`,{},`${a.length} result${a.length===1?``:`s`} for “${e}”${Z?` in ${Z}`:``}`,n?U(`small`,{},` · matching words; search by meaning is loading`):null),c),a.length?U(`ul`,{className:`list`},a.slice(0,40).map(({r:e,also:t})=>X(e,{terms:o,also:t}))):U(`p`,{className:`empty`},`No matches. Try other words, or All places.`))}function tn(e){let t=At.get(e);if(!t)return Q(U(`p`,{className:`empty`},`That record is not in this app any more. `,U(`a`,{href:`#/`},`Home`)));let n=Ft(t),r=B(t,q),a=new Set([`id`,`owner`,`text`,`vector`,`norm`,`embed`,`entityType`,q.identity,...q.title,...q.subtitle,...q.media,...q.temporal??[]]),o=Object.entries(t).filter(([e,t])=>!a.has(e)&&!/(_id|_sha256)$/.test(e)&&(typeof t==`string`||typeof t==`number`)&&String(t).length<120),c=U(`div`,{className:`doc`}),l=n?U(`button`,{type:`button`,className:`act`,onclick:()=>{if(c.firstChild){c.replaceChildren(),l.textContent=`View document`;return}c.append(U(`iframe`,{src:`./doc?u=${encodeURIComponent(n)}${Number(t.page)>1?`#page=${t.page}`:``}`,title:`Source document`,loading:`lazy`})),l.textContent=`Hide document`}},`View document`):null,u=rt(W.rows.filter(e=>Y(e)===Y(t)&&Pt(e)===Pt(t)&&i(e,q)===i(t,q)),q,{facet:J}),d=[...u.upcoming,...u.past].flatMap(e=>e.items).filter(e=>s(e,q)!==s(t,q)),f=We(W.rows,t.id,q,{limit:12}).near.map(e=>jt.get(e.id)).filter(e=>e&&s(e,q)!==s(t,q)).slice(0,6);Q(U(`p`,{},U(`a`,{href:`#/`,onclick:e=>{history.length>1&&(e.preventDefault(),history.back())}},`← Back`)),U(`article`,{className:`record`},U(`small`,{},[Y(t),i(t,q)].filter(Boolean).join(` · `)),U(`h2`,{},Rt(t)),r?U(`p`,{},r):U(`p`,{className:`hint`},`No decision is recorded under this item (it may be on an agenda, before the meeting).`),o.length?U(`dl`,{},o.map(([e,t])=>[U(`dt`,{},e.replace(/_/g,` `)),U(`dd`,{},String(t))])):null,U(`div`,{className:`acts`},Ht(t),l,n?U(`a`,{href:n,target:`_blank`,rel:`noopener`,className:`act`},`Source ↗`):null),bt&&t.paid_sha256?U(`p`,{className:`hint`},`Agents can buy this item's structured record for ${Number(bt.price)/10**(bt.decimals??6)} ${bt.symbol??`USDC`} (x402).`):null,c),d.length?U(`section`,{},U(`h2`,{},`Same meeting`),U(`ul`,{className:`list`},d.slice(0,12).map(e=>X(e,{meta:!1})))):null,f.length?U(`section`,{},U(`h2`,{},`Similar`),U(`ul`,{className:`list`},f.map(e=>X(e)))):null)}function nn(e,t,n){let r=U(`a`,{href:URL.createObjectURL(new Blob([t],{type:n})),download:e});document.body.append(r),r.click(),r.remove()}var rn={get(){try{return JSON.parse(localStorage.getItem(`${Ct}:knobs`))??{}}catch{return{}}},set(e){try{localStorage.setItem(`${Ct}:knobs`,JSON.stringify(e))}catch{}}},$={...Object.fromEntries(Object.entries(Xe).map(([e,[t]])=>[e,t])),...rn.get(),seed:1},an={lookahead:[`Lookahead`,`what you like now`,`where you're heading`],variety:[`Variety`,`close to each other`,`all different`],surprise:[`Surprise`,`best first`,`shuffled`],reach:[`Reach`,`nearest`,`further out`]};function on(){let{likes:e,dislikes:t}=W.votes(),n=I(W.rows.filter(Gt),e,t,{...$,limit:30}),r=e=>{let[t,n,r]=an[e],i=U(`output`,{},`${Math.round($[e]*100)}%`),a=U(`input`,{type:`range`,min:0,max:1,step:.05,value:$[e],id:`k-${e}`,title:Xe[e][1]});return a.oninput=()=>{i.textContent=`${Math.round(a.value*100)}%`},a.onchange=()=>{$[e]=Number(a.value),rn.set({...$,seed:void 0}),on(),document.getElementById(`k-${e}`)?.focus()},U(`label`,{className:`knob`,htmlFor:`k-${e}`},U(`span`,{},t,i),a,U(`small`,{},`${n} ↔ ${r}`))},i=(e,t)=>U(`li`,{className:t?`no`:``},e.title,U(`button`,{type:`button`,ariaLabel:`Forget ${e.title}`,onclick:()=>W.rate(e.id,`clear`)},`×`));Q(U(`h2`,{className:`page`},`For you`),Wt(),U(`section`,{className:`taste`},e.length||t.length?U(`ul`,{className:`pills`},e.slice(-30).map(e=>i(e)),t.slice(-10).map(e=>i(e,!0))):U(`p`,{className:`hint`},`Tap 👍 on records you like and 👎 on ones you don't. Newer likes count more; it all stays in this browser.`),n.taste?U(`p`,{className:`hint`},n.taste.heading?`Your recent likes point somewhere new; Lookahead follows them.`:`Like 4 or more and Lookahead can follow where your taste is heading.`):null,U(`div`,{className:`knobs`},Object.keys(Xe).map(r)),U(`button`,{type:`button`,className:`act`,disabled:!$.surprise,title:$.surprise?``:`Turn up Surprise to reroll`,onclick:()=>{$.seed++,on()}},`Reroll`)),n.picks.length?U(`ul`,{className:`list`},n.picks.map(({row:e})=>X(e))):null)}function sn(){let e=K.saved(),t=K.taste(),n=G.toLowerCase().replace(/\W+/g,`-`),r=()=>JSON.stringify(K.bundle({name:G,url:location.origin}),null,1),i=U(`button`,{type:`button`,className:`act`,onclick:async()=>{try{await navigator.clipboard.writeText(r()),i.textContent=`Copied`}catch{nn(`${n}-session.json`,r(),`application/json`)}}},`Copy for an agent`);Q(U(`h2`,{className:`page`},`Liked (${e.length})`),e.length?U(`div`,{className:`acts`},U(`button`,{type:`button`,className:`act`,onclick:()=>nn(`${n}-saved.json`,r(),`application/json`)},`Export JSON`),U(`button`,{type:`button`,className:`act`,onclick:()=>nn(`${n}-saved.csv`,ct(e),`text/csv`)},`CSV`),U(`button`,{type:`button`,className:`act`,onclick:()=>nn(`${n}-saved.md`,lt(e,`${G}: saved`),`text/markdown`)},`Markdown`),i):U(`p`,{className:`empty`},`Nothing liked yet. Tap 👍 on a record; likes stay on this device.`),t?U(`p`,{className:`hint`},`"For you" is built from these ${t.n}${t.rejected.length?`, and away from ${t.rejected.length} you passed on`:``}. It lives in this browser; the export carries it, so an agent can use it too. `,U(`button`,{type:`button`,className:`linkish`,onclick:()=>{K.clear(`passed`),sn(),ln()}},`Forget what I passed on`)):null,U(`ul`,{className:`list`},e.slice().reverse().map(e=>{let t=At.get(e.key);return U(`li`,{className:`row`},U(`div`,{className:`main`},U(`a`,{href:t?zt(t):e.url??`#/`,className:`title`},e.title),U(`small`,{},[e.place,e.subtitle].filter(Boolean).join(` · `)),e.detail?U(`p`,{className:`detail`},ht(e.detail)):null),U(`button`,{type:`button`,className:`vote`,ariaLabel:`Forget ${e.title}`,title:`Forget`,onclick:()=>{K.unvote(e.key),sn(),ln()}},`×`))})))}function cn(){let e=K.history();Q(U(`h2`,{className:`page`},`Searches this session`),e.length?U(`ul`,{className:`list`},e.map(({q:e,at:t})=>U(`li`,{className:`row`},U(`div`,{className:`main`},U(`a`,{href:`#/search/${encodeURIComponent(e)}`,className:`title`},e),U(`small`,{},new Date(t).toLocaleTimeString()))))):U(`p`,{className:`empty`},`No searches yet.`),e.length?U(`button`,{type:`button`,className:`act`,onclick:()=>{K.clear(`history`),cn()}},`Clear`):null)}function ln(){let e=K.saved().length;H(`#nsaved`).textContent=e?` (${e})`:``}function un(){let[,e=``,t=``]=location.hash.match(/^#\/([^/]*)\/?(.*)$/)??[],n=decodeURIComponent(t);for(let t of document.querySelectorAll(`nav a`))t.classList.toggle(`on`,t.getAttribute(`href`)===`#/${e}`);return document.body.classList.toggle(`wide`,e===`map`),e===`search`&&n?$t(n):e===`item`&&n?tn(n):e===`saved`?sn():e===`for-you`?on():e===`history`?cn():e===`map`&&xt?(Qt??=mt(xt,{el:U,show:Q,row:X,placeOf:Y,ctx:W})).render(...t.split(`/`).map(decodeURIComponent)):(H(`#q input`).value=``,Yt())}var dn;St.oninput=()=>{clearTimeout(dn);let e=St.value.trim();dn=setTimeout(()=>{if(!e){location.hash.startsWith(`#/search`)&&(location.hash=`#/`);return}history.replaceState(null,``,`#/search/${encodeURIComponent(e)}`),$t(e)},250)},H(`#q`).onsubmit=e=>{e.preventDefault();let t=St.value.trim();t&&(K.remember(t),location.hash=`#/search/${encodeURIComponent(t)}`)},Kt.addEventListener(`click`,e=>{e.target.closest(`a.title`)&&location.hash.startsWith(`#/search/`)&&K.remember(St.value)}),window.onhashchange=un,ln(),un(),W.rows=await Ot,Et=!0,Nt(),tt(W),un();
@@ -1,6 +1,6 @@
1
1
  <!doctype html>
2
2
  <html lang="en">
3
- <script type="module" crossorigin src="./assets/index-DxAeTEch.js"></script>
3
+ <script type="module" crossorigin src="./assets/index-w2wfUwhm.js"></script>
4
4
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-Dd_uD5pT.js">
5
5
  <link rel="modulepreload" crossorigin href="./assets/preload-helper-uBIymjUX.js">
6
6
  <link rel="modulepreload" crossorigin href="./assets/roles-C9V_uDr_.js">
package/site/worker.js CHANGED
@@ -94,10 +94,12 @@ export default {
94
94
  const p = url.pathname;
95
95
  if (p === "/.well-known/agent-card.json" || p.startsWith("/view/")) out.headers.set("access-control-allow-origin", "*");
96
96
  if (p.startsWith("/assets/")) out.headers.set("cache-control", "public, max-age=31536000, immutable");
97
- // Shards are content-named, but not forever: a retracted record's shard is deleted, and
98
- // pages.dev's edge cache cannot be purged. An hour bounds how long a deleted one lingers.
97
+ // Shards are content-named, so a reader's browser keeps one for good: a change or a
98
+ // retraction writes new names. `private`: pages.dev's edge cache cannot be purged, so it
99
+ // must never hold one, and a retracted record's shard stops being served when the deploy
100
+ // drops it. (This worker's header wins over _headers, which Pages skips for worker responses.)
99
101
  else if (/^\/view\/cdn\/domains\/[^/]+\/shards\//.test(p))
100
- out.headers.set("cache-control", (res.headers.get("content-type") ?? "").includes("html") ? "no-store" : "public, max-age=3600");
102
+ out.headers.set("cache-control", (res.headers.get("content-type") ?? "").includes("html") ? "no-store" : "private, max-age=31536000, immutable");
101
103
  return out;
102
104
  },
103
105
  };
@@ -1 +0,0 @@
1
- let e=null;const t=()=>e??=(async()=>{let{pipeline:e}=await import(`./transformers.web-BgUm7F_-.js`);return e(`feature-extraction`,`nomic-ai/nomic-embed-text-v1.5`,{dtype:`q8`})})();function n(e,t=256){let n=e.length,r=0;for(let t=0;t<n;t++)r+=e[t];r/=n;let i=0;for(let t=0;t<n;t++)i+=(e[t]-r)**2;let a=Math.sqrt(i/n+1e-5),o=Array(Math.min(t,n));for(let t=0;t<o.length;t++)o[t]=(e[t]-r)/a;let s=0;for(let e of o)s+=e*e;if(s=Math.sqrt(s),s)for(let e=0;e<o.length;e++)o[e]/=s;return o}async function r(e){return n((await(await t())(`search_query: ${e}`,{pooling:`mean`,normalize:!1})).data)}async function i(e){return n((await(await t())(`search_document: ${e}`,{pooling:`mean`,normalize:!1})).data)}const a=()=>t().then(()=>{});function o(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n++){let r=Math.round(Math.max(-1,Math.min(1,e[n]))*127);t[n]=r<0?r+256:r}let n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function s(e){try{let t=atob(e),n=new Float32Array(t.length);for(let e=0;e<t.length;e++){let r=t.charCodeAt(e);n[e]=(r>127?r-256:r)/127}return n.length?n:null}catch{return null}}function c(e){let t=new Uint8Array(Math.ceil(e.length/8));for(let n=0;n<e.length;n++)e[n]>=0&&(t[n>>3]|=128>>(n&7));let n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function l(e){try{let t=atob(e.padEnd(Math.ceil(e.length/4)*4,`=`)),n=new Float32Array(t.length*8);for(let e=0;e<n.length;e++)n[e]=t.charCodeAt(e>>3)>>7-(e&7)&1?1:-1;return n.length?n:null}catch{return null}}if(typeof process<`u`&&import.meta.url===`file://${process.argv[1]}`&&process.argv[1].endsWith(`/embed.js`)){let e=n(Array.from({length:768},(e,t)=>Math.sin(t))),t=0;for(let n of e)t+=n*n;if(Math.abs(Math.sqrt(t)-1)>1e-6)throw Error(`matryoshka must L2-normalize`);if(e.length!==256)throw Error(`matryoshka must truncate to 256`);let r=s(o(e));if(r.length!==e.length)throw Error(`pack/unpack changed the dimension`);let i=0,a=0;for(let t=0;t<e.length;t++)i+=e[t]*r[t],a+=r[t]*r[t];let u=i/Math.sqrt(a);if(u<.999)throw Error(`int8 round-trip cosine ${u} — too lossy to rank with`);let d=s(o([-1,-.5,0,.5,1]));if(d[0]>-.99||d[1]>-.49||d[1]<-.51)throw Error(`negative components corrupted: ${[...d]}`);if(s(`!!!not base64!!!`)!==null)throw Error(`malformed vector must return null, not throw`);let f=c(e);if(f.length>48)throw Error(`sign bits must stay link-sized, got ${f.length} chars`);let p=l(f);if(p.length!==e.length)throw Error(`sign round-trip changed the dimension`);for(let t=0;t<e.length;t++)if(Math.sign(p[t])!==(e[t]<0?-1:1))throw Error(`sign flipped at ${t}`);if(c(p)!==f)throw Error(`sign packing must be idempotent`);if(l(`!!!not base64!!!`)!==null)throw Error(`malformed bits must return null, not throw`);console.log(`embed.js self-check ok — matryoshka norm, int8 round-trip, negatives, malformed input, sign bits`)}const u={query:r,document:i};self.onmessage=async({data:{id:e,kind:t,text:n}})=>{try{if(t===`warm`)return await a(),self.postMessage({id:e,vec:null});self.postMessage({id:e,vec:await u[t](n)})}catch(t){self.postMessage({id:e,error:t?.message??String(t)})}};