diff --git a/.ascii-to-svg-manifest.json b/.ascii-to-svg-manifest.json new file mode 100644 index 0000000..689c7a8 --- /dev/null +++ b/.ascii-to-svg-manifest.json @@ -0,0 +1,56 @@ +{ + "version": "1.0.0", + "lastSync": "2026-11-05T19:40:31Z", + "diagrams": [ + { + "id": "three-outputs", + "sourceFile": "README.md", + "sourceLine": 42, + "svgFile": "assets/diagrams/three-outputs.svg", + "asciiHash": "sha256:7082517f21d167c59b50d6abde2576e45af1403eedab8492e11877477d84b88f", + "svgHash": "sha256:2dadf13f32f4e295fac5349ce47ed1e74fc1a571a22f906de647e78c2887b7d3", + "diagramType": "flowchart", + "lastConverted": "2026-11-05T19:08:23Z" + }, + { + "id": "stations", + "sourceFile": "README.md", + "sourceLine": 70, + "svgFile": "assets/diagrams/stations.svg", + "asciiHash": "sha256:dd9281870048657b723ef94cc813dff8205f3c9ae78976946726b6120fe1a581", + "svgHash": "sha256:295f1246180abfa142db95e9064df861b1447d33fb7cb6107a7c4906cc2877d8", + "diagramType": "architecture", + "lastConverted": "2026-11-05T19:08:23Z" + }, + { + "id": "quality-gate", + "sourceFile": "README.md", + "sourceLine": 105, + "svgFile": "assets/diagrams/quality-gate.svg", + "asciiHash": "sha256:5ff394c8fac5028bd000d6bc2c9d3049f2f46cd42d836b76f456e0e0701f1d38", + "svgHash": "sha256:aa9cf10d6b700ba38f87d528b88ca0aa32c80792a05540eb72a64d18a9e316ec", + "diagramType": "flowchart", + "lastConverted": "2026-11-05T19:08:23Z" + }, + { + "id": "learning-loop", + "sourceFile": "README.md", + "sourceLine": 136, + "svgFile": "assets/diagrams/learning-loop.svg", + "asciiHash": "sha256:345b491348a7383ef598b0f8ee7422fb536314b89eee21f365bfaba4755ede7f", + "svgHash": "sha256:8a6e6b453f4b94bfa87d3ecde1ede90f54ffd9cdcfbc27e399216c4c3348d2b8", + "diagramType": "flowchart", + "lastConverted": "2026-11-05T19:08:23Z" + }, + { + "id": "two-doors", + "sourceFile": "README.md", + "sourceLine": 162, + "svgFile": "assets/diagrams/two-doors.svg", + "asciiHash": "sha256:22445671b2e3f554eefc3a6bd8fd1a49ad2c83fd5c7f036831774edc70ac8b51", + "svgHash": "sha256:858bb7f307f752ece197c6730e906476fed3e942145201b723d1eca6157d7109", + "diagramType": "architecture", + "lastConverted": "2026-11-05T19:08:23Z" + } + ] +} diff --git a/.github/workflows/build-explainer.yml b/.github/workflows/build-explainer.yml index 711827b..3de1b0c 100644 --- a/.github/workflows/build-explainer.yml +++ b/.github/workflows/build-explainer.yml @@ -4,13 +4,8 @@ name: Build Explainer # keys (repo secrets), deploy it to its own Netlify site, and write progress back to a status # gist that the website polls. Triggered by the /build Netlify function. # -# ARCHITECTURE (2026-07-04 rebuild — see project memory "hosted-agentic-architecture", approved -# 2026-06-30 but never actually wired until now): this invokes bin/agentic-runner.mjs, which runs -# the real explainmyrepo SKILL as a headless Claude Code agent — the brain decides, tools/*.mjs do -# the mechanics — instead of the old deterministic orchestrator.mjs pipeline. GitHub Actions is -# still the right HOST for this (ADR-033, agent-harness-generator: triggered, autonomous, no human -# at the keyboard); what changed is that it now runs the AGENT, which adapts per-repo, instead of a -# fixed script that broke on off-mold repos (empty dep-graphs, oversized monorepos). +# ARCHITECTURE: bin/agentic-runner.mjs runs the explainmyrepo SKILL as a headless Claude Code agent (the brain +# decides, tools/*.mjs do the mechanics); GitHub Actions is only the host. The local door is src/orchestrator.mjs. # # RAILS: timeout-minutes is COMPUTED from budget_min (a pre-flight repo-size signal from build.js) # instead of one fixed ceiling for every repo · serialized concurrency (no cost fan-out) · the @@ -57,19 +52,16 @@ jobs: runs-on: ubuntu-latest # The agent enforces its OWN budget (budget_min) internally and exits cleanly well before this # outer ceiling would ever need to fire — this is just the backstop. timeout_min is budget_min + - # a fixed overhead buffer, computed in build.js (plain JS), not here: GitHub Actions expressions - # don't support arithmetic on inputs the way `fromJSON(x) + 10` implies — learned this the hard - # way, it rejects the whole dispatch at parse time, which a YAML-structure check doesn't catch - # since it's an expression-syntax error, not a YAML one. + # a fixed overhead buffer computed in build.js (Actions expressions cannot add to an input). timeout-minutes: ${{ fromJSON(inputs.timeout_min || '30') }} steps: - name: Checkout the explainer tool - uses: actions/checkout@v4 + uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0 - name: Set up Node - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: - node-version: "20" + node-version: 22 - name: Validate input (abuse guard) env: @@ -79,34 +71,29 @@ jobs: REPO: ${{ github.event.inputs.target_repo }} run: | echo "target: $REPO" - if ! printf '%s' "$REPO" | grep -qE '^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$'; then + if ! printf '%s' "$REPO" | grep -qE '^[A-Za-z0-9_][A-Za-z0-9_.-]*/[A-Za-z0-9_][A-Za-z0-9_.-]*$'; then echo "::error::invalid repo format (expected owner/name): $REPO"; exit 1 fi - name: Install dependencies run: | - npm ci || npm install - # Belt-and-suspenders: guarantee the 3 runtime deps are present (CI 'npm ci' was leaving - # playwright unresolved -> quality-grade failed). EXACT pinned versions + --no-save so this - # cannot drift to a newer/compromised patch or rewrite the committed lockfile (no supply- - # chain bypass; these match package-lock.json). - npm install --no-save playwright@1.61.1 @xenova/transformers@2.17.2 @ruvector/rvf@0.2.2 + # The lockfile is the single source of truth for runtime deps (playwright, @xenova/transformers, + # @ruvector/rvf, sharp); no ad-hoc --no-save installs that could drift from it. + npm ci npx playwright install --with-deps chromium # System tools the pipeline shells out to (scanned from tools/*.mjs), not all preinstalled # on the runner: ImageMagick (magick/convert/identify — favicon, social card), xmllint - # (libxml2-utils — diagram SVG validation), dot (graphviz — diagram layout), zip (AI pack). + # (libxml2-utils — diagram SVG validation), zip (AI pack). # Fonts help text render in generated imagery. - sudo apt-get update && sudo apt-get install -y imagemagick libxml2-utils graphviz zip fonts-liberation fonts-dejavu-core + sudo apt-get update && sudo apt-get install -y imagemagick libxml2-utils zip fonts-liberation fonts-dejavu-core # The agentic kernel itself (bin/agentic-runner.mjs spawns this headless) — pinned exact # version, same rationale as the runtime deps above: no supply-chain drift on a bare runner. npm install -g @anthropic-ai/claude-code@2.1.201 claude --version - # 2026-07-16 HF outage (build 79f135b3): a CloudFront outage made the mandatory embedding - # model undownloadable and the agent burned its whole budget discovering it. Cache the - # 33 MB model between runs so KB builds are offline-first; the warm step downloads it only - # when the cache is cold and VALIDATES it with one real embedding. Warm failure is a soft - # warning: the runner's own embedding preflight is the honest gate and alerts in seconds. + # Cache the embedding model between runs so KB builds are offline-first (an HF outage once burned a whole + # agent budget); the warm step downloads only when cold and validates with one real embedding. A warm + # failure is a soft warning: the runner's embedding preflight is the honest gate. - name: Restore embedding model cache (offline-first KB) uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3 with: @@ -122,9 +109,7 @@ jobs: # failure alert) — the runner builds a SEPARATE, much narrower allowlist for the spawned # agent process itself (see bin/agentic-runner.mjs), which never sees GH/SMTP creds. ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} - # Failover lane only (2026-07-19): engaged by the runner's preflight EXCLUSIVELY when the - # primary key is usage-limited — same executor model via OpenRouter's Anthropic Skin. - # Empty when the secret is unset: the lane stays inert and behavior is unchanged. + # Failover lane only: the runner's preflight uses it when the primary key is usage-limited. OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }} NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} @@ -164,11 +149,8 @@ jobs: exit 1 fi - # A failed run's assembled work is NOT garbage (learned 2026-07-15: autonomous-wealth-builder - # built a complete grounded site, stalled at B5 56/58, and the runner's _temp dir evaporated - # with the job — the whole spend was lost when a 10-minute operator cure could have finished - # it). Preserve the curable core (site + build.json + graded assets; NOT the repo clone, NOT - # logs) so the operator can download, fix, re-grade, and deploy without a rebuild. + # A failed run's assembled work is not garbage: keep the curable core (site + build.json + graded assets; + # not the clone, not logs) so an operator can fix, re-grade and deploy without a rebuild. - name: Preserve curable build on failure if: failure() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9927abc..0b693ad 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,9 +1,7 @@ # The test gate — ONE definition, used two ways: on every pull request and push to main (so a red suite # cannot merge unnoticed), and called by release.yml before it will publish anything. # -# 2026-10-06: the tests used to run ONLY when a release tag was pushed. Ten commits merged on Sep 20 with -# two tests newly red and nobody knew — and the release job had by then been failing for three months -# for a different reason (the sharp step below), so there was no signal at all. +# Why: the tests used to run ONLY when a release tag was pushed, so a red suite could merge unnoticed. name: CI @@ -26,18 +24,18 @@ jobs: with: node-version: 22 - # --ignore-scripts: dependency install hooks never run in CI (supply-chain posture) ... + # --ignore-scripts: dependency install hooks never run in CI (supply-chain posture). - run: npm ci --ignore-scripts - # ... with ONE deliberate exception. @xenova/transformers carries its own nested `sharp`, whose native - # binary is fetched by its install script. Skipped, importing the package throws and the 9 kb-delta - # end-to-end tests fail — which blocked every release since July. Rebuilding ONLY sharp restores the - # one binary that needs it. Reproduced and verified in a clean v0.9.0 checkout (185 tests, 0 failing). - - run: npm rebuild sharp + # The ask-service has its own manifest (it deploys as a separate Netlify site); its tests import it. + - run: npm ci --ignore-scripts --prefix ask-service - # The diagram tests spawn make-diagrams, which shells out to graphviz's `dot` and `xmllint` — present - # locally and in build-explainer.yml but not on a bare runner. Their absence failed the v0.4.0 release's - # test job (execSync ENOENT) with a green suite locally; system deps here must mirror what the tools invoke. - - run: sudo apt-get update && sudo apt-get install -y graphviz libxml2-utils + # The diagram tests spawn make-diagrams, which shells out to `xmllint` to validate every SVG. A bare + # runner does not have it; system deps here must mirror what the tools invoke (nothing calls `dot`). + # imagemagick: make-social-card renders the share card with it; without it the card-legibility tests SKIP. + - run: sudo apt-get update && sudo apt-get install -y libxml2-utils imagemagick - run: npm test + + # End-to-end suite (real embeddings + RVF stores in a temp dir; downloads the small bge model on a fresh runner). + - run: npm run test:e2e diff --git a/.github/workflows/deploy-preserved-goodies.yml b/.github/workflows/deploy-preserved-goodies.yml deleted file mode 100644 index 822b41c..0000000 --- a/.github/workflows/deploy-preserved-goodies.yml +++ /dev/null @@ -1,47 +0,0 @@ -name: Deploy preserved Goodies artifact -on: - workflow_dispatch: -permissions: - actions: read - contents: read -jobs: - deploy: - runs-on: ubuntu-latest - timeout-minutes: 15 - steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 - with: - node-version: '22' - - name: Install deterministic runtime only - run: sudo apt-get update && sudo apt-get install -y libxml2-utils zip unzip - - name: Recover Build 120 artifact - env: - GH_TOKEN: ${{ github.token }} - run: | - gh api repos/${{ github.repository }}/actions/artifacts/10608084895/zip > artifact.zip - echo '0f15e8c8abecd5432742764962fc24c4571a35faceaa022259e96f64be1c5364 artifact.zip' | sha256sum -c - - mkdir build && unzip -q artifact.zip -d build - mkdir -p kb/stores/the-goodies /tmp/pack - unzip -oq build/site/the-goodies-knowledge-pack.zip 'for-ai/*' 'for-humans/*' -d /tmp/pack - cp /tmp/pack/for-ai/the-goodies-* kb/stores/the-goodies/ - cp /tmp/pack/for-humans/the-goodies-primer.md kb/stores/the-goodies/ - jq ' - .repo.clonePath="/tmp/no-clone-needed" | - .visuals.hero.file="assets/hero.png" | - .visuals.sections |= map(.file=("assets/" + (.file|split("/")|last))) | - .brand.socialCard.file="assets/social-card.png" - ' build/build.json > build/build.tmp && mv build/build.tmp build/build.json - - name: Deterministically redraw and assemble - run: | - node tools/make-diagrams.mjs build - node tools/assemble-page.mjs build - ! grep -Rqi 'concept archetype: strata\|Nested containment\|nested frames' build/site/assets/big-idea.svg build/site/index.html - grep -q 'concept archetype: ribbon' build/site/assets/big-idea.svg - test "$(find build/site -type f | wc -l)" -ge 20 - - name: Deploy preserved site without model calls - env: - NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} - NETLIFY_SITE_NAME: the-goodies-explainer - EXPLAINER_SUBMITTED_REPO: adrianco/the-goodies - run: node tools/deploy.mjs build diff --git a/.gitignore b/.gitignore index 6c95c19..891576a 100644 --- a/.gitignore +++ b/.gitignore @@ -5,9 +5,9 @@ docs/.env # deps & build +node_modules node_modules/ **/node_modules/ -.vercel/ # cloned upstream repos (not ours) .targets/ @@ -27,6 +27,7 @@ ruvector.db # local agent DB + model cache + per-run build outputs (all regenerable, not source) agentdb.rvf agentdb.rvf.lock +agentdb.rvf.idmap.json kb/models-cache/ explainer-builds/ @@ -50,3 +51,6 @@ explainer-builds/ # pasted screenshots — one showed a complete npm token on 2026-10-06; never source .docs/ + +# generated explainer builds at the repo root (the ruv-explainer-* hand-built generation was removed; builds live on Netlify) +/ruv-explainer-*/ diff --git a/README.md b/README.md index 9e01070..d8a1595 100644 --- a/README.md +++ b/README.md @@ -4,15 +4,13 @@ ### Point it at any GitHub repo. Get back an explainer a stranger — and their AI — actually understands. -## 🌐 The website — there is only ONE +## The website # → **[explainmyrepo.isovision.ai](https://explainmyrepo.isovision.ai)** ← -This is the live site: the concept, the full process, and all six example explainers on one page. +Paste a public repo's URL, get the page by email. Private repos and your own keys: use the command below. -> **Heads up:** the old `repo-explainer-website.vercel.app` was an earlier draft that told people to run a command (`npx repo-explainer`) that was never published. It now **redirects here**. If you ever land on anything other than **explainmyrepo.isovision.ai**, you're on the wrong (old) page. - -*Complex repos deserve clear introductions. This builds them, then refuses to ship until they're good.* +*Complex repos deserve clear introductions. This builds them, grades them honestly, and tells you the grade.* @@ -39,109 +37,164 @@ That's the bar. `explainmyrepo` exists to clear it, on every build. --- -## What you get — three artifacts from one command +## What you get from one command + +![One GitHub URL goes into explainmyrepo. Out come a live explainer page and a downloadable AI knowledge pack from either door, plus a GitHub repo you own from the local door.](assets/diagrams/three-outputs.svg) -One command reads a repo and produces three things, each quality-gated: +
+ASCII Version (for AI/accessibility) -![One GitHub URL in, three quality-gated artifacts out: a live explainer page, a GitHub repo you own, and a downloadable AI knowledge pack.](assets/diagrams/three-outputs.svg) +``` +github.com/owner/name + | + v + explainmyrepo + | + +--> 1. a live explainer page (both doors) the link you share; diagrams drawn from the code + +--> 2. an AI knowledge pack (both doors) a .zip: vector KB + search CLI + MCP server + +--> 3. a GitHub repo you own (local door only) you are invited as collaborator +``` -1. **A live explainer web page** — the link you share. A bespoke, art-directed walkthrough with a real architecture diagram and a real data-flow diagram drawn from the code itself. -2. **A GitHub repo you own** — you're invited as a collaborator on the explainer's own repo, so you can edit it. It's yours. -3. **A downloadable AI knowledge pack** — a drop-in `.zip` containing a vector knowledge base of the repo, a search CLI, and an MCP server, so Claude Code or Cursor answer from the **real source** instead of guessing. +
+ +1. **A live explainer web page** — a bespoke, art-directed walkthrough with an architecture diagram and a flow diagram drawn from the repo's real dependency graph and entrypoints, never invented. +2. **A downloadable AI knowledge pack** — a `.zip` with a vector knowledge base of the repo, a search CLI and an MCP server, so Claude Code or Cursor answer from the **real source** instead of guessing. +3. **A GitHub repo you own** *(local door only)* — the explainer gets its own repo and you are invited as a collaborator, so you can edit it. --- -## How it works — the process +## How it works — one station table -`explainmyrepo` is not a template filler and not a doc scraper. It's a single Claude Code **skill** that holds the judgment (the *brain*) plus small, pure **tools** that do the mechanics — with one data contract flowing between them. No brittle multi-phase pipeline. +`explainmyrepo` is not a template filler. The judgment (understand, conceive, author, judge) is done by a model; small, deterministic **tools** do the mechanics; one `build.json` carries the data between them. The order of every step lives in **one file**, [`src/stations.mjs`](src/stations.mjs), and the CLI help, the `--from/--to/--only` checks and the tests all read it; a drift test fails if the hosted station table in `skills/explainmyrepo/SKILL.md` stops matching the hosted tool stations here (same set, same order). -The brain runs the repo through an ordered sequence. Each step has one job: +![The station table in four phases: set up (clone-repo, kb:register, build-kb, concept-tournament), build and grade (primer, index-primer, concept, content, check-claims, visual-brief, generate-image, make-favicon, make-social-card, make-diagrams, assemble-page, make-pack, make-ask, quality-grade), ship (deploy, publish-repo, repo-seo, readme-enhance, notify) and follow-ups after delivery (make-overview, redeploy, republish). Solid stations stop the build on failure; dashed ones are advisory.](assets/diagrams/stations.svg) -![The pipeline: read (identity-pinned clone + self-healing credential probe), compete (three models pitch concepts in text, a judge picks one), understand, conceive, author, visualize (bespoke animated SVGs, every image teaches), assemble, grade (worst animation frame included), ship (the verdict enforced as a deploy rail) — with a refine loop that reopens only the named weak slot, and a learning return: every outcome and reader grade feeds the store so the next build starts smarter.](assets/diagrams/pipeline.svg) +
+ASCII Version (for AI/accessibility) -1. **Read** — clone the **exact** repo (identity-pinned, so nothing can substitute a lookalike) and **live-probe every credential** before a cent is spent: the preflight walks each key's candidate sources and self-heals onto the first one that actually works. -2. **Compete** — before any expensive work, **three frontier models fight in plain text** (Claude Sonnet, Claude Fable, GPT-5.6) to art-direct this repo: each pitches a visual metaphor, palette, hero animation, and story arc; an independent judge scores them swap-test-first and the winner's concept seeds the build. Premium creative judgment at *pennies*, so the expensive execution runs once, on the cheaper tier. -3. **Understand** — build a real RVF vector knowledge base from the actual code: structure-aware chunks, local 384-dim embeddings (`bge-small-en-v1.5`), plus an extracted symbol index, dependency graph, and entrypoints. Then author a plain-language primer. Everything downstream is grounded in this KB — **no invented capabilities**. -4. **Conceive** — validate the tournament's winning concept against the full KB and sharpen it with grounded specifics. The truth rails stay with the agent; the creativity already won its seat. -5. **Author** — write the copy along a **comprehension arc** — the questions a newcomer actually asks, in order: *What world am I in? Why does this exist? What does it do? Why is it clever? How is it built? Could I use it? How do I start?* Every claim is traceable to a KB passage. -6. **Visualize** — every image must **teach** (the swap test: if an image could ship unchanged on a different repo, it fails). Labeled, mechanism-bearing illustrations via `gpt-image-2`/Grok; **bespoke *animated* SVG diagrams** hand-authored per an archetype menu (journey · containment · field · fan · tree · exchange — **no two diagrams on one page may share a form**), with every label width-budgeted so text can never collide. The flow diagram must *perform* the repo's thesis in motion, not name stages. Architecture and data-flow diagrams are mandatory and drawn from the repo's *real* dependency graph — never invented. -7. **Assemble** — render the page **once** onto a shared design system (with universal click-to-zoom on every figure), build the downloadable AI knowledge pack, and wire in SEO + social (JSON-LD, a 1200×630 social card, `llms.txt` for AI crawlers). -8. **Grade** — the quality gate (see below). Real screenshots, both devices, every diagram at full size, and **animations sampled at multiple loop phases and judged at their worst frame**. -9. **Ship** — the gate's verdict is enforced as a **deterministic rail at the deploy boundary** (its only override is human-only, terminal-gated — an agent cannot reach it). A refused build isn't garbage: it survives as an artifact with the grader's own words, and the runner can spend one trusted "operator's grade" on a documented post-cap fix. On success: deploy, verify HTTP 200, update the public status page with the full scorecard, and email you every link — including a one-click **grade-this-page** ask. +``` +1 set up clone-repo > kb:register > build-kb > concept-tournament (advisory) +2 build + grade primer > index-primer > concept > content > check-claims (advisory) > visual-brief + > generate-image > make-favicon > make-social-card > make-diagrams > assemble-page + > make-pack > make-ask (advisory, local) > quality-grade +3 ship deploy > publish-repo (local) > repo-seo (local) > readme-enhance (local, advisory) > notify (advisory) +4 follow-ups make-overview (local) > redeploy (local) > republish (local) all advisory, after delivery + +solid = a failure stops the build dashed = advisory, the build carries on L = local door only +``` + +
+ +In plain words: + +1. **Read** — clone the **exact** repo (identity-pinned, so nothing can substitute a lookalike). +2. **Compete** — before expensive work, three models (Claude Sonnet, Claude Fable, GPT-5.6) each pitch a visual metaphor, palette, hero animation and story arc in plain text; a judge picks one. It is a cheap step that fails open: it needs both an Anthropic and an OpenAI key, and when it skips, a single-shot concept is authored instead. +3. **Understand** — build a real RVF vector knowledge base from the actual code (structure-aware chunks, local 384-dim embeddings, a symbol index, a dependency graph, entrypoints), then author a plain-language primer. Everything downstream is grounded in it. +4. **Author** — write the copy along a comprehension arc for a curious fifteen-year-old: *What world am I in? Why does this exist? What does it do? Why is it clever? How is it built? Could I use it? How do I start?* An advisory check compares the page's citations and commands with the KB. +5. **Visualize** — every image must teach (if it could ship unchanged on a different repo, it fails). Diagrams are **drawn by code** from the real graph, or from the structure the model authored; no two diagrams on a page share a form. +6. **Assemble** — render the page once onto a shared design system and wire in SEO and social: JSON-LD, `llms.txt`, and a required, verified 1200×630 share card. +7. **Grade** — the quality gate, below. +8. **Ship** — deploy to its own Netlify site, verify it answers 200, and email you every link. --- -## The quality gate — why the output is a class above +## The quality gate — it tells you the truth -This is the part that makes the difference. A generic generator emits something and stops. `explainmyrepo` **does not ship until an independent critic and a set of operator questions both pass.** +A generic generator emits something and stops. `explainmyrepo` renders the page in a real browser and grades it. **The gate advises; it does not veto** ([ADR-0011](docs/adr/0011-the-gate-advises-never-destroys.md)): a below-bar page is delivered with its weakest axis named, instead of the requester getting nothing. -![The quality gate: real screenshots at 390px and 1440px go to an independent vision critic (Gate A substance, Gate B craft) and six operator questions; the bar is mean ≥ 90, min axis ≥ 85, all six YES — anything less loops back to refine the named weakness.](assets/diagrams/quality-gate.svg) +![The quality gate: the page is rendered at 390px and 1440px, free jargon and reading-level checks run first, then a vision critic grades eleven axes and six operator questions. Exemplary is mean 90, minimum 85 and all six yes. A page at mean 82, minimum 70 and the five ship questions yes ships. Below that it still ships with its weakest axis disclosed. Deploy refuses only on integrity.](assets/diagrams/quality-gate.svg) -The gate renders the live page in a real browser at **390px (mobile)** and **1440px (desktop)**, takes full-page screenshots, and scores them on **two independent rubrics**: +
+ASCII Version (for AI/accessibility) -- **Gate A — "Do they actually get it?"** (substance): visual effectiveness, storytelling, clueless-to-convinced, usefulness-to-*you*, completeness of the arc, and implementation confidence. -- **Gate B — "Did someone who gives a shit make this?"** (craft / anti-slop): typography, alignment, spacing, polish, and imagery craft — including whether the diagrams are genuinely explanatory. +``` +1 render for real 390px phone + 1440px desktop, full-page screenshots +2 free checks first INV-20 unexplained jargon, INV-24 reads at fifteen (no model call) +3 vision critic 11 axes (A1-A6 substance, B1-B5 craft) + six operator questions + mean 79-85: graded twice, samples merged +verdict + exemplary mean 90+, min axis 85+, all six YES + ships mean 82+, min axis 70+, five ship questions YES, both diagrams present + below the bar still ships, its weakest axis named to the requester +At most 3 grading passes. Deploy refuses only on integrity: unassembled page, a different repo +than submitted, a page linking files it does not ship, or no scorecard with no recorded reason. +``` -The bar has **two tiers, both enforced in code**: the **exemplar bar** (mean ≥ 90, minimum axis ≥ 85, both devices) is what the refine loop climbs toward, and the **ship floor** (mean ≥ 82, minimum axis ≥ 70, all operator questions YES) is a hard rail at the deploy boundary — `deploy` recomputes it from the scorecard and refuses anything below it, no matter what any agent believes. The minimum-axis floor is the anti-slop catch: one weak axis (a raw ASCII diagram, a mood image that fails the swap test, an animation whose *worst sampled frame* has colliding text) fails the whole build. Every image is individually interrogated — what does a stranger learn from its pixels alone, and could it ship unchanged on a different repo? +
-On top of the numbers, the operator must answer **YES to all six questions** — a separate, independent gate: +The gate scores two independent rubrics: -1. Would this make me believe I understand this? -2. Would this make it approachable? -3. Would this explain it for somebody who doesn't understand it? -4. Would it give me confidence I understand the architecture? -5. Does it make me smile — "oh, that's cool"? -6. Could someone who knows **nothing** about this domain read the first four sections and explain the problem and the solution back to me? +- **Gate A — "Do they actually get it?"** (substance): visual effectiveness, storytelling, clueless-to-convinced, usefulness to *you*, completeness of the arc, implementation confidence. +- **Gate B — "Did someone who cares make this?"** (craft): typography, alignment, spacing, polish, and imagery craft, including whether the diagrams explain anything. -A single axis below the bar, or a single NO, names the exact weakness, reopens just that slot, re-renders, and re-grades. **Iterating over a few revisions is expected by design** — it's how the build climbs to genuinely high quality. Three sets of eyes see the same pixels: the vision-model critic, the operator, and finally you (the owner) on delivery. If a repo genuinely can't reach the bar, the build **says so honestly** rather than shipping slop and calling it done — and the honest refusal is preserved (site + scorecard + the grader's reasons) so a ten-minute cure beats a rebuild. +Six operator questions sit beside the numbers (understand it? approachable? explainable to a novice? confident about the architecture? makes me smile? could a zero-knowledge reader follow the first four sections?). The minimum-axis floor is the anti-slop catch: one weak axis fails a tier no matter how good the mean is. The reader on every page is a curious fifteen-year-old, and two free checks measure that before a single vision token is spent. --- -## The factory learns — every build makes the next one better +## The factory learns -Most generators are amnesiac: build #100 is exactly as naive as build #1. This one closes the loop: +![What each build leaves behind: its scorecard and cost, the reader's own grade, a local learning store, and changes to the skill, gate and tools.](assets/diagrams/learning-loop.svg) -![The learning loop: a shipped page emits its gate outcome and the reader's own 1-to-100 grade; both land in a measured-truth oracle store; patterns are distilled and promoted only when backed by outcomes; the recipe itself — the skill, the gate, the tools — carries the lessons into the next build.](assets/diagrams/learning-loop.svg) +
+ASCII Version (for AI/accessibility) -- **Two verdicts per page, side by side**: the machine grader's scorecard *and* the reader's own 1–100 + comments (every delivery email asks for it). The admin dashboard plots the synthesized score over time — the factory has to prove it's getting better, not claim it. -- **Only measured truth is promoted**: build outcomes and human grades land in an oracle-tier learning store; patterns distilled from it are marked trustworthy only when execution-observed. -- **Lessons live in the recipe, not in anyone's memory**: when a failure teaches something (an animation that hid its worst frame, a label that collided at column scale, a $0 pre-check that burned real grade budget), the *skill, the gate, or a tool* is changed the same day — so the fix fires on every future build even when nobody remembers the incident. +``` +a shipped page --> scorecard, cost, weakest axis, diagram forms are recorded + | + v +reader's own grade (1-100 + comments, linked from the delivery email; npm run pull-ratings ingests them) + | + v +learning store (local ruflo memory namespace; the admin page plots the trend) + | + v +the recipe changes: when a failure teaches something, the skill, the gate or a tool is changed +``` + +
-The receipts are in the git log: the first fully-autonomous build after this week's lessons went **first-try exemplary — one grade pass, 37 minutes, zero human minutes**. +Lessons live in the recipe (the skill, the gate, the tools), not in anyone's memory, so a fix fires on every later build. --- -## One brain, three doors +## Two doors + +![Two doors, one station table: the local door (npx explainmyrepo, your keys, any repo) and the hosted door (the website, public repos, zero keys) read the same station table, run the same tools and apply the same quality gate.](assets/diagrams/two-doors.svg) -The judgment lives in **one** place — a Claude Code skill. The same core is exposed through three thin adapters that each run the *identical* skill; none of them contains explainer logic of its own. Improve the brain once, and it improves everywhere. +
+ASCII Version (for AI/accessibility) + +``` + src/stations.mjs + tools/*.mjs + / \ + local door hosted door + npx explainmyrepo explainmyrepo.isovision.ai + your keys, any repo incl. private zero keys, public repos only + src/orchestrator.mjs runs every GitHub Action -> bin/agentic-runner.mjs: clone, credential + local station (authoring: src/brain.mjs) probes, concept tournament, then a headless agent that follows + also: explainer repo, Ask box, skills/explainmyrepo/SKILL.md; the runner adds a bounded cure + video + infographic, README outreach stage, the claims check and the delivery email + no GitHub repo, no Ask box yet +``` -![One brain, three doors: the website builds public repos with zero keys; npx handles private repos and your own keys (one key — OpenAI — inside Claude Code); the Claude Code plugin runs it with a slash command.](assets/diagrams/three-doors.svg) +
-- **Hosted website** — paste a GitHub URL in the browser. **Public repos, zero setup** — the easiest door. -- **npx CLI** — the one-liner below. **Private repos and your own keys.** -- **Claude Code plugin** — run it from inside Claude Code with a slash command. +**Pick your door with one question — is the repo public, and whose keys should do the work?** Public repo and you just want the page: use the website. Private repo, or you want it on your own accounts: use the CLI, and run it **inside a VS Code / Claude Code session** in a project whose `.env` already holds your keys, so everything is picked up automatically. (`/explainmyrepo ` inside Claude Code runs the same skill by hand.) -**Pick your door with one question — is the repo public, and whose keys should do the work?** -Public repo and you just want the page: use the website, done. Private repo, or you want it on -your own accounts: use the CLI — and run it **inside a VS Code / Claude Code session**, in a -project whose `.env` already holds your keys, so everything is picked up automatically. +The two doors stay in step by test, not by hope: `tests/two-doors-conform.test.mjs` pins the reader standard and the image rules in both places, and a drift test parses the hosted station table in `skills/explainmyrepo/SKILL.md` and fails unless it lists exactly the hosted tool stations of `src/stations.mjs`, in the same order (the brain stations and the runner's own prose are checked more loosely: each both-door station must be named somewhere the hosted agent reads). --- -## Every explainer can answer follow-up questions +## Local door: every explainer can answer follow-up questions -Each page ends with an **Ask box**: type a question in plain words and get a short written answer, with -numbered links to the exact files it came from. It searches the page and the repo's own files in the reader's -browser, then a small model writes the answer through one central service (`ask-service/`) — the explainer stays -a plain static site. If the service is down it shows the closest passages instead, and says so. Set -`ASK_SIGNING_SECRET` (same value on the service and your build machine) to turn on written answers; -`ASK_DISABLE=1` leaves the box off. Deploy also now refuses a page that links a file it does not ship. -See `docs/adr/0016-ask-this-project.md`. +Pages built by the **local door** end with an **Ask box**: type a question in plain words and get a short written answer with numbered links to the exact files it came from. It searches the page and the repo's own files in the reader's browser, then a small model writes the answer through one central service ([`ask-service/`](ask-service/README.md)), so the explainer itself stays a plain static site. If the service is down it shows the closest passages and says so. Set `ASK_SIGNING_SECRET` (the same value on the service and your build machine) to turn on written answers; `ASK_DISABLE=1` leaves the box off. The service screens every question and every answer with AIMDS and fails closed. Hosted-door builds do not get the box yet. Deploy also refuses a page that links a file it does not ship. See [ADR-0016](docs/adr/0016-ask-this-project.md). + +--- ## Get started ```bash -# Point it at any GitHub repo. Walk away. Get back a live page, a repo you own, and an AI pack. +# Point it at any GitHub repo. Walk away. Get back a live page and an AI pack. npx explainmyrepo https://github.com/owner/repo ``` @@ -149,38 +202,33 @@ npx explainmyrepo https://github.com/owner/repo | For | What | Notes | |---|---|---| -| The brain | `OPENROUTER_API_KEY`, **or** `ANTHROPIC_API_KEY`, **or nothing** if you're logged into Claude Code | any one of the three is enough. With an OpenRouter key the authoring runs on `z-ai/glm-5.2` — measured 15× cheaper than Sonnet 5 *and* higher-scoring on a blind art-direction A/B. Pin the old model with `EXPLAINMYREPO_AUTHORING=anthropic` | -| Art + quality gate | `OPENAI_API_KEY` in `.env` | hero imagery and the vision grader | -| **ImageMagick** | `magick` (v7) or `convert` (v6) on your `PATH` | **required** — the favicon station shells out to it and fails loudly without it. `brew install imagemagick` on macOS, `apt install imagemagick` on Debian/Ubuntu | -| The live URL | `NETLIFY_AUTH_TOKEN` in `.env` — optional | skip with `--no-deploy` and you still get the complete page locally | +| The brain | `ANTHROPIC_API_KEY`, **or** `OPENROUTER_API_KEY`, **or nothing** if you're logged into Claude Code | any one of the three is enough. With an Anthropic key (or Claude Code login) authoring runs on `claude-sonnet-5-5`. With **only** an OpenRouter key it runs on `z-ai/glm-5.3`; set `EXPLAINMYREPO_AUTHORING=openrouter` to choose it on purpose or `=anthropic` to refuse it | +| Art + quality gate | `OPENAI_API_KEY` in `.env` | hero imagery (`gpt-image-2.5-flare`, falling back to `gpt-image-2`, then Grok when there is no OpenAI key or the OpenAI chain fails) and the vision grader | +| **ImageMagick** | `magick` (v7) or `convert` (v6) on your `PATH` | **required** — the favicon and share-card stations shell out to it and fail loudly without it. `brew install imagemagick` on macOS, `apt install imagemagick` on Debian/Ubuntu | +| The live URL | `NETLIFY_AUTH_TOKEN` in `.env` | required unless you pass `--no-deploy` (the preflight stops without it); with `--no-deploy` you still get the complete page locally | | Private repos | `gh auth login` | public repos need nothing | -**The count, plainly:** website — **zero keys**. npx **inside Claude Code** (recommended) — -**one key** (OpenAI); add a Netlify token only if you want the live URL. npx in a bare -terminal — **two keys** (add Anthropic). Private repo — no extra key, just `gh auth login` once. +**The count, plainly:** website — **zero keys**. npx **inside Claude Code** (recommended) — **one key** (OpenAI); add a Netlify token for the live URL (or pass `--no-deploy`). npx in a bare terminal — **two keys** (add Anthropic). Private repo — no extra key, just `gh auth login` once. -**Recommended:** run it inside a **VS Code / Claude Code session** in a project whose `.env` -already has these — nothing to export, nothing to paste, and Claude Code itself carries the -brain on your existing subscription. In a bare terminal it works too; you'll just be told up -front which keys to add. +**Recommended:** run it inside a **VS Code / Claude Code session** in a project whose `.env` already has these — nothing to export, nothing to paste, and Claude Code itself carries the brain on your existing subscription. -**What happens:** it reads the repo, understands it, art-directs and writes the page, generates the imagery and the real architecture + data-flow diagrams, grades the result on mobile and desktop until it clears the bar, then deploys it. +**What you get back:** a live URL (in your terminal and by email), the downloadable AI pack, and on the local door a GitHub repo you're a collaborator on — plus the scorecard and both screenshots, so you're the final set of eyes. -**What you get back:** a live URL (in your terminal and by email), a GitHub repo you're a collaborator on, and the downloadable AI knowledge pack — plus the scorecard and both screenshots, so you're the final set of eyes. +> **Status:** `npx explainmyrepo` is **live on npm** (3.x). The hosted website is live at [explainmyrepo.isovision.ai](https://explainmyrepo.isovision.ai). Found it valuable? **[A star on this repo](https://github.com/stuinfla/Repo-Explainer)** genuinely helps. Hit a problem? **[Open an issue](https://github.com/stuinfla/Repo-Explainer/issues)** — happy to help fix it and make it better. -> **Status:** `npx explainmyrepo` is **live on npm** (v0.2+). The hosted website is live at [explainmyrepo.isovision.ai](https://explainmyrepo.isovision.ai). Found it valuable? **[A star on this repo](https://github.com/stuinfla/Repo-Explainer)** genuinely helps. Hit a problem? **[Open an issue](https://github.com/stuinfla/Repo-Explainer/issues)** — happy to help fix it and make it better. +**Don't want to pay per token for the authoring brain?** The same skill runs through a **Codex** session signed in with a ChatGPT subscription, which drops the text-model cost to $0 (only `gpt-image-2.5-flare` imagery stays metered). It also builds straight from a **local checkout**, so private source never leaves the machine. See [`docs/prompts/codex-explainer-build.md`](docs/prompts/codex-explainer-build.md) for the setup and a copy-paste prompt template. -**Don't want to pay per token for the authoring brain?** The same skill runs through a **Codex** session signed in with a ChatGPT subscription, which drops the text-model cost to $0 (only `gpt-image-2` imagery stays metered, at cents per build). It also builds straight from a **local checkout**, so private source never leaves the machine. See [`docs/prompts/codex-explainer-build.md`](docs/prompts/codex-explainer-build.md) for the setup and a copy-paste prompt template. +**Contacting maintainers.** After a local build ships, the readme-enhance station opens **one** friendly GitHub issue showing the maintainer a better README for their repo (their README exactly as written, plus an explainer link and diagrams), and offers a pull request only if they say yes. Never your own repo or a private one, one contact per repo, at most five a day. A single check-in note, sent only by running `npx explainmyrepo outreach followup` a week or more later, is posted only if they have not replied, and any maintainer-email draft goes to you, never to them. Switch it off with `--no-readme-pr` or `README_ENHANCE=0`. See [ADR-0015](docs/adr/0015-readme-outreach-issue-first.md). --- ## See a real one -The agenticow explainer below was generated end to end from [`ruvnet/agenticow`](https://github.com/ruvnet/agenticow): a captivating hero, a plain-language walkthrough, **a real architecture diagram and data-flow diagram drawn from agenticow's own code**, concrete use-cases, and a one-click AI knowledge pack. +The agenticow explainer above was generated end to end from [`ruvnet/agenticow`](https://github.com/ruvnet/agenticow): a captivating hero, a plain-language walkthrough, **an architecture diagram and a data-flow diagram drawn from agenticow's own code**, concrete use-cases, and a one-click AI knowledge pack. -### [Open the live agenticow explainer →](https://stuinfla.github.io/Repo-Explainer/agenticow/) +### [Open the live agenticow explainer →](https://agenticow-explainer.netlify.app/) -The bar these are calibrated against — five hand-built explainers, five completely different looks, same engine, same gate: +Earlier hand-built explainers the bar is calibrated against — five completely different looks, same engine, same gate: | | | | |---|---|---| @@ -195,36 +243,44 @@ The bar these are calibrated against — five hand-built explainers, five comple | Layer | Tool | |---|---| -| Concept tournament | Claude Sonnet 5 · Claude Fable 5 · GPT-5.6 competing in text; GPT-5.6 judging | -| Knowledge base | RVF single-file vector DB (`@ruvector/rvf`) + `bge-small-en-v1.5` (local, 384-dim) | -| Imagery | `gpt-image-2` / Grok (labeled, mechanism-bearing illustration) + bespoke hand-authored **animated SVG** diagrams (archetype-diverse, width-budgeted) | -| Quality gate | Playwright dual-viewport render + GPT-5.6 vision grading (configurable) — every diagram at full size, animations at their worst sampled frame, ship floor enforced as a deploy rail | -| Feedback + learning | Reader 1–100 grades beside machine grades on the admin; outcomes + grades feed an oracle-tier learning store | -| Companions (local) | [HyperFrames](https://github.com/heygen-com/hyperframes) — the page's own gated assets re-rendered into a 30–40s trailer and a 10s social loop (16:9 + 9:16), locally, for ~$0 | -| Hosting | Netlify by default (provider-agnostic adapter) | +| Concept tournament | Claude Sonnet 5.5 · Claude Fable 5.1 · GPT-5.6 Sol competing in text; GPT-5.6 Terra judging | +| Authoring brain | `claude-sonnet-5-5` by default; `z-ai/glm-5.3` via OpenRouter only as the sole credential or by opt-in | +| Knowledge base | RVF single-file vector DB (`@ruvector/rvf`) + a local embedder named by each target's `embed` block (`bge-small-en-v1.5`, 384-dim, for every registered target) | +| Imagery | `gpt-image-2.5-flare` at `xhigh`, then `gpt-image-2`, then Grok when there is no OpenAI key or the OpenAI chain fails (labeled, mechanism-bearing illustration) · diagrams drawn deterministically as SVG by `tools/make-diagrams.mjs` | +| Quality gate | Playwright dual-viewport render + GPT-5.6 Sol vision grading (`QUALITY_VISION_MODEL`) — ship tier 82/70, exemplary tier 90/85, deploy refuses only on integrity | +| Feedback + learning | Reader 1–100 grades beside machine grades; outcomes feed a local learning store | +| Companions (local) | [HyperFrames](https://github.com/heygen-com/hyperframes) — a page's own assets re-rendered into a trailer and a social loop, locally | +| Hosting | Netlify, one site per explainer | + +Prices for `gpt-image-2.5-flare` are not published to us, so cost receipts say **unpriced** for it rather than guessing; rates for the Anthropic models come from third-party price lists, not a bill. -The full recipe lives in [`docs/adr/0005-skill-based-explainer-recipe.md`](docs/adr/0005-skill-based-explainer-recipe.md); the domain model in [`docs/ddd/explainmyrepo-recipe-domain.md`](docs/ddd/explainmyrepo-recipe-domain.md). +The founding decision is [`docs/adr/0005-skill-based-explainer-recipe.md`](docs/adr/0005-skill-based-explainer-recipe.md) (read its banner first: later ADRs 0006–0016 supersede parts of it); the slot-by-slot data contract is [`tools/CONTRACT.md`](tools/CONTRACT.md); every tool's own header is collected in [`skills/explainmyrepo/TOOLS-CONTRACT.md`](skills/explainmyrepo/TOOLS-CONTRACT.md), which a test keeps in step with the tools. ## The Alive Kit — what a finished page can become (local runs only) -A gated build's assets are reusable creative truth, so this repo can turn a finished -explainer into **companion artifacts** — but only when you clone it and run them yourself, -and only for capabilities that have actually been **proven**: +A gated build's assets are reusable creative truth, so this repo can turn a finished explainer into **companion artifacts** — but only when you clone it and run them yourself, and only for capabilities that have actually been **proven**: ``` npx explainmyrepo capabilities ``` -That command renders the verified-capability registry (`capabilities.json`) — the *only* -source of what's enabled, so it can never overstate. Today it shows two ✓ (a shareable -**trailer** and a 16:9 + 9:16 **social loop**, each verified end-to-end with recorded -receipts, ~$0 to render) and two ○ that are specified but honestly *not enabled* until -they pass their own supervised verification runs. Companions never run on the hosted door, -never touch a build's artifacts, and can never block a page from shipping. Governance: -[`docs/adr/0009-alive-kit-local-companions.md`](docs/adr/0009-alive-kit-local-companions.md). +That command renders the verified-capability registry (`capabilities.json`) — the *only* source of what's enabled, so it can never overstate. Companions never run on the hosted door, never touch a build's artifacts, and can never block a page from shipping. Governance: [`docs/adr/0009-alive-kit-local-companions.md`](docs/adr/0009-alive-kit-local-companions.md). --- +## Known limits + +Plainly, as of this release: + +- **The Ask box is local-door only.** Hosted-door pages do not have one yet. +- **The hosted door cannot yet move deploy into the runner.** The hosted agent still runs `deploy` itself; the runner only retries and cures around it. +- **Image prices are partly unknown.** `gpt-image-2.5-flare` has no known per-image price, so cost totals leave it out and say so. +- **Story diagrams on a phone.** Every diagram is drawn twice, wide and as a 360px phone twin, and `make-diagrams` fails the step if any label would be under 11px on a 390px phone. The story diagrams (system map, decision) have been exercised on fewer real builds than the radial architecture map. +- **Hero scenes are untested against a live model.** The local brain now authors an animated hero scene and a valid one replaces the raster hero, but the validator and repair pass have been proven on fixtures, not across real builds. +- **Page weight is checked, not tuned.** `deploy` and the site check fail a page whose images total over 1.5 MB (lightbox originals are not counted) and warn when the first view (gzipped HTML + CSS + the images above the fold) passes 300 KB (`src/site-check.mjs`). Image files are not content-fingerprinted and `deploy` writes no `_headers` file, so pages use Netlify's default revalidating cache; fingerprinted long-cache filenames would need `tools/deploy.mjs` to emit a `_headers` file first, and that is not built. +- **No branch protection on `main` yet.** CI runs on every pull request, but nothing forces it. +- **Outreach response rates are unmeasured.** The ledger exists to find out; no claim is made yet. + ## Credit The tools in the examples above belong to [Reuven Cohen / @ruvnet](https://github.com/ruvnet). `explainmyrepo` is an independent project that exists to help more people — and their AIs — discover, understand, and adopt great work. diff --git a/ask-service/README.md b/ask-service/README.md index ce08944..349f772 100644 --- a/ask-service/README.md +++ b/ask-service/README.md @@ -1,20 +1,44 @@ # explainmyrepo ask service -One Netlify function (`/api/ask`) that writes the short, cited answers for the "Ask this project" box on every -explainer. Explainer sites call it; they keep no key and need no function of their own. +One Netlify function (`/api/ask`) that writes the short, cited answers for the "Ask this project" box on +explainers built by the **local door** (the hosted door does not add the box yet; see ADR-0016). Explainer sites +call it; they keep no key and need no function of their own. **Why central:** the first prototype put a function and the model key on each explainer site. Review showed the page supplied its own excerpts, so the endpoint was an open proxy on the key. Here the browser sends only the question and passage ids; the service verifies a signed token for the site's host, fetches that site's own `ask/index.json`, and builds the passages itself. -**Environment (set on this site):** +## What a request goes through (in order, `netlify/functions/ask.mjs`) + +1. Not configured (no `ASK_SIGNING_SECRET` or `OPENROUTER_API_KEY`): refused, so the page shows the closest passages. +2. The signed token must verify (`verifyToken`) and the browser `Origin` must match the signed host. +3. **AIMDS inbound** (`lib/guard.mjs`, `@claude-flow/aidefence`): the question is scanned before anything is spent or + sent. Threats at medium severity or above are refused, and so are personal data and credentials (they must not be + forwarded to a third-party model). +4. The per-site and global daily counters (Netlify Blobs) take a slot. No working counter means no answer. +5. The model writes the answer from the site's own passages. +6. **AIMDS outbound**: the answer is scanned before the visitor sees it. A threat withholds it. Every scanner error + on either side blocks (fail closed). + +**Answers are buffered, not streamed.** The reply is held until it has been scanned, because a stream cannot be taken +back once it has started. Answers are under 150 words, so the wait is a few seconds. + +## Environment (set on this site) | Variable | Purpose | | --- | --- | -| `OPENROUTER_API_KEY` | model access. Give this site its own key with a spend limit set at OpenRouter — that limit is the hard backstop | -| `ASK_SIGNING_SECRET` | same value as in the build machine's `.env`; tokens are `base64url(host).HMAC(host)` | +| `OPENROUTER_API_KEY` | model access. Give this site its own key with a spend limit set at OpenRouter; that limit is the hard backstop | +| `ASK_SIGNING_SECRET` | same value as in the build machine's `.env` (at least 24 characters); tokens are `base64url(host).HMAC(host)` | | `ASK_MODEL` | default `anthropic/claude-haiku-5.5` | | `ASK_SITE_CAP` / `ASK_DAILY_CAP` | questions per site per day (default 150) / across all sites (default 1500) | -Fails closed: no key, no secret, or no working counter means no answer — the page falls back to showing the closest passages. +## Where the token code lives + +The service **verifies** (`verifyToken` in `netlify/functions/ask.mjs`); the build machine only **signs** +(`src/ask-token.mjs`). They are deployed separately, so each side owns its half, and `tests/ask.test.mjs` runs the +signer and the service's verifier against each other (forged, truncated and wrong-secret tokens are rejected). +`tests/ask-service.test.mjs` drives the guard through the service's real handler. + +Fails closed: no key, no secret, no working counter, or no scanner verdict means no answer. The page then falls back +to showing the closest passages and says so. diff --git a/ask-service/lib/guard.mjs b/ask-service/lib/guard.mjs new file mode 100644 index 0000000..b733f22 --- /dev/null +++ b/ask-service/lib/guard.mjs @@ -0,0 +1,35 @@ +// guard.mjs — AIMDS screening for the Ask service (global rule 8): the visitor's question is scanned before it +// reaches the model, the model's answer is scanned before it reaches the visitor. Every failure path BLOCKS. +// +// @claude-flow/aidefence 3.1.0 has no `blockThreshold` option (checked against its published types), so the +// threshold is applied here to the severity of each returned threat: 'medium' blocks medium, high and critical. +import { createAIDefence } from '@claude-flow/aidefence'; + +const RANK = { low: 1, medium: 2, high: 3, critical: 4 }; +export const BLOCK_THRESHOLD = 'medium'; + +/** @param {{ scanner?: { detect(text: string): Promise }, blockThreshold?: keyof typeof RANK }} [opts] + * `scanner` is injectable so tests can drive every verdict without the real pattern packs. */ +export function createGuard({ scanner, blockThreshold = BLOCK_THRESHOLD } = {}) { + const s = scanner ?? createAIDefence({ enableLearning: true }); + const floor = RANK[blockThreshold] ?? RANK[BLOCK_THRESHOLD]; + + async function check(text, { blockPii }) { + let r; + try { r = await s.detect(String(text)); } catch { return { ok: false, reason: 'scanner-error' }; } // no verdict = no pass + if (!r || typeof r !== 'object') return { ok: false, reason: 'scanner-error' }; + const threats = Array.isArray(r.threats) ? r.threats : []; + const hit = threats.filter((t) => (RANK[t?.severity] ?? Infinity) >= floor); // unknown severity counts as blocking + if (hit.length) return { ok: false, reason: 'threat', types: [...new Set(hit.map((t) => String(t.type)))] }; + if (r.safe === false && !threats.length) return { ok: false, reason: 'threat', types: [] }; // unsafe with no detail + if (blockPii && r.piiFound) return { ok: false, reason: 'pii' }; + return { ok: true }; + } + + return { + /** Inbound: also refuses personal data / credentials, which must not be forwarded to a third-party model. */ + checkQuestion: (q) => check(q, { blockPii: true }), + /** Outbound: threats only. Answers come from public repo files and may legitimately quote a contact address. */ + checkAnswer: (a) => check(a, { blockPii: false }), + }; +} diff --git a/ask-service/netlify/functions/ask.mjs b/ask-service/netlify/functions/ask.mjs index 4a7b6f9..14fe51a 100644 --- a/ask-service/netlify/functions/ask.mjs +++ b/ask-service/netlify/functions/ask.mjs @@ -2,13 +2,15 @@ // Trusts nothing from the browser but a question and passage ids. Everything the model reads comes from the // asking site's own published ask/index.json, fetched here, for a host proven ours by a signed token. import crypto from 'node:crypto'; +import { createGuard } from '../../lib/guard.mjs'; export const MODEL = () => process.env.ASK_MODEL || 'anthropic/claude-haiku-5.5'; const num = (v, d) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Number(v) : d); const MAX_INDEX_BYTES = 12 * 1024 * 1024, INDEX_TTL_MS = 10 * 60 * 1000; -// ---- token (same format as src/ask-token.mjs in the main repo) ---- -const isHost = (h) => typeof h === 'string' && h.length <= 120 && /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(h); +// ---- token (same format as src/ask-token.mjs; this site is deployed on its own, so it cannot import across the +// boundary — tests/ask.test.mjs signs with one and verifies with the other, and feeds both the same host corpus) ---- +export const isHost = (h) => typeof h === 'string' && h.length <= 120 && /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/.test(h); export function verifyToken(token, secret) { if (typeof token !== 'string' || !secret) return null; const [h, sig, extra] = token.split('.'); if (!h || !sig || extra !== undefined) return null; @@ -37,13 +39,26 @@ export function buildPassages(index, ids) { return out; } +// Read a response body with a hard byte cap, whatever Content-Length claims (chunked/missing/lying headers). +export async function readCapped(res, max) { + if (!res.body) { const t = await res.text(); if (Buffer.byteLength(t) > max) throw new Error('index too large'); return t; } + const reader = res.body.getReader(), chunks = []; let total = 0; + for (;;) { + const { done, value } = await reader.read(); if (done) break; + total += value.byteLength; + if (total > max) { try { await reader.cancel(); } catch {} throw new Error('index too large'); } + chunks.push(value); + } + return Buffer.concat(chunks).toString('utf8'); +} + const cache = new Map(); // host -> { at, index } (per warm instance) -async function siteIndex(host) { +async function siteIndex(host, doFetch) { const hit = cache.get(host); if (hit && Date.now() - hit.at < INDEX_TTL_MS) return hit.index; - const r = await fetch(`https://${host}/ask/index.json`, { redirect: 'error', signal: AbortSignal.timeout(8000) }); + const r = await doFetch(`https://${host}/ask/index.json`, { redirect: 'error', signal: AbortSignal.timeout(8000) }); if (!r.ok) throw new Error(`index ${r.status}`); if (Number(r.headers.get('content-length') || 0) > MAX_INDEX_BYTES) throw new Error('index too large'); - const index = JSON.parse(await r.text()); + const index = JSON.parse(await readCapped(r, MAX_INDEX_BYTES)); cache.set(host, { at: Date.now(), index }); return index; } @@ -79,7 +94,15 @@ Write the answer a smart friend would give someone who is not an engineer: const json = (o, status = 200, h = {}) => new Response(JSON.stringify(o), { status, headers: { 'content-type': 'application/json', ...h } }); const originOk = (o) => { try { const u = new URL(o); return u.protocol === 'https:' && isHost(u.hostname) ? u.origin : null; } catch { return null; } }; -export default async (req) => { +let defaultGuard; +// Salted hash of the caller IP (never stored raw); null when the platform gives us no address. +export function callerHash(req) { + const ip = (req.headers.get('x-nf-client-connection-ip') || (req.headers.get('x-forwarded-for') || '').split(',')[0] || '').trim(); + return ip ? crypto.createHmac('sha256', process.env.ASK_SIGNING_SECRET || 'x').update(ip).digest('hex').slice(0, 24) : null; +} + +export async function handle(req, deps = {}) { + const guard = deps.guard ?? (defaultGuard ??= createGuard()), doFetch = deps.fetch ?? fetch; const origin = originOk(req.headers.get('origin') || ''); const cors = origin ? { 'access-control-allow-origin': origin, 'access-control-allow-methods': 'POST, OPTIONS', 'access-control-allow-headers': 'content-type', vary: 'origin' } : { vary: 'origin' }; if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: cors }); @@ -93,41 +116,53 @@ export default async (req) => { if (!origin || new URL(origin).hostname !== host) return json({ error: 'not allowed' }, 403, cors); // browsers always send Origin; it must match the signed host const question = String(body.q || '').trim().slice(0, 300); if (question.length < 2) return json({ error: 'bad request' }, 400, cors); + if (!(await guard.checkQuestion(question)).ok) return json({ error: 'question not allowed' }, 422, cors); // AIMDS, before anything is spent or sent let passages; - try { passages = buildPassages(await siteIndex(host), body.ids); } catch { return json({ error: 'site index unavailable' }, 502, cors); } + try { passages = buildPassages(await siteIndex(host, doFetch), body.ids); } catch { return json({ error: 'site index unavailable' }, 502, cors); } if (!passages.length) return json({ error: 'bad request' }, 400, cors); try { // atomic per-site and global daily caps; no working counter means no answer (fail closed) - const { getStore } = await import('@netlify/blobs'); - const ok = await takeSlot(getStore('ask-usage'), [`site:${host}`, 'all'], [num(process.env.ASK_SITE_CAP, 150), num(process.env.ASK_DAILY_CAP, 1500)], new Date().toISOString().slice(0, 10)); + const getStore = deps.getStore ?? (await import('@netlify/blobs')).getStore; + const ipH = callerHash(req); // per-caller cap first, so one abuser cannot burn the site/global budget + const keys = [...(ipH ? [`ip:${ipH}`] : []), `site:${host}`, 'all']; + const caps = [...(ipH ? [num(process.env.ASK_IP_CAP, 40)] : []), num(process.env.ASK_SITE_CAP, 150), num(process.env.ASK_DAILY_CAP, 1500)]; + const ok = await takeSlot(getStore('ask-usage'), keys, caps, new Date().toISOString().slice(0, 10)); if (!ok) return json({ error: 'daily limit' }, 429, cors); } catch { return json({ error: 'counter unavailable' }, 503, cors); } const name = host.replace(/-explainer\.netlify\.app$/, '').replace(/\..*$/, ''); const prompt = `QUESTION: ${question}\n\nNOTES:\n` + passages.map((e, i) => `[${i + 1}] (${e.src})\n${e.text}`).join('\n\n'); - const up = await fetch('https://openrouter.ai/api/v1/chat/completions', { - method: 'POST', headers: { Authorization: `Bearer ${key}`, 'content-type': 'application/json', 'HTTP-Referer': `https://${host}`, 'X-Title': 'explainmyrepo ask' }, - body: JSON.stringify({ model: MODEL(), stream: true, max_tokens: 1200, reasoning: { effort: 'low' }, temperature: 0.2, messages: [{ role: 'system', content: SYSTEM(name) }, { role: 'user', content: prompt }] }), - }); - if (!up.ok || !up.body) return json({ error: 'upstream' }, 502, cors); - const enc = new TextEncoder(), dec = new TextDecoder(); - const stream = new ReadableStream({ - async start(ctl) { - const rd = up.body.getReader(); let buf = ''; - try { - for (;;) { - const { done, value } = await rd.read(); if (done) break; buf += dec.decode(value, { stream: true }); - let i; while ((i = buf.indexOf('\n')) > -1) { - const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1); - if (!line.startsWith('data:')) continue; const d = line.slice(5).trim(); if (d === '[DONE]') continue; - try { const t = JSON.parse(d).choices?.[0]?.delta?.content; if (t) ctl.enqueue(enc.encode(t)); } catch { /* keep-alive comment */ } - } - } - } finally { ctl.close(); } - }, - }); - return new Response(stream, { headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', ...cors } }); -}; + let answer; + try { + const up = await doFetch('https://openrouter.ai/api/v1/chat/completions', { + method: 'POST', headers: { Authorization: `Bearer ${key}`, 'content-type': 'application/json', 'HTTP-Referer': `https://${host}`, 'X-Title': 'explainmyrepo ask' }, + body: JSON.stringify({ model: MODEL(), stream: true, max_tokens: 1200, reasoning: { effort: 'low' }, temperature: 0.2, messages: [{ role: 'system', content: SYSTEM(name) }, { role: 'user', content: prompt }] }), + }); + if (!up.ok || !up.body) return json({ error: 'upstream' }, 502, cors); + answer = await readAnswer(up.body); + } catch { return json({ error: 'upstream' }, 502, cors); } + // The answer is held until it has been scanned: a stream cannot be taken back once it has started. Answers are + // under 150 words, so the wait is a few seconds. + if (!answer.trim()) return json({ error: 'upstream' }, 502, cors); + if (!(await guard.checkAnswer(answer)).ok) return json({ error: 'answer withheld' }, 502, cors); + return new Response(answer, { headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store', ...cors } }); +} + +export default (req) => handle(req); + +async function readAnswer(stream) { + const rd = stream.getReader(), dec = new TextDecoder(); + let buf = '', out = ''; + for (;;) { + const { done, value } = await rd.read(); if (done) break; buf += dec.decode(value, { stream: true }); + let i; while ((i = buf.indexOf('\n')) > -1) { + const line = buf.slice(0, i).trim(); buf = buf.slice(i + 1); + if (!line.startsWith('data:')) continue; const d = line.slice(5).trim(); if (d === '[DONE]') continue; + try { out += JSON.parse(d).choices?.[0]?.delta?.content || ''; } catch { /* keep-alive comment */ } + } + } + return out; +} export const config = { path: '/api/ask' }; diff --git a/ask-service/package-lock.json b/ask-service/package-lock.json index b296c40..2448db5 100644 --- a/ask-service/package-lock.json +++ b/ask-service/package-lock.json @@ -6,7 +6,25 @@ "": { "name": "explainmyrepo-ask-service", "dependencies": { - "@netlify/blobs": "latest" + "@claude-flow/aidefence": "^3.1.0", + "@netlify/blobs": "^11.1.7" + } + }, + "node_modules/@claude-flow/aidefence": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@claude-flow/aidefence/-/aidefence-3.1.0.tgz", + "integrity": "sha512-q/y8Gyc061DIC4d8ZRIlGYpDQBiK5rOz0r+rLR/AcYEANlLSCk5ao4hoftNNLjWLofKY6tRvPfxa/Fh39Wtc5g==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "agentdb": ">=2.0.0-alpha.1" + }, + "peerDependenciesMeta": { + "agentdb": { + "optional": true + } } }, "node_modules/@envelop/instrumentation": { @@ -23,19 +41,19 @@ } }, "node_modules/@fastify/busboy": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.3.tgz", - "integrity": "sha512-fmo/IKgkenPzz3qTKG+sIUXdF/Kv83AkvvOXJHPTHJeKJbat8SsL1ihUaFaDotqoEl4UZ1Lf8Eb/3vK6eaWX2A==", + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.5.tgz", + "integrity": "sha512-y8MTAeBlEQUNVnskmZQwpseZN3EgCksQNOULlfxWY6o6VEqh01+oExMgbM7gN6YLQ8pNDYeweNPKJRt8jQm2ZQ==", "license": "MIT" }, "node_modules/@netlify/blobs": { - "version": "11.1.4", - "resolved": "https://registry.npmjs.org/@netlify/blobs/-/blobs-11.1.4.tgz", - "integrity": "sha512-rtvtXG0NQkmIdpdI8AI/LKesf3TdZJwNP0VaxodPpb/yYzME62YAaqYVmB2MC5gO5Wxls1aIzcCK2xJFRNRhoQ==", + "version": "11.1.7", + "resolved": "https://registry.npmjs.org/@netlify/blobs/-/blobs-11.1.7.tgz", + "integrity": "sha512-iOOQSC990P5JtvBGfPMngRxId9H7FWJWAZrzGyYWanCreYElkU5VjoTBt0DgJE859ukNGHAwULZlOdiYHESHfA==", "license": "MIT", "dependencies": { - "@netlify/dev-utils": "6.0.3", - "@netlify/otel": "^7.0.4", + "@netlify/dev-utils": "6.0.4", + "@netlify/otel": "^7.0.6", "@netlify/runtime-utils": "3.0.0" }, "engines": { @@ -43,9 +61,9 @@ } }, "node_modules/@netlify/dev-utils": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/@netlify/dev-utils/-/dev-utils-6.0.3.tgz", - "integrity": "sha512-p+M9a8mI0H0rRohY7Z4TkblvJMwsl5nfNKzmmhz1XBgSLBoDcgwf1TroHvM0TyK5sRiD8LViXe1wuJbzYlilUQ==", + "version": "6.0.4", + "resolved": "https://registry.npmjs.org/@netlify/dev-utils/-/dev-utils-6.0.4.tgz", + "integrity": "sha512-VZgq2gqRLQual8P2v6B8/W1WgUNYJvVvgqCIbviPR/BcI6hKvxVBdAMjz+84eU3qpfMau1Bn2J70JDSQSNkNgg==", "license": "MIT", "dependencies": { "@whatwg-node/server": "^0.11.0", @@ -65,16 +83,16 @@ } }, "node_modules/@netlify/otel": { - "version": "7.0.4", - "resolved": "https://registry.npmjs.org/@netlify/otel/-/otel-7.0.4.tgz", - "integrity": "sha512-HrGxXgauSZEzSd2mKu5YlqCvHpaNjQzf/yvwBdVXstZLRWWvbWIZBanrbXG0poyq70PBuiL+zVp3lU48aWnRNg==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/@netlify/otel/-/otel-7.0.6.tgz", + "integrity": "sha512-PUE0NwWiXU2xh64WNb2y5cFFjkn3CvMH5ReL1zL8M9cue3BmEpqpCb1VPdsnrMtZdatjqmGDND8ACmGdrR/THg==", "license": "MIT", "dependencies": { "@opentelemetry/api": "1.9.1", - "@opentelemetry/core": "2.10.0", - "@opentelemetry/instrumentation": "^0.221.0", - "@opentelemetry/resources": "2.10.0", - "@opentelemetry/sdk-trace-node": "2.10.0" + "@opentelemetry/core": "2.12.0", + "@opentelemetry/instrumentation": "^0.223.0", + "@opentelemetry/resources": "2.12.0", + "@opentelemetry/sdk-trace-node": "2.12.0" }, "engines": { "node": ">=22.12.0" @@ -99,9 +117,9 @@ } }, "node_modules/@opentelemetry/api-logs": { - "version": "0.221.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.221.0.tgz", - "integrity": "sha512-OlanaW1vv7ufTqQ3/fPLI4arGt5ZoM+P8abOMki6uEYnpRazepSWDwDnnw+la7kE26SHVC18//SMccrDvLKOXQ==", + "version": "0.223.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.223.0.tgz", + "integrity": "sha512-Oepm6etVPFCn0VWB1t833iOTgz1eYBDUPxcrOR/XvwzD1+Ag9VzSPSrrKAFNJ/haatj+8CXbG47pZXvdNQKDJw==", "license": "Apache-2.0", "dependencies": { "@opentelemetry/api": "^1.3.0" @@ -111,9 +129,9 @@ } }, "node_modules/@opentelemetry/context-async-hooks": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-2.10.0.tgz", - "integrity": "sha512-bvyMcgLEkozzSzpEEEo1OMoeQ97bxj6Qs2uN3mPrSdDvObMI1myffD/BPqcLlzZO9//d1SqQA/WPw7Cz2AiqhA==", + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-2.12.0.tgz", + "integrity": "sha512-iK/1nD7mmZVkuYjVjkdFBiCvzntJdFny1S3CYbUYyOq7V5enL6XX+gJ7eh965L1LnS11VA8mQ7Ej/ck04SB0MQ==", "license": "Apache-2.0", "engines": { "node": "^18.19.0 || >=20.6.0" @@ -123,9 +141,9 @@ } }, "node_modules/@opentelemetry/core": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.10.0.tgz", - "integrity": "sha512-/wNZ8twnEQQA4HoHu22+vcsdru6pWPWxW+7w+FlxT6Id7PE/WIbZmVKkte+PF72e0F2dnImFeHD2syyE1Mw6MQ==", + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.12.0.tgz", + "integrity": "sha512-1HsSAuvT4/my0QrXWsyXFdWjKaPeCHsismKZgEEIb8NK13LP6DrMRlsUbvD/0F9mDWK3xDom9AMv3IscxgOnOQ==", "license": "Apache-2.0", "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" @@ -138,12 +156,12 @@ } }, "node_modules/@opentelemetry/instrumentation": { - "version": "0.221.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.221.0.tgz", - "integrity": "sha512-cCk80Z/iRDf/5gfsKMB4f74LqVA5yKETB/9ojPzVW/6/f70iu89nJvGxsFCxx4XfSohaOofkU19kiYm84AiAlw==", + "version": "0.223.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.223.0.tgz", + "integrity": "sha512-tttBo88TbwK1zpsH6VeJoxLQopxOjW3cnrP50fsQJRZftkSKDDwjolXXBvow2jy0LKXlNRkDQh0NT6yI/q+BEQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "0.221.0", + "@opentelemetry/api-logs": "0.223.0", "import-in-the-middle": "^3.0.0", "require-in-the-middle": "^8.0.0" }, @@ -155,12 +173,12 @@ } }, "node_modules/@opentelemetry/resources": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.10.0.tgz", - "integrity": "sha512-q6MMm2zhggzsHVNbabYwut+a6nbuQQe3URUoxaojM/8K1IBfwwPzvxIjNi2/lI1TFe+fMHMW9MWhrtDLEXEnkA==", + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.12.0.tgz", + "integrity": "sha512-+rSRoOdln6NhXTVcBdHSlZxJDNzwxadeweK2ltZO3tVtfp6aklABc06xclDk6ovRR+EiGgIcSbh/6NgjFhnb3A==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.10.0", + "@opentelemetry/core": "2.12.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { @@ -171,13 +189,13 @@ } }, "node_modules/@opentelemetry/sdk-trace": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace/-/sdk-trace-2.10.0.tgz", - "integrity": "sha512-MfQGq3GRmTh5fM/y+OjaO0vj6+luCB1XO2gfXCalKCfgKw0eHL++sm75DNweC6ohlp+aFvACqeE0fYayqdRaoQ==", + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace/-/sdk-trace-2.12.0.tgz", + "integrity": "sha512-ImVuRQ6faOsTi1Wna88s2avgrrf/iDgXPigIeynkUhjstMuoQUDOJXgkez2j1mlU4btjXcXBGa+q7qKFYR3GsA==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.10.0", - "@opentelemetry/resources": "2.10.0", + "@opentelemetry/core": "2.12.0", + "@opentelemetry/resources": "2.12.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { @@ -188,14 +206,15 @@ } }, "node_modules/@opentelemetry/sdk-trace-base": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.10.0.tgz", - "integrity": "sha512-GuYQQT7QD2EeO8lcZLRQzcbOyhqAzL+6WWTKTU9mSUBYBazkEDl+VrQcXQhbB08OWM9anD1aHleVadzulpOaUQ==", + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.12.0.tgz", + "integrity": "sha512-JOERgZCxRM06FEJ5kEWxlSRChah6MmXDx3KwCruqEv/iEyLkTokCSemf2y1w8oIHtfrr8EVTpzebq/31vn2Cpg==", + "deprecated": "Use @opentelemetry/sdk-trace package", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.10.0", - "@opentelemetry/resources": "2.10.0", - "@opentelemetry/sdk-trace": "2.10.0", + "@opentelemetry/core": "2.12.0", + "@opentelemetry/resources": "2.12.0", + "@opentelemetry/sdk-trace": "2.12.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { @@ -206,14 +225,15 @@ } }, "node_modules/@opentelemetry/sdk-trace-node": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-node/-/sdk-trace-node-2.10.0.tgz", - "integrity": "sha512-GZK/G6oZyBLGlH1pUgeDch7D91KoHd2uotUGIkWCPi9GI5T9X0p4L7nNAMDR1BQjkRYoDqo+ddfVx9t5Uhys+Q==", + "version": "2.12.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-node/-/sdk-trace-node-2.12.0.tgz", + "integrity": "sha512-9DufH1IlmQMoKAfot5y/FhTP1RnmhLb5K6eKmJO/bvzPjYwPAazoiAUbTZFdPbqxOXN0FEbhZx/e6SB1Og4jmg==", + "deprecated": "Use @opentelemetry/sdk-trace package", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/context-async-hooks": "2.10.0", - "@opentelemetry/core": "2.10.0", - "@opentelemetry/sdk-trace-base": "2.10.0" + "@opentelemetry/context-async-hooks": "2.12.0", + "@opentelemetry/core": "2.12.0", + "@opentelemetry/sdk-trace-base": "2.12.0" }, "engines": { "node": "^18.19.0 || >=20.6.0" @@ -223,9 +243,9 @@ } }, "node_modules/@opentelemetry/semantic-conventions": { - "version": "1.43.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.43.0.tgz", - "integrity": "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==", + "version": "1.44.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.44.0.tgz", + "integrity": "sha512-E3JkOlMBi3N8OGGkbl7tFyqk2MAS6/lySRZBK3Mu7AzjF1fT8oIChH9ChE48SUWzDn9Kdwta+G/p5LJ4xW4CLQ==", "license": "Apache-2.0", "engines": { "node": ">=14" @@ -301,9 +321,9 @@ } }, "node_modules/ansis": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/ansis/-/ansis-4.4.0.tgz", - "integrity": "sha512-9k3v7xcHwgdO/DruxGIg4HtjvlAZlcnsX/mzqUb1t3NkYnl9kK2UJ+Gq0io+vQf7iT//BD/HB/NBkUR1LWxoeA==", + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/ansis/-/ansis-4.5.0.tgz", + "integrity": "sha512-KwIVkfFfJSSzBmZhDGuTmkhWqTdyB5oNVzzznBJbBZ5bZtHiqSrcugRF0RKJKT4Ss3d7ZrcjnlFVDlQNmtWfWw==", "license": "ISC", "engines": { "node": ">=14" @@ -423,13 +443,13 @@ "license": "MIT" }, "node_modules/import-in-the-middle": { - "version": "3.5.2", - "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-3.5.2.tgz", - "integrity": "sha512-WseIA/4o56+GYO3RmlOPvejYi771OFeJEeK/ejROsr9bdjW+E5NXTOD1Di8TL40Qgg3JJX9aa97Hf8iiSVIKZw==", + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-3.5.3.tgz", + "integrity": "sha512-usm/IiY63VtOyx/dm7uEoZV+EsanCDmwRUroQZIkFLGu1NVXZ8mZqIOhaN4QIJ7EsbMTuQbJXwCySCx+ozMA8g==", "license": "Apache-2.0", "dependencies": { "cjs-module-lexer": "^2.2.0", - "es-module-lexer": "^3.0.2", + "es-module-lexer": "^3.0.3", "module-details-from-path": "^1.0.4" }, "engines": { @@ -484,9 +504,9 @@ } }, "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -511,9 +531,9 @@ "license": "MIT" }, "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", "license": "0BSD" }, "node_modules/type-fest": { diff --git a/ask-service/package.json b/ask-service/package.json index cbf73cb..7a0efaf 100644 --- a/ask-service/package.json +++ b/ask-service/package.json @@ -1 +1 @@ -{ "name": "explainmyrepo-ask-service", "private": true, "type": "module", "dependencies": { "@netlify/blobs": "latest" } } +{ "name": "explainmyrepo-ask-service", "private": true, "type": "module", "dependencies": { "@claude-flow/aidefence": "^3.1.0", "@netlify/blobs": "^11.1.7" } } diff --git a/assets/design-system/design-system.css b/assets/design-system/design-system.css index ea5f8ac..200ae05 100644 --- a/assets/design-system/design-system.css +++ b/assets/design-system/design-system.css @@ -856,6 +856,8 @@ footer .fine { margin-top: var(--space-l); padding-top: var(--space-m); border-t .hero-grid { grid-template-columns: 1.05fr 0.95fr; gap: var(--space-2xl); align-items: start; } .hero-art { position: sticky; top: var(--space-l); align-self: start; } .dual { grid-template-columns: 1fr 1fr; } + /* two technical diagrams carry 12px labels only at full width: stack them, never share a half-width row */ + .dual.dual-diagrams { grid-template-columns: 1fr; } /* Paragraph-length sequential steps read best at 2 columns: ~60-char lines, 4 steps land as a clean 2x2 with no orphaned card, graceful for any count. (repeat(3,1fr) forced columns too narrow -> 1-2 words/line + orphaned 4th.) */ diff --git a/assets/diagrams/learning-loop.svg b/assets/diagrams/learning-loop.svg index c7908fd..79900d1 100644 --- a/assets/diagrams/learning-loop.svg +++ b/assets/diagrams/learning-loop.svg @@ -1,44 +1,26 @@ - - - - - - - - - - - the factory learns — every build makes the next one better - - - SHIPPEDPAGE - gate outcome11 axes × 2 devices, cost - reader gradetheir 1–100 + comments - ORACLE STOREmeasured truth only - distilledpatterns - THERECIPE - - - - - - - - - - - - - - the skill, the gate, and the tools carry the lessons — they fire on the next build even when nobody remembers ↻ - - - plus every honest failure: - refused builds survive as - artifacts, alerts carry the - grader's own words - promoted only when - backed by measured - outcomes - + + What each build leaves behind + Every hosted build records its measured outcome, and readers can add their own 1 to 100 grade. Both go to a local learning store. Lessons are then written into the skill, the gate and the tools so the next build starts from them. + + + what each build leaves behind + + a shipped page + its scorecard, cost, weakest axis and the form of each diagram are + recorded with the result + + + the reader's own grade + the delivery email links a 30-second 1-100 grade with comments; npm + run pull-ratings brings them into the store + + + the learning store + both verdicts land side by side in a local ruflo memory namespace, + and the admin page plots the trend + + + the recipe changes + when a failure teaches something, the skill, the gate or a tool is + changed so the fix fires on every later build diff --git a/assets/diagrams/pipeline.svg b/assets/diagrams/pipeline.svg deleted file mode 100644 index 430ff65..0000000 --- a/assets/diagrams/pipeline.svg +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - - - - the pipeline — each step has one job - - - - READ - COMPETE3 models - UNDER-STAND - CONCEIVE - AUTHOR - VISUALIZE - ASSEMBLE - GRADE - SHIP - - - - - - - - - - - - - - - clone the EXACTrepo; live-probeevery credential - concepts fight inTEXT for pennies;a judge picks one - real vector KBfrom the code - validate the wonconcept vs the KB - comprehensionladder copy - bespoke ANIMATEDSVGs + labeled art;every image teaches - render the pageexactly once - 2 viewports, 11 axes,6 operators, worstANIMATION frame - deploy RAIL: theverdict is law, thenverify HTTP 200 - - - - - below the bar? reopen ONLY the named weak slot ↻ - - - - every outcome + every reader grade feeds the learning store — the NEXT build starts smarter ↻ - diff --git a/assets/diagrams/quality-gate.svg b/assets/diagrams/quality-gate.svg index 320d77d..8500b02 100644 --- a/assets/diagrams/quality-gate.svg +++ b/assets/diagrams/quality-gate.svg @@ -1,56 +1,39 @@ - - - - - - - - - - - - - - the quality gate — it does not ship until independent eyes say yes - - - - - 390px - - - 1440px - real browser, full-page - screenshots — both devices - - - - - - independent vision critic - Gate A · substance - "do they actually get it?" — 6 axes - Gate B · craft (anti-slop) - typography, spacing, imagery — 5 axes - - - - - - six operator questions - believe I understand · approachable · - novice · architecture · makes me smile · - a zero-knowledge reader can follow it - mean ≥ 90 · min ≥ 85 · all six YES - - - - - SHIP - - - - one weak axis or one NO → name the exact weakness, reopen just that slot, re-render, re-grade - - can't honestly reach the bar? the build SAYS SO — it never ships slop and calls it done + + The quality gate advises + The assembled page is rendered at 390 pixels and 1440 pixels. Free checks for unexplained jargon and reading level run first. A vision critic then grades eleven axes and six operator questions. Pages that reach mean 90, minimum 85 and all six YES are exemplary. Pages at mean 82, minimum 70 and the five ship questions YES ship. A page below that still ships, with its weakest axis disclosed. Delivery is refused only for integrity failures. + + + the quality gate advises, it does not veto + + 1 · render for real + the assembled page in a real browser at 390px (phone) and 1440px + (desktop), full-page screenshots + + + 2 · free checks first + INV-20 unexplained jargon and INV-24 reads-at-fifteen are measured + with no model call. A failure is recorded and the vision pass is + skipped + + + 3 · the vision critic + grades section crops on 11 axes (A1-A6 substance, B1-B5 craft) and + six operator questions. A page near the line (mean 79-85) is graded + twice and the two samples merged + + + exemplary + mean 90+ · min axis 85+ · all six YES + + ships + mean 82+ · min axis 70+ · five ship questions YES · + both diagrams present + + below the bar + still ships, with its weakest axis named to the + requester + A weak axis reopens just that slot (at most 3 grading passes). Deploy + refuses only on integrity: an unassembled page, a different repo than + the one submitted, a page linking files it does not ship, or no + scorecard with no recorded reason. diff --git a/assets/diagrams/stations.svg b/assets/diagrams/stations.svg new file mode 100644 index 0000000..e5953bd --- /dev/null +++ b/assets/diagrams/stations.svg @@ -0,0 +1,131 @@ + + The one station table + The build is one ordered list of stations in four phases: set up, build and grade, ship, and follow-ups after delivery. Solid outline stations stop the build if they fail; dashed outline stations are advisory. Stations marked L run on the local door only. + + + one station table (src/stations.mjs) + + 1 · set up + clone the exact repo, build the KB + + + clone-repo + + + + kb:register + + + + build-kb + + + + concept-tournament + + + + 2 · build + grade + author, draw, assemble, pack, grade + + + primer + + + + index-primer + + + + concept + + + + content + + + + check-claims + + + + visual-brief + + + + generate-image + + + + make-favicon + + + + make-social-card + + + + make-diagrams + + + + assemble-page + + + + make-pack + + + + make-ask L + + + + quality-grade + + + + 3 · ship + deploy, then tell people + + + deploy + + + + publish-repo L + + + + repo-seo L + + + + readme-enhance L + + + + notify + + + + 4 · follow-ups + after delivery, never block it + + + make-overview L + + + + redeploy L + + + + republish L + + + solid: a failure stops the build + + dashed: advisory, the build carries on + L: local door only + diff --git a/assets/diagrams/three-doors.svg b/assets/diagrams/three-doors.svg deleted file mode 100644 index 0fa5e60..0000000 --- a/assets/diagrams/three-doors.svg +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - - - - - - ONE BRAIN — the explainmyrepo skill - all judgment lives here; improve it once, every door improves - - - - - - - - - - 01 · the website — PUBLIC repos - keys you need: ZERO - paste the URL, we build + host + email - you the link — nothing to install - explainmyrepo.isovision.ai - - - - 02 · npx — private repos, your keys - keys: ONE (OpenAI) inside Claude Code - the brain rides your Claude login; add a - Netlify token only for a live URL. Private - repo: gh auth login first. - npx explainmyrepo <github-url> - - - - 03 · Claude Code plugin - keys: ONE (OpenAI) - your session does the thinking; explain - any repo with a slash command - /explainmyrepo <github-url> - - pick your door with one question: is the repo public, and whose keys should do the work? - diff --git a/assets/diagrams/three-outputs.svg b/assets/diagrams/three-outputs.svg index f94eded..e505c72 100644 --- a/assets/diagrams/three-outputs.svg +++ b/assets/diagrams/three-outputs.svg @@ -1,38 +1,27 @@ - - - - - - - - one command in  →  three quality-gated artifacts out - - - - any GitHub repo - github.com/owner/name - - - - - - explainmyrepo - reads · designs · grades - - - - - - - - 1 · live explainer page - the link you share — real diagrams inside - - - 2 · a GitHub repo you own - you're a collaborator — it's yours to edit - - - 3 · downloadable AI knowledge pack - vector KB + search CLI + MCP server + + One GitHub URL in, three artifacts out + One GitHub repo URL goes into explainmyrepo. Out come a live explainer page and a downloadable AI knowledge pack from either door, plus a GitHub repo you own from the local door. + + + one GitHub URL in, three things out + + github.com/owner/name + + + explainmyrepo + + + 1 · a live explainer page + the link you share; real diagrams drawn from the code + both doors + + + 2 · an AI knowledge pack + a .zip: vector KB + search CLI + MCP server + both doors + + + 3 · a GitHub repo you own + you are invited as collaborator + local door only diff --git a/assets/diagrams/two-doors.svg b/assets/diagrams/two-doors.svg new file mode 100644 index 0000000..e0b1d6b --- /dev/null +++ b/assets/diagrams/two-doors.svg @@ -0,0 +1,37 @@ + + Two doors, one station table + The local door runs from your machine with npx explainmyrepo and your own keys, for any repo including private ones, and runs every station. The hosted door is the website: a GitHub Action runs a headless agent that follows SKILL.md for public repos with no keys. Both read the same station table, run the same tools and apply the same quality gate. + + + two doors, one station table + + src/stations.mjs + tools/*.mjs + + + local door + npx explainmyrepo <url> + · + your keys, any repo including private ones + · + src/orchestrator.mjs runs every local station in table order, + with src/brain.mjs authoring prompts + · + also does: GitHub explainer repo, the Ask box, video + + infographic after delivery, README outreach + + hosted door + explainmyrepo.isovision.ai + · + zero keys, public repos only + · + a GitHub Action starts bin/agentic-runner.mjs: clone, credential + probes, concept tournament, then a headless agent that follows + skills/explainmyrepo/SKILL.md + · + the runner then handles a bounded cure stage, the advisory claims + check and the delivery email + · + no GitHub repo is published and there is no Ask box yet + Same tools, same gate, same standards: tests fail when the two doors + drift apart. + diff --git a/bin/agentic-runner.mjs b/bin/agentic-runner.mjs index 2217e0b..3e4bc8f 100644 --- a/bin/agentic-runner.mjs +++ b/bin/agentic-runner.mjs @@ -1,36 +1,32 @@ #!/usr/bin/env node -// bin/agentic-runner.mjs — the AGENTIC hosted runner (replaces the deterministic orchestrator.mjs -// call for the hosted /build flow). Runs the real explainmyrepo SKILL as a headless Claude Code -// agent (`claude -p`) — the brain decides, tools/*.mjs do the mechanics (CONTRACT), instead of a -// fixed 19-station bash pipeline. See docs memory "hosted-agentic-architecture" (approved -// 2026-06-30) and ADR-033 (agent-harness-generator) for why: GitHub Actions is the right HOST for -// this triggered, autonomous class of task; what it invokes should be the agent, not a rigid script. +// bin/agentic-runner.mjs — the HOSTED door. Deterministic preflight (clone, live credential and +// embedding probes, concept tournament), then `claude -p` running skills/explainmyrepo/SKILL.md, then +// the cure stage, then notify. The decisions live in runner-lib.mjs / runner-preflight.mjs / cure.mjs +// (importable, unit-tested); this file is the wiring. // -// Usage: node bin/agentic-runner.mjs --build-dir [--budget-min N] [--budget-usd N] -// [--submitter ] [--run-url ] [--build-id ] +// Usage: node bin/agentic-runner.mjs --build-dir [--budget-min N] +// [--budget-usd N] [--submitter ] [--run-url ] [--build-id ] [--gist-id ] // -// Behavior: -// - Spawns `claude -p` headless, non-interactive (--permission-mode bypassPermissions, --bare to -// skip hooks/CLAUDE.md/plugin-sync — irrelevant/unsafe on a shared CI runner), with the -// explainmyrepo skill as the task brief and Bash/Read/Write/Edit/Glob/Grep as its only tools. -// - Streams --output-format stream-json so tool calls are visible AS THEY HAPPEN (real progress, -// not a fixed step counter) — printed to stderr and, if --build-id/--gist-id are set, patched to -// the status gist so the website's poll shows the agent's actual current action. -// - Enforces its OWN wall-clock (--budget-min) and $ (--budget-usd) ceilings, ending the run -// cleanly with an honest reason BEFORE the outer GH Actions job timeout would SIGKILL it — a -// clean stop can still report; a SIGKILL cannot. This is the dynamic-per-repo budget: the caller -// (landing/netlify/functions/build.js) sizes --budget-min from a cheap pre-flight repo check. -// - On ANY failure (non-zero exit, timeout, budget exceeded, or a completed run with no live URL -// in build.json), calls tools/alert-owner.mjs with full particulars — never fails silently. - -import { spawn, spawnSync } from 'node:child_process'; +// - The agent runs headless with --permission-mode bypassPermissions and --bare, tools limited to +// Bash/Read/Write/Edit/Glob/Grep, env limited to AGENT_ENV_ALLOWLIST, .env reads disallowed. +// - stream-json shows tool calls as they happen (status gist gets a human progress line). +// - The runner enforces its own wall-clock and $ ceilings so it can still report before the outer +// job is SIGKILLed. +// - Any failure (non-zero exit, budget kill, no verified live URL) alerts the owner AND the submitter. + +import { spawnSync } from 'node:child_process'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; -import { classifyEndState, buildCurePrompt, CURE } from './cure.mjs'; +import { runCureStage, createCostMeter, maxBudgetArgs, CURE } from './cure.mjs'; +import { probeCredentials, probeEmbedding } from './runner-preflight.mjs'; +import { NPX_LINE, mainAgentSpawn, cureAgentSpawn, spawnAndWait, startAgent, createStreamHandler, repoId, elapsedMinutes, agentWallMs, MIN_AGENT_WALL_MS, STATUS_RETRY_DELAYS_MS, + classifyFailure, agentReportOf, liveUrlOf, finalizeRun, disclosureOf, scorecardOf, buildAgentPrompt } from './runner-lib.mjs'; +import { recordClaims } from '../src/claims-record.mjs'; const HERE = path.dirname(fileURLToPath(import.meta.url)); const REPO_ROOT = path.resolve(HERE, '..'); +const startedAt = Date.now(); function parseArgs(argv) { const out = { _: [] }; @@ -45,9 +41,7 @@ function parseArgs(argv) { const args = parseArgs(process.argv.slice(2)); let repoUrl = args._[0]; if (!repoUrl) { console.error('usage: agentic-runner.mjs --build-dir [--budget-min N] [--budget-usd N]'); process.exit(2); } -// The workflow passes the bare "owner/name" form (build.js sends fullName, not a URL) — normalize -// to a full URL up front so the identity pin, build.json seed, and clone all see the same thing. -// (Learned live 2026-07-08: the first INV-21 preflight failed CLOSED on exactly this — safe, but wrong.) +// The workflow passes bare "owner/name": normalize to a full URL so the identity pin, build.json seed and clone agree. if (!/^[a-z]+:\/\//i.test(repoUrl) && !/github\.com/i.test(repoUrl)) repoUrl = `https://github.com/${repoUrl.replace(/^\/+/, '')}`; const buildDir = path.resolve(args['build-dir'] || path.join(REPO_ROOT, 'build', `hosted-${Date.now()}`)); @@ -56,70 +50,30 @@ const budgetUsd = Number(args['budget-usd'] || 8); const submitter = args.submitter || ''; const runUrl = args['run-url'] || ''; const buildId = args['build-id'] || ''; -// Executor model economics (owner directive 2026-07-13, "build-economics-text-first"): the -// premium creative judgment happens in the TEXT-MODE CONCEPT TOURNAMENT below (Fable/Sonnet/Sol -// compete on specs for cents; a cheap judge ranks them) — so the implementation agent runs on -// the low-cost tier. All-Fable implementation measured $7-9/page; tournament + Sonnet executor -// targets $2.50-4.00 at the same gate bar. Both IDs verified live via GET /v1/models 2026-07-13. +// The tournament (text-mode, cents) holds the premium creative judgment, so the implementation +// agent runs on the low-cost tier (build-economics-text-first). const model = args.model || 'claude-sonnet-5-5'; -// Which endpoint + billing lane runs the executor (`claude -p`). Default: first-party Anthropic. -// The credential preflight may FAIL THIS OVER to OpenRouter's Anthropic-compatible endpoint -// (their "Anthropic Skin" — same executor model, billed to the owner's OpenRouter credits) when -// the primary key is capacity-dead. MetaHarness ADR-167 router shape: reroute on a VERIFIED -// failure only; the grader + ship-bar rail are lane-independent, so quality is enforced the same -// either way. The Skin is only guaranteed for Anthropic first-party models — never point this -// lane at a non-Anthropic model (that experiment is a separate, deliberate lane via Moonshot). let executor = { lane: 'anthropic', model, baseUrl: null, key: null }; -// Defined up here (not beside classifyFailure) because the credential preflight's usage-limit -// message also needs it, and that block runs at module load — before the classifier section. -const NPX_LINE = 'Run it yourself with no wait and no budget limit: npx explainmyrepo in a VS Code / Claude Code session (or Codex) — it uses your own API key and takes about 15 minutes.'; fs.mkdirSync(buildDir, { recursive: true }); const buildJsonPath = path.join(buildDir, 'build.json'); -if (!fs.existsSync(buildJsonPath)) { - fs.writeFileSync(buildJsonPath, JSON.stringify({ repo: { url: repoUrl } }, null, 2) + '\n'); -} - -function log(msg) { process.stderr.write(`[agentic-runner] ${msg}\n`); } +if (!fs.existsSync(buildJsonPath)) fs.writeFileSync(buildJsonPath, JSON.stringify({ repo: { url: repoUrl } }, null, 2) + '\n'); -// Confirmed bug (tests/spawn-error-handling.test.mjs): none of this file's spawn() calls -// registered an .on('error', ...) listener — a missing/misconfigured binary (a bad `claude` -// PATH, a moved node executable) crashes the WHOLE process with a raw Node stack trace, -// contradicting this file's own "never fail silently" contract. Fire-and-forget notification -// spawns (alert-owner, notify, notify-failure) go through this: waits for close OR error, -// logs either way, never throws, never hangs. -function spawnAndWait(label, bin, args, opts) { - return new Promise((resolve) => { - const child = spawn(bin, args, opts); - let settled = false; - child.on('error', (e) => { if (settled) return; settled = true; log(`${label} FAILED TO START: ${e.message}`); resolve(-1); }); - child.on('close', (code) => { if (settled) return; settled = true; resolve(code); }); - }); -} +const log = (msg) => process.stderr.write(`[agentic-runner] ${msg}\n`); +const run = (label, bin, argv, opts) => spawnAndWait(label, bin, argv, opts, log); +const readBuild = () => JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')); +const repoSlug = repoUrl.replace(/^https?:\/\/github\.com\//, ''); -// Canonical "owner/name" identity for a GitHub URL — what the whole build is pinned to (INV-21). -function repoId(u) { - const m = String(u || '').trim().replace(/\/+$/, '').match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/i); - return m ? `${m[1]}/${m[2]}`.toLowerCase() : null; -} const submittedRepoId = repoId(repoUrl); if (!submittedRepoId) { console.error(`[agentic-runner] cannot parse owner/name from "${repoUrl}" — need a github.com/owner/name URL`); process.exit(2); } -// Status-gist patching lives ABOVE the preflight so access failures can reach the status page too. +// ── status gist (the submitter's progress page) ────────────────────────────────────────────────── const gistId = args['gist-id'] || ''; const ghToken = process.env.EXPLAINER_GH_TOKEN || process.env.GITHUB_TOKEN || ''; -// status: 'building' while in progress (the default); MUST be called with 'done'/'failed' at the -// end too — a real production run (2026-07-06, sindresorhus/p-map, budget-exceeded) proved this -// wasn't happening: the gist froze on the last in-progress step forever, so anyone watching the -// live status page (as opposed to the email alert, which DID fire correctly) saw no indication the -// build had actually finished, successfully or not. That is exactly the silent-failure mode this -// whole rebuild exists to close. -// Progress patches are throttled: one gist PATCH per tool call blew GitHub's secondary -// rate limit mid-build (2026-07-09, agentveil-sdk) — and the 403 landed on the one patch -// that mattered, `done`, leaving the submitter staring at "building" while their page was -// live. Progress is best-effort every ≥20s; terminal states retry through the limit. let lastProgressPatchAt = 0; +// 'building' patches are throttled (a patch per tool call hit GitHub's secondary rate limit); the +// terminal 'done'/'failed' patch must land, so it retries through the limit. Never throws. async function patchStatus(stepName, status = 'building', result = null, error = null, internalReason = null) { if (!gistId || !ghToken || !buildId) { if (status !== 'building') log(`patchStatus(${status}) SKIPPED — missing ${!gistId ? 'gistId' : !ghToken ? 'ghToken' : 'buildId'}`); @@ -129,23 +83,16 @@ async function patchStatus(stepName, status = 'building', result = null, error = if (Date.now() - lastProgressPatchAt < 20_000) return; lastProgressPatchAt = Date.now(); } - // Terminal states (done/failed) must land even if a secondary rate limit is active — - // GitHub's write-burst limits clear within a minute or two, so wait them out. - const delaysMs = status === 'building' ? [] : [30_000, 60_000, 120_000]; + const delaysMs = status === 'building' ? [] : STATUS_RETRY_DELAYS_MS; for (let attempt = 0; ; attempt++) { try { const resp = await fetch(`https://api.github.com/gists/${gistId}`, { method: 'PATCH', headers: { Authorization: `Bearer ${ghToken}`, Accept: 'application/vnd.github+json', 'Content-Type': 'application/json' }, - // internalReason is the real diagnostic (e.g. "Credit balance is too low") — it rides in - // the same gist for the admin dashboard to read, but app.js (the submitter's own status - // page) only ever displays `error`, never this, so nothing internal leaks publicly. - body: JSON.stringify({ files: { 'status.json': { content: JSON.stringify({ buildId, step: 0, totalSteps: 1, stepName, status, repo: repoUrl, result, error, internalReason }, null, 2) } } }), + // internalReason is for the admin dashboard; the submitter's page only shows `error`. + body: JSON.stringify({ files: { 'status.json': { content: JSON.stringify({ buildId, stepName, status, repo: repoUrl, result, error, internalReason }, null, 2) } } }), }); if (resp.ok) return; - // A silent swallow here is exactly the anti-pattern this whole rebuild exists to close — a - // gist-patch failure on the TERMINAL state is itself worth knowing about, even though it must - // never invert the real build outcome (hence: log loudly, but never throw). const body = await resp.text().catch(() => ''); if (status !== 'building') log(`patchStatus(${status}) attempt ${attempt + 1} FAILED: HTTP ${resp.status} ${body.slice(0, 200)}`); if (attempt >= delaysMs.length) return; @@ -157,16 +104,24 @@ async function patchStatus(stepName, status = 'building', result = null, error = } } -// ── SOURCE-IDENTITY GATE: Station 0–1 (validate + clone) runs HERE, pre-agent, deterministic ──── -// Incident 2026-07-08 (submitted mamd69/SONA-Trader, shipped Dar-41/Virtual-Trader-SONA-AI-): the -// agent, unable to clone a private-but-shared repo (the env allowlist strips GITHUB_TOKEN — -// correctly), treated the clone failure as an obstacle to work around, GitHub-searched a lookalike, -// edited repo.url in build.json, and shipped a stranger's repo to the submitter as theirs. Two -// structural conclusions, both enforced here: -// 1. The clone belongs in trusted deterministic code that MAY hold the token — never in the -// agent. Private repos shared with our account now work; the agent still never sees a token. -// 2. If the EXACT submitted repo cannot be cloned, the build ends before the agent exists, -// loudly, with an actionable message to the human. Nothing can "work around" it. +// A preflight failure ends the run before any cost: tell the status page, the OWNER and the SUBMITTER. +async function failBeforeBuild({ stepName, publicMessage, reason }) { + await patchStatus(stepName, 'failed', null, publicMessage); + await run('alert-owner', process.execPath, [ + path.join(REPO_ROOT, 'tools', 'alert-owner.mjs'), + '--repo', repoSlug, '--submitter', submitter || '(none)', '--build-id', buildId || '(none)', '--run-url', runUrl || '(none)', + '--reason', reason, '--elapsed-min', String(elapsedMinutes(startedAt)), + ], { cwd: REPO_ROOT, env: process.env, stdio: 'inherit' }); + if (submitter) { + await run('notify-failure', process.execPath, [path.join(REPO_ROOT, 'tools', 'notify-failure.mjs'), '--repo', repoSlug, '--to', submitter, '--message', publicMessage], + { cwd: REPO_ROOT, env: process.env, stdio: 'inherit' }); + } + process.exit(1); +} + +// ── SOURCE-IDENTITY GATE: validate + clone run HERE, before the agent exists (INV-21) ───────────── +// The clone needs the token, which the agent must never hold; and if the EXACT submitted repo cannot +// be cloned, the build ends loudly — nothing can "work around" it by substituting a lookalike. log(`preflight: cloning ${repoUrl} deterministically (pre-agent, token never enters the agent env)`); const cloneEnv = { ...process.env, EXPLAINER_SUBMITTED_REPO: submittedRepoId }; if (!cloneEnv.GITHUB_TOKEN && cloneEnv.EXPLAINER_GH_TOKEN) cloneEnv.GITHUB_TOKEN = cloneEnv.EXPLAINER_GH_TOKEN; @@ -177,331 +132,92 @@ try { cloneOut = JSON.parse((cloneRes.stdout || '').trim().split('\n').pop()); } if (cloneRes.status !== 0 || !cloneOut?.ok) { const why = cloneOut?.error || (cloneRes.stderr || '').trim().split('\n').pop() || `clone-repo exited ${cloneRes.status}`; log(`PREFLIGHT FAILED — ${why}`); - await patchStatus('Stopped before building: we could not access this repo.', 'failed', null, - `We couldn't access ${repoUrl}. If it's private, share it with our GitHub account or make it public, then rebuild. Nothing was built — we never build from a guess or a similar-looking repo.`); - await spawnAndWait('alert-owner', process.execPath, [ - path.join(REPO_ROOT, 'tools', 'alert-owner.mjs'), - '--repo', repoUrl.replace(/^https?:\/\/github\.com\//, ''), - '--submitter', submitter || '(none)', - '--build-id', buildId || '(none)', - '--run-url', runUrl || '(none)', - '--reason', `repo inaccessible at preflight: ${why}`, - '--elapsed-min', '0', - ], { cwd: REPO_ROOT, env: process.env, stdio: 'inherit' }); - process.exit(1); + await failBeforeBuild({ + stepName: 'Stopped before building: we could not access this repo.', + publicMessage: `We couldn't access ${repoUrl}. If it's private, share it with our GitHub account or make it public, then rebuild. Nothing was built — we never build from a guess or a similar-looking repo.`, + reason: `repo inaccessible at preflight: ${why}`, + }); } log(`preflight OK — cloned ${cloneOut.outputs?.repo?.owner}/${cloneOut.outputs?.repo?.name} (private=${cloneOut.outputs?.repo?.private})`); -// CREDENTIAL PREFLIGHT — live-verify every key this run will need BEFORE any expensive work. -// A rotated key discovered at agent turn 1 costs minutes; discovered at deploy (minute ~9) it -// costs the whole build; discovered here it costs three parallel HTTP probes (~2s total). -// Learned live 2026-07-13: a stale ANTHROPIC_API_KEY in the caller's shell env killed a local -// build on its first turn while a valid key sat unused in the repo .env — the runner trusted -// the env instead of proving it. Images note: generate-image.mjs self-loads GROK_AI_KEY from -// the repo .env as its own fallback, so Grok is probed through the same resolution order and -// a dead Grok key only WARNS (gpt-image fallback exists) — a dead OpenAI key FAILS (it also -// backs vision grading, which has no fallback). -// Every source that HAS a value, in priority order (process env first, then repo .env), -// deduped by value. The probe walks this list and the first LIVE key wins — learned live -// 2026-07-14: a dead key PRESENT in process env shadowed a proven-live .env key, so -// "first that exists" failed a build that "first that works" would have started. -function credCandidates(...names) { - const out = []; - for (const n of names) if (process.env[n]) out.push({ val: process.env[n], src: `process env ${n}` }); - try { - const txt = fs.readFileSync(path.join(REPO_ROOT, '.env'), 'utf8'); - for (const n of names) { - const m = txt.match(new RegExp(`^${n}=("?)(.*?)\\1\\s*$`, 'm')); - if (m?.[2] && !out.some((c) => c.val === m[2])) out.push({ val: m[2], src: `.env ${n}` }); - } - } catch { /* no .env in CI — env-only is the normal hosted case */ } - return out; -} -async function probeCred(label, candidates, url, headers) { - if (!candidates.length) return { label, ok: false, why: 'not set anywhere (process env or repo .env)' }; - const dead = []; - for (const cred of candidates) { - try { - const r = await fetch(url, { headers: headers(cred.val), signal: AbortSignal.timeout(5000) }); - if (r.ok) return { label, ok: true, val: cred.val, why: dead.length ? `OK via ${cred.src} — self-healed past: ${dead.join('; ')}` : `OK via ${cred.src}` }; - dead.push(`${cred.src} HTTP ${r.status}`); - } catch (e) { dead.push(`${cred.src} unreachable (${e.message})`); } - } - return { label, ok: false, why: `every source dead: ${dead.join('; ')}` }; -} +// ── CREDENTIAL + EMBEDDING PREFLIGHT: prove every key and the model source BEFORE any cost ───────── { - const bearer = (v) => ({ Authorization: `Bearer ${v}` }); - const [a, n, o, g] = await Promise.all([ - probeCred('ANTHROPIC_API_KEY (agent reasoning)', credCandidates('ANTHROPIC_API_KEY', 'CLAUDE_API_KEY'), 'https://api.anthropic.com/v1/models', (v) => ({ 'x-api-key': v, 'anthropic-version': '2023-06-01' })), - probeCred('NETLIFY_AUTH_TOKEN (deploy)', credCandidates('NETLIFY_AUTH_TOKEN'), 'https://api.netlify.com/api/v1/user', bearer), - probeCred('OPENAI_API_KEY (vision grading + image fallback)', credCandidates('OPENAI_API_KEY', 'OPEN_AI_KEY'), 'https://api.openai.com/v1/models', bearer), - probeCred('GROK_AI_KEY (primary image engine)', credCandidates('GROK_AI_KEY', 'GROK_API_KEY'), 'https://api.x.ai/v1/models', bearer), - ]); - // Authentication is NOT capacity (2026-07-19, run 29714490286: a monthly usage-limit 400 sailed - // straight through the /v1/models probe — a metadata endpoint that spends nothing — and killed - // the build one step later with a generic "snag" message). Prove the Anthropic key can actually - // SPEND with a 1-token completion on the same model the agent will use; classify the - // usage-limit case distinctly so the submitter hears the honest budget truth + reset date. - if (a.ok) { - try { - const r = await fetch('https://api.anthropic.com/v1/messages', { - method: 'POST', - headers: { 'x-api-key': a.val, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' }, - body: JSON.stringify({ model, max_tokens: 1, messages: [{ role: 'user', content: 'ping' }] }), - signal: AbortSignal.timeout(15_000), - }); - if (!r.ok) { - const body = await r.text().catch(() => ''); - if (/usage limits|regain access/i.test(body)) { - a.ok = false; - a.usageLimited = true; - a.why = `key authenticates but has hit its API usage limit (spend-probe HTTP ${r.status}): ${body.slice(0, 300)}`; - } else { - a.ok = false; - a.why = `key authenticates but a real 1-token completion on ${model} failed (HTTP ${r.status}): ${body.slice(0, 300)}`; - } - } - } catch (e) { log(`credential preflight: spend-probe inconclusive (${e.message}) — proceeding on the auth probe`); } - } - // EXECUTOR FAILOVER LANE (2026-07-19, after run 29714490286 turned a monthly cap into a - // pipeline-wide outage): usage-limited — and ONLY usage-limited — primary key + an OpenRouter - // key present → run the SAME executor model through OpenRouter's Anthropic Skin on the owner's - // OR credits. A dead/invalid key is a config bug the operator must see, never silently re-bill. - // The lane is spend-probed exactly like the primary: engage only on a PROVEN-live 1-token - // completion (which also validates the model slug + credits in one shot, loudly). - if (!a.ok && a.usageLimited) { - const orCands = credCandidates('OPENROUTER_API_KEY'); - const orModel = process.env.OPENROUTER_ANTHROPIC_MODEL || 'anthropic/claude-sonnet-5.5'; - for (const cand of orCands) { - try { - const r = await fetch('https://openrouter.ai/api/v1/messages', { - method: 'POST', - headers: { 'x-api-key': cand.val, Authorization: `Bearer ${cand.val}`, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' }, - body: JSON.stringify({ model: orModel, max_tokens: 1, messages: [{ role: 'user', content: 'ping' }] }), - signal: AbortSignal.timeout(20_000), - }); - if (r.ok) { - executor = { lane: 'openrouter', model: orModel, baseUrl: 'https://openrouter.ai/api', key: cand.val }; - a.ok = true; - a.why = `primary key usage-limited — FAILOVER ENGAGED: same executor model via OpenRouter's Anthropic Skin (${orModel}, ${cand.src}), billed to OpenRouter credits`; - break; - } - const body = await r.text().catch(() => ''); - log(`failover probe: OpenRouter Skin refused (${cand.src}, HTTP ${r.status}): ${body.slice(0, 200)}`); - } catch (e) { log(`failover probe: ${cand.src} unreachable (${e.message})`); } - } - if (executor.lane !== 'openrouter') log(orCands.length ? 'failover: no live OpenRouter lane — the honest usage-limit refusal stands' : 'failover: no OPENROUTER_API_KEY configured — the honest usage-limit refusal stands'); - } - // The spawned agent and every tool authenticate from process.env — hand each the PROVEN-LIVE - // value, OVERWRITING whatever was there (a dead value present is exactly the failure mode). - if (a.ok) process.env.ANTHROPIC_API_KEY = a.val; + let dotenvText = ''; + try { dotenvText = fs.readFileSync(path.join(REPO_ROOT, '.env'), 'utf8'); } catch { /* no .env in CI — env-only is the normal hosted case */ } + const { a, n, o, executor: lane } = await probeCredentials({ model, env: process.env, dotenvText, log }); + executor = lane; + // The agent and every tool authenticate from process.env: hand each the PROVEN-live value, overwriting a dead one. + if (a.ok && executor.lane === 'anthropic') process.env.ANTHROPIC_API_KEY = a.val; if (n.ok) process.env.NETLIFY_AUTH_TOKEN = n.val; if (o.ok) process.env.OPENAI_API_KEY = o.val; - if (g.ok) process.env.GROK_AI_KEY = g.val; - for (const r of [a, n, o, g]) log(`credential preflight: ${r.ok ? '✓' : '✗'} ${r.label} — ${r.why}`); - if (!g.ok) log('credential preflight: WARN — Grok unavailable, images will use the gpt-image fallback'); + for (const r of [a, n, o]) log(`credential preflight: ${r.ok ? '✓' : '✗'} ${r.label} — ${r.why}`); const fatal = [a, n, o].filter((r) => !r.ok); if (fatal.length) { const why = fatal.map((r) => `${r.label}: ${r.why}`).join('; '); log(`PREFLIGHT FAILED — dead/missing credentials, stopping before any cost is incurred: ${why}`); - const publicWhy = a.usageLimited - ? `We ran this build for free, and it's been genuinely popular — the community budget is used up for the moment (it resets monthly), not anything wrong with your repo. Nothing was built and nothing was charged. ${NPX_LINE}` - : 'A service credential this build needs is missing or expired. Nothing was built and nothing was charged. The operator has been alerted with specifics.'; - await patchStatus(a.usageLimited ? 'Stopped before building: the free community budget is used up for the moment.' : 'Stopped before building: a required service credential is invalid.', 'failed', null, publicWhy); - await spawnAndWait('alert-owner', process.execPath, [ - path.join(REPO_ROOT, 'tools', 'alert-owner.mjs'), - '--repo', repoUrl.replace(/^https?:\/\/github\.com\//, ''), - '--submitter', submitter || '(none)', - '--build-id', buildId || '(none)', - '--run-url', runUrl || '(none)', - '--reason', `credential preflight failed: ${why}`, - '--elapsed-min', '0', - ], { cwd: REPO_ROOT, env: process.env, stdio: 'inherit' }); - process.exit(1); - } - - // EMBEDDING SOURCE (2026-07-16 HF outage, build 79f135b3): station 1's KB build hard-requires - // a real embedding model (INV-06/07 — grounding is never fabricated). A cached model needs no - // network; otherwise huggingface.co must actually be up. Probe BOTH here, in seconds — the - // alternative was the agent discovering it 40 minutes in, on the clock and on the meter. - // The workflow warms kb/models-cache via actions/cache + kb/warm-model-cache.mjs, so the - // cached branch is the normal hosted case; this probe is the honest gate when it isn't. - const EMBED_MODEL_DIR = path.join(REPO_ROOT, 'kb', 'models-cache', 'Xenova', 'bge-small-en-v1.5'); - let embed; - if (fs.existsSync(path.join(EMBED_MODEL_DIR, 'onnx', 'model_quantized.onnx'))) { - embed = { ok: true, why: 'model cached locally — KB build needs no network' }; - } else { - // Source order mirrors kb/warm-model-cache.mjs: our own release asset first (github.com — - // the one origin an Actions runner can always reach; HF rate-limits runner IPs with 429, - // observed live 2026-07-17 run 29557533994), HF only as the last resort. - const probe = async (label, url) => { - try { - const r = await fetch(url, { method: 'HEAD', redirect: 'follow', signal: AbortSignal.timeout(8000) }); - return r.ok ? { ok: true, why: `no local cache; ${label} reachable (HTTP ${r.status}) — model will download once` } - : { ok: false, why: `${label} HTTP ${r.status}` }; - } catch (e) { return { ok: false, why: `${label} unreachable (${e.message})` }; } - }; - const rel = await probe('release asset (github.com)', 'https://github.com/stuinfla/Repo-Explainer/releases/download/kb-models-v1/bge-small-en-v1.5.tgz'); - if (rel.ok) embed = rel; - else { - const hf = await probe('huggingface.co', 'https://huggingface.co/Xenova/bge-small-en-v1.5/resolve/main/config.json'); - embed = hf.ok ? hf : { ok: false, why: `no local model cache and no reachable source: ${rel.why}; ${hf.why}` }; - } + await failBeforeBuild({ + stepName: a.usageLimited ? 'Stopped before building: the free community budget is used up for the moment.' : 'Stopped before building: a required service credential is invalid.', + publicMessage: a.usageLimited + ? `We ran this build for free, and it's been genuinely popular — the community budget is used up for the moment (it resets monthly), not anything wrong with your repo. Nothing was built and nothing was charged. ${NPX_LINE}` + : 'A service credential this build needs is missing or expired. Nothing was built and nothing was charged. The operator has been alerted with specifics.', + reason: `credential preflight failed: ${why}`, + }); } + const embed = await probeEmbedding({ cachedModelExists: fs.existsSync(path.join(REPO_ROOT, 'kb', 'models-cache', 'Xenova', 'bge-small-en-v1.5', 'onnx', 'model_quantized.onnx')) }); log(`embedding preflight: ${embed.ok ? '✓' : '✗'} ${embed.why}`); if (!embed.ok) { log(`PREFLIGHT FAILED — no embedding source, stopping before any cost is incurred: ${embed.why}`); - await patchStatus('Stopped before building: the knowledge-base embedding model is unavailable.', 'failed', null, - 'The embedding model this build grounds itself on has no local cache and its download source (huggingface.co) is unreachable — usually a temporary outage on their side. Nothing was built and nothing was charged. Please try again in a little while.'); - await spawnAndWait('alert-owner', process.execPath, [ - path.join(REPO_ROOT, 'tools', 'alert-owner.mjs'), - '--repo', repoUrl.replace(/^https?:\/\/github\.com\//, ''), - '--submitter', submitter || '(none)', - '--build-id', buildId || '(none)', - '--run-url', runUrl || '(none)', - '--reason', `embedding preflight failed in seconds (not 40 minutes): ${embed.why}. Fix: none needed if HF recovers on its own; the workflow's actions/cache + kb/warm-model-cache.mjs step keeps this from recurring once any run has downloaded the model.`, - '--elapsed-min', '0', - ], { cwd: REPO_ROOT, env: process.env, stdio: 'inherit' }); - process.exit(1); + await failBeforeBuild({ + stepName: 'Stopped before building: the knowledge-base embedding model is unavailable.', + publicMessage: 'The embedding model this build grounds itself on has no local cache and its download source (huggingface.co) is unreachable — usually a temporary outage on their side. Nothing was built and nothing was charged. Please try again in a little while.', + reason: `embedding preflight failed in seconds: ${embed.why}. The workflow's kb/warm-model-cache.mjs step seeds the cache first (sha256-pinned release asset, else Hugging Face), so reaching here means that seeding failed and Hugging Face is unreachable too; a later run recovers once either source is up.`, + }); } } -// THE CONCEPT TOURNAMENT (owner directive 2026-07-13): concepts compete as TEXT before any -// expensive work — three models spec, a cheap judge ranks, the winner seeds build.json.concept. -// Fail-open by design: a skipped/failed tournament logs loud and the agent invents the concept -// itself (the old path); it never blocks a build. Skipped entirely on resume (concept exists). -if (!JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')).concept) { +// ── CONCEPT TOURNAMENT: concepts compete as text before any expensive work. Fail-open: a skipped or +// failed tournament logs loud and the agent invents the concept; skipped on resume (concept exists). +if (!readBuild().concept) { log('concept tournament: starting (text-mode, pre-agent)'); const tRes = spawnSync(process.execPath, [path.join(REPO_ROOT, 'tools', 'concept-tournament.mjs'), buildDir], { cwd: REPO_ROOT, env: process.env, stdio: ['ignore', 'pipe', 'inherit'], timeout: 300_000 }); if (tRes.status === 0) { - const seeded = JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')).concept; + const seeded = readBuild().concept; log(seeded?.tournament ? `concept tournament: winner ${seeded.tournament.winnerModel}` : 'concept tournament: skipped (agent will invent the concept)'); - } else { - log(`concept tournament FAILED (exit ${tRes.status}) — proceeding, agent will invent the concept`); - } + } else log(`concept tournament FAILED (exit ${tRes.status}) — proceeding, agent will invent the concept`); } -const prompt = `Use the explainmyrepo skill (skills/explainmyrepo/SKILL.md is the brain — read it, follow it) to build a bespoke explainer for this repo: - -TOKEN ECONOMY: skills/explainmyrepo/TOOLS-CONTRACT.md is the complete toolbox reference (every tool's own header docs: usage, flags, gotchas). Read THAT instead of tool source files — open a tool's source ONLY if the contract is genuinely ambiguous about something you need. Re-deriving tool interfaces from source has measured at ~25% of build spend; it is waste. - - ${repoUrl} - -Build directory (already created, seeded with build.json): ${buildDir} -Station 0–1 (validate + clone) is ALREADY DONE by the harness: the repo is cloned, verified, and pinned at ${buildDir}/repo. Do NOT re-run clone-repo, and do NOT touch repo.url in build.json. - -THE SOURCE-IDENTITY LAW (INV-21 — overrides every other instruction in this brief, including the workaround license below): the repo named above IS this build's identity. If its clone is missing, broken, or anything else makes it unusable, STOP and report ok:false with the specific reason. NEVER search for, substitute, fetch, or reconstruct a different repo or its README — an explainer of the wrong repo is fabrication, the one unforgivable output. There is no workaround for source identity. -Ship mode: --ship-best-effort semantics — if you cannot reach the exemplar bar (mean>=90/min>=85/all six operators) after a reasonable refine attempt, ship the best HONEST version you have (the SHIP_OPERATORS bar: mean>=82, min>=70, real legible diagrams, comprehension operators YES) rather than nothing. The one thing you must NEVER ship broken is the mandatory architecture + flow diagrams (INV-18) — hold rather than ship if those didn't render as real vectors. -Do NOT publish a separate GitHub repo for this build (skip that station — no write-scoped GitHub token is provisioned in this hosted context, by design). -Do NOT run the notify station (station 9) — sending the submitter's email is handled OUTSIDE your process; you have no SMTP credentials and should not need them. Your job ends once quality-grade + deploy are done and build.json's publish.liveUrl is set. -The refine loop is capped at 3 total quality-grade calls (1 initial + 2 refines) and this is now ENFORCED by the tool itself, not just this instruction — a 4th call returns the prior scorecard unchanged at zero cost rather than re-grading. Do not try to work around it. At the cap, RUN DEPLOY AND YOU ARE DONE. -DELIVERY IS NO LONGER CONDITIONAL ON THE SCORE (ADR-0011, 2026-08-06). deploy.mjs refuses only on INTEGRITY — a page that did not assemble, a source-identity violation, or a missing scorecard. It does NOT refuse on a low grade. A below-bar page ships to its live URL and the requester gets an honest note naming the weakest axis and an offer to re-run. Before this change, 56 of 104 hosted builds delivered NOTHING at ~$5 each, because one weak axis could veto an otherwise-finished page — so the most valuable thing you can do at the cap is DELIVER, not agonise. -Two consequences for how you work. FIRST: there is no post-cap rescue dance any more. Do not write quality.postCapManualFix, do not end with ok:false hoping a runner re-grade saves you, and do not try to force a deploy — there is nothing left to force past. Run deploy, confirm publish.liveUrl is set, report ok:true. SECOND, and more important: because the score no longer gates delivery, you have NOTHING to gain by making the page look better to the grader than it is. The scorecard is now DISCLOSURE — it goes to the requester verbatim. Grade-chasing, flattering self-assessments, and cosmetic changes aimed at the rubric rather than the reader are now pure waste and actively dishonest. Spend your remaining effort on what genuinely helps a stranger understand this repo, and let the number land where it honestly lands. - -You have an approximate budget of ${budgetMin} minutes and $${budgetUsd}. Track your own elapsed time and cost as you work. This repo's actual size/complexity is unknown to me in advance — YOU are the one who discovers it by reading the repo, so budget your own effort accordingly: for a small repo, take your time and polish; for a large/deep monorepo, work faster and be willing to cap exhaustiveness (e.g. don't try to full-text-sweep every file in a 10,000-file repo — sample the important ones: READMEs, top-level docs, the most-referenced components) rather than trying to be exhaustive and running out of budget. - -CRITICAL — never fail silently (this is INV-04 in the skill, restated because it is the single most important rule for this run): if a tool fails, or a repo's structure breaks an assumption (e.g. the dependency graph comes back empty, or the repo is unusually deep/large), do NOT just crash. STOP, THINK about why, and try a reasonable workaround — always WITHIN the pinned repo; the SOURCE-IDENTITY LAW above is never workaroundable — (e.g. hand-write a minimal-but-honest architecture note if the automated extractor genuinely cannot produce one for this repo's structure) before giving up. If you truly cannot produce a working page, say EXACTLY why in plain language as your final message — a specific, honest reason a human could act on, never a bare stack trace or a vague "something went wrong." - -At the end, print your final status as the LAST line of your response in this exact form (nothing after it): -RESULT: {"ok": true, "liveUrl": ""} — on success -RESULT: {"ok": false, "reason": ""} — on failure`; - log(`starting: ${repoUrl} (budget ${budgetMin}min / $${budgetUsd}, build dir ${buildDir})`); -// SECURITY (flagged by automated review, confirmed real): the target repo is untrusted, internet- -// submitted input, and this agent runs with bypassed permission checks. It must NOT see credentials -// it has no legitimate need for — a malicious README/CONTEXT.md in a submitted repo is a realistic -// prompt-injection vector, and a leaked token would be exfiltratable via the agent's own Bash access. -// Build an explicit allowlist rather than forwarding process.env wholesale. Only what the TOOLS this -// agent is told to invoke actually need: OpenAI (images + vision grading) and Netlify (deploy, scoped -// to an isolated {repo}-explainer site per the approved architecture). ANTHROPIC_API_KEY is -// unavoidable — `claude -p` needs it to authenticate its own reasoning in a fresh CI runner with no -// existing OAuth session (the documented headless-auth path). Explicitly EXCLUDED: EXPLAINER_GH_TOKEN -// /GITHUB_TOKEN (gist-write + repo-publish scope — this runner patches the status gist itself, -// outside the agent, and publish-repo is disabled for hosted builds) and all SMTP/GMAIL creds -// (notify is handled post-agent below, not by the agent). -const AGENT_ENV_ALLOWLIST = ['PATH', 'HOME', 'LANG', 'TERM', 'TMPDIR', 'NODE_ENV', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'NETLIFY_AUTH_TOKEN']; -const agentEnv = {}; -for (const key of AGENT_ENV_ALLOWLIST) if (process.env[key] !== undefined) agentEnv[key] = process.env[key]; -// --executor-auth subscription (owner ask 2026-07-15, verified live: headless `claude -p` with no -// ANTHROPIC_API_KEY answers on the machine's logged-in Claude subscription session): for LOCAL, -// OWNER-INITIATED builds only, strip the API key from the agent env so the executor's reasoning — -// the $3-5 slice of every build — rides the subscription instead of metered billing. Hybrid by -// design: the concept tournament and every OpenAI/Netlify tool still use API keys (raw API calls -// have no subscription path). NEVER set this on CI/hosted builds — a fresh runner has no OAuth -// session (it would just fail), and third-party traffic on a consumer plan violates its terms. -if (args['executor-auth'] === 'subscription') { - delete agentEnv.ANTHROPIC_API_KEY; - log('executor-auth=subscription — agent reasoning rides the local Claude login; API keys stay with tournament/tools only'); -} -// Not a secret — the INV-21 identity pin. clone-repo.mjs and deploy.mjs refuse to run against any -// repo.url that doesn't match it, so even a misbehaving agent cannot swap the source mid-build. -agentEnv.EXPLAINER_SUBMITTED_REPO = submittedRepoId; -// EXECUTOR LANE WIRING: when the preflight engaged a failover lane, point the claude binary at -// it. Claude Code sends ANTHROPIC_AUTH_TOKEN as a Bearer and ANTHROPIC_API_KEY as x-api-key — -// set BOTH to the lane's key; the Anthropic-compatible endpoint takes what it needs. The cure -// agent inherits agentEnv, so a cure runs on the same lane as the build it cures. -if (executor.baseUrl) { - agentEnv.ANTHROPIC_BASE_URL = executor.baseUrl; - agentEnv.ANTHROPIC_API_KEY = executor.key; - agentEnv.ANTHROPIC_AUTH_TOKEN = executor.key; - log(`executor lane: ${executor.lane} (${executor.model}) via ${executor.baseUrl}`); -} +// --executor-auth subscription: LOCAL, owner-initiated builds only (a fresh CI runner has no OAuth +// session, and third-party traffic on a consumer plan violates its terms). +const subscription = args['executor-auth'] === 'subscription'; +if (subscription) log('executor-auth=subscription — agent reasoning rides the local Claude login; API keys stay with tournament/tools only'); +if (executor.baseUrl) log(`executor lane: ${executor.lane} (${executor.model}) via ${executor.baseUrl}`); const claudeBin = process.env.CLAUDE_BIN || 'claude'; -const child = spawn(claudeBin, [ - '-p', prompt, - '--permission-mode', 'bypassPermissions', - '--bare', - '--output-format', 'stream-json', - '--verbose', - '--model', executor.model, - '--allowed-tools', 'Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep', - // Defense in depth beyond the env allowlist above: observed live in testing (2026-07-04) that the - // agent will happily `cat .env` if it perceives a missing credential and try to work around it — - // harmless in that specific local test (no .env exists in the production checkout at all — fresh - // clone via actions/checkout, .env is gitignored/never committed) but there's no reason to leave - // the door open rather than close it explicitly. - '--disallowed-tools', 'Read(./.env)', 'Read(./.env.*)', 'Read(**/.env)', 'Read(**/.env.*)', -], { - cwd: REPO_ROOT, - env: agentEnv, - stdio: ['ignore', 'pipe', 'inherit'], -}); - -// A missing/misconfigured `claude` binary previously crashed this whole process with an -// unhandled 'error' throw and a raw Node stack trace — the exact "fail silently" this file's -// own header comment forbids. spawnErrorMsg feeds the `reason` classification below; 'close' -// never fires if spawn itself failed to start, so this also resolves exitCode instead of -// hanging the build forever. -let spawnErrorMsg = null; -child.on('error', (e) => { spawnErrorMsg = e.message; log(`claude spawn FAILED TO START: ${e.message}`); }); +if (!maxBudgetArgs(budgetUsd).length) log(`WARN — --budget-usd "${args['budget-usd']}" is not a positive number; the main run has NO dollar ceiling`); + +// Pre-agent work (clone, probes, tournament) is part of the budget: the agent gets what is left. +const agentMs = agentWallMs({ budgetMin, startedAt }); +if (!agentMs) { + await failBeforeBuild({ + stepName: 'Stopped before building: setup used the time budget.', + publicMessage: `Setup took longer than expected and left too little time to build this round — nothing was built. ${NPX_LINE}`, + reason: `pre-agent stages used ${elapsedMinutes(startedAt)} of the ${budgetMin}-minute budget; under ${MIN_AGENT_WALL_MS / 60_000} min left for the agent`, + }); +} +const agentBudgetMin = Math.max(1, Math.floor(agentMs / 60_000)); +const spawnCtx = { claudeBin, executor, procEnv: process.env, submittedRepoId, subscription, cwd: REPO_ROOT }; +const mainSpawn = mainAgentSpawn({ ...spawnCtx, prompt: buildAgentPrompt({ repoUrl, buildDir, budgetMin: agentBudgetMin, budgetUsd }), budgetUsd }); +const { child, state: agentState, exited } = startAgent(mainSpawn.bin, mainSpawn.argv, mainSpawn.opts, log); let killedForBudget = false; -let lastActivity = Date.now(); -let totalCostUsd = 0; -let finalResultText = ''; -let sawResultEvent = false; - -// Failure classification for the PUBLIC-facing message (owner mandate 2026-07-10: "don't just -// fail silently — tell them why, and if it's a budget thing, tell them exactly that and point -// to npx"). Distinct from `internalReason`, which carries the raw diagnostic for admin's eyes; -// this is the honest, friendly line the submitter themselves sees and gets emailed. -function classifyFailure(reason) { - const r = String(reason || ''); - if (/credit balance|insufficient.*balance|billing|usage limits|regain access/i.test(r)) { - return `We ran this build for free, and it's been genuinely popular — the community budget is tapped out for the moment, not anything wrong with your repo. ${NPX_LINE}`; - } - if (/exceeded its.*budget|wall-clock/i.test(r)) { - return `Your repo needed more time than we could give it for free this round — not a failure of the build itself. ${NPX_LINE}`; - } - return `It didn't complete this time — not necessarily your repo's fault, our free hosted builds do sometimes hit a snag. ${NPX_LINE}`; -} +const costMeter = createCostMeter(executor.model); +if (!costMeter.known) log(`WARN — no rate for ${executor.model}; the streamed $ backstop is off, only --max-budget-usd guards the ceiling`); -// The status gist is read by the submitter's browser — it gets a human progress line, never the -// raw tool call (a reader watching their build saw `node tools/generate-image.mjs … PID=$!` as -// the "step", 2026-07-09). The raw command still goes to the workflow log for debugging. +// The status gist is read by the submitter's browser: a human progress line, never the raw tool call +// (which still goes to the workflow log). function friendlyStep(name, input) { if (name === 'Bash') { const cmd = String(input?.command || ''); @@ -523,275 +239,69 @@ function friendlyStep(name, input) { return 'Thinking…'; } +const stopAgent = () => { child.kill('SIGTERM'); setTimeout(() => child.kill('SIGKILL'), 10_000); }; const hardTimer = setTimeout(() => { killedForBudget = true; - log(`WALL-CLOCK BUDGET EXCEEDED (${budgetMin} min) — stopping the agent cleanly rather than letting the outer job get SIGKILLed.`); - child.kill('SIGTERM'); - setTimeout(() => child.kill('SIGKILL'), 10_000); -}, budgetMin * 60_000); - -let buf = ''; -child.stdout.on('data', (chunk) => { - lastActivity = Date.now(); - buf += chunk.toString('utf8'); - const lines = buf.split('\n'); - buf = lines.pop(); - for (const line of lines) { - if (!line.trim()) continue; - let evt; - try { evt = JSON.parse(line); } catch { continue; } - if (evt.type === 'assistant' && Array.isArray(evt.message?.content)) { - for (const block of evt.message.content) { - if (block.type === 'tool_use') { - const summary = block.name === 'Bash' - ? String(block.input?.command || '').slice(0, 140) - : `${block.name} ${JSON.stringify(block.input || {}).slice(0, 100)}`; - log(`→ ${summary}`); - patchStatus(friendlyStep(block.name, block.input)); - } - } - } else if (evt.type === 'result') { - sawResultEvent = true; - totalCostUsd = evt.total_cost_usd || 0; - finalResultText = evt.result || ''; - log(`agent finished: is_error=${evt.is_error} cost=$${totalCostUsd.toFixed(2)} turns=${evt.num_turns}`); - // Two builds failed on 2026-07-09 with nothing but "exited 1" in the log — when the - // session itself errors, its own words are the diagnosis. Log them. - if (evt.is_error) log(`agent error result: ${String(evt.result || '(no result text)').slice(0, 600)}`); - } - } + log(`WALL-CLOCK BUDGET EXCEEDED (${budgetMin} min, ${elapsedMinutes(startedAt)} used) — stopping the agent cleanly rather than letting the outer job get SIGKILLed.`); + stopAgent(); +}, agentMs); + +const stream = createStreamHandler({ + costMeter, budgetUsd, stop: stopAgent, log, + onToolUse: (block) => { + log(`→ ${block.name === 'Bash' ? String(block.input?.command || '').slice(0, 140) : `${block.name} ${JSON.stringify(block.input || {}).slice(0, 100)}`}`); + patchStatus(friendlyStep(block.name, block.input)); + }, }); +child.stdout.on('data', (chunk) => stream.feed(chunk)); -const exitCode = await new Promise((resolve) => { - if (spawnErrorMsg) { resolve(-1); return; } - child.on('close', resolve); - child.on('error', () => resolve(-1)); // covers an 'error' that fires after this Promise is built -}); +const exitCode = await exited; clearTimeout(hardTimer); - -// ── Determine outcome ──────────────────────────────────────────────────────────────────────────── -const resultLineMatch = finalResultText.match(/RESULT:\s*(\{.*\})\s*$/s); -let agentReported = null; -if (resultLineMatch) { try { agentReported = JSON.parse(resultLineMatch[1]); } catch { /* fall through */ } } - -let liveUrl = agentReported?.ok ? agentReported.liveUrl : null; -if (!liveUrl) { - // Cross-check against build.json directly — the agent's own final-line report is a courtesy, - // not the source of truth (INV-05's "eyes agree" principle: verify, don't just trust the claim). - try { - const ctx = JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')); - if (ctx.publish?.liveUrl && ctx.publish?.http200) liveUrl = ctx.publish.liveUrl; - } catch { /* build.json may not exist on a very early failure */ } +const { killedForUsd, finalResultText, sawResultEvent } = stream.state; +let totalCostUsd = stream.state.totalCostUsd; +const spawnErrorMsg = agentState.spawnErrorMsg; +if (!sawResultEvent && costMeter.usd > totalCostUsd) { + totalCostUsd = costMeter.usd; // killed/crashed before the final `result` event — the streamed estimate is the best figure + log(`no result event — cost taken from the streamed usage estimate: ~$${totalCostUsd.toFixed(2)}`); } -// Source-identity re-verification at the exit boundary (INV-21, defense in depth vs a mid-build -// swap): the repo the build ENDED on must be the repo the human submitted, or nothing ships. -let identityViolation = null; -try { - const finalCtx = JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')); - const finalId = repoId(finalCtx?.repo?.url); - if (finalId !== submittedRepoId) identityViolation = `build ended on "${finalCtx?.repo?.url}" but was submitted for ${submittedRepoId}`; -} catch { /* unreadable build.json already fails the liveUrl check */ } - -// THE CURE STAGE (2026-07-19) — the systemic fix for the 07/15–07/17 failure streak: the -// pipeline was ONE-SHOT, so any unforeseen last-mile condition became a terminal user-visible -// failure even with a finished, floor-clearing page on disk. This generalizes the 2026-07-15 -// operator-grade block (which fired only on quality.postCapManualFix — a key nothing ever taught -// the agent to write, so it never fired in production): the runner now CLASSIFIES every unshipped -// ending deterministically (bin/cure.mjs, unit-tested against the three real incident shapes) and -// routes a NEAR-MISS — page already at/above the ship-floor mean, no slop axis, every blocker -// nameable — through ONE bounded cure cycle: a narrow cure agent fixes ONLY the named weaknesses -// (skipped when the main agent already fixed and documented via postCapManualFix), then ONE fresh -// grade, then tools/deploy.mjs — the ship-bar rail stays the ONLY judge. Genuine below-bar -// endings stay refused, honestly. Fires at most once per run; never on budget kills or crashes. -// ADR-0011: `liveUrl` is no longer a reason to skip this block. Delivery is now unconditional on -// quality, so a below-bar page arrives here ALREADY LIVE — and that is exactly the page the cure -// lane exists to improve. classifyEndState distinguishes the two cases ('near-miss' = not yet -// delivered, 'shipped-below-bar' = delivered and improvable); the redeploy is ratcheted so a live -// page can only ever be replaced by a measurably better one. -if (exitCode === 0 && !killedForBudget && !identityViolation) { - try { - const bc = JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')); - const endState = classifyEndState({ - exitCode, killedForBudget, identityViolation, spawnError: spawnErrorMsg, liveUrl, - siteExists: fs.existsSync(path.join(buildDir, 'site', 'index.html')), - quality: bc.quality, - }); - log(`cure stage: end-state classified as ${endState.cls}${endState.weaknesses ? ` (${endState.weaknesses.length} named weakness(es))` : ''}`); +// ── outcome: the agent's RESULT line is a courtesy; build.json is the truth ──────────────────────── +const agentReported = agentReportOf(finalResultText); +let finalCtx = null; +try { finalCtx = readBuild(); } catch { /* build.json may not exist on a very early failure */ } +let liveUrl = liveUrlOf(finalCtx); +const identityViolation = finalizeRun({ exitCode, spawnErrorMsg, liveUrl, finalCtx, submittedRepoId }).identityViolation; + +// ── THE CURE STAGE (bin/cure.mjs runCureStage): every unshipped or below-bar ending is classified +// deterministically. A near-miss gets ONE bounded cycle: a narrow cure agent fixes ONLY the named +// weaknesses, ONE fresh grade, then tools/deploy.mjs. A page already live is replaced only by a strictly +// better verdict. +const tool = (name) => spawnSync(process.execPath, [path.join(REPO_ROOT, 'tools', name), buildDir], + { cwd: REPO_ROOT, env: process.env, stdio: ['ignore', 'pipe', 'inherit'], timeout: name === 'deploy.mjs' ? CURE.DEPLOY_WALL_MS : CURE.GRADE_WALL_MS }); +const cure = await runCureStage({ buildDir, repoUrl, exitCode, killedForBudget, killedForUsd, identityViolation, spawnErrorMsg, liveUrl, totalCostUsd, budgetUsd }, { + readBuild, writeBuild: (o) => fs.writeFileSync(buildJsonPath, JSON.stringify(o, null, 2) + '\n'), + siteExists: () => fs.existsSync(path.join(buildDir, 'site', 'index.html')), + deploy: () => tool('deploy.mjs'), grade: () => tool('quality-grade.mjs'), + cureAgent: ({ prompt, remainingUsd }) => { const sp = cureAgentSpawn({ ...spawnCtx, prompt, remainingUsd }); return spawnSync(sp.bin, sp.argv, sp.opts); }, + patchStatus, log, +}); +liveUrl = cure.liveUrl; +totalCostUsd = cure.totalCostUsd; - if (endState.cure === 'redeploy') { - // Graded PASS but undeployed (deploy-side infra hiccup) — one plain retry through the rail. - log('cure stage: page already passed the gate but never deployed — retrying deploy once'); - const d = spawnSync(process.execPath, [path.join(REPO_ROOT, 'tools', 'deploy.mjs'), buildDir], - { cwd: REPO_ROOT, env: process.env, stdio: ['ignore', 'pipe', 'inherit'], timeout: CURE.DEPLOY_WALL_MS }); - const shipped = JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')); - if (d.status === 0 && shipped.publish?.liveUrl && shipped.publish?.http200) { - liveUrl = shipped.publish.liveUrl; - log(`cure stage: redeploy succeeded — ${liveUrl}`); - } else log(`cure stage: redeploy failed too (exit ${d.status}) — leaving run as failed`); - } else if ((endState.cure === 'fix-and-regrade' || endState.cure === 'improve-and-redeploy') && totalCostUsd < budgetUsd) { - await patchStatus('One fix from passing — running the automatic cure…'); - const q = bc.quality; - const savedNote = q.postCapManualFix || null; - // 2026-08-06: this used to read `let cureAgentOk = !!savedNote` — i.e. if the MAIN agent wrote a - // note claiming it had fixed the problem, the independent cure agent was SKIPPED and the runner - // spent its single verification grade on the agent's own self-diagnosis. On 2026-08-03 that - // self-diagnosis was wrong (it moved the flow diagram INTO the form family the big-idea diagram - // already occupied, re-tripping the very cap it was trying to clear) and no second actor existed - // to catch it. That is the one-shot failure mode the cure stage was built to eliminate, - // reappearing one level up: an agent could disarm its own reviewer by writing a claim to disk. - // The cure agent now ALWAYS runs; a documented note is CONTEXT for it, never a substitute for it. - let cureAgentOk = false; - if (savedNote) log('cure stage: main agent documented a post-cap fix — passing it to the cure agent as context, NOT accepting it in place of one'); - { - log(`cure stage: spawning the narrow cure agent (fix ONLY: ${endState.weaknesses.map((w) => `${w.device}/${w.name}`).join(', ')})`); - const curePrompt = buildCurePrompt({ repoUrl, buildDir, weaknesses: endState.weaknesses, quality: q }); - const c = spawnSync(claudeBin, [ - '-p', curePrompt, '--permission-mode', 'bypassPermissions', '--bare', - '--output-format', 'json', '--model', executor.model, - '--allowed-tools', 'Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep', - '--disallowed-tools', 'Read(./.env)', 'Read(./.env.*)', 'Read(**/.env)', 'Read(**/.env.*)', - ], { cwd: REPO_ROOT, env: agentEnv, encoding: 'utf8', timeout: CURE.AGENT_WALL_MS, maxBuffer: 32 * 1024 * 1024 }); - try { - const res = JSON.parse(String(c.stdout || '').trim().split('\n').pop()); - if (typeof res?.total_cost_usd === 'number') totalCostUsd += res.total_cost_usd; - log(`cure stage: cure agent exit ${c.status}, cost +$${(res?.total_cost_usd || 0).toFixed(2)}`); - } catch { log(`cure stage: cure agent exit ${c.status} (unparseable output — cost uncounted)`); } - cureAgentOk = c.status === 0; - if (!cureAgentOk) log('cure stage: cure agent failed — an unchanged page is not regraded (that would be dice-rolling, not verification)'); - } - if (cureAgentOk) { - const before = JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')); - before.quality.iterations = before.quality.iterations - 1; // authorize exactly ONE verification grade - fs.writeFileSync(buildJsonPath, JSON.stringify(before, null, 2) + '\n'); - const g = spawnSync(process.execPath, [path.join(REPO_ROOT, 'tools', 'quality-grade.mjs'), buildDir], - { cwd: REPO_ROOT, env: process.env, stdio: ['ignore', 'pipe', 'inherit'], timeout: CURE.GRADE_WALL_MS }); - const after = JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')); - if (savedNote) after.quality.postCapManualFix = savedNote; // quality-grade rewrites the slot; re-attach the record - after.quality.cure = { - authorizedBy: 'runner (deterministic near-miss classification, bin/cure.mjs)', - endState: endState.cls, weaknesses: endState.weaknesses.length, - cureAgentSpawned: true, mainAgentNote: Boolean(savedNote), gradeExit: g.status, - }; - fs.writeFileSync(buildJsonPath, JSON.stringify(after, null, 2) + '\n'); - if (g.status === 0) { - // THE RATCHET (ADR-0011 + 2026-08-06 adversarial review). When the page is ALREADY LIVE, - // a redeploy REPLACES something the customer already has at a URL they may already have - // shared. This project's own history records that the refine loop can regress, so an - // unconditional redeploy would let an automatic "cure" downgrade a delivered page. - // Therefore: measure, and only replace on a strictly better verdict. Delivery is a floor - // that is never given back — the cure may raise the page, never lower it. - const scoreOf = (qq) => { - const devs = Array.isArray(qq?.scorecard) ? qq.scorecard : []; - const axes = devs.flatMap((d2) => [...Object.values(d2.gateA || {}), ...Object.values(d2.gateB || {})]) - .filter((n) => typeof n === 'number'); - if (!axes.length) return null; - return { min: Math.min(...axes), mean: axes.reduce((a, b) => a + b, 0) / axes.length }; - }; - const wasLive = Boolean(liveUrl); - const pre = scoreOf(before.quality); - const post = scoreOf(after.quality); - const improved = !pre || !post - ? false - : (post.min > pre.min) || (post.min === pre.min && post.mean > pre.mean + 0.5); - if (wasLive && !improved) { - log(`cure stage: the cure did NOT improve the page (min ${pre?.min}→${post?.min}, mean ${pre?.mean?.toFixed(1)}→${post?.mean?.toFixed(1)}) ` - + `— KEEPING the already-delivered version. A live page is never replaced by a worse one.`); - } else { - log(`cure stage: fresh verification grade complete (passed=${after.quality?.passed}${pre && post ? `, min ${pre.min}→${post.min}, mean ${pre.mean.toFixed(1)}→${post.mean.toFixed(1)}` : ''}) — delivering`); - const d = spawnSync(process.execPath, [path.join(REPO_ROOT, 'tools', 'deploy.mjs'), buildDir], - { cwd: REPO_ROOT, env: process.env, stdio: ['ignore', 'pipe', 'inherit'], timeout: CURE.DEPLOY_WALL_MS }); - const shipped = JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')); - if (d.status === 0 && shipped.publish?.liveUrl && shipped.publish?.http200) { - liveUrl = shipped.publish.liveUrl; - log(`cure stage: ${wasLive ? 'IMPROVED AND REDEPLOYED' : 'CURED AND SHIPPED'} — ${liveUrl}`); - } else if (wasLive) { - log(`cure stage: redeploy of the improved page failed (exit ${d.status}) — the originally delivered page is still live and untouched`); - } else { - log(`cure stage: deploy failed after the cure (exit ${d.status}) — integrity refusal stands, honestly`); - } - } - } else { - log(`cure stage: verification grade errored (exit ${g.status}) — run outcome unchanged`); - } - } - } else if (endState.cure === 'fix-and-regrade' || endState.cure === 'improve-and-redeploy') { - log(`cure stage: near-miss but $ budget already spent ($${totalCostUsd.toFixed(2)} of $${budgetUsd}) — holding honestly instead of overspending`); - } - } catch (e) { log(`cure stage: skipped on error (${e?.message || e}) — run outcome unchanged`); } -} +// ADVISORY claims check on the page that is actually live: lands in build.json `claims`, never blocks. +if (exitCode === 0 && fs.existsSync(path.join(buildDir, 'site', 'index.html'))) recordClaims(buildDir, { root: REPO_ROOT, log }); -const budgetExceeded = killedForBudget; -const ok = exitCode === 0 && !budgetExceeded && !!liveUrl && !identityViolation; -const elapsedMin = ((Date.now() - (lastActivity - 0)) / 60000); // approx; refined below -const reason = identityViolation - ? `SOURCE-IDENTITY VIOLATION: ${identityViolation} — treating any deploy from this run as invalid` - : spawnErrorMsg - ? `could not start the claude binary: ${spawnErrorMsg}` - : budgetExceeded - ? `exceeded its ${budgetMin}-minute budget before finishing` - : agentReported && agentReported.ok === false ? agentReported.reason - : exitCode !== 0 ? `claude process exited ${exitCode}` - : !liveUrl ? 'agent finished but no verified live URL was found in build.json' - : 'unknown'; +try { finalCtx = readBuild(); } catch { finalCtx = null; } +const { ok, reason } = finalizeRun({ exitCode, killedForBudget, killedForUsd, spawnErrorMsg, agentReported, liveUrl, finalCtx, submittedRepoId, budgetMin, budgetUsd, totalCostUsd }); -// The status gist is each build's permanent public record, so the GRADES and the cost of -// production travel with the result — the admin dashboard trends them across builds (owner -// ask 2026-07-09: "grade every one 1-100 and tell yourself if you're getting better, worse, -// or the same"). Extraction is defensive: a missing scorecard never blocks the ship. -let scorecard = null; -// ADR-0011 D4 (2026-08-06) — TRACK BELOW-BAR DELIVERIES. Removing the gate's teeth without building -// the mechanism that replaces them is how a signal becomes decorative, and this repo has form: a -// keystone test shipped red for a week, and the session hook printed its own defect daily for eight -// days, both unread. So the disclosure that reaches the customer is also RECORDED here — which axis -// held the page back, and what visual FORM each diagram actually took (ADR-0012 D4). Those two -// together are what makes the INV-23 family taxonomy falsifiable: if the grader keeps calling two -// diagrams same-form while the resolver recorded them as distinct families, the taxonomy is wrong -// and the receipts will say so. Without this, that disagreement stays invisible forever. -let publishDisclosure = null; -let diagramForms = null; -try { - const ctxAll = JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')); - const pub = ctxAll.publish || {}; - publishDisclosure = { - belowBar: pub.belowBar === true, - graderUnavailable: pub.graderUnavailable === true, - weakest: pub.weakest || null, - }; - const v = ctxAll.visuals || {}; - diagramForms = Object.fromEntries(['architectureDiagram', 'flowDiagram', 'bigIdeaDiagram', 'insightDiagram'] - .filter((k) => v[k]).map((k) => [k, { form: v[k].form ?? null, variant: v[k].formVariant ?? null }])); -} catch { /* build.json unreadable — the liveUrl check already reflects that */ } +// The status gist is each build's permanent public record: grades and cost travel with the result. +// Which axis held a below-bar page back, and the FORM each diagram took, are recorded so the +// "same form" taxonomy stays falsifiable (ADR-0011 D4 / ADR-0012 D4). +const { publishDisclosure, diagramForms } = disclosureOf(finalCtx); +const scorecard = scorecardOf(finalCtx, executor.lane); -try { - const q = JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')).quality; - if (q && Array.isArray(q.scorecard) && q.scorecard.length) { - scorecard = { - passed: !!q.passed, - exemplary: !!q.exemplary, - belowBarDelivery: publishDisclosure, // ADR-0011 D4 - diagramForms, // ADR-0012 D4 - executor: executor.lane, // which billing/endpoint lane built this — admin attributes grades + cost per lane - - iterations: Number.isInteger(q.iterations) ? q.iterations : null, - gradedAt: q.gradedAt || null, - devices: q.scorecard.map((c) => ({ - device: c.deviceLabel || c.device || null, - headline: c.headlineScore ?? null, - gateA: c.gateA || null, - gateB: c.gateB || null, - operators: c.operatorQuestions || null, - })), - }; - } -} catch { /* build.json unreadable — already reflected in the liveUrl check */ } - -// ADR-174 oracle feed (2026-07-15): the memory distiller PROMOTES patterns only from -// execution-observed outcomes, judged by the `feedback` namespace — and no build ever wrote one, -// so all 282 distilled patterns sat proxy-tier (promoted: 0). Every completed build now records -// its MEASURED result (real vision-graded axes, verified deploy, cost) as a feedback entry. -// Best-effort by design: ruflo is a machine-global binary, absent on CI runners (which have no -// memory substrate anyway) — a miss must never touch the build outcome. +// Feed the memory distiller one MEASURED outcome per build (ADR-174 oracle tier). Best-effort: the +// ruflo binary is absent on CI runners, and telemetry never inverts a build outcome. try { const fb = { kind: 'explainer-build-outcome', repo: repoUrl, ok, reason: ok ? null : reason.slice(0, 400), @@ -802,63 +312,43 @@ try { }; const fbRes = spawnSync('ruflo', ['memory', 'store', '-k', `build-outcome-${buildId || Date.now()}`, '--value', JSON.stringify(fb), '--namespace', 'feedback'], { cwd: REPO_ROOT, timeout: 20_000, stdio: 'ignore' }); - if (fbRes.status === 0) log('build outcome recorded to feedback namespace (ADR-174 oracle tier — distiller promotes from these)'); + if (fbRes.status === 0) log('build outcome recorded to feedback namespace (ADR-174 oracle tier)'); } catch { /* telemetry never inverts a build outcome */ } if (ok) { console.log(`LIVE: ${liveUrl}`); log(`SUCCESS — ${liveUrl} (cost $${totalCostUsd.toFixed(2)})`); - await patchStatus('Done — your explainer is live.', 'done', - { liveUrl, scorecard, costUsd: Math.round(totalCostUsd * 100) / 100 }, null); - // Notify runs HERE, not inside the agent (see the env allowlist above) — this is plain - // deterministic code, not an LLM interpreting untrusted repo content, so it's the safe place to - // hold SMTP creds. Non-blocking: a notify failure must never flip a successful build to failed. - if (submitter) { - const notifyEnv = { ...process.env, EMAIL_TO: submitter }; - await spawnAndWait('notify', process.execPath, [path.join(REPO_ROOT, 'tools', 'notify.mjs'), buildDir], { cwd: REPO_ROOT, env: notifyEnv, stdio: 'inherit' }); - } + await patchStatus('Done — your explainer is live.', 'done', { liveUrl, scorecard, costUsd: Math.round(totalCostUsd * 100) / 100 }, null); + // Notify runs HERE, not in the agent: this is deterministic code, the safe place to hold SMTP creds. + // A notify failure must never flip a successful build to failed. + if (submitter) await run('notify', process.execPath, [path.join(REPO_ROOT, 'tools', 'notify.mjs'), buildDir], { cwd: REPO_ROOT, env: { ...process.env, EMAIL_TO: submitter }, stdio: 'inherit' }); process.exit(0); -} else { - log(`FAILED — ${reason}`); - const publicMessage = classifyFailure(reason); - await patchStatus('The build could not finish.', 'failed', null, publicMessage, reason); - // Gate-refusal alerts must carry the grader's ACTUAL complaints (learned 2026-07-15: - // autonomous-wealth-builder's alert said "B5 stayed at 56/58" but not WHY, so the operator - // couldn't judge whether it was worth curing without re-running the whole build). Append the - // rationale of every floor-failing axis + false operator questions from the final scorecard. - let gateDetail = ''; - try { - const q = JSON.parse(fs.readFileSync(buildJsonPath, 'utf8')).quality; - for (const dev of q?.scorecard || []) { - for (const [axis, score] of Object.entries({ ...dev.gateA, ...dev.gateB })) { - if (score < 70) gateDetail += `\n[${dev.device} ${axis}=${score}] ${String(dev.rationales?.[axis] || '').slice(0, 500)}`; - } - const falseOps = Object.entries(dev.operatorQuestions || {}).filter(([, v]) => !v).map(([k]) => k); - if (falseOps.length) gateDetail += `\n[${dev.device} operators false] ${falseOps.join(', ')}`; +} + +log(`FAILED — ${reason}`); +const publicMessage = classifyFailure(reason); +await patchStatus('The build could not finish.', 'failed', null, publicMessage, reason); +// The owner's alert carries the grader's ACTUAL complaints (every floor-failing axis + false operator +// question), so the operator can judge whether a cure is worth it without re-running the build. +let gateDetail = ''; +try { + for (const dev of finalCtx?.quality?.scorecard || []) { + for (const [axis, score] of Object.entries({ ...dev.gateA, ...dev.gateB })) { + if (score < 70) gateDetail += `\n[${dev.device} ${axis}=${score}] ${String(dev.rationales?.[axis] || '').slice(0, 500)}`; } - } catch { /* no scorecard — nothing to append */ } - const alertArgs = [ - path.join(REPO_ROOT, 'tools', 'alert-owner.mjs'), - '--repo', repoUrl.replace(/^https?:\/\/github\.com\//, ''), - '--submitter', submitter || '(none)', - '--build-id', buildId || '(none)', - '--run-url', runUrl || '(none)', - '--reason', gateDetail ? `${reason}\n\nGATE DETAIL (grader's own words):${gateDetail}` : reason, - '--elapsed-min', String(Math.round(budgetMin)), - ]; - await spawnAndWait('alert-owner', process.execPath, alertArgs, { cwd: REPO_ROOT, env: process.env, stdio: 'inherit' }); - // The submitter used to hear NOTHING on failure beyond a status page most people stop - // watching after 20 minutes — the exact "silent failure" the owner flagged 2026-07-10. - // Non-blocking, mirrors alert-owner's own tolerance: an email failure must never invert - // the real build outcome. - if (submitter) { - const failNotifyArgs = [ - path.join(REPO_ROOT, 'tools', 'notify-failure.mjs'), - '--repo', repoUrl.replace(/^https?:\/\/github\.com\//, ''), - '--to', submitter, - '--message', publicMessage, - ]; - await spawnAndWait('notify-failure', process.execPath, failNotifyArgs, { cwd: REPO_ROOT, env: process.env, stdio: 'inherit' }); + const falseOps = Object.entries(dev.operatorQuestions || {}).filter(([, v]) => !v).map(([k]) => k); + if (falseOps.length) gateDetail += `\n[${dev.device} operators false] ${falseOps.join(', ')}`; } - process.exit(1); +} catch { /* no scorecard — nothing to append */ } +await run('alert-owner', process.execPath, [ + path.join(REPO_ROOT, 'tools', 'alert-owner.mjs'), + '--repo', repoSlug, '--submitter', submitter || '(none)', '--build-id', buildId || '(none)', '--run-url', runUrl || '(none)', + '--reason', gateDetail ? `${reason}\n\nGATE DETAIL (grader's own words):${gateDetail}` : reason, + '--elapsed-min', String(elapsedMinutes(startedAt)), +], { cwd: REPO_ROOT, env: process.env, stdio: 'inherit' }); +// The submitter hears about a failure by email too; non-blocking, like the alert. +if (submitter) { + await run('notify-failure', process.execPath, [path.join(REPO_ROOT, 'tools', 'notify-failure.mjs'), '--repo', repoSlug, '--to', submitter, '--message', publicMessage], + { cwd: REPO_ROOT, env: process.env, stdio: 'inherit' }); } +process.exit(1); diff --git a/bin/cure.mjs b/bin/cure.mjs index 003e6a9..a8b8211 100644 --- a/bin/cure.mjs +++ b/bin/cure.mjs @@ -1,19 +1,15 @@ -// bin/cure.mjs — the recovery stage's brain: classify how a build ENDED, and when the ending is -// a near-miss, build the narrow prompt that cures it. +// bin/cure.mjs — the recovery stage's brain: classify how a hosted build ENDED and, for a near-miss, +// build the narrow prompt that cures it. History: docs/adr/0011-the-gate-advises-never-destroys.md. // -// WHY THIS EXISTS (2026-07-19, after three straight public failures 07/15–07/17): the pipeline -// was one-shot — no component owned recovery after the agent stopped, so ANY unforeseen last-mile -// condition became a terminal user-visible "failed", even with a finished floor-clearing page on -// disk. This module generalizes the 427ffbb operator-grade block from "fires only on a confession -// key the agent was never taught" to "fires on any deterministically-classified near-miss." -// -// TRUST STRUCTURE (non-negotiable, from the DEPLOY_FORCE incident): the agent may only DESCRIBE -// a fix; this classifier (deterministic, agent-untouchable) decides whether ONE verification -// grade is spent; the ship-bar rail in tools/deploy.mjs stays the ONLY judge of publishability. -// Nothing here bypasses, weakens, or pre-judges the rail. -// -// Pure module: no I/O, no env, fully unit-tested in tests/cure.test.mjs against fixtures shaped -// like the three real incidents (66HEX/frame, supertone-inc/supertonic, bissanmu/spring3). +// TRUST: the agent may only DESCRIBE a fix; this deterministic classifier decides whether ONE +// verification grade is spent; tools/deploy.mjs refuses only on integrity (ADR-0011), so the ratchet +// below (cureImproved/decideCureDeploy) is what keeps a worse page from replacing a live one. +// Pure except runCureStage (its effects are injected), the snapshot/restore pair and the cost meter. + +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { MODEL_RATES, priceUsd } from '../src/claude.mjs'; export const CURE = { // Near-miss envelope: every device already reads as a genuinely good page (mean at/above the @@ -23,7 +19,7 @@ export const CURE = { MIN_AXIS_FLOOR: 55, MAX_WEAKNESSES: 4, // Wall-clock bounds for the whole cure cycle — must fit the dispatch buffer (build.js - // budgetMin + 25) with margin, asserted by tests/cure.test.mjs. + // budgetMin + 25) with margin, asserted by tests/review-f3a-budget.test.mjs. AGENT_WALL_MS: 10 * 60_000, GRADE_WALL_MS: 7 * 60_000, DEPLOY_WALL_MS: 3 * 60_000, @@ -35,6 +31,7 @@ function deviceAxes(dev) { // Every item that blocks the SHIP gate, by name — the cure may touch these and NOTHING else. export function namedWeaknesses(quality) { + quality = quality || {}; const out = []; const saw = (deviceLabel, criterion) => (quality.refineNotes || []).find((n) => n.device === deviceLabel && String(n.criterion).includes(criterion))?.saw || null; @@ -54,47 +51,84 @@ export function namedWeaknesses(quality) { } // s: { exitCode, killedForBudget, identityViolation, spawnError, liveUrl, siteExists, quality } -// Returns { cls, cure, weaknesses? } — cure is false, 'redeploy', or 'fix-and-regrade'. +// Returns { cls, cure, weaknesses? } — cure is false, 'redeploy', 'fix-and-regrade' (held page) or +// 'improve-and-redeploy' (delivered page; the ratchet decides whether the improved one replaces it). export function classifyEndState(s) { if (s.identityViolation) return { cls: 'identity-violation', cure: false }; - // ADR-0011 (2026-08-06) — a live URL no longer means "done". Delivery is now unconditional on - // quality, so EVERY below-bar ending arrives here with liveUrl set. Short-circuiting on liveUrl - // therefore made the whole fix-and-regrade lane — the deterministic near-miss cure built - // 2026-07-19 as the systemic fix for the 07/15-07/17 streak, unit-tested against three real - // incidents — unreachable overnight. A near-miss that used to be repaired to ~90 for ~$1 would - // have shipped at 84 with an email offering the customer a full-cost manual rebuild: replacing an - // automatic repair that already exists, is already tested, and is already paid for. - // Caught in adversarial review the same day, before any customer build ran. - // - // The order is DELIVER, THEN IMPROVE. The page is already live and the customer already has it — - // that floor is never given back. The cure can only raise the page from there, and the runner - // redeploys ONLY on a strictly better verdict, so this can never downgrade what was delivered. + // Delivery is unconditional on quality (ADR-0011), so a live URL no longer means "done": a below-bar + // page is delivered first, then improved; the runner redeploys only on a strictly better verdict. if (s.liveUrl) { if (s.quality?.passed === true) return { cls: 'shipped', cure: false }; + // tools/deploy.mjs delivers a gate-refused page too (ADR-0011) — it must still reach the cure. + const refusalLive = gateRefusalWeakness(s); + if (refusalLive) return { cls: 'shipped-gate-refusal', cure: 'improve-and-redeploy', weaknesses: [refusalLive] }; const weaknesses = namedWeaknesses(s.quality); if (!weaknesses.length) return { cls: 'shipped', cure: false }; + // Only a NEAR-MISS is repaired: diffuse mediocrity or a slop axis gets the same honest "no cure" a held + // page gets, not a 10-minute cure agent plus a regrade the ratchet would almost always discard. + if (!isNearMiss(s.quality, weaknesses)) return { cls: 'shipped-below-bar', cure: false, weaknesses }; return { cls: 'shipped-below-bar', cure: 'improve-and-redeploy', weaknesses }; } if (s.killedForBudget) return { cls: 'budget-exhausted', cure: false }; if (s.spawnError || s.exitCode !== 0) return { cls: 'crash', cure: false }; const q = s.quality; - if (!s.siteExists || !q || !Array.isArray(q.scorecard) || q.scorecard.length === 0) { - return { cls: 'unbuilt', cure: false }; // env/preflight failures land here — nothing graded to verify - } + const refusal = gateRefusalWeakness(s); + if (refusal) return { cls: 'gate-refusal', cure: 'fix-and-regrade', weaknesses: [refusal] }; + const ungraded = !q || !Array.isArray(q.scorecard) || q.scorecard.length === 0; + // The page is built, the grader was recorded unavailable, nothing deployed: deploy accepts exactly + // this (quality.graderUnavailable, ADR-0011), so one plain redeploy ships it, disclosed as ungraded. + if (s.siteExists && ungraded && q?.graderUnavailable === true) return { cls: 'ungraded-undeployed', cure: 'redeploy' }; + if (!s.siteExists || ungraded) return { cls: 'unbuilt', cure: false }; // env/preflight failures: nothing graded to verify if (q.passed === true) return { cls: 'graded-pass-undeployed', cure: 'redeploy' }; const weaknesses = namedWeaknesses(q); - const inEnvelope = (q.scorecard || []).every((dev) => { + if (isNearMiss(q, weaknesses)) return { cls: 'near-miss', cure: 'fix-and-regrade', weaknesses }; + return { cls: 'below-bar', cure: false, weaknesses }; +} + +// A deterministic pre-check refusal (quality.gateRefusal — e.g. INV-20 acronyms, INV-24 reading +// level) leaves no scorecard because the vision pass never ran, but the page EXISTS and the +// blocker is named copy the cure agent can fix. Classing it 'unbuilt' threw that repair away. +function hasGateRefusal(q) { + return Boolean(q && typeof q.gateRefusal === 'string' && q.gateRefusal.trim()); +} +function gateRefusalWeakness(s) { + const q = s.quality; + if (!s.siteExists || !hasGateRefusal(q) || (Array.isArray(q.scorecard) && q.scorecard.length > 0)) return null; + const note = (q.refineNotes || []).map((n) => n?.note || n?.saw).filter(Boolean).join(' ') || null; + return { device: 'both', kind: 'gate-refusal', name: q.gateRefusal.trim(), saw: note }; +} + +function scoreOf(q) { + const axes = (Array.isArray(q?.scorecard) ? q.scorecard : []).flatMap(deviceAxes); + if (!axes.length) return null; + return { min: Math.min(...axes), mean: axes.reduce((a, b) => a + b, 0) / axes.length }; +} + +// May the cured page REPLACE a live one? Only on a strictly better measured result. A live page +// delivered on a pre-check refusal has no scores to beat; a cure that clears the pre-check AND carries +// a real vision grade is the better page. +export function cureImproved(preQ, postQ) { + const pre = scoreOf(preQ); + const post = scoreOf(postQ); + if (!post || hasGateRefusal(postQ)) return { improved: false, pre, post }; + if (!pre) return { improved: hasGateRefusal(preQ), pre, post }; + return { improved: post.min > pre.min || (post.min === pre.min && post.mean > pre.mean + 0.5), pre, post }; +} + +// THE RATCHET as one decision (ADR-0011): a page that is already live is replaced only by a strictly +// better measured one; a page that is not live is delivered whatever the fresh grade says. +export function decideCureDeploy({ wasLive, beforeQuality, afterQuality }) { + const { improved, pre, post } = cureImproved(beforeQuality, afterQuality); + return { deploy: !wasLive || improved, improved, pre, post }; +} + +function isNearMiss(q, weaknesses) { + return (q.scorecard || []).every((dev) => { const axes = deviceAxes(dev); if (!axes.length) return false; const mean = axes.reduce((a, b) => a + b, 0) / axes.length; return mean >= CURE.MEAN_FLOOR && Math.min(...axes) >= CURE.MIN_AXIS_FLOOR; }) && weaknesses.length >= 1 && weaknesses.length <= CURE.MAX_WEAKNESSES; - // An agent-documented post-cap fix is honored even outside the envelope (427ffbb behavior): - // there is something concrete and new to verify, which is the whole test. - if (inEnvelope || (q.postCapManualFix && Number.isInteger(q.iterations) && q.iterations >= 3)) { - return { cls: 'near-miss', cure: 'fix-and-regrade', weaknesses }; - } - return { cls: 'below-bar', cure: false, weaknesses }; } export function buildCurePrompt({ repoUrl, buildDir, weaknesses, quality }) { @@ -112,7 +146,7 @@ Rules — narrower than a normal build, and absolute: - If two diagrams share one visual form (an imagery-craft repetition cap), regenerate the offending figure(s) with node tools/make-diagrams.mjs ${buildDir} — the archetype dispatcher guarantees distinct forms per slot. - After any edit, re-run: node tools/assemble-page.mjs ${buildDir} - Do NOT run quality-grade (the runner spends the one verification grade itself, after you finish). -- Do NOT run deploy (the runner deploys through the ship-bar rail on the fresh verdict). +- Do NOT run deploy (the runner deploys the cured page only if the fresh verdict is strictly better). - Do NOT touch build.json's quality or repo slots, and never any file outside ${buildDir}. - Budget: roughly 8 minutes. If a weakness genuinely cannot be fixed (the repo lacks what it asks for), say so honestly instead of faking it. @@ -129,3 +163,213 @@ function meanLine(quality) { }); return per.join(', ') || 'unknown'; } + +// ── CURE SNAPSHOT ────────────────────────────────────────────────────────────────────────────── +// When the cure does NOT replace the live page, the build dir must describe the page that IS live +// (status gist and requester email read it). Snapshot before the cure agent edits; restore on any +// path that keeps the live page. +const SNAP_DIRS = ['site', 'assets']; + +export function snapshotForCure(buildDir) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cure-snap-')); + for (const d of SNAP_DIRS) { + const src = path.join(buildDir, d); + if (fs.existsSync(src)) fs.cpSync(src, path.join(dir, d), { recursive: true }); + } + fs.copyFileSync(path.join(buildDir, 'build.json'), path.join(dir, 'build.json')); + return dir; +} + +// Restores site/, assets/ and build.json exactly as they were, then records what the cure tried +// (cureRecord) on quality.cure so the attempt stays visible without its scores masquerading as live. +export function restoreCureSnapshot(buildDir, snapDir, cureRecord = null) { + for (const d of SNAP_DIRS) { + const dst = path.join(buildDir, d); + fs.rmSync(dst, { recursive: true, force: true }); + const src = path.join(snapDir, d); + if (fs.existsSync(src)) fs.cpSync(src, dst, { recursive: true }); + } + const ctx = JSON.parse(fs.readFileSync(path.join(snapDir, 'build.json'), 'utf8')); + if (cureRecord && ctx.quality && typeof ctx.quality === 'object') ctx.quality.cure = cureRecord; + fs.writeFileSync(path.join(buildDir, 'build.json'), JSON.stringify(ctx, null, 2) + '\n'); +} + +export function discardCureSnapshot(snapDir) { + if (snapDir) fs.rmSync(snapDir, { recursive: true, force: true }); +} + +// The build dir must be rolled back exactly when a page was live before the cure and the cured +// version did not replace it. +export function shouldRestoreAfterCure({ wasLive, redeployed }) { + return Boolean(wasLive) && !redeployed; +} + +// ── $ BUDGET ─────────────────────────────────────────────────────────────────────────────────── +// Primary stop: Claude Code's --max-budget-usd (final `result` subtype error_max_budget_usd). The +// streamed meter is the BACKSTOP: total_cost_usd only arrives on the final event. +export function maxBudgetArgs(usd) { + const n = Number(usd); + // Floor at one cent: the CLI rejects 0, and a sub-cent remainder must still be a ceiling. + return Number.isFinite(n) && n > 0 ? ['--max-budget-usd', String(Math.max(0.01, Math.round(n * 100) / 100))] : []; +} + +export const USD_BACKSTOP_FACTOR = 1.25; // fires only if the native cap failed to + +// The OpenRouter lane names the same model 'anthropic/claude-sonnet-5.5'. Rates: src/claude.mjs MODEL_RATES. +const modelId = (model) => String(model || '').replace(/^anthropic\//, '').replace(/\./g, '-'); +export function rateFor(model) { + return MODEL_RATES[modelId(model)] || null; +} + +// One API message can surface as several stream-json `assistant` events (one per content block), +// each carrying the SAME message.id and usage. Summing every event would double count, so cost is +// keyed by message.id and the largest figure seen for that id wins. Events with no id are summed +// (over-counting is the safe direction for a ceiling). Cache writes priced at 1.25x input and +// cache reads at 0.1x input (standard Anthropic prompt-caching multipliers). +export function createCostMeter(model) { + const id = modelId(model); + const rate = rateFor(model); + const byId = new Map(); + let anon = 0; + return { + known: Boolean(rate), + add(evt) { + if (!rate || evt?.type !== 'assistant') return; + const u = evt.message?.usage; + if (!u) return; + const usd = priceUsd(id, { in: u.input_tokens || 0, out: u.output_tokens || 0, cacheWrite: u.cache_creation_input_tokens || 0, cacheRead: u.cache_read_input_tokens || 0 }); + const msgId = evt.message?.id; + if (msgId) byId.set(msgId, Math.max(byId.get(msgId) || 0, usd)); + else anon += usd; + }, + get usd() { let t = anon; for (const v of byId.values()) t += v; return t; }, + }; +} + +export function overUsdBackstop(estimateUsd, budgetUsd) { + return Number(budgetUsd) > 0 && estimateUsd > budgetUsd * USD_BACKSTOP_FACTOR; +} + +export function isNativeBudgetStop(evt) { + return evt?.type === 'result' && evt.subtype === 'error_max_budget_usd'; +} + +// ── THE CURE STAGE ───────────────────────────────────────────────────────────────────────────── +// Did a deploy attempt put the new version in front of readers? tools/deploy.mjs can fail AFTER the zip +// reached Netlify (the share-card check records publish.shareCardError and exits non-zero), so the exit +// code alone would claim the old page is "still live and untouched". A success is exit 0 plus a verified +// record; the failure-after-landing signals are a new shareCardError or a deployId that changed. +export function deployLanded(status, beforePublish, afterPublish) { + const b = beforePublish || {}; + const a = afterPublish || {}; + if (status === 0 && a.liveUrl && a.http200) return { landed: true, verified: true, liveUrl: a.liveUrl }; + if (a.liveUrl && a.http200 && a.shareCardError && a.shareCardError !== b.shareCardError) { + return { landed: true, verified: false, liveUrl: a.liveUrl, why: `live but ${a.shareCardError}` }; + } + if (a.liveUrl && a.deployId && a.deployId !== b.deployId) { + return { landed: true, verified: false, liveUrl: a.http200 ? a.liveUrl : null, why: 'a new deploy reached Netlify but verification failed' }; + } + return { landed: false, verified: false, liveUrl: null }; +} + +// Runs the whole cure cycle for a run that exited cleanly. All effects come in through `deps`, so the +// ratchet, the budget guard and the restore-after-reject decisions are exercised by tests with stubs: +// readBuild() writeBuild(obj) siteExists() deploy()->{status} cureAgent({prompt, remainingUsd})->{status, stdout} +// grade()->{status}, patchStatus(msg), log(msg), snapshot{take,restore,discard} +// Returns { liveUrl, totalCostUsd, cureRedeployed, cureRecord, endState }. +export async function runCureStage(s, deps) { + const { readBuild, writeBuild, siteExists, deploy, cureAgent, grade, patchStatus = async () => {}, log = () => {}, + snapshot = { take: snapshotForCure, restore: restoreCureSnapshot, discard: discardCureSnapshot } } = deps; + const { buildDir, repoUrl, budgetUsd } = s; + let { liveUrl, totalCostUsd } = s; + const liveBeforeCure = liveUrl; + let cureSnapshot = null; + let cureRedeployed = false; + let cureRecord = null; + let endState = null; + const result = () => ({ liveUrl, totalCostUsd, cureRedeployed, cureRecord, endState }); + // A deploy attempt: run it, then judge from build.json whether it landed. + const attemptDeploy = () => { + const before = readBuild().publish; + const d = deploy(); + const landing = deployLanded(d.status, before, readBuild().publish); + return { d, landing }; + }; + + if (!(s.exitCode === 0 && !s.killedForBudget && !s.killedForUsd && !s.identityViolation)) return result(); + try { + const bc = readBuild(); + endState = classifyEndState({ + exitCode: s.exitCode, killedForBudget: s.killedForBudget, identityViolation: s.identityViolation, spawnError: s.spawnErrorMsg, liveUrl, + siteExists: siteExists(), quality: bc.quality, + }); + log(`cure stage: end-state classified as ${endState.cls}${endState.weaknesses ? ` (${endState.weaknesses.length} named weakness(es))` : ''}`); + + if (endState.cure === 'redeploy') { + log(`cure stage: ${endState.cls} — retrying deploy once`); + const { d, landing } = attemptDeploy(); + if (landing.landed && landing.liveUrl) { + liveUrl = landing.liveUrl; + log(`cure stage: redeploy ${landing.verified ? 'succeeded' : `landed but unverified (${landing.why})`} — ${liveUrl}`); + } else log(`cure stage: redeploy failed too (exit ${d.status}) — leaving run as failed`); + } else if ((endState.cure === 'fix-and-regrade' || endState.cure === 'improve-and-redeploy') && totalCostUsd < budgetUsd) { + await patchStatus('One fix from passing — running the automatic cure…'); + log(`cure stage: spawning the narrow cure agent (fix ONLY: ${endState.weaknesses.map((w) => `${w.device}/${w.name}`).join(', ')})`); + if (liveBeforeCure) cureSnapshot = snapshot.take(buildDir); + // The cure agent ALWAYS runs: an agent-written note can never stand in for the independent fixer. + const c = cureAgent({ prompt: buildCurePrompt({ repoUrl, buildDir, weaknesses: endState.weaknesses, quality: bc.quality }), remainingUsd: budgetUsd - totalCostUsd }); + try { + const res = JSON.parse(String(c.stdout || '').trim().split('\n').pop()); + if (typeof res?.total_cost_usd === 'number') totalCostUsd += res.total_cost_usd; + log(`cure stage: cure agent exit ${c.status}, cost +$${(res?.total_cost_usd || 0).toFixed(2)}`); + } catch { log(`cure stage: cure agent exit ${c.status} (unparseable output — cost uncounted)`); } + if (c.status !== 0) log('cure stage: cure agent failed — an unchanged page is not regraded (that would be dice-rolling, not verification)'); + else { + const before = readBuild(); + // authorize exactly ONE verification grade (never below 0: a gate-refusal cure arrives uncharged) + before.quality.iterations = Math.max(0, (Number.isInteger(before.quality.iterations) ? before.quality.iterations : 0) - 1); + writeBuild(before); + const g = grade(); + const after = readBuild(); + after.quality.cure = { + authorizedBy: 'runner (deterministic near-miss classification, bin/cure.mjs)', + endState: endState.cls, weaknesses: endState.weaknesses.length, cureAgentSpawned: true, gradeExit: g.status, + }; + cureRecord = after.quality.cure; + writeBuild(after); + if (g.status !== 0) log(`cure stage: verification grade errored (exit ${g.status}) — run outcome unchanged`); + else { + const wasLive = Boolean(liveUrl); + const { deploy: doDeploy, pre, post } = decideCureDeploy({ wasLive, beforeQuality: before.quality, afterQuality: after.quality }); + if (!doDeploy) { + log(`cure stage: the cure did NOT improve the page (min ${pre?.min}→${post?.min}, mean ${pre?.mean?.toFixed(1)}→${post?.mean?.toFixed(1)}) — KEEPING the already-delivered version. A live page is never replaced by a worse one.`); + } else { + log(`cure stage: fresh verification grade complete (passed=${after.quality?.passed}${pre && post ? `, min ${pre.min}→${post.min}, mean ${pre.mean.toFixed(1)}→${post.mean.toFixed(1)}` : ''}) — delivering`); + const { d, landing } = attemptDeploy(); + if (landing.landed) { + cureRedeployed = true; + if (landing.liveUrl) liveUrl = landing.liveUrl; + log(`cure stage: ${wasLive ? 'IMPROVED AND REDEPLOYED' : 'CURED AND SHIPPED'}${landing.verified ? '' : ` (deploy exit ${d.status}: ${landing.why} — the cured page IS what is served)`} — ${liveUrl}`); + } else if (wasLive) log(`cure stage: redeploy of the improved page failed (exit ${d.status}) — the originally delivered page is still live and untouched`); + else log(`cure stage: deploy failed after the cure (exit ${d.status}) — integrity refusal stands, honestly`); + } + } + } + } else if (endState.cure === 'fix-and-regrade' || endState.cure === 'improve-and-redeploy') { + log(`cure stage: near-miss but $ budget already spent ($${totalCostUsd.toFixed(2)} of $${budgetUsd}) — holding honestly instead of overspending`); + } + } catch (e) { log(`cure stage: skipped on error (${e?.message || e}) — run outcome unchanged`); } + + if (cureSnapshot) { + // The cure did not replace the live page: put back exactly what IS live, so the status gist and the + // requester email describe the deployed page, not the rejected repair. + if (shouldRestoreAfterCure({ wasLive: liveBeforeCure, redeployed: cureRedeployed })) { + try { + snapshot.restore(buildDir, cureSnapshot, cureRecord ? { ...cureRecord, outcome: 'not-deployed — build dir restored to the live version' } : null); + log('cure stage: restored site/, assets/ and build.json to the version that is actually live'); + } catch (e) { log(`cure stage: RESTORE FAILED (${e?.message || e}) — build.json/site may describe the rejected repair, not the live page`); } + } + snapshot.discard(cureSnapshot); + } + return result(); +} diff --git a/bin/explainmyrepo.mjs b/bin/explainmyrepo.mjs index 61928e1..ee4f3da 100755 --- a/bin/explainmyrepo.mjs +++ b/bin/explainmyrepo.mjs @@ -2,9 +2,7 @@ // bin/explainmyrepo.mjs — the `npx explainmyrepo ` entry point. // // Turns any GitHub repo into a bespoke, art-directed explainer site — for humans AND their AI — in -// one command. It runs the deterministic pipeline tools (tools/*.mjs, per tools/CONTRACT.md) in -// order and calls Claude in the loop to author the judgment slots (concept, content, the Station-4 -// image briefs + diagram ASCII, and the primer). See src/orchestrator.mjs for the station map. +// one command. The station order lives in src/stations.mjs; src/orchestrator.mjs runs it. // // Usage: npx explainmyrepo [flags] // Reads credentials from the environment / a gitignored .env (never printed): ANTHROPIC_API_KEY @@ -14,8 +12,8 @@ import { readFileSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { run } from '../src/orchestrator.mjs'; -import { loadEnv, getSecret } from '../src/env.mjs'; -import { claudeCliAvailable } from '../src/claude.mjs'; +import { loadEnv } from '../src/env.mjs'; +import { stationHelpText } from '../src/stations.mjs'; const HERE = path.dirname(fileURLToPath(import.meta.url)); function version() { @@ -34,7 +32,8 @@ ARGUMENTS OPTIONS --out build directory (default: ./explainer-builds/) - --model Anthropic model for the brain steps (default: claude-sonnet-5-5) + --model model for the brain steps (default: claude-sonnet-5-5; with only an OPENROUTER_API_KEY + and no Anthropic credential, the default is z-ai/glm-5.3 via OpenRouter) --no-deploy skip the deploy station (build + grade locally only) --no-publish skip publish-repo + repo-seo (no GitHub explainer repo) --no-notify skip the email notify station @@ -42,11 +41,6 @@ OPTIONS --no-quality skip the local vision quality gate (faster dry iterations) --no-refine grade once but don't auto-iterate the copy to lift weak axes --max-refine max content-refine passes when below the quality bar (default 2) - --ship-best-effort always deploy the best version (with an honest scorecard) instead of - holding when the world-class bar isn't reached — guarantees a URL. - Only truly broken pages (missing/broken diagrams) still hold. - --register-kb OPT-IN: if the repo isn't a kb.config target, inject a generated - entry into kb/kb.config.mjs (the one step that edits the shared registry) --from resume: start at this station id (needs an existing --out build) --to stop after this station id --only run just one station id @@ -54,17 +48,16 @@ OPTIONS -h, --help show this help -v, --version print version -STATIONS (ids for --from/--to/--only) - clone-repo · kb:register · build-kb · primer · concept · content · visual-brief · - generate-image · make-favicon · make-social-card · make-diagrams · assemble-page · - make-pack · quality-grade · deploy · publish-repo · repo-seo · readme-enhance · notify +STATIONS (ids for --from/--to/--only, in run order) +${stationHelpText('local')} WHAT YOU NEED (checked up-front — you'll be told exactly what's missing and what to do) - Brain ANTHROPIC_API_KEY in .env — OR just a logged-in Claude Code install: with no - key set, the judgment steps run on your Claude subscription automatically. + Brain ANTHROPIC_API_KEY in .env, OR OPENROUTER_API_KEY alone, OR just a logged-in Claude Code + install: with no key set, the judgment steps run on your Claude subscription automatically. + (On a terminal, anything missing is asked for and saved to .env; elsewhere the run stops and says what to set.) Visuals OPENAI_API_KEY|OPEN_AI_KEY — hero art + the vision quality gate. - Live URL NETLIFY_AUTH_TOKEN — optional: skip with --no-deploy and you still get the - complete page in your build folder. + Live URL NETLIFY_AUTH_TOKEN — needed to deploy; without it the run stops up front, or pass + --no-deploy and you still get the complete page in your build folder. GitHub nothing for public repos; PRIVATE repos need "gh auth login" first. (SMTP_USER/SMTP_PASS/EMAIL_TO — notify only, optional, failure is non-blocking.) @@ -92,7 +85,7 @@ EXAMPLES npx explainmyrepo owner/cool-lib --from concept --out ./explainer-builds/cool-lib `; -const BOOL_FLAGS = new Set(['--no-deploy', '--no-publish', '--no-notify', '--no-readme-pr', '--no-quality', '--no-refine', '--ship-best-effort', '--register-kb', '--dry-run', '-h', '--help', '-v', '--version']); +const BOOL_FLAGS = new Set(['--no-deploy', '--no-publish', '--no-notify', '--no-readme-pr', '--no-quality', '--no-refine', '--dry-run', '-h', '--help', '-v', '--version']); const VALUE_FLAGS = new Set(['--out', '--model', '--from', '--to', '--only', '--max-refine']); function parseArgs(argv) { @@ -169,7 +162,6 @@ async function main() { if (opts.help || positional.length === 0) { process.stdout.write(HELP); process.exit(opts.help ? 0 : 2); } const url = positional[0]; - preflight(opts); try { const res = await run(url, opts); process.exit(res.ok ? 0 : 1); @@ -179,42 +171,4 @@ async function main() { } } -// Up-front environment doctor (owner direction 2026-07-08: a missing key must never surface as a -// mid-build crash 20 minutes in — say what's missing, what it's for, and the easiest way out, in -// second zero). Mirrors the orchestrator's env resolution exactly (loadEnv = .env-over-ambient). -function preflight(opts) { - if (opts.dryRun || opts['dry-run']) return; // a dry run makes no API calls at all - const env = loadEnv(path.join(HERE, '..')); - const anthropic = getSecret(env, ['ANTHROPIC_API_KEY', 'CLAUDE_API_KEY']); - const openai = getSecret(env, ['OPENAI_API_KEY', 'OPEN_AI_KEY']); - const netlify = getSecret(env, ['NETLIFY_AUTH_TOKEN']); - const cli = anthropic ? false : claudeCliAvailable(); - const inClaudeCode = process.env.CLAUDECODE === '1'; - const noDeploy = Boolean(opts['no-deploy'] || opts.noDeploy); - - const rows = [ - ['Brain', anthropic ? 'ok — Anthropic API key' : cli ? 'ok — no API key, riding your Claude Code login' : 'MISSING'], - ['Visuals', openai ? 'ok — OpenAI key' : 'MISSING'], - ['Live URL', netlify ? 'ok — Netlify token' : noDeploy ? 'skipped (--no-deploy)' : 'MISSING'], - ]; - const fatal = []; - if (!anthropic && !cli) fatal.push('Brain: set ANTHROPIC_API_KEY (or CLAUDE_API_KEY) in .env — or install Claude Code and log in, and the brain runs on your Claude subscription with no key at all.'); - if (!openai) fatal.push('Visuals: set OPENAI_API_KEY in .env (hero art + the vision quality gate need it).'); - if (!netlify && !noDeploy) fatal.push('Live URL: set NETLIFY_AUTH_TOKEN in .env — or re-run with --no-deploy to build the complete page locally with no Netlify account.'); - - if (!fatal.length) { - process.stderr.write(`preflight: ${rows.map(([k, v]) => `${k.toLowerCase()} ${v.split(' — ')[0]}`).join(' · ')}\n`); - return; - } - process.stderr.write('\nBefore this can run, a quick environment check:\n\n'); - for (const [k, v] of rows) process.stderr.write(` ${v.startsWith('MISSING') ? '✗' : '✓'} ${k.padEnd(9)} ${v}\n`); - process.stderr.write('\nWhat to do:\n'); - for (const f of fatal) process.stderr.write(` • ${f}\n`); - if (!inClaudeCode) { - process.stderr.write('\nRECOMMENDED: run this inside a VS Code / Claude Code session, in a project whose .env\nalready holds these keys — they are picked up automatically, nothing to re-export.\n'); - } - process.stderr.write('\nPUBLIC repo and no keys at hand? The zero-setup path is the website:\n https://explainmyrepo.isovision.ai\n\n'); - process.exit(2); -} - main(); diff --git a/bin/runner-lib.mjs b/bin/runner-lib.mjs new file mode 100644 index 0000000..ce1ac0c --- /dev/null +++ b/bin/runner-lib.mjs @@ -0,0 +1,250 @@ +// bin/runner-lib.mjs — the hosted runner's decisions as plain exported functions, so tests run the +// real code instead of grepping bin/agentic-runner.mjs (a top-level script that cannot be imported). + +import { spawn } from 'node:child_process'; +import { MAX_QUALITY_ITERATIONS } from '../tools/quality-grade.mjs'; +import { overUsdBackstop, isNativeBudgetStop, maxBudgetArgs, CURE } from './cure.mjs'; + +export const NPX_LINE = 'Run it yourself with no wait and no budget limit: npx explainmyrepo in a VS Code / Claude Code session (or Codex) — it uses your own API key and takes about 15 minutes.'; + +// The repo-controlled agent sees ONLY these. No GitHub token (gist-write / repo-publish scope) and no +// SMTP credential is ever forwarded: a hostile README is a realistic prompt-injection vector and the +// agent has Bash. ANTHROPIC_API_KEY is needed by `claude -p` itself; OPENAI + NETLIFY by the tools. +export const AGENT_ENV_ALLOWLIST = ['PATH', 'HOME', 'LANG', 'TERM', 'TMPDIR', 'NODE_ENV', 'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'NETLIFY_AUTH_TOKEN']; + +// Files the agent may never read, even though its env is already scrubbed. +export const AGENT_DISALLOWED_TOOLS = ['Read(./.env)', 'Read(./.env.*)', 'Read(**/.env)', 'Read(**/.env.*)']; +export const AGENT_ALLOWED_TOOLS = ['Bash', 'Read', 'Write', 'Edit', 'Glob', 'Grep']; + +// The agent's environment: the allowlist, the INV-21 identity pin (not a secret), and — when the +// preflight engaged the OpenRouter lane — that lane's endpoint and key. `subscription` (local, +// owner-initiated builds only) strips the API key so reasoning rides the local Claude login. +// CI=1 is set on purpose: the local-door-only tools (make-trailer, make-social-loop, make-overview) +// refuse to run when CI is set (ADR-0009 INV-31), and the allowlist would otherwise hide it from them. +export function buildAgentEnv(procEnv, { submittedRepoId, executor, subscription = false }) { + const env = {}; + for (const key of AGENT_ENV_ALLOWLIST) if (procEnv[key] !== undefined) env[key] = procEnv[key]; + if (subscription) delete env.ANTHROPIC_API_KEY; + env.CI = '1'; + env.EXPLAINER_SUBMITTED_REPO = submittedRepoId; + if (executor?.baseUrl) { + env.ANTHROPIC_BASE_URL = executor.baseUrl; + env.ANTHROPIC_API_KEY = executor.key; + env.ANTHROPIC_AUTH_TOKEN = executor.key; + } + return env; +} + +// Fire-and-forget spawns (alert, notify) must never crash the runner or hang it: a missing binary +// emits 'error' and never 'close'. Resolves the exit code, or -1 if the process could not start. +export function spawnAndWait(label, bin, args, opts, log = () => {}) { + return new Promise((resolve) => { + const child = spawn(bin, args, opts); + let settled = false; + child.on('error', (e) => { if (settled) return; settled = true; log(`${label} FAILED TO START: ${e.message}`); resolve(-1); }); + child.on('close', (code) => { if (settled) return; settled = true; resolve(code); }); + }); +} + +// Starts the main agent. A missing/misconfigured binary emits 'error' and never 'close': record it +// in state.spawnErrorMsg and resolve `exited` with -1, or the build would hang (or crash with a raw +// stack trace). The listener is registered synchronously, before any event can fire. +export function startAgent(bin, argv, opts, log = () => {}) { + const state = { spawnErrorMsg: null }; + const child = spawn(bin, argv, opts); + const exited = new Promise((resolve) => { + child.on('error', (e) => { state.spawnErrorMsg = e.message; log(`claude spawn FAILED TO START: ${e.message}`); resolve(-1); }); + child.on('close', resolve); + }); + return { child, state, exited }; +} + +// Folds the agent's stream-json lines into run state and enforces the $ backstop. The native +// --max-budget-usd stop is the primary guard; total_cost_usd only arrives on the final `result` +// event, so the streamed meter is what can stop an agent that ignores the native cap. +export function createStreamHandler({ costMeter, budgetUsd, stop = () => {}, onToolUse = () => {}, log = () => {} }) { + const state = { killedForUsd: null, totalCostUsd: 0, finalResultText: '', sawResultEvent: false }; + let buf = ''; + function handleLine(line) { + let evt; + try { evt = JSON.parse(line); } catch { return; } + costMeter.add(evt); + if (!state.killedForUsd && overUsdBackstop(costMeter.usd, budgetUsd)) { + state.killedForUsd = 'backstop'; + log(`DOLLAR BUDGET EXCEEDED — streamed usage estimates $${costMeter.usd.toFixed(2)} against a $${budgetUsd} ceiling and the native cap did not stop the agent; stopping it now.`); + stop(); + } + if (evt.type === 'assistant' && Array.isArray(evt.message?.content)) { + for (const block of evt.message.content) if (block.type === 'tool_use') onToolUse(block); + } else if (evt.type === 'result') { + state.sawResultEvent = true; + state.totalCostUsd = evt.total_cost_usd || 0; + state.finalResultText = evt.result || ''; + if (isNativeBudgetStop(evt)) { + state.killedForUsd = state.killedForUsd || 'native'; + log(`DOLLAR BUDGET EXCEEDED — Claude Code stopped the agent at $${state.totalCostUsd.toFixed(2)} (ceiling $${budgetUsd}).`); + } + log(`agent finished: is_error=${evt.is_error} cost=$${state.totalCostUsd.toFixed(2)} turns=${evt.num_turns}`); + if (evt.is_error) log(`agent error result: ${String(evt.result || '(no result text)').slice(0, 600)}`); + } + } + return { + state, + feed(chunk) { + buf += chunk.toString('utf8'); + const lines = buf.split('\n'); + buf = lines.pop(); + for (const line of lines) if (line.trim()) handleLine(line); + }, + }; +} + +// Canonical lowercase "owner/name" for a GitHub URL — the identity the whole build is pinned to (INV-21). +export function repoId(u) { + const m = String(u || '').trim().replace(/\/+$/, '').match(/github\.com[/:]([^/]+)\/([^/]+?)(?:\.git)?$/i); + return m ? `${m[1]}/${m[2]}`.toLowerCase() : null; +} + +export const elapsedMinutes = (startMs, nowMs = Date.now()) => Math.max(0, Math.round((nowMs - startMs) / 60_000)); + +// The honest, friendly line the SUBMITTER sees; the raw reason goes to the admin only. +export function classifyFailure(reason) { + const r = String(reason || ''); + if (/credit balance|insufficient.*balance|billing|usage limits|regain access/i.test(r)) { + return `We ran this build for free, and it's been genuinely popular — the community budget is tapped out for the moment, not anything wrong with your repo. ${NPX_LINE}`; + } + if (/dollar budget/i.test(r)) return `Your repo needed more work than our free per-build budget covers this round — not a failure of the build itself. ${NPX_LINE}`; + if (/exceeded its.*budget|wall-clock/i.test(r)) return `Your repo needed more time than we could give it for free this round — not a failure of the build itself. ${NPX_LINE}`; + return `It didn't complete this time — not necessarily your repo's fault, our free hosted builds do sometimes hit a snag. ${NPX_LINE}`; +} + +// The repo the build ENDED on must be the repo the human submitted, or nothing ships (INV-21). +// An unreadable build.json yields null here: the live-URL check already fails that case. +export function identityViolationOf(finalCtx, submittedRepoId) { + if (!finalCtx) return null; + const finalId = repoId(finalCtx?.repo?.url); + return finalId === submittedRepoId ? null : `build ended on "${finalCtx?.repo?.url}" but was submitted for ${submittedRepoId}`; +} + +// Where did the agent's run end? The agent's own RESULT line is a courtesy; build.json is the truth. +export function agentReportOf(finalResultText) { + const m = String(finalResultText || '').match(/RESULT:\s*(\{.*\})\s*$/s); + if (!m) return null; + try { return JSON.parse(m[1]); } catch { return null; } +} +// Only the deploy tool's own verified record counts. An agent's RESULT line is repo-influenced text: +// never trusted for a URL that goes into the submitter's status page and email. +export function liveUrlOf(ctx) { + return ctx?.publish?.liveUrl && ctx.publish.http200 === true ? ctx.publish.liveUrl : null; +} + +// The run's verdict: ok only for a clean exit, inside both budgets, with a verified live URL on the +// submitted repo. `liveUrl` is the FINAL one (after any cure redeploy); identity is re-checked here. +export function finalizeRun({ exitCode, killedForBudget, killedForUsd, spawnErrorMsg, agentReported, liveUrl, finalCtx, submittedRepoId, budgetMin, budgetUsd, totalCostUsd }) { + const identityViolation = identityViolationOf(finalCtx, submittedRepoId); + const budgetExceeded = Boolean(killedForBudget || killedForUsd); + const ok = exitCode === 0 && !budgetExceeded && Boolean(liveUrl) && !identityViolation; + const reason = identityViolation + ? `SOURCE-IDENTITY VIOLATION: ${identityViolation} — treating any deploy from this run as invalid` + : spawnErrorMsg + ? `could not start the claude binary: ${spawnErrorMsg}` + : killedForUsd + ? `exceeded its $${budgetUsd} dollar budget before finishing (~$${Number(totalCostUsd || 0).toFixed(2)} spent; stopped by ${killedForUsd === 'native' ? 'Claude Code --max-budget-usd' : 'the streamed-usage backstop'})` + : budgetExceeded + ? `exceeded its ${budgetMin}-minute budget before finishing` + : agentReported && agentReported.ok === false ? agentReported.reason + : exitCode !== 0 ? `claude process exited ${exitCode}` + : !liveUrl ? 'agent finished but no verified live URL was found in build.json' + : 'unknown'; + return { ok, reason, identityViolation, budgetExceeded }; +} + +// ADR-0011 D4 / ADR-0012 D4: which axis held a below-bar delivery back, and the FORM each diagram took. +export function disclosureOf(ctx) { + const pub = ctx?.publish || {}; + const publishDisclosure = { belowBar: pub.belowBar === true, graderUnavailable: pub.graderUnavailable === true, weakest: pub.weakest || null }; + const v = ctx?.visuals || {}; + const diagramForms = Object.fromEntries(['architectureDiagram', 'flowDiagram', 'bigIdeaDiagram', 'insightDiagram'] + .filter((k) => v[k]).map((k) => [k, { form: v[k].form ?? null, variant: v[k].formVariant ?? null }])); + return { publishDisclosure, diagramForms }; +} + +// The graded record that travels in the status gist; null when nothing was graded. +export function scorecardOf(ctx, executorLane) { + const q = ctx?.quality; + if (!q || !Array.isArray(q.scorecard) || !q.scorecard.length) return null; + const { publishDisclosure, diagramForms } = disclosureOf(ctx); + return { + passed: !!q.passed, + exemplary: !!q.exemplary, + belowBarDelivery: publishDisclosure, + diagramForms, + executor: executorLane, // which billing/endpoint lane built this: admin attributes grades and cost per lane + iterations: Number.isInteger(q.iterations) ? q.iterations : null, + gradedAt: q.gradedAt || null, + devices: q.scorecard.map((c) => ({ device: c.deviceLabel || c.device || null, headline: c.headlineScore ?? null, gateA: c.gateA || null, gateB: c.gateB || null, operators: c.operatorQuestions || null })), + }; +} + +// Pre-agent work (clone, probes, concept tournament) is part of the build's wall-clock budget, so the +// agent gets what is LEFT. Returns the milliseconds the agent may run, or 0 when too little remains. +export const MIN_AGENT_WALL_MS = 3 * 60_000; +export function agentWallMs({ budgetMin, startedAt, now = Date.now() }) { + const left = budgetMin * 60_000 - Math.max(0, now - startedAt); + return left >= MIN_AGENT_WALL_MS ? left : 0; +} + +// The terminal status patch retries through GitHub's secondary rate limit with these waits (3.5 min). +export const STATUS_RETRY_DELAYS_MS = [30_000, 60_000, 120_000]; + +// Worst-case minutes the runner can spend AFTER the agent's own budget: the cure cycle plus the +// terminal status retries. The dispatch timeout (landing build.js budgetMin + 25) must cover it. +export const postAgentWorstCaseMin = () => + (CURE.AGENT_WALL_MS + CURE.GRADE_WALL_MS + CURE.DEPLOY_WALL_MS + STATUS_RETRY_DELAYS_MS.reduce((a, b) => a + b, 0)) / 60_000; + +// The exact spawn spec for the main agent and the cure agent, so what each child may see (env) and +// spend (budget flags) is one tested decision rather than wiring inside a top-level script. +const TOOL_ARGS = ['--allowed-tools', ...AGENT_ALLOWED_TOOLS, '--disallowed-tools', ...AGENT_DISALLOWED_TOOLS]; +export function mainAgentSpawn({ claudeBin, prompt, executor, budgetUsd, procEnv, submittedRepoId, subscription = false, cwd }) { + return { + bin: claudeBin, + argv: ['-p', prompt, '--permission-mode', 'bypassPermissions', '--bare', '--output-format', 'stream-json', '--verbose', + '--model', executor.model, ...maxBudgetArgs(budgetUsd), ...TOOL_ARGS], + opts: { cwd, env: buildAgentEnv(procEnv, { submittedRepoId, executor, subscription }), stdio: ['ignore', 'pipe', 'inherit'] }, + }; +} +export function cureAgentSpawn({ claudeBin, prompt, executor, remainingUsd, procEnv, submittedRepoId, subscription = false, cwd }) { + return { + bin: claudeBin, + argv: ['-p', prompt, '--permission-mode', 'bypassPermissions', '--bare', '--output-format', 'json', '--model', executor.model, + ...maxBudgetArgs(remainingUsd), ...TOOL_ARGS], + opts: { cwd, env: buildAgentEnv(procEnv, { submittedRepoId, executor, subscription }), encoding: 'utf8', timeout: CURE.AGENT_WALL_MS, maxBuffer: 32 * 1024 * 1024 }, + }; +} + +export function buildAgentPrompt({ repoUrl, buildDir, budgetMin, budgetUsd }) { + const cap = MAX_QUALITY_ITERATIONS; + return `Use the explainmyrepo skill (skills/explainmyrepo/SKILL.md is the brain — read it, follow it) to build a bespoke explainer for this repo: + +TOKEN ECONOMY: skills/explainmyrepo/TOOLS-CONTRACT.md is the complete toolbox reference (every tool's own header docs: usage, flags, gotchas). Read THAT instead of tool source files — open a tool's source ONLY if the contract is genuinely ambiguous about something you need. Re-deriving tool interfaces from source has measured at ~25% of build spend; it is waste. + + ${repoUrl} + +Build directory (already created, seeded with build.json): ${buildDir} +Station 0–1 (validate + clone) is ALREADY DONE by the harness: the repo is cloned, verified, and pinned at ${buildDir}/repo. Do NOT re-run clone-repo, and do NOT touch repo.url in build.json. + +THE SOURCE-IDENTITY LAW (INV-21 — overrides every other instruction in this brief): the repo named above IS this build's identity. If its clone is missing, broken, or anything else makes it unusable, STOP and report ok:false with the specific reason. NEVER search for, substitute, fetch, or reconstruct a different repo or its README — an explainer of the wrong repo is fabrication, the one unforgivable output. There is no workaround for source identity. +Do NOT publish a separate GitHub repo for this build (skip that station — no write-scoped GitHub token is provisioned in this hosted context, by design). +Do NOT run the notify station (station 9) — sending the submitter's email is handled OUTSIDE your process; you have no SMTP credentials and should not need them. Your job ends once quality-grade + deploy are done and build.json's publish.liveUrl is set. +The refine loop is capped at ${cap} total quality-grade calls (1 initial + ${cap - 1} refines), ENFORCED by the tool itself: a further call returns the prior scorecard unchanged at zero cost. Do not try to work around it. At the cap, RUN DEPLOY AND YOU ARE DONE. +DELIVERY IS NOT CONDITIONAL ON THE SCORE (ADR-0011). deploy.mjs refuses only on INTEGRITY — a page that did not assemble, a source-identity violation, or a missing scorecard. It does NOT refuse on a low grade: a below-bar page ships to its live URL and the requester gets an honest note naming the weakest axis. So at the cap, DELIVER. Run deploy, confirm publish.liveUrl is set, report ok:true; do not try to force a deploy, there is nothing left to force past. +Because the score does not gate delivery, you have NOTHING to gain by making the page look better to the grader than it is. The scorecard is DISCLOSURE — it goes to the requester verbatim. Grade-chasing, flattering self-assessments, and cosmetic changes aimed at the rubric rather than the reader are waste and dishonest. Spend your remaining effort on what genuinely helps a stranger understand this repo, and let the number land where it honestly lands. + +You have an approximate budget of ${budgetMin} minutes and $${budgetUsd}. Track your own elapsed time and cost as you work. This repo's actual size/complexity is unknown to me in advance — YOU are the one who discovers it by reading the repo, so budget your own effort accordingly: for a small repo, take your time and polish; for a large/deep monorepo, work faster and be willing to cap exhaustiveness (e.g. don't try to full-text-sweep every file in a 10,000-file repo — sample the important ones: READMEs, top-level docs, the most-referenced components) rather than trying to be exhaustive and running out of budget. + +CRITICAL — never fail silently (this is INV-04 in the skill, restated because it is the single most important rule for this run): if a tool fails, or a repo's structure breaks an assumption (e.g. the dependency graph comes back empty, or the repo is unusually deep/large), do NOT just crash. STOP, THINK about why, and try a reasonable workaround — always WITHIN the pinned repo; the SOURCE-IDENTITY LAW above is never workaroundable — (e.g. hand-write a minimal-but-honest architecture note if the automated extractor genuinely cannot produce one for this repo's structure) before giving up. If you truly cannot produce a working page, say EXACTLY why in plain language as your final message — a specific, honest reason a human could act on, never a bare stack trace or a vague "something went wrong." + +At the end, print your final status as the LAST line of your response in this exact form (nothing after it): +RESULT: {"ok": true, "liveUrl": ""} — on success +RESULT: {"ok": false, "reason": ""} — on failure`; +} diff --git a/bin/runner-preflight.mjs b/bin/runner-preflight.mjs new file mode 100644 index 0000000..ae0383a --- /dev/null +++ b/bin/runner-preflight.mjs @@ -0,0 +1,114 @@ +// bin/runner-preflight.mjs — the hosted runner's live credential and embedding probes. +// Pure of process state: env, .env text and fetch are injected, so tests drive every branch. + +// Every source that HAS a value, in priority order (process env first, then repo .env), deduped by +// value: the probe walks the list and the first LIVE key wins, so a dead key in process env cannot +// shadow a proven-live .env key. +export function credCandidates(names, { env = process.env, dotenvText = '' } = {}) { + const out = []; + for (const n of names) if (env[n]) out.push({ val: env[n], src: `process env ${n}` }); + for (const n of names) { + const m = dotenvText.match(new RegExp(`^${n}=("?)(.*?)\\1\\s*$`, 'm')); + if (m?.[2] && !out.some((c) => c.val === m[2])) out.push({ val: m[2], src: `.env ${n}` }); + } + return out; +} + +export async function probeCred(label, candidates, url, headers, fetchFn = fetch) { + if (!candidates.length) return { label, ok: false, why: 'not set anywhere (process env or repo .env)' }; + const dead = []; + for (const cred of candidates) { + try { + const r = await fetchFn(url, { headers: headers(cred.val), signal: AbortSignal.timeout(5000) }); + if (r.ok) return { label, ok: true, val: cred.val, why: dead.length ? `OK via ${cred.src} — self-healed past: ${dead.join('; ')}` : `OK via ${cred.src}` }; + dead.push(`${cred.src} HTTP ${r.status}`); + } catch (e) { dead.push(`${cred.src} unreachable (${e.message})`); } + } + return { label, ok: false, why: `every source dead: ${dead.join('; ')}` }; +} + +// Failover is for CAPACITY only: a merely-dead or invalid key is a config bug the operator must see. +export function shouldFailOver(anthropicProbe) { + return anthropicProbe.ok === false && anthropicProbe.usageLimited === true; +} + +// Authentication is not capacity: /v1/models spends nothing, so a 1-token completion on the agent's +// own model proves the key can SPEND, and classifies a usage-limit 400 distinctly. +async function spendProbe(a, model, fetchFn, log) { + try { + const r = await fetchFn('https://api.anthropic.com/v1/messages', { + method: 'POST', + headers: { 'x-api-key': a.val, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' }, + body: JSON.stringify({ model, max_tokens: 1, messages: [{ role: 'user', content: 'ping' }] }), + signal: AbortSignal.timeout(15_000), + }); + if (r.ok) return; + const body = await r.text().catch(() => ''); + a.ok = false; + if (/usage limits|regain access/i.test(body)) { + a.usageLimited = true; + a.why = `key authenticates but has hit its API usage limit (spend-probe HTTP ${r.status}): ${body.slice(0, 300)}`; + } else { + a.why = `key authenticates but a real 1-token completion on ${model} failed (HTTP ${r.status}): ${body.slice(0, 300)}`; + } + } catch (e) { log(`credential preflight: spend-probe inconclusive (${e.message}) — proceeding on the auth probe`); } +} + +// Same executor model through OpenRouter's Anthropic-compatible endpoint, engaged only on a +// PROVEN-live 1-token completion. Returns the executor descriptor or null. +async function tryOpenRouterLane({ env, dotenvText, fetchFn, log }) { + const cands = credCandidates(['OPENROUTER_API_KEY'], { env, dotenvText }); + const orModel = env.OPENROUTER_ANTHROPIC_MODEL || 'anthropic/claude-sonnet-5.5'; + for (const cand of cands) { + try { + const r = await fetchFn('https://openrouter.ai/api/v1/messages', { + method: 'POST', + headers: { 'x-api-key': cand.val, Authorization: `Bearer ${cand.val}`, 'anthropic-version': '2023-06-01', 'content-type': 'application/json' }, + body: JSON.stringify({ model: orModel, max_tokens: 1, messages: [{ role: 'user', content: 'ping' }] }), + signal: AbortSignal.timeout(20_000), + }); + if (r.ok) return { executor: { lane: 'openrouter', model: orModel, baseUrl: 'https://openrouter.ai/api', key: cand.val }, src: cand.src }; + const body = await r.text().catch(() => ''); + log(`failover probe: OpenRouter Skin refused (${cand.src}, HTTP ${r.status}): ${body.slice(0, 200)}`); + } catch (e) { log(`failover probe: ${cand.src} unreachable (${e.message})`); } + } + log(cands.length ? 'failover: no live OpenRouter lane — the honest usage-limit refusal stands' : 'failover: no OPENROUTER_API_KEY configured — the honest usage-limit refusal stands'); + return null; +} + +// Probes the three keys a hosted run needs (agent reasoning, deploy, vision grading). Returns +// { a, n, o, executor }; the caller applies the proven-live values to process.env. +export async function probeCredentials({ model, env = process.env, dotenvText = '', fetchFn = fetch, log = () => {} }) { + const cands = (...names) => credCandidates(names, { env, dotenvText }); + const bearer = (v) => ({ Authorization: `Bearer ${v}` }); + const [a, n, o] = await Promise.all([ + probeCred('ANTHROPIC_API_KEY (agent reasoning)', cands('ANTHROPIC_API_KEY', 'CLAUDE_API_KEY'), 'https://api.anthropic.com/v1/models', (v) => ({ 'x-api-key': v, 'anthropic-version': '2023-06-01' }), fetchFn), + probeCred('NETLIFY_AUTH_TOKEN (deploy)', cands('NETLIFY_AUTH_TOKEN'), 'https://api.netlify.com/api/v1/user', bearer, fetchFn), + probeCred('OPENAI_API_KEY (images + vision grading)', cands('OPENAI_API_KEY', 'OPEN_AI_KEY'), 'https://api.openai.com/v1/models', bearer, fetchFn), + ]); + if (a.ok) await spendProbe(a, model, fetchFn, log); + let executor = { lane: 'anthropic', model, baseUrl: null, key: null }; + if (shouldFailOver(a)) { + const lane = await tryOpenRouterLane({ env, dotenvText, fetchFn, log }); + if (lane) { + executor = lane.executor; + a.ok = true; + a.why = `primary key usage-limited — FAILOVER ENGAGED: same executor model via OpenRouter's Anthropic Skin (${lane.executor.model}, ${lane.src}), billed to OpenRouter credits`; + } + } + return { a, n, o, executor }; +} + +// KB build hard-requires a real embedding model (grounding is never fabricated). The workflow's +// kb/warm-model-cache.mjs step seeds the cache BEFORE this runs (release asset, sha256-pinned, then HF); +// if the cache is still cold here, the only source the KB build itself uses is huggingface.co, so that +// is the only thing worth probing. +export async function probeEmbedding({ cachedModelExists, fetchFn = fetch }) { + if (cachedModelExists) return { ok: true, why: 'model cached locally — KB build needs no network' }; + try { + const r = await fetchFn('https://huggingface.co/Xenova/bge-small-en-v1.5/resolve/main/config.json', { method: 'HEAD', redirect: 'follow', signal: AbortSignal.timeout(8000) }); + return r.ok + ? { ok: true, why: `no local cache; huggingface.co reachable (HTTP ${r.status}) — the KB build will download the model from there` } + : { ok: false, why: `no local model cache and huggingface.co answered HTTP ${r.status}` }; + } catch (e) { return { ok: false, why: `no local model cache and huggingface.co unreachable (${e.message})` }; } +} diff --git a/commands/explainmyrepo.md b/commands/explainmyrepo.md index 20a667c..d797309 100644 --- a/commands/explainmyrepo.md +++ b/commands/explainmyrepo.md @@ -27,9 +27,10 @@ control to the skill. only its declared inputs, merges its slot into `build.json`, and **fails loud** (non-zero exit, clear message) — never a silent placeholder. Read `tools/CONTRACT.md` before running any tool. 4. **Report honestly.** When the build finishes, return the live URL, the explainer repo, the AI - knowledge pack link, the dual-gate scorecard, and both screenshots. If any station could not - clear its bar (e.g. a criterion that genuinely cannot reach 95), **flag it honestly** — never - ship slop and call it done (INV-05). + knowledge pack link, the dual-gate scorecard, and both screenshots. If the page landed below the + exemplary bar (mean 90, min axis 85, all six operator questions yes), **say so and name the weakest + axis** (the ship tier is mean 82, min axis 70). The gate advises (ADR-0011): a below-bar page is + still delivered, with the shortfall disclosed. Never present a below-bar page as if it cleared the bar. -> The completion bar is the mission, not a slogan: a stranger looks at the result and smiles — -> *"that's really cool."* If a build cannot clear that bar, it is not done. +> The target is the mission, not a slogan: a stranger looks at the result and smiles — +> *"that's really cool."* Aim for the 90/85 bar, and report honestly where the page landed. diff --git a/docs/SHIP-CHECKLIST.md b/docs/SHIP-CHECKLIST.md deleted file mode 100644 index d30f720..0000000 --- a/docs/SHIP-CHECKLIST.md +++ /dev/null @@ -1,208 +0,0 @@ -# Ship Checklist — explainmyrepo - -> Ordered steps to ship the canonical `explainmyrepo` landing page, point the domain at it, -> retire stale deploys, and publish the npm package. -> -> **BLOCKED ON OWNER TOKENS** markers call out every step that requires credentials that are -> not in this repo. Do those steps manually or with the right token in hand. - ---- - -## Prerequisites - -- [ ] Vercel account access for the `isovision` org (team `team_J1ktaVpPnXdvDZsFH9Z4yH6t`) - **BLOCKED ON OWNER TOKENS: Vercel login required** -- [ ] GitHub `gh` CLI authenticated as `stuinfla` (or org member with repo write access) -- [ ] npm logged in as a member of the `@isovision` org - **BLOCKED ON OWNER TOKENS: `npm login` + confirm `@isovision` org exists on npm** -- [ ] DNS control for `isovision.ai` (to add the `explainmyrepo` subdomain CNAME) - **BLOCKED ON OWNER TOKENS: DNS access required** - ---- - -## Phase A — Deploy ONE canonical page to the "repo-explainer" Vercel project and rename it - -The canonical landing page lives in `www/`. Its current Vercel project is named **`repo-explainer`** -(`projectId: prj_KbSbSjdTfeGzW6x4O2TftTU8jXi1`, `www/.vercel/project.json`). - -1. **Verify the working deploy from `www/`** - - ```bash - cd www - npx vercel --prod --yes # re-deploy latest www/ to the repo-explainer project - ``` - - Confirm the deployment URL resolves and the landing page loads correctly. - -2. **Rename the Vercel project from `repo-explainer` → `explainmyrepo`** - - In the Vercel dashboard: Settings → General → Project Name → change to `explainmyrepo`. - This will change the auto-assigned URL from `repo-explainer.vercel.app` to - `explainmyrepo.vercel.app`. Update `www/.vercel/project.json` `projectName` field to match. - - **BLOCKED ON OWNER TOKENS: Vercel project settings access required** - -3. **Update the `www/.vercel/project.json` locally after renaming** - - Change `"projectName": "repo-explainer"` → `"projectName": "explainmyrepo"`. - -4. **Update in-page branding now that the project is confirmed live** (separate PR — not this - checklist's scope, but note that `www/index.html` still shows "Repo Explainer" in ``, - `og:title`, the nav logo, hero copy, and footer. See naming inventory for the full list.) - ---- - -## Phase B — Point `isovision.ai` / `explainmyrepo.isovision.ai` at the Vercel project - -5. **Add the custom domain in Vercel** - - Dashboard → explainmyrepo project → Settings → Domains → Add domain: - - `explainmyrepo.isovision.ai` - - Optionally: `isovision.ai` if that root should redirect here too - - Vercel will show the required DNS record (typically a CNAME to `cname.vercel-dns.com` for the - subdomain, or A/ALIAS for the apex). - - **BLOCKED ON OWNER TOKENS: Vercel project access required** - -6. **Add the DNS record at your DNS provider for `isovision.ai`** - - ``` - CNAME explainmyrepo.isovision.ai → cname.vercel-dns.com - ``` - - (Exact value comes from step 5. If using Vercel DNS, run `vercel dns add …` instead.) - - **BLOCKED ON OWNER TOKENS: DNS provider access required** - -7. **Verify TLS and propagation** - - ```bash - curl -sI https://explainmyrepo.isovision.ai | head -4 - # expect: HTTP/2 200 - ``` - - Vercel auto-provisions TLS once the CNAME resolves. Allow up to 24 h for DNS propagation. - -8. **Update `www/vercel.json`** if a canonical redirect from the old `.vercel.app` URL is needed. - Add a redirect rule pointing `repo-explainer.vercel.app` → `https://explainmyrepo.isovision.ai`. - Vercel will continue serving the old auto-assigned URL until you delete it. - ---- - -## Phase C — Retire stale deploys and note the dead metaharness URL - -The following Vercel projects are stale per-repo explainer outputs, NOT part of the landing page. -Retire them by removing them from Vercel and archiving or deleting their GitHub repos. - -| Stale Vercel URL | Vercel project name | Local dir | Action | -|---|---|---|---| -| `repo-explainer.vercel.app` | `repo-explainer` (becomes `explainmyrepo.vercel.app` after step 2) | `www/` | Keep — this is the canonical page | -| `repo-explainer-six.vercel.app` | unknown — no local project.json found | — | **Delete** in Vercel dashboard | -| `repo-explainer-website.vercel.app` | unknown — no local project.json found | — | **Delete** in Vercel dashboard | -| `ruv-explainer-agent-harness-generator.vercel.app` | `ruv-explainer-agent-harness-generator` | `ruv-explainer-agent-harness-generator/` | **Delete or archive** (see dead URL note below) | -| `ruvn-explainer.vercel.app` | `ruvn-explainer` | `ruv-explainer-ruvn/` | Delete or archive | -| `ruqu-explainer.vercel.app` | `ruqu-explainer` | `ruv-explainer-ruqu/` | Delete or archive | -| `photonlayer-explainer.vercel.app` | `photonlayer-explainer` | `ruv-explainer-photonlayer/` | Delete or archive | - -**Dead URL — MetaHarness / agent-harness-generator:** -The file `ruv-explainer-agent-harness-generator/package.json` references homepage -`https://ruv-explainer-agent-harness-generator.vercel.app`. This URL is stale and should be -considered dead. The studio link inside the explainer (`ruvnet.github.io/agent-harness-generator/`) -points to a GitHub Pages URL that may or may not still be live — verify independently before -removing the link from the explainer HTML. - -**Steps to retire:** - -9. **Identify stale project IDs** for `repo-explainer-six` and `repo-explainer-website` — they - have no local `project.json` in this repo. Check the Vercel dashboard to find them. - - **BLOCKED ON OWNER TOKENS: Vercel access required** - -10. **Delete stale projects in Vercel dashboard** (Settings → General → Delete Project). - - Before deleting, confirm each project has no active custom domain pointing at it, and that - no external links in READMEs or docs you care about reference it. - -11. **Archive or delete the stale per-repo GitHub repos** (if they were created as separate repos): - - `stuinfla/ruv-explainer-agent-harness-generator` (referenced in that project's package.json) - - Any other `stuinfla/ruv-explainer-*` repos created as per-explainer outputs - - The source code for all of them lives in this monorepo; the GitHub repos are deployment - artifacts and can be archived once Vercel projects are deleted. - ---- - -## Phase D — Publish `@isovision/explainmyrepo` to npm - -The package is already named correctly (`package.json`: `"name": "@isovision/explainmyrepo"`, -`"version": "0.1.0"`). These steps complete the publish. - -12. **Confirm the `@isovision` npm org exists** - - ```bash - npm org ls @isovision # or check https://www.npmjs.com/org/isovision - ``` - - If the org does not exist, create it at `https://www.npmjs.com` before proceeding. - - **BLOCKED ON OWNER TOKENS: npm login required; @isovision org existence unconfirmed** - -13. **Log in to npm** - - ```bash - npm login - # follow prompts; confirm you have publish rights to @isovision - ``` - - **BLOCKED ON OWNER TOKENS: npm credentials required** - -14. **Dry-run the publish** - - ```bash - npm pack --dry-run - # review the file list — confirm no .env, secrets, or large binaries are included - ``` - -15. **Publish** - - ```bash - npm publish --access public - ``` - -16. **Verify the package is live** - - ```bash - npm info @isovision/explainmyrepo - # should return version 0.1.0 - ``` - -17. **Test the npx invocation** (the README shows `npx @isovision/explainmyrepo `). - Confirm the bin entry in `package.json` is set and the entry script runs correctly: - - ```bash - npx @isovision/explainmyrepo --help # or whatever the CLI entry point is - ``` - ---- - -## Blocked items summary - -| Item | Blocker | -|---|---| -| Netlify re-auth | Netlify token is returning 401; existing Netlify deploys (e.g. `agenticow-explainer.netlify.app`) cannot be managed until a valid token is provided. Per-repo explainer outputs may still deploy via Netlify if the Netlify integration is used. | -| npm login + @isovision org | Must log in to npm as a user with publish rights; must verify `@isovision` org exists before `npm publish`. | -| Vercel project rename + domain + cleanup | Requires Vercel access to the `isovision` org (team `team_J1ktaVpPnXdvDZsFH9Z4yH6t`). Cannot rename project, add custom domain, or delete stale projects without this. | -| DNS for `explainmyrepo.isovision.ai` | Requires access to the DNS provider for `isovision.ai`. | - ---- - -## Notes - -- The e2e test output in the scratchpad (`e2e/site/`) uses `agenticow-explainer.netlify.app` as - its base URL. That is correct for a per-repo explainer output (agenticow was the test repo). - The SEO meta tags, sitemap, robots.txt, and llms.txt in that output are all well-formed and - correctly reference the Netlify URL, not the landing page URL. -- The sitemap's `` and robots.txt `Sitemap:` directive will need to be parameterised (or - the build tool updated) to use `explainmyrepo.isovision.ai` once that domain is live and - per-repo explainers are deployed under it rather than under Netlify. diff --git a/docs/adr/0005-skill-based-explainer-recipe.md b/docs/adr/0005-skill-based-explainer-recipe.md index de1eb21..ef1d584 100644 --- a/docs/adr/0005-skill-based-explainer-recipe.md +++ b/docs/adr/0005-skill-based-explainer-recipe.md @@ -1,8 +1,28 @@ # ADR-0005: The Skill-Based Explainer Recipe — One Brain, Three Doors -Updated: 2026-06-29 10:40:00 EDT | Version 1.7.0 +Updated: 2026-11-05 12:00:00 EST | Version 1.8.0 Created: 2026-06-28 00:00:00 EDT +Status: Accepted — **superseded in part** (see the 3.0.1 note below) +Date: 2026-06-28 +Updated: 2026-11-05 + +> **Superseded in part (3.0.1, 2026-11-05).** This is the origin recipe and is kept as written for its +> reasoning. Where it disagrees with the code, the code wins. What has changed since: +> +> | This ADR says | The code now | +> |---|---| +> | "One brain, three doors" | **Two doors.** The local orchestrator (`src/orchestrator.mjs`, the `npx` CLI; its authoring calls live in `src/brain.mjs`) and the agent that follows `skills/explainmyrepo/SKILL.md` (the hosted runner; the slash command loads the same file). They are held in step by tests (`tests/two-doors-conform.test.mjs`, `tests/review-p4b-parity.test.mjs`), not by sharing one brain. | +> | The station list in this ADR | `src/stations.mjs` is the one station table (id, tool, kind, fatal, doors, phase). | +> | `kb/make-dropin.mjs` builds the pack; its `must()` needs the primer; `.small.rvf` stores | `kb/make-dropin.mjs` is deleted. `tools/make-pack.mjs` is a port (one slot, `pack = { zipPath }`); the store is `-kb.rvf` (`rvfSuffix: '.rvf'`); `@ruvector/rvf` is `^0.4.2`. | +> | Bar: mean >= 90 and min >= 85, five operator questions, below it the build does not ship | **Two tiers.** EXEMPLARY mean >= 90, min >= 85, **six** operator questions (ADR-0006); SHIP mean >= 82, min >= 70, five ship operators. **The gate advises** (ADR-0011): deploy refuses only on integrity. | +> | Station 4: the brain authors ASCII / SVGs | `make-diagrams` draws every slot from authored `rows` and verified story models (ADR-0012, ADR-0014); only `heroAnim.sceneSvg` is authored as SVG (ADR-0013). | +> | Explainer targets MUST set an `embed` block; the engine default is MiniLM and writes `.small.rvf`; bge-small is required | **No default embedder.** `kb/build-kb.mjs` refuses a target with no `embed` block (model + dim) and the suffix is always `.rvf` (`rvfSuffix`). The model the store was built with is recorded in `-kb.rvf.embed.json` and that sidecar governs queries; every registered target happens to use `Xenova/bge-small-en-v1.5`, but nothing requires that model. `kb/index-primer.mjs` throws if the sidecar is missing or names a different model than `ids.json`. | +> | Image engine: primary `gpt-image-2`, fallback `gpt-image-1` | `gpt-image-2.5-flare` at `xhigh`, then `gpt-image-2`, then Grok if the OpenAI chain fails or there is no OpenAI key (`tools/generate-image.mjs`). Prices for `-flare` are unknown and receipts say so. | +> | Deploy adapter is provider-agnostic, "Vercel is a one-line swap" | `tools/deploy.mjs` deploys to Netlify only. | +> | Station 8b offers a README pull request | Issue first, PR only after a yes (ADR-0015). | +> | (not in this ADR) | The Ask box (ADR-0016) and the share-card gate are later additions. | + > **v1.7.0 (2026-06-29) — quality-bar reconciliation + implementation-experience.** Owner-signed > changes to the gate: (1) the literal "≥95 on every axis" floor is replaced by the > **exemplar-anchored bar — mean ≥ 90 AND minimum axis ≥ 85 on both devices** — because an honest @@ -173,8 +193,7 @@ The KB is **not rebuilt**. The skill's KB tools **wrap the real, working `kb/` e - `-kb.ids.json` (per-id kind/preview index) - `-kb.rvf.embed.json` (embedder sidecar so the *query* uses the same model as the corpus) - Build self-reconciles: `chunks == vectors == passages == ids` or it `exit(1)`s. -- **Embedder — explainer targets MUST set an `embed` block (the MiniLM default is *not* the - operative path here).** The engine's bare default is `Xenova/all-MiniLM-L6-v2` (384-dim) — but on +- **Embedder — explainer targets MUST set an `embed` block (SUPERSEDED, see the 3.0.1 banner: there is now no default embedder, the suffix is always `.rvf`, and the `.small.rvf` text below is history).** The engine's bare default is `Xenova/all-MiniLM-L6-v2` (384-dim) — but on that default `build-kb.mjs` (`RVF_SUFFIX = target.embed ? '.rvf' : '.small.rvf'`, line 244) writes `-kb.`**`small`**`.rvf`, while `kb/make-dropin.mjs` globs the literal `-kb.rvf`; so a default-embedder target produces a store the pack builder cannot find and the pack's `must()` check @@ -185,7 +204,7 @@ The KB is **not rebuilt**. The skill's KB tools **wrap the real, working `kb/` e `kb/models-cache/` so CI never cold-downloads. - `node kb/ask-kb.mjs "question" [k]` is the real search CLI. It joins `.rvf` hits to `.passages.jsonl` by id and prints **full passages** through an intent-routing + rerank layer. -- `node kb/make-dropin.mjs ` builds the downloadable AI pack (see Station 6 — +- `node kb/make-dropin.mjs ` — **[REMOVED; historical — the pack is built by `tools/make-pack.mjs` today]** — built the downloadable AI pack (see Station 6 — ASSEMBLE + PACK, and INV-07). - `kb/kb-mcp-server.mjs` is the real MCP server. It exposes **four** tools: `search_kb`, `lookup_symbol`, `get_entrypoints`, `get_dep_graph`, returning `content:[{type:'text', text:…}]`. @@ -382,8 +401,7 @@ stations in order, filling `BuildContext` slot by slot; the tools do the mechani ### Station 1 — UNDERSTAND - **Do:** Clone the repo. Run the **real** `kb/` engine to build the RVF KB: `node kb/build-kb.mjs --target ` (after registering the target in `kb/kb.config.mjs` - **with an `embed` block** — see D3; without it build-kb writes `-kb.small.rvf`, which the - Station 6 pack builder cannot find). Then **run the structured-extraction build step** — + **with an `embed` block** — see D3; without it build-kb now refuses; the `.small.rvf` fallback this once described is gone). Then **run the structured-extraction build step** — `node kb/extract-symbols.mjs `, `node kb/dep-graph.mjs `, `node kb/entrypoints.mjs ` — which is a **REQUIRED build step, not optional reading**: its `-symbols.json` / `-dep-graph.json` / `-entrypoints.json` outputs are @@ -481,7 +499,7 @@ stations in order, filling `BuildContext` slot by slot; the tools do the mechani - **Do:** (a) **Render the page once** onto the shared design system (D8) — compose the brief + content + visuals into the component skeleton. (b) Build the **AI knowledge pack** with the studio-less pack builder (see the deviation note below): - `node kb/make-dropin.mjs /-knowledge-pack.zip`. The pack ships the + `node kb/make-dropin.mjs /-knowledge-pack.zip` **[REMOVED; historical — use `tools/make-pack.mjs`]**. The pack ships the `for-ai/` half — `-kb.rvf` + `-kb.rvf.idmap.json` + `-kb.rvf.embed.json` + `-kb.passages.jsonl` + `-kb.ids.json` + **`-symbols.json` + `-dep-graph.json` + `-entrypoints.json`** + `ask-kb.mjs` + `kb-mcp-server.mjs` + `kb.config.mjs` + @@ -821,7 +839,7 @@ These are always-true properties, enforced in code (design system + tools) and a | Search CLI | `node kb/ask-kb.mjs "question" [k]` — joins `.rvf` hits to `.passages.jsonl` by id; intent-routing + rerank | | Pack builder | `node kb/make-dropin.mjs ` — `for-ai/` + `for-humans/`; declares `@ruvector/rvf@^0.2.2` + `@xenova/transformers@^2.17.2` | | MCP server | `kb/kb-mcp-server.mjs` — four tools: `search_kb`, `lookup_symbol`, `get_entrypoints`, `get_dep_graph`. The latter three READ `-symbols.json` / `-entrypoints.json` / `-dep-graph.json` (produced by `kb/extract-symbols.mjs` / `kb/entrypoints.mjs` / `kb/dep-graph.mjs`) — these MUST be in the pack or three of the four tools return nothing | -| Embedders | `Xenova/all-MiniLM-L6-v2` (384-dim, engine default → writes `.small.rvf`) or `Xenova/bge-small-en-v1.5` (384-dim, the explainer's **required** `embed` override → canonical `.rvf`) — both cached at `kb/models-cache/` | +| Embedders | historical (see banner): `Xenova/all-MiniLM-L6-v2` (384-dim) and `Xenova/bge-small-en-v1.5` (384-dim); today the target's `embed` block and the `.embed.json` sidecar decide — both cached at `kb/models-cache/` | | Real packages | `@ruvector/rvf@^0.2.2` (query), `@ruvector/rvf-node` (native, transitive), `@xenova/transformers@^2.17.2` (local ONNX) | | Fictional (npm 404) | `@rvf/forge`, `@ruvector/search-cli`, `@ruvector/mcp-server` — never reference (re-verified via `npm view` at edit time) | | Real but NOT used | `@ruvector/rvf-mcp-server` (npm `0.1.4`, real) — deliberately not pulled in; the pack ships the in-repo `kb/kb-mcp-server.mjs` instead | diff --git a/docs/adr/0006-comprehension-ladder-first-principles.md b/docs/adr/0006-comprehension-ladder-first-principles.md index 122bb5e..795d45b 100644 --- a/docs/adr/0006-comprehension-ladder-first-principles.md +++ b/docs/adr/0006-comprehension-ladder-first-principles.md @@ -1,8 +1,18 @@ # ADR-0006: The Comprehension Ladder — First-Principles Altitude Control -Updated: 2026-07-03 13:20:00 EDT | Version 1.1.0 +Updated: 2026-11-05 12:00:00 EST | Version 1.2.1 Created: 2026-07-03 12:05:00 EDT +Status: Accepted + Implemented (D4 shipped; reader model amended by v1.2.0) +Date: 2026-07-03 +Updated: 2026-11-05 + +> **Note (3.0.1).** Verified against code: the sixth operator question exists (`OPERATOR_QUESTIONS` in +> `tools/quality-grade.mjs`, `zeroKnowledgeReader`), and the INV-20 and INV-24 pre-checks run before the +> vision pass. The "mean >= 90 / min >= 85" bar this ADR keeps is now the **EXEMPLARY** tier; delivery is +> judged against the SHIP tier (mean >= 82, min >= 70, five ship operators) and the gate only advises +> (ADR-0011). + > **v1.1.0 (2026-07-03) — proof-run findings folded in.** Rebuilding lattice under v1.0.0 > surfaced four refinements, all implemented: (1) **D1 gains the CONCEPT BUDGET** — a gloss is > not a free pass; rungs 1–4 may introduce at most THREE domain concepts total (the critic @@ -20,8 +30,8 @@ Created: 2026-07-03 12:05:00 EDT > about; the ladder-authored rebuild passes INV-20 and is held only by the (correctly) stricter > beginner-persona operators — the gate now refuses what it used to ship. -**Status:** Proposed — awaiting owner sign-off (D4 changes the operator gate, which is -owner-signed by ADR-0005 convention; everything else is ready to implement on approval). +**Status (v1.0.0, historical):** Proposed — awaiting owner sign-off. It was signed off and implemented; the +current status is at the top of this file. **Amends:** ADR-0005 (Station 3 AUTHOR, Station 6 ASSEMBLE, Station 7 QUALITY GATE / The QA System). Does **not** supersede it — the one-brain/three-doors architecture, the stations, the diff --git a/docs/adr/0007-source-identity-invariant.md b/docs/adr/0007-source-identity-invariant.md index a96b705..4f68690 100644 --- a/docs/adr/0007-source-identity-invariant.md +++ b/docs/adr/0007-source-identity-invariant.md @@ -1,8 +1,16 @@ # ADR-0007: INV-21 Source-Identity — the submitted repo is the build, or there is no build -Updated: 2026-07-08 19:50:00 EDT | Version 1.2.0 +Updated: 2026-11-05 12:00:00 EST | Version 1.2.1 Created: 2026-07-08 17:10:00 EDT +Status: Accepted + Implemented +Date: 2026-07-08 +Updated: 2026-11-05 + +> **Note (3.0.1).** Re-checked against code: `tools/clone-repo.mjs` and `tools/deploy.mjs` both read +> `EXPLAINER_SUBMITTED_REPO`. Only the hosted runner sets it (`bin/agentic-runner.mjs`, `bin/runner-lib.mjs`), so +> the pin is armed on the hosted door and **unarmed on the local door**, as ADR-0011's honesty note records. + > **v1.2.0 — the open question is RESOLVED (owner decision, same day): the hosted door builds > PUBLIC repos only.** A hosted build publishes a public page, which must never quietly expose > private code. The landing /build function now rejects private repos at submit time and routes diff --git a/docs/adr/0008-every-image-teaches.md b/docs/adr/0008-every-image-teaches.md index f8f4ab9..36749cf 100644 --- a/docs/adr/0008-every-image-teaches.md +++ b/docs/adr/0008-every-image-teaches.md @@ -2,6 +2,7 @@ Status: Accepted + Implemented Date: 2026-07-13 +Updated: 2026-11-05 Amends: ADR-0005 (skill-based recipe), ADR-0006 (comprehension ladder) ## Context @@ -40,6 +41,11 @@ better than this page." He was right, and the cause was in the spec, not the exe element carries the next beat. 7. **Creative engine.** The runner's default model is `claude-fable-5` (verified live 2026-07-13) — the product is creative judgment, so the top-tier model is the correct spend. + *(Superseded 2026-11-05: the runner's default is now `claude-sonnet-5-5` (`bin/agentic-runner.mjs` + `args.model || 'claude-sonnet-5-5'`; `src/claude.mjs` `DEFAULT_MODEL`). The local door uses OpenRouter + `z-ai/glm-5.3` only when it is the sole credential or asked for. Image generation is a separate chain: + `gpt-image-2.5-flare` at `xhigh`, then `gpt-image-2`, with Grok when there is no OpenAI key or the whole OpenAI chain fails (`tools/generate-image.mjs`); the + flare price is unknown and receipts say UNPRICED, never $0.)* ## Consequences diff --git a/docs/adr/0009-alive-kit-local-companions.md b/docs/adr/0009-alive-kit-local-companions.md index 8e2d9a4..59b82d7 100644 --- a/docs/adr/0009-alive-kit-local-companions.md +++ b/docs/adr/0009-alive-kit-local-companions.md @@ -2,14 +2,19 @@ **Status**: Accepted — per-capability status lives ONLY in `capabilities.json` (render it with `explainmyrepo capabilities`); this ADR never transcribes it **Date**: 2026-07-17 -**Updated**: 2026-07-17 +**Updated**: 2026-11-05 **Authors**: Claude Code (Fable 5), directed by Stuart Kerr **Supersedes**: None **Related ADRs**: ADR-0005 (skill-based recipe), ADR-0008 (every image teaches) -**Code touchpoints**: the ship-bar rail (tools/deploy.mjs, 2026-07-13), the operator's grade (bin/agentic-runner.mjs, 2026-07-15) +**Code touchpoints**: `capabilities.json`, `tools/make-trailer.mjs`, `tools/make-social-loop.mjs`, `tests/capabilities-registry.test.mjs` --- +> **Renumbered (3.0.1, 2026-11-05).** This ADR's invariants were INV-24 to INV-28. INV-24 is the reading-level +> gate (ReadsAtFifteen, ADR-0006), so the Alive Kit set is now **INV-29 to INV-33** (old to new: 24 to 29, +> 25 to 30, 26 to 31, 27 to 32, 28 to 33). The source comments and test titles +> (`tools/make-social-loop.mjs`, `tests/capabilities-registry.test.mjs`) carry the new numbers. + ## Context The pipeline produces one gated page per repo. This week's HyperFrames pilot proved the page's @@ -47,7 +52,7 @@ policy this ADR encodes: `capabilities.json` at the repo root lists every companion with: `{ id, title, status: specified | built | verified, verifiedAt?, receipts?, entry? }`. -**INV-24 (the gating invariant)**: a capability is *advertised* (shown as available by any +**INV-29 (the gating invariant)**: a capability is *advertised* (shown as available by any user-facing surface) **iff `status: "verified"`** — meaning one supervised end-to-end proof run produced a real artifact whose receipts (date, output, cost, duration) are recorded in the registry entry. `specified` and `built` entries may be listed only under an explicit "not yet @@ -55,12 +60,12 @@ verified — not enabled" label. Truth-in-advertising is enforced by the registr data source the CLI reads; there is no second list to drift — which is why this ADR itself carries no per-capability status or receipts anywhere, including its Status line. -**INV-25**: `status: "verified"` ⇒ `receipts` and `verifiedAt` present, and `entry` points at a +**INV-30**: `status: "verified"` ⇒ `receipts` and `verifiedAt` present, and `entry` points at a real tool. Mechanically enforced: `tests/capabilities-registry.test.mjs` fails the suite on any -registry shape that violates this (or INV-24's schema), so a promotion without receipts cannot +registry shape that violates this (or INV-29's schema), so a promotion without receipts cannot land through a green build. -### 2. Local-door-only invariant (INV-26) +### 2. Local-door-only invariant (INV-31) Companions run **only** on a locally cloned repo, invoked explicitly by the person at the keyboard. Enforcement is mechanical, not advisory: @@ -74,7 +79,7 @@ people who **bring the solution down and run it themselves**. ### 3. The four capabilities, specified Common contract for all four: **input is a completed, gated build directory** (`build.json` + -`site/` + `assets/`) consumed read-only (INV-28); the engine is a HyperFrames workflow authored in a +`site/` + `assets/`) consumed read-only (INV-33); the engine is a HyperFrames workflow authored in a local Claude Code session (subscription-covered, per the 2026-07-15 `--executor-auth` finding); rendering is local FFmpeg ($0); output lands in the build directory and is never auto-deployed. @@ -89,9 +94,9 @@ capabilities`); this table defines each capability's contract and its objective | 4 | `social-loop` | `/motion-graphics`, ≤10s loop from the page's hero animation | `renders/social-loop.mp4` (+ 9:16 variant) | one supervised run; worst-frame check passes in BOTH aspect ratios | Verification promotes `status` to `verified` in the same commit that records the receipts -(INV-25). +(INV-30). -### 4. Fail-open, always (INV-27) +### 4. Fail-open, always (INV-32) A companion failure logs loudly, records the failure in the build dir, and exits non-zero — and changes nothing about the page, the gate verdict, or the deploy. No companion sits between @@ -166,8 +171,8 @@ verification run per §3's pass condition. ## References - `capabilities.json` — the registry (this ADR §1); all live status + receipts live there -- `tests/capabilities-registry.test.mjs` — INV-24/INV-25 mechanical enforcement +- `tests/capabilities-registry.test.mjs` — INV-29/INV-30 mechanical enforcement - `tools/make-trailer.mjs` — the trailer capability's scaffolder/entry - `bin/explainmyrepo.mjs` — the `capabilities` subcommand (§7) -- `docs/ddd/alive-kit-domain.md` — the companion domain model (INV-24…INV-28) +- `docs/ddd/alive-kit-domain.md` — the companion domain model (INV-29 to INV-33) - heygen-com/hyperframes (Apache-2.0 core; skills unlicensed — hence §5) diff --git a/docs/adr/0010-incremental-delta-kb-builds.md b/docs/adr/0010-incremental-delta-kb-builds.md index ee52ce6..6bb851e 100644 --- a/docs/adr/0010-incremental-delta-kb-builds.md +++ b/docs/adr/0010-incremental-delta-kb-builds.md @@ -2,15 +2,20 @@ **Status**: Accepted (converged after adversarial review round, Fable 5 vs GPT-5.6-Sol, 2026-07-24) **Date**: 2026-07-24 -**Updated**: 2026-07-24 +**Updated**: 2026-11-05 **Authors**: Claude Code (Fable 5), directed by Stuart Kerr; adversarial reviewer GPT-5.6-Sol (codex) **Prompted by**: [GitHub issue #14](https://github.com/stuinfla/Repo-Explainer/issues/14) (Jordi Izquierdo, Data Driven Solutions) — heavy user, 15,316-chunk corpus, ~50 min local embed per rebuild, ~99% of it recomputing unchanged vectors **Supersedes**: None **Related ADRs**: ADR-0001 (repo-primer recipe; chunker D5, single-384 v1.3.1), ADR-0007 (source identity invariant) -**Code touchpoints**: `kb/build-kb.mjs` (`--delta`), new `kb/chunker.mjs`, new `kb/store-set.mjs`, `kb/index-primer.mjs` (idempotent replace + metadata fix), `tests/kb-delta.e2e.mjs` +**Code touchpoints**: `kb/build-kb.mjs` (`--delta`), new `kb/chunker.mjs`, new `kb/store-set.mjs`, `kb/index-primer.mjs` (idempotent replace + metadata fix), `tests-e2e/kb-delta.e2e.test.mjs` --- +> **Note (3.0.1, 2026-11-05).** The end-to-end test is `tests-e2e/kb-delta.e2e.test.mjs`. It moved out of +> `npm test` (which runs `tests/*.test.mjs`) and runs with `npm run test:e2e` (`tests-e2e/*.test.mjs`). +> `@ruvector/rvf` is now `^0.4.2` (`package.json`); the 0.3.0 `metadata` regression described below is the +> reason D0 exists. + ## Context `kb/build-kb.mjs` is batch-from-scratch: every run re-walks the tree, re-chunks, and @@ -82,8 +87,9 @@ delta tools import the *real* chunker; the drift risk the issue's replica guarde disappears by construction. Zero behavior change — proven by byte-comparing full-build sidecars before and after the factoring. -`make-dropin.mjs` is unaffected: the drop-in ships `ask-kb.mjs` / `kb-mcp-server.mjs` / -`kb.config.mjs` / `resolve-deps.mjs`, none of which import the chunker. +The pack is unaffected: it ships `ask-kb.mjs` / `kb-mcp-server.mjs` / +`kb.config.mjs` / `resolve-deps.mjs`, none of which import the chunker. *(2026-11-05: `kb/make-dropin.mjs` +is gone; `tools/make-pack.mjs` builds the pack with the same four engine files.)* ### D2 — `--delta` on `build-kb.mjs`, invalidating at FILE granularity diff --git a/docs/adr/0011-the-gate-advises-never-destroys.md b/docs/adr/0011-the-gate-advises-never-destroys.md index 42155f1..e4e0b94 100644 --- a/docs/adr/0011-the-gate-advises-never-destroys.md +++ b/docs/adr/0011-the-gate-advises-never-destroys.md @@ -2,7 +2,7 @@ **Status**: Accepted (adversarial review round 1 complete — Fable 5, 2026-08-06; five defects found and repaired, see Review below. GPT-5.6-Sol could not run: codex usage limit. A second independent reviewer is still owed.) **Date**: 2026-08-06 -**Updated**: 2026-08-06 +**Updated**: 2026-11-05 **Authors**: Claude Code (Opus 5), directed by Stuart Kerr **Prompted by**: Two consecutive hosted-build failures for `PolymathWizard/BHIL-Colophon-Spec` (runs [30857458852](https://github.com/stuinfla/Repo-Explainer/actions/runs/30857458852), @@ -11,17 +11,28 @@ two complete pages rendered, **nothing delivered to the requester** **Supersedes**: None **Related ADRs**: ADR-0005 (Station recipe), ADR-0006 (comprehension ladder), ADR-0007 (source identity invariant), ADR-0008 (every image teaches / INV-22) -**Code touchpoints**: `tools/deploy.mjs` (ship-bar rail), `bin/agentic-runner.mjs` (cure stage, +**Code touchpoints**: `tools/deploy.mjs` (integrity refusals only), `bin/agentic-runner.mjs` + `bin/cure.mjs` (cure stage, failure path), `tools/notify.mjs` / `tools/notify-failure.mjs` (delivery), `tools/quality-grade.mjs` (scorecard is unchanged — only its *consequence* changes) --- +> **Note (3.0.1, 2026-11-05) — verified against code.** (1) Deploy refuses only on integrity: an unassembled +> page, a source-identity violation (when the pin is armed), a site-integrity failure (`src/site-check.mjs`), +> or no scorecard with no recorded reason. (2) The ship-bar rail is gone and no force-deploy escape hatch exists +> in `tools/deploy.mjs`; the recorded `quality.graderUnavailable` is the only no-scorecard path. (3) The cure +> stage is `bin/cure.mjs` (`classifyEndState`): it classifies how a hosted build ended, runs at most one +> bounded cure with an independent agent (only for a near-miss: diffuse mediocrity gets the honest "no cure"), and redeploys only a strictly better verdict. There is no manual-fix +> escape: a build the cure stage cannot improve stays as delivered (`tests/cure.test.mjs`). (4) `quality.gateRefusal` +> records why a free pre-check (INV-20 / INV-24) refused. (5) The identity pin is still armed on the hosted +> door only (the honesty note in D1 remains true). + ## Context -The ship-bar rail is binary. `tools/quality-grade.mjs:350` (`evaluateShipworthy`) returns +*(Context as of 2026-08-06, before this ADR.)* The ship-bar rail was binary. `evaluateShipworthy` in +`tools/quality-grade.mjs` returns pass/fail on `mean >= 82 && min >= 70 && SHIP_OPERATORS.every(YES)`, and -`tools/deploy.mjs` refuses to publish on `false`. A refusal is terminal: the run exits 1, +`tools/deploy.mjs` then refused to publish on `false`. A refusal is terminal: the run exits 1, the assembled page is uploaded as a private Actions artifact with 7-day retention, and the requester receives a failure email containing no page and no link. @@ -44,7 +55,7 @@ page existed. It was rendered, graded, and thrown away. The Aug 4 build was killed by a single axis — **B5 (imagery craft) = 55 on desktop**, with every other axis between 88 and 94 and a mean of 88. B5 was capped at 55 by the INV-22 raster rule, which fires only when a raster fails **both** the takeaway test *and* the swap -test (`tools/quality-grade.mjs:149`). +test (the INV-22 cap in the `tools/quality-grade.mjs` rubric). The raster in question (`assets/problem.png`, inspected directly) renders its brief faithfully: labelled binders (`ACME-2026-Q3`, `RUBICON-2026-Q1`), a legible handwritten @@ -96,7 +107,7 @@ renders is a page that ships. > hosted path, unarmed on the local path, and closing that is tracked work — not a claim to make in > the present tense. -**A recorded grader OUTAGE is deliverable; a missing grade is not.** Before this ADR, `DEPLOY_FORCE` +**A recorded grader OUTAGE is deliverable; a missing grade is not.** Before this ADR, a human force-deploy flag (since deleted) skipped the entire quality block *including* the no-scorecard refusal, so a human could still ship during a vision-API outage. Removing the quality gate removed that escape too — leaving the stochastic judge holding a veto through its own **availability**, this ADR's thesis exactly @@ -176,10 +187,10 @@ hard versus which are mis-firing (as B5 did on 2026-08-04). | Alternative | Why rejected | |---|---| -| **Lower the ship bar** (e.g. `min >= 55`) | Dishonest — it renames failure as success and destroys the scorecard's diagnostic value. Rule 9 forbids it. Also fails to fix the real problem: *some* threshold still destroys value. | +| **Lower the ship bar** (for example, a minimum-axis floor of 55) | Dishonest — it renames failure as success and destroys the scorecard's diagnostic value. Rule 9 forbids it. Also fails to fix the real problem: *some* threshold still destroys value. | | **Preview-only URL for below-bar builds** | The customer cannot share what they paid for, which is most of the value. Rejected by the owner. | | **Quality banner on the page itself** | Degrades the artifact for every third party the owner shares it with. Rejected by the owner in favour of an honest email. | -| **Deliver only above a floor (mean ≥ 80)** | Keeps a category of paid-for-and-destroyed builds for no clear benefit. Rejected by the owner: deliver anything that renders. | +| **Deliver only above a floor (a mean floor of 80)** | Keeps a category of paid-for-and-destroyed builds for no clear benefit. Rejected by the owner: deliver anything that renders. | | **Retry until it passes** | Unbounded cost against a stochastic judge; already the failure mode the 3-call cap exists to prevent. | ## Verification @@ -213,9 +224,9 @@ the house recipe requires. A second round is still owed. | 2 | **Same-URL downgrade.** Every below-bar email invites a re-run; a re-run targets the same Netlify URL; the refine loop is known to regress. The old gate was accidentally a ratchet protecting delivered pages. | **Fixed.** Redeploy requires a strictly better verdict. | | 3 | **The honest note lied.** `notify.mjs` hardcoded "the rest scored well" unconditionally — worst exactly when the page was worst. | **Fixed.** Derived from the real scorecard. | | 4 | **Weakest-axis misattribution.** `passed:false` from an operator or INV-18 failure would blame an axis scoring 83 while an invisible diagram was the truth. | **Fixed.** A numeric axis below 70 wins when one exists; otherwise the non-numeric blocker is named. | -| 5 | **Grader outage = total delivery outage.** `DEPLOY_FORCE` used to cover the no-scorecard refusal. | **Fixed.** Recorded outages deliver, ungraded and stated. | +| 5 | **Grader outage = total delivery outage.** A force-deploy flag used to cover the no-scorecard refusal. | **Fixed.** Recorded outages deliver, ungraded and stated. | | 6 | **D4 was unimplemented** — the mechanism named as keeping the grader honest did not exist. | **Fixed.** See D4. | -| 7 | **The no-banner argument stops at the owner's preferred conclusion.** It treats "one soft axis" and "mean 45 with broken images" as one class, and never weighs the zero-cost middle option: an invisible machine-readable scorecard (meta tag / JSON-LD) on the page. | **Open.** The owner's decision on the visible banner stands; the machine-readable option is genuinely unconsidered and should be. | +| 7 | **The no-banner argument stops at the owner's preferred conclusion.** It treats "one soft axis" and "a failing mean with broken images" as one class, and never weighs the zero-cost middle option: an invisible machine-readable scorecard (meta tag / JSON-LD) on the page. | **Open.** The owner's decision on the visible banner stands; the machine-readable option is genuinely unconsidered and should be. | | 8 | **No content-security pass at the delivery boundary.** A hostile README that prompt-injects the `bypassPermissions` agent yields a page that assembles, grades well, and ships publicly. Not a regression — but this boundary now explicitly claims to be *the* delivery gate, and house Rule 8 (AIMDS) is unapplied here. | **Open.** Pre-existing; newly load-bearing. | | 9 | **"Removing the gate doesn't weaken honesty" is not self-evidently true.** The scorecard stays honest; nothing forces anyone to *read* it. D4 now creates the record, but no one is yet required to look at it. | **Partly addressed.** D4 exists; a standing review of below-bar distributions does not. | diff --git a/docs/adr/0012-deterministic-rails-before-the-stochastic-judge.md b/docs/adr/0012-deterministic-rails-before-the-stochastic-judge.md index 7411ddf..186041d 100644 --- a/docs/adr/0012-deterministic-rails-before-the-stochastic-judge.md +++ b/docs/adr/0012-deterministic-rails-before-the-stochastic-judge.md @@ -2,7 +2,7 @@ **Status**: Accepted (adversarial review round 1 — Fable 5, 2026-08-06. Findings 2–5 resolved by moving the form pin; see "The pin was on the wrong diagram". GPT-5.6-Sol could not run: codex usage limit, so a second reviewer is still owed.) **Date**: 2026-08-06 -**Updated**: 2026-08-06 +**Updated**: 2026-11-05 **Authors**: Claude Code (Opus 5), directed by Stuart Kerr **Prompted by**: The INV-23 form collision that failed `PolymathWizard/BHIL-Colophon-Spec` twice — discovered by a ~$0.30 vision call at the refine cap, when a 20-line function could have prevented it @@ -10,11 +10,15 @@ for $0 before a single pixel rendered **Supersedes**: None **Related ADRs**: ADR-0005 (Station recipe), ADR-0008 (every image teaches / INV-22), ADR-0011 (the gate advises, never destroys) -**Code touchpoints**: `tools/make-diagrams.mjs` (`FORM`, `resolveForms`, `flowRowsFromModel`), +**Code touchpoints**: `tools/diagrams/models.mjs` (`FORM`, `resolveForms`), `tools/diagrams/concept.mjs` (`renderConcept`), `tools/make-diagrams.mjs` (slot assembly), `tools/quality-grade.mjs` (INV-20 acronym gate — the existing precedent), `tests/diagram-form-diversity.test.mjs` --- +> **Note (3.0.1, 2026-11-05).** Every diagram is now also drawn as a 360px phone twin, and `make-diagrams` +> fails if any label on it would be under 11px on a 390px phone (ADR-0014). The form-family resolver and the +> pre-render collision check described here are unchanged. + ## Context The quality rubric mixes two kinds of criteria, and the pipeline currently pays the same price for both: @@ -157,7 +161,7 @@ vision model every build. The vision grader's budget belongs to judgements only |---|---|---| | 1 | **The taxonomy has two linear-chain families.** `vertical-stack` and `horizontal-run` are the same *information shape* — a chain of cards joined by arrows, rotated 90°. The rubric's own vocabulary (`quality-grade.mjs`, check (c)) names the shapes "containment, journey, field, fan"; both of ours are **journey**. So the resolver can guarantee distinctness in *its* taxonomy while the judge scores in a *different* one — and they may disagree on exactly the pair the resolver most often emits (grounded architecture + demoted flow). There is also no `field`/`grid` family at all. | **Open, and now measurable.** See the risk note below. | | 2 | **The flow demotion loses the page's densest information**, and a 6-item single-row ribbon is ~1,380px wide — illegible when fit to a 390px phone. | **MEASURED AND CONFIRMED, then mitigated.** Rendered for real: ribbon 3 items=731px, 4=949px, 5=1167px, 6=1385px; every other archetype stays portrait at any length (orbit 806px, strata 824px for the same chain). At 390px fit-to-width a 1385px ribbon renders 13px labels at **3.66px**, against the 568px grounded architecture diagram that graded as legible — 2.4x the width, ~40% the text size. `RIBBON_MAX_ITEMS = 3` now keeps a long chain off the ribbon entirely. The IN/OUT loss is unmitigated and stands as debt. | -| 3 | **The demotion satisfies check (c) by feeding check (d).** "Stages-in-boxes with arrows is a list, not a flow" is precisely what `flowRowsFromModel` + `conceptRibbon` produce. | **Open.** | +| 3 | **The demotion satisfies check (c) by feeding check (d).** "Stages-in-boxes with arrows is a list, not a flow" is precisely what the ribbon form of `renderConcept` produces (these were `flowRowsFromModel` + `conceptRibbon` when this was written; neither name exists now). | **Open.** | | 4 | **The dominant alternative was never considered.** `archModel` already computes a `hub`; a grounded *radial* architecture plus a grounded vertical `renderFlow` keeps BOTH diagrams fully grounded with zero demotion. That strictly dominates demoting flow, and appears nowhere in the alternatives table. | **Open — this is probably the right answer.** | | 5 | **`conceptStrata` silently drops `connect` semantics.** A demoted architecture authored as a chain (`cli → router → parser`, `connect:true`) renders as concentric nested frames — asserting *containment*, which is false — while the `asciiFallback` for the same diagram still says `cli → router → parser`. The pixels and the accessible text describe different structures. | **Open — a correctness bug, not a taste issue.** | | 6 | **D5 was violated by its own commit.** The INV-22 cap shipped as a prompt plea asking the model that already botched the arithmetic to redo it in the right order. | **Fixed.** Verdicts are now structured output (`rasters[].takeaway/.swappable`) and the cap is arithmetic in `applyRasterCap`, with grader/arithmetic disagreements logged rather than invisible. `tests/raster-cap.test.mjs`. | @@ -217,9 +221,14 @@ Result: **four grounded-or-authored diagrams, four distinct families, zero demot |---|---|---|---| | architecture | `radial` | `renderArchitectureRadial` | real dep-graph, hub, dependent counts, externals | | flow | `vertical-stack` | `renderFlow` | real entrypoints, with IN/OUT per stage | -| big idea | `containment` | `conceptStrata` | -| `grid` | `conceptGrid` — a wrapped **field** (added 2026-08-06) | brain-authored rows | -| insight | `horizontal-run` | `conceptRibbon` | brain-authored rows | +| big idea | `containment` | `conceptStrata` | brain-authored rows | +| insight | `grid` | `conceptGrid` — a wrapped **field** (added 2026-08-06) | brain-authored rows | + +*(This table is the 2026-08-06 resolution on one real build. It is not a fixed assignment: the resolver +(`resolveForms`, `tools/diagrams/models.mjs`) picks the first free family from each slot's preference +list. As of 3.0.1 those lists are architecture `strata, orbit, grid, ribbon, column`; flow `ribbon, +column, grid, strata, orbit`; big idea `ribbon, grid, column, orbit` (it never claims containment from its +own wording); insight `orbit, ribbon, grid, strata, column`. A ribbon is only offered for a short chain.)* ### What the geometry cost, and what fixed it diff --git a/docs/adr/0013-motion-that-performs-the-argument.md b/docs/adr/0013-motion-that-performs-the-argument.md index 6e38ccd..fee9512 100644 --- a/docs/adr/0013-motion-that-performs-the-argument.md +++ b/docs/adr/0013-motion-that-performs-the-argument.md @@ -1,9 +1,21 @@ # ADR-0013 — Motion that performs the argument (the hero scene, and where 3D belongs) -Status: Accepted + Implemented +Status: Accepted + Implemented, including the local door authoring the scene (3.0.1); not yet validated against a live model at scale. Date: 2026-09-17 +Updated: 2026-11-05 Amends: ADR-0005 (skill-based recipe), ADR-0008 (every image teaches) +> **Note (3.0.1, 2026-11-05).** Verified: `tools/make-diagrams.mjs` installs `visuals.heroAnim.sceneSvg` and refuses +> it without a `viewBox`, real animation or a `prefers-reduced-motion` end state, and it checks the scene's +> phone layout against the 11px floor. The scene is still **optional**: a build that authors none gets the chips +> band or no band on the hosted door. **On the local door the brain now authors the scene** (`src/brain.mjs` +> `settleHeroScene`): it is validated by `tools/diagrams/scene.mjs` (viewBox, real animation, reduced-motion +> end state, scoped ids, no scripts or external refs, 11px phone text floor, xmllint, 25 KB), gets ONE repair +> pass, and otherwise falls back with `visuals.heroAnimSkipped.reason`. A valid scene replaces the raster hero +> (`hero.rasterSkipped: 'scene'`; `generate-image` skips it, a static backdrop feeds the favicon and share card). +> Both routes meet the same strict contract: `sceneMarkup` (the local brain, inline) and `sceneSvg` (a file the hosted agent writes) are checked by the same validator in `make-diagrams`. +> The scene is the only SVG the brain still authors; the four diagram slots are drawn by `make-diagrams` (ADR-0012, ADR-0014). + ## Context The owner asked for "a little bit of a flourish" and, twice, specifically about Three.js. Measured on diff --git a/docs/adr/0014-story-diagrams-verified-claims.md b/docs/adr/0014-story-diagrams-verified-claims.md index f31f3fe..adde0ad 100644 --- a/docs/adr/0014-story-diagrams-verified-claims.md +++ b/docs/adr/0014-story-diagrams-verified-claims.md @@ -2,8 +2,16 @@ Status: Accepted + Implemented (renderers, verifier, `make-diagrams` wiring, brain schema, tests); **not yet validated across a corpus of real builds** — see Consequences. Date: 2026-10-10 +Updated: 2026-11-05 Amends: ADR-0005 (Station 4), ADR-0012 (grounded radial architecture), INV-23 (every image teaches) +> **Note (3.0.1, 2026-11-05) — the "mobile legibility is the known weakness" consequence below is addressed.** +> Every story diagram is now drawn twice from the one verified model, wide and as a 360px phone twin +> (`src/story-diagrams-mobile.mjs`; `tools/diagrams/story.mjs`), and `make-diagrams` fails the step if any +> label on the twin would be under 11px on a 390px phone (`mobileLabelPx`, `MOBILE_FLOOR_PX` in +> `tools/diagrams/legibility.mjs`). Still true: the story diagrams have been exercised on few real builds, so +> the corpus-level claim in Consequences remains unmeasured. + ## Context The owner reviewed the architecture and flow graphics the pipeline produced for `realiti4/claude-swap` @@ -64,10 +72,7 @@ external references. ## Consequences -- **Mobile legibility is the known weakness.** Both canvases are ~1100 px wide; on a 312 px column - the 13 px labels render near 3.7 px. The page's tap-to-zoom lightbox covers it for now, and - `legibilityOf` does not see CSS-sized text, so these report `null`. A portrait layout is the - follow-up; do not claim mobile parity until it exists. +- **Mobile legibility was the known weakness (addressed in 3.0.1, see the note above).** When this ADR was written both canvases were ~1100 px wide and the 13 px labels rendered near 3.7 px on a 312 px column. Each story diagram now has a 360px phone twin and the 11px floor is enforced by `make-diagrams`. - **Not yet validated on a corpus.** Two repos' worth of evidence exists (claude-swap, hand-authored). Whether the brain authors good `systemMap` / `decision` models unprompted across many repos is unmeasured. The fallback keeps that safe; the gain is unproven until measured. diff --git a/docs/adr/0015-readme-outreach-issue-first.md b/docs/adr/0015-readme-outreach-issue-first.md index 6dea18e..4a096a8 100644 --- a/docs/adr/0015-readme-outreach-issue-first.md +++ b/docs/adr/0015-readme-outreach-issue-first.md @@ -3,9 +3,23 @@ Status: Accepted + Implemented (station, CLI, ledger, tests). **Response rates are not yet known** — the tracking exists to find out; no claim is made that this works until it has been measured. Date: 2026-10-10 +Updated: 2026-11-05 Amends: ADR-0005 (Station 8b readme-enhance) Builds on: ADR-0014 (the diagrams it sends are the per-repo story diagrams) +> **Follow-up rule (3.0.1, 2026-11-05) — verified against code.** +> - **One check-in, 7 days later, run by the owner.** Nothing schedules it: `explainmyrepo outreach followup` posts at most one short note per issue, +> `OUTREACH_FOLLOWUP_DAYS` (default 7) after our last contact, and stays silent if they replied or closed it +> (`src/outreach-followup.mjs`). +> - **A maintainer email is drafted for the OWNER only.** `tools/readme-enhance.mjs` sends the owner a review copy +> with a draft addressed to a public commit address, marked NOT sent; nothing is ever mailed to the maintainer. +> (Decision 4, "never email", therefore still holds for the maintainer.) +> - **Issue first, on by default.** The station opens an issue; the PR comes through +> `outreach open-pr `, which requires an issue already on record for that repo +> (`src/outreach-cli.mjs`), or only when the operator sets `README_OUTREACH=pr` explicitly. One contact per repo, a daily cap of 5, additions only, every send in the ledger. +> - **Door.** `readme-enhance` is `doors: ['local']` in `src/stations.mjs`: the hosted agent never runs it +> (it has no GitHub write token and the hosted brief does not mention the station). + ## Context Station 8b could offer a source repo's maintainer a better README as a pull request, but it was gated diff --git a/docs/adr/0016-ask-this-project.md b/docs/adr/0016-ask-this-project.md index 25136a3..be2f4d4 100644 --- a/docs/adr/0016-ask-this-project.md +++ b/docs/adr/0016-ask-this-project.md @@ -1,13 +1,26 @@ -# ADR-0016 — "Ask this project": a written, cited answer box on every explainer +# ADR-0016 — "Ask this project": a written, cited answer box on local-door explainers Status: Accepted + Implemented (station, central service, deploy gate, tests). **Answer quality at scale is not yet measured** — it was checked on one repo (REA) with 11 reader-style questions, not across repos. Date: 2026-10-16 +Updated: 2026-11-05 Amends: ADR-0005 (adds Station 6c `make-ask`; `deploy` gains a site-integrity gate) Version: ships in 3.0.0 Prior-decision check: the recorded-decision recall timed out, so that history is UNKNOWN. Reading `docs/adr/` 0005–0015 and searching them for an on-page chat or ask box found nothing to conflict with or supersede. +> **Amended (3.0.1, 2026-11-05) — verified against code.** +> - **Local door only for now.** `make-ask` is `doors: ['local']` in `src/stations.mjs`; hosted-door pages do not +> get an Ask box yet. The title and the "every explainer" wording below describe the intent, not today's reach. +> The note under "Consequences / open" about the hosted runner's `ASK_SIGNING_SECRET` applies only once the hosted door adds the station. +> - **AIMDS guard, fail closed** (`ask-service/lib/guard.mjs`, `@claude-flow/aidefence`): the +> question is scanned before any spend, the answer before the visitor sees it; any scanner error blocks. +> - **Answers are buffered, not streamed**, so a scanned answer is the only thing a visitor can receive. +> - **Who signs and who verifies.** `src/ask-token.mjs` only **signs**; the service verifies +> (`verifyToken` in `ask.mjs`), because the two are separate deploys. `tests/ask.test.mjs` runs them against each +> other. Decision 3's "(`src/ask-token.mjs`)" names the signer. +> - The default answer model is `anthropic/claude-haiku-5.5` (`ASK_MODEL`). + ## Context An explainer answers the questions its author anticipated. A reader's next question — "does it work with X?", diff --git a/docs/ddd/alive-kit-domain.md b/docs/ddd/alive-kit-domain.md index e2ee6ce..f6d02cc 100644 --- a/docs/ddd/alive-kit-domain.md +++ b/docs/ddd/alive-kit-domain.md @@ -1,7 +1,7 @@ # DDD — The Alive Kit domain (companion artifacts) **Paired ADR:** [ADR-0009](../adr/0009-alive-kit-local-companions.md) -**Status**: Accepted · **Date**: 2026-07-17 · **Updated**: 2026-07-17 +**Status**: Accepted · **Date**: 2026-07-17 · **Updated**: 2026-11-05 ## Bounded contexts @@ -41,24 +41,24 @@ Capability { } ``` -**Invariants** (numbered continuing the core DDD's INV series, which ends at INV-23). Three are +**Invariants** (numbered INV-29 to INV-33; renumbered on 2026-11-05 because the old INV-24 clashed with the ReadsAtFifteen gate, old to new: 24 to 29, 25 to 30, 26 to 31, 27 to 32, 28 to 33). Three are mechanically enforced; two are conventions with a named human enforcement point — the doc set is honest about which is which (the ADR's Consequences section says registry upkeep is a discipline; these labels agree with it): -- **INV-24** `advertised ⇒ status == verified` — MECHANICAL: the CLI renders availability only +- **INV-29** `advertised ⇒ status == verified` — MECHANICAL: the CLI renders availability only from the registry (`bin/explainmyrepo.mjs`), so there is no second list to drift; the registry schema itself is checked by `tests/capabilities-registry.test.mjs`. -- **INV-25** `status == verified ⇒ receipts + verifiedAt present, entry exists` — MECHANICAL: +- **INV-30** `status == verified ⇒ receipts + verifiedAt present, entry exists` — MECHANICAL: `tests/capabilities-registry.test.mjs` fails the suite on violation, so a receipt-less promotion cannot land through a green build. Promotion and receipts land in the same commit. -- **INV-26** **hosted context never loads a companion** — MECHANICAL: every companion entry tool +- **INV-31** **hosted context never loads a companion** — MECHANICAL: every companion entry tool exits at startup when `CI`/`GITHUB_ACTIONS` is set, and the hosted runner has no invoking code path. -- **INV-27** **companions are fail-open** — CONVENTION, enforced by placement: no companion is +- **INV-32** **companions are fail-open** — CONVENTION, enforced by placement: no companion is wired between GRADE and SHIP, so a companion's non-zero exit cannot change the page, the verdict, or the deploy. Guarded at review time whenever the pipeline's station map changes. -- **INV-28** **read-only consumption** — CONVENTION, enforced at code review of each companion +- **INV-33** **read-only consumption** — CONVENTION, enforced at code review of each companion tool: a companion never mutates BuildArtifacts; outputs are additive (`trailer-project/`, `renders/`, `deck/`). Current tools honor it (`make-trailer.mjs` copies assets out and writes only its own project dir). diff --git a/docs/ddd/explainmyrepo-recipe-domain.md b/docs/ddd/explainmyrepo-recipe-domain.md index 8906148..75e0aa5 100644 --- a/docs/ddd/explainmyrepo-recipe-domain.md +++ b/docs/ddd/explainmyrepo-recipe-domain.md @@ -1,8 +1,14 @@ # Repo Explainer (Recipe) — Domain-Driven Design Model -**Version:** 1.2.0 +> **HISTORICAL (2026-11-05).** This is the original domain model from June 2026 and is kept for its reasoning. +> It is **not** a description of the current code: it predates the single station table (`src/stations.mjs`), +> the two doors, the SHIP/EXEMPLARY tiers and the advising gate (ADR-0011), `make-pack` replacing +> `make-dropin`, and the Ask box (ADR-0016). For what the tools read and write today, use +> `tools/CONTRACT.md`; for the stations, `src/stations.mjs`; for the decisions since, `docs/adr/`. + +**Version:** 1.2.1 **Created:** 2026-06-28 -**Updated:** 2026-06-29 (v1.2.0 — quality-bar reconciliation + implementation-experience, owner-signed: +**Updated:** 2026-11-05 (v1.2.1 — historical banner, superseded invariants marked inline); 2026-06-29 (v1.2.0 — quality-bar reconciliation + implementation-experience, owner-signed: the ≥95-on-every-axis floor → the exemplar-anchored bar `meanScore` ≥ 90 AND `headlineScore` (MIN) ≥ 85; a new five-question binary **operator qualitative gate** (the owner's words, all must be YES); a new scored axis **A6 Implementation-confidence**; invariants **INV-18 ArchitectureAndFlowRequired** + **INV-19 @@ -405,7 +411,7 @@ ArtDirectionBrief { metaphor: VisualMetaphor // e.g. "prism" (PhotonLayer), "evidence dossier" (ruvn) palette: Palette // colours chosen to fit the metaphor typePersonality:TypePersonality // type that carries the metaphor's voice - layoutRhythm: SectionArchetype[] // ordered archetypes → the page's cadence + layoutRhythm: SectionArchetype[] // (removed from the code; no longer authored or read) heroConcept: HeroConcept // the single emotional opening image idea copyVoice: CopyVoice // tone/register for all authored text } @@ -585,7 +591,7 @@ checkpoint cue is satisfied with positive evidence (fail loud, never silent — | # | State (Station) | Checkpoint cue (loud postcondition) | |---|---|---| | 0 | `Validating` | URL parsed; TargetRepo reachable (incl. private/own, authenticated) — or stop with a clear reason. | -| 1 | `Understanding` | `kb/build-kb.mjs` wrote the canonical `-kb.rvf` (explicit `embed` block set — not `.small.rvf`); it answers "what is this repo?" correctly; repo named correctly; the three structured JSONs (`-symbols.json` / `-dep-graph.json` / `-entrypoints.json`) exist; **the authored `-primer.md` exists** (without it the S6 pack builder hard-fails at its line-79 `must()`). | +| 1 | `Understanding` | `kb/build-kb.mjs` wrote the canonical `-kb.rvf` (a target must carry an `embed` block; the `.small.rvf` suffix no longer exists); it answers "what is this repo?" correctly; repo named correctly; the three structured JSONs (`-symbols.json` / `-dep-graph.json` / `-entrypoints.json`) exist; **the authored `-primer.md` exists** (it is the for-humans half of the pack). | | 2 | `Conceiving` | `ArtDirectionBrief` is specific to THIS repo; the metaphor fits. | | 3 | `Authoring` | All arc questions answered; zero placeholder text; every claim traceable to a KB passage. | | 4 | `Visualizing` | Every raster rung valid + HTTP 200 (gpt-image-2, the verified primary); every structural rung valid SVG (ascii-to-svg, xmllint-clean); each answers its arc question at the right altitude. | @@ -803,13 +809,13 @@ These hold for every Build. The aggregate (§7) or a context boundary enforces e - **INV-01 — Build isolation.** Each Build is self-contained with its own per-build deploy target; Builds never share mutable state. -- **INV-02 — Responsive-great-verified.** A Build passes only with both viewports (390 + 1440) +- **INV-02 — Responsive-great-verified.** *(Both viewports are still graded; the bar is now the two tiers in ADR-0011.)* A Build passes only with both viewports (390 + 1440) clearing the bar (mean ≥ 90, min ≥ 85, five operator YES) on real screenshots. - **INV-03 — Quarantine of long-async/optional steps.** Studio (or any optional long-async step) is quarantined and optional; it NEVER blocks or sinks the core (StudioQuarantine). - **INV-04 — Never fail silently.** Every station has a loud postcondition (its checkpoint cue); any failure surfaces inline AND by email. A station that advances without evidence is a defect. -- **INV-05 — Never ship below the exemplar bar.** The completion criterion (owner-signed 2026-06-29): +- **INV-05 — Never ship below the exemplar bar.** *(SUPERSEDED, ADR-0011: the gate advises. Below-bar pages ship with disclosure; ship tier is mean 82 / min 70 with five ship operators, exemplary is mean 90 / min 85 with all six. Deploy refuses only on integrity.)* The completion criterion (owner-signed 2026-06-29): on BOTH devices, `meanScore` ≥ 90 AND `headlineScore` (MIN of the eleven A1–A6/B1–B5 axes) ≥ 85 AND all five `operatorQuestions` true. Anchored to the owner's own example sites (~88 headline / ~92 mean); a literal "95 on every axis" is unreachable by an honest grader and would reject those exemplars. The @@ -821,8 +827,8 @@ These hold for every Build. The aggregate (§7) or a context boundary enforces e for-AI half (`.rvf` + `.passages.jsonl` + `.ids.json` + the three structured indexes `-symbols.json` / `-dep-graph.json` / `-entrypoints.json` so all four MCP tools return data, + `ask-kb.mjs` + `kb-mcp-server.mjs`) AND the for-humans half (the authored - `-primer.md`) — built by the **studio-less** variant of `kb/make-dropin.mjs` (§6.5). -- **INV-08 — One-source-of-truth.** All three adapters call the identical Brain/Skill; no adapter + `-primer.md`) — built by `tools/make-pack.mjs` *(was `kb/make-dropin.mjs`, deleted)*. +- **INV-08 — One-source-of-truth.** *(SUPERSEDED: two brains, held in step by tests, `tests/two-doors-conform.test.mjs`. The local door authors through `src/brain.mjs`, the hosted door follows `skills/explainmyrepo/SKILL.md`.)* All three adapters call the identical Brain/Skill; no adapter contains explainer logic of its own. - **INV-09 — Brain/Tools split.** Tools are pure, receive only their args, return `{ ok | loud failure }`, and never read the `BuildContext` or another tool's files. @@ -838,13 +844,13 @@ These hold for every Build. The aggregate (§7) or a context boundary enforces e - **INV-14 — ShipsSocialCard.** Every Page ships Open Graph + Twitter Card (`summary_large_image`) meta pointing at a designed **1200×630** social card (tagline baked in) plus the full favicon set (favicon + apple-touch-icon + standard sizes). Verified at Brand & Social (S5) + Assembly (S6). -- **INV-15 — StructuralDiagramsAsSVG.** The structural/explanatory ladder rungs (big-idea, the +- **INV-15 — StructuralDiagramsAsSVG.** *(Still true; the SVGs are now drawn by `tools/make-diagrams.mjs`, not the `ascii-to-svg` skill.)* The structural/explanatory ladder rungs (big-idea, the "aha" insight, architecture, flow, quickstart, pack) are SVG via `ascii-to-svg` (xmllint-clean, ASCII fallback) — never raster — and the SAME SVGs are shared by the Page and the README PR. -- **INV-16 — SourceRepoTouchedViaPROnly.** Any change to the TargetRepo (README enhancement + +- **INV-16 — SourceRepoTouchedViaPROnly.** *(SUPERSEDED, ADR-0015: an issue first, a PR only after a yes.)* Any change to the TargetRepo (README enhancement + source-repo SEO suggestions) is OPTIONAL, offered, and delivered ONLY as a pull request — never a direct push. It is quarantined (INV-03) and NEVER blocks, gates, or sinks the core. -- **INV-17 — VerifiedImagePrimary.** Raster generation uses **`gpt-image-2` as the verified +- **INV-17 — VerifiedImagePrimary.** *(SUPERSEDED: `gpt-image-2.5-flare` at xhigh, then `gpt-image-2`, then Grok; see ADR-0008.)* Raster generation uses **`gpt-image-2` as the verified primary** (`GET /v1/models/gpt-image-2` → HTTP 200, confirmed 2026-06-28); **`gpt-image-1` is the fallback ONLY**, used solely if a **build-time availability probe** of `gpt-image-2` (at Station 4) fails. The build never silently downgrades and never treats gpt-image-2 as unproven. @@ -909,7 +915,7 @@ kb/ ← REUSED, NOT REBUILT (P3) — one g entrypoints.mjs → Station 1: writes -entrypoints.json (pack prerequisite) index-primer.mjs → Station 1: indexes the authored -primer.md into the store ask-kb.mjs → grounding retrieval (INV-06) - make-dropin.mjs → Assembly (Station 6): builds the AIKnowledgePack via its --no-studio variant (INV-07) + make-dropin.mjs → [REMOVED in 3.0.1 — historical; the pack is now built by tools/make-pack.mjs] (INV-07) kb-mcp-server.mjs → the MCP server shipped inside the pack (4 tools; 3 read the structured JSONs) www/ ← thin website door (validate → run core) diff --git a/docs/prompts/codex-explainer-build.md b/docs/prompts/codex-explainer-build.md index ba43734..6d6569b 100644 --- a/docs/prompts/codex-explainer-build.md +++ b/docs/prompts/codex-explainer-build.md @@ -8,7 +8,7 @@ subscription, and Codex itself becomes the brain. Authoring and grading then cos the flat subscription you already pay for. This is not a new pipeline. It is the same skill (`skills/explainmyrepo/SKILL.md`) entered through -a different door, which is exactly what INV-08 ("one brain, many doors") anticipates. +a different host: the skill is the hosted door's brain, and Codex can run it the same way a headless agent does. --- @@ -25,18 +25,21 @@ The npx CLI knocks on the metered doors. A Codex session knocks on the subscript Codex is a coding agent, not an image model, so it does not produce imagery. It does not need to: `tools/generate-image.mjs` calls the OpenAI image API directly. Codex conducts, the tool paints. -Codex *does* accept image input (`codex --image`), so it can read the rendered screenshots and run -the Gate A/B quality grade itself. +Codex *does* accept image input (`codex --image`), so it can read the rendered screenshots and give its +own Gate A/B judgment as a second opinion. (`tools/quality-grade.mjs` still makes its own metered vision +call; see below.) ### What each step costs | Step | Engine | Cost | |---|---|---| -| Understand, author, grade | Codex on a ChatGPT subscription | $0 marginal | -| Embeddings for the KB | `bge-small-en-v1.5`, runs locally | $0 | -| Imagery (hero, problem, use-case) | `gpt-image-2` via the OpenAI API | cents per image | +| Understand, author, your own grade | Codex on a ChatGPT subscription | $0 marginal | +| The `quality-grade` tool's vision call | the vision model named by `QUALITY_VISION_MODEL`, via the OpenAI API | metered, per grading call | +| Embeddings for the KB | the model named in the target's `embed` block (`bge-small-en-v1.5` for registered targets), runs locally | $0 | +| Imagery (hero, problem, use-case) | `gpt-image-2.5-flare` at `xhigh`, falling back to `gpt-image-2`, via the OpenAI API | metered; the flare price is **unknown** (receipts say UNPRICED, never $0) | -Image generation is the only unavoidable metered spend, and it lands well under $1 per build. +Image generation and the tool's vision grading are the metered spend. Neither has a measured per-build total +for the flare engine, so no dollar figure is claimed here; read the build's receipt. --- @@ -146,18 +149,19 @@ Do NOT run tools/clone-repo.mjs and do NOT touch the network. Prepare the source Then resume at SKILL.md Station 1: register a "{{SLUG}}" target in kb/kb.config.mjs (copy an existing target's shape; set repoDir to the ABS path above and the embed block -to Xenova/bge-small-en-v1.5, 384-dim — SKILL.md explains why the explicit embed block is -required), run node tools/build-kb.mjs "$BUILD", author + index the primer, then proceed +to Xenova/bge-small-en-v1.5, 384-dim — build-kb refuses a target with no embed block), run node tools/build-kb.mjs "$BUILD", author + index the primer, then proceed concept → content → visual-brief → images/diagrams → assemble → grade. ── OVERRIDE 2: MODEL ROUTING (subscription first, minimise API) ────────────── YOU (Codex, on the ChatGPT subscription) do ALL authoring and ALL quality judgment: the primer, concept, content, visual briefs, and the Gate A/B + six operator questions. Images are made by tools/generate-image.mjs via OPENAI_API_KEY in .env — expected and -fine (a few cents each). For grading, run node tools/quality-grade.mjs "$BUILD" to RENDER -the 390px + 1440px screenshots; then OPEN those PNGs under "$BUILD/assets/" and grade them -YOURSELF against the verbatim Gate A/B rubric in SKILL.md, writing the quality slot. -Refine-loop until BOTH devices clear: mean ≥ 90, min axis ≥ 85, all six operator YES. +fine. For grading, run node tools/quality-grade.mjs "$BUILD": it renders the 390px + 1440px +screenshots AND grades them with its own metered vision call, writing the quality slot (there is no +render-only mode). Then OPEN those PNGs under "$BUILD/assets/" and judge them YOURSELF against the +verbatim Gate A/B rubric in SKILL.md as a second opinion; if you disagree with the tool, say so. +Refine-loop (the tool enforces a cap of 3 grading calls) aiming for the EXEMPLARY bar on BOTH devices: +mean ≥ 90, min axis ≥ 85, all six operator YES. The SHIP tier is mean ≥ 82, min ≥ 70. ── OVERRIDE 3: SHIP OR HOLD ────────────────────────────────────────────────── If the source repo is PRIVATE: stop after the quality gate passes. Do NOT run deploy, @@ -184,9 +188,10 @@ locally. ## Notes and limits -- **Private repos stay private.** Nothing is cloned and nothing is deployed under Override 3. The - source never leaves the machine except as imagery prompts, which describe the concept rather than - the code. +- **Private repos stay unpublished, not off the network.** Nothing is cloned and nothing is deployed under + Override 3, but the Codex session itself reads the source and sends it to OpenAI under your ChatGPT account; + the image prompts go to the image API; and `quality-grade` uploads screenshots of the built page (which + quote your source) to the OpenAI vision API. If the source must not reach OpenAI at all, do not use this flow. - **Grading calibration.** The numeric bar (mean ≥ 90, min axis ≥ 85) was tuned against the vision grader in `tools/quality-grade.mjs`. A different grader is a different harsh critic, so treat the first Codex-graded build as a recalibration point rather than a like-for-like score. diff --git a/explainer-agentic-qe/.gitignore b/explainer-agentic-qe/.gitignore deleted file mode 100644 index e985853..0000000 --- a/explainer-agentic-qe/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.vercel diff --git a/explainer-agentic-qe/index.html b/explainer-agentic-qe/index.html deleted file mode 100644 index 4472f6a..0000000 --- a/explainer-agentic-qe/index.html +++ /dev/null @@ -1,1039 +0,0 @@ - - - - - - Agentic QE Fleet — AI-powered quality engineering agents - - - - - - - - - - - - - -
-
-

- A plain-language explainer for - proffesor-for-testing/agentic-qe - by Dragan Spiridonov - (@proffesor-for-testing) - and contributors. - An independent walkthrough of the open-source project. -

-

- - Updated 2026-06-25 · source @ c092dce · v3.11.1 · MIT License -

-
-
- - -
- -
- - -
-
-
-
-

proffesor-for-testing · agentic-qe

-

Quality is
the product.

-

- Agentic QE Fleet is a free, open-source AI-powered quality engineering - platform. It deploys 60 specialized agents and - 75 skills that generate tests, find coverage gaps, - detect flaky tests, and learn your codebase patterns — across - 11 coding agent platforms. -

- - View on GitHub → -
- -
-
- - -
-
- -
-

This explainer is built from the public GitHub repository:

-

- https://github.com/proffesor-for-testing/agentic-qe -

-

- All source code, releases, and downloads linked from this page are - publicly available under the MIT License. No login required. -

-
- - GitHub Repo → - -
-
- - -
-
- - -
- - 01 - -

Why it was built

- The problem every team hits: tests that don’t keep up with code. -
- -
-
- -
- - - - Before Agentic QE vs. After - - - - Before: Manual QE - - Dev ships code - - - - Manual testwriting - - - - Coveragegaps - - - - ✗Tests fall behind — days to write by hand - ✗Flaky tests erode trust in CI - ✗Tool sprawl: SAST, coverage, linting = 5+ tools - ✗No pattern memory — every test starts from scratch - - - - - - - - - - - After: Agentic QE Fleet - - Dev ships code - - - - 60 AI agentsauto-generate - - - - 96%+ - - - - ✓Tests generated in seconds, not days - ✓ML-powered flaky test detection + fixes - ✓One fleet = 13 QE domains, one interface - ✓Pattern learning across sessions + projects - - -
Before: manual testing can't keep up with shipping speed. After: 60 AI agents auto-generate, analyze, and gate quality across the full surface.
-
-

- Every team ships faster than their tests can follow. New features - land daily; test suites fall behind. Coverage gaps hide in the - cracks. Flaky tests erode trust until the team stops reading CI - results. -

-

- Dragan Spiridonov built Agentic QE because - existing solutions attacked one slice of the problem — - generation or coverage or flakiness — but - never the whole surface. A coordinated fleet of AI agents, each - a specialist in one QE domain, can cover the full lifecycle: - generate, analyze, execute, learn, and gate. -

-

- The project is open-source (MIT), free to use, fork, and contribute - to. It is based on the Agentic QE Framework - created by Dragan Spiridonov. -

-

- - View the source → github.com/proffesor-for-testing/agentic-qe - -

-
-
- - -
- - 02 - -

What problem it solves

- Tests fall behind, coverage rots, flaky tests erode trust. -
- -
-
- -
- - - - Six problems AQE solves at once - Each one has a dedicated domain of specialized agents - - - - - - Test Generation Gap - Writing tests by hand takes days. - AQE generates them in seconds across - 15+ frameworks (Jest, pytest, JUnit...) - 4 agents - - - Coverage Blind Spots - Line-coverage says what ran, not what - matters. AQE does risk-weighted analysis - to prioritize the most impactful paths. - 2 agents - - - Flaky Tests - Tests that pass today and fail tomorrow. - ML-powered detection, root-cause analysis, - and automated stabilization. - 4 agents - - - - Pattern Amnesia - Every new test file starts from scratch. - AQE remembers patterns across sessions - and projects, improving over time. - 4 agents - - - Tool Sprawl - SAST here, coverage there, linter elsewhere. - AQE coordinates 60 agents across 13 - domains through one interface. - 13 domains - - - AI Cost Overhead - Sending everything to the biggest model - is expensive. TinyDancer routes to the - right tier: Haiku / Sonnet / Opus. - auto-routed - - - - Each problem mapped to a dedicated agent domain — all orchestrated by the Queen Coordinator - -
Six problems that plague every team's quality process, each addressed by a dedicated domain of specialized AI agents.
-
-

- Modern codebases grow faster than any human team can test. - Agentic QE attacks the full quality surface at once, not just - one slice. Each problem above maps to a dedicated agent domain - with specialists trained for that exact task. -

-
-
- - -
- - 03 - -

Why now

- Coding agents exist — now QE needs agents too. -
- -
-
- -
- - - - Three forces converging right now - - - - - Coding Agents Exist - Claude Code, Cursor, Copilot - accelerate dev 10x — - QE must keep pace - - - - MCP Standard - Model Context Protocol lets AI - tools share context and call - specialized servers - - - - Free Local Models - Ollama + open models = $0 - routine test gen, cloud only - when you need it - - - - - - - - - - aqe init --auto → 60 QE agents on call - -
Three technological forces converging: coding agents accelerate dev, MCP enables tool interop, free local models cut costs to zero for routine tasks.
-
-

- Coding agents like Claude Code, Cursor, and Copilot accelerate - development. Code output has increased 10x for many teams. But - quality engineering hasn’t kept pace. The MCP standard now - lets AI tools share context, and free local models make routine - test generation cost $0. -

-

- AQE plugs into all three: one aqe init --auto and your - coding agent has 60 QE specialists on call. No new IDE, no new - workflow. It meets developers where they already work. -

-
-
- - -
- - 04 - -

How it works

- A fleet of 60 specialized agents, coordinated by a Queen. -
- -
-
- -
- - - - - - - - How the Queen coordinates 60 agents - - - - YOUR REQUEST - "Generate tests for PaymentService with 95% coverage" - - - - - - - Queen Coordinator - Decomposes, spawns, coordinates, synthesizes - - - - - - - - - - - test-architect - Generate unit tests - Jest / Vitest / pytest - - - coverage-specialist - Risk-weighted gaps - - - property-tester - Edge case discovery - - - quality-gate - Anti-sycophancy - - - security-scanner - SAST/DAST sweep - - - - - - - - - - - Synthesized Result - 48 tests / 96.2% coverage / 78% pattern reuse - Grounded, gated, ready to commit - -
The Queen Coordinator decomposes your request, fans out to domain specialists running in parallel, then synthesizes results with quality gates.
-
- - - - - - - - - - - - - - - - - - - - -
DomainAgentsWhat they do
Test Generation4Generate tests, TDD workflows, mutation testing, property testing
Test Execution3Run tests in parallel, handle retries, integration testing
Coverage Analysis2Find untested code, prioritize by risk
Quality Assessment4Go/no-go gates, risk scoring, adversarial review
Defect Intelligence4Predict bugs, find root causes, fix flaky tests
Requirements2Validate testability, generate BDD scenarios
Code Intelligence4Knowledge graphs, semantic search, change impact
Security3SAST/DAST, compliance audits, exploit validation
Contracts2API contracts, GraphQL schema testing
Visual & A11y3Visual regression, WCAG compliance, viewport testing
Chaos & Performance3Fault injection, load testing, performance validation
Learning4Cross-project learning, pattern discovery, metrics
Enterprise7SAP, SOAP, ESB, OData, JMS/AMQP/Kafka
- - -
- - - - TinyDancer — Intelligent Model Routing - Automatically routes tasks to the right model tier to minimize cost - - - - Task - Any QE request - - - - - - - TinyDancer - Complexity scorer - 0–100 scale - - - - - - - - - Simple (0–20) - Haiku — type additions, refactors - $ - - - Moderate (20–70) - Sonnet — bug fixes, test gen - $$ - - - Critical (70+) - Opus — architecture, security - $$$ - - - - Free Tier Mode - AQE_FREE_TIER=1 - Route simple tasks - to local Ollama - $0 cost - -
TinyDancer scores task complexity (0–100) and routes to the cheapest model that can handle it. Free-tier mode uses local Ollama for routine tasks at $0.
-
-
-
- - -
- - 05 - -

What solved looks like

- Ask for tests and get them — generated, validated, gated. -
- -
-
- -
- - - - - - - - - - claude — agentic-qe - - - - $ - "Generate tests for src/services/PaymentService.ts with 95% coverage" - - [queen-coordinator] Decomposing task... - [queen-coordinator] Spawning: test-architect, coverage-specialist, property-tester, quality-gate - - [test-architect]Generating unit tests (Jest)... - [coverage-specialist]Analyzing risk-weighted gaps... - [property-tester]Discovering edge cases... - [quality-gate]Anti-sycophancy check: PASS (no tautological assertions) - - Generated 48 tests across 4 files: - - unit/PaymentService.test.ts(32 unit tests) - - property/PaymentValidation.property.test.ts(8 property tests) - - integration/PaymentFlow.integration.test.ts(8 integration tests) - - Coverage: 96.2% - | - Pattern reuse: 78% - | - Quality gate: PASS - - -
A real interaction: the Queen spawns 4 specialists in parallel, each handling their domain. Result: 48 tests at 96.2% coverage, quality-gated.
-
- -

75 Skills, Trust-Tiered

- -
- - - - 75 Skills — Trust Tiers - - - - Tier 3 — Verified - Full evaluation test suite, production-ready - 49 - - - - Tier 2 — Validated - Has executable validator - 7 - - - - Tier 1 — Structured - JSON output schema - 5 - - - - Tier 0 — Advisory - 5 - - - - 75 - total skills - 65% verified - -
75 skills rated by trust tier. 49 are fully verified with test suites. Tier-0 untested skills are excluded by policy.
-
-
-
- - -
- - 06 - -

Platform support

- One MCP server, 11 coding agent platforms. -
- -
-
- -
- - - - One MCP Server → 11 Platforms - - - - AQE MCP Server - npx agentic-qe mcp - - - - - Claude Code - - - - GitHub Copilot - - - - Cursor - - - - Cline - - - - OpenCode - - - - AWS Kiro - - - - - - - Kilo Code - - - Roo Code - - - OpenAI Codex CLI - - - Windsurf - - - Continue.dev - - - aqe init --auto --with-all-platforms — set up every platform in one command - -
One MCP server connects to 11 coding agent platforms. Set up all at once or add platforms one by one.
-
- -
# Set up all platforms at once
-aqe init --auto --with-all-platforms
-
-# Or add a platform later
-aqe platform setup cursor
-aqe platform list       # show install status
-aqe platform verify cursor  # validate config
- -

LLM Providers

-

- AQE’s HybridRouter auto-detects available providers. Set one - or more API keys and it picks the best route: -

-
    -
  • Claude (ANTHROPIC_API_KEY) — default
  • -
  • OpenAI (OPENAI_API_KEY)
  • -
  • Gemini (GOOGLE_AI_API_KEY) — free tier available
  • -
  • OpenRouter (OPENROUTER_API_KEY) — 300+ models
  • -
  • Ollama — local, free, offline
  • -
  • Azure OpenAI, Bedrock
  • -
-
-
- - -
- - 07 - -

How to start

- Three commands and you’re running. -
- -
-
- -
- - - - - - - 1 - Install - npm install -g agentic-qe - Public npm package. Free. MIT. - Works on macOS, Linux, Windows. - - - - - - - 2 - Initialize - cd your-project - aqe init --auto - Auto-detects tech stack + MCP. - - - - - - - 3 - Use it - "Generate tests for src/" - 60 agents available instantly - in your coding agent. - -
Three commands: install, initialize, use. MCP tools are available immediately in your coding agent.
-
- -
-

Quick Start

-
# Install globally from npm (public, free)
-npm install -g agentic-qe
-
-# Initialize your project (auto-detects tech stack, configures MCP)
-cd your-project && aqe init --auto
-
-# That's it — MCP tools are available immediately in Claude Code
-

- All packages are public on npm: - npmjs.com/package/agentic-qe -

-
- -

Alternative: Claude Code Plugin

-
# From a local checkout
-git clone https://github.com/proffesor-for-testing/agentic-qe.git
-claude --plugin-dir ./agentic-qe/plugins/agentic-qe-fleet
- -

Development Setup

-
git clone https://github.com/proffesor-for-testing/agentic-qe.git
-cd agentic-qe && npm install && npm run build && npm test -- --run
-

- - Full source on GitHub → github.com/proffesor-for-testing/agentic-qe - -

-
-
- - -
- - 08 - -

Use cases

- From test generation to chaos engineering to security audits. -
- -
-
-
-
- Test Generation -

Generate a full test suite

-

- qe-test-architect generates unit, integration, - property-based, and BDD tests across 15+ frameworks. -

-
"Create tests for PaymentService with 95% coverage"
-
-
- Coverage Analysis -

Find coverage gaps by risk

-

- qe-coverage-specialist finds untested code and - ranks it by risk, not line count. -

-
"Find coverage gaps in src/ and prioritize"
-
-
- Flaky Tests -

Hunt and fix flaky tests

-

- qe-flaky-hunter uses ML detection, root-cause - analysis, and stabilization fixes. -

-
"Stabilize flaky tests in tests/integration/"
-
-
- Security -

Security audit

-

- qe-security-scanner: SAST/DAST, dependency - scanning, API security, and chaos testing. -

-
"Run security scan on the auth module"
-
-
- TDD -

Red-Green-Refactor

-

- qe-tdd-specialist coordinates 5 subagents through - the full TDD cycle. -

-
"Implement UserAuth with full TDD cycle"
-
-
- Chaos Engineering -

Fault injection

-

- qe-chaos-engineer injects network partitions, - latency spikes, resource exhaustion. -

-
"Inject network partitions into order flow"
-
-
-
-
- - -
- - 09 - -

Get it

- All links are public. No login, no paywall, no lock-in. -
- -
-
-

- Everything about Agentic QE is publicly available. No Vercel login, - no gated downloads, no auth walls. Every link below goes to a - public URL you can access right now. -

- - - -

CLI Reference

-
aqe init [--auto]              # Initialize project
-aqe agent list                 # List available agents
-aqe fleet status               # Fleet health
-aqe learning stats             # Learning statistics
-aqe brain export/import        # Portable intelligence
-aqe platform list/setup/verify # Manage platforms
-aqe health                     # System health
-aqe code index src/            # Index codebase
-aqe code search "auth"         # Semantic search
-
-
- -
-
-
- - - - - - - diff --git a/explainer-agentic-qe/main.js b/explainer-agentic-qe/main.js deleted file mode 100644 index d5858df..0000000 --- a/explainer-agentic-qe/main.js +++ /dev/null @@ -1,27 +0,0 @@ -/* ============================================================================= - Agentic QE Explainer — main.js - Progressive enhancement only. The page is fully usable with JS disabled. - ========================================================================== */ -(function () { - "use strict"; - - /* --- 1. Deep-link a section open ---------------------------------------- */ - function openFromHash() { - var id = (location.hash || "").replace(/^#/, ""); - if (!id) return; - var el = document.getElementById(id); - while (el && el.tagName !== "DETAILS") el = el.parentElement; - if (el && !el.open) el.open = true; - } - window.addEventListener("hashchange", openFromHash); - openFromHash(); - - document.querySelectorAll('a[href^="#"]').forEach(function (a) { - a.addEventListener("click", function () { - var id = a.getAttribute("href").slice(1); - var sec = document.getElementById(id); - while (sec && sec.tagName !== "DETAILS") sec = sec.parentElement; - if (sec && !sec.open) sec.open = true; - }); - }); -})(); diff --git a/explainer-agentic-qe/styles.css b/explainer-agentic-qe/styles.css deleted file mode 100644 index 9501568..0000000 --- a/explainer-agentic-qe/styles.css +++ /dev/null @@ -1,535 +0,0 @@ -/* ============================================================================= - Agentic QE Explainer — FORGE / FLEET - Aesthetic: deep warm-charcoal substrate, amber/copper accents, industrial - display type, generous space. Adapted from Ruv-Explainer design system. - ========================================================================== */ - -/* ---- Google Fonts (CDN) --------------------------------------------------- */ -@import url('https://fonts.googleapis.com/css2?family=Big+Shoulders+Display:wght@600;900&family=IBM+Plex+Mono:wght@400&family=IBM+Plex+Sans:wght@400;500&display=swap'); - -/* ---- :root DESIGN TOKENS ------------------------------------------------- */ -:root { - --bg: #16120e; - --bg-2: #1d1812; - --panel: #241d15; - --panel-2: #2c2418; - --ridge: #3a2f1f; - - --amber: #ff9e2c; - --amber-hot: #ffb650; - --copper: #c2703a; - --copper-deep: #8a4a26; - --ember: #e8531f; - --brass: #d9a441; - - --ink: #f3e8d8; - --ink-2: #d6c5ac; - --muted: #9c8b72; - --faint: #6b5e49; - --on-amber: #1a1206; - - --line: rgba(217,164,65,0.14); - --line-strong: rgba(217,164,65,0.30); - --fill-amber: rgba(255,158,44,0.10); - --fill-copper: rgba(194,112,58,0.12); - - --shadow: 0 22px 48px -26px rgba(0,0,0,0.82); - --shadow-deep: 0 38px 90px -40px rgba(0,0,0,0.9); - --emboss: inset 0 1px 0 rgba(255,196,120,0.07), - inset 0 -1px 0 rgba(0,0,0,0.45); - --glow-amber: 0 0 0 1px rgba(255,158,44,0.25), - 0 14px 40px -16px rgba(255,158,44,0.32); - - --display: "Big Shoulders Display", "Arial Narrow", system-ui, sans-serif; - --sans: "IBM Plex Sans", system-ui, -apple-system, sans-serif; - --mono: "IBM Plex Mono", ui-monospace, "SF Mono", Menlo, monospace; - - --maxw: 1120px; - --gutter: clamp(20px, 5vw, 56px); - --radius: 14px; - --radius-s: 9px; - --ease: cubic-bezier(0.22, 0.61, 0.36, 1); -} - -/* ---- Reset / base --------------------------------------------------------- */ -*, *::before, *::after { box-sizing: border-box; } -html { -webkit-text-size-adjust: 100%; scroll-behavior: smooth; } - -body { - margin: 0; - background: var(--bg); - color: var(--ink); - font-family: var(--sans); - font-size: 16.5px; - line-height: 1.65; - -webkit-font-smoothing: antialiased; - text-rendering: optimizeLegibility; - background-image: - radial-gradient(1100px 620px at 78% -8%, rgba(255,158,44,0.10), transparent 60%), - radial-gradient(900px 700px at -10% 8%, rgba(194,112,58,0.08), transparent 55%), - linear-gradient(180deg, var(--bg) 0%, var(--bg-2) 100%); - background-attachment: fixed; -} - -img { max-width: 100%; height: auto; display: block; } - -a { - color: var(--amber); - text-decoration: none; - transition: color 0.18s var(--ease); -} -a:hover { color: var(--amber-hot); } -a:focus-visible, -summary:focus-visible, -button:focus-visible, -[tabindex]:focus-visible { - outline: 2px solid var(--amber); - outline-offset: 3px; - border-radius: 4px; -} - -/* ---- Layout --------------------------------------------------------------- */ -.wrap { width: 100%; max-width: var(--maxw); margin: 0 auto; padding: 0 var(--gutter); } - -/* ---- Type system ---------------------------------------------------------- */ -h1, h2, h3, h4 { - font-family: var(--display); - font-weight: 900; - line-height: 0.98; - letter-spacing: 0.005em; - margin: 0 0 0.5em; - text-transform: uppercase; -} -h1 { font-size: clamp(2.8rem, 8vw, 5.6rem); } -h2 { font-size: clamp(1.9rem, 4.4vw, 3rem); } -h3 { font-size: 1.5rem; font-weight: 600; letter-spacing: 0.01em; } -p { margin: 0 0 1rem; max-width: 68ch; color: var(--ink-2); } - -.eyebrow { - font-family: var(--mono); - font-size: 12px; - letter-spacing: 0.36em; - text-transform: uppercase; - color: var(--brass); - font-weight: 400; - margin: 0 0 14px; -} -.mono { font-family: var(--mono); } -.lede { font-size: 1.18rem; color: var(--ink); max-width: 64ch; } - -ol, ul { margin: 0 0 1rem; padding-left: 1.4em; max-width: 68ch; color: var(--ink-2); } -li { margin: 0 0 0.55em; } -li::marker { color: var(--copper); } -li strong { color: var(--ink); } - -pre.code-block { - font-family: var(--mono); - font-size: 0.85rem; - line-height: 1.6; - color: var(--amber-hot); - background: var(--bg); - border: 1px solid var(--line-strong); - border-left: 3px solid var(--copper); - border-radius: var(--radius-s); - padding: 16px 18px; - margin: 0 0 1rem; - overflow-x: auto; - box-shadow: var(--emboss); - max-width: 68ch; -} -pre.code-block code { - background: none; border: none; box-shadow: none; padding: 0; - font-size: inherit; color: inherit; white-space: pre; -} - -code, .cmd { - font-family: var(--mono); - font-size: 0.86em; - color: var(--amber-hot); - background: var(--fill-amber); - border: 1px solid var(--line-strong); - border-radius: 6px; - padding: 0.12em 0.45em; - box-shadow: var(--emboss); -} - -/* ---- Source repo banner --------------------------------------------------- */ -.repo-banner { - background: linear-gradient(96deg, var(--fill-amber) 0%, var(--panel) 100%); - border: 2px solid var(--amber); - border-radius: var(--radius); - padding: 18px 24px; - margin: 0 0 28px; - display: flex; - align-items: center; - gap: 16px; - flex-wrap: wrap; - box-shadow: var(--glow-amber), var(--emboss); -} -.repo-banner-icon { - font-size: 1.6rem; - flex: 0 0 auto; -} -.repo-banner-text { - flex: 1 1 auto; - min-width: 0; -} -.repo-banner-text p { margin: 0; color: var(--ink); } -.repo-banner-text .repo-url { - font-family: var(--mono); - font-size: 0.85rem; - color: var(--brass); - word-break: break-all; -} -.repo-banner-cta { - display: inline-flex; - align-items: center; - gap: 8px; - padding: 10px 20px; - background: linear-gradient(96deg, var(--amber-hot), var(--copper)); - color: var(--on-amber); - font-family: var(--display); - font-weight: 600; - font-size: 0.95rem; - letter-spacing: 0.02em; - text-transform: uppercase; - border-radius: 8px; - box-shadow: var(--glow-amber); - transition: transform 0.16s var(--ease), filter 0.16s var(--ease); - flex: 0 0 auto; -} -.repo-banner-cta:hover { - transform: translateY(-2px); - filter: brightness(1.07); - color: var(--on-amber); -} - -/* ---- Provenance / attribution banner -------------------------------------- */ -.prov-banner { - border-bottom: 1px solid var(--line); - background: - linear-gradient(180deg, rgba(44,36,24,0.55), rgba(29,24,18,0.45)); - backdrop-filter: blur(6px); - -webkit-backdrop-filter: blur(6px); -} -.prov-banner-inner { - display: flex; flex-wrap: wrap; align-items: center; - justify-content: space-between; gap: 10px 26px; - padding-top: 9px; padding-bottom: 9px; -} -.prov-attr { - margin: 0; max-width: none; - font-family: var(--sans); font-size: 12.5px; line-height: 1.5; - color: var(--muted); letter-spacing: 0.01em; -} -.prov-attr strong { color: var(--ink-2); font-weight: 500; } -.prov-attr a { color: var(--brass); } -.prov-attr a:hover { color: var(--amber-hot); } -.prov-live { - margin: 0; flex: 0 0 auto; - font-family: var(--mono); font-size: 11.5px; letter-spacing: 0.05em; - color: var(--faint); white-space: nowrap; - display: inline-flex; align-items: center; gap: 8px; -} -.prov-live code { - font-size: 0.95em; color: var(--brass); - background: var(--fill-amber); padding: 0.08em 0.4em; -} -.prov-dot { - color: var(--amber); font-size: 9px; - filter: drop-shadow(0 0 4px rgba(255,158,44,0.8)); - animation: prov-pulse 2.6s var(--ease) infinite; -} -@keyframes prov-pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.35; } -} - -/* ---- Header / nav --------------------------------------------------------- */ -.site-head { - position: sticky; top: 0; z-index: 40; - background: rgba(22,18,14,0.78); - backdrop-filter: blur(11px); - -webkit-backdrop-filter: blur(11px); - border-bottom: 1px solid var(--line); -} -.site-head .wrap { - display: flex; align-items: center; justify-content: space-between; - height: 64px; -} -.brand { - display: inline-flex; align-items: center; gap: 12px; - font-family: var(--display); font-weight: 900; font-size: 1.25rem; - letter-spacing: 0.04em; text-transform: uppercase; color: var(--ink); -} -.brand .coin { - width: 30px; height: 30px; border-radius: 50%; - display: grid; place-items: center; - font-family: var(--display); font-weight: 900; font-size: 13px; - color: var(--on-amber); - background: radial-gradient(circle at 34% 28%, var(--amber-hot), var(--copper) 78%, var(--copper-deep)); - box-shadow: var(--glow-amber), var(--emboss); -} -.nav-links { display: flex; gap: 4px; } -.nav-links a { - font-family: var(--mono); font-size: 12px; letter-spacing: 0.05em; - color: var(--muted); padding: 7px 11px; border-radius: 7px; - transition: color 0.18s var(--ease), background 0.18s var(--ease); -} -.nav-links a:hover { color: var(--ink); background: var(--fill-amber); } - -/* ---- Hero ----------------------------------------------------------------- */ -.hero { padding: clamp(64px, 12vw, 132px) 0 clamp(48px, 8vw, 88px); } -.hero h1 { color: var(--ink); } -.hero h1 .molten { - background: linear-gradient(96deg, var(--amber-hot), var(--copper) 60%, var(--ember)); - -webkit-background-clip: text; background-clip: text; color: transparent; -} -.hero .lede { margin-top: 20px; } -.hero .meta-row { - display: flex; gap: 26px; flex-wrap: wrap; margin-top: 34px; - font-family: var(--mono); font-size: 12px; color: var(--faint); - letter-spacing: 0.05em; -} -.hero .meta-row b { color: var(--brass); font-weight: 400; } -.cta { - display: inline-flex; align-items: center; gap: 10px; margin-top: 34px; - font-family: var(--display); font-weight: 600; font-size: 1.05rem; - letter-spacing: 0.03em; text-transform: uppercase; - color: var(--on-amber); - background: linear-gradient(96deg, var(--amber-hot), var(--copper)); - padding: 13px 26px; border-radius: 10px; - box-shadow: var(--glow-amber), var(--emboss); - transition: transform 0.16s var(--ease), filter 0.16s var(--ease); -} -.cta:hover { transform: translateY(-2px); filter: brightness(1.06); color: var(--on-amber); } - -.hero-inner { - display: flex; - align-items: center; - gap: clamp(32px, 5vw, 72px); - flex-wrap: wrap; -} -.hero-copy { flex: 1 1 320px; min-width: 0; } -@media (max-width: 700px) { - .hero-inner { flex-direction: column; } -} - -/* ---- Sections (native
) ----------------------------------------- */ -.sections { padding: clamp(32px, 6vw, 64px) 0 clamp(64px, 10vw, 110px); } - -.section { - background: - linear-gradient(180deg, var(--panel) 0%, var(--bg-2) 100%); - border: 1px solid var(--ridge); - border-radius: var(--radius); - box-shadow: var(--shadow), var(--emboss); - margin: 0 0 18px; - overflow: hidden; -} -.section[open] { box-shadow: var(--shadow-deep), var(--emboss); } - -.section > summary { - list-style: none; cursor: pointer; - display: flex; align-items: baseline; gap: 18px; - padding: 26px clamp(20px, 4vw, 34px); - user-select: none; - transition: background 0.2s var(--ease); -} -.section > summary::-webkit-details-marker { display: none; } -.section > summary:hover { background: var(--fill-amber); } - -.section .num { - font-family: var(--mono); font-size: 13px; letter-spacing: 0.22em; - color: var(--copper); flex: 0 0 auto; padding-top: 6px; -} -.section .head-text { flex: 1 1 auto; } -.section .head-text h2 { - margin: 0; color: var(--ink); - font-size: clamp(1.4rem, 3.2vw, 2.05rem); -} -.section .head-text .q { - display: block; font-family: var(--mono); font-size: 12px; - letter-spacing: 0.06em; color: var(--muted); margin-top: 6px; - text-transform: none; -} -.section .chev { - flex: 0 0 auto; width: 26px; height: 26px; align-self: center; - border-radius: 50%; display: grid; place-items: center; - border: 1px solid var(--line-strong); color: var(--amber); - font-size: 13px; line-height: 1; - transition: transform 0.25s var(--ease), background 0.2s var(--ease); -} -.section[open] .chev { transform: rotate(90deg); background: var(--fill-amber); } - -.section .body { - padding: 4px clamp(20px, 4vw, 34px) 32px; - border-top: 1px solid var(--line); - margin-top: 2px; -} -.section .body > *:first-child { margin-top: 18px; } - -/* Figure slot */ -.figure { - margin: 24px 0; border: 1px solid var(--ridge); border-radius: var(--radius-s); - background: var(--panel-2); padding: 18px; box-shadow: var(--emboss); -} -.figure figcaption { - margin-top: 12px; color: var(--muted); - font-family: var(--mono); font-size: 12px; letter-spacing: 0.03em; -} -.figure.diagram { background: var(--bg); } -.figure.diagram > svg { - display: block; width: 100%; height: auto; max-width: 100%; - border-radius: 6px; -} - -/* Grid cards */ -.grid { - display: grid; gap: 16px; - grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); - margin-top: 18px; -} -.card { - background: var(--panel-2); border: 1px solid var(--ridge); - border-radius: var(--radius-s); padding: 20px; box-shadow: var(--emboss); -} -.card .tag { - font-family: var(--mono); font-size: 11px; letter-spacing: 0.16em; - text-transform: uppercase; color: var(--copper); -} -.card h3 { margin: 8px 0 10px; color: var(--ink); } - -/* Agent table */ -.agent-table { - width: 100%; - border-collapse: collapse; - margin: 18px 0; - font-size: 0.92rem; -} -.agent-table th { - text-align: left; - font-family: var(--mono); - font-size: 11px; - letter-spacing: 0.12em; - text-transform: uppercase; - color: var(--copper); - padding: 10px 14px; - border-bottom: 2px solid var(--ridge); -} -.agent-table td { - padding: 10px 14px; - border-bottom: 1px solid var(--line); - color: var(--ink-2); - vertical-align: top; -} -.agent-table td:first-child { - color: var(--ink); - font-weight: 500; -} -.agent-table tr:hover td { - background: var(--fill-amber); -} - -/* Platform badges */ -.platform-badges { - display: flex; - flex-wrap: wrap; - gap: 8px; - margin: 14px 0; -} -.platform-badge { - display: inline-flex; - align-items: center; - gap: 6px; - padding: 6px 14px; - background: var(--panel-2); - border: 1px solid var(--ridge); - border-radius: 20px; - font-family: var(--mono); - font-size: 12px; - color: var(--ink-2); -} -.platform-badge.active { - border-color: var(--amber); - color: var(--amber); -} - -/* ---- Get started section -------------------------------------------------- */ -.install-block { - margin: 18px 0; - padding: 20px 24px; - border: 2px solid var(--amber); - border-radius: var(--radius); - background: linear-gradient(135deg, var(--fill-amber) 0%, var(--panel) 100%); - box-shadow: var(--glow-amber), var(--emboss); -} - -/* ---- Dropzone ------------------------------------------------------------- */ -.dropzone { - margin-top: 22px; border: 2px dashed var(--copper-deep); - border-radius: var(--radius); padding: clamp(28px, 6vw, 52px); - text-align: center; background: var(--fill-copper); - transition: border-color 0.2s var(--ease), background 0.2s var(--ease), - transform 0.2s var(--ease); - cursor: pointer; - display: block; -} -.dropzone:hover { border-color: var(--copper); background: var(--fill-amber); color: var(--ink); } -.dropzone .dz-icon { - font-family: var(--display); font-weight: 900; font-size: 2rem; - color: var(--amber); margin-bottom: 8px; -} -.dropzone .dz-hint { - font-family: var(--mono); font-size: 12px; color: var(--muted); - letter-spacing: 0.04em; margin-top: 10px; -} - -/* ---- Footer --------------------------------------------------------------- */ -footer { - border-top: 1px solid var(--line); - padding: 48px 0 72px; - color: var(--faint); - font-family: var(--mono); font-size: 12.5px; letter-spacing: 0.03em; -} -footer a { color: var(--brass); } -footer .prov { margin-top: 10px; color: var(--muted); } -footer .builder-credit { - margin-top: 16px; - padding-top: 16px; - border-top: 1px solid var(--line); - color: var(--faint); -} - -.stack-links { - display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px 22px; - margin-bottom: 16px; padding-bottom: 16px; - border-bottom: 1px solid var(--line); -} -.stack-links .stack-lead { - color: var(--faint); text-transform: uppercase; letter-spacing: 0.12em; -} -.stack-links a { color: var(--brass); } -.stack-links a:hover { color: var(--amber-hot); } - -/* ---- Responsive ----------------------------------------------------------- */ -@media (max-width: 640px) { - body { font-size: 16px; } - .nav-links { display: none; } - .section > summary { gap: 12px; padding: 20px 18px; } - .section .num { padding-top: 4px; } - .hero .meta-row { gap: 16px; } - .repo-banner { flex-direction: column; align-items: flex-start; } -} - -/* ---- Reduced motion ------------------------------------------------------- */ -@media (prefers-reduced-motion: reduce) { - html { scroll-behavior: auto; } - *, *::before, *::after { - animation-duration: 0.001ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.001ms !important; - scroll-behavior: auto !important; - } - .cta:hover { transform: none; } -} diff --git a/kb/ask-kb.mjs b/kb/ask-kb.mjs index 0379f0c..fbe8899 100644 --- a/kb/ask-kb.mjs +++ b/kb/ask-kb.mjs @@ -1,22 +1,20 @@ #!/usr/bin/env node -// ask-kb.mjs — self-contained CLI to query a Cognitum RVF knowledge base and print -// the FULL top-k passages (not previews). Joins .rvf vector hits to the full-text -// passages sidecar (.passages.jsonl) by id. +// ask-kb.mjs — self-contained CLI to query an RVF knowledge base and print the FULL top-k +// documents (not previews). Joins .rvf vector hits to the full-text passages sidecar +// (.passages.jsonl) by id. // // Usage: // node kb/ask-kb.mjs "your question" [k] (store slugs come from kb.config.mjs) // -// Deps: @ruvector/rvf + @xenova/transformers (resolved PORTABLY — see resolve-deps.mjs: -// project node_modules first, then RVF_MODULE_PATH/XENOVA_PATH env, then author Mac paths) -// + the bundled kb/*.rvf and kb/*.passages.jsonl files. So `cd kb && npm i` then run. -// Model cache is configurable via KB_MODEL_CACHE (offline if cached, else downloads MiniLM -// from HuggingFace — works on a fresh machine). +// Deps: @ruvector/rvf + @xenova/transformers, resolved by resolve-deps.mjs (project node_modules +// first, then RVF_MODULE_PATH / XENOVA_PATH). Model cache: KB_MODEL_CACHE (offline if cached, +// else downloaded from HuggingFace). import fs from 'node:fs'; import path from 'node:path'; import readline from 'node:readline'; import { fileURLToPath } from 'node:url'; -import { loadRvf, loadTransformers, configureModel } from './resolve-deps.mjs'; +import { loadRvf, loadTransformers } from './resolve-deps.mjs'; import { targets as CONFIG_TARGETS, defaultTarget as CONFIG_DEFAULT } from './kb.config.mjs'; const { mod: rvfMod, via: rvfVia } = loadRvf(); @@ -27,11 +25,9 @@ const __filename = fileURLToPath(import.meta.url); // decodes %20 etc. const KB_DIR = path.dirname(__filename); // =================================================================================== -// CONFIG BRIDGE — per-store config is read from kb.config.mjs (NO hard-coded repo names). -// Everything the intent/rerank layer needs that used to be a hard-coded ruvector/ruview map is -// now derived here from the target entry: metaName, productNames, componentRoots, componentWord, -// disambiguation, offtopicMagnets, primerSlugs (auto = discovered from the live sidecar at query -// time). knownStore() replaces the hard-coded `store !== 'ruvector' && store !== 'ruview'` checks. +// CONFIG BRIDGE — per-store config is read from kb.config.mjs (no repo names live in this file): +// metaName, productNames, componentRoots, componentWord, disambiguation, offtopicMagnets and +// primerSlugs (an explicit archetype map, or 'auto' = discovered from the live sidecar). // =================================================================================== const KNOWN_STORES = new Set(Object.keys(CONFIG_TARGETS)); function knownStore(store) { return KNOWN_STORES.has(store); } @@ -80,79 +76,37 @@ function productNameRe(store) { return new RegExp(`\\b(?:${alt})\\b`, 'i'); } -// ---------- variant-aware store resolution ---------- -// Two builds ship per repo (same passages, different embedder): -// small (384-dim MiniLM) — the Seed-compatible default; files: -kb.rvf -// big (768-dim bge) — sharper, for Mac/PC; files: -kb.big.rvf -// One tool serves both: the embedder for a query is read from the .embed.json -// sidecar the build wrote next to each .rvf, so the query is always embedded with the -// SAME model the corpus was. Absent that sidecar we fall back to MiniLM (the small build). +// ---------- store resolution ---------- +// The embedder for a query is read from the .embed.json sidecar the build wrote next to the +// .rvf, so a query is always embedded with the SAME model as the corpus. Absent that sidecar we +// fall back to MiniLM. const MINILM_CFG = { model: 'Xenova/all-MiniLM-L6-v2', pooling: 'mean', normalize: true, queryPrefix: '' }; -// KB data files live in kb/stores// when organized that way (clear, per-repo), and -// fall back to a flat kb/ layout otherwise (bundles unzip flat). One rule, both layouts. +// Store files live in kb/stores//; knowledge packs (make-pack) unzip them flat beside this +// file, so fall back to KB_DIR when the per-store dir is absent. function storeDir(store) { const sub = path.join(KB_DIR, 'stores', store); return fs.existsSync(sub) ? sub : KB_DIR; } -function variantPaths(store, variant) { +// File set + embedder config for a store. +function resolveConf(store) { + if (!knownStore(store)) throw new Error(`unknown store: ${store} (use ${[...KNOWN_STORES].join('|')})`); const dir = storeDir(store); const base = path.join(dir, `${store}-kb`); - // metadata sidecar (per-path `kind`): the generic builder writes *.ids.json; legacy stores used - // *.meta.json. Prefer ids.json, fall back to the legacy name when only it exists. (No repo baked in.) - const idsName = `${store}-kb.ids.json`; - const legacyName = `${store}-kb.meta.json`; - const metaFile = fs.existsSync(path.join(dir, idsName)) ? idsName - : (fs.existsSync(path.join(dir, legacyName)) ? legacyName : idsName); - // BOTH versions are explicitly named: .big.rvf (768-dim) and .small.rvf (384-dim). - // passages + metadata are SHARED (un-tagged) — built once, used by both. - // Single-384 build (recipe v1.3.1) writes the canonical un-suffixed -kb.rvf; prefer it - // for the small variant, falling back to the legacy .small.rvf tag. - let rvf; - if (variant === 'big') { - rvf = `${base}.big.rvf`; - } else { - const plain = `${base}.rvf`; - rvf = fs.existsSync(plain) ? plain : `${base}.small.rvf`; - } - return { - rvf, - passages: `${base}.passages.jsonl`, - meta: path.join(dir, metaFile), - embedCfgPath: `${rvf}.embed.json`, - }; -} - -// Resolve the file set + embedder config for a (store, variant). variant defaults to -// 'big' when a big build is present (best answers), else 'small' — so a fresh checkout -// with only the Seed build still works, and a Mac bundle auto-uses the sharp one. -function resolveConf(store, variant) { - if (!knownStore(store)) throw new Error(`unknown store: ${store} (use ${[...KNOWN_STORES].join('|')})`); - if (variant !== 'big' && variant !== 'small') { - variant = fs.existsSync(path.join(storeDir(store), `${store}-kb.big.rvf`)) ? 'big' : 'small'; - } - const p = variantPaths(store, variant); - // The big variant indexes the SAME passages/metadata as the small build (only the embedder - // differs), so a bundle ships ONE copy. If the big-tagged sidecars are absent, fall back to - // the small (untagged) ones — same content, ~115 MB smaller download per repo. - if (variant === 'big') { - const small = variantPaths(store, 'small'); - if (!fs.existsSync(p.passages)) p.passages = small.passages; - if (!fs.existsSync(p.meta)) p.meta = small.meta; - } + const rvf = `${base}.rvf`; + const embedCfgPath = `${rvf}.embed.json`; let embedCfg = { ...MINILM_CFG }; - if (fs.existsSync(p.embedCfgPath)) { - try { embedCfg = { ...MINILM_CFG, ...JSON.parse(fs.readFileSync(p.embedCfgPath, 'utf8')) }; } - catch (e) { if (process.env.KB_DEBUG) console.error(`[ask-kb] bad embed.json (${p.embedCfgPath}): ${e.message}`); } + if (fs.existsSync(embedCfgPath)) { + try { embedCfg = { ...MINILM_CFG, ...JSON.parse(fs.readFileSync(embedCfgPath, 'utf8')) }; } + catch (e) { if (process.env.KB_DEBUG) console.error(`[ask-kb] bad embed.json (${embedCfgPath}): ${e.message}`); } } - return { ...p, embedCfg, variant }; + return { rvf, passages: `${base}.passages.jsonl`, meta: path.join(dir, `${store}-kb.ids.json`), embedCfg }; } // ---------- embedder (lazy, per-model, offline-first with remote fallback) ---------- -// Cached per model name so a single process can serve both the small (MiniLM) and big -// (bge) builds without reloading. Remote download is allowed only when THAT model isn't -// already cached locally (so a Seed-only box never reaches for the network). +// Cached per model name so a process can serve stores built with different embedders. Remote +// download is allowed only when THAT model isn't already cached locally. const _feCache = new Map(); async function getEmbedder(model) { if (_feCache.has(model)) return _feCache.get(model); @@ -213,7 +167,7 @@ function loadPassages(file) { // ---------- kind metadata sidecar loader ---------- // The passages sidecar (.passages.jsonl) carries only {id,text,path,title}. The per-chunk // `kind` (source / crate-src / adr / doc / doc-deep / primer-orientation / …) lives in the -// build metadata sidecar (.ids.json / .meta.json) keyed by the SAME numeric id. The intent +// build metadata sidecar (.ids.json) keyed by the SAME numeric id. The intent // layer (code-vs-doc routing, ADR-vs-code pairing, PRIMER detection) needs `kind`, so we load // it once and fold it down to a per-PATH kind. If the sidecar is missing the layer degrades // gracefully (kind unknown -> no kind-based adjustments; vector+rerank still works). @@ -320,7 +274,7 @@ const PRIMER_DEMOTE_WHEN_SPECIFIC = 0.60; // =================================================================================== // Retrieval-quality layer (retrieval-only; KBs are NOT rebuilt). // FIX 1 whole-document return, FIX 2 demote low-signal files, -// FIX 3 exact-term/ADR/title boost, FIX 4 "Cognitum Seed" disambiguation. +// FIX 3 exact-term/ADR/title boost, FIX 4 config-driven disambiguation. // =================================================================================== const MAX_DOC_CHARS = 12000; // cap for an assembled full document @@ -345,12 +299,6 @@ const LOW_SIGNAL = [ { re: /(_test\.rs|\.test\.[jt]s|_spec\.rb)$/i, pen: 0.16, allow: /\btest/i }, ]; -// FIX 4 — "Cognitum Seed" product disambiguation. When the query is about the Seed -// product/onboarding, bias toward onboarding/Seed docs and away from RNG/pretraining seeds. -const SEED_QUERY_RE = /\b(cognitum\s+seed|seed\s+(onboard\w*|pipeline|product)|onboard\w*\s+seed)\b/i; -const SEED_GOOD_RE = /(adr[-_]?069|adr[-_]?116|(^|\/)seed|onboard|(^|\/)cog-)/i; -const SEED_BAD_RE = /(rng|random|pretrain|nvsim|prng|np\.random|torch\.manual_seed)/i; - // FIX 5 — TOP-DOWN ORIENTATION LAYER. The primers are indexed as synthetic `PRIMER#
` // documents (kind 'primer-orientation') that synthesize the answers to the six comprehension- // journey archetypes a raw repo lacks: what-is-it / concepts / how-each-works / maturity / @@ -418,37 +366,9 @@ function orientationBoost(query, path, title = '', suppressGeneric = false) { // All of this is layered as effective-distance adjustments / hard rank overrides — no rebuild. // =================================================================================== -// Per-store map of orientation archetype -> the EXACT PRIMER# slug that answers it. Slugs were -// discovered from the live sidecars (grep 'PRIMER#…' on the ids/meta files); only real slugs are -// listed. `adr` is the docs-location archetype's ADR-specific sub-target (the ADR index table). -// Legacy hard-coded PRIMER slug maps are kept ONLY as a fallback for the prototype stores so an old -// ruvector/ruview KB still routes; new targets supply slugs via config (an explicit per-archetype -// map) or use primerSlugs:'auto' (slugs discovered from the live sidecar at query time — see -// resolvePrimerSlug). NO new repo names are added here. -const LEGACY_PRIMER_SLUGS = { - ruvector: { - maturity: 'PRIMER#8-maturity-gotchas', - capabilities: 'PRIMER#2-the-big-capabilities-and-how-to-actually-call-them', - docs: 'PRIMER#5-docs-tutorials-examples-skills', - adr: 'PRIMER#4-adr-index-the-complete-table-208-main-series-files-in-docs-adr-54-in-4-sub-ser', - playbook: 'PRIMER#0-executive-summary-which-crate-do-i-need', - whatis: 'PRIMER#1-what-ruvector-is', - crates: 'PRIMER#3-complete-crate-inventory', - hardware: null, - glossary: null, - }, - ruview: { - maturity: 'PRIMER#7-capabilities-graded-honestly', - capabilities: 'PRIMER#7-capabilities-graded-honestly', - docs: 'PRIMER#9-docs-tutorials-scripts-firmware-where-everything-lives', - adr: 'PRIMER#8-the-complete-adr-index-160-adr-numbered-files-156-unique-numbers', - playbook: 'PRIMER#0-1-instant-playbooks-task-exact-steps', - whatis: 'PRIMER#1-what-ruview-is', - crates: 'PRIMER#3-the-crates-v2-workspace-39-incl-the-ruv-neural-git-submodule-and-homecore-plug', - hardware: 'PRIMER#10-hardware-matrix', - glossary: 'PRIMER#0-3-glossary-so-terms-are-never-guessed', - }, -}; +// Orientation archetype -> the PRIMER# that answers it. A target supplies an explicit per-archetype map +// (`adr` is the docs-location archetype's ADR-index sub-target) or primerSlugs:'auto' (slugs discovered from the +// live sidecar at query time — see resolvePrimerSlug). // Keyword cues per archetype used by 'auto' slug discovery (matched against a PRIMER# path). // First section whose slug matches the archetype's cues wins; whatis prefers an early "what-is"/#1. @@ -466,14 +386,12 @@ const AUTO_SLUG_CUES = { // Resolve the PRIMER# for an archetype, store, and the live sidecar paths. // 1. explicit config map (target.primerSlugs is an object): use it. -// 2. legacy hard-coded map (ruvector/ruview): use it. -// 3. 'auto' (or anything else): discover from byPath PRIMER#… keys via AUTO_SLUG_CUES. +// 2. 'auto' (or anything else): discover from byPath PRIMER#… keys via AUTO_SLUG_CUES. function resolvePrimerSlug(archetype, store, byPath) { if (!archetype) return null; const t = cfgFor(store); const ps = t && t.primerSlugs; if (ps && typeof ps === 'object') return ps[archetype] ?? null; - if (LEGACY_PRIMER_SLUGS[store]) return LEGACY_PRIMER_SLUGS[store][archetype] ?? null; // 'auto' discovery from the live sidecar. const cues = AUTO_SLUG_CUES[archetype]; if (!cues || !byPath) return null; @@ -855,31 +773,16 @@ function crateOverviewAdjust(crateTok, path, store) { // FIX B — targeted off-topic-magnet down-weight (RETRIEVAL POLISH). A specific document that // keeps surfacing as off-topic noise on UNRELATED queries gets a mild penalty UNLESS the query is // actually about that document's subject. General mechanism (a small allow-listed down-weight -// table); currently a single entry for ADR-096 (rvCSI crate layout), which intruded on unrelated -// queries (e.g. worldgraph spatial relationships). The penalty is mild so an on-topic query -// (about rvCSI crate layout / structure) still surfaces it normally via its allow regex. +// table). The penalty is mild so an on-topic query still surfaces the document via its allow regex. +// Entries come from config.offtopicMagnets: { re|reSource, pen, allow|allowSource }. // =================================================================================== -// Legacy default magnet table (ruvector/ruview only): ADR-096 (rvCSI crate layout) intruded on -// unrelated queries. New targets supply their own via config.offtopicMagnets (filled during gate-A -// tuning, P6a) — each entry { re|reSource, pen, allow|allowSource }. -const LEGACY_OFFTOPIC_MAGNETS = { - ruvector: [ - { re: /(^|\/)adr[-_]?0*96\b/i, pen: 0.22, - allow: /\b(rvcsi|rv[-_]?csi|crate\s+layout|crate\s+structure|crate\s+organi|workspace\s+layout|adr[-\s_]?0*96)\b/i }, - ], - ruview: [ - { re: /(^|\/)adr[-_]?0*96\b/i, pen: 0.22, - allow: /\b(rvcsi|rv[-_]?csi|crate\s+layout|crate\s+structure|crate\s+organi|workspace\s+layout|adr[-\s_]?0*96)\b/i }, - ], -}; // Compile a config magnet entry (which may carry string sources or RegExp objects) into a usable // { re, pen, allow } triple. Cached per store so we don't recompile each call. const _magnetCache = new Map(); function magnetsFor(store) { if (_magnetCache.has(store)) return _magnetCache.get(store); const t = cfgFor(store); - let list = (t && Array.isArray(t.offtopicMagnets) && t.offtopicMagnets.length) ? t.offtopicMagnets : null; - if (!list) list = LEGACY_OFFTOPIC_MAGNETS[store] || []; + const list = (t && Array.isArray(t.offtopicMagnets)) ? t.offtopicMagnets : []; const compiled = list.map((m) => ({ re: m.re instanceof RegExp ? m.re : new RegExp(m.reSource || String(m.re || ''), 'i'), allow: m.allow instanceof RegExp ? m.allow : (m.allow || m.allowSource ? new RegExp(m.allowSource || String(m.allow), 'i') : null), @@ -964,21 +867,12 @@ function substanceBoost(chunks) { // Disambiguation adjustment (negative = boost a "good" path, positive = penalize a "bad" path) for // queries matching a config disambiguation entry. Each entry: { whenSource|when, goodSource|good, -// badSource|bad, goodBoost?, badPenalty? }. New targets fill target.disambiguation during gate-A -// tuning (P6a). Legacy ruvector/ruview keep the hard-coded "Cognitum Seed" rule as a fallback only. +// badSource|bad, goodBoost?, badPenalty? } from target.disambiguation. const _disambigCache = new Map(); function disambigFor(store) { if (_disambigCache.has(store)) return _disambigCache.get(store); const t = cfgFor(store); - let list = (t && Array.isArray(t.disambiguation) && t.disambiguation.length) ? t.disambiguation : null; - if (!list) { - // legacy fallback: the prototype's "Cognitum Seed" product disambiguation. - if (store === 'ruvector' || store === 'ruview') { - list = [{ when: SEED_QUERY_RE, good: SEED_GOOD_RE, bad: SEED_BAD_RE, goodBoost: 0.25, badPenalty: 0.30 }]; - } else { - list = []; - } - } + const list = (t && Array.isArray(t.disambiguation)) ? t.disambiguation : []; const compiled = list.map((d) => ({ when: d.when instanceof RegExp ? d.when : new RegExp(d.whenSource || String(d.when || ''), 'i'), good: d.good instanceof RegExp ? d.good : (d.good || d.goodSource ? new RegExp(d.goodSource || String(d.good), 'i') : null), @@ -989,7 +883,7 @@ function disambigFor(store) { _disambigCache.set(store, compiled); return compiled; } -function seedAdjust(query, path, store) { +function disambigAdjust(query, path, store) { let adj = 0; for (const d of disambigFor(store)) { if (!d.when.test(query)) continue; @@ -1099,12 +993,15 @@ function assembleDocument(chunks, matchedId) { } // ---------- core search: returns whole-document results ---------- -// Each result: { path, title, fullText, bestDistance, effDistance, chunksJoined, truncated, -// distance (alias of bestDistance), text (alias of fullText) }. -export async function searchKb({ query, k = 6, store, n, variant }) { - const conf = resolveConf(store, variant); - if (!fs.existsSync(conf.rvf)) throw new Error(`rvf not found: ${conf.rvf} (variant=${conf.variant}; run \`npm i\` then build, or copy the bundle in)`); - const topN = Math.max(1, n || 5); +// Each result: { path, title, fullText, bestDistance, effDistance, kind, adrStatus, statusLabel, +// label, chunksJoined, truncated } (+ designIntentWarning on a proposal-as-reality top hit). +// `k` is the result count; both callers (CLI, MCP) pass it. +export function resultCount({ k } = {}) { return Math.max(1, k ?? 6); } + +export async function searchKb({ query, k = 6, store }) { + const conf = resolveConf(store); + if (!fs.existsSync(conf.rvf)) throw new Error(`rvf not found: ${conf.rvf} (run \`npm i\` then build, or copy the pack in)`); + const topN = resultCount({ k }); const [qv, { byId, byPath }] = await Promise.all([embed(query, conf.embedCfg), loadPassages(conf.passages)]); const byPathKind = loadKinds(conf.meta); // intent layer: per-path content kind const terms = queryTerms(query); @@ -1127,7 +1024,7 @@ export async function searchKb({ query, k = 6, store, n, variant }) { } // 'whatis-concept' is a NON-routing archetype: no force-route to a PRIMER, instead a mild concept // boost (below) lets the vector+rerank pipeline surface the true DEFINING doc. Other archetypes - // force-route to their PRIMER slug (null slug -> no force-route, e.g. ruvector hardware). + // force-route to their PRIMER slug (null slug -> no force-route). const targetPrimerSlug = (archetype && archetype !== 'whatis-concept') ? resolvePrimerSlug(archetype, store, byPath) : null; @@ -1274,7 +1171,7 @@ export async function searchKb({ query, k = 6, store, n, variant }) { const dkind = byPathKind.get(d.path) || null; const pen = demotionPenalty(query, d.path); const boost = lexicalBoost(query, terms, d.path, d.title); - const seed = seedAdjust(query, d.path, store); + const disambig = disambigAdjust(query, d.path, store); const sub = substanceBoost(byPath.get(d.path)); // FIX 1 — when a specific entity is named, the generic orientation lift is suppressed AND // primer-orientation docs are demoted below source/adr/crate-src/doc for this query. @@ -1312,11 +1209,10 @@ export async function searchKb({ query, k = 6, store, n, variant }) { } // RANK SCALE — the additive offsets below were calibrated against MiniLM's distance scale - // (relevant ~0.9–1.1). bge-base packs relevant docs much tighter (~0.4–0.8), so the same - // raw offset over-corrects and inverts good raw rankings. Scale the WHOLE offset bundle by - // the per-variant rankScale (small=1.0 → unchanged; big<1 → gentler, trusts bge's raw order). + // (relevant ~0.9–1.1); bge packs relevant docs tighter, so scale the WHOLE offset bundle by the + // store's embed.rankScale (1.0 = MiniLM scale; <1 = gentler, trusts the raw vector order). const RANK_SCALE = conf.embedCfg.rankScale ?? 1; - const offsets = pen - boost + seed - sub - orient - concept - intentAdj + const offsets = pen - boost + disambig - sub - orient - concept - intentAdj + primerDemote + crateAdj + implAdj + namedCrateAdj + magnetPen + matAdj; const effDistance = d.bestDistance + RANK_SCALE * offsets; return { ...d, effDistance, kind: dkind }; @@ -1361,14 +1257,11 @@ export async function searchKb({ query, k = 6, store, n, variant }) { bestDistance: d.bestDistance, effDistance: d.effDistance, kind, - adrStatus, // FIX 4 — parsed ADR status (null if none) — carried to MCP + adrStatus, // FIX 4 — parsed ADR status (null if none) statusLabel, // FIX 4 — human-visible "[ADR STATUS: …]" tag label: label || null, // intent label (e.g. 'paired-source') for callers/UI chunksJoined, truncated, - // back-compat aliases for callers that still read .text / .distance - text: fullText, - distance: d.bestDistance, }; }; @@ -1400,6 +1293,17 @@ export async function searchKb({ query, k = 6, store, n, variant }) { return out; } +// One search result as text for the MCP server. Carries the ADR status tag and the +// proposal-as-reality warning, so an MCP reader never mistakes a design proposal for shipped code. +export function formatDocument(r, i) { + return `#${i + 1} (distance ${r.bestDistance.toFixed(4)})${r.kind ? ` kind=${r.kind}` : ''}${r.label ? ` [${r.label}]` : ''}${r.statusLabel ? ` [${r.statusLabel}]` : ''}\n` + + `path : ${r.path}\n` + + `title: ${r.title}\n` + + (r.designIntentWarning ? `${r.designIntentWarning}\n` : '') + + `----- full document (${r.fullText.length} chars, ${r.chunksJoined} chunk(s)${r.truncated ? ', truncated' : ''}) -----\n` + + `${r.fullText}\n`; +} + // ---------- structured lookups (exact, not semantic) ---------- // The drop-in for-ai/ ships -symbols.json / -dep-graph.json / -entrypoints.json. These give // an AI EXACT answers (a function signature, who-depends-on-what, the build/test/run commands) @@ -1453,20 +1357,16 @@ async function main() { return; } - // optional trailing [big|small] variant selector; default auto-picks big if present - let variant; - const vIdx = argv.findIndex((a) => a === 'big' || a === 'small'); - if (vIdx !== -1) variant = argv.splice(vIdx, 1)[0]; const [store, query, kArg] = argv; if (!store || !query) { - console.error(`Usage: node kb/ask-kb.mjs <${[...KNOWN_STORES].join('|')}> "question" [k] [big|small]`); + console.error(`Usage: node kb/ask-kb.mjs <${[...KNOWN_STORES].join('|')}> "question" [k]`); console.error(` or: node kb/ask-kb.mjs --symbol | --entrypoints | --deps`); process.exit(2); } const k = Math.max(1, parseInt(kArg || '6', 10) || 6); - const conf = resolveConf(store, variant); - const results = await searchKb({ query, k, store, variant }); - console.log(`\n=== ${store} KB (${conf.variant} · ${conf.embedCfg.model}) — "${query}" — top ${results.length} documents ===\n`); + const conf = resolveConf(store); + const results = await searchKb({ query, k, store }); + console.log(`\n=== ${store} KB (${conf.embedCfg.model}) — "${query}" — top ${results.length} documents ===\n`); results.forEach((r, i) => { console.log(`#${i + 1} distance=${r.bestDistance.toFixed(4)} (eff=${r.effDistance.toFixed(4)})` + `${r.kind ? ` kind=${r.kind}` : ''}${r.label ? ` [${r.label}]` : ''}` diff --git a/kb/build-kb.mjs b/kb/build-kb.mjs index 654fee9..4e786d2 100644 --- a/kb/build-kb.mjs +++ b/kb/build-kb.mjs @@ -31,15 +31,11 @@ import { RULE_IMPLS } from './corpus-rules.mjs'; import { makeContext } from './chunker.mjs'; import { SYNTHETIC_PATH_RE, acquireLock, readPassages, readIdsIndex, - cloneFile, publish, firstIdOrderViolation, + cloneFile, publish, firstIdOrderViolation, storeDirFor, } from './store-set.mjs'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); // kb/ -// Default embedder (legacy / Seed-compatible): MiniLM-384 → -kb.small.rvf. -// A target may override via an `embed` block in kb.config.mjs (ADR-0001 v1.3.1). -const DEFAULT_MODEL = 'Xenova/all-MiniLM-L6-v2'; -const DEFAULT_DIM = 384; const BATCH = 32; const CHURN_LIMIT = 0.4; // delta refuses above this work fraction (ADR-0010 D3) @@ -56,23 +52,25 @@ function parseArgs(argv) { } // ---------- shared pieces ---------- -function resolveEmbedder(target) { - const emb = target.embed || {}; +// A target MUST carry an `embed` block: there is no default model, because a store embedded with a guessed +// model would be indistinguishable from a correct one (same 384 dimensions) and silently retrieve garbage. +export function resolveEmbedder(target) { + const emb = target.embed; + if (!emb || !emb.model || !emb.dim) { + throw new Error(`kb target "${target.slug}" has no embed block (model + dim) in kb.config.mjs — refusing to guess an embedder`); + } return { - MODEL: emb.model || DEFAULT_MODEL, - DIM: emb.dim || DEFAULT_DIM, + MODEL: emb.model, + DIM: emb.dim, POOLING: emb.pooling || 'mean', QUERY_PREFIX: emb.queryPrefix || '', // passages are embedded WITHOUT the prefix RANK_SCALE: typeof emb.rankScale === 'number' ? emb.rankScale : 1.0, - RVF_SUFFIX: emb.rvfSuffix || (target.embed ? '.rvf' : '.small.rvf'), - hasOverride: !!target.embed, + RVF_SUFFIX: emb.rvfSuffix || '.rvf', }; } function storePaths(slug, RVF_SUFFIX) { - const storeDir = process.env.KB_STORE_DIR - ? path.resolve(process.env.KB_STORE_DIR) - : path.join(__dirname, 'stores', slug); + const storeDir = storeDirFor(slug); const base = path.join(storeDir, `${slug}-kb`); return { storeDir, base, @@ -105,7 +103,7 @@ function buildCorpus(target) { async function initEmbedder(MODEL) { const { T, via: tVia } = await loadTransformers(); - const cache = chooseModelCache(MODEL); + const cache = chooseModelCache(); const { haveLocalModel } = configureModel(T, cache, MODEL); console.log(`[build-kb] transformers via ${tVia} | model ${haveLocalModel ? 'local' : 'remote'} (${cache})`); return T.pipeline('feature-extraction', MODEL, { quantized: true }); @@ -139,7 +137,7 @@ const fileHash = (texts) => crypto.createHash('sha256').update(JSON.stringify(te // ---------- full build ---------- async function fullBuild({ slug, target, entries, embCfg, paths, RvfDatabase, fe }) { - const { MODEL, DIM, POOLING, QUERY_PREFIX, RANK_SCALE, hasOverride } = embCfg; + const { MODEL, DIM, POOLING, QUERY_PREFIX, RANK_SCALE } = embCfg; const { OUT_RVF, OUT_PASSAGES, OUT_IDS, OUT_EMBEDCFG } = paths; fs.rmSync(OUT_RVF, { force: true }); @@ -177,11 +175,9 @@ async function fullBuild({ slug, target, entries, embCfg, paths, RvfDatabase, fe }, null, 0)); // Embedder sidecar (read by ask-kb + index-primer so the QUERY/primer use the SAME model). - if (hasOverride) { - fs.writeFileSync(OUT_EMBEDCFG, JSON.stringify({ - model: MODEL, pooling: POOLING, normalize: true, queryPrefix: QUERY_PREFIX, rankScale: RANK_SCALE, - }, null, 2)); - } + fs.writeFileSync(OUT_EMBEDCFG, JSON.stringify({ + model: MODEL, pooling: POOLING, normalize: true, queryPrefix: QUERY_PREFIX, rankScale: RANK_SCALE, + }, null, 2)); const idCount = Object.keys(idsIndex).length; const ok = status.totalVectors === entries.length && passageLines === entries.length && idCount === entries.length; @@ -415,4 +411,6 @@ async function main() { } } -main().catch((e) => { console.error('[build-kb] ERROR:', e); process.exit(1); }); +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + main().catch((e) => { console.error('[build-kb] ERROR:', e); process.exit(1); }); +} diff --git a/kb/chunker.mjs b/kb/chunker.mjs index 8953d1c..3eb5fd5 100644 --- a/kb/chunker.mjs +++ b/kb/chunker.mjs @@ -3,7 +3,7 @@ // Factored VERBATIM out of build-kb.mjs so external tools (delta builders, audits) can import // the REAL chunker instead of replicating it — replication drift was the corruption risk that // motivated issue #14's hash guard. Everything here is pure text ops + fs walking; no embedder, -// no store. build-kb.mjs is the only in-repo consumer; the drop-in zips do not ship this file. +// no store. Consumers: build-kb.mjs and index-primer.mjs; knowledge packs do not ship this file. // // Exports: CHUNK_CHARS, OVERLAP_CHARS, STRUCT_TARGET_CHARS, STRUCT_MIN_CHARS, // windowChunk(), structureBoundaries(), chunk(), classifySourceType(), makeContext(). @@ -173,6 +173,7 @@ export function makeContext(target) { const sourceCounts = {}; // kind -> source-file count const ingestedPaths = new Set(); // absolute paths already ingested (md-sweep / literal de-dup) const fullBodyPaths = new Set(); // absolute paths ingested as full source bodies + const docBlockPaths = new Set(); // absolute paths whose leading doc block is already emitted function addDoc(relPath, kind, title, text, absPath) { const source_type = classifySourceType(relPath, kind); @@ -192,6 +193,8 @@ export function makeContext(target) { alreadyIngested: (absPath) => ingestedPaths.has(absPath), isFullBody: (absPath) => fullBodyPaths.has(absPath), markFullBody: (absPath) => { if (absPath) fullBodyPaths.add(absPath); }, + hasDocBlock: (absPath) => docBlockPaths.has(absPath), + markDocBlock: (absPath) => { if (absPath) docBlockPaths.add(absPath); }, entries, sourceCounts, }; diff --git a/kb/corpus-rules.mjs b/kb/corpus-rules.mjs index 96da6c3..b6ac621 100644 --- a/kb/corpus-rules.mjs +++ b/kb/corpus-rules.mjs @@ -4,11 +4,10 @@ // walk helper, exclusion set, chunker, addDoc collector, etc.) plus the rule's own config object // (from `kb.config.mjs` target.include[]) and APPENDS entries to the corpus via ctx.addDoc(...). // -// The mechanics are generalized from the proven Cognitum prototype (build-ruview-kb.mjs): -// repo-shape is now DATA (roots / exts / files / headLines) instead of hard-coded ruview/ruvector -// paths. NO repo name is baked in here. build-kb.mjs wires these rules together per config. +// Repo shape is DATA (roots / exts / files / headLines); no repo name is baked in here. +// build-kb.mjs wires these rules together per config. // -// Rule types (build-plan-metaharness.md §2a [D5]): +// Rule types: // mdSweepFullText — every *.md/.mdx/.txt under the given roots, verbatim (untruncated). // componentManifests— each component's package.json / Cargo.toml summarized (name/desc/scripts/deps). // componentLead — each component's README / lead doc (full text) + lead source doc-block. @@ -16,6 +15,7 @@ // docCommentSweep — leading doc comments only (//!, /** */, """...""", #-prefixed) from source. // literalFiles — an explicit list of files, full text (guarantees key docs are present). // htmlText — visible text of *.html under the roots (scripts/styles/tags stripped). +// testsAndExamples — full bodies of test/example/bench source (the best usage docs). // templates — scaffolding templates (.tmpl/.hbs/...): first-N-lines + path, kind:'template'. // // A `kind` is attached to every entry so the intent layer (ask-kb) can route by content kind. @@ -181,9 +181,11 @@ export function componentLead(ctx, rule) { if (lead) { const text = read(lead); const doc = docBlock(text, 200); - if (doc) { + // docCommentSweep emits the same file's doc block, so record it to avoid a duplicate chunk. + if (doc && !ctx.hasDocBlock(lead)) { ctx.addDoc(ctx.rel(lead), 'crate-src', `${dirent.name} ${path.basename(lead)}`, `Component ${dirent.name} — ${path.basename(lead)} leading doc:\n${doc}`, /*absPath*/ undefined); + ctx.markDocBlock(lead); n++; } } @@ -200,10 +202,7 @@ export function sourceBodies(ctx, rule) { const ROOTS_FILE = /(^|\/)(lib\.rs|main\.rs|mod\.rs|index\.ts|index\.js|index\.mjs)$/i; const MINIFIED = /\.(min|bundle)\.(js|css|mjs)$/i; const TESTY = /(^|\/)(tests?|benches?|__tests__|__mocks__|spec)\//i; - // NAMING A ROOT *IS* THE SCOPE DECISION (2026-09-17, ruvnet/mcp-studio). The /src/ + root-file - // convention below is the fallback for a target that named no specific root ("." or none). A - // Next.js app keeps its code in app/ + lib/ + components/ with no src/ anywhere, so the - // convention silently ingested ZERO source and the KB came out as README + config only. + // A named root is the scope; the src/ + root-file convention applies only to '.' or no root. const named = (rule.roots || []).filter((r) => r && r !== '.'); const inScope = (rel) => { if (MINIFIED.test(rel)) return false; @@ -232,7 +231,7 @@ export function sourceBodies(ctx, rule) { // testsAndExamples — full bodies of TEST / EXAMPLE / BENCH source files under the roots. These are // the single best USAGE documentation a repo has (real call sites + expected results), so they are // ingested deliberately (sourceBodies excludes them on purpose; this rule is the complement). The -// source_type tagger in build-kb.mjs marks each as 'test' or 'example' from its path. kind stays +// source_type tagger (chunker.classifySourceType) marks each as 'test' or 'example' from its path. kind stays // 'source' so the existing source-routing/reranking treats them like code. export function testsAndExamples(ctx, rule) { const exts = (rule.ext || ['.rs', '.ts', '.tsx', '.js', '.mjs']).map((e) => e.toLowerCase()); @@ -266,10 +265,12 @@ export function docCommentSweep(ctx, rule) { for (const p of ctx.walk(root)) { if (!hasExt(p, exts)) continue; if (ctx.isFullBody(p)) continue; // already ingested in full by sourceBodies + if (ctx.hasDocBlock(p)) continue; // componentLead already emitted this file's doc block const doc = docBlock(firstLines(read(p), 40), 40); if (!doc) continue; const rel = ctx.rel(p); ctx.addDoc(rel, 'crate-src', path.basename(p), `Module ${rel} — doc comment:\n${doc}`, /*absPath*/ undefined); + ctx.markDocBlock(p); n++; } } @@ -312,7 +313,7 @@ export function htmlText(ctx, rule) { // templates — scaffolding templates (.tmpl/.hbs/.handlebars): path + first-N-lines, kind:'template'. // These are the bulk of "what does a generated harness contain" — neither prose nor runnable source, -// so we index a head sample + the path (decided IN, not skipped — plan top risk #2). +// so we index a head sample + the path. export function templates(ctx, rule) { const exts = (rule.ext || ['.tmpl', '.hbs', '.handlebars']).map((e) => e.toLowerCase()); const headLines = rule.headLines || 40; @@ -343,5 +344,3 @@ export const RULE_IMPLS = { htmlText, templates, }; - -export default RULE_IMPLS; diff --git a/kb/dep-graph.mjs b/kb/dep-graph.mjs index 5e34242..8ae248e 100644 --- a/kb/dep-graph.mjs +++ b/kb/dep-graph.mjs @@ -10,13 +10,10 @@ // TS/JS: import scan of the source tree (no madge dependency required) → module/package graph // (internal edges between componentRoots packages via workspace imports + external deps // from each package.json). -// Python: pyproject.toml workspace/member discovery + import scan → package dependency graph. -// This matters for repos such as the-goodies: treating an unsupported ecosystem as an -// empty graph used to force an authored list into a nested-box renderer, which looked like -// random concentric boxes rather than architecture. +// Python: pyproject.toml workspace/member discovery + import scan → package dependency graph +// (an unsupported ecosystem must not become an empty graph). // -// Repo shape is DATA (kb.config.mjs target: repoDir, scopeExclude, componentRoots). Ships in the -// drop-in for-ai/. NO repo name is baked in here. +// Repo shape is DATA (kb.config.mjs target: repoDir, scopeExclude, componentRoots). // // Usage: node kb/dep-graph.mjs --target ruqu | node kb/dep-graph.mjs ruqu @@ -152,8 +149,7 @@ function tsGraph(repoDir, skip, componentRoots) { const pkgDirs = []; for (const r of [...(componentRoots || ['packages']), 'cli', 'apps', 'npm/packages', '.']) { const abs = path.join(repoDir, r); - // componentRoots can be AI-authored (kb:register) and may name a FILE (execa's "index.js" - // crashed readdirSync here, run 28666874765) — only directories are scannable roots. + // componentRoots can be AI-authored (kb:register) and may name a FILE — only directories are scannable roots. if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) continue; if (fs.existsSync(path.join(abs, 'package.json'))) { pkgDirs.push(abs); continue; } for (const d of fs.readdirSync(abs, { withFileTypes: true })) { diff --git a/kb/entrypoints.mjs b/kb/entrypoints.mjs index eb73b30..dd95abc 100644 --- a/kb/entrypoints.mjs +++ b/kb/entrypoints.mjs @@ -9,8 +9,8 @@ // Repo shape is DATA (kb.config.mjs target: repoDir, scopeExclude, componentRoots). NO repo // name is baked in here — the same script runs for ruqu / photonlayer / ruvn / metaharness. // -// This file ships in the drop-in for-ai/ so the AI gets EXACT entrypoint lookups (how do I -// build / test / run / install this) instead of guessing from semantic search. +// Its OUTPUT (-entrypoints.json) ships in the drop-in for-ai/ so the AI gets EXACT entrypoint +// lookups (how do I build / test / run / install this); this script itself does not ship. // // Usage: node kb/entrypoints.mjs --target ruqu // node kb/entrypoints.mjs ruqu @@ -107,7 +107,6 @@ function main() { target: slug, metaName: target.metaName, generated: new Date().toISOString(), - repo: target.bundle?.blurb ? undefined : undefined, workspace: { kind: null, members: [] }, // rust workspace | npm | mixed components: [], // { name, path, kind:'crate'|'package', description, bins, examples, scripts, deps } binaries: [], // { name, component, path } diff --git a/kb/extract-symbols.mjs b/kb/extract-symbols.mjs index 7cbd919..008ca75 100644 --- a/kb/extract-symbols.mjs +++ b/kb/extract-symbols.mjs @@ -12,7 +12,8 @@ // TS/JS: ripgrep-style scan of `export ...` (function/class/interface/type/const) + JSDoc. // // Repo shape is DATA (kb.config.mjs target: repoDir, scopeExclude, componentRoots, codeExt). NO -// repo name is baked in here. Ships in the drop-in for-ai/ so the AI gets EXACT API lookups. +// repo name is baked in here. Its OUTPUT (-symbols.json) ships in the drop-in for-ai/ for EXACT API +// lookups; this script itself does not ship. // // Usage: node kb/extract-symbols.mjs --target ruqu [--no-rustdoc] // node kb/extract-symbols.mjs ruqu @@ -102,8 +103,8 @@ function symbolsFromRustdoc(jsonPath, crateName) { const out = []; const get = (id) => idx[id]; - // Render a struct's fields into a compact "{ name: Type, … }" string + emit per-field symbols. - const renderStructFields = (st, parentName) => { + // Render a struct's fields into a compact "{ name: Type, … }" string. + const renderStructFields = (st) => { const k = st.kind || {}; const fieldIds = k.plain ? (k.plain.fields || []) : (Array.isArray(k.fields) ? k.fields : []); const fields = []; @@ -151,7 +152,7 @@ function symbolsFromRustdoc(jsonPath, crateName) { let signature; if (kind === 'function') signature = renderFnSig(it.name, inner.function); else if (kind === 'struct') { - const fields = renderStructFields(inner.struct, it.name); + const fields = renderStructFields(inner.struct); signature = fields.length ? `struct ${it.name} { ${fields.join(', ')} }` : `struct ${it.name}`; } else if (kind === 'enum') { const variants = (inner.enum.variants || []).map((vid) => { const v = get(vid); return v && v.name; }).filter(Boolean); @@ -239,6 +240,7 @@ function main() { let symbols = []; let method = 'source-scan'; + const rustdocCrates = new Set(); // crate dirs (member paths) rustdoc actually covered // ---- Rust: try rustdoc-json per workspace crate ---- const rootCargo = tryRead(path.join(repoDir, 'Cargo.toml')); @@ -252,7 +254,6 @@ function main() { const name = cargo && (cargo.match(/^\s*name\s*=\s*"([^"]+)"/m) || [])[1]; if (name) crateNames.push(name); } - var rustdocCrates = new Set(); // crate dirs (member paths) rustdoc actually covered let anyDoc = false; for (let mi = 0; mi < members.length; mi++) { const cn = crateNames[mi]; @@ -274,7 +275,6 @@ function main() { } } if (anyDoc) method = symbols.length ? 'rustdoc-json' : 'source-scan'; - var rustdocMemberSet = rustdocCrates; } // ---- Fallback / complement: source scan for any file type not covered by rustdoc-json ---- @@ -283,7 +283,7 @@ function main() { const seen = new Set(symbols.map((s) => `${s.file}|${s.name}|${s.kind}`)); const scan = symbolsFromSourceScan(repoDir, skip, rel, target.codeExt); const haveRustdoc = method === 'rustdoc-json'; - const coveredByRustdoc = (typeof rustdocMemberSet !== 'undefined') ? rustdocMemberSet : new Set(); + const coveredByRustdoc = rustdocCrates; // A .rs file is authoritatively covered ONLY if its crate member dir was rustdoc'd. Crates whose // rustdoc failed (e.g. a build error) still get their public symbols from the source scan. const fileCoveredByRustdoc = (relp) => { diff --git a/kb/index-primer.mjs b/kb/index-primer.mjs index 801a735..66bd3e8 100644 --- a/kb/index-primer.mjs +++ b/kb/index-primer.mjs @@ -1,93 +1,48 @@ #!/usr/bin/env node // index-primer.mjs — TOP-DOWN ORIENTATION LAYER. // -// Indexes a synthesized "primer" markdown INTO an existing Cognitum RVF knowledge base so the -// six top-down comprehension-journey questions (what is it / concepts / how each works / -// maturity / where are the docs / how to use end-to-end) return a whole synthesized section -// instead of a raw repo fragment. This is an idempotent REPLACE (ADR-0010 D6): any existing -// PRIMER# generation is deleted from the store and filtered from the sidecars before the fresh -// one is ingested, so re-running never duplicates the orientation layer. Mutation is staged on -// a clone of the .rvf (+ .idmap.json) and published atomically with the sidecars, under the -// StoreSet lock shared with build-kb.mjs --delta. Ids are allocated from the persisted -// high-water mark (ids.json maxIdEver) so they never collide or reuse. PARITY holds throughout. +// Indexes a synthesized "primer" markdown INTO an existing RVF knowledge base so the six +// top-down comprehension-journey questions (what is it / concepts / how each works / maturity / +// where are the docs / how to use end-to-end) return a whole synthesized section instead of a raw +// repo fragment. This is an idempotent REPLACE (ADR-0010 D6): any existing PRIMER# generation is +// deleted from the store and filtered from the sidecars before the fresh one is ingested, so +// re-running never duplicates the orientation layer. Mutation is staged on a clone of the .rvf +// (+ .idmap.json) and published atomically with the sidecars, under the StoreSet lock shared with +// build-kb.mjs --delta. Ids are allocated from the persisted high-water mark (ids.json maxIdEver) +// so they never collide or reuse. PARITY holds throughout. // -// Usage: -// node kb/index-primer.mjs ruvector # indexes ../ruvector-primer.md into ruvector-kb -// node kb/index-primer.mjs ruview # indexes ../ruview-primer.md into ruview-kb +// Usage: node kb/index-primer.mjs # indexes /-primer.md into -kb +// Library: import { indexPrimer } from './index-primer.mjs'; await indexPrimer(slug) (throws on failure) // -// Section splitting: split the primer into logical documents on level-2 markdown headers -// (## ...), fence-aware (a '#' inside a ``` code block is NOT a header). Each ## section -// (with its nested ### subsections) is ONE logical document under a synthetic path -// `PRIMER#`. A short level-1 title/preamble at the top is folded into the first section -// so nothing is lost. Sections > CHUNK_CHARS are chunked, but all chunks keep the SAME -// synthetic path so whole-doc retrieval reassembles them. -// -// Deps resolved PORTABLY via resolve-deps.mjs (project node_modules -> env -> Mac paths). +// Section splitting: the primer is split on level-2 markdown headers (## ...), fence-aware (a '#' +// inside a ``` code block is NOT a header). Each ## section (with its nested ### subsections) is +// ONE logical document under a synthetic path `PRIMER#`. A short level-1 title/preamble at +// the top is folded into the first section so nothing is lost. Sections > CHUNK_CHARS are chunked, +// but all chunks keep the SAME synthetic path so whole-doc retrieval reassembles them. import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { loadRvf, loadTransformers, configureModel, chooseModelCache } from './resolve-deps.mjs'; -import { targets } from './kb.config.mjs'; -import { SYNTHETIC_PATH_RE, acquireLock, readPassages, cloneFile, publish } from './store-set.mjs'; - -const KB_DIR = path.dirname(fileURLToPath(import.meta.url)); -const ROOT = path.resolve(KB_DIR, '..'); - -const CHUNK_CHARS = 4000; // match the corpus chunker; sections under this stay whole -const OVERLAP_CHARS = 400; // same sliding-window overlap the corpus uses (stitch() de-overlaps) - -// data lives in kb/stores// when organized; flat kb/ otherwise. Indexes the primer -// sections into the SMALL (.small.rvf) build (the Seed default + the source of the bundles). -// KB_STORE_DIR overrides (same convention as build-kb.mjs — lets tests/staging avoid real stores). -const sd = (s) => { - if (process.env.KB_STORE_DIR) return path.resolve(process.env.KB_STORE_DIR); - return fs.existsSync(path.join(KB_DIR, 'stores', s)) ? path.join(KB_DIR, 'stores', s) : KB_DIR; -}; - -// The index/meta sidecar + its chunk-field convention. Generic builds write -kb.ids.json -// with { chunk, of } ('split' style); legacy ruview used -kb.meta.json with "1/3" ('slash'). -function resolveIndex(slug) { - const ids = path.join(sd(slug), `${slug}-kb.ids.json`); - const legacy = path.join(sd(slug), `${slug}-kb.meta.json`); - if (fs.existsSync(ids)) return { index: ids, chunkStyle: 'split' }; - if (fs.existsSync(legacy)) return { index: legacy, chunkStyle: 'slash' }; - return { index: ids, chunkStyle: 'split' }; // default for a not-yet-built store -} - -// Primer path: kb/stores//-primer.md (per plan §2a). Fall back to the legacy flat -// ROOT/-primer.md if a store-local primer is not present. -function primerPath(slug) { - const local = path.join(sd(slug), `${slug}-primer.md`); - const legacy = path.join(ROOT, `${slug}-primer.md`); - return fs.existsSync(local) ? local : legacy; +import { SYNTHETIC_PATH_RE, acquireLock, readPassages, cloneFile, publish, storeDirFor } from './store-set.mjs'; +import { windowChunk } from './chunker.mjs'; + +const __filename = fileURLToPath(import.meta.url); + +// Files of one store: kb/stores// (KB_STORE_DIR overrides, same convention as build-kb.mjs). +function storeFiles(slug) { + const dir = storeDirFor(slug); + const base = path.join(dir, `${slug}-kb`); + return { + dir, base, + primer: path.join(dir, `${slug}-primer.md`), + rvf: `${base}.rvf`, + passages: `${base}.passages.jsonl`, + index: `${base}.ids.json`, + }; } -// Resolve the ship variant: a single-768 build (recipe v1.3.0) writes only -kb.big.rvf; -// the legacy dual-variant build writes -kb.small.rvf. Prefer .big.rvf when present so the -// primer is embedded with — and ingested into — the SAME store/model the corpus used. -function resolveRvf(slug) { - const big = path.join(sd(slug), `${slug}-kb.big.rvf`); - const plain = path.join(sd(slug), `${slug}-kb.rvf`); // single-384 build (recipe v1.3.1) - const small = path.join(sd(slug), `${slug}-kb.small.rvf`); - if (fs.existsSync(big)) return big; - if (fs.existsSync(plain)) return plain; - return small; -} - -// STORES is DERIVED from the config registry — NO hard-coded repo names. -const STORES = Object.fromEntries(Object.keys(targets).map((slug) => { - const ri = resolveIndex(slug); - return [slug, { - primer: primerPath(slug), - rvf: resolveRvf(slug), - passages: path.join(sd(slug), `${slug}-kb.passages.jsonl`), - index: ri.index, - chunkStyle: ri.chunkStyle, - }]; -})); - -function slugify(s) { +export function slugify(s) { return s.toLowerCase() .replace(/[`*_~]/g, '') .replace(/[^a-z0-9]+/g, '-') @@ -98,7 +53,7 @@ function slugify(s) { // Split markdown into level-2 (##) sections, fence-aware. A level-1 (#) title or any preamble // before the first ## is folded into the first section so no text is lost. Returns // [{ title, body }] where body INCLUDES the heading line. -function splitSections(md) { +export function splitSections(md) { const lines = md.split('\n'); let inFence = false; const sections = []; @@ -133,88 +88,80 @@ function splitSections(md) { return sections; } -// Chunk a long section, mirroring the corpus chunker (paragraph-preferred, overlapping window). -function chunkText(text) { - if (text.length <= CHUNK_CHARS) return [text]; - const out = []; - let i = 0; - while (i < text.length) { - let end = Math.min(i + CHUNK_CHARS, text.length); - if (end < text.length) { - const para = text.lastIndexOf('\n\n', end); - if (para > i + CHUNK_CHARS / 2) end = para; - } - out.push(text.slice(i, end)); - if (end >= text.length) break; - i = end - OVERLAP_CHARS; - } - return out; -} - -async function main() { - const store = process.argv[2]; - const conf = STORES[store]; - if (!conf) { console.error(`Usage: node kb/index-primer.mjs <${Object.keys(STORES).join('|')}>`); process.exit(2); } +// Index 's primer into its KB. Throws on any failure (the live store is left untouched). +// Returns { sections, replaced, ingested, totalVectors }. +export async function indexPrimer(slug, { log = console.log } = {}) { + if (!slug) throw new Error('indexPrimer: slug is required'); + const conf = storeFiles(slug); for (const f of [conf.primer, conf.rvf, conf.passages, conf.index]) { - if (!fs.existsSync(f)) { console.error(`MISSING: ${f}`); process.exit(1); } + if (!fs.existsSync(f)) throw new Error(`MISSING: ${f}`); } if (!fs.existsSync(`${conf.rvf}.idmap.json`)) { - console.error(`MISSING: ${conf.rvf}.idmap.json (needed to replace an existing primer generation) — rebuild the KB fully, then re-run`); - process.exit(1); + throw new Error(`MISSING: ${conf.rvf}.idmap.json (needed to replace an existing primer generation) — rebuild the KB fully, then re-run`); } // ---- build the orientation documents ---- - const md = fs.readFileSync(conf.primer, 'utf8'); - const sections = splitSections(md); + const sections = splitSections(fs.readFileSync(conf.primer, 'utf8')); - // entries: { synthPath, title, chunkIdx, chunkTotal, text } + // entries: { path, title, chunkIdx, chunkTotal, text } const entries = []; for (const s of sections) { const synthPath = `PRIMER#${slugify(s.title)}`; - const chunks = chunkText(s.body); + const chunks = windowChunk(s.body); chunks.forEach((c, i) => entries.push({ path: synthPath, title: s.title, chunkIdx: i, chunkTotal: chunks.length, text: c, })); } - const releaseLock = acquireLock(path.join(sd(store), `${store}-kb`)); - try { await replacePrimer(store, conf, sections, entries); } + const releaseLock = acquireLock(conf.base); + try { return await replacePrimer(slug, conf, sections, entries, log); } finally { releaseLock(); } } -async function replacePrimer(store, conf, sections, entries) { - const idx = JSON.parse(fs.readFileSync(conf.index, 'utf8')); - const prevPassages = await readPassages(conf.passages); - - // ---- idempotent REPLACE: drop any existing PRIMER# generation first (ADR-0010 D6) ---- +// Which rows of the previous generation go, which are kept, and where new ids start (never reused: INV-KB7). +// Mutates idx.entries (drops the old primer ids) so re-running can never duplicate the orientation layer. +export function planPrimerReplace(prevPassages, idx) { const oldPrimer = prevPassages.filter((r) => SYNTHETIC_PATH_RE.test(r.path)); const keepLines = prevPassages.filter((r) => !SYNTHETIC_PATH_RE.test(r.path)).map((r) => r.raw); for (const r of oldPrimer) delete idx.entries[r.id]; - - // NEW ids from the persisted high-water mark — never reused, never colliding (INV-KB7). let maxIdEver = Number(idx.maxIdEver || 0); for (const r of prevPassages) { const n = Number(r.id); if (n > maxIdEver) maxIdEver = n; } - const startId = maxIdEver; - console.log(`[index-primer:${store}] sections=${sections.length} new-chunks=${entries.length} ` + return { oldPrimer, keepLines, startId: maxIdEver }; +} + +// The embedder the store was BUILT with: .embed.json, cross-checked against ids.json.model. Primer vectors from +// any other model would be accepted by the store (same dimension) and silently rank wrong, so this throws. +export function readEmbedConfig(embedPath, idx) { + if (!fs.existsSync(embedPath)) throw new Error(`MISSING: ${embedPath} (the embedder the store was built with) — rebuild the KB fully, then re-run`); + let cfg; + try { cfg = JSON.parse(fs.readFileSync(embedPath, 'utf8')); } catch (e) { throw new Error(`UNREADABLE: ${embedPath}: ${e.message}`); } + if (!cfg.model) throw new Error(`INVALID: ${embedPath} has no model`); + if (idx && idx.model && idx.model !== cfg.model) { + throw new Error(`embedder mismatch: ids.json says the store was built with ${idx.model} but ${path.basename(embedPath)} says ${cfg.model} — rebuild the KB fully`); + } + return cfg; +} + +async function replacePrimer(store, conf, sections, entries, log) { + const idx = JSON.parse(fs.readFileSync(conf.index, 'utf8')); + const prevPassages = await readPassages(conf.passages); + + // ---- idempotent REPLACE: drop any existing PRIMER# generation first (ADR-0010 D6) ---- + const { oldPrimer, keepLines, startId } = planPrimerReplace(prevPassages, idx); + log(`[index-primer:${store}] sections=${sections.length} new-chunks=${entries.length} ` + `replacing=${oldPrimer.length} old primer chunks | start-id=${startId + 1}`); // ---- embed (same model/pooling/normalize as the corpus build) ---- - // Read the embedder config the build wrote next to the .rvf (.embed.json). For a single-768 - // bge store that is { model: bge, pooling: cls } so the primer is embedded with the SAME model - // (else 384-dim vectors would be rejected by a 768-dim store). PASSAGES get NO query prefix. - const embedCfg = (() => { - const p = `${conf.rvf}.embed.json`; - if (fs.existsSync(p)) { try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { /* fall through */ } } - return { model: 'Xenova/all-MiniLM-L6-v2', pooling: 'mean', normalize: true }; - })(); - const EMBED_MODEL = embedCfg.model || 'Xenova/all-MiniLM-L6-v2'; + // PASSAGES get NO query prefix. The embedder identity comes from the sidecar the build wrote, never a guess. + const embedCfg = readEmbedConfig(`${conf.rvf}.embed.json`, idx); + const EMBED_MODEL = embedCfg.model; const EMBED_POOLING = embedCfg.pooling || 'mean'; const { mod: rvfMod, via: rvfVia } = loadRvf(); const { RvfDatabase } = rvfMod; const { T, via: tVia } = await loadTransformers(); - const modelCache = chooseModelCache(EMBED_MODEL); + const modelCache = chooseModelCache(); const { haveLocalModel } = configureModel(T, modelCache, EMBED_MODEL); - console.log(`[index-primer:${store}] rvf via ${rvfVia} | transformers via ${tVia} | model ${EMBED_MODEL} ` + log(`[index-primer:${store}] rvf via ${rvfVia} | transformers via ${tVia} | model ${EMBED_MODEL} ` + `${haveLocalModel ? 'local' : 'remote'} (${modelCache}) | pooling ${EMBED_POOLING}`); const fe = await T.pipeline('feature-extraction', EMBED_MODEL, { quantized: true }); @@ -222,7 +169,9 @@ async function replacePrimer(store, conf, sections, entries) { const S = `${conf.rvf}.staged`; cloneFile(conf.rvf, S); cloneFile(`${conf.rvf}.idmap.json`, `${S}.idmap.json`); - const cleanupStaged = () => { for (const f of [S, `${S}.idmap.json`]) fs.rmSync(f, { force: true }); }; + const stagedPassages = `${conf.passages}.staged`; + const stagedIndex = `${conf.index}.staged`; + const cleanupStaged = () => { for (const f of [S, `${S}.idmap.json`, stagedPassages, stagedIndex]) fs.rmSync(f, { force: true }); }; const newLines = []; let ingested = 0; @@ -243,12 +192,8 @@ async function replacePrimer(store, conf, sections, entries) { const ingest = batch.map((e, j) => { const id = String(startId + i + j + 1); newLines.push(JSON.stringify({ id, text: e.text, path: e.path, title: e.title })); - // index entry — match each KB's existing chunk-field convention - const chunkField = conf.chunkStyle === 'slash' - ? { chunk: `${e.chunkIdx + 1}/${e.chunkTotal}` } - : { chunk: e.chunkIdx + 1, of: e.chunkTotal }; idx.entries[id] = { - path: e.path, kind: 'primer-orientation', title: e.title, ...chunkField, + path: e.path, kind: 'primer-orientation', title: e.title, chunk: e.chunkIdx + 1, of: e.chunkTotal, preview: e.text.slice(0, 240).replace(/\s+/g, ' '), }; // NO metadata field: @ruvector/rvf 0.3.0 rejects it (issue #704); the sidecars carry it. @@ -268,10 +213,8 @@ async function replacePrimer(store, conf, sections, entries) { await db.close(); // writes the staged .idmap.json idx.maxIdEver = startId + entries.length; - const stagedPassages = `${conf.passages}.staged`; fs.writeFileSync(stagedPassages, keepLines.concat(newLines).join('\n') + '\n'); - const stagedIndex = `${conf.index}.staged`; - fs.writeFileSync(stagedIndex, JSON.stringify(idx, null, conf.chunkStyle === 'slash' ? 1 : 0)); + fs.writeFileSync(stagedIndex, JSON.stringify(idx, null, 0)); publish([ { staged: S, live: conf.rvf }, { staged: `${S}.idmap.json`, live: `${conf.rvf}.idmap.json` }, @@ -280,12 +223,18 @@ async function replacePrimer(store, conf, sections, entries) { ]); } catch (e) { cleanupStaged(); - console.error(`[index-primer:${store}] FAILED (live store untouched):`, e.message); - process.exit(1); + throw new Error(`index-primer ${store} FAILED (live store untouched): ${e.message}`); } - console.log(`[index-primer:${store}] OK — replaced ${oldPrimer.length} old primer chunks with ${ingested} fresh ` - + `| orientation sections=${sections.length} | totalVectors=${keepLines.length + entries.length}`); + const totalVectors = keepLines.length + entries.length; + log(`[index-primer:${store}] OK — replaced ${oldPrimer.length} old primer chunks with ${ingested} fresh ` + + `| orientation sections=${sections.length} | totalVectors=${totalVectors}`); + return { sections: sections.length, replaced: oldPrimer.length, ingested, totalVectors }; } -main().catch((e) => { console.error('ERROR:', e); process.exit(1); }); +// Run as CLI only when invoked directly, so importing this module never exits the process. +if (process.argv[1] && path.resolve(process.argv[1]) === __filename) { + const slug = process.argv[2]; + if (!slug) { console.error('Usage: node kb/index-primer.mjs '); process.exit(2); } + indexPrimer(slug).catch((e) => { console.error(e.message); process.exit(1); }); +} diff --git a/kb/kb-mcp-server.mjs b/kb/kb-mcp-server.mjs index 0920808..ed5259c 100644 --- a/kb/kb-mcp-server.mjs +++ b/kb/kb-mcp-server.mjs @@ -1,30 +1,29 @@ #!/usr/bin/env node -// kb-mcp-server.mjs — self-contained MCP stdio server for the Cognitum RVF knowledge bases. +// kb-mcp-server.mjs — self-contained MCP stdio server for the RVF knowledge bases in kb.config.mjs. // -// Exposes ONE tool: -// search_kb({ query: string, k?: number = 6, store: "ruvector"|"ruview" }) -// It embeds the query locally (MiniLM), queries the requested .rvf readonly, then loads -// the FULL passage text for each hit from the matching .passages.jsonl and returns it as -// readable text (path + title + full passage). +// Tools: search_kb({ query, k?: 6, store? }), lookup_symbol, get_entrypoints, get_dep_graph. +// `store` is optional: it defaults to the only configured store (a knowledge pack ships one), +// else to the config's defaultTarget. search_kb embeds the query locally with the store's own +// embedder, queries the .rvf readonly and returns whole matched documents (path + title + text). // -// Self-contained: needs only @ruvector/rvf (npm-global), @xenova/transformers (AppealArmor -// build), and the bundled kb/*.rvf + kb/*.passages.jsonl. It implements the MCP JSON-RPC -// stdio protocol directly (no @modelcontextprotocol/sdk dependency), so it runs anywhere -// Node 18+ is available. +// Self-contained: needs only @ruvector/rvf and @xenova/transformers (see resolve-deps.mjs) plus +// the store files. It implements the MCP JSON-RPC stdio protocol directly (no +// @modelcontextprotocol/sdk dependency), so it runs anywhere Node 18+ is available. // -// Wire it into .mcp.json (see kb/README) — DO NOT use @ruvector/rvf-mcp-server (a stub). -// -// Env overrides: KB_TRANSFORMERS_PATH, KB_MODEL_CACHE (see ask-kb.mjs). +// Env overrides: XENOVA_PATH, RVF_MODULE_PATH, KB_MODEL_CACHE (see resolve-deps.mjs). + +import { searchKb, lookupSymbol, getEntrypoints, getDepGraph, formatDocument } from './ask-kb.mjs'; +import * as kbConfig from './kb.config.mjs'; -import { searchKb, lookupSymbol, getEntrypoints, getDepGraph } from './ask-kb.mjs'; -import { targets, defaultTarget } from './kb.config.mjs'; +const { targets } = kbConfig; const PROTOCOL_VERSION = '2024-11-05'; // Server identity + tool surface are DERIVED from the config registry — NO hard-coded repo names. const STORE_SLUGS = Object.keys(targets); const KNOWN_STORES = new Set(STORE_SLUGS); -const DEFAULT_STORE = defaultTarget; +// A single-store pack defaults to its own store; a multi-store registry to its defaultTarget when that is known. +const DEFAULT_STORE = KNOWN_STORES.has(kbConfig.defaultTarget) ? kbConfig.defaultTarget : STORE_SLUGS[0]; const META_NAME = (targets[DEFAULT_STORE] && targets[DEFAULT_STORE].metaName) || DEFAULT_STORE; const SERVER_INFO = { name: `${DEFAULT_STORE}-kb`, version: '1.0.0' }; @@ -40,7 +39,7 @@ const TOOLS = [ { name: 'search_kb', description: - `Semantic search over the ${META_NAME} RVF knowledge base(s). Returns up to 5 whole, ` + `Semantic search over the ${META_NAME} RVF knowledge base(s). Returns up to k (default 6) whole, ` + 'self-contained matched DOCUMENTS (all chunks of each reassembled in order, not fragments) ' + '— READMEs, ADRs, package/component docs, source doc-comments, primers — each with its repo ' + `path and title. Available stores: ${STORE_DESCRIPTIONS}.`, @@ -49,7 +48,7 @@ const TOOLS = [ properties: { query: { type: 'string', description: 'Natural-language question or keywords.' }, store: { type: 'string', enum: STORE_SLUGS, description: 'Which knowledge base to search.', default: DEFAULT_STORE }, - k: { type: 'integer', description: 'Number of passages to return (default 6).', default: 6 }, + k: { type: 'integer', description: 'Number of documents to return (default 6).', default: 6 }, }, required: ['query'], }, @@ -88,7 +87,7 @@ const TOOLS = [ }, ]; -// ---------- minimal JSON-RPC over stdio (newline-delimited, also tolerates LSP framing) ---------- +// ---------- minimal JSON-RPC over stdio (newline-delimited JSON only; Content-Length framing is NOT supported) ---------- function send(obj) { process.stdout.write(JSON.stringify(obj) + '\n'); } @@ -124,13 +123,7 @@ async function handle(msg) { const k = Math.max(1, parseInt(args.k ?? 6, 10) || 6); if (!query) return err(id, -32602, 'query is required'); const results = await searchKb({ query, k, store }); - const text = results.map((r, i) => - `#${i + 1} (distance ${r.bestDistance.toFixed(4)})\n` - + `path : ${r.path}\n` - + `title: ${r.title}\n` - + `----- full document (${r.fullText.length} chars, ${r.chunksJoined} chunk(s)${r.truncated ? ', truncated' : ''}) -----\n` - + `${r.fullText}\n` - ).join('\n========================================================\n\n'); + const text = results.map(formatDocument).join('\n========================================================\n\n'); return ok(id, { content: [{ type: 'text', text: text || '(no results)' }], isError: false }); } if (name === 'lookup_symbol') { diff --git a/kb/kb.config.mjs b/kb/kb.config.mjs index e0e798f..c72e980 100644 --- a/kb/kb.config.mjs +++ b/kb/kb.config.mjs @@ -1,17 +1,14 @@ -// kb.config.mjs — Config registry for the generic, config-driven KB pipeline. -// P0 scaffold: the `agent-harness-generator` ("MetaHarness") target entry only. -// Binding: build-plan-metaharness.md §2a [D10, A]. ONE target until ≥98 + sign-off [L]. -// -// Mechanics are preserved from the proven Cognitum prototype; repo-shape becomes DATA here. -// All on-page commands + KB `mustContain` facts use `metaharness` as PRIMARY, -// note `create-agent-harness` as the ALIAS (same tool; reconciliation note in the plan §0). +// kb.config.mjs — registry of KB targets for the config-driven KB engine (repo shape is DATA here). +// A target missing from this file is registered per build, not by editing it: src/station-runners.mjs +// (kbRegister) writes {slug: entry} JSON to the file named by KB_TARGET_OVERLAY, merged into `targets` below. +// repoDir values are relative; KB_REPO_DIR (set by tools/build-kb.mjs) overrides them for a real build. +// Fields every reader consumes: slug, metaName, embed (REQUIRED), productNames, repoDir, scopeExclude, +// codeExt, componentRoots, componentWord, include; ask-kb also reads primerSlugs, disambiguation and +// offtopicMagnets; kb-mcp-server reads bundle.blurb. -/** - * componentWord synonym group — first-class config knob injected into every intent regex - * in ask-kb.mjs. AHG is npm-package-based (`packages/`), NOT crate-based, so the - * hard-coded "crate" token in the prototype must be widened or Stage-3/4 retrieval under-fires. - * (Top risk #1 in the plan.) - */ +import fs from 'node:fs'; + +/** Generic component synonym group, injected into ask-kb's intent regexes. */ const componentWord = ['crate', 'package', 'module', 'component']; /** @type {Record} keyed by target slug. */ @@ -28,7 +25,7 @@ export const targets = { "rvfSuffix": ".rvf" }, "productNames": [], - "repoDir": "/Users/stuartkerr/Code/Ruv-Explainer/explainer-builds/mcp-studio/repo", + "repoDir": "../.targets/mcp-studio", "scopeExclude": [ "node_modules", "dist", @@ -50,12 +47,6 @@ export const targets = { ".mjs", ".js" ], - "fullTextExt": [ - ".md", - ".mdx", - ".txt" - ], - "templateExt": [], "componentRoots": [ "app", "lib", @@ -113,7 +104,7 @@ export const targets = { "rvfSuffix": ".rvf" }, "productNames": [], - "repoDir": "/Users/stuartkerr/Code/Ruv-Explainer/explainer-builds/ruos/repo", + "repoDir": "../.targets/ruos", "scopeExclude": [ "node_modules", "dist", @@ -130,12 +121,6 @@ export const targets = { ".mjs", ".json" ], - "fullTextExt": [ - ".md", - ".mdx", - ".txt" - ], - "templateExt": [], "componentRoots": [ "mcp", "src", @@ -192,7 +177,7 @@ export const targets = { "productNames": [ "ternlight" ], - "repoDir": "/Users/stuartkerr/Code/Ruv-Explainer/explainer-builds/ternlight/repo", + "repoDir": "../.targets/ternlight", "scopeExclude": [ "node_modules", "dist", @@ -216,12 +201,6 @@ export const targets = { ".cpp", ".h" ], - "fullTextExt": [ - ".md", - ".mdx", - ".txt" - ], - "templateExt": [], "componentRoots": [ "src" ], @@ -282,7 +261,7 @@ export const targets = { "MTWM", "gateway-v2" ], - "repoDir": "/Users/stuartkerr/Code/Ruv-Explainer/explainer-builds/autonomous-wealth-builder/repo", + "repoDir": "../.targets/autonomous-wealth-builder", "scopeExclude": [ "node_modules", "dist", @@ -305,12 +284,6 @@ export const targets = { ".sh", ".sql" ], - "fullTextExt": [ - ".md", - ".mdx", - ".txt" - ], - "templateExt": [], "componentRoots": [ "services", "mtwm-ui", @@ -374,7 +347,7 @@ export const targets = { "productNames": [ "AgentBBS" ], - "repoDir": "/Users/stuartkerr/Code/Ruv-Explainer/explainer-builds/agentbbs/repo", + "repoDir": "../.targets/AgentBBS", "scopeExclude": [ "node_modules", "dist", @@ -395,13 +368,6 @@ export const targets = { ".rb", ".sh" ], - "fullTextExt": [ - ".md", - ".mdx", - ".txt", - ".rst" - ], - "templateExt": [], "componentRoots": [ "src", "lib", @@ -471,7 +437,7 @@ export const targets = { "productNames": [ "chalk" ], - "repoDir": "/tmp/agentic-smoke-chalk2/repo", + "repoDir": "../.targets/chalk", "scopeExclude": [ "node_modules", "dist", @@ -487,12 +453,6 @@ export const targets = { ".mjs", ".cjs" ], - "fullTextExt": [ - ".md", - ".mdx", - ".txt" - ], - "templateExt": [], "componentRoots": [ "source", "src", @@ -551,7 +511,7 @@ export const targets = { "productNames": [ "helix" ], - "repoDir": "/Users/stuartkerr/Code/Ruv-Explainer/explainer-builds/helix/repo", + "repoDir": "../.targets/helix", "scopeExclude": [ "node_modules", "dist", @@ -575,13 +535,6 @@ export const targets = { ".yml", ".json" ], - "fullTextExt": [ - ".md", - ".mdx", - ".txt", - ".rst" - ], - "templateExt": [], "componentRoots": [ "src", "lib", @@ -646,7 +599,7 @@ export const targets = { // public API in src/index.js (open/openBase/branch/fork/checkpoint/rollback/diff/ // promote/query), the CLI in bin/agenticow.js, and the runnable use-case scripts // in examples/. repoDir points at the live build-dir clone. Registered for the - // explainmyrepo recipe acceptance run (2026-06-28). + // explainmyrepo recipe acceptance run. // ────────────────────────────────────────────────────────────────────────── agenticow: { slug: 'agenticow', @@ -672,24 +625,6 @@ export const targets = { docs: 'PRIMER#6-where-do-i-read-more-the-docs-map', adr: 'PRIMER#6-where-do-i-read-more-the-docs-map', playbook: 'PRIMER#7-how-do-i-install-and-use-it-end-to-end', - extensibility: 'PRIMER#8-how-do-i-extend-agenticow', - gotchas: 'PRIMER#9-cost-latency-and-gotchas', - }, - extensionFiles: { - 'verb': ['src/index.js', 'src/index.d.ts'], - 'branch': ['src/index.js', 'examples/git-workflow.mjs'], - 'cli': ['bin/agenticow.js'], - 'command':['bin/agenticow.js'], - 'example':['examples/red-team-sandbox.mjs', 'examples/parallel-agents.mjs'], - }, - docFiles: { - cli: ['README.md', 'bin/agenticow.js'], - usage: ['README.md', 'examples/README.md'], - }, - typeAliases: { - 'memory': 'AgenticMemory', - 'open': 'open', - 'fork': 'fork', }, // ── Source scope (force-walk; clone has no .gitmodules) ── @@ -697,8 +632,6 @@ export const targets = { scopeExclude: ['node_modules', 'dist', 'target', '.git', 'coverage', 'pkg', '.next', 'docs'], codeExt: ['.ts', '.tsx', '.js', '.mjs', '.cjs'], - fullTextExt: ['.md', '.mdx', '.txt'], - templateExt: [], componentRoots: ['src', 'bin', 'examples'], componentWord: ['verb', 'method', 'api', 'module', 'component', 'example'], @@ -717,12 +650,12 @@ export const targets = { // ── Identity ──────────────────────────────────────────────────────────── slug: 'agent-harness-generator', metaName: 'MetaHarness', - // ── Embedder (ADR-0001 v1.3.1: SINGLE 384-dim desktop variant) ──────────── + // ── Embedder (single 384-dim variant) ───────────────────────────────────── // bge-small-en-v1.5 (cls-pooled, normalized, asymmetric query prefix) — the SAME embedder // proven on ruqu/ruvn. build-kb.mjs writes the canonical un-suffixed // stores/agent-harness-generator/agent-harness-generator-kb.rvf + a .embed.json sidecar that // ask-kb + index-primer read (so query + primer use the SAME model). Model is cached offline at - // kb/models-cache/Xenova/bge-small-en-v1.5 (HF_HUB_OFFLINE=1) for fast deterministic builds. + // kb/models-cache/Xenova/bge-small-en-v1.5 for fast deterministic builds. embed: { model: 'Xenova/bge-small-en-v1.5', dim: 384, @@ -756,67 +689,6 @@ export const targets = { docs: 'PRIMER#6-where-do-i-read-about-the-architecture', adr: 'PRIMER#6-where-do-i-read-about-the-architecture', playbook: 'PRIMER#7-how-do-i-start-the-fastest-end-to-end', - // §8/§9 added for the AI-comprehension gate (extensibility + gotchas dimensions). - extensibility: 'PRIMER#8-how-do-i-extend-metaharness-safely-the-extension-points', - gotchas: 'PRIMER#9-performance-and-gotchas-running-the-generator', - }, - - // extensionFiles — concept word -> the real extension-point file(s) it touches. Consumed by the - // AI-comprehension grader (and a useful map for any AI): "add a host" -> the kernel HostAdapter - // contract + a reference adapter, etc. Every file below IS indexed (in passages.jsonl); PRIMER#8 - // names them in prose. Paths verified against .targets/agent-harness-generator 2026-06-19. - extensionFiles: { - 'host': ['packages/kernel-js/src/types.ts', 'packages/host-claude-code/src/index.ts', 'docs/adrs/ADR-004-host-integration-model.md'], - 'adapter': ['packages/host-claude-code/src/index.ts', 'packages/kernel-js/src/types.ts', 'docs/adrs/ADR-004-host-integration-model.md'], - 'vertical': ['packages/vertical-base/src/index.ts', 'packages/create-agent-harness/src/registry.ts', 'docs/adrs/ADR-013-vertical-packs-publishing.md'], - 'template': ['packages/create-agent-harness/src/walker.ts', 'packages/create-agent-harness/src/renderer.ts', 'docs/adrs/ADR-003-generator-architecture.md'], - 'composer': ['packages/create-agent-harness/src/index.ts', 'packages/create-agent-harness/src/wizard.ts', 'docs/adrs/ADR-003-generator-architecture.md'], - 'scaffold': ['packages/create-agent-harness/src/index.ts', 'packages/create-agent-harness/src/walker.ts'], - 'generator': ['packages/create-agent-harness/src/index.ts', 'docs/adrs/ADR-003-generator-architecture.md'], - 'wizard': ['packages/create-agent-harness/src/wizard.ts'], - 'render': ['packages/create-agent-harness/src/renderer.ts', 'packages/create-agent-harness/src/walker.ts'], - 'rename': ['packages/create-agent-harness/src/rename.ts'], - 'plugin': ['packages/create-agent-harness/src/plugin-init-cmd.ts', 'packages/create-agent-harness/src/registry.ts', 'docs/adrs/ADR-005-marketplace-plugin-design.md'], - 'marketplace':['docs/adrs/ADR-005-marketplace-plugin-design.md', 'packages/create-agent-harness/src/registry.ts'], - 'kernel': ['packages/kernel-js/src/index.ts', 'packages/kernel-js/src/types.ts', 'docs/adrs/ADR-002-kernel-boundary.md'], - 'router': ['packages/router/src/index.ts'], - 'agent': ['packages/sdk/src/index.ts'], - 'skill': ['packages/sdk/src/index.ts'], - 'tool': ['packages/sdk/src/index.ts'], - 'sdk': ['packages/sdk/src/index.ts'], - 'subcommand': ['packages/create-agent-harness/src/subcommands.ts', 'packages/create-agent-harness/src/index.ts'], - 'command': ['packages/create-agent-harness/src/subcommands.ts', 'packages/create-agent-harness/src/index.ts'], - 'manifest': ['packages/create-agent-harness/src/manifest.ts', 'docs/adrs/ADR-003-generator-architecture.md'], - 'upgrade': ['packages/create-agent-harness/src/upgrade.ts', 'docs/adrs/ADR-008-drift-detection.md'], - 'drift': ['packages/create-agent-harness/src/upgrade.ts', 'docs/adrs/ADR-008-drift-detection.md'], - }, - // docFiles — per-dimension authoritative docs the grader injects (the AI reads these for the - // dimension). CLI per-command table lives in docs/USAGE.md; usage examples in the package READMEs. - docFiles: { - cli: ['docs/USAGE.md', 'packages/create-agent-harness/src/index.ts', 'packages/create-agent-harness/src/subcommands.ts'], - // usage: the SDK builders + Router API + the shared kernel TYPE definitions (types.ts holds the - // full HostAdapter / HarnessSpec / HookSpec / McpServerSpec interface bodies — TS interface - // MEMBERS aren't captured as method symbols, so the grader needs the file body to show the - // generateConfig(spec: HarnessSpec) signature) + a reference host adapter implementation. - usage: ['packages/sdk/src/index.ts', 'packages/router/src/index.ts', 'packages/kernel-js/src/types.ts', 'packages/host-claude-code/src/index.ts', 'docs/USAGE.md'], - }, - // typeAliases — concept word in a question -> the public TS type/class whose definition + members - // answer it (the AI reads symbols.json + the file body). Names verified to exist in symbols.json. - typeAliases: { - 'host': 'HostAdapter', - 'adapter': 'HostAdapter', - 'harness spec':'HarnessSpec', - 'spec': 'HarnessSpec', - 'router': 'Router', - 'route': 'RouteResult', - 'vertical': 'VerticalPack', - 'manifest': 'HarnessManifest', - 'agent': 'AgentDef', - 'skill': 'SkillDef', - 'tool': 'ToolDef', - 'genome': 'HarnessPlan', - 'plan': 'HarnessPlan', - 'settings': 'ClaudeCodeSettings', }, // ── Source scope (force-walk; NO .gitmodules in this repo → walk no-op) ── @@ -850,24 +722,17 @@ export const targets = { // ── Extension classes (what each file is, by suffix) ───────────────────── // code: bodies swept via sourceBodies / docCommentSweep rule types. codeExt: ['.ts', '.tsx', '.js', '.mjs', '.cjs', '.rs'], - // fullText: prose swept verbatim (untruncated) via mdSweepFullText. - fullTextExt: ['.md', '.mdx', '.txt'], - // template: the .tmpl/.hbs harness scaffolding (294 files) — first-N-lines + path, - // kind:'template'. Stage-4/7 "what does a generated harness contain" depends on these. - templateExt: ['.tmpl', '.hbs', '.handlebars'], // ── Component model ────────────────────────────────────────────────────── - // componentRoots per plan §2a. NOTE: repo ALSO has crates/, apps/, examples-packages/; - // plan specifies ["packages"] only for P0 — see deviation note in the P0 report. + // The repo also has crates/, apps/, examples-packages/; only packages/ are components. componentRoots: ['packages'], componentWord, // ['crate','package','module','component'] synonym group - // ── Disambiguation / off-topic magnets (filled during gate-A tuning, P6a) ── + // ── Disambiguation / off-topic magnets ── disambiguation: [], offtopicMagnets: [], - // ── Corpus include rules (consumed by build-kb.mjs / corpus-rules.mjs in P1) ── - // P0 lays the intent; rule-type implementations land in P1 (corpus-rules.mjs). + // ── Corpus include rules (corpus-rules.mjs) ── include: [ { rule: 'mdSweepFullText', roots: ['docs', 'docs/adrs', '.'] }, // README + docs + ADRs, verbatim { rule: 'componentManifests', roots: ['packages', 'examples-packages'] }, // package.json per component @@ -884,75 +749,12 @@ export const targets = { { rule: 'templates', roots: ['packages'], ext: ['.tmpl', '.hbs', '.handlebars'], headLines: 40 }, ], - // ── Verification queries: ONE per arc stage (7 total) ───────────────────── - // Arc: why-built → what-problem/capabilities → inventory → how-each-works(composer) - // → maturity → docs-where → end-to-end-usage. Facts verified against source 2026-06-19. - verificationQueries: [ - { - stage: 1, - arc: 'what-is-it', - query: 'What is metaharness?', - wantPaths: ['README.md', 'docs/OVERVIEW.md'], - mustContain: ['factory for agent frameworks', 'harness is the product', 'npx metaharness'], - }, - { - stage: 2, - arc: 'capabilities', - query: 'What can the tool do to a repo?', - wantPaths: ['README.md', 'docs/USAGE.md'], - mustContain: ['score', 'genome', 'mcp-scan', 'threat-model', 'router', 'Darwin'], - }, - { - stage: 3, - arc: 'inventory-components', - query: 'What packages make up metaharness?', - wantPaths: ['packages', 'docs/ARCHITECTURE.md'], - mustContain: ['kernel', 'host-claude-code', 'router', 'darwin', 'three-layer'], - }, - { - stage: 4, - arc: 'how-each-works-composer', - query: 'How does the composer scaffold a harness?', - wantPaths: ['docs/adrs/ADR-003-generator-architecture.md', 'docs/ARCHITECTURE.md'], - // Composer 7 stages, verified ADR-003 lines 104–110. - mustContain: ['Identity', 'Hosts', 'Primitives', 'Agents', 'Skills', 'Plugins', 'Features', 'mcp'], - }, - { - stage: 5, - arc: 'maturity', - query: 'Is this production-ready?', - wantPaths: ['README.md', 'docs/USERGUIDE.md'], - mustContain: ['v0.1.x beta', '568', 'never'], - }, - { - stage: 6, - arc: 'docs-where-things-live', - query: 'Where do I read about the architecture?', - wantPaths: ['docs/ARCHITECTURE.md', 'docs/adrs'], - mustContain: ['ARCHITECTURE.md', 'OVERVIEW.md', 'USERGUIDE.md', 'INDEX.md'], - }, - { - stage: 7, - arc: 'end-to-end-usage', - query: 'How do I start the fastest?', - wantPaths: ['README.md', 'docs/USAGE.md'], - mustContain: ['npx metaharness --wizard', '--template', '--host', 'npm install'], - }, - ], - - // ── Bundle metadata (consumed by make-bundles.mjs in P1/P7) ─────────────── + // ── Bundle metadata (kb-mcp-server reads blurb) ─────────────────────────── bundle: { blurb: 'MetaHarness drop-in knowledge base — mint a custom AI agent harness from any repo. ' + 'Two halves: for-ai/ (RVF + retrieval brain + MCP server) and for-humans/ (the primer). ' + 'Canonical CLI `npx metaharness` (alias `create-agent-harness`).', - questions: [ - 'What is metaharness and what does it produce?', - 'What can the tool do to a repo before I build?', - 'How does the composer scaffold a harness end-to-end?', - 'Is this production-ready and what are its honest limits?', - 'How do I start the fastest?', - ], }, }, @@ -962,13 +764,13 @@ export const targets = { // metaharness (vertical:research). NOT crate-based: its "components" are the // six pipeline AGENTS in src/agents/ (scout → web-searcher → source-grader → // synthesizer → fact-checker → citer). No .gitmodules → force-walk own tree. - // Facts verified against .targets/ruvn 2026-06-19 (README/CLAUDE.md/package.json + // Facts verified against .targets/ruvn (README/CLAUDE.md/package.json // /src/agents/*/bin/cli.js/scripts/openrouter-validate.mjs/.harness/manifest.json). // ────────────────────────────────────────────────────────────────────────── ruvn: { slug: 'ruvn', metaName: 'ruvn', - // ── Embedder (ADR-0001 v1.3.1: SINGLE 384-dim desktop variant) ──────────── + // ── Embedder (single 384-dim variant) ───────────────────────────────────── // bge-small-en-v1.5 — a strong retrieval model (beats all-MiniLM); mean-pooled, // normalized, with the BGE asymmetric query prefix. build-kb.mjs writes the // canonical un-suffixed stores/ruvn/ruvn-kb.rvf + a .embed.json sidecar that @@ -1005,46 +807,6 @@ export const targets = { docs: 'PRIMER#6-where-do-i-read-more-the-docs-map', adr: 'PRIMER#6-where-do-i-read-more-the-docs-map', playbook: 'PRIMER#7-how-do-i-install-and-use-it-end-to-end', - // §8/§9 added for the AI-comprehension gate (extensibility + gotchas dimensions). - extensibility: 'PRIMER#8-how-do-i-extend-ruvn-safely-the-extension-points', - gotchas: 'PRIMER#9-cost-latency-and-gotchas-running-the-pipeline', - }, - // extensionFiles — concept word -> the real extension-point file(s) it touches. Consumed by the - // AI-comprehension grader (and a useful map for any AI): "add a new agent" -> src/agents/*.ts + - // the validate script that discovers agents, "add a CLI command" -> bin/cli.js, "add a host" -> - // package.json. These files ARE indexed (in passages.jsonl); PRIMER#8 names them in prose. - extensionFiles: { - 'agent': ['src/agents/scout.ts', 'src/agents/synthesizer.ts', 'scripts/openrouter-validate.mjs'], - 'prompt': ['src/agents/scout.ts', 'src/agents/source-grader.ts'], - 'system_prompt': ['src/agents/scout.ts', 'src/agents/synthesizer.ts'], - 'pipeline': ['src/agents/scout.ts', 'src/agents/citer.ts', 'CLAUDE.md'], - 'grade': ['src/agents/source-grader.ts', 'src/agents/synthesizer.ts'], - 'grading': ['src/agents/source-grader.ts'], - 'rubric': ['src/agents/source-grader.ts', 'CLAUDE.md'], - 'tier': ['src/agents/web-searcher.ts', 'scripts/openrouter-validate.mjs'], - 'model': ['scripts/openrouter-validate.mjs', 'src/agents/web-searcher.ts'], - 'cli': ['bin/cli.js'], - 'command': ['bin/cli.js'], - 'subcommand': ['bin/cli.js'], - 'host': ['package.json', 'README.md', 'install.md'], - 'adapter': ['package.json', 'bin/cli.js'], - 'validate': ['scripts/openrouter-validate.mjs', '__tests__/openrouter.integration.test.ts'], - 'test': ['__tests__/smoke.test.ts', '__tests__/openrouter.integration.test.ts'], - }, - // docFiles — per-dimension authoritative docs the grader injects (the AI reads these for the - // dimension). ruvn has no cli/README.md: the CLI is bin/cli.js + the README "Install & use" - // section; usage examples live in the README + the agent prompt files + the validate script. - docFiles: { - cli: ['README.md', 'bin/cli.js'], - usage: ['README.md', 'CLAUDE.md'], - }, - // typeAliases — concept word in a question -> the public symbol whose signature answers it. - // ruvn's "API" is the agent prompt modules (each exports SYSTEM_PROMPT/NAME/TIER) + the CLI - // `run(argv)` dispatcher. The grader's usage-injector matches struct/enum names; ruvn has none, - // so this map mainly documents intent (the agent modules + run are surfaced by name match). - typeAliases: { - 'dispatch': 'run', - 'cli': 'run', }, // ── Source scope (force-walk; NO .gitmodules in this repo → walk no-op) ── @@ -1061,8 +823,6 @@ export const targets = { // ── Extension classes ──────────────────────────────────────────────────── codeExt: ['.ts', '.tsx', '.js', '.mjs', '.cjs'], - fullTextExt: ['.md', '.mdx', '.txt'], - templateExt: [], // ── Component model: the six agents live under src/agents/ ──────────────── // componentWord widened with 'agent' so the inventory archetype fires for @@ -1070,7 +830,7 @@ export const targets = { componentRoots: ['src/agents'], componentWord: ['agent', 'host', 'crate', 'package', 'module', 'component'], - // ── Disambiguation / off-topic magnets (filled during gate-A tuning) ────── + // ── Disambiguation / off-topic magnets ──────────────────────────────────── // ruvn is a SMALL corpus (16 source chunks + 7 primer sections). A few one-/two-line // host stub files (AGENTS.md, SYSTEM.md, install.md) and the single-prompt agent .ts // files are vector-close to orientation queries and out-rank the rich PRIMER/README. @@ -1080,7 +840,7 @@ export const targets = { disambiguation: [ // capabilities: "what can ruvn do / give me / value / final dossier / synthesizer allowed / // live-model validation" -> PRIMER#2 + README, not the maturity/scope section, the inventory - // section, a single agent .ts, or a host stub. (Widened during gate-A re-tune on bge-small.) + // section, a single agent .ts, or a host stub. { whenSource: '\\b(what can|what does ruvn do|do for me|give me|value of ruvn|value|capabilit|in the (final )?dossier|what is in the|synthesizer (allowed|use)|allowed to use|live model|end-?to-?end|validate ruvn|run ruvn end)\\b', goodSource: 'PRIMER#2-what-can-ruvn-do-for-you|README\\.md', badSource: 'PRIMER#5|PRIMER#3|PRIMER#7|src/agents/|AGENTS\\.md|SYSTEM\\.md', goodBoost: 0.34, badPenalty: 0.32 }, @@ -1133,7 +893,7 @@ export const targets = { // (carries six-pass cost, sonnet/haiku tiers, no ruvn-research-command, host-owns-web-search, // grade-A/B caps coverage, starting-dossier-not-verdict). Fires on cost/perf/empty phrasings. // Deliberately does NOT match "grading rubric" or a bare "run a research pipeline" (those are - // the docs / install+pipeline questions Gate A owns); it owns cost/latency/empty-result/gotcha. + // the docs / install+pipeline questions); it owns cost/latency/empty-result/gotcha. { whenSource: '\\b(cost|how much|expensive|token|slow|latency|how (many|long).{0,20}(model|call|pass|run)|six (model )?passes|why is.{0,12}(it|ruvn|my run).{0,8}slow|(dossier|it|results?) (come|comes|came) back (empty|thin)|(empty|thin) (dossier|result)|dossier (be|is|come).{0,12}(empty|thin)|gotcha|footgun|pitfall|does ruvn (do|run|have).{0,14}(its own )?(web )?search|(own|bundle).{0,8}(web )?search|no (ruvn )?(research|dossier) command|is there a (research|dossier) command|prompts? not (an )?engine|engine or prompts|build step|need to build before)\\b', goodSource: 'PRIMER#9-cost-latency-and-gotchas|README\\.md', badSource: 'PRIMER#(1|2|3|5|6|7)|AGENTS\\.md|SYSTEM\\.md', goodBoost: 0.46, badPenalty: 0.36 }, @@ -1181,72 +941,12 @@ export const targets = { { rule: 'docCommentSweep', roots: ['src', 'bin', 'scripts', '__tests__'] }, // leading doc comments across tree ], - // ── Verification queries: ONE per arc stage (7 total). Facts verified 2026-06-19. - verificationQueries: [ - { - stage: 1, - arc: 'what-is-it', - query: 'What is ruvn?', - wantPaths: ['PRIMER#1-what-is-ruvn', 'README.md', 'CLAUDE.md'], - mustContain: ['graded, cited evidence dossier', 'research', 'every claim is cited'], - }, - { - stage: 2, - arc: 'capabilities', - query: 'What can ruvn do for me?', - wantPaths: ['PRIMER#2-what-can-ruvn-do-for-you', 'README.md'], - mustContain: ['grades every source', 'adversarially fact-checks', 'bibliography'], - }, - { - stage: 3, - arc: 'inventory-components', - query: 'What agents and hosts make up ruvn?', - wantPaths: ['PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts', 'README.md', 'CLAUDE.md'], - mustContain: ['scout', 'web-searcher', 'source-grader', 'synthesizer', 'fact-checker', 'citer', '9 hosts'], - }, - { - stage: 4, - arc: 'how-it-works-pipeline', - query: 'How does the ruvn pipeline work step by step?', - wantPaths: ['PRIMER#4-how-the-pipeline-works-step-by-step', 'CLAUDE.md', 'README.md'], - mustContain: ['each agent only sees', 'A/B/C/D', 'grade A and B', 'six agents in a line'], - }, - { - stage: 5, - arc: 'maturity', - query: 'Is ruvn production-ready and what are its limits?', - wantPaths: ['PRIMER#5-is-it-production-ready-scope-and-honest-limits', 'README.md'], - mustContain: ['v0.1.1', 'research tool', 'does not give medical advice', 'starting dossier'], - }, - { - stage: 6, - arc: 'docs-where-things-live', - query: 'Where do I read more about ruvn?', - wantPaths: ['PRIMER#6-where-do-i-read-more-the-docs-map', 'README.md', 'install.md'], - mustContain: ['README.md', 'CLAUDE.md', 'install.md'], - }, - { - stage: 7, - arc: 'end-to-end-usage', - query: 'How do I install and use ruvn?', - wantPaths: ['PRIMER#7-how-do-i-install-and-use-it-end-to-end', 'README.md'], - mustContain: ['npm i -g @ruvnet/ruvn', 'ruvn init', 'ruvn doctor', 'validate:openrouter'], - }, - ], - bundle: { blurb: 'ruvn drop-in knowledge base — an AI research harness that turns a question into a graded, ' + 'cited evidence dossier. Six agents in a line (scout → web-searcher → source-grader → ' + 'synthesizer → fact-checker → citer), A/B/C/D source grading, every claim cited. ' + 'Ships adapters for 9 hosts; OpenRouter-validated. Install: npm i -g @ruvnet/ruvn.', - questions: [ - 'What is ruvn and what does it give me back?', - 'What does a graded, cited evidence dossier mean here?', - 'What are the six agents and the nine hosts?', - 'How does the grading + fact-checking pipeline work?', - 'How do I install ruvn and validate it against a real model?', - ], }, }, @@ -1256,19 +956,19 @@ export const targets = { // compressed task-useful MEASUREMENT (a few numbers) instead of a full image; // a small digital decoder reads the answer; every run emits a BLAKE3 receipt. // Rust workspace of 4 crates (core / bench / wasm / cli). No .gitmodules → - // force-walk own tree. Single 768-dim bge variant (recipe v1.3.0). - // Facts verified against .targets/photonlayer @ fe86c9f, 2026-06-19 + // force-walk own tree. + // Facts verified against .targets/photonlayer @ fe86c9f. // (README.md / crates/*/src/*.rs / crates/*/README.md / docs/README.md / // examples/README.md / crates/photonlayer-core/src/lib.rs). // ────────────────────────────────────────────────────────────────────────── photonlayer: { slug: 'photonlayer', metaName: 'PhotonLayer', - // ── Embedder (ADR-0001 v1.3.1: SINGLE 384-dim desktop variant) ──────────── + // ── Embedder (single 384-dim variant) ───────────────────────────────────── // bge-small-en-v1.5 (cls-pooled, normalized, asymmetric query prefix). build-kb.mjs writes the // canonical un-suffixed stores/photonlayer/photonlayer-kb.rvf + a .embed.json sidecar that - // ask-kb + index-primer read (so query + primer use the SAME model). Gate-A tuned at - // rankScale 0.6 (trust bge's raw order gently). Matches the existing .embed.json sidecar. + // ask-kb + index-primer read (so query + primer use the SAME model). rankScale 0.6 trusts + // bge's raw order gently. // Model cached offline at kb/models-cache/Xenova/bge-small-en-v1.5 for fast builds. embed: { model: 'Xenova/bge-small-en-v1.5', @@ -1303,62 +1003,6 @@ export const targets = { docs: 'PRIMER#6-where-do-i-read-more-the-docs-map', adr: 'PRIMER#6-where-do-i-read-more-the-docs-map', playbook: 'PRIMER#7-how-do-i-install-and-run-it-end-to-end', - // §8/§9 added for the AI-comprehension gate (extensibility + gotchas dimensions). - extensibility: 'PRIMER#8-how-do-i-extend-photonlayer-safely-the-extension-points', - gotchas: 'PRIMER#9-performance-determinism-and-gotchas', - }, - // extensionFiles — concept word -> the real extension-point file(s) it touches. Consumed by the - // AI-comprehension grader (and a useful map for any AI). Files verified present in source + - // indexed in passages.jsonl; PRIMER#8 names them in prose. (Facts checked against source.) - extensionFiles: { - 'propagation': ['crates/photonlayer-core/src/propagate.rs', 'crates/photonlayer-core/src/config.rs'], - 'diffraction': ['crates/photonlayer-core/src/propagate.rs', 'crates/photonlayer-core/src/config.rs'], - 'propagation mode': ['crates/photonlayer-core/src/config.rs', 'crates/photonlayer-core/src/propagate.rs'], - 'adjoint': ['crates/photonlayer-core/src/propagate.rs', 'crates/photonlayer-core/tests/gradient_check.rs'], - 'mask': ['crates/photonlayer-core/src/mask.rs'], - 'phase mask': ['crates/photonlayer-core/src/mask.rs'], - 'detector': ['crates/photonlayer-core/src/detector.rs', 'crates/photonlayer-core/src/config.rs'], - 'sensor': ['crates/photonlayer-core/src/detector.rs', 'crates/photonlayer-core/src/config.rs'], - 'differential': ['crates/photonlayer-bench/src/diffdetect.rs', 'crates/photonlayer-core/src/detector.rs'], - 'decoder': ['crates/photonlayer-bench/src/decoder.rs'], - 'training': ['crates/photonlayer-bench/src/grad_train.rs', 'crates/photonlayer-bench/src/learn.rs'], - 'train': ['crates/photonlayer-bench/src/grad_train.rs', 'crates/photonlayer-bench/src/learn.rs'], - 'gradient': ['crates/photonlayer-bench/src/grad_train.rs', 'crates/photonlayer-core/src/propagate.rs'], - 'optimizer': ['crates/photonlayer-bench/src/grad_adam.rs', 'crates/photonlayer-bench/src/grad_train.rs'], - 'cascade': ['crates/photonlayer-bench/src/grad_cascade.rs'], - 'multiplane': ['crates/photonlayer-bench/src/grad_cascade.rs'], - 'cli': ['crates/photonlayer-cli/src/main.rs'], - 'subcommand': ['crates/photonlayer-cli/src/main.rs'], - 'command': ['crates/photonlayer-cli/src/main.rs'], - 'wasm': ['crates/photonlayer-wasm/src/lib.rs'], - 'binding': ['crates/photonlayer-wasm/src/lib.rs'], - 'javascript': ['crates/photonlayer-wasm/src/lib.rs'], - 'receipt': ['crates/photonlayer-core/src/receipt.rs'], - 'simulator': ['crates/photonlayer-core/src/simulator.rs'], - 'metric': ['crates/photonlayer-core/src/metrics.rs'], - }, - // docFiles — per-dimension authoritative docs the grader injects. CLI usage lives in the CLI - // README + main.rs; runnable usage examples live in the crate READMEs + examples/. - docFiles: { - cli: ['crates/photonlayer-cli/src/main.rs', 'README.md'], - usage: ['crates/photonlayer-core/README.md', 'README.md'], - }, - // typeAliases — concept word in a question -> the public type whose method signatures answer it. - // Lets "run the optical simulator" surface ScalarSimulator's simulate/trace from symbols.json. - // All type names verified against crates/photonlayer-core/src/*.rs. - typeAliases: { - 'simulator': 'ScalarSimulator', - 'simulation': 'ScalarSimulator', - 'mask': 'PhaseMask', - 'config': 'OpticalConfig', - 'field': 'OpticalField', - 'image': 'InputImage', - 'frame': 'OpticalFrame', - 'propagator': 'Propagator', - 'propagation': 'PropagationMode', - 'complex': 'Complex', - 'detector': 'DetectorConfig', - 'receipt': 'ExperimentReceipt', }, // ── Source scope (force-walk; NO .gitmodules in this repo → walk own tree) ── @@ -1377,14 +1021,12 @@ export const targets = { // ── Extension classes ──────────────────────────────────────────────────── codeExt: ['.rs'], - fullTextExt: ['.md', '.mdx', '.txt'], - templateExt: [], // ── Component model: the four crates live under crates/ ──────────────────── componentRoots: ['crates'], componentWord: ['crate', 'module', 'component', 'package'], - // ── Disambiguation / off-topic magnets (gate-A tuned + AI-comprehension §8/§9) ── + // ── Disambiguation / off-topic magnets ── // photonlayer's Rust source is heavily doc-commented and vector-close to orientation queries, // so raw .rs files out-rank the synthesized PRIMER sections for architecture/extensibility/ // gotchas archetypes. These rules route each comprehension archetype to its PRIMER section + @@ -1444,59 +1086,6 @@ export const targets = { { rule: 'docCommentSweep', roots: ['crates'] }, // leading doc comments across tree ], - // ── Verification queries: ONE per arc stage (7 total). Facts verified 2026-06-19. - verificationQueries: [ - { - stage: 1, - arc: 'what-is-it', - query: 'What is PhotonLayer?', - wantPaths: ['PRIMER#1-what-is-photonlayer', 'README.md', 'crates/photonlayer-core/src/lib.rs'], - mustContain: ['phase mask', 'sensor', 'deterministic'], - }, - { - stage: 2, - arc: 'capabilities', - query: 'What can PhotonLayer do?', - wantPaths: ['PRIMER#2-what-can-photonlayer-do', 'README.md'], - mustContain: ['compress', 'sensor pixels', 'receipt'], - }, - { - stage: 3, - arc: 'inventory-components', - query: 'What crates make up PhotonLayer?', - wantPaths: ['PRIMER#3-what-is-photonlayer-made-of-the-four-crates', 'README.md'], - mustContain: ['photonlayer-core', 'photonlayer-bench', 'photonlayer-wasm', 'photonlayer-cli'], - }, - { - stage: 4, - arc: 'how-it-works-pipeline', - query: 'How does the optical pipeline work step by step?', - wantPaths: ['PRIMER#4-how-the-optical-pipeline-works-step-by-step', 'crates/photonlayer-core/src/lib.rs', 'README.md'], - mustContain: ['phase mask', 'propagat', 'sensor', 'decoder'], - }, - { - stage: 5, - arc: 'maturity', - query: 'Is PhotonLayer production-ready and what are its limits?', - wantPaths: ['PRIMER#5-is-it-production-ready-scope-and-honest-limits', 'README.md'], - mustContain: ['simulator', 'No privacy', 'single', 'not'], - }, - { - stage: 6, - arc: 'docs-where-things-live', - query: 'Where do I read more about PhotonLayer?', - wantPaths: ['PRIMER#6-where-do-i-read-more-the-docs-map', 'README.md', 'examples/README.md'], - mustContain: ['README', 'examples', 'crates'], - }, - { - stage: 7, - arc: 'end-to-end-usage', - query: 'How do I install and run PhotonLayer?', - wantPaths: ['PRIMER#7-how-do-i-install-and-run-it-end-to-end', 'README.md'], - mustContain: ['cargo add photonlayer-core', 'cargo run', 'hello_optics'], - }, - ], - bundle: { blurb: 'PhotonLayer drop-in knowledge base — a deterministic optical-AI front end in pure Rust. ' + @@ -1504,13 +1093,6 @@ export const targets = { 'task-useful measurement (a few numbers) instead of a full image; a small decoder reads ' + 'the answer; every run emits a BLAKE3 receipt. Four crates (core / bench / wasm / cli). ' + 'Live demo runs in-browser via WASM. Today a Rust simulator; hardware is on the roadmap.', - questions: [ - 'What is PhotonLayer and what does it actually capture?', - 'What does a learned phase mask do, and how is it different from a normal camera + model?', - 'What are the four crates and what does each one do?', - 'How does the optical pipeline work end to end (image → mask → sensor → decoder → receipt)?', - 'How do I install photonlayer-core and run the first example?', - ], }, }, @@ -1521,18 +1103,16 @@ export const targets = { // engine, and WASM bindings that run ~25-qubit circuits in the browser. Crate-based: // its "components" are the five crates under crates/ (ruqu-core, ruqu-algorithms, // ruqu-exotic, ruqu-wasm, ruQu coherence engine) plus the npx CLI (cli/). - // Single 768-dim bge variant (recipe v1.3.0). Facts verified against - // .targets/ruqu @026d63ef 2026-06-19 (README + each crate README + lib.rs + // Facts verified against .targets/ruqu @026d63ef (README + each crate README + lib.rs // doc-comments + cli/README + cli/package.json). // ────────────────────────────────────────────────────────────────────────── ruqu: { slug: 'ruqu', metaName: 'ruqu', - // ── Embedder (ADR-0001 v1.3.1: SINGLE 384-dim desktop variant) ──────────── + // ── Embedder (single 384-dim variant) ───────────────────────────────────── // bge-small-en-v1.5 (cls-pooled, normalized, asymmetric query prefix). build-kb.mjs writes the // canonical un-suffixed stores/ruqu/ruqu-kb.rvf + a .embed.json sidecar that ask-kb + - // index-primer read (so query + primer use the SAME model). The 1035-chunk ruqu corpus cleared - // Gate A at 384 — no step-up to 768 needed (memory: embedding-final-768-plus-chunking). + // index-primer read (so query + primer use the SAME model). embed: { model: 'Xenova/bge-small-en-v1.5', dim: 384, @@ -1560,43 +1140,6 @@ export const targets = { docs: 'PRIMER#6-where-do-i-read-more-the-docs-map', adr: 'PRIMER#6-where-do-i-read-more-the-docs-map', playbook: 'PRIMER#7-how-do-i-install-and-run-it-end-to-end', - // §8/§9 added for the AI-comprehension gate (extensibility + gotchas dimensions). - extensibility: 'PRIMER#8-how-do-i-extend-ruqu-safely-the-extension-points', - gotchas: 'PRIMER#9-performance-memory-and-gotchas-running-large-circuits', - }, - // extensionFiles — concept word -> the real extension-point file(s) it touches. Consumed by the - // AI-comprehension grader (and a useful map for any AI): "add a CLI subcommand" -> cli/bin/cli.js, - // etc. These files ARE indexed (in passages.jsonl); PRIMER#8 names them in prose. - extensionFiles: { - 'gate': ['crates/ruqu-core/src/gate.rs', 'crates/ruqu-core/src/clifford_t.rs'], - 'backend': ['crates/ruqu-core/src/backend.rs', 'crates/ruqu-core/src/simulator.rs'], - 'decoder': ['crates/ruqu-core/src/decoder.rs'], - 'provider': ['crates/ruqu-core/src/hardware.rs'], - 'hardware': ['crates/ruqu-core/src/hardware.rs'], - 'algorithm': ['crates/ruqu-algorithms/src/lib.rs', 'crates/ruqu-algorithms/src/grover.rs'], - 'cli': ['cli/bin/cli.js'], - 'subcommand': ['cli/bin/cli.js'], - 'command': ['cli/bin/cli.js'], - 'wasm': ['crates/ruqu-wasm/src/lib.rs'], - 'binding': ['crates/ruqu-wasm/src/lib.rs'], - 'javascript': ['crates/ruqu-wasm/src/lib.rs'], - 'coherence': ['crates/ruQu/src/lib.rs'], - }, - // docFiles — per-dimension authoritative docs the grader injects (the AI reads these for the - // dimension). CLI per-command table lives in cli/README.md; usage gate examples in the crate READMEs. - docFiles: { - cli: ['cli/README.md', 'cli/bin/cli.js'], - usage: ['crates/ruqu-core/README.md', 'crates/ruqu-algorithms/README.md'], - }, - // typeAliases — concept word in a question -> the public type whose method signatures answer it. - // Lets "build and run a circuit" surface QuantumCircuit's gate methods (h/cnot/…) from symbols.json. - typeAliases: { - 'circuit': 'QuantumCircuit', - 'simulator': 'Simulator', - 'simulation': 'Simulator', - 'grover': 'GroverConfig', - 'backend': 'BackendType', - 'analyze': 'CircuitAnalysis', }, repoDir: '../.targets/ruqu', @@ -1612,15 +1155,13 @@ export const targets = { ], codeExt: ['.rs', '.ts', '.tsx', '.js', '.mjs', '.cjs'], - fullTextExt: ['.md', '.mdx', '.txt'], - templateExt: [], // Five crates live under crates/ (+ the npx CLI in cli/). componentWord widened // with 'engine' so "the coherence engine" matches the product/inventory matchers. componentRoots: ['crates'], componentWord: ['crate', 'engine', 'package', 'module', 'component'], - // ── Disambiguation (gate-A tuning, 384 bge-small) ───────────────────────── + // ── Disambiguation ──────────────────────────────────────────────────────── // ruqu is a DENSE corpus (1035 chunks): every crate's full Rust source + ADRs + DDDs // are indexed, and many low-level files (noise.rs, backend.rs, simulator.rs, Cargo.toml, // ADR/DDD design docs) are vector-close to orientation queries but DON'T carry the plain @@ -1710,58 +1251,6 @@ export const targets = { { rule: 'literalFiles', files: ['README.md', 'cli/README.md', 'cli/package.json', 'cli/bin/cli.js', 'crates/ruqu-core/README.md', 'crates/ruqu-algorithms/README.md', 'crates/ruqu-wasm/README.md', 'crates/ruqu-exotic/README.md', 'crates/ruQu/README.md'] }, ], - verificationQueries: [ - { - stage: 1, - arc: 'what-is-it', - query: 'What is ruqu?', - wantPaths: ['PRIMER#1-what-is-ruqu', 'README.md'], - mustContain: ['quantum', 'pure Rust', 'state-vector', 'WebAssembly'], - }, - { - stage: 2, - arc: 'capabilities', - query: 'What can ruqu do for me?', - wantPaths: ['PRIMER#2-what-can-ruqu-do-for-you', 'README.md', 'crates/ruqu-algorithms/README.md'], - mustContain: ['VQE', 'Grover', 'QAOA', 'Surface Code'], - }, - { - stage: 3, - arc: 'inventory-components', - query: 'What crates make up ruqu?', - wantPaths: ['PRIMER#3-what-is-ruqu-made-of-the-five-crates', 'README.md'], - mustContain: ['ruqu-core', 'ruqu-algorithms', 'ruqu-exotic', 'ruqu-wasm', 'coherence'], - }, - { - stage: 4, - arc: 'how-it-works-pipeline', - query: 'How does a quantum circuit run on the simulator?', - wantPaths: ['PRIMER#4-how-a-circuit-runs-the-simulation-pipeline', 'crates/ruqu-core/README.md'], - mustContain: ['StateVector', 'planner', 'backend', 'noise'], - }, - { - stage: 5, - arc: 'maturity', - query: 'Is ruqu production-ready and what are its limits?', - wantPaths: ['PRIMER#5-is-it-production-ready-scope-and-honest-limits', 'README.md'], - mustContain: ['25', 'simulator', 'MIT'], - }, - { - stage: 6, - arc: 'docs-where-things-live', - query: 'Where do I read more about ruqu?', - wantPaths: ['PRIMER#6-where-do-i-read-more-the-docs-map', 'README.md'], - mustContain: ['ruqu-core', 'ruqu-algorithms', 'README'], - }, - { - stage: 7, - arc: 'end-to-end-usage', - query: 'How do I install and run ruqu?', - wantPaths: ['PRIMER#7-how-do-i-install-and-run-it-end-to-end', 'README.md', 'cli/README.md'], - mustContain: ['cargo add ruqu-core', 'npx @ruvector/ruqu', 'wasm-pack', 'simulate'], - }, - ], - bundle: { blurb: 'ruqu drop-in knowledge base — a quantum computing simulator in pure Rust + WebAssembly. ' + @@ -1769,13 +1258,6 @@ export const targets = { 'quantum algorithms (VQE, Grover, QAOA, surface-code error correction), and ~25-qubit ' + 'in-browser WASM. Run circuits with no quantum hardware, even in a browser tab. ' + 'Install: cargo add ruqu-core ruqu-algorithms · or npx @ruvector/ruqu simulate.', - questions: [ - 'What is ruqu and what does it let me do without quantum hardware?', - 'What is a state-vector simulator and what are VQE / Grover / QAOA?', - 'What are the five crates that make up ruqu?', - 'How does a circuit run — backends, noise, the cost-model planner?', - 'How do I install ruqu or run it from the terminal with npx?', - ], }, }, @@ -1788,7 +1270,7 @@ export const targets = { // Rust core + Python library (PyPI: ruview / wifi-densepose) + JavaScript UI // + ESP32 C/Rust firmware. Pretrained weights on Hugging Face. Docker image. // Works with Home Assistant, Apple Home, Google Home, Alexa, Matter. - // Registered for the explainmyrepo recipe run (2026-07-04). + // Registered for the explainmyrepo recipe run. // ────────────────────────────────────────────────────────────────────────── RuView: { slug: 'RuView', @@ -1822,13 +1304,10 @@ export const targets = { docs: 'PRIMER#6-where-do-i-read-more-the-docs-map', adr: 'PRIMER#6-where-do-i-read-more-the-docs-map', playbook: 'PRIMER#7-how-do-i-install-and-use-it-end-to-end', - extensibility: 'PRIMER#8-how-do-i-extend-ruview', - gotchas: 'PRIMER#9-hardware-limits-and-gotchas', }, - // 2026-09-17: repoDir pointed at a hosted proof run's scratch clone (/tmp/agentic-proof-ruview), - // which no longer exists; the local door clones into explainer-builds//repo. - repoDir: '/Users/stuartkerr/Code/Ruv-Explainer/explainer-builds/ruview/repo', + // The local door clones into explainer-builds//repo. + repoDir: '../.targets/RuView', scopeExclude: [ 'node_modules', 'dist', @@ -1862,8 +1341,6 @@ export const targets = { ], codeExt: ['.rs', '.py', '.js', '.ts', '.mjs', '.sh', '.toml'], - fullTextExt: ['.md', '.mdx', '.txt', '.rst'], - templateExt: [], componentRoots: [ 'wifi_densepose', @@ -1901,7 +1378,7 @@ export const targets = { // gatherings that actually connect people. Pure-markdown skill (SKILL.md + // 5 reference libraries + 5 workshop templates), Claude Code / Cowork plugin. // Created by Klara Hermesz (AI Enablement Academy). v3.0.0, CC BY 4.0. - // Registered for the explainmyrepo recipe 2026-07-04. + // Registered for the explainmyrepo recipe. // ────────────────────────────────────────────────────────────────────────── 'gathering-architect': { slug: 'gathering-architect', @@ -1919,7 +1396,7 @@ export const targets = { 'Gathering Architect', 'gathering architect', ], - repoDir: '/tmp/agentic-proof-gathering-architect/repo', + repoDir: '../.targets/gathering-architect', scopeExclude: [ 'node_modules', '.git', @@ -1928,8 +1405,6 @@ export const targets = { 'coverage', ], codeExt: [], - fullTextExt: ['.md', '.mdx', '.txt'], - templateExt: [], componentRoots: [ 'plugins/gathering-architect/skills/gathering-architect', ], @@ -1967,14 +1442,12 @@ export const targets = { "rvfSuffix": ".rvf" }, "productNames": ["OpenConnector", "open-connector"], - "repoDir": "/Users/stuartkerr/Code/Ruv-Explainer/explainer-builds/open-connector/repo", + "repoDir": "../.targets/open-connector", "scopeExclude": [ "node_modules", "dist", "target", ".git", "coverage", "pkg", ".next", "__pycache__", ".venv", "venv", "providers", "public", "assets", ".wrangler" ], "codeExt": [".ts", ".tsx", ".js", ".mjs"], - "fullTextExt": [".md", ".mdx", ".txt"], - "templateExt": [], "componentRoots": ["src", "web/src", "scripts", "docs"], "componentWord": ["module", "service", "gateway", "provider"], "include": [ @@ -1995,14 +1468,12 @@ export const targets = { "rvfSuffix": ".rvf" }, "productNames": ["agentic-kit", "@pacphi/agentic-kit", "ak"], - "repoDir": "/Users/stuartkerr/Code/Ruv-Explainer/explainer-builds/agentic-kit/repo", + "repoDir": "../.targets/agentic-kit", "scopeExclude": [ "node_modules", "dist", "target", ".git", "coverage", "pkg", ".next", "__pycache__", ".venv", "venv" ], "codeExt": [".mjs", ".js", ".cjs"], - "fullTextExt": [".md", ".mdx", ".txt"], - "templateExt": [], "componentRoots": ["src", "src/commands", "src/lib", "src/tools", "bin", "claude"], "componentWord": ["module", "command", "guard", "healer"], "include": [ @@ -2013,10 +1484,16 @@ export const targets = { }, }; -/** Default target for CLI scripts that omit --target while only one repo is in scope [L]. */ +// Per-build overlay (see header): entries here extend or replace the registry for THIS process only. +if (process.env.KB_TARGET_OVERLAY) { + const extra = JSON.parse(fs.readFileSync(process.env.KB_TARGET_OVERLAY, 'utf8')); + for (const [slug, entry] of Object.entries(extra)) targets[slug] = entry; +} + +/** Default target for CLI scripts that omit --target. */ export const defaultTarget = 'agent-harness-generator'; -/** Lookup helper used by build-kb / ask-kb / guard-check / grade-kb / gate. */ +/** Target lookup used by build-kb and the structured-index scripts. */ export function getTarget(slug = defaultTarget) { const t = targets[slug]; if (!t) { @@ -2026,11 +1503,10 @@ export function getTarget(slug = defaultTarget) { } // KB_REPO_DIR — set by tools/build-kb.mjs from build.json's repo.clonePath so that every // kb/ engine script indexes the correct build-dir clone, not the config's default repoDir. - // Without this, a fresh run on a new build dir silently reads the wrong repo (Blocker-1 fix). + // Without this, a fresh run on a new build dir silently reads the wrong repo. // Direct / legacy invocations (no env var) fall back to target.repoDir as before. const repoDirOverride = process.env.KB_REPO_DIR; if (repoDirOverride) return { ...t, repoDir: repoDirOverride }; return t; } -export default { targets, defaultTarget, getTarget }; diff --git a/kb/make-dropin.mjs b/kb/make-dropin.mjs deleted file mode 100644 index 0843cb1..0000000 --- a/kb/make-dropin.mjs +++ /dev/null @@ -1,224 +0,0 @@ -#!/usr/bin/env node -// make-dropin.mjs — build the v1.3.1 single-384 drop-in zip for ONE target. -// -// Layout (mirrors the proven #1 metaharness-dropin.zip, single-variant): -// for-ai/ -kb.rvf (+ .idmap.json) + -kb.passages.jsonl + -kb.ids.json -// + ask-kb.mjs + kb-mcp-server.mjs + kb.config.mjs + resolve-deps.mjs + package.json -// for-humans/ -primer.md + studio/{audio + report + prompt} ← STUDIO IS IN THE ZIP (D13/V) -// README.md manifest.json -// -// Usage: node kb/make-dropin.mjs ruvn ../ruv-explainer-ruvn/downloads/ruvn-dropin.zip -// -// Self-contained: the studio media (NotebookLM audio overview + report + prompt) is bundled INSIDE -// the zip's for-humans/studio/ — verify with `unzip -l`. Uses system `zip`. - -import { execFileSync } from 'node:child_process'; -import fs from 'node:fs'; -import path from 'node:path'; -import os from 'node:os'; -import { fileURLToPath } from 'node:url'; - -const KB_DIR = path.dirname(fileURLToPath(import.meta.url)); // kb/ -const ROOT = path.resolve(KB_DIR, '..'); - -const slug = process.argv[2]; -const outArg = process.argv[3]; -if (!slug || !outArg) { - console.error('usage: node kb/make-dropin.mjs '); - process.exit(2); -} -const OUT = path.isAbsolute(outArg) ? outArg : path.resolve(process.cwd(), outArg); -const storeDir = path.join(KB_DIR, 'stores', slug); -const studioDir = path.join(storeDir, 'studio', 'for-humans'); - -// Read provenance from kb.config (sha/date) + the gate score we just proved. -function readLastBuilt() { - const p = path.join(KB_DIR, '.last-built.json'); - try { return JSON.parse(fs.readFileSync(p, 'utf8')); } catch { return {}; } -} - -function must(p) { if (!fs.existsSync(p)) throw new Error(`missing: ${p}`); return p; } - -const FOR_AI = [ - [`${slug}-kb.rvf`, `for-ai/${slug}-kb.rvf`], - [`${slug}-kb.rvf.idmap.json`, `for-ai/${slug}-kb.rvf.idmap.json`], - [`${slug}-kb.rvf.embed.json`, `for-ai/${slug}-kb.rvf.embed.json`], - [`${slug}-kb.passages.jsonl`, `for-ai/${slug}-kb.passages.jsonl`], - [`${slug}-kb.ids.json`, `for-ai/${slug}-kb.ids.json`], -].map(([f, dst]) => [path.join(storeDir, f), dst]); - -// Structured enrichment artifacts (AI-comprehension recipe v1.3.2): exact symbol/dep/entrypoint -// lookups the AI uses alongside semantic search. Generated by kb/extract-symbols|dep-graph| -// entrypoints.mjs. Shipped if present; a build that skips them still produces a valid drop-in. -const FOR_AI_STRUCTURED = [ - [`${slug}-symbols.json`, `for-ai/${slug}-symbols.json`], - [`${slug}-dep-graph.json`, `for-ai/${slug}-dep-graph.json`], - [`${slug}-entrypoints.json`, `for-ai/${slug}-entrypoints.json`], -].map(([f, dst]) => [path.join(storeDir, f), dst]).filter(([src]) => fs.existsSync(src)); - -const FOR_AI_TOOLS = [ - ['ask-kb.mjs', 'for-ai/ask-kb.mjs'], - ['kb-mcp-server.mjs', 'for-ai/kb-mcp-server.mjs'], - ['kb.config.mjs', 'for-ai/kb.config.mjs'], - ['resolve-deps.mjs', 'for-ai/resolve-deps.mjs'], -].map(([f, dst]) => [path.join(KB_DIR, f), dst]); - -// for-ai/package.json (drop-in runnable) -const forAiPkg = { - name: `${slug}-dropin-kb`, - version: '0.1.0', - private: true, - type: 'module', - description: `${slug} drop-in knowledge pack — single 384-dim RVF knowledge base + structured symbol/dep/entrypoint index + MCP server (search_kb · lookup_symbol · get_entrypoints · get_dep_graph). Run \`npm i\` then \`node ask-kb.mjs ${slug} "your question"\` or \`node ask-kb.mjs ${slug} --symbol \`.`, - scripts: { ask: `node ask-kb.mjs ${slug}`, mcp: 'node kb-mcp-server.mjs' }, - dependencies: { '@ruvector/rvf': '^0.3.0', '@xenova/transformers': '^2.17.2' }, - engines: { node: '>=18' }, -}; - -// for-humans/ primer + studio (studio MUST be present — D13/V; fail RED otherwise) -const primerSrc = must(path.join(storeDir, `${slug}-primer.md`)); -// `studio-links.json` is metadata (notebook/video URLs) read below — NOT a file to ship in the zip. -const studioFiles = fs.existsSync(studioDir) - ? fs.readdirSync(studioDir) - .filter((f) => !f.startsWith('.') && f !== 'studio-links.json') - .map((f) => [path.join(studioDir, f), `for-humans/studio/${f}`]) - : []; -const hasAudio = studioFiles.some(([, d]) => /\.(m4a|mp3|wav)$/i.test(d)); -const hasReport = studioFiles.some(([, d]) => /report\.md$/i.test(d)); -if (!studioFiles.length || !hasAudio || !hasReport) { - throw new Error(`STUDIO-IN-ZIP guard (D13/V): for-humans/studio must contain the audio overview AND report. ` + - `Found under ${studioDir}: ${studioFiles.map(([, d]) => path.basename(d)).join(', ') || '(none)'}. ` + - `Refusing to build a studio-less drop-in.`); -} - -// Optional EXTRA studio artifacts that ride in the zip (infographic PNG, slide-deck PDF/PPTX). -const infographicFile = studioFiles.find(([, d]) => /infographic.*\.png$/i.test(d)); -const slidesFile = studioFiles.find(([, d]) => /slides?.*\.(pdf|pptx)$/i.test(d)); -const infographicName = infographicFile ? path.basename(infographicFile[1]) : null; -const slidesName = slidesFile ? path.basename(slidesFile[1]) : null; - -// Optional links to the (large) video + the public NotebookLM notebook, kept OUT of the zip to stay light. -// Read from studio/for-humans/studio-links.json: { "notebookUrl": "...", "videoUrl": "...", "videoNote": "..." } -let studioLinks = {}; -try { studioLinks = JSON.parse(fs.readFileSync(path.join(studioDir, 'studio-links.json'), 'utf8')); } catch { /* optional */ } - -const lb = readLastBuilt(); -const manifest = { - name: `${slug}-dropin`, - version: lb.version || 'v0.1.1', - builtAt: lb.builtAt || new Date().toISOString().slice(0, 10), - sha: lb.targetRepoSha || lb.sha || null, - embedder: 'Xenova/bge-small-en-v1.5 (384-dim, single variant, recipe v1.3.1)', - gateA: lb.gateA || { passed: true }, - contents: { - 'for-ai': [...FOR_AI, ...FOR_AI_STRUCTURED, ...FOR_AI_TOOLS].map(([, d]) => d.replace('for-ai/', '')).concat(['package.json']), - 'for-humans': [`${slug}-primer.md`, ...studioFiles.map(([, d]) => d.replace('for-humans/', ''))], - }, - structured: { - symbols: FOR_AI_STRUCTURED.some(([, d]) => d.endsWith('-symbols.json')) ? `${slug}-symbols.json` : null, - depGraph: FOR_AI_STRUCTURED.some(([, d]) => d.endsWith('-dep-graph.json')) ? `${slug}-dep-graph.json` : null, - entrypoints: FOR_AI_STRUCTURED.some(([, d]) => d.endsWith('-entrypoints.json')) ? `${slug}-entrypoints.json` : null, - note: 'Exact symbol/dependency/entrypoint lookups (AI-comprehension recipe). Use alongside ask-kb semantic search.', - }, - studio: { - audio: studioFiles.find(([, d]) => /\.(m4a|mp3|wav)$/i.test(d))?.[1] || null, - report: studioFiles.find(([, d]) => /report\.md$/i.test(d))?.[1] || null, - prompt: studioFiles.find(([, d]) => /prompt\.md$/i.test(d))?.[1] || null, - infographic: infographicFile?.[1] || null, - slides: slidesFile?.[1] || null, - notebookUrl: studioLinks.notebookUrl || null, - videoUrl: studioLinks.videoUrl || null, - note: 'NotebookLM media pack — play the audio first, then skim the report; infographic + slides ride inside; the video + live notebook are linked (see README).', - }, - description: `${slug} drop-in knowledge pack. Unzip, npm i in for-ai/, point .mcp.json at kb-mcp-server.mjs, add CLAUDE.md gate. The for-humans/studio/ media (audio, report, infographic, slides) ride inside this zip; the video + public notebook are linked from the README. See README.md.`, -}; - -const audioName = path.basename(manifest.studio.audio || `${slug}-audio-overview.m4a`); -const reportName = path.basename(manifest.studio.report || `${slug}-report.md`); - -const extraTreeLines = [ - infographicName ? ` 🖼 ${infographicName} — the whole story on one sheet (NotebookLM infographic)` : null, - slidesName ? ` 📊 ${slidesName} — a detailed slide deck you can flip through` : null, -].filter(Boolean).join('\n'); - -const linkLines = [ - studioLinks.notebookUrl ? `- **Open the full NotebookLM studio (public):** ${studioLinks.notebookUrl}` : null, - studioLinks.videoUrl - ? `- **Watch the video overview:** ${studioLinks.videoUrl}${studioLinks.videoNote ? ` — ${studioLinks.videoNote}` : ''}` - : null, -].filter(Boolean).join('\n'); - -const readme = `# ${slug} Drop-in - -One zip. Two halves. The NotebookLM studio media rides **inside** this zip. - -## What's inside - -\`\`\` -${slug}-dropin/ - for-humans/ — read & listen first - ${slug}-primer.md - studio/ - 🎧 ${audioName} — NotebookLM AUDIO OVERVIEW (play this first) - 📄 ${reportName} — the written deep-dive briefing -${extraTreeLines ? extraTreeLines + '\n' : ''} audio-overview-prompt.md — the prompt that generated the audio - for-ai/ — the searchable knowledge pack (wire this into your agent) - ${slug}-kb.rvf — single 384-dim bge-small vector DB (the "brain") - ${slug}-kb.passages.jsonl — full passage text (tagged source_type: src|test|example|doc|config) - ${slug}-kb.ids.json — id → passage index - ${slug}-symbols.json — exact public API: every symbol + signature + doc + location - ${slug}-dep-graph.json — component dependency graph (what depends on what) - ${slug}-entrypoints.json — build/test/run/install commands + binaries - ask-kb.mjs · kb-mcp-server.mjs · kb.config.mjs · resolve-deps.mjs · package.json - README.md — this file - manifest.json — build metadata + Gate A score -\`\`\` - -## Studio (NotebookLM) -Start with the audio: play \`for-humans/studio/${audioName}\` — a friendly two-host overview of ${slug}. -Prefer reading? Open \`for-humans/studio/${reportName}\`.${infographicName ? ` -Want it on one sheet? Open \`for-humans/studio/${infographicName}\`.` : ''}${slidesName ? ` -Prefer slides? Open \`for-humans/studio/${slidesName}\`.` : ''} -${linkLines ? ` -The full media pack also includes a **video overview**, linked below to keep this download light: - -${linkLines} -` : ''} - -## Three steps to wire the AI half in -\`\`\`bash -# 1 — unzip + install (two deps, Node 18+) -unzip ${slug}-dropin.zip && cd ${slug}-dropin/for-ai && npm install - -# 2 — ask the brain a question straight away -node ask-kb.mjs ${slug} "what does ${slug} actually do" - -# 3 — point your AI host at it with a .mcp.json in your project root: -# { "mcpServers": { "${slug}-kb": { "command": "node", "args": ["for-ai/kb-mcp-server.mjs"] } } } -\`\`\` - -Built with the Repo-Primer recipe (ADR-0001 v1.3.1). Embedder: ${manifest.embedder}. -Source: github.com/ruvnet/${slug} @ ${manifest.sha || '(see manifest)'}. -`; - -// ---- stage + zip ---- -const stage = fs.mkdtempSync(path.join(os.tmpdir(), `dropin-${slug}-`)); -function copy(src, dst) { - const d = path.join(stage, dst); - fs.mkdirSync(path.dirname(d), { recursive: true }); - fs.copyFileSync(src, d); -} -for (const [src, dst] of [...FOR_AI, ...FOR_AI_STRUCTURED, ...FOR_AI_TOOLS]) copy(must(src), dst); -copy(primerSrc, `for-humans/${slug}-primer.md`); -for (const [src, dst] of studioFiles) copy(src, dst); -fs.writeFileSync(path.join(stage, 'for-ai/package.json'), JSON.stringify(forAiPkg, null, 2) + '\n'); -fs.writeFileSync(path.join(stage, 'README.md'), readme); -fs.writeFileSync(path.join(stage, 'manifest.json'), JSON.stringify(manifest, null, 2) + '\n'); - -fs.mkdirSync(path.dirname(OUT), { recursive: true }); -fs.rmSync(OUT, { force: true }); -execFileSync('zip', ['-r', '-X', OUT, '.'], { cwd: stage, stdio: 'inherit' }); -fs.rmSync(stage, { recursive: true, force: true }); -const size = fs.statSync(OUT).size; -console.log(`\nbuilt ${path.relative(ROOT, OUT)} (${(size / 1e6).toFixed(1)} MB)`); -console.log(`studio in zip: 🎧 ${audioName} 📄 ${reportName}`); diff --git a/kb/package-lock.json b/kb/package-lock.json deleted file mode 100644 index 3499d32..0000000 --- a/kb/package-lock.json +++ /dev/null @@ -1,1016 +0,0 @@ -{ - "name": "metaharness-kb", - "version": "3.0.0", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "metaharness-kb", - "version": "3.0.0", - "dependencies": { - "@ruvector/rvf": "^0.3.0", - "@xenova/transformers": "^2.17.2" - }, - "bin": { - "kb-ask": "ask-kb.mjs", - "kb-mcp": "kb-mcp-server.mjs" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/@huggingface/jinja": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/@huggingface/jinja/-/jinja-0.2.2.tgz", - "integrity": "sha512-/KPde26khDUIPkTGU82jdtTW9UAuvUTumCAbFs/7giR0SxsvZC4hru51PBvpijH6BVkHcROcvZM/lpy5h1jRRA==", - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/@protobufjs/aspromise": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", - "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/base64": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", - "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/codegen": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", - "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/eventemitter": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", - "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/fetch": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", - "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", - "license": "BSD-3-Clause", - "dependencies": { - "@protobufjs/aspromise": "^1.1.1" - } - }, - "node_modules/@protobufjs/float": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", - "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/inquire": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.2.tgz", - "integrity": "sha512-pa0vFRuws4wkvaXKK1uXZMAwAX4/t8ANaJo45iw/oQHNQ9q5xUzwgFmVJGXiga2BeN+zpX7Vf9vmsiIa2J+MUw==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/path": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", - "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/pool": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", - "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/utf8": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.1.tgz", - "integrity": "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==", - "license": "BSD-3-Clause" - }, - "node_modules/@ruvector/rvf": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/@ruvector/rvf/-/rvf-0.3.0.tgz", - "integrity": "sha512-j3AZsh7FYYD7aM23vBSCKroT10KaycV4L0Naa1JKQTIQngCqxFzP/PDKmavLlDLAAz6rJrZq4m0rmwF8WvNFJw==", - "license": "MIT", - "dependencies": { - "@ruvector/rvf-node": "^0.1.7" - }, - "optionalDependencies": { - "@ruvector/rvf-solver": "^0.1.0", - "@ruvector/rvf-wasm": "^0.1.7" - } - }, - "node_modules/@ruvector/rvf-node": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-node/-/rvf-node-0.1.8.tgz", - "integrity": "sha512-1rbSr9XAiq69wnEPs36FW93ZEfFMYEiI2fANZ0bfQcEH4uNWlwxaZFgKs47PNQPhCgx/cbONpnVsnyX+uOTagw==", - "license": "MIT", - "engines": { - "node": ">= 16" - }, - "optionalDependencies": { - "@ruvector/rvf-node-darwin-arm64": "0.1.7", - "@ruvector/rvf-node-darwin-x64": "0.1.7", - "@ruvector/rvf-node-linux-arm64-gnu": "0.1.7", - "@ruvector/rvf-node-linux-x64-gnu": "0.1.7", - "@ruvector/rvf-node-win32-x64-msvc": "0.1.7" - } - }, - "node_modules/@ruvector/rvf-node-darwin-arm64": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-darwin-arm64/-/rvf-node-darwin-arm64-0.1.7.tgz", - "integrity": "sha512-vll3WJwDn3oOfy1PB10IG7/f3zBpFiMNHL2/2tdJmeRR8La/rSPJ0ZH5MDIsfleiVtaWzh9bvVCtVkZ6uo2jeg==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@ruvector/rvf-node-darwin-x64": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-darwin-x64/-/rvf-node-darwin-x64-0.1.7.tgz", - "integrity": "sha512-Qi/l2bVuVz5YQ2RcYPYF0LNZVkytiIZHzvWhS71+Tt5GEIrsToauHQIcnJQmDNypvwxO8wYk+EeT2xcHR3ZSQQ==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@ruvector/rvf-node-linux-arm64-gnu": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-linux-arm64-gnu/-/rvf-node-linux-arm64-gnu-0.1.7.tgz", - "integrity": "sha512-oZwrtfs7XqRVaDP6iiw6G52l7+NdP3NbTwR2iM+EP8r8X4e1+p4opwV2Ig+lyT7wAz72wcyOpkzpu1MlbK4NKA==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@ruvector/rvf-node-linux-x64-gnu": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-linux-x64-gnu/-/rvf-node-linux-x64-gnu-0.1.7.tgz", - "integrity": "sha512-CRq9nc7dIj8QbcY9sSXvVau7cr1ESh3VnYUPp1IodzZ4SegN0H3oeieF5nUMNYyq+43MkBR4yrEwFgDBZ00QHQ==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@ruvector/rvf-node-win32-x64-msvc": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-win32-x64-msvc/-/rvf-node-win32-x64-msvc-0.1.7.tgz", - "integrity": "sha512-sgnoNphOnbD4d3+YyQ83MlGO7sX4kbcDwsFNz7p2mlTaDR8coQXoudSaPrMeMpeUojFUqoxeDvVly/un3jADig==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@ruvector/rvf-solver": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-solver/-/rvf-solver-0.1.8.tgz", - "integrity": "sha512-YM7L6TvhVoC5w0kUMl8ASback2ka3MesPvuf+lRYSJEcaf6bncPX7YGzcrsheOe4BBwyiyx39vAijVPx1nZkWA==", - "license": "MIT", - "optional": true - }, - "node_modules/@ruvector/rvf-wasm": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-wasm/-/rvf-wasm-0.1.7.tgz", - "integrity": "sha512-VTGPau9ikQXG9Tvjkjk5ff90ZcCMcwOYv3l6rJ+PL2fH/9EtxM1FWE7H1i7gdhh8dCSqRv4moXOAMSDbJ5oubQ==", - "license": "MIT", - "optional": true - }, - "node_modules/@types/long": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz", - "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==", - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "26.0.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.0.0.tgz", - "integrity": "sha512-vf2YFi1iY9lHGwNJMs01biZFbKJkrZR1T6/MlzjhJLPdntOHLhTrDSnSVcdtvjihi4VQNlrFRIxLsDBlQpAipA==", - "license": "MIT", - "dependencies": { - "undici-types": "~8.3.0" - } - }, - "node_modules/@xenova/transformers": { - "version": "2.17.2", - "resolved": "https://registry.npmjs.org/@xenova/transformers/-/transformers-2.17.2.tgz", - "integrity": "sha512-lZmHqzrVIkSvZdKZEx7IYY51TK0WDrC8eR0c5IMnBsO8di8are1zzw8BlLhyO2TklZKLN5UffNGs1IJwT6oOqQ==", - "license": "Apache-2.0", - "dependencies": { - "@huggingface/jinja": "^0.2.2", - "onnxruntime-web": "1.14.0", - "sharp": "^0.32.0" - }, - "optionalDependencies": { - "onnxruntime-node": "1.14.0" - } - }, - "node_modules/b4a": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.8.1.tgz", - "integrity": "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==", - "license": "Apache-2.0", - "peerDependencies": { - "react-native-b4a": "*" - }, - "peerDependenciesMeta": { - "react-native-b4a": { - "optional": true - } - } - }, - "node_modules/bare-events": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.1.tgz", - "integrity": "sha512-Z0oHEHAFDZkffN8Qc39zNZjQlMDkPJRyyyZieU1VH7u8c5S+qHZ2S8ixdKIAxEjfHO7FJxXmJWgteOghVanIsg==", - "license": "Apache-2.0", - "peerDependencies": { - "bare-abort-controller": "*" - }, - "peerDependenciesMeta": { - "bare-abort-controller": { - "optional": true - } - } - }, - "node_modules/bare-fs": { - "version": "4.7.2", - "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.7.2.tgz", - "integrity": "sha512-aTvMFUWkBmjzKtEQMDGGDNF8bkfpD5N1b/FCwt7A3wrU4t1o/e/85Wzkluh6JlODCjqVESYCkQCdTXqZ9G7VFg==", - "license": "Apache-2.0", - "dependencies": { - "bare-events": "^2.5.4", - "bare-path": "^3.0.0", - "bare-stream": "^2.6.4", - "bare-url": "^2.2.2", - "fast-fifo": "^1.3.2" - }, - "engines": { - "bare": ">=1.16.0" - }, - "peerDependencies": { - "bare-buffer": "*" - }, - "peerDependenciesMeta": { - "bare-buffer": { - "optional": true - } - } - }, - "node_modules/bare-os": { - "version": "3.9.1", - "resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.9.1.tgz", - "integrity": "sha512-6M5XjcnsygQNPMCMPXSK379xrJFiZ/AEMNBmFEmQW8d/789VQATvriyi5r0HYTL9TkQ26rn3kgdTG3aisbrXkQ==", - "license": "Apache-2.0", - "engines": { - "bare": ">=1.14.0" - } - }, - "node_modules/bare-path": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.0.1.tgz", - "integrity": "sha512-ghj2DSK/2e99a1anTVPCV4m4YIYtrbXhfM7V3D7XZLOTsybnYyaJloymGqssQc8l/or0UoDyRtNQkmkEF/ysgQ==", - "license": "Apache-2.0", - "dependencies": { - "bare-os": "^3.0.1" - } - }, - "node_modules/bare-stream": { - "version": "2.13.3", - "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.3.tgz", - "integrity": "sha512-Kc+brLqvEqGkjyfiwJmImAOqLZL7OsoLKuavx+hJjgVV3nLTOjloJyPMFxjUPerGGHrNH0fLU06jjykMLWrERQ==", - "license": "Apache-2.0", - "dependencies": { - "b4a": "^1.8.1", - "streamx": "^2.25.0", - "teex": "^1.0.1" - }, - "peerDependencies": { - "bare-abort-controller": "*", - "bare-buffer": "*", - "bare-events": "*" - }, - "peerDependenciesMeta": { - "bare-abort-controller": { - "optional": true - }, - "bare-buffer": { - "optional": true - }, - "bare-events": { - "optional": true - } - } - }, - "node_modules/bare-url": { - "version": "2.4.5", - "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.4.5.tgz", - "integrity": "sha512-K+y9xF1tN+CdPu4qWwr0QiK1Al07eFPGYK5M2pDXcmHdMdgC/tT/bpmMe1hrmRHaidKLkXrC+cRNYf3XVDUhSQ==", - "license": "Apache-2.0", - "dependencies": { - "bare-path": "^3.0.0" - } - }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "license": "MIT", - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } - }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, - "node_modules/chownr": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", - "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", - "license": "ISC" - }, - "node_modules/color": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", - "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1", - "color-string": "^1.9.0" - }, - "engines": { - "node": ">=12.5.0" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "license": "MIT" - }, - "node_modules/color-string": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", - "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", - "license": "MIT", - "dependencies": { - "color-name": "^1.0.0", - "simple-swizzle": "^0.2.2" - } - }, - "node_modules/decompress-response": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", - "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", - "license": "MIT", - "dependencies": { - "mimic-response": "^3.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/deep-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "license": "MIT", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/end-of-stream": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", - "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", - "license": "MIT", - "dependencies": { - "once": "^1.4.0" - } - }, - "node_modules/events-universal": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz", - "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==", - "license": "Apache-2.0", - "dependencies": { - "bare-events": "^2.7.0" - } - }, - "node_modules/expand-template": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", - "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", - "license": "(MIT OR WTFPL)", - "engines": { - "node": ">=6" - } - }, - "node_modules/fast-fifo": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz", - "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==", - "license": "MIT" - }, - "node_modules/flatbuffers": { - "version": "1.12.0", - "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-1.12.0.tgz", - "integrity": "sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==", - "license": "SEE LICENSE IN LICENSE.txt" - }, - "node_modules/fs-constants": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", - "license": "MIT" - }, - "node_modules/github-from-package": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", - "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", - "license": "MIT" - }, - "node_modules/guid-typescript": { - "version": "1.0.9", - "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", - "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", - "license": "ISC" - }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "license": "ISC" - }, - "node_modules/is-arrayish": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz", - "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==", - "license": "MIT" - }, - "node_modules/long": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", - "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==", - "license": "Apache-2.0" - }, - "node_modules/mimic-response": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", - "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/mkdirp-classic": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", - "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", - "license": "MIT" - }, - "node_modules/napi-build-utils": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", - "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", - "license": "MIT" - }, - "node_modules/node-abi": { - "version": "3.92.0", - "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.92.0.tgz", - "integrity": "sha512-KdHvFWZjEKDf0cakgFjebl371GPsISX2oZHcuyKqM7DtogIsHrqKeLTo8wBHxaXRAQlY2PsPlZmfo+9ZCxEREQ==", - "license": "MIT", - "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/node-addon-api": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-6.1.0.tgz", - "integrity": "sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==", - "license": "MIT" - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/onnx-proto": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/onnx-proto/-/onnx-proto-4.0.4.tgz", - "integrity": "sha512-aldMOB3HRoo6q/phyB6QRQxSt895HNNw82BNyZ2CMh4bjeKv7g/c+VpAFtJuEMVfYLMbRx61hbuqnKceLeDcDA==", - "license": "MIT", - "dependencies": { - "protobufjs": "^6.8.8" - } - }, - "node_modules/onnxruntime-common": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.14.0.tgz", - "integrity": "sha512-3LJpegM2iMNRX2wUmtYfeX/ytfOzNwAWKSq1HbRrKc9+uqG/FsEA0bbKZl1btQeZaXhC26l44NWpNUeXPII7Ew==", - "license": "MIT" - }, - "node_modules/onnxruntime-node": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.14.0.tgz", - "integrity": "sha512-5ba7TWomIV/9b6NH/1x/8QEeowsb+jBEvFzU6z0T4mNsFwdPqXeFUM7uxC6QeSRkEbWu3qEB0VMjrvzN/0S9+w==", - "license": "MIT", - "optional": true, - "os": [ - "win32", - "darwin", - "linux" - ], - "dependencies": { - "onnxruntime-common": "~1.14.0" - } - }, - "node_modules/onnxruntime-web": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/onnxruntime-web/-/onnxruntime-web-1.14.0.tgz", - "integrity": "sha512-Kcqf43UMfW8mCydVGcX9OMXI2VN17c0p6XvR7IPSZzBf/6lteBzXHvcEVWDPmCKuGombl997HgLqj91F11DzXw==", - "license": "MIT", - "dependencies": { - "flatbuffers": "^1.12.0", - "guid-typescript": "^1.0.9", - "long": "^4.0.0", - "onnx-proto": "^4.0.4", - "onnxruntime-common": "~1.14.0", - "platform": "^1.3.6" - } - }, - "node_modules/platform": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/platform/-/platform-1.3.6.tgz", - "integrity": "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg==", - "license": "MIT" - }, - "node_modules/prebuild-install": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", - "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", - "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", - "license": "MIT", - "dependencies": { - "detect-libc": "^2.0.0", - "expand-template": "^2.0.3", - "github-from-package": "0.0.0", - "minimist": "^1.2.3", - "mkdirp-classic": "^0.5.3", - "napi-build-utils": "^2.0.0", - "node-abi": "^3.3.0", - "pump": "^3.0.0", - "rc": "^1.2.7", - "simple-get": "^4.0.0", - "tar-fs": "^2.0.0", - "tunnel-agent": "^0.6.0" - }, - "bin": { - "prebuild-install": "bin.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/prebuild-install/node_modules/tar-fs": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", - "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", - "license": "MIT", - "dependencies": { - "chownr": "^1.1.1", - "mkdirp-classic": "^0.5.2", - "pump": "^3.0.0", - "tar-stream": "^2.1.4" - } - }, - "node_modules/prebuild-install/node_modules/tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", - "license": "MIT", - "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/protobufjs": { - "version": "6.11.6", - "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.11.6.tgz", - "integrity": "sha512-k8BHqgPBOtrlougZZqF2uUk5Z7bN8f0wj+3e8M3hvtSv0NBAz4VBy5f6R5Nxq/l+i7mRFTgNZb2trxqTpHNY/A==", - "hasInstallScript": true, - "license": "BSD-3-Clause", - "dependencies": { - "@protobufjs/aspromise": "^1.1.2", - "@protobufjs/base64": "^1.1.2", - "@protobufjs/codegen": "^2.0.4", - "@protobufjs/eventemitter": "^1.1.0", - "@protobufjs/fetch": "^1.1.0", - "@protobufjs/float": "^1.0.2", - "@protobufjs/inquire": "^1.1.0", - "@protobufjs/path": "^1.1.2", - "@protobufjs/pool": "^1.1.0", - "@protobufjs/utf8": "^1.1.0", - "@types/long": "^4.0.1", - "@types/node": ">=13.7.0", - "long": "^4.0.0" - }, - "bin": { - "pbjs": "bin/pbjs", - "pbts": "bin/pbts" - } - }, - "node_modules/pump": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", - "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", - "license": "MIT", - "dependencies": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "node_modules/rc": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", - "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", - "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", - "dependencies": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "bin": { - "rc": "cli.js" - } - }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "license": "MIT", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/semver": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.4.tgz", - "integrity": "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/sharp": { - "version": "0.32.6", - "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.32.6.tgz", - "integrity": "sha512-KyLTWwgcR9Oe4d9HwCwNM2l7+J0dUQwn/yf7S0EnTtb0eVS4RxO0eUSvxPtzT4F3SY+C4K6fqdv/DO27sJ/v/w==", - "hasInstallScript": true, - "license": "Apache-2.0", - "dependencies": { - "color": "^4.2.3", - "detect-libc": "^2.0.2", - "node-addon-api": "^6.1.0", - "prebuild-install": "^7.1.1", - "semver": "^7.5.4", - "simple-get": "^4.0.1", - "tar-fs": "^3.0.4", - "tunnel-agent": "^0.6.0" - }, - "engines": { - "node": ">=14.15.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/simple-concat": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", - "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/simple-get": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", - "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "decompress-response": "^6.0.0", - "once": "^1.3.1", - "simple-concat": "^1.0.0" - } - }, - "node_modules/simple-swizzle": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz", - "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==", - "license": "MIT", - "dependencies": { - "is-arrayish": "^0.3.1" - } - }, - "node_modules/streamx": { - "version": "2.28.0", - "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.0.tgz", - "integrity": "sha512-1Yowhzjf0ivGMrTIkY9hav5TxobO9qIVqUE41fiCGMGgc3CLlf4MY+9AHmZqBWgDTue0fY9zWjYFVyf6Diuobw==", - "license": "MIT", - "dependencies": { - "events-universal": "^1.0.0", - "fast-fifo": "^1.3.2", - "text-decoder": "^1.1.0" - } - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/tar-fs": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.2.tgz", - "integrity": "sha512-QGxxTxxyleAdyM3kpFs14ymbYmNFrfY+pHj7Z8FgtbZ7w2//VAgLMac7sT6nRpIHjppXO2AwwEOg0bPFVRcmXw==", - "license": "MIT", - "dependencies": { - "pump": "^3.0.0", - "tar-stream": "^3.1.5" - }, - "optionalDependencies": { - "bare-fs": "^4.0.1", - "bare-path": "^3.0.0" - } - }, - "node_modules/tar-stream": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.0.tgz", - "integrity": "sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg==", - "license": "MIT", - "dependencies": { - "b4a": "^1.6.4", - "bare-fs": "^4.5.5", - "fast-fifo": "^1.2.0", - "streamx": "^2.15.0" - } - }, - "node_modules/teex": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz", - "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==", - "license": "MIT", - "dependencies": { - "streamx": "^2.12.5" - } - }, - "node_modules/text-decoder": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz", - "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==", - "license": "Apache-2.0", - "dependencies": { - "b4a": "^1.6.4" - } - }, - "node_modules/tunnel-agent": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", - "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", - "license": "Apache-2.0", - "dependencies": { - "safe-buffer": "^5.0.1" - }, - "engines": { - "node": "*" - } - }, - "node_modules/undici-types": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", - "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", - "license": "MIT" - }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "license": "MIT" - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "license": "ISC" - } - } -} diff --git a/kb/package.json b/kb/package.json deleted file mode 100644 index 7a250ae..0000000 --- a/kb/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "metaharness-kb", - "version": "3.0.0", - "private": true, - "type": "module", - "description": "Generic, config-driven RVF knowledge-base engine (build/grade/gate) + portable CLI and MCP stdio server. Targets are defined in kb.config.mjs; pass --target to the scripts.", - "bin": { - "kb-ask": "./ask-kb.mjs", - "kb-mcp": "./kb-mcp-server.mjs" - }, - "scripts": { - "ask": "node ask-kb.mjs", - "mcp": "node kb-mcp-server.mjs", - "build": "node build-kb.mjs", - "build:big": "node build-big-variant.mjs both", - "index-primer": "node index-primer.mjs", - "guard": "node guard-check.mjs", - "grade": "node grade-kb.mjs", - "gate": "node gate.mjs", - "bundles": "node make-bundles.mjs" - }, - "dependencies": { - "@ruvector/rvf": "^0.3.0", - "@xenova/transformers": "^2.17.2" - }, - "engines": { - "node": ">=18" - } -} diff --git a/kb/questions/README.md b/kb/questions/README.md deleted file mode 100644 index 4cd6ee3..0000000 --- a/kb/questions/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# KB grading question sets - -`grade-kb.mjs` and `gate.mjs` resolve question files here as -`kb/questions/..jsonl` — e.g. -`agent-harness-generator.tuned.jsonl` and `agent-harness-generator.heldout.jsonl`. - -These are **authored in P6a** (gate A), AFTER the target repo is cloned and the KB is built, so -every `mustContain` token can be verified against text actually present in the source (the ≥98 -deterministic bar requires verified facts, not guessed ones — build-plan §3-A, top risk #3). - -## Line schema (one JSON object per line; `//` / `#` comment lines are skipped) - -```json -{"stage":1,"arc":"what-is-it","query":"What is metaharness?","wantPaths":["README.md","docs/OVERVIEW.md"],"mustContain":["factory for agent frameworks","npx metaharness"],"niceToHave":["harness is the product"],"forbidden":["9 hosts"]} -``` - -| field | required | meaning | -|---|---|---| -| `stage` | yes | arc stage 1–7 (per-stage score = mean of its questions; gate needs every stage ≥ 95) | -| `arc` | no | human label for the stage | -| `query` | yes | the question, run through the SAME `searchKb()` the CLI/MCP use | -| `wantPaths` | yes | path substrings; M1 = 0.6·[top-1 ∈ wantPaths] + 0.4·[any top-k ∈ wantPaths] | -| `mustContain` | yes | verified facts; coverage = fraction present in the assembled top-k answer | -| `niceToHave` | no | bonus facts (15% weight in M2) | -| `forbidden` | no | tokens that must NOT appear (proposal-as-reality, wrong product, invented API); penalize M2 | - -- **tuned** set: used while tuning the reranker. -- **heldout** set: disjoint phrasings of the same 7 stages, NEVER consulted during tuning - (overfit-proof). Gate A passes only when BOTH sets pass on BOTH variants. - -Run: `node grade-kb.mjs --target agent-harness-generator --set tuned` (exit 1 if below threshold). diff --git a/kb/questions/agent-harness-generator.aiq.jsonl b/kb/questions/agent-harness-generator.aiq.jsonl deleted file mode 100644 index a4c1996..0000000 --- a/kb/questions/agent-harness-generator.aiq.jsonl +++ /dev/null @@ -1,21 +0,0 @@ -{ "dimension": "onboarding", "query": "I just got this repo. How do I install, scaffold a harness, build it, and run its tests from scratch? Give me the exact commands.", "mustContain": ["npx metaharness", "npm install", "npm run build", "npm test"] } -{ "dimension": "onboarding", "query": "What is the fastest way to see metaharness actually produce a harness, with the least setup?", "mustContain": ["npx metaharness", "--wizard", "harness doctor"] } -{ "dimension": "onboarding", "query": "How do I scaffold a coding harness for Claude Code in one command and then check it is healthy?", "mustContain": ["npx metaharness", "--template", "--host", "harness doctor"] } -{ "dimension": "what-it-is", "query": "What is metaharness and what specific problem does it solve for me?", "mustContain": ["factory for agent frameworks", "harness is the product", "npx metaharness"] } -{ "dimension": "what-it-is", "query": "Why would I use metaharness instead of forking ruflo, and what do I actually own after generating?", "mustContain": ["harness", "own", "brand"] } -{ "dimension": "what-it-is", "query": "What does 'the harness is the product, not the generator' mean in metaharness?", "mustContain": ["harness", "generator", "own"] } -{ "dimension": "architecture", "query": "What packages make up metaharness and how do they relate? What is the three-layer model?", "mustContain": ["kernel", "host-claude-code", "router", "three-layer"] } -{ "dimension": "architecture", "query": "What is the kernel boundary and which packages are frozen vs free to change?", "mustContain": ["kernel", "@metaharness/kernel", "semver"] } -{ "dimension": "architecture", "query": "If I change the kernel, what is the contract I must honor and what could break downstream?", "mustContain": ["kernel", "HostAdapter", "deprecation"] } -{ "dimension": "capabilities", "query": "What can metaharness do? List the harness subcommands and what each does.", "mustContain": ["doctor", "validate", "score", "genome", "threat-model"] } -{ "dimension": "capabilities", "query": "What can the tool do to a repo before and during scaffolding — scoring, genome, mcp-scan, threat-model, router, Darwin?", "mustContain": ["score", "genome", "mcp-scan", "threat-model", "router", "Darwin"] } -{ "dimension": "capabilities", "query": "Which hosts can metaharness target and what are the main packages it ships?", "mustContain": ["claude-code", "codex", "kernel", "router", "host"] } -{ "dimension": "usage", "query": "Show me how to define an agent, skill, and tool in code with the SDK — what are the functions and types and a real example?", "mustContain": ["defineAgent", "defineSkill", "defineTool", "AgentDef"] } -{ "dimension": "usage", "query": "What is the public API of the Router — how do I construct it, what does route() return, and what options does it take?", "mustContain": ["Router", "route", "RouteResult", "RouterOptions"] } -{ "dimension": "usage", "query": "What does a host adapter implement to turn a harness spec into config files? What is the function signature?", "mustContain": ["HostAdapter", "generateConfig", "HarnessSpec"] } -{ "dimension": "best-practices", "query": "Is metaharness production-ready? What are its honest limits and what should I treat with caution?", "mustContain": ["v0.1.x beta", "kernel", "limit"] } -{ "dimension": "best-practices", "query": "What are the performance budgets and the native vs WASM kernel tradeoff I should know about?", "mustContain": ["90s", "native", "WASM"] } -{ "dimension": "best-practices", "query": "What are the gotchas around Codex trusted projects, Hermes thinking blocks, and the smoke gate?", "mustContain": ["Codex", "Hermes", "smoke"] } -{ "dimension": "extensibility", "query": "How do I add a new host to metaharness? Which interface do I implement and which reference adapter should I copy?", "mustContain": ["HostAdapter", "host-claude-code", "generateConfig"] } -{ "dimension": "extensibility", "query": "How do I add or modify a template, and what is the scaffold/render pipeline that turns a template into a harness?", "mustContain": ["scaffold", "render", "manifest"] } -{ "dimension": "extensibility", "query": "How do I add a new vertical pack and a marketplace plugin safely without breaking the kernel API?", "mustContain": ["VerticalPack", "kernel", "plugin"] } diff --git a/kb/questions/agent-harness-generator.heldout.jsonl b/kb/questions/agent-harness-generator.heldout.jsonl deleted file mode 100644 index fcd73f1..0000000 --- a/kb/questions/agent-harness-generator.heldout.jsonl +++ /dev/null @@ -1,27 +0,0 @@ -{ "stage": 1, "arc": "what-is-it", "query": "In one line, what does MetaHarness turn a repo into?", "wantPaths": ["PRIMER#1-what-is-metaharness", "README.md", "docs/USERGUIDE.md"], "mustContain": ["agent", "harness", "any repo"], "niceToHave": ["factory for agent frameworks", "npm package", "branded CLI"] } -{ "stage": 1, "arc": "what-is-it", "query": "Why is it called a factory and not a framework?", "wantPaths": ["PRIMER#1-what-is-metaharness", "README.md"], "mustContain": ["factory for agent frameworks", "not another agent framework"], "niceToHave": ["harness is the product", "model is replaceable", "client-side"] } -{ "stage": 1, "arc": "what-is-it", "query": "Do I need a MetaHarness account or a server?", "wantPaths": ["PRIMER#1-what-is-metaharness", "README.md", "docs/USAGE.md"], "mustContain": ["client-side", "no account", "hosted backend"], "niceToHave": ["factory for agent frameworks", "npx metaharness", "any repo"] } -{ "stage": 2, "arc": "capabilities", "query": "How do I score a repo before committing to a harness?", "wantPaths": ["PRIMER#2-what-can-the-tool-do-to-a-repo", "README.md", "docs/USAGE.md"], "mustContain": ["metaharness score", "cost-per-run", "report card"], "niceToHave": ["genome", "mcp-scan", "static analysis only"] } -{ "stage": 2, "arc": "capabilities", "query": "What does harness genome report?", "wantPaths": ["PRIMER#2-what-can-the-tool-do-to-a-repo", "docs/USAGE.md"], "mustContain": ["genome", "ready", "needs-work", "blocked"], "niceToHave": ["mcp-scan", "cost-per-run", "static analysis only"] } -{ "stage": 2, "arc": "capabilities", "query": "What is the npm audit for agent tools command?", "wantPaths": ["PRIMER#2-what-can-the-tool-do-to-a-repo", "README.md"], "mustContain": ["mcp-scan", "static", "HIGH"], "niceToHave": ["genome", "threat-model", "cost-per-run"] } -{ "stage": 2, "arc": "capabilities", "query": "What artifact does threat-model produce?", "wantPaths": ["PRIMER#2-what-can-the-tool-do-to-a-repo", "docs/USAGE.md"], "mustContain": ["threat-model", "clean", "medium", "high"], "niceToHave": ["mcp-scan", "genome", "static analysis only"] } -{ "stage": 3, "arc": "inventory-components", "query": "What does the kernel boundary forbid?", "wantPaths": ["PRIMER#3-what-packages-make-up-metaharness", "docs/ARCHITECTURE.md"], "mustContain": ["Layer 1", "imports", "portable"], "niceToHave": ["three-layer", "@metaharness/kernel", "ADR-002"] } -{ "stage": 3, "arc": "inventory-components", "query": "Which packages live in the user-facing surface layer?", "wantPaths": ["PRIMER#3-what-packages-make-up-metaharness", "docs/ARCHITECTURE.md"], "mustContain": ["create-agent-harness", "harness", "marketplace plugin"], "niceToHave": ["three-layer", "user-facing", "Layer 3"] } -{ "stage": 3, "arc": "inventory-components", "query": "What does the model router package do at component level?", "wantPaths": ["PRIMER#3-what-packages-make-up-metaharness", "docs/ARCHITECTURE.md"], "mustContain": ["router", "model"], "niceToHave": ["cheapest model", "quality bar", "eval logs"] } -{ "stage": 3, "arc": "inventory-components", "query": "What kernel subsystems are bundled in the Rust core?", "wantPaths": ["PRIMER#3-what-packages-make-up-metaharness", "docs/ARCHITECTURE.md"], "mustContain": ["claims", "hooks", "memory", "routing", "witness"], "niceToHave": ["@metaharness/kernel", "wasm", "NAPI-RS"] } -{ "stage": 4, "arc": "how-each-works-composer", "query": "What object drives template selection in the composer?", "wantPaths": ["PRIMER#4-how-does-the-composer-scaffold-a-harness", "docs/adrs/ADR-003-generator-architecture.md"], "mustContain": ["HarnessChoice", "interactive", "non-interactive"], "niceToHave": ["9 stages", "Identity", "Confirm"] } -{ "stage": 4, "arc": "how-each-works-composer", "query": "Which composer stage toggles kernel subsystems?", "wantPaths": ["PRIMER#4-how-does-the-composer-scaffold-a-harness", "docs/adrs/ADR-003-generator-architecture.md"], "mustContain": ["Primitives", "mcp", "always on", "default: all on"], "niceToHave": ["9 stages", "HarnessChoice", "Confirm"] } -{ "stage": 4, "arc": "how-each-works-composer", "query": "Is the 7-arc teaching outline the same as the composer stages?", "wantPaths": ["PRIMER#4-how-does-the-composer-scaffold-a-harness", "docs/adrs/ADR-003-generator-architecture.md"], "mustContain": ["9 stages", "teaching", "do not conflate"], "niceToHave": ["HarnessChoice", "Identity", "Confirm"] } -{ "stage": 4, "arc": "how-each-works-composer", "query": "What is the last composer stage before generation?", "wantPaths": ["PRIMER#4-how-does-the-composer-scaffold-a-harness", "docs/adrs/ADR-003-generator-architecture.md"], "mustContain": ["Confirm", "file list", "kernel version"], "niceToHave": ["9 stages", "HarnessChoice", "Identity"] } -{ "stage": 5, "arc": "maturity", "query": "Should I assert one fixed test count?", "wantPaths": ["PRIMER#5-is-this-production-ready-maturity-and-honest-limits", "README.md"], "mustContain": ["568", "snapshot", "badge"], "niceToHave": ["v0.1.x beta", "doc-reconciliation", "CI matrix"] } -{ "stage": 5, "arc": "maturity", "query": "What release status is MetaHarness in right now?", "wantPaths": ["PRIMER#5-is-this-production-ready-maturity-and-honest-limits", "README.md"], "mustContain": ["v0.1.x beta", "published", "doc-reconciliation"], "niceToHave": ["CI matrix", "568", "default-deny"] } -{ "stage": 5, "arc": "maturity", "query": "Which three hosts are the newer additions?", "wantPaths": ["PRIMER#5-is-this-production-ready-maturity-and-honest-limits", "README.md"], "mustContain": ["copilot", "opencode", "github-actions"], "niceToHave": ["nine", "six stable", "v0.1.x beta"] } -{ "stage": 5, "arc": "maturity", "query": "How mature is the release pipeline compared to the product?", "wantPaths": ["PRIMER#5-is-this-production-ready-maturity-and-honest-limits", "README.md"], "mustContain": ["CI matrix", "security pipeline", "single-command releases"], "niceToHave": ["v0.1.x beta", "568", "default-deny"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Which doc gives the plain-language usage and FAQ?", "wantPaths": ["PRIMER#6-where-do-i-read-about-the-architecture", "docs/ARCHITECTURE.md"], "mustContain": ["USERGUIDE.md", "FAQ", "limits"], "niceToHave": ["ARCHITECTURE.md", "INDEX.md", "OVERVIEW.md"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where is the three-layer model and CI matrix described?", "wantPaths": ["PRIMER#6-where-do-i-read-about-the-architecture", "docs/ARCHITECTURE.md"], "mustContain": ["ARCHITECTURE.md", "three-layer", "CI matrix"], "niceToHave": ["INDEX.md", "OVERVIEW.md", "USERGUIDE.md"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "What is the read-in-order index for the ADR series?", "wantPaths": ["PRIMER#6-where-do-i-read-about-the-architecture", "docs/ARCHITECTURE.md"], "mustContain": ["INDEX.md", "ADR"], "niceToHave": ["ARCHITECTURE.md", "OVERVIEW.md", "ADR-003"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where does the host integration model live?", "wantPaths": ["PRIMER#6-where-do-i-read-about-the-architecture", "docs/ARCHITECTURE.md"], "mustContain": ["ADR-004", "host"], "niceToHave": ["ARCHITECTURE.md", "INDEX.md", "OVERVIEW.md"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "What is the fastest path if I don't know what to pick?", "wantPaths": ["PRIMER#7-how-do-i-start-the-fastest-end-to-end", "README.md", "docs/USAGE.md"], "mustContain": ["npx metaharness --wizard", "4-question"], "niceToHave": ["harness doctor", "own", "harness validate"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "Show the one-liner to scaffold a coding harness for Claude Code.", "wantPaths": ["PRIMER#7-how-do-i-start-the-fastest-end-to-end", "README.md"], "mustContain": ["--template", "--host", "npm install"], "niceToHave": ["npx metaharness", "harness doctor", "own"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "After scaffolding, do I own the files and can I trim them?", "wantPaths": ["PRIMER#7-how-do-i-start-the-fastest-end-to-end", "README.md", "docs/USAGE.md"], "mustContain": ["own", "trim", "tune"], "niceToHave": ["harness doctor", "harness validate", "npx metaharness"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "What command clears every release gate before publishing?", "wantPaths": ["PRIMER#7-how-do-i-start-the-fastest-end-to-end", "docs/USAGE.md"], "mustContain": ["harness validate", "npm publish --provenance"], "niceToHave": ["own", "npx my-bot init", "harness doctor"] } diff --git a/kb/questions/agent-harness-generator.tuned.jsonl b/kb/questions/agent-harness-generator.tuned.jsonl deleted file mode 100644 index 86893d5..0000000 --- a/kb/questions/agent-harness-generator.tuned.jsonl +++ /dev/null @@ -1,28 +0,0 @@ -{ "stage": 1, "arc": "what-is-it", "query": "What is metaharness?", "wantPaths": ["PRIMER#1-what-is-metaharness", "README.md", "docs/USERGUIDE.md"], "mustContain": ["factory for agent frameworks", "harness is the product", "npx metaharness"], "niceToHave": ["branded CLI", "client-side", "any repo"] } -{ "stage": 1, "arc": "what-is-it", "query": "What does metaharness produce when I run it?", "wantPaths": ["PRIMER#1-what-is-metaharness", "README.md", "docs/USERGUIDE.md"], "mustContain": ["npm package", "scoped memory", "safety policy"], "niceToHave": ["branded CLI", "npx metaharness", "any repo"] } -{ "stage": 1, "arc": "what-is-it", "query": "Is the harness the model or a wrapper around it?", "wantPaths": ["PRIMER#1-what-is-metaharness", "docs/USERGUIDE.md"], "mustContain": ["wrapper", "Claude or GPT", "model is replaceable"], "niceToHave": ["harness is the product", "factory for agent frameworks", "branded CLI"] } -{ "stage": 1, "arc": "what-is-it", "query": "What is the published CLI name versus create-agent-harness?", "wantPaths": ["PRIMER#1-what-is-metaharness", "README.md"], "mustContain": ["metaharness", "create-agent-harness", "alias"], "niceToHave": ["factory for agent frameworks", "no account", "client-side"] } -{ "stage": 2, "arc": "capabilities", "query": "What can the tool do to a repo before I build?", "wantPaths": ["PRIMER#2-what-can-the-tool-do-to-a-repo", "README.md", "docs/USAGE.md"], "mustContain": ["score", "genome", "mcp-scan", "router", "Darwin"], "niceToHave": ["static analysis only", "cost-per-run", "threat-model"] } -{ "stage": 2, "arc": "capabilities", "query": "Does metaharness ever execute my repository code?", "wantPaths": ["PRIMER#2-what-can-the-tool-do-to-a-repo", "README.md"], "mustContain": ["static analysis only", "never", "execution: disabled"], "niceToHave": ["genome", "mcp-scan", "trust: inferred"] } -{ "stage": 2, "arc": "capabilities", "query": "How does metaharness cut my model cost?", "wantPaths": ["PRIMER#2-what-can-the-tool-do-to-a-repo", "README.md"], "mustContain": ["router", "cheapest model", "quality bar"], "niceToHave": ["eval logs", "Darwin", "genome"] } -{ "stage": 2, "arc": "capabilities", "query": "What does Darwin Mode do?", "wantPaths": ["PRIMER#2-what-can-the-tool-do-to-a-repo", "README.md"], "mustContain": ["mutates its own config", "sandbox", "model stays frozen"], "niceToHave": ["npm run evolve", "measurably improves", "harness evolves"] } -{ "stage": 3, "arc": "inventory-components", "query": "What packages make up metaharness?", "wantPaths": ["PRIMER#3-what-packages-make-up-metaharness", "docs/ARCHITECTURE.md"], "mustContain": ["kernel", "host-claude-code", "router", "darwin", "three-layer"], "niceToHave": ["NAPI-RS", "user-facing", "create-agent-harness"] } -{ "stage": 3, "arc": "inventory-components", "query": "What is the kernel and what is in it?", "wantPaths": ["PRIMER#3-what-packages-make-up-metaharness", "docs/ARCHITECTURE.md"], "mustContain": ["@metaharness/kernel", "Rust", "wasm", "NAPI-RS"], "niceToHave": ["three-layer", "Layer 1", "claims"] } -{ "stage": 3, "arc": "inventory-components", "query": "What are the three layers of the architecture?", "wantPaths": ["PRIMER#3-what-packages-make-up-metaharness", "docs/ARCHITECTURE.md"], "mustContain": ["Kernel", "Adapter", "user-facing"], "niceToHave": ["three-layer", "Layer 1", "host-claude-code"] } -{ "stage": 3, "arc": "inventory-components", "query": "Which host adapter packages exist?", "wantPaths": ["PRIMER#3-what-packages-make-up-metaharness", "docs/ARCHITECTURE.md"], "mustContain": ["host-codex", "host-pi-dev", "host-hermes", "host-openclaw"], "niceToHave": ["host-rvm", "host-copilot", "host-github-actions"] } -{ "stage": 4, "arc": "how-each-works-composer", "query": "How does the composer scaffold a harness?", "wantPaths": ["PRIMER#4-how-does-the-composer-scaffold-a-harness", "docs/adrs/ADR-003-generator-architecture.md"], "mustContain": ["Identity", "Hosts", "Primitives", "Agents", "Skills", "Plugins", "Features"], "niceToHave": ["9 stages", "HarnessChoice", "Confirm"] } -{ "stage": 4, "arc": "how-each-works-composer", "query": "How many stages does the composer have and what are they?", "wantPaths": ["PRIMER#4-how-does-the-composer-scaffold-a-harness", "docs/adrs/ADR-003-generator-architecture.md"], "mustContain": ["9 stages", "Branding", "Confirm", "HarnessChoice"], "niceToHave": ["Identity", "Primitives", "Agents"] } -{ "stage": 4, "arc": "how-each-works-composer", "query": "How do template overlays merge?", "wantPaths": ["PRIMER#4-how-does-the-composer-scaffold-a-harness", "docs/adrs/ADR-003-generator-architecture.md"], "mustContain": ["_base", "host overlay", "feature overlay", "later wins"], "niceToHave": ["HarnessChoice", "9 stages", "Confirm"] } -{ "stage": 4, "arc": "how-each-works-composer", "query": "What are the default agents and skills the composer picks?", "wantPaths": ["PRIMER#4-how-does-the-composer-scaffold-a-harness", "docs/adrs/ADR-003-generator-architecture.md"], "mustContain": ["coder", "reviewer", "tester", "hooks-automation", "memory-search"], "niceToHave": ["swarm-orchestration", "9 stages", "HarnessChoice"] } -{ "stage": 5, "arc": "maturity", "query": "Is this production-ready?", "wantPaths": ["PRIMER#5-is-this-production-ready-maturity-and-honest-limits", "README.md"], "mustContain": ["v0.1.x beta", "568", "never"], "niceToHave": ["doc-reconciliation", "CI matrix", "default-deny"] } -{ "stage": 5, "arc": "maturity", "query": "How many hosts are stable versus newer?", "wantPaths": ["PRIMER#5-is-this-production-ready-maturity-and-honest-limits", "README.md"], "mustContain": ["nine", "six", "copilot", "opencode", "github-actions"], "niceToHave": ["v0.1.x beta", "six stable", "newer additions"] } -{ "stage": 5, "arc": "maturity", "query": "What is the default-deny posture of the generated MCP server?", "wantPaths": ["PRIMER#5-is-this-production-ready-maturity-and-honest-limits", "README.md"], "mustContain": ["default-deny", "no network", "no shell", "no file-write"], "niceToHave": ["v0.1.x beta", "CI matrix", "never executes"] } -{ "stage": 5, "arc": "maturity", "query": "What is metaharness NOT?", "wantPaths": ["PRIMER#5-is-this-production-ready-maturity-and-honest-limits", "docs/USERGUIDE.md"], "mustContain": ["not a chatbot", "no-code platform", "hosted service", "fine-tune"], "niceToHave": ["v0.1.x beta", "default-deny", "never executes"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where do I read about the architecture?", "wantPaths": ["PRIMER#6-where-do-i-read-about-the-architecture", "docs/ARCHITECTURE.md"], "mustContain": ["ARCHITECTURE.md", "OVERVIEW.md", "USERGUIDE.md", "INDEX.md"], "niceToHave": ["USAGE.md", "ADR-003", "three-layer"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Which doc covers the build to publish flow and subcommands?", "wantPaths": ["PRIMER#6-where-do-i-read-about-the-architecture", "docs/ARCHITECTURE.md"], "mustContain": ["USAGE.md", "harness", "subcommand"], "niceToHave": ["ARCHITECTURE.md", "INDEX.md", "OVERVIEW.md"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where is the composer 9-stage flow documented?", "wantPaths": ["PRIMER#6-where-do-i-read-about-the-architecture", "docs/ARCHITECTURE.md"], "mustContain": ["ADR-003", "ADR-004", "INDEX.md"], "niceToHave": ["ARCHITECTURE.md", "OVERVIEW.md", "USAGE.md"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where do I read why metaharness exists?", "wantPaths": ["PRIMER#6-where-do-i-read-about-the-architecture", "docs/ARCHITECTURE.md"], "mustContain": ["OVERVIEW.md", "scope", "ADR-001"], "niceToHave": ["ARCHITECTURE.md", "INDEX.md", "USERGUIDE.md"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "How do I start the fastest?", "wantPaths": ["PRIMER#7-how-do-i-start-the-fastest-end-to-end", "README.md", "docs/USAGE.md"], "mustContain": ["npx metaharness --wizard", "--template", "--host", "npm install"], "niceToHave": ["harness doctor", "harness validate", "own"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "What does the wizard ask me?", "wantPaths": ["PRIMER#7-how-do-i-start-the-fastest-end-to-end", "README.md"], "mustContain": ["4-question", "name", "template", "host", "description"], "niceToHave": ["npx metaharness --wizard", "harness doctor", "own"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "How do I check the scaffold is healthy after generating?", "wantPaths": ["PRIMER#7-how-do-i-start-the-fastest-end-to-end", "docs/USERGUIDE.md"], "mustContain": ["harness doctor", "scaffold"], "niceToHave": ["npx metaharness --wizard", "harness validate", "own"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "How do I publish my harness and what do my users run?", "wantPaths": ["PRIMER#7-how-do-i-start-the-fastest-end-to-end", "docs/USAGE.md"], "mustContain": ["harness validate", "npm publish --provenance", "npx my-bot init"], "niceToHave": ["own", "harness doctor", "npx metaharness"] } diff --git a/kb/questions/photonlayer.aiq.jsonl b/kb/questions/photonlayer.aiq.jsonl deleted file mode 100644 index 8864cfb..0000000 --- a/kb/questions/photonlayer.aiq.jsonl +++ /dev/null @@ -1,21 +0,0 @@ -{ "dimension": "onboarding", "query": "I just got this repo. How do I install, build, run, and test PhotonLayer from scratch? Give me the exact commands.", "mustContain": ["cargo add photonlayer-core", "cargo build", "cargo test", "cargo run", "hello_optics"] } -{ "dimension": "onboarding", "query": "What is the fastest way to see PhotonLayer actually run something with no setup, and what is the first example I should run locally?", "mustContain": ["hello_optics", "cargo run", "example"] } -{ "dimension": "onboarding", "query": "How do I run PhotonLayer in a browser, and which crate provides the WebAssembly bindings?", "mustContain": ["photonlayer-wasm", "wasm", "browser"] } -{ "dimension": "what-it-is", "query": "What is PhotonLayer and what specific problem does it solve for me?", "mustContain": ["phase mask", "sensor", "deterministic", "compress", "decoder"] } -{ "dimension": "what-it-is", "query": "How is PhotonLayer different from a normal camera plus a neural network, and what does the sensor actually capture?", "mustContain": ["phase mask", "measurement", "compress", "decoder"] } -{ "dimension": "what-it-is", "query": "What does a 'learned phase mask' do, and what is the receipt that every run emits?", "mustContain": ["phase mask", "receipt", "BLAKE3"] } -{ "dimension": "architecture", "query": "What crates make up PhotonLayer and how do they depend on each other? Which crate is the foundation?", "mustContain": ["photonlayer-core", "photonlayer-bench", "photonlayer-wasm", "photonlayer-cli"] } -{ "dimension": "architecture", "query": "If I change something in photonlayer-core, which other crates could be affected?", "mustContain": ["photonlayer-bench", "photonlayer-wasm", "photonlayer-cli"] } -{ "dimension": "architecture", "query": "Which crate owns the optical simulator versus the training and benchmarks, and what does each module in core do?", "mustContain": ["photonlayer-core", "photonlayer-bench", "mask", "propagate", "detector"] } -{ "dimension": "capabilities", "query": "What can PhotonLayer do? List its features: compression, gradient training, multi-plane cascade, and receipts.", "mustContain": ["compress", "gradient", "cascade", "receipt"] } -{ "dimension": "capabilities", "query": "Which CLI subcommands does PhotonLayer expose and what does each do?", "mustContain": ["bench", "barcode", "edge", "privacy-gate", "verify-receipt"] } -{ "dimension": "capabilities", "query": "What are PhotonLayer's measured results — the accuracy numbers for gradient training and the multi-plane cascade at 16x compression?", "mustContain": ["83.30", "88.80", "compression"] } -{ "dimension": "usage", "query": "Show me how to run the optical simulator in photonlayer-core — what are the key types and a real minimal example?", "mustContain": ["ScalarSimulator", "PhaseMask", "InputImage", "OpticalConfig"] } -{ "dimension": "usage", "query": "What is the public API of the phase mask — how do I create a random, designed, or learned PhaseMask?", "mustContain": ["PhaseMask", "random"] } -{ "dimension": "usage", "query": "How do I propagate an optical field and run a diffraction step — what function and propagation modes are available?", "mustContain": ["propagate", "PropagationMode", "Fresnel"] } -{ "dimension": "best-practices", "query": "Is PhotonLayer production-ready? What are its honest limits around hardware, privacy, and the accuracy figures?", "mustContain": ["simulator", "privacy", "hardware", "not"] } -{ "dimension": "best-practices", "query": "What should I treat with caution in PhotonLayer — what does the privacy probe actually measure and what does the 16x MAC reduction count?", "mustContain": ["privacy", "linear", "decoder"] } -{ "dimension": "best-practices", "query": "What are the gotchas around memory, grid size, determinism, and training when running PhotonLayer?", "mustContain": ["deterministic", "FFT", "memory"] } -{ "dimension": "extensibility", "query": "If I want to add a new propagation mode or diffraction model, where does it go and what is the contract I must satisfy (forward and adjoint)?", "mustContain": ["propagate", "PropagationMode", "adjoint"] } -{ "dimension": "extensibility", "query": "How would I safely add a new phase mask type or training method to photonlayer-bench without breaking the core or wasm crates?", "mustContain": ["PhaseMask", "photonlayer-core", "gradient"] } -{ "dimension": "extensibility", "query": "Where do I add a new CLI subcommand or a new wasm binding, and what wires the Rust simulator to JavaScript?", "mustContain": ["photonlayer-cli", "photonlayer-wasm", "wasm_bindgen"] } diff --git a/kb/questions/photonlayer.heldout.jsonl b/kb/questions/photonlayer.heldout.jsonl deleted file mode 100644 index 23a704e..0000000 --- a/kb/questions/photonlayer.heldout.jsonl +++ /dev/null @@ -1,14 +0,0 @@ -{ "stage": 1, "arc": "what-is-it", "query": "In one line, what does PhotonLayer turn light into?", "wantPaths": ["PRIMER#1-what-is-photonlayer", "README.md", "crates/photonlayer-core"], "mustContain": ["measurement", "sensor", "phase mask"], "niceToHave": ["compress", "answer", "decoder"] } -{ "stage": 1, "arc": "what-is-it", "query": "Why is PhotonLayer described as a front end?", "wantPaths": ["PRIMER#1-what-is-photonlayer", "README.md", "crates/photonlayer-core"], "mustContain": ["light", "trained", "digital"], "niceToHave": ["before", "transformation", "backend"] } -{ "stage": 2, "arc": "capabilities", "query": "What does the front end actually output?", "wantPaths": ["PRIMER#4-how-the-optical-pipeline-works-step-by-step", "PRIMER#2-what-can-photonlayer-do", "README.md"], "mustContain": ["measurement", "sensor", "decoder"], "niceToHave": ["compressed", "numbers", "answer"] } -{ "stage": 2, "arc": "capabilities", "query": "Can PhotonLayer reproduce the exact same result twice?", "wantPaths": ["PRIMER#2-what-can-photonlayer-do", "README.md", "crates/photonlayer-core"], "mustContain": ["deterministic", "receipt", "reproducible"], "niceToHave": ["bit-identical", "BLAKE3", "hash"] } -{ "stage": 2, "arc": "capabilities", "query": "What does a multi-plane cascade achieve?", "wantPaths": ["PRIMER#2-what-can-photonlayer-do", "README.md"], "mustContain": ["88.80", "plane"], "niceToHave": ["cascade", "decorrelated", "compression"] } -{ "stage": 3, "arc": "inventory-components", "query": "Which crate holds the command-line driver?", "wantPaths": ["PRIMER#3-what-is-photonlayer-made-of-the-four-crates", "README.md", "crates/photonlayer-cli"], "mustContain": ["photonlayer-cli", "command-line"], "niceToHave": ["verify-receipt", "bench", "edge"] } -{ "stage": 3, "arc": "inventory-components", "query": "What types does the core prelude export?", "wantPaths": ["PRIMER#3-what-is-photonlayer-made-of-the-four-crates", "crates/photonlayer-core"], "mustContain": ["PhaseMask", "ScalarSimulator", "OpticalConfig"], "niceToHave": ["prelude", "InputImage", "OpticalField"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "What happens after the light hits the sensor?", "wantPaths": ["PRIMER#4-how-the-optical-pipeline-works-step-by-step", "crates/photonlayer-core", "README.md"], "mustContain": ["decoder", "measurement", "decision"], "niceToHave": ["receipt", "metrics", "tiny"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "What propagation modes can the field use?", "wantPaths": ["PRIMER#4-how-the-optical-pipeline-works-step-by-step", "crates/photonlayer-core", "README.md"], "mustContain": ["Fresnel", "Fraunhofer"], "niceToHave": ["angular-spectrum", "diffraction", "propagat"] } -{ "stage": 5, "arc": "maturity", "query": "Does PhotonLayer beat a CNN on MNIST?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["not", "single", "decoder"], "niceToHave": ["CNN", "state-of-the-art", "baseline"] } -{ "stage": 5, "arc": "maturity", "query": "What is out of scope for PhotonLayer?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["single", "not", "simulator"], "niceToHave": ["multi-layer", "out of scope", "hardware"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where is the in-browser demo documented?", "wantPaths": ["PRIMER#6-where-do-i-read-more-the-docs-map", "README.md", "docs"], "mustContain": ["browser", "demo", "WASM"], "niceToHave": ["playground", "live", "client-side"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "How do I add PhotonLayer to a Rust project?", "wantPaths": ["PRIMER#7-how-do-i-install-and-run-it-end-to-end", "README.md"], "mustContain": ["cargo add photonlayer-core"], "niceToHave": ["prelude", "ScalarSimulator", "simulate"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "How can I try PhotonLayer without installing anything?", "wantPaths": ["PRIMER#7-how-do-i-install-and-run-it-end-to-end", "README.md"], "mustContain": ["browser", "demo"], "niceToHave": ["live", "WASM", "no install"] } diff --git a/kb/questions/photonlayer.tuned.jsonl b/kb/questions/photonlayer.tuned.jsonl deleted file mode 100644 index 2bf7b06..0000000 --- a/kb/questions/photonlayer.tuned.jsonl +++ /dev/null @@ -1,23 +0,0 @@ -{ "stage": 1, "arc": "what-is-it", "query": "What is PhotonLayer?", "wantPaths": ["PRIMER#1-what-is-photonlayer", "README.md", "crates/photonlayer-core"], "mustContain": ["phase mask", "sensor", "deterministic", "decoder"], "niceToHave": ["pure Rust", "front end", "receipt"] } -{ "stage": 1, "arc": "what-is-it", "query": "What does PhotonLayer actually do in plain language?", "wantPaths": ["PRIMER#1-what-is-photonlayer", "README.md"], "mustContain": ["phase mask", "light", "measurement", "answer"], "niceToHave": ["smart glass", "compress", "tiny sensor"] } -{ "stage": 1, "arc": "what-is-it", "query": "Is PhotonLayer an optical neural network?", "wantPaths": ["PRIMER#1-what-is-photonlayer", "README.md"], "mustContain": ["not", "optical neural network", "compression"], "niceToHave": ["auditable", "task-useful", "wedge"] } -{ "stage": 1, "arc": "what-is-it", "query": "What is a learned phase mask?", "wantPaths": ["PRIMER#1-what-is-photonlayer", "crates/photonlayer-core", "README.md"], "mustContain": ["phase mask", "light", "trained"], "niceToHave": ["mask", "learned", "transform"] } -{ "stage": 2, "arc": "capabilities", "query": "What can PhotonLayer do?", "wantPaths": ["PRIMER#2-what-can-photonlayer-do", "README.md"], "mustContain": ["compress", "sensor pixels", "receipt", "gradient"], "niceToHave": ["16", "accuracy", "BLAKE3"] } -{ "stage": 2, "arc": "capabilities", "query": "How much does PhotonLayer compress the capture?", "wantPaths": ["PRIMER#2-what-can-photonlayer-do", "README.md", "crates/photonlayer-core"], "mustContain": ["16", "64", "sensor pixels"], "niceToHave": ["fewer", "reduction", "learned mask"] } -{ "stage": 2, "arc": "capabilities", "query": "What does the BLAKE3 receipt prove?", "wantPaths": ["PRIMER#2-what-can-photonlayer-do", "README.md", "crates/photonlayer-core"], "mustContain": ["receipt", "reproducible", "measurement"], "niceToHave": ["BLAKE3", "tamper", "determinism"] } -{ "stage": 2, "arc": "capabilities", "query": "What accuracy does gradient training reach?", "wantPaths": ["PRIMER#2-what-can-photonlayer-do", "README.md"], "mustContain": ["83.30", "gradient", "adjoint"], "niceToHave": ["ceiling", "hill-climb", "88.80"] } -{ "stage": 3, "arc": "inventory-components", "query": "What crates make up PhotonLayer?", "wantPaths": ["PRIMER#3-what-is-photonlayer-made-of-the-four-crates", "README.md"], "mustContain": ["photonlayer-core", "photonlayer-bench", "photonlayer-wasm", "photonlayer-cli"], "niceToHave": ["four crates", "simulator", "benchmarks"] } -{ "stage": 3, "arc": "inventory-components", "query": "What does the photonlayer-core crate contain?", "wantPaths": ["PRIMER#3-what-is-photonlayer-made-of-the-four-crates", "crates/photonlayer-core", "README.md"], "mustContain": ["diffraction", "FFT", "phase mask", "receipt"], "niceToHave": ["Fresnel", "Fraunhofer", "detector"] } -{ "stage": 3, "arc": "inventory-components", "query": "What is the photonlayer-bench crate for?", "wantPaths": ["PRIMER#3-what-is-photonlayer-made-of-the-four-crates", "README.md", "crates/photonlayer-bench"], "mustContain": ["benchmark", "MNIST", "differential"], "niceToHave": ["compression sweep", "ablation", "training"] } -{ "stage": 3, "arc": "inventory-components", "query": "What does photonlayer-wasm do?", "wantPaths": ["PRIMER#3-what-is-photonlayer-made-of-the-four-crates", "README.md", "crates/photonlayer-wasm"], "mustContain": ["WASM", "browser", "receipt"], "niceToHave": ["playground", "bindings", "WebAssembly", "client-side"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "How does the optical pipeline work step by step?", "wantPaths": ["PRIMER#4-how-the-optical-pipeline-works-step-by-step", "crates/photonlayer-core", "README.md"], "mustContain": ["phase mask", "propagat", "sensor", "decoder"], "niceToHave": ["input image", "diffraction", "receipt"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "What are the stages from image to decision?", "wantPaths": ["PRIMER#4-how-the-optical-pipeline-works-step-by-step", "crates/photonlayer-core"], "mustContain": ["input image", "phase mask", "propagat", "sensor"], "niceToHave": ["field", "detector", "metrics"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "How is PhotonLayer different from a normal camera and model?", "wantPaths": ["PRIMER#4-how-the-optical-pipeline-works-step-by-step", "PRIMER#1-what-is-photonlayer", "README.md"], "mustContain": ["light", "sensor", "measurement"], "niceToHave": ["normal camera", "before", "compute"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "How is the phase mask trained?", "wantPaths": ["PRIMER#4-how-the-optical-pipeline-works-step-by-step", "README.md", "crates/photonlayer-bench"], "mustContain": ["gradient", "adjoint", "hill-climb"], "niceToHave": ["Adam", "backward", "descent"] } -{ "stage": 5, "arc": "maturity", "query": "Is PhotonLayer production-ready and what are its limits?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["simulator", "single", "No privacy", "not"], "niceToHave": ["roadmap", "hardware", "state-of-the-art"] } -{ "stage": 5, "arc": "maturity", "query": "Does PhotonLayer guarantee privacy?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["No privacy", "measurement", "not the raw image"], "niceToHave": ["linear", "reconstruction", "guarantee"] } -{ "stage": 5, "arc": "maturity", "query": "Is PhotonLayer real hardware or a simulator?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["simulator", "Rust", "roadmap"], "niceToHave": ["hardware", "glass", "reproducible"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where do I read more about PhotonLayer?", "wantPaths": ["PRIMER#6-where-do-i-read-more-the-docs-map", "README.md", "examples/README.md"], "mustContain": ["README", "examples", "crates"], "niceToHave": ["docs", "citations", "playground"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where are the runnable examples documented?", "wantPaths": ["PRIMER#6-where-do-i-read-more-the-docs-map", "examples/README.md", "README.md"], "mustContain": ["examples", "cargo run"], "niceToHave": ["hello_optics", "ladder", "offline"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "How do I install and run PhotonLayer?", "wantPaths": ["PRIMER#7-how-do-i-install-and-run-it-end-to-end", "README.md"], "mustContain": ["cargo add photonlayer-core", "cargo run", "hello_optics"], "niceToHave": ["live demo", "browser", "example"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "What is the first example I should run?", "wantPaths": ["PRIMER#7-how-do-i-install-and-run-it-end-to-end", "README.md", "examples/README.md"], "mustContain": ["hello_optics", "cargo run", "photonlayer-core"], "niceToHave": ["minimal", "frame hash", "bit-identical"] } diff --git a/kb/questions/ruqu.aiq.jsonl b/kb/questions/ruqu.aiq.jsonl deleted file mode 100644 index 8604726..0000000 --- a/kb/questions/ruqu.aiq.jsonl +++ /dev/null @@ -1,21 +0,0 @@ -{ "dimension": "onboarding", "query": "I just got this repo. How do I install, build, run, and test ruqu from scratch? Give me the exact commands.", "mustContain": ["cargo add ruqu-core", "cargo build", "cargo test", "wasm-pack build", "npx @ruvector/ruqu"] } -{ "dimension": "onboarding", "query": "What is the fastest way to see ruqu actually run something, with no Rust toolchain set up?", "mustContain": ["npx @ruvector/ruqu", "simulate", "qubits"] } -{ "dimension": "onboarding", "query": "How do I build the WebAssembly bundle so ruqu runs in a browser?", "mustContain": ["wasm-pack build", "ruqu-wasm", "--target web"] } -{ "dimension": "what-it-is", "query": "What is ruqu and what specific problem does it solve for me?", "mustContain": ["quantum", "state-vector", "simulator", "no quantum hardware", "Rust"] } -{ "dimension": "what-it-is", "query": "Why would I use ruqu instead of running on a real quantum computer, and what are its answers like?", "mustContain": ["exact", "no quantum hardware", "simulator"] } -{ "dimension": "what-it-is", "query": "What does 'state-vector simulator' mean in ruqu and why does it matter?", "mustContain": ["full quantum state", "complex amplitudes", "exact"] } -{ "dimension": "architecture", "query": "What crates make up ruqu and how do they depend on each other? Which crate is the foundation?", "mustContain": ["ruqu-core", "ruqu-algorithms", "ruqu-exotic", "ruqu-wasm", "coherence"] } -{ "dimension": "architecture", "query": "If I change something in ruqu-core, which other crates could be affected?", "mustContain": ["ruqu-algorithms", "ruqu-exotic", "ruqu-wasm"] } -{ "dimension": "architecture", "query": "What is the coherence engine (ruQu) and where does it sit relative to the simulator crates?", "mustContain": ["coherence", "ruQu"] } -{ "dimension": "capabilities", "query": "What can ruqu do? List the algorithms and features it ships with.", "mustContain": ["VQE", "Grover", "QAOA", "Surface Code", "noise"] } -{ "dimension": "capabilities", "query": "Which CLI commands does ruqu expose and what does each do?", "mustContain": ["simulate", "grover", "qaoa", "capabilities", "doctor"] } -{ "dimension": "capabilities", "query": "What quantum algorithms come built in, and what does each one solve (chemistry, search, optimization, error correction)?", "mustContain": ["VQE", "Grover", "QAOA", "Surface Code"] } -{ "dimension": "usage", "query": "Show me how to build and run a quantum circuit in ruqu-core — what are the key types and functions and a real example?", "mustContain": ["QuantumCircuit", "Simulator", "StateVector"] } -{ "dimension": "usage", "query": "How do I run Grover's search with ruqu-algorithms? What is the function signature and config?", "mustContain": ["run_grover", "Grover"] } -{ "dimension": "usage", "query": "What is the public API for picking a simulation backend — what function analyzes a circuit and what does it return?", "mustContain": ["analyze_circuit", "backend"] } -{ "dimension": "best-practices", "query": "Is ruqu production-ready? What are its honest limits and how many qubits can it handle?", "mustContain": ["simulator", "no quantum hardware", "qubit", "MIT"] } -{ "dimension": "best-practices", "query": "What is experimental or quantum-inspired in ruqu that I should treat with caution?", "mustContain": ["exotic", "experimental"] } -{ "dimension": "best-practices", "query": "What are the gotchas around qubit count and memory when running large circuits?", "mustContain": ["qubit", "memory", "state-vector"] } -{ "dimension": "extensibility", "query": "If I want to add a new quantum algorithm, which crate should it go in and what does it depend on?", "mustContain": ["ruqu-algorithms", "ruqu-core"] } -{ "dimension": "extensibility", "query": "How would I safely add a new gate or backend to ruqu-core without breaking the algorithms or wasm crates?", "mustContain": ["ruqu-core", "backend"] } -{ "dimension": "extensibility", "query": "Where do I add a new CLI subcommand or wasm binding, and what wires the Rust simulator to JavaScript?", "mustContain": ["ruqu-wasm", "wasm-bindgen"] } diff --git a/kb/questions/ruqu.heldout.jsonl b/kb/questions/ruqu.heldout.jsonl deleted file mode 100644 index 54261a8..0000000 --- a/kb/questions/ruqu.heldout.jsonl +++ /dev/null @@ -1,25 +0,0 @@ -{ "stage": 1, "arc": "what-is-it", "query": "In one line, what is ruqu and what hardware do I need?", "wantPaths": ["PRIMER#1-what-is-ruqu", "README.md"], "mustContain": ["quantum", "no quantum hardware", "Rust"], "niceToHave": ["state-vector", "WebAssembly", "browser"] } -{ "stage": 1, "arc": "what-is-it", "query": "Can I run quantum circuits without owning a quantum computer?", "wantPaths": ["PRIMER#1-what-is-ruqu", "README.md"], "mustContain": ["no quantum hardware", "simulator"], "niceToHave": ["laptop", "browser", "state-vector"] } -{ "stage": 1, "arc": "what-is-it", "query": "Why are ruqu's answers exact instead of noisy?", "wantPaths": ["PRIMER#1-what-is-ruqu"], "mustContain": ["exact", "complex amplitudes", "linear algebra"], "niceToHave": ["state-vector", "not", "sampled"] } -{ "stage": 1, "arc": "what-is-it", "query": "Does ruqu need a server or account to run in the browser?", "wantPaths": ["PRIMER#1-what-is-ruqu", "crates/ruqu-wasm/README.md"], "mustContain": ["browser", "no server"], "niceToHave": ["WebAssembly", "no install", "zero dependencies"] } -{ "stage": 2, "arc": "capabilities", "query": "Which quantum algorithms come built in?", "wantPaths": ["PRIMER#2-what-can-ruqu-do-for-you", "crates/ruqu-algorithms/README.md"], "mustContain": ["VQE", "Grover", "QAOA", "Surface Code"], "niceToHave": ["batteries-included", "chemistry", "MaxCut"] } -{ "stage": 2, "arc": "capabilities", "query": "What kind of speedup does Grover give?", "wantPaths": ["PRIMER#2-what-can-ruqu-do-for-you", "crates/ruqu-algorithms/README.md"], "mustContain": ["quadratic speedup", "unstructured search"], "niceToHave": ["amplitude amplification", "oracle", "Grover"] } -{ "stage": 2, "arc": "capabilities", "query": "What does QAOA solve?", "wantPaths": ["PRIMER#2-what-can-ruqu-do-for-you"], "mustContain": ["combinatorial optimization", "MaxCut"], "niceToHave": ["mixing layers", "phase", "approximate"] } -{ "stage": 2, "arc": "capabilities", "query": "Can I export my circuit to a standard format?", "wantPaths": ["PRIMER#2-what-can-ruqu-do-for-you", "crates/ruqu-core/README.md"], "mustContain": ["OpenQASM", "export"], "niceToHave": ["3.0", "standard", "circuit"] } -{ "stage": 2, "arc": "capabilities", "query": "What is ruqu-exotic used for?", "wantPaths": ["PRIMER#2-what-can-ruqu-do-for-you", "crates/ruqu-exotic/README.md"], "mustContain": ["experimental", "AI systems"], "niceToHave": ["interference search", "memory decay", "swarm"] } -{ "stage": 3, "arc": "inventory-components", "query": "List the crates and the CLI in ruqu.", "wantPaths": ["PRIMER#3-what-is-ruqu-made-of-the-five-crates", "README.md"], "mustContain": ["ruqu-core", "ruqu-algorithms", "ruqu-wasm", "ruqu-exotic"], "niceToHave": ["coherence", "five crates", "npx @ruvector/ruqu"] } -{ "stage": 3, "arc": "inventory-components", "query": "Which crate holds the actual simulator engine?", "wantPaths": ["PRIMER#3-what-is-ruqu-made-of-the-five-crates", "crates/ruqu-core/README.md"], "mustContain": ["ruqu-core", "state-vector", "backends"], "niceToHave": ["cost-model planner", "SIMD", "simulator"] } -{ "stage": 3, "arc": "inventory-components", "query": "What does the coherence engine do and how?", "wantPaths": ["PRIMER#3-what-is-ruqu-made-of-the-five-crates", "crates/ruQu/README.md"], "mustContain": ["coherence", "dynamic min-cut"], "niceToHave": ["real time", "nervous system", "ruQu"] } -{ "stage": 3, "arc": "inventory-components", "query": "Besides exact state-vector, what other backends exist?", "wantPaths": ["PRIMER#3-what-is-ruqu-made-of-the-five-crates", "crates/ruqu-core/README.md"], "mustContain": ["Stabilizer", "Clifford+T", "TensorNetwork", "Hardware"], "niceToHave": ["millions", "MPS", "device profiles"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "Show me the steps to build and run a Bell state.", "wantPaths": ["PRIMER#4-how-a-circuit-runs-the-simulation-pipeline", "crates/ruqu-core/README.md"], "mustContain": ["QuantumCircuit", "cnot", "probabilities"], "niceToHave": ["Bell state", "Simulator", "h(0)"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "How does the planner choose a backend automatically?", "wantPaths": ["PRIMER#4-how-a-circuit-runs-the-simulation-pipeline", "crates/ruqu-core/README.md"], "mustContain": ["cost-model planner", "optimal backend"], "niceToHave": ["qubit count", "T-count", "auto-select"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "What makes gate application fast in ruqu?", "wantPaths": ["PRIMER#4-how-a-circuit-runs-the-simulation-pipeline", "crates/ruqu-core/README.md"], "mustContain": ["SIMD", "multi-threading"], "niceToHave": ["AVX2", "NEON", "Rayon"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "How do I run a simulation entirely in JavaScript?", "wantPaths": ["PRIMER#4-how-a-circuit-runs-the-simulation-pipeline", "crates/ruqu-wasm/README.md"], "mustContain": ["Circuit", "Simulator", "measureAll"], "niceToHave": ["init", "ruqu-wasm", "browser"] } -{ "stage": 5, "arc": "maturity", "query": "What are ruqu's honest limits?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["classical simulator", "32 qubits", "25 qubits"], "niceToHave": ["no quantum hardware", "experimental", "memory"] } -{ "stage": 5, "arc": "maturity", "query": "What version are the ruqu crates and the CLI?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits"], "mustContain": ["2.2", "0.2.0"], "niceToHave": ["ruqu-core", "@ruvector/ruqu", "version"] } -{ "stage": 5, "arc": "maturity", "query": "What license is ruqu under?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["MIT"], "niceToHave": ["Ruvector", "ecosystem", "ADR-257"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where is the simulator documented versus the algorithms?", "wantPaths": ["PRIMER#6-where-do-i-read-more-the-docs-map", "README.md"], "mustContain": ["ruqu-core", "ruqu-algorithms", "README"], "niceToHave": ["backends", "VQE", "Grover"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where do I find the browser/WASM guide?", "wantPaths": ["PRIMER#6-where-do-i-read-more-the-docs-map", "crates/ruqu-wasm/README.md"], "mustContain": ["ruqu-wasm", "browser"], "niceToHave": ["25-qubit", "React", "npm"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "Give me the fastest way to see ruqu run.", "wantPaths": ["PRIMER#7-how-do-i-install-and-run-it-end-to-end", "cli/README.md"], "mustContain": ["npx @ruvector/ruqu", "simulate"], "niceToHave": ["capabilities", "grover", "qaoa"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "What do I add to Cargo to use the simulator and algorithms?", "wantPaths": ["PRIMER#7-how-do-i-install-and-run-it-end-to-end", "README.md"], "mustContain": ["cargo add ruqu-core", "ruqu-algorithms"], "niceToHave": ["VQE", "Grover", "QAOA"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "How do I build the WebAssembly bundle myself?", "wantPaths": ["PRIMER#7-how-do-i-install-and-run-it-end-to-end", "README.md"], "mustContain": ["wasm-pack", "ruqu-wasm"], "niceToHave": ["--target web", "npm install", "init"] } diff --git a/kb/questions/ruqu.tuned.jsonl b/kb/questions/ruqu.tuned.jsonl deleted file mode 100644 index 8cc2983..0000000 --- a/kb/questions/ruqu.tuned.jsonl +++ /dev/null @@ -1,28 +0,0 @@ -{ "stage": 1, "arc": "what-is-it", "query": "What is ruqu?", "wantPaths": ["PRIMER#1-what-is-ruqu", "README.md"], "mustContain": ["quantum", "pure Rust", "state-vector", "WebAssembly"], "niceToHave": ["no quantum hardware", "circuit simulator", "in the browser"] } -{ "stage": 1, "arc": "what-is-it", "query": "What does ruqu actually do?", "wantPaths": ["PRIMER#1-what-is-ruqu", "README.md"], "mustContain": ["build and run real quantum circuits", "no quantum hardware"], "niceToHave": ["state-vector", "algorithms", "browser"] } -{ "stage": 1, "arc": "what-is-it", "query": "What is a state-vector simulator?", "wantPaths": ["PRIMER#1-what-is-ruqu"], "mustContain": ["full quantum state", "complex amplitudes", "exact"], "niceToHave": ["32 qubits", "gate", "memory"] } -{ "stage": 1, "arc": "what-is-it", "query": "What does running ruqu in WASM let me do?", "wantPaths": ["PRIMER#1-what-is-ruqu", "README.md"], "mustContain": ["browser", "WebAssembly", "no native addon"], "niceToHave": ["25 qubits", "npx @ruvector/ruqu", "no install"] } -{ "stage": 1, "arc": "what-is-it", "query": "Is ruqu written in Python or Rust?", "wantPaths": ["PRIMER#1-what-is-ruqu", "README.md"], "mustContain": ["pure Rust", "no FFI", "no Python"], "niceToHave": ["wasm32", "memory-safe", "no C++"] } -{ "stage": 2, "arc": "capabilities", "query": "What can ruqu do for me?", "wantPaths": ["PRIMER#2-what-can-ruqu-do-for-you", "crates/ruqu-algorithms/README.md"], "mustContain": ["VQE", "Grover", "QAOA", "Surface Code"], "niceToHave": ["noise", "OpenQASM", "gate set"] } -{ "stage": 2, "arc": "capabilities", "query": "What are VQE, Grover, and QAOA in one line each?", "wantPaths": ["PRIMER#2-what-can-ruqu-do-for-you"], "mustContain": ["ground-state energies", "unstructured search", "combinatorial optimization"], "niceToHave": ["chemistry", "MaxCut", "amplitude amplification"] } -{ "stage": 2, "arc": "capabilities", "query": "What is surface-code error correction here?", "wantPaths": ["PRIMER#2-what-can-ruqu-do-for-you"], "mustContain": ["quantum error correction", "distance-3", "syndrome"], "niceToHave": ["stabilizer", "fault-tolerant", "noise injection"] } -{ "stage": 2, "arc": "capabilities", "query": "What gates and noise models does ruqu support?", "wantPaths": ["PRIMER#2-what-can-ruqu-do-for-you", "crates/ruqu-core/README.md"], "mustContain": ["universal gate set", "depolarizing", "OpenQASM"], "niceToHave": ["CNOT", "Kraus", "mitigation"] } -{ "stage": 2, "arc": "capabilities", "query": "Why would I use ruqu for quantum chemistry?", "wantPaths": ["PRIMER#2-what-can-ruqu-do-for-you", "crates/ruqu-algorithms/README.md"], "mustContain": ["VQE", "molecular Hamiltonians", "ground-state"], "niceToHave": ["ansatz", "chemistry", "energy"] } -{ "stage": 3, "arc": "inventory-components", "query": "What crates make up ruqu?", "wantPaths": ["PRIMER#3-what-is-ruqu-made-of-the-five-crates", "README.md"], "mustContain": ["ruqu-core", "ruqu-algorithms", "ruqu-exotic", "ruqu-wasm", "coherence"], "niceToHave": ["five crates", "workspace", "cli"] } -{ "stage": 3, "arc": "inventory-components", "query": "What does ruqu-core do?", "wantPaths": ["PRIMER#3-what-is-ruqu-made-of-the-five-crates", "crates/ruqu-core/README.md"], "mustContain": ["state-vector", "five simulation backends", "cost-model planner"], "niceToHave": ["SIMD", "StateVector", "Stabilizer"] } -{ "stage": 3, "arc": "inventory-components", "query": "What is the coherence engine?", "wantPaths": ["PRIMER#3-what-is-ruqu-made-of-the-five-crates", "crates/ruQu/README.md"], "mustContain": ["coherence", "dynamic min-cut", "real time"], "niceToHave": ["nervous system", "execution intelligence", "ruQu"] } -{ "stage": 3, "arc": "inventory-components", "query": "What are the five simulation backends?", "wantPaths": ["PRIMER#3-what-is-ruqu-made-of-the-five-crates", "crates/ruqu-core/README.md"], "mustContain": ["StateVector", "Stabilizer", "Clifford+T", "TensorNetwork", "Hardware"], "niceToHave": ["32 qubits", "millions", "MPS"] } -{ "stage": 3, "arc": "inventory-components", "query": "What is ruqu-wasm?", "wantPaths": ["PRIMER#3-what-is-ruqu-made-of-the-five-crates", "crates/ruqu-wasm/README.md"], "mustContain": ["WebAssembly", "browser", "25-qubit"], "niceToHave": ["@ruvector/ruqu-wasm", "JavaScript", "no server"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "How does a quantum circuit run on the simulator?", "wantPaths": ["PRIMER#4-how-a-circuit-runs-the-simulation-pipeline", "crates/ruqu-core/README.md"], "mustContain": ["QuantumCircuit", "Simulator", "probabilities", "backend"], "niceToHave": ["Bell state", "cost-model planner", "gates"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "How does ruqu pick which backend to use?", "wantPaths": ["PRIMER#4-how-a-circuit-runs-the-simulation-pipeline", "crates/ruqu-core/README.md"], "mustContain": ["cost-model planner", "auto-select", "qubit count"], "niceToHave": ["T-count", "gate mix", "StateVector"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "How does ruqu speed up simulation?", "wantPaths": ["PRIMER#4-how-a-circuit-runs-the-simulation-pipeline", "crates/ruqu-core/README.md"], "mustContain": ["SIMD", "multi-threading", "mixed precision"], "niceToHave": ["AVX2", "Rayon", "2-4"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "How do I model noise and then correct for it?", "wantPaths": ["PRIMER#4-how-a-circuit-runs-the-simulation-pipeline", "crates/ruqu-core/README.md"], "mustContain": ["noise", "depolarizing", "error mitigation"], "niceToHave": ["zero-noise extrapolation", "Kraus", "NISQ"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "How do I run a circuit in the browser?", "wantPaths": ["PRIMER#4-how-a-circuit-runs-the-simulation-pipeline", "crates/ruqu-wasm/README.md"], "mustContain": ["Circuit", "Simulator", "measureAll"], "niceToHave": ["ruqu-wasm", "init", "cnot"] } -{ "stage": 5, "arc": "maturity", "query": "Is ruqu production-ready and what are its limits?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["classical simulator", "no quantum hardware", "MIT"], "niceToHave": ["32 qubits", "25", "experimental"] } -{ "stage": 5, "arc": "maturity", "query": "Does ruqu connect to a real quantum computer?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits"], "mustContain": ["classical simulator", "models", "noise"], "niceToHave": ["not", "QPU", "hardware"] } -{ "stage": 5, "arc": "maturity", "query": "How many qubits can ruqu simulate?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "crates/ruqu-wasm/README.md"], "mustContain": ["32 qubits", "25 qubits", "Stabilizer"], "niceToHave": ["browser", "millions", "Clifford"] } -{ "stage": 5, "arc": "maturity", "query": "Is ruqu-exotic real physics or experimental?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "crates/ruqu-exotic/README.md"], "mustContain": ["experimental", "quantum-inspired", "AI systems"], "niceToHave": ["interference search", "memory decay", "not a physics result"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where do I read more about ruqu?", "wantPaths": ["PRIMER#6-where-do-i-read-more-the-docs-map", "README.md"], "mustContain": ["README", "ruqu-core", "ruqu-algorithms"], "niceToHave": ["ruqu-wasm", "cli", "coherence"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where are the CLI commands documented?", "wantPaths": ["PRIMER#6-where-do-i-read-more-the-docs-map", "cli/README.md"], "mustContain": ["cli", "simulate", "doctor"], "niceToHave": ["grover", "qaoa", "capabilities"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "How do I install and run ruqu?", "wantPaths": ["PRIMER#7-how-do-i-install-and-run-it-end-to-end", "README.md", "cli/README.md"], "mustContain": ["cargo add ruqu-core", "npx @ruvector/ruqu", "wasm-pack"], "niceToHave": ["simulate", "ruqu-algorithms", "cargo build"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "How do I run ruqu from my terminal with no install?", "wantPaths": ["PRIMER#7-how-do-i-install-and-run-it-end-to-end", "cli/README.md"], "mustContain": ["npx @ruvector/ruqu", "simulate", "capabilities"], "niceToHave": ["grover", "qaoa", "doctor"] } diff --git a/kb/questions/ruvn.aiq.jsonl b/kb/questions/ruvn.aiq.jsonl deleted file mode 100644 index 7369895..0000000 --- a/kb/questions/ruvn.aiq.jsonl +++ /dev/null @@ -1,25 +0,0 @@ -// ruvn.aiq.jsonl — AI-comprehension question battery (dimensions 1-6 + 8; dim-7 deep-dive is -// generated at runtime from random buried files). Facts verified against .targets/ruvn 2026-06-19 -// (README.md, CLAUDE.md, package.json, bin/cli.js, src/agents/*.ts, src/init.ts, -// scripts/openrouter-validate.mjs, __tests__/*). mustContain = anchors used only by the --dry proxy. -{ "dimension": "onboarding", "query": "I just got this repo. How do I install, run, and test ruvn from scratch, including running it with no install? Give me the exact commands.", "mustContain": ["npm i -g @ruvnet/ruvn", "ruvn init", "ruvn doctor", "npx @ruvnet/ruvn", "npm test"] } -{ "dimension": "onboarding", "query": "What is the fastest way to see ruvn actually do something, and what does `ruvn doctor` check?", "mustContain": ["ruvn doctor", "ruvn init", "kernel", "host adapter"] } -{ "dimension": "onboarding", "query": "How do I validate ruvn end-to-end against a real model, and what env var do I need?", "mustContain": ["validate:openrouter", "OPENROUTER_API_KEY", "agents"] } -{ "dimension": "what-it-is", "query": "What is ruvn and what specific problem does it solve for me?", "mustContain": ["research", "graded", "cited", "dossier", "evidence"] } -{ "dimension": "what-it-is", "query": "Why would I use ruvn instead of just asking an AI a research question directly? What does it give me back?", "mustContain": ["grades every source", "cited", "dossier", "bibliography"] } -{ "dimension": "what-it-is", "query": "What does a 'graded, cited evidence dossier' mean in ruvn, and what is ruvn explicitly NOT?", "mustContain": ["TL;DR", "bibliography", "not", "medical advice"] } -{ "dimension": "architecture", "query": "What are the six agents in ruvn, in what order do they run, and how does information flow between them?", "mustContain": ["scout", "web-searcher", "source-grader", "synthesizer", "fact-checker", "citer"] } -{ "dimension": "architecture", "query": "What does ruvn depend on (kernel, hosts), and how is the package structured? Which hosts does it support?", "mustContain": ["@metaharness/kernel", "host", "9 hosts"] } -{ "dimension": "architecture", "query": "What does it mean that 'each agent only sees the previous agent's output', and why is the pipeline built that way?", "mustContain": ["previous agent", "grading", "verification", "gates"] } -{ "dimension": "capabilities", "query": "What can ruvn do? List the pipeline stages and what each agent produces.", "mustContain": ["scout", "source-grader", "synthesizer", "fact-checker", "citer", "A/B/C/D"] } -{ "dimension": "capabilities", "query": "How does ruvn grade sources — what do grades A, B, C, and D mean, and which grades is the synthesizer allowed to use?", "mustContain": ["primary source", "tertiary", "discard", "grade A and B"] } -{ "dimension": "capabilities", "query": "Which CLI commands does ruvn expose and what does each do?", "mustContain": ["init", "doctor", "--version", "--help"] } -{ "dimension": "usage", "query": "Show me how to actually run a research question through ruvn end-to-end and what I get back. What is the real workflow?", "mustContain": ["ruvn init", "Claude Code", "pipeline", "dossier"] } -{ "dimension": "usage", "query": "What does each agent's SYSTEM_PROMPT instruct it to do, and what model tier runs each one?", "mustContain": ["SYSTEM_PROMPT", "TIER", "sonnet", "haiku"] } -{ "dimension": "usage", "query": "How do I drive the CLI from code? What is the signature of the dispatcher and how do the tests call it?", "mustContain": ["run", "argv", "doctor", "exit code"] } -{ "dimension": "best-practices", "query": "Is ruvn production-ready? What are its honest limits and scope?", "mustContain": ["research tool", "not", "medical advice", "starting dossier"] } -{ "dimension": "best-practices", "query": "What are the gotchas around cost and latency when running ruvn, and where does the web search actually happen?", "mustContain": ["six", "model", "WebSearch", "host"] } -{ "dimension": "best-practices", "query": "Why might my ruvn dossier come back empty or thin, and is that a bug?", "mustContain": ["grade A", "B", "only", "by design"] } -{ "dimension": "extensibility", "query": "How do I add a new research agent to ruvn? What file does it go in, what does it export, and how do I keep the pipeline working?", "mustContain": ["src/agents", "SYSTEM_PROMPT", "NAME", "TIER", "pipeline"] } -{ "dimension": "extensibility", "query": "Where is the A/B/C/D grading rubric defined and how do I safely change it without breaking ruvn's trust guarantee?", "mustContain": ["source-grader", "synthesizer", "grade A and B", "CLAUDE.md"] } -{ "dimension": "extensibility", "query": "How do I change which model tier an agent uses, and how do I add a new CLI subcommand or a new host?", "mustContain": ["TIER", "TIER_MODEL", "bin/cli.js", "package.json"] } diff --git a/kb/questions/ruvn.heldout.jsonl b/kb/questions/ruvn.heldout.jsonl deleted file mode 100644 index 577a4d8..0000000 --- a/kb/questions/ruvn.heldout.jsonl +++ /dev/null @@ -1,27 +0,0 @@ -{ "stage": 1, "arc": "what-is-it", "query": "In one sentence, what does ruvn turn a question into?", "wantPaths": ["PRIMER#1-what-is-ruvn", "README.md"], "mustContain": ["graded, cited evidence dossier", "research"], "niceToHave": ["every claim is cited", "harness"] } -{ "stage": 1, "arc": "what-is-it", "query": "Why should I trust ruvn's output more than a normal AI answer?", "wantPaths": ["PRIMER#6-where-do-i-read-more-the-docs-map", "README.md", "PRIMER#2-what-can-ruvn-do-for-you", "PRIMER#1-what-is-ruvn"], "mustContain": ["grades every source", "every claim is cited"], "niceToHave": ["receipts", "starting dossier", "defend"] } -{ "stage": 1, "arc": "what-is-it", "query": "What was ruvn originally built for?", "wantPaths": ["PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", "README.md", "PRIMER#1-what-is-ruvn"], "mustContain": ["ruv-neural", "40 hz", "research question"], "niceToHave": ["gamma", "modalities", "safety"] } -{ "stage": 1, "arc": "what-is-it", "query": "Does ruvn run on its own or inside a tool I already use?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "PRIMER#7-how-do-i-install-and-use-it-end-to-end", "README.md", "PRIMER#1-what-is-ruvn"], "mustContain": ["AI host", "harness"], "niceToHave": ["Claude Code", "Codex", "Copilot", "no model of its own"] } -{ "stage": 2, "arc": "capabilities", "query": "What is the value of ruvn in one line?", "wantPaths": ["PRIMER#1-what-is-ruvn", "PRIMER#2-what-can-ruvn-do-for-you", "README.md"], "mustContain": ["graded", "cited", "dossier"], "niceToHave": ["defensible", "before", "after"] } -{ "stage": 2, "arc": "capabilities", "query": "How does the grader rank a primary research paper versus a forum post?", "wantPaths": ["PRIMER#4-how-the-pipeline-works-step-by-step", "CLAUDE.md", "src/agents/source-grader.ts", "README.md"], "mustContain": ["primary source", "discarded", "forum"], "niceToHave": ["paper", "on-topic", "unsourced"] } -{ "stage": 2, "arc": "capabilities", "query": "Can I run ruvn end-to-end against a live model?", "wantPaths": ["PRIMER#7-how-do-i-install-and-use-it-end-to-end", "PRIMER#2-what-can-ruvn-do-for-you", "README.md"], "mustContain": ["openrouter", "validate:openrouter"], "niceToHave": ["npm test", "live model", "end-to-end"] } -{ "stage": 2, "arc": "capabilities", "query": "Which grades is the synthesizer allowed to use?", "wantPaths": ["PRIMER#2-what-can-ruvn-do-for-you", "README.md"], "mustContain": ["only allowed to use a and b", "synthesizer"], "niceToHave": ["grade a", "grade b", "the whole point"] } -{ "stage": 3, "arc": "inventory-components", "query": "List the agents in the ruvn pipeline in order.", "wantPaths": ["PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", "CLAUDE.md", "README.md"], "mustContain": ["scout", "web-searcher", "source-grader", "synthesizer", "fact-checker", "citer"], "niceToHave": ["six agents", "pipeline", "in a line"] } -{ "stage": 3, "arc": "inventory-components", "query": "Which model tier does each ruvn agent run on?", "wantPaths": ["PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", "CLAUDE.md"], "mustContain": ["sonnet", "haiku", "web-searcher"], "niceToHave": ["tier", "scout", "citer"] } -{ "stage": 3, "arc": "inventory-components", "query": "What files ship for the Claude Code host?", "wantPaths": ["PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", "README.md"], "mustContain": [".claude/settings.json", ".claude-plugin/plugin.json"], "niceToHave": ["host", "config", "Claude Code"] } -{ "stage": 3, "arc": "inventory-components", "query": "Who generated ruvn and from what template?", "wantPaths": ["PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", "README.md"], "mustContain": ["metaharness", "vertical:research"], "niceToHave": ["generated", "extended", "nine hosts"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "What is the order of operations from question to dossier?", "wantPaths": ["PRIMER#4-how-the-pipeline-works-step-by-step", "README.md", "CLAUDE.md"], "mustContain": ["scout", "source-grader", "synthesizer", "citer"], "niceToHave": ["subqueries", "grade", "bibliography"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "What does the scout produce first?", "wantPaths": ["PRIMER#1-what-is-ruvn", "PRIMER#4-how-the-pipeline-works-step-by-step", "README.md"], "mustContain": ["scout", "subqueries"], "niceToHave": ["standalone", "non-overlapping", "3", "7"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "What does the citer add and what does it refuse to ship?", "wantPaths": ["PRIMER#4-how-the-pipeline-works-step-by-step", "README.md"], "mustContain": ["every claim must cite", "no claim", "receipt"], "niceToHave": ["inline citation", "bibliography", "graded source"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "What is grade A versus grade C in the rubric?", "wantPaths": ["src/agents/source-grader.ts", "PRIMER#4-how-the-pipeline-works-step-by-step", "CLAUDE.md", "README.md"], "mustContain": ["primary source", "tertiary"], "niceToHave": ["on-topic", "wikipedia", "context only"] } -{ "stage": 5, "arc": "maturity", "query": "What version is ruvn at?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["v0.1.1"], "niceToHave": ["early", "research", "limits"] } -{ "stage": 5, "arc": "maturity", "query": "Should I treat ruvn's dossier as a final answer?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["starting dossier", "verify", "not a conclusion"], "niceToHave": ["research", "scope", "efficacy"] } -{ "stage": 5, "arc": "maturity", "query": "Is the OpenRouter validation required to use ruvn?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["opt-in", "skipped", "openrouter_api_key"], "niceToHave": ["offline", "npm test", "key"] } -{ "stage": 5, "arc": "maturity", "query": "What does ruvn depend on to do the actual searching and grading?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["harness", "live model", "discipline"], "niceToHave": ["host", "pipeline", "rubric"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Which doc should I start with for ruvn?", "wantPaths": ["PRIMER#6-where-do-i-read-more-the-docs-map", "README.md"], "mustContain": ["readme.md", "start here"], "niceToHave": ["pitch", "agent table", "rubric"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where is the operating contract for the model running the harness?", "wantPaths": ["PRIMER#1-what-is-ruvn", "PRIMER#6-where-do-i-read-more-the-docs-map", "README.md", "CLAUDE.md"], "mustContain": ["harness", "pipeline"], "niceToHave": ["claude.md", "rubric", "dossier", "agents"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where do I read about ruv-neural and metaharness?", "wantPaths": ["PRIMER#6-where-do-i-read-more-the-docs-map", "README.md"], "mustContain": ["ruv-neural", "metaharness"], "niceToHave": ["upstream", "gamma", "factory"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Which npm package and commands does ruvn ship?", "wantPaths": ["PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", "PRIMER#7-how-do-i-install-and-use-it-end-to-end", "README.md"], "mustContain": ["@ruvnet/ruvn", "ruvn init"], "niceToHave": ["ruvn doctor", "single npm package", "npx"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "Give me the fastest way to install ruvn into Claude Code.", "wantPaths": ["PRIMER#7-how-do-i-install-and-use-it-end-to-end", "README.md"], "mustContain": ["npm i -g @ruvnet/ruvn", "ruvn init", "ruvn doctor"], "niceToHave": ["Claude Code", "plugin", "settings"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "What is the no-install one-liner for ruvn?", "wantPaths": ["PRIMER#7-how-do-i-install-and-use-it-end-to-end", "README.md"], "mustContain": ["npx @ruvnet/ruvn"], "niceToHave": ["no install", "init", "one-off"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "After installing, how do I actually run a research pipeline?", "wantPaths": ["PRIMER#4-how-the-pipeline-works-step-by-step", "PRIMER#7-how-do-i-install-and-use-it-end-to-end", "README.md"], "mustContain": ["research pipeline", "claude code"], "niceToHave": ["agents", "rubric", "ask"] } diff --git a/kb/questions/ruvn.tuned.jsonl b/kb/questions/ruvn.tuned.jsonl deleted file mode 100644 index 16cb6bb..0000000 --- a/kb/questions/ruvn.tuned.jsonl +++ /dev/null @@ -1,28 +0,0 @@ -{ "stage": 1, "arc": "what-is-it", "query": "What is ruvn?", "wantPaths": ["PRIMER#1-what-is-ruvn", "README.md", "CLAUDE.md"], "mustContain": ["graded, cited evidence dossier", "research agent", "every claim is cited"], "niceToHave": ["harness", "grades every source", "ruv-neural"] } -{ "stage": 1, "arc": "what-is-it", "query": "What is an evidence dossier and what does ruvn give me back?", "wantPaths": ["PRIMER#1-what-is-ruvn", "README.md"], "mustContain": ["dossier", "every claim is cited", "bibliography"], "niceToHave": ["TL;DR", "letter grade", "Markdown"] } -{ "stage": 1, "arc": "what-is-it", "query": "What does graded and cited mean in ruvn?", "wantPaths": ["PRIMER#1-what-is-ruvn", "README.md"], "mustContain": ["grades every source", "every claim is cited", "A/B/C/D"], "niceToHave": ["starting dossier", "receipts", "trust"] } -{ "stage": 1, "arc": "what-is-it", "query": "Is ruvn a model or a harness, and is it a hosted service?", "wantPaths": ["PRIMER#1-what-is-ruvn", "README.md"], "mustContain": ["harness", "not a hosted service", "AI coding host"], "niceToHave": ["Claude Code", "your own model", "drop them into"] } -{ "stage": 2, "arc": "capabilities", "query": "What can ruvn do for me?", "wantPaths": ["PRIMER#2-what-can-ruvn-do-for-you", "README.md"], "mustContain": ["grades every source", "adversarially fact-checks", "bibliography"], "niceToHave": ["defensible research artifact", "synthesizer", "graded source"] } -{ "stage": 2, "arc": "capabilities", "query": "How does ruvn decide which sources to trust?", "wantPaths": ["PRIMER#2-what-can-ruvn-do-for-you", "README.md"], "mustContain": ["primary source", "reputable secondary", "discarded"], "niceToHave": ["authority", "freshness", "relevance"] } -{ "stage": 2, "arc": "capabilities", "query": "What does ruvn do differently from a plain AI that blends sources into one answer?", "wantPaths": ["README.md", "PRIMER#2-what-can-ruvn-do-for-you"], "mustContain": ["blends good and bad", "refuses", "only allowed to use"], "niceToHave": ["confident", "grades every source", "the whole point"] } -{ "stage": 2, "arc": "capabilities", "query": "What is in the final dossier ruvn produces?", "wantPaths": ["PRIMER#2-what-can-ruvn-do-for-you", "README.md", "CLAUDE.md"], "mustContain": ["tl;dr", "every claim", "bibliography with"], "niceToHave": ["inline citation", "grade tags", "markdown"] } -{ "stage": 3, "arc": "inventory-components", "query": "What are the six agents and the nine hosts in ruvn?", "wantPaths": ["PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", "README.md", "CLAUDE.md"], "mustContain": ["scout", "web-searcher", "source-grader", "synthesizer", "fact-checker", "citer", "nine hosts"], "niceToHave": ["Claude Code", "Codex", "Copilot"] } -{ "stage": 3, "arc": "inventory-components", "query": "What are the nine hosts ruvn supports?", "wantPaths": ["PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", "README.md"], "mustContain": ["claude code", "codex", "copilot", "opencode", "github actions", "pi-dev", "hermes", "openclaw", "rvm"], "niceToHave": ["adapters", "config", "host"] } -{ "stage": 3, "arc": "inventory-components", "query": "What is the role of each agent in the ruvn pipeline?", "wantPaths": ["README.md", "PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", "CLAUDE.md"], "mustContain": ["scout", "source-grader", "synthesizer", "fact-checker", "citer"], "niceToHave": ["sonnet", "haiku", "decompose"] } -{ "stage": 3, "arc": "inventory-components", "query": "Is ruvn a monorepo or one npm package, and what is the metaharness kernel?", "wantPaths": ["PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", "README.md"], "mustContain": ["@metaharness/kernel", "no model calls", "your host provides the model"], "niceToHave": ["orchestration", "memory", "trajectory"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "How does the ruvn pipeline work, with each agent only seeing the previous output?", "wantPaths": ["CLAUDE.md", "PRIMER#4-how-the-pipeline-works-step-by-step", "README.md"], "mustContain": ["only sees the output", "grading", "verification gates"], "niceToHave": ["a/b/c/d", "pipeline", "scout"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "Why does each agent only see the previous agent's output?", "wantPaths": ["PRIMER#4-how-the-pipeline-works-step-by-step", "CLAUDE.md"], "mustContain": ["only sees the output", "grading", "verification gates"], "niceToHave": ["forces", "flow", "previous"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "How does ruvn adversarially fact-check claims before they reach me?", "wantPaths": ["README.md", "PRIMER#4-how-the-pipeline-works-step-by-step", "CLAUDE.md"], "mustContain": ["adversarially", "fact-check", "claim"], "niceToHave": ["unsupported", "verify", "grade a"] } -{ "stage": 4, "arc": "how-it-works-pipeline", "query": "What is the A B C D grading rubric and which grades reach the synthesis?", "wantPaths": ["PRIMER#4-how-the-pipeline-works-step-by-step", "README.md", "CLAUDE.md"], "mustContain": ["primary source", "reputable secondary", "tertiary", "discarded", "grade a and b"], "niceToHave": ["on-topic", "context only", "dead link"] } -{ "stage": 5, "arc": "maturity", "query": "Is ruvn production-ready and what are its limits?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["v0.1.1", "research", "does not give medical advice", "starting dossier"], "niceToHave": ["scope", "verify", "not a conclusion"] } -{ "stage": 5, "arc": "maturity", "query": "Does ruvn give medical advice?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["does not give medical advice", "research", "starting dossier to verify"], "niceToHave": ["efficacy", "conclusion", "gamma"] } -{ "stage": 5, "arc": "maturity", "query": "What is ruvn not?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["not a chatbot", "not a hosted service", "research tool"], "niceToHave": ["medical device", "harness", "discipline"] } -{ "stage": 5, "arc": "maturity", "query": "Where does ruvn's intelligence actually come from?", "wantPaths": ["PRIMER#5-is-it-production-ready-scope-and-honest-limits", "README.md"], "mustContain": ["harness", "live model", "discipline"], "niceToHave": ["metaharness", "host", "pipeline"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where do I read more about ruvn?", "wantPaths": ["PRIMER#6-where-do-i-read-more-the-docs-map", "README.md", "install.md"], "mustContain": ["readme.md", "claude.md", "install.md"], "niceToHave": ["src/agents", "ruv-neural", "metaharness"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Which file has the pipeline diagram and the grading rubric?", "wantPaths": ["CLAUDE.md", "PRIMER#4-how-the-pipeline-works-step-by-step", "PRIMER#6-where-do-i-read-more-the-docs-map"], "mustContain": ["claude.md", "pipeline", "rubric"], "niceToHave": ["agents", "tiers", "dossier"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "Where is the per-host install documented?", "wantPaths": ["PRIMER#6-where-do-i-read-more-the-docs-map", "install.md", "README.md"], "mustContain": ["install.md", "per-host", "host"], "niceToHave": ["copilot", "mcp", "steps"] } -{ "stage": 6, "arc": "docs-where-things-live", "query": "In which directory is each ruvn agent's behavior defined?", "wantPaths": ["PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", "PRIMER#6-where-do-i-read-more-the-docs-map", "README.md"], "mustContain": ["src/agents"], "niceToHave": ["source of truth", "behavior", "tweak", "system prompt"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "How do I install and use ruvn?", "wantPaths": ["PRIMER#7-how-do-i-install-and-use-it-end-to-end", "README.md"], "mustContain": ["npm i -g @ruvnet/ruvn", "ruvn init", "ruvn doctor", "validate:openrouter"], "niceToHave": ["npx", "claude code", "health check"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "How do I validate ruvn against a real model with OpenRouter?", "wantPaths": ["PRIMER#2-what-can-ruvn-do-for-you", "PRIMER#7-how-do-i-install-and-use-it-end-to-end", "README.md"], "mustContain": ["openrouter", "validate:openrouter"], "niceToHave": ["sonnet", "haiku", "npm test", "live model"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "What does ruvn init do and what does ruvn doctor check?", "wantPaths": ["PRIMER#7-how-do-i-install-and-use-it-end-to-end", "README.md"], "mustContain": ["ruvn init", "ruvn doctor", "kernel"], "niceToHave": ["host adapter", "pass", "backend"] } -{ "stage": 7, "arc": "end-to-end-usage", "query": "How do I install ruvn without a global install, and do I run build first?", "wantPaths": ["PRIMER#7-how-do-i-install-and-use-it-end-to-end", "README.md"], "mustContain": ["npx @ruvnet/ruvn", "npm i -g @ruvnet/ruvn", "npm run build"], "niceToHave": ["no build step", "no install", "tsc"] } diff --git a/kb/resolve-deps.mjs b/kb/resolve-deps.mjs index ed67ccb..05db0ca 100644 --- a/kb/resolve-deps.mjs +++ b/kb/resolve-deps.mjs @@ -1,16 +1,14 @@ -// resolve-deps.mjs — portable resolver for the Cognitum KB scripts. -// -// Resolves the two runtime deps the KB needs in a machine-independent order: +// resolve-deps.mjs — portable resolver for the KB scripts. // +// Resolves the two runtime deps the KB needs: // @ruvector/rvf -> RvfDatabase (the .rvf vector store) -// @xenova/transformers -> the MiniLM embedder +// @xenova/transformers -> the embedder // // Resolution order (first hit wins) for EACH dep: // 1. The project's own node_modules (so `cd kb && npm i` or a root install just works). -// 2. An explicit env override (RVF_MODULE_PATH / XENOVA_PATH). -// 3. The author's Mac npm-global / AppealArmor paths (LAST resort, so local dev still runs). +// 2. An explicit env override (RVF_MODULE_PATH / XENOVA_PATH). // -// This file ships INSIDE the zips, so it must not assume anything beyond Node 18+ and the +// This file ships INSIDE knowledge packs, so it must not assume anything beyond Node 18+ and the // two npm deps being installable via `npm i @ruvector/rvf @xenova/transformers`. import { createRequire } from 'node:module'; @@ -27,8 +25,7 @@ const localRequire = createRequire(__filename); // @ruvector/rvf and @xenova/transformers are declared dependencies, so they resolve from // node_modules (step 1) on any machine after `npm install`. The env overrides remain for -// non-standard layouts. (No machine-specific fallback paths — those don't belong in a -// published package.) +// non-standard layouts. function existsModuleDir(p) { // p may be a package root dir OR a file path; treat presence as resolvable. @@ -37,7 +34,7 @@ function existsModuleDir(p) { /** * Resolve and return the @ruvector/rvf module ({ RvfDatabase, ... }). - * Order: project node_modules -> RVF_MODULE_PATH env -> Mac npm-global. + * Order: project node_modules -> RVF_MODULE_PATH env. */ export function loadRvf() { // 1. project node_modules (kb/ or root) @@ -68,7 +65,7 @@ export function loadRvf() { /** * Resolve and dynamically import @xenova/transformers. - * Order: project node_modules -> XENOVA_PATH env -> Mac AppealArmor build. + * Order: project node_modules -> XENOVA_PATH env. * Returns { T, modelCache, via } where T is the imported module namespace. */ export async function loadTransformers() { @@ -103,24 +100,16 @@ export async function loadTransformers() { } /** - * Pick a model cache directory. KB_MODEL_CACHE wins; otherwise a kb-local `models-cache` - * if it already has the model; otherwise the Mac cache if present; otherwise a kb-local - * dir (created lazily) into which a remote download will be cached. - * `modelName` lets the big (bge) variant resolve its cache by its own model, not just MiniLM; - * defaults to MiniLM-384 so existing small-build callers are unchanged. + * Pick a model cache directory: KB_MODEL_CACHE wins, otherwise a kb-local `models-cache` + * (a remote download lands there on first run). */ -export function chooseModelCache(modelName = 'Xenova/all-MiniLM-L6-v2') { - if (process.env.KB_MODEL_CACHE) return process.env.KB_MODEL_CACHE; - const kbLocal = path.join(KB_DIR, 'models-cache'); - if (fs.existsSync(path.join(kbLocal, modelName))) return kbLocal; - return kbLocal; // remote download lands here on first run +export function chooseModelCache() { + return process.env.KB_MODEL_CACHE || path.join(KB_DIR, 'models-cache'); } /** * Configure a transformers namespace `T` for a given model: point at the cache, and allow * remote download ONLY when THAT model isn't already cached (offline-first). - * `modelName` defaults to the MiniLM-384 embedder so existing callers keep working; the big - * variant passes `'Xenova/bge-base-en-v1.5'` so its own cache check is correct. * Returns { modelCache, haveLocalModel }. */ export function configureModel(T, modelCache, modelName = 'Xenova/all-MiniLM-L6-v2') { diff --git a/kb/store-set.mjs b/kb/store-set.mjs index 2df74b2..f8f1462 100644 --- a/kb/store-set.mjs +++ b/kb/store-set.mjs @@ -9,10 +9,19 @@ import fs from 'node:fs'; import path from 'node:path'; import readline from 'node:readline'; +import { fileURLToPath } from 'node:url'; + +const KB_DIR = path.dirname(fileURLToPath(import.meta.url)); export const SYNTHETIC_PATH_RE = /^PRIMER#/; // the documented "synthetic, preserve on delta" marker const LOCK_STALE_MS = 60 * 60 * 1000; // 1 h — a builder that old is presumed dead +// Directory holding a slug's StoreSet: kb/stores// (KB_STORE_DIR overrides, so tests and +// staging never touch real stores). One rule shared by build-kb.mjs and index-primer.mjs. +export function storeDirFor(slug) { + return process.env.KB_STORE_DIR ? path.resolve(process.env.KB_STORE_DIR) : path.join(KB_DIR, 'stores', slug); +} + // ---------- StoreSet lock ---------- // Exclusive-create lockfile next to the store. Both builders take it BEFORE reading any state. export function acquireLock(baseNoExt) { @@ -63,13 +72,7 @@ export function readIdsIndex(file) { return { header: { model: j.model, dimensions: j.dimensions, metric: j.metric, maxIdEver: j.maxIdEver }, entries: j.entries || {} }; } -// ---------- atomic write + staged publish ---------- -export function writeFileAtomic(filePath, content) { - const tmp = `${filePath}.tmp-${process.pid}`; - fs.writeFileSync(tmp, content); - fs.renameSync(tmp, filePath); -} - +// ---------- staged publish ---------- // Clone a file for staging. COPYFILE_FICLONE is instant (CoW) on APFS and silently falls // back to a real copy elsewhere. export function cloneFile(src, dst) { diff --git a/kb/stores/StrongHold/StrongHold-dep-graph.json b/kb/stores/StrongHold/StrongHold-dep-graph.json deleted file mode 100644 index a0bafec..0000000 --- a/kb/stores/StrongHold/StrongHold-dep-graph.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "target": "StrongHold", - "metaName": "StrongHold", - "generated": "2026-07-01T02:41:58.027Z", - "ecosystems": [ - "npm" - ], - "componentCount": 1, - "internalEdgeCount": 0, - "externalDepCount": 4, - "nodes": [ - { - "name": "agenticow-ruflo-memory", - "version": "0.1.0", - "description": "Per-agent COW memory for ruflo-style multi-agent workflows, backed by agenticow + local all-MiniLM-L6-v2 embeddings.", - "manifest": "package.json", - "deps": [ - "@anthropic-ai/sdk", - "@huggingface/transformers", - "agenticow", - "fastify" - ], - "ecosystem": "npm" - } - ], - "internalEdges": [], - "externalDeps": { - "agenticow-ruflo-memory": [ - { - "name": "@anthropic-ai/sdk", - "req": "*", - "kind": "normal" - }, - { - "name": "@huggingface/transformers", - "req": "*", - "kind": "normal" - }, - { - "name": "agenticow", - "req": "*", - "kind": "normal" - }, - { - "name": "fastify", - "req": "*", - "kind": "normal" - } - ] - }, - "externalDepNames": [ - "@anthropic-ai/sdk", - "@huggingface/transformers", - "agenticow", - "fastify" - ] -} diff --git a/kb/stores/StrongHold/StrongHold-entrypoints.json b/kb/stores/StrongHold/StrongHold-entrypoints.json deleted file mode 100644 index feb39f7..0000000 --- a/kb/stores/StrongHold/StrongHold-entrypoints.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "target": "StrongHold", - "metaName": "StrongHold", - "generated": "2026-07-01T02:41:58.079Z", - "workspace": { - "kind": "npm", - "members": [] - }, - "components": [ - { - "name": "agenticow-ruflo-memory", - "path": "", - "kind": "package", - "description": "Per-agent COW memory for ruflo-style multi-agent workflows, backed by agenticow + local all-MiniLM-L6-v2 embeddings.", - "scripts": { - "demo": "node demo.js", - "start": "node service/server.js" - }, - "bins": [], - "deps": [ - "@anthropic-ai/sdk", - "@huggingface/transformers", - "agenticow", - "fastify" - ] - } - ], - "binaries": [], - "commands": [ - { - "cmd": "npm run demo", - "raw": "node demo.js", - "category": "other", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run start", - "raw": "node service/server.js", - "category": "run", - "source": "package.json", - "note": null - }, - { - "cmd": "node service/mint-stronghold-token.mjs --url http://localhost:8771 --agent-type researcher", - "category": "other", - "source": "docs/DEVELOPER_QUICKSTART.md", - "note": null - }, - { - "cmd": "node scripts/mint-token.js --sub colleague-name", - "category": "other", - "source": "docs/OPS_RUNBOOK.md", - "note": "prints a Bearer JWT" - }, - { - "cmd": "docker ps -a --filter name=agentmem-sbx", - "category": "other", - "source": "docs/OPS_RUNBOOK.md", - "note": "rootful: none (GOOD)" - } - ], - "install": [], - "quickstart": [ - "npm run start" - ] -} diff --git a/kb/stores/StrongHold/StrongHold-kb.ids.json b/kb/stores/StrongHold/StrongHold-kb.ids.json deleted file mode 100644 index d7ef140..0000000 --- a/kb/stores/StrongHold/StrongHold-kb.ids.json +++ /dev/null @@ -1 +0,0 @@ -{"model":"Xenova/bge-small-en-v1.5","dimensions":384,"metric":"cosine","entries":{"1":{"path":"backend/LOVABLE.md","kind":"doc","source_type":"doc","title":"Calling StrongHold from Lovable","chunk":1,"of":10,"preview":"# Calling StrongHold from Lovable **StrongHold** is a sovereign, memory-centric AI-agent harness served as an API (\"Harness as a Service\") — same capabilities as a cloud AI-agent service, but it runs entirely on the owner's own hardware (t"},"2":{"path":"backend/LOVABLE.md","kind":"doc","source_type":"doc","title":"Calling StrongHold from Lovable","chunk":2,"of":10,"preview":"## Endpoints | Method | Path | Body | Returns | |--------|------|------|---------| | GET | `/health` | — | `{status, baseVectors, internal}` (no auth) | | GET | `/agents` | — | `Agent[]` (caller's agents) | | POST | `/agents` | `{agentTy"},"3":{"path":"backend/LOVABLE.md","kind":"doc","source_type":"doc","title":"Calling StrongHold from Lovable","chunk":3,"of":10,"preview":"### `/fanout` — sub-agent fan-out Up to 8 ephemeral workers run `tasks[]` in parallel, results are aggregated, then the workers are dismissed (no graduation). `tasks` can be plain strings or per-task objects `{prompt, tools?, profile?}`, s"},"4":{"path":"backend/LOVABLE.md","kind":"doc","source_type":"doc","title":"Calling StrongHold from Lovable","chunk":4,"of":10,"preview":"## Picking quality vs. speed — the `tier` knob (optional) You never name a model. Add an optional `tier` to `chat` / `act` / `fanout`; omit it and you get smart defaults. Every response reports the `provider` (`local` / `cloud` / `openrout"},"5":{"path":"backend/LOVABLE.md","kind":"doc","source_type":"doc","title":"Calling StrongHold from Lovable","chunk":5,"of":10,"preview":"## Choosing tools per task — the `profile` / `tools` knob (act + fanout) By default an agent can use **all** tools. To scope what the model is allowed to touch on a given `/act` (or `/fanout`) call, pass either a named `profile` **or** an "},"6":{"path":"backend/LOVABLE.md","kind":"doc","source_type":"doc","title":"Calling StrongHold from Lovable","chunk":6,"of":10,"preview":"## Drop-in client (`src/lib/agentMemory.ts`) ```ts const BASE = \"https://spark-47d8.tail333a1d.ts.net/agentmem/v1\"; // Prototype: paste the test token. Production: return the Supabase access token. const getToken = () => \" api(\"/agents\"), spawn: (agentType: string, label?: string) => api(\"/agents\", { method: \"POST\", body: JSON.stringify({ agentType, label }) }), remember: (id: string, text: string | str"},"8":{"path":"backend/LOVABLE.md","kind":"doc","source_type":"doc","title":"Calling StrongHold from Lovable","chunk":8,"of":10,"preview":"## Rate limits Each tenant gets a token bucket (burst capacity ~30, refill ~1/sec). Heavy ops — `act`, `fanout`, `chat`, `sandbox/run` — cost ~5 each, and there's a global cap on simultaneous heavy jobs. When you exceed it the API returns "},"9":{"path":"backend/LOVABLE.md","kind":"doc","source_type":"doc","title":"Calling StrongHold from Lovable","chunk":9,"of":10,"preview":"## Production auth (per-user, via Supabase) — ALREADY WIRED, zero config The backend already verifies real Supabase user tokens for **any** of your projects — past, present, or future — with no per-project setup. It detects the token's sig"},"10":{"path":"backend/LOVABLE.md","kind":"doc","source_type":"doc","title":"Calling StrongHold from Lovable","chunk":10,"of":10,"preview":"### Locked to your projects (active) The API is restricted to an allowlist of Supabase project refs (`SUPABASE_ALLOWED_REFS` in `backend/.env`). It **fails closed**: with no allowlist set, asymmetric tokens are rejected unless `SUPABASE_AL"},"11":{"path":"docs/adr/0001-two-tier-topology.md","kind":"adr","source_type":"doc","title":"ADR-0001: Two-tier topology — internal harness + public backend","chunk":1,"of":2,"preview":"# ADR-0001: Two-tier topology — internal harness + public backend - **Status:** Accepted - **Date:** 2026-06-29 ## Context StrongHold exposes an LLM harness (memory, agentic loop, sandbox, MCP tools) to a customer-facing app (Lovable) ov"},"12":{"path":"docs/adr/0001-two-tier-topology.md","kind":"adr","source_type":"doc","title":"ADR-0001: Two-tier topology — internal harness + public backend","chunk":2,"of":2,"preview":"## Consequences - **Positive:** the internet-facing surface is tiny and dependency-free (small image, nothing to `npm audit`); secrets never live at the edge; the public API contract (`openapi.yaml`) is decoupled from the internal impl"},"13":{"path":"docs/adr/0002-durable-log-source-of-truth.md","kind":"adr","source_type":"doc","title":"ADR-0002: Append-only durable log is the source of truth","chunk":1,"of":2,"preview":"# ADR-0002: Append-only durable log is the source of truth - **Status:** Accepted - **Date:** 2026-06-29 ## Context Memory is built on **agenticow** (copy-on-write vector branching — \"Git for agent memory\"). Its persistence (`*.rvf` + ma"},"14":{"path":"docs/adr/0002-durable-log-source-of-truth.md","kind":"adr","source_type":"doc","title":"ADR-0002: Append-only durable log is the source of truth","chunk":2,"of":2,"preview":"## Consequences - **Positive:** memory (with text) survives restarts/reboots deterministically; embeddings are local + deterministic so a rebuild is exact; the log is a simple, inspectable, greppable file; it doubles as the unit of cro"},"15":{"path":"docs/adr/0003-dual-mode-jwt-auth.md","kind":"adr","source_type":"doc","title":"ADR-0003: Dual-mode JWT auth — HS256 + multi-project Supabase JWKS","chunk":1,"of":2,"preview":"# ADR-0003: Dual-mode JWT auth — HS256 + multi-project Supabase JWKS - **Status:** Accepted - **Date:** 2026-06-29 ## Context The public backend must authenticate users from a customer-facing app and derive a stable, isolated tenant key "},"16":{"path":"docs/adr/0003-dual-mode-jwt-auth.md","kind":"adr","source_type":"doc","title":"ADR-0003: Dual-mode JWT auth — HS256 + multi-project Supabase JWKS","chunk":2,"of":2,"preview":"## Consequences - **Positive:** zero-config onboarding of any of the owner's Supabase projects; cross-project tenant isolation for free; key rotation handled via JWKS; a simple escape hatch (HS256) for non-Supabase clients; open-regist"},"17":{"path":"docs/adr/0004-rootless-docker-privilege.md","kind":"adr","source_type":"doc","title":"ADR-0004: Run the harness as an unprivileged user on its own rootless Docker","chunk":1,"of":2,"preview":"# ADR-0004: Run the harness as an unprivileged user on its own rootless Docker - **Status:** Accepted - **Date:** 2026-06-29 ## Context The harness runs model-generated code in Docker containers (ADR-0006). Initially the internal service"},"18":{"path":"docs/adr/0004-rootless-docker-privilege.md","kind":"adr","source_type":"doc","title":"ADR-0004: Run the harness as an unprivileged user on its own rootless Docker","chunk":2,"of":2,"preview":"## Consequences - **Positive:** a harness RCE no longer implies host root — it lands as an unprivileged user with no rootful socket; container escape maps to an unprivileged subuid, not host root (verified: container-root cannot write "},"19":{"path":"docs/adr/0005-provider-agnostic-model-router.md","kind":"adr","source_type":"doc","title":"ADR-0005: Provider-agnostic model router with a single `tier` knob","chunk":1,"of":3,"preview":"# ADR-0005: Provider-agnostic model router with a single `tier` knob - **Status:** Accepted - **Date:** 2026-06-29 ## Context The whole thesis of StrongHold is a **metaharness**: the model is a swappable component, not the fixed center o"},"20":{"path":"docs/adr/0005-provider-agnostic-model-router.md","kind":"adr","source_type":"doc","title":"ADR-0005: Provider-agnostic model router with a single `tier` knob","chunk":2,"of":3,"preview":"## Consequences - **Positive:** the metaharness promise is real — swap/add models by editing `OLLAMA_URLS` or a key, no caller changes; graceful degradation when a provider is down or unkeyed; genuine local parallelism across two DGX S"},"21":{"path":"docs/adr/0005-provider-agnostic-model-router.md","kind":"adr","source_type":"doc","title":"ADR-0005: Provider-agnostic model router with a single `tier` knob","chunk":3,"of":3,"preview":"## Update 2026-06-30 (commit 68342fe) The router widens from \"one local model + cloud\" to **any model on the cluster + any OpenAI-compatible engine**, all selectable by config — without breaking the `tier`-only contract. Three additions, a"},"22":{"path":"docs/adr/0006-sovereign-sandbox.md","kind":"adr","source_type":"doc","title":"ADR-0006: Sovereign sandbox — hardened ephemeral containers for model code","chunk":1,"of":2,"preview":"# ADR-0006: Sovereign sandbox — hardened ephemeral containers for model code - **Status:** Accepted - **Date:** 2026-06-29 ## Context To match (and exceed) a hosted \"Harness as a Service,\" the agentic loop needs to *run* code the model w"},"23":{"path":"docs/adr/0006-sovereign-sandbox.md","kind":"adr","source_type":"doc","title":"ADR-0006: Sovereign sandbox — hardened ephemeral containers for model code","chunk":2,"of":2,"preview":"## Alternatives considered - **No sandbox (describe-only).** Rejected: that's the gap a real harness fills. - **MicroVMs (Firecracker/Kata) or gVisor.** Stronger isolation but much heavier to operate; revisit if the threat model hardens."},"24":{"path":"docs/adr/0007-mcp-hub-and-tool-profiles.md","kind":"adr","source_type":"doc","title":"ADR-0007: External tools via an MCP hub + per-task tool profiles","chunk":1,"of":2,"preview":"# ADR-0007: External tools via an MCP hub + per-task tool profiles - **Status:** Accepted - **Date:** 2026-06-29 ## Context The harness should reach external capability (ruflo's coordination tools, read/write access to LucidLink filespac"},"25":{"path":"docs/adr/0007-mcp-hub-and-tool-profiles.md","kind":"adr","source_type":"doc","title":"ADR-0007: External tools via an MCP hub + per-task tool profiles","chunk":2,"of":2,"preview":"## Consequences - **Positive:** new external capability is a config entry, not code; the harness survives flaky/crashing MCP servers; tasks run with least privilege and defense-in-depth (offered *and* enforced); secrets don't leak into"},"26":{"path":"docs/adr/0008-lucidlink-common-namespace.md","kind":"adr","source_type":"doc","title":"ADR-0008: LucidLink as canonical cross-agent memory — one common namespace","chunk":1,"of":2,"preview":"# ADR-0008: LucidLink as canonical cross-agent memory — one common namespace - **Status:** Accepted - **Date:** 2026-06-30 ## Context The per-agent COW memory (ADR-0002) is a *semantic index* local to one box. The product promise is **no"},"27":{"path":"docs/adr/0008-lucidlink-common-namespace.md","kind":"adr","source_type":"doc","title":"ADR-0008: LucidLink as canonical cross-agent memory — one common namespace","chunk":2,"of":2,"preview":"## Consequences - **Positive:** one canonical, cross-machine, encrypted, lock-coordinated memory namespace — the headline \"no handoffs\" feature; a 1:1 proof-point of LucidLink's own agentic-scaling positioning; the write boundary is en"},"28":{"path":"docs/adr/0009-per-tenant-memory-isolation.md","kind":"adr","source_type":"doc","title":"ADR-0009: Per-tenant memory isolation via tenant-scoped graduation + replay","chunk":1,"of":3,"preview":"# ADR-0009: Per-tenant memory isolation via tenant-scoped graduation + replay - **Status:** Accepted - **Date:** 2026-06-30 ## Context Per-agent memories were already private, and agent *ownership* was enforced at the backend (cross-tena"},"29":{"path":"docs/adr/0009-per-tenant-memory-isolation.md","kind":"adr","source_type":"doc","title":"ADR-0009: Per-tenant memory isolation via tenant-scoped graduation + replay","chunk":2,"of":3,"preview":"## Decision Keep **one** agenticow instance; make **graduation and recall tenant-scoped**: 1. Tag each agent with its `tenant` (the backend's JWT-derived key, ADR-0003) on spawn; persist it in the ruflo agent-store record. 2. `graduate"},"30":{"path":"docs/adr/0009-per-tenant-memory-isolation.md","kind":"adr","source_type":"doc","title":"ADR-0009: Per-tenant memory isolation via tenant-scoped graduation + replay","chunk":3,"of":3,"preview":"## Consequences - **Positive:** a tenant's vetted learnings reach only that tenant's future agents, never across tenants — closes risk #2; reuses the existing rehydrate/`ingestRaw` machinery and the single bridge (small blast radius on"},"31":{"path":"docs/adr/0010-per-tenant-filespace-isolation.md","kind":"adr","source_type":"doc","title":"ADR-0010: Per-tenant LucidLink filespace isolation (hard isolation)","chunk":1,"of":4,"preview":"# ADR-0010: Per-tenant LucidLink filespace isolation (hard isolation) - **Status:** Accepted - **Date:** 2026-06-30 - **Supersedes (storage layer of):** the subfolder note in [0009](0009-per-tenant-memory-isolation.md) "},"32":{"path":"docs/adr/0010-per-tenant-filespace-isolation.md","kind":"adr","source_type":"doc","title":"ADR-0010: Per-tenant LucidLink filespace isolation (hard isolation)","chunk":2,"of":4,"preview":"## Context ADR-0009 made graduation and recall tenant-scoped, and at the storage layer (ADR-0008) `mem-sync` wrote each tenant's memory to `tenants//memory.json` inside the **one shared `agenticow` filespace** — *logical* isolation"},"33":{"path":"docs/adr/0010-per-tenant-filespace-isolation.md","kind":"adr","source_type":"doc","title":"ADR-0010: Per-tenant LucidLink filespace isolation (hard isolation)","chunk":3,"of":4,"preview":"## Decision **One dedicated LucidLink filespace per tenant (`stronghold-`), with confinement enforced by a stdio shim, not by token scope.** 1. **Provisioning** — `service/provision-tenant.sh ` (idempotent): creates the "},"34":{"path":"docs/adr/0010-per-tenant-filespace-isolation.md","kind":"adr","source_type":"doc","title":"ADR-0010: Per-tenant LucidLink filespace isolation (hard isolation)","chunk":4,"of":4,"preview":"## Consequences - **Positive:** hard *cryptographic* data separation per tenant — independent filespace, bucket, and encryption keyspace; confinement enforced **server-side at the bridge**, not just by a client allowlist, so even a dir"},"35":{"path":"docs/adr/0011-token-usage-metering.md","kind":"adr","source_type":"doc","title":"ADR-0011: Token usage metering & observability across providers, calls, and tools","chunk":1,"of":2,"preview":"# ADR-0011: Token usage metering & observability across providers, calls, and tools - **Status:** Accepted - **Date:** 2026-06-30 ## Context StrongHold routes work across local Ollama models, cloud Claude, OpenRouter, and (ADR-0005) arbi"},"36":{"path":"docs/adr/0011-token-usage-metering.md","kind":"adr","source_type":"doc","title":"ADR-0011: Token usage metering & observability across providers, calls, and tools","chunk":2,"of":2,"preview":"## Consequences - **Positive:** real-time, per-model / per-provider / per-tool cost attribution with no external dashboard or telemetry pipeline; the free/sovereign-local vs paid-cloud spend is visible as you work; the public backend ("},"37":{"path":"docs/adr/README.md","kind":"adr","source_type":"doc","title":"Architecture Decision Records","chunk":1,"of":1,"preview":"# Architecture Decision Records Load-bearing decisions behind StrongHold (the \"Harness as a Service\" metaharness), recorded so collaborators understand the *why*, not just the *what*. Format is a lightweight [MADR](https://adr.github.io/ma"},"38":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":1,"of":15,"preview":"# StrongHold — Architecture & Security Brief *StrongHold is our Harness as a Service (HaaS).* For technical reviewers and security. Covers the full architecture, the trust boundaries, every security and resilience control now in place, an"},"39":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":2,"of":15,"preview":"## 1. Architecture ``` Browser app (Lovable) / any client holding a per-user Bearer JWT │ HTTPS + Bearer JWT ▼ Tailscale Funnel https://spark-47d8.tail333a1d.ts.net/agentmem/v1 ── public internet edge │ "},"40":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":3,"of":15,"preview":"### Two-tier design (defense in depth) | Tier | File / port | Auth | Holds | Exposure | |---|---|---|---|---| | **Tier 2 — public backend** | `backend/server.js` · `:8771` | Bearer JWT | nothing sensitive — no model keys, no memory; per-te"},"41":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":4,"of":15,"preview":"### Dual-GPU Ollama pool (`service/ollama.js`) Both DGX Sparks run Ollama; local inference is a **load-balanced pool**, not a single host. `OLLAMA_URLS` (csv) lists backends, default `http://spark-a1d7:11434,http://localhost:11434`. Each b"},"42":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":5,"of":15,"preview":"### Model router (`service/router.js`) One `tier` knob → ordered provider preference, failing over on error/timeout. The caller never has to name a model. | `tier` | Provider order | |---|---| | `fast` / `balanced` / `local` | `[local]` |"},"43":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":6,"of":15,"preview":"### Token / LLM usage metering (`service/router.js`, `service/mcp-stronghold.js`) Every model call's token usage is now **captured** from the provider (previously received upstream and discarded) and normalized to `{input, output, total}` "},"44":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":7,"of":15,"preview":"### MCP external tools (`service/mcp-client.js`, `mcp-servers.json`) Generic MCP stdio client + hub. Tools are namespaced `__` and auto-added to the act loop. Per-server `include`/`exclude` allowlist. - **ruflo** — `npx @cla"},"45":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":8,"of":15,"preview":"## 2. Trust boundaries ``` ── boundary A ── public internet ⇄ Tailscale Funnel ⇄ backend :8771 only authentication: a valid Bearer JWT. /health is the only unauth route. ── boundary B ── backend :8771 ⇄ internal service :8"},"46":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":9,"of":15,"preview":"## 3. Authentication & multi-tenancy (`backend/server.js`) Public auth is **Bearer JWT, algorithm auto-detected from the token header**. ### Asymmetric Supabase (RS/ES/PS) Verified against the JWKS of the token's **own issuer** (`https:/"},"47":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":10,"of":15,"preview":"### Rate limiting & concurrency caps | Control | Env / default | Behavior | |---|---|---| | Per-tenant token bucket | `RATE_BURST` `30` capacity, refill `RATE_PER_SEC` `1`/s | heavy ops (`act`/`fanout`/`chat`/`sandbox`) cost `HEAVY_COST` `"},"48":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":11,"of":15,"preview":"### MCP resilience A dead MCP child (SSH bridge drop, ruflo crash) is detected and **auto-respawned with exponential backoff** (1s → 30s cap). `has()`/`call()` are gated on `ready`, tools are read live so respawns restore them, and MCP boo"},"49":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":12,"of":15,"preview":"### Data-egress matrix | Request | Leaves the box? | To | |---|---|---| | memory ops, recall, embeddings | No | local MiniLM-L6 (384-dim) | | `/sandbox/run`, `run_code` | No | local Docker | | `tier:fast` / `balanced` / `local` chat/act | "},"50":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":13,"of":15,"preview":"## 5. Residual risks (v0.1) — honest mitigations | # | Risk | Severity | Status / mitigation | |---|---|---|---| | 1 | **Harness runs as a docker-group user.** An RCE in the harness process *itself* (not the sandbox — the host service) wou"},"51":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":14,"of":15,"preview":"edicated key (`/home/stronghold/.ssh/id_ed25519_lucidlink`), no longer reusing markt's. The Mac `authorized_keys` entry pins `restrict` + a forced command, so the key can **only** launch the read-only `lucidlink-mcp` bridge — verified that "},"52":{"path":"docs/ARCHITECTURE_SECURITY.md","kind":"doc","source_type":"doc","title":"StrongHold — Architecture & Security Brief","chunk":15,"of":15,"preview":"## 6. Tech & supply chain - **Node.js 22 (ESM).** Backend: **zero** runtime dependencies (`node:http` + `node:crypto`). Internal service: Fastify, `agenticow`, `@huggingface/transformers` (MiniLM-L6 embedder, run in a `worker_thread` s"},"53":{"path":"docs/deck/README.md","kind":"doc","source_type":"doc","title":"StrongHold deck","chunk":1,"of":1,"preview":"# StrongHold deck `StrongHold.pptx` — the layman/leadership slide deck (18 slides: title + 17), mirroring `../EXEC_BRIEF.md`. Two slides are **drawn** diagrams (the \"big-AI-harness vs metaharness\" contrast and the live request-path), the r"},"54":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":1,"of":14,"preview":"# StrongHold — Developer Quickstart *StrongHold is our Harness as a Service (HaaS).* A per-user memory + agent API you can call from any app. Local-first models with optional cloud escalation; you never name a model unless you want to. Ev"},"55":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":2,"of":14,"preview":"## 3. Endpoints at a glance | Method | Path | Body | Returns | |---|---|---|---| | GET | `/health` | — | `{status, baseVectors, internal}` (no auth) | | GET | `/agents` | — | `Agent[]` (yours only) | | POST | `/agents` | `{agentType, label"},"56":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":3,"of":14,"preview":"# recall — semantic search of THIS agent's memory (+ your base), k results curl -s -H \"$AUTH\" -H \"$CT\" -d '{\"query\":\"how to contact the customer\",\"k\":5}' \\ $BASE/agents/$AID/recall ``` `/memory/search` is the same idea but searches only "},"57":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":4,"of":14,"preview":"## 8. Per-task tool selection (`profile` / `tools`) By default a task may use **all** tools (back-compat). To scope it, pass either a named `profile` or an explicit `tools` allowlist. Selection is enforced in two layers: it filters the too"},"58":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":5,"of":14,"preview":"## 9. The `tier` knob (model routing) Optional on `chat` / `act` / `fanout`. One knob picks an ordered provider preference; the router fails over on error/timeout. You never have to name a model. | `tier` | Provider order | Meaning | |---"},"59":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":6,"of":14,"preview":"async function streamChat(base: string, token: string, agentId: string, prompt: string, onToken: (t: string) => void) { const res = await fetch(`${base}/agents/${agentId}/chat`, { method: \"POST\", headers:"},"60":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":7,"of":14,"preview":"export class StrongHold { constructor( private base = \"https://spark-47d8.tail333a1d.ts.net/agentmem/v1\", private getToken: () => Promise = async () => \"\", ) {} private async req(path: string, body?: unknown"},"61":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":8,"of":14,"preview":"## 13. Gotchas - **Streaming:** use `fetch` + a stream reader with `Accept: text/event-stream`, **not** `EventSource` (no auth header). Streaming is local-model only. See §10. - **Your tenant base:** deleting an agent *graduates* its mem"},"62":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":9,"of":14,"preview":"# 3. Confirm. claude mcp list # -> stronghold ... ✔ Connected ``` > New MCP servers become callable (`mcp__stronghold__*`) **after a session reload/restart**. **Tools** (12): `stronghold_health`, `stronghold_list_agents`, `stro"},"63":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":10,"of":14,"preview":"### 14.1 Auto-memory hooks (StrongHold \"kicks on\" automatically) The MCP makes the tools *available*; these optional hooks make Claude Code *use* memory on its own — no need to remember to call the tools. The helper **`service/sh-memory.mj"},"64":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":11,"of":14,"preview":"# Replace the node path with `which node` on your machine. ``` ```jsonc \"SessionStart\": [ { \"hooks\": [ { \"type\": \"command\", \"command\": \"/path/to/node ~/.stronghold/sh-memory.mjs session-start\", \"timeout\": 8000, \"statusM"},"65":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":12,"of":14,"preview":"## 15. Token & usage metering Every model call's token usage is captured from the provider and normalized to `{input, output, total}`, so you can see exactly how many tokens each model / provider / tool burned — local (free/sovereign) vs c"},"66":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":13,"of":14,"preview":"## 16. Routing to more models & backends StrongHold is no longer pinned to one local model + cloud. Beyond the `tier` knob (§9), pass an explicit `model` to route by **what the model is** — an explicit `model` always wins over tier orderin"},"67":{"path":"docs/DEVELOPER_QUICKSTART.md","kind":"doc","source_type":"doc","title":"StrongHold — Developer Quickstart","chunk":14,"of":14,"preview":"# 3. Restart the internal service so it reloads config. sudo systemctl restart agentmem-internal ``` Then target it with an explicit slug: `{ \"model\": \"webui/llama3.1:70b\" }`. - **Env alternatives** (instead of the files): `LLM_BACKENDS` "},"68":{"path":"docs/EXEC_BRIEF.md","kind":"doc","source_type":"doc","title":"StrongHold — Executive Brief","chunk":1,"of":8,"preview":"# StrongHold — Executive Brief *StrongHold is our Harness as a Service (HaaS).* **One line:** A private AI-agent platform that runs entirely on hardware we already own — giving us the capabilities of a commercial cloud \"AI agent service\" "},"69":{"path":"docs/EXEC_BRIEF.md","kind":"doc","source_type":"doc","title":"StrongHold — Executive Brief","chunk":2,"of":8,"preview":"## Two things only StrongHold has Most of what StrongHold does, a rented cloud harness can also do. Two things it **structurally cannot**, and they are the moat: 1. **It's a metaharness — it orchestrates the orchestrators.** A rented harn"},"70":{"path":"docs/EXEC_BRIEF.md","kind":"doc","source_type":"doc","title":"StrongHold — Executive Brief","chunk":3,"of":8,"preview":"## The economics The headline isn't \"it's cheaper.\" It's that StrongHold **inverts the cost curve**: - **We already paid for the hardware (capex is sunk); every extra agent run is then essentially free** — the marginal cost of a local r"},"71":{"path":"docs/EXEC_BRIEF.md","kind":"doc","source_type":"doc","title":"StrongHold — Executive Brief","chunk":4,"of":8,"preview":"## What it runs on StrongHold runs on two NVIDIA DGX Spark supercomputers that we already own. The everyday AI work is handled by our own on-premise model at zero per-use cost. By default, **no data leaves our hardware** — a credible, conc"},"72":{"path":"docs/EXEC_BRIEF.md","kind":"doc","source_type":"doc","title":"StrongHold — Executive Brief","chunk":5,"of":8,"preview":"## What's new This release moves StrongHold from a working prototype to a resilient, shareable platform. The headline additions: - **Double the horsepower from hardware we already own.** StrongHold now uses *both* DGX Spark machines tog"},"73":{"path":"docs/EXEC_BRIEF.md","kind":"doc","source_type":"doc","title":"StrongHold — Executive Brief","chunk":6,"of":8,"preview":"## What it can do today - **Remembers** — persistent, per-user memory that survives restarts; each user's data is isolated from the rest. - **Converses** — answers questions grounded in that memory. - **Acts** — autonomous agents that ca"},"74":{"path":"docs/EXEC_BRIEF.md","kind":"doc","source_type":"doc","title":"StrongHold — Executive Brief","chunk":7,"of":8,"preview":"## Strategic value 1. **A real moat — the metaharness.** We don't own a model; we own the *layer above the models*. That's the durable, defensible asset competitors who only rent the cloud can't replicate, because their whole model d"},"75":{"path":"docs/EXEC_BRIEF.md","kind":"doc","source_type":"doc","title":"StrongHold — Executive Brief","chunk":8,"of":8,"preview":"## Before a broad external rollout (known next steps) This is an early but genuinely working platform, and the previously-flagged knowledge-sharing gap is now closed (learned knowledge is per-tenant). Two items remain before exposing it *w"},"76":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":1,"of":28,"preview":"# StrongHold — System Documentation *StrongHold — a Personal Harness as a Service (HaaS).* **Status:** live on `spark-47d8` · **Public API:** `https://spark-47d8.tail333a1d.ts.net/agentmem/v1` **Last updated:** 2026-06-29 > This is the M"},"77":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":2,"of":28,"preview":"## 1. What it is **StrongHold** is a **sovereign, memory-centric AI-agent *metaharness***, served as an API, running entirely on the owner's own hardware (two NVIDIA DGX Spark supercomputers). A \"harness\" (per Dan Cleary's *Harness as a Se"},"78":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":3,"of":28,"preview":"## 1a. The metaharness thesis (positioning) The frontier model is hard to replicate; **the harness around it is not** — it is orchestration plumbing. The labs bundle the two and price the bundle as if the harness were the scarce part. It i"},"79":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":4,"of":28,"preview":"## 2. Architecture & topology ``` Browser app (Lovable) │ HTTPS + Bearer JWT (per user) ▼ Tailscale Funnel https://spark-47d8.tail333a1d.ts.net/agentmem │ (public path mount → localhost) ▼ TIER 2 —"},"80":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":5,"of":28,"preview":"### Two tiers, on purpose - **Tier 1 — internal service** (`service/server.js`, Fastify, port **8770**, `X-API-Key` auth). The memory + harness core. Bound to all interfaces but API-key protected; intended for the backend + localhost on"},"81":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":6,"of":28,"preview":"## 3. Core capabilities (overview) 1. **Per-tenant persistent memory** — copy-on-write vector branches (agenticow), local MiniLM-L6 embeddings (384-dim). Each agent has private memory over a shared base. Graduate-on-terminate promote"},"82":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":7,"of":28,"preview":"### 4.1 Per-user copy-on-write memory (the core) - Built on **agenticow** — copy-on-write vector branching (\"Git for agent memory\"). A shared **base** plus cheap per-agent **branches**. Each agent has private memory over the shared base; "},"83":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":8,"of":28,"preview":"### 4.5 LucidLink — the fleet-wide single source of truth (the other headline) The per-tenant COW memory above is the *semantic index*. **LucidLink is the canonical truth that index points at.** It is not \"one of the MCP tools\" (that frami"},"84":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":9,"of":28,"preview":"## 5. Agents Lightweight, addressable units that own a memory branch. Spawn → remember/recall → chat/act → delete (graduate). Created via the API; backed by the ruflo agent registry. --- ## 6. Recall-augmented chat (`/chat`) Single-shot c"},"85":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":10,"of":28,"preview":"## 9. Sovereign code sandbox (`/sandbox/run` + the `run_code` tool) Runs `python` / `node` / `bash` in an **ephemeral, locked-down Docker container** on your box: - `--network none` (network-isolated) - `--cap-drop ALL` (dropped capabilitie"},"86":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":11,"of":28,"preview":"## 10. Model routing (`service/router.js`) The caller **never names a model**; they pass an optional `tier`. The tier knob maps to an ordered provider preference and fails over on error/timeout: | `tier` | Provider order | Meaning | |---|"},"87":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":12,"of":28,"preview":"### 10.1 Multi-LLM routing beyond Ollama (NEW — config-driven) StrongHold is no longer pinned to one local model + cloud. It routes to **any model on the cluster** and **any OpenAI-compatible engine**, swappable purely by config with no co"},"88":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":13,"of":28,"preview":"## 11. Dual-GPU load balancing (NEW — `service/ollama.js`) Both DGX Sparks run Ollama; local inference is a **pool** load-balanced across them. - `OLLAMA_URLS` (csv) lists the backends. Default: `http://spark-a1d7:11434,http://localhost"},"89":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":14,"of":28,"preview":"## 11a. Observability — token/LLM usage metering (NEW) Every model call's token usage is now **captured** from the provider (it was previously received from upstream and discarded) and normalized to `{input, output, total}`. Ollama and Ope"},"90":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":15,"of":28,"preview":"### 12.1 Connected servers - **ruflo** — launched as `npx @claude-flow/cli@latest mcp start`; 305 tools curated to **8**: `memory_search`, `memory_store`, `memory_retrieve`, `swarm_status`, `agent_list`, `task_create`, `task_status`, `s"},"91":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":16,"of":28,"preview":"### 12.3 Minimal MCP env (NEW) - MCP children get **only a safe allowlist** (PATH/HOME/…) plus the per-server `env` override — **NEVER the service secrets**. Verified: the ruflo child env has no `ANTHROPIC` / `OPENROUTER` / `INTERNAL` /"},"92":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":17,"of":28,"preview":"## 13. Per-task tool selection (\"tools UX\", NEW) `/act` and `/fanout` accept either `profile` (a named bundle) OR `tools` (an explicit allowlist of names, `server__tool`, or `*` wildcard). Fanout also accepts per-task `{prompt, tools, prof"},"93":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":18,"of":28,"preview":"## 14. Public API reference Base URL: `https://spark-47d8.tail333a1d.ts.net/agentmem/v1` Auth: `Authorization: Bearer ` on everything except `GET /health`. (The `/agentmem` and `/v1` prefixes are both optional/stripped by the backend."},"94":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":19,"of":28,"preview":"## 15. Auth & multi-tenancy (`backend/server.js`) Bearer **JWT**, algorithm auto-detected: - **Asymmetric Supabase (RS/ES/PS)** — verified against the **JWKS of the token's OWN issuer** (`https://.supabase.co/auth/v1`); ANY of the "},"95":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":20,"of":28,"preview":"## 16. Security posture | Control | Detail | |---|---| | **Fail-closed secrets (NEW)** | Both tiers refuse to boot on a default/weak/missing key: `API_KEY` on the internal service; `JWT_SECRET` and `INTERNAL_API_KEY` < 24 chars on the back"},"96":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":21,"of":28,"preview":"### Known residual risk / v0.1 caveats - ~~The service runs as a docker-group user, so an RCE in the harness ITSELF would be host-root.~~ **MITIGATED (2026-06-29):** the service runs as the dedicated unprivileged user `stronghold` (NOT "},"97":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":22,"of":28,"preview":"## 18a. Economics (why the metaharness pays for itself) StrongHold doesn't merely undercut a rented harness — it **inverts the cost curve**. A rented harness is variable opex that rises with usage (the more value you extract, the more you "},"98":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":23,"of":28,"preview":"## 19. Health endpoint shape (`/healthz`, authed) ``` { status: ok | degraded, uptime, degraded?: { mcpDown[] }, baseVectors, durableMemories, agents, rehydrated, sandbox, sandboxQueue: { active, queued, max }, mcpServe"},"99":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":24,"of":28,"preview":"### 20.1 Internal service (`:8770`) — `/etc/agentmem-internal.env` | Var | Default / note | Purpose | |---|---|---| | `API_KEY` | **required, no default** | Shared key the backend uses to call the internal service (fail-closed) | | `PORT` |"},"100":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":25,"of":28,"preview":"### 20.2 Public backend (`:8771`) — `backend/.env` + compose env | Var | Default / note | Purpose | |---|---|---| | `PORT` | `8771` | Listen port | | `INTERNAL_URL` | `http://host.docker.internal:8770` | Reach the internal service | | `INTE"},"101":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":26,"of":28,"preview":"### 21.2 Lovable / browser Use the drop-in TypeScript client and instructions in **`backend/LOVABLE.md`**. Essentials: - Base URL above; `Authorization: Bearer `. - For real per-user memory, set the token to the Supabase session acce"},"102":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":27,"of":28,"preview":"## 23. Tech stack - **Runtime:** Node.js (ESM). Internal service uses **Fastify**; backend is **zero-dependency** `node:http` + `node:crypto`. - **Memory:** `agenticow` (COW vectors) + `@huggingface/transformers` (local MiniLM embeddings,"},"103":{"path":"docs/HARNESS.md","kind":"doc","source_type":"doc","title":"StrongHold — System Documentation","chunk":28,"of":28,"preview":"## 25. Glossary - **Harness** — everything around a model that lets it do work (loop, tools, sandbox, memory, auth, routing). Scoped to one vendor's model. - **Metaharness** — a harness whose *models, tool runtimes, sandboxes, memory back"},"104":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":1,"of":18,"preview":"# StrongHold — Operations Runbook *StrongHold is our Harness as a Service (HaaS).* How to run, monitor, configure, and troubleshoot the system on `spark-47d8`. Repo root: `/home/markt/agenticow-ruflo-memory`. Sudo: `markt` / password on f"},"105":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":2,"of":18,"preview":"## 1. Processes | Component | Type | Manage | Port | Restart policy | |---|---|---|---|---| | Internal service (`service/server.js`, Fastify, `X-API-Key`) | systemd `agentmem-internal` (**User=stronghold**, enabled) | `sudo systemctl {stat"},"106":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":3,"of":18,"preview":"## 3. Dual-GPU Ollama pool Both DGX Sparks run Ollama; local inference is a **pool** load-balanced across them so two GPUs give true parallelism (2 concurrent inferences, wall-time ≈ single not 2×). - `OLLAMA_URLS` (csv) lists the backend"},"107":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":4,"of":18,"preview":"## 4. LucidLink MCP bridge Read-only access to LucidLink filespaces (9 tools: list_filespaces, link_filespace, current_filespace, whoami, read_file, list_files, find_files, grep_files, read_lines). The `lucidlink-mcp` package runs on **ai-"},"108":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":5,"of":18,"preview":"### 4.1 Write bridge + per-tenant memory sync A second bridge **`lucidlink-rw`** (read+write, confined to the `agenticow` filespace = the `/stronghold-mem` common namespace) backs `mem-sync`. The `stronghold-mem-sync.timer` (oneshot, `floc"},"109":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":6,"of":18,"preview":"# forced-command (running the confine-mcp.py shim), and the registry entry. SUDO_PASS=… service/provision-tenant.sh # e.g. pilot01 sudo systemctl start stronghold-mem-sync.service # push that tenant's memory ``` - **Con"},"110":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":7,"of":18,"preview":"## 5. MCP health & auto-respawn MCP external tools (ruflo + lucidlink) are stdio children of the internal service, namespaced `__` and auto-added to the act loop. - A dead MCP child (ssh bridge drop, ruflo crash) is detected"},"111":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":8,"of":18,"preview":"# Internal full report (X-API-Key = internal API_KEY) curl -s -H \"x-api-key: \" localhost:8770/healthz ``` Unauthenticated `/healthz` returns only `{status, uptime}` (info-leak closed); the detailed report requires the API key. Aut"},"112":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":9,"of":18,"preview":"### Internal service (:8770) | Var | Default | Notes | |---|---|---| | `API_KEY` | *(required, no default)* | `X-API-Key`; boot refuses on weak/missing | | `PORT` | 8770 | | | `HOST` | all interfaces | | | `BASE_PATH` | | durable-log / dat"},"113":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":10,"of":18,"preview":"### Public backend (:8771) | Var | Default | Notes | |---|---|---| | `PORT` | 8771 | | | `INTERNAL_URL` | `host.docker.internal:8770` | reaches internal service | | `INTERNAL_API_KEY` | *(strong, required)* | = internal `API_KEY`; boot ref"},"114":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":11,"of":18,"preview":"# After a refuse-to-start on corruption: locate the backup, then restart ls -la /home/markt/agenticow-ruflo-memory/data/*.corrupt.* sudo systemctl restart agentmem-internal ``` ## 10. Minting colleague JWT test tokens Test tokens are HS25"},"115":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":12,"of":18,"preview":"## 11. Troubleshooting | Symptom | Likely cause | Fix | |---|---|---| | Local inference slow / `ollama.backends[].healthy:false` for a1d7 | spark-a1d7 down or tailnet offline | Pool **fails over** to localhost then router escalates to **cl"},"116":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":13,"of":18,"preview":"## 12. Reboot behaviour All layers are reboot-safe: `stronghold`'s **linger** is enabled so its user manager + rootless `docker.service` come up at boot; systemd restarts the internal service (`on-failure` + enabled) which rehydrates memor"},"117":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":14,"of":18,"preview":"## 13. Rootless sandbox (`stronghold` user) The internal service runs as the dedicated unprivileged user **`stronghold`** (uid 1001), which is **not** in the docker group, and executes sandboxed code on its **own rootless Docker daemon**. "},"118":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":15,"of":18,"preview":"## 14. MCP server for Claude Code (`service/mcp-stronghold.js`) A stdio MCP server that bridges the public backend into Claude Code tools (the inverse of the LucidLink/ruflo MCP **clients** in §4–5). It is **not** a long-running service: t"},"119":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":16,"of":18,"preview":"# writes ~/.stronghold/mcp.json (chmod 600); reads JWT_SECRET from backend/.env, never prints it ``` **Register / inspect / remove**: ```bash claude mcp add stronghold --scope user -- node /home/markt/agenticow-ruflo-memory/service/mcp-str"},"120":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":17,"of":18,"preview":"### 15.1 Activate extra LLM backends Extra **Ollama** models need **no config** — the pool is model-aware (each request routes to a host that actually has the requested model, and the health gate no longer demands the single `OLLAMA_MODEL`"},"121":{"path":"docs/OPS_RUNBOOK.md","kind":"doc","source_type":"doc","title":"StrongHold — Operations Runbook","chunk":18,"of":18,"preview":"# Cumulative since boot — totals + per-provider + per-model curl -s -H \"x-api-key: \" localhost:8770/healthz | jq '.usageTotals' ``` - `usageTotals` = `{ totals, byProvider, byModel }`, each `{input, output, total, calls}`, since"},"122":{"path":"README.md","kind":"doc","source_type":"doc","title":"StrongHold","chunk":1,"of":2,"preview":"# StrongHold *A sovereign Harness as a Service (HaaS).* A memory-centric AI agent harness — served as an API, running entirely on your own hardware (two NVIDIA DGX Spark supercomputers). Per-user persistent memory, recall-augmented chat, a"},"123":{"path":"README.md","kind":"doc","source_type":"doc","title":"StrongHold","chunk":2,"of":2,"preview":"## Docs | Doc | For | |---|---| | [`docs/EXEC_BRIEF.md`](docs/EXEC_BRIEF.md) | Leadership — what it is and why it matters | | [`docs/DEVELOPER_QUICKSTART.md`](docs/DEVELOPER_QUICKSTART.md) | Engineers — auth, endpoints, the `tier` knob, ex"},"124":{"path":"ROADMAP.md","kind":"doc","source_type":"doc","title":"StrongHold — Roadmap","chunk":1,"of":4,"preview":"# StrongHold — Roadmap Where StrongHold is and what's next. StrongHold is **live, hardened, and multi-tenant isolated** today; nothing below blocks internal use or a controlled pilot. This doc tracks the path to broad multi-organization pr"},"125":{"path":"ROADMAP.md","kind":"doc","source_type":"doc","title":"StrongHold — Roadmap","chunk":2,"of":4,"preview":"## Shipped (context) - **Two-tier topology, dual-mode JWT auth, rootless-Docker privilege isolation, provider-agnostic model router, sovereign sandbox, MCP hub + tool profiles** — ADR-0001…0007, all live and verified. - **LucidLink rea"},"126":{"path":"ROADMAP.md","kind":"doc","source_type":"doc","title":"StrongHold — Roadmap","chunk":3,"of":4,"preview":"### 1. Cloud-spend caps + sign-up controls · _priority: high_ Paid model tiers (Claude / OpenRouter) cost money per call, and any user from an allowlisted Supabase project can authenticate. Per-tenant rate limiting and a global heavy-op c"},"127":{"path":"ROADMAP.md","kind":"doc","source_type":"doc","title":"StrongHold — Roadmap","chunk":4,"of":4,"preview":"### 4. Per-tenant scoped tokens · _depends on: LucidLink_ If LucidLink ships filespace-scoped service-account tokens (today every token is workspace-admin), mint one per tenant and drop the shim's reliance — confinement would move to the "},"128":{"path":"package.json","kind":"doc","source_type":"config","title":"package.json","chunk":1,"of":1,"preview":"{ \"name\": \"agenticow-ruflo-memory\", \"version\": \"0.1.0\", \"private\": true, \"type\": \"module\", \"description\": \"Per-agent COW memory for ruflo-style multi-agent workflows, backed by agenticow + local all-MiniLM-L6-v2 embeddings.\", \"s"},"129":{"path":"src/agent-memory.js","kind":"source","source_type":"src","title":"agent-memory.js","chunk":1,"of":4,"preview":"Source src/agent-memory.js (full): // agent-memory.js — per-agent COW memory for ruflo-style multi-agent workflows. // // Model: // MemoryHub = one shared, embedded base memory (common knowledge). // Agent = a copy-on-write fork o"},"130":{"path":"src/agent-memory.js","kind":"source","source_type":"src","title":"agent-memory.js","chunk":2,"of":4,"preview":"export class MemoryHub { /** @param {AgenticMemory} mem @param {string} path @param {import('./durable-store.js').DurableStore} [store] */ constructor(mem, path, store = null) { this.mem = mem; this.path = path; this.store"},"131":{"path":"src/agent-memory.js","kind":"source","source_type":"src","title":"agent-memory.js","chunk":3,"of":4,"preview":"export class Agent { /** @param {AgenticMemory} branch @param {string} name @param {number} idx @param {import('./durable-store.js').DurableStore} [store] */ constructor(branch, name, idx, store = null) { this.branch = branch; t"},"132":{"path":"src/agent-memory.js","kind":"source","source_type":"src","title":"agent-memory.js","chunk":4,"of":4,"preview":"function hitToObj(h) { return { id: h.id, text: h.text, distance: Number(h.distance.toFixed(4)), source: h.branch }; } "},"133":{"path":"src/durable-store.js","kind":"source","source_type":"src","title":"durable-store.js","chunk":1,"of":2,"preview":"Source src/durable-store.js (full): // durable-store.js — the persistence the agenticow .rvf manifest doesn't give us. // // agenticow saves VECTORS but not text payloads, so a reload loses all content. // This is a tiny append-only log of "},"134":{"path":"src/durable-store.js","kind":"source","source_type":"src","title":"durable-store.js","chunk":2,"of":2,"preview":"export class DurableStore { /** @param {string} filePath */ constructor(filePath) { this.filePath = filePath; /** @type {{id:number, text:string, scope:string}[]} */ this.entries = []; this._timer = null; if (fs.exis"},"135":{"path":"src/embed-worker.js","kind":"source","source_type":"src","title":"embed-worker.js","chunk":1,"of":1,"preview":"Source src/embed-worker.js (full): // embed-worker.js — runs the MiniLM ONNX embedder in a worker_thread so the model // forward pass (CPU-bound) doesn't block the main event loop that serves all HTTP. // Receives { id, texts }, replies { i"},"136":{"path":"src/embedder.js","kind":"source","source_type":"src","title":"embedder.js","chunk":1,"of":2,"preview":"Source src/embedder.js (full): // embedder.js — real text→vector embeddings, fully local. // // Uses Xenova/all-MiniLM-L6-v2 (384-dim, L2-normalized) via Transformers.js. The // forward pass is CPU-bound and would block the single Node even"},"137":{"path":"src/embedder.js","kind":"source","source_type":"src","title":"embedder.js","chunk":2,"of":2,"preview":"function embedBatchWorker(texts) { const w = ensureWorker(); if (!w) return Promise.reject(new Error('no embed worker')); const id = nextId++; return new Promise((resolve, reject) => { pending.set(id, { resolve, reject }); w"},"138":{"path":"src/ruflo-bridge.js","kind":"source","source_type":"src","title":"ruflo-bridge.js","chunk":1,"of":7,"preview":"Source src/ruflo-bridge.js (full): // ruflo-bridge.js — bind agenticow per-agent memory to REAL ruflo agent spawns. // // The durable ruflo agent registry (the one `mcp__ruflo__agent_spawn` writes, // shared with the MCP daemon) lives at: /"},"139":{"path":"src/ruflo-bridge.js","kind":"source","source_type":"src","title":"ruflo-bridge.js","chunk":2,"of":7,"preview":"export class RufloMemoryBridge { /** * @param {import('./agent-memory.js').MemoryHub} hub * @param {{registryPath?: string, agentStorePath?: string, * onGraduate?: (info: {agentId:string, agentType?:string, * "},"140":{"path":"src/ruflo-bridge.js","kind":"source","source_type":"src","title":"ruflo-bridge.js","chunk":3,"of":7,"preview":". */ _tbaseScope(tenant) { return `tbase:${tenant}`; } /** The tenant an agent belongs to (in-memory cache, else the persisted store). */ tenantOf(agentId) { if (this.tenantOfId.has(agentId)) return this.tenantOfId.get(agentId); "},"141":{"path":"src/ruflo-bridge.js","kind":"source","source_type":"src","title":"ruflo-bridge.js","chunk":4,"of":7,"preview":": [], tasks: [], config: { topology: opts.topology || 'hierarchical', maxAgents: opts.maxAgents || 8, strategy: 'specialized', communicationProtocol: 'message-bus', autoScali"},"142":{"path":"src/ruflo-bridge.js","kind":"source","source_type":"src","title":"ruflo-bridge.js","chunk":5,"of":7,"preview":"anch for ${agentId} — call sync() after it spawns`); } /** True if ruflo's durable stores still consider this agent live (survives our restart). */ _knownAgent(agentId) { const rec = (this._readAgentStore().agents || {})[agentId]"},"143":{"path":"src/ruflo-bridge.js","kind":"source","source_type":"src","title":"ruflo-bridge.js","chunk":6,"of":7,"preview":" slotFor(id)); this.agents.set(id, agent); if (rec.agentType) this.typeOf.set(id, rec.agentType); this.tenantOfId.set(id, rec.tenant); await this._replayTenantBase(agent, rec.tenant); agents++; } return"},"144":{"path":"src/ruflo-bridge.js","kind":"source","source_type":"src","title":"ruflo-bridge.js","chunk":7,"of":7,"preview":" } } // Safety-net poll (also covers platforms where fs.watch is flaky). if (opts.pollMs) this._watchers.push({ close: () => clearInterval(this._poll), _i: (this._poll = setInterval(() => this.reconcile().catch(() => {}), opts.p"}}} \ No newline at end of file diff --git a/kb/stores/StrongHold/StrongHold-kb.passages.jsonl b/kb/stores/StrongHold/StrongHold-kb.passages.jsonl deleted file mode 100644 index 135b99f..0000000 --- a/kb/stores/StrongHold/StrongHold-kb.passages.jsonl +++ /dev/null @@ -1,144 +0,0 @@ -{"id":"1","text":"# Calling StrongHold from Lovable\n\n**StrongHold** is a sovereign, memory-centric AI-agent harness served as an API (\"Harness as a Service\") — same capabilities as a cloud AI-agent service, but it runs entirely on the owner's own hardware (two DGX Sparks), data stays local.\n\n**Base URL:** `https://spark-47d8.tail333a1d.ts.net/agentmem/v1`\n**Auth:** `Authorization: Bearer ` on every request except `GET /health`.\n**CORS:** enabled — works from any Lovable preview/custom domain.\n**Streaming:** `POST /agents/{id}/chat` returns SSE when `Accept: text/event-stream`.\nUse `fetch` + a stream reader for streaming — **not** `EventSource` (it can't send the `Authorization` header).\n**Rate limits:** per-tenant token bucket (heavy ops cost more). Be a good client — handle `429` with `Retry-After` (see [Rate limits](#rate-limits)).\n\n## Token\n\nFor getting started, one shared long-lived HS256 test token (sub `lovable-user`):\n\n```\n\n```\n\n> ⚠️ This single token is visible in the browser bundle and maps everyone to ONE user. Fine for a prototype. For real per-user memory, use Supabase auth (see [bottom](#production-auth-per-user-via-supabase--already-wired-zero-config)) so each signed-in user gets their own isolated memory.\n\n","path":"backend/LOVABLE.md","title":"Calling StrongHold from Lovable","source_type":"doc","kind":"doc"} -{"id":"2","text":"## Endpoints\n\n| Method | Path | Body | Returns |\n|--------|------|------|---------|\n| GET | `/health` | — | `{status, baseVectors, internal}` (no auth) |\n| GET | `/agents` | — | `Agent[]` (caller's agents) |\n| POST | `/agents` | `{agentType, label?}` | `Agent` |\n| GET | `/agents/{id}` | — | `Agent` |\n| DELETE | `/agents/{id}` | — | `{agentId, promoted:{ingested,deleted}, gatedOut}` (graduate-on-terminate) |\n| POST | `/agents/{id}/memories` | `{text: string \\| string[]}` | `{ids, count}` (durable before it returns 200/201) |\n| POST | `/agents/{id}/recall` | `{query, k?}` | `MemoryHit[]` (base ∪ this agent's private; child wins) |\n| POST | `/agents/{id}/chat` | `{prompt, tier?, recallK?}` | `{text, provider, model, usedMemories, usage}` or SSE |\n| POST | `/agents/{id}/act` | `{prompt, tier?, profile?, tools?, maxSteps?, recallK?}` | `{text, steps[], usedMemories, provider, model, usage}` — **agentic loop** |\n| POST | `/agents/{id}/fanout` | `{tasks[], tier?, profile?, tools?, agentType?, maxStepsPer?}` | aggregated sub-agent results (incl. `usage`) |\n| POST | `/sandbox/run` | `{language, code, timeoutMs?}` | `{stdout, stderr, exitCode, timedOut, durationMs}` |\n| POST | `/memory/search` | `{query, k?}` | `MemoryHit[]` (caller's shared base) |\n\n`Agent = {agentId, agentType, label, status, createdAt}`\n`MemoryHit = {id, text, distance /* lower = closer */, source /* 'base' or agentId */}`\n`Usage = {input, output, total}` — token counts for the request, so you can show cost/usage per call. On `chat` it's the single model call; on `act` / `fanout` it's **summed across the whole agentic loop / all sub-agents**.\n\n### `/act` — the agentic loop\n\nThe model recalls relevant memories, injects them, then calls tools (run code in the sandbox, recall/remember memory, and any permitted external tools), feeds results back, and returns a concise final answer. `steps[]` is the trace (`{tool, args, result}`).\n\n","path":"backend/LOVABLE.md","title":"Calling StrongHold from Lovable","source_type":"doc","kind":"doc"} -{"id":"3","text":"### `/fanout` — sub-agent fan-out\n\nUp to 8 ephemeral workers run `tasks[]` in parallel, results are aggregated, then the workers are dismissed (no graduation). `tasks` can be plain strings or per-task objects `{prompt, tools?, profile?}`, so each worker can get its own toolset. Top-level `tier` / `profile` / `tools` / `agentType` / `maxStepsPer` apply as defaults.\n\n### `/sandbox/run` — sovereign code sandbox\n\nHardened ephemeral Docker container: `--network none`, all caps dropped, read-only rootfs, non-root, `/tmp` tmpfs noexec, memory/CPU/pids/time limited. Languages: `python`, `node`, `bash`. No network from inside.\n\n","path":"backend/LOVABLE.md","title":"Calling StrongHold from Lovable","source_type":"doc","kind":"doc"} -{"id":"4","text":"## Picking quality vs. speed — the `tier` knob (optional)\n\nYou never name a model. Add an optional `tier` to `chat` / `act` / `fanout`; omit it and you get smart defaults. Every response reports the `provider` (`local` / `cloud` / `openrouter`) and `model` that actually answered.\n\n| `tier` | What you get |\n|---|---|\n| `\"fast\"` / `\"balanced\"` | Local model — free, private, on your hardware. |\n| *(omitted)* / `\"auto\"` | **Local first**, transparently falls over to cloud Claude, then OpenRouter. Good default. |\n| `\"max\"` | **Best reasoning** — cloud Claude (Opus), falls back to OpenRouter then local. |\n| `\"openrouter\"` | Route to OpenRouter (GPT/Gemini/Llama/…), local fallback. |\n\nLocal inference is load-balanced across **both DGX Sparks** (two GPUs = true parallelism), so fan-out and concurrent chats don't all pile onto one GPU. If a provider's key isn't set, *every* tier transparently skips it — nothing breaks, you just don't get that option. Example: `AgentMemory.chat(id, prompt, { tier: \"max\" })`.\n\n**Pick a specific model (power users):** instead of (or alongside) `tier`, pass an explicit `model`. An **explicit `model` wins routing** over the tier's defaults:\n- A **bare model id** (e.g. `{ model: \"deepseek-r1:32b\" }`) routes to the local Ollama pool — any model loaded on the cluster is reachable by name, not just the default.\n- A **`prefix/model` slug** routes by its prefix: if the prefix is a configured OpenAI-compatible backend name it goes there (`{ model: \"webui/llama3.1:70b\" }`), otherwise it's treated as an OpenRouter vendor slug (`{ model: \"google/gemini-2.0-flash\" }`). Which backends exist is a server-side config detail.\n\nMost callers should just use `tier` and never name a model.\n\n`GET /health`'s `router.{cloud,openrouter}` flip from `false` to the model name when those keys are configured. Data leaves your hardware only for cloud/OpenRouter requests — `fast`/`balanced` always stay local.\n\n","path":"backend/LOVABLE.md","title":"Calling StrongHold from Lovable","source_type":"doc","kind":"doc"} -{"id":"5","text":"## Choosing tools per task — the `profile` / `tools` knob (act + fanout)\n\nBy default an agent can use **all** tools. To scope what the model is allowed to touch on a given `/act` (or `/fanout`) call, pass either a named `profile` **or** an explicit `tools` allowlist. Scoping is enforced two ways: the filtered set is what's *offered* to the model, and any call to a non-permitted tool is rejected at dispatch with \"not permitted\".\n\nBuilt-in profiles:\n\n| `profile` | Tools the agent can use |\n|---|---|\n| `all` | Everything (the default if you pass nothing) |\n| `memory` | Recall / remember only |\n| `code` | Run code in the sandbox |\n| `files` | LucidLink filespace tools (`lucidlink__*`) |\n| `research` | Files + memory + code for read/search-heavy work |\n| `lucid-readonly` | Read-only LucidLink access |\n\n```ts\n// Let the agent read & search the team's LucidLink files while answering:\nAgentMemory.act(id, \"Summarize the latest project brief in our filespace\", { profile: \"research\" });\n\n// Or an explicit allowlist (names, \"server__tool\", or \"*\" wildcard):\nAgentMemory.act(id, \"...\", { tools: [\"recall_memory\", \"lucidlink__read_file\", \"lucidlink__grep_files\"] });\n```\n\n### LucidLink filespace tools\n\nWith the `files` / `research` / `lucid-readonly` profile, the agent gains **read-only** access to the team's LucidLink filespaces: `list_filespaces`, `link_filespace`, `current_filespace`, `whoami`, `read_file`, `list_files`, `find_files`, `grep_files`, `read_lines`. So an `/act` agent can locate, search, and read the team's actual files to ground its answer — it cannot write or delete. (Owner-scoped v1: one service-account view shared across tenants.)\n\n","path":"backend/LOVABLE.md","title":"Calling StrongHold from Lovable","source_type":"doc","kind":"doc"} -{"id":"6","text":"## Drop-in client (`src/lib/agentMemory.ts`)\n\n```ts\nconst BASE = \"https://spark-47d8.tail333a1d.ts.net/agentmem/v1\";\n// Prototype: paste the test token. Production: return the Supabase access token.\nconst getToken = () => \"\";\n\ntype Tier = \"fast\" | \"balanced\" | \"local\" | \"auto\" | \"max\" | \"openrouter\";\n// Per-task tool scope: a named profile or an explicit allowlist.\ntype ToolScope = { profile?: string; tools?: string[] };\n// Token usage returned on chat/act/fanout responses (act/fanout sum across the loop).\ntype Usage = { input: number; output: number; total: number };\n// Quality/speed: pass `tier`, OR an explicit `model` (a bare id -> local Ollama pool,\n// a \"vendor/model\" slug -> a configured OpenAI-compatible backend). `model` wins routing.\ntype ModelOpt = { tier?: Tier; model?: string };\n\nasync function api(path: string, init: RequestInit = {}) {\n const res = await fetch(BASE + path, {\n ...init,\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${getToken()}`,\n ...(init.headers || {}),\n },\n });\n if (res.status === 429) {\n const retry = res.headers.get(\"retry-after\");\n throw new Error(`rate limited; retry after ${retry ?? \"?\"}s`);\n }\n if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);\n return res.status === 204 ? null : res.json();\n}\n\n","path":"backend/LOVABLE.md","title":"Calling StrongHold from Lovable","source_type":"doc","kind":"doc"} -{"id":"7","text":"export const AgentMemory = {\n listAgents: () => api(\"/agents\"),\n spawn: (agentType: string, label?: string) =>\n api(\"/agents\", { method: \"POST\", body: JSON.stringify({ agentType, label }) }),\n remember: (id: string, text: string | string[]) =>\n api(`/agents/${id}/memories`, { method: \"POST\", body: JSON.stringify({ text }) }),\n recall: (id: string, query: string, k = 5) =>\n api(`/agents/${id}/recall`, { method: \"POST\", body: JSON.stringify({ query, k }) }),\n searchBase: (query: string, k = 5) =>\n api(\"/memory/search\", { method: \"POST\", body: JSON.stringify({ query, k }) }),\n terminate: (id: string) => api(`/agents/${id}`, { method: \"DELETE\" }),\n\n // tier/model = quality/speed knob; usually you never name a model.\n // Returns { text, provider, model, usedMemories, usage } (usage: Usage).\n chat: (id: string, prompt: string, opts: { recallK?: number } & ModelOpt = {}) =>\n api(`/agents/${id}/chat`, { method: \"POST\", body: JSON.stringify({ prompt, ...opts }) }),\n\n // Agentic loop: the model uses tools (run_code in the sandbox, recall, remember, and any\n // permitted external tools) to do work. Scope tools with `profile` or `tools`.\n // Returns { text, steps: [{tool, args, result}], usedMemories, provider, model, usage }\n // where `usage` is summed across every model call in the loop.\n act: (\n id: string,\n prompt: string,\n opts: { maxSteps?: number; recallK?: number } & ModelOpt & ToolScope = {},\n ) => api(`/agents/${id}/act`, { method: \"POST\", body: JSON.stringify({ prompt, ...opts }) }),\n\n // Fan-out: up to 8 ephemeral workers run tasks in parallel, then are dismissed.\n // tasks: string[] OR { prompt, tools?, profile? }[] for per-task tool scoping.\n // Aggregated result includes `usage` summed across all sub-agents.\n fanout: (\n id: string,\n tasks: (string | { prompt: string; tools?: string[]; profile?: string })[],\n opts: { agentType?: string; maxStepsPer?: number } & ModelOpt & ToolScope = {},\n ) => api(`/agents/${id}/fanout`, { method: \"POST\", body: JSON.stringify({ tasks, ...opts }) }),\n\n // Direct sandboxed code execution (python | node | bash; no network).\n runCode: (language: string, code: string, timeoutMs?: number) =>\n api(\"/sandbox/run\", { method: \"POST\", body: JSON.stringify({ language, code, timeoutMs }) }),\n\n // Streaming chat — fetch + reader (NOT EventSource, which can't send auth headers).\n async chatStream(\n id: string,\n prompt: string,\n onDelta: (t: string) => void,\n opts: ModelOpt = {},\n ) {\n const res = await fetch(`${BASE}/agents/${id}/chat`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n authorization: `Bearer ${getToken()}`,\n },\n body: JSON.stringify({ prompt, ...opts }),\n });\n if (res.status === 429) throw new Error(`rate limited; retry after ${res.headers.get(\"retry-after\") ?? \"?\"}s`);\n const reader = res.body!.getReader();\n const dec = new TextDecoder();\n let buf = \"\";\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buf += dec.decode(value, { stream: true });\n const lines = buf.split(\"\\n\");\n buf = lines.pop()!;\n for (const ln of lines) {\n const t = ln.trim();\n if (!t.startsWith(\"data:\")) continue;\n const p = t.slice(5).trim();\n if (p === \"[DONE]\") return;\n try { const { delta } = JSON.parse(p); if (delta) onDelta(delta); } catch {}\n }\n }\n },\n};\n```\n\n","path":"backend/LOVABLE.md","title":"Calling StrongHold from Lovable","source_type":"doc","kind":"doc"} -{"id":"8","text":"## Rate limits\n\nEach tenant gets a token bucket (burst capacity ~30, refill ~1/sec). Heavy ops — `act`, `fanout`, `chat`, `sandbox/run` — cost ~5 each, and there's a global cap on simultaneous heavy jobs. When you exceed it the API returns **`429`** with a **`Retry-After`** header (seconds). Be a good client: back off and retry after that delay rather than hammering. The `api()` helper above surfaces the `Retry-After` so you can schedule the retry. Also note request bodies over ~1 MB return `413`.\n\n## Prompt to paste into Lovable\n\n> Build a chat UI backed by my StrongHold API at\n> `https://spark-47d8.tail333a1d.ts.net/agentmem/v1`. Use the client in\n> `src/lib/agentMemory.ts` (already added). On first load, call `spawn(\"assistant\")`\n> and keep the returned `agentId`. Send chat with `AgentMemory.chatStream(agentId, prompt, onDelta)`\n> and render tokens as they arrive. Add a \"remember this\" button that calls\n> `remember(agentId, text)`, and a search box that calls `searchBase(query)`. Add a\n> \"research\" action that calls `act(agentId, q, { profile: \"research\" })` so the agent\n> can read our LucidLink files. Auth is a Bearer token already wired in `getToken()`.\n> If a call throws a \"rate limited\" error, show a toast and retry after the delay.\n\n","path":"backend/LOVABLE.md","title":"Calling StrongHold from Lovable","source_type":"doc","kind":"doc"} -{"id":"9","text":"## Production auth (per-user, via Supabase) — ALREADY WIRED, zero config\n\nThe backend already verifies real Supabase user tokens for **any** of your projects —\npast, present, or future — with no per-project setup. It detects the token's signing\nalgorithm and, for Supabase asymmetric tokens (RS256/ES256/PS256, what every current\nproject uses), fetches the JWKS of the **token's own issuer**\n(`https://.supabase.co/auth/v1`), verifies the signature, and scopes memory to\n`\":\"` — so the same user UUID in two different projects is two\nisolated tenants. JWKS is cached and refetched on key rotation (and a briefly\nunreachable IdP serves the last-good key rather than failing every login). The HS256\nprototype token keeps working alongside.\n\nIn Lovable, just point `getToken()` at the Supabase session (make `api()` await it):\n\n```ts\nconst getToken = async () =>\n (await supabase.auth.getSession()).data.session?.access_token ?? \"\";\n```\n\nThat's it — no backend change needed when you add new Supabase projects.\n\n","path":"backend/LOVABLE.md","title":"Calling StrongHold from Lovable","source_type":"doc","kind":"doc"} -{"id":"10","text":"### Locked to your projects (active)\n\nThe API is restricted to an allowlist of Supabase project refs (`SUPABASE_ALLOWED_REFS`\nin `backend/.env`). It **fails closed**: with no allowlist set, asymmetric tokens are\nrejected unless `SUPABASE_ALLOW_ANY=1`. Tokens from any non-allowed project are rejected\nwith `project not allowed`.\n\n**To onboard another Lovable project** (new or existing): find its ref — the `` in\n`https://.supabase.co` (Lovable → Supabase integration, or Supabase dashboard →\nProject Settings → API → Project URL) — append it to the comma-separated list in\n`backend/.env`, then:\n\n```\ncd /home/markt/agenticow-ruflo-memory/backend && docker compose up -d\n```\n\nNo code change, no rebuild — the new project's signed-in users authenticate immediately,\neach isolated as `\":\"`. To **remove** a project, delete its ref and redeploy.\n\nLegacy HS256-only projects: set `JWT_SECRET` to that project's JWT Secret (this also\ndisables the shared prototype test token). Rotate `JWT_SECRET` to a fresh random value to\nkill the prototype token.\n","path":"backend/LOVABLE.md","title":"Calling StrongHold from Lovable","source_type":"doc","kind":"doc"} -{"id":"11","text":"# ADR-0001: Two-tier topology — internal harness + public backend\n\n- **Status:** Accepted\n- **Date:** 2026-06-29\n\n## Context\n\nStrongHold exposes an LLM harness (memory, agentic loop, sandbox, MCP tools) to a\ncustomer-facing app (Lovable) over the public internet via a Tailscale Funnel. The\nharness holds everything sensitive: model API keys, the memory corpus, MCP server\ncredentials, and the ability to spawn/delete any agent and run a code sandbox. A\nsingle process facing the internet would put all of that one bug away from\ncompromise, and would couple the public contract to the internal implementation.\n\n## Decision\n\nSplit into two processes:\n\n- **Tier 1 — internal harness** (`service/server.js`, Fastify, `:8770`). Holds all\n capability and all secrets. Authenticated by a single `X-API-Key`. Addresses\n agents by `agentId`; knows nothing about end users. Bound to localhost + the\n Docker bridge.\n- **Tier 2 — public backend** (`backend/server.js`, zero-dependency\n `node:http` + `node:crypto`, `:8771`). The only internet-facing edge. Verifies\n the Bearer JWT, derives the tenant from the token (never the body), enforces\n per-tenant ownership, applies CORS / rate limits / body caps, and proxies to\n Tier 1. Holds **no** model keys and **no** memory — only a tenant→agent\n ownership map.\n\nThe backend is co-located on spark with the internal service (reachable via\n`host.docker.internal`), not on a separate host — simpler, and relocatable by\nrepointing `INTERNAL_URL`.\n\n","path":"docs/adr/0001-two-tier-topology.md","title":"ADR-0001: Two-tier topology — internal harness + public backend","source_type":"doc","kind":"adr"} -{"id":"12","text":"## Consequences\n\n- **Positive:** the internet-facing surface is tiny and dependency-free (small\n image, nothing to `npm audit`); secrets never live at the edge; the public API\n contract (`openapi.yaml`) is decoupled from the internal implementation; abuse\n controls live at the edge where the tenant identity is known.\n- **Negative:** an extra network hop and a second process to operate; the\n ownership map (`owners.json`) is a small stateful component the backend must\n persist and protect.\n- **Neutral:** the internal service's strong `X-API-Key` becomes the trust anchor\n between tiers — see ADR-0004 for why the internal service is also deprivileged.\n\n## Alternatives considered\n\n- **Single process.** Rejected: couples public contract to internals and exposes\n all secrets/capability at the internet edge.\n- **Backend on a separate host (ai-factory-mini).** Deferred: more moving parts;\n co-location is simpler and the split is what matters for the security boundary.\n","path":"docs/adr/0001-two-tier-topology.md","title":"ADR-0001: Two-tier topology — internal harness + public backend","source_type":"doc","kind":"adr"} -{"id":"13","text":"# ADR-0002: Append-only durable log is the source of truth\n\n- **Status:** Accepted\n- **Date:** 2026-06-29\n\n## Context\n\nMemory is built on **agenticow** (copy-on-write vector branching — \"Git for agent\nmemory\"). Its persistence (`*.rvf` + manifest) saves **vectors but not the text\npayloads**. So a naive reload survived the vector *count* but returned hits with\n`undefined` text — memory content did not actually survive a restart, and the\nservice is reboot-safe (it *will* restart). The per-user base-agent id cached in\nthe backend also didn't survive an internal restart, causing `agent not found`.\n\n## Decision\n\nMake a tiny **append-only log of `{id, text, scope, vector?}`** the *source of\ntruth* (`src/durable-store.js`, `.durable.json`). On every boot the\nservice **wipes the agenticow vector files and rebuilds the in-RAM index from the\nlog** (`bridge.rehydrate()`), re-embedding only entries that lack a persisted\nvector. `scope` is `base`, a per-agent id, or (later) `tbase:`.\n\nSupporting rules:\n- `remember()` **flushes the log before acknowledging** — a 201 never lies about\n durability.\n- The persisted embedding vector (base64 `Float32`) lives alongside the text, so\n rehydrate is ~O(load), not O(re-embed corpus).\n- A corrupt log is **backed up and the service refuses to start** rather than\n silently blanking memory.\n\n","path":"docs/adr/0002-durable-log-source-of-truth.md","title":"ADR-0002: Append-only durable log is the source of truth","source_type":"doc","kind":"adr"} -{"id":"14","text":"## Consequences\n\n- **Positive:** memory (with text) survives restarts/reboots deterministically;\n embeddings are local + deterministic so a rebuild is exact; the log is a simple,\n inspectable, greppable file; it doubles as the unit of cross-machine sync\n (ADR-0008) and the substrate for per-tenant grouping (ADR-0009).\n- **Negative:** writes happen twice (agenticow index + log); the full log is read\n into memory at boot (fine at current corpus size, revisit at very large scale);\n the agenticow manifest path is now effectively vestigial.\n- **Neutral:** rehydrate is the one place that must understand every scope kind,\n so scope semantics (graduation, tenancy) are centralized there.\n\n## Alternatives considered\n\n- **Trust the agenticow manifest.** Rejected: it loses text — the actual content.\n- **A real embedded DB (SQLite/LMDB).** Overkill for the corpus size and would add\n a dependency to a service that prizes a tiny surface; the append-only JSON log is\n enough and trivially portable.\n","path":"docs/adr/0002-durable-log-source-of-truth.md","title":"ADR-0002: Append-only durable log is the source of truth","source_type":"doc","kind":"adr"} -{"id":"15","text":"# ADR-0003: Dual-mode JWT auth — HS256 + multi-project Supabase JWKS\n\n- **Status:** Accepted\n- **Date:** 2026-06-29\n\n## Context\n\nThe public backend must authenticate users from a customer-facing app and derive a\nstable, isolated tenant key per user. The app stack is Supabase (which issues\n**asymmetric** RS/ES/PS JWTs per project, rotating keys via JWKS), but we also need\na simple long-lived token for prototypes, local tooling, and the MCP wrapper. We\ndid not want per-project configuration or a shared secret shipped in browser\nbundles to be the only option.\n\n## Decision\n\nVerify the Bearer JWT with the algorithm **auto-detected from the token header**:\n\n- **Asymmetric (RS/ES/PS)** — verify against the **JWKS of the token's OWN issuer**\n (`https://.supabase.co/auth/v1`, validated by `SUPABASE_ISS_REGEX`). Any of\n the owner's Supabase projects — past or future — works with zero config. Tenant\n key = `\":\"`, so the same user UUID in two projects is two isolated\n tenants. JWKS is cached per-issuer (1h) and refetched on an unknown `kid`; if the\n IdP is briefly unreachable the last-good key is served rather than failing every\n login.\n- **HS256** — verify against `JWT_SECRET`; tenant `\"hs:\"`. For the prototype\n token, single-secret/legacy projects, and the MCP wrapper.\n\n**Fail closed:** with no `SUPABASE_ALLOWED_REFS` allowlist, asymmetric tokens are\n**rejected** unless `SUPABASE_ALLOW_ANY=1` is explicitly set (otherwise anyone with\nany Supabase account could spawn agents and burn the model budget). The backend\nalso refuses to boot on a weak/default `JWT_SECRET` or `INTERNAL_API_KEY`.\n\n`userId` always comes from the `sub` claim — **never** the request body.\n\n","path":"docs/adr/0003-dual-mode-jwt-auth.md","title":"ADR-0003: Dual-mode JWT auth — HS256 + multi-project Supabase JWKS","source_type":"doc","kind":"adr"} -{"id":"16","text":"## Consequences\n\n- **Positive:** zero-config onboarding of any of the owner's Supabase projects;\n cross-project tenant isolation for free; key rotation handled via JWKS; a simple\n escape hatch (HS256) for non-Supabase clients; open-registration cost-abuse is\n closed by default.\n- **Negative:** two code paths to maintain; the HS256 prototype token, if leaked,\n maps everyone to one tenant until `JWT_SECRET` is rotated (tracked as a residual\n risk); JWKS adds an outbound dependency on the IdP (mitigated by the stale-cache\n fallback).\n- **Neutral:** the tenant key shape (`:` / `hs:`) is the seam every\n downstream isolation layer keys off (ADR-0009).\n\n## Alternatives considered\n\n- **Single shared HS256 secret only.** Rejected: doesn't fit Supabase's asymmetric,\n rotating, per-project keys; forces secret distribution.\n- **Static per-project JWKS config.** Rejected: every new project needs a config\n change; deriving JWKS from the token's own issuer + an allowlist is zero-touch.\n","path":"docs/adr/0003-dual-mode-jwt-auth.md","title":"ADR-0003: Dual-mode JWT auth — HS256 + multi-project Supabase JWKS","source_type":"doc","kind":"adr"} -{"id":"17","text":"# ADR-0004: Run the harness as an unprivileged user on its own rootless Docker\n\n- **Status:** Accepted\n- **Date:** 2026-06-29\n\n## Context\n\nThe harness runs model-generated code in Docker containers (ADR-0006). Initially\nthe internal service ran as `markt`, who is in the `docker` group. Membership of\nthe `docker` group is effectively **host root** (the Docker socket can mount the\nhost filesystem). So an RCE in the harness process *itself* — not the sandbox, the\nhost service — would own the box. That is too much blast radius for an\ninternet-reachable service.\n\n## Decision\n\nRun the internal service as a dedicated unprivileged user **`stronghold`** (uid\n1001, **not** in the `docker` group, locked password, own home, `subuid`/`subgid`\nrange) talking to its **own rootless Docker daemon**\n(`systemctl --user docker.service`, socket `unix:///run/user/1001/docker.sock`).\nSandbox container UID 0 maps to `stronghold`'s subuid range — powerless on the\nhost. The app stays in place at `/home/markt/agenticow-ruflo-memory`; `stronghold`\ngets surgical **POSIX ACLs** (traverse `/home/markt`, `rwX` on the app dir and the\nruflo registry/agent-store, read on the bridge's SSH key) rather than relocating\nthe app. `markt` keeps `docker`-group membership for the rootful fleet\n(ruvector, the backend container, etc.).\n\n","path":"docs/adr/0004-rootless-docker-privilege.md","title":"ADR-0004: Run the harness as an unprivileged user on its own rootless Docker","source_type":"doc","kind":"adr"} -{"id":"18","text":"## Consequences\n\n- **Positive:** a harness RCE no longer implies host root — it lands as an\n unprivileged user with no rootful socket; container escape maps to an\n unprivileged subuid, not host root (verified: container-root cannot write a\n markt-owned file and appears as `nobody`); the rootful daemon never runs sandbox\n containers.\n- **Negative:** operational complexity (rootless dockerd, `subuid`/`subgid`,\n `linger`, ACLs); some sharp edges hit during migration (MCP children needed\n explicit `HOME`/known_hosts ACLs; the npx cache under the new HOME had to be\n re-warmed). Never ACL a *private key* — it bumps the group bits and `ssh` then\n refuses it.\n- **Neutral:** the internal `X-API-Key` (ADR-0001) and this deprivileging together\n define the Tier-1 trust boundary.\n\n## Alternatives considered\n\n- **Keep running as a docker-group user.** Rejected: harness RCE = host root.\n- **Rootful Docker with `--userns-remap`.** Partial; rootless is a stronger, more\n self-contained boundary and keeps the harness off the rootful socket entirely.\n- **gVisor / Kata / Firecracker.** Heavier; the rootless + hardened-container combo\n (ADR-0006) is sufficient for the current threat model and far simpler to operate.\n","path":"docs/adr/0004-rootless-docker-privilege.md","title":"ADR-0004: Run the harness as an unprivileged user on its own rootless Docker","source_type":"doc","kind":"adr"} -{"id":"19","text":"# ADR-0005: Provider-agnostic model router with a single `tier` knob\n\n- **Status:** Accepted\n- **Date:** 2026-06-29\n\n## Context\n\nThe whole thesis of StrongHold is a **metaharness**: the model is a swappable\ncomponent, not the fixed center of a vendor's harness. Callers should ask for a\n*quality/cost tier*, not name a model — and the system should fail over across\nproviders (local GPU, Claude, OpenRouter) without callers knowing. But the\nproviders disagree on wire format (OpenAI-style `tool_calls` vs Anthropic\n`tool_use`/`tool_result`, system-message handling), and a single local 32B GPU\nserializes concurrent work.\n\n## Decision\n\nA router (`service/router.js`) exposes one **`tier`** knob on chat/act/fanout;\ncallers never name a model (unless they pass an explicit `model`):\n\n- `fast`/`balanced` → local only; `auto` → local→cloud failover; `max` →\n cloud→local. Providers: **local** = Ollama pool (`service/ollama.js`), **cloud**\n = Claude via `@anthropic-ai/sdk`, plus **OpenRouter** (`service/openrouter.js`,\n OpenAI-compatible) as failover / explicit tier. Each provider is enabled only\n when its key is present, else that tier silently runs local (graceful).\n- The router translates messages and tools **OpenAI ↔ Anthropic** so the agentic\n loop is provider-independent (merges consecutive tool results into one user\n turn, drops empty assistant turns — Anthropic rejects those).\n- The local backend is a **health-aware pool** (`OLLAMA_URLS`): each GPU host gets\n a one-job semaphore for true N-way parallelism, a host is healthy only if\n reachable *and* holding the model, and a failed call fails over to a sibling\n host before the router escalates to cloud. Every model call has an AbortSignal\n timeout so a hung host triggers failover instead of hanging.\n\n","path":"docs/adr/0005-provider-agnostic-model-router.md","title":"ADR-0005: Provider-agnostic model router with a single `tier` knob","source_type":"doc","kind":"adr"} -{"id":"20","text":"## Consequences\n\n- **Positive:** the metaharness promise is real — swap/add models by editing\n `OLLAMA_URLS` or a key, no caller changes; graceful degradation when a provider\n is down or unkeyed; genuine local parallelism across two DGX Sparks.\n- **Negative:** message/tool translation is fiddly and a real source of edge cases\n (each provider's quirks must be handled); a tier's behavior depends on which keys\n are configured, which can surprise.\n- **Neutral:** tool-call recovery from *text* content (some local models emit tool\n calls as prose) lives next to the router in the act loop (ADR-0007).\n\n## Alternatives considered\n\n- **Caller names the model.** Rejected: leaks provider choice into every client and\n defeats the swappable-model thesis.\n- **One provider.** Rejected: no failover, no cost/quality control, vendor lock-in.\n- **An off-the-shelf gateway (LiteLLM etc.).** Rejected for now: another dependency\n and process; the translation we need is small and the router stays in-process.\n\n","path":"docs/adr/0005-provider-agnostic-model-router.md","title":"ADR-0005: Provider-agnostic model router with a single `tier` knob","source_type":"doc","kind":"adr"} -{"id":"21","text":"## Update 2026-06-30 (commit 68342fe)\n\nThe router widens from \"one local model + cloud\" to **any model on the cluster +\nany OpenAI-compatible engine**, all selectable by config — without breaking the\n`tier`-only contract. Three additions, all backward compatible (empty config =\nexactly prior behavior):\n\n- **Model-aware Ollama pool.** Each request now routes to a pool host that actually\n *has* the requested model, and the health gate no longer requires the single\n default model — a host is healthy if reachable and holding *some* model. Extra\n models already loaded on the cluster Ollamas (`deepseek-r1:32b`, `qwen2.5:32b`,\n `llama3.1:70b`) are reachable and metered by name with **zero config**. Bare\n model names still go to the Ollama pool and are never shadowed by a compat backend.\n- **Generic OpenAI-compatible provider** (`service/openai-compat.js`): a config\n registry of named backends `{ name, url, apiKey?, models? }` for any\n OpenAI-compatible server (vLLM, llama.cpp `--server`, TGI, Open WebUI, LM Studio).\n Config source, first found: env `LLM_BACKENDS` (inline JSON) → env\n `LLM_BACKENDS_CONFIG` (path) → `./llm-backends.json`. Target a backend with an\n explicit `\"/\"` slug (e.g. `\"webui/llama3.1:70b\"`); usage is metered\n under provider label `compat:`. Real config files are gitignored (keys +\n private URLs); only `*.example` templates are committed. Optional\n `COMPAT_TIMEOUT_MS` (default 120000) bounds compat calls.\n- **Tier→model aliases (`TIER_MODELS`).** Two selection modes now coexist: (a) an\n explicit model slug **wins** routing — route by what the model *is*, not the\n tier's default provider order; (b) optional tier→model aliases (env `TIER_MODELS`\n inline JSON → env `TIER_MODELS_CONFIG` → `./tier-models.json`), e.g.\n `{\"reason\":\"deepseek-r1:32b\",\"big\":\"webui/llama3.1:70b\"}`, so a bare `tier`\n resolves to a specific cluster model. `providersFor` only routes by model when one\n is given, else the tier order is unchanged.\n\n`routerInfo` (`/healthz.router`) now also reports `compat` (array of backend names,\nor `false`) and `tierModels`. The Docker public backend (:8771) needs no rebuild —\nit proxies chat/act/fanout verbatim. Activation: `cp llm-backends.json.example\nllm-backends.json` (fill URL + key), optionally `cp tier-models.json.example\ntier-models.json`, then restart the internal service; extra Ollama models need none.\n\n- **Consequence:** the metaharness promise widens — more/larger/specialized local\n models and any OpenAI-compatible engine are swappable purely by config, no code\n change, and (with ADR-0011 metering) every backend's token spend is visible.\n","path":"docs/adr/0005-provider-agnostic-model-router.md","title":"ADR-0005: Provider-agnostic model router with a single `tier` knob","source_type":"doc","kind":"adr"} -{"id":"22","text":"# ADR-0006: Sovereign sandbox — hardened ephemeral containers for model code\n\n- **Status:** Accepted\n- **Date:** 2026-06-29\n\n## Context\n\nTo match (and exceed) a hosted \"Harness as a Service,\" the agentic loop needs to\n*run* code the model writes — compute, verify, transform — not just talk about it.\nThat means executing arbitrary, model-generated code automatically, on our own\nhardware, reachable (behind auth) from the public edge. This is sovereign RCE by\ndesign; the entire question is containment.\n\n## Decision\n\n`service/sandbox.js` runs each `run_code` / `/sandbox/run` request in an\n**ephemeral, hardened Docker container**, then removes it:\n\n`--network none --cap-drop ALL --security-opt no-new-privileges --read-only\n--tmpfs /tmp (noexec) --user 1000:1000 --memory 512m --cpus 1 --pids-limit 128\n--rm`, with a timeout that `docker kill`s the container.\n\nLanguages: python, node, bash. Gated by `SANDBOX_ENABLED` (a kill switch). A global\ncontainer semaphore (`SANDBOX_MAX_CONCURRENCY`) prevents fan-out from exhausting\nhost RAM. The daemon it runs on is `stronghold`'s **rootless** Docker (ADR-0004),\nso even a container escape lands on an unprivileged subuid, not host root.\n\n## Consequences\n\n- **Positive:** the harness can actually do work (verified: it wrote and ran code\n to compute results inside the act loop); no network, no caps, non-root, read-only\n FS, `noexec` /tmp, and resource caps make the escape surface small; layered with\n rootless Docker for defense in depth; one switch disables it entirely.\n- **Negative:** it is still arbitrary code execution — the residual risk is the\n container-escape surface itself, accepted and mitigated rather than eliminated;\n per-run container creation has latency (a warm pool was rejected — it would break\n per-run isolation).\n- **Neutral:** sandbox concurrency shares the same abuse-control philosophy as the\n rate limiter (ADR-0001's edge controls).\n\n","path":"docs/adr/0006-sovereign-sandbox.md","title":"ADR-0006: Sovereign sandbox — hardened ephemeral containers for model code","source_type":"doc","kind":"adr"} -{"id":"23","text":"## Alternatives considered\n\n- **No sandbox (describe-only).** Rejected: that's the gap a real harness fills.\n- **MicroVMs (Firecracker/Kata) or gVisor.** Stronger isolation but much heavier to\n operate; revisit if the threat model hardens. The current flags + rootless daemon\n are sufficient for internal use and a controlled pilot.\n- **Warm container pool for latency.** Rejected: breaks the per-run isolation that\n is the whole point.\n","path":"docs/adr/0006-sovereign-sandbox.md","title":"ADR-0006: Sovereign sandbox — hardened ephemeral containers for model code","source_type":"doc","kind":"adr"} -{"id":"24","text":"# ADR-0007: External tools via an MCP hub + per-task tool profiles\n\n- **Status:** Accepted\n- **Date:** 2026-06-29\n\n## Context\n\nThe harness should reach external capability (ruflo's coordination tools,\nread/write access to LucidLink filespaces) without bespoke integrations, and it\nshould be able to *scope* which tools a given task may use — both for safety\n(don't offer write tools to a doc-summarizing task) and for steering the model.\nExternal MCP servers are separate processes that can crash or hang.\n\n## Decision\n\nA generic MCP client + **`McpHub`** (`service/mcp-client.js`) speaks JSON-RPC over\nstdio to multiple servers, namespacing tools `__` with a per-server\n`include`/`exclude` allowlist. Configured via `mcp-servers.json`. Dead children are\n**auto-respawned with exponential backoff**; the act loop reads tools **live** via\n`mcpHub.toolDefs()` (only *ready* servers), so a crashed-then-respawned server drops\nout of and back into the toolset automatically. MCP children get a **minimal env\nallowlist** (no secrets leak to third-party packages).\n\n**Per-task tool selection** (`service/server.js`): `/act` and `/fanout` accept a\none-word `profile` (named bundle in `tool-profiles.json`) **or** an explicit\n`tools` allowlist (names, `server__tool`, or `*`). Selection filters the tools\n*offered* to the model **and** is enforced at *dispatch* (`allowedNames`) — a tool\ncall the task isn't permitted returns \"not permitted\" even if the model conjures\nit. No selection = all tools (back-compat).\n\n","path":"docs/adr/0007-mcp-hub-and-tool-profiles.md","title":"ADR-0007: External tools via an MCP hub + per-task tool profiles","source_type":"doc","kind":"adr"} -{"id":"25","text":"## Consequences\n\n- **Positive:** new external capability is a config entry, not code; the harness\n survives flaky/crashing MCP servers; tasks run with least privilege and\n defense-in-depth (offered *and* enforced); secrets don't leak into third-party\n MCP processes; profiles are the seam for a future per-tenant saved-tool UX.\n- **Negative:** stdio MCP processes are operational weight (respawn, env, known\n hosts); namespacing and the truncation/quirks of each server must be handled;\n the per-task knob is per-request today, not yet per-tenant-persisted.\n- **Neutral:** the same selection mechanism gates the confined LucidLink write\n bridge (ADR-0008) — e.g. the `lucid-rw` profile.\n\n## Alternatives considered\n\n- **Hard-coded integrations per tool.** Rejected: doesn't scale, no uniform\n lifecycle/allowlisting.\n- **Offer all tools always.** Rejected: unsafe (write/destructive tools exposed to\n every task) and worse for steering the model.\n","path":"docs/adr/0007-mcp-hub-and-tool-profiles.md","title":"ADR-0007: External tools via an MCP hub + per-task tool profiles","source_type":"doc","kind":"adr"} -{"id":"26","text":"# ADR-0008: LucidLink as canonical cross-agent memory — one common namespace\n\n- **Status:** Accepted\n- **Date:** 2026-06-30\n\n## Context\n\nThe per-agent COW memory (ADR-0002) is a *semantic index* local to one box. The\nproduct promise is **no memory handoffs**: agents on different machines/sites, and\nthe human's own Claude markdown memory, should share one canonical, durable,\nlock-coordinated store. LucidLink (the filespace product — globally consistent,\nE2E-encrypted, Raft-locked) is that store. Constraints: spark is `aarch64` and\n`lucidlink` ships no ARM-Linux wheel (can't mount on spark); an agent with write\naccess must not be able to roam the whole account or destroy data.\n\n## Decision\n\nAccess LucidLink over the MCP bridge (ADR-0007), with **two** bridges:\n\n- **`lucidlink`** — broad **read-only** (core toolset, 9 tools) for doc processing.\n- **`lucidlink-rw`** — full data plane (write + Raft locking tools) but **confined\n to a single filespace** (`agenticow`) = the common namespace `/stronghold-mem`.\n\nThe confinement boundary is **the filespace, enforced on the Mac**: a dedicated\nkey's `authorized_keys` pins a forced command\n`LUCIDLINK_FILESPACE=agenticow … uvx lucidlink-mcp` (overrides anything spark\nsends), and the spark-side `include` allowlist drops every destructive op\n(no delete/move/rename) and omits `link_filespace`. There is no path-jail in\n`lucidlink-mcp`, so the filespace is the only hard write boundary. spark can't\nmount LucidLink, so a sync (`service/mem-sync.mjs`, `flock`-guarded systemd timer)\n**streams** COW memory + Claude markdown memory into the namespace through the same\nconfined bridge. `write_file(exclusive=true)` uses Raft global locking for safe\nconcurrent multi-agent writes.\n\n","path":"docs/adr/0008-lucidlink-common-namespace.md","title":"ADR-0008: LucidLink as canonical cross-agent memory — one common namespace","source_type":"doc","kind":"adr"} -{"id":"27","text":"## Consequences\n\n- **Positive:** one canonical, cross-machine, encrypted, lock-coordinated memory\n namespace — the headline \"no handoffs\" feature; a 1:1 proof-point of LucidLink's\n own agentic-scaling positioning; the write boundary is enforced *server-side* on\n the Mac, not trusted from the client.\n- **Negative:** depends on ai-factory-mini being awake (it sleeps after macOS\n updates); MCP rate limits throttle bulk sync (handled with backoff + pacing);\n `write_file` rejects some `.json` as a string, so non-`.md` is sent base64;\n `stronghold` reuses access via ACLs/keys that must be maintained.\n- **Neutral:** the namespace is **owner-scoped** in v0.1 — the per-tenant layout\n on top of it is ADR-0009; per-tenant *filespaces* are the multi-org upgrade.\n\n## Alternatives considered\n\n- **Mount LucidLink on spark.** Impossible: no ARM-Linux wheel.\n- **Direct S3 to the managed filespace.** Not available for the LucidLink-managed\n fs; the MCP bridge is the supported path.\n- **One broad read/write bridge.** Rejected: an agent could leave the namespace or\n delete data — hence the second, confined, destructive-op-free bridge.\n","path":"docs/adr/0008-lucidlink-common-namespace.md","title":"ADR-0008: LucidLink as canonical cross-agent memory — one common namespace","source_type":"doc","kind":"adr"} -{"id":"28","text":"# ADR-0009: Per-tenant memory isolation via tenant-scoped graduation + replay\n\n- **Status:** Accepted\n- **Date:** 2026-06-30\n\n## Context\n\nPer-agent memories were already private, and agent *ownership* was enforced at the\nbackend (cross-tenant access → 404). But **graduation leaked across tenants**:\ndeleting an agent promoted its vetted learnings (`promoteTo`) into the *one* shared\nagenticow base, and **every** agent of **every** tenant forks off that single base\n— so tenant B recalled tenant A's graduated content (and `/memory/search`, routed\nthrough a per-user base agent that also forked the shared base, did too). This was\nthe documented `v0.1` residual risk #2 and a hard blocker for multi-org use.\n\nStructural fact: agenticow's `fork(base)` makes one base the parent of all\nbranches. Giving tenant A's agents a different base than tenant B's means either\n**separate `AgenticMemory` instances per tenant** (per-tenant hubs) or **not using\nthe shared base for tenant-private graduation at all**.\n\n","path":"docs/adr/0009-per-tenant-memory-isolation.md","title":"ADR-0009: Per-tenant memory isolation via tenant-scoped graduation + replay","source_type":"doc","kind":"adr"} -{"id":"29","text":"## Decision\n\nKeep **one** agenticow instance; make **graduation and recall tenant-scoped**:\n\n1. Tag each agent with its `tenant` (the backend's JWT-derived key, ADR-0003) on\n spawn; persist it in the ruflo agent-store record.\n2. `graduate()` re-scopes a tenant agent's learnings into a **per-tenant durable\n scope `tbase:`** (`DurableStore.graduate(scope, toScope)`) and **does\n not** `promoteTo` the shared agenticow base.\n3. Every one of a tenant's agents **inherits `tbase:`** into its branch at\n spawn / attach / rehydrate, via a new `Agent.inherit()` that ingests the text\n with **fresh own-slot ids, RAM-only, and no durable re-record**. (Routing the\n replay through `ingestRaw`, which preserves source ids, would corrupt the\n target branch's `_seq` and re-graduate the entries on the next delete — hence a\n dedicated method.)\n4. `/memory/search` recalls over a bridge-maintained **per-tenant base branch**\n (`tenantBase(tenant)`), rebuilt on restart and kept fresh as the tenant\n graduates agents.\n5. The **global** agenticow base is now reserved for explicitly-curated shared\n infra (`addKnowledge`) — never fed by auto-graduation. Untagged/legacy agents\n keep the old global-base behavior.\n\nAt the storage layer (ADR-0008), `mem-sync` exports each tenant's memory to\n`tenants//memory.json` (grouped from the durable log) — logical isolation\nby subpath; the filespace stays owner-scoped.\n\n","path":"docs/adr/0009-per-tenant-memory-isolation.md","title":"ADR-0009: Per-tenant memory isolation via tenant-scoped graduation + replay","source_type":"doc","kind":"adr"} -{"id":"30","text":"## Consequences\n\n- **Positive:** a tenant's vetted learnings reach only that tenant's future agents,\n never across tenants — closes risk #2; reuses the existing rehydrate/`ingestRaw`\n machinery and the single bridge (small blast radius on a *live* service); the\n shared-infra tier is still available, now opt-in; verified by a 22-check\n in-process suite + an HTTP round-trip on a scratch service + a live end-to-end\n test through the public backend, isolation surviving a restart.\n- **Negative:** a tenant's `tbase` is **copied** into each of its agent branches at\n attach (duplication in RAM — fine at current corpus size, revisit at scale); the\n long-lived `/memory/search` tenant branch can lag a just-graduated entry until\n refreshed (handled on graduate + rebuilt on restart); pre-existing global-base\n content stays shared (isolation is not retroactive — we stop *new* leaks).\n- **Neutral:** the tenant key shape comes straight from ADR-0003; hard storage\n isolation (per-tenant *filespace* + scoped token via the workspace gateway) is\n the documented multi-org upgrade and the next seam.\n\n## Alternatives considered\n\n- **Per-tenant hubs (separate `AgenticMemory` per tenant).** Conceptually cleanest\n and avoids per-branch duplication, but requires a tenant-aware bridge, N base\n files, and a rewrite of the delicate rehydrate/registry paths on a live service.\n Rejected for now on blast-radius grounds; the replay approach is reversible into\n this later if duplication or scale demands it.\n- **Stop graduating entirely.** Rejected: graduation (a tenant's agents learning\n from each other) is a core feature; we scoped it, not removed it.\n","path":"docs/adr/0009-per-tenant-memory-isolation.md","title":"ADR-0009: Per-tenant memory isolation via tenant-scoped graduation + replay","source_type":"doc","kind":"adr"} -{"id":"31","text":"# ADR-0010: Per-tenant LucidLink filespace isolation (hard isolation)\n\n- **Status:** Accepted\n- **Date:** 2026-06-30\n- **Supersedes (storage layer of):** the subfolder note in [0009](0009-per-tenant-memory-isolation.md)\n\n","path":"docs/adr/0010-per-tenant-filespace-isolation.md","title":"ADR-0010: Per-tenant LucidLink filespace isolation (hard isolation)","source_type":"doc","kind":"adr"} -{"id":"32","text":"## Context\n\nADR-0009 made graduation and recall tenant-scoped, and at the storage layer\n(ADR-0008) `mem-sync` wrote each tenant's memory to `tenants//memory.json`\ninside the **one shared `agenticow` filespace** — *logical* isolation by subpath.\nMulti-org use wants **hard** isolation: a tenant's data physically separate, in its\nown end-to-end-encrypted filespace, so a bug, a misrouted write, or a curious agent\ncannot reach another tenant's bytes. ADR-0009 parked this as \"per-tenant filespace +\nscoped token via the workspace gateway.\"\n\nWe investigated whether that's buildable. Findings (all verified against the live\nLucidLink Service API on spark `:3003` and the `lucidlink-mcp` 0.10 server on the Mac):\n\n1. **Filespace lifecycle is fully API-automatable.** `POST/GET/DELETE\n /api/v1/filespaces` create/list/delete filespaces with LucidLink-managed storage\n (`storageOwner:lucidlink`). No portal step is required.\n2. **Service-account tokens cannot be scoped to a filespace.** Per LucidLink, a\n service account \"inherits the full permissions/scope of a workspace administrator.\"\n So the \"scoped token per tenant\" half of the ADR-0009 plan **is not available**;\n every token sees every filespace in the workspace.\n3. **The forced command alone does not confine.** `LUCIDLINK_FILESPACE=` only sets\n the *default* auto-link. `lucidlink-mcp` exposes `link_filespace` (annotated\n `stateful`, so **not** blocked by `READ_ONLY`, which only blocks additive/\n destructive ops) and has **no per-tool server-side exclude**. A holder of the\n bridge key can therefore `link_filespace` to any other filespace — verified\n directly. The previous \"an agent cannot leave the namespace\" guarantee held only\n for *harness agents* (via the spark-side `include` allowlist), **not** for a direct\n key holder such as `mem-sync`.\n\nSo the confinement boundary cannot be the token (can't scope it) or the forced-command\nenv (only a default) — it has to remove the filespace-switching tools from the wire.\n\n","path":"docs/adr/0010-per-tenant-filespace-isolation.md","title":"ADR-0010: Per-tenant LucidLink filespace isolation (hard isolation)","source_type":"doc","kind":"adr"} -{"id":"33","text":"## Decision\n\n**One dedicated LucidLink filespace per tenant (`stronghold-`), with\nconfinement enforced by a stdio shim, not by token scope.**\n\n1. **Provisioning** — `service/provision-tenant.sh ` (idempotent): creates the\n filespace via the Service API and polls to `ready`; generates a dedicated SSH key\n for the `stronghold` user (`id_ed25519_ll_`); pins a forced command on the\n Mac's `authorized_keys`; and registers the tenant in\n `service/tenant-filespaces.json`.\n2. **Confinement = `service/confine-mcp.py`** — the forced command runs this stdio\n JSON-RPC shim *instead of* `lucidlink-mcp` directly. The shim launches the real\n server (inheriting `LUCIDLINK_FILESPACE`) and **strips `link_filespace` /\n `list_filespaces`** from `tools/list` and rejects them on `tools/call`. With no way\n to switch or even enumerate other filespaces, the workspace-admin token is pinned to\n the single auto-linked filespace — for *any* caller of that key, harness or not.\n3. **Routing** — `mem-sync.mjs` reads the registry: a registered tenant's export is\n written to `/stronghold-mem/memory.json` in its **own** filespace via its own key;\n an unregistered tenant falls back to the `agenticow` `tenants//` subfolder\n (ADR-0009 behaviour). The state key encodes the destination so a tenant promoted\n from subfolder → own filespace is re-pushed.\n4. **Hardening the shared bridge** — the existing `agenticow` rw bridge forced command\n was switched to the same shim, closing the identical `link_filespace` hole there\n (it should only ever touch `agenticow`; the read-only bridge is intentionally left\n un-confined so it can browse multiple filespaces for document processing).\n\nVerified end-to-end with reference tenant `pilot01`: `link_filespace(agenticow)` is\nrefused; `current_filespace` is `stronghold-pilot01`; `/stronghold-mem/base` does not\nexist there (a clean, separate filespace); a real `mem-sync` run routes\n`tbase:pilot01` into the pilot01 filespace while **excluding** the shared `base`\nscope; and the `agenticow` namespace contains neither the secret nor a pilot01\nsubfolder.\n\n","path":"docs/adr/0010-per-tenant-filespace-isolation.md","title":"ADR-0010: Per-tenant LucidLink filespace isolation (hard isolation)","source_type":"doc","kind":"adr"} -{"id":"34","text":"## Consequences\n\n- **Positive:** hard *cryptographic* data separation per tenant — independent\n filespace, bucket, and encryption keyspace; confinement enforced **server-side at the\n bridge**, not just by a client allowlist, so even a direct key holder is pinned;\n provisioning is one idempotent script (no portal step); fully reversible\n (`DELETE /filespaces/{id}` + drop the key/line/registry entry).\n- **Negative / residual:** the service-account **token is still workspace-admin** and\n lives on the Mac — a *Mac* compromise exposes every filespace regardless of the shim\n (the shim confines the spark-side key holders, not the token's own power). True\n token-level scoping awaits either LucidLink scoped-token support or a separate\n LucidLink **workspace** (hence its own token) per tenant — account/billing-level, not\n automatable from here. The shim is an extra moving part on the Mac. `mem-sync` opens\n the shared `agenticow` bridge even for a tenant-only sync (cheap, idempotent dir\n creation). One filespace per tenant grows LucidLink-managed storage/billing.\n- **Neutral:** subfolder isolation (ADR-0009) remains the documented fallback for\n untenanted/legacy agents and for tenants not (yet) provisioned a filespace.\n\n## Alternatives considered\n\n- **Scoped service-account token per tenant** — the original ADR-0009 plan; not\n possible today (tokens are workspace-admin scope).\n- **Per-tenant LucidLink *workspace* + its own token** — would give real token-level\n isolation, but creating workspaces is an account/billing operation outside the\n Service API used here; revisit if LucidLink exposes it or multi-org demands it.\n- **Rely on the client-side `include` allowlist alone** — insufficient: it confines\n harness agents but not a direct holder of the bridge key (e.g. `mem-sync`, or a\n compromised `stronghold` process).\n- **Subfolders in one shared filespace (ADR-0009)** — logical isolation only; kept as\n the fallback, not the multi-org answer.\n","path":"docs/adr/0010-per-tenant-filespace-isolation.md","title":"ADR-0010: Per-tenant LucidLink filespace isolation (hard isolation)","source_type":"doc","kind":"adr"} -{"id":"35","text":"# ADR-0011: Token usage metering & observability across providers, calls, and tools\n\n- **Status:** Accepted\n- **Date:** 2026-06-30\n\n## Context\n\nStrongHold routes work across local Ollama models, cloud Claude, OpenRouter, and\n(ADR-0005) arbitrary OpenAI-compatible backends — a mix of *free/sovereign* local\nspend and *paid* cloud spend. Every provider already returns token usage on each\ncall, but StrongHold **received and discarded it**. So there was no way to answer\nthe operational question the metaharness makes acute: *how many tokens did each\nmodel / provider / tool actually burn?* Without that, the local-vs-cloud cost\ntradeoff is invisible, and a runaway agentic loop or fanout shows up only on a\nprovider's bill, after the fact.\n\n## Decision\n\nCapture provider token usage at the router and surface it at three granularities:\n\n1. **Normalize at the source.** Each model call's usage is read from the provider\n and normalized to `{ input, output, total }`. Ollama and OpenRouter read the\n OpenAI `usage` block; cloud Claude reads Anthropic `res.usage.{input_tokens,\n output_tokens}`. Compat backends (ADR-0005) report under provider label\n `compat:`.\n2. **Per call.** `chat`/`act`/`fanout` responses now include a `usage` block.\n `act` **sums** usage across every model call in the agentic loop; `fanout`\n **sums** across all sub-agents — so the number reflects the whole operation,\n not just the last hop.\n3. **Cumulative (process).** The internal service `/healthz` reports\n `usageTotals = { totals, byProvider, byModel }`, each entry `{ input, output,\n total, calls }`, accumulated since process start — real-time per-model and\n per-backend attribution with no external dashboard.\n4. **Per session (MCP).** The StrongHold MCP server keeps a per-session tally and\n exposes a new tool `stronghold_usage` (per-session totals + per-tool breakdown),\n computed client-side with no backend call. MCP tool count goes 11 → 12.\n\n","path":"docs/adr/0011-token-usage-metering.md","title":"ADR-0011: Token usage metering & observability across providers, calls, and tools","source_type":"doc","kind":"adr"} -{"id":"36","text":"## Consequences\n\n- **Positive:** real-time, per-model / per-provider / per-tool cost attribution\n with no external dashboard or telemetry pipeline; the free/sovereign-local vs\n paid-cloud spend is visible as you work; the public backend (:8771) needs no\n change — it proxies the new `usage` field verbatim. Verified live 2026-06-30:\n local qwen chat `{input:56,output:5,total:61}`, `deepseek-r1:32b {44,557,601}`,\n `/healthz.byModel` tracking each model by name, compat path reporting under\n `compat:`.\n- **Negative / known limitation:** the cumulative tally is currently\n **process-global, not per-tenant** — `usageTotals` aggregates across all callers,\n so it answers \"what did this service burn?\" not \"what did tenant A burn?\".\n Per-tenant cost attribution (keying totals by the ADR-0003 tenant) is the natural\n future refinement; the per-session MCP tally already gives a single client its own\n numbers.\n- **Neutral:** numbers are token counts, not currency — price-per-model mapping\n (and any billing) is left to the consumer of `usageTotals` / `stronghold_usage`.\n\n## Alternatives considered\n\n- **External observability (OpenTelemetry / a metrics backend).** Rejected for now:\n another process and dependency for what is a small in-router tally; the data is\n most useful inline on the same call/`/healthz` surface callers already hit.\n- **Keep discarding usage.** Rejected: the provider already hands it to us for free,\n and cost-blindness is untenable once routing spans free-local and paid-cloud.\n","path":"docs/adr/0011-token-usage-metering.md","title":"ADR-0011: Token usage metering & observability across providers, calls, and tools","source_type":"doc","kind":"adr"} -{"id":"37","text":"# Architecture Decision Records\n\nLoad-bearing decisions behind StrongHold (the \"Harness as a Service\" metaharness),\nrecorded so collaborators understand the *why*, not just the *what*. Format is a\nlightweight [MADR](https://adr.github.io/madr/): Context → Decision → Consequences\n→ Alternatives. The code comments and the docs in `../` are the *what*; these are\nthe rationale and the roads not taken.\n\nAn ADR is immutable once Accepted — to change a decision, add a new ADR that\nsupersedes it (note it in both).\n\n| # | Decision | Status |\n|---|----------|--------|\n| [0001](0001-two-tier-topology.md) | Two-tier topology: internal harness (:8770) + public backend (:8771) | Accepted |\n| [0002](0002-durable-log-source-of-truth.md) | Append-only durable log is the source of truth (agenticow persists vectors, not text) | Accepted |\n| [0003](0003-dual-mode-jwt-auth.md) | Dual-mode JWT auth: HS256 + multi-project Supabase JWKS, fail-closed allowlist | Accepted |\n| [0004](0004-rootless-docker-privilege.md) | Run the harness as an unprivileged user on its own rootless Docker | Accepted |\n| [0005](0005-provider-agnostic-model-router.md) | Provider-agnostic model router with a single `tier` knob | Accepted |\n| [0006](0006-sovereign-sandbox.md) | Sovereign sandbox: hardened ephemeral containers for model-generated code | Accepted |\n| [0007](0007-mcp-hub-and-tool-profiles.md) | External tools via an MCP hub + per-task tool profiles | Accepted |\n| [0008](0008-lucidlink-common-namespace.md) | LucidLink as canonical cross-agent memory: one common namespace, confined rw bridge | Accepted |\n| [0009](0009-per-tenant-memory-isolation.md) | Per-tenant memory isolation via tenant-scoped graduation + branch replay | Accepted |\n| [0010](0010-per-tenant-filespace-isolation.md) | Per-tenant LucidLink filespace isolation (hard isolation; confine-mcp shim, not token scope) | Accepted |\n| [0011](0011-token-usage-metering.md) | Token usage metering & observability: normalized per-call usage + cumulative `byProvider`/`byModel` on `/healthz` + per-session `stronghold_usage` | Accepted |\n\n*Deciders: markt (owner) with the StrongHold collaborators. Dates are when the\ndecision was taken in the build, not necessarily when the ADR was written.*\n","path":"docs/adr/README.md","title":"Architecture Decision Records","source_type":"doc","kind":"adr"} -{"id":"38","text":"# StrongHold — Architecture & Security Brief\n\n*StrongHold is our Harness as a Service (HaaS).*\n\nFor technical reviewers and security. Covers the full architecture, the trust\nboundaries, every security and resilience control now in place, and the residual\nrisks (with honest mitigations) of the current `v0.1`.\n\nStrongHold is a **sovereign, memory-centric AI-agent harness served as an API**,\nrunning entirely on the owner's own hardware (two NVIDIA DGX Spark\nsupercomputers). Same capabilities as a cloud \"AI agent service\" — owned end to\nend, data local. Repo: private GitHub `markt-heximal/StrongHold`; host root\n`/home/markt/agenticow-ruflo-memory`.\n\nFull feature reference: `docs/HARNESS.md`. Operations: `docs/OPS_RUNBOOK.md`.\n\n---\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"39","text":"## 1. Architecture\n\n```\n Browser app (Lovable) / any client holding a per-user Bearer JWT\n │ HTTPS + Bearer JWT\n ▼\n Tailscale Funnel https://spark-47d8.tail333a1d.ts.net/agentmem/v1 ── public internet edge\n │ funnel path /agentmem → 127.0.0.1:8771\n ▼\n┌─────────────────────────────────────────────────────────────────────┐\n│ TIER 2 — PUBLIC BACKEND (Docker, node:http, :8771, Bearer JWT) │\n│ internet-facing edge · per-tenant isolation · stateless · no keys │\n└─────────────────────────────────────────────────────────────────────┘\n │ X-API-Key over host.docker.internal:8770 (NOT published via Funnel)\n ▼\n┌─────────────────────────────────────────────────────────────────────┐\n│ TIER 1 — INTERNAL SERVICE (systemd, Fastify, :8770, X-API-Key) │\n│ memory + harness core · agent loop · sandbox · MCP hub · router │\n│ ├─ per-tenant COW vector memory (agenticow) + MiniLM-L6 (384-dim) │\n│ ├─ Docker code sandbox (ephemeral, --network none) │\n│ ├─ MCP hub (stdio) → ruflo (local) , lucidlink (SSH-stdio bridge) │\n│ └─ model router → Ollama POOL | Anthropic | OpenRouter | OAI-compat│\n└─────────────────────────────────────────────────────────────────────┘\n │ │\n ▼ dual-GPU Ollama pool ▼ SSH-stdio\n spark-47d8:11434 + spark-a1d7:11434 ai-factory-mini (Mac) → uvx lucidlink-mcp\n (qwen2.5-coder:32b, 1 slot/GPU) (read-only LucidLink filespaces)\n```\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"40","text":"### Two-tier design (defense in depth)\n\n| Tier | File / port | Auth | Holds | Exposure |\n|---|---|---|---|---|\n| **Tier 2 — public backend** | `backend/server.js` · `:8771` | Bearer JWT | nothing sensitive — no model keys, no memory; per-tenant ownership map only | internet, via Funnel `/agentmem` |\n| **Tier 1 — internal service** | `service/server.js` · `:8770` | `X-API-Key` | memory, model keys, code execution, MCP children | LAN/tailnet only; **never** published through the Funnel |\n\n- The **public backend** is the only internet-facing component. It is a small,\n **zero-dependency** `node:http`+`node:crypto` process whose job is exactly:\n verify the JWT, derive the tenant, enforce per-tenant ownership, proxy to the\n internal service. It carries no model keys and no memory.\n- The **internal service** holds everything sensitive. It authenticates callers\n with a shared `X-API-Key`. It binds all interfaces (so the backend and\n localhost can reach it on `:8770`) but the Tailscale Funnel path maps **only**\n to `:8771`, so the internal service is not internet-reachable.\n- Backend → service hop is `host.docker.internal:8770`.\n\n### Hosts\n\n| Host | Role | Exposure |\n|---|---|---|\n| `spark-47d8` (DGX Spark, GB10) | Backend, internal service, sandbox, Funnel, one Ollama backend | `/agentmem` path public via Funnel |\n| `spark-a1d7` (DGX Spark, GB10) | Second Ollama backend (`:11434`) in the pool | Cluster network only |\n| `ai-factory-mini` (Apple Silicon Mac) | LucidLink MCP server, bridged to spark over SSH-stdio | Cluster network only |\n| Anthropic / OpenRouter | Optional cloud models | Outbound, opt-in per request |\n| Configured OpenAI-compatible backends (vLLM / llama.cpp / TGI / Open WebUI) | Optional, **config-driven** extra models | Outbound HTTP, opt-in per config |\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"41","text":"### Dual-GPU Ollama pool (`service/ollama.js`)\n\nBoth DGX Sparks run Ollama; local inference is a **load-balanced pool**, not a\nsingle host. `OLLAMA_URLS` (csv) lists backends, default\n`http://spark-a1d7:11434,http://localhost:11434`. Each backend gets a per-backend\nslot (`OLLAMA_CONCURRENCY`, default `1` = one GPU, one job) → **true\nparallelism** (2 GPUs = 2 concurrent inferences; verified: 2 concurrent requests\nran on both GPUs at once, wall-time ≈ single not 2×). A backend is healthy only\nif reachable **AND** it has the model (a host still pulling auto-excludes itself).\nOn a call error the request **fails over to the sibling backend before the router\nreaches cloud**. Background re-check `OLLAMA_HEALTH_MS` (`15000`). Legacy single\n`OLLAMA_URL` is still honored.\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"42","text":"### Model router (`service/router.js`)\n\nOne `tier` knob → ordered provider preference, failing over on error/timeout. The\ncaller never has to name a model.\n\n| `tier` | Provider order |\n|---|---|\n| `fast` / `balanced` / `local` | `[local]` |\n| `auto` (DEFAULT) | `[local → cloud → openrouter]` |\n| `max` | `[cloud → openrouter → local]` |\n| `openrouter` | `[openrouter → local]` |\n\n- **local** = Ollama pool, model `qwen2.5-coder:32b`.\n- **cloud** = Anthropic Claude `claude-opus-4-8` — only when `ANTHROPIC_API_KEY`\n is set, otherwise those tiers resolve to local.\n- **openrouter** = OpenAI-compatible (one key → GPT/Gemini/Llama/…), default slug\n `openai/gpt-4o`. An explicit `vendor/model` slug prefers OpenRouter but keeps\n local as failover.\n- **compat** = a generic **OpenAI-compatible backend** provider\n (`service/openai-compat.js`) reaching ANY server that speaks\n `/v1/chat/completions` over HTTP — vLLM, llama.cpp `--server`, TGI, Open WebUI,\n LM Studio. A config registry of named backends `{ name, url, apiKey?, models? }`\n is **selectable purely by config, no code change** (source, first found: env\n `LLM_BACKENDS` inline JSON | `LLM_BACKENDS_CONFIG` path | `./llm-backends.json`).\n Target one with an explicit `/` slug (e.g. `webui/llama3.1:70b`);\n usage is metered under provider label `compat:`.\n- Routing is now **model-aware**: an explicit model slug *wins* — the router\n routes by what the model **is**, not the tier's default order. Bare model names\n still go to the Ollama pool (never shadowed); optional `tier → model` aliases\n (`TIER_MODELS` / `./tier-models.json`) let a bare `tier` resolve to a specific\n cluster model. Empty config = exactly the prior tier behavior (backward compatible).\n- The response reports the `provider` + `model` that actually answered.\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"43","text":"### Token / LLM usage metering (`service/router.js`, `service/mcp-stronghold.js`)\n\nEvery model call's token usage is now **captured** from the provider (previously\nreceived upstream and discarded) and normalized to `{input, output, total}`\n(Ollama / OpenRouter / compat read the OpenAI `usage` block; cloud Claude reads\n`res.usage.{input_tokens,output_tokens}`). Three scopes:\n\n- **Per call** — `chat` / `act` / `fanout` responses carry a `usage` block; `act`\n and `fanout` **sum** usage across every model call in the agentic loop / across\n all sub-agents.\n- **Cumulative** — the internal service `/healthz` reports `usageTotals =\n { totals, byProvider, byModel }` (each `{input, output, total, calls}`) since\n process start. `healthz.router` also reports `compat` (backend names, or false)\n and `tierModels`.\n- **Per session** — the StrongHold MCP server keeps a per-session tally exposed via\n a new 12th tool `stronghold_usage` (per-session totals + per-tool breakdown;\n client-side, no backend call). MCP tool count goes 11 → 12.\n\nNet effect: **per-model and per-backend cost attribution with no external\ndashboard** — local (free/sovereign) vs cloud (paid) spend is visible in real time.\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"44","text":"### MCP external tools (`service/mcp-client.js`, `mcp-servers.json`)\n\nGeneric MCP stdio client + hub. Tools are namespaced `__` and\nauto-added to the act loop. Per-server `include`/`exclude` allowlist.\n\n- **ruflo** — `npx @claude-flow/cli@latest mcp start`; 305 tools curated down to 8\n (`memory_search`/`store`/`retrieve`, `swarm_status`, `agent_list`,\n `task_create`/`status`, `system_status`).\n- **lucidlink** — read-only access to LucidLink filespaces. The package\n `lucidlink-mcp` runs on **ai-factory-mini** (spark is aarch64 and the package\n has no ARM-Linux wheel), bridged to spark via **SSH-stdio**\n (`command: ssh … uvx lucidlink-mcp`). Read-only + core toolset = **9 tools**:\n `list_filespaces`, `link_filespace`, `current_filespace`, `whoami`, `read_file`,\n `list_files`, `find_files`, `grep_files`, `read_lines`. The `sa_live:` token\n lives in `~/.lucidlink/mcp-config.json` **on the Mac**, never in git.\n- **lucidlink-rw** — read **and** write, confined to the `agenticow` filespace =\n the StrongHold common memory namespace (`/stronghold-mem`). The Mac\n `authorized_keys` forced command pins `LUCIDLINK_FILESPACE=agenticow` **and runs\n the `confine-mcp.py` shim** (ADR-0010), which strips `link_filespace`/\n `list_filespaces` so the key cannot switch to or enumerate any other filespace —\n the include allowlist also drops destructive ops. (The read-only `lucidlink`\n bridge is intentionally *not* shimmed: it browses many filespaces for document\n processing.)\n\n **Per-tenant isolation of memory storage (ADR-0010, 2026-06-30):** each provisioned\n tenant gets its **own** end-to-end-encrypted LucidLink filespace\n (`stronghold-`, separate bucket + keyspace), created by\n `service/provision-tenant.sh` and reached via a dedicated key whose forced command\n runs the same shim pinned to that filespace. `mem-sync` routes a registered tenant's\n export into its own filespace (`tenant-filespaces.json`); an unregistered tenant\n falls back to the `agenticow` `tenants//` subfolder (ADR-0009 logical\n isolation). **Residual:** LucidLink service-account tokens are workspace-admin scope\n (cannot be narrowed per filespace), so the confinement boundary is the shim, not the\n token — a *Mac* compromise (where the token lives) still exposes all filespaces. Full\n token-level isolation awaits LucidLink scoped-token support or a per-tenant workspace.\n\n---\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"45","text":"## 2. Trust boundaries\n\n```\n ── boundary A ── public internet ⇄ Tailscale Funnel ⇄ backend :8771\n only authentication: a valid Bearer JWT. /health is the only unauth route.\n\n ── boundary B ── backend :8771 ⇄ internal service :8770\n only authentication: shared X-API-Key. Not reachable from the internet.\n\n ── boundary C ── internal service ⇄ MCP child processes (ruflo, lucidlink)\n children get a MINIMAL env (no service secrets); lucidlink also crosses\n an SSH-stdio hop to a different host (ai-factory-mini).\n\n ── boundary D ── internal service ⇄ sandbox container (rootless Docker)\n --network none, cap-drop ALL, read-only, non-root; no host FS, no egress.\n Daemon is rootless under the unprivileged `stronghold` user → container\n UID 0 maps to a subuid, so even a container escape gets no host root.\n\n ── boundary E ── internal service ⇄ cloud / configured model backends (opt-in, outbound)\n only on tier:auto-fallback / max / openrouter, or an explicit compat\n slug; local tiers never leave. Compat backends speak only OpenAI\n /v1/chat/completions; their keys + URLs live solely in gitignored\n llm-backends.json (not in the repo).\n```\n\n| # | Boundary | Crossed by | Control |\n|---|---|---|---|\n| A | Internet ↔ backend | Bearer JWT only | JWT verification + per-tenant isolation; TLS via Funnel |\n| B | Backend ↔ internal service | `X-API-Key` | shared key; service not on the Funnel |\n| C | Service ↔ MCP children | minimal env allowlist | no secrets leak to third-party MCP processes |\n| D | Service ↔ sandbox | hardened container flags + rootless daemon | network/cap/FS isolation; escape maps to an unprivileged subuid, not host root |\n| E | Service ↔ cloud / configured LLM backends | per-request / per-config opt-in | local-by-default; egress only on chosen tiers or an explicit compat slug; compat keys + URLs only in gitignored `llm-backends.json` |\n\n---\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"46","text":"## 3. Authentication & multi-tenancy (`backend/server.js`)\n\nPublic auth is **Bearer JWT, algorithm auto-detected from the token header**.\n\n### Asymmetric Supabase (RS/ES/PS)\n\nVerified against the JWKS of the token's **own issuer**\n(`https://.supabase.co/auth/v1`), so **any** of the owner's Supabase\nprojects work with zero config. Tenant key = `\":\"`. The same user UUID\nin two different projects is two isolated tenants.\n\n- **Project allowlist** — `SUPABASE_ALLOWED_REFS` (csv). **Fail closed**: with no\n allowlist set, asymmetric tokens are **rejected** unless `SUPABASE_ALLOW_ANY=1`\n is explicitly set. Issuer shape is constrained by `SUPABASE_ISS_REGEX`.\n- **JWKS serve-last-good** — if the IdP is briefly unreachable, the stale cached\n key is used rather than rejecting every login. (Resilience without failing open\n on identity, since the cached key is the IdP's own published key.)\n\n### HS256\n\nVerified against `JWT_SECRET`; tenant `\"hs:\"`. Intended for the prototype /\nsingle-secret case.\n\n### Isolation\n\n`userId` is the `sub` claim, **never** taken from the request body. Per-tenant\nagent ownership is enforced — a caller can only see/use/delete agents they own;\ncross-tenant access returns **404**. Verified: user B cannot reach user A's agent.\n`GET /health` is the only unauthenticated route.\n\n---\n\n## 4. Security controls (current)\n\nAll four hardening tranches are DONE and verified live (2026-06-29).\n\n### Fail-closed secrets (refuse-to-boot)\n\nBoth tiers refuse to start on a default / weak / missing key:\n\n- Internal service: `API_KEY` is **required, no default**.\n- Backend: `JWT_SECRET` and `INTERNAL_API_KEY` must be **≥ 24 chars**; shorter →\n refuse to boot.\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"47","text":"### Rate limiting & concurrency caps\n\n| Control | Env / default | Behavior |\n|---|---|---|\n| Per-tenant token bucket | `RATE_BURST` `30` capacity, refill `RATE_PER_SEC` `1`/s | heavy ops (`act`/`fanout`/`chat`/`sandbox`) cost `HEAVY_COST` `5` → **429 + Retry-After** |\n| Global heavy-op concurrency | `MAX_INFLIGHT_HEAVY` `4` | 5th simultaneous heavy job across all tenants → **429** |\n| Global sandbox container cap | `SANDBOX_MAX_CONCURRENCY` `4` | sandbox runs queue beyond 4 |\n| Request body limit | `MAX_BODY_BYTES` `1000000` | oversize → **413**; malformed JSON → **400** |\n| Per-request loop budget | `ACT_BUDGET_MS` `180000` wall-clock + `MAX_TOOLCALLS_PER_STEP` `8` | bounds a runaway agent loop |\n\n### Sandbox isolation (`/sandbox/run`, `run_code` tool)\n\nEach run is an ephemeral Docker container: `--network none`, `--cap-drop ALL`,\n`--read-only` rootfs, **non-root**, `/tmp` tmpfs **noexec**, and memory / CPU /\npids / wall-clock limited, `--rm` on exit. Languages: python, node, bash. Public\nRCE-by-design is gated behind the JWT **and** the rate limit, the global heavy-op\ncap, and the global sandbox cap above. `SANDBOX_ENABLED` is a kill switch.\n\nThe sandbox runs on a **rootless Docker daemon** owned by the dedicated\nunprivileged `stronghold` service user (not the rootful host daemon). This is a\ndefence-in-depth layer *under* the container flags: even a full container escape\nlands as one of `stronghold`'s subuids (container UID 0 → host subuid 165536+),\nwith no privilege over host files or the rootful socket. The harness process\nitself cannot reach `/var/run/docker.sock`.\n\n### Minimal MCP child env\n\nMCP children receive only a safe env allowlist (PATH/HOME/…) plus the per-server\n`env` override — **never** the service secrets. Verified: the ruflo child env has\nno `ANTHROPIC` / `OPENROUTER` / `INTERNAL` / `JWT` / `LUCIDLINK` keys. Third-party\nMCP processes therefore cannot exfiltrate model keys or the internal API key.\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"48","text":"### MCP resilience\n\nA dead MCP child (SSH bridge drop, ruflo crash) is detected and\n**auto-respawned with exponential backoff** (1s → 30s cap). `has()`/`call()` are\ngated on `ready`, tools are read live so respawns restore them, and MCP boot is\n**parallel** (servers start concurrently). `/healthz` shows per-server\n`ready`/`restarts`/`lastExit` and goes `degraded` when a server is down.\n\n### Timeouts & failover\n\nEvery model call has a timeout so a hung host triggers failover, not a hang:\n`OLLAMA_TIMEOUT_MS` / `OPENROUTER_TIMEOUT_MS` / `CLOUD_TIMEOUT_MS` default\n`120000`; backend→internal non-stream `INTERNAL_TIMEOUT_MS` `300000`. A GPU\nsemaphore makes fan-out queue instead of dogpiling a single GPU.\n\n### Durability (no \"stored\" lies)\n\nThe append-only durable log is the source of truth. `remember` **flushes to disk\nBEFORE acknowledging** the write (no false \"stored\" 200s). A corrupt durable /\nowners file is backed up to `.corrupt.` and the service **refuses to start**\nrather than silently wiping it. The backend flushes `owners.json` on\nSIGTERM/SIGINT. Restart policy: internal `Restart=on-failure`; backend Docker\n`restart=unless-stopped`.\n\n### Health info-leak closed\n\nUnauthenticated `/healthz` returns only `{status, uptime}`; the detailed\ndiagnostics (base vectors, agent counts, MCP/Ollama internals, etc.) require the\nAPI key. The public backend's `GET /health` returns only `{status, baseVectors,\ninternal}` and is intentionally the one unauthenticated route.\n\n### Secrets handling\n\nSecrets live **only** on the host — `/etc/agentmem-internal.env` and\n`backend/.env` — never in git, never baked into the Docker image. Model keys live\nonly in the internal service. The LucidLink `sa_live:` token lives only on\nai-factory-mini. The OpenAI-compatible backends' API keys and private URLs live\n**only** in the gitignored `llm-backends.json` (and `tier-models.json`) on the\nhost — only the `*.example` templates are committed; the internal service speaks\nnothing but OpenAI `/v1/chat/completions` to those backends.\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"49","text":"### Data-egress matrix\n\n| Request | Leaves the box? | To |\n|---|---|---|\n| memory ops, recall, embeddings | No | local MiniLM-L6 (384-dim) |\n| `/sandbox/run`, `run_code` | No | local Docker |\n| `tier:fast` / `balanced` / `local` chat/act | No | Ollama pool on the cluster |\n| `tier:auto` fallback / `tier:max` | Yes | Anthropic (Claude `claude-opus-4-8`) |\n| `tier:openrouter` / explicit model slug | Yes | OpenRouter |\n| explicit `compat:` slug | Outbound HTTP | configured OpenAI-compatible backend (vLLM / llama.cpp / TGI / Open WebUI) |\n| LucidLink file tools | Stays on cluster | ai-factory-mini over SSH-stdio (read-only) |\n\n---\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"50","text":"## 5. Residual risks (v0.1) — honest mitigations\n\n| # | Risk | Severity | Status / mitigation |\n|---|---|---|---|\n| 1 | **Harness runs as a docker-group user.** An RCE in the harness process *itself* (not the sandbox — the host service) would have Docker socket access, i.e. effectively **host-root**. | ~~High if reached~~ | **MITIGATED 2026-06-29.** The internal service now runs as a dedicated unprivileged user `stronghold` (uid 1001, **not** in the docker group) wired to its **own rootless Docker daemon** (`unix:///run/user/1001/docker.sock`). The harness process is denied the rootful socket, and container UID 0 maps to `stronghold`'s subuid range — powerless on the host. Verified: container-root cannot write a host file (appears as `nobody`), rootful daemon never runs sandbox containers. See OPS_RUNBOOK §\"Rootless sandbox\". |\n| 2 | **Graduation used to promote to a single cross-tenant base.** Deleting / graduating an agent promoted its vetted learnings into one shared base, so graduated content became visible across tenants via `/memory/search`. | ~~Medium~~ | **MITIGATED 2026-06-30.** Graduation is now **per-tenant**: each agent is tagged with its tenant (JWT-derived) on spawn, and `terminateAndGraduate` re-scopes its learnings into a per-tenant durable scope `tbase:` — **never** the global base. A tenant's future agents inherit only `tbase:`, and `/memory/search` recalls over a per-tenant base branch, so no tenant reads another's graduated content. The global agenticow base is now reserved for explicitly-curated shared infra (`addKnowledge`), never fed by auto-graduation. Untagged/legacy agents keep the old global-base behavior. Verified: a new tenant-B agent does not recall tenant-A's graduated secret (in-process + over HTTP), and isolation survives a service restart (rehydrate rebuilds per-tenant bases). |\n| 3 | **Sandboxed RCE is a feature.** `/sandbox/run` and `run_code` execute arbitrary, model-generated code automatically inside the act loop. | Medium (contained) | Strong container hardening (§4) + the global sandbox cap + per-tenant rate limit + `SANDBOX_ENABLED` kill switch. Risk is the container-escape surface, mitigated by `--network none` / `--cap-drop ALL` / read-only / non-root / noexec. |\n| 4 | **Allowlist breadth + cloud spend.** Any user from any allowlisted Supabase project authenticates, and cloud / compat tiers cost money per call. | Medium (cost/abuse) | Per-tenant token bucket + global heavy-op cap now bound abuse rate; keep `SUPABASE_ALLOWED_REFS` tight and avoid `SUPABASE_ALLOW_ANY=1` in production. **Spend is now observable**: token-usage metering (§Token / LLM usage metering) attributes tokens per model / provider (`byProvider` / `byModel` on `/healthz`), pairing with the rate limits / heavy-op caps to make spend visible per backend. **Refinement:** the metering tally is process-global today (not yet per-tenant), and hard spend caps remain a follow-up. |\n| 5 | **Prototype HS256 token.** Long-lived single-secret token, potentially visible in client bundles. | Low–Medium | Rotate `JWT_SECRET` and disable HS256 once all clients use Supabase asymmetric tokens. |\n| 6 | **Credential hygiene.** Keys were entered operationally and live in host env files. | Low | Keys are root-only in host env files and not internet-exposed; rotate at the owner's discretion. Consider a secrets manager if the fleet grows. |\n| 7 | **Service user's SSH key for the LucidLink bridge.** `stronghold` authenticates the SSH-stdio bridge to ai-factory-mini. | ~~Low~~ | **MITIGATED 2026-06-29.** `stronghold` uses its **own** dedicated key (`/home/stronghold/.ssh/id_ed25519_lucidlink`), no longer reusing markt's. The Mac `authorized_keys` entry pins `restrict` + a forced command, so the key can **only** launch the read-only `lucidlink-mcp` bridge — verified that arbitrary commands over this key are ignored. (The temporary ACLs on markt's key were removed.) The write bridges additionally run the `confine-mcp.py` shim (ri","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"51","text":"edicated key (`/home/stronghold/.ssh/id_ed25519_lucidlink`), no longer reusing markt's. The Mac `authorized_keys` entry pins `restrict` + a forced command, so the key can **only** launch the read-only `lucidlink-mcp` bridge — verified that arbitrary commands over this key are ignored. (The temporary ACLs on markt's key were removed.) The write bridges additionally run the `confine-mcp.py` shim (risk #8). |\n| 8 | **LucidLink service-account token is workspace-admin scope.** Tokens cannot be narrowed to one filespace, so a write-bridge key could otherwise `link_filespace` to any tenant's filespace. | ~~Medium~~ | **MITIGATED 2026-06-30 (ADR-0010).** The write bridges' forced command runs `confine-mcp.py`, a stdio shim that strips `link_filespace`/`list_filespaces`, hard-pinning each key to its one filespace — verified a tenant key is refused a cross-filespace link. **Residual:** the token itself remains admin-scope and lives on the Mac, so a *Mac* compromise exposes all filespaces; full token-level isolation awaits LucidLink scoped-token support or a per-tenant workspace. |\n\nNone of these block internal use or a controlled pilot. Risks **(1)**, **(2)**, the\nSSH key **(7)**, and the filespace-confinement **(8)** are now mitigated, and\n**per-tenant *filespace* hard isolation is shipped (ADR-0010)**; **(4)** (allowlist\nbreadth / cloud spend caps) is the main remaining gate before fully open\nmulti-organization production.\n\n---\n\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"52","text":"## 6. Tech & supply chain\n\n- **Node.js 22 (ESM).** Backend: **zero** runtime dependencies\n (`node:http` + `node:crypto`). Internal service: Fastify, `agenticow`,\n `@huggingface/transformers` (MiniLM-L6 embedder, run in a `worker_thread` so\n embeds don't block the event loop; `EMBED_IN_PROCESS=1` forces in-proc with a\n transparent fallback), `@anthropic-ai/sdk`.\n- **Models:** Ollama pool (local), Anthropic SDK (Claude), OpenRouter (HTTP),\n generic OpenAI-compatible backends (HTTP, config-driven via `llm-backends.json`).\n- **Infra:** Docker (backend + sandbox), systemd (internal service), Tailscale\n Funnel (edge), SSH-stdio bridge to ai-factory-mini (LucidLink MCP).\n\n### Ops quick facts\n\n- Internal service: `sudo systemctl {status,restart} agentmem-internal` (runs as\n user `stronghold`, sandboxes via that user's rootless Docker — see OPS_RUNBOOK).\n- Backend: `cd backend && docker compose up -d --build`.\n- Funnel: `sudo tailscale funnel --bg --set-path /agentmem 8771`.\n- LucidLink: needs `uv`/`uvx` + the `sa_live:` token file on ai-factory-mini; the\n persistent SSH bridge must be (re)started **after** the token file exists (the\n MCP server reads the token once at startup).\n\n---\n\n*Status: all four hardening tranches + dual-GPU pool + the docker-privilege\nmigration (risk #1) + the dedicated scope-locked SSH key for the LucidLink bridge\n(risk #7) + **per-tenant graduation/recall isolation (risk #2)** + **per-tenant\nfilespace hard isolation with the confine-mcp shim (risk #8, ADR-0010)** — all\n2026-06-30 — are DONE and verified live. No open hardening items; remaining multi-org\nwork is cloud-spend caps / sign-up controls (#4).*\n","path":"docs/ARCHITECTURE_SECURITY.md","title":"StrongHold — Architecture & Security Brief","source_type":"doc","kind":"doc"} -{"id":"53","text":"# StrongHold deck\n\n`StrongHold.pptx` — the layman/leadership slide deck (18 slides: title + 17),\nmirroring `../EXEC_BRIEF.md`. Two slides are **drawn** diagrams (the \"big-AI-harness\nvs metaharness\" contrast and the live request-path), the rest are content slides.\n\n## Regenerate\n\nThe content is authored **in `build_deck.py`** (not parsed from markdown), so keep\nit in sync with `../EXEC_BRIEF.md` by hand when the brief changes.\n\n```bash\npython3 -m venv .venv && . .venv/bin/activate\npip install python-pptx # 1.0.2 known-good\npython build_deck.py StrongHold.pptx\n# optional: render to PDF to eyeball it\nlibreoffice --headless --convert-to pdf StrongHold.pptx\n```\n\nBrand palette (navy/teal/blue/gray) and layout helpers live at the top of\n`build_deck.py`. Last regenerated 2026-06-30 to reflect the shipped\nread/write LucidLink namespace (ADR-0008) and per-tenant isolation (ADR-0009).\n","path":"docs/deck/README.md","title":"StrongHold deck","source_type":"doc","kind":"doc"} -{"id":"54","text":"# StrongHold — Developer Quickstart\n\n*StrongHold is our Harness as a Service (HaaS).*\n\nA per-user memory + agent API you can call from any app. Local-first models with optional cloud\nescalation; you never name a model unless you want to. Every response reports the `provider` and\n`model` that actually answered.\n\n- **Base URL:** `https://spark-47d8.tail333a1d.ts.net/agentmem/v1`\n- **Auth:** `Authorization: Bearer ` on every call except `GET /health`\n- **Content type:** `application/json`\n- **CORS:** enabled (`*`) — call it directly from a browser app\n\n---\n\n## 1. Get a token\n\n- **Production (per-user):** a **Supabase** session access token. The backend derives the user\n from the token's `sub` claim — each signed-in user is an isolated memory tenant automatically.\n Your project must be on the allowlist (ask the maintainer to add your Supabase project ref).\n- **Prototyping:** an HS256 token signed with the shared `JWT_SECRET` maps everyone to one\n tenant — fine for a demo, not for real multi-user. A drop-in test token is in `backend/LOVABLE.md`.\n\n```ts\n// Lovable / browser\nconst getToken = async () =>\n (await supabase.auth.getSession()).data.session?.access_token ?? \"\";\n```\n\n## 2. 60-second curl\n\n```bash\nBASE=https://spark-47d8.tail333a1d.ts.net/agentmem/v1\nAUTH=\"authorization: Bearer $TOKEN\"; CT=\"content-type: application/json\"\n\nAID=$(curl -s -H \"$AUTH\" -H \"$CT\" -d '{\"agentType\":\"assistant\"}' $BASE/agents | jq -r .agentId)\ncurl -s -H \"$AUTH\" -H \"$CT\" -d '{\"text\":\"Launch is Sept 9.\"}' $BASE/agents/$AID/memories\ncurl -s -H \"$AUTH\" -H \"$CT\" -d '{\"prompt\":\"When is launch?\"}' $BASE/agents/$AID/chat\n```\n\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"55","text":"## 3. Endpoints at a glance\n\n| Method | Path | Body | Returns |\n|---|---|---|---|\n| GET | `/health` | — | `{status, baseVectors, internal}` (no auth) |\n| GET | `/agents` | — | `Agent[]` (yours only) |\n| POST | `/agents` | `{agentType, label?}` | `Agent` |\n| GET | `/agents/{id}` | — | `Agent` |\n| DELETE | `/agents/{id}` | — | graduate result (promotes vetted memories to your base) |\n| POST | `/agents/{id}/memories` | `{text}` | `{ids, count}` |\n| POST | `/agents/{id}/recall` | `{query, k?}` | `MemoryHit[]` |\n| POST | `/agents/{id}/chat` | `{prompt, tier?, recallK?}` | `{text, model, provider, ...}` or SSE |\n| POST | `/agents/{id}/act` | `{prompt, tier?, profile?, tools?, maxSteps?, recallK?}` | `{text, steps[], provider, model}` |\n| POST | `/agents/{id}/fanout` | `{tasks[], tier?, profile?, tools?, agentType?, maxStepsPer?}` | `{results[]}` (≤ 8 parallel) |\n| POST | `/memory/search` | `{query, k?}` | `MemoryHit[]` (your shared base) |\n| POST | `/sandbox/run` | `{language, code, timeoutMs?}` | `{stdout, stderr, exitCode, ...}` |\n\n`Agent = {agentId, agentType, label, status, createdAt}` ·\n`MemoryHit = {id, text, distance, source}` (lower distance = closer; `source` is `'base'` or an agentId)\n\n## 4. Agents (CRUD)\n\n```bash\n# create — agentType is any string; label is optional\ncurl -s -H \"$AUTH\" -H \"$CT\" -d '{\"agentType\":\"assistant\",\"label\":\"support-bot\"}' $BASE/agents\n# list yours\ncurl -s -H \"$AUTH\" $BASE/agents\n# get one\ncurl -s -H \"$AUTH\" $BASE/agents/$AID\n# delete — GRADUATES vetted memories into your shared base (see §10)\ncurl -s -X DELETE -H \"$AUTH\" $BASE/agents/$AID\n```\n\nAgents are owned by your tenant; another tenant's agentId resolves to `404`.\n\n## 5. Memories — `remember` & `recall`\n\n```bash\n# remember — store text on an agent's private memory.\n# Durable: the call doesn't return 2xx until it's flushed to disk (no \"stored\" lies).\ncurl -s -H \"$AUTH\" -H \"$CT\" -d '{\"text\":\"Customer prefers email over phone.\"}' \\\n $BASE/agents/$AID/memories\n\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"56","text":"# recall — semantic search of THIS agent's memory (+ your base), k results\ncurl -s -H \"$AUTH\" -H \"$CT\" -d '{\"query\":\"how to contact the customer\",\"k\":5}' \\\n $BASE/agents/$AID/recall\n```\n\n`/memory/search` is the same idea but searches only **your tenant's base** (your graduated\nmemories — never another tenant's), not a specific agent:\n\n```bash\ncurl -s -H \"$AUTH\" -H \"$CT\" -d '{\"query\":\"launch date\",\"k\":5}' $BASE/memory/search\n```\n\n## 6. `act` — the agentic loop (with tier + tools)\n\n`/act` runs a recall → think → call tools → feed results back → answer loop. It can **write & run\ncode** in the secure sandbox (`python`/`node`/`bash`, no network), call memory tools (`recall_memory`,\n`remember`), and use connected external MCP tools. The response carries a `steps[]` trace of every\ntool call plus the `provider`/`model` that answered.\n\n```bash\ncurl -s -H \"$AUTH\" -H \"$CT\" -d '{\n \"prompt\": \"Compute the 20th Fibonacci number and remember it.\",\n \"tier\": \"auto\",\n \"profile\": \"code\",\n \"maxSteps\": 6\n}' $BASE/agents/$AID/act\n```\n\nKnobs:\n- `tier` — model routing, see §9.\n- `profile` / `tools` — per-task tool selection, see §8.\n- `maxSteps` — cap on tool-using iterations.\n- `recallK` — how many memories to inject up front.\n\n## 7. `fanout` — parallel sub-agents\n\nUp to **8** ephemeral workers run tasks in parallel, results aggregated, then dismissed (fan-out\nworkers do **not** graduate memory). `tier` / `profile` / `tools` set defaults for the batch; each\ntask can also be an object that overrides `prompt`, `tools`, and `profile` per task.\n\n```bash\ncurl -s -H \"$AUTH\" -H \"$CT\" -d '{\n \"tier\": \"auto\",\n \"profile\": \"research\",\n \"tasks\": [\n \"Summarize our Q3 launch plan.\",\n { \"prompt\": \"List the open files for the redesign.\", \"profile\": \"files\" },\n { \"prompt\": \"Sanity-check this regex in code.\", \"tools\": [\"run_code\"] }\n ],\n \"agentType\": \"worker\",\n \"maxStepsPer\": 4\n}' $BASE/agents/$AID/fanout\n```\n\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"57","text":"## 8. Per-task tool selection (`profile` / `tools`)\n\nBy default a task may use **all** tools (back-compat). To scope it, pass either a named `profile`\nor an explicit `tools` allowlist. Selection is enforced in two layers: it filters the tools\n*offered* to the model AND blocks them at dispatch — a call to a non-permitted tool returns\n\"not permitted\".\n\n**`tools` allowlist syntax** — an array of: bare built-in names (e.g. `\"run_code\"`,\n`\"recall_memory\"`, `\"remember\"`), namespaced MCP tools `\"__\"` (e.g.\n`\"lucidlink__grep_files\"`), or `\"*\"` wildcard.\n\n**Built-in `profile` names** (defined in `tool-profiles.json`, merged over defaults):\n\n| `profile` | What it allows |\n|---|---|\n| `all` | every tool (same as omitting) |\n| `memory` | memory tools only (recall / remember) |\n| `code` | the code sandbox |\n| `files` | LucidLink filespace tools (`lucidlink__*`) |\n| `research` | research-oriented bundle |\n| `lucid-readonly` | read-only LucidLink access |\n\nDiscover what's wired up: **`GET /tools`** returns `builtin`, `mcp` (per-server), `available`\n(all tool names you can put in `tools`), and `profiles`.\n\n> **LucidLink filespace tools** let an agent read & search your team's LucidLink files\n> (`list_filespaces`, `read_file`, `list_files`, `find_files`, `grep_files`, `read_lines`, …),\n> exposed as `lucidlink__*` and read-only. Use `profile: \"files\"` or `\"lucid-readonly\"` to enable them.\n\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"58","text":"## 9. The `tier` knob (model routing)\n\nOptional on `chat` / `act` / `fanout`. One knob picks an ordered provider preference; the router\nfails over on error/timeout. You never have to name a model.\n\n| `tier` | Provider order | Meaning |\n|---|---|---|\n| `fast` / `balanced` / `local` | local | on-prem Ollama (`qwen2.5-coder:32b`) — free, private |\n| *(omitted)* / `auto` | local → cloud → openrouter | **default**: local first, escalate if needed |\n| `max` | cloud → openrouter → local | best reasoning (Claude), cloud-first |\n| `openrouter` | openrouter → local | OpenRouter (GPT/Gemini/Llama/…), local fallback |\n\n`local` is load-balanced across both DGX Spark GPUs. `cloud` (Claude `claude-opus-4-8`) is only\navailable when the host has an Anthropic key configured; otherwise those tiers resolve to local.\n\nPower user: pass an explicit `vendor/model` slug as `model` (e.g.\n`{ \"model\": \"google/gemini-2.0-flash\" }`) to target a specific OpenRouter model (keeps local as\nfailover). The response always reports the actual `provider` + `model`.\n\n## 10. `chat` — recall-augmented chat (+ SSE streaming)\n\n`/chat` recalls relevant memory, injects it, and answers. Non-streaming returns JSON. For live\ntokens, send `Accept: text/event-stream` and read the SSE stream — but you **cannot** use the\nbrowser `EventSource` API because it can't attach the `Authorization` header. Use `fetch` + a\nstream reader instead:\n\n```ts\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"59","text":"async function streamChat(base: string, token: string, agentId: string, prompt: string,\n onToken: (t: string) => void) {\n const res = await fetch(`${base}/agents/${agentId}/chat`, {\n method: \"POST\",\n headers: {\n authorization: `Bearer ${token}`,\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n },\n body: JSON.stringify({ prompt, tier: \"fast\" }),\n });\n const reader = res.body!.getReader();\n const dec = new TextDecoder();\n let buf = \"\";\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buf += dec.decode(value, { stream: true });\n const events = buf.split(\"\\n\\n\");\n buf = events.pop() ?? \"\";\n for (const ev of events) {\n const line = ev.split(\"\\n\").find((l) => l.startsWith(\"data:\"));\n if (!line) continue;\n const data = line.slice(5).trim();\n if (data === \"[DONE]\") return;\n try { onToken(JSON.parse(data).token ?? \"\"); } catch {}\n }\n }\n}\n```\n\nStreaming is local-model only.\n\n## 11. `sandbox/run` — the code sandbox directly\n\nRun code without the agent loop. Hardened ephemeral Docker container: `--network none`,\n`--cap-drop ALL`, `--read-only` rootfs, non-root, `/tmp` tmpfs `noexec`, memory/CPU/pids/time\nlimited. Languages: `python`, `node`, `bash`.\n\n```bash\ncurl -s -H \"$AUTH\" -H \"$CT\" -d '{\n \"language\": \"python\",\n \"code\": \"print(sum(range(100)))\",\n \"timeoutMs\": 5000\n}' $BASE/sandbox/run\n# -> {stdout:\"4950\\n\", stderr:\"\", exitCode:0, ...}\n```\n\n## 12. Drop-in TypeScript client\n\n```ts\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"60","text":"export class StrongHold {\n constructor(\n private base = \"https://spark-47d8.tail333a1d.ts.net/agentmem/v1\",\n private getToken: () => Promise = async () => \"\",\n ) {}\n\n private async req(path: string, body?: unknown, method = \"POST\") {\n const res = await fetch(`${this.base}${path}`, {\n method: body || method !== \"GET\" ? method : \"GET\",\n headers: {\n authorization: `Bearer ${await this.getToken()}`,\n \"content-type\": \"application/json\",\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);\n return res.json();\n }\n\n createAgent(agentType = \"assistant\", label?: string) {\n return this.req(\"/agents\", { agentType, label });\n }\n listAgents() { return this.req(\"/agents\", undefined, \"GET\"); }\n getAgent(id: string) { return this.req(`/agents/${id}`, undefined, \"GET\"); }\n deleteAgent(id: string) { return this.req(`/agents/${id}`, undefined, \"DELETE\"); }\n\n remember(id: string, text: string | string[]) {\n return this.req(`/agents/${id}/memories`, { text });\n }\n recall(id: string, query: string, k = 5) {\n return this.req(`/agents/${id}/recall`, { query, k });\n }\n searchBase(query: string, k = 5) { return this.req(\"/memory/search\", { query, k }); }\n\n // tier: fast | balanced | local | auto | max | openrouter\n // profile: all | memory | code | files | research | lucid-readonly\n act(id: string, prompt: string, opts: {\n tier?: string; profile?: string; tools?: string[]; maxSteps?: number; recallK?: number;\n } = {}) {\n return this.req(`/agents/${id}/act`, { prompt, ...opts });\n }\n fanout(id: string, tasks: (string | { prompt: string; tools?: string[]; profile?: string })[],\n opts: { tier?: string; profile?: string; tools?: string[]; agentType?: string;\n maxStepsPer?: number } = {}) {\n return this.req(`/agents/${id}/fanout`, { tasks, ...opts });\n }\n chat(id: string, prompt: string, opts: { tier?: string; recallK?: number } = {}) {\n return this.req(`/agents/${id}/chat`, { prompt, ...opts });\n }\n runCode(language: \"python\" | \"node\" | \"bash\", code: string, timeoutMs?: number) {\n return this.req(\"/sandbox/run\", { language, code, timeoutMs });\n }\n tools() { return this.req(\"/tools\", undefined, \"GET\"); }\n}\n```\n\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"61","text":"## 13. Gotchas\n\n- **Streaming:** use `fetch` + a stream reader with `Accept: text/event-stream`, **not**\n `EventSource` (no auth header). Streaming is local-model only. See §10.\n- **Your tenant base:** deleting an agent *graduates* its memories into **your tenant's** base\n (scope `tbase:`), which `/memory/search` reads and your future agents inherit. Raw\n private memories stay per-agent; graduated ones are shared **only within your tenant** — never\n with other tenants. (A separate global base holds explicitly-curated cross-tenant infra only.)\n- **Latency:** the local 32B model takes ~20–30 s per step; `tier:\"max\"`/`openrouter` (cloud)\n are faster. Multi-step `/act` and `fanout` are correspondingly slower on local.\n- **Rate limits:** heavy ops (act/fanout/chat/sandbox) cost more from your token bucket; expect\n `429` + `Retry-After` under burst, and `413` on bodies over ~1 MB.\n\n## 14. Use StrongHold from Claude Code (MCP)\n\nStrongHold ships a **stdio MCP server** (`service/mcp-stronghold.js`, zero-dependency)\nthat exposes the public API as native tools to Claude Code or any MCP client. It is the\nmirror image of §12 in `HARNESS.md`: there StrongHold is an MCP *client* (it consumes\nLucidLink/ruflo); here StrongHold is an MCP *server*.\n\n**One-time setup** (on the host, or any box that can reach the backend):\n\n```bash\n# 1. Mint a token + write the config file (~/.stronghold/mcp.json, chmod 600).\n# Reads JWT_SECRET from backend/.env at runtime — never prints it.\nnode service/mint-stronghold-token.mjs --url http://localhost:8771 --agent-type researcher\n# (off-box: --url https://spark-47d8.tail333a1d.ts.net/agentmem/v1)\n\n# 2. Register the server with Claude Code (user scope = all projects).\nclaude mcp add stronghold --scope user -- node /ABS/PATH/service/mcp-stronghold.js\n\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"62","text":"# 3. Confirm.\nclaude mcp list # -> stronghold ... ✔ Connected\n```\n\n> New MCP servers become callable (`mcp__stronghold__*`) **after a session reload/restart**.\n\n**Tools** (12): `stronghold_health`, `stronghold_list_agents`, `stronghold_spawn_agent`,\n`stronghold_delete_agent`, `stronghold_remember`, `stronghold_recall`,\n`stronghold_memory_search`, `stronghold_chat`, `stronghold_act`, `stronghold_fanout`,\n`stronghold_run_code`, `stronghold_usage` (per-session token totals + per-tool breakdown,\nclient-side — see §15). The memory/chat/act tools take an **optional** `agentId`; omit it\nand the server lazily spawns one default agent and caches its id (zero-config).\n\n**Config** (`~/.stronghold/mcp.json`, or override per key with env vars):\n\n| Key | Env override | Meaning |\n|---|---|---|\n| `url` | `STRONGHOLD_URL` | Public backend base (default `http://localhost:8771`) |\n| `token` | `STRONGHOLD_JWT` | Bearer JWT (per-tenant) |\n| `agent` | `STRONGHOLD_AGENT` | Default agentId (auto-cached on first use) |\n| `defaultAgentType` | `STRONGHOLD_DEFAULT_AGENT_TYPE` | Type for the lazily-spawned agent |\n| — | `STRONGHOLD_CONFIG` | Alternate config-file path |\n\nThe minted token uses the **HS256 prototype tenant** (`hs:`) — it bypasses the\nSupabase allowlist and is invalidated if `JWT_SECRET` is rotated. Remove the server with\n`claude mcp remove stronghold -s user`.\n\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"63","text":"### 14.1 Auto-memory hooks (StrongHold \"kicks on\" automatically)\n\nThe MCP makes the tools *available*; these optional hooks make Claude Code *use* memory\non its own — no need to remember to call the tools. The helper **`service/sh-memory.mjs`**\ntalks to the same backend over HTTP (hooks can't call MCP tools) and reads the same\n`~/.stronghold/mcp.json` token, so **it writes to your own tenant automatically** — each\ncolleague's notes stay isolated to their tenant (and, if that tenant has a provisioned\nfilespace, ride mem-sync into it).\n\nWhat it does:\n- **SessionStart** → recalls notes relevant to the current project, injects them as context.\n- **SessionEnd** → a *detached* worker distills up to 5 durable takeaways via your **local**\n model tier and stores them. Non-blocking; skips trivial sessions.\n\nBoth are **fail-safe**: no token / backend down / any error → exit 0 with no output, so a\nhook never blocks or breaks a session. All notes go to one long-lived per-tenant\n`claude-code-notes` agent (used for both recall and remember).\n\nSetup:\n```bash\n# 1. Install the helper (it's standalone Node; needs your ~/.stronghold/mcp.json token).\nmkdir -p ~/.stronghold && cp service/sh-memory.mjs ~/.stronghold/sh-memory.mjs\n\n# 2. Add two hooks to your GLOBAL settings (~/.claude/settings.json), under \"hooks\".\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"64","text":"# Replace the node path with `which node` on your machine.\n```\n```jsonc\n\"SessionStart\": [\n { \"hooks\": [\n { \"type\": \"command\",\n \"command\": \"/path/to/node ~/.stronghold/sh-memory.mjs session-start\",\n \"timeout\": 8000, \"statusMessage\": \"Loading StrongHold memory…\" } ] }\n],\n\"SessionEnd\": [\n { \"hooks\": [\n { \"type\": \"command\",\n \"command\": \"/path/to/node ~/.stronghold/sh-memory.mjs remember\",\n \"timeout\": 8000, \"statusMessage\": \"Saving session takeaways to StrongHold…\" } ] }\n]\n```\nMerge into existing `SessionStart`/`SessionEnd` arrays rather than replacing them. Hooks\ntake effect on the next session. To disable, delete the two entries (or open `/hooks`).\nPer-prompt recall is intentionally omitted (latency/noise); `sh-memory.mjs recall` exists\nif you want to wire a `UserPromptSubmit` hook yourself.\n\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"65","text":"## 15. Token & usage metering\n\nEvery model call's token usage is captured from the provider and normalized to\n`{input, output, total}`, so you can see exactly how many tokens each model / provider / tool\nburned — local (free/sovereign) vs cloud (paid) spend, with no external dashboard.\n\n**Per call.** `chat` / `act` / `fanout` responses now carry a `usage` block. For `act` and\n`fanout` it is **summed** across every model call in the agentic loop / across all sub-agents:\n\n```jsonc\n// POST /agents/{id}/chat\n{\n \"text\": \"Launch is Sept 9.\",\n \"provider\": \"ollama\",\n \"model\": \"qwen2.5-coder:32b\",\n \"usage\": { \"input\": 56, \"output\": 5, \"total\": 61 }\n}\n```\n\n**Cumulative (process-wide).** The internal service `GET /healthz` reports `usageTotals` since\nprocess start, broken down by provider and by model:\n\n```jsonc\n// GET /healthz (internal service)\n\"usageTotals\": {\n \"totals\": { \"input\": 1234, \"output\": 890, \"total\": 2124, \"calls\": 7 },\n \"byProvider\": { \"ollama\": { \"input\": 600, \"output\": 61, \"total\": 661, \"calls\": 4 } },\n \"byModel\": { \"deepseek-r1:32b\": { \"input\": 44, \"output\": 557, \"total\": 601, \"calls\": 1 } }\n}\n```\n\n**Per session (MCP).** From Claude Code, call **`stronghold_usage`** for this session's running\ntotals plus a per-tool breakdown — it's client-side bookkeeping, no backend round-trip.\n\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"66","text":"## 16. Routing to more models & backends\n\nStrongHold is no longer pinned to one local model + cloud. Beyond the `tier` knob (§9), pass an\nexplicit `model` to route by **what the model is** — an explicit `model` always wins over tier\nordering:\n\n| `model` form | Routes to | Example |\n|---|---|---|\n| bare model name | the **Ollama pool** (a host that actually has it) | `\"deepseek-r1:32b\"` |\n| `\"/\"` | a registered OpenAI-compatible backend (below) | `\"webui/llama3.1:70b\"` |\n| `vendor/model` OpenRouter slug | OpenRouter (see §9) | `\"google/gemini-2.0-flash\"` |\n\nExtra models already loaded on the cluster Ollamas (`deepseek-r1:32b`, `qwen2.5:32b`,\n`llama3.1:70b`, …) are reachable + metered **by name with zero config** — just name them.\n\nYou can also map a bare `tier` to a specific cluster model with **tier→model aliases** in\n`tier-models.json`, e.g. `{\"reason\":\"deepseek-r1:32b\",\"big\":\"webui/llama3.1:70b\"}`. Compat\nbackends are metered under provider label `compat:`; `healthz.router` reports `compat`\n(the backend names) and `tierModels`.\n\n### 16.1 Add an OpenAI-compatible backend\n\nRegister any OpenAI-compatible server (vLLM, `llama.cpp --server`, TGI, Open WebUI, LM Studio):\n\n```bash\n# 1. Copy the committed template and fill it in (this file is GITIGNORED — it holds keys/URLs).\ncp llm-backends.json.example llm-backends.json\n```\n```jsonc\n// llm-backends.json — an array of named backends\n[\n { \"name\": \"webui\", \"url\": \"http://10.0.1.x:3000/v1\",\n \"apiKey\": \"Bearer sk-...\", // Open WebUI requires a Bearer key\n \"models\": [\"llama3.1:70b\"] } // optional hint; omit to allow any\n]\n```\n```bash\n# 2. (optional) tier->model aliases.\ncp tier-models.json.example tier-models.json\n\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"67","text":"# 3. Restart the internal service so it reloads config.\nsudo systemctl restart agentmem-internal\n```\n\nThen target it with an explicit slug: `{ \"model\": \"webui/llama3.1:70b\" }`.\n\n- **Env alternatives** (instead of the files): `LLM_BACKENDS` (inline JSON array) or\n `LLM_BACKENDS_CONFIG` (path); `TIER_MODELS` (inline JSON) or `TIER_MODELS_CONFIG` (path).\n Optional `COMPAT_TIMEOUT_MS` (default `120000`) bounds compat backend calls.\n- Only the `*.example` templates are committed; your real `llm-backends.json` /\n `tier-models.json` are gitignored.\n- **Backward compatible:** empty config = exactly the prior behavior (tier order unchanged;\n `model` only changes routing when you supply one).\n\n## 17. More\nDrop-in TypeScript client + the paste-into-Lovable prompt: **`backend/LOVABLE.md`**.\nFull system reference: **`docs/HARNESS.md`**.\n","path":"docs/DEVELOPER_QUICKSTART.md","title":"StrongHold — Developer Quickstart","source_type":"doc","kind":"doc"} -{"id":"68","text":"# StrongHold — Executive Brief\n\n*StrongHold is our Harness as a Service (HaaS).*\n\n**One line:** A private AI-agent platform that runs entirely on hardware we already\nown — giving us the capabilities of a commercial cloud \"AI agent service\" without\nsending our data, our code, or our customers' information to a third party.\n\n---\n\n## The idea\n\nEvery modern AI product is built on a *harness* — the software around an AI model that\nlets it actually do work: remember things, use tools, run code, and take multi-step\nactions. Today most companies rent that harness from the big AI labs and run it inside\nthe labs' cloud, paying per use and trusting an outside vendor with their data.\n\nStrongHold is not merely our own copy of that harness — it is a **metaharness**: a layer\nthat sits *above* the AI vendors and treats each one (our own on-premise model, Claude,\nGPT, Gemini, and others) as an interchangeable part. The big labs build a harness *for\ntheir model*, with their model at the center — by design, to keep you on it. StrongHold\nputs the **orchestration** at the center and demotes every model to a swappable component\nwe choose per task. Same capabilities — **owned end to end, data kept local, and beholden\nto no single vendor.**\n\n## Why it matters\n\n| | Rented cloud harness | StrongHold |\n|---|---|---|\n| **Data** | Sent to a vendor's cloud | Stays on our hardware by default |\n| **Cost** | Metered per use, indefinitely | Fixed hardware we already own; cloud models optional |\n| **Lock-in** | Tied to one vendor's models | Any model — our own, Claude, or others — swappable |\n| **Control** | Vendor sets the rules | We own the stack, the memory, and the data |\n\n","path":"docs/EXEC_BRIEF.md","title":"StrongHold — Executive Brief","source_type":"doc","kind":"doc"} -{"id":"69","text":"## Two things only StrongHold has\n\nMost of what StrongHold does, a rented cloud harness can also do. Two things it\n**structurally cannot**, and they are the moat:\n\n1. **It's a metaharness — it orchestrates the orchestrators.** A rented harness can run\n *its own* model and *its own* tools. StrongHold runs *any* model and absorbs *entire\n other AI systems* as interchangeable parts behind one interface, choosing the cheapest\n model that's good enough for each task and falling over to another vendor mid-job if\n one fails. The big labs can't copy this — their business depends on their model being\n the center, not a swappable part. We are the layer that makes *their* product one of\n *our* backends.\n\n2. **One shared source of truth across every agent, everywhere — on LucidLink.** This is\n the part we have badly undersold. LucidLink is a single, global, streaming filesystem:\n every agent — on either Spark, on the Mac, at the Florida or California sites — reads\n and writes the **same** files, instantly, with no copying and no \"which version is\n right?\" Our agents are short-lived by design; the *truth* can't live inside any one of\n them. On LucidLink it lives in one durable, versioned, shared place that no single\n agent owns and that outlives all of them. That gives us something a rented memory\n store fundamentally isn't: **one canonical memory for the whole fleet**, that we own,\n that streams on demand (so no machine has to hold the whole corpus), and that we never\n pay a vendor to replicate or query. The metaharness is the brain; **LucidLink is the\n shared, sovereign memory all the brains agree on.**\n\n","path":"docs/EXEC_BRIEF.md","title":"StrongHold — Executive Brief","source_type":"doc","kind":"doc"} -{"id":"70","text":"## The economics\n\nThe headline isn't \"it's cheaper.\" It's that StrongHold **inverts the cost curve**:\n\n- **We already paid for the hardware (capex is sunk); every extra agent run is then\n essentially free** — the marginal cost of a local request is electricity, not a\n per-token fee. A rented harness is pure ongoing cost that scales *up* with success: the\n more value you get from it, the more you pay, forever.\n- **The cost gap is widest exactly where the value is highest.** A one-shot chat is cheap\n to rent. An *agent* that reasons over many steps and fans out to sub-agents makes dozens\n of model calls per task — and a rented harness meters every one. Those agentic\n workloads, the valuable ones, are where renting hurts most and where owning the GPUs\n flips the math.\n- **Cloud is opt-in and surgical.** The default path is our free on-premise model. We pay\n premium frontier prices *only* on the specific requests that ask for \"best.\" So we get a\n blended cost — free for the routine 90%, premium for the 10% that earns it — instead of\n paying a premium price for 100% of calls.\n- **The whole memory layer is free.** Embeddings, search, and recall run on-device. On a\n rented stack each of those is separately metered (per-embedding, per-vector stored,\n per-query). With LucidLink + our own object storage, one canonical copy streams to every\n agent — we don't pay to duplicate, sync, or query memory across machines or sites.\n- **No lock-in means pricing power.** Because models are swappable, no vendor can raise\n prices on us without us routing around them. The metaharness is itself a cost-control\n engine: it spends frontier dollars only where they pay for themselves.\n- **It resells with real margin.** Because the marginal cost of serving a tenant is near\n zero, a product built *on* StrongHold has gross margins limited only by hardware we've\n already bought. A competitor reselling a rented harness has the vendor's per-token fee as\n a permanent floor under their costs.\n\n","path":"docs/EXEC_BRIEF.md","title":"StrongHold — Executive Brief","source_type":"doc","kind":"doc"} -{"id":"71","text":"## What it runs on\n\nStrongHold runs on two NVIDIA DGX Spark supercomputers that we already own. The\neveryday AI work is handled by our own on-premise model at zero per-use cost. By\ndefault, **no data leaves our hardware** — a credible, concrete answer to the question\nevery customer and partner eventually asks: *\"Where does our data go?\"*\n\n","path":"docs/EXEC_BRIEF.md","title":"StrongHold — Executive Brief","source_type":"doc","kind":"doc"} -{"id":"72","text":"## What's new\n\nThis release moves StrongHold from a working prototype to a resilient, shareable\nplatform. The headline additions:\n\n- **Double the horsepower from hardware we already own.** StrongHold now uses *both*\n DGX Spark machines together as a single pool, running two AI jobs at the same time —\n one on each — for roughly **2× the throughput** with no new hardware spend. If one\n machine is busy or briefly unavailable, work automatically shifts to the other.\n\n- **The agents can now work over our own files.** StrongHold can securely read the\n team's existing LucidLink files — searching, reading, and reasoning over documents we\n already control. The connection is **read-only** (it cannot change or delete files),\n and the file content stays inside our environment.\n\n- **Hardened for resilience — it heals itself.** Connections and helper services that\n drop are detected and automatically restarted. Every AI request has a time limit, so\n a stuck machine triggers an automatic switch to a backup rather than hanging. If all\n of our local capacity is occupied, StrongHold can **automatically fail over to a\n cloud model** to keep responding — then return to local-first by default. Memory is\n written to disk before anything is reported as \"saved,\" so a restart never loses or\n silently corrupts data.\n\n- **Hardened for security.** Each customer gets their own **usage limits** so no single\n tenant can overwhelm the system. The platform **refuses to start** with a weak or\n missing security key (it \"fails closed\" instead of running insecurely). Any code the\n agents run executes in a **locked-down sandbox** — no network access, no special\n privileges, strict time and memory limits. And our sensitive credentials are kept\n away from the helper tools: **no third-party component ever receives our API keys.**\n The platform itself now runs **with no special privileges on the host machine** — so\n even a full compromise of the agent process or its sandbox cannot take over the\n underlying computer. The connection to our own files runs over a **single-purpose,\n locked-down key** that can do nothing but read those files.\n\n- **Cost visibility, built in — see every token as it's spent (2026-06-30).** StrongHold\n now meters every AI call and shows exactly how many tokens each model, provider, and\n tool consumed — broken out **live by backend**, so the free, sovereign on-premise work\n and the paid cloud spend are visible side by side, in real time, with no external\n dashboard or third-party billing tool. Cost attribution is now a property of the\n platform itself, not something we reconstruct after the fact.\n\n- **Any model on the cluster, swappable by configuration (2026-06-30).** StrongHold is no\n longer pinned to a single local model plus cloud. It now routes to *any* model running\n on our cluster — including more, larger, or specialized local models — and is wired to\n reach *any* standard (\"OpenAI-compatible\") inference engine, all selectable by\n configuration with **no code change**. The extra local models are live and metered\n today; the additional outside engines are wired and ready, awaiting only their access\n keys. Combined with the metering above, every backend we add arrives with its\n usage and cost already visible.\n\n- **Shareable with colleagues.** StrongHold is multi-tenant and sits behind a sign-in,\n so colleagues can each be given their own isolated workspace on the same shared\n platform, with their data walled off from everyone else's.\n\n","path":"docs/EXEC_BRIEF.md","title":"StrongHold — Executive Brief","source_type":"doc","kind":"doc"} -{"id":"73","text":"## What it can do today\n\n- **Remembers** — persistent, per-user memory that survives restarts; each user's data\n is isolated from the rest.\n- **Converses** — answers questions grounded in that memory.\n- **Acts** — autonomous agents that can write and run code in the secure sandbox to\n complete real tasks, not just chat.\n- **Connects** — plugs into our own tools and files (including LucidLink) to do useful\n work over data we already own.\n- **Chooses the right model** — uses our private on-premise model by default, and can\n escalate to top-tier cloud models on demand, with automatic fallback if one is\n unavailable. The user simply asks for \"fast\" or \"best\" and never has to pick a model.\n Behind that simple choice, the pool of models it can reach is now open-ended: any model\n on our cluster and any standard inference engine we wire in, swappable by configuration.\n- **Shows what it costs** — every call is metered, so token usage is visible per model,\n provider, and tool in real time, making the free local vs. paid cloud spend plain as\n you work.\n\n","path":"docs/EXEC_BRIEF.md","title":"StrongHold — Executive Brief","source_type":"doc","kind":"doc"} -{"id":"74","text":"## Strategic value\n\n1. **A real moat — the metaharness.** We don't own a model; we own the *layer above the\n models*. That's the durable, defensible asset competitors who only rent the cloud\n can't replicate, because their whole model depends on keeping their model at the center.\n2. **One sovereign memory for the whole fleet — LucidLink.** Every agent, on every\n machine and site, shares one canonical, streaming, versioned source of truth that we\n own. This is both a capability no rented memory store offers and a cost advantage (no\n replication, no per-query fees).\n3. **Inverted cost curve** — sunk hardware means near-zero marginal cost per agent run;\n paid cloud models are opt-in per request. Costs fall as volume grows, instead of\n rising with it.\n4. **Privacy & sovereignty** — a credible answer to \"where does our data go?\": *nowhere\n it doesn't have to.*\n5. **More value from owned assets** — the dual-machine capability roughly doubles\n throughput from the cluster we already paid for, at zero new spend.\n6. **No lock-in = pricing power** — we adopt the best (or cheapest-adequate) model from\n any vendor without re-platforming, and route around price hikes.\n\n## Status\n\n- **Live** and serving requests over a secure connection, on our own hardware.\n- All major resilience and security improvements above are **done and verified live**.\n- As of **2026-06-30**, built-in cost metering (per model, provider, and tool) and routing\n to additional models on the cluster are **live and verified**; the path to outside\n inference engines is wired and awaits only their activation keys.\n- **Multi-tenant** — designed to sit behind a customer-facing app (currently wired to a\n Lovable frontend) with per-user isolation. As of 2026-06-30 each tenant's *learned*\n knowledge is also isolated: what one workspace teaches the system stays private to that\n workspace; only explicitly-curated shared knowledge is common. Each tenant's memory also\n lands in its own folder in the shared storage namespace.\n\n","path":"docs/EXEC_BRIEF.md","title":"StrongHold — Executive Brief","source_type":"doc","kind":"doc"} -{"id":"75","text":"## Before a broad external rollout (known next steps)\n\nThis is an early but genuinely working platform, and the previously-flagged knowledge-sharing\ngap is now closed (learned knowledge is per-tenant). Two items remain before exposing it\n*widely* (neither blocks internal use or a pilot): (1) tightening who can sign up and adding\nspend caps on the paid AI tiers — the per-model and per-tenant cost visibility those caps\nbuild on is now in place, so this narrows to enforcing limits on top of numbers we already\ntrack; and (2) the strongest form of storage isolation — giving each\ncustomer their **own** encrypted storage space rather than a shared one partitioned by folder —\nwhich we can provision through the workspace gateway we already built.\n\n---\n*Internal document. Contains no customer data. Technical and operational details are\navailable in the companion Developer, Architecture & Security, and Operations\ndocuments.*\n","path":"docs/EXEC_BRIEF.md","title":"StrongHold — Executive Brief","source_type":"doc","kind":"doc"} -{"id":"76","text":"# StrongHold — System Documentation\n\n*StrongHold — a Personal Harness as a Service (HaaS).*\n\n**Status:** live on `spark-47d8` · **Public API:** `https://spark-47d8.tail333a1d.ts.net/agentmem/v1`\n**Last updated:** 2026-06-29\n\n> This is the MASTER reference for the whole system: what it is, how it's built, what it does,\n> how to use it, and how to operate it. It is intentionally complete and is the superset every\n> other doc is derived from — audience-specific handouts (the Lovable quickstart in\n> `backend/LOVABLE.md`, a one-page exec brief, an ops runbook) are subsets of this.\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"77","text":"## 1. What it is\n\n**StrongHold** is a **sovereign, memory-centric AI-agent *metaharness***, served as an API, running\nentirely on the owner's own hardware (two NVIDIA DGX Spark supercomputers). A \"harness\" (per Dan\nCleary's *Harness as a Service*) is everything around a model that lets it do real work: the agent\nloop, tool runtime, sandbox, memory, session/auth, and model routing. The labs (Anthropic, OpenAI,\nCursor) sell a *managed* harness in their cloud — a harness built *for their model*, with their\nmodel at the center.\n\n**StrongHold is a metaharness: it orchestrates the orchestrators.** The model, the tool runtime,\nthe sandbox, the memory backend, and even whole external agent frameworks (ruflo/claude-flow over\nMCP) are interchangeable leaves. The orchestration sits *above* them, and every model is a\nswappable commodity chosen per request. A harness orchestrates tool calls; a metaharness\norchestrates harnesses. (See §1a.) StrongHold is the same capability set as a rented \"AI agent\nservice\" — **owned end-to-end, with data kept local, and beholden to no single vendor**:\n\n- **Sovereign** — runs on DGX Spark hardware; inference goes to a local LLM pool over the cluster\n network; data never leaves your hardware unless a request explicitly opts into a cloud model.\n- **Metaharness / model-agnostic** — local model by default; Claude and OpenRouter\n (GPT/Gemini/Llama/…) are opt-in tiers with automatic failover. The model is a leaf, not the\n center.\n- **Memory-centric, with a fleet-wide source of truth** — persistent, per-tenant, branchable\n memory is the centerpiece; LucidLink provides one shared, sovereign source of truth across every\n agent and site (see §4.5).\n- **Multi-tenant** — per-user isolation via JWT, designed to back a Lovable (or any) frontend.\n\nRepo root on host: `/home/markt/agenticow-ruflo-memory`. Private GitHub repo\n`markt-heximal/StrongHold`. Category: **Harness as a Service (HaaS)** — specifically, a *metaharness*.\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"78","text":"## 1a. The metaharness thesis (positioning)\n\nThe frontier model is hard to replicate; **the harness around it is not** — it is orchestration\nplumbing. The labs bundle the two and price the bundle as if the harness were the scarce part. It\nisn't. StrongHold's thesis is to **own the plumbing and rent the model à la carte**, only on the\ncalls that genuinely need a frontier brain.\n\n| | Rented harness (the labs) | StrongHold (metaharness) |\n|---|---|---|\n| Center of gravity | *Their* model | *Your* orchestration; models are leaves |\n| Models available | One vendor's | Local + Claude + OpenRouter (any slug), swapped per task, with mid-task failover |\n| Other agent frameworks | N/A | Absorbed as just-another-toolset via MCP (ruflo's 305 tools curated to 8) |\n| Code execution | Their black-box interpreter | Your sovereign rootless-Docker sandbox (caps/network/limits you set) |\n| Source of truth | Their memory store | LucidLink — one global filesystem you own (§4.5) |\n| Lock-in | By design | Structurally none — every model is interchangeable |\n\nThis is a difference the labs **cannot** copy without abandoning their business model: their\neconomics depend on their model being the center, whereas a metaharness demotes every model to a\ncommodity. StrongHold is the layer that makes *their* product one of *our* backends.\n\nThe two things that make StrongHold categorically different (not just a cheaper clone) are this\n**metaharness** structure and the **LucidLink single source of truth** in §4.5. Read them as the\nheadline; everything else is implementation.\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"79","text":"## 2. Architecture & topology\n\n```\n Browser app (Lovable)\n │ HTTPS + Bearer JWT (per user)\n ▼\n Tailscale Funnel https://spark-47d8.tail333a1d.ts.net/agentmem\n │ (public path mount → localhost)\n ▼\n TIER 2 — PUBLIC BACKEND (backend/server.js, zero-dep node:http, Docker, :8771)\n │ JWT auth · per-tenant isolation · CORS · rate limit · body limit\n │ reaches internal via host.docker.internal:8770 (X-API-Key)\n ▼\n TIER 1 — INTERNAL SERVICE (service/server.js, Fastify, :8770, X-API-Key)\n ├── per-tenant COW memory (agenticow + MiniLM-L6 384-dim, worker-thread embedder)\n ├── Docker sandbox (ephemeral, --network none, locked down)\n ├── MCP hub → ruflo (stdio) + lucidlink (SSH-stdio bridge)\n ├── per-task tool selection (profiles / tools)\n └── model router ──┬── local pool → Ollama (model-aware, dual-GPU, load-balanced)\n ├── cloud → Claude claude-opus-4-8 (Anthropic SDK)\n ├── openrouter → openai/gpt-4o (+ any slug)\n └── compat → any OpenAI-compatible server (config registry)\n```\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"80","text":"### Two tiers, on purpose\n- **Tier 1 — internal service** (`service/server.js`, Fastify, port **8770**, `X-API-Key` auth).\n The memory + harness core. Bound to all interfaces but API-key protected; intended for the\n backend + localhost only. **Not exposed through the Funnel.**\n- **Tier 2 — public backend** (`backend/server.js`, zero-dependency `node:http`, port **8771**,\n Bearer-JWT auth, per-tenant isolation). The only internet-facing edge. Zero LLM/memory logic of\n its own — it authenticates, scopes per tenant, applies CORS/limits, and proxies to the internal\n service via `host.docker.internal:8770`.\n\nThis split keeps the security-sensitive surface (the internet edge) small and stateless, while the\npowerful surface (code exec, memory, model keys) sits behind it.\n\n- **Public URL:** `https://spark-47d8.tail333a1d.ts.net/agentmem/v1` (Tailscale Funnel, path\n `/agentmem`, also accepts an optional `/v1`).\n\n### Hosts\n| Host | Hardware | Role |\n|---|---|---|\n| `spark-47d8` (this box) | DGX Spark, GB10 GPU | Runs the backend, internal service, sandbox, Funnel; one Ollama backend in the local pool |\n| `spark-a1d7` | DGX Spark, GB10 GPU | Second Ollama backend in the local pool (`:11434`), reached over the cluster network |\n| `ai-factory-mini` | Apple Silicon Mac | Runs the LucidLink MCP server, bridged to spark over SSH-stdio |\n| Anthropic / OpenRouter | Cloud | Optional cloud model providers (opt-in per request) |\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"81","text":"## 3. Core capabilities (overview)\n\n1. **Per-tenant persistent memory** — copy-on-write vector branches (agenticow), local MiniLM-L6\n embeddings (384-dim). Each agent has private memory over a shared base. Graduate-on-terminate\n promotes vetted learnings to a **per-tenant** base (`tbase:`), isolated across tenants.\n2. **Recall-augmented chat** — `/chat`, streams tokens via SSE (local tier).\n3. **Agentic act loop** — `/act`: recall → inject memories → model calls tools (run_code /\n recall_memory / remember / external MCP tools) → feeds results back → concise final answer.\n4. **Sub-agent fan-out** — `/fanout`: up to 8 ephemeral workers run tasks in parallel, aggregated,\n then dismissed (no graduation).\n5. **Sovereign code sandbox** — `/sandbox/run`: hardened ephemeral Docker container; python, node,\n bash.\n6. **Model router** — one `tier` knob; the caller never names a model (unless they want to). Routes\n to local (model-aware Ollama pool), Claude, OpenRouter, or any registered OpenAI-compatible\n backend, with per-call token-usage metering (§10.1, §11a).\n7. **External tools via MCP** — ruflo + LucidLink.\n8. **Per-task tool selection** — `profile` / `tools` knob.\n\n---\n\n## 4. Memory\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"82","text":"### 4.1 Per-user copy-on-write memory (the core)\n- Built on **agenticow** — copy-on-write vector branching (\"Git for agent memory\"). A shared\n **base** plus cheap per-agent **branches**. Each agent has private memory over the shared base;\n on recall, the agent's private memories union with the base (child wins on id collision).\n- **Embeddings are local**: `Xenova/all-MiniLM-L6-v2` (384-dim) — no network, no token cost, works\n offline. Memory is model-independent.\n- **graduate-on-terminate (per-tenant, 2026-06-30)**: deleting an agent promotes its vetted\n memories into its **tenant's** base scope `tbase:` (ids preserved), then releases the\n branch. Every one of that tenant's agents inherits `tbase:` at spawn, and\n `/memory/search` recalls over a per-tenant base — so a tenant's graduated learnings reach only\n that tenant's future agents, never across tenants. The **global** agenticow base is reserved for\n explicitly-curated shared infra (`addKnowledge`) and is no longer fed by auto-graduation.\n (Untagged/legacy agents fall back to the old global-base behavior.)\n\n### 4.2 Durability (source of truth)\n- An **append-only durable log** is the source of truth. `remember` **flushes to disk BEFORE\n acknowledging** — no \"stored\" lies; a memory is durable before the API returns 200/201.\n- A **corrupt durable/owners file is backed up** (`.corrupt.`) and the service **refuses to\n start** rather than silently wiping data.\n- The backend flushes `owners.json` on `SIGTERM`/`SIGINT`.\n\n### 4.3 Persisted embeddings (NEW)\n- The **embedding vector is stored alongside the text** in the durable log, so a restart\n **rehydrates WITHOUT re-embedding the corpus** — boot cost is O(load), not O(embed all)). Legacy\n text-only entries embed once.\n\n### 4.4 Worker-thread embedder (NEW)\n- MiniLM runs in a **worker_thread** so embeds don't block the event loop.\n- `EMBED_IN_PROCESS=1` forces in-process embedding; there is a transparent fallback to in-proc if\n the worker can't start.\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"83","text":"### 4.5 LucidLink — the fleet-wide single source of truth (the other headline)\n\nThe per-tenant COW memory above is the *semantic index*. **LucidLink is the canonical truth that\nindex points at.** It is not \"one of the MCP tools\" (that framing, in §12.1, is just the wiring) —\nit is the architectural answer to the hardest problem in any multi-agent system: *where does shared\ntruth live when agents are ephemeral and spread across machines?*\n\nLucidLink is a **planet-scale, streaming, mountable filesystem with one global namespace** (backed\nby the owner's UGREEN MinIO object storage). That makes it the substrate that lets every agent —\nregardless of which node or site it runs on — converge on the same canonical bytes:\n\n- **One namespace, every node.** An agent on `spark-47d8`, another on `spark-a1d7`, the Mac, the\n Florida V0 fleet, or the California site all mount the *same* filespace and see the *same* files\n on demand. No replication, no sync conflicts, no \"which copy is canonical\" — the filesystem *is*\n the canon.\n- **Truth outlives the agent.** Agents are ephemeral by design (`/fanout` spawns and `dismiss()`es\n them). Truth therefore cannot live in a context window or a per-node index; on LucidLink it lives\n in a durable, shared, **versioned** filesystem that no single agent owns.\n- **Streaming, so memory isn't bounded by local disk.** A petabyte corpus, but each agent streams\n only the bytes it reads; hot data is cached locally, the long tail stays in object storage.\n- **A coordination plane, not just storage.** Agent A writes a result; Agent B on another machine\n reads it. File-level semantics let agents coordinate *through the truth layer itself* rather than\n a fragile message bus.\n\n**The fusion is the unique claim: a *metaharness whose shared source of truth is a planet-scale\nfilesystem*.** The COW vector/durable layer is the semantic index over that truth — agents recall\nsemantically, then read the authoritative bytes from LucidLink. The index can be rebuilt; the truth\nnever moves. No rented harness offers this, because (a) it has no incentive to let your agents\nconverge on *your* filesystem instead of its memory store, and (b) a metaharness over a sovereign\nglobal filesystem is the opposite of the lock-in model.\n\n> Current wiring (v0.1): the LucidLink MCP bridge is **read-only** (9 curated tools — see §12.1)\n> and owner-scoped. The architecture above is the direction; read/write and per-tenant filespace\n> scoping are the next steps toward agents treating LucidLink as a read-write shared workspace.\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"84","text":"## 5. Agents\nLightweight, addressable units that own a memory branch. Spawn → remember/recall → chat/act →\ndelete (graduate). Created via the API; backed by the ruflo agent registry.\n\n---\n\n## 6. Recall-augmented chat (`/chat`)\nSingle-shot chat that first recalls the agent's most relevant memories and injects them as context,\nthen answers via the model router. Supports **SSE token streaming** when `Accept:\ntext/event-stream` (local tier).\n\n---\n\n## 7. Agentic act loop (`/act`)\nA real tool-using agent loop: **recall → inject memories → the model calls tools → results fed back\n→ repeat (up to `maxSteps`) → concise final answer.** Returns a full `steps[]` trace. Built-in\ntools:\n- `run_code` — sandboxed code execution\n- `recall_memory` — search the agent's memory\n- `remember` — persist a fact\n- plus any connected **MCP** tools (namespaced `server__tool`)\n\nWorks on any provider; for Claude the loop translates tool calls between OpenAI and Anthropic\nformats automatically.\n\n**Loop budget (security/resilience):** wall-clock `ACT_BUDGET_MS` (default 180000) plus a per-step\ntool-call cap `MAX_TOOLCALLS_PER_STEP` (default 8).\n\n---\n\n## 8. Sub-agent fan-out (`/fanout`)\nSpawn up to **8** ephemeral sub-agents, run tasks in parallel through the agent loop, aggregate\nresults, then **dismiss the workers (no graduation)**. Fan-out queues against the GPU semaphore so\nit doesn't dogpile a single GPU; with the dual-GPU pool, two inferences run truly in parallel.\nFanout also takes per-task `{prompt, tools, profile}` for per-task tool selection.\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"85","text":"## 9. Sovereign code sandbox (`/sandbox/run` + the `run_code` tool)\nRuns `python` / `node` / `bash` in an **ephemeral, locked-down Docker container** on your box:\n- `--network none` (network-isolated)\n- `--cap-drop ALL` (dropped capabilities)\n- `--read-only` rootfs\n- non-root user\n- `/tmp` tmpfs **noexec**\n- memory / CPU / pids / time limited\n- auto-removed after the run\n\nNo code ever leaves your hardware. Toggle with `SANDBOX_ENABLED`. Public RCE is intentional but\nstrongly contained, behind JWT plus the global caps below. A **global sandbox container cap**\n(`SANDBOX_MAX_CONCURRENCY`, default 4) bounds simultaneous containers.\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"86","text":"## 10. Model routing (`service/router.js`)\n\nThe caller **never names a model**; they pass an optional `tier`. The tier knob maps to an ordered\nprovider preference and fails over on error/timeout:\n\n| `tier` | Provider order | Meaning |\n|---|---|---|\n| `fast` / `balanced` / `local` | `[local]` | Free, private, on your hardware |\n| `auto` *(DEFAULT)* | `[local → cloud → openrouter]` | Local-first, cloud failover |\n| `max` | `[cloud → openrouter → local]` | Best reasoning (Claude), then fallbacks |\n| `openrouter` | `[openrouter → local]` | GPT/Gemini/Llama/… with local failover |\n\n**Providers**\n- **local** = Ollama, default model `qwen2.5-coder:32b` (served from the dual-GPU pool — see §11).\n The pool is **model-aware**: a bare model name still goes to local, routed to a pool host that\n actually has that model (see §10.1).\n- **cloud** = Anthropic Claude `claude-opus-4-8`, used **only when `ANTHROPIC_API_KEY` is set**\n (otherwise the affected tiers resolve to local).\n- **openrouter** = OpenAI-compatible endpoint (one key → GPT/Gemini/Llama/…), default slug\n `openai/gpt-4o`. An explicit `vendor/model` slug **prefers OpenRouter but keeps local as\n failover**.\n- **compat** (NEW) = any **generic OpenAI-compatible** server you register — vLLM, `llama.cpp\n --server`, TGI, Open WebUI, LM Studio. Targeted by an explicit `/` slug; metered\n under the provider label `compat:` (see §10.1).\n\n**Behavior**\n- **Graceful degradation**: a provider with no key is silently skipped — nothing breaks.\n- **Per-provider failover** on error/timeout.\n- The response **reports the `provider` + `model` that actually answered**.\n- **Explicit model wins routing** — when a request names a model (a bare name, a `vendor/model`\n slug, or a `/` compat slug), routing follows what the model *is*, not the tier's\n default provider order (see §10.1).\n- **Data egress**: `fast`/`balanced`/`local` stay 100% local; `max` and `auto`-fallback may use\n Claude; `openrouter`/slug uses OpenRouter; a `compat:` slug goes to that registered server.\n Cloud is strictly opt-in per request.\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"87","text":"### 10.1 Multi-LLM routing beyond Ollama (NEW — config-driven)\n\nStrongHold is no longer pinned to one local model + cloud. It routes to **any model on the cluster**\nand **any OpenAI-compatible engine**, swappable purely by config with no code change. Two selection\nmodes operate on top of the tier knob; both are **backward compatible** — empty config = exactly the\nprior behavior, and `providersFor` only routes by model when one is given, else the tier order is\nunchanged.\n\n**Model-aware Ollama pool.** Each request is routed to a pool host that actually **has** the\nrequested model, and the health gate **no longer requires the single default model**. So extra\nmodels already loaded on the cluster Ollamas (e.g. `deepseek-r1:32b`, `qwen2.5:32b`, `llama3.1:70b`)\nare reachable and metered **by name with zero config** — pass a bare model name and it goes to the\nOllama pool (never shadowed by another provider).\n\n**Generic OpenAI-compatible provider** (`service/openai-compat.js`). A config registry of named\nbackends `{ name, url, apiKey?, models? }` for any OpenAI-compatible server — vLLM, `llama.cpp\n--server`, TGI, Open WebUI, LM Studio. Config source (first found): env `LLM_BACKENDS` (inline JSON\narray) → env `LLM_BACKENDS_CONFIG` (path) → `./llm-backends.json`. Target a backend with an explicit\n**`/` slug** (e.g. `webui/llama3.1:70b`); usage is metered under provider label\n`compat:`. Real `llm-backends.json` is **gitignored** (holds API keys + private URLs); only\n`llm-backends.json.example` is committed. Open WebUI needs a Bearer API key. `COMPAT_TIMEOUT_MS`\n(default **120000**) bounds compat backend calls.\n\n**Two selection modes.**\n- **(a) Explicit model slug WINS routing** — route by what the model *is*, not the tier's default\n order. A bare model name → Ollama pool; a `vendor/model` slug → OpenRouter; a `/`\n slug → that compat backend.\n- **(b) Tier→model aliases** (optional) — `TIER_MODELS` maps a bare tier to a specific cluster model\n so a tier resolves to a concrete model. Config source (first found): env `TIER_MODELS` (inline\n JSON) → env `TIER_MODELS_CONFIG` → `./tier-models.json`, e.g.\n `{\"reason\":\"deepseek-r1:32b\",\"big\":\"webui/llama3.1:70b\"}`. Only `tier-models.json.example` is\n committed.\n\n`routerInfo` (in `healthz.router`) now also reports **`compat`** (array of registered backend names,\nor `false`) and **`tierModels`**.\n\n**Activation:** `cp llm-backends.json.example llm-backends.json` (fill URL + key), optionally\n`cp tier-models.json.example tier-models.json`, then restart the internal service\n(`sudo systemctl restart agentmem-internal`). Extra Ollama models need no config.\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"88","text":"## 11. Dual-GPU load balancing (NEW — `service/ollama.js`)\n\nBoth DGX Sparks run Ollama; local inference is a **pool** load-balanced across them.\n\n- `OLLAMA_URLS` (csv) lists the backends. Default:\n `http://spark-a1d7:11434,http://localhost:11434`. Legacy single `OLLAMA_URL` is still honored.\n- Each backend gets a per-backend slot: `OLLAMA_CONCURRENCY` (default **1** = one GPU, one job) →\n **TRUE parallelism** (2 GPUs = 2 concurrent inferences). Verified: 2 concurrent requests ran on\n both GPUs at once; wall-time ≈ single, not 2×.\n- The pool is **model-aware** (NEW): each request is routed to a backend that actually **has the\n requested model**, and the health gate **no longer requires the single default model** — so extra\n models already loaded on a cluster Ollama are reachable by name with zero config (see §10.1). A\n reachable backend is healthy; one still pulling the requested model is skipped for that request.\n- On a call error, the request **fails over to the sibling backend before the router reaches\n cloud**.\n- Background health re-check interval: `OLLAMA_HEALTH_MS` (default **15s**).\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"89","text":"## 11a. Observability — token/LLM usage metering (NEW)\n\nEvery model call's token usage is now **captured** from the provider (it was previously received\nfrom upstream and discarded) and normalized to `{input, output, total}`. Ollama and OpenRouter read\nthe OpenAI `usage` block; cloud Claude reads `res.usage.{input_tokens, output_tokens}`. This makes\nlocal (free/sovereign) vs. cloud (paid) spend — and per-model, per-backend cost attribution —\nvisible in real time, with no external dashboard.\n\n- **Per call** — `chat`/`act`/`fanout` responses now include a `usage` block. `act` and `fanout`\n **sum** usage across every model call in the agentic loop (and across all sub-agents for fanout).\n- **Cumulative** — the internal service `/healthz` now reports **`usageTotals` =\n `{ totals, byProvider, byModel }`**, each `{input, output, total, calls}`, since process start.\n `byModel` tracks each model by name (including `compat:` backends).\n- **Session** — the StrongHold MCP server keeps a per-session tally and exposes the new\n `stronghold_usage` tool (per-session totals + per-tool breakdown; client-side, no backend call —\n see §12.5).\n- **No rebuild needed** — the Docker public backend (`:8771`) proxies `chat`/`act`/`fanout` (and\n thus the new `usage` field) **verbatim**.\n\n---\n\n## 12. External tools via MCP (`service/mcp-client.js`, `mcp-servers.json`)\n\nA generic MCP (Model Context Protocol) **stdio client + hub**. Tools are namespaced\n`__` and auto-added to the act loop. Configured via `mcp-servers.json` (or the\n`MCP_SERVERS` / `MCP_CONFIG` env vars). Each server supports an `include`/`exclude` allowlist.\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"90","text":"### 12.1 Connected servers\n- **ruflo** — launched as `npx @claude-flow/cli@latest mcp start`; 305 tools curated to **8**:\n `memory_search`, `memory_store`, `memory_retrieve`, `swarm_status`, `agent_list`, `task_create`,\n `task_status`, `system_status`.\n- **lucidlink** (NEW) — read access to LucidLink filespaces. **This is the wiring for the\n fleet-wide single source of truth described in §4.5 — read that for the architectural point; this\n entry is just how the bridge is plumbed.** Package `lucidlink-mcp` runs on **ai-factory-mini**\n (spark is aarch64 and the package has no ARM-Linux wheel), bridged via **SSH-stdio**\n (`command: ssh ... uvx lucidlink-mcp`). Read-only + core toolset = **9 tools**:\n `list_filespaces`, `link_filespace`, `current_filespace`, `whoami`, `read_file`, `list_files`,\n `find_files`, `grep_files`, `read_lines`. The token (`sa_live:…`) lives in\n `~/.lucidlink/mcp-config.json` **on the Mac** (never in git).\n- **lucidlink-rw** — read+write, confined to the `agenticow` filespace (`/stronghold-mem` common\n namespace) via a Mac-side forced command + destructive-op-free allowlist. `mem-sync` partitions\n the namespace per tenant: each tenant's memory is exported to `tenants//memory.json`\n (logical isolation by subpath; the filespace is still owner-scoped). The hard-isolation upgrade\n for multi-org is a **per-tenant filespace + scoped token** via the workspace-manager gateway —\n the subfolder layout is the seam (§4.5).\n\n### 12.2 MCP resilience (NEW)\n- A **dead MCP child** (ssh bridge drop, ruflo crash) is detected and **auto-respawned with\n exponential backoff** (1s → 30s cap).\n- `has()` / `call()` are **gated on `ready`** — calls into a not-ready server are blocked.\n- `/healthz` shows per-server `ready` / `restarts` / `lastExit` and goes **`degraded`** when a\n server is down.\n- Tools are **read live**, so respawns restore them automatically.\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"91","text":"### 12.3 Minimal MCP env (NEW)\n- MCP children get **only a safe allowlist** (PATH/HOME/…) plus the per-server `env` override —\n **NEVER the service secrets**. Verified: the ruflo child env has no `ANTHROPIC` / `OPENROUTER` /\n `INTERNAL` / `JWT` / `LUCIDLINK` keys.\n\n### 12.4 Parallel boot (NEW)\n- MCP servers **start concurrently**, not back-to-back.\n\n### 12.5 StrongHold *as* an MCP server (Claude Code integration, NEW)\nEverything above is StrongHold as an MCP **client**. The reverse bridge —\n`service/mcp-stronghold.js` — makes StrongHold itself an MCP **server** so Claude Code\n(or any MCP host) can call the whole harness as native tools.\n- **Zero-dependency stdio server** (newline-delimited JSON-RPC 2.0; Node built-in\n `fetch`/`crypto`, no SDK). It targets the **public backend** (`:8771` / the Funnel)\n with a per-tenant Bearer JWT, so all auth, rate-limiting, and isolation apply unchanged.\n- **12 tools** — `stronghold_{health, list_agents, spawn_agent, delete_agent, remember,\n recall, memory_search, chat, act, fanout, run_code, usage}`.\n- **`stronghold_usage` (NEW)** reports this MCP session's token tally — per-session totals plus a\n per-tool breakdown — computed **client-side** from the `usage` blocks the server returns on\n `chat`/`act`/`fanout` (no backend call). See §11a for the metering pipeline.\n- **Zero-config agent:** memory/chat/act tools take an optional `agentId`; if omitted the\n server lazily spawns one default agent and caches its id (spawn promise memoized, so\n concurrent first-use shares one agent rather than racing).\n- **Config** `~/.stronghold/mcp.json` (0600): `{url, token, agent, defaultAgentType}`,\n each overridable by `STRONGHOLD_*` env. Token minted by `service/mint-stronghold-token.mjs`\n (HS256 prototype tenant `hs:`; reads `JWT_SECRET` from `backend/.env`, never echoes it).\n- **Register:** `claude mcp add stronghold --scope user -- node …/service/mcp-stronghold.js`.\n Setup/usage detail: `docs/DEVELOPER_QUICKSTART.md` §14; ops: `docs/OPS_RUNBOOK.md` §14.\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"92","text":"## 13. Per-task tool selection (\"tools UX\", NEW)\n\n`/act` and `/fanout` accept either `profile` (a named bundle) OR `tools` (an explicit allowlist of\nnames, `server__tool`, or `*` wildcard). Fanout also accepts per-task `{prompt, tools, profile}`.\n**No selection = all tools** (back-compat).\n\n**Two-layer enforcement:** the selection filters the tools **OFFERED** to the model AND is enforced\n**at dispatch** (`allowedNames`) — a call to a non-permitted tool returns \"not permitted\".\n\n**Built-in profiles** (editable in `tool-profiles.json`, merged over defaults):\n\n| Profile | Contents |\n|---|---|\n| `all` | All available tools |\n| `memory` | Memory tools |\n| `code` | Code/sandbox tools |\n| `files` | `lucidlink__*` |\n| `research` | Research bundle |\n| `lucid-readonly` | Read-only LucidLink bundle |\n\n**`GET /tools`** (internal) returns `builtin`, `mcp` (per-server), `available` (all tool names), and\n`profiles`.\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"93","text":"## 14. Public API reference\n\nBase URL: `https://spark-47d8.tail333a1d.ts.net/agentmem/v1`\nAuth: `Authorization: Bearer ` on everything except `GET /health`.\n(The `/agentmem` and `/v1` prefixes are both optional/stripped by the backend.)\n\n| Method | Path | Body | Notes |\n|---|---|---|---|\n| GET | `/health` | — | **No auth.** `{status, baseVectors, internal}` |\n| GET | `/agents` | — | The caller's agents |\n| POST | `/agents` | `{agentType, label?}` | Create agent |\n| GET | `/agents/{id}` | — | Get agent |\n| DELETE | `/agents/{id}` | — | Graduate-on-terminate |\n| POST | `/agents/{id}/memories` | `{text}` | Store memory (**durable before 200/201**) |\n| POST | `/agents/{id}/recall` | `{query, k?}` | Base ∪ this agent's private (child wins) |\n| POST | `/agents/{id}/act` | `{prompt, tier?, profile?, tools?, maxSteps?, recallK?}` | Agentic loop; returns `steps[]` |\n| POST | `/agents/{id}/fanout` | `{tasks[], tier?, profile?, tools?, agentType?, maxStepsPer?}` | ≤ 8 tasks |\n| POST | `/agents/{id}/chat` | `{prompt, tier?, recallK?}` | SSE if `Accept: text/event-stream` |\n| POST | `/sandbox/run` | `{language, code, timeoutMs?}` | `language` = `python`/`node`/`bash` |\n| POST | `/memory/search` | `{query, k?}` | Per-tenant base recall (shared infra ∪ caller's graduated learnings; never another tenant's) |\n\n**Types**\n- `Agent = {agentId, agentType, label, status, createdAt}`\n- `MemoryHit = {id, text, distance /* lower = closer */, source /* 'base' or agentId */}`\n- `steps[] = [{tool, args, result}]`\n- `usage = {input, output, total}` — token usage on `chat`/`act`/`fanout` responses; `act`/`fanout`\n sum it across the loop / all sub-agents (§11a). Proxied verbatim by the public backend.\n\n**Internal service (`:8770`, `X-API-Key`, not via the Funnel)** mirrors these routes (addressed by\n`agentId`; the backend passes an optional `tenant` on `POST /agents` and `POST /memory/search` so\ngraduation and search are tenant-scoped — see §4.1) plus:\n- `GET /healthz` — full capability/health report (see §17)\n- `GET /tools` — built-in + MCP tool inventory + profiles (see §13)\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"94","text":"## 15. Auth & multi-tenancy (`backend/server.js`)\n\nBearer **JWT**, algorithm auto-detected:\n\n- **Asymmetric Supabase (RS/ES/PS)** — verified against the **JWKS of the token's OWN issuer**\n (`https://.supabase.co/auth/v1`); ANY of the owner's Supabase projects work with zero\n config. Tenant key = `\":\"`.\n- **HS256** — verified against `JWT_SECRET`; tenant `\"hs:\"` (prototype / single-secret).\n\n`userId` comes from the `sub` claim, never the request body.\n\n- **Project allowlist** — `SUPABASE_ALLOWED_REFS` (csv). **Fail closed (NEW):** with no allowlist,\n asymmetric tokens are **REJECTED** unless `SUPABASE_ALLOW_ANY=1`.\n- **JWKS serve-last-good (NEW):** if the IdP is briefly unreachable, the stale cached key is used\n rather than rejecting every login.\n- **Per-tenant agent ownership enforced** — cross-tenant access → **404**.\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"95","text":"## 16. Security posture\n\n| Control | Detail |\n|---|---|\n| **Fail-closed secrets (NEW)** | Both tiers refuse to boot on a default/weak/missing key: `API_KEY` on the internal service; `JWT_SECRET` and `INTERNAL_API_KEY` < 24 chars on the backend. |\n| **Public auth** | Bearer JWT (asymmetric Supabase JWKS or HS256); `/health` is the only unauthed public route. |\n| **Per-tenant isolation** | Caller only sees/uses/deletes their own agents; cross-tenant → 404. |\n| **Internal auth** | Shared `X-API-Key`; internal service not exposed through the Funnel. |\n| **Per-tenant rate limit (NEW)** | Token bucket: `RATE_BURST` 30 capacity, refill `RATE_PER_SEC` 1. Heavy ops (act/fanout/chat/sandbox) cost `HEAVY_COST` 5 → **429 + Retry-After**. |\n| **Global heavy-op concurrency cap (NEW)** | `MAX_INFLIGHT_HEAVY` 4 simultaneous heavy jobs across all tenants → 429 when exceeded. |\n| **Global sandbox container cap (NEW)** | `SANDBOX_MAX_CONCURRENCY` 4. |\n| **Request body limit (NEW)** | `MAX_BODY_BYTES` 1,000,000 → **413**; malformed JSON → **400**. |\n| **Per-request loop budget (NEW)** | `ACT_BUDGET_MS` 180000 wall-clock + `MAX_TOOLCALLS_PER_STEP` 8 per step. |\n| **Sandbox** | Network-isolated, cap-dropped, non-root, read-only rootfs, `/tmp` noexec, resource-limited. Public RCE behind JWT + the limits above. |\n| **Minimal MCP env (NEW)** | MCP children never receive the service secrets (see §12.3). |\n| **Health info-leak closed (NEW)** | Unauthenticated `/healthz` returns only `{status, uptime}`; detailed diagnostics require the API key. |\n| **CORS** | Enabled (`*` by default) so browser apps can call it; safe because auth is a Bearer token, not cookies. |\n| **Secrets at rest** | Live ONLY on the host (`/etc/agentmem-internal.env`, `backend/.env`), never in git or the Docker image. The LucidLink `sa_live:` token lives only on ai-factory-mini in `~/.lucidlink/mcp-config.json`. |\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"96","text":"### Known residual risk / v0.1 caveats\n- ~~The service runs as a docker-group user, so an RCE in the harness ITSELF would be host-root.~~\n **MITIGATED (2026-06-29):** the service runs as the dedicated unprivileged user `stronghold` (NOT\n in the docker group) on its **own rootless Docker daemon** — the harness can't reach the rootful\n socket and a container escape maps to an unprivileged subuid. The LucidLink SSH bridge also uses\n `stronghold`'s **own** dedicated key (`id_ed25519_lucidlink`), pinned on the Mac with `restrict` +\n a forced command so the key can only launch the read-only bridge.\n- `v0.1` **graduation promotes to a shared base** (the intended shared-infra tier): raw private\n memories stay isolated, but *graduated* ones are visible across tenants via `/memory/search` by\n design. Hard per-tenant graduation would need a per-tenant base (a future change).\n\n---\n\n## 17. Resilience (NEW)\n\n- **Timeouts on every model call** so a hung host triggers failover, not a hang:\n `OLLAMA_TIMEOUT_MS` / `OPENROUTER_TIMEOUT_MS` / `CLOUD_TIMEOUT_MS` / `COMPAT_TIMEOUT_MS` default\n **120000**; the backend→internal non-stream call uses `INTERNAL_TIMEOUT_MS` default **300000**.\n- **GPU semaphore** so fan-out queues instead of dogpiling a single GPU.\n- **MCP auto-respawn** with exponential backoff (see §12.2).\n- **Durability** — append-only durable log is the source of truth; `remember` flushes before ack;\n corrupt durable/owners files are backed up (`.corrupt.`) and the service refuses to start\n rather than wiping; backend flushes `owners.json` on `SIGTERM`/`SIGINT` (see §4.2).\n- **Restart policy** — internal service `Restart=on-failure`; backend Docker\n `restart=unless-stopped`.\n\n---\n\n## 18. Performance (NEW)\n\n- **Dual-GPU pool** — true 2-GPU parallel local inference (see §11).\n- **Persisted embeddings** — restart rehydrates without re-embedding the corpus (see §4.3).\n- **Worker-thread embedder** — MiniLM off the event loop (see §4.4).\n- **Parallel MCP boot** — servers start concurrently (see §12.4).\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"97","text":"## 18a. Economics (why the metaharness pays for itself)\n\nStrongHold doesn't merely undercut a rented harness — it **inverts the cost curve**. A rented\nharness is variable opex that rises with usage (the more value you extract, the more you pay,\nindefinitely). StrongHold is sunk capex plus a near-zero marginal cost per request that *falls* per\nunit as volume grows.\n\n- **Marginal cost of a local call ≈ electricity, not a per-token fee.** The two DGX Sparks are\n already bought; once the capex is sunk, every additional local agent run is essentially free. The\n router defaults to the local pool, so the common path costs nothing per token.\n- **The cost gap is widest exactly where the value is highest.** A one-shot chat is cheap to rent.\n An *agent* is not: `/act` issues up to `MAX_STEPS` (≤10) model calls per task (reason → tool →\n observe → repeat), and `/fanout` multiplies that by the number of sub-agents. A rented harness\n meters every one of those calls. Agentic workloads — the valuable ones — are precisely where\n renting hurts most and where owning the GPUs flips the math.\n- **Cloud is opt-in and surgical.** Frontier token prices are paid *only* on `tier:max` (or an\n explicit `vendor/model` slug) requests that genuinely need Opus/GPT-class reasoning. The result\n is a **blended cost**: free local for the routine majority, premium cloud for the minority that\n earns it — versus paying a premium price for 100% of calls on a rented stack.\n- **The memory layer is free.** Embeddings (`all-MiniLM-L6-v2`), vector storage, and recall all run\n on-device (§4.1). On a rented stack each is separately metered (per-embedding, per-vector stored,\n per-query). With LucidLink + the owner's MinIO (§4.5), one canonical copy streams to every agent —\n no charge to duplicate, sync, or query memory across machines or sites.\n- **No replication tax across the fleet.** Because LucidLink is a single global namespace, adding a\n node or a site does not multiply storage or sync cost — agents stream the same canonical bytes.\n Object storage ($/TB) is far cheaper than a managed vector DB's per-vector/per-query pricing.\n- **The metaharness is itself a cost-optimization engine.** Tiering routes cheap tasks to cheap\n models and spends frontier dollars only where they pay for themselves; swappability means no\n vendor can raise prices on us without us routing around them. **No lock-in = pricing power.**\n- **It resells with structural margin.** Marginal cost per tenant is near zero, so a product built\n *on* StrongHold has gross margins bounded only by already-owned hardware. A competitor reselling a\n rented harness carries the vendor's per-token fee as a permanent floor under COGS.\n\n**Net:** rent the frontier brain by the sip, for the 10% of calls that need it; own everything else.\nCost scales with hardware you control, not with a meter someone else runs.\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"98","text":"## 19. Health endpoint shape (`/healthz`, authed)\n\n```\n{\n status: ok | degraded,\n uptime,\n degraded?: { mcpDown[] },\n baseVectors,\n durableMemories,\n agents,\n rehydrated,\n sandbox,\n sandboxQueue: { active, queued, max },\n mcpServers: [ { name, ready, tools, restarts, lastExit } ],\n mcpTools,\n ollamaQueue: { queued, perBackend, backends: [ { url, active, healthy } ] },\n router, // routerInfo — also reports `compat` (backend names | false) + `tierModels` (§10.1)\n usageTotals: { totals, byProvider, byModel }, // each {input, output, total, calls}, since boot (§11a)\n ollama: { reachable, backends[] },\n ollamaUrl\n}\n```\n\n(Unauthenticated `/healthz` returns only `{status, uptime}` — see §16.)\n\n---\n\n## 20. Configuration / env reference\n\nSecrets live ONLY on the host (`/etc/agentmem-internal.env`, `backend/.env`), never in git.\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"99","text":"### 20.1 Internal service (`:8770`) — `/etc/agentmem-internal.env`\n| Var | Default / note | Purpose |\n|---|---|---|\n| `API_KEY` | **required, no default** | Shared key the backend uses to call the internal service (fail-closed) |\n| `PORT` | `8770` | Listen port |\n| `HOST` | all interfaces | Bind host |\n| `BASE_PATH` | — | Memory base path (durable log derived from it) |\n| `SANDBOX_ENABLED` | — | Code-exec kill switch |\n| `OLLAMA_URLS` / `OLLAMA_URL` | `http://spark-a1d7:11434,http://localhost:11434` (csv) | Local Ollama pool backends (legacy single URL honored) |\n| `OLLAMA_MODEL` | `qwen2.5-coder:32b` | Local model |\n| `OLLAMA_TIMEOUT_MS` | `120000` | Local call timeout |\n| `OLLAMA_CONCURRENCY` | `1` | Per-backend slot (1 = one GPU, one job) |\n| `OLLAMA_HEALTH_MS` | `15000` | Background backend health re-check interval |\n| `OPENROUTER_TIMEOUT_MS` | `120000` | OpenRouter call timeout |\n| `ANTHROPIC_API_KEY` | — | Enables the `cloud` (Claude) tier |\n| `CLOUD_MODEL` | `claude-opus-4-8` | Claude model |\n| `CLOUD_MAX_TOKENS` | — | Claude max output |\n| `CLOUD_TIMEOUT_MS` | `120000` | Cloud call timeout |\n| `OPENROUTER_API_KEY` | — | Enables the `openrouter` tier |\n| `OPENROUTER_MODEL` | `openai/gpt-4o` | Default OpenRouter model |\n| `LLM_BACKENDS` / `LLM_BACKENDS_CONFIG` | — / `./llm-backends.json` | Generic OpenAI-compatible backend registry (inline JSON array or path; gitignored, target via `/`) — §10.1 |\n| `TIER_MODELS` / `TIER_MODELS_CONFIG` | — / `./tier-models.json` | Optional tier→model aliases (inline JSON or path) — §10.1 |\n| `COMPAT_TIMEOUT_MS` | `120000` | Compat (OpenAI-compatible) backend call timeout |\n| `ACT_BUDGET_MS` | `180000` | Per-request act-loop wall-clock budget |\n| `MAX_TOOLCALLS_PER_STEP` | `8` | Per-step tool-call cap |\n| `SANDBOX_MAX_CONCURRENCY` | `4` | Global sandbox container cap |\n| `EMBED_IN_PROCESS` | — | `1` forces in-process embedding (else worker_thread) |\n| `MCP_SERVERS` / `MCP_CONFIG` | — / `./mcp-servers.json` | MCP server config (inline JSON or path) |\n| `TOOL_PROFILES_CONFIG` | — | Tool-profiles config path (`tool-profiles.json`) |\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"100","text":"### 20.2 Public backend (`:8771`) — `backend/.env` + compose env\n| Var | Default / note | Purpose |\n|---|---|---|\n| `PORT` | `8771` | Listen port |\n| `INTERNAL_URL` | `http://host.docker.internal:8770` | Reach the internal service |\n| `INTERNAL_API_KEY` | **strong, ≥24 chars** | Must equal the internal `API_KEY` (fail-closed) |\n| `JWT_SECRET` | **strong, ≥24 chars** | HS256 verification secret (fail-closed) |\n| `OWNER_DB` | — | Per-tenant ownership map (Docker volume) |\n| `PUBLIC_PREFIX` | `/agentmem` | Funnel path prefix to strip |\n| `ALLOWED_ORIGIN` | `*` | CORS origin |\n| `MAX_BODY_BYTES` | `1000000` | Request body limit (→ 413) |\n| `INTERNAL_TIMEOUT_MS` | `300000` | Backend→internal non-stream timeout |\n| `SUPABASE_ISS_REGEX` | — | Trusted issuer pattern |\n| `SUPABASE_ALLOWED_REFS` | — (csv) | Allowed Supabase project refs |\n| `SUPABASE_ALLOW_ANY` | — | `1` allows asymmetric tokens with no allowlist |\n| `RATE_BURST` | `30` | Token-bucket capacity |\n| `RATE_PER_SEC` | `1` | Token-bucket refill rate |\n| `HEAVY_COST` | `5` | Cost of heavy ops (act/fanout/chat/sandbox) |\n| `MAX_INFLIGHT_HEAVY` | `4` | Global heavy-op concurrency cap |\n\n---\n\n## 21. How to use it\n\n### 21.1 Quickstart (curl)\n```bash\nBASE=https://spark-47d8.tail333a1d.ts.net/agentmem/v1\nTOKEN= # Supabase session token, or the prototype test token\n\n# spawn an agent\nAID=$(curl -s -H \"authorization: Bearer $TOKEN\" -H 'content-type: application/json' \\\n -d '{\"agentType\":\"assistant\"}' $BASE/agents | jq -r .agentId)\n\n# teach it, then chat\ncurl -s -H \"authorization: Bearer $TOKEN\" -H 'content-type: application/json' \\\n -d '{\"text\":\"The launch date is Sept 9.\"}' $BASE/agents/$AID/memories\ncurl -s -H \"authorization: Bearer $TOKEN\" -H 'content-type: application/json' \\\n -d '{\"prompt\":\"When is launch?\",\"tier\":\"fast\"}' $BASE/agents/$AID/chat\n```\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"101","text":"### 21.2 Lovable / browser\nUse the drop-in TypeScript client and instructions in **`backend/LOVABLE.md`**. Essentials:\n- Base URL above; `Authorization: Bearer `.\n- For real per-user memory, set the token to the Supabase session access token; each signed-in\n user becomes an isolated tenant automatically.\n- Streaming chat uses `fetch` + a stream reader (not `EventSource`, which can't send auth headers).\n- Optional `tier` knob; omit it for sensible defaults.\n\n### 21.3 Choosing quality vs. speed, and tools\n- Pass `tier` (`fast` / `balanced` / `auto` / `max` / `openrouter` / `local`) — or nothing. Power\n users can pass a `vendor/model` slug. Every response reports `provider` + `model`.\n- On `/act` and `/fanout`, narrow the toolset with `profile` (e.g. `lucid-readonly`) or an explicit\n `tools` allowlist (see §13).\n\n---\n\n## 22. Operations\n\n### 22.1 Process & lifecycle\n| Layer | Manage | Notes |\n|---|---|---|\n| Internal service | `sudo systemctl {status,restart} agentmem-internal` | systemd unit, `Restart=on-failure` |\n| Public backend | `cd backend && docker compose up -d --build` | container `agentmem-backend`, `restart=unless-stopped` |\n| Funnel | `sudo tailscale funnel --bg --set-path /agentmem 8771` | adds the public path; `tailscale funnel status` to inspect |\n\n### 22.2 LucidLink bridge\n- Needs `uv` / `uvx` plus the `sa_live:` token file (`~/.lucidlink/mcp-config.json`) on\n **ai-factory-mini**.\n- The persistent SSH-stdio bridge must be (re)started **AFTER** the token file exists — the MCP\n server reads the token once at startup.\n\n### 22.3 Health\n- Public: `curl $BASE/health` → `{status, baseVectors, internal}`.\n- Internal (full report): `curl -H \"x-api-key: \" localhost:8770/healthz` → the shape in\n §19. Unauthenticated `/healthz` returns only `{status, uptime}`.\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"102","text":"## 23. Tech stack\n- **Runtime:** Node.js (ESM). Internal service uses **Fastify**; backend is **zero-dependency**\n `node:http` + `node:crypto`.\n- **Memory:** `agenticow` (COW vectors) + `@huggingface/transformers` (local MiniLM embeddings,\n worker-thread).\n- **Models:** Ollama (local, model-aware dual-GPU pool), `@anthropic-ai/sdk` (Claude), OpenRouter\n and any generic OpenAI-compatible server (`service/openai-compat.js` — vLLM/llama.cpp/TGI/Open\n WebUI/LM Studio).\n- **MCP:** generic stdio client + hub (ruflo via `npx`; LucidLink via SSH-stdio to ai-factory-mini).\n- **Infra:** Docker (backend + sandbox), systemd (internal service), Tailscale Funnel (public edge).\n- **Repo:** `/home/markt/agenticow-ruflo-memory` (`service/` internal, `backend/` public, `data/`\n memory, `docs/` this).\n\n---\n\n## 24. Status & roadmap\n- All four hardening tranches + dual-GPU + the **docker-privilege migration** (dedicated\n unprivileged `stronghold` user on rootless Docker) + the **dedicated scope-locked SSH key** for\n the LucidLink bridge are **DONE and verified live (2026-06-29)**.\n- **No open hardening items.** Next functional milestones: (1) elevate LucidLink from read-only to\n a **read/write shared workspace** with per-tenant filespace scoping, so agents treat the single\n source of truth (§4.5) as a coordination plane; (2) per-tenant graduation for a future\n multi-organization tier (see §\"Known residual risk / v0.1 caveats\").\n\n---\n\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"103","text":"## 25. Glossary\n- **Harness** — everything around a model that lets it do work (loop, tools, sandbox, memory, auth,\n routing). Scoped to one vendor's model.\n- **Metaharness** — a harness whose *models, tool runtimes, sandboxes, memory backends, and even\n other agent frameworks are interchangeable leaves*. It orchestrates harnesses; the model is a\n swappable commodity, not the center. StrongHold is a metaharness (§1a).\n- **Single source of truth** — the one canonical store all agents converge on regardless of which\n node/site they run on. In StrongHold, LucidLink's global filesystem (§4.5); the COW vector memory\n is the semantic index over it.\n- **Tenant** — an isolated memory owner, keyed by `:` (Supabase) or `hs:` (HS256).\n- **Base / branch** — shared memory vs. a per-agent copy-on-write fork.\n- **Graduate** — promote an agent's memories into the shared base on termination.\n- **Tier** — the one-word quality/cost knob that selects a provider order.\n- **Provider** — `local` (Ollama pool), `cloud` (Claude), `openrouter`, or `compat:` (any\n registered OpenAI-compatible server — §10.1).\n- **Profile** — a named tool bundle (`all`, `memory`, `code`, `files`, `research`, `lucid-readonly`).\n","path":"docs/HARNESS.md","title":"StrongHold — System Documentation","source_type":"doc","kind":"doc"} -{"id":"104","text":"# StrongHold — Operations Runbook\n\n*StrongHold is our Harness as a Service (HaaS).*\n\nHow to run, monitor, configure, and troubleshoot the system on `spark-47d8`.\nRepo root: `/home/markt/agenticow-ruflo-memory`. Sudo: `markt` / password on file.\n\nStrongHold is a sovereign, memory-centric AI-agent harness served as an API and\nrunning entirely on our own hardware (two NVIDIA DGX Sparks). Two processes make\nup the stack: a **systemd internal service** (`agentmem-internal`, :8770) and a\n**Docker public backend** (`agentmem-backend`, :8771), fronted by a Tailscale\nFunnel at `https://spark-47d8.tail333a1d.ts.net/agentmem/v1`.\n\n---\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"105","text":"## 1. Processes\n\n| Component | Type | Manage | Port | Restart policy |\n|---|---|---|---|---|\n| Internal service (`service/server.js`, Fastify, `X-API-Key`) | systemd `agentmem-internal` (**User=stronghold**, enabled) | `sudo systemctl {status,restart,stop,start} agentmem-internal` | 8770 | `Restart=on-failure` |\n| Rootless Docker (sandbox backend for the internal service) | **user** systemd `docker.service` under `stronghold` (linger-enabled) | `sudo -u stronghold XDG_RUNTIME_DIR=/run/user/1001 systemctl --user {status,restart} docker` | — (socket `/run/user/1001/docker.sock`) | enabled + linger |\n| Public backend (`backend/server.js`, node:http, Bearer-JWT, per-tenant) | Docker `agentmem-backend` (rootful) | `cd backend && docker compose {up -d,down,logs -f,restart}` | 8771 | `restart=unless-stopped` |\n| Public edge | Tailscale Funnel path `/agentmem` → `:8771` | `tailscale funnel status` | 443 | persisted |\n\n- Unit file: `/etc/systemd/system/agentmem-internal.service`. Compose: `backend/docker-compose.yml`.\n- **The internal service runs as the dedicated unprivileged user `stronghold`** (uid 1001, NOT in the docker group) and sandboxes via *its own* rootless Docker — see §\"Rootless sandbox\". The rootful daemon (backend, ruvector, lucidlink, open-webui) is still managed by `markt` as before.\n- The backend reaches the internal service via `host.docker.internal:8770`.\n- The internal service is bound to all interfaces but is API-key protected;\n it is intended for the backend + localhost only.\n\n## 2. Start / stop / restart\n\n```bash\n# Internal service (memory, models, sandbox, MCP) — boots by re-loading the\n# durable log and reconnecting MCP servers (MCP boot is parallel).\nsudo systemctl restart agentmem-internal\n\n# Public backend\ncd /home/markt/agenticow-ruflo-memory/backend && docker compose up -d --build # or: restart / down\n\n# (Re)publish the public path if the Funnel was reset (additive; leaves other paths intact)\nsudo tailscale funnel --bg --set-path /agentmem 8771\n```\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"106","text":"## 3. Dual-GPU Ollama pool\n\nBoth DGX Sparks run Ollama; local inference is a **pool** load-balanced across\nthem so two GPUs give true parallelism (2 concurrent inferences, wall-time ≈\nsingle not 2×).\n\n- `OLLAMA_URLS` (csv) lists the backends. Default:\n `http://spark-a1d7:11434,http://localhost:11434` (sibling GPU host + local 47d8).\n- Each backend gets a per-backend slot `OLLAMA_CONCURRENCY` (default `1` = one\n GPU one job). Background health re-check every `OLLAMA_HEALTH_MS` (default\n `15s`). Legacy single `OLLAMA_URL` is still honored.\n- A backend is **healthy only if reachable AND it has the model** — a host still\n pulling `qwen2.5-coder:32b` auto-excludes itself. On a call error the request\n fails over to the sibling backend BEFORE the router escalates to cloud.\n- The pool is **model-aware**: extra models already loaded on a pool host\n (`deepseek-r1:32b`, `qwen2.5:32b`, `llama3.1:70b`) are reachable + metered by\n name with **no config** — see §15.\n\n**Add a GPU host to the pool**\n1. On the new host: install Ollama and `ollama pull qwen2.5-coder:32b`\n (`OLLAMA_MODEL`). The host stays excluded from the pool until the model is\n fully present.\n2. Append its URL to `OLLAMA_URLS` in `/etc/agentmem-internal.env`, e.g.\n `...,http://new-gpu-host:11434`.\n3. `sudo systemctl restart agentmem-internal`.\n4. Verify in `/healthz`: `ollamaQueue.backends[]` and `ollama.backends[]` list\n the new url with `healthy:true`.\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"107","text":"## 4. LucidLink MCP bridge\n\nRead-only access to LucidLink filespaces (9 tools: list_filespaces,\nlink_filespace, current_filespace, whoami, read_file, list_files, find_files,\ngrep_files, read_lines). The `lucidlink-mcp` package runs on **ai-factory-mini**\n(spark is aarch64; the package has no ARM-Linux wheel) and is bridged to spark\nover **SSH-stdio** (`command: ssh ... uvx lucidlink-mcp`), configured in\n`mcp-servers.json`.\n\nOperational requirements ON ai-factory-mini:\n- `uv` / `uvx` must be installed (uvx launches `lucidlink-mcp`).\n- The service-account token (`sa_live:…`) lives in\n `~/.lucidlink/mcp-config.json` ON THE MAC — never in git.\n\n**CRITICAL GOTCHA:** the MCP server reads the token **once at startup**. The\npersistent bridge must be (re)started **AFTER** the token file exists. If the\nbridge was launched before the token was written, restart the internal service\n(which respawns the MCP child) so it picks up the token:\n\n```bash\nsudo systemctl restart agentmem-internal\n# then confirm the lucidlink server is ready (§5)\n```\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"108","text":"### 4.1 Write bridge + per-tenant memory sync\n\nA second bridge **`lucidlink-rw`** (read+write, confined to the `agenticow`\nfilespace = the `/stronghold-mem` common namespace) backs `mem-sync`. The\n`stronghold-mem-sync.timer` (oneshot, `flock -n`, every 10 min, `User=stronghold`)\nruns `service/mem-sync.mjs`, which mirrors COW memory + Claude markdown memory into\nthe namespace and, since 2026-06-30, writes a **per-tenant** export to\n`tenants//memory.json` (that tenant's `tbase:` graduated base + its\nagents' private memories, grouped from the durable log via the tenant-tagged ruflo\nagent store). The shared global base + Claude memory stay at the namespace root.\n\n```bash\nsystemctl status stronghold-mem-sync.timer\njournalctl -u stronghold-mem-sync.service -n 20 # \"... ; tenants: N written, ...\"\nsudo -u stronghold .../node service/mem-sync.mjs --full # force a complete re-sync\n```\n\nInspecting the durable log: per-tenant graduated learnings live under scope\n`tbase:`; the global `base` scope holds only curated shared infra. A tenant\nwith no `tbase:*` scope and no tagged agents simply has no export folder yet.\n\n### 4.2 Per-tenant filespace (hard isolation, ADR-0010)\n\nFor hard isolation, a tenant gets its **own** LucidLink filespace instead of an\n`agenticow` subfolder. Provisioning is one idempotent script:\n\n```bash\n# creates filespace stronghold-, a dedicated stronghold SSH key, the Mac\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"109","text":"# forced-command (running the confine-mcp.py shim), and the registry entry.\nSUDO_PASS=… service/provision-tenant.sh # e.g. pilot01\nsudo systemctl start stronghold-mem-sync.service # push that tenant's memory\n```\n\n- **Confinement boundary** is `service/confine-mcp.py` (deployed to the Mac at\n `~/.lucidlink/confine-mcp.py`), run by the forced command instead of `lucidlink-mcp`\n directly. It strips `link_filespace`/`list_filespaces`, so the bridge key is pinned\n to the one filespace — LucidLink tokens are workspace-admin scope and cannot be\n narrowed, so this shim *is* the isolation. The `agenticow` rw bridge runs the same\n shim; the read-only bridge does not (it browses many filespaces by design).\n- **Registry** `service/tenant-filespaces.json` maps `tenant → {filespace, key}`;\n `mem-sync` routes a registered tenant to its own filespace, unregistered ones to the\n subfolder fallback.\n- **Verify a bridge is confined:** connect with the tenant key and call a file tool\n (e.g. `list_files /`) — it auto-links only `stronghold-`; `link_filespace`\n to anything else returns \"tool … is disabled on this filespace-confined bridge\".\n- **Deprovision (reverse order):** remove the tenant from the registry; drop the Mac\n `authorized_keys` line `lucidlink-rw-`; delete the key\n `/home/stronghold/.ssh/id_ed25519_ll_*`; `DELETE\n /api/v1/filespaces/` (id is in the registry entry).\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"110","text":"## 5. MCP health & auto-respawn\n\nMCP external tools (ruflo + lucidlink) are stdio children of the internal\nservice, namespaced `__` and auto-added to the act loop.\n\n- A dead MCP child (ssh bridge drop, ruflo crash) is detected and\n **auto-respawned with exponential backoff** (1s → 30s cap). `has()`/`call()`\n are gated on `ready`, and tools are read live so respawns restore them.\n- MCP children get only a safe env allowlist (PATH/HOME/…) plus the per-server\n `env` override — never the service secrets.\n\n**Read per-server health** from authed `/healthz` → `mcpServers[]`:\n\n```bash\ncurl -s -H \"x-api-key: \" localhost:8770/healthz | jq '.mcpServers, .degraded'\n# each entry: { name, ready, tools, restarts, lastExit }\n```\n\n- `ready:false` with a climbing `restarts` and a non-zero `lastExit` = that\n server is flapping (check the bridge / package on its host).\n- When any MCP server is down, top-level `status` goes `degraded` and\n `degraded.mcpDown[]` lists the offending server names. Auto-respawn keeps\n retrying; no manual action is needed unless a server stays down (then fix its\n host and it will reconnect, or restart the internal service).\n\n## 6. Health checks\n\n```bash\n# Public (no auth) — {status, baseVectors, internal}\ncurl -s https://spark-47d8.tail333a1d.ts.net/agentmem/health\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"111","text":"# Internal full report (X-API-Key = internal API_KEY)\ncurl -s -H \"x-api-key: \" localhost:8770/healthz\n```\n\nUnauthenticated `/healthz` returns only `{status, uptime}` (info-leak closed);\nthe detailed report requires the API key. Authed shape:\n\n```\n{ status: ok|degraded, uptime, degraded?:{mcpDown[]}, baseVectors, durableMemories,\n agents, rehydrated, sandbox, sandboxQueue:{active,queued,max},\n mcpServers:[{name,ready,tools,restarts,lastExit}], mcpTools,\n ollamaQueue:{queued,perBackend,backends:[{url,active,healthy}]},\n router, ollama:{reachable,backends[]}, ollamaUrl,\n usageTotals:{totals,byProvider,byModel} }\n```\n\n- `ollama.reachable` must be `true` for local/`fast`/`balanced` tiers.\n- `router` reports which providers are live (cloud / openrouter `false` = no key);\n `router.compat` lists registered OpenAI-compatible backend names and\n `router.tierModels` the tier→model aliases (§15).\n- `usageTotals` is cumulative token metering since boot — see §15.2.\n\n## 7. Logs\n\n```bash\nsudo journalctl -u agentmem-internal -n 100 --no-pager # internal service\ncd /home/markt/agenticow-ruflo-memory/backend && docker compose logs -f # public backend\n```\n\n## 8. Configuration / env reference\n\nSecrets and config live ONLY on the host: **`/etc/agentmem-internal.env`**\n(root, `600`) and **`backend/.env`** (`600`). Never in git, never echoed into\nlogs. After editing the internal env file: `sudo systemctl restart\nagentmem-internal`. After editing `backend/.env`: `cd backend && docker compose\nup -d`.\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"112","text":"### Internal service (:8770)\n\n| Var | Default | Notes |\n|---|---|---|\n| `API_KEY` | *(required, no default)* | `X-API-Key`; boot refuses on weak/missing |\n| `PORT` | 8770 | |\n| `HOST` | all interfaces | |\n| `BASE_PATH` | | durable-log / data path |\n| `SANDBOX_ENABLED` | on | code-exec kill switch |\n| `OLLAMA_URLS` | `http://spark-a1d7:11434,http://localhost:11434` | pool backends (csv) |\n| `OLLAMA_URL` | | legacy single backend (still honored) |\n| `OLLAMA_MODEL` | `qwen2.5-coder:32b` | required per-backend to be \"healthy\" |\n| `OLLAMA_TIMEOUT_MS` | 120000 | |\n| `OLLAMA_CONCURRENCY` | 1 | per-backend slots (1 = one GPU one job) |\n| `OLLAMA_HEALTH_MS` | 15000 | background re-check interval |\n| `OPENROUTER_TIMEOUT_MS` | 120000 | |\n| `ANTHROPIC_API_KEY` | *(unset)* | enables `cloud` provider; else tiers resolve local |\n| `CLOUD_MODEL` | `claude-opus-4-8` | |\n| `CLOUD_MAX_TOKENS` | | |\n| `CLOUD_TIMEOUT_MS` | 120000 | |\n| `OPENROUTER_API_KEY` | *(unset)* | |\n| `OPENROUTER_MODEL` | `openai/gpt-4o` | |\n| `ACT_BUDGET_MS` | 180000 | per-request wall-clock loop budget |\n| `MAX_TOOLCALLS_PER_STEP` | 8 | per-step tool-call cap |\n| `SANDBOX_MAX_CONCURRENCY` | 4 | global sandbox container cap |\n| `EMBED_IN_PROCESS` | *(off)* | `1` forces in-proc MiniLM (default = worker_thread) |\n| `MCP_SERVERS` / `MCP_CONFIG` | `mcp-servers.json` | MCP config source |\n| `TOOL_PROFILES_CONFIG` | `tool-profiles.json` | tool-profile overrides |\n| `LLM_BACKENDS` / `LLM_BACKENDS_CONFIG` | `llm-backends.json` | OpenAI-compatible backend registry: inline JSON array / path / file (§15) |\n| `TIER_MODELS` / `TIER_MODELS_CONFIG` | `tier-models.json` | tier→model aliases: inline JSON / path / file (§15) |\n| `COMPAT_TIMEOUT_MS` | 120000 | per-call timeout for compat backends (§15) |\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"113","text":"### Public backend (:8771)\n\n| Var | Default | Notes |\n|---|---|---|\n| `PORT` | 8771 | |\n| `INTERNAL_URL` | `host.docker.internal:8770` | reaches internal service |\n| `INTERNAL_API_KEY` | *(strong, required)* | = internal `API_KEY`; boot refuses if <24 chars |\n| `JWT_SECRET` | *(strong, required)* | HS256 verify; boot refuses if weak/<24 chars |\n| `OWNER_DB` | | per-tenant ownership store (`owners.json` / volume) |\n| `PUBLIC_PREFIX` | `/agentmem` | Funnel path prefix stripped from inbound paths |\n| `ALLOWED_ORIGIN` | | CORS |\n| `MAX_BODY_BYTES` | 1000000 | over → 413; malformed JSON → 400 |\n| `INTERNAL_TIMEOUT_MS` | 300000 | backend→internal non-stream |\n| `SUPABASE_ISS_REGEX` | | issuer match |\n| `SUPABASE_ALLOWED_REFS` | *(empty)* | csv project allowlist; fail-closed |\n| `SUPABASE_ALLOW_ANY` | *(unset)* | `1` allows any asymmetric token when no allowlist |\n| `RATE_BURST` | 30 | token-bucket capacity |\n| `RATE_PER_SEC` | 1 | refill rate |\n| `HEAVY_COST` | 5 | cost of act/fanout/chat/sandbox |\n| `MAX_INFLIGHT_HEAVY` | 4 | global heavy-op concurrency cap |\n\n## 9. Durability\n\n- **Durable log is the source of truth** — an append-only log holds each memory\n with its text and its embedding vector. On restart the index rehydrates from\n the log WITHOUT re-embedding the corpus (boot cost O(load), not O(embed all));\n legacy text-only entries embed once.\n- **Flush-before-ack** — `remember` flushes to disk BEFORE acknowledging, so a\n `200/201` never lies about a memory being stored. The backend also flushes\n `owners.json` on SIGTERM/SIGINT.\n- **Corrupt-file refuse-to-start** — if the durable log or owners file is\n corrupt, the service backs it up as `.corrupt.` and **refuses to start**\n rather than silently wiping. Recovery: inspect/repair (or remove) the corrupt\n file, optionally restore from the `.corrupt.` backup, then restart.\n\n```bash\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"114","text":"# After a refuse-to-start on corruption: locate the backup, then restart\nls -la /home/markt/agenticow-ruflo-memory/data/*.corrupt.*\nsudo systemctl restart agentmem-internal\n```\n\n## 10. Minting colleague JWT test tokens\n\nTest tokens are HS256, verified against `JWT_SECRET` (tenant `\"hs:\"`). The\nminting script **reads `JWT_SECRET` at runtime** (from `backend/.env` / env) and\nmust NEVER embed the secret value. Hand a colleague a token, not the secret.\n\n```bash\ncd /home/markt/agenticow-ruflo-memory/backend\n# Script loads JWT_SECRET from the environment / .env at runtime — never hard-coded.\nnode scripts/mint-token.js --sub colleague-name # prints a Bearer JWT\n```\n\nFor real users, prefer asymmetric Supabase tokens (verified against the issuer's\nJWKS; add the project ref to `SUPABASE_ALLOWED_REFS`).\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"115","text":"## 11. Troubleshooting\n\n| Symptom | Likely cause | Fix |\n|---|---|---|\n| Local inference slow / `ollama.backends[].healthy:false` for a1d7 | spark-a1d7 down or tailnet offline | Pool **fails over** to localhost then router escalates to **cloud**; bring a1d7 back (`curl spark-a1d7:11434/api/tags`; see networking notes), it auto-rejoins once the model is present |\n| `status:degraded`, `degraded.mcpDown[]` populated | An MCP child (ruflo / lucidlink ssh bridge) died | **Auto-respawn** is retrying (backoff 1s→30s). Fix the server's host if it stays down; lucidlink → confirm token file then restart internal service (§4) |\n| LucidLink tools missing / unauthorized | Bridge started before token file existed (token read once at startup) | Ensure `~/.lucidlink/mcp-config.json` exists on ai-factory-mini, then `sudo systemctl restart agentmem-internal` |\n| `429` + `Retry-After` | Per-tenant rate limit (`RATE_BURST` 30 / `RATE_PER_SEC` 1; heavy op costs `HEAVY_COST` 5) OR global cap (`MAX_INFLIGHT_HEAVY` 4) hit | Back off and retry per `Retry-After`; raise the limit knobs in `backend/.env` only if capacity allows |\n| `413` request too large | Body exceeded `MAX_BODY_BYTES` (1,000,000) | Shrink the payload, or raise `MAX_BODY_BYTES` |\n| Service refuses to boot, logs cite key | Fail-closed secrets: weak/missing `API_KEY` (internal) or `JWT_SECRET`/`INTERNAL_API_KEY` <24 chars (backend) | Set a strong (≥24 char) secret in the env file, restart |\n| Service refuses to boot, cites corrupt file | Durable/owners file corrupt (backed up `.corrupt.`) | See §9 recovery |\n| `tier:max` answers `provider:local` | No/invalid `ANTHROPIC_API_KEY` | Check `/healthz` `router`; fix key + restart |\n| Asymmetric token rejected | Project ref not in `SUPABASE_ALLOWED_REFS` (fail-closed) | Add ref to `SUPABASE_ALLOWED_REFS` (or set `SUPABASE_ALLOW_ANY=1`); `docker compose up -d` |\n| Public calls 502 / hang | Internal service down | `systemctl status agentmem-internal`; restart |\n| Leftover `agentmem-sbx-*` containers | Sandbox run interrupted | They live in **stronghold's rootless** daemon, not rootful: `sudo -u stronghold XDG_RUNTIME_DIR=/run/user/1001 DOCKER_HOST=unix:///run/user/1001/docker.sock docker ps -a --filter name=agentmem-sbx` then `docker rm -f`; normally auto-removed |\n| Sandbox calls fail `spawn error` / `Cannot connect to the Docker daemon` | stronghold's rootless `docker.service` is down | `sudo -u stronghold XDG_RUNTIME_DIR=/run/user/1001 systemctl --user restart docker` (see §\"Rootless sandbox\") |\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"116","text":"## 12. Reboot behaviour\n\nAll layers are reboot-safe: `stronghold`'s **linger** is enabled so its user\nmanager + rootless `docker.service` come up at boot; systemd restarts the\ninternal service (`on-failure` + enabled) which rehydrates memory from the\ndurable log; Docker restarts the backend (`unless-stopped`); the Funnel config\npersists. The internal service starts independently of the rootless daemon — the\nsandbox is lazy (per-request), so a first sandbox call shortly after boot just\nwaits for the daemon to be ready. Verify with the two health checks in §6.\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"117","text":"## 13. Rootless sandbox (`stronghold` user)\n\nThe internal service runs as the dedicated unprivileged user **`stronghold`**\n(uid 1001), which is **not** in the docker group, and executes sandboxed code on\nits **own rootless Docker daemon**. This is the docker-privilege hardening: an\nRCE in the harness process cannot reach the rootful socket or host root, and a\ncontainer escape maps to a `stronghold` subuid (powerless on the host).\n\n**Layout**\n- Service unit env: `User/Group=stronghold`, `DOCKER_HOST=unix:///run/user/1001/docker.sock`, `XDG_RUNTIME_DIR=/run/user/1001`, `HOME=/home/stronghold`, `UMask=0002`, plus pinned `REGISTRY_PATH`/`AGENT_STORE_PATH` (markt's `~/.claude-flow` state).\n- Rootless daemon: user service `docker.service` under `stronghold` (image store under `/home/stronghold/.local/share/docker`). Sandbox images (`python:3.12-alpine`, `node:22-alpine`, `alpine:3.20`) are pre-pulled into it.\n- App stays at `/home/markt/agenticow-ruflo-memory`; `stronghold` has it via **POSIX ACLs** (`getfacl` to inspect): rwX on the app dir + `~/.claude-flow/{swarm,agents}`, traverse on `/home/markt`. The LucidLink bridge uses `stronghold`'s **own** key + known_hosts under `/home/stronghold/.ssh/` (no ACLs on markt's `~/.ssh`).\n\n**Manage the rootless daemon** (always set the two env vars):\n```bash\nS='sudo -u stronghold XDG_RUNTIME_DIR=/run/user/1001 DOCKER_HOST=unix:///run/user/1001/docker.sock'\n$S systemctl --user status docker # daemon state\n$S systemctl --user restart docker # restart it\n$S docker ps -a --filter name=agentmem-sbx # inspect sandbox containers\n$S docker images # confirm the 3 images are present\n$S docker pull python:3.12-alpine # re-pull if an image is missing\n```\n\n**Verify isolation** (should all hold):\n```bash\nsudo -u stronghold docker -H unix:///var/run/docker.sock ps # → permission denied (GOOD)\ndocker ps -a --filter name=agentmem-sbx # rootful: none (GOOD)\n```\n\n**If linger ever gets cleared** (rootless daemon won't start at boot):\n`sudo loginctl enable-linger stronghold`.\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"118","text":"## 14. MCP server for Claude Code (`service/mcp-stronghold.js`)\n\nA stdio MCP server that bridges the public backend into Claude Code tools (the inverse\nof the LucidLink/ruflo MCP **clients** in §4–5). It is **not** a long-running service:\nthe MCP host (Claude Code) spawns it on demand and talks JSON-RPC over stdio, so there is\nnothing to start/stop here — only the backend (§1) must be up.\n\n**Provision / re-mint the token** (e.g. after a `JWT_SECRET` rotation):\n```bash\ncd /home/markt/agenticow-ruflo-memory\nnode service/mint-stronghold-token.mjs --url http://localhost:8771 --agent-type researcher\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"119","text":"# writes ~/.stronghold/mcp.json (chmod 600); reads JWT_SECRET from backend/.env, never prints it\n```\n\n**Register / inspect / remove**:\n```bash\nclaude mcp add stronghold --scope user -- node /home/markt/agenticow-ruflo-memory/service/mcp-stronghold.js\nclaude mcp get stronghold # status; expect ✔ Connected\nclaude mcp remove stronghold -s user\n```\n\n**Config** `~/.stronghold/mcp.json` (`{url, token, agent, defaultAgentType}`); each key is\noverridable by `STRONGHOLD_URL` / `STRONGHOLD_JWT` / `STRONGHOLD_AGENT` /\n`STRONGHOLD_DEFAULT_AGENT_TYPE` / `STRONGHOLD_CONFIG`. `url` defaults to `http://localhost:8771`\n(same box); point it at the Funnel (`…/agentmem/v1`) for off-box hosts.\n\n**Troubleshooting**\n- `token MISSING` in stderr → run the mint script (or set `STRONGHOLD_JWT`).\n- `401 unauthorized` → token invalid/expired or `JWT_SECRET` rotated → re-mint.\n- Server shows Connected but tools absent in a chat → MCP servers added mid-session become\n callable only after a **session reload/restart**. (The newest tool `stronghold_usage`\n (§15.2), shipped in the MCP server code, likewise appears only after a reload.)\n- Manual smoke test (no Claude needed):\n ```bash\n printf '%s\\n' \\\n '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{}}}' \\\n '{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"stronghold_health\",\"arguments\":{}}}' \\\n | node service/mcp-stronghold.js\n ```\n\nFull reference: `docs/HARNESS.md`.\n\n## 15. Extra LLM backends & token-usage metering\n\nStrongHold is no longer pinned to one local model + cloud: it routes to any model\nalready on the cluster Ollamas (§3) **and** any OpenAI-compatible server (vLLM,\nllama.cpp `--server`, TGI, Open WebUI, LM Studio), swappable purely by config with\nno code change. Every model call's token usage is now captured from the provider\nand metered. **Empty config = exactly prior behavior** (backward compatible).\n\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"120","text":"### 15.1 Activate extra LLM backends\n\nExtra **Ollama** models need **no config** — the pool is model-aware (each request\nroutes to a host that actually has the requested model, and the health gate no\nlonger demands the single `OLLAMA_MODEL`), so models already loaded on the cluster\nOllamas (`deepseek-r1:32b`, `qwen2.5:32b`, `llama3.1:70b`) are reachable + metered\nby name. Target one with a bare model name (the Ollama pool is never shadowed).\n\nFor any **OpenAI-compatible** server, register a named backend:\n\n```bash\ncd /home/markt/agenticow-ruflo-memory\ncp llm-backends.json.example llm-backends.json # fill {name,url,apiKey?,models?}\ncp tier-models.json.example tier-models.json # OPTIONAL: tier→model aliases\n# restart the internal service to pick up the new config (bang-shell sudo idiom):\nprintf '\\n' | sudo -S -p '' systemctl restart agentmem-internal\n```\n\n- Each entry is `{ name, url, apiKey?, models? }`. **Open WebUI on `:8080` needs a\n Bearer `apiKey`.** Target a backend with an explicit model slug `\"/\"`\n (e.g. `\"webui/llama3.1:70b\"`) — an explicit slug **wins** routing (route by what\n the model IS, not the tier's default order). Usage is metered under provider label\n `compat:`.\n- `tier-models.json` maps a tier to a specific cluster model, e.g.\n `{\"reason\":\"deepseek-r1:32b\",\"big\":\"webui/llama3.1:70b\"}`, so a bare `tier`\n resolves to that model.\n- **Both files are gitignored** (they hold API keys + private URLs); only the\n `*.example` templates are committed — secrets stay on the host. Config can\n alternatively come from env: `LLM_BACKENDS` (inline JSON array) /\n `LLM_BACKENDS_CONFIG` (path), and `TIER_MODELS` (inline JSON) /\n `TIER_MODELS_CONFIG` (path); optional `COMPAT_TIMEOUT_MS` (default `120000`)\n bounds compat backend calls (§8).\n\n### 15.2 Read token usage\n\n```bash\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"121","text":"# Cumulative since boot — totals + per-provider + per-model\ncurl -s -H \"x-api-key: \" localhost:8770/healthz | jq '.usageTotals'\n```\n\n- `usageTotals` = `{ totals, byProvider, byModel }`, each `{input, output, total,\n calls}`, since process start (each model/provider tracked by name; compat backends\n under `compat:`). Makes local (free/sovereign) vs cloud (paid) spend visible\n in real time, with no external dashboard.\n- **Per call:** chat/act/fanout responses now include a `usage` block; `act` and\n `fanout` SUM usage across every model call in the agentic loop / across all\n sub-agents.\n- **Per session:** the `stronghold_usage` MCP tool (§14) returns this Claude Code\n session's per-session totals + per-tool breakdown (client-side; no backend call).\n\n### 15.3 Verify a backend\n\n```bash\n# Confirm registered compat backends + tier aliases\ncurl -s -H \"x-api-key: \" localhost:8770/healthz | jq '.router.compat, .router.tierModels'\n```\n\n- `router.compat` is an array of registered backend names (or `false` if none).\n- **Compat backend:** an explicit-slug chat (e.g. model `\"webui/llama3.1:70b\"`)\n returns `provider: \"compat:\"` plus a `usage` block — that pair confirms the\n backend is live and metered.\n- **Extra Ollama models:** just call by name and confirm the model-aware route\n reaches a host that has it (usage then shows under that model in `byModel`).\n\n### Notes\n\n- The `stronghold_usage` tool ships in the MCP server code\n (`service/mcp-stronghold.js`), so it appears **only after a Claude Code session\n reload** (new MCP server code is loaded on respawn — §14).\n- The **Docker public backend (:8771) needs no rebuild** — it proxies\n chat/act/fanout (and thus the new `usage` field) **verbatim**.\n","path":"docs/OPS_RUNBOOK.md","title":"StrongHold — Operations Runbook","source_type":"doc","kind":"doc"} -{"id":"122","text":"# StrongHold\n\n*A sovereign Harness as a Service (HaaS).* A memory-centric AI agent harness — served as an\nAPI, running entirely on your own hardware (two NVIDIA DGX Spark supercomputers). Per-user\npersistent memory, recall-augmented chat, an agentic tool loop with a secure code sandbox,\nexternal tools via MCP, sub-agent fan-out, and a model router (local-first, with optional\nClaude / OpenRouter escalation) behind a one-word `tier` knob.\n\n**Highlights**\n\n- **Dual-GPU** — local inference is load-balanced across both DGX Sparks (true parallelism,\n automatic failover to the sibling GPU, then cloud).\n- **LucidLink files** — agents can read & search the team's LucidLink filespaces (read-only,\n via an MCP bridge) using the `files` / `research` tool profile.\n- **Per-task tool selection** — scope an agent's tools with one word (`profile`) or an explicit\n `tools` allowlist; enforced, not just advisory.\n- **Token/LLM usage metering** — every model call's token usage is captured from the provider and\n normalized to `{input, output, total}`. `chat` / `act` / `fanout` return a per-call `usage` block\n (summed across the agentic loop and sub-agents); the internal `/healthz` reports cumulative\n `usageTotals` `{ totals, byProvider, byModel }`; and the MCP server exposes a `stronghold_usage`\n tool for per-session, per-tool totals — per-model and per-backend cost attribution, no external\n dashboard.\n- **Config-driven multi-LLM routing** — no longer pinned to one local model + cloud. The Ollama pool\n is model-aware (extra cluster models like `deepseek-r1:32b` / `qwen2.5:32b` / `llama3.1:70b` are\n routable + metered by name with zero config), a generic OpenAI-compatible provider reaches any\n vLLM / llama.cpp / TGI / Open WebUI / LM Studio backend via an explicit `/` slug, and\n optional `tier`→model aliases map a one-word tier to a specific model — all swappable purely by\n config, backward-compatible (empty config = prior behavior).\n- **Use it from Claude Code** — a zero-dep stdio MCP server (`service/mcp-stronghold.js`) exposes\n the whole harness as native tools to Claude Code / any MCP host (see `docs/DEVELOPER_QUICKSTART.md` §14).\n- **Hardened & resilient** — runs as an unprivileged user on a rootless-Docker sandbox (a\n container escape ≠ host root), per-tenant rate limits, fail-closed auth, self-healing\n MCP/connection respawn, model-call timeouts + failover, and durable-before-ack memory.\n\n","path":"README.md","title":"StrongHold","source_type":"doc","kind":"doc"} -{"id":"123","text":"## Docs\n\n| Doc | For |\n|---|---|\n| [`docs/EXEC_BRIEF.md`](docs/EXEC_BRIEF.md) | Leadership — what it is and why it matters |\n| [`docs/DEVELOPER_QUICKSTART.md`](docs/DEVELOPER_QUICKSTART.md) | Engineers — auth, endpoints, the `tier` knob, examples |\n| [`docs/ARCHITECTURE_SECURITY.md`](docs/ARCHITECTURE_SECURITY.md) | Reviewers / security — design, threat model, risks |\n| [`docs/OPS_RUNBOOK.md`](docs/OPS_RUNBOOK.md) | Operators — run, monitor, configure, troubleshoot |\n| [`docs/HARNESS.md`](docs/HARNESS.md) | Full system reference (everything) |\n| [`docs/adr/`](docs/adr/README.md) | Architecture Decision Records — the *why* behind the load-bearing choices |\n| [`ROADMAP.md`](ROADMAP.md) | Where we are and what's next — multi-org gates + improvements |\n| [`backend/LOVABLE.md`](backend/LOVABLE.md) | Browser/Lovable client + paste-in prompt |\n\n## Layout\n\n```\nservice/ internal service (:8770) — memory, agent loop, sandbox, MCP, model router\nbackend/ public backend (:8771) — JWT auth, per-tenant scoping, proxy (Docker)\nsrc/ agenticow memory library (MemoryHub, Agent, durable store, ruflo bridge)\ndocs/ documentation (above)\nopenapi.yaml public API spec\n```\n\n## Configuration & secrets\n\nSecrets are **not** in this repo. They live in `/etc/agentmem-internal.env` (internal service)\nand `backend/.env` (backend) on the host — both git-ignored. See the env-var reference in\n`docs/OPS_RUNBOOK.md` and `docs/HARNESS.md`.\n\n> Early/internal version. See the residual-risk register in `docs/ARCHITECTURE_SECURITY.md`\n> before any broad or multi-organization rollout.\n","path":"README.md","title":"StrongHold","source_type":"doc","kind":"doc"} -{"id":"124","text":"# StrongHold — Roadmap\n\nWhere StrongHold is and what's next. StrongHold is **live, hardened, and multi-tenant\nisolated** today; nothing below blocks internal use or a controlled pilot. This doc\ntracks the path to broad multi-organization production and the improvements surfaced\nalong the way. Decisions live in [`docs/adr/`](docs/adr/README.md); this is the\nforward view.\n\n_Last updated: 2026-06-30._\n\n","path":"ROADMAP.md","title":"StrongHold — Roadmap","source_type":"doc","kind":"doc"} -{"id":"125","text":"## Shipped (context)\n\n- **Two-tier topology, dual-mode JWT auth, rootless-Docker privilege isolation,\n provider-agnostic model router, sovereign sandbox, MCP hub + tool profiles** —\n ADR-0001…0007, all live and verified.\n- **LucidLink read+write, one common namespace** — agents read and write a single\n sovereign source of truth, no handoffs (ADR-0008).\n- **Per-tenant memory isolation** — tenant-scoped graduation + recall; a tenant's\n learned knowledge never reaches another tenant (ADR-0009).\n- **Per-tenant filespace hard isolation** — each provisioned tenant gets its own\n end-to-end-encrypted LucidLink filespace, bridge-confined by the `confine-mcp.py`\n shim so a tenant key cannot reach any other filespace; one-command provisioning;\n proven end-to-end with a reference tenant (ADR-0010).\n- **Token/LLM usage metering + config-driven multi-model routing** — _DONE 2026-06-30\n (commit 68342fe)._ Every model call's token usage is captured and normalized\n `{input, output, total}`; `chat`/`act`/`fanout` return a per-call `usage` block,\n `/healthz` reports cumulative `usageTotals` `{ totals, byProvider, byModel }`, and the\n MCP server adds a `stronghold_usage` tool — per-model/per-backend cost attribution with\n no external dashboard. Routing is now config-driven: the Ollama pool is model-aware so\n extra cluster models (`deepseek-r1:32b`, `qwen2.5:32b`, `llama3.1:70b`) are routable +\n metered by name with zero config, plus a generic OpenAI-compatible provider and optional\n `tier`→model aliases — all backward-compatible (empty config = prior behavior). _Live in\n prod: metering + extra-Ollama-model routing. Coded but NOT yet activated: the extra\n non-Ollama backends (Open WebUI, vLLM) — they need API keys / private URLs in the\n gitignored `llm-backends.json` before use._\n\n## Near-term — the multi-org gates\n\nThese are what stand between \"pilot-ready\" and \"open multi-organization production.\"\n\n","path":"ROADMAP.md","title":"StrongHold — Roadmap","source_type":"doc","kind":"doc"} -{"id":"126","text":"### 1. Cloud-spend caps + sign-up controls · _priority: high_\nPaid model tiers (Claude / OpenRouter) cost money per call, and any user from an\nallowlisted Supabase project can authenticate. Per-tenant rate limiting and a global\nheavy-op cap already bound abuse *rate*; what's missing is a hard *spend* ceiling and\ntighter sign-up.\n- Per-tenant monthly spend cap with a kill-switch when exceeded.\n- Cost accounting per tenant (tokens × tier price), surfaced in health/admin.\n _(Token metering primitive shipped 2026-06-30 — `/healthz` `usageTotals` by\n provider/model; still TODO: per-tenant attribution × tier price + the spend cap itself.)_\n- Keep `SUPABASE_ALLOWED_REFS` tight; sign-up gating before opening registration.\n- _Ref: ARCHITECTURE_SECURITY risk #4._\n\n### 2. Retire the prototype HS256 token · _priority: medium_\nA long-lived single-secret HS256 token bypasses the Supabase allowlist path. Rotate\n`JWT_SECRET` and disable HS256 once all clients use Supabase asymmetric tokens.\n- _Ref: ARCHITECTURE_SECURITY risk #5._\n\n### 3. Self-service tenant provisioning UX · _priority: medium_\n`service/provision-tenant.sh` is fully scriptable today but operator-run. Wire it\nbehind the LucidLink workspace-manager gateway (or the product UI) so a tenant can be\nprovisioned (filespace + confined bridge + registry entry) without shell access, and\nadd a matching **deprovision** path (delete filespace, drop key + forced-command line,\nremove registry entry) as a first-class, audited operation.\n\n## Vendor-dependent — true token-level isolation\n\nThe biggest residual from ADR-0010: per-tenant filespaces give hard *cryptographic\ndata* separation, but the LucidLink **service-account token is workspace-admin scope**\nand lives on the Mac, so a Mac compromise still exposes every filespace. The shim\nconfines the spark-side key holders; it does not shrink the token's own power. Two ways\nto close this, both gated on a control-plane change:\n\n","path":"ROADMAP.md","title":"StrongHold — Roadmap","source_type":"doc","kind":"doc"} -{"id":"127","text":"### 4. Per-tenant scoped tokens · _depends on: LucidLink_\nIf LucidLink ships filespace-scoped service-account tokens (today every token is\nworkspace-admin), mint one per tenant and drop the shim's reliance — confinement would\nmove to the token itself. Track LucidLink's service-account roadmap.\n\n### 5. Per-tenant LucidLink *workspace* · _depends on: LucidLink account/billing_\nA separate workspace per tenant gives each its own token that can only see that\nworkspace's filespaces — real token-level isolation without waiting for scoped tokens.\nCreating workspaces is an account/billing operation outside the Service API we use for\nfilespaces; assess cost/automation before committing.\n\n## Later / nice-to-have\n\n- **Retroactive isolation** — ADR-0009 stops *new* cross-tenant leaks; pre-existing\n global-base content stays shared. A migration to re-scope or quarantine legacy\n global-base entries if a tenant needs a clean slate.\n- **Per-tenant filespace lifecycle & billing visibility** — storage/cost per tenant\n filespace surfaced for capacity planning as tenant count grows.\n- **mem-sync efficiency** — it opens the shared `agenticow` bridge even for a\n tenant-only sync (cheap, idempotent today; revisit at scale).\n- **Genericized external doc variants** — customer-facing versions of the doc set.\n- **Secrets manager** — move host env-file secrets behind a manager if the fleet grows\n (ARCHITECTURE_SECURITY risk #6).\n\n---\n\n_Deciders: markt (owner) with the StrongHold collaborators. Items are roughly ordered\nwithin each section; priorities are the owner's call._\n","path":"ROADMAP.md","title":"StrongHold — Roadmap","source_type":"doc","kind":"doc"} -{"id":"128","text":"{\n \"name\": \"agenticow-ruflo-memory\",\n \"version\": \"0.1.0\",\n \"private\": true,\n \"type\": \"module\",\n \"description\": \"Per-agent COW memory for ruflo-style multi-agent workflows, backed by agenticow + local all-MiniLM-L6-v2 embeddings.\",\n \"scripts\": {\n \"demo\": \"node demo.js\",\n \"start\": \"node service/server.js\"\n },\n \"dependencies\": {\n \"@anthropic-ai/sdk\": \"^0.106.0\",\n \"@huggingface/transformers\": \"^4.2.0\",\n \"agenticow\": \"^0.2.3\",\n \"fastify\": \"^5.9.0\"\n }\n}\n","path":"package.json","title":"package.json","source_type":"config","kind":"doc"} -{"id":"129","text":"Source src/agent-memory.js (full):\n// agent-memory.js — per-agent COW memory for ruflo-style multi-agent workflows.\n//\n// Model:\n// MemoryHub = one shared, embedded base memory (common knowledge).\n// Agent = a copy-on-write fork of the base (~162 B / ~7 ms regardless of\n// base size). Each agent reads base ∪ its own edits, child wins,\n// with private writes, tombstones, checkpoint/rollback, and the\n// ability to PROMOTE vetted learnings back into the shared base.\n//\n// Text is stored alongside each vector, so recall() returns the actual memory\n// content plus which lineage node it came from ('base' vs the agent's branch).\n\nimport { open, AgenticMemory } from 'agenticow';\nimport { embed, embedBatch, DIM } from './embedder.js';\n\n// Keep id spaces disjoint so base facts and per-agent private memories never\n// collide by accident (a real collision would mean \"agent overrides base fact\").\nconst BASE_ID_BASE = 1; // base knowledge: 1, 2, 3, ...\nconst AGENT_ID_BASE = 1_000_000_000; // agent N private: 1e9 + N*1e6 + seq\n\n// Return a vector per entry: use the persisted one when present, embed only the\n// rest — so a rehydrate from a vector-bearing durable log does ZERO embedding.\nasync function vectorsFor(entries) {\n const missing = [];\n for (let i = 0; i < entries.length; i++) if (!entries[i].vector) missing.push(i);\n const embedded = missing.length ? await embedBatch(missing.map((i) => entries[i].text)) : [];\n const out = new Array(entries.length);\n let m = 0;\n for (let i = 0; i < entries.length; i++) out[i] = entries[i].vector || embedded[m++];\n return out;\n}\n\n","path":"src/agent-memory.js","title":"agent-memory.js","source_type":"src","kind":"source"} -{"id":"130","text":"export class MemoryHub {\n /** @param {AgenticMemory} mem @param {string} path @param {import('./durable-store.js').DurableStore} [store] */\n constructor(mem, path, store = null) {\n this.mem = mem;\n this.path = path;\n this.store = store; // durable text log (source of truth across restarts)\n this._baseSeq = 0;\n this._agentCount = 0;\n }\n\n /** Create a fresh shared base memory at `path`. */\n static create(path, store = null) {\n const mem = open(path, { dimension: DIM, metric: 'cosine' });\n return new MemoryHub(mem, path, store);\n }\n\n /** Reopen a base saved earlier with hub.save(manifestPath). NOTE: agenticow\n * persists vectors but not text — prefer rebuilding from the DurableStore. */\n static load(manifestPath, store = null) {\n const mem = AgenticMemory.load(manifestPath);\n const hub = new MemoryHub(mem, manifestPath, store);\n hub._baseSeq = mem.status().totalVectors;\n return hub;\n }\n\n /** Re-ingest base records with explicit ids + text (rehydrate path). Uses each\n * entry's persisted vector; only entries WITHOUT one are (re-)embedded. */\n async ingestRaw(entries) {\n if (!entries.length) return;\n const vecs = await vectorsFor(entries);\n this.mem.ingest(entries.map((e, i) => ({ id: e.id, vector: vecs[i], text: e.text })));\n for (const e of entries) // advance the base id counter past anything restored\n if (e.id >= BASE_ID_BASE && e.id < AGENT_ID_BASE)\n this._baseSeq = Math.max(this._baseSeq, e.id - BASE_ID_BASE + 1);\n }\n\n /**\n * Embed and ingest shared knowledge into the base.\n * @param {string[]} facts\n * @returns {Promise} the ids assigned\n */\n async addKnowledge(facts) {\n const list = Array.isArray(facts) ? facts : [facts];\n const vecs = await embedBatch(list);\n const records = list.map((text, i) => ({\n id: BASE_ID_BASE + this._baseSeq + i,\n vector: vecs[i],\n text,\n }));\n this._baseSeq += list.length;\n this.mem.ingest(records);\n if (this.store) this.store.record('base', records);\n return records.map((r) => r.id);\n }\n\n /**\n * Spawn a per-agent COW branch off the shared base.\n * @param {string} name branch label (use the ruflo agentId to bind them)\n * @param {number} [idx] id-space slot; pass a stable value (e.g. derived\n * from the agentId) so private ids are reproducible.\n */\n spawn(name, idx = this._agentCount++) {\n const branch = this.mem.fork(name);\n return new Agent(branch, name, idx, this.store);\n }\n\n /** Top-k recall against the shared base only. */\n async recall(query, k = 5) {\n const v = await embed(query);\n return this.mem.query(v, k).map(hitToObj);\n }\n\n status() { return this.mem.status(); }\n save(manifestPath) { return this.mem.save(manifestPath); }\n close() { this.mem.close(); }\n}\n\n","path":"src/agent-memory.js","title":"agent-memory.js","source_type":"src","kind":"source"} -{"id":"131","text":"export class Agent {\n /** @param {AgenticMemory} branch @param {string} name @param {number} idx @param {import('./durable-store.js').DurableStore} [store] */\n constructor(branch, name, idx, store = null) {\n this.branch = branch;\n this.name = name;\n this.idx = idx;\n this.store = store;\n this._seq = 0;\n }\n\n _nextId() {\n return AGENT_ID_BASE + this.idx * 1_000_000 + this._seq++;\n }\n\n /** Re-ingest this branch's records with explicit ids + text (rehydrate path).\n * Uses persisted vectors; only entries WITHOUT one are (re-)embedded. */\n async ingestRaw(entries) {\n if (!entries.length) return;\n const vecs = await vectorsFor(entries);\n this.branch.ingest(entries.map((e, i) => ({ id: e.id, vector: vecs[i], text: e.text })));\n const base = AGENT_ID_BASE + this.idx * 1_000_000;\n for (const e of entries) this._seq = Math.max(this._seq, e.id - base + 1);\n }\n\n /**\n * Store a private memory for this agent only.\n * @param {string|string[]} text\n * @returns {Promise} ids written\n */\n async remember(text) {\n const list = Array.isArray(text) ? text : [text];\n const vecs = await embedBatch(list);\n const records = list.map((t, i) => ({ id: this._nextId(), vector: vecs[i], text: t }));\n this.branch.ingest(records);\n if (this.store) { this.store.record(this.name, records); await this.store.flushAsync(); } // durable before ack\n return records.map((r) => r.id);\n }\n\n /**\n * Inherit shared text into THIS branch with FRESH own-slot ids — used to replay\n * a tenant's graduated base (durable scope `tbase:`) into every one of\n * that tenant's agent branches, so they see their tenant's vetted learnings\n * without those learnings touching the cross-tenant global base.\n *\n * Unlike ingestRaw (which preserves source ids — wrong for foreign ids, they'd\n * corrupt this branch's _seq), this assigns ids in this agent's own id-space via\n * _nextId, and does NOT record to the durable store (the entries already live in\n * the durable `tbase:` scope; recording them under this agentId would\n * re-graduate them on the next DELETE and multiply them on every spawn).\n * @param {{id?:number,text:string,vector?:Float32Array}[]} entries\n * @returns {Promise} count inherited\n */\n async inherit(entries) {\n if (!entries || !entries.length) return 0;\n const vecs = await vectorsFor(entries);\n const records = entries.map((e, i) => ({ id: this._nextId(), vector: vecs[i], text: e.text }));\n this.branch.ingest(records);\n return records.length;\n }\n\n /** Recall over base ∪ this agent's private memories (child wins, tombstones masked). */\n async recall(query, k = 5) {\n const v = await embed(query);\n return this.branch.query(v, k).map(hitToObj);\n }\n\n /** Hide specific ids from this agent's view (tombstone). Works on base or private ids. */\n forget(ids) {\n return this.branch.delete(Array.isArray(ids) ? ids : [ids]);\n }\n\n /** Freeze a restore point before a risky batch. */\n checkpoint(label) { return this.branch.checkpoint(label); }\n\n /** Discard everything since the given checkpoint (or the last one). */\n rollback(checkpointId) { return this.branch.rollback(checkpointId); }\n\n /** What this agent has changed vs its parent: { added, overridden, deleted }. */\n diff() { return this.branch.diff(); }\n\n /** The COW chain for this agent (base → checkpoints → working). */\n lineage() { return this.branch.lineage(); }\n\n /**\n * Merge this agent's vetted learnings INTO the shared base, so every future\n * agent inherits them. Defaults to promoting into the fork's parent (the hub).\n * @param {MemoryHub} [hub]\n */\n promoteTo(hub) {\n return this.branch.promote(hub ? hub.mem : undefined);\n }\n\n close() { this.branch.close(); }\n}\n\n","path":"src/agent-memory.js","title":"agent-memory.js","source_type":"src","kind":"source"} -{"id":"132","text":"function hitToObj(h) {\n return { id: h.id, text: h.text, distance: Number(h.distance.toFixed(4)), source: h.branch };\n}\n","path":"src/agent-memory.js","title":"agent-memory.js","source_type":"src","kind":"source"} -{"id":"133","text":"Source src/durable-store.js (full):\n// durable-store.js — the persistence the agenticow .rvf manifest doesn't give us.\n//\n// agenticow saves VECTORS but not text payloads, so a reload loses all content.\n// This is a tiny append-only log of {id, text, scope} (scope = 'base' or an\n// agentId) that IS the durable source of truth. On boot the service rebuilds the\n// in-RAM agenticow index from this log by re-embedding the text (the embedder is\n// local + deterministic), so memory survives restarts/reboots WITH its text.\n\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n// Persist the embedding vector alongside the text so a restart doesn't have to\n// RE-EMBED the whole corpus (boot cost was O(N embeddings)). Stored compactly as\n// base64 of the Float32Array bytes.\nconst encV = (vec) => (vec ? Buffer.from(Float32Array.from(vec).buffer).toString('base64') : undefined);\nconst decV = (b64) => {\n if (!b64) return undefined;\n const buf = Buffer.from(b64, 'base64');\n return new Float32Array(buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength));\n};\n\n","path":"src/durable-store.js","title":"durable-store.js","source_type":"src","kind":"source"} -{"id":"134","text":"export class DurableStore {\n /** @param {string} filePath */\n constructor(filePath) {\n this.filePath = filePath;\n /** @type {{id:number, text:string, scope:string}[]} */\n this.entries = [];\n this._timer = null;\n if (fs.existsSync(filePath)) {\n const raw = fs.readFileSync(filePath, 'utf8');\n try {\n this.entries = JSON.parse(raw).entries || [];\n } catch {\n // NEVER silently blank a corrupt log — that's total memory loss. Preserve\n // it and refuse to start so an operator can inspect/restore.\n const bak = `${filePath}.corrupt.${Date.now()}`;\n try { fs.writeFileSync(bak, raw); } catch { /* best effort */ }\n throw new Error(`durable store ${filePath} is corrupt (backed up to ${bak}); refusing to start to avoid wiping memory.`);\n }\n }\n }\n\n /** Append memories. @param {string} scope @param {{id:number,text:string,vector?:Float32Array}[]} items */\n record(scope, items) {\n for (const r of (Array.isArray(items) ? items : [items])) {\n if (r && typeof r.id === 'number') {\n const e = { id: r.id, text: r.text, scope };\n const v = encV(r.vector);\n if (v) e.v = v; // persist embedding so rehydrate skips re-embedding\n this.entries.push(e);\n }\n }\n this._persist();\n }\n\n /**\n * Graduation: re-scope an agent's memories (ids unchanged). Targets the global\n * shared `base` by default (legacy), or a per-tenant base scope `tbase:`\n * so a tenant's vetted learnings stay isolated to that tenant.\n * @param {string} scope the agent scope to graduate\n * @param {string} [toScope] destination scope (default 'base')\n */\n graduate(scope, toScope = 'base') {\n let n = 0;\n for (const e of this.entries) if (e.scope === scope) { e.scope = toScope; n++; }\n if (n) this._persist();\n return n;\n }\n\n /** Drop a scope's memories entirely (e.g. a hard delete). */\n dropScope(scope) {\n const before = this.entries.length;\n this.entries = this.entries.filter((e) => e.scope !== scope);\n if (this.entries.length !== before) this._persist();\n }\n\n /** @returns {Map} scope -> entries */\n byScope() {\n const m = new Map();\n for (const e of this.entries) {\n if (!m.has(e.scope)) m.set(e.scope, []);\n m.get(e.scope).push({ id: e.id, text: e.text, vector: decV(e.v) });\n }\n return m;\n }\n\n count() { return this.entries.length; }\n\n _persist() {\n clearTimeout(this._timer);\n this._timer = setTimeout(() => this.flush(), 200);\n }\n\n /** Synchronous atomic write — call on shutdown to guarantee the latest is on disk. */\n flush() {\n clearTimeout(this._timer);\n fs.mkdirSync(path.dirname(this.filePath), { recursive: true });\n fs.writeFileSync(this.filePath + '.tmp', JSON.stringify({ entries: this.entries }));\n fs.renameSync(this.filePath + '.tmp', this.filePath);\n }\n\n /** Async atomic write — await before acknowledging a write so a 201 never lies\n * about durability (cancels the pending debounce; no double-write). */\n async flushAsync() {\n clearTimeout(this._timer);\n await fs.promises.mkdir(path.dirname(this.filePath), { recursive: true });\n await fs.promises.writeFile(this.filePath + '.tmp', JSON.stringify({ entries: this.entries }));\n await fs.promises.rename(this.filePath + '.tmp', this.filePath);\n }\n}\n","path":"src/durable-store.js","title":"durable-store.js","source_type":"src","kind":"source"} -{"id":"135","text":"Source src/embed-worker.js (full):\n// embed-worker.js — runs the MiniLM ONNX embedder in a worker_thread so the model\n// forward pass (CPU-bound) doesn't block the main event loop that serves all HTTP.\n// Receives { id, texts }, replies { id, ok, buffer } where buffer is a transferable\n// Float32Array of length texts.length*DIM (sliced back into per-text vectors).\n\nimport { parentPort } from 'node:worker_threads';\nimport { pipeline } from '@huggingface/transformers';\n\nconst MODEL_ID = 'Xenova/all-MiniLM-L6-v2';\nconst DIM = 384;\n\nlet extractorP = null;\nconst getExtractor = () => (extractorP ||= pipeline('feature-extraction', MODEL_ID));\n\nparentPort.on('message', async ({ id, texts }) => {\n try {\n const ex = await getExtractor();\n const out = await ex(texts, { pooling: 'mean', normalize: true });\n const data = Float32Array.from(out.data); // length = texts.length * DIM\n parentPort.postMessage({ id, ok: true, count: texts.length, buffer: data.buffer }, [data.buffer]);\n } catch (e) {\n parentPort.postMessage({ id, ok: false, error: String((e && e.message) || e) });\n }\n});\n","path":"src/embed-worker.js","title":"embed-worker.js","source_type":"src","kind":"source"} -{"id":"136","text":"Source src/embedder.js (full):\n// embedder.js — real text→vector embeddings, fully local.\n//\n// Uses Xenova/all-MiniLM-L6-v2 (384-dim, L2-normalized) via Transformers.js. The\n// forward pass is CPU-bound and would block the single Node event loop that serves\n// every HTTP request (recall embeds the query on EVERY call), so by default it runs\n// in a worker_thread (./embed-worker.js). If the worker can't start, we transparently\n// fall back to in-process embedding — same result, just on the main thread.\n//\n// Set EMBED_IN_PROCESS=1 to force the in-process path (e.g. for debugging).\n\nimport { Worker } from 'node:worker_threads';\n\nexport const MODEL_ID = 'Xenova/all-MiniLM-L6-v2';\nexport const DIM = 384;\n\nconst FORCE_IN_PROCESS = process.env.EMBED_IN_PROCESS === '1';\n\n// ── worker path ────────────────────────────────────────────────────────────────\nlet worker = null;\nlet workerBroken = FORCE_IN_PROCESS;\nlet nextId = 1;\nconst pending = new Map();\n\nfunction failWorker(err) {\n workerBroken = true;\n for (const p of pending.values()) p.reject(err);\n pending.clear();\n try { worker?.terminate(); } catch { /* ignore */ }\n worker = null;\n}\n\nfunction ensureWorker() {\n if (worker || workerBroken) return worker;\n try {\n worker = new Worker(new URL('./embed-worker.js', import.meta.url));\n worker.on('message', (msg) => {\n const p = pending.get(msg.id);\n if (!p) return;\n pending.delete(msg.id);\n if (msg.ok) {\n const all = new Float32Array(msg.buffer);\n const res = [];\n for (let i = 0; i < msg.count; i++) res.push(all.slice(i * DIM, (i + 1) * DIM));\n p.resolve(res);\n } else p.reject(new Error(msg.error));\n });\n worker.on('error', (e) => failWorker(e));\n worker.on('exit', () => { if (pending.size) failWorker(new Error('embed worker exited')); worker = null; });\n } catch {\n workerBroken = true;\n worker = null;\n }\n return worker;\n}\n\n","path":"src/embedder.js","title":"embedder.js","source_type":"src","kind":"source"} -{"id":"137","text":"function embedBatchWorker(texts) {\n const w = ensureWorker();\n if (!w) return Promise.reject(new Error('no embed worker'));\n const id = nextId++;\n return new Promise((resolve, reject) => {\n pending.set(id, { resolve, reject });\n w.postMessage({ id, texts });\n });\n}\n\n// ── in-process fallback ─────────────────────────────────────────────────────────\nlet _extractor = null;\nasync function getExtractor() {\n if (!_extractor) {\n const { pipeline } = await import('@huggingface/transformers');\n _extractor = await pipeline('feature-extraction', MODEL_ID);\n }\n return _extractor;\n}\nasync function embedBatchInProc(texts) {\n const ex = await getExtractor();\n const out = await ex(texts, { pooling: 'mean', normalize: true });\n const res = [];\n for (let i = 0; i < texts.length; i++) res.push(Float32Array.from(out.data.slice(i * DIM, (i + 1) * DIM)));\n return res;\n}\n\n// ── public API ───────────────────────────────────────────────────────────────────\n/** Embed many strings → Float32Array(384)[]. Worker thread if available, else in-proc. */\nexport async function embedBatch(texts) {\n if (texts.length === 0) return [];\n if (!workerBroken) {\n try { return await embedBatchWorker(texts); }\n catch { /* worker failed — fall through to in-process (and stay there) */ }\n }\n return embedBatchInProc(texts);\n}\n\n/** Embed one string → Float32Array(384). */\nexport async function embed(text) {\n return (await embedBatch([text]))[0];\n}\n","path":"src/embedder.js","title":"embedder.js","source_type":"src","kind":"source"} -{"id":"138","text":"Source src/ruflo-bridge.js (full):\n// ruflo-bridge.js — bind agenticow per-agent memory to REAL ruflo agent spawns.\n//\n// The durable ruflo agent registry (the one `mcp__ruflo__agent_spawn` writes,\n// shared with the MCP daemon) lives at:\n// ~/.claude-flow/swarm/swarm-state.json\n// { swarms: { : { status, agents: [, ...] } } }\n//\n// This bridge reads that registry and gives every LIVE agent its own\n// copy-on-write memory branch, keyed by agentId. So the flow is:\n//\n// mcp__ruflo__agent_spawn(...) → agentId lands in swarm-state.json\n// bridge.sync() → that agentId gets a COW memory branch\n// bridge.agent(agentId).remember / .recall / .forget\n// bridge.graduate(agentId) → promote its learnings into the shared base\n//\n// Branches are keyed by agentId and their private id-space is derived\n// deterministically from the agentId, so re-syncing is idempotent.\n\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nconst DEFAULT_REGISTRY = path.join(os.homedir(), '.claude-flow', 'swarm', 'swarm-state.json');\n// Authoritative per-agent status (status: 'idle'|'active'|'terminated'|...).\n// swarm-state.json only tracks swarm→agents membership and does NOT flip on\n// individual agent termination, so liveness must come from here.\nconst DEFAULT_AGENT_STORE = path.join(os.homedir(), '.claude-flow', 'agents', 'store.json');\n\n/** base36 random suffix, matching ruflo's `agent--` id format. */\nfunction rand(n = 6) {\n let s = '';\n while (s.length < n) s += Math.random().toString(36).slice(2);\n return s.slice(0, n);\n}\n\n/** Stable small int from an agentId, for a disjoint private id-space slot. */\nfunction slotFor(agentId) {\n let h = 2166136261;\n for (let i = 0; i < agentId.length; i++) {\n h ^= agentId.charCodeAt(i);\n h = Math.imul(h, 16777619);\n }\n return (h >>> 0) % 900000; // keep headroom under the 1e6 stride in agent-memory\n}\n\n","path":"src/ruflo-bridge.js","title":"ruflo-bridge.js","source_type":"src","kind":"source"} -{"id":"139","text":"export class RufloMemoryBridge {\n /**\n * @param {import('./agent-memory.js').MemoryHub} hub\n * @param {{registryPath?: string, agentStorePath?: string,\n * onGraduate?: (info: {agentId:string, agentType?:string,\n * promoted:{ingested:number,deleted:number}, reason:string}) => void}} [opts]\n */\n constructor(hub, opts = {}) {\n this.hub = hub;\n this.registryPath = opts.registryPath || DEFAULT_REGISTRY;\n this.agentStorePath = opts.agentStorePath || DEFAULT_AGENT_STORE;\n this.onGraduate = opts.onGraduate || null;\n /** @type {Map} */\n this.agents = new Map();\n /** @type {Map} agentId -> swarmId */\n this.swarmOf = new Map();\n /** @type {Map} agentId -> agentType (set by spawnAndBind) */\n this.typeOf = new Map();\n /** @type {Map} agentId -> tenant (set by spawnAndBind / read from the agent store) */\n this.tenantOfId = new Map();\n /** @type {Map} tenant -> live tenant-base branch\n * (base ∪ that tenant's graduated learnings) used for /memory/search. */\n this.tenantBases = new Map();\n this._watchers = [];\n }\n\n /** Parse the ruflo registry → [{ swarmId, status, agents: string[] }]. */\n readRegistry() {\n if (!fs.existsSync(this.registryPath)) return [];\n const raw = JSON.parse(fs.readFileSync(this.registryPath, 'utf8'));\n return Object.values(raw.swarms || {}).map((s) => ({\n swarmId: s.swarmId,\n status: s.status,\n agents: s.agents || [],\n }));\n }\n\n /** Full registry object for read-modify-write. */\n _readRaw() {\n if (!fs.existsSync(this.registryPath)) return { swarms: {}, version: '1.0.0' };\n return JSON.parse(fs.readFileSync(this.registryPath, 'utf8'));\n }\n\n _writeRaw(raw) {\n fs.mkdirSync(path.dirname(this.registryPath), { recursive: true });\n fs.writeFileSync(this.registryPath, JSON.stringify(raw, null, 2));\n }\n\n _readAgentStore() {\n if (!fs.existsSync(this.agentStorePath)) return { agents: {}, version: '1.0.0' };\n return JSON.parse(fs.readFileSync(this.agentStorePath, 'utf8'));\n }\n\n _writeAgentStore(store) {\n fs.mkdirSync(path.dirname(this.agentStorePath), { recursive: true });\n fs.writeFileSync(this.agentStorePath, JSON.stringify(store, null, 2));\n }\n\n /** agentId -> status ('idle'|'active'|'terminated'|...) from the per-agent store. */\n agentStatuses() {\n const m = new Map();\n // store.agents is an object keyed by agentId ({ \"\": {record} }).\n for (const a of Object.values(this._readAgentStore().agents || {})) m.set(a.agentId, a.status);\n return m;\n }\n\n // ── multi-tenant isolation ──────────────────────────────────────────────────\n // Each agent is tagged with its owning tenant (the JWT-derived user/project key\n // the public backend passes on spawn). Graduation re-scopes an agent's learnings\n // into a PER-TENANT durable scope `tbase:` (NOT the cross-tenant global\n // `base`), and every one of that tenant's agent branches inherits `tbase:`\n // at attach time — so a tenant's vetted learnings flow only to that tenant's\n // future agents, never across tenants. The global agenticow base stays reserved\n // for explicitly-curated shared infra (hub.addKnowledge), which is never fed by\n // auto-graduation. Untenanted agents (legacy / pre-tenant) keep the old behavior.\n\n /** The durable scope holding a tenant's graduated base. */\n _tbaseScope(tenant) { return `tbase:${tenant}`; }\n\n /** The tenant an agent belongs to (in-memory cache, else the persisted store). */\n tenantOf(agentId) {\n if (this.tenantOfId.has(agentId)) return this.tenantOfId.get(agentId);\n const rec = (this._readAgentStore().agents || {})[agentId];\n const t = rec?.tenant;\n if (t) this.tenantOfId.set(agentId, t);\n return t || null;\n }","path":"src/ruflo-bridge.js","title":"ruflo-bridge.js","source_type":"src","kind":"source"} -{"id":"140","text":". */\n _tbaseScope(tenant) { return `tbase:${tenant}`; }\n\n /** The tenant an agent belongs to (in-memory cache, else the persisted store). */\n tenantOf(agentId) {\n if (this.tenantOfId.has(agentId)) return this.tenantOfId.get(agentId);\n const rec = (this._readAgentStore().agents || {})[agentId];\n const t = rec?.tenant;\n if (t) this.tenantOfId.set(agentId, t);\n return t || null;\n }\n\n /** A tenant's graduated entries from the durable log ({id,text,vector}[]). */\n _tbaseEntries(tenant) {\n if (!this.hub.store) return [];\n return this.hub.store.byScope().get(this._tbaseScope(tenant)) || [];\n }\n\n /** Replay a tenant's graduated base into a freshly-attached agent branch. */\n async _replayTenantBase(agent, tenant) {\n if (!tenant) return 0;\n return agent.inherit(this._tbaseEntries(tenant));\n }\n\n /**\n * The live per-tenant base branch (base ∪ that tenant's graduated learnings),\n * used by /memory/search so a tenant searches only its own + shared-infra memory.\n * Built lazily and kept fresh as graduation appends to the tenant's tbase.\n */\n async tenantBase(tenant) {\n let a = this.tenantBases.get(tenant);\n if (!a) {\n a = this.hub.spawn(`tenant-base:${tenant}`, slotFor(`tenant-base:${tenant}`));\n await a.inherit(this._tbaseEntries(tenant));\n this.tenantBases.set(tenant, a);\n }\n return a;\n }\n\n /** True when ruflo considers this agent gone (terminated, or absent from a terminated swarm). */\n _isTerminated(agentId, statuses) {\n const st = statuses.get(agentId);\n if (st === 'terminated') return true;\n if (st === undefined) {\n // not in the per-agent store — gone only if its swarm is also terminated\n const swarmId = this.swarmOf.get(agentId);\n const sw = this.readRegistry().find((s) => s.swarmId === swarmId);\n return !sw || sw.status === 'terminated';\n }\n return false;\n }\n\n /**\n * Register a NEW ruflo agent in the shared registry AND bind it a COW memory\n * branch — the one-call equivalent of `mcp__ruflo__agent_spawn` + `sync()`.\n *\n * A standalone script can't call the MCP tool, so this writes the same\n * `swarm-state.json` store the MCP daemon and CLI read (read-modify-write).\n * The agent is therefore visible to `mcp__ruflo__swarm_status`, `agent_list`,\n * and `ruflo agent list`, exactly like an MCP-spawned one.\n *\n * @param {string} agentType\n * @param {{ swarmId?: string, agentId?: string, topology?: string, maxAgents?: number,\n * tenant?: string }} [opts] tenant tags the agent for per-tenant isolation\n * @returns {Promise<{ agentId: string, agentType: string, swarmId: string,\n * agent: import('./agent-memory.js').Agent }>}\n */\n async spawnAndBind(agentType, opts = {}) {\n const raw = this._readRaw();\n raw.swarms = raw.swarms || {};\n\n // Pick the target swarm: explicit id → that one; else the most-recent\n // running swarm; else create one (mirrors MCP swarm_init's schema).\n let swarm = opts.swarmId ? raw.swarms[opts.swarmId] : null;\n if (!swarm) {\n const running = Object.values(raw.swarms).filter((s) => s.status === 'running');\n swarm = running.sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1))[0];\n }\n if (!swarm) {\n const now = new Date().toISOString();\n const swarmId = `swarm-${Date.now()}-${rand(6)}`;\n swarm = {\n swarmId,\n topology: opts.topology || 'hierarchical',\n maxAgents: opts.maxAgents || 8,\n status: 'running',\n agents: [],\n tasks: [],\n config: {\n topology: opts.topology || 'hierarchical',\n maxAgents: opts.maxAgents || 8,\n strategy: 'specialized',\n communicationProtocol: 'message-bus',\n autoScaling: true,\n consensusMechanism: 'majority',\n },\n createdAt: now,\n updatedAt: now,\n };\n raw.swarms[swarmId] = swarm;\n }","path":"src/ruflo-bridge.js","title":"ruflo-bridge.js","source_type":"src","kind":"source"} -{"id":"141","text":": [],\n tasks: [],\n config: {\n topology: opts.topology || 'hierarchical',\n maxAgents: opts.maxAgents || 8,\n strategy: 'specialized',\n communicationProtocol: 'message-bus',\n autoScaling: true,\n consensusMechanism: 'majority',\n },\n createdAt: now,\n updatedAt: now,\n };\n raw.swarms[swarmId] = swarm;\n }\n\n const agentId = opts.agentId || `agent-${Date.now()}-${rand(6)}`;\n swarm.agents = swarm.agents || [];\n swarm.agents.push(agentId);\n swarm.updatedAt = new Date().toISOString();\n this._writeRaw(raw);\n\n // Also register in the per-agent store so the agent is first-class:\n // visible to agent_list / agent_status and terminable via agent_terminate.\n const store = this._readAgentStore();\n store.agents = store.agents || {};\n if (!store.agents[agentId]) {\n store.agents[agentId] = {\n agentId,\n agentType,\n status: 'idle',\n health: 1,\n taskCount: 0,\n config: { model: opts.model || 'inherit' },\n createdAt: new Date().toISOString(),\n model: opts.model || 'inherit',\n modelRoutedBy: 'explicit',\n tenant: opts.tenant || null, // persisted so graduate/rehydrate know the owner\n };\n this._writeAgentStore(store);\n }\n\n const agent = this.hub.spawn(agentId, slotFor(agentId));\n this.agents.set(agentId, agent);\n this.swarmOf.set(agentId, swarm.swarmId);\n this.typeOf.set(agentId, agentType);\n if (opts.tenant) {\n this.tenantOfId.set(agentId, opts.tenant);\n await this._replayTenantBase(agent, opts.tenant); // inherit this tenant's graduated base\n }\n return { agentId, agentType, swarmId: swarm.swarmId, agent };\n }\n\n /** The ruflo agentType recorded for a bound agent (if spawned via spawnAndBind). */\n typeOf_(agentId) {\n return this.typeOf.get(agentId);\n }\n\n /**\n * Attach a COW memory branch to every live ruflo agent that lacks one.\n * Idempotent — call it whenever new agents may have been spawned.\n * @param {{ swarmId?: string }} [filter]\n * @returns {{ liveSwarms: string[], attached: string[], total: number }}\n */\n sync(filter = {}) {\n const attached = [];\n const liveSwarms = [];\n for (const sw of this.readRegistry()) {\n if (sw.status !== 'running') continue;\n if (filter.swarmId && sw.swarmId !== filter.swarmId) continue;\n liveSwarms.push(sw.swarmId);\n for (const agentId of sw.agents) {\n if (this.agents.has(agentId)) continue;\n this.agents.set(agentId, this.hub.spawn(agentId, slotFor(agentId)));\n this.swarmOf.set(agentId, sw.swarmId);\n attached.push(agentId);\n }\n }\n return { liveSwarms, attached, total: this.agents.size };\n }\n\n /** The memory handle for a ruflo agent. Lazily re-attaches a branch after a\n * service restart for any agent ruflo still knows (its private memories are\n * restored separately by rehydrate(); an unknown/terminated id throws). */\n agent(agentId) {\n let a = this.agents.get(agentId);\n if (a) return a;\n if (this._knownAgent(agentId)) {\n a = this.hub.spawn(agentId, slotFor(agentId));\n this.agents.set(agentId, a);\n return a;\n }\n throw new Error(`no memory branch for ${agentId} — call sync() after it spawns`);\n }\n\n /** True if ruflo's durable stores still consider this agent live (survives our restart). */\n _knownAgent(agentId) {\n const rec = (this._readAgentStore().agents || {})[agentId];\n if (rec && rec.status !== 'terminated') return true;\n return this.readRegistry().some((s) => s.status === 'running' && s.agents.includes(agentId));\n }","path":"src/ruflo-bridge.js","title":"ruflo-bridge.js","source_type":"src","kind":"source"} -{"id":"142","text":"anch for ${agentId} — call sync() after it spawns`);\n }\n\n /** True if ruflo's durable stores still consider this agent live (survives our restart). */\n _knownAgent(agentId) {\n const rec = (this._readAgentStore().agents || {})[agentId];\n if (rec && rec.status !== 'terminated') return true;\n return this.readRegistry().some((s) => s.status === 'running' && s.agents.includes(agentId));\n }\n\n /**\n * Rebuild the in-RAM agenticow index from the DurableStore after a restart:\n * re-ingest base knowledge into the hub, and re-attach + refill each agent's\n * private branch. This is what makes memory (with text) survive restarts.\n */\n async rehydrate(store = this.hub.store) {\n if (!store) return { base: 0, agents: 0, tenantBases: 0 };\n const byScope = store.byScope();\n const baseEntries = byScope.get('base') || [];\n await this.hub.ingestRaw(baseEntries);\n const typeRecs = (this._readAgentStore().agents) || {};\n // 1. Per-tenant base branches (from `tbase:` scopes) for /memory/search.\n let tenantBases = 0;\n for (const [scope] of byScope) {\n if (!scope.startsWith('tbase:')) continue;\n const tenant = scope.slice('tbase:'.length);\n await this.tenantBase(tenant); // builds + inherits the tenant's graduated base\n tenantBases++;\n }\n // 2. Each agent's private branch (its own remembers), then inherit its tenant base.\n let agents = 0;\n for (const [scope, entries] of byScope) {\n if (scope === 'base' || scope.startsWith('tbase:')) continue; // not an agent scope\n const agent = this.hub.spawn(scope, slotFor(scope));\n await agent.ingestRaw(entries);\n this.agents.set(scope, agent);\n const rec = typeRecs[scope];\n if (rec?.agentType) this.typeOf.set(scope, rec.agentType);\n if (rec?.tenant) { this.tenantOfId.set(scope, rec.tenant); await this._replayTenantBase(agent, rec.tenant); }\n agents++;\n }\n // 3. Attach any tenant-tagged agent ruflo still knows but that has NO private\n // memories yet (so it wasn't covered above) — it still must see its tenant base.\n for (const [id, rec] of Object.entries(typeRecs)) {\n if (this.agents.has(id) || rec.status === 'terminated' || !rec.tenant) continue;\n const agent = this.hub.spawn(id, slotFor(id));\n this.agents.set(id, agent);\n if (rec.agentType) this.typeOf.set(id, rec.agentType);\n this.tenantOfId.set(id, rec.tenant);\n await this._replayTenantBase(agent, rec.tenant);\n agents++;\n }\n return { base: baseEntries.length, agents, tenantBases };\n }\n\n /** agentIds currently holding a memory branch. */\n list() {\n return [...this.agents.keys()];\n }","path":"src/ruflo-bridge.js","title":"ruflo-bridge.js","source_type":"src","kind":"source"} -{"id":"143","text":" slotFor(id));\n this.agents.set(id, agent);\n if (rec.agentType) this.typeOf.set(id, rec.agentType);\n this.tenantOfId.set(id, rec.tenant);\n await this._replayTenantBase(agent, rec.tenant);\n agents++;\n }\n return { base: baseEntries.length, agents, tenantBases };\n }\n\n /** agentIds currently holding a memory branch. */\n list() {\n return [...this.agents.keys()];\n }\n\n /**\n * Promote a ruflo agent's vetted learnings, then release its branch.\n * - Tenant-tagged agent → re-scope its learnings into the PER-TENANT base\n * `tbase:` (isolated; inherited only by that tenant's future agents).\n * The global agenticow base is NOT touched, so nothing leaks cross-tenant.\n * - Untenanted agent (legacy) → promote into the global shared base (old behavior).\n * @returns {Promise<{ ingested: number, deleted: number, tenant?: string }>}\n */\n async graduate(agentId) {\n const a = this.agent(agentId);\n const tenant = this.tenantOf(agentId);\n let res;\n if (tenant && this.hub.store) {\n const scope = this._tbaseScope(tenant);\n const promoted = this.hub.store.byScope().get(agentId) || []; // this agent's private entries\n const n = this.hub.store.graduate(agentId, scope); // private -> tenant base (durable)\n // Keep the live tenant-base branch fresh so /memory/search sees it immediately\n // (only if one is already materialized; otherwise it'll be built on first use).\n const tb = this.tenantBases.get(tenant);\n if (tb && promoted.length) await tb.inherit(promoted);\n res = { ingested: n, deleted: 0, tenant };\n } else {\n res = a.promoteTo(this.hub);\n if (this.hub.store) this.hub.store.graduate(agentId); // legacy: scope -> global base\n }\n if (this.hub.store) await this.hub.store.flushAsync(); // durable before we ack/close (no durability lie)\n a.close();\n this.agents.delete(agentId);\n this.swarmOf.delete(agentId);\n this.tenantOfId.delete(agentId);\n return res;\n }\n\n /**\n * Graduate-on-terminate, pull form: inspect ruflo's per-agent status store and\n * auto-graduate every bound agent ruflo now reports as terminated. Idempotent.\n * @returns {Array<{agentId:string, agentType?:string, promoted:{ingested:number,deleted:number}}>}\n */\n async reconcile() {\n const statuses = this.agentStatuses();\n const graduated = [];\n for (const agentId of [...this.agents.keys()]) {\n if (!this._isTerminated(agentId, statuses)) continue;\n const agentType = this.typeOf.get(agentId);\n const promoted = await this.graduate(agentId); // promotes learnings + closes branch\n const info = { agentId, agentType, promoted, reason: 'terminated' };\n graduated.push(info);\n if (this.onGraduate) this.onGraduate(info);\n }\n return graduated;\n }\n\n /**\n * Graduate-on-terminate, push form: watch ruflo's status store + swarm registry\n * and auto-reconcile whenever they change. Returns a stop() function.\n * @param {{ debounceMs?: number, pollMs?: number }} [opts]\n */\n watch(opts = {}) {\n const debounce = opts.debounceMs ?? 200;\n let timer = null;\n const fire = () => {\n clearTimeout(timer);\n timer = setTimeout(() => this.reconcile().catch((e) => { /* graduation is best-effort */ void e; }), debounce);\n };\n for (const p of [this.agentStorePath, this.registryPath]) {\n try {\n if (fs.existsSync(p)) this._watchers.push(fs.watch(p, fire));\n } catch {\n /* fs.watch unsupported here — fall back to polling below */\n }\n }\n // Safety-net poll (also covers platforms where fs.watch is flaky).\n if (opts.pollMs) this._watchers.push({ close: () => clearInterval(this._poll), _i: (this._poll = setInterval(() => this.reconcile().catch(() => {}), opts.pollMs)) });\n return () => this.unwatch();\n }\n\n unwatch() {\n for (const w of this._watchers) { try { w.close(); } catch {} }\n this._watchers = [];\n }","path":"src/ruflo-bridge.js","title":"ruflo-bridge.js","source_type":"src","kind":"source"} -{"id":"144","text":" }\n }\n // Safety-net poll (also covers platforms where fs.watch is flaky).\n if (opts.pollMs) this._watchers.push({ close: () => clearInterval(this._poll), _i: (this._poll = setInterval(() => this.reconcile().catch(() => {}), opts.pollMs)) });\n return () => this.unwatch();\n }\n\n unwatch() {\n for (const w of this._watchers) { try { w.close(); } catch {} }\n this._watchers = [];\n }\n\n /**\n * Explicit graduate-on-terminate: mark the agent terminated in ruflo's store\n * (and drop it from swarm membership), then graduate its learnings into the\n * base. Use this when YOUR code ends an agent. Pairs with spawnAndBind.\n * @returns {Promise<{agentId:string, promoted:{ingested:number,deleted:number}}>}\n */\n async terminateAndGraduate(agentId) {\n // 1. flip status in the per-agent store\n const store = this._readAgentStore();\n const rec = (store.agents || {})[agentId];\n if (rec) { rec.status = 'terminated'; rec.terminatedAt = new Date().toISOString(); this._writeAgentStore(store); }\n // 2. drop from swarm membership\n const raw = this._readRaw();\n for (const sw of Object.values(raw.swarms || {})) {\n if (sw.agents) sw.agents = sw.agents.filter((id) => id !== agentId);\n }\n this._writeRaw(raw);\n // 3. graduate memory (tenant-scoped if the agent is tenant-tagged)\n const agentType = this.typeOf.get(agentId);\n const promoted = await this.graduate(agentId);\n const info = { agentId, agentType, promoted, reason: 'explicit' };\n if (this.onGraduate) this.onGraduate(info);\n return info;\n }\n\n /**\n * Release an ephemeral agent WITHOUT graduating its learnings: close its\n * branch, drop it from the bridge, mark it terminated in ruflo's store + swarm,\n * and purge its durable memories. Used for short-lived fan-out workers.\n */\n dismiss(agentId) {\n const a = this.agents.get(agentId);\n if (a) { try { a.close(); } catch {} this.agents.delete(agentId); }\n this.swarmOf.delete(agentId);\n this.typeOf.delete(agentId);\n this.tenantOfId.delete(agentId);\n const store = this._readAgentStore();\n const rec = (store.agents || {})[agentId];\n if (rec) { rec.status = 'terminated'; rec.terminatedAt = new Date().toISOString(); this._writeAgentStore(store); }\n const raw = this._readRaw();\n for (const sw of Object.values(raw.swarms || {})) if (sw.agents) sw.agents = sw.agents.filter((id) => id !== agentId);\n this._writeRaw(raw);\n if (this.hub.store) this.hub.store.dropScope(agentId);\n }\n\n /** Release all branches (does not touch the shared base). */\n close() {\n this.unwatch();\n for (const a of this.agents.values()) a.close();\n for (const a of this.tenantBases.values()) { try { a.close(); } catch { /* ignore */ } }\n this.agents.clear();\n this.tenantBases.clear();\n }\n}\n","path":"src/ruflo-bridge.js","title":"ruflo-bridge.js","source_type":"src","kind":"source"} diff --git a/kb/stores/StrongHold/StrongHold-kb.rvf b/kb/stores/StrongHold/StrongHold-kb.rvf deleted file mode 100644 index 49c7d6c..0000000 Binary files a/kb/stores/StrongHold/StrongHold-kb.rvf and /dev/null differ diff --git a/kb/stores/StrongHold/StrongHold-kb.rvf.embed.json b/kb/stores/StrongHold/StrongHold-kb.rvf.embed.json deleted file mode 100644 index b82b54c..0000000 --- a/kb/stores/StrongHold/StrongHold-kb.rvf.embed.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "model": "Xenova/bge-small-en-v1.5", - "pooling": "mean", - "normalize": true, - "queryPrefix": "Represent this sentence for searching relevant passages: ", - "rankScale": 0.6 -} \ No newline at end of file diff --git a/kb/stores/StrongHold/StrongHold-kb.rvf.idmap.json b/kb/stores/StrongHold/StrongHold-kb.rvf.idmap.json deleted file mode 100644 index 203e83d..0000000 --- a/kb/stores/StrongHold/StrongHold-kb.rvf.idmap.json +++ /dev/null @@ -1 +0,0 @@ -{"idToLabel":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"23":23,"24":24,"25":25,"26":26,"27":27,"28":28,"29":29,"30":30,"31":31,"32":32,"33":33,"34":34,"35":35,"36":36,"37":37,"38":38,"39":39,"40":40,"41":41,"42":42,"43":43,"44":44,"45":45,"46":46,"47":47,"48":48,"49":49,"50":50,"51":51,"52":52,"53":53,"54":54,"55":55,"56":56,"57":57,"58":58,"59":59,"60":60,"61":61,"62":62,"63":63,"64":64,"65":65,"66":66,"67":67,"68":68,"69":69,"70":70,"71":71,"72":72,"73":73,"74":74,"75":75,"76":76,"77":77,"78":78,"79":79,"80":80,"81":81,"82":82,"83":83,"84":84,"85":85,"86":86,"87":87,"88":88,"89":89,"90":90,"91":91,"92":92,"93":93,"94":94,"95":95,"96":96,"97":97,"98":98,"99":99,"100":100,"101":101,"102":102,"103":103,"104":104,"105":105,"106":106,"107":107,"108":108,"109":109,"110":110,"111":111,"112":112,"113":113,"114":114,"115":115,"116":116,"117":117,"118":118,"119":119,"120":120,"121":121,"122":122,"123":123,"124":124,"125":125,"126":126,"127":127,"128":128,"129":129,"130":130,"131":131,"132":132,"133":133,"134":134,"135":135,"136":136,"137":137,"138":138,"139":139,"140":140,"141":141,"142":142,"143":143,"144":144},"labelToId":{"1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","10":"10","11":"11","12":"12","13":"13","14":"14","15":"15","16":"16","17":"17","18":"18","19":"19","20":"20","21":"21","22":"22","23":"23","24":"24","25":"25","26":"26","27":"27","28":"28","29":"29","30":"30","31":"31","32":"32","33":"33","34":"34","35":"35","36":"36","37":"37","38":"38","39":"39","40":"40","41":"41","42":"42","43":"43","44":"44","45":"45","46":"46","47":"47","48":"48","49":"49","50":"50","51":"51","52":"52","53":"53","54":"54","55":"55","56":"56","57":"57","58":"58","59":"59","60":"60","61":"61","62":"62","63":"63","64":"64","65":"65","66":"66","67":"67","68":"68","69":"69","70":"70","71":"71","72":"72","73":"73","74":"74","75":"75","76":"76","77":"77","78":"78","79":"79","80":"80","81":"81","82":"82","83":"83","84":"84","85":"85","86":"86","87":"87","88":"88","89":"89","90":"90","91":"91","92":"92","93":"93","94":"94","95":"95","96":"96","97":"97","98":"98","99":"99","100":"100","101":"101","102":"102","103":"103","104":"104","105":"105","106":"106","107":"107","108":"108","109":"109","110":"110","111":"111","112":"112","113":"113","114":"114","115":"115","116":"116","117":"117","118":"118","119":"119","120":"120","121":"121","122":"122","123":"123","124":"124","125":"125","126":"126","127":"127","128":"128","129":"129","130":"130","131":"131","132":"132","133":"133","134":"134","135":"135","136":"136","137":"137","138":"138","139":"139","140":"140","141":"141","142":"142","143":"143","144":"144"},"nextLabel":145} \ No newline at end of file diff --git a/kb/stores/StrongHold/StrongHold-primer.md b/kb/stores/StrongHold/StrongHold-primer.md deleted file mode 100644 index 33945e4..0000000 --- a/kb/stores/StrongHold/StrongHold-primer.md +++ /dev/null @@ -1,83 +0,0 @@ -# StrongHold — Human Primer - -## 1. What is StrongHold - -StrongHold is a sovereign, memory-centric AI-agent harness served as an API — described in the codebase as "Harness as a Service." The key distinction from a cloud AI-agent service is that it runs entirely on the owner's own hardware (two DGX Sparks), so data stays local. It exposes its capabilities over a public HTTPS endpoint via Tailscale Funnel, with JWT authentication on every request except the health check. - -The base URL is `https://spark-47d8.tail333a1d.ts.net/agentmem/v1`. - -## 2. What can it do for you - -StrongHold gives callers a set of durable, agentic primitives over a REST API: - -- **Persistent agent memory** — store text into a named agent's memory (`/memories`) and retrieve semantically relevant passages later (`/recall`). Memory survives restarts because it is backed by an append-only durable log (the source of truth), not just an in-memory vector index. -- **Chat and agentic loops** — `POST /agents/{id}/chat` streams responses via SSE; `/act` runs a multi-step tool-using loop; both accept an optional `tier` knob to select quality vs. speed without naming a model directly. -- **Sub-agent fan-out** — `/fanout` runs up to 8 ephemeral parallel workers against a list of tasks, then aggregates results and dismisses the workers. -- **Sovereign code sandbox** — `/sandbox/run` executes Python, Node, or Bash in a hardened ephemeral Docker container: no network, all capabilities dropped, read-only rootfs, non-root user, memory/CPU/pids/time limited. -- **Tool scoping** — per-call `profile` or explicit `tools` allowlist controls exactly which tools a model may invoke; calls to non-permitted tools are rejected at dispatch. -- **Graduate-on-terminate** — deleting an agent (`DELETE /agents/{id}`) promotes its memories before removal. - -## 3. What is it made of (the components) - -The repo contains one component: **agenticow-ruflo-memory**. - -It depends on four external packages: - -| Package | Role | -|---|---| -| `agenticow` | Copy-on-write vector branching ("Git for agent memory") — provides the `*.rvf` vector store | -| `@huggingface/transformers` | Local embedding generation (384-dimensional vectors) | -| `@anthropic-ai/sdk` | Cloud Claude integration for the `max` tier | -| `fastify` | HTTP server framework | - -The architecture is intentionally two-tier (ADR-0001): a small, dependency-light internet-facing backend handles auth, rate limiting, and tenant isolation; the internal harness holds model API keys, the memory corpus, MCP credentials, and the sandbox. The two tiers communicate over a strong `X-API-Key`. - -## 4. How it works - -**Memory persistence:** `agenticow` saves vectors but not text payloads. StrongHold solves this with an append-only durable log that stores both. On restart, the service rehydrates the vector index from the log, making memory deterministically exact across reboots (ADR-0002). - -**Authentication:** Bearer JWTs are verified in dual mode (ADR-0003). Supabase projects use asymmetric RS256/ES256/PS256 tokens — the backend fetches the JWKS from the token's own issuer, verifies the signature, and scopes memory to `:`. Long-lived HS256 tokens serve prototypes and local tooling. An allowlist of Supabase project refs (`SUPABASE_ALLOWED_REFS`) means the API fails closed by default. - -**Model routing:** Callers pass an optional `tier` rather than a model name (ADR-0005). `"fast"/"balanced"` uses a local model; omitting tier or passing `"auto"` tries local first, then falls over to cloud Claude, then OpenRouter. `"max"` targets cloud Claude Opus with the same fallback chain. Every response reports the `provider` and `model` that actually answered. Local inference runs across two DGX Sparks in parallel. - -**Security posture:** The harness runs as an unprivileged user under rootless Docker (ADR-0004), so a harness-level RCE does not imply host root. The sandbox adds a second containment layer with no network and a read-only filesystem. - -**Rate limiting:** Each tenant gets a token bucket (burst ~30, refill ~1/sec). Heavy operations (`act`, `fanout`, `chat`, `sandbox/run`) cost ~5 each. Exceeding limits returns `429` with a `Retry-After` header. Request bodies over ~1 MB return `413`. - -## 5. How do I install and use it - -No install command is documented in the repo. The quickstart is: - -```bash -npm run start -``` - -Additional documented commands: - -```bash -# Run the demo -npm run demo - -# Mint a StrongHold token for a specific agent type -node service/mint-stronghold-token.mjs --url http://localhost:8771 --agent-type researcher - -# Mint a token scoped to a colleague -node scripts/mint-token.js --sub colleague-name - -# Check running sandbox containers -docker ps -a --filter name=agentmem-sbx -``` - -A drop-in TypeScript client (`src/lib/agentMemory.ts`) is included. It wraps the REST API with typed helpers — `listAgents`, `spawn`, `remember`, `recall`, `searchBase` — and surfaces `Retry-After` on 429 responses. The `AgentMemory` object is the intended integration point for Lovable or any frontend. - -For Supabase-backed frontends, the backend automatically verifies real Supabase user tokens with no per-project setup beyond adding the project ref to `SUPABASE_ALLOWED_REFS` in `backend/.env`. - -## 6. Honest scope and limits - -- **Single-owner hardware.** StrongHold runs on two specific DGX Sparks. There is no documented path to running it on arbitrary hardware or in a generic cloud environment. -- **No published install steps.** The repo brief lists no install command. Getting the service running from scratch requires reading the source. -- **HS256 token risk.** A leaked prototype token maps all holders to one tenant until `JWT_SECRET` is rotated — acknowledged as a residual risk in ADR-0003. -- **Log-at-boot scaling.** The full durable log is read into memory at startup. This is noted as fine at current corpus size but flagged for revisit at very large scale (ADR-0002). -- **Two processes to operate.** The two-tier topology means two services to deploy, monitor, and keep in sync, plus the `owners.json` ownership map as a small stateful component the backend must persist. -- **Provider behavior depends on key configuration.** Which model actually runs for a given `tier` depends on which API keys are present. Behavior can differ between deployments without obvious indication to callers. -- **32 public symbols, 144 indexed passages.** This is a focused, single-component system — not a large framework with broad extension points. diff --git a/kb/stores/StrongHold/StrongHold-symbols.json b/kb/stores/StrongHold/StrongHold-symbols.json deleted file mode 100644 index cd2ab22..0000000 --- a/kb/stores/StrongHold/StrongHold-symbols.json +++ /dev/null @@ -1,378 +0,0 @@ -{ - "target": "StrongHold", - "metaName": "StrongHold", - "generated": "2026-07-01T02:41:57.961Z", - "method": "source-scan", - "count": 32, - "byKind": { - "class": 6, - "fn": 16, - "const": 10 - }, - "byCrate": { - "service/mcp-client.js": 2, - "service/ollama.js": 5, - "service/openai-compat.js": 5, - "service/openrouter.js": 4, - "service/router.js": 5, - "service/sandbox.js": 3, - "src/agent-memory.js": 2, - "src/durable-store.js": 1, - "src/embedder.js": 4, - "src/ruflo-bridge.js": 1 - }, - "symbols": [ - { - "name": "McpStdioClient", - "kind": "class", - "signature": "export class McpStdioClient", - "module": "service::mcp-client.js", - "crate": "service/mcp-client.js", - "doc": null, - "file": "service/mcp-client.js", - "line": 28, - "source": "source-scan" - }, - { - "name": "McpHub", - "kind": "class", - "signature": "export class McpHub", - "module": "service::mcp-client.js", - "crate": "service/mcp-client.js", - "doc": null, - "file": "service/mcp-client.js", - "line": 171, - "source": "source-scan" - }, - { - "name": "ollamaQueueDepth", - "kind": "fn", - "signature": "export function ollamaQueueDepth()", - "module": "service::ollama.js", - "crate": "service/ollama.js", - "doc": null, - "file": "service/ollama.js", - "line": 78, - "source": "source-scan" - }, - { - "name": "chat", - "kind": "fn", - "signature": "export async function chat({ messages, model = DEFAULT_MODEL, temperature = 0.7 })", - "module": "service::ollama.js", - "crate": "service/ollama.js", - "doc": null, - "file": "service/ollama.js", - "line": 95, - "source": "source-scan" - }, - { - "name": "chatRaw", - "kind": "fn", - "signature": "export async function chatRaw({ messages, tools, model = DEFAULT_MODEL, temperature = 0.3 })", - "module": "service::ollama.js", - "crate": "service/ollama.js", - "doc": null, - "file": "service/ollama.js", - "line": 110, - "source": "source-scan" - }, - { - "name": "health", - "kind": "fn", - "signature": "export async function health()", - "module": "service::ollama.js", - "crate": "service/ollama.js", - "doc": null, - "file": "service/ollama.js", - "line": 185, - "source": "source-scan" - }, - { - "name": "ollamaConfig", - "kind": "const", - "signature": "export const ollamaConfig =", - "module": "service::ollama.js", - "crate": "service/ollama.js", - "doc": null, - "file": "service/ollama.js", - "line": 194, - "source": "source-scan" - }, - { - "name": "compatAvailable", - "kind": "const", - "signature": "export const compatAvailable = BACKENDS.length > 0;", - "module": "service::openai-compat.js", - "crate": "service/openai-compat.js", - "doc": null, - "file": "service/openai-compat.js", - "line": 48, - "source": "source-scan" - }, - { - "name": "compatConfig", - "kind": "const", - "signature": "export const compatConfig =", - "module": "service::openai-compat.js", - "crate": "service/openai-compat.js", - "doc": null, - "file": "service/openai-compat.js", - "line": 49, - "source": "source-scan" - }, - { - "name": "resolveCompat", - "kind": "fn", - "signature": "export function resolveCompat(slug)", - "module": "service::openai-compat.js", - "crate": "service/openai-compat.js", - "doc": null, - "file": "service/openai-compat.js", - "line": 55, - "source": "source-scan" - }, - { - "name": "chat", - "kind": "fn", - "signature": "export async function chat({ backend, model, messages, temperature = 0.4 })", - "module": "service::openai-compat.js", - "crate": "service/openai-compat.js", - "doc": null, - "file": "service/openai-compat.js", - "line": 83, - "source": "source-scan" - }, - { - "name": "chatRaw", - "kind": "fn", - "signature": "export async function chatRaw({ backend, model, messages, tools, temperature = 0.3 })", - "module": "service::openai-compat.js", - "crate": "service/openai-compat.js", - "doc": null, - "file": "service/openai-compat.js", - "line": 89, - "source": "source-scan" - }, - { - "name": "openrouterAvailable", - "kind": "const", - "signature": "export const openrouterAvailable = !!OPENROUTER_API_KEY;", - "module": "service::openrouter.js", - "crate": "service/openrouter.js", - "doc": null, - "file": "service/openrouter.js", - "line": 13, - "source": "source-scan" - }, - { - "name": "openrouterConfig", - "kind": "const", - "signature": "export const openrouterConfig = { url: OPENROUTER_URL, defaultModel: DEFAULT_MODEL };", - "module": "service::openrouter.js", - "crate": "service/openrouter.js", - "doc": null, - "file": "service/openrouter.js", - "line": 14, - "source": "source-scan" - }, - { - "name": "chat", - "kind": "fn", - "signature": "export async function chat({ messages, model, temperature = 0.4 })", - "module": "service::openrouter.js", - "crate": "service/openrouter.js", - "doc": null, - "file": "service/openrouter.js", - "line": 41, - "source": "source-scan" - }, - { - "name": "chatRaw", - "kind": "fn", - "signature": "export async function chatRaw({ messages, tools, model, temperature = 0.3 })", - "module": "service::openrouter.js", - "crate": "service/openrouter.js", - "doc": null, - "file": "service/openrouter.js", - "line": 47, - "source": "source-scan" - }, - { - "name": "cloudAvailable", - "kind": "const", - "signature": "export const cloudAvailable = !!cloudClient;", - "module": "service::router.js", - "crate": "service/router.js", - "doc": null, - "file": "service/router.js", - "line": 63, - "source": "source-scan" - }, - { - "name": "routerInfo", - "kind": "const", - "signature": "export const routerInfo =", - "module": "service::router.js", - "crate": "service/router.js", - "doc": null, - "file": "service/router.js", - "line": 64, - "source": "source-scan" - }, - { - "name": "usageTotals", - "kind": "fn", - "signature": "export function usageTotals() { return usageTally; }", - "module": "service::router.js", - "crate": "service/router.js", - "doc": null, - "file": "service/router.js", - "line": 174, - "source": "source-scan" - }, - { - "name": "complete", - "kind": "fn", - "signature": "export async function complete({ messages, tier, model })", - "module": "service::router.js", - "crate": "service/router.js", - "doc": null, - "file": "service/router.js", - "line": 206, - "source": "source-scan" - }, - { - "name": "completeWithTools", - "kind": "fn", - "signature": "export async function completeWithTools({ messages, tools, tier, model })", - "module": "service::router.js", - "crate": "service/router.js", - "doc": null, - "file": "service/router.js", - "line": 233, - "source": "source-scan" - }, - { - "name": "sandboxLanguages", - "kind": "const", - "signature": "export const sandboxLanguages = Object.keys(RUNTIMES);", - "module": "service::sandbox.js", - "crate": "service/sandbox.js", - "doc": null, - "file": "service/sandbox.js", - "line": 19, - "source": "source-scan" - }, - { - "name": "sandboxQueueDepth", - "kind": "fn", - "signature": "export function sandboxQueueDepth() { return { active, queued: waiters.length, max: MAX_CONCURRENCY }; }", - "module": "service::sandbox.js", - "crate": "service/sandbox.js", - "doc": null, - "file": "service/sandbox.js", - "line": 30, - "source": "source-scan" - }, - { - "name": "runCode", - "kind": "fn", - "signature": "export async function runCode(opts = {})", - "module": "service::sandbox.js", - "crate": "service/sandbox.js", - "doc": null, - "file": "service/sandbox.js", - "line": 33, - "source": "source-scan" - }, - { - "name": "MemoryHub", - "kind": "class", - "signature": "export class MemoryHub", - "module": "src::agent-memory.js", - "crate": "src/agent-memory.js", - "doc": null, - "file": "src/agent-memory.js", - "line": 33, - "source": "source-scan" - }, - { - "name": "Agent", - "kind": "class", - "signature": "export class Agent", - "module": "src::agent-memory.js", - "crate": "src/agent-memory.js", - "doc": null, - "file": "src/agent-memory.js", - "line": 110, - "source": "source-scan" - }, - { - "name": "DurableStore", - "kind": "class", - "signature": "export class DurableStore", - "module": "src::durable-store.js", - "crate": "src/durable-store.js", - "doc": null, - "file": "src/durable-store.js", - "line": 22, - "source": "source-scan" - }, - { - "name": "MODEL_ID", - "kind": "const", - "signature": "export const MODEL_ID = 'Xenova/all-MiniLM-L6-v2';", - "module": "src::embedder.js", - "crate": "src/embedder.js", - "doc": null, - "file": "src/embedder.js", - "line": 13, - "source": "source-scan" - }, - { - "name": "DIM", - "kind": "const", - "signature": "export const DIM = 384;", - "module": "src::embedder.js", - "crate": "src/embedder.js", - "doc": null, - "file": "src/embedder.js", - "line": 14, - "source": "source-scan" - }, - { - "name": "embedBatch", - "kind": "fn", - "signature": "export async function embedBatch(texts)", - "module": "src::embedder.js", - "crate": "src/embedder.js", - "doc": null, - "file": "src/embedder.js", - "line": 85, - "source": "source-scan" - }, - { - "name": "embed", - "kind": "fn", - "signature": "export async function embed(text)", - "module": "src::embedder.js", - "crate": "src/embedder.js", - "doc": null, - "file": "src/embedder.js", - "line": 95, - "source": "source-scan" - }, - { - "name": "RufloMemoryBridge", - "kind": "class", - "signature": "export class RufloMemoryBridge", - "module": "src::ruflo-bridge.js", - "crate": "src/ruflo-bridge.js", - "doc": null, - "file": "src/ruflo-bridge.js", - "line": 46, - "source": "source-scan" - } - ] -} diff --git a/kb/stores/agent-harness-generator/agent-harness-generator-aiq-report.json b/kb/stores/agent-harness-generator/agent-harness-generator-aiq-report.json deleted file mode 100644 index 7888e46..0000000 --- a/kb/stores/agent-harness-generator/agent-harness-generator-aiq-report.json +++ /dev/null @@ -1,336 +0,0 @@ -{ - "target": "agent-harness-generator", - "judge": "claude-opus-4-1", - "seed": 19, - "generated": "2026-06-19T22:35:10.214Z", - "composite": 95, - "weakestDimension": "what-it-is", - "pass": true, - "questionsFile": "/Users/stuartkerr/Code/Ruv-Explainer/kb/questions/agent-harness-generator.aiq.jsonl", - "dimensionsScored": 8, - "dimensionsTotal": 8, - "perDimension": [ - { - "id": 1, - "key": "onboarding", - "name": "Onboarding (install/build/run/test)", - "n": 3, - "score": 96 - }, - { - "id": 2, - "key": "what-it-is", - "name": "What it is + problem it solves", - "n": 3, - "score": 95 - }, - { - "id": 3, - "key": "architecture", - "name": "Architecture (components + relations)", - "n": 3, - "score": 95 - }, - { - "id": 4, - "key": "capabilities", - "name": "Capabilities (features/commands/API)", - "n": 3, - "score": 96 - }, - { - "id": 5, - "key": "usage", - "name": "Usage (functions + signatures + example)", - "n": 3, - "score": 95 - }, - { - "id": 6, - "key": "best-practices", - "name": "Best practices / patterns / gotchas", - "n": 3, - "score": 96 - }, - { - "id": 7, - "key": "deep-dive", - "name": "Deep-dive (3 random buried files)", - "n": 3, - "score": 96 - }, - { - "id": 8, - "key": "extensibility", - "name": "Extensibility (safe modification)", - "n": 3, - "score": 95 - } - ], - "perQuestion": [ - { - "dimension": "onboarding", - "query": "I just got this repo. How do I install, scaffold a harness, build it, and run its tests from scratch? Give me the exact commands.", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides exact commands for install (npm install), scaffold (npx metaharness), build (npm run build), and test (npm test/npm run test) with complete workflow details.", - "top1": "PRIMER#7-how-do-i-start-the-fastest-end-to-end", - "contextChars": 30579 - }, - { - "dimension": "onboarding", - "query": "What is the fastest way to see metaharness actually produce a harness, with the least setup?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete instructions including the wizard command, direct scaffold command with flags, and post-generation steps.", - "top1": "docs/adrs/ADR-041-metaharness-as-program-synthesis.md", - "contextChars": 19704 - }, - { - "dimension": "onboarding", - "query": "How do I scaffold a coding harness for Claude Code in one command and then check it is healthy?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides the exact command to scaffold (npx metaharness) and the doctor command to check health, with full implementation details.", - "top1": "examples-packages/claude-code/package.json", - "contextChars": 27650 - }, - { - "dimension": "what-it-is", - "query": "What is metaharness and what specific problem does it solve for me?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides comprehensive information about what MetaHarness is (a CLI/Studio that generates AI agent harnesses from repos) and the specific problem it solves (avoiding forking ruflo, providing ownership, maintaining upgrade paths).", - "top1": "docs/adrs/ADR-041-metaharness-as-program-synthesis.md", - "contextChars": 17332 - }, - { - "dimension": "what-it-is", - "query": "Why would I use metaharness instead of forking ruflo, and what do I actually own after generating?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides comprehensive information about why to use metaharness instead of forking ruflo and what you own after generation, including specific details from ADR-016 and the PRIMER.", - "top1": "docs/adrs/ADR-016-migration-for-ruflo-users.md", - "contextChars": 17358 - }, - { - "dimension": "what-it-is", - "query": "What does 'the harness is the product, not the generator' mean in metaharness?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides the exact quote and its meaning from the PRIMER document, explaining that the harness is the wrapper/product around the model, not the generator itself.", - "top1": "docs/adrs/ADR-035-product-naming.md", - "contextChars": 15810 - }, - { - "dimension": "architecture", - "query": "What packages make up metaharness and how do they relate? What is the three-layer model?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides comprehensive details about MetaHarness's three-layer architecture, all package names, their relationships, and the dependency graph.", - "top1": "PRIMER#3-what-packages-make-up-metaharness", - "contextChars": 26348 - }, - { - "dimension": "architecture", - "query": "What is the kernel boundary and which packages are frozen vs free to change?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides comprehensive details about the kernel boundary, frozen packages, and change rules from ADR-002 and supporting files.", - "top1": "PRIMER#3-what-packages-make-up-metaharness", - "contextChars": 36774 - }, - { - "dimension": "architecture", - "query": "If I change the kernel, what is the contract I must honor and what could break downstream?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides comprehensive details about the kernel contract, breaking change rules, semver requirements, deprecation windows, and downstream impacts through multiple ADRs and source files.", - "top1": "PRIMER#8-how-do-i-extend-metaharness-safely-the-extension-points", - "contextChars": 36698 - }, - { - "dimension": "capabilities", - "query": "What can metaharness do? List the harness subcommands and what each does.", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides comprehensive information about harness subcommands through imports, documentation, and test files showing all available commands and their purposes.", - "top1": "PRIMER#2-what-can-the-tool-do-to-a-repo", - "contextChars": 36683 - }, - { - "dimension": "capabilities", - "query": "What can the tool do to a repo before and during scaffolding — scoring, genome, mcp-scan, threat-model, router, Darwin?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides comprehensive details about all six capabilities mentioned in the question through direct file content and structured artifacts.", - "top1": "PRIMER#2-what-can-the-tool-do-to-a-repo", - "contextChars": 36892 - }, - { - "dimension": "capabilities", - "query": "Which hosts can metaharness target and what are the main packages it ships?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context explicitly lists all 9 hosts and describes the main packages across the three-layer architecture with specific names.", - "top1": "PRIMER#3-what-packages-make-up-metaharness", - "contextChars": 37105 - }, - { - "dimension": "usage", - "query": "Show me how to define an agent, skill, and tool in code with the SDK — what are the functions and types and a real example?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides complete function signatures, types, and a real usage example showing how to define agents, skills, and tools with the SDK.", - "top1": "docs/adrs/ADR-062-example-pinecone.md", - "contextChars": 40319 - }, - { - "dimension": "usage", - "query": "What is the public API of the Router — how do I construct it, what does route() return, and what options does it take?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides Router's constructor via class definition, route() method signature in RouteResult interface, and RouterOptions interface with all fields.", - "top1": "packages/harness/src/router.ts", - "contextChars": 36709 - }, - { - "dimension": "usage", - "query": "What does a host adapter implement to turn a harness spec into config files? What is the function signature?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The HostAdapter interface definition and generateConfig signature are explicitly shown in packages/kernel-js/src/types.ts.", - "top1": "packages/create-agent-harness/src/host-config.ts", - "contextChars": 37309 - }, - { - "dimension": "best-practices", - "query": "Is metaharness production-ready? What are its honest limits and what should I treat with caution?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides comprehensive coverage of production readiness status, performance limits, gotchas, and honest limitations from multiple PRIMER sections.", - "top1": "PRIMER#5-is-this-production-ready-maturity-and-honest-limits", - "contextChars": 18669 - }, - { - "dimension": "best-practices", - "query": "What are the performance budgets and the native vs WASM kernel tradeoff I should know about?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides comprehensive details on performance budgets (≤90s, ≤5s, ≤10MB) and native vs WASM tradeoffs (3-5x speed difference, fallback behavior, determinism).", - "top1": "PRIMER#9-performance-and-gotchas-running-the-generator", - "contextChars": 18597 - }, - { - "dimension": "best-practices", - "query": "What are the gotchas around Codex trusted projects, Hermes thinking blocks, and the smoke gate?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides comprehensive details about all three gotchas: Codex trusted projects, Hermes thinking blocks, and the smoke gate.", - "top1": "docs/adrs/ADR-029-cross-language-invariants.md", - "contextChars": 22757 - }, - { - "dimension": "extensibility", - "query": "How do I add a new host to metaharness? Which interface do I implement and which reference adapter should I copy?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides the HostAdapter interface, reference adapter (host-claude-code), and explicit instructions in PRIMER#8 on how to add a new host.", - "top1": "docs/adrs/ADR-045-cli-scaffold-host-adapter-wiring.md", - "contextChars": 44488 - }, - { - "dimension": "extensibility", - "query": "How do I add or modify a template, and what is the scaffold/render pipeline that turns a template into a harness?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides complete details on template modification (renderer.ts, walker.ts), the scaffold/render pipeline (walkTemplate→render→writeAtomic), and template structure (ADR-003).", - "top1": "PRIMER#4-how-does-the-composer-scaffold-a-harness", - "contextChars": 46460 - }, - { - "dimension": "extensibility", - "query": "How do I add a new vertical pack and a marketplace plugin safely without breaking the kernel API?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides complete information on adding vertical packs (ADR-013 structure, VerticalPack interface) and marketplace plugins (ADR-005 schema, kernelEngines requirement, registry entry building) without breaking the kernel API (ADR-002 boundary rules).", - "top1": "docs/adrs/ADR-013-vertical-packs-publishing.md", - "contextChars": 45845 - }, - { - "dimension": "deep-dive", - "query": "Explain specifically what the file packages/create-agent-harness/templates/vertical_support/.claude-plugin/plugin.json.tmpl does and the key symbols it defines. What is its responsibility within the crate?", - "generated": true, - "deepFile": "packages/create-agent-harness/templates/vertical_support/.claude-plugin/plugin.json.tmpl", - "score": 95, - "missing": "nothing", - "reason": "The context provides the complete file content showing it's a Claude plugin manifest template with all fields (name, version, description, author, license, categories, tags, homepage) and their template variable placeholders.", - "top1": "packages/create-agent-harness/templates/vertical_support/package.json.tmpl", - "contextChars": 16708 - }, - { - "dimension": "deep-dive", - "query": "Explain specifically what the file packages/darwin-mode/src/openrouter-mutator.ts does and the key symbols it defines (it defines OpenRouterMutatorOptions, MutatorTelemetry, OpenRouterMutator). What is its responsibility within the crate?", - "generated": true, - "deepFile": "packages/darwin-mode/src/openrouter-mutator.ts", - "score": 98, - "missing": "nothing", - "reason": "The context provides the complete file content, all three key symbols with their definitions, and explains its role as an OpenRouter-backed CodeGenerator for mutation.", - "top1": "packages/darwin-mode/README.md", - "contextChars": 27935 - }, - { - "dimension": "deep-dive", - "query": "Explain specifically what the file packages/create-agent-harness/templates/vertical_advertising/tsconfig.json.tmpl does and the key symbols it defines. What is its responsibility within the crate?", - "generated": true, - "deepFile": "packages/create-agent-harness/templates/vertical_advertising/tsconfig.json.tmpl", - "score": 95, - "missing": "nothing", - "reason": "The context provides the complete file content showing it's a TypeScript config template with all compiler options, include/exclude patterns, and its role as a template in the create-agent-harness package.", - "top1": "packages/create-agent-harness/templates/vertical_trading/tsconfig.json.tmpl", - "contextChars": 15523 - } - ] -} diff --git a/kb/stores/agent-harness-generator/agent-harness-generator-coverage-report.json b/kb/stores/agent-harness-generator/agent-harness-generator-coverage-report.json deleted file mode 100644 index 4db3ad3..0000000 --- a/kb/stores/agent-harness-generator/agent-harness-generator-coverage-report.json +++ /dev/null @@ -1,273 +0,0 @@ -{ - "target": "agent-harness-generator", - "generated": "2026-06-19T21:58:52.967Z", - "pass": true, - "hardFail": false, - "checks": { - "coverageRatio": { - "value": 0.9841, - "pass": true, - "hardFail": false, - "threshold": 0.92, - "indexed": 247, - "authored": 251 - }, - "perComponentMin": { - "pass": true, - "thin": [], - "threshold": 3 - }, - "passageRatio": { - "value": 10.54, - "pass": true, - "threshold": 4, - "distinctSourceFiles": 247, - "passages": 2603 - }, - "spotCheck": { - "value": 0.95, - "pass": true, - "threshold": 0.8, - "hits": 19, - "of": 20 - } - }, - "sourceTypeCounts": { - "doc": 1523, - "test": 291, - "example": 299, - "config": 56, - "src": 423, - "(untagged)": 11 - }, - "summary": { - "authoredSourceFiles": 251, - "indexedAuthoredFiles": 247, - "coverage": 0.9841, - "totalPassages": 2603, - "distinctIndexedPaths": 920, - "passageRatio": 10.54, - "components": 18, - "thinComponents": 0 - }, - "notIndexedSample": [ - "crates/kernel/build.rs", - "crates/kernel-napi/build.rs", - "packages/create-agent-harness/templates/catalog.def.mjs", - "vitest.config.ts" - ], - "perComponent": [ - { - "component": "packages/agent-harness-generator-lib", - "passages": 7, - "ok": true - }, - { - "component": "packages/create-agent-harness", - "passages": 520, - "ok": true - }, - { - "component": "packages/darwin-mode", - "passages": 193, - "ok": true - }, - { - "component": "packages/harness", - "passages": 47, - "ok": true - }, - { - "component": "packages/host-claude-code", - "passages": 10, - "ok": true - }, - { - "component": "packages/host-codex", - "passages": 8, - "ok": true - }, - { - "component": "packages/host-copilot", - "passages": 10, - "ok": true - }, - { - "component": "packages/host-github-actions", - "passages": 14, - "ok": true - }, - { - "component": "packages/host-hermes", - "passages": 10, - "ok": true - }, - { - "component": "packages/host-openclaw", - "passages": 12, - "ok": true - }, - { - "component": "packages/host-opencode", - "passages": 12, - "ok": true - }, - { - "component": "packages/host-pi-dev", - "passages": 8, - "ok": true - }, - { - "component": "packages/host-rvm", - "passages": 20, - "ok": true - }, - { - "component": "packages/kernel-js", - "passages": 34, - "ok": true - }, - { - "component": "packages/router", - "passages": 27, - "ok": true - }, - { - "component": "packages/sdk", - "passages": 9, - "ok": true - }, - { - "component": "packages/vertical-base", - "passages": 11, - "ok": true - }, - { - "component": "packages/vertical-trading", - "passages": 6, - "ok": true - } - ], - "spotResults": [ - { - "file": "packages/create-agent-harness/__tests__/plugin-init.test.ts", - "indexed": true, - "retrieved": true, - "top1": "packages/create-agent-harness/__tests__/plugin-init.test.ts" - }, - { - "file": "packages/darwin-mode/__tests__/sandbox.test.ts", - "indexed": true, - "retrieved": true, - "top1": "packages/darwin-mode/src/repo_profiler.ts" - }, - { - "file": "packages/darwin-mode/__tests__/perf/mapLimit.test.ts", - "indexed": true, - "retrieved": true, - "top1": "packages/darwin-mode/src/repo_profiler.ts" - }, - { - "file": "packages/create-agent-harness/src/oia-manifest.ts", - "indexed": true, - "retrieved": true, - "top1": "packages/create-agent-harness/src/oia-manifest.ts" - }, - { - "file": "crates/kernel/src/claims.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/kernel/src/claims.rs" - }, - { - "file": "packages/darwin-mode/src/cli.ts", - "indexed": true, - "retrieved": true, - "top1": "packages/darwin-mode/src/cli.ts" - }, - { - "file": "packages/darwin-mode/src/repo_profiler.ts", - "indexed": true, - "retrieved": true, - "top1": "packages/darwin-mode/src/repo_profiler.ts" - }, - { - "file": "crates/kernel/build.rs", - "indexed": false, - "retrieved": false, - "top1": "docs/adrs/ADR-002-kernel-boundary.md" - }, - { - "file": "packages/create-agent-harness/__tests__/repo-scorecard.test.ts", - "indexed": true, - "retrieved": true, - "top1": "packages/create-agent-harness/__tests__/repo-scorecard.test.ts" - }, - { - "file": "packages/harness/src/consensus.ts", - "indexed": true, - "retrieved": false, - "top1": "docs/USAGE.md" - }, - { - "file": "examples/federation/federation.mjs", - "indexed": true, - "retrieved": true, - "top1": "examples/federation/federation.mjs" - }, - { - "file": "packages/kernel-js/__tests__/memory-rvf.test.ts", - "indexed": true, - "retrieved": true, - "top1": "packages/kernel-js/__tests__/memory-rvf.test.ts" - }, - { - "file": "packages/kernel-js/src/memory.ts", - "indexed": true, - "retrieved": true, - "top1": "packages/kernel-js/src/index.ts" - }, - { - "file": "packages/harness/src/index.ts", - "indexed": true, - "retrieved": false, - "top1": "docs/USAGE.md" - }, - { - "file": "__tests__/harness-diag.test.ts", - "indexed": true, - "retrieved": true, - "top1": "__tests__/harness-diag.test.ts" - }, - { - "file": "__tests__/harness-wizard.test.ts", - "indexed": true, - "retrieved": true, - "top1": "__tests__/harness-wizard.test.ts" - }, - { - "file": "packages/create-agent-harness/src/federate.ts", - "indexed": true, - "retrieved": true, - "top1": "packages/create-agent-harness/src/index.ts" - }, - { - "file": "packages/darwin-mode/__tests__/e2e/safety-invariant.e2e.test.ts", - "indexed": true, - "retrieved": false, - "top1": "packages/darwin-mode/src/safety.ts" - }, - { - "file": "packages/kernel-js/__tests__/dispatch.test.ts", - "indexed": true, - "retrieved": true, - "top1": "packages/kernel-js/src/index.ts" - }, - { - "file": "__tests__/cli-flags-completions.test.ts", - "indexed": true, - "retrieved": true, - "top1": "__tests__/cli-flags-completions.test.ts" - } - ] -} diff --git a/kb/stores/photonlayer/photonlayer-aiq-report.json b/kb/stores/photonlayer/photonlayer-aiq-report.json deleted file mode 100644 index 9a011ff..0000000 --- a/kb/stores/photonlayer/photonlayer-aiq-report.json +++ /dev/null @@ -1,336 +0,0 @@ -{ - "target": "photonlayer", - "judge": "claude-sonnet-4-5", - "seed": 7, - "generated": "2026-06-19T22:04:30.498Z", - "composite": 97.3, - "weakestDimension": "architecture", - "pass": true, - "questionsFile": "/Users/stuartkerr/Code/Ruv-Explainer/kb/questions/photonlayer.aiq.jsonl", - "dimensionsScored": 8, - "dimensionsTotal": 8, - "perDimension": [ - { - "id": 1, - "key": "onboarding", - "name": "Onboarding (install/build/run/test)", - "n": 3, - "score": 98 - }, - { - "id": 2, - "key": "what-it-is", - "name": "What it is + problem it solves", - "n": 3, - "score": 98 - }, - { - "id": 3, - "key": "architecture", - "name": "Architecture (components + relations)", - "n": 3, - "score": 97.3 - }, - { - "id": 4, - "key": "capabilities", - "name": "Capabilities (features/commands/API)", - "n": 3, - "score": 98 - }, - { - "id": 5, - "key": "usage", - "name": "Usage (functions + signatures + example)", - "n": 3, - "score": 98 - }, - { - "id": 6, - "key": "best-practices", - "name": "Best practices / patterns / gotchas", - "n": 3, - "score": 98 - }, - { - "id": 7, - "key": "deep-dive", - "name": "Deep-dive (3 random buried files)", - "n": 3, - "score": 98 - }, - { - "id": 8, - "key": "extensibility", - "name": "Extensibility (safe modification)", - "n": 3, - "score": 98 - } - ], - "perQuestion": [ - { - "dimension": "onboarding", - "query": "I just got this repo. How do I install, build, run, and test PhotonLayer from scratch? Give me the exact commands.", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides exact install/build/run/test commands, workspace structure, crate dependencies, and multiple example commands with categories — a complete onboarding answer is trivially composable from the shown material.", - "top1": "PRIMER#7-how-do-i-install-and-run-it-end-to-end", - "contextChars": 26898 - }, - { - "dimension": "onboarding", - "query": "What is the fastest way to see PhotonLayer actually run something with no setup, and what is the first example I should run locally?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides the fastest no-setup path (live browser demo URL), the first local example to run (hello_optics with exact command), installation steps, and a complete examples ladder with descriptions and commands.", - "top1": "PRIMER#7-how-do-i-install-and-run-it-end-to-end", - "contextChars": 18475 - }, - { - "dimension": "onboarding", - "query": "How do I run PhotonLayer in a browser, and which crate provides the WebAssembly bindings?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context explicitly states photonlayer-wasm provides WebAssembly bindings and shows the exact wasm-pack build command and local server command to run the browser demo.", - "top1": "PRIMER#3-what-is-photonlayer-made-of-the-four-crates", - "contextChars": 17858 - }, - { - "dimension": "what-it-is", - "query": "What is PhotonLayer and what specific problem does it solve for me?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete, specific answers to what PhotonLayer is (deterministic optical-AI front end, learned phase mask system) and what problems it solves (data reduction, faster/cheaper decisions, privacy by physics, deterministic receipts), with concrete examples and benchmarks.", - "top1": "PRIMER#1-what-is-photonlayer", - "contextChars": 15117 - }, - { - "dimension": "what-it-is", - "query": "How is PhotonLayer different from a normal camera plus a neural network, and what does the sensor actually capture?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete, specific answers: normal camera captures all pixels then processes vs PhotonLayer's phase mask compresses light optically before digitization, and the sensor captures a tiny compressed measurement (e.g., 4 pixels at 64× reduction) of task-useful information, not a viewable image.", - "top1": "PRIMER#1-what-is-photonlayer", - "contextChars": 15314 - }, - { - "dimension": "what-it-is", - "query": "What does a 'learned phase mask' do, and what is the receipt that every run emits?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context fully explains what a learned phase mask does (compresses light into task-useful information before digitization) and what the receipt is (a BLAKE3-bound record of input_hash, mask_hash, config_hash, output_hash, metrics_hash, provenance, and rvf_receipt_hash that proves reproducibility).", - "top1": "PRIMER#4-how-the-optical-pipeline-works-step-by-step", - "contextChars": 16745 - }, - { - "dimension": "architecture", - "query": "What crates make up PhotonLayer and how do they depend on each other? Which crate is the foundation?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides the four crates, their purposes, and the complete dependency graph showing photonlayer-core as the foundation with all others depending on it.", - "top1": "PRIMER#3-what-is-photonlayer-made-of-the-four-crates", - "contextChars": 13752 - }, - { - "dimension": "architecture", - "query": "If I change something in photonlayer-core, which other crates could be affected?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The dependency graph explicitly shows all crates that depend on photonlayer-core (photonlayer-bench, photonlayer-wasm, photonlayer-cli), providing a complete answer to which crates could be affected by changes.", - "top1": "crates/photonlayer-core/src/metrics.rs", - "contextChars": 14622 - }, - { - "dimension": "architecture", - "query": "Which crate owns the optical simulator versus the training and benchmarks, and what does each module in core do?", - "generated": false, - "deepFile": null, - "score": 96, - "missing": "nothing", - "reason": "The context provides the crate ownership (core owns simulator, bench owns training/benchmarks) and describes each core module's purpose (field, mask, propagate, detector, metrics, receipt, rng, simulator, etc.).", - "top1": "PRIMER#3-what-is-photonlayer-made-of-the-four-crates", - "contextChars": 27285 - }, - { - "dimension": "capabilities", - "query": "What can PhotonLayer do? List its features: compression, gradient training, multi-plane cascade, and receipts.", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "All four features (compression, gradient training, multi-plane cascade, receipts) are explicitly detailed with concrete numbers, commands, and implementation specifics across the README, PRIMER, and code.", - "top1": "PRIMER#2-what-can-photonlayer-do", - "contextChars": 33509 - }, - { - "dimension": "capabilities", - "query": "Which CLI subcommands does PhotonLayer expose and what does each do?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The CLI subcommands, their purposes, and invocation patterns are explicitly documented in main.rs and the entrypoints artifact.", - "top1": "PRIMER#3-what-is-photonlayer-made-of-the-four-crates", - "contextChars": 32165 - }, - { - "dimension": "capabilities", - "query": "What are PhotonLayer's measured results — the accuracy numbers for gradient training and the multi-plane cascade at 16x compression?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The gradient training accuracy (83.30% at 16× compression) and multi-plane cascade results (2 planes → 88.80%, 3 planes → 89.80%) are explicitly stated in PRIMER#2 and README.md, with the 2-plane 88.80% noted as the robust headline.", - "top1": "crates/photonlayer-bench/tests/cascade_gradient_check.rs", - "contextChars": 35006 - }, - { - "dimension": "usage", - "query": "Show me how to run the optical simulator in photonlayer-core — what are the key types and a real minimal example?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "All key types (ScalarSimulator, InputImage, PhaseMask, OpticalConfig, OpticalFrame), their constructors/methods, and a complete minimal example are present in the context.", - "top1": "crates/photonlayer-core/src/simulator.rs", - "contextChars": 39734 - }, - { - "dimension": "usage", - "query": "What is the public API of the phase mask — how do I create a random, designed, or learned PhaseMask?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete constructor signatures (new, identity, random, lens), full method signatures (apply, phase_histogram), the struct definition with all fields, and concrete usage examples from multiple sources.", - "top1": "PRIMER#4-how-the-optical-pipeline-works-step-by-step", - "contextChars": 30654 - }, - { - "dimension": "usage", - "query": "How do I propagate an optical field and run a diffraction step — what function and propagation modes are available?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides the propagate function signature, all three PropagationMode variants (Fresnel/Fraunhofer/AngularSpectrum), the Propagator struct with propagate/propagate_into methods, a complete working example (propagation_modes.rs), and the full propagate.rs source showing how to call it — everything needed for a correct, complete answer.", - "top1": "crates/photonlayer-core/examples/propagation_modes.rs", - "contextChars": 40636 - }, - { - "dimension": "best-practices", - "query": "Is PhotonLayer production-ready? What are its honest limits around hardware, privacy, and the accuracy figures?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides comprehensive, specific answers to all three dimensions: production-readiness (simulator, not hardware), hardware limits (power-of-two grids, MAX_GRID_DIM=4096, memory scaling), privacy (linear probe only, no guarantee), and accuracy figures (73% hill-climb, 83.30% gradient, 88.80% 2-plane, 89.80% 3-plane, all noise-free continuous-phase simulation).", - "top1": "PRIMER#5-is-it-production-ready-scope-and-honest-limits", - "contextChars": 18973 - }, - { - "dimension": "best-practices", - "query": "What should I treat with caution in PhotonLayer — what does the privacy probe actually measure and what does the 16x MAC reduction count?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The PRIMER#5 passage explicitly states what the privacy probe measures (linear invertibility only, not a guarantee) and what the 16× MAC reduction counts (digital decoder only, 640 vs 10,240, optical transform not counted), plus the privacy_probe.rs example confirms the linear-attack methodology with the honest caveat printed in output.", - "top1": "PRIMER#9-performance-determinism-and-gotchas", - "contextChars": 14139 - }, - { - "dimension": "best-practices", - "query": "What are the gotchas around memory, grid size, determinism, and training when running PhotonLayer?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The PRIMER#9 passage directly and comprehensively answers all four dimensions (memory, grid size, determinism, training) with concrete specifics: MAX_GRID_DIM=4096, power-of-two requirement, memory formula (8 bytes/pixel, 134MB for 4096²), determinism guarantees within-platform with the libm cross-platform gap, training ceilings (73% hill-climb, 83.30% gradient, 88.80% 2-plane, 89.80% 3-plane init-sensitive), and all relevant gotchas.", - "top1": "PRIMER#9-performance-determinism-and-gotchas", - "contextChars": 24472 - }, - { - "dimension": "extensibility", - "query": "If I want to add a new propagation mode or diffraction model, where does it go and what is the contract I must satisfy (forward and adjoint)?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides the exact enum location (config.rs), the implementation file (propagate.rs with transfer_kernel and Propagator::backward_into), the adjoint contract (conj(H) for transfer modes, validated via ⟨P(a),b⟩==⟨a,Pᴴ(b)⟩), and the test location (gradient_check.rs) — all concrete facts the question demands.", - "top1": "PRIMER#8-how-do-i-extend-photonlayer-safely-the-extension-points", - "contextChars": 40402 - }, - { - "dimension": "extensibility", - "query": "How would I safely add a new phase mask type or training method to photonlayer-bench without breaking the core or wasm crates?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete extension points (PRIMER#8), full source for both training methods (learn.rs, grad_train.rs, grad_cascade.rs), the PhaseMask API (mask.rs), the crate dependency graph, and the stable prelude contract — everything needed to write a correct, specific answer.", - "top1": "crates/photonlayer-bench/src/grad_train.rs", - "contextChars": 41031 - }, - { - "dimension": "extensibility", - "query": "Where do I add a new CLI subcommand or a new wasm binding, and what wires the Rust simulator to JavaScript?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context shows the CLI subcommand dispatch in main.rs (match args.first() over \"bench\", \"barcode\", etc.), the WASM #[wasm_bindgen] pattern in lib.rs (simulate, compress, verify_receipt_json), and the ScalarSimulator trait/struct wiring Rust to JS via photonlayer-core → photonlayer-wasm.", - "top1": "crates/photonlayer-core/src/simulator.rs", - "contextChars": 52873 - }, - { - "dimension": "deep-dive", - "query": "Explain specifically what the file crates/photonlayer-bench/tests/mnist_gradient_bench.rs does and the key symbols it defines. What is its responsibility within the crate?", - "generated": true, - "deepFile": "crates/photonlayer-bench/tests/mnist_gradient_bench.rs", - "score": 98, - "missing": "nothing", - "reason": "The full file body, its imports, constants, helper functions, and test structure are all present; the question is fully answerable from the provided context.", - "top1": "crates/photonlayer-bench/src/mnist.rs", - "contextChars": 22799 - }, - { - "dimension": "deep-dive", - "query": "Explain specifically what the file crates/photonlayer-core/src/propagate.rs does and the key symbols it defines (it defines propagate, propagate, Propagator, new, new). What is its responsibility within the crate?", - "generated": true, - "deepFile": "crates/photonlayer-core/src/propagate.rs", - "score": 98, - "missing": "nothing", - "reason": "The full file body, module doc, all key symbols (propagate fn, Propagator struct, new method, propagate method), their signatures, and implementation details are present in the context.", - "top1": "crates/photonlayer-core/src/propagate.rs", - "contextChars": 21897 - }, - { - "dimension": "deep-dive", - "query": "Explain specifically what the file crates/photonlayer-bench/src/privacy.rs does and the key symbols it defines (it defines privacy, clone, fmt, serialize, deserialize). What is its responsibility within the crate?", - "generated": true, - "deepFile": "crates/photonlayer-bench/src/privacy.rs", - "score": 98, - "missing": "nothing", - "reason": "The full file body, module doc, struct definition with all three fields, and all five derived trait methods (clone, fmt, serialize, deserialize, plus the privacy_leakage function) are explicitly shown in the context.", - "top1": "crates/photonlayer-bench/src/privacy.rs", - "contextChars": 20785 - } - ] -} diff --git a/kb/stores/photonlayer/photonlayer-coverage-report.json b/kb/stores/photonlayer/photonlayer-coverage-report.json deleted file mode 100644 index 7b8e351..0000000 --- a/kb/stores/photonlayer/photonlayer-coverage-report.json +++ /dev/null @@ -1,198 +0,0 @@ -{ - "target": "photonlayer", - "generated": "2026-06-19T22:17:28.137Z", - "pass": true, - "hardFail": false, - "checks": { - "coverageRatio": { - "value": 1, - "pass": true, - "hardFail": false, - "threshold": 0.92, - "indexed": 50, - "authored": 50 - }, - "perComponentMin": { - "pass": true, - "thin": [], - "threshold": 3 - }, - "passageRatio": { - "value": 4.98, - "pass": true, - "threshold": 4, - "distinctSourceFiles": 50, - "passages": 249 - }, - "spotCheck": { - "value": 1, - "pass": true, - "threshold": 0.8, - "hits": 20, - "of": 20 - } - }, - "sourceTypeCounts": { - "doc": 16, - "example": 35, - "config": 4, - "src": 146, - "test": 37, - "(untagged)": 11 - }, - "summary": { - "authoredSourceFiles": 50, - "indexedAuthoredFiles": 50, - "coverage": 1, - "totalPassages": 249, - "distinctIndexedPaths": 68, - "passageRatio": 4.98, - "components": 4, - "thinComponents": 0 - }, - "notIndexedSample": [], - "perComponent": [ - { - "component": "crates/photonlayer-bench", - "passages": 114, - "ok": true - }, - { - "component": "crates/photonlayer-cli", - "passages": 12, - "ok": true - }, - { - "component": "crates/photonlayer-core", - "passages": 81, - "ok": true - }, - { - "component": "crates/photonlayer-wasm", - "passages": 18, - "ok": true - } - ], - "spotResults": [ - { - "file": "crates/photonlayer-bench/tests/mnist_differential_bench.rs", - "indexed": true, - "retrieved": false, - "top1": "crates/photonlayer-bench/src/mnist.rs" - }, - { - "file": "crates/photonlayer-core/src/hash.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-core/src/hash.rs" - }, - { - "file": "crates/photonlayer-bench/src/lib.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-bench/src/lib.rs" - }, - { - "file": "crates/photonlayer-bench/src/verification.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-bench/src/verification.rs" - }, - { - "file": "crates/photonlayer-core/src/field.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-core/src/field.rs" - }, - { - "file": "crates/photonlayer-bench/src/learn.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-bench/src/learn.rs" - }, - { - "file": "crates/photonlayer-cli/src/main.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-cli/Cargo.toml" - }, - { - "file": "crates/photonlayer-bench/src/bin/bench.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-bench/src/baselines.rs" - }, - { - "file": "crates/photonlayer-bench/tests/cascade_gradient_check.rs", - "indexed": true, - "retrieved": false, - "top1": "crates/photonlayer-bench/src/baselines.rs" - }, - { - "file": "crates/photonlayer-core/examples/compression.rs", - "indexed": true, - "retrieved": false, - "top1": "crates/photonlayer-core/README.md" - }, - { - "file": "crates/photonlayer-bench/tests/more_data_bench.rs", - "indexed": true, - "retrieved": false, - "top1": "crates/photonlayer-bench/src/baselines.rs" - }, - { - "file": "crates/photonlayer-bench/examples/learn_mask.rs", - "indexed": true, - "retrieved": false, - "top1": "crates/photonlayer-bench/src/lib.rs" - }, - { - "file": "crates/photonlayer-wasm/src/lib.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-wasm/src/lib.rs" - }, - { - "file": "crates/photonlayer-core/src/receipt.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-core/src/receipt.rs" - }, - { - "file": "crates/photonlayer-core/src/mask.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-core/src/mask.rs" - }, - { - "file": "crates/photonlayer-core/examples/receipt.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-core/src/receipt.rs" - }, - { - "file": "crates/photonlayer-bench/src/mnist_bench.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-bench/src/mnist.rs" - }, - { - "file": "crates/photonlayer-core/src/config.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-core/src/config.rs" - }, - { - "file": "crates/photonlayer-core/src/propagate.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-core/src/propagate.rs" - }, - { - "file": "crates/photonlayer-bench/src/grad_adam.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/photonlayer-bench/src/grad_adam.rs" - } - ] -} diff --git a/kb/stores/ruqu/ruqu-aiq-report.json b/kb/stores/ruqu/ruqu-aiq-report.json deleted file mode 100644 index 53dc29f..0000000 --- a/kb/stores/ruqu/ruqu-aiq-report.json +++ /dev/null @@ -1,336 +0,0 @@ -{ - "target": "ruqu", - "judge": "claude-sonnet-4-5", - "seed": 7, - "generated": "2026-06-19T21:35:45.885Z", - "composite": 98, - "weakestDimension": "onboarding", - "pass": true, - "questionsFile": "/Users/stuartkerr/Code/Ruv-Explainer/kb/questions/ruqu.aiq.jsonl", - "dimensionsScored": 8, - "dimensionsTotal": 8, - "perDimension": [ - { - "id": 1, - "key": "onboarding", - "name": "Onboarding (install/build/run/test)", - "n": 3, - "score": 98 - }, - { - "id": 2, - "key": "what-it-is", - "name": "What it is + problem it solves", - "n": 3, - "score": 98 - }, - { - "id": 3, - "key": "architecture", - "name": "Architecture (components + relations)", - "n": 3, - "score": 98 - }, - { - "id": 4, - "key": "capabilities", - "name": "Capabilities (features/commands/API)", - "n": 3, - "score": 98 - }, - { - "id": 5, - "key": "usage", - "name": "Usage (functions + signatures + example)", - "n": 3, - "score": 98 - }, - { - "id": 6, - "key": "best-practices", - "name": "Best practices / patterns / gotchas", - "n": 3, - "score": 98 - }, - { - "id": 7, - "key": "deep-dive", - "name": "Deep-dive (3 random buried files)", - "n": 3, - "score": 98 - }, - { - "id": 8, - "key": "extensibility", - "name": "Extensibility (safe modification)", - "n": 3, - "score": 98 - } - ], - "perQuestion": [ - { - "dimension": "onboarding", - "query": "I just got this repo. How do I install, build, run, and test ruqu from scratch? Give me the exact commands.", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides exact install/build/run/test commands for all three surfaces (npx CLI, Rust crates, WASM), with concrete examples and flags.", - "top1": "PRIMER#7-how-do-i-install-and-run-it-end-to-end", - "contextChars": 23577 - }, - { - "dimension": "onboarding", - "query": "What is the fastest way to see ruqu actually run something, with no Rust toolchain set up?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete, specific instructions for the fastest zero-install method (npx commands) with concrete examples and no Rust toolchain requirement.", - "top1": "PRIMER#7-how-do-i-install-and-run-it-end-to-end", - "contextChars": 17373 - }, - { - "dimension": "onboarding", - "query": "How do I build the WebAssembly bundle so ruqu runs in a browser?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context explicitly shows the exact wasm-pack command with target and path, plus npm install alternative, covering all build steps.", - "top1": "PRIMER#7-how-do-i-install-and-run-it-end-to-end", - "contextChars": 17384 - }, - { - "dimension": "what-it-is", - "query": "What is ruqu and what specific problem does it solve for me?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides a complete, specific answer: ruqu is a pure-Rust quantum circuit simulator with WASM support, solving the problem of running quantum simulations without hardware, Python, or heavyweight dependencies, with concrete details on what it does, how it works, qubit limits, and usage.", - "top1": "PRIMER#1-what-is-ruqu", - "contextChars": 14597 - }, - { - "dimension": "what-it-is", - "query": "Why would I use ruqu instead of running on a real quantum computer, and what are its answers like?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete, specific answers: ruqu is a classical simulator (not real hardware) with exact state-vector math, qubit limits (32 native/25 browser), and concrete output format (SimulationResult with exact probability distributions like 0000/1111 each ~0.5), directly addressing both why-use-it and what-answers-look-like.", - "top1": "PRIMER#5-is-it-production-ready-scope-and-honest-limits", - "contextChars": 16894 - }, - { - "dimension": "what-it-is", - "query": "What does 'state-vector simulator' mean in ruqu and why does it matter?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides a complete definition of 'state-vector simulator' (holds full quantum state as complex amplitudes, applies gates as exact linear algebra), explains why it matters (exact results vs. noisy hardware, deterministic probabilities, no quantum hardware needed), and gives concrete specifics (memory limits, qubit counts, return types, example outputs).", - "top1": "PRIMER#1-what-is-ruqu", - "contextChars": 13939 - }, - { - "dimension": "architecture", - "query": "What crates make up ruqu and how do they depend on each other? Which crate is the foundation?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete crate names, dependency relationships, foundation identification, and even the rationale for the architecture.", - "top1": "PRIMER#3-what-is-ruqu-made-of-the-five-crates", - "contextChars": 18665 - }, - { - "dimension": "architecture", - "query": "If I change something in ruqu-core, which other crates could be affected?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The dependency graph explicitly shows all internal edges from ruqu-core to dependent crates (ruqu-algorithms, ruqu-exotic, ruqu-wasm), and the primer confirms ruQu is independent, providing a complete answer.", - "top1": "crates/ruqu-core/README.md", - "contextChars": 18601 - }, - { - "dimension": "architecture", - "query": "What is the coherence engine (ruQu) and where does it sit relative to the simulator crates?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides a complete, specific answer: ruQu is the coherence engine (classical nervous system for quantum machines, real-time syndrome processing via dynamic min-cut), and it is architecturally independent of the simulator crates (no dependency edges in either direction per the dep-graph and PRIMER#3).", - "top1": "PRIMER#3-what-is-ruqu-made-of-the-five-crates", - "contextChars": 22696 - }, - { - "dimension": "capabilities", - "query": "What can ruqu do? List the algorithms and features it ships with.", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides comprehensive coverage of ruqu's algorithms (VQE, Grover, QAOA, Surface Code), features (5 simulation backends, universal gate set, noise models, error mitigation, OpenQASM export, SIMD/multi-threading), and CLI commands (simulate, grover, qaoa, capabilities, doctor, init, version) with specific details from multiple sources including the primer, READMEs, and CLI code.", - "top1": "PRIMER#2-what-can-ruqu-do-for-you", - "contextChars": 27077 - }, - { - "dimension": "capabilities", - "query": "Which CLI commands does ruqu expose and what does each do?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The CLI commands, their flags, and what each does are fully detailed in cli/bin/cli.js and cli/README.md.", - "top1": "PRIMER#8-how-do-i-extend-ruqu-safely-the-extension-points", - "contextChars": 27217 - }, - { - "dimension": "capabilities", - "query": "What quantum algorithms come built in, and what does each one solve (chemistry, search, optimization, error correction)?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context explicitly lists all four built-in algorithms (VQE for chemistry, Grover for search, QAOA for optimization, Surface Code for error correction) with their use cases and speedups in multiple places.", - "top1": "PRIMER#2-what-can-ruqu-do-for-you", - "contextChars": 27741 - }, - { - "dimension": "usage", - "query": "Show me how to build and run a quantum circuit in ruqu-core — what are the key types and functions and a real example?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides QuantumCircuit constructor, all gate methods (h, x, y, z, cnot, etc.), Simulator::run signature, result types, and complete working examples from README and PRIMER.", - "top1": "crates/ruqu-wasm/README.md", - "contextChars": 41948 - }, - { - "dimension": "usage", - "query": "How do I run Grover's search with ruqu-algorithms? What is the function signature and config?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides the complete function signature (run_grover(&GroverConfig) -> Result), the full GroverConfig struct definition with all fields (num_qubits, target_states, num_iterations, seed), a working example from the README, and the primer's end-to-end usage showing both the Rust API and CLI invocation.", - "top1": "crates/ruqu-algorithms/README.md", - "contextChars": 39272 - }, - { - "dimension": "usage", - "query": "What is the public API for picking a simulation backend — what function analyzes a circuit and what does it return?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The function analyze_circuit is shown with full signature and return type CircuitAnalysis, whose fields include recommended_backend; the context provides the complete API.", - "top1": "PRIMER#4-how-a-circuit-runs-the-simulation-pipeline", - "contextChars": 35908 - }, - { - "dimension": "best-practices", - "query": "Is ruqu production-ready? What are its honest limits and how many qubits can it handle?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete, specific answers: ruqu is a classical simulator (not production hardware), handles ≤32 qubits native/~25 browser (exact memory limits given), Stabilizer backend reaches millions for Clifford-only circuits, ruqu-exotic is experimental, versions are stated, and all concrete limits/gotchas are enumerated.", - "top1": "PRIMER#5-is-it-production-ready-scope-and-honest-limits", - "contextChars": 16645 - }, - { - "dimension": "best-practices", - "query": "What is experimental or quantum-inspired in ruqu that I should treat with caution?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context explicitly identifies ruqu-exotic as experimental quantum-inspired tooling for AI systems (not physics), states it should be treated with caution, and confirms the rest of ruqu is solidly real production code.", - "top1": "PRIMER#5-is-it-production-ready-scope-and-honest-limits", - "contextChars": 12893 - }, - { - "dimension": "best-practices", - "query": "What are the gotchas around qubit count and memory when running large circuits?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides comprehensive, specific details on memory limits (2^n amplitudes, 32 qubits native, 25 browser, exact GB figures), the Stabilizer escape hatch, tile memory budgets (64KB, specific error types), performance tips (SIMD, rayon, --release), and the analyze_circuit planner—all concrete facts the question demands.", - "top1": "PRIMER#9-performance-memory-and-gotchas-running-large-circuits", - "contextChars": 19305 - }, - { - "dimension": "extensibility", - "query": "If I want to add a new quantum algorithm, which crate should it go in and what does it depend on?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides the exact crate (ruqu-algorithms), the pattern (add your_algo.rs, expose run_* + Config/Result, pub mod in lib.rs), and the dependencies (ruqu-core's QuantumCircuit, Simulator, gate methods), with concrete examples from grover.rs and the primer.", - "top1": "PRIMER#2-what-can-ruqu-do-for-you", - "contextChars": 30733 - }, - { - "dimension": "extensibility", - "query": "How would I safely add a new gate or backend to ruqu-core without breaking the algorithms or wasm crates?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete, specific details on adding gates (Gate enum in gate.rs, apply_gate methods in backends, test location) and backends (BackendType enum, analyze_circuit planner in backend.rs, Simulator API stability), with concrete file paths, function signatures, and the dependency-safety rule (ruqu-core is the foundation, changes ripple to ruqu-algorithms/ruqu-wasm).", - "top1": "crates/ruqu-core/src/backend.rs", - "contextChars": 38614 - }, - { - "dimension": "extensibility", - "query": "Where do I add a new CLI subcommand or wasm binding, and what wires the Rust simulator to JavaScript?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context shows the exact files (cli.js, lib.rs) and patterns (switch dispatch, #[wasm_bindgen]) for adding CLI subcommands and WASM bindings, plus the PRIMER explicitly documents both extension points with concrete examples.", - "top1": "crates/ruqu-wasm/README.md", - "contextChars": 41741 - }, - { - "dimension": "deep-dive", - "query": "Explain specifically what the file crates/ruqu-core/src/mitigation.rs does and the key symbols it defines (it defines mitigation, fmt, clone, fmt, clone). What is its responsibility within the crate?", - "generated": true, - "deepFile": "crates/ruqu-core/src/mitigation.rs", - "score": 98, - "missing": "nothing", - "reason": "The full file body is provided with all key symbols (ZneConfig, ExtrapolationMethod, fold_circuit, richardson_extrapolate, polynomial_extrapolate, linear_extrapolate, MeasurementCorrector, CdrConfig) and their signatures, plus complete implementation details and module-level documentation explaining the three mitigation strategies.", - "top1": "crates/ruqu-core/README.md", - "contextChars": 24881 - }, - { - "dimension": "deep-dive", - "query": "Explain specifically what the file crates/ruqu-core/src/stabilizer.rs does and the key symbols it defines (it defines stabilizer, StabilizerState, new, new, new_with_seed). What is its responsibility within the crate?", - "generated": true, - "deepFile": "crates/ruqu-core/src/stabilizer.rs", - "score": 98, - "missing": "nothing", - "reason": "The full file body, all key symbols (StabilizerState, new, new_with_seed, hadamard, phase_gate, cnot, measure, etc.), their signatures, and the module's responsibility (Aaronson-Gottesman stabilizer simulator for Clifford circuits) are explicitly present in the context.", - "top1": "crates/ruqu-core/README.md", - "contextChars": 25382 - }, - { - "dimension": "deep-dive", - "query": "Explain specifically what the file crates/ruQu/tests/integration_tests.rs does and the key symbols it defines. What is its responsibility within the crate?", - "generated": true, - "deepFile": "crates/ruQu/tests/integration_tests.rs", - "score": 98, - "missing": "nothing", - "reason": "The full file body is provided with all imports, test functions, and their logic clearly shown.", - "top1": "PRIMER#3-what-is-ruqu-made-of-the-five-crates", - "contextChars": 23484 - } - ] -} diff --git a/kb/stores/ruqu/ruqu-coverage-report.json b/kb/stores/ruqu/ruqu-coverage-report.json deleted file mode 100644 index 0ebe336..0000000 --- a/kb/stores/ruqu/ruqu-coverage-report.json +++ /dev/null @@ -1,210 +0,0 @@ -{ - "target": "ruqu", - "generated": "2026-06-19T21:31:12.529Z", - "pass": true, - "hardFail": false, - "checks": { - "coverageRatio": { - "value": 0.99, - "pass": true, - "hardFail": false, - "threshold": 0.92, - "indexed": 99, - "authored": 100 - }, - "perComponentMin": { - "pass": true, - "thin": [], - "threshold": 3 - }, - "passageRatio": { - "value": 13.38, - "pass": true, - "threshold": 4, - "distinctSourceFiles": 99, - "passages": 1325 - }, - "spotCheck": { - "value": 1, - "pass": true, - "threshold": 0.8, - "hits": 20, - "of": 20 - } - }, - "sourceTypeCounts": { - "doc": 133, - "config": 17, - "src": 855, - "test": 236, - "example": 74, - "(untagged)": 10 - }, - "summary": { - "authoredSourceFiles": 100, - "indexedAuthoredFiles": 99, - "coverage": 0.99, - "totalPassages": 1325, - "distinctIndexedPaths": 138, - "passageRatio": 13.38, - "components": 6, - "thinComponents": 0 - }, - "notIndexedSample": [ - "cli/wasm/ruqu_wasm.js" - ], - "perComponent": [ - { - "component": "crates/ruQu", - "passages": 545, - "ok": true - }, - { - "component": "crates/ruqu-algorithms", - "passages": 59, - "ok": true - }, - { - "component": "crates/ruqu-core", - "passages": 555, - "ok": true - }, - { - "component": "crates/ruqu-exotic", - "passages": 113, - "ok": true - }, - { - "component": "crates/ruqu-wasm", - "passages": 20, - "ok": true - }, - { - "component": "cli", - "passages": 15, - "ok": true - } - ], - "spotResults": [ - { - "file": "crates/ruQu/benches/mincut_bench.rs", - "indexed": true, - "retrieved": false, - "top1": "PRIMER#3-what-is-ruqu-made-of-the-five-crates" - }, - { - "file": "crates/ruqu-core/src/simulator.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/ruqu-core/README.md" - }, - { - "file": "crates/ruQu/examples/quantum_fabric_basic.rs", - "indexed": true, - "retrieved": false, - "top1": "PRIMER#3-what-is-ruqu-made-of-the-five-crates" - }, - { - "file": "crates/ruqu-core/src/gate.rs", - "indexed": true, - "retrieved": false, - "top1": "crates/ruqu-core/README.md" - }, - { - "file": "cli/src/agents/hypothesizer.ts", - "indexed": true, - "retrieved": true, - "top1": "cli/src/agents/hypothesizer.ts" - }, - { - "file": "crates/ruqu-core/src/decoder.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/ruqu-core/README.md" - }, - { - "file": "crates/ruQu/benches/latency_bench.rs", - "indexed": true, - "retrieved": false, - "top1": "PRIMER#3-what-is-ruqu-made-of-the-five-crates" - }, - { - "file": "crates/ruqu-exotic/src/reversible_memory.rs", - "indexed": true, - "retrieved": false, - "top1": "cli/bin/cli.js" - }, - { - "file": "crates/ruqu-core/src/lib.rs", - "indexed": true, - "retrieved": false, - "top1": "crates/ruqu-core/README.md" - }, - { - "file": "crates/ruQu/src/stim.rs", - "indexed": true, - "retrieved": false, - "top1": "PRIMER#3-what-is-ruqu-made-of-the-five-crates" - }, - { - "file": "crates/ruQu/src/syndrome.rs", - "indexed": true, - "retrieved": false, - "top1": "PRIMER#3-what-is-ruqu-made-of-the-five-crates" - }, - { - "file": "crates/ruqu-core/src/transpiler.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/ruqu-core/README.md" - }, - { - "file": "crates/ruQu/examples/early_warning_validation.rs", - "indexed": true, - "retrieved": false, - "top1": "PRIMER#3-what-is-ruqu-made-of-the-five-crates" - }, - { - "file": "crates/ruqu-core/tests/test_state.rs", - "indexed": true, - "retrieved": false, - "top1": "crates/ruqu-core/README.md" - }, - { - "file": "crates/ruQu/benches/throughput_bench.rs", - "indexed": true, - "retrieved": false, - "top1": "PRIMER#3-what-is-ruqu-made-of-the-five-crates" - }, - { - "file": "crates/ruqu-core/src/control_theory.rs", - "indexed": true, - "retrieved": false, - "top1": "crates/ruqu-core/README.md" - }, - { - "file": "crates/ruqu-core/src/benchmark.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/ruqu-core/README.md" - }, - { - "file": "crates/ruQu/src/metrics.rs", - "indexed": true, - "retrieved": false, - "top1": "PRIMER#3-what-is-ruqu-made-of-the-five-crates" - }, - { - "file": "crates/ruqu-core/src/hardware.rs", - "indexed": true, - "retrieved": true, - "top1": "crates/ruqu-core/README.md" - }, - { - "file": "crates/ruqu-exotic/src/interference_search.rs", - "indexed": true, - "retrieved": false, - "top1": "cli/bin/cli.js" - } - ] -} diff --git a/kb/stores/ruvn/ruvn-aiq-report.json b/kb/stores/ruvn/ruvn-aiq-report.json deleted file mode 100644 index e83a4be..0000000 --- a/kb/stores/ruvn/ruvn-aiq-report.json +++ /dev/null @@ -1,336 +0,0 @@ -{ - "target": "ruvn", - "judge": "claude-opus-4-1", - "seed": 19, - "generated": "2026-06-19T22:19:39.537Z", - "composite": 95, - "weakestDimension": "usage", - "pass": true, - "questionsFile": "/Users/stuartkerr/Code/Ruv-Explainer/kb/questions/ruvn.aiq.jsonl", - "dimensionsScored": 8, - "dimensionsTotal": 8, - "perDimension": [ - { - "id": 1, - "key": "onboarding", - "name": "Onboarding (install/build/run/test)", - "n": 3, - "score": 98 - }, - { - "id": 2, - "key": "what-it-is", - "name": "What it is + problem it solves", - "n": 3, - "score": 98 - }, - { - "id": 3, - "key": "architecture", - "name": "Architecture (components + relations)", - "n": 3, - "score": 96 - }, - { - "id": 4, - "key": "capabilities", - "name": "Capabilities (features/commands/API)", - "n": 3, - "score": 98 - }, - { - "id": 5, - "key": "usage", - "name": "Usage (functions + signatures + example)", - "n": 3, - "score": 95 - }, - { - "id": 6, - "key": "best-practices", - "name": "Best practices / patterns / gotchas", - "n": 3, - "score": 95.3 - }, - { - "id": 7, - "key": "deep-dive", - "name": "Deep-dive (3 random buried files)", - "n": 3, - "score": 98 - }, - { - "id": 8, - "key": "extensibility", - "name": "Extensibility (safe modification)", - "n": 3, - "score": 96 - } - ], - "perQuestion": [ - { - "dimension": "onboarding", - "query": "I just got this repo. How do I install, run, and test ruvn from scratch, including running it with no install? Give me the exact commands.", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides all exact commands for install (npm i -g @ruvnet/ruvn), run (ruvn init, ruvn doctor), test (npm test), and no-install usage (npx @ruvnet/ruvn init).", - "top1": "PRIMER#7-how-do-i-install-and-use-it-end-to-end", - "contextChars": 24402 - }, - { - "dimension": "onboarding", - "query": "What is the fastest way to see ruvn actually do something, and what does `ruvn doctor` check?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete details on the fastest way to see ruvn work (npm install + ruvn init) and explicitly states what ruvn doctor checks (four PASS/FAIL checks: kernel loads, reports version, backend is native|wasm|js, host adapter has name).", - "top1": "PRIMER#7-how-do-i-install-and-use-it-end-to-end", - "contextChars": 16130 - }, - { - "dimension": "onboarding", - "query": "How do I validate ruvn end-to-end against a real model, and what env var do I need?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context explicitly shows `npm run validate:openrouter` command and `OPENROUTER_API_KEY` env var for end-to-end validation against real models.", - "top1": "PRIMER#7-how-do-i-install-and-use-it-end-to-end", - "contextChars": 16130 - }, - { - "dimension": "what-it-is", - "query": "What is ruvn and what specific problem does it solve for me?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides comprehensive information about what ruvn is (research agent for graded/cited evidence dossiers) and the specific problem it solves (trust/defensibility in AI research by grading sources A-D and only using good ones).", - "top1": "README.md", - "contextChars": 14561 - }, - { - "dimension": "what-it-is", - "query": "Why would I use ruvn instead of just asking an AI a research question directly? What does it give me back?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides comprehensive details about ruvn's value proposition over direct AI queries, including source grading, citation requirements, fact-checking pipeline, and the specific defensible dossier output format.", - "top1": "PRIMER#2-what-can-ruvn-do-for-you", - "contextChars": 14549 - }, - { - "dimension": "what-it-is", - "query": "What does a 'graded, cited evidence dossier' mean in ruvn, and what is ruvn explicitly NOT?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context explicitly defines 'graded, cited evidence dossier' and clearly states what ruvn is NOT (not a chatbot, not a hosted service, not a medical device, not a replacement for reading sources).", - "top1": "PRIMER#1-what-is-ruvn", - "contextChars": 14622 - }, - { - "dimension": "architecture", - "query": "What are the six agents in ruvn, in what order do they run, and how does information flow between them?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete information about all six agents, their execution order (scout → web-searcher → source-grader → synthesizer → fact-checker → citer), and how information flows sequentially between them.", - "top1": "PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", - "contextChars": 21384 - }, - { - "dimension": "architecture", - "query": "What does ruvn depend on (kernel, hosts), and how is the package structured? Which hosts does it support?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides complete information about ruvn's dependencies (@metaharness/kernel and 9 host adapters), package structure (single npm package with agents in src/agents/), and supported hosts (all 9 hosts listed with their config files).", - "top1": "PRIMER#3-what-is-ruvn-made-of-the-six-agents-and-nine-hosts", - "contextChars": 23814 - }, - { - "dimension": "architecture", - "query": "What does it mean that 'each agent only sees the previous agent's output', and why is the pipeline built that way?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context fully explains that 'each agent only sees the previous agent's output' means a linear pipeline forcing information through grading/verification gates, with complete architectural rationale.", - "top1": "PRIMER#4-how-the-pipeline-works-step-by-step", - "contextChars": 18683 - }, - { - "dimension": "capabilities", - "query": "What can ruvn do? List the pipeline stages and what each agent produces.", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete details about ruvn's capabilities, the six pipeline stages (scout → web-searcher → source-grader → synthesizer → fact-checker → citer), and what each agent produces.", - "top1": "PRIMER#2-what-can-ruvn-do-for-you", - "contextChars": 26178 - }, - { - "dimension": "capabilities", - "query": "How does ruvn grade sources — what do grades A, B, C, and D mean, and which grades is the synthesizer allowed to use?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete definitions of grades A/B/C/D and explicitly states the synthesizer uses only A/B sources.", - "top1": "PRIMER#2-what-can-ruvn-do-for-you", - "contextChars": 21704 - }, - { - "dimension": "capabilities", - "query": "Which CLI commands does ruvn expose and what does each do?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete details about all CLI commands (init, doctor, --version, --help) with their exact implementations and descriptions.", - "top1": "PRIMER#8-how-do-i-extend-ruvn-safely-the-extension-points", - "contextChars": 24753 - }, - { - "dimension": "usage", - "query": "Show me how to actually run a research question through ruvn end-to-end and what I get back. What is the real workflow?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides complete end-to-end workflow details: install via npm, run `ruvn init` to wire into Claude Code, ask Claude to run the pipeline, get back a cited markdown dossier with grades.", - "top1": "PRIMER#7-how-do-i-install-and-use-it-end-to-end", - "contextChars": 22267 - }, - { - "dimension": "usage", - "query": "What does each agent's SYSTEM_PROMPT instruct it to do, and what model tier runs each one?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides complete SYSTEM_PROMPT content and TIER values for all six agents through the symbols.json, which shows the exact exports from each agent file.", - "top1": "PRIMER#5-is-it-production-ready-scope-and-honest-limits", - "contextChars": 23788 - }, - { - "dimension": "usage", - "query": "How do I drive the CLI from code? What is the signature of the dispatcher and how do the tests call it?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context shows the complete `run(argv)` signature at bin/cli.js:53 and multiple test examples calling it with argv arrays.", - "top1": "__tests__/smoke.test.ts", - "contextChars": 28210 - }, - { - "dimension": "best-practices", - "query": "Is ruvn production-ready? What are its honest limits and scope?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides comprehensive coverage of ruvn's production readiness (v0.1.1, early stage), honest limits (research tool not oracle, no medical advice, depends on host model), and scope (six-agent pipeline, graded citations, starting dossier to verify).", - "top1": "PRIMER#5-is-it-production-ready-scope-and-honest-limits", - "contextChars": 18225 - }, - { - "dimension": "best-practices", - "query": "What are the gotchas around cost and latency when running ruvn, and where does the web search actually happen?", - "generated": false, - "deepFile": null, - "score": 96, - "missing": "nothing", - "reason": "The context comprehensively answers all three parts: cost/latency gotchas (6 sequential model calls, sonnet/haiku tiers), and web search happens in the host's WebSearch/WebFetch tools, not ruvn itself.", - "top1": "PRIMER#9-cost-latency-and-gotchas-running-the-pipeline", - "contextChars": 18141 - }, - { - "dimension": "best-practices", - "query": "Why might my ruvn dossier come back empty or thin, and is that a bug?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides comprehensive explanations for why dossiers might be empty/thin (grade quality caps, no A/B sources, host web tool issues) and explicitly states this is by design, not a bug.", - "top1": "README.md", - "contextChars": 15474 - }, - { - "dimension": "extensibility", - "query": "How do I add a new research agent to ruvn? What file does it go in, what does it export, and how do I keep the pipeline working?", - "generated": false, - "deepFile": null, - "score": 98, - "missing": "nothing", - "reason": "The context provides complete details: agents go in src/agents/.ts, must export SYSTEM_PROMPT/NAME/TIER, and pipeline order must be maintained in CLAUDE.md/README.md.", - "top1": "PRIMER#8-how-do-i-extend-ruvn-safely-the-extension-points", - "contextChars": 24366 - }, - { - "dimension": "extensibility", - "query": "Where is the A/B/C/D grading rubric defined and how do I safely change it without breaking ruvn's trust guarantee?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides complete information about the A/B/C/D grading rubric location (CLAUDE.md and source-grader.ts) and explicit safety instructions for modification (keep both locations in sync, update synthesizer if loosening).", - "top1": "PRIMER#8-how-do-i-extend-ruvn-safely-the-extension-points", - "contextChars": 21270 - }, - { - "dimension": "extensibility", - "query": "How do I change which model tier an agent uses, and how do I add a new CLI subcommand or a new host?", - "generated": false, - "deepFile": null, - "score": 95, - "missing": "nothing", - "reason": "The context provides complete instructions for changing model tiers (edit TIER in agent files), adding CLI subcommands (modify bin/cli.js switch statement), and adding new hosts (add dependencies and config files).", - "top1": "PRIMER#8-how-do-i-extend-ruvn-safely-the-extension-points", - "contextChars": 28855 - }, - { - "dimension": "deep-dive", - "query": "Explain specifically what the file src/agents/web-searcher.ts does and the key symbols it defines (it defines SYSTEM_PROMPT, NAME, TIER). What is its responsibility within the crate?", - "generated": true, - "deepFile": "src/agents/web-searcher.ts", - "score": 98, - "missing": "nothing", - "reason": "The context provides the complete file content showing all three exported constants (SYSTEM_PROMPT, NAME, TIER) and their exact values, plus context from other agent files showing web-searcher's role in the multi-agent research system.", - "top1": "src/agents/web-searcher.ts", - "contextChars": 3983 - }, - { - "dimension": "deep-dive", - "query": "Explain specifically what the file src/agents/source-grader.ts does and the key symbols it defines (it defines SYSTEM_PROMPT, NAME, TIER). What is its responsibility within the crate?", - "generated": true, - "deepFile": "src/agents/source-grader.ts", - "score": 98, - "missing": "nothing", - "reason": "The context provides the complete file content showing all three exported symbols (SYSTEM_PROMPT, NAME, TIER) and clearly explains the source grader's role in evaluating search results by grade.", - "top1": "src/agents/source-grader.ts", - "contextChars": 4155 - }, - { - "dimension": "deep-dive", - "query": "Explain specifically what the file src/agents/scout.ts does and the key symbols it defines (it defines SYSTEM_PROMPT, NAME, TIER). What is its responsibility within the crate?", - "generated": true, - "deepFile": "src/agents/scout.ts", - "score": 98, - "missing": "nothing", - "reason": "The context provides the complete file content, all three exported symbols with their exact values, and enough surrounding agent files to understand scout's role as the initial query decomposer in the research pipeline.", - "top1": "src/agents/scout.ts", - "contextChars": 3955 - } - ] -} diff --git a/kb/stores/ruvn/ruvn-coverage-report.json b/kb/stores/ruvn/ruvn-coverage-report.json deleted file mode 100644 index 3eb89bb..0000000 --- a/kb/stores/ruvn/ruvn-coverage-report.json +++ /dev/null @@ -1,122 +0,0 @@ -{ - "target": "ruvn", - "generated": "2026-06-19T21:50:27.519Z", - "pass": true, - "hardFail": false, - "checks": { - "coverageRatio": { - "value": 1, - "pass": true, - "hardFail": false, - "threshold": 0.92, - "indexed": 11, - "authored": 11 - }, - "perComponentMin": { - "pass": true, - "thin": [], - "threshold": 3 - }, - "passageRatio": { - "value": 4.09, - "pass": true, - "threshold": 4, - "distinctSourceFiles": 11, - "passages": 45 - }, - "spotCheck": { - "value": 1, - "pass": true, - "threshold": 0.8, - "hits": 11, - "of": 11 - } - }, - "sourceTypeCounts": { - "doc": 25, - "config": 1, - "src": 7, - "test": 2, - "(untagged)": 10 - }, - "summary": { - "authoredSourceFiles": 11, - "indexedAuthoredFiles": 11, - "coverage": 1, - "totalPassages": 45, - "distinctIndexedPaths": 39, - "passageRatio": 4.09, - "components": 0, - "thinComponents": 0 - }, - "notIndexedSample": [], - "perComponent": [], - "spotResults": [ - { - "file": "src/agents/scout.ts", - "indexed": true, - "retrieved": true, - "top1": "src/agents/source-grader.ts" - }, - { - "file": "src/agents/citer.ts", - "indexed": true, - "retrieved": true, - "top1": "src/agents/source-grader.ts" - }, - { - "file": "__tests__/smoke.test.ts", - "indexed": true, - "retrieved": true, - "top1": "__tests__/smoke.test.ts" - }, - { - "file": "src/agents/web-searcher.ts", - "indexed": true, - "retrieved": true, - "top1": "src/agents/web-searcher.ts" - }, - { - "file": "src/agents/source-grader.ts", - "indexed": true, - "retrieved": true, - "top1": "src/agents/source-grader.ts" - }, - { - "file": "bin/cli.js", - "indexed": true, - "retrieved": true, - "top1": "bin/cli.js" - }, - { - "file": "scripts/openrouter-validate.mjs", - "indexed": true, - "retrieved": true, - "top1": "scripts/openrouter-validate.mjs" - }, - { - "file": "src/agents/fact-checker.ts", - "indexed": true, - "retrieved": true, - "top1": "src/agents/fact-checker.ts" - }, - { - "file": "src/agents/synthesizer.ts", - "indexed": true, - "retrieved": true, - "top1": "src/agents/synthesizer.ts" - }, - { - "file": "src/init.ts", - "indexed": true, - "retrieved": false, - "top1": "src/agents/fact-checker.ts" - }, - { - "file": "__tests__/openrouter.integration.test.ts", - "indexed": true, - "retrieved": true, - "top1": "__tests__/openrouter.integration.test.ts" - } - ] -} diff --git a/kb/stores/slugify/slugify-dep-graph.json b/kb/stores/slugify/slugify-dep-graph.json deleted file mode 100644 index c8e2f9e..0000000 --- a/kb/stores/slugify/slugify-dep-graph.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "target": "slugify", - "metaName": "sindresorhus/slugify", - "generated": "2026-07-02T18:04:02.995Z", - "ecosystems": [ - "npm" - ], - "componentCount": 2, - "internalEdgeCount": 0, - "externalDepCount": 2, - "nodes": [ - { - "name": "@sindresorhus/slugify", - "version": "3.0.0", - "description": "Slugify a string", - "manifest": "package.json", - "deps": [ - "@sindresorhus/transliterate", - "escape-string-regexp" - ], - "ecosystem": "npm" - }, - { - "name": "@sindresorhus/slugify", - "version": "3.0.0", - "description": "Slugify a string", - "manifest": "package.json", - "deps": [ - "@sindresorhus/transliterate", - "escape-string-regexp" - ], - "ecosystem": "npm" - } - ], - "internalEdges": [], - "externalDeps": { - "@sindresorhus/slugify": [ - { - "name": "@sindresorhus/transliterate", - "req": "*", - "kind": "normal" - }, - { - "name": "escape-string-regexp", - "req": "*", - "kind": "normal" - } - ] - }, - "externalDepNames": [ - "@sindresorhus/transliterate", - "escape-string-regexp" - ] -} diff --git a/kb/stores/slugify/slugify-entrypoints.json b/kb/stores/slugify/slugify-entrypoints.json deleted file mode 100644 index 634ea83..0000000 --- a/kb/stores/slugify/slugify-entrypoints.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "target": "slugify", - "metaName": "sindresorhus/slugify", - "generated": "2026-07-02T18:04:03.111Z", - "workspace": { - "kind": "npm", - "members": [] - }, - "components": [ - { - "name": "@sindresorhus/slugify", - "path": "", - "kind": "package", - "description": "Slugify a string", - "scripts": { - "test": "xo && ava" - }, - "bins": [], - "deps": [ - "@sindresorhus/transliterate", - "escape-string-regexp" - ] - } - ], - "binaries": [], - "commands": [ - { - "cmd": "npm run test", - "raw": "xo && ava", - "category": "test", - "source": "package.json", - "note": null - }, - { - "cmd": "npm install @sindresorhus/slugify", - "category": "install", - "source": "README.md", - "note": null - } - ], - "install": [ - "npm install @sindresorhus/slugify" - ], - "quickstart": [] -} diff --git a/kb/stores/slugify/slugify-kb.ids.json b/kb/stores/slugify/slugify-kb.ids.json deleted file mode 100644 index a7c33c7..0000000 --- a/kb/stores/slugify/slugify-kb.ids.json +++ /dev/null @@ -1 +0,0 @@ -{"model":"Xenova/bge-small-en-v1.5","dimensions":384,"metric":"cosine","entries":{"1":{"path":".github/security.md","kind":"doc","source_type":"doc","title":"Security Policy","chunk":1,"of":1,"preview":"# Security Policy To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. "},"2":{"path":"readme.md","kind":"doc","source_type":"doc","title":"slugify","chunk":1,"of":4,"preview":"# slugify > Slugify a string Useful for URLs, filenames, and IDs. It handles most major languages, including [German (umlauts)](https://en.wikipedia.org/wiki/Germanic_umlaut), Vietnamese, Arabic, Russian, [and more](https://github.com/si"},"3":{"path":"readme.md","kind":"doc","source_type":"doc","title":"slugify","chunk":2,"of":4,"preview":"##### customReplacements Type: `Array`\\ Default: `[ ['&', ' and '], ['🦄', ' unicorn '], ['♥', ' love '] ]` Add your own custom replacements. The replacements are run on the original string before any other transformations. "},"4":{"path":"readme.md","kind":"doc","source_type":"doc","title":"slugify","chunk":3,"of":4,"preview":"##### preserveCharacters Type: `string[]`\\ Default: `[]` Preserve certain characters. It cannot contain the `separator`. For example, if you want to slugify URLs, but preserve the HTML fragment `#` character. ```js import slugify from "},"5":{"path":"readme.md","kind":"doc","source_type":"doc","title":"slugify","chunk":4,"of":4,"preview":"#### Example ```js import {slugifyWithCounter} from '@sindresorhus/slugify'; const slugify = slugifyWithCounter(); slugify('foo bar'); //=> 'foo-bar' slugify('foo bar'); //=> 'foo-bar-2' slugify.reset(); slugify('foo bar'); //=> 'foo-"},"6":{"path":"README.md","kind":"doc","source_type":"doc","title":"slugify","chunk":1,"of":4,"preview":"# slugify > Slugify a string Useful for URLs, filenames, and IDs. It handles most major languages, including [German (umlauts)](https://en.wikipedia.org/wiki/Germanic_umlaut), Vietnamese, Arabic, Russian, [and more](https://github.com/si"},"7":{"path":"README.md","kind":"doc","source_type":"doc","title":"slugify","chunk":2,"of":4,"preview":"##### customReplacements Type: `Array`\\ Default: `[ ['&', ' and '], ['🦄', ' unicorn '], ['♥', ' love '] ]` Add your own custom replacements. The replacements are run on the original string before any other transformations. "},"8":{"path":"README.md","kind":"doc","source_type":"doc","title":"slugify","chunk":3,"of":4,"preview":"##### preserveCharacters Type: `string[]`\\ Default: `[]` Preserve certain characters. It cannot contain the `separator`. For example, if you want to slugify URLs, but preserve the HTML fragment `#` character. ```js import slugify from "},"9":{"path":"README.md","kind":"doc","source_type":"doc","title":"slugify","chunk":4,"of":4,"preview":"#### Example ```js import {slugifyWithCounter} from '@sindresorhus/slugify'; const slugify = slugifyWithCounter(); slugify('foo bar'); //=> 'foo-bar' slugify('foo bar'); //=> 'foo-bar-2' slugify.reset(); slugify('foo bar'); //=> 'foo-"},"10":{"path":"package.json","kind":"doc","source_type":"config","title":"package.json","chunk":1,"of":1,"preview":"{ \"name\": \"@sindresorhus/slugify\", \"version\": \"3.0.0\", \"description\": \"Slugify a string\", \"license\": \"MIT\", \"repository\": \"sindresorhus/slugify\", \"funding\": \"https://github.com/sponsors/sindresorhus\", \"author\": { \"name\": \"Sindre So"},"11":{"path":"index.js","kind":"doc","source_type":"doc","title":"index.js","chunk":1,"of":3,"preview":"import escapeStringRegexp from 'escape-string-regexp'; import transliterate from '@sindresorhus/transliterate'; import builtinOverridableReplacements from './overridable-replacements.js'; const decamelize = string => string // Separate ca"},"12":{"path":"index.js","kind":"doc","source_type":"doc","title":"index.js","chunk":2,"of":3,"preview":"export default function slugify(string, options) { if (typeof string !== 'string') { throw new TypeError(`Expected a string, got \\`${typeof string}\\``); } options = { separator: '-', lowercase: true, decamelize: true, customRe"},"13":{"path":"index.js","kind":"doc","source_type":"doc","title":"index.js","chunk":3,"of":3,"preview":"export function slugifyWithCounter() { const occurrences = new Map(); const countable = (string, options) => { string = slugify(string, options); if (!string) { return ''; } const stringLower = string.toLowerCase(); const "},"14":{"path":"index.d.ts","kind":"doc","source_type":"doc","title":"index.d.ts","chunk":1,"of":3,"preview":"export type Options = { /** @default '-' @example ``` import slugify from '@sindresorhus/slugify'; slugify('BAR and baz'); //=> 'bar-and-baz' slugify('BAR and baz', {separator: '_'}); //=> 'bar_and_baz' slugify('BAR and baz', "},"15":{"path":"index.d.ts","kind":"doc","source_type":"doc","title":"index.d.ts","chunk":2,"of":3,"preview":"transliteration. @default true @example ``` import slugify from '@sindresorhus/slugify'; slugify('Déjà Vu'); //=> 'deja-vu' slugify('Déjà Vu', {transliterate: false}); //=> 'déjà-vu' ``` */ readonly transliterate?: boolean; }"},"16":{"path":"index.d.ts","kind":"doc","source_type":"doc","title":"index.d.ts","chunk":3,"of":3,"preview":"export default function slugify(string: string, options?: Options): string; export type CountableSlugify = { /** Reset the counter. @example ``` import {slugifyWithCounter} from '@sindresorhus/slugify'; const slugify = slugifyWithC"},"17":{"path":"index.js","kind":"source","source_type":"src","title":"index.js","chunk":1,"of":3,"preview":"Source index.js (full): import escapeStringRegexp from 'escape-string-regexp'; import transliterate from '@sindresorhus/transliterate'; import builtinOverridableReplacements from './overridable-replacements.js'; const decamelize = string ="},"18":{"path":"index.js","kind":"source","source_type":"src","title":"index.js","chunk":2,"of":3,"preview":"export default function slugify(string, options) { if (typeof string !== 'string') { throw new TypeError(`Expected a string, got \\`${typeof string}\\``); } options = { separator: '-', lowercase: true, decamelize: true, customRe"},"19":{"path":"index.js","kind":"source","source_type":"src","title":"index.js","chunk":3,"of":3,"preview":"export function slugifyWithCounter() { const occurrences = new Map(); const countable = (string, options) => { string = slugify(string, options); if (!string) { return ''; } const stringLower = string.toLowerCase(); const "}}} \ No newline at end of file diff --git a/kb/stores/slugify/slugify-kb.passages.jsonl b/kb/stores/slugify/slugify-kb.passages.jsonl deleted file mode 100644 index 32054ca..0000000 --- a/kb/stores/slugify/slugify-kb.passages.jsonl +++ /dev/null @@ -1,19 +0,0 @@ -{"id":"1","text":"# Security Policy\n\nTo report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.\n","path":".github/security.md","title":"Security Policy","source_type":"doc","kind":"doc"} -{"id":"2","text":"# slugify\n\n> Slugify a string\n\nUseful for URLs, filenames, and IDs.\n\nIt handles most major languages, including [German (umlauts)](https://en.wikipedia.org/wiki/Germanic_umlaut), Vietnamese, Arabic, Russian, [and more](https://github.com/sindresorhus/transliterate#supported-languages).\n\n## Install\n\n```sh\nnpm install @sindresorhus/slugify\n```\n\n## Usage\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('I ♥ Dogs');\n//=> 'i-love-dogs'\n\nslugify(' Déjà Vu! ');\n//=> 'deja-vu'\n\nslugify('fooBar 123 $#%');\n//=> 'foo-bar-123'\n\nslugify('я люблю единорогов');\n//=> 'ya-lyublyu-edinorogov'\n```\n\n## API\n\n### slugify(string, options?)\n\n#### string\n\nType: `string`\n\nString to slugify.\n\n#### options\n\nType: `object`\n\n##### separator\n\nType: `string`\\\nDefault: `'-'`\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('BAR and baz');\n//=> 'bar-and-baz'\n\nslugify('BAR and baz', {separator: '_'});\n//=> 'bar_and_baz'\n\nslugify('BAR and baz', {separator: ''});\n//=> 'barandbaz'\n```\n\n##### lowercase\n\nType: `boolean`\\\nDefault: `true`\n\nMake the slug lowercase.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('Déjà Vu!');\n//=> 'deja-vu'\n\nslugify('Déjà Vu!', {lowercase: false});\n//=> 'Deja-Vu'\n```\n\n##### decamelize\n\nType: `boolean`\\\nDefault: `true`\n\nConvert camelcase to separate words. Internally it does `fooBar` → `foo bar`.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('fooBar');\n//=> 'foo-bar'\n\nslugify('fooBar', {decamelize: false});\n//=> 'foobar'\n```\n\n","path":"readme.md","title":"slugify","source_type":"doc","kind":"doc"} -{"id":"3","text":"##### customReplacements\n\nType: `Array`\\\nDefault: `[\n\t['&', ' and '],\n\t['🦄', ' unicorn '],\n\t['♥', ' love ']\n]`\n\nAdd your own custom replacements.\n\nThe replacements are run on the original string before any other transformations.\n\nThis only overrides a default replacement if you set an item with the same key, like `&`.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('Foo@unicorn', {\n\tcustomReplacements: [\n\t\t['@', 'at']\n\t]\n});\n//=> 'fooatunicorn'\n```\n\nAdd a leading and trailing space to the replacement to have it separated by dashes:\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('foo@unicorn', {\n\tcustomReplacements: [\n\t\t['@', ' at ']\n\t]\n});\n//=> 'foo-at-unicorn'\n```\n\nAnother example:\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('I love 🐶', {\n\tcustomReplacements: [\n\t\t['🐶', 'dogs']\n\t]\n});\n//=> 'i-love-dogs'\n```\n\n##### preserveLeadingUnderscore\n\nType: `boolean`\\\nDefault: `false`\n\nIf your string starts with an underscore, it will be preserved in the slugified string.\n\nSometimes leading underscores are intentional, for example, filenames representing hidden paths on a website.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('_foo_bar');\n//=> 'foo-bar'\n\nslugify('_foo_bar', {preserveLeadingUnderscore: true});\n//=> '_foo-bar'\n```\n\n##### preserveTrailingDash\n\nType: `boolean`\\\nDefault: `false`\n\nIf your string ends with a dash, it will be preserved in the slugified string.\n\nFor example, using slugify on an input field would allow for validation while not preventing the user from writing a slug.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('foo-bar-');\n//=> 'foo-bar'\n\nslugify('foo-bar-', {preserveTrailingDash: true});\n//=> 'foo-bar-'\n```\n\n","path":"readme.md","title":"slugify","source_type":"doc","kind":"doc"} -{"id":"4","text":"##### preserveCharacters\n\nType: `string[]`\\\nDefault: `[]`\n\nPreserve certain characters.\n\nIt cannot contain the `separator`.\n\nFor example, if you want to slugify URLs, but preserve the HTML fragment `#` character.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('foo_bar#baz', {preserveCharacters: ['#']});\n//=> 'foo-bar#baz'\n```\n\n##### locale\n\nType: `string`\\\nDefault: `undefined`\n\nThe locale to use for language-specific transliteration.\n\nSee the [`@sindresorhus/transliterate` package](https://github.com/sindresorhus/transliterate#locale) for more info.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('Räksmörgås');\n//=> 'raeksmoergas'\n\nslugify('Räksmörgås', {locale: 'sv'});\n//=> 'raksmorgas'\n```\n\n##### transliterate\n\nType: `boolean`\\\nDefault: `true`\n\nWhether to transliterate Unicode characters to ASCII.\n\nWhen `false`, non-ASCII characters will be preserved instead of being transliterated. This can improve performance when you don't need transliteration.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('Déjà Vu');\n//=> 'deja-vu'\n\nslugify('Déjà Vu', {transliterate: false});\n//=> 'déjà-vu'\n```\n\n### slugifyWithCounter()\n\nReturns a new instance of `slugify(string, options?)` with a counter to handle multiple occurrences of the same string.\n\n#### Example\n\n```js\nimport {slugifyWithCounter} from '@sindresorhus/slugify';\n\nconst slugify = slugifyWithCounter();\n\nslugify('foo bar');\n//=> 'foo-bar'\n\nslugify('foo bar');\n//=> 'foo-bar-2'\n\nslugify.reset();\n\nslugify('foo bar');\n//=> 'foo-bar'\n```\n\n#### Use-case example of counter\n\nIf, for example, you have a document with multiple sections where each subsection has an example.\n\n```md\n## Section 1\n\n### Example\n\n## Section 2\n\n### Example\n```\n\nYou can then use `slugifyWithCounter()` to generate unique HTML `id`'s to ensure anchors will link to the right headline.\n\n### slugify.reset()\n\nReset the counter\n\n","path":"readme.md","title":"slugify","source_type":"doc","kind":"doc"} -{"id":"5","text":"#### Example\n\n```js\nimport {slugifyWithCounter} from '@sindresorhus/slugify';\n\nconst slugify = slugifyWithCounter();\n\nslugify('foo bar');\n//=> 'foo-bar'\n\nslugify('foo bar');\n//=> 'foo-bar-2'\n\nslugify.reset();\n\nslugify('foo bar');\n//=> 'foo-bar'\n```\n\n## Related\n\n- [slugify-cli](https://github.com/sindresorhus/slugify-cli) - CLI for this module\n- [transliterate](https://github.com/sindresorhus/transliterate) - Convert Unicode characters to Latin characters using transliteration\n- [filenamify](https://github.com/sindresorhus/filenamify) - Convert a string to a valid safe filename\n","path":"readme.md","title":"slugify","source_type":"doc","kind":"doc"} -{"id":"6","text":"# slugify\n\n> Slugify a string\n\nUseful for URLs, filenames, and IDs.\n\nIt handles most major languages, including [German (umlauts)](https://en.wikipedia.org/wiki/Germanic_umlaut), Vietnamese, Arabic, Russian, [and more](https://github.com/sindresorhus/transliterate#supported-languages).\n\n## Install\n\n```sh\nnpm install @sindresorhus/slugify\n```\n\n## Usage\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('I ♥ Dogs');\n//=> 'i-love-dogs'\n\nslugify(' Déjà Vu! ');\n//=> 'deja-vu'\n\nslugify('fooBar 123 $#%');\n//=> 'foo-bar-123'\n\nslugify('я люблю единорогов');\n//=> 'ya-lyublyu-edinorogov'\n```\n\n## API\n\n### slugify(string, options?)\n\n#### string\n\nType: `string`\n\nString to slugify.\n\n#### options\n\nType: `object`\n\n##### separator\n\nType: `string`\\\nDefault: `'-'`\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('BAR and baz');\n//=> 'bar-and-baz'\n\nslugify('BAR and baz', {separator: '_'});\n//=> 'bar_and_baz'\n\nslugify('BAR and baz', {separator: ''});\n//=> 'barandbaz'\n```\n\n##### lowercase\n\nType: `boolean`\\\nDefault: `true`\n\nMake the slug lowercase.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('Déjà Vu!');\n//=> 'deja-vu'\n\nslugify('Déjà Vu!', {lowercase: false});\n//=> 'Deja-Vu'\n```\n\n##### decamelize\n\nType: `boolean`\\\nDefault: `true`\n\nConvert camelcase to separate words. Internally it does `fooBar` → `foo bar`.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('fooBar');\n//=> 'foo-bar'\n\nslugify('fooBar', {decamelize: false});\n//=> 'foobar'\n```\n\n","path":"README.md","title":"slugify","source_type":"doc","kind":"doc"} -{"id":"7","text":"##### customReplacements\n\nType: `Array`\\\nDefault: `[\n\t['&', ' and '],\n\t['🦄', ' unicorn '],\n\t['♥', ' love ']\n]`\n\nAdd your own custom replacements.\n\nThe replacements are run on the original string before any other transformations.\n\nThis only overrides a default replacement if you set an item with the same key, like `&`.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('Foo@unicorn', {\n\tcustomReplacements: [\n\t\t['@', 'at']\n\t]\n});\n//=> 'fooatunicorn'\n```\n\nAdd a leading and trailing space to the replacement to have it separated by dashes:\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('foo@unicorn', {\n\tcustomReplacements: [\n\t\t['@', ' at ']\n\t]\n});\n//=> 'foo-at-unicorn'\n```\n\nAnother example:\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('I love 🐶', {\n\tcustomReplacements: [\n\t\t['🐶', 'dogs']\n\t]\n});\n//=> 'i-love-dogs'\n```\n\n##### preserveLeadingUnderscore\n\nType: `boolean`\\\nDefault: `false`\n\nIf your string starts with an underscore, it will be preserved in the slugified string.\n\nSometimes leading underscores are intentional, for example, filenames representing hidden paths on a website.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('_foo_bar');\n//=> 'foo-bar'\n\nslugify('_foo_bar', {preserveLeadingUnderscore: true});\n//=> '_foo-bar'\n```\n\n##### preserveTrailingDash\n\nType: `boolean`\\\nDefault: `false`\n\nIf your string ends with a dash, it will be preserved in the slugified string.\n\nFor example, using slugify on an input field would allow for validation while not preventing the user from writing a slug.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('foo-bar-');\n//=> 'foo-bar'\n\nslugify('foo-bar-', {preserveTrailingDash: true});\n//=> 'foo-bar-'\n```\n\n","path":"README.md","title":"slugify","source_type":"doc","kind":"doc"} -{"id":"8","text":"##### preserveCharacters\n\nType: `string[]`\\\nDefault: `[]`\n\nPreserve certain characters.\n\nIt cannot contain the `separator`.\n\nFor example, if you want to slugify URLs, but preserve the HTML fragment `#` character.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('foo_bar#baz', {preserveCharacters: ['#']});\n//=> 'foo-bar#baz'\n```\n\n##### locale\n\nType: `string`\\\nDefault: `undefined`\n\nThe locale to use for language-specific transliteration.\n\nSee the [`@sindresorhus/transliterate` package](https://github.com/sindresorhus/transliterate#locale) for more info.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('Räksmörgås');\n//=> 'raeksmoergas'\n\nslugify('Räksmörgås', {locale: 'sv'});\n//=> 'raksmorgas'\n```\n\n##### transliterate\n\nType: `boolean`\\\nDefault: `true`\n\nWhether to transliterate Unicode characters to ASCII.\n\nWhen `false`, non-ASCII characters will be preserved instead of being transliterated. This can improve performance when you don't need transliteration.\n\n```js\nimport slugify from '@sindresorhus/slugify';\n\nslugify('Déjà Vu');\n//=> 'deja-vu'\n\nslugify('Déjà Vu', {transliterate: false});\n//=> 'déjà-vu'\n```\n\n### slugifyWithCounter()\n\nReturns a new instance of `slugify(string, options?)` with a counter to handle multiple occurrences of the same string.\n\n#### Example\n\n```js\nimport {slugifyWithCounter} from '@sindresorhus/slugify';\n\nconst slugify = slugifyWithCounter();\n\nslugify('foo bar');\n//=> 'foo-bar'\n\nslugify('foo bar');\n//=> 'foo-bar-2'\n\nslugify.reset();\n\nslugify('foo bar');\n//=> 'foo-bar'\n```\n\n#### Use-case example of counter\n\nIf, for example, you have a document with multiple sections where each subsection has an example.\n\n```md\n## Section 1\n\n### Example\n\n## Section 2\n\n### Example\n```\n\nYou can then use `slugifyWithCounter()` to generate unique HTML `id`'s to ensure anchors will link to the right headline.\n\n### slugify.reset()\n\nReset the counter\n\n","path":"README.md","title":"slugify","source_type":"doc","kind":"doc"} -{"id":"9","text":"#### Example\n\n```js\nimport {slugifyWithCounter} from '@sindresorhus/slugify';\n\nconst slugify = slugifyWithCounter();\n\nslugify('foo bar');\n//=> 'foo-bar'\n\nslugify('foo bar');\n//=> 'foo-bar-2'\n\nslugify.reset();\n\nslugify('foo bar');\n//=> 'foo-bar'\n```\n\n## Related\n\n- [slugify-cli](https://github.com/sindresorhus/slugify-cli) - CLI for this module\n- [transliterate](https://github.com/sindresorhus/transliterate) - Convert Unicode characters to Latin characters using transliteration\n- [filenamify](https://github.com/sindresorhus/filenamify) - Convert a string to a valid safe filename\n","path":"README.md","title":"slugify","source_type":"doc","kind":"doc"} -{"id":"10","text":"{\n\t\"name\": \"@sindresorhus/slugify\",\n\t\"version\": \"3.0.0\",\n\t\"description\": \"Slugify a string\",\n\t\"license\": \"MIT\",\n\t\"repository\": \"sindresorhus/slugify\",\n\t\"funding\": \"https://github.com/sponsors/sindresorhus\",\n\t\"author\": {\n\t\t\"name\": \"Sindre Sorhus\",\n\t\t\"email\": \"sindresorhus@gmail.com\",\n\t\t\"url\": \"https://sindresorhus.com\"\n\t},\n\t\"type\": \"module\",\n\t\"exports\": {\n\t\t\"types\": \"./index.d.ts\",\n\t\t\"default\": \"./index.js\"\n\t},\n\t\"sideEffects\": false,\n\t\"engines\": {\n\t\t\"node\": \">=20\"\n\t},\n\t\"scripts\": {\n\t\t\"test\": \"xo && ava\"\n\t},\n\t\"files\": [\n\t\t\"index.js\",\n\t\t\"index.d.ts\",\n\t\t\"overridable-replacements.js\"\n\t],\n\t\"keywords\": [\n\t\t\"string\",\n\t\t\"slugify\",\n\t\t\"slug\",\n\t\t\"url\",\n\t\t\"url-safe\",\n\t\t\"urlify\",\n\t\t\"transliterate\",\n\t\t\"transliteration\",\n\t\t\"deburr\",\n\t\t\"unicode\",\n\t\t\"ascii\",\n\t\t\"text\",\n\t\t\"decamelize\",\n\t\t\"pretty\",\n\t\t\"clean\",\n\t\t\"filename\",\n\t\t\"id\"\n\t],\n\t\"dependencies\": {\n\t\t\"@sindresorhus/transliterate\": \"^2.0.0\",\n\t\t\"escape-string-regexp\": \"^5.0.0\"\n\t},\n\t\"devDependencies\": {\n\t\t\"ava\": \"^6.4.1\",\n\t\t\"xo\": \"^1.2.2\"\n\t},\n\t\"xo\": {\n\t\t\"rules\": {\n\t\t\t\"@typescript-eslint/member-ordering\": \"off\"\n\t\t}\n\t}\n}\n","path":"package.json","title":"package.json","source_type":"config","kind":"doc"} -{"id":"11","text":"import escapeStringRegexp from 'escape-string-regexp';\nimport transliterate from '@sindresorhus/transliterate';\nimport builtinOverridableReplacements from './overridable-replacements.js';\n\nconst decamelize = string => string\n\t// Separate capitalized words.\n\t.replaceAll(/([A-Z]{2,})(\\d+)/g, '$1 $2')\n\t.replaceAll(/([a-z\\d]+)([A-Z]{2,})/g, '$1 $2')\n\n\t.replaceAll(/([a-z\\d])([A-Z])/g, '$1 $2')\n\t// `[a-rt-z]` matches all lowercase characters except `s`.\n\t// This avoids matching plural acronyms like `APIs`.\n\t.replaceAll(/([A-Z]+)([A-Z][a-rt-z\\d]+)/g, '$1 $2');\n\nconst removeMootSeparators = (string, separator) => {\n\tconst escapedSeparator = escapeStringRegexp(separator);\n\n\treturn string\n\t\t.replaceAll(new RegExp(`(?:${escapedSeparator}){2,}`, 'g'), separator)\n\t\t.replaceAll(new RegExp(`^(?:${escapedSeparator})|(?:${escapedSeparator})$`, 'g'), '');\n};\n\nconst buildPatternSlug = options => {\n\tlet negationSetPattern = String.raw`a-z\\d`;\n\tnegationSetPattern += options.lowercase ? '' : 'A-Z';\n\n\t// When transliteration is disabled, preserve Unicode characters\n\tif (options.transliterate === false) {\n\t\tnegationSetPattern += String.raw`\\p{L}\\p{N}`;\n\t}\n\n\tif (options.preserveCharacters.length > 0) {\n\t\tfor (const character of options.preserveCharacters) {\n\t\t\tif (character === options.separator) {\n\t\t\t\tthrow new Error(`The separator character \\`${options.separator}\\` cannot be included in preserved characters: ${options.preserveCharacters}`);\n\t\t\t}\n\n\t\t\tnegationSetPattern += escapeStringRegexp(character);\n\t\t}\n\t}\n\n\tconst flags = options.transliterate ? 'g' : 'gu';\n\treturn new RegExp(`[^${negationSetPattern}]+`, flags);\n};\n\n","path":"index.js","title":"index.js","source_type":"doc","kind":"doc"} -{"id":"12","text":"export default function slugify(string, options) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError(`Expected a string, got \\`${typeof string}\\``);\n\t}\n\n\toptions = {\n\t\tseparator: '-',\n\t\tlowercase: true,\n\t\tdecamelize: true,\n\t\tcustomReplacements: [],\n\t\tpreserveLeadingUnderscore: false,\n\t\tpreserveTrailingDash: false,\n\t\tpreserveCharacters: [],\n\t\ttransliterate: true,\n\t\t...options,\n\t};\n\n\tconst shouldPrependUnderscore = options.preserveLeadingUnderscore && string.startsWith('_');\n\tconst shouldAppendDash = options.preserveTrailingDash && string.endsWith('-');\n\n\tif (options.transliterate) {\n\t\tconst customReplacements = new Map([\n\t\t\t...builtinOverridableReplacements,\n\t\t\t...options.customReplacements,\n\t\t]);\n\n\t\tstring = transliterate(string, {customReplacements, locale: options.locale});\n\t} else if (options.customReplacements.length > 0) {\n\t\t// Apply custom replacements even when transliteration is disabled\n\t\tfor (const [key, value] of options.customReplacements) {\n\t\t\tstring = string.replaceAll(key, value);\n\t\t}\n\t}\n\n\tif (options.decamelize) {\n\t\tstring = decamelize(string);\n\t}\n\n\tconst patternSlug = buildPatternSlug(options);\n\n\tif (options.lowercase) {\n\t\tstring = options.locale ? string.toLocaleLowerCase(options.locale) : string.toLowerCase();\n\t}\n\n\t// Detect contractions/possessives by looking for any word followed by a `'t` or `'s`\n\t// in isolation and then remove it. Handles both straight and curly apostrophes.\n\tstring = string.replaceAll(/([a-zA-Z\\d]+)['\\u2019]([ts])(\\s|$)/g, '$1$2$3');\n\n\tstring = string.replace(patternSlug, options.separator);\n\tstring = string.replaceAll('\\\\', '');\n\n\tif (options.separator) {\n\t\tstring = removeMootSeparators(string, options.separator);\n\t}\n\n\tif (shouldPrependUnderscore) {\n\t\tstring = `_${string}`;\n\t}\n\n\tif (shouldAppendDash) {\n\t\tstring = `${string}-`;\n\t}\n\n\treturn string;\n}\n\n","path":"index.js","title":"index.js","source_type":"doc","kind":"doc"} -{"id":"13","text":"export function slugifyWithCounter() {\n\tconst occurrences = new Map();\n\n\tconst countable = (string, options) => {\n\t\tstring = slugify(string, options);\n\n\t\tif (!string) {\n\t\t\treturn '';\n\t\t}\n\n\t\tconst stringLower = string.toLowerCase();\n\t\tconst numberless = occurrences.get(stringLower.replace(/(?:-\\d+?)+?$/, '')) || 0;\n\t\tconst counter = occurrences.get(stringLower);\n\t\toccurrences.set(stringLower, typeof counter === 'number' ? counter + 1 : 1);\n\t\tconst newCounter = occurrences.get(stringLower) || 2;\n\t\tif (newCounter >= 2 || numberless > 2) {\n\t\t\tstring = `${string}-${newCounter}`;\n\t\t}\n\n\t\treturn string;\n\t};\n\n\tcountable.reset = () => {\n\t\toccurrences.clear();\n\t};\n\n\treturn countable;\n}\n","path":"index.js","title":"index.js","source_type":"doc","kind":"doc"} -{"id":"14","text":"export type Options = {\n\t/**\n\t@default '-'\n\n\t@example\n\t```\n\timport slugify from '@sindresorhus/slugify';\n\n\tslugify('BAR and baz');\n\t//=> 'bar-and-baz'\n\n\tslugify('BAR and baz', {separator: '_'});\n\t//=> 'bar_and_baz'\n\n\tslugify('BAR and baz', {separator: ''});\n\t//=> 'barandbaz'\n\t```\n\t*/\n\treadonly separator?: string;\n\n\t/**\n\tMake the slug lowercase.\n\n\t@default true\n\n\t@example\n\t```\n\timport slugify from '@sindresorhus/slugify';\n\n\tslugify('Déjà Vu!');\n\t//=> 'deja-vu'\n\n\tslugify('Déjà Vu!', {lowercase: false});\n\t//=> 'Deja-Vu'\n\t```\n\t*/\n\treadonly lowercase?: boolean;\n\n\t/**\n\tConvert camelcase to separate words. Internally it does `fooBar` → `foo bar`.\n\n\t@default true\n\n\t@example\n\t```\n\timport slugify from '@sindresorhus/slugify';\n\n\tslugify('fooBar');\n\t//=> 'foo-bar'\n\n\tslugify('fooBar', {decamelize: false});\n\t//=> 'foobar'\n\t```\n\t*/\n\treadonly decamelize?: boolean;\n\n\t/**\n\tAdd your own custom replacements.\n\n\tThe replacements are run on the original string before any other transformations.\n\n\tThis only overrides a default replacement if you set an item with the same key, like `&`.\n\n\tAdd a leading and trailing space to the replacement to have it separated by dashes.\n\n\t@default [ ['&', ' and '], ['🦄', ' unicorn '], ['♥', ' love '] ]\n\n\t@example\n\t```\n\timport slugify from '@sindresorhus/slugify';\n\n\tslugify('Foo@unicorn', {\n\t\tcustomReplacements: [\n\t\t\t['@', 'at']\n\t\t]\n\t});\n\t//=> 'fooatunicorn'\n\n\tslugify('foo@unicorn', {\n\t\tcustomReplacements: [\n\t\t\t['@', ' at ']\n\t\t]\n\t});\n\t//=> 'foo-at-unicorn'\n\n\tslugify('I love 🐶', {\n\t\tcustomReplacements: [\n\t\t\t['🐶', 'dogs']\n\t\t]\n\t});\n\t//=> 'i-love-dogs'\n\t```\n\t*/\n\treadonly customReplacements?: ReadonlyArray<[string, string]>;\n\n\t/**\n\tIf your string starts with an underscore, it will be preserved in the slugified string.\n\n\tSometimes leading underscores are intentional, for example, filenames representing hidden paths on a website.\n\n\t@default false\n\n\t@example\n\t```\n\timport slugify from '@sindresorhus/slugify';\n\n\tslugify('_foo_bar');\n\t//=> 'foo-bar'\n\n\tslugify('_foo_bar', {preserveLeadingUnderscore: true});\n\t//=> '_foo-bar'\n\t```\n\t*/\n\treadonly preserveLeadingUnderscore?: boolean;\n\n\t/**\n\tIf your string ends with a dash, it will be preserved in the slugified string.\n\n\tFor example, using slugify on an input field would allow for validation while not preventing the user from writing a slug.\n\n\t@default false\n\n\t@example\n\t```\n\timport slugify from '@sindresorhus/slugify';\n\n\tslugify('foo-bar-');\n\t//=> 'foo-bar'\n\n\tslugify('foo-bar-', {preserveTrailingDash: true});\n\t//=> 'foo-bar-'\n\t```\n\t */\n\treadonly preserveTrailingDash?: boolean;\n\n\t/**\n\tPreserve certain characters.\n\n\tIt cannot contain the `separator`.\n\n\tFor example, if you want to slugify URLs, but preserve the HTML fragment `#` character, you could set `preserveCharacters: ['#']`.\n\n\t@default []\n\n\t@example\n\t```\n\timport slugify from '@sindresorhus/slugify';\n\n\tslugify('foo_bar#baz', {preserveCharacters: ['#']});\n\t//=> 'foo-bar#baz'\n\t```\n\t*/\n\treadonly preserveCharacters?: string[];\n\n\t/**\n\tThe locale to use for language-specific transliteration.\n\n\tSee the [`@sindresorhus/transliterate` package](https://github.com/sindresorhus/transliterate#locale) for more info.\n\n\t@default undefined\n\n\t@example\n\t```\n\timport slugify from '@sindresorhus/slugify';\n\n\tslugify('Räksmörgås');\n\t//=> 'raeksmoergas'\n\n\tslugify('Räksmörgås', {locale: 'sv'});\n\t//=> 'raksmorgas'\n\t```\n\t*/\n\treadonly locale?: string | undefined;\n\n\t/**\n\tWhether to transliterate Unicode characters to ASCII.\n\n\tWhen `false`, non-ASCII characters will be preserved instead of being transliterated. This can improve performance when you don't need transliteration.\n\n\t@default true\n\n\t@example\n\t```\n\timport slugify from '@sindresorhus/slugify';\n\n\tslugify('Déjà Vu');\n\t//=> 'deja-vu'\n\n\tslugify('Déjà Vu', {transliterate: false});\n\t//=> 'déjà-vu'\n\t```\n\t*/\n\treadonly transliterate?: boolean;\n};\n\n/**\nSlugify a string.\n\n@param string - String to slugify.\n\n@example\n```\nimport slugify from '@sindresorhus/slugify';\n\nslugify('I ♥ Dogs');\n//=> 'i-love-dogs'","path":"index.d.ts","title":"index.d.ts","source_type":"doc","kind":"doc"} -{"id":"15","text":"transliteration.\n\n\t@default true\n\n\t@example\n\t```\n\timport slugify from '@sindresorhus/slugify';\n\n\tslugify('Déjà Vu');\n\t//=> 'deja-vu'\n\n\tslugify('Déjà Vu', {transliterate: false});\n\t//=> 'déjà-vu'\n\t```\n\t*/\n\treadonly transliterate?: boolean;\n};\n\n/**\nSlugify a string.\n\n@param string - String to slugify.\n\n@example\n```\nimport slugify from '@sindresorhus/slugify';\n\nslugify('I ♥ Dogs');\n//=> 'i-love-dogs'\n\nslugify(' Déjà Vu! ');\n//=> 'deja-vu'\n\nslugify('fooBar 123 $#%');\n//=> 'foo-bar-123'\n\nslugify('я люблю единорогов');\n//=> 'ya-lyublyu-edinorogov'\n```\n*/\n","path":"index.d.ts","title":"index.d.ts","source_type":"doc","kind":"doc"} -{"id":"16","text":"export default function slugify(string: string, options?: Options): string;\n\nexport type CountableSlugify = {\n\t/**\n\tReset the counter.\n\n\t@example\n\t```\n\timport {slugifyWithCounter} from '@sindresorhus/slugify';\n\n\tconst slugify = slugifyWithCounter();\n\n\tslugify('foo bar');\n\t//=> 'foo-bar'\n\n\tslugify('foo bar');\n\t//=> 'foo-bar-2'\n\n\tslugify.reset();\n\n\tslugify('foo bar');\n\t//=> 'foo-bar'\n\t```\n\t*/\n\treset: () => void;\n\n\t/**\n\tReturns a new instance of `slugify(string, options?)` with a counter to handle multiple occurrences of the same string.\n\n\t@param string - String to slugify.\n\n\t@example\n\t```\n\timport {slugifyWithCounter} from '@sindresorhus/slugify';\n\n\tconst slugify = slugifyWithCounter();\n\n\tslugify('foo bar');\n\t//=> 'foo-bar'\n\n\tslugify('foo bar');\n\t//=> 'foo-bar-2'\n\n\tslugify.reset();\n\n\tslugify('foo bar');\n\t//=> 'foo-bar'\n\t```\n\n\t__Use case example of counter__\n\n\tIf, for example, you have a document with multiple sections where each subsection has an example.\n\n\t```\n\t## Section 1\n\n\t### Example\n\n\t## Section 2\n\n\t### Example\n\t```\n\n\tYou can then use `slugifyWithCounter()` to generate unique HTML `id`'s to ensure anchors will link to the right headline.\n\t*/\n\t(string: string, options?: Options): string;\n};\n\nexport function slugifyWithCounter(): CountableSlugify;\n","path":"index.d.ts","title":"index.d.ts","source_type":"doc","kind":"doc"} -{"id":"17","text":"Source index.js (full):\nimport escapeStringRegexp from 'escape-string-regexp';\nimport transliterate from '@sindresorhus/transliterate';\nimport builtinOverridableReplacements from './overridable-replacements.js';\n\nconst decamelize = string => string\n\t// Separate capitalized words.\n\t.replaceAll(/([A-Z]{2,})(\\d+)/g, '$1 $2')\n\t.replaceAll(/([a-z\\d]+)([A-Z]{2,})/g, '$1 $2')\n\n\t.replaceAll(/([a-z\\d])([A-Z])/g, '$1 $2')\n\t// `[a-rt-z]` matches all lowercase characters except `s`.\n\t// This avoids matching plural acronyms like `APIs`.\n\t.replaceAll(/([A-Z]+)([A-Z][a-rt-z\\d]+)/g, '$1 $2');\n\nconst removeMootSeparators = (string, separator) => {\n\tconst escapedSeparator = escapeStringRegexp(separator);\n\n\treturn string\n\t\t.replaceAll(new RegExp(`(?:${escapedSeparator}){2,}`, 'g'), separator)\n\t\t.replaceAll(new RegExp(`^(?:${escapedSeparator})|(?:${escapedSeparator})$`, 'g'), '');\n};\n\nconst buildPatternSlug = options => {\n\tlet negationSetPattern = String.raw`a-z\\d`;\n\tnegationSetPattern += options.lowercase ? '' : 'A-Z';\n\n\t// When transliteration is disabled, preserve Unicode characters\n\tif (options.transliterate === false) {\n\t\tnegationSetPattern += String.raw`\\p{L}\\p{N}`;\n\t}\n\n\tif (options.preserveCharacters.length > 0) {\n\t\tfor (const character of options.preserveCharacters) {\n\t\t\tif (character === options.separator) {\n\t\t\t\tthrow new Error(`The separator character \\`${options.separator}\\` cannot be included in preserved characters: ${options.preserveCharacters}`);\n\t\t\t}\n\n\t\t\tnegationSetPattern += escapeStringRegexp(character);\n\t\t}\n\t}\n\n\tconst flags = options.transliterate ? 'g' : 'gu';\n\treturn new RegExp(`[^${negationSetPattern}]+`, flags);\n};\n\n","path":"index.js","title":"index.js","source_type":"src","kind":"source"} -{"id":"18","text":"export default function slugify(string, options) {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError(`Expected a string, got \\`${typeof string}\\``);\n\t}\n\n\toptions = {\n\t\tseparator: '-',\n\t\tlowercase: true,\n\t\tdecamelize: true,\n\t\tcustomReplacements: [],\n\t\tpreserveLeadingUnderscore: false,\n\t\tpreserveTrailingDash: false,\n\t\tpreserveCharacters: [],\n\t\ttransliterate: true,\n\t\t...options,\n\t};\n\n\tconst shouldPrependUnderscore = options.preserveLeadingUnderscore && string.startsWith('_');\n\tconst shouldAppendDash = options.preserveTrailingDash && string.endsWith('-');\n\n\tif (options.transliterate) {\n\t\tconst customReplacements = new Map([\n\t\t\t...builtinOverridableReplacements,\n\t\t\t...options.customReplacements,\n\t\t]);\n\n\t\tstring = transliterate(string, {customReplacements, locale: options.locale});\n\t} else if (options.customReplacements.length > 0) {\n\t\t// Apply custom replacements even when transliteration is disabled\n\t\tfor (const [key, value] of options.customReplacements) {\n\t\t\tstring = string.replaceAll(key, value);\n\t\t}\n\t}\n\n\tif (options.decamelize) {\n\t\tstring = decamelize(string);\n\t}\n\n\tconst patternSlug = buildPatternSlug(options);\n\n\tif (options.lowercase) {\n\t\tstring = options.locale ? string.toLocaleLowerCase(options.locale) : string.toLowerCase();\n\t}\n\n\t// Detect contractions/possessives by looking for any word followed by a `'t` or `'s`\n\t// in isolation and then remove it. Handles both straight and curly apostrophes.\n\tstring = string.replaceAll(/([a-zA-Z\\d]+)['\\u2019]([ts])(\\s|$)/g, '$1$2$3');\n\n\tstring = string.replace(patternSlug, options.separator);\n\tstring = string.replaceAll('\\\\', '');\n\n\tif (options.separator) {\n\t\tstring = removeMootSeparators(string, options.separator);\n\t}\n\n\tif (shouldPrependUnderscore) {\n\t\tstring = `_${string}`;\n\t}\n\n\tif (shouldAppendDash) {\n\t\tstring = `${string}-`;\n\t}\n\n\treturn string;\n}\n\n","path":"index.js","title":"index.js","source_type":"src","kind":"source"} -{"id":"19","text":"export function slugifyWithCounter() {\n\tconst occurrences = new Map();\n\n\tconst countable = (string, options) => {\n\t\tstring = slugify(string, options);\n\n\t\tif (!string) {\n\t\t\treturn '';\n\t\t}\n\n\t\tconst stringLower = string.toLowerCase();\n\t\tconst numberless = occurrences.get(stringLower.replace(/(?:-\\d+?)+?$/, '')) || 0;\n\t\tconst counter = occurrences.get(stringLower);\n\t\toccurrences.set(stringLower, typeof counter === 'number' ? counter + 1 : 1);\n\t\tconst newCounter = occurrences.get(stringLower) || 2;\n\t\tif (newCounter >= 2 || numberless > 2) {\n\t\t\tstring = `${string}-${newCounter}`;\n\t\t}\n\n\t\treturn string;\n\t};\n\n\tcountable.reset = () => {\n\t\toccurrences.clear();\n\t};\n\n\treturn countable;\n}\n","path":"index.js","title":"index.js","source_type":"src","kind":"source"} diff --git a/kb/stores/slugify/slugify-kb.rvf b/kb/stores/slugify/slugify-kb.rvf deleted file mode 100644 index 45695fc..0000000 Binary files a/kb/stores/slugify/slugify-kb.rvf and /dev/null differ diff --git a/kb/stores/slugify/slugify-kb.rvf.embed.json b/kb/stores/slugify/slugify-kb.rvf.embed.json deleted file mode 100644 index b82b54c..0000000 --- a/kb/stores/slugify/slugify-kb.rvf.embed.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "model": "Xenova/bge-small-en-v1.5", - "pooling": "mean", - "normalize": true, - "queryPrefix": "Represent this sentence for searching relevant passages: ", - "rankScale": 0.6 -} \ No newline at end of file diff --git a/kb/stores/slugify/slugify-kb.rvf.idmap.json b/kb/stores/slugify/slugify-kb.rvf.idmap.json deleted file mode 100644 index 1fb79c4..0000000 --- a/kb/stores/slugify/slugify-kb.rvf.idmap.json +++ /dev/null @@ -1 +0,0 @@ -{"idToLabel":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":17,"18":18,"19":19},"labelToId":{"1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","10":"10","11":"11","12":"12","13":"13","14":"14","15":"15","16":"16","17":"17","18":"18","19":"19"},"nextLabel":20} \ No newline at end of file diff --git a/kb/stores/slugify/slugify-symbols.json b/kb/stores/slugify/slugify-symbols.json deleted file mode 100644 index 8297410..0000000 --- a/kb/stores/slugify/slugify-symbols.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "target": "slugify", - "metaName": "sindresorhus/slugify", - "generated": "2026-07-02T18:04:02.864Z", - "method": "source-scan", - "count": 6, - "byKind": { - "type_alias": 2, - "fn": 4 - }, - "byCrate": { - "index.d.ts": 4, - "index.js": 2 - }, - "symbols": [ - { - "name": "Options", - "kind": "type_alias", - "signature": "export type Options =", - "module": "index.d.ts", - "crate": "index.d.ts", - "doc": null, - "file": "index.d.ts", - "line": 1, - "source": "source-scan" - }, - { - "name": "slugify", - "kind": "fn", - "signature": "export default function slugify(string: string, options?: Options): string;", - "module": "index.d.ts", - "crate": "index.d.ts", - "doc": "Slugify a string.", - "file": "index.d.ts", - "line": 218, - "source": "source-scan" - }, - { - "name": "CountableSlugify", - "kind": "type_alias", - "signature": "export type CountableSlugify =", - "module": "index.d.ts", - "crate": "index.d.ts", - "doc": null, - "file": "index.d.ts", - "line": 220, - "source": "source-scan" - }, - { - "name": "slugifyWithCounter", - "kind": "fn", - "signature": "export function slugifyWithCounter(): CountableSlugify;", - "module": "index.d.ts", - "crate": "index.d.ts", - "doc": null, - "file": "index.d.ts", - "line": 286, - "source": "source-scan" - }, - { - "name": "slugify", - "kind": "fn", - "signature": "export default function slugify(string, options)", - "module": "index.js", - "crate": "index.js", - "doc": null, - "file": "index.js", - "line": 46, - "source": "source-scan" - }, - { - "name": "slugifyWithCounter", - "kind": "fn", - "signature": "export function slugifyWithCounter()", - "module": "index.js", - "crate": "index.js", - "doc": null, - "file": "index.js", - "line": 112, - "source": "source-scan" - } - ] -} diff --git a/kb/stores/zustand/zustand-dep-graph.json b/kb/stores/zustand/zustand-dep-graph.json deleted file mode 100644 index 2812e86..0000000 --- a/kb/stores/zustand/zustand-dep-graph.json +++ /dev/null @@ -1,151 +0,0 @@ -{ - "target": "zustand", - "metaName": "zustand", - "generated": "2026-07-02T13:45:25.305Z", - "ecosystems": [ - "npm" - ], - "componentCount": 3, - "internalEdgeCount": 2, - "externalDepCount": 11, - "nodes": [ - { - "name": "demo", - "version": "0.0.0", - "description": null, - "manifest": "examples/demo/package.json", - "deps": [ - "@react-three/drei", - "@react-three/fiber", - "@react-three/postprocessing", - "@types/three", - "meshline", - "postprocessing", - "prism-react-renderer", - "prismjs", - "react", - "react-dom", - "three", - "zustand" - ], - "ecosystem": "npm" - }, - { - "name": "starter", - "version": "0.0.0", - "description": null, - "manifest": "examples/starter/package.json", - "deps": [ - "zustand", - "react", - "react-dom" - ], - "ecosystem": "npm" - }, - { - "name": "zustand", - "version": "5.0.14", - "description": "🐻 Bear necessities for state management in React", - "manifest": "package.json", - "deps": [], - "ecosystem": "npm" - } - ], - "internalEdges": [ - { - "from": "demo", - "to": "zustand", - "kind": "normal" - }, - { - "from": "starter", - "to": "zustand", - "kind": "normal" - } - ], - "externalDeps": { - "demo": [ - { - "name": "@react-three/drei", - "req": "*", - "kind": "normal" - }, - { - "name": "@react-three/fiber", - "req": "*", - "kind": "normal" - }, - { - "name": "@react-three/postprocessing", - "req": "*", - "kind": "normal" - }, - { - "name": "@types/three", - "req": "*", - "kind": "normal" - }, - { - "name": "meshline", - "req": "*", - "kind": "normal" - }, - { - "name": "postprocessing", - "req": "*", - "kind": "normal" - }, - { - "name": "prism-react-renderer", - "req": "*", - "kind": "normal" - }, - { - "name": "prismjs", - "req": "*", - "kind": "normal" - }, - { - "name": "react", - "req": "*", - "kind": "normal" - }, - { - "name": "react-dom", - "req": "*", - "kind": "normal" - }, - { - "name": "three", - "req": "*", - "kind": "normal" - } - ], - "starter": [ - { - "name": "react", - "req": "*", - "kind": "normal" - }, - { - "name": "react-dom", - "req": "*", - "kind": "normal" - } - ], - "zustand": [] - }, - "externalDepNames": [ - "@react-three/drei", - "@react-three/fiber", - "@react-three/postprocessing", - "@types/three", - "meshline", - "postprocessing", - "prism-react-renderer", - "prismjs", - "react", - "react-dom", - "three" - ] -} diff --git a/kb/stores/zustand/zustand-entrypoints.json b/kb/stores/zustand/zustand-entrypoints.json deleted file mode 100644 index cfb1629..0000000 --- a/kb/stores/zustand/zustand-entrypoints.json +++ /dev/null @@ -1,331 +0,0 @@ -{ - "target": "zustand", - "metaName": "zustand", - "generated": "2026-07-02T13:45:25.361Z", - "workspace": { - "kind": "npm", - "members": [] - }, - "components": [ - { - "name": "zustand", - "path": "", - "kind": "package", - "description": "🐻 Bear necessities for state management in React", - "scripts": { - "prebuild": "shx rm -rf dist", - "build": "pnpm run prebuild && pnpm run \"/^build:.*/\" && pnpm run postbuild", - "build-watch": "pnpm run \"/^build:.*/\" --watch", - "build:base": "rollup -c", - "build:vanilla": "rollup -c --config-vanilla", - "build:react": "rollup -c --config-react", - "build:middleware": "rollup -c --config-middleware", - "build:middleware:immer": "rollup -c --config-middleware_immer", - "build:shallow": "rollup -c --config-shallow", - "build:vanilla:shallow": "rollup -c --config-vanilla_shallow", - "build:react:shallow": "rollup -c --config-react_shallow", - "build:traditional": "rollup -c --config-traditional", - "postbuild": "pnpm run patch-d-ts && pnpm run copy && pnpm run patch-old-ts && pnpm run patch-esm-ts", - "fix": "pnpm run fix:lint && pnpm run fix:format", - "fix:format": "prettier . --write", - "fix:lint": "eslint . --fix", - "test": "pnpm run \"/^test:.*/\"", - "test:format": "prettier . --list-different", - "test:types": "tsc --noEmit", - "test:lint": "eslint .", - "test:spec": "vitest run", - "patch-d-ts": "node --input-type=module -e \"import { entries } from './rollup.config.mjs'; import shelljs from 'shelljs'; const { find, sed } = shelljs; find('dist/**/*.d.ts').forEach(f => { entries.forEach(({ find, replacement }) => { sed('-i', new RegExp(' from \\'' + find.source.slice(0, -1) + '\\';$'), ' from \\'' + replacement + '\\';', f); }); sed('-i', / from '(\\.[^']+)\\.ts';$/, ' from \\'\\$1\\';', f); });\"", - "copy": "shx cp -r dist/src/* dist/esm && shx cp -r dist/src/* dist && shx rm -rf dist/src && shx rm -rf dist/{src,tests} && shx cp package.json README.md LICENSE dist && json -I -f dist/package.json -e \"this.private=false; this.devDependencies=undefined; this.optionalDependencies=undefined; this.scripts=undefined; this.prettier=undefined;\"", - "patch-old-ts": "shx touch dist/ts_version_4.5_and_above_is_required.d.ts", - "patch-esm-ts": "node -e \"require('shelljs').find('dist/esm/**/*.d.ts').forEach(f=>{var f2=f.replace(/\\.ts$/,'.mts');require('fs').renameSync(f,f2);require('shelljs').sed('-i',/ from '(\\.[^']+)';$/,' from \\'\\$1.mjs\\';',f2);require('shelljs').sed('-i',/^declare module '(\\.[^']+)'/,'declare module \\'\\$1.mjs\\'',f2)})\"" - }, - "bins": [], - "deps": [] - }, - { - "name": "demo", - "path": "examples/demo", - "kind": "package", - "description": null, - "scripts": { - "dev": "vite", - "build": "vite build", - "lint": "eslint .", - "preview": "vite preview" - }, - "bins": [], - "deps": [ - "@react-three/drei", - "@react-three/fiber", - "@react-three/postprocessing", - "@types/three", - "meshline", - "postprocessing", - "prism-react-renderer", - "prismjs", - "react", - "react-dom", - "three", - "zustand" - ] - }, - { - "name": "starter", - "path": "examples/starter", - "kind": "package", - "description": null, - "scripts": { - "dev": "vite", - "build": "tsc && vite build", - "preview": "vite preview" - }, - "bins": [], - "deps": [ - "zustand", - "react", - "react-dom" - ] - } - ], - "binaries": [], - "commands": [ - { - "cmd": "npm run prebuild", - "raw": "shx rm -rf dist", - "category": "other", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run build", - "raw": "pnpm run prebuild && pnpm run \"/^build:.*/\" && pnpm run postbuild", - "category": "build", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run build-watch", - "raw": "pnpm run \"/^build:.*/\" --watch", - "category": "build", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run build:base", - "raw": "rollup -c", - "category": "build", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run build:vanilla", - "raw": "rollup -c --config-vanilla", - "category": "build", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run build:react", - "raw": "rollup -c --config-react", - "category": "build", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run build:middleware", - "raw": "rollup -c --config-middleware", - "category": "build", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run build:middleware:immer", - "raw": "rollup -c --config-middleware_immer", - "category": "build", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run build:shallow", - "raw": "rollup -c --config-shallow", - "category": "build", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run build:vanilla:shallow", - "raw": "rollup -c --config-vanilla_shallow", - "category": "build", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run build:react:shallow", - "raw": "rollup -c --config-react_shallow", - "category": "build", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run build:traditional", - "raw": "rollup -c --config-traditional", - "category": "build", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run postbuild", - "raw": "pnpm run patch-d-ts && pnpm run copy && pnpm run patch-old-ts && pnpm run patch-esm-ts", - "category": "run", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run fix", - "raw": "pnpm run fix:lint && pnpm run fix:format", - "category": "run", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run fix:format", - "raw": "prettier . --write", - "category": "other", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run fix:lint", - "raw": "eslint . --fix", - "category": "other", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run test", - "raw": "pnpm run \"/^test:.*/\"", - "category": "test", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run test:format", - "raw": "prettier . --list-different", - "category": "test", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run test:types", - "raw": "tsc --noEmit", - "category": "test", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run test:lint", - "raw": "eslint .", - "category": "test", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run test:spec", - "raw": "vitest run", - "category": "test", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run patch-d-ts", - "raw": "node --input-type=module -e \"import { entries } from './rollup.config.mjs'; import shelljs from 'shelljs'; const { find, sed } = shelljs; find('dist/**/*.d.ts').forEach(f => { entries.forEach(({ find, replacement }) => { sed('-i', new RegExp(' from \\'' + find.source.slice(0, -1) + '\\';$'), ' from \\'' + replacement + '\\';', f); }); sed('-i', / from '(\\.[^']+)\\.ts';$/, ' from \\'\\$1\\';', f); });\"", - "category": "other", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run copy", - "raw": "shx cp -r dist/src/* dist/esm && shx cp -r dist/src/* dist && shx rm -rf dist/src && shx rm -rf dist/{src,tests} && shx cp package.json README.md LICENSE dist && json -I -f dist/package.json -e \"this.private=false; this.devDependencies=undefined; this.optionalDependencies=undefined; this.scripts=undefined; this.prettier=undefined;\"", - "category": "other", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run patch-old-ts", - "raw": "shx touch dist/ts_version_4.5_and_above_is_required.d.ts", - "category": "other", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run patch-esm-ts", - "raw": "node -e \"require('shelljs').find('dist/esm/**/*.d.ts').forEach(f=>{var f2=f.replace(/\\.ts$/,'.mts');require('fs').renameSync(f,f2);require('shelljs').sed('-i',/ from '(\\.[^']+)';$/,' from \\'\\$1.mjs\\';',f2);require('shelljs').sed('-i',/^declare module '(\\.[^']+)'/,'declare module \\'\\$1.mjs\\'',f2)})\"", - "category": "other", - "source": "package.json", - "note": null - }, - { - "cmd": "npm run dev", - "raw": "vite", - "category": "run", - "source": "examples/demo/package.json", - "note": null - }, - { - "cmd": "npm run build", - "raw": "vite build", - "category": "build", - "source": "examples/demo/package.json", - "note": null - }, - { - "cmd": "npm run lint", - "raw": "eslint .", - "category": "other", - "source": "examples/demo/package.json", - "note": null - }, - { - "cmd": "npm run preview", - "raw": "vite preview", - "category": "other", - "source": "examples/demo/package.json", - "note": null - }, - { - "cmd": "npm run dev", - "raw": "vite", - "category": "run", - "source": "examples/starter/package.json", - "note": null - }, - { - "cmd": "npm run build", - "raw": "tsc && vite build", - "category": "build", - "source": "examples/starter/package.json", - "note": null - }, - { - "cmd": "npm run preview", - "raw": "vite preview", - "category": "other", - "source": "examples/starter/package.json", - "note": null - }, - { - "cmd": "npm install zustand", - "category": "install", - "source": "README.md", - "note": null - } - ], - "install": [ - "npm install zustand" - ], - "quickstart": [ - "npm run postbuild", - "npm run fix", - "npm run dev" - ] -} diff --git a/kb/stores/zustand/zustand-kb.ids.json b/kb/stores/zustand/zustand-kb.ids.json deleted file mode 100644 index c18916a..0000000 --- a/kb/stores/zustand/zustand-kb.ids.json +++ /dev/null @@ -1 +0,0 @@ -{"model":"Xenova/bge-small-en-v1.5","dimensions":384,"metric":"cosine","entries":{"1":{"path":".github/ISSUE_TEMPLATE/bug_report.md","kind":"doc","source_type":"doc","title":"bug_report.md","chunk":1,"of":1,"preview":"--- name: Assigned issue about: This is to create a new issue that already has an assignee. Please open a new discussion otherwise. title: '' labels: '' assignees: '' --- "},"2":{"path":".github/pull_request_template.md","kind":"doc","source_type":"doc","title":"pull_request_template.md","chunk":1,"of":1,"preview":"## Related Bug Reports or Discussions Fixes # ## Summary ## Check List - [ ] `pnpm run fix` for formatting and linting code and docs "},"3":{"path":"CONTRIBUTING.md","kind":"doc","source_type":"doc","title":"Contributing","chunk":1,"of":3,"preview":"# Contributing ## General Guideline ### Reporting Issues If you have found what you think is a bug, please [start a discussion](https://github.com/pmndrs/zustand/discussions/new?category=bug-report). For any usage questions, please [sta"},"4":{"path":"CONTRIBUTING.md","kind":"doc","source_type":"doc","title":"Contributing","chunk":2,"of":3,"preview":"#### General 1. Fork this repository. 2. Create a new feature branch based off the `main` branch. 3. Follow the [Core](#Core) and/or the [Documentation](#Documentation) guide below and come back to this once done. 4. Run `pnpm run fix:form"},"5":{"path":"CONTRIBUTING.md","kind":"doc","source_type":"doc","title":"Contributing","chunk":3,"of":3,"preview":"##### Documentation Our [docs](https://zustand.docs.pmnd.rs) are based on [`pmndrs/docs`](https://github.com/pmndrs/docs). 1. Separately, clone the `pmndrs/docs`. (you don't need to fork it). 2. Inside the `pmndrs/docs` directory: 1. C"},"6":{"path":"docs/index.md","kind":"doc","source_type":"doc","title":"index.md","chunk":1,"of":1,"preview":"--- pageType: home hero: text: Bear necessities for React state tagline: A tiny, predictable store with hooks-first ergonomics and escape hatches that stay out of your way. actions: - theme: brand text: Introduction l"},"7":{"path":"docs/learn/getting-started/comparison.md","kind":"doc","source_type":"doc","title":"comparison.md","chunk":1,"of":6,"preview":"--- title: Comparison description: How Zustand stacks up against similar libraries nav: 2 --- Zustand is one of many state management libraries for React. On this page we will discuss Zustand in comparison to some of these libraries, inclu"},"8":{"path":"docs/learn/getting-started/comparison.md","kind":"doc","source_type":"doc","title":"comparison.md","chunk":2,"of":6,"preview":"### State Model (vs Redux) Conceptually, Zustand and Redux are quite similar, both are based on an immutable state model. However, Redux requires your app to be wrapped in context providers; Zustand does not. **Zustand** ```ts import { c"},"9":{"path":"docs/learn/getting-started/comparison.md","kind":"doc","source_type":"doc","title":"comparison.md","chunk":3,"of":6,"preview":"### Render Optimization (vs Redux) When it comes to render optimizations within your app, there are no major differences in approach between Zustand and Redux. In both libraries it is recommended that you manually apply render optimization"},"10":{"path":"docs/learn/getting-started/comparison.md","kind":"doc","source_type":"doc","title":"comparison.md","chunk":4,"of":6,"preview":"## Valtio ### State Model (vs Valtio) Zustand and Valtio approach state management in a fundamentally different way. Zustand is based on the **immutable** state model, while Valtio is based on the **mutable** state model. **Zustand** ``"},"11":{"path":"docs/learn/getting-started/comparison.md","kind":"doc","source_type":"doc","title":"comparison.md","chunk":5,"of":6,"preview":"### Render Optimization (vs Jotai) Jotai achieves render optimizations through atom dependency. However, with Zustand it is recommended that you manually apply render optimizations by using selectors. **Zustand** ```ts import { create } "},"12":{"path":"docs/learn/getting-started/comparison.md","kind":"doc","source_type":"doc","title":"comparison.md","chunk":6,"of":6,"preview":"### Render Optimization (vs Recoil) Similar to previous optimization comparisons, Recoil makes render optimizations through atom dependency. Whereas with Zustand, it is recommended that you manually apply render optimizations by using sele"},"13":{"path":"docs/learn/getting-started/introduction.md","kind":"doc","source_type":"doc","title":"NPM","chunk":1,"of":2,"preview":"--- title: Introduction description: How to use Zustand nav: 1 ---
\"Logo
A small, fast, and scalable bearbones state management solution. Zustand has "},"14":{"path":"docs/learn/getting-started/introduction.md","kind":"doc","source_type":"doc","title":"NPM","chunk":2,"of":2,"preview":"function Controls() { const increasePopulation = useBear((state) => state.increasePopulation) return } ``` "},"15":{"path":"docs/learn/guides/advanced-typescript.md","kind":"doc","source_type":"doc","title":"advanced-typescript.md","chunk":1,"of":11,"preview":"--- title: Advanced TypeScript Guide nav: 13 --- "},"16":{"path":"docs/learn/guides/advanced-typescript.md","kind":"doc","source_type":"doc","title":"advanced-typescript.md","chunk":2,"of":11,"preview":"## Basic usage The difference when using TypeScript is that instead of writing `create(...)`, you have to write `create()(...)` (notice the extra parentheses `()` too along with the type parameter) where `T` is the type of the state to "},"17":{"path":"docs/learn/guides/advanced-typescript.md","kind":"doc","source_type":"doc","title":"advanced-typescript.md","chunk":3,"of":11,"preview":"ompiles. But if we run it, we'll get an exception: \"Uncaught TypeError: Cannot read properties of undefined (reading 'foo')\". This is because `get` would return `undefined` before the initial state is created (hence you shouldn't call `get`"},"18":{"path":"docs/learn/guides/advanced-typescript.md","kind":"doc","source_type":"doc","title":"advanced-typescript.md","chunk":4,"of":11,"preview":"ernatively, you can also use `combine`, which infers the state so that you do not need to type it. ```ts import { create } from 'zustand' import { combine } from 'zustand/middleware' const useBearStore = create( combine({ bears: 0 }, (s"},"19":{"path":"docs/learn/guides/advanced-typescript.md","kind":"doc","source_type":"doc","title":"advanced-typescript.md","chunk":5,"of":11,"preview":"## Using middlewares You do not have to do anything special to use middlewares in TypeScript. ```ts import { create } from 'zustand' import { devtools, persist } from 'zustand/middleware' interface BearState { bears: number increase:"},"20":{"path":"docs/learn/guides/advanced-typescript.md","kind":"doc","source_type":"doc","title":"advanced-typescript.md","chunk":6,"of":11,"preview":"## Authoring middlewares and advanced usage Imagine you had to write this hypothetical middleware. ```ts import { create } from 'zustand' const foo = (f, bar) => (set, get, store) => { store.foo = bar return f(set, get, store) } con"},"21":{"path":"docs/learn/guides/advanced-typescript.md","kind":"doc","source_type":"doc","title":"advanced-typescript.md","chunk":7,"of":11,"preview":"#### Example with `as Parameters` Workaround ```ts import { create } from 'zustand' interface BearState { bears: number increase: (by: number) => void } const useBearStore = create()((set) => ({ bears: 0, increase: (by"},"22":{"path":"docs/learn/guides/advanced-typescript.md","kind":"doc","source_type":"doc","title":"advanced-typescript.md","chunk":8,"of":11,"preview":"### Middleware that changes the store type ```ts import { create, StateCreator, StoreMutatorIdentifier, Mutate, StoreApi, } from 'zustand' type Foo = < T, A, Mps extends [StoreMutatorIdentifier, unknown][] = [], Mcs exte"},"23":{"path":"docs/learn/guides/advanced-typescript.md","kind":"doc","source_type":"doc","title":"advanced-typescript.md","chunk":9,"of":11,"preview":"### Slices pattern ```ts import { create, StateCreator } from 'zustand' interface BearSlice { bears: number addBear: () => void eatFish: () => void } interface FishSlice { fishes: number addFish: () => void } interface SharedS"},"24":{"path":"docs/learn/guides/advanced-typescript.md","kind":"doc","source_type":"doc","title":"advanced-typescript.md","chunk":10,"of":11,"preview":"### Bounded `useStore` hook for vanilla stores ```ts import { useStore } from 'zustand' import { createStore } from 'zustand/vanilla' interface BearState { bears: number increase: (by: number) => void } const bearStore = createStore<"},"25":{"path":"docs/learn/guides/advanced-typescript.md","kind":"doc","source_type":"doc","title":"advanced-typescript.md","chunk":11,"of":11,"preview":"## Middlewares and their mutators reference - `devtools` — `[\"zustand/devtools\", never]` - `persist` — `[\"zustand/persist\", YourPersistedState]`
`YourPersistedState` is the type of state you are going to persist, ie the return type "},"26":{"path":"docs/learn/guides/auto-generating-selectors.md","kind":"doc","source_type":"doc","title":"auto-generating-selectors.md","chunk":1,"of":2,"preview":"--- title: Auto Generating Selectors nav: 14 --- We recommend using selectors when using either the properties or actions from the store. You can access values from the store like so: ```typescript const bears = useBearStore((state) => st"},"27":{"path":"docs/learn/guides/auto-generating-selectors.md","kind":"doc","source_type":"doc","title":"auto-generating-selectors.md","chunk":2,"of":2,"preview":"## Vanilla Store If you are using a vanilla store, use the following `createSelectors` function: ```typescript import { StoreApi, useStore } from 'zustand' type WithSelectors = S extends { getState: () => infer T } ? S & { use: { [K"},"28":{"path":"docs/learn/guides/beginner-typescript.md","kind":"doc","source_type":"doc","title":"beginner-typescript.md","chunk":1,"of":6,"preview":"--- title: Beginner TypeScript Guide nav: 12 --- Zustand is a lightweight state manager, particularly used with React. Zustand avoids reducers, context, and boilerplate. Paired with TypeScript, you get a strongly typed store-state, actions"},"29":{"path":"docs/learn/guides/beginner-typescript.md","kind":"doc","source_type":"doc","title":"beginner-typescript.md","chunk":2,"of":6,"preview":"function BearCounter() { // Select only 'bears' to avoid unnecessary re-renders const bears = useBearStore((s) => s.bears) return

{bears} bears around

} ``` ### Resetting the Store Resetting is useful after logout or “clear"},"30":{"path":"docs/learn/guides/beginner-typescript.md","kind":"doc","source_type":"doc","title":"beginner-typescript.md","chunk":3,"of":6,"preview":"function logBearState(state: BearState) { console.log(`We have ${state.bears} bears eating ${state.food}`) } logBearState(useBearStore.getState()) ``` ### Selectors #### Multiple Selectors Sometimes you need more than one property. Re"},"31":{"path":"docs/learn/guides/beginner-typescript.md","kind":"doc","source_type":"doc","title":"beginner-typescript.md","chunk":4,"of":6,"preview":"function TotalFood() { // Derived value: required amount food for all bears const totalFood = useBearStore((s) => s.bears * s.foodPerBear) // don't need to have extra property `{ totalFood: 6 }` in your Store return
We need ${to"},"32":{"path":"docs/learn/guides/beginner-typescript.md","kind":"doc","source_type":"doc","title":"beginner-typescript.md","chunk":5,"of":6,"preview":"#### `persist` middleware This middleware keeps your store in `localStorage` (or another storage). This means your bears survive a page refresh. Great for apps where persistence matters. In TS, the state type stays consistent, so no runtim"},"33":{"path":"docs/learn/guides/beginner-typescript.md","kind":"doc","source_type":"doc","title":"beginner-typescript.md","chunk":6,"of":6,"preview":"### Multiple Stores You can create more than one store for different domains. For example, `BearStore` manages bears and `FishStore` manages fish. This keeps state isolated and easier to maintain in larger apps. With TypeScript, each store"},"34":{"path":"docs/learn/guides/connect-to-state-with-url-hash.md","kind":"doc","source_type":"doc","title":"connect-to-state-with-url-hash.md","chunk":1,"of":3,"preview":"--- title: Connect to state with URL nav: 10 --- ## Connect State with URL Hash If you want to connect state of a store to URL hash, you can create your own hash storage. ```ts import { create } from 'zustand' import { persist, StateStor"},"35":{"path":"docs/learn/guides/connect-to-state-with-url-hash.md","kind":"doc","source_type":"doc","title":"connect-to-state-with-url-hash.md","chunk":2,"of":3,"preview":"## Persist and Connect State with URL Parameters (Example: URL Query Parameters) There are times when you want to conditionally connect the state to the URL. This example depicts usage of the URL query parameters while keeping it synced wi"},"36":{"path":"docs/learn/guides/connect-to-state-with-url-hash.md","kind":"doc","source_type":"doc","title":"connect-to-state-with-url-hash.md","chunk":3,"of":3,"preview":"export const buildShareableUrl = (params, version) => { return `${window.location.origin}?${buildURLSuffix(params, version)}` } ``` The generated URL would look like (here without any encoding, for readability): `https://localhost/searc"},"37":{"path":"docs/learn/guides/event-handler-in-pre-react-18.md","kind":"doc","source_type":"doc","title":"event-handler-in-pre-react-18.md","chunk":1,"of":1,"preview":"--- title: Calling actions outside a React event handler in pre React 18 nav: 11 --- Because React handles `setState` synchronously if it's called outside an event handler, updating the state outside an event handler will force react to up"},"38":{"path":"docs/learn/guides/flux-inspired-practice.md","kind":"doc","source_type":"doc","title":"flux-inspired-practice.md","chunk":1,"of":2,"preview":"--- title: Flux inspired practice nav: 19 --- Although Zustand is an unopinionated library, we do recommend a few patterns. These are inspired by practices originally found in [Flux](https://github.com/facebookarchive/flux), and more recen"},"39":{"path":"docs/learn/guides/flux-inspired-practice.md","kind":"doc","source_type":"doc","title":"flux-inspired-practice.md","chunk":2,"of":2,"preview":"## Redux-like patterns If you can't live without Redux-like reducers, you can define a `dispatch` function on the root level of the store: ```typescript const types = { increase: 'INCREASE', decrease: 'DECREASE' } const reducer = (state,"},"40":{"path":"docs/learn/guides/how-to-reset-state.md","kind":"doc","source_type":"doc","title":"how-to-reset-state.md","chunk":1,"of":1,"preview":"--- title: How to reset state nav: 20 --- The following pattern can be used to reset the state to its initial value. ```ts const useSomeStore = create()((set, get, store) => ({ // your code here reset: () => { set"},"41":{"path":"docs/learn/guides/immutable-state-and-merging.md","kind":"doc","source_type":"doc","title":"immutable-state-and-merging.md","chunk":1,"of":1,"preview":"--- title: Immutable state and merging nav: 7 --- Like with React's `useState`, we need to update state immutably. Here's a typical example: ```jsx import { create } from 'zustand' const useCountStore = create((set) => ({ count: 0, "},"42":{"path":"docs/learn/guides/initialize-state-with-props.md","kind":"doc","source_type":"doc","title":"initialize-state-with-props.md","chunk":1,"of":3,"preview":"--- title: Initialize state with props nav: 17 --- In cases where [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection) is needed, such as when a store should be initialized with props from a component, the recommended"},"43":{"path":"docs/learn/guides/initialize-state-with-props.md","kind":"doc","source_type":"doc","title":"initialize-state-with-props.md","chunk":2,"of":3,"preview":"function BearProvider({ children, ...props }: BearProviderProps) { const [store] = useState(() => createBearStore(props)) return {children} } ``` ### Extracting context logic i"},"44":{"path":"docs/learn/guides/initialize-state-with-props.md","kind":"doc","source_type":"doc","title":"initialize-state-with-props.md","chunk":3,"of":3,"preview":"// Provider wrapper & custom hook consumer function App2() { return ( ) } ``` "},"45":{"path":"docs/learn/guides/maps-and-sets-usage.md","kind":"doc","source_type":"doc","title":"Map and Set in Zustand","chunk":1,"of":1,"preview":"--- title: Map and Set Usage nav: 8 --- # Map and Set in Zustand Map and Set are mutable data structures. To use them in Zustand, you must create new instances when updating. ## Map ### Reading a Map ```typescript const foo = useSomeSt"},"46":{"path":"docs/learn/guides/nextjs.md","kind":"doc","source_type":"doc","title":"nextjs.md","chunk":1,"of":5,"preview":"--- title: Setup with Next.js nav: 15 --- > [!NOTE] > We will be updating this guide soon based on our discussion in https://github.com/pmndrs/zustand/discussions/2740. [Next.js](https://nextjs.org) is a popular server-side rendering fram"},"47":{"path":"docs/learn/guides/nextjs.md","kind":"doc","source_type":"doc","title":"nextjs.md","chunk":2,"of":5,"preview":"### Creating a store per request Let's write our store factory function that will create a new store for each request. ```json // tsconfig.json { \"compilerOptions\": { \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"], \"allowJs\": true, "},"48":{"path":"docs/learn/guides/nextjs.md","kind":"doc","source_type":"doc","title":"nextjs.md","chunk":3,"of":5,"preview":"export interface CounterStoreProviderProps { children: ReactNode } export const CounterStoreProvider = ({ children, }: CounterStoreProviderProps) => { const [store] = useState(() => createCounterStore()) return ( { const { count, incrementCount, decrementCount } = useCounterStore( (state) => state, ) return (
Count: {count}
) } ``` ```ts // components/counter/i"},"66":{"path":"docs/learn/guides/testing.md","kind":"doc","source_type":"doc","title":"testing.md","chunk":9,"of":13,"preview":"export const CounterWithContext = () => { return ( ) } ``` ```tsx // components/counter-with-context/index.ts export * from './counter-with-context' ``` ```tsx /"},"67":{"path":"docs/learn/guides/testing.md","kind":"doc","source_type":"doc","title":"testing.md","chunk":10,"of":13,"preview":"export const useCounterStore = create()(counterStoreCreator) ``` ```tsx // contexts/use-counter-store-context.tsx import { type ReactNode, createContext, useContext, useState } from 'react' import { createStore } from 'zustan"},"68":{"path":"docs/learn/guides/testing.md","kind":"doc","source_type":"doc","title":"testing.md","chunk":11,"of":13,"preview":"export function Counter() { const { count, inc } = useCounterStore() return (

Counter Store

{count}

) } ``` ```ts // components/counter/i"},"69":{"path":"docs/learn/guides/testing.md","kind":"doc","source_type":"doc","title":"testing.md","chunk":12,"of":13,"preview":"export const CounterWithContext = () => { return ( ) } ``` ```tsx // components/counter-with-context/index.ts export * from './counter-with-context' ``` ```tsx /"},"70":{"path":"docs/learn/guides/testing.md","kind":"doc","source_type":"doc","title":"testing.md","chunk":13,"of":13,"preview":"## References - **React Testing Library**: [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro) is a very lightweight solution for testing React components. It provides utility functions on top of"},"71":{"path":"docs/learn/guides/tutorial-tic-tac-toe.md","kind":"doc","source_type":"doc","title":"Tutorial: Tic-Tac-Toe","chunk":1,"of":24,"preview":"--- title: 'Tutorial: Tic-Tac-Toe' description: Building a game nav: 3 --- # Tutorial: Tic-Tac-Toe ## Building a game You will build a small tic-tac-toe game during this tutorial. This tutorial does assume existing React knowledge. The t"},"72":{"path":"docs/learn/guides/tutorial-tic-tac-toe.md","kind":"doc","source_type":"doc","title":"Tutorial: Tic-Tac-Toe","chunk":2,"of":24,"preview":"function Square({ value, onSquareClick }) { return ( \n}\n```\n","path":"docs/learn/getting-started/introduction.md","title":"NPM","source_type":"doc","kind":"doc"} -{"id":"15","text":"---\ntitle: Advanced TypeScript Guide\nnav: 13\n---\n\n","path":"docs/learn/guides/advanced-typescript.md","title":"advanced-typescript.md","source_type":"doc","kind":"doc"} -{"id":"16","text":"## Basic usage\n\nThe difference when using TypeScript is that instead of writing `create(...)`, you have to write `create()(...)` (notice the extra parentheses `()` too along with the type parameter) where `T` is the type of the state to annotate it. For example:\n\n```ts\nimport { create } from 'zustand'\n\ninterface BearState {\n bears: number\n increase: (by: number) => void\n}\n\nconst useBearStore = create()((set) => ({\n bears: 0,\n increase: (by) => set((state) => ({ bears: state.bears + by })),\n}))\n```\n\n
\n Why can't we simply infer the type from the initial state?\n\n
\n\n**TLDR**: Because state generic `T` is invariant.\n\nConsider this minimal version `create`:\n\n```ts\ndeclare const create: (f: (get: () => T) => T) => T\n\nconst x = create((get) => ({\n foo: 0,\n bar: () => get(),\n}))\n// `x` is inferred as `unknown` instead of\n// interface X {\n// foo: number,\n// bar: () => X\n// }\n```\n\nHere, if you look at the type of `f` in `create`, i.e. `(get: () => T) => T`, it \"gives\" `T` via return (making it covariant), but it also \"takes\" `T` via `get` (making it contravariant). \"So where does `T` come from?\" TypeScript wonders. It's like that chicken or egg problem. At the end TypeScript, gives up and infers `T` as `unknown`.\n\nSo, as long as the generic to be inferred is invariant (i.e. both covariant and contravariant), TypeScript will be unable to infer it. Another simple example would be this:\n\n```ts\nconst createFoo = {} as (f: (t: T) => T) => T\nconst x = createFoo((_) => 'hello')\n```\n\nHere again, `x` is `unknown` instead of `string`.\n\n
\n More about the inference (just for the people curious and interested in TypeScript)\n\nIn some sense this inference failure is not a problem because a value of type `(f: (t: T) => T) => T` cannot be written. That is to say you can't write the real runtime implementation of `createFoo`. Let's try it:\n\n```js\nconst createFoo = (f) => f(/* ? */)\n```\n\n`createFoo` needs to return the return value of `f`. And to do that we first have to call `f`. And to call it we have to pass a value of type `T`. And to pass a value of type `T` we first have to produce it. But how can we produce a value of type `T` when we don't even know what `T` is? The only way to produce a value of type `T` is to call `f`, but then to call `f` itself we need a value of type `T`. So you see it's impossible to actually write `createFoo`.\n\nSo what we're saying is, the inference failure in case of `createFoo` is not really a problem because it's impossible to implement `createFoo`. But what about the inference failure in case of `create`? That also is not really a problem because it's impossible to implement `create` too. Wait a minute, if it's impossible to implement `create` then how does Zustand implement it? The answer is, it doesn't.\n\nZustand lies that it implemented `create`'s type, it implemented only the most part of it. Here's a simple proof by showing unsoundness. Consider the following code:\n\n```ts\nimport { create } from 'zustand'\n\nconst useBoundStore = create<{ foo: number }>()((_, get) => ({\n foo: get().foo,\n}))\n```\n\nThis code compiles. But if we run it, we'll get an exception: \"Uncaught TypeError: Cannot read properties of undefined (reading 'foo')\". This is because `get` would return `undefined` before the initial state is created (hence you shouldn't call `get` when creating the initial state). The types promise that `get` will never return `undefined` but it does initially, which means Zustand failed to implement it.","path":"docs/learn/guides/advanced-typescript.md","title":"advanced-typescript.md","source_type":"doc","kind":"doc"} -{"id":"17","text":"ompiles. But if we run it, we'll get an exception: \"Uncaught TypeError: Cannot read properties of undefined (reading 'foo')\". This is because `get` would return `undefined` before the initial state is created (hence you shouldn't call `get` when creating the initial state). The types promise that `get` will never return `undefined` but it does initially, which means Zustand failed to implement it.\n\nAnd of course Zustand failed because it's impossible to implement `create` the way types promise (in the same way it's impossible to implement `createFoo`). In other words we don't have a type to express the actual `create` we have implemented. We can't type `get` as `() => T | undefined` because it would cause inconvenience and it still won't be correct as `get` is indeed `() => T` eventually, just if called synchronously it would be `() => undefined`. What we need is some kind of TypeScript feature that allows us to type `get` as `(() => T) & WhenSync<() => undefined>`, which of course is extremely far-fetched.\n\nSo we have two problems: lack of inference and unsoundness. Lack of inference can be solved if TypeScript can improve its inference for invariants. And unsoundness can be solved if TypeScript introduces something like `WhenSync`. To work around lack of inference we manually annotate the state type. And we can't work around unsoundness, but it's not a big deal because it's not much, calling `get` synchronously anyway doesn't make sense.\n\n
\n\n
\n\n
\n Why the currying `()(...)`?\n\n
\n\n**TLDR**: It is a workaround for [microsoft/TypeScript#10571](https://github.com/microsoft/TypeScript/issues/10571).\n\nImagine you have a scenario like this:\n\n```ts\ndeclare const withError: (\n p: Promise,\n) => Promise<[error: undefined, value: T] | [error: E, value: undefined]>\ndeclare const doSomething: () => Promise\n\nconst main = async () => {\n let [error, value] = await withError(doSomething())\n}\n```\n\nHere, `T` is inferred to be a `string` and `E` is inferred to be `unknown`. You might want to annotate `E` as `Foo`, because you are certain of the shape of error `doSomething()` would throw. However, you can't do that. You can either pass all generics or none. Along with annotating `E` as `Foo`, you will also have to annotate `T` as `string` even though it gets inferred anyway. The solution is to make a curried version of `withError` that does nothing at runtime. Its purpose is to just allow you annotate `E`.\n\n```ts\ndeclare const withError: {\n (): (\n p: Promise,\n ) => Promise<[error: undefined, value: T] | [error: E, value: undefined]>\n (\n p: Promise,\n ): Promise<[error: undefined, value: T] | [error: E, value: undefined]>\n}\ndeclare const doSomething: () => Promise\ninterface Foo {\n bar: string\n}\n\nconst main = async () => {\n let [error, value] = await withError()(doSomething())\n}\n```\n\nThis way, `T` gets inferred and you get to annotate `E`. Zustand has the same use case when we want to annotate the state (the first type parameter) but allow other parameters to get inferred.\n\n
\n\nAlternatively, you can also use `combine`, which infers the state so that you do not need to type it.\n\n```ts\nimport { create } from 'zustand'\nimport { combine } from 'zustand/middleware'\n\nconst useBearStore = create(\n combine({ bears: 0 }, (set) => ({\n increase: (by: number) => set((state) => ({ bears: state.bears + by })),\n })),\n)\n```\n\n
\n Be a little careful\n\n
","path":"docs/learn/guides/advanced-typescript.md","title":"advanced-typescript.md","source_type":"doc","kind":"doc"} -{"id":"18","text":"ernatively, you can also use `combine`, which infers the state so that you do not need to type it.\n\n```ts\nimport { create } from 'zustand'\nimport { combine } from 'zustand/middleware'\n\nconst useBearStore = create(\n combine({ bears: 0 }, (set) => ({\n increase: (by: number) => set((state) => ({ bears: state.bears + by })),\n })),\n)\n```\n\n
\n Be a little careful\n\n
\n\nWe achieve the inference by lying a little in the types of `set`, `get`, and `store` that you receive as parameters. The lie is that they're typed as if the state is the first parameter, when in fact the state is the shallow-merge (`{ ...a, ...b }`) of both first parameter and the second parameter's return. For example, `get` from the second parameter has type `() => { bears: number }` and that is a lie as it should be `() => { bears: number, increase: (by: number) => void }`. And `useBearStore` still has the correct type; for example, `useBearStore.getState` is typed as `() => { bears: number, increase: (by: number) => void }`.\n\nIt isn't really a lie because `{ bears: number }` is still a subtype of `{ bears: number, increase: (by: number) => void }`. Therefore, there will be no problem in most cases. You should just be careful while using replace. For example, `set({ bears: 0 }, true)` would compile but will be unsound as it will delete the `increase` function. Another instance where you should be careful is if you use `Object.keys`. `Object.keys(get())` will return `[\"bears\", \"increase\"]` and not `[\"bears\"]`. The return type of `get` can make you fall for these mistakes.\n\n`combine` trades off a little type-safety for the convenience of not having to write a type for state. Hence, you should use `combine` accordingly. It is fine in most cases and you can use it conveniently.\n\n
\n\nNote that we don't use the curried version when using `combine` because `combine` \"creates\" the state. When using a middleware that creates the state, it isn't necessary to use the curried version because the state now can be inferred. Another middleware that creates state is `redux`. So when using `combine`, `redux`, or any other custom middleware that creates the state, we don't recommend using the curried version.\n\nIf you want to infer state type also outside of state declaration, you can use the `ExtractState` type helper:\n\n```ts\nimport { create, ExtractState } from 'zustand'\nimport { combine } from 'zustand/middleware'\n\ntype BearState = ExtractState\n\nconst useBearStore = create(\n combine({ bears: 0 }, (set) => ({\n increase: (by: number) => set((state) => ({ bears: state.bears + by })),\n })),\n)\n```\n\n","path":"docs/learn/guides/advanced-typescript.md","title":"advanced-typescript.md","source_type":"doc","kind":"doc"} -{"id":"19","text":"## Using middlewares\n\nYou do not have to do anything special to use middlewares in TypeScript.\n\n```ts\nimport { create } from 'zustand'\nimport { devtools, persist } from 'zustand/middleware'\n\ninterface BearState {\n bears: number\n increase: (by: number) => void\n}\n\nconst useBearStore = create()(\n devtools(\n persist(\n (set) => ({\n bears: 0,\n increase: (by) => set((state) => ({ bears: state.bears + by })),\n }),\n { name: 'bearStore' },\n ),\n ),\n)\n```\n\nJust make sure you are using them immediately inside `create` so as to make the contextual inference work. Doing something even remotely fancy like the following `myMiddlewares` would require more advanced types.\n\n```ts\nimport { create } from 'zustand'\nimport { devtools, persist } from 'zustand/middleware'\n\nconst myMiddlewares = (f) => devtools(persist(f, { name: 'bearStore' }))\n\ninterface BearState {\n bears: number\n increase: (by: number) => void\n}\n\nconst useBearStore = create()(\n myMiddlewares((set) => ({\n bears: 0,\n increase: (by) => set((state) => ({ bears: state.bears + by })),\n })),\n)\n```\n\nAlso, we recommend using `devtools` middleware as last as possible. For example, when you use it with `immer` as a middleware, it should be `devtools(immer(...))` and not `immer(devtools(...))`. This is because`devtools` mutates the `setState` and adds a type parameter on it, which could get lost if other middlewares (like `immer`) also mutate `setState` before `devtools`. Hence using `devtools` at the end makes sure that no middlewares mutate `setState` before it.\n\n","path":"docs/learn/guides/advanced-typescript.md","title":"advanced-typescript.md","source_type":"doc","kind":"doc"} -{"id":"20","text":"## Authoring middlewares and advanced usage\n\nImagine you had to write this hypothetical middleware.\n\n```ts\nimport { create } from 'zustand'\n\nconst foo = (f, bar) => (set, get, store) => {\n store.foo = bar\n return f(set, get, store)\n}\n\nconst useBearStore = create(foo(() => ({ bears: 0 }), 'hello'))\nconsole.log(useBearStore.foo.toUpperCase())\n```\n\nZustand middlewares can mutate the store. But how could we possibly encode the mutation on the type-level? That is to say how could we type `foo` so that this code compiles?\n\nFor a usual statically typed language, this is impossible. But thanks to TypeScript, Zustand has something called a \"higher-kinded mutator\" that makes this possible. If you are dealing with complex type problems, like typing a middleware or using the `StateCreator` type, you will have to understand this implementation detail. For this, you can [check out #710](https://github.com/pmndrs/zustand/issues/710).\n\nIf you are eager to know what the answer is to this particular problem then you can [see it here](#middleware-that-changes-the-store-type).\n\n### Handling Dynamic `replace` Flag\n\nIf the value of the `replace` flag is not known at compile time and is determined dynamically, you might face issues. To handle this, you can use a workaround by annotating the `replace` parameter with the parameters of the `setState` function:\n\n```ts\nconst replaceFlag = Math.random() > 0.5\nconst args = [{ bears: 5 }, replaceFlag] as Parameters<\n typeof useBearStore.setState\n>\nstore.setState(...args)\n```\n\n","path":"docs/learn/guides/advanced-typescript.md","title":"advanced-typescript.md","source_type":"doc","kind":"doc"} -{"id":"21","text":"#### Example with `as Parameters` Workaround\n\n```ts\nimport { create } from 'zustand'\n\ninterface BearState {\n bears: number\n increase: (by: number) => void\n}\n\nconst useBearStore = create()((set) => ({\n bears: 0,\n increase: (by) => set((state) => ({ bears: state.bears + by })),\n}))\n\nconst replaceFlag = Math.random() > 0.5\nconst args = [{ bears: 5 }, replaceFlag] as Parameters<\n typeof useBearStore.setState\n>\nuseBearStore.setState(...args) // Using the workaround\n```\n\nBy following this approach, you can ensure that your code handles dynamic `replace` flags without encountering type issues.\n\n## Common recipes\n\n### Middleware that doesn't change the store type\n\n```ts\nimport { create, StateCreator, StoreMutatorIdentifier } from 'zustand'\n\ntype Logger = <\n T,\n Mps extends [StoreMutatorIdentifier, unknown][] = [],\n Mcs extends [StoreMutatorIdentifier, unknown][] = [],\n>(\n f: StateCreator,\n name?: string,\n) => StateCreator\n\ntype LoggerImpl = (\n f: StateCreator,\n name?: string,\n) => StateCreator\n\nconst loggerImpl: LoggerImpl = (f, name) => (set, get, store) => {\n const loggedSet: typeof set = (...a) => {\n set(...(a as Parameters))\n console.log(...(name ? [`${name}:`] : []), get())\n }\n const setState = store.setState\n store.setState = (...a) => {\n setState(...(a as Parameters))\n console.log(...(name ? [`${name}:`] : []), store.getState())\n }\n\n return f(loggedSet, get, store)\n}\n\nexport const logger = loggerImpl as unknown as Logger\n\n// ---\n\nconst useBearStore = create()(\n logger(\n (set) => ({\n bears: 0,\n increase: (by) => set((state) => ({ bears: state.bears + by })),\n }),\n 'bear-store',\n ),\n)\n```\n\n","path":"docs/learn/guides/advanced-typescript.md","title":"advanced-typescript.md","source_type":"doc","kind":"doc"} -{"id":"22","text":"### Middleware that changes the store type\n\n```ts\nimport {\n create,\n StateCreator,\n StoreMutatorIdentifier,\n Mutate,\n StoreApi,\n} from 'zustand'\n\ntype Foo = <\n T,\n A,\n Mps extends [StoreMutatorIdentifier, unknown][] = [],\n Mcs extends [StoreMutatorIdentifier, unknown][] = [],\n>(\n f: StateCreator,\n bar: A,\n) => StateCreator\n\ndeclare module 'zustand' {\n interface StoreMutators {\n foo: Write, { foo: A }>\n }\n}\n\ntype FooImpl = (\n f: StateCreator,\n bar: A,\n) => StateCreator\n\nconst fooImpl: FooImpl = (f, bar) => (set, get, _store) => {\n type T = ReturnType\n type A = typeof bar\n\n const store = _store as Mutate, [['foo', A]]>\n store.foo = bar\n return f(set, get, _store)\n}\n\nexport const foo = fooImpl as unknown as Foo\n\ntype Write = Omit & U\n\ntype Cast = T extends U ? T : U\n\n// ---\n\nconst useBearStore = create(foo(() => ({ bears: 0 }), 'hello'))\nconsole.log(useBearStore.foo.toUpperCase())\n```\n\n### `create` without curried workaround\n\nThe recommended way to use `create` is using the curried workaround like so: `create()(...)`. This is because it enables you to infer the store type. But if for some reason you do not want to use the workaround, you can pass the type parameters like the following. Note that in some cases, this acts as an assertion instead of annotation, so we don't recommend it.\n\n```ts\nimport { create } from \"zustand\"\n\ninterface BearState {\n bears: number\n increase: (by: number) => void\n}\n\nconst useBearStore = create<\n BearState,\n [\n ['zustand/persist', BearState],\n ['zustand/devtools', never]\n ]\n>(devtools(persist((set) => ({\n bears: 0,\n increase: (by) => set((state) => ({ bears: state.bears + by })),\n}), { name: 'bearStore' }))\n```\n\n","path":"docs/learn/guides/advanced-typescript.md","title":"advanced-typescript.md","source_type":"doc","kind":"doc"} -{"id":"23","text":"### Slices pattern\n\n```ts\nimport { create, StateCreator } from 'zustand'\n\ninterface BearSlice {\n bears: number\n addBear: () => void\n eatFish: () => void\n}\n\ninterface FishSlice {\n fishes: number\n addFish: () => void\n}\n\ninterface SharedSlice {\n addBoth: () => void\n getBoth: () => number\n}\n\nconst createBearSlice: StateCreator<\n BearSlice & FishSlice,\n [],\n [],\n BearSlice\n> = (set) => ({\n bears: 0,\n addBear: () => set((state) => ({ bears: state.bears + 1 })),\n eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),\n})\n\nconst createFishSlice: StateCreator<\n BearSlice & FishSlice,\n [],\n [],\n FishSlice\n> = (set) => ({\n fishes: 0,\n addFish: () => set((state) => ({ fishes: state.fishes + 1 })),\n})\n\nconst createSharedSlice: StateCreator<\n BearSlice & FishSlice,\n [],\n [],\n SharedSlice\n> = (set, get) => ({\n addBoth: () => {\n // you can reuse previous methods\n get().addBear()\n get().addFish()\n // or do them from scratch\n // set((state) => ({ bears: state.bears + 1, fishes: state.fishes + 1 })\n },\n getBoth: () => get().bears + get().fishes,\n})\n\nconst useBoundStore = create()((...a) => ({\n ...createBearSlice(...a),\n ...createFishSlice(...a),\n ...createSharedSlice(...a),\n}))\n```\n\nA detailed explanation on the slices pattern can be found [here](./slices-pattern.md).\n\nIf you have some middlewares then replace `StateCreator` with `StateCreator`. For example, if you are using `devtools` then it will be `StateCreator`. See the [\"Middlewares and their mutators reference\"](#middlewares-and-their-mutators-reference) section for a list of all mutators.\n\n","path":"docs/learn/guides/advanced-typescript.md","title":"advanced-typescript.md","source_type":"doc","kind":"doc"} -{"id":"24","text":"### Bounded `useStore` hook for vanilla stores\n\n```ts\nimport { useStore } from 'zustand'\nimport { createStore } from 'zustand/vanilla'\n\ninterface BearState {\n bears: number\n increase: (by: number) => void\n}\n\nconst bearStore = createStore()((set) => ({\n bears: 0,\n increase: (by) => set((state) => ({ bears: state.bears + by })),\n}))\n\nfunction useBearStore(): BearState\nfunction useBearStore(selector: (state: BearState) => T): T\nfunction useBearStore(selector?: (state: BearState) => T) {\n return useStore(bearStore, selector!)\n}\n```\n\nYou can also make an abstract `createBoundedUseStore` function if you need to create bounded `useStore` hooks often and want to DRY things up...\n\n```ts\nimport { useStore, StoreApi } from 'zustand'\nimport { createStore } from 'zustand/vanilla'\n\ninterface BearState {\n bears: number\n increase: (by: number) => void\n}\n\nconst bearStore = createStore()((set) => ({\n bears: 0,\n increase: (by) => set((state) => ({ bears: state.bears + by })),\n}))\n\nconst createBoundedUseStore = ((store) => (selector) =>\n useStore(store, selector)) as >(\n store: S,\n) => {\n (): ExtractState\n (selector: (state: ExtractState) => T): T\n}\n\ntype ExtractState = S extends { getState: () => infer X } ? X : never\n\nconst useBearStore = createBoundedUseStore(bearStore)\n```\n\n","path":"docs/learn/guides/advanced-typescript.md","title":"advanced-typescript.md","source_type":"doc","kind":"doc"} -{"id":"25","text":"## Middlewares and their mutators reference\n\n- `devtools` — `[\"zustand/devtools\", never]`\n- `persist` — `[\"zustand/persist\", YourPersistedState]`
\n `YourPersistedState` is the type of state you are going to persist, ie the return type of `options.partialize`, if you're not passing `partialize` options the `YourPersistedState` becomes `Partial`. Also [sometimes](https://github.com/pmndrs/zustand/issues/980#issuecomment-1162289836) passing actual `PersistedState` won't work. In those cases, try passing `unknown`.\n- `immer` — `[\"zustand/immer\", never]`\n- `subscribeWithSelector` — `[\"zustand/subscribeWithSelector\", never]`\n- `redux` — `[\"zustand/redux\", YourAction]`\n- `combine` — no mutator as `combine` does not mutate the store\n","path":"docs/learn/guides/advanced-typescript.md","title":"advanced-typescript.md","source_type":"doc","kind":"doc"} -{"id":"26","text":"---\ntitle: Auto Generating Selectors\nnav: 14\n---\n\nWe recommend using selectors when using either the properties or actions from the store. You can access values from the store like so:\n\n```typescript\nconst bears = useBearStore((state) => state.bears)\n```\n\nHowever, writing these could be tedious. If that is the case for you, you can auto-generate your selectors.\n\n## Create the following function: `createSelectors`\n\n```typescript\nimport { StoreApi, UseBoundStore } from 'zustand'\n\ntype WithSelectors = S extends { getState: () => infer T }\n ? S & { use: { [K in keyof T]: () => T[K] } }\n : never\n\nconst createSelectors = >>(\n _store: S,\n) => {\n const store = _store as WithSelectors\n store.use = {}\n for (const k of Object.keys(store.getState())) {\n ;(store.use as any)[k] = () => store((s) => s[k as keyof typeof s])\n }\n\n return store\n}\n```\n\nIf you have a store like this:\n\n```typescript\ninterface BearState {\n bears: number\n increase: (by: number) => void\n increment: () => void\n}\n\nconst useBearStoreBase = create()((set) => ({\n bears: 0,\n increase: (by) => set((state) => ({ bears: state.bears + by })),\n increment: () => set((state) => ({ bears: state.bears + 1 })),\n}))\n```\n\nApply that function to your store:\n\n```typescript\nconst useBearStore = createSelectors(useBearStoreBase)\n```\n\nNow the selectors are auto generated and you can access them directly:\n\n```typescript\n// get the property\nconst bears = useBearStore.use.bears()\n\n// get the action\nconst increment = useBearStore.use.increment()\n```\n\n","path":"docs/learn/guides/auto-generating-selectors.md","title":"auto-generating-selectors.md","source_type":"doc","kind":"doc"} -{"id":"27","text":"## Vanilla Store\n\nIf you are using a vanilla store, use the following `createSelectors` function:\n\n```typescript\nimport { StoreApi, useStore } from 'zustand'\n\ntype WithSelectors = S extends { getState: () => infer T }\n ? S & { use: { [K in keyof T]: () => T[K] } }\n : never\n\nconst createSelectors = >(_store: S) => {\n const store = _store as WithSelectors\n store.use = {}\n for (const k of Object.keys(store.getState())) {\n ;(store.use as any)[k] = () =>\n useStore(_store, (s) => s[k as keyof typeof s])\n }\n\n return store\n}\n```\n\nThe usage is the same as a React store. If you have a store like this:\n\n```typescript\nimport { createStore } from 'zustand'\n\ninterface BearState {\n bears: number\n increase: (by: number) => void\n increment: () => void\n}\n\nconst store = createStore()((set) => ({\n bears: 0,\n increase: (by) => set((state) => ({ bears: state.bears + by })),\n increment: () => set((state) => ({ bears: state.bears + 1 })),\n}))\n```\n\nApply that function to your store:\n\n```typescript\nconst useBearStore = createSelectors(store)\n```\n\nNow the selectors are auto generated and you can access them directly:\n\n```typescript\n// get the property\nconst bears = useBearStore.use.bears()\n\n// get the action\nconst increment = useBearStore.use.increment()\n```\n\n## Live Demo\n\nFor a working example of this, see the [Code Sandbox](https://codesandbox.io/s/zustand-auto-generate-selectors-forked-rl8v5e?file=/src/selectors.ts).\n\n## Third-party Libraries\n\n- [auto-zustand-selectors-hook](https://github.com/Albert-Gao/auto-zustand-selectors-hook)\n- [react-hooks-global-state](https://github.com/dai-shi/react-hooks-global-state)\n- [zustood](https://github.com/udecode/zustood)\n- [@davstack/store](https://github.com/DawidWraga/davstack)\n","path":"docs/learn/guides/auto-generating-selectors.md","title":"auto-generating-selectors.md","source_type":"doc","kind":"doc"} -{"id":"28","text":"---\ntitle: Beginner TypeScript Guide\nnav: 12\n---\n\nZustand is a lightweight state manager, particularly used with React. Zustand avoids reducers, context, and boilerplate.\nPaired with TypeScript, you get a strongly typed store-state, actions, and selectors-with autocomplete and compile-time safety.\n\nIn this basic guide we’ll cover:\n\n- Creating a typed store (state + actions)\n- Using the store in React components with type safety\n- Resetting the store safely with types\n- Extracting and reusing Store type (for props, tests, and utilities)\n- Composing multiple selectors and building derived state (with type inference and without extra re-renders)\n- Middlewares with TypeScript support (`combine`, `devtools`, `persist`)\n- Async actions with typed API responses\n- Working with `createWithEqualityFn` (enhanced `create` store function)\n- Structuring and coordinating multiple stores\n\n### Creating a Store with State & Actions\n\nHere we describe state and actions using an Typescript interface. The `` generic forces the store to match this shape.\nThis means if you forget a field or use the wrong type, TypeScript will complain. Unlike plain JS, this guarantees type-safe state management.\nThe `create` function uses the curried form, which results in a store of type `UseBoundStore>`.\n\n```ts\n// store.ts\nimport { create } from 'zustand'\n\n// Define types for state & actions\ninterface BearState {\n bears: number\n food: string\n feed: (food: string) => void\n}\n\n// Create store using the curried form of `create`\nexport const useBearStore = create()((set) => ({\n bears: 2,\n food: 'honey',\n feed: (food) => set(() => ({ food })),\n}))\n```\n\n### Using the Store in Components\n\nInside components, you can read state and call actions. Selectors `(s) => s.bears` subscribe to only what you need.\nThis reduces re-renders and improves performance. JS can do this too, but with TS your IDE autocompletes state fields.\n\n```tsx\nimport { useBearStore } from './store'\n\n","path":"docs/learn/guides/beginner-typescript.md","title":"beginner-typescript.md","source_type":"doc","kind":"doc"} -{"id":"29","text":"function BearCounter() {\n // Select only 'bears' to avoid unnecessary re-renders\n const bears = useBearStore((s) => s.bears)\n return

{bears} bears around

\n}\n```\n\n### Resetting the Store\n\nResetting is useful after logout or “clear session”. We use `typeof initialState` to avoid repeating property types.\nTypeScript updates automatically if `initialState` changes. This is safer and cleaner compared to JS.\n\n```tsx\nimport { create } from 'zustand'\n\nconst initialState = { bears: 0, food: 'honey' }\n\n// Reuse state type dynamically\ntype BearState = typeof initialState & {\n increase: (by: number) => void\n reset: () => void\n}\n\nconst useBearStore = create()((set) => ({\n ...initialState,\n increase: (by) => set((s) => ({ bears: s.bears + by })),\n reset: () => set(initialState),\n}))\n\nfunction ResetZoo() {\n const { bears, increase, reset } = useBearStore()\n\n return (\n
\n
{bears}
\n \n \n
\n )\n}\n```\n\n### Extracting Types\n\nZustand provides a built-in helper called `ExtractState`. This is useful for tests, utility functions, or component props.\nIt returns the full type of your store’s state and actions without having to manually redefine them. Extracting the Store type:\n\n```ts\n// store.ts\nimport { create, type ExtractState } from 'zustand'\n\nexport const useBearStore = create((set) => ({\n bears: 3,\n food: 'honey',\n increase: (by: number) => set((s) => ({ bears: s.bears + by })),\n}))\n\n// Extract the type of the whole store state\nexport type BearState = ExtractState\n```\n\nUsing extracted type in tests:\n\n```ts\n// test.cy.ts\nimport { BearState } from './store.ts'\n\ntest('should reset store', () => {\n const snapshot: BearState = useBearStore.getState()\n expect(snapshot.bears).toBeGreaterThanOrEqual(0)\n})\n```\n\nand in utility function:\n\n```ts\n// util.ts\nimport { BearState } from './store.ts'\n\n","path":"docs/learn/guides/beginner-typescript.md","title":"beginner-typescript.md","source_type":"doc","kind":"doc"} -{"id":"30","text":"function logBearState(state: BearState) {\n console.log(`We have ${state.bears} bears eating ${state.food}`)\n}\n\nlogBearState(useBearStore.getState())\n```\n\n### Selectors\n\n#### Multiple Selectors\n\nSometimes you need more than one property. Returning an object from the selector lets you access multiple fields at once.\nHowever, directly destructuring properties from that object can cause unnecessary re-renders.\nTo avoid this, it’s recommended to wrap the selector with `useShallow`, which prevents re-renders when the selected values remain shallowly equal.\nThis is more efficient than subscribing to the whole store. TypeScript ensures you can’t accidentally misspell `bears` or `food`.\nSee the [API documentation](../../reference/hooks/use-shallow.md) for more details on `useShallow`.\n\n```tsx\nimport { create } from 'zustand'\nimport { useShallow } from 'zustand/react/shallow'\n\n// Bear store with explicit types\ninterface BearState {\n bears: number\n food: number\n}\n\nconst useBearStore = create()(() => ({\n bears: 2,\n food: 10,\n}))\n\n// In components, you can use both stores safely\nfunction MultipleSelectors() {\n const { bears, food } = useBearStore(\n useShallow((state) => ({ bears: state.bears, food: state.food })),\n )\n\n return (\n
\n We have {food} units of food for {bears} bears\n
\n )\n}\n```\n\n#### Derived State with Selectors\n\nNot all values need to be stored directly - some can be computed from existing state. You can derive values using selectors.\nThis avoids duplication and keeps the store minimal. TypeScript ensures `bears` is a number, so math is safe.\n\n```tsx\nimport { create } from 'zustand'\n\ninterface BearState {\n bears: number\n foodPerBear: number\n}\n\nconst useBearStore = create()(() => ({\n bears: 3,\n foodPerBear: 2,\n}))\n\n","path":"docs/learn/guides/beginner-typescript.md","title":"beginner-typescript.md","source_type":"doc","kind":"doc"} -{"id":"31","text":"function TotalFood() {\n // Derived value: required amount food for all bears\n const totalFood = useBearStore((s) => s.bears * s.foodPerBear) // don't need to have extra property `{ totalFood: 6 }` in your Store\n\n return
We need ${totalFood} jars of honey
\n}\n```\n\n### Middlewares\n\n#### `combine` middleware\n\nThis middleware separates initial state and actions, making the code cleaner.\nTS automatically infers types from the state and actions, no interface needed.\nThis is different from JS, where type safety is missing. It’s a very popular style in TypeScript projects.\nSee the [API documentation](../../reference/middlewares/combine.md) for more details.\n\n```ts\nimport { create } from 'zustand'\nimport { combine } from 'zustand/middleware'\n\ninterface BearState {\n bears: number\n increase: () => void\n}\n\n// State + actions are separated\nexport const useBearStore = create()(\n combine({ bears: 0 }, (set) => ({\n increase: () => set((s) => ({ bears: s.bears + 1 })),\n })),\n)\n```\n\n#### `devtools` middleware\n\nThis middleware connects Zustand to Redux DevTools. You can inspect changes, time-travel, and debug state.\nIt’s extremely useful in development. TS ensures your actions and state remain type-checked even here.\nSee the [API documentation](../../reference/middlewares/devtools.md) for more details.\n\n```ts\nimport { create } from 'zustand'\nimport { devtools } from 'zustand/middleware'\n\ninterface BearState {\n bears: number\n increase: () => void\n}\n\nexport const useBearStore = create()(\n devtools((set) => ({\n bears: 0,\n increase: () => set((s) => ({ bears: s.bears + 1 })),\n })),\n)\n```\n\n","path":"docs/learn/guides/beginner-typescript.md","title":"beginner-typescript.md","source_type":"doc","kind":"doc"} -{"id":"32","text":"#### `persist` middleware\n\nThis middleware keeps your store in `localStorage` (or another storage). This means your bears survive a page refresh.\nGreat for apps where persistence matters. In TS, the state type stays consistent, so no runtime surprises.\nSee the [API documentation](../../reference/middlewares/persist.md) for more details.\n\n```ts\nimport { create } from 'zustand'\nimport { persist } from 'zustand/middleware'\n\ninterface BearState {\n bears: number\n increase: () => void\n}\n\nexport const useBearStore = create()(\n persist(\n (set) => ({\n bears: 0,\n increase: () => set((s) => ({ bears: s.bears + 1 })),\n }),\n { name: 'bear-storage' }, // localStorage key\n ),\n)\n```\n\n### Async Actions\n\nActions can be async to fetch remote data. Here we fetch bears count and update state.\nTS enforces correct API response type (`BearData`). In JS you might misspell `count` - TS prevents that.\n\n```ts\nimport { create } from 'zustand'\n\ninterface BearData {\n count: number\n}\n\ninterface BearState {\n bears: number\n fetchBears: () => Promise\n}\n\nexport const useBearStore = create()((set) => ({\n bears: 0,\n fetchBears: async () => {\n const res = await fetch('/api/bears')\n const data: BearData = await res.json()\n\n set({ bears: data.count })\n },\n}))\n```\n\n### `createWithEqualityFn`\n\nVariant of `create` with equality built-in. Useful if you always want custom equality checks.\nNot common, but shows Zustand’s flexibility. TS still keeps full type inference.\nSee the [API documentation](../../reference/apis/create-with-equality-fn.md) for more details.\n\n```ts\nimport { createWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/shallow'\n\nconst useBearStore = createWithEqualityFn(() => ({\n bears: 0,\n}))\n\nconst bears = useBearStore((s) => s.bears, Object.is)\n// or\nconst bears = useBearStore((s) => ({ bears: s.bears }), shallow)\n```\n\n","path":"docs/learn/guides/beginner-typescript.md","title":"beginner-typescript.md","source_type":"doc","kind":"doc"} -{"id":"33","text":"### Multiple Stores\n\nYou can create more than one store for different domains. For example, `BearStore` manages bears and `FishStore` manages fish.\nThis keeps state isolated and easier to maintain in larger apps. With TypeScript, each store has its own strict type - you can’t accidentally mix bears and fish.\n\n```tsx\nimport { create } from 'zustand'\n\n// Bear store with explicit types\ninterface BearState {\n bears: number\n addBear: () => void\n}\n\nconst useBearStore = create()((set) => ({\n bears: 2,\n addBear: () => set((s) => ({ bears: s.bears + 1 })),\n}))\n\n// Fish store with explicit types\ninterface FishState {\n fish: number\n addFish: () => void\n}\n\nconst useFishStore = create()((set) => ({\n fish: 5,\n addFish: () => set((s) => ({ fish: s.fish + 1 })),\n}))\n\n// In components, you can use both stores safely\nfunction Zoo() {\n const { bears, addBear } = useBearStore()\n const { fish, addFish } = useFishStore()\n\n return (\n
\n
\n {bears} bears and {fish} fish\n
\n \n \n
\n )\n}\n```\n\n### Conclusion\n\nZustand together with TypeScript provides a balance: you keep the simplicity of small, minimalistic stores, while gaining the safety of strong typing.\nYou don’t need boilerplate or complex patterns - state and actions live side by side, fully typed, and ready to use.\nStart with a basic store to learn the pattern, then expand gradually: use `combine` for cleaner inference, `persist` for storage, and `devtools` for debugging.\n","path":"docs/learn/guides/beginner-typescript.md","title":"beginner-typescript.md","source_type":"doc","kind":"doc"} -{"id":"34","text":"---\ntitle: Connect to state with URL\nnav: 10\n---\n\n## Connect State with URL Hash\n\nIf you want to connect state of a store to URL hash, you can create your own hash storage.\n\n```ts\nimport { create } from 'zustand'\nimport { persist, StateStorage, createJSONStorage } from 'zustand/middleware'\n\nconst hashStorage: StateStorage = {\n getItem: (key): string => {\n const searchParams = new URLSearchParams(location.hash.slice(1))\n const storedValue = searchParams.get(key) ?? ''\n return JSON.parse(storedValue)\n },\n setItem: (key, newValue): void => {\n const searchParams = new URLSearchParams(location.hash.slice(1))\n searchParams.set(key, JSON.stringify(newValue))\n location.hash = searchParams.toString()\n },\n removeItem: (key): void => {\n const searchParams = new URLSearchParams(location.hash.slice(1))\n searchParams.delete(key)\n location.hash = searchParams.toString()\n },\n}\n\nexport const useBoundStore = create()(\n persist(\n (set, get) => ({\n fishes: 0,\n addAFish: () => set({ fishes: get().fishes + 1 }),\n }),\n {\n name: 'food-storage', // unique name\n storage: createJSONStorage(() => hashStorage),\n },\n ),\n)\n```\n\n","path":"docs/learn/guides/connect-to-state-with-url-hash.md","title":"connect-to-state-with-url-hash.md","source_type":"doc","kind":"doc"} -{"id":"35","text":"## Persist and Connect State with URL Parameters (Example: URL Query Parameters)\n\nThere are times when you want to conditionally connect the state to the URL.\nThis example depicts usage of the URL query parameters\nwhile keeping it synced with another persistence implementation, like `localstorage`.\n\nIf you want the URL params to always populate, the conditional check on `getUrlSearch()` can be removed.\n\nThe implementation below will update the URL in place, without refresh, as the relevant states change.\n\n```ts\nimport { create } from 'zustand'\nimport { persist, StateStorage, createJSONStorage } from 'zustand/middleware'\n\nconst getUrlSearch = () => {\n return window.location.search.slice(1)\n}\n\nconst persistentStorage: StateStorage = {\n getItem: (key): string => {\n // Check URL first\n if (getUrlSearch()) {\n const searchParams = new URLSearchParams(getUrlSearch())\n const storedValue = searchParams.get(key)\n return JSON.parse(storedValue as string)\n } else {\n // Otherwise, we should load from localstorage or alternative storage\n return JSON.parse(localStorage.getItem(key) as string)\n }\n },\n setItem: (key, newValue): void => {\n // Check if query params exist at all, can remove check if always want to set URL\n if (getUrlSearch()) {\n const searchParams = new URLSearchParams(getUrlSearch())\n searchParams.set(key, JSON.stringify(newValue))\n window.history.replaceState(null, '', `?${searchParams.toString()}`)\n }\n\n localStorage.setItem(key, JSON.stringify(newValue))\n },\n removeItem: (key): void => {\n const searchParams = new URLSearchParams(getUrlSearch())\n searchParams.delete(key)\n window.location.search = searchParams.toString()\n },\n}\n\ntype LocalAndUrlStore = {\n typesOfFish: string[]\n addTypeOfFish: (fishType: string) => void\n numberOfBears: number\n setNumberOfBears: (newNumber: number) => void\n}\n\nconst storageOptions = {\n name: 'fishAndBearsStore',\n storage: createJSONStorage(() => persistentStorage),\n}\n\nconst useLocalAndUrlStore = create()(\n persist(\n (set) => ({\n typesOfFish: [],\n addTypeOfFish: (fishType) =>\n set((state) => ({ typesOfFish: [...state.typesOfFish, fishType] })),\n\n numberOfBears: 0,\n setNumberOfBears: (numberOfBears) => set(() => ({ numberOfBears })),\n }),\n storageOptions,\n ),\n)\n\nexport default useLocalAndUrlStore\n```\n\nWhen generating the URL from a component, you can call buildShareableUrl:\n\n```ts\nconst buildURLSuffix = (params, version = 0) => {\n const searchParams = new URLSearchParams()\n\n const zustandStoreParams = {\n state: {\n typesOfFish: params.typesOfFish,\n numberOfBears: params.numberOfBears,\n },\n version: version, // version is here because that is included with how Zustand sets the state\n }\n\n // The URL param key should match the name of the store, as specified as in storageOptions above\n searchParams.set('fishAndBearsStore', JSON.stringify(zustandStoreParams))\n return searchParams.toString()\n}\n\n","path":"docs/learn/guides/connect-to-state-with-url-hash.md","title":"connect-to-state-with-url-hash.md","source_type":"doc","kind":"doc"} -{"id":"36","text":"export const buildShareableUrl = (params, version) => {\n return `${window.location.origin}?${buildURLSuffix(params, version)}`\n}\n```\n\nThe generated URL would look like (here without any encoding, for readability):\n\n`https://localhost/search?fishAndBearsStore={\"state\":{\"typesOfFish\":[\"tilapia\",\"salmon\"],\"numberOfBears\":15},\"version\":0}}`\n\n### Demo\n\n- Hash: https://stackblitz.com/edit/vitejs-vite-9vg24prg\n- Query: https://stackblitz.com/edit/vitejs-vite-hyc97ynf\n","path":"docs/learn/guides/connect-to-state-with-url-hash.md","title":"connect-to-state-with-url-hash.md","source_type":"doc","kind":"doc"} -{"id":"37","text":"---\ntitle: Calling actions outside a React event handler in pre React 18\nnav: 11\n---\n\nBecause React handles `setState` synchronously if it's called outside an event handler, updating the state outside an event handler will force react to update the components synchronously. Therefore, there is a risk of encountering the zombie-child effect.\nIn order to fix this, the action needs to be wrapped in `unstable_batchedUpdates` like so:\n\n```jsx\nimport { unstable_batchedUpdates } from 'react-dom' // or 'react-native'\n\nconst useFishStore = create((set) => ({\n fishes: 0,\n increaseFishes: () => set((prev) => ({ fishes: prev.fishes + 1 })),\n}))\n\nconst nonReactCallback = () => {\n unstable_batchedUpdates(() => {\n useFishStore.getState().increaseFishes()\n })\n}\n```\n\nMore details: https://github.com/pmndrs/zustand/issues/302\n","path":"docs/learn/guides/event-handler-in-pre-react-18.md","title":"event-handler-in-pre-react-18.md","source_type":"doc","kind":"doc"} -{"id":"38","text":"---\ntitle: Flux inspired practice\nnav: 19\n---\n\nAlthough Zustand is an unopinionated library, we do recommend a few patterns.\nThese are inspired by practices originally found in [Flux](https://github.com/facebookarchive/flux),\nand more recently [Redux](https://redux.js.org/understanding/thinking-in-redux/three-principles),\nso if you are coming from another library, you should feel right at home.\n\nHowever, Zustand does differ in some fundamental ways,\nso some terminology may not perfectly align to other libraries.\n\n## Recommended patterns\n\n### Single store\n\nYour applications global state should be located in a single Zustand store.\n\nIf you have a large application, Zustand supports [splitting the store into slices](./slices-pattern.md).\n\n### Use `set` / `setState` to update the store\n\nAlways use `set` (or `setState`) to perform updates to your store.\n`set` (and `setState`) ensures the described update is correctly merged and listeners are appropriately notified.\n\n### Colocate store actions\n\nIn Zustand, state can be updated without the use of dispatched actions and reducers found in other Flux libraries.\nThese store actions can be added directly to the store as shown below.\n\nOptionally, by using `setState` they can be [located external to the store](./practice-with-no-store-actions.md)\n\n```js\nconst useBoundStore = create((set) => ({\n storeSliceA: ...,\n storeSliceB: ...,\n storeSliceC: ...,\n updateX: () => set(...),\n updateY: () => set(...),\n}))\n```\n\n","path":"docs/learn/guides/flux-inspired-practice.md","title":"flux-inspired-practice.md","source_type":"doc","kind":"doc"} -{"id":"39","text":"## Redux-like patterns\n\nIf you can't live without Redux-like reducers, you can define a `dispatch` function on the root level of the store:\n\n```typescript\nconst types = { increase: 'INCREASE', decrease: 'DECREASE' }\n\nconst reducer = (state, { type, by = 1 }) => {\n switch (type) {\n case types.increase:\n return { grumpiness: state.grumpiness + by }\n case types.decrease:\n return { grumpiness: state.grumpiness - by }\n }\n}\n\nconst useGrumpyStore = create((set) => ({\n grumpiness: 0,\n dispatch: (args) => set((state) => reducer(state, args)),\n}))\n\nconst dispatch = useGrumpyStore((state) => state.dispatch)\ndispatch({ type: types.increase, by: 2 })\n```\n\nYou could also use our redux-middleware. It wires up your main reducer, sets initial state, and adds a dispatch function to the state itself and the vanilla api.\n\n```typescript\nimport { redux } from 'zustand/middleware'\n\nconst useReduxStore = create(redux(reducer, initialState))\n```\n\nAnother way to update the store could be through functions wrapping the state functions. These could also handle side-effects of actions. For example, with HTTP-calls. To use Zustand in a non-reactive way, see [the readme](https://github.com/pmndrs/zustand#readingwriting-state-and-reacting-to-changes-outside-of-components).\n","path":"docs/learn/guides/flux-inspired-practice.md","title":"flux-inspired-practice.md","source_type":"doc","kind":"doc"} -{"id":"40","text":"---\ntitle: How to reset state\nnav: 20\n---\n\nThe following pattern can be used to reset the state to its initial value.\n\n```ts\nconst useSomeStore = create()((set, get, store) => ({\n // your code here\n reset: () => {\n set(store.getInitialState())\n },\n}))\n```\n\nResetting multiple stores at once\n\n```ts\nimport type { StateCreator } from 'zustand'\nimport { create: actualCreate } from 'zustand'\n\nconst storeResetFns = new Set<() => void>()\n\nconst resetAllStores = () => {\n storeResetFns.forEach((resetFn) => {\n resetFn()\n })\n}\n\nexport const create = (() => {\n return (stateCreator: StateCreator) => {\n const store = actualCreate(stateCreator)\n storeResetFns.add(() => {\n store.setState(store.getInitialState(), true)\n })\n return store\n }\n}) as typeof actualCreate\n```\n\n## Demo\n\n- Basic: https://stackblitz.com/edit/zustand-how-to-reset-state-basic\n- Advanced: https://stackblitz.com/edit/zustand-how-to-reset-state-advanced\n","path":"docs/learn/guides/how-to-reset-state.md","title":"how-to-reset-state.md","source_type":"doc","kind":"doc"} -{"id":"41","text":"---\ntitle: Immutable state and merging\nnav: 7\n---\n\nLike with React's `useState`, we need to update state immutably.\n\nHere's a typical example:\n\n```jsx\nimport { create } from 'zustand'\n\nconst useCountStore = create((set) => ({\n count: 0,\n inc: () => set((state) => ({ count: state.count + 1 })),\n}))\n```\n\nThe `set` function is to update state in the store.\nBecause the state is immutable, it should have been like this:\n\n```js\nset((state) => ({ ...state, count: state.count + 1 }))\n```\n\nHowever, as this is a common pattern, `set` actually merges state, and\nwe can skip the `...state` part:\n\n```js\nset((state) => ({ count: state.count + 1 }))\n```\n\n## Nested objects\n\nThe `set` function merges state at only one level.\nIf you have a nested object, you need to merge them explicitly. You will use the spread operator pattern like so:\n\n```jsx\nimport { create } from 'zustand'\n\nconst useCountStore = create((set) => ({\n nested: { count: 0 },\n inc: () =>\n set((state) => ({\n nested: { ...state.nested, count: state.nested.count + 1 },\n })),\n}))\n```\n\nFor complex use cases, consider using some libraries that help with immutable updates.\nYou can refer to [Updating nested state object values](./updating-state.md#deeply-nested-object).\n\n## Replace flag\n\nTo disable the merging behavior, you can specify a `replace` boolean value for `set` like so:\n\n```js\nset((state) => newState, true)\n```\n","path":"docs/learn/guides/immutable-state-and-merging.md","title":"immutable-state-and-merging.md","source_type":"doc","kind":"doc"} -{"id":"42","text":"---\ntitle: Initialize state with props\nnav: 17\n---\n\nIn cases where [dependency injection](https://en.wikipedia.org/wiki/Dependency_injection) is needed, such as when a store should be initialized with props from a component, the recommended approach is to use a vanilla store with React.context.\n\n## Store creator with `createStore`\n\n```ts\nimport { createStore } from 'zustand'\n\ninterface BearProps {\n bears: number\n}\n\ninterface BearState extends BearProps {\n addBear: () => void\n}\n\ntype BearStore = ReturnType\n\nconst createBearStore = (initProps?: Partial) => {\n const DEFAULT_PROPS: BearProps = {\n bears: 0,\n }\n return createStore()((set) => ({\n ...DEFAULT_PROPS,\n ...initProps,\n addBear: () => set((state) => ({ bears: ++state.bears })),\n }))\n}\n```\n\n## Creating a context with `React.createContext`\n\n```ts\nimport { createContext } from 'react'\n\nexport const BearContext = createContext(null)\n```\n\n## Basic component usage\n\n```tsx\n// Provider implementation\nimport { useState } from 'react'\n\nfunction App() {\n const [store] = useState(() => createBearStore())\n return (\n \n \n \n )\n}\n```\n\n```tsx\n// Consumer component\nimport { useContext } from 'react'\nimport { useStore } from 'zustand'\n\nfunction BasicConsumer() {\n const store = useContext(BearContext)\n if (!store) throw new Error('Missing BearContext.Provider in the tree')\n\n const bears = useStore(store, (s) => s.bears)\n const addBear = useStore(store, (s) => s.addBear)\n\n return (\n <>\n
{bears} Bears.
\n \n \n )\n}\n```\n\n## Common patterns\n\n### Wrapping the context provider\n\n```tsx\n// Provider wrapper\nimport { useState } from 'react'\n\ntype BearProviderProps = React.PropsWithChildren\n\n","path":"docs/learn/guides/initialize-state-with-props.md","title":"initialize-state-with-props.md","source_type":"doc","kind":"doc"} -{"id":"43","text":"function BearProvider({ children, ...props }: BearProviderProps) {\n const [store] = useState(() => createBearStore(props))\n return {children}\n}\n```\n\n### Extracting context logic into a custom hook\n\n```tsx\n// Mimic the hook returned by `create`\nimport { useContext } from 'react'\nimport { useStore } from 'zustand'\n\nfunction useBearContext(selector: (state: BearState) => T): T {\n const store = useContext(BearContext)\n if (!store) throw new Error('Missing BearContext.Provider in the tree')\n return useStore(store, selector)\n}\n```\n\n```tsx\n// Consumer usage of the custom hook\nfunction CommonConsumer() {\n const bears = useBearContext((s) => s.bears)\n const addBear = useBearContext((s) => s.addBear)\n return (\n <>\n
{bears} Bears.
\n \n \n )\n}\n```\n\n### Optionally use memoized selector for stable outputs\n\n```tsx\nimport { useShallow } from 'zustand/react/shallow'\n\nconst meals = ['Salmon', 'Berries', 'Nuts']\n\nfunction CommonConsumer() {\n const bearMealsOrder = useBearContext(\n useShallow((s) =>\n Array.from({ length: s.bears }).map((_, index) =>\n meals.at(index % meals.length),\n ),\n ),\n )\n return (\n <>\n Order:\n
    \n {bearMealsOrder.map((meal) => (\n
  • {meal}
  • \n ))}\n
\n \n )\n}\n```\n\n### Optionally allow using a custom equality function\n\n```tsx\n// Allow custom equality function by using useStoreWithEqualityFn instead of useStore\nimport { useContext } from 'react'\nimport { useStoreWithEqualityFn } from 'zustand/traditional'\n\nfunction useBearContext(\n selector: (state: BearState) => T,\n equalityFn?: (left: T, right: T) => boolean,\n): T {\n const store = useContext(BearContext)\n if (!store) throw new Error('Missing BearContext.Provider in the tree')\n return useStoreWithEqualityFn(store, selector, equalityFn)\n}\n```\n\n### Complete example\n\n```tsx\n","path":"docs/learn/guides/initialize-state-with-props.md","title":"initialize-state-with-props.md","source_type":"doc","kind":"doc"} -{"id":"44","text":"// Provider wrapper & custom hook consumer\nfunction App2() {\n return (\n \n \n \n )\n}\n```\n","path":"docs/learn/guides/initialize-state-with-props.md","title":"initialize-state-with-props.md","source_type":"doc","kind":"doc"} -{"id":"45","text":"---\ntitle: Map and Set Usage\nnav: 8\n---\n\n# Map and Set in Zustand\n\nMap and Set are mutable data structures. To use them in Zustand, you must create new instances when updating.\n\n## Map\n\n### Reading a Map\n\n```typescript\nconst foo = useSomeStore((state) => state.foo)\n```\n\n### Updating a Map\n\nAlways create a new Map instance:\n\n```ts\n// Update single entry\nset((state) => ({\n foo: new Map(state.foo).set(key, value),\n}))\n\n// Delete entry\nset((state) => {\n const next = new Map(state.foo)\n next.delete(key)\n return { foo: next }\n})\n\n// Update multiple entries\nset((state) => {\n const next = new Map(state.foo)\n next.set('key1', 'value1')\n next.set('key2', 'value2')\n return { foo: next }\n})\n\n// Clear\nset({ foo: new Map() })\n```\n\n## Set\n\n### Reading a Set\n\n```ts\nconst bar = useSomeStore((state) => state.bar)\n```\n\n### Updating a Set\n\nAlways create a new Set instance:\n\n```ts\n// Add item\nset((state) => ({\n bar: new Set(state.bar).add(item),\n}))\n\n// Delete item\nset((state) => {\n const next = new Set(state.bar)\n next.delete(item)\n return { bar: next }\n})\n\n// Toggle item\nset((state) => {\n const next = new Set(state.bar)\n next.has(item) ? next.delete(item) : next.add(item)\n return { bar: next }\n})\n\n// Clear\nset({ bar: new Set() })\n```\n\n## Why New Instances?\n\nZustand detects changes by comparing references. Mutating a Map or Set doesn't change its reference:\n\n```ts\n// ❌ Wrong - same reference, no re-render\nset((state) => {\n state.foo.set(key, value)\n return { foo: state.foo }\n})\n\n// ✅ Correct - new reference, triggers re-render\nset((state) => ({\n foo: new Map(state.foo).set(key, value),\n}))\n```\n\n## Pitfall: Type Hints for Empty Collections\n\nProvide type hints when initializing empty Maps and Sets:\n\n```ts\n{\n ids: new Set([] as string[]),\n users: new Map([] as [string, User][])\n}\n```\n\nWithout type hints, TypeScript infers `never[]` which prevents adding items later.\n\n## Demos\n\nBasic: https://stackblitz.com/edit/vitejs-vite-5cu5ddvx\n","path":"docs/learn/guides/maps-and-sets-usage.md","title":"Map and Set in Zustand","source_type":"doc","kind":"doc"} -{"id":"46","text":"---\ntitle: Setup with Next.js\nnav: 15\n---\n\n> [!NOTE]\n> We will be updating this guide soon based on our discussion in https://github.com/pmndrs/zustand/discussions/2740.\n\n[Next.js](https://nextjs.org) is a popular server-side rendering framework for React that presents\nsome unique challenges for using Zustand properly.\nKeep in mind that Zustand store is a global\nvariable (AKA module state) making it optional to use a `Context`.\nThese challenges include:\n\n- **Per-request store:** A Next.js server can handle multiple requests simultaneously. This means\n that the store should be created per request and should not be shared across requests.\n- **SSR friendly:** Next.js applications are rendered twice, first on the server\n and again on the client. Having different outputs on both the client and the server will result\n in \"hydration errors.\" The store will have to be initialized on the server and then\n re-initialized on the client with the same data in order to avoid that. Please read more about\n that in our [SSR and Hydration](./ssr-and-hydration.md) guide.\n- **SPA routing friendly:** Next.js supports a hybrid model for client side routing, which means\n that in order to reset a store, we need to initialize it at the component level using a\n `Context`.\n- **Server caching friendly:** Recent versions of Next.js (specifically applications using the App\n Router architecture) support aggressive server caching. Due to our store being a **module state**,\n it is completely compatible with this caching.\n\nWe have these general recommendations for the appropriate use of Zustand:\n\n- **No global stores** - Because the store should not be shared across requests, it should not be defined\n as a global variable. Instead, the store should be created per request.\n- **React Server Components should not read from or write to the store** - RSCs cannot use hooks or context. They aren't\n meant to be stateful. Having an RSC read from or write values to a global store violates the\n architecture of Next.js.\n\n","path":"docs/learn/guides/nextjs.md","title":"nextjs.md","source_type":"doc","kind":"doc"} -{"id":"47","text":"### Creating a store per request\n\nLet's write our store factory function that will create a new store for each\nrequest.\n\n```json\n// tsconfig.json\n{\n \"compilerOptions\": {\n \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n \"allowJs\": true,\n \"skipLibCheck\": true,\n \"strict\": true,\n \"noEmit\": true,\n \"esModuleInterop\": true,\n \"module\": \"esnext\",\n \"moduleResolution\": \"bundler\",\n \"resolveJsonModule\": true,\n \"isolatedModules\": true,\n \"jsx\": \"preserve\",\n \"incremental\": true,\n \"plugins\": [\n {\n \"name\": \"next\"\n }\n ],\n \"paths\": {\n \"@/*\": [\"./src/*\"]\n }\n },\n \"include\": [\"next-env.d.ts\", \"**/*.ts\", \"**/*.tsx\", \".next/types/**/*.ts\"],\n \"exclude\": [\"node_modules\"]\n}\n```\n\n> **Note:** do not forget to remove all comments from your `tsconfig.json` file.\n\n### Initializing the store\n\n```ts\n// src/stores/counter-store.ts\nimport { createStore } from 'zustand/vanilla'\n\nexport type CounterState = {\n count: number\n}\n\nexport type CounterActions = {\n decrementCount: () => void\n incrementCount: () => void\n}\n\nexport type CounterStore = CounterState & CounterActions\n\nexport const defaultInitState: CounterState = {\n count: 0,\n}\n\nexport const createCounterStore = (\n initState: CounterState = defaultInitState,\n) => {\n return createStore()((set) => ({\n ...initState,\n decrementCount: () => set((state) => ({ count: state.count - 1 })),\n incrementCount: () => set((state) => ({ count: state.count + 1 })),\n }))\n}\n```\n\n### Providing the store\n\nLet's use the `createCounterStore` in our component and share it using a context provider.\n\n```tsx\n// src/providers/counter-store-provider.tsx\n'use client'\n\nimport { type ReactNode, createContext, useState, useContext } from 'react'\nimport { useStore } from 'zustand'\n\nimport { type CounterStore, createCounterStore } from '@/stores/counter-store'\n\nexport type CounterStoreApi = ReturnType\n\nexport const CounterStoreContext = createContext(\n undefined,\n)\n\n","path":"docs/learn/guides/nextjs.md","title":"nextjs.md","source_type":"doc","kind":"doc"} -{"id":"48","text":"export interface CounterStoreProviderProps {\n children: ReactNode\n}\n\nexport const CounterStoreProvider = ({\n children,\n}: CounterStoreProviderProps) => {\n const [store] = useState(() => createCounterStore())\n return (\n \n {children}\n \n )\n}\n\nexport const useCounterStore = (\n selector: (store: CounterStore) => T,\n): T => {\n const counterStoreContext = useContext(CounterStoreContext)\n if (!counterStoreContext) {\n throw new Error(`useCounterStore must be used within CounterStoreProvider`)\n }\n\n return useStore(counterStoreContext, selector)\n}\n```\n\n> **Note:** In this example, we ensure that this component is re-render-safe by checking the\n> value of the reference, so that the store is only created once. This component will only be\n> rendered once per request on the server, but might be re-rendered multiple times on the client if\n> there are stateful client components located above this component in the tree, or if this component\n> also contains other mutable state that causes a re-render.\n\n### Using the store with different architectures\n\nThere are two architectures for a Next.js application: the\n[Pages Router](https://nextjs.org/docs/pages/building-your-application/routing) and the\n[App Router](https://nextjs.org/docs/app/building-your-application/routing). The usage of Zustand on\nboth architectures should be the same with slight differences related to each architecture.\n\n#### Pages Router\n\n```tsx\n// src/components/pages/home-page.tsx\nimport { useCounterStore } from '@/providers/counter-store-provider'\n\n","path":"docs/learn/guides/nextjs.md","title":"nextjs.md","source_type":"doc","kind":"doc"} -{"id":"49","text":"export const HomePage = () => {\n const { count, incrementCount, decrementCount } = useCounterStore(\n (state) => state,\n )\n\n return (\n
\n Count: {count}\n
\n \n \n
\n )\n}\n```\n\n```tsx\n// src/_app.tsx\nimport type { AppProps } from 'next/app'\n\nimport { CounterStoreProvider } from '@/providers/counter-store-provider'\n\nexport default function App({ Component, pageProps }: AppProps) {\n return (\n \n \n \n )\n}\n```\n\n```tsx\n// src/pages/index.tsx\nimport { HomePage } from '@/components/pages/home-page'\n\nexport default function Home() {\n return \n}\n```\n\n> **Note:** creating a store per route would require creating and sharing the store\n> at page (route) component level. Try not to use this if you do not need to create\n> a store per route.\n\n```tsx\n// src/pages/index.tsx\nimport { CounterStoreProvider } from '@/providers/counter-store-provider'\nimport { HomePage } from '@/components/pages/home-page'\n\nexport default function Home() {\n return (\n \n \n \n )\n}\n```\n\n#### App Router\n\n```tsx\n// src/components/pages/home-page.tsx\n'use client'\n\nimport { useCounterStore } from '@/providers/counter-store-provider'\n\n","path":"docs/learn/guides/nextjs.md","title":"nextjs.md","source_type":"doc","kind":"doc"} -{"id":"50","text":"export const HomePage = () => {\n const { count, incrementCount, decrementCount } = useCounterStore(\n (state) => state,\n )\n\n return (\n
\n Count: {count}\n
\n \n \n
\n )\n}\n```\n\n```tsx\n// src/app/layout.tsx\nimport type { Metadata } from 'next'\nimport { Inter } from 'next/font/google'\nimport './globals.css'\n\nimport { CounterStoreProvider } from '@/providers/counter-store-provider'\n\nconst inter = Inter({ subsets: ['latin'] })\n\nexport const metadata: Metadata = {\n title: 'Create Next App',\n description: 'Generated by create next app',\n}\n\nexport default function RootLayout({\n children,\n}: Readonly<{\n children: React.ReactNode\n}>) {\n return (\n \n \n {children}\n \n \n )\n}\n```\n\n```tsx\n// src/app/page.tsx\nimport { HomePage } from '@/components/pages/home-page'\n\nexport default function Home() {\n return \n}\n```\n\n> **Note:** creating a store per route would require creating and sharing the store\n> at page (route) component level. Try not to use this if you do not need to create\n> a store per route.\n\n```tsx\n// src/app/page.tsx\nimport { CounterStoreProvider } from '@/providers/counter-store-provider'\nimport { HomePage } from '@/components/pages/home-page'\n\nexport default function Home() {\n return (\n \n \n \n )\n}\n```\n","path":"docs/learn/guides/nextjs.md","title":"nextjs.md","source_type":"doc","kind":"doc"} -{"id":"51","text":"---\ntitle: Practice with no store actions\nnav: 5\n---\n\nThe recommended usage is to colocate actions and states within the store (let your actions be located together with your state).\n\nFor example:\n\n```js\nexport const useBoundStore = create((set) => ({\n count: 0,\n text: 'hello',\n inc: () => set((state) => ({ count: state.count + 1 })),\n setText: (text) => set({ text }),\n}))\n```\n\nThis creates a self-contained store with data and actions together.\n\n---\n\nAn alternative approach is to define actions at module level, external to the store.\n\n```js\nexport const useBoundStore = create(() => ({\n count: 0,\n text: 'hello',\n}))\n\nexport const inc = () =>\n useBoundStore.setState((state) => ({ count: state.count + 1 }))\n\nexport const setText = (text) => useBoundStore.setState({ text })\n```\n\nThis has a few advantages:\n\n- It doesn't require a hook to call an action;\n- It facilitates code splitting.\n\nWhile this pattern doesn't offer any downsides, some may prefer colocating due to its encapsulated nature.\n","path":"docs/learn/guides/practice-with-no-store-actions.md","title":"practice-with-no-store-actions.md","source_type":"doc","kind":"doc"} -{"id":"52","text":"---\ntitle: Prevent rerenders with useShallow\nnav: 9\n---\n\nWhen you need to subscribe to a computed state from a store, the recommended way is to\nuse a selector.\n\nThe computed selector will cause a rerender if the output has changed according to [Object.is](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is?retiredLocale=it).\n\nIn this case you might want to use `useShallow` to avoid a rerender if the computed value is always shallow\nequal the previous one.\n\n## Example\n\nWe have a store that associates to each bear a meal and we want to render their names.\n\n```js\nimport { create } from 'zustand'\n\nconst useMeals = create(() => ({\n papaBear: 'large porridge-pot',\n mamaBear: 'middle-size porridge pot',\n littleBear: 'A little, small, wee pot',\n}))\n\nexport const BearNames = () => {\n const names = useMeals((state) => Object.keys(state))\n\n return
{names.join(', ')}
\n}\n```\n\nNow papa bear wants a pizza instead:\n\n```js\nuseMeals.setState({\n papaBear: 'a large pizza',\n})\n```\n\nThis change causes `BearNames` rerenders even though the actual output of `names` has not changed according to shallow equal.\n\nWe can fix that using `useShallow`!\n\n```js\nimport { create } from 'zustand'\nimport { useShallow } from 'zustand/react/shallow'\n\nconst useMeals = create(() => ({\n papaBear: 'large porridge-pot',\n mamaBear: 'middle-size porridge pot',\n littleBear: 'A little, small, wee pot',\n}))\n\nexport const BearNames = () => {\n const names = useMeals(useShallow((state) => Object.keys(state)))\n\n return
{names.join(', ')}
\n}\n```\n\nNow they can all order other meals without causing unnecessary rerenders of our `BearNames` component.\n","path":"docs/learn/guides/prevent-rerenders-with-use-shallow.md","title":"prevent-rerenders-with-use-shallow.md","source_type":"doc","kind":"doc"} -{"id":"53","text":"---\ntitle: Slices Pattern\nnav: 6\n---\n\n## Slicing the store into smaller stores\n\nYour store can become bigger and bigger and tougher to maintain as you add more features.\n\nYou can divide your main store into smaller individual stores to achieve modularity. This is simple to accomplish in Zustand!\n\nThe first individual store:\n\n```js\nexport const createFishSlice = (set) => ({\n fishes: 0,\n addFish: () => set((state) => ({ fishes: state.fishes + 1 })),\n})\n```\n\nAnother individual store:\n\n```js\nexport const createBearSlice = (set) => ({\n bears: 0,\n addBear: () => set((state) => ({ bears: state.bears + 1 })),\n eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),\n})\n```\n\nYou can now combine both the stores into **one bounded store**:\n\n```js\nimport { create } from 'zustand'\nimport { createBearSlice } from './bearSlice'\nimport { createFishSlice } from './fishSlice'\n\nexport const useBoundStore = create((...a) => ({\n ...createBearSlice(...a),\n ...createFishSlice(...a),\n}))\n```\n\n### Usage in a React component\n\n```jsx\nimport { useBoundStore } from './stores/useBoundStore'\n\nfunction App() {\n const bears = useBoundStore((state) => state.bears)\n const fishes = useBoundStore((state) => state.fishes)\n const addBear = useBoundStore((state) => state.addBear)\n return (\n
\n

Number of bears: {bears}

\n

Number of fishes: {fishes}

\n \n
\n )\n}\n\nexport default App\n```\n\n### Updating multiple stores\n\nYou can update multiple stores, at the same time, in a single function.\n\n```js\nexport const createBearFishSlice = (set, get) => ({\n addBearAndFish: () => {\n get().addBear()\n get().addFish()\n },\n})\n```\n\nCombining all the stores together is the same as before.\n\n```js\nimport { create } from 'zustand'\nimport { createBearSlice } from './bearSlice'\nimport { createFishSlice } from './fishSlice'\nimport { createBearFishSlice } from './createBearFishSlice'\n\n","path":"docs/learn/guides/slices-pattern.md","title":"slices-pattern.md","source_type":"doc","kind":"doc"} -{"id":"54","text":"export const useBoundStore = create((...a) => ({\n ...createBearSlice(...a),\n ...createFishSlice(...a),\n ...createBearFishSlice(...a),\n}))\n```\n\n## Adding middlewares\n\nAdding middlewares to a combined store is the same as with other normal stores.\n\nAdding [`persist` middleware](../../reference/integrations/persisting-store-data.md) to our `useBoundStore`:\n\n```js\nimport { create } from 'zustand'\nimport { createBearSlice } from './bearSlice'\nimport { createFishSlice } from './fishSlice'\nimport { persist } from 'zustand/middleware'\n\nexport const useBoundStore = create(\n persist(\n (...a) => ({\n ...createBearSlice(...a),\n ...createFishSlice(...a),\n }),\n { name: 'bound-store' },\n ),\n)\n```\n\nPlease keep in mind you should only apply middlewares in the combined store. Applying them inside individual slices can lead to unexpected issues.\n\n## Usage with TypeScript\n\nA detailed guide on how to use the slice pattern in Zustand with TypeScript can be found [here](./advanced-typescript.md#slices-pattern).\n","path":"docs/learn/guides/slices-pattern.md","title":"slices-pattern.md","source_type":"doc","kind":"doc"} -{"id":"55","text":"---\ntitle: SSR and Hydration\nnav: 16\n---\n\n## Server-side Rendering (SSR)\n\nServer-side Rendering (SSR) is a technique that helps us render our components into\nHTML strings on the server, send them directly to the browser, and finally \"hydrate\" the\nstatic markup into a fully interactive app on the client.\n\n### React\n\nLet's say we want to render a stateless app using React. In order to do that, we need\nto use `express`, `react` and `react-dom/server`. We don't need `react-dom/client`\nsince it's a stateless app.\n\nLet's dive into that:\n\n- `express` helps us build a web app that we can run using Node,\n- `react` helps us build the UI components that we use in our app,\n- `react-dom/server` helps us render our components on a server.\n\n```json\n// tsconfig.json\n{\n \"compilerOptions\": {\n \"noImplicitAny\": false,\n \"noEmitOnError\": true,\n \"removeComments\": false,\n \"sourceMap\": true,\n \"target\": \"esnext\"\n },\n \"include\": [\"**/*\"]\n}\n```\n\n> **Note:** do not forget to remove all comments from your `tsconfig.json` file.\n\n```tsx\n// app.tsx\nexport const App = () => {\n return (\n \n \n \n \n Static Server-side-rendered App\n \n \n
Hello World!
\n \n \n )\n}\n```\n\n```tsx\n// server.tsx\nimport express from 'express'\nimport React from 'react'\nimport ReactDOMServer from 'react-dom/server'\n\nimport { App } from './app.tsx'\n\nconst port = Number.parseInt(process.env.PORT || '3000', 10)\nconst app = express()\n\napp.get('/', (_, res) => {\n const { pipe } = ReactDOMServer.renderToPipeableStream(, {\n onShellReady() {\n res.setHeader('content-type', 'text/html')\n pipe(res)\n },\n })\n})\n\napp.listen(port, () => {\n console.log(`Server is listening at ${port}`)\n})\n```\n\n```sh\ntsc --build\n```\n\n```sh\nnode server.js\n```\n\n","path":"docs/learn/guides/ssr-and-hydration.md","title":"ssr-and-hydration.md","source_type":"doc","kind":"doc"} -{"id":"56","text":"## Hydration\n\nHydration turns the initial HTML snapshot from the server into a fully interactive app\nthat runs in the browser. The right way to \"hydrate\" a component is by using `hydrateRoot`.\n\n### React\n\nLet's say we want to render a stateful app using React. In order to do that we need to\nuse `express`, `react`, `react-dom/server` and `react-dom/client`.\n\nLet's dive into that:\n\n- `express` helps us build a web app that we can run using Node,\n- `react` helps us build the UI components that we use in our app,\n- `react-dom/server` helps us render our components on a server,\n- `react-dom/client` helps us hydrate our components on a client.\n\n> **Note:** Do not forget that even if we can render our components on a server, it is\n> important to \"hydrate\" them on a client to make them interactive.\n\n```json\n// tsconfig.json\n{\n \"compilerOptions\": {\n \"noImplicitAny\": false,\n \"noEmitOnError\": true,\n \"removeComments\": false,\n \"sourceMap\": true,\n \"target\": \"esnext\"\n },\n \"include\": [\"**/*\"]\n}\n```\n\n> **Note:** do not forget to remove all comments in your `tsconfig.json` file.\n\n```tsx\n","path":"docs/learn/guides/ssr-and-hydration.md","title":"ssr-and-hydration.md","source_type":"doc","kind":"doc"} -{"id":"57","text":"// app.tsx\nexport const App = () => {\n return (\n \n \n \n \n Static Server-side-rendered App\n \n \n
Hello World!
\n \n \n )\n}\n```\n\n```tsx\n// main.tsx\nimport ReactDOMClient from 'react-dom/client'\n\nimport { App } from './app.tsx'\n\nReactDOMClient.hydrateRoot(document, )\n```\n\n```tsx\n// server.tsx\nimport express from 'express'\nimport React from 'react'\nimport ReactDOMServer from 'react-dom/server'\n\nimport { App } from './app.tsx'\n\nconst port = Number.parseInt(process.env.PORT || '3000', 10)\nconst app = express()\n\napp.use('/', (_, res) => {\n const { pipe } = ReactDOMServer.renderToPipeableStream(, {\n bootstrapScripts: ['/main.js'],\n onShellReady() {\n res.setHeader('content-type', 'text/html')\n pipe(res)\n },\n })\n})\n\napp.listen(port, () => {\n console.log(`Server is listening at ${port}`)\n})\n```\n\n```sh\ntsc --build\n```\n\n```sh\nnode server.js\n```\n\n> **Warning:** The React tree you pass to `hydrateRoot` needs to produce the same output as it did on the server.\n> The most common causes leading to hydration errors include:\n>\n> - Extra whitespace (like newlines) around the React-generated HTML inside the root node.\n> - Using checks like typeof window !== 'undefined' in your rendering logic.\n> - Using browser-only APIs like `window.matchMedia` in your rendering logic.\n> - Rendering different data on the server and the client.\n>\n> React recovers from some hydration errors, but you must fix them like other bugs. In the best case, they’ll lead to a slowdown; in the worst case, event handlers can get attached to the wrong elements.\n\nYou can read more about the caveats and pitfalls here: [hydrateRoot](https://react.dev/reference/react-dom/client/hydrateRoot)\n","path":"docs/learn/guides/ssr-and-hydration.md","title":"ssr-and-hydration.md","source_type":"doc","kind":"doc"} -{"id":"58","text":"---\ntitle: Testing\ndescription: Writing Tests\nnav: 18\n---\n\n## Setting Up a Test Environment\n\n### Test Runners\n\nUsually, your test runner needs to be configured to run JavaScript/TypeScript syntax. If you're\ngoing to be testing UI components, you will likely need to configure the test runner to use JSDOM\nto provide a mock DOM environment.\n\nSee these resources for test runner configuration instructions:\n\n- **Jest**\n - [Jest: Getting Started](https://jestjs.io/docs/getting-started)\n - [Jest: Configuration - Test Environment](https://jestjs.io/docs/configuration#testenvironment-string)\n- **Vitest**\n - [Vitest: Getting Started](https://vitest.dev/guide)\n - [Vitest: Configuration - Test Environment](https://vitest.dev/config/#environment)\n\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"59","text":"### UI and Network Testing Tools\n\n**We recommend using [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro)\nto test out React components that connect to Zustand**. RTL is a simple and complete React DOM\ntesting utility that encourages good testing practices. It uses ReactDOM's `render` function and\n`act` from `react-dom/test-utils`. Furthermore, [Native Testing Library (RNTL)](https://testing-library.com/docs/react-native-testing-library/intro)\nis the alternative to RTL to test out React Native components. The [Testing Library](https://testing-library.com/)\nfamily of tools also includes adapters for many other popular frameworks.\n\nWe also recommend using [Mock Service Worker (MSW)](https://mswjs.io/) to mock network requests, as\nthis means your application logic does not need to be changed or mocked when writing tests.\n\n- **React Testing Library (DOM)**\n - [DOM Testing Library: Setup](https://testing-library.com/docs/dom-testing-library/setup)\n - [React Testing Library: Setup](https://testing-library.com/docs/react-testing-library/setup)\n - [Testing Library Jest-DOM Matchers](https://testing-library.com/docs/ecosystem-jest-dom)\n- **Native Testing Library (React Native)**\n - [Native Testing Library: Setup](https://testing-library.com/docs/react-native-testing-library/setup)\n- **User Event Testing Library (DOM)**\n - [User Event Testing Library: Setup](https://testing-library.com/docs/user-event/setup)\n- **TypeScript for Jest**\n - [TypeScript for Jest: Setup](https://kulshekhar.github.io/ts-jest/docs/getting-started/installation)\n- **TypeScript for Node**\n - [TypeScript for Node: Setup](https://typestrong.org/ts-node/docs/installation)\n- **Mock Service Worker**\n - [MSW: Installation](https://mswjs.io/docs/getting-started/install)\n - [MSW: Setting up mock requests](https://mswjs.io/docs/getting-started/mocks/rest-api)\n - [MSW: Mock server configuration for Node](https://mswjs.io/docs/getting-started/integrate/node)\n\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"60","text":"## Setting Up Zustand for testing\n\n> **Note**: Since Jest and Vitest have slight differences, like Vitest using **ES modules** and Jest using\n> **CommonJS modules**, you need to keep that in mind if you are using Vitest instead of Jest.\n\nThe mock provided below will enable the relevant test runner to reset the zustand stores after each test.\n\n### Shared code just for testing purposes\n\nThis shared code was added to avoid code duplication in our demo since we use the same counter store\ncreator for both implementations, with and without `Context` API — `createStore` and `create`, respectively.\n\n```ts\n// shared/counter-store-creator.ts\nimport { type StateCreator } from 'zustand'\n\nexport type CounterStore = {\n count: number\n inc: () => void\n}\n\nexport const counterStoreCreator: StateCreator = (set) => ({\n count: 1,\n inc: () => set((state) => ({ count: state.count + 1 })),\n})\n```\n\n### Jest\n\nIn the next steps we are going to setup our Jest environment in order to mock Zustand.\n\n```ts\n// __mocks__/zustand.ts\nimport { act } from '@testing-library/react'\nimport type * as ZustandExportedTypes from 'zustand'\nexport * from 'zustand'\n\nconst { create: actualCreate, createStore: actualCreateStore } =\n jest.requireActual('zustand')\n\n// a variable to hold reset functions for all stores declared in the app\nexport const storeResetFns = new Set<() => void>()\n\nconst createUncurried = (\n stateCreator: ZustandExportedTypes.StateCreator,\n) => {\n const store = actualCreate(stateCreator)\n const initialState = store.getInitialState()\n storeResetFns.add(() => {\n store.setState(initialState, true)\n })\n return store\n}\n\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"61","text":"// when creating a store, we get its initial state, create a reset function and add it in the set\nexport const create = ((\n stateCreator: ZustandExportedTypes.StateCreator,\n) => {\n console.log('zustand create mock')\n\n // to support curried version of create\n return typeof stateCreator === 'function'\n ? createUncurried(stateCreator)\n : createUncurried\n}) as typeof ZustandExportedTypes.create\n\nconst createStoreUncurried = (\n stateCreator: ZustandExportedTypes.StateCreator,\n) => {\n const store = actualCreateStore(stateCreator)\n const initialState = store.getInitialState()\n storeResetFns.add(() => {\n store.setState(initialState, true)\n })\n return store\n}\n\n// when creating a store, we get its initial state, create a reset function and add it in the set\nexport const createStore = ((\n stateCreator: ZustandExportedTypes.StateCreator,\n) => {\n console.log('zustand createStore mock')\n\n // to support curried version of createStore\n return typeof stateCreator === 'function'\n ? createStoreUncurried(stateCreator)\n : createStoreUncurried\n}) as typeof ZustandExportedTypes.createStore\n\n// reset all stores after each test run\nafterEach(() => {\n act(() => {\n storeResetFns.forEach((resetFn) => {\n resetFn()\n })\n })\n})\n```\n\n```ts\n// setup-jest.ts\nimport '@testing-library/jest-dom'\n```\n\n```ts\n// jest.config.ts\nimport type { JestConfigWithTsJest } from 'ts-jest'\n\nconst config: JestConfigWithTsJest = {\n preset: 'ts-jest',\n testEnvironment: 'jsdom',\n setupFilesAfterEnv: ['./setup-jest.ts'],\n}\n\nexport default config\n```\n\n> **Note**: to use TypeScript we need to install two packages `ts-jest` and `ts-node`.\n\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"62","text":"### Vitest\n\nIn the next steps we are going to setup our Vitest environment in order to mock Zustand.\n\n> **Warning:** In Vitest you can change the [root](https://vitest.dev/config/#root).\n> Due to that, you need make sure that you are creating your `__mocks__` directory in the right place.\n> Let's say that you change the **root** to `./src`, that means you need to create a `__mocks__`\n> directory under `./src`. The end result would be `./src/__mocks__`, rather than `./__mocks__`.\n> Creating `__mocks__` directory in the wrong place can lead to issues when using Vitest.\n\n```ts\n// __mocks__/zustand.ts\nimport { act } from '@testing-library/react'\nimport type * as ZustandExportedTypes from 'zustand'\nexport * from 'zustand'\n\nconst { create: actualCreate, createStore: actualCreateStore } =\n await vi.importActual('zustand')\n\n// a variable to hold reset functions for all stores declared in the app\nexport const storeResetFns = new Set<() => void>()\n\nconst createUncurried = (\n stateCreator: ZustandExportedTypes.StateCreator,\n) => {\n const store = actualCreate(stateCreator)\n const initialState = store.getInitialState()\n storeResetFns.add(() => {\n store.setState(initialState, true)\n })\n return store\n}\n\n// when creating a store, we get its initial state, create a reset function and add it in the set\nexport const create = ((\n stateCreator: ZustandExportedTypes.StateCreator,\n) => {\n console.log('zustand create mock')\n\n // to support curried version of create\n return typeof stateCreator === 'function'\n ? createUncurried(stateCreator)\n : createUncurried\n}) as typeof ZustandExportedTypes.create\n\nconst createStoreUncurried = (\n stateCreator: ZustandExportedTypes.StateCreator,\n) => {\n const store = actualCreateStore(stateCreator)\n const initialState = store.getInitialState()\n storeResetFns.add(() => {\n store.setState(initialState, true)\n })\n return store\n}\n\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"63","text":"// when creating a store, we get its initial state, create a reset function and add it in the set\nexport const createStore = ((\n stateCreator: ZustandExportedTypes.StateCreator,\n) => {\n console.log('zustand createStore mock')\n\n // to support curried version of createStore\n return typeof stateCreator === 'function'\n ? createStoreUncurried(stateCreator)\n : createStoreUncurried\n}) as typeof ZustandExportedTypes.createStore\n\n// reset all stores after each test run\nafterEach(() => {\n act(() => {\n storeResetFns.forEach((resetFn) => {\n resetFn()\n })\n })\n})\n```\n\n> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need\n> to add `import { afterEach, vi } from 'vitest'` at the top.\n\n```ts\n// global.d.ts\n/// \n/// \n```\n\n> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we do\n> need to remove `/// `.\n\n```ts\n// setup-vitest.ts\nimport '@testing-library/jest-dom/vitest'\n\nvi.mock('zustand') // to make it work like Jest (auto-mocking)\n```\n\n> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need\n> to add `import { vi } from 'vitest'` at the top.\n\n```ts\n// vitest.config.ts\nimport { defineConfig, mergeConfig } from 'vitest/config'\nimport viteConfig from './vite.config'\n\nexport default defineConfig((configEnv) =>\n mergeConfig(\n viteConfig(configEnv),\n defineConfig({\n test: {\n globals: true,\n environment: 'jsdom',\n setupFiles: ['./setup-vitest.ts'],\n },\n }),\n ),\n)\n```\n\n### Testing Components\n\nIn the next examples we are going to use `useCounterStore`\n\n> **Note**: all of these examples are written using TypeScript.\n\n```ts\n// shared/counter-store-creator.ts\nimport { type StateCreator } from 'zustand'\n\nexport type CounterStore = {\n count: number\n inc: () => void\n}\n\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"64","text":"export const counterStoreCreator: StateCreator = (set) => ({\n count: 1,\n inc: () => set((state) => ({ count: state.count + 1 })),\n})\n```\n\n```ts\n// stores/use-counter-store.ts\nimport { create } from 'zustand'\n\nimport {\n type CounterStore,\n counterStoreCreator,\n} from '../shared/counter-store-creator'\n\nexport const useCounterStore = create()(counterStoreCreator)\n```\n\n```tsx\n// contexts/use-counter-store-context.tsx\nimport { type ReactNode, createContext, useContext, useState } from 'react'\nimport { createStore } from 'zustand'\nimport { useStoreWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/shallow'\n\nimport {\n type CounterStore,\n counterStoreCreator,\n} from '../shared/counter-store-creator'\n\nexport const createCounterStore = () => {\n return createStore(counterStoreCreator)\n}\n\nexport type CounterStoreApi = ReturnType\n\nexport const CounterStoreContext = createContext(\n undefined,\n)\n\nexport interface CounterStoreProviderProps {\n children: ReactNode\n}\n\nexport const CounterStoreProvider = ({\n children,\n}: CounterStoreProviderProps) => {\n const [store] = useState(() => createCounterStore())\n return (\n \n {children}\n \n )\n}\n\nexport type UseCounterStoreContextSelector = (store: CounterStore) => T\n\nexport const useCounterStoreContext = (\n selector: UseCounterStoreContextSelector,\n): T => {\n const counterStoreContext = useContext(CounterStoreContext)\n\n if (counterStoreContext === undefined) {\n throw new Error(\n 'useCounterStoreContext must be used within CounterStoreProvider',\n )\n }\n\n return useStoreWithEqualityFn(counterStoreContext, selector, shallow)\n}\n```\n\n```tsx\n// components/counter/counter.tsx\nimport { useCounterStore } from '../../stores/use-counter-store'\n\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"65","text":"export function Counter() {\n const { count, inc } = useCounterStore()\n\n return (\n
\n

Counter Store

\n

{count}

\n \n
\n )\n}\n```\n\n```ts\n// components/counter/index.ts\nexport * from './counter'\n```\n\n```tsx\n// components/counter/counter.test.tsx\nimport { act, render, screen } from '@testing-library/react'\nimport userEvent from '@testing-library/user-event'\n\nimport { Counter } from './counter'\n\ndescribe('Counter', () => {\n test('should render with initial state of 1', async () => {\n renderCounter()\n\n expect(await screen.findByText(/^1$/)).toBeInTheDocument()\n expect(\n await screen.findByRole('button', { name: /one up/i }),\n ).toBeInTheDocument()\n })\n\n test('should increase count by clicking a button', async () => {\n const user = userEvent.setup()\n\n renderCounter()\n\n expect(await screen.findByText(/^1$/)).toBeInTheDocument()\n\n await user.click(await screen.findByRole('button', { name: /one up/i }))\n\n expect(await screen.findByText(/^2$/)).toBeInTheDocument()\n })\n})\n\nconst renderCounter = () => {\n return render()\n}\n```\n\n```tsx\n// components/counter-with-context/counter-with-context.tsx\nimport {\n CounterStoreProvider,\n useCounterStoreContext,\n} from '../../contexts/use-counter-store-context'\n\nconst Counter = () => {\n const { count, inc } = useCounterStoreContext((state) => state)\n\n return (\n
\n

Counter Store Context

\n

{count}

\n \n
\n )\n}\n\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"66","text":"export const CounterWithContext = () => {\n return (\n \n \n \n )\n}\n```\n\n```tsx\n// components/counter-with-context/index.ts\nexport * from './counter-with-context'\n```\n\n```tsx\n// components/counter-with-context/counter-with-context.test.tsx\nimport { act, render, screen } from '@testing-library/react'\nimport userEvent from '@testing-library/user-event'\n\nimport { CounterWithContext } from './counter-with-context'\n\ndescribe('CounterWithContext', () => {\n test('should render with initial state of 1', async () => {\n renderCounterWithContext()\n\n expect(await screen.findByText(/^1$/)).toBeInTheDocument()\n expect(\n await screen.findByRole('button', { name: /one up/i }),\n ).toBeInTheDocument()\n })\n\n test('should increase count by clicking a button', async () => {\n const user = userEvent.setup()\n\n renderCounterWithContext()\n\n expect(await screen.findByText(/^1$/)).toBeInTheDocument()\n\n await user.click(await screen.findByRole('button', { name: /one up/i }))\n\n expect(await screen.findByText(/^2$/)).toBeInTheDocument()\n })\n})\n\nconst renderCounterWithContext = () => {\n return render()\n}\n```\n\n> **Note**: without [globals configuration](https://vitest.dev/config/#globals) enabled, we need\n> to add `import { describe, test, expect } from 'vitest'` at the top of each test file.\n\n### Testing Stores\n\nIn the next examples we are going to use `useCounterStore`\n\n> **Note**: all of these examples are written using TypeScript.\n\n```ts\n// shared/counter-store-creator.ts\nimport { type StateCreator } from 'zustand'\n\nexport type CounterStore = {\n count: number\n inc: () => void\n}\n\nexport const counterStoreCreator: StateCreator = (set) => ({\n count: 1,\n inc: () => set((state) => ({ count: state.count + 1 })),\n})\n```\n\n```ts\n// stores/use-counter-store.ts\nimport { create } from 'zustand'\n\nimport {\n type CounterStore,\n counterStoreCreator,\n} from '../shared/counter-store-creator'\n\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"67","text":"export const useCounterStore = create()(counterStoreCreator)\n```\n\n```tsx\n// contexts/use-counter-store-context.tsx\nimport { type ReactNode, createContext, useContext, useState } from 'react'\nimport { createStore } from 'zustand'\nimport { useStoreWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/shallow'\n\nimport {\n type CounterStore,\n counterStoreCreator,\n} from '../shared/counter-store-creator'\n\nexport const createCounterStore = () => {\n return createStore(counterStoreCreator)\n}\n\nexport type CounterStoreApi = ReturnType\n\nexport const CounterStoreContext = createContext(\n undefined,\n)\n\nexport interface CounterStoreProviderProps {\n children: ReactNode\n}\n\nexport const CounterStoreProvider = ({\n children,\n}: CounterStoreProviderProps) => {\n const [store] = useState(() => createCounterStore())\n return (\n \n {children}\n \n )\n}\n\nexport type UseCounterStoreContextSelector = (store: CounterStore) => T\n\nexport const useCounterStoreContext = (\n selector: UseCounterStoreContextSelector,\n): T => {\n const counterStoreContext = useContext(CounterStoreContext)\n\n if (counterStoreContext === undefined) {\n throw new Error(\n 'useCounterStoreContext must be used within CounterStoreProvider',\n )\n }\n\n return useStoreWithEqualityFn(counterStoreContext, selector, shallow)\n}\n```\n\n```tsx\n// components/counter/counter.tsx\nimport { useCounterStore } from '../../stores/use-counter-store'\n\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"68","text":"export function Counter() {\n const { count, inc } = useCounterStore()\n\n return (\n
\n

Counter Store

\n

{count}

\n \n
\n )\n}\n```\n\n```ts\n// components/counter/index.ts\nexport * from './counter'\n```\n\n```tsx\n// components/counter/counter.test.tsx\nimport { act, render, screen } from '@testing-library/react'\nimport userEvent from '@testing-library/user-event'\n\nimport { Counter, useCounterStore } from '../../../stores/use-counter-store.ts'\n\ndescribe('Counter', () => {\n test('should render with initial state of 1', async () => {\n renderCounter()\n\n expect(useCounterStore.getState().count).toBe(1)\n })\n\n test('should increase count by clicking a button', async () => {\n const user = userEvent.setup()\n\n renderCounter()\n\n expect(useCounterStore.getState().count).toBe(1)\n\n await user.click(await screen.findByRole('button', { name: /one up/i }))\n\n expect(useCounterStore.getState().count).toBe(2)\n })\n})\n\nconst renderCounter = () => {\n return render()\n}\n```\n\n```tsx\n// components/counter-with-context/counter-with-context.tsx\nimport {\n CounterStoreProvider,\n useCounterStoreContext,\n} from '../../contexts/use-counter-store-context'\n\nconst Counter = () => {\n const { count, inc } = useCounterStoreContext((state) => state)\n\n return (\n
\n

Counter Store Context

\n

{count}

\n \n
\n )\n}\n\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"69","text":"export const CounterWithContext = () => {\n return (\n \n \n \n )\n}\n```\n\n```tsx\n// components/counter-with-context/index.ts\nexport * from './counter-with-context'\n```\n\n```tsx\n// components/counter-with-context/counter-with-context.test.tsx\nimport { act, render, screen } from '@testing-library/react'\nimport userEvent from '@testing-library/user-event'\n\nimport { CounterStoreContext } from '../../../contexts/use-counter-store-context'\nimport { counterStoreCreator } from '../../../shared/counter-store-creator'\n\ndescribe('CounterWithContext', () => {\n test('should render with initial state of 1', async () => {\n const counterStore = counterStoreCreator()\n\n renderCounterWithContext(counterStore)\n\n expect(counterStore.getState().count).toBe(1)\n expect(\n await screen.findByRole('button', { name: /one up/i }),\n ).toBeInTheDocument()\n })\n\n test('should increase count by clicking a button', async () => {\n const user = userEvent.setup()\n const counterStore = counterStoreCreator()\n\n renderCounterWithContext(counterStore)\n\n expect(counterStore.getState().count).toBe(1)\n\n await user.click(await screen.findByRole('button', { name: /one up/i }))\n\n expect(counterStore.getState().count).toBe(2)\n })\n})\n\nconst renderCounterWithContext = (store) => {\n return render(, {\n wrapper: ({ children }) => (\n \n {children}\n \n ),\n })\n}\n```\n\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"70","text":"## References\n\n- **React Testing Library**: [React Testing Library (RTL)](https://testing-library.com/docs/react-testing-library/intro)\n is a very lightweight solution for testing React components. It provides utility functions on top\n of `react-dom` and `react-dom/test-utils`, in a way that encourages better testing practices. Its\n primary guiding principle is: \"The more your tests resemble the way your software is used, the\n more confidence they can give you.\"\n- **Native Testing Library**: [Native Testing Library (RNTL)](https://testing-library.com/docs/react-native-testing-library/intro)\n is a very lightweight solution for testing React Native components, similarly to RTL, but its\n functions are built on top of `react-test-renderer`.\n- **Testing Implementation Details**: Blog post by Kent C. Dodds on why he recommends to avoid\n [testing implementation details](https://kentcdodds.com/blog/testing-implementation-details).\n\n## Demos\n\n- Jest: https://stackblitz.com/edit/jest-zustand\n- Vitest: https://stackblitz.com/edit/vitest-zustand\n","path":"docs/learn/guides/testing.md","title":"testing.md","source_type":"doc","kind":"doc"} -{"id":"71","text":"---\ntitle: 'Tutorial: Tic-Tac-Toe'\ndescription: Building a game\nnav: 3\n---\n\n# Tutorial: Tic-Tac-Toe\n\n## Building a game\n\nYou will build a small tic-tac-toe game during this tutorial. This tutorial does assume existing\nReact knowledge. The techniques you'll learn in the tutorial are fundamental to building any React\napp, and fully understanding it will give you a deep understanding of React and Zustand.\n\n> [!NOTE]\n> This tutorial is crafted for those who learn best through hands-on experience and want to swiftly\n> create something tangible. It draws inspiration from React's tic-tac-toe tutorial.\n\nThe tutorial is divided into several sections:\n\n- Setup for the tutorial will give you a starting point to follow the tutorial.\n- Overview will teach you the fundamentals of React: components, props, and state.\n- Completing the game will teach you the most common techniques in React development.\n- Adding time travel will give you a deeper insight into the unique strengths of React.\n\n### What are you building?\n\nIn this tutorial, you'll build an interactive tic-tac-toe game with React and Zustand.\n\nYou can see what it will look like when you're finished here:\n\n```jsx\nimport { create } from 'zustand'\nimport { combine } from 'zustand/middleware'\n\nconst useGameStore = create(\n combine(\n {\n history: [Array(9).fill(null)],\n currentMove: 0,\n },\n (set, get) => {\n return {\n setHistory: (nextHistory) => {\n set((state) => ({\n history:\n typeof nextHistory === 'function'\n ? nextHistory(state.history)\n : nextHistory,\n }))\n },\n setCurrentMove: (nextCurrentMove) => {\n set((state) => ({\n currentMove:\n typeof nextCurrentMove === 'function'\n ? nextCurrentMove(state.currentMove)\n : nextCurrentMove,\n }))\n },\n }\n },\n ),\n)\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"72","text":"function Square({ value, onSquareClick }) {\n return (\n \n {value}\n \n )\n}\n\nfunction Board({ xIsNext, squares, onPlay }) {\n const winner = calculateWinner(squares)\n const turns = calculateTurns(squares)\n const player = xIsNext ? 'X' : 'O'\n const status = calculateStatus(winner, turns, player)\n\n function handleClick(i) {\n if (squares[i] || winner) return\n const nextSquares = squares.slice()\n nextSquares[i] = player\n onPlay(nextSquares)\n }\n\n return (\n <>\n
{status}
\n \n {squares.map((_, i) => (\n handleClick(i)}\n />\n ))}\n
\n \n )\n}\n\nexport default function Game() {\n const history = useGameStore((state) => state.history)\n const setHistory = useGameStore((state) => state.setHistory)\n const currentMove = useGameStore((state) => state.currentMove)\n const setCurrentMove = useGameStore((state) => state.setCurrentMove)\n const xIsNext = currentMove % 2 === 0\n const currentSquares = history[currentMove]\n\n function handlePlay(nextSquares) {\n const nextHistory = [...history.slice(0, currentMove + 1), nextSquares]\n setHistory(nextHistory)\n setCurrentMove(nextHistory.length - 1)\n }\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"73","text":" function jumpTo(nextMove) {\n setCurrentMove(nextMove)\n }\n\n return (\n \n
\n \n
\n
\n
    \n {history.map((_, historyIndex) => {\n const description =\n historyIndex > 0\n ? `Go to move #${historyIndex}`\n : 'Go to game start'\n\n return (\n
  1. \n \n
  2. \n )\n })}\n
\n
\n \n )\n}\n\nfunction calculateWinner(squares) {\n const lines = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [0, 3, 6],\n [1, 4, 7],\n [2, 5, 8],\n [0, 4, 8],\n [2, 4, 6],\n ]\n\n for (let i = 0; i < lines.length; i++) {\n const [a, b, c] = lines[i]\n if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {\n return squares[a]\n }\n }\n\n return null\n}\n\nfunction calculateTurns(squares) {\n return squares.filter((square) => !square).length\n}\n\nfunction calculateStatus(winner, turns, player) {\n if (!winner && !turns) return 'Draw'\n if (winner) return `Winner ${winner}`\n return `Next player: ${player}`\n}\n```\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"74","text":"### Building the board\n\nLet's start by creating the `Square` component, which will be a building block for our `Board`\ncomponent. This component will represent each square in our game.\n\nThe `Square` component should take `value` and `onSquareClick` as props. It should return a\n`\n )\n}\n```\n\nLet's move on to creating the Board component, which will consist of 9 squares arranged in a grid.\nThis component will serve as the main playing area for our game.\n\nThe `Board` component should return a `
` element styled as a grid. The grid layout is achieved\nusing CSS Grid, with three columns and three rows, each taking up an equal fraction of the available\nspace. The overall size of the grid is determined by the width and height properties, ensuring that\nit is square-shaped and appropriately sized.\n\nInside the grid, we place nine Square components, each with a value prop representing its position.\nThese Square components will eventually hold the game symbols (`'X'` or `'O'`) and handle user\ninteractions.\n\nHere's the code for the `Board` component:\n\n```jsx\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"75","text":"export default function Board() {\n return (\n \n \n \n \n \n \n \n \n \n \n
\n )\n}\n```\n\nThis Board component sets up the basic structure for our game board by arranging nine squares in a\n3x3 grid. It positions the squares neatly, providing a foundation for adding more features and\nhandling player interactions in the future.\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"76","text":"### Lifting state up\n\nEach `Square` component could maintain a part of the game's state. To check for a winner in a\ntic-tac-toe game, the `Board` component would need to somehow know the state of each of the 9\n`Square` components.\n\nHow would you approach that? At first, you might guess that the `Board` component needs to ask each\n`Square` component for that `Square`'s component state. Although this approach is technically\npossible in React, we discourage it because the code becomes difficult to understand, susceptible\nto bugs, and hard to refactor. Instead, the best approach is to store the game's state in the\nparent `Board` component instead of in each `Square` component. The `Board` component can tell each\n`Square` component what to display by passing a prop, like you did when you passed a number to each\n`Square` component.\n\n> [!IMPORTANT]\n> To collect data from multiple children, or to have two or more child components\n> communicate with each other, declare the shared state in their parent component instead. The\n> parent component can pass that state back down to the children via props. This keeps the child\n> components in sync with each other and with their parent.\n\nLet's take this opportunity to try it out. Edit the `Board` component so that it declares a state\nvariable named squares that defaults to an array of 9 nulls corresponding to the 9 squares:\n\n```jsx\nimport { create } from 'zustand'\nimport { combine } from 'zustand/middleware'\n\nconst useGameStore = create(\n combine({ squares: Array(9).fill(null) }, (set) => {\n return {\n setSquares: (nextSquares) => {\n set((state) => ({\n squares:\n typeof nextSquares === 'function'\n ? nextSquares(state.squares)\n : nextSquares,\n }))\n },\n }\n }),\n)\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"77","text":"export default function Board() {\n const squares = useGameStore((state) => state.squares)\n const setSquares = useGameStore((state) => state.setSquares)\n\n return (\n \n {squares.map((square, squareIndex) => (\n \n ))}\n \n )\n}\n```\n\n`Array(9).fill(null)` creates an array with nine elements and sets each of them to `null`. The\n`useGameStore` declares a `squares` state that's initially set to that array. Each entry in the\narray corresponds to the value of a square. When you fill the board in later, the squares array\nwill look like this:\n\n```js\nconst squares = ['O', null, 'X', 'X', 'X', 'O', 'O', null, null]\n```\n\nEach Square will now receive a `value` prop that will either be `'X'`, `'O'`, or `null` for empty\nsquares.\n\nNext, you need to change what happens when a `Square` component is clicked. The `Board` component\nnow maintains which squares are filled. You'll need to create a way for the `Square` component to\nupdate the `Board`'s component state. Since state is private to a component that defines it, you\ncannot update the `Board`'s component state directly from `Square` component.\n\nInstead, you'll pass down a function from the Board component to the `Square` component, and you'll\nhave `Square` component call that function when a square is clicked. You'll start with the function\nthat the `Square` component will call when it is clicked. You'll call that function `onSquareClick`:\n\nNow you'll connect the `onSquareClick` prop to a function in the `Board` component that you'll name\n`handleClick`. To connect `onSquareClick` to `handleClick` you'll pass an inline function to the\n`onSquareClick` prop of the first Square component:\n\n```jsx\n handleClick(i)} />\n```\n\nLastly, you will define the `handleClick` function inside the `Board` component to update the\nsquares array holding your board's state.\n\nThe `handleClick` function should take the index of the square to update and create a copy of the\n`squares` array (`nextSquares`). Then, `handleClick` updates the `nextSquares` array by adding `X`\nto the square at the specified index (`i`) if is not already filled.\n\n```jsx {5-10,27}\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"78","text":"export default function Board() {\n const squares = useGameStore((state) => state.squares)\n const setSquares = useGameStore((state) => state.setSquares)\n\n function handleClick(i) {\n if (squares[i]) return\n const nextSquares = squares.slice()\n nextSquares[i] = 'X'\n setSquares(nextSquares)\n }\n\n return (\n \n {squares.map((square, squareIndex) => (\n handleClick(squareIndex)}\n />\n ))}\n \n )\n}\n```\n\n> [!IMPORTANT]\n> Note how in `handleClick` function, you call `.slice()` to create a copy of the squares array\n> instead of modifying the existing array.\n\n### Taking turns\n\nIt's now time to fix a major defect in this tic-tac-toe game: the `'O'`s cannot be used on the\nboard.\n\nYou'll set the first move to be `'X'` by default. Let's keep track of this by adding another piece\nof state to the `useGameStore` hook:\n\n```jsx {2,12-18}\nconst useGameStore = create(\n combine({ squares: Array(9).fill(null), xIsNext: true }, (set) => {\n return {\n setSquares: (nextSquares) => {\n set((state) => ({\n squares:\n typeof nextSquares === 'function'\n ? nextSquares(state.squares)\n : nextSquares,\n }))\n },\n setXIsNext: (nextXIsNext) => {\n set((state) => ({\n xIsNext:\n typeof nextXIsNext === 'function'\n ? nextXIsNext(state.xIsNext)\n : nextXIsNext,\n }))\n },\n }\n }),\n)\n```\n\nEach time a player moves, `xIsNext` (a boolean) will be flipped to determine which player goes next\nand the game's state will be saved. You'll update the Board's `handleClick` function to flip the\nvalue of `xIsNext`:\n\n```jsx {2-3,6,11,13}\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"79","text":"export default function Board() {\n const xIsNext = useGameStore((state) => state.xIsNext)\n const setXIsNext = useGameStore((state) => state.setXIsNext)\n const squares = useGameStore((state) => state.squares)\n const setSquares = useGameStore((state) => state.setSquares)\n const player = xIsNext ? 'X' : 'O'\n\n function handleClick(i) {\n if (squares[i]) return\n const nextSquares = squares.slice()\n nextSquares[i] = player\n setSquares(nextSquares)\n setXIsNext(!xIsNext)\n }\n\n return (\n \n {squares.map((square, squareIndex) => (\n handleClick(squareIndex)}\n />\n ))}\n \n )\n}\n```\n\n### Declaring a winner or draw\n\nNow that the players can take turns, you'll want to show when the game is won or drawn and there\nare no more turns to make. To do this you'll add three helper functions. The first helper function\ncalled `calculateWinner` that takes an array of 9 squares, checks for a winner and returns `'X'`,\n`'O'`, or `null` as appropriate. The second helper function called `calculateTurns` that takes the\nsame array, checks for remaining turns by filtering out only `null` items, and returns the count of\nthem. The last helper called `calculateStatus` that takes the remaining turns, the winner, and the\ncurrent player (`'X' or 'O'`):\n\n```js\nfunction calculateWinner(squares) {\n const lines = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [0, 3, 6],\n [1, 4, 7],\n [2, 5, 8],\n [0, 4, 8],\n [2, 4, 6],\n ]\n\n for (let i = 0; i < lines.length; i++) {\n const [a, b, c] = lines[i]\n if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {\n return squares[a]\n }\n }\n\n return null\n}\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"80","text":"function calculateTurns(squares) {\n return squares.filter((square) => !square).length\n}\n\nfunction calculateStatus(winner, turns, player) {\n if (!winner && !turns) return 'Draw'\n if (winner) return `Winner ${winner}`\n return `Next player: ${player}`\n}\n```\n\nYou will use the result of `calculateWinner(squares)` in the Board component's `handleClick`\nfunction to check if a player has won. You can perform this check at the same time you check if a\nuser has clicked a square that already has a `'X'` or and `'O'`. We'd like to return early in\nboth cases:\n\n```js {2}\nfunction handleClick(i) {\n if (squares[i] || winner) return\n const nextSquares = squares.slice()\n nextSquares[i] = player\n setSquares(nextSquares)\n setXIsNext(!xIsNext)\n}\n```\n\nTo let the players know when the game is over, you can display text such as `'Winner: X'` or\n`'Winner: O'`. To do that you'll add a `status` section to the `Board` component. The status will\ndisplay the winner or draw if the game is over and if the game is ongoing you'll display which\nplayer's turn is next:\n\n```jsx {6-7,9,20-21,40}\nexport default function Board() {\n const xIsNext = useGameStore((state) => state.xIsNext)\n const setXIsNext = useGameStore((state) => state.setXIsNext)\n const squares = useGameStore((state) => state.squares)\n const setSquares = useGameStore((state) => state.setSquares)\n const winner = calculateWinner(squares)\n const turns = calculateTurns(squares)\n const player = xIsNext ? 'X' : 'O'\n const status = calculateStatus(winner, turns, player)\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"81","text":" function handleClick(i) {\n if (squares[i] || winner) return\n const nextSquares = squares.slice()\n nextSquares[i] = player\n setSquares(nextSquares)\n setXIsNext(!xIsNext)\n }\n\n return (\n <>\n
{status}
\n \n {squares.map((square, squareIndex) => (\n handleClick(squareIndex)}\n />\n ))}\n \n \n )\n}\n```\n\nCongratulations! You now have a working tic-tac-toe game. And you've just learned the basics of\nReact and Zustand too. So you are the real winner here. Here is what the code should look like:\n\n```jsx\nimport { create } from 'zustand'\nimport { combine } from 'zustand/middleware'\n\nconst useGameStore = create(\n combine({ squares: Array(9).fill(null), xIsNext: true }, (set) => {\n return {\n setSquares: (nextSquares) => {\n set((state) => ({\n squares:\n typeof nextSquares === 'function'\n ? nextSquares(state.squares)\n : nextSquares,\n }))\n },\n setXIsNext: (nextXIsNext) => {\n set((state) => ({\n xIsNext:\n typeof nextXIsNext === 'function'\n ? nextXIsNext(state.xIsNext)\n : nextXIsNext,\n }))\n },\n }\n }),\n)\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"82","text":"function Square({ value, onSquareClick }) {\n return (\n \n {value}\n \n )\n}\n\nexport default function Board() {\n const xIsNext = useGameStore((state) => state.xIsNext)\n const setXIsNext = useGameStore((state) => state.setXIsNext)\n const squares = useGameStore((state) => state.squares)\n const setSquares = useGameStore((state) => state.setSquares)\n const winner = calculateWinner(squares)\n const turns = calculateTurns(squares)\n const player = xIsNext ? 'X' : 'O'\n const status = calculateStatus(winner, turns, player)\n\n function handleClick(i) {\n if (squares[i] || winner) return\n const nextSquares = squares.slice()\n nextSquares[i] = player\n setSquares(nextSquares)\n setXIsNext(!xIsNext)\n }\n\n return (\n <>\n
{status}
\n \n {squares.map((square, squareIndex) => (\n handleClick(squareIndex)}\n />\n ))}\n \n \n )\n}\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"83","text":"function calculateWinner(squares) {\n const lines = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [0, 3, 6],\n [1, 4, 7],\n [2, 5, 8],\n [0, 4, 8],\n [2, 4, 6],\n ]\n\n for (let i = 0; i < lines.length; i++) {\n const [a, b, c] = lines[i]\n if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {\n return squares[a]\n }\n }\n\n return null\n}\n\nfunction calculateTurns(squares) {\n return squares.filter((square) => !square).length\n}\n\nfunction calculateStatus(winner, turns, player) {\n if (!winner && !turns) return 'Draw'\n if (winner) return `Winner ${winner}`\n return `Next player: ${player}`\n}\n```\n\n### Adding time travel\n\nAs a final exercise, let's make it possible to “go back in time” and revisit previous moves in the\ngame.\n\nIf you had directly modified the squares array, implementing this time-travel feature would be very\ndifficult. However, since you used `slice()` to create a new copy of the squares array after every\nmove, treating it as immutable, you can store every past version of the squares array and navigate\nbetween them.\n\nYou'll keep track of these past squares arrays in a new state variable called `history`. This\n`history` array will store all board states, from the first move to the latest one, and will look\nsomething like this:\n\n```js\nconst history = [\n // First move\n [null, null, null, null, null, null, null, null, null],\n // Second move\n ['X', null, null, null, null, null, null, null, null],\n // Third move\n ['X', 'O', null, null, null, null, null, null, null],\n // and so on...\n]\n```\n\nThis approach allows you to easily navigate between different game states and implement the\ntime-travel feature.\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"84","text":"### Lifting state up, again\n\nNext, you will create a new top-level component called `Game` to display a list of past moves. This\nis where you will store the `history` state that contains the entire game history.\n\nBy placing the `history` state in the `Game` component, you can remove the `squares` state from the\n`Board` component. You will now lift the state up from the `Board` component to the top-level `Game`\ncomponent. This change allows the `Game` component to have full control over the `Board`'s\ncomponent data and instruct the `Board` component to render previous turns from the `history`.\n\nFirst, add a `Game` component with `export default` and remove it from `Board` component. Here is\nwhat the code should look like:\n\n```jsx {1,44-61}\nfunction Board() {\n const xIsNext = useGameStore((state) => state.xIsNext)\n const setXIsNext = useGameStore((state) => state.setXIsNext)\n const squares = useGameStore((state) => state.squares)\n const setSquares = useGameStore((state) => state.setSquares)\n const winner = calculateWinner(squares)\n const turns = calculateTurns(squares)\n const player = xIsNext ? 'X' : 'O'\n const status = calculateStatus(winner, turns, player)\n\n function handleClick(i) {\n if (squares[i] || winner) return\n const nextSquares = squares.slice()\n nextSquares[i] = player\n setSquares(nextSquares)\n setXIsNext(!xIsNext)\n }\n\n return (\n <>\n
{status}
\n \n {squares.map((square, squareIndex) => (\n handleClick(squareIndex)}\n />\n ))}\n \n \n )\n}\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"85","text":"export default function Game() {\n return (\n \n
\n \n
\n
\n
    {/* TODO */}
\n
\n \n )\n}\n```\n\nAdd some state to the `useGameStore` hook to track the history of moves:\n\n```js {2,4-11}\nconst useGameStore = create(\n combine({ history: [Array(9).fill(null)], xIsNext: true }, (set) => {\n return {\n setHistory: (nextHistory) => {\n set((state) => ({\n history:\n typeof nextHistory === 'function'\n ? nextHistory(state.history)\n : nextHistory,\n }))\n },\n setXIsNext: (nextXIsNext) => {\n set((state) => ({\n xIsNext:\n typeof nextXIsNext === 'function'\n ? nextXIsNext(state.xIsNext)\n : nextXIsNext,\n }))\n },\n }\n }),\n)\n```\n\nNotice how `[Array(9).fill(null)]` creates an array with a single item, which is itself an array of\n9 null values.\n\nTo render the squares for the current move, you'll need to read the most recent squares array from\nthe `history` state. You don't need an extra state for this because you already have enough\ninformation to calculate it during rendering:\n\n```jsx {2-6}\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"86","text":"export default function Game() {\n const history = useGameStore((state) => state.history)\n const setHistory = useGameStore((state) => state.setHistory)\n const xIsNext = useGameStore((state) => state.xIsNext)\n const setXIsNext = useGameStore((state) => state.setXIsNext)\n const currentSquares = history[history.length - 1]\n\n return (\n \n
\n \n
\n
\n
    {/*TODO*/}
\n
\n \n )\n}\n```\n\nNext, create a `handlePlay` function inside the `Game` component that will be called by the `Board`\ncomponent to update the game. Pass `xIsNext`, `currentSquares` and `handlePlay` as props to the\n`Board` component:\n\n```jsx {8-10,21}\nexport default function Game() {\n const history = useGameStore((state) => state.history)\n const setHistory = useGameStore((state) => state.setHistory)\n const xIsNext = useGameStore((state) => state.xIsNext)\n const setXIsNext = useGameStore((state) => state.setXIsNext)\n const currentSquares = history[history.length - 1]\n\n function handlePlay(nextSquares) {\n // TODO\n }\n\n return (\n \n
\n \n
\n
\n
    {/*TODO*/}
\n
\n \n )\n}\n```\n\nLet's make the `Board` component fully controlled by the props it receives. To do this, we'll modify\nthe `Board` component to accept three props: `xIsNext`, `squares`, and a new `onPlay` function that\nthe `Board` component can call with the updated squares array when a player makes a move.\n\n```jsx {1,11}\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"87","text":"function Board({ xIsNext, squares, onPlay }) {\n const winner = calculateWinner(squares)\n const turns = calculateTurns(squares)\n const player = xIsNext ? 'X' : 'O'\n const status = calculateStatus(winner, turns, player)\n\n function handleClick(i) {\n if (squares[i] || winner) return\n const nextSquares = squares.slice()\n nextSquares[i] = player\n onPlay(nextSquares)\n }\n\n return (\n <>\n
{status}
\n \n {squares.map((square, squareIndex) => (\n handleClick(squareIndex)}\n />\n ))}\n \n \n )\n}\n```\n\nThe `Board` component is now fully controlled by the props passed to it by the `Game` component. To\nget the game working again, you need to implement the `handlePlay` function in the `Game`\ncomponent.\n\nWhat should `handlePlay` do when called? Previously, the `Board` component called `setSquares` with\nan updated array; now it passes the updated squares array to `onPlay`.\n\nThe `handlePlay` function needs to update the `Game` component's state to trigger a re-render.\nInstead of using `setSquares`, you'll update the `history` state variable by appending the updated\nsquares array as a new `history` entry. You also need to toggle `xIsNext`, just as the `Board`\ncomponent used\nto do.\n\n```js {2-3}\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"88","text":"function handlePlay(nextSquares) {\n setHistory(history.concat([nextSquares]))\n setXIsNext(!xIsNext)\n}\n```\n\nAt this point, you've moved the state to live in the `Game` component, and the UI should be fully\nworking, just as it was before the refactor. Here is what the code should look like at this point:\n\n```jsx\nimport { create } from 'zustand'\nimport { combine } from 'zustand/middleware'\n\nconst useGameStore = create(\n combine({ history: [Array(9).fill(null)], xIsNext: true }, (set) => {\n return {\n setHistory: (nextHistory) => {\n set((state) => ({\n history:\n typeof nextHistory === 'function'\n ? nextHistory(state.history)\n : nextHistory,\n }))\n },\n setXIsNext: (nextXIsNext) => {\n set((state) => ({\n xIsNext:\n typeof nextXIsNext === 'function'\n ? nextXIsNext(state.xIsNext)\n : nextXIsNext,\n }))\n },\n }\n }),\n)\n\nfunction Square({ value, onSquareClick }) {\n return (\n \n {value}\n \n )\n}\n\nfunction Board({ xIsNext, squares, onPlay }) {\n const winner = calculateWinner(squares)\n const turns = calculateTurns(squares)\n const player = xIsNext ? 'X' : 'O'\n const status = calculateStatus(winner, turns, player)\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"89","text":" function handleClick(i) {\n if (squares[i] || winner) return\n const nextSquares = squares.slice()\n nextSquares[i] = player\n onPlay(nextSquares)\n }\n\n return (\n <>\n
{status}
\n \n {squares.map((square, squareIndex) => (\n handleClick(squareIndex)}\n />\n ))}\n \n \n )\n}\n\nexport default function Game() {\n const history = useGameStore((state) => state.history)\n const setHistory = useGameStore((state) => state.setHistory)\n const xIsNext = useGameStore((state) => state.xIsNext)\n const setXIsNext = useGameStore((state) => state.setXIsNext)\n const currentSquares = history[history.length - 1]\n\n function handlePlay(nextSquares) {\n setHistory(history.concat([nextSquares]))\n setXIsNext(!xIsNext)\n }\n\n return (\n \n
\n \n
\n
\n
    {/*TODO*/}
\n
\n \n )\n}\n\nfunction calculateWinner(squares) {\n const lines = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8],\n [0, 3, 6],\n [1, 4, 7],\n [2, 5, 8],\n [0, 4, 8],\n [2, 4, 6],\n ]\n\n for (let i = 0; i < lines.length; i++) {\n const [a, b, c] = lines[i]\n if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {\n return squares[a]\n }\n }\n\n return null\n}\n\nfunction calculateTurns(squares) {\n return squares.filter((square) => !square).length\n}\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"90","text":"function calculateStatus(winner, turns, player) {\n if (!winner && !turns) return 'Draw'\n if (winner) return `Winner ${winner}`\n return `Next player: ${player}`\n}\n```\n\n### Showing the past moves\n\nSince you are recording the tic-tac-toe game's history, you can now display a list of past moves to\nthe player.\n\nYou already have an array of `history` moves in store, so now you need to transform it to an array\nof React elements. In JavaScript, to transform one array into another, you can use the Array\n`.map()` method:\n\nYou'll use `map` to transform your `history` of moves into React elements representing buttons on the\nscreen, and display a list of buttons to **jump** to past moves. Let's `map` over the `history` in\nthe `Game` component:\n\n```jsx {13-15,29-44}\nexport default function Game() {\n const history = useGameStore((state) => state.history)\n const setHistory = useGameStore((state) => state.setHistory)\n const xIsNext = useGameStore((state) => state.xIsNext)\n const setXIsNext = useGameStore((state) => state.setXIsNext)\n const currentSquares = history[history.length - 1]\n\n function handlePlay(nextSquares) {\n setHistory(history.concat([nextSquares]))\n setXIsNext(!xIsNext)\n }\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"91","text":" function jumpTo(nextMove) {\n // TODO\n }\n\n return (\n \n
\n \n
\n
\n
    \n {history.map((_, historyIndex) => {\n const description =\n historyIndex > 0\n ? `Go to move #${historyIndex}`\n : 'Go to game start'\n\n return (\n
  1. \n \n
  2. \n )\n })}\n
\n
\n \n )\n}\n```\n\nBefore you can implement the `jumpTo` function, you need the `Game` component to keep track of which\nstep the user is currently viewing. To do this, define a new state variable called `currentMove`,\nwhich will start at `0`:\n\n```js {3,14-21}\nconst useGameStore = create(\n combine(\n { history: [Array(9).fill(null)], currentMove: 0, xIsNext: true },\n (set) => {\n return {\n setHistory: (nextHistory) => {\n set((state) => ({\n history:\n typeof nextHistory === 'function'\n ? nextHistory(state.history)\n : nextHistory,\n }))\n },\n setCurrentMove: (nextCurrentMove) => {\n set((state) => ({\n currentMove:\n typeof nextCurrentMove === 'function'\n ? nextCurrentMove(state.currentMove)\n : nextCurrentMove,\n }))\n },\n setXIsNext: (nextXIsNext) => {\n set((state) => ({\n xIsNext:\n typeof nextXIsNext === 'function'\n ? nextXIsNext(state.xIsNext)\n : nextXIsNext,\n }))\n },\n }\n },\n ),\n)\n```\n\nNext, update the `jumpTo` function inside `Game` component to update that `currentMove`. You’ll\nalso set `xIsNext` to `true` if the number that you’re changing `currentMove` to is even.\n\n```js {2-3}\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"92","text":"function jumpTo(nextMove) {\n setCurrentMove(nextMove)\n setXIsNext(currentMove % 2 === 0)\n}\n```\n\nYou will now make two changes to the `handlePlay` function in the `Game` component, which is called\nwhen you click on a square.\n\n- If you \"go back in time\" and then make a new move from that point, you only want to keep the\n history up to that point. Instead of adding `nextSquares` after all items in the history (using\n the Array `.concat()` method), you'll add it after all items in\n `history.slice(0, currentMove + 1)` to keep only that portion of the old history.\n- Each time a move is made, you need to update `currentMove` to point to the latest history entry.\n\n```js {2-4}\nfunction handlePlay(nextSquares) {\n const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])\n setHistory(nextHistory)\n setCurrentMove(nextHistory.length - 1)\n setXIsNext(!xIsNext)\n}\n```\n\nFinally, you will modify the `Game` component to render the currently selected move, instead of\nalways rendering the final move:\n\n```jsx {4-5,8}\nexport default function Game() {\n const history = useGameStore((state) => state.history)\n const setHistory = useGameStore((state) => state.setHistory)\n const currentMove = useGameStore((state) => state.currentMove)\n const setCurrentMove = useGameStore((state) => state.setCurrentMove)\n const xIsNext = useGameStore((state) => state.xIsNext)\n const setXIsNext = useGameStore((state) => state.setXIsNext)\n const currentSquares = history[currentMove]\n\n function handlePlay(nextSquares) {\n const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])\n setHistory(nextHistory)\n setCurrentMove(nextHistory.length - 1)\n setXIsNext(!xIsNext)\n }\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"93","text":" function jumpTo(nextMove) {\n setCurrentMove(nextMove)\n setXIsNext(nextMove % 2 === 0)\n }\n\n return (\n \n
\n \n
\n
\n
    \n {history.map((_, historyIndex) => {\n const description =\n historyIndex > 0\n ? `Go to move #${historyIndex}`\n : 'Go to game start'\n\n return (\n
  1. \n \n
  2. \n )\n })}\n
\n
\n \n )\n}\n```\n\n### Final cleanup\n\nIf you look closely at the code, you'll see that `xIsNext` is `true` when `currentMove` is even and\n`false` when `currentMove` is odd. This means that if you know the value of `currentMove`, you can\nalways determine what `xIsNext` should be.\n\nThere's no need to store `xIsNext` separately in the state. It’s better to avoid redundant state\nbecause it can reduce bugs and make your code easier to understand. Instead, you can calculate\n`xIsNext` based on `currentMove`:\n\n```jsx {6,13,17}\nexport default function Game() {\n const history = useGameStore((state) => state.history)\n const setHistory = useGameStore((state) => state.setHistory)\n const currentMove = useGameStore((state) => state.currentMove)\n const setCurrentMove = useGameStore((state) => state.setCurrentMove)\n const xIsNext = currentMove % 2 === 0\n const currentSquares = history[currentMove]\n\n function handlePlay(nextSquares) {\n const nextHistory = history.slice(0, currentMove + 1).concat([nextSquares])\n setHistory(nextHistory)\n setCurrentMove(nextHistory.length - 1)\n }\n\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"94","text":" function jumpTo(nextMove) {\n setCurrentMove(nextMove)\n }\n\n return (\n \n
\n \n
\n
\n
    \n {history.map((_, historyIndex) => {\n const description =\n historyIndex > 0\n ? `Go to move #${historyIndex}`\n : 'Go to game start'\n\n return (\n
  1. \n \n
  2. \n )\n })}\n
\n
\n \n )\n}\n```\n\nYou no longer need the `xIsNext` state declaration or the calls to `setXIsNext`. Now, there’s no\nchance for `xIsNext` to get out of sync with `currentMove`, even if you make a mistake while coding\nthe components.\n\n### Wrapping up\n\nCongratulations! You’ve created a tic-tac-toe game that:\n\n- Lets you play tic-tac-toe,\n- Indicates when a player has won the game or when is drawn,\n- Stores a game’s history as a game progresses,\n- Allows players to review a game’s history and see previous versions of a game’s board.\n\nNice work! We hope you now feel like you have a decent grasp of how React and Zustand works.\n","path":"docs/learn/guides/tutorial-tic-tac-toe.md","title":"Tutorial: Tic-Tac-Toe","source_type":"doc","kind":"doc"} -{"id":"95","text":"---\ntitle: Updating state\nnav: 4\n---\n\n## Flat updates\n\nUpdating state with Zustand is simple! Call the provided `set` function with\nthe new state, and it will be shallowly merged with the existing state in the\nstore. **Note** See next section for nested state.\n\n```tsx\nimport { create } from 'zustand'\n\ntype State = {\n firstName: string\n lastName: string\n}\n\ntype Action = {\n updateFirstName: (firstName: State['firstName']) => void\n updateLastName: (lastName: State['lastName']) => void\n}\n\n// Create your store, which includes both state and (optionally) actions\nconst usePersonStore = create()((set) => ({\n firstName: '',\n lastName: '',\n updateFirstName: (firstName) => set(() => ({ firstName: firstName })),\n updateLastName: (lastName) => set(() => ({ lastName: lastName })),\n}))\n\n// In consuming app\nfunction App() {\n // \"select\" the needed state and actions, in this case, the firstName value\n // and the action updateFirstName\n const firstName = usePersonStore((state) => state.firstName)\n const updateFirstName = usePersonStore((state) => state.updateFirstName)\n\n return (\n
\n \n\n

\n Hello, {firstName}!\n

\n
\n )\n}\n```\n\n## Deeply nested object\n\nIf you have a deep state object like this:\n\n```ts\ntype State = {\n deep: {\n nested: {\n obj: { count: number }\n }\n }\n}\n```\n\nUpdating nested state requires some effort to ensure the process is completed\nimmutably.\n\n","path":"docs/learn/guides/updating-state.md","title":"updating-state.md","source_type":"doc","kind":"doc"} -{"id":"96","text":"### Normal approach\n\nSimilar to React or Redux, the normal approach is to copy each level of the\nstate object. This is done with the spread operator `...`, and by manually\nmerging that in with the new state values. Like so:\n\n```ts\n normalInc: () =>\n set((state) => ({\n deep: {\n ...state.deep,\n nested: {\n ...state.deep.nested,\n obj: {\n ...state.deep.nested.obj,\n count: state.deep.nested.obj.count + 1\n }\n }\n }\n })),\n```\n\nThis is very long! Let's explore some alternatives that will make your life\neasier.\n\n### With Immer\n\nMany people use [Immer](https://github.com/immerjs/immer) to update nested\nvalues. Immer can be used anytime you need to update nested state such as in\nReact, Redux and of course, Zustand!\n\nYou can use Immer to shorten your state updates for deeply nested object. Let's\ntake a look at an example:\n\n```ts\n immerInc: () =>\n set(produce((state: State) => { ++state.deep.nested.obj.count })),\n```\n\nWhat a reduction! Please take note of the [gotchas listed here](../../reference/integrations/immer-middleware.md).\n\n### With optics-ts\n\nThere is another option with [optics-ts](https://github.com/akheron/optics-ts/):\n\n```ts\n opticsInc: () =>\n set(O.modify(O.optic().path(\"deep.nested.obj.count\"))((c) => c + 1)),\n```\n\nUnlike Immer, optics-ts doesn't use proxies or mutation syntax.\n\n### With Ramda\n\nYou can also use [Ramda](https://ramdajs.com/):\n\n```ts\n ramdaInc: () =>\n set(R.modifyPath([\"deep\", \"nested\", \"obj\", \"count\"], (c) => c + 1)),\n```\n\nBoth ramda and optics-ts also work with types.\n\n### Demo\n\nhttps://stackblitz.com/edit/vitejs-vite-j6bjdygu\n","path":"docs/learn/guides/updating-state.md","title":"updating-state.md","source_type":"doc","kind":"doc"} -{"id":"97","text":"---\ntitle: Learn\ndescription: A guided path to understand Zustand fundamentals, common patterns, and when to reach for specific tools.\n---\n\n## Start here\n\nIf you are new to Zustand, begin here for installation, a high-level overview, and a hands-on tutorial.\n\n- [Introduction](./getting-started/introduction.md) — Install Zustand and create your first store.\n- [Comparison with other tools](./getting-started/comparison.md) — See how Zustand compares to Redux, Jotai, Recoil, and others.\n- [Tutorial: Tic Tac Toe](./guides/tutorial-tic-tac-toe.md) — Build a complete game to learn Zustand concepts step by step.\n\n## Core concepts\n\nThe fundamentals of reading and updating state in a Zustand store.\n\n- [Updating state](./guides/updating-state.md) — How to update primitive values, objects, and nested state.\n- [Practice with no store actions](./guides/practice-with-no-store-actions.md) — Define state updates outside the store for simpler patterns.\n- [Slices pattern](./guides/slices-pattern.md) — Split a large store into smaller, composable slices.\n- [Immutable state and merging](./guides/immutable-state-and-merging.md) — Understand how Zustand merges state and when to spread manually.\n- [Maps and sets usage](./guides/maps-and-sets-usage.md) — Work with `Map` and `Set` inside Zustand state correctly.\n\n## Performance and rendering\n\nTechniques for keeping re-renders minimal and components fast.\n\n- [Prevent rerenders with useShallow](./guides/prevent-rerenders-with-use-shallow.md) — Use shallow comparison to avoid unnecessary re-renders when selecting objects.\n- [Connect to state with URL hash](./guides/connect-to-state-with-url-hash.md) — Sync store state with the URL hash for shareable UI state.\n- [Event handler in pre React 18](./guides/event-handler-in-pre-react-18.md) — Handle the batching edge case in React 17 and earlier.\n\n","path":"docs/learn/index.md","title":"index.md","source_type":"doc","kind":"doc"} -{"id":"98","text":"## TypeScript path\n\nGuides for typing stores, actions, and selectors with TypeScript.\n\n- [Beginner TypeScript](./guides/beginner-typescript.md) — Type a basic store with state and actions.\n- [Advanced TypeScript](./guides/advanced-typescript.md) — Type slices, middleware stacks, and complex patterns.\n- [Auto-generating selectors](./guides/auto-generating-selectors.md) — Generate typed selectors automatically from a store definition.\n\n## Frameworks and platforms\n\nUsing Zustand in server-rendered and framework-specific environments.\n\n- [Next.js](./guides/nextjs.md) — Set up Zustand in a Next.js app with proper SSR handling.\n- [SSR and hydration](./guides/ssr-and-hydration.md) — Avoid hydration mismatches when rendering on the server.\n- [Initialize state with props](./guides/initialize-state-with-props.md) — Seed a store's initial state from React component props.\n\n## Testing and quality\n\nBest practices for writing reliable, maintainable code with Zustand.\n\n- [Testing stores and components](./guides/testing.md) — Test store logic and React components that consume a store.\n- [Flux-inspired practice](./guides/flux-inspired-practice.md) — Apply Flux conventions to keep state changes predictable.\n- [How to reset state](./guides/how-to-reset-state.md) — Reset a store back to its initial state on demand.\n","path":"docs/learn/index.md","title":"index.md","source_type":"doc","kind":"doc"} -{"id":"99","text":"---\ntitle: createStore\ndescription: How to create vanilla stores\nnav: 22\n---\n\n`createStore` lets you create a vanilla store that exposes API utilities.\n\n```js\nconst someStore = createStore(stateCreatorFn)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n- [Reference](#reference)\n- [Usage](#usage)\n - [Updating state based on previous state](#updating-state-based-on-previous-state)\n - [Updating Primitives in State](#updating-primitives-in-state)\n - [Updating Objects in State](#updating-objects-in-state)\n - [Updating Arrays in State](#updating-arrays-in-state)\n - [Subscribing to state updates](#subscribing-to-state-updates)\n- [Troubleshooting](#troubleshooting)\n - [I’ve updated the state, but the screen doesn’t update](#i’ve-updated-the-state,-but-the-screen-doesn’t-update)\n\n## Types\n\n### Signature\n\n```ts\ncreateStore()(stateCreatorFn: StateCreator): StoreApi\n```\n\n## Reference\n\n### `createStore(stateCreatorFn)`\n\n#### Parameters\n\n- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.\n Usually, you will return an object with the methods you want to expose.\n\n#### Returns\n\n`createStore` returns a vanilla store that exposes API utilities, `setState`, `getState`,\n`getInitialState` and `subscribe`.\n\n## Usage\n\n### Updating state based on previous state\n\nThis example shows how you can support **updater functions** within **actions**.\n\n```tsx\nimport { createStore } from 'zustand/vanilla'\n\ntype AgeStoreState = { age: number }\n\ntype AgeStoreActions = {\n setAge: (\n nextAge:\n | AgeStoreState['age']\n | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),\n ) => void\n}\n\ntype AgeStore = AgeStoreState & AgeStoreActions\n\nconst ageStore = createStore()((set) => ({\n age: 42,\n setAge: (nextAge) =>\n set((state) => ({\n age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,\n })),\n}))\n\n","path":"docs/reference/apis/create-store.md","title":"create-store.md","source_type":"doc","kind":"doc"} -{"id":"100","text":"function increment() {\n ageStore.getState().setAge((currentAge) => currentAge + 1)\n}\n\nconst $yourAgeHeading = document.getElementById(\n 'your-age',\n) as HTMLHeadingElement\nconst $incrementBy3Button = document.getElementById(\n 'increment-by-3',\n) as HTMLButtonElement\nconst $incrementBy1Button = document.getElementById(\n 'increment-by-1',\n) as HTMLButtonElement\n\n$incrementBy3Button.addEventListener('click', () => {\n increment()\n increment()\n increment()\n})\n\n$incrementBy1Button.addEventListener('click', () => {\n increment()\n})\n\nconst render: Parameters[0] = (state) => {\n $yourAgeHeading.innerHTML = `Your age: ${state.age}`\n}\n\nrender(ageStore.getInitialState(), ageStore.getInitialState())\n\nageStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n

\n\n\n```\n\n","path":"docs/reference/apis/create-store.md","title":"create-store.md","source_type":"doc","kind":"doc"} -{"id":"101","text":"### Updating Primitives in State\n\nState can hold any kind of JavaScript value. When you want to update built-in primitive values like\nnumbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied\ncorrectly, and avoid unexpected behaviors.\n\n> [!NOTE]\n> By default, `set` function performs a shallow merge. If you need to completely replace\n> the state with a new one, use the `replace` parameter set to `true`\n\n```ts\nimport { createStore } from 'zustand/vanilla'\n\ntype XStore = number\n\nconst xStore = createStore()(() => 0)\n\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n xStore.setState(event.clientX, true)\n})\n\nconst render: Parameters[0] = (x) => {\n $dot.style.transform = `translate(${x}px, 0)`\n}\n\nrender(xStore.getInitialState(), xStore.getInitialState())\n\nxStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n \n\n```\n\n","path":"docs/reference/apis/create-store.md","title":"create-store.md","source_type":"doc","kind":"doc"} -{"id":"102","text":"### Updating Objects in State\n\nObjects are **mutable** in JavaScript, but you should treat them as **immutable** when you store\nthem in state. Instead, when you want to update an object, you need to create a new one (or make a\ncopy of an existing one), and then set the state to use the new object.\n\nBy default, `set` function performs a shallow merge. For most updates where you only need to modify\nspecific properties, the default shallow merge is preferred as it's more efficient. To completely\nreplace the state with a new one, use the `replace` parameter set to `true` with caution, as it\ndiscards any existing nested data within the state.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n}))\n\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getInitialState(), positionStore.getInitialState())\n\npositionStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n \n\n```\n\n","path":"docs/reference/apis/create-store.md","title":"create-store.md","source_type":"doc","kind":"doc"} -{"id":"103","text":"### Updating Arrays in State\n\nArrays are mutable in JavaScript, but you should treat them as immutable when you store them in\nstate. Just like with objects, when you want to update an array stored in state, you need to create\na new one (or make a copy of an existing one), and then set state to use the new array.\n\nBy default, `set` function performs a shallow merge. To update array values we should assign new\nvalues to ensure updates are applied correctly, and avoid unexpected behaviors. To completely\nreplace the state with a new one, use the `replace` parameter set to `true`.\n\n> [!IMPORTANT]\n> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,\n> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid\n> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,\n> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\n\ntype PositionStore = [number, number]\n\nconst positionStore = createStore()(() => [0, 0])\n\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.setState([event.clientX, event.clientY], true)\n})\n\nconst render: Parameters[0] = ([x, y]) => {\n $dot.style.transform = `translate(${x}px, ${y}px)`\n}\n\nrender(positionStore.getInitialState(), positionStore.getInitialState())\n\npositionStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n \n\n```\n\n","path":"docs/reference/apis/create-store.md","title":"create-store.md","source_type":"doc","kind":"doc"} -{"id":"104","text":"### Subscribing to state updates\n\nBy subscribing to state updates, you register a callback that fires whenever the store's state\nupdates. We can use `subscribe` for external state management.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n}))\n\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dot.addEventListener('mouseenter', (event) => {\n const parent = event.currentTarget.parentElement\n const parentWidth = parent.clientWidth\n const parentHeight = parent.clientHeight\n\n positionStore.getState().setPosition({\n x: Math.ceil(Math.random() * parentWidth),\n y: Math.ceil(Math.random() * parentHeight),\n })\n})\n\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getInitialState(), positionStore.getInitialState())\n\npositionStore.subscribe(render)\n\nconst logger: Parameters[0] = (state) => {\n console.log('new position', { position: state.position })\n}\n\npositionStore.subscribe(logger)\n```\n\nHere's the `html` code\n\n```html\n\n \n\n```\n\n## Troubleshooting\n\n","path":"docs/reference/apis/create-store.md","title":"create-store.md","source_type":"doc","kind":"doc"} -{"id":"105","text":"### I’ve updated the state, but the screen doesn’t update\n\nIn the previous example, the `position` object is always created fresh from the current cursor\nposition. But often, you will want to include existing data as a part of the new object you’re\ncreating. For example, you may want to update only one field in a form, but keep the previous\nvalues for all other fields.\n\nThese input fields don’t work because the `oninput` handlers mutate the state:\n\n```ts\nimport { createStore } from 'zustand/vanilla'\n\ntype PersonStoreState = {\n person: { firstName: string; lastName: string; email: string }\n}\n\ntype PersonStoreActions = {\n setPerson: (nextPerson: PersonStoreState['person']) => void\n}\n\ntype PersonStore = PersonStoreState & PersonStoreActions\n\nconst personStore = createStore()((set) => ({\n person: {\n firstName: 'Barbara',\n lastName: 'Hepworth',\n email: 'bhepworth@sculpture.com',\n },\n setPerson: (person) => set({ person }),\n}))\n\nconst $firstNameInput = document.getElementById(\n 'first-name',\n) as HTMLInputElement\nconst $lastNameInput = document.getElementById('last-name') as HTMLInputElement\nconst $emailInput = document.getElementById('email') as HTMLInputElement\nconst $result = document.getElementById('result') as HTMLDivElement\n\nfunction handleFirstNameChange(event: Event) {\n personStore.getState().person.firstName = (event.target as any).value\n}\n\nfunction handleLastNameChange(event: Event) {\n personStore.getState().person.lastName = (event.target as any).value\n}\n\n","path":"docs/reference/apis/create-store.md","title":"create-store.md","source_type":"doc","kind":"doc"} -{"id":"106","text":"function handleEmailChange(event: Event) {\n personStore.getState().person.email = (event.target as any).value\n}\n\n$firstNameInput.addEventListener('input', handleFirstNameChange)\n$lastNameInput.addEventListener('input', handleLastNameChange)\n$emailInput.addEventListener('input', handleEmailChange)\n\nconst render: Parameters[0] = (state) => {\n $firstNameInput.value = state.person.firstName\n $lastNameInput.value = state.person.lastName\n $emailInput.value = state.person.email\n\n $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`\n}\n\nrender(personStore.getInitialState(), personStore.getInitialState())\n\npersonStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n\n\n

\n```\n\nFor example, this line mutates the state from a past render:\n\n```ts\npersonStore.getState().firstName = (e.target as any).value\n```\n\nThe reliable way to get the behavior you’re looking for is to create a new object and pass it to\n`setPerson`. But here you want to also copy the existing data into it because only one of the\nfields has changed:\n\n```ts\npersonStore.getState().setPerson({\n firstName: e.target.value, // New first name from the input\n})\n```\n\n> [!NOTE]\n> We don’t need to copy every property separately due to `set` function performing shallow merge by\n> default.\n\nNow the form works!\n\nNotice how you didn’t declare a separate state variable for each input field. For large forms,\nkeeping all data grouped in an object is very convenient—as long as you update it correctly!\n\n```ts {32-34,38-40,44-46}\nimport { createStore } from 'zustand/vanilla'\n\ntype PersonStoreState = {\n person: { firstName: string; lastName: string; email: string }\n}\n\ntype PersonStoreActions = {\n setPerson: (nextPerson: PersonStoreState['person']) => void\n}\n\ntype PersonStore = PersonStoreState & PersonStoreActions\n\nconst personStore = createStore()((set) => ({\n person: {\n firstName: 'Barbara',\n lastName: 'Hepworth',\n email: 'bhepworth@sculpture.com',\n },\n setPerson: (person) => set({ person }),\n}))\n\nconst $firstNameInput = document.getElementById(\n 'first-name',\n) as HTMLInputElement\nconst $lastNameInput = document.getElementById('last-name') as HTMLInputElement\nconst $emailInput = document.getElementById('email') as HTMLInputElement\nconst $result = document.getElementById('result') as HTMLDivElement\n\n","path":"docs/reference/apis/create-store.md","title":"create-store.md","source_type":"doc","kind":"doc"} -{"id":"107","text":"function handleFirstNameChange(event: Event) {\n personStore.getState().setPerson({\n ...personStore.getState().person,\n firstName: (event.target as any).value,\n })\n}\n\nfunction handleLastNameChange(event: Event) {\n personStore.getState().setPerson({\n ...personStore.getState().person,\n lastName: (event.target as any).value,\n })\n}\n\nfunction handleEmailChange(event: Event) {\n personStore.getState().setPerson({\n ...personStore.getState().person,\n email: (event.target as any).value,\n })\n}\n\n$firstNameInput.addEventListener('input', handleFirstNameChange)\n$lastNameInput.addEventListener('input', handleLastNameChange)\n$emailInput.addEventListener('input', handleEmailChange)\n\nconst render: Parameters[0] = (state) => {\n $firstNameInput.value = state.person.firstName\n $lastNameInput.value = state.person.lastName\n $emailInput.value = state.person.email\n\n $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`\n}\n\nrender(personStore.getInitialState(), personStore.getInitialState())\n\npersonStore.subscribe(render)\n```\n","path":"docs/reference/apis/create-store.md","title":"create-store.md","source_type":"doc","kind":"doc"} -{"id":"108","text":"---\ntitle: createWithEqualityFn\ndescription: How to create efficient stores\ntag: react\nnav: 23\n---\n\n`createWithEqualityFn` lets you create a React Hook with API utilities attached, just like `create`.\nHowever, it offers a way to define a custom equality check. This allows for more granular control\nover when components re-render, improving performance and responsiveness.\n\n> [!IMPORTANT]\n> In order to use `createWithEqualityFn` from `zustand/traditional` you need to install\n> `use-sync-external-store` library due to `zustand/traditional` relies on `useSyncExternalStoreWithSelector`.\n\n```js\nconst useSomeStore = createWithEqualityFn(stateCreatorFn, defaultEqualityFn)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n- [Reference](#reference)\n- [Usage](#usage)\n - [Updating state based on previous state](#updating-state-based-on-previous-state)\n - [Updating Primitives in State](#updating-primitives-in-state)\n - [Updating Objects in State](#updating-objects-in-state)\n - [Updating Arrays in State](#updating-arrays-in-state)\n - [Updating state with no store actions](#updating-state-with-no-store-actions)\n - [Subscribing to state updates](#subscribing-to-state-updates)\n- [Troubleshooting](#troubleshooting)\n - [I’ve updated the state, but the screen doesn’t update](#i’ve-updated-the-state,-but-the-screen-doesn’t-update)\n\n## Types\n\n### Signature\n\n```ts\ncreateWithEqualityFn()(stateCreatorFn: StateCreator, defaultEqualityFn?: (a: U, b: U) => boolean): UseBoundStore>\n```\n\n## Reference\n\n### `createWithEqualityFn(stateCreatorFn, defaultEqualityFn)`\n\n#### Parameters\n\n- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.\n Usually, you will return an object with the methods you want to expose.\n- **optional** `defaultEqualityFn`: Defaults to `Object.is`. A function that lets you skip re-renders.\n\n","path":"docs/reference/apis/create-with-equality-fn.md","title":"create-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"109","text":"#### Returns\n\n`createWithEqualityFn` returns a React Hook with API utilities attached, just like `create`. It\nlets you return data that is based on current state, using a selector function, and lets you skip\nre-renders using an equality function. It should take a selector function, and an equality function\nas arguments.\n\n## Usage\n\n### Updating state based on previous state\n\nTo update a state based on previous state we should use **updater functions**. Read more\nabout that [here](https://react.dev/learn/queueing-a-series-of-state-updates).\n\nThis example shows how you can support **updater functions** within **actions**.\n\n```tsx\nimport { createWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/vanilla/shallow'\n\ntype AgeStoreState = { age: number }\n\ntype AgeStoreActions = {\n setAge: (\n nextAge:\n | AgeStoreState['age']\n | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),\n ) => void\n}\n\ntype AgeStore = AgeStoreState & AgeStoreActions\n\nconst useAgeStore = createWithEqualityFn()(\n (set) => ({\n age: 42,\n setAge: (nextAge) =>\n set((state) => ({\n age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,\n })),\n }),\n shallow,\n)\n\nexport default function App() {\n const age = useAgeStore((state) => state.age)\n const setAge = useAgeStore((state) => state.setAge)\n\n function increment() {\n setAge((currentAge) => currentAge + 1)\n }\n\n return (\n <>\n

Your age: {age}

\n {\n increment()\n increment()\n increment()\n }}\n >\n +3\n \n {\n increment()\n }}\n >\n +1\n \n \n )\n}\n```\n\n","path":"docs/reference/apis/create-with-equality-fn.md","title":"create-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"110","text":"### Updating Primitives in State\n\nState can hold any kind of JavaScript value. When you want to update built-in primitive values like\nnumbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied\ncorrectly, and avoid unexpected behaviors.\n\n> [!NOTE]\n> By default, `set` function performs a shallow merge. If you need to completely replace\n> the state with a new one, use the `replace` parameter set to `true`\n\n```tsx\nimport { createWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/vanilla/shallow'\n\ntype XStore = number\n\nconst useXStore = createWithEqualityFn()(() => 0, shallow)\n\nexport default function MovingDot() {\n const x = useXStore()\n const setX = (nextX: number) => {\n useXStore.setState(nextX, true)\n }\n const position = { y: 0, x }\n\n return (\n {\n setX(e.clientX)\n }}\n style={{\n position: 'relative',\n width: '100vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n```\n\n","path":"docs/reference/apis/create-with-equality-fn.md","title":"create-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"111","text":"### Updating Objects in State\n\nObjects are **mutable** in JavaScript, but you should treat them as **immutable** when you store\nthem in state. Instead, when you want to update an object, you need to create a new one (or make a\ncopy of an existing one), and then set the state to use the new object.\n\nBy default, `set` function performs a shallow merge. For most updates where you only need to modify\nspecific properties, the default shallow merge is preferred as it's more efficient. To completely\nreplace the state with a new one, use the `replace` parameter set to `true` with caution, as it\ndiscards any existing nested data within the state.\n\n```tsx\nimport { createWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/vanilla/shallow'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst usePositionStore = createWithEqualityFn()(\n (set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }),\n shallow,\n)\n\nexport default function MovingDot() {\n const position = usePositionStore((state) => state.position)\n const setPosition = usePositionStore((state) => state.setPosition)\n\n return (\n {\n setPosition({\n x: e.clientX,\n y: e.clientY,\n })\n }}\n style={{\n position: 'relative',\n width: '100vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n```\n\n","path":"docs/reference/apis/create-with-equality-fn.md","title":"create-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"112","text":"### Updating Arrays in State\n\nArrays are mutable in JavaScript, but you should treat them as immutable when you store them in\nstate. Just like with objects, when you want to update an array stored in state, you need to create\na new one (or make a copy of an existing one), and then set state to use the new array.\n\nBy default, `set` function performs a shallow merge. To update array values we should assign new\nvalues to ensure updates are applied correctly, and avoid unexpected behaviors. To completely\nreplace the state with a new one, use the `replace` parameter set to `true`.\n\n> [!IMPORTANT]\n> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,\n> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid\n> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,\n> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.\n\n```tsx\nimport { createWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/vanilla/shallow'\n\ntype PositionStore = [number, number]\n\nconst usePositionStore = createWithEqualityFn()(\n () => [0, 0],\n shallow,\n)\n\nexport default function MovingDot() {\n const [x, y] = usePositionStore()\n const position = { x, y }\n const setPosition: typeof usePositionStore.setState = (nextPosition) => {\n usePositionStore.setState(nextPosition, true)\n }\n\n return (\n {\n setPosition([e.clientX, e.clientY])\n }}\n style={{\n position: 'relative',\n width: '100vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n```\n\n","path":"docs/reference/apis/create-with-equality-fn.md","title":"create-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"113","text":"### Updating state with no store actions\n\nDefining actions at module level, external to the store have a few advantages like: it doesn't\nrequire a hook to call an action, and it facilitates code splitting.\n\n> [!NOTE]\n> The recommended way is to colocate actions and states within the store (let your actions be\n> located together with your state).\n\n```tsx\nimport { createWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/vanilla/shallow'\n\nconst usePositionStore = createWithEqualityFn<{\n x: number\n y: number\n}>()(() => ({ x: 0, y: 0 }), shallow)\n\nconst setPosition: typeof usePositionStore.setState = (nextPosition) => {\n usePositionStore.setState(nextPosition)\n}\n\nexport default function MovingDot() {\n const position = usePositionStore()\n\n return (\n \n {\n const parent = event.currentTarget.parentElement\n const parentWidth = parent.clientWidth\n const parentHeight = parent.clientHeight\n\n setPosition({\n x: Math.ceil(Math.random() * parentWidth),\n y: Math.ceil(Math.random() * parentHeight),\n })\n }}\n />\n \n )\n}\n```\n\n","path":"docs/reference/apis/create-with-equality-fn.md","title":"create-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"114","text":"### Subscribing to state updates\n\nBy subscribing to state updates, you register a callback that fires whenever the store's state\nupdates. We can use `subscribe` for external state management.\n\n```tsx\nimport { useEffect } from 'react'\nimport { createWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/vanilla/shallow'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst usePositionStore = createWithEqualityFn()(\n (set) => ({\n position: { x: 0, y: 0 },\n setPosition: (nextPosition) => set({ position: nextPosition }),\n }),\n shallow,\n)\n\nexport default function MovingDot() {\n const position = usePositionStore((state) => state.position)\n const setPosition = usePositionStore((state) => state.setPosition)\n\n useEffect(() => {\n const unsubscribePositionStore = usePositionStore.subscribe(\n ({ position }) => {\n console.log('new position', { position })\n },\n )\n\n return () => {\n unsubscribePositionStore()\n }\n }, [])\n\n return (\n \n {\n const parent = event.currentTarget.parentElement\n const parentWidth = parent.clientWidth\n const parentHeight = parent.clientHeight\n\n setPosition({\n x: Math.ceil(Math.random() * parentWidth),\n y: Math.ceil(Math.random() * parentHeight),\n })\n }}\n />\n \n )\n}\n```\n\n## Troubleshooting\n\n","path":"docs/reference/apis/create-with-equality-fn.md","title":"create-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"115","text":"### I’ve updated the state, but the screen doesn’t update\n\nIn the previous example, the `position` object is always created fresh from the current cursor\nposition. But often, you will want to include existing data as a part of the new object you’re\ncreating. For example, you may want to update only one field in a form, but keep the previous\nvalues for all other fields.\n\nThese input fields don’t work because the `onChange` handlers mutate the state:\n\n```tsx\nimport { createWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/vanilla/shallow'\n\ntype PersonStoreState = {\n person: { firstName: string; lastName: string; email: string }\n}\n\ntype PersonStoreActions = {\n setPerson: (nextPerson: PersonStoreState['person']) => void\n}\n\ntype PersonStore = PersonStoreState & PersonStoreActions\n\nconst usePersonStore = createWithEqualityFn()(\n (set) => ({\n person: {\n firstName: 'Barbara',\n lastName: 'Hepworth',\n email: 'bhepworth@sculpture.com',\n },\n setPerson: (person) => set({ person }),\n }),\n shallow,\n)\n\nexport default function Form() {\n const person = usePersonStore((state) => state.person)\n const setPerson = usePersonStore((state) => state.setPerson)\n\n function handleFirstNameChange(e: ChangeEvent) {\n person.firstName = e.target.value\n }\n\n function handleLastNameChange(e: ChangeEvent) {\n person.lastName = e.target.value\n }\n\n","path":"docs/reference/apis/create-with-equality-fn.md","title":"create-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"116","text":" function handleEmailChange(e: ChangeEvent) {\n person.email = e.target.value\n }\n\n return (\n <>\n \n \n \n

\n {person.firstName} {person.lastName} ({person.email})\n

\n \n )\n}\n```\n\nFor example, this line mutates the state from a past render:\n\n```tsx\nperson.firstName = e.target.value\n```\n\nThe reliable way to get the behavior you’re looking for is to create a new object and pass it to\n`setPerson`. But here you want to also copy the existing data into it because only one of the\nfields has changed:\n\n```ts\nsetPerson({ ...person, firstName: e.target.value }) // New first name from the input\n```\n\n> [!NOTE]\n> We don’t need to copy every property separately due to `set` function performing shallow merge by\n> default.\n\nNow the form works!\n\nNotice how you didn’t declare a separate state variable for each input field. For large forms,\nkeeping all data grouped in an object is very convenient—as long as you update it correctly!\n\n```tsx {32,36,40}\nimport { type ChangeEvent } from 'react'\nimport { createWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/vanilla/shallow'\n\ntype PersonStoreState = {\n person: { firstName: string; lastName: string; email: string }\n}\n\ntype PersonStoreActions = {\n setPerson: (nextPerson: PersonStoreState['person']) => void\n}\n\ntype PersonStore = PersonStoreState & PersonStoreActions\n\nconst usePersonStore = createWithEqualityFn()(\n (set) => ({\n person: {\n firstName: 'Barbara',\n lastName: 'Hepworth',\n email: 'bhepworth@sculpture.com',\n },\n setPerson: (nextPerson) => set({ person: nextPerson }),\n }),\n shallow,\n)\n\n","path":"docs/reference/apis/create-with-equality-fn.md","title":"create-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"117","text":"export default function Form() {\n const person = usePersonStore((state) => state.person)\n const setPerson = usePersonStore((state) => state.setPerson)\n\n function handleFirstNameChange(e: ChangeEvent) {\n setPerson({ ...person, firstName: e.target.value })\n }\n\n function handleLastNameChange(e: ChangeEvent) {\n setPerson({ ...person, lastName: e.target.value })\n }\n\n function handleEmailChange(e: ChangeEvent) {\n setPerson({ ...person, email: e.target.value })\n }\n\n return (\n <>\n \n \n \n

\n {person.firstName} {person.lastName} ({person.email})\n

\n \n )\n}\n```\n","path":"docs/reference/apis/create-with-equality-fn.md","title":"create-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"118","text":"---\ntitle: create\ndescription: How to create stores\ntag: react\nnav: 21\n---\n\n`create` lets you create a React Hook with API utilities attached.\n\n```js\nconst useSomeStore = create(stateCreatorFn)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n- [Reference](#reference)\n- [Usage](#usage)\n - [Updating state based on previous state](#updating-state-based-on-previous-state)\n - [Updating Primitives in State](#updating-primitives-in-state)\n - [Updating Objects in State](#updating-objects-in-state)\n - [Updating Arrays in State](#updating-arrays-in-state)\n - [Updating state with no store actions](#updating-state-with-no-store-actions)\n - [Subscribing to state updates](#subscribing-to-state-updates)\n- [Troubleshooting](#troubleshooting)\n - [I’ve updated the state, but the screen doesn’t update](#i’ve-updated-the-state,-but-the-screen-doesn’t-update)\n\n## Types\n\n### Signature\n\n```ts\ncreate()(stateCreatorFn: StateCreator): UseBoundStore>\n```\n\n## Reference\n\n### `create(stateCreatorFn)`\n\n#### Parameters\n\n- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.\n Usually, you will return an object with the methods you want to expose.\n\n#### Returns\n\n`create` returns a React Hook with API utilities, `setState`, `getState`, `getInitialState` and\n`subscribe`, attached. It lets you return data that is based on current state, using a selector\nfunction. It should take a selector function as its only argument.\n\n## Usage\n\n","path":"docs/reference/apis/create.md","title":"create.md","source_type":"doc","kind":"doc"} -{"id":"119","text":"### Updating state based on previous state\n\nTo update a state based on previous state we should use **updater functions**. Read more\nabout that [here](https://react.dev/learn/queueing-a-series-of-state-updates).\n\nThis example shows how you can support **updater functions** within **actions**.\n\n```tsx\nimport { create } from 'zustand'\n\ntype AgeStoreState = { age: number }\n\ntype AgeStoreActions = {\n setAge: (\n nextAge:\n | AgeStoreState['age']\n | ((currentAge: AgeStoreState['age']) => AgeStoreState['age']),\n ) => void\n}\n\ntype AgeStore = AgeStoreState & AgeStoreActions\n\nconst useAgeStore = create()((set) => ({\n age: 42,\n setAge: (nextAge) => {\n set((state) => ({\n age: typeof nextAge === 'function' ? nextAge(state.age) : nextAge,\n }))\n },\n}))\n\nexport default function App() {\n const age = useAgeStore((state) => state.age)\n const setAge = useAgeStore((state) => state.setAge)\n\n function increment() {\n setAge((currentAge) => currentAge + 1)\n }\n\n return (\n <>\n

Your age: {age}

\n {\n increment()\n increment()\n increment()\n }}\n >\n +3\n \n {\n increment()\n }}\n >\n +1\n \n \n )\n}\n```\n\n### Updating Primitives in State\n\nState can hold any kind of JavaScript value. When you want to update built-in primitive values like\nnumbers, strings, booleans, etc. you should directly assign new values to ensure updates are applied\ncorrectly, and avoid unexpected behaviors.\n\n> [!NOTE]\n> By default, `set` function performs a shallow merge. If you need to completely replace the state\n> with a new one, use the `replace` parameter set to `true`\n\n```tsx\nimport { create } from 'zustand'\n\ntype XStore = number\n\nconst useXStore = create()(() => 0)\n\n","path":"docs/reference/apis/create.md","title":"create.md","source_type":"doc","kind":"doc"} -{"id":"120","text":"export default function MovingDot() {\n const x = useXStore()\n const setX = (nextX: number) => {\n useXStore.setState(nextX, true)\n }\n const position = { y: 0, x }\n\n return (\n {\n setX(e.clientX)\n }}\n style={{\n position: 'relative',\n width: '100vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n```\n\n### Updating Objects in State\n\nObjects are **mutable** in JavaScript, but you should treat them as **immutable** when you store\nthem in state. Instead, when you want to update an object, you need to create a new one (or make a\ncopy of an existing one), and then set the state to use the new object.\n\nBy default, `set` function performs a shallow merge. For most updates where you only need to modify\nspecific properties, the default shallow merge is preferred as it's more efficient. To completely\nreplace the state with a new one, use the `replace` parameter set to `true` with caution, as it\ndiscards any existing nested data within the state.\n\n```tsx\nimport { create } from 'zustand'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst usePositionStore = create()((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (nextPosition) => set({ position: nextPosition }),\n}))\n\n","path":"docs/reference/apis/create.md","title":"create.md","source_type":"doc","kind":"doc"} -{"id":"121","text":"export default function MovingDot() {\n const position = usePositionStore((state) => state.position)\n const setPosition = usePositionStore((state) => state.setPosition)\n\n return (\n {\n setPosition({\n x: e.clientX,\n y: e.clientY,\n })\n }}\n style={{\n position: 'relative',\n width: '100vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n```\n\n### Updating Arrays in State\n\nArrays are mutable in JavaScript, but you should treat them as immutable when you store them in\nstate. Just like with objects, when you want to update an array stored in state, you need to create\na new one (or make a copy of an existing one), and then set state to use the new array.\n\nBy default, `set` function performs a shallow merge. To update array values we should assign new\nvalues to ensure updates are applied correctly, and avoid unexpected behaviors. To completely\nreplace the state with a new one, use the `replace` parameter set to `true`.\n\n> [!IMPORTANT]\n> We should prefer immutable operations like: `[...array]`, `concat(...)`, `filter(...)`,\n> `slice(...)`, `map(...)`, `toSpliced(...)`, `toSorted(...)`, and `toReversed(...)`, and avoid\n> mutable operations like `array[arrayIndex] = ...`, `push(...)`, `unshift(...)`, `pop(...)`,\n> `shift(...)`, `splice(...)`, `reverse(...)`, and `sort(...)`.\n\n```tsx\nimport { create } from 'zustand'\n\ntype PositionStore = [number, number]\n\nconst usePositionStore = create()(() => [0, 0])\n\n","path":"docs/reference/apis/create.md","title":"create.md","source_type":"doc","kind":"doc"} -{"id":"122","text":"export default function MovingDot() {\n const [x, y] = usePositionStore()\n const setPosition: typeof usePositionStore.setState = (nextPosition) => {\n usePositionStore.setState(nextPosition, true)\n }\n const position = { x, y }\n\n return (\n {\n setPosition([e.clientX, e.clientY])\n }}\n style={{\n position: 'relative',\n width: '100vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n```\n\n### Updating state with no store actions\n\nDefining actions at module level, external to the store have a few advantages like: it doesn't\nrequire a hook to call an action, and it facilitates code splitting.\n\n> [!NOTE]\n> The recommended way is to colocate actions and states within the store (let your actions be\n> located together with your state).\n\n```tsx\nimport { create } from 'zustand'\n\nconst usePositionStore = create<{\n x: number\n y: number\n}>()(() => ({ x: 0, y: 0 }))\n\nconst setPosition: typeof usePositionStore.setState = (nextPosition) => {\n usePositionStore.setState(nextPosition)\n}\n\n","path":"docs/reference/apis/create.md","title":"create.md","source_type":"doc","kind":"doc"} -{"id":"123","text":"export default function MovingDot() {\n const position = usePositionStore()\n\n return (\n \n {\n const parent = event.currentTarget.parentElement\n const parentWidth = parent.clientWidth\n const parentHeight = parent.clientHeight\n\n setPosition({\n x: Math.ceil(Math.random() * parentWidth),\n y: Math.ceil(Math.random() * parentHeight),\n })\n }}\n />\n \n )\n}\n```\n\n### Subscribing to state updates\n\nBy subscribing to state updates, you register a callback that fires whenever the store's state\nupdates. We can use `subscribe` for external state management.\n\n```tsx\nimport { useEffect } from 'react'\nimport { create } from 'zustand'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst usePositionStore = create()((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (nextPosition) => set({ position: nextPosition }),\n}))\n\n","path":"docs/reference/apis/create.md","title":"create.md","source_type":"doc","kind":"doc"} -{"id":"124","text":"export default function MovingDot() {\n const position = usePositionStore((state) => state.position)\n const setPosition = usePositionStore((state) => state.setPosition)\n\n useEffect(() => {\n const unsubscribePositionStore = usePositionStore.subscribe(\n ({ position }) => {\n console.log('new position', { position })\n },\n )\n\n return () => {\n unsubscribePositionStore()\n }\n }, [])\n\n return (\n \n {\n const parent = event.currentTarget.parentElement\n const parentWidth = parent.clientWidth\n const parentHeight = parent.clientHeight\n\n setPosition({\n x: Math.ceil(Math.random() * parentWidth),\n y: Math.ceil(Math.random() * parentHeight),\n })\n }}\n />\n \n )\n}\n```\n\n## Troubleshooting\n\n","path":"docs/reference/apis/create.md","title":"create.md","source_type":"doc","kind":"doc"} -{"id":"125","text":"### I’ve updated the state, but the screen doesn’t update\n\nIn the previous example, the `position` object is always created fresh from the current cursor\nposition. But often, you will want to include existing data as a part of the new object you’re\ncreating. For example, you may want to update only one field in a form, but keep the previous\nvalues for all other fields.\n\nThese input fields don’t work because the `onChange` handlers mutate the state:\n\n```tsx\nimport { create } from 'zustand'\n\ntype PersonStoreState = {\n firstName: string\n lastName: string\n email: string\n}\n\ntype PersonStoreActions = {\n setPerson: (nextPerson: Partial) => void\n}\n\ntype PersonStore = PersonStoreState & PersonStoreActions\n\nconst usePersonStore = create()((set) => ({\n firstName: 'Barbara',\n lastName: 'Hepworth',\n email: 'bhepworth@sculpture.com',\n setPerson: (nextPerson) => set(nextPerson),\n}))\n\nexport default function Form() {\n const person = usePersonStore((state) => state)\n const setPerson = usePersonStore((state) => state.setPerson)\n\n function handleFirstNameChange(e: ChangeEvent) {\n person.firstName = e.target.value\n }\n\n function handleLastNameChange(e: ChangeEvent) {\n person.lastName = e.target.value\n }\n\n","path":"docs/reference/apis/create.md","title":"create.md","source_type":"doc","kind":"doc"} -{"id":"126","text":" function handleEmailChange(e: ChangeEvent) {\n person.email = e.target.value\n }\n\n return (\n <>\n \n \n \n

\n {person.firstName} {person.lastName} ({person.email})\n

\n \n )\n}\n```\n\nFor example, this line mutates the state from a past render:\n\n```tsx\nperson.firstName = e.target.value\n```\n\nThe reliable way to get the behavior you’re looking for is to create a new object and pass it to\n`setPerson`. But here you want to also copy the existing data into it because only one of the\nfields has changed:\n\n```ts\nsetPerson({ ...person, firstName: e.target.value }) // New first name from the input\n```\n\n> [!NOTE]\n> We don’t need to copy every property separately due to `set` function performing shallow merge by\n> default.\n\nNow the form works!\n\nNotice how you didn’t declare a separate state variable for each input field. For large forms,\nkeeping all data grouped in an object is very convenient—as long as you update it correctly!\n\n```tsx {27,31,35}\nimport { create } from 'zustand'\n\ntype PersonStoreState = {\n person: { firstName: string; lastName: string; email: string }\n}\n\ntype PersonStoreActions = {\n setPerson: (nextPerson: PersonStoreState['person']) => void\n}\n\ntype PersonStore = PersonStoreState & PersonStoreActions\n\nconst usePersonStore = create()((set) => ({\n person: {\n firstName: 'Barbara',\n lastName: 'Hepworth',\n email: 'bhepworth@sculpture.com',\n },\n setPerson: (nextPerson) => set(nextPerson),\n}))\n\n","path":"docs/reference/apis/create.md","title":"create.md","source_type":"doc","kind":"doc"} -{"id":"127","text":"export default function Form() {\n const person = usePersonStore((state) => state.person)\n const setPerson = usePersonStore((state) => state.setPerson)\n\n function handleFirstNameChange(e: ChangeEvent) {\n setPerson({ ...person, firstName: e.target.value })\n }\n\n function handleLastNameChange(e: ChangeEvent) {\n setPerson({ ...person, lastName: e.target.value })\n }\n\n function handleEmailChange(e: ChangeEvent) {\n setPerson({ ...person, email: e.target.value })\n }\n\n return (\n <>\n \n \n \n

\n {person.firstName} {person.lastName} ({person.email})\n

\n \n )\n}\n```\n","path":"docs/reference/apis/create.md","title":"create.md","source_type":"doc","kind":"doc"} -{"id":"128","text":"---\ntitle: shallow\ndescription: How compare simple data effectively\nnav: 24\n---\n\n`shallow` lets you run fast checks on simple data structures. It effectively identifies changes in\n**top-level** properties when you're working with data structures that don't have nested objects or\narrays within them.\n\n> [!NOTE]\n> Shallow lets you perform quick comparisons, but keep its limitations in mind.\n\n```js\nconst equal = shallow(a, b)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n- [Reference](#reference)\n- [Usage](#usage)\n - [Comparing Primitives](#comparing-primitives)\n - [Comparing Objects](#comparing-objects)\n - [Comparing Sets](#comparing-sets)\n - [Comparing Maps](#comparing-maps)\n- [Troubleshooting](#troubleshooting)\n - [Comparing objects returns `false` even if they are identical](#comparing-objects-returns-false-even-if-they-are-identical)\n - [Comparing objects with different prototypes](#comparing-objects-with-different-prototypes)\n\n## Types\n\n### Signature\n\n```ts\nshallow(a: T, b: T): boolean\n```\n\n## Reference\n\n### `shallow(a, b)`\n\n#### Parameters\n\n- `a`: The first value.\n- `b`: The second value.\n\n#### Returns\n\n`shallow` returns `true` when `a` and `b` are equal based on a shallow comparison of their\n**top-level** properties. Otherwise, it should return `false`.\n\n## Usage\n\n","path":"docs/reference/apis/shallow.md","title":"shallow.md","source_type":"doc","kind":"doc"} -{"id":"129","text":"### Comparing Primitives\n\nWhen comparing primitive values like `string`s, `number`s, `boolean`s, and `BigInt`s, both\n`Object.is` and `shallow` function return `true` if the values are the same. This is because\nprimitive values are compared by their actual value rather than by reference.\n\n```ts\nconst stringLeft = 'John Doe'\nconst stringRight = 'John Doe'\n\nObject.is(stringLeft, stringRight) // -> true\nshallow(stringLeft, stringRight) // -> true\n\nconst numberLeft = 10\nconst numberRight = 10\n\nObject.is(numberLeft, numberRight) // -> true\nshallow(numberLeft, numberRight) // -> true\n\nconst booleanLeft = true\nconst booleanRight = true\n\nObject.is(booleanLeft, booleanRight) // -> true\nshallow(booleanLeft, booleanRight) // -> true\n\nconst bigIntLeft = 1n\nconst bigIntRight = 1n\n\nObject.is(bigIntLeft, bigIntRight) // -> true\nshallow(bigIntLeft, bigIntRight) // -> true\n```\n\n### Comparing Objects\n\nWhen comparing objects, it's important to understand how `Object.is` and `shallow` function\noperate, as they handle comparisons differently.\n\nThe `shallow` function returns `true` because shallow performs a shallow comparison of the objects.\nIt checks if the top-level properties and their values are the same. In this case, the top-level\nproperties (`firstName`, `lastName`, and `age`) and their values are identical between `objectLeft`\nand `objectRight`, so shallow considers them equal.\n\n```ts\nconst objectLeft = {\n firstName: 'John',\n lastName: 'Doe',\n age: 30,\n}\nconst objectRight = {\n firstName: 'John',\n lastName: 'Doe',\n age: 30,\n}\n\nObject.is(objectLeft, objectRight) // -> false\nshallow(objectLeft, objectRight) // -> true\n```\n\n","path":"docs/reference/apis/shallow.md","title":"shallow.md","source_type":"doc","kind":"doc"} -{"id":"130","text":"### Comparing Sets\n\nWhen comparing sets, it's important to understand how `Object.is` and `shallow` function operate,\nas they handle comparisons differently.\n\nThe `shallow` function returns `true` because shallow performs a shallow comparison of the sets. It\nchecks if the top-level properties (in this case, the sets themselves) are the same. Since `setLeft`\nand `setRight` are both instances of the Set object and contain the same elements, shallow considers\nthem equal.\n\n```ts\nconst setLeft = new Set([1, 2, 3])\nconst setRight = new Set([1, 2, 3])\n\nObject.is(setLeft, setRight) // -> false\nshallow(setLeft, setRight) // -> true\n```\n\n### Comparing Maps\n\nWhen comparing maps, it's important to understand how `Object.is` and `shallow` function operate, as\nthey handle comparisons differently.\n\nThe `shallow` returns `true` because shallow performs a shallow comparison of the maps. It checks if\nthe top-level properties (in this case, the maps themselves) are the same. Since `mapLeft` and\n`mapRight` are both instances of the Map object and contain the same key-value pairs, shallow\nconsiders them equal.\n\n```ts\nconst mapLeft = new Map([\n [1, 'one'],\n [2, 'two'],\n [3, 'three'],\n])\nconst mapRight = new Map([\n [1, 'one'],\n [2, 'two'],\n [3, 'three'],\n])\n\nObject.is(mapLeft, mapRight) // -> false\nshallow(mapLeft, mapRight) // -> true\n```\n\n## Troubleshooting\n\n","path":"docs/reference/apis/shallow.md","title":"shallow.md","source_type":"doc","kind":"doc"} -{"id":"131","text":"### Comparing objects returns `false` even if they are identical\n\nThe `shallow` function performs a shallow comparison. A shallow comparison checks if the top-level\nproperties of two objects are equal. It does not check nested objects or deeply nested properties.\nIn other words, it only compares the references of the properties.\n\nIn the following example, the shallow function returns `false` because it compares only the\ntop-level properties and their references. The address property in both objects is a nested object,\nand even though their contents are identical, their references are different. Consequently, shallow\nsees them as different, resulting in `false`.\n\n```ts\nconst objectLeft = {\n firstName: 'John',\n lastName: 'Doe',\n age: 30,\n address: {\n street: 'Kulas Light',\n suite: 'Apt. 556',\n city: 'Gwenborough',\n zipcode: '92998-3874',\n geo: {\n lat: '-37.3159',\n lng: '81.1496',\n },\n },\n}\nconst objectRight = {\n firstName: 'John',\n lastName: 'Doe',\n age: 30,\n address: {\n street: 'Kulas Light',\n suite: 'Apt. 556',\n city: 'Gwenborough',\n zipcode: '92998-3874',\n geo: {\n lat: '-37.3159',\n lng: '81.1496',\n },\n },\n}\n\nObject.is(objectLeft, objectRight) // -> false\nshallow(objectLeft, objectRight) // -> false\n```\n\nIf we remove the `address` property, the shallow comparison would work as expected because all\ntop-level properties would be primitive values or references to the same values:\n\n```ts\nconst objectLeft = {\n firstName: 'John',\n lastName: 'Doe',\n age: 30,\n}\nconst objectRight = {\n firstName: 'John',\n lastName: 'Doe',\n age: 30,\n}\n\nObject.is(objectLeft, objectRight) // -> false\nshallow(objectLeft, objectRight) // -> true\n```\n\nIn this modified example, `objectLeft` and `objectRight` have the same top-level properties and\nprimitive values. Since `shallow` function only compares the top-level properties, it will return\n`true` because the primitive values (`firstName`, `lastName`, and `age`) are identical in both\nobjects.\n\n","path":"docs/reference/apis/shallow.md","title":"shallow.md","source_type":"doc","kind":"doc"} -{"id":"132","text":"### Comparing objects with different prototypes\n\nThe `shallow` function checks whether the two objects have the same prototype. If their prototypes\nare referentially different, shallow will return `false`. This comparison is done using:\n\n```ts\nObject.getPrototypeOf(a) === Object.getPrototypeOf(b)\n```\n\n> [!IMPORTANT]\n> Objects created with the object initializer (`{}`) or with `new Object()` inherit from\n> `Object.prototype` by default. However, objects created with `Object.create(proto)` inherit from\n> the proto you pass in—which may not be `Object.prototype.`\n\n```ts\nconst a = Object.create({}) // -> prototype is `{}`\nconst b = {} // -> prototype is `Object.prototype`\n\nshallow(a, b) // -> false\n```\n","path":"docs/reference/apis/shallow.md","title":"shallow.md","source_type":"doc","kind":"doc"} -{"id":"133","text":"---\ntitle: useShallow\ndescription: How to memoize selector functions\ntag: react\nnav: 27\n---\n\n`useShallow` is a React Hook that lets you optimize re-renders.\n\n```js\nconst memoizedSelector = useShallow(selector)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n- [Reference](#reference)\n- [Usage](#usage)\n - [Writing a memoized selector](#writing-a-memoized-selector)\n- [Troubleshooting](#troubleshooting)\n\n## Types\n\n### Signature\n\n```ts\nuseShallow(selectorFn: (state: T) => U): (state: T) => U\n```\n\n## Reference\n\n### `useShallow(selectorFn)`\n\n#### Parameters\n\n- `selectorFn`: A function that lets you return data that is based on current state.\n\n#### Returns\n\n`useShallow` returns a memoized version of a selector function using a shallow comparison for\nmemoization.\n\n## Usage\n\n### Writing a memoized selector\n\nFirst, we need to setup a store to hold the state for the bear family. In this store, we define\nthree properties: `papaBear`, `mamaBear`, and `babyBear`, each representing a different member of\nthe bear family and their respective oatmeal pot sizes.\n\n```tsx\nimport { create } from 'zustand'\n\ntype BearFamilyMealsStore = {\n [key: string]: string\n}\n\nconst useBearFamilyMealsStore = create()(() => ({\n papaBear: 'large porridge-pot',\n mamaBear: 'middle-size porridge pot',\n babyBear: 'A little, small, wee pot',\n}))\n```\n\nNext, we'll create a `BearNames` component that retrieves the keys of our state (the bear family\nmembers) and displays them.\n\n```tsx\n","path":"docs/reference/hooks/use-shallow.md","title":"use-shallow.md","source_type":"doc","kind":"doc"} -{"id":"134","text":"function BearNames() {\n const names = useBearFamilyMealsStore((state) => Object.keys(state))\n\n return
{names.join(', ')}
\n}\n```\n\nNext, we will create a `UpdateBabyBearMeal` component that periodically updates baby bear's meal\nchoice.\n\n```tsx\nconst meals = [\n 'A tiny, little, wee bowl',\n 'A small, petite, tiny pot',\n 'A wee, itty-bitty, small bowl',\n 'A little, petite, tiny dish',\n 'A tiny, small, wee vessel',\n 'A small, little, wee cauldron',\n 'A little, tiny, small cup',\n 'A wee, small, little jar',\n 'A tiny, wee, small pan',\n 'A small, wee, little crock',\n]\n\nfunction UpdateBabyBearMeal() {\n useEffect(() => {\n const timer = setInterval(() => {\n useBearFamilyMealsStore.setState({\n babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],\n })\n }, 1000)\n\n return () => {\n clearInterval(timer)\n }\n }, [])\n\n return null\n}\n```\n\nFinally, we combine both components in the `App` component to see them in action.\n\n```tsx\nexport default function App() {\n return (\n <>\n \n \n \n )\n}\n```\n\nHere is what the code should look like:\n\n```tsx\nimport { useEffect } from 'react'\nimport { create } from 'zustand'\n\ntype BearFamilyMealsStore = {\n [key: string]: string\n}\n\nconst useBearFamilyMealsStore = create()(() => ({\n papaBear: 'large porridge-pot',\n mamaBear: 'middle-size porridge pot',\n babyBear: 'A little, small, wee pot',\n}))\n\nconst meals = [\n 'A tiny, little, wee bowl',\n 'A small, petite, tiny pot',\n 'A wee, itty-bitty, small bowl',\n 'A little, petite, tiny dish',\n 'A tiny, small, wee vessel',\n 'A small, little, wee cauldron',\n 'A little, tiny, small cup',\n 'A wee, small, little jar',\n 'A tiny, wee, small pan',\n 'A small, wee, little crock',\n]\n\n","path":"docs/reference/hooks/use-shallow.md","title":"use-shallow.md","source_type":"doc","kind":"doc"} -{"id":"135","text":"function UpdateBabyBearMeal() {\n useEffect(() => {\n const timer = setInterval(() => {\n useBearFamilyMealsStore.setState({\n babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],\n })\n }, 1000)\n\n return () => {\n clearInterval(timer)\n }\n }, [])\n\n return null\n}\n\nfunction BearNames() {\n const names = useBearFamilyMealsStore((state) => Object.keys(state))\n\n return
{names.join(', ')}
\n}\n\nexport default function App() {\n return (\n <>\n \n \n \n )\n}\n```\n\nEverything might look fine, but there’s a small problem: the `BearNames` component keeps\nre-rendering even if the names haven’t changed. This happens because the component re-renders\nwhenever any part of the state changes, even if the specific part we care about (the list of names) hasn’t changed.\n\nTo fix this, we use `useShallow` to make sure the component only re-renders when the actual keys of\nthe state change:\n\n```tsx\nfunction BearNames() {\n const names = useBearFamilyMealsStore(\n useShallow((state) => Object.keys(state)),\n )\n\n return
{names.join(', ')}
\n}\n```\n\nHere is what the code should look like:\n\n```tsx\nimport { useEffect } from 'react'\nimport { create } from 'zustand'\nimport { useShallow } from 'zustand/react/shallow'\n\ntype BearFamilyMealsStore = {\n [key: string]: string\n}\n\nconst useBearFamilyMealsStore = create()(() => ({\n papaBear: 'large porridge-pot',\n mamaBear: 'middle-size porridge pot',\n babyBear: 'A little, small, wee pot',\n}))\n\nconst meals = [\n 'A tiny, little, wee bowl',\n 'A small, petite, tiny pot',\n 'A wee, itty-bitty, small bowl',\n 'A little, petite, tiny dish',\n 'A tiny, small, wee vessel',\n 'A small, little, wee cauldron',\n 'A little, tiny, small cup',\n 'A wee, small, little jar',\n 'A tiny, wee, small pan',\n 'A small, wee, little crock',\n]\n\n","path":"docs/reference/hooks/use-shallow.md","title":"use-shallow.md","source_type":"doc","kind":"doc"} -{"id":"136","text":"function UpdateBabyBearMeal() {\n useEffect(() => {\n const timer = setInterval(() => {\n useBearFamilyMealsStore.setState({\n babyBear: meals[Math.floor(Math.random() * (meals.length - 1))],\n })\n }, 1000)\n\n return () => {\n clearInterval(timer)\n }\n }, [])\n\n return null\n}\n\nfunction BearNames() {\n const names = useBearFamilyMealsStore(\n useShallow((state) => Object.keys(state)),\n )\n\n return
{names.join(', ')}
\n}\n\nexport default function App() {\n return (\n <>\n \n \n \n )\n}\n```\n\nBy using `useShallow`, we optimized the rendering process, ensuring that the component only\nre-renders when necessary, which improves overall performance.\n\n## Troubleshooting\n\n","path":"docs/reference/hooks/use-shallow.md","title":"use-shallow.md","source_type":"doc","kind":"doc"} -{"id":"137","text":"### I get \"Maximum update depth exceeded\" when reading multiple values from the store\n\nSince v5, selectors that return a new reference on every render can trigger infinite update loops because the default equality check is `Object.is`. The most common case is bundling multiple values into a single object inside the selector. The following triggers the error:\n\n```tsx\nconst { searchValue, setSearchValue } = useStore((state) => ({\n searchValue: state.searchValue,\n setSearchValue: state.setSearchValue,\n}))\n```\n\nThe wrapper object is recreated on every render, so each comparison fails and the component re-subscribes in a loop.\n\nWrap the selector with `useShallow` so the wrapper's properties are compared by reference instead of the wrapper itself:\n\n```tsx\nconst { searchValue, setSearchValue } = useStore(\n useShallow((state) => ({\n searchValue: state.searchValue,\n setSearchValue: state.setSearchValue,\n })),\n)\n```\n\nAlternatively, subscribe to each value with its own selector — there is no wrapper object to recreate:\n\n```tsx\nconst searchValue = useStore((state) => state.searchValue)\nconst setSearchValue = useStore((state) => state.setSearchValue)\n```\n\nSee [Requiring stable selector outputs](../migrations/migrating-to-v5.md#requiring-stable-selector-outputs) in the v5 migration guide for the underlying behavior change.\n","path":"docs/reference/hooks/use-shallow.md","title":"use-shallow.md","source_type":"doc","kind":"doc"} -{"id":"138","text":"---\ntitle: useStoreWithEqualityFn\ndescription: How to use vanilla stores effectively in React\ntag: react\nnav: 26\n---\n\n`useStoreWithEqualityFn` is a React Hook that lets you use a vanilla store in React, just like\n`useStore`. However, it offers a way to define a custom equality check. This allows for more\ngranular control over when components re-render, improving performance and responsiveness.\n\n> [!IMPORTANT]\n> In order to use `useStoreWithEqualityFn` from `zustand/traditional` you need to install\n> `use-sync-external-store` library due to `zustand/traditional` relies on `useSyncExternalStoreWithSelector`.\n\n```js\nconst someState = useStoreWithEqualityFn(store, selectorFn, equalityFn)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n- [Reference](#reference)\n- [Usage](#usage)\n - [Using a global vanilla store in React](#using-a-global-vanilla-store-in-react)\n - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)\n - [Using scoped (non-global) vanilla store in React](<#using-scoped-(non-global)-vanilla-store-in-react>)\n - [Using dynamic scoped (non-global) vanilla stores in React](<#using-dynamic-scoped-(non-global)-vanilla-stores-in-react>)\n- [Troubleshooting](#troubleshooting)\n\n## Types\n\n### Signature\n\n```ts\nuseStoreWithEqualityFn(store: StoreApi, selectorFn: (state: T) => U, equalityFn?: (a: U, b: U) => boolean): U\n```\n\n## Reference\n\n### `useStoreWithEqualityFn(store, selectorFn, equalityFn)`\n\n#### Parameters\n\n- `storeApi`: The instance that lets you access to store API utilities.\n- `selectorFn`: A function that lets you return data that is based on current state.\n- `equalityFn`: A function that lets you skip re-renders.\n\n#### Returns\n\n`useStoreWithEqualityFn` returns any data based on current state depending on the selector function,\nand lets you skip re-renders using an equality function. It should take a store, a selector\nfunction, and an equality function as arguments.\n\n## Usage\n\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"139","text":"### Using a global vanilla store in React\n\nFirst, let's set up a store that will hold the position of the dot on the screen. We'll define the\nstore to manage `x` and `y` coordinates and provide an action to update these coordinates.\n\n```tsx\nimport { createStore, useStore } from 'zustand'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n}))\n```\n\nNext, we'll create a `MovingDot` component that renders a div representing the dot. This component\nwill use the store to track and update the dot's position.\n\n```tsx\nfunction MovingDot() {\n const position = useStoreWithEqualityFn(\n positionStore,\n (state) => state.position,\n shallow,\n )\n const setPosition = useStoreWithEqualityFn(\n positionStore,\n (state) => state.setPosition,\n shallow,\n )\n\n return (\n {\n setPosition({\n x: e.clientX,\n y: e.clientY,\n })\n }}\n style={{\n position: 'relative',\n width: '100vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n```\n\nFinally, we’ll render the `MovingDot` component in our `App` component.\n\n```tsx\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"140","text":"export default function App() {\n return \n}\n```\n\nHere is what the code should look like:\n\n```tsx\nimport { createStore } from 'zustand'\nimport { useStoreWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/shallow'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n}))\n\nfunction MovingDot() {\n const position = useStoreWithEqualityFn(\n positionStore,\n (state) => state.position,\n shallow,\n )\n const setPosition = useStoreWithEqualityFn(\n positionStore,\n (state) => state.setPosition,\n shallow,\n )\n\n return (\n {\n setPosition({\n x: e.clientX,\n y: e.clientY,\n })\n }}\n style={{\n position: 'relative',\n width: '100vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n\nexport default function App() {\n return \n}\n```\n\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"141","text":"### Using dynamic global vanilla stores in React\n\nFirst, we'll create a factory function that generates a store for managing the counter state.\nEach tab will have its own instance of this store.\n\n```ts\nimport { createStore } from 'zustand'\n\ntype CounterState = {\n count: number\n}\n\ntype CounterActions = { increment: () => void }\n\ntype CounterStore = CounterState & CounterActions\n\nconst createCounterStore = () => {\n return createStore()((set) => ({\n count: 0,\n increment: () => {\n set((state) => ({ count: state.count + 1 }))\n },\n }))\n}\n```\n\nNext, we'll create a factory function that manages the creation and retrieval of counter stores.\nThis allows each tab to have its own independent counter.\n\n```ts\nconst defaultCounterStores = new Map<\n string,\n ReturnType\n>()\n\nconst createCounterStoreFactory = (\n counterStores: typeof defaultCounterStores,\n) => {\n return (counterStoreKey: string) => {\n if (!counterStores.has(counterStoreKey)) {\n counterStores.set(counterStoreKey, createCounterStore())\n }\n return counterStores.get(counterStoreKey)!\n }\n}\n\nconst getOrCreateCounterStoreByKey =\n createCounterStoreFactory(defaultCounterStores)\n```\n\nNow, let’s build the Tabs component, where users can switch between tabs and increment each tab’s\ncounter.\n\n```tsx\nconst [currentTabIndex, setCurrentTabIndex] = useState(0)\nconst counterState = useStoreWithEqualityFn(\n getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),\n (state) => state,\n shallow,\n)\n\nreturn (\n
\n \n setCurrentTabIndex(0)}\n >\n Tab 1\n \n setCurrentTabIndex(1)}\n >\n Tab 2\n \n setCurrentTabIndex(2)}\n >\n Tab 3\n \n
\n
\n Content of Tab {currentTabIndex + 1}\n

\n \n
\n \n)\n```\n\nFinally, we'll create the `App` component, which renders the tabs and their respective counters.\nThe counter state is managed independently for each tab.\n\n```tsx\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"142","text":"export default function App() {\n return \n}\n```\n\nHere is what the code should look like:\n\n```tsx\nimport { useState } from 'react'\nimport { createStore } from 'zustand'\nimport { useStoreWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/shallow'\n\ntype CounterState = {\n count: number\n}\n\ntype CounterActions = { increment: () => void }\n\ntype CounterStore = CounterState & CounterActions\n\nconst createCounterStore = () => {\n return createStore()((set) => ({\n count: 0,\n increment: () => {\n set((state) => ({ count: state.count + 1 }))\n },\n }))\n}\n\nconst defaultCounterStores = new Map<\n string,\n ReturnType\n>()\n\nconst createCounterStoreFactory = (\n counterStores: typeof defaultCounterStores,\n) => {\n return (counterStoreKey: string) => {\n if (!counterStores.has(counterStoreKey)) {\n counterStores.set(counterStoreKey, createCounterStore())\n }\n return counterStores.get(counterStoreKey)!\n }\n}\n\nconst getOrCreateCounterStoreByKey =\n createCounterStoreFactory(defaultCounterStores)\n\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"143","text":"export default function App() {\n const [currentTabIndex, setCurrentTabIndex] = useState(0)\n const counterState = useStoreWithEqualityFn(\n getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),\n (state) => state,\n shallow,\n )\n\n return (\n
\n \n setCurrentTabIndex(0)}\n >\n Tab 1\n \n setCurrentTabIndex(1)}\n >\n Tab 2\n \n setCurrentTabIndex(2)}\n >\n Tab 3\n \n
\n
\n Content of Tab {currentTabIndex + 1}\n

\n \n
\n \n )\n}\n```\n\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"144","text":"### Using scoped (non-global) vanilla store in React\n\nFirst, let's set up a store that will hold the position of the dot on the screen. We'll define the\nstore to manage `x` and `y` coordinates and provide an action to update these coordinates.\n\n```tsx\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst createPositionStore = () => {\n return createStore()((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }))\n}\n```\n\nNext, we'll create a context and a provider component to pass down the store through the React\ncomponent tree. This allows each `MovingDot` component to have its own independent state.\n\n```tsx\nconst PositionStoreContext = createContext | null>(null)\n\nfunction PositionStoreProvider({ children }: { children: ReactNode }) {\n const [store] = useState(() => createPositionStore())\n return (\n \n {children}\n \n )\n}\n```\n\nTo simplify accessing the store, we’ll create a React custom hook, `usePositionStore`. This hook\nwill read the store from the context and allow us to select specific parts of the state.\n\n```ts\nfunction usePositionStore(selector: (state: PositionStore) => U) {\n const store = useContext(PositionStoreContext)\n\n if (store === null) {\n throw new Error(\n 'usePositionStore must be used within PositionStoreProvider',\n )\n }\n\n return useStoreWithEqualityFn(store, selector, shallow)\n}\n```\n\nNow, let's create the `MovingDot` component, which will render a dot that follows the mouse cursor\nwithin its container.\n\n```tsx\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"145","text":"function MovingDot({ color }: { color: string }) {\n const position = usePositionStore((state) => state.position)\n const setPosition = usePositionStore((state) => state.setPosition)\n\n return (\n {\n setPosition({\n x:\n e.clientX > e.currentTarget.clientWidth\n ? e.clientX - e.currentTarget.clientWidth\n : e.clientX,\n y: e.clientY,\n })\n }}\n style={{\n position: 'relative',\n width: '50vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n```\n\nFinally, we'll bring everything together in the `App` component, where we render two `MovingDot`\ncomponents, each with its own independent state.\n\n```tsx\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"146","text":"export default function App() {\n return (\n
\n \n \n \n \n \n \n
\n )\n}\n```\n\nHere is what the code should look like:\n\n```tsx\nimport { type ReactNode, useState, createContext, useContext } from 'react'\nimport { createStore } from 'zustand'\nimport { useStoreWithEqualityFn } from 'zustand/traditional'\nimport { shallow } from 'zustand/shallow'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst createPositionStore = () => {\n return createStore()((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }))\n}\n\nconst PositionStoreContext = createContext | null>(null)\n\nfunction PositionStoreProvider({ children }: { children: ReactNode }) {\n const [store] = useState(() => createPositionStore())\n return (\n \n {children}\n \n )\n}\n\nfunction usePositionStore(selector: (state: PositionStore) => U) {\n const store = useContext(PositionStoreContext)\n\n if (store === null) {\n throw new Error(\n 'usePositionStore must be used within PositionStoreProvider',\n )\n }\n\n return useStoreWithEqualityFn(store, selector, shallow)\n}\n\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"147","text":"function MovingDot({ color }: { color: string }) {\n const position = usePositionStore((state) => state.position)\n const setPosition = usePositionStore((state) => state.setPosition)\n\n return (\n {\n setPosition({\n x:\n e.clientX > e.currentTarget.clientWidth\n ? e.clientX - e.currentTarget.clientWidth\n : e.clientX,\n y: e.clientY,\n })\n }}\n style={{\n position: 'relative',\n width: '50vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n\nexport default function App() {\n return (\n
\n \n \n \n \n \n \n
\n )\n}\n```\n\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"148","text":"### Using dynamic scoped (non-global) vanilla stores in React\n\nFirst, we'll create a factory function that generates a store for managing the counter state.\nEach tab will have its own instance of this store.\n\n```ts\ntype CounterState = {\n count: number\n}\n\ntype CounterActions = { increment: () => void }\n\ntype CounterStore = CounterState & CounterActions\n\nconst createCounterStore = () => {\n return createStore()((set) => ({\n count: 0,\n increment: () => {\n set((state) => ({ count: state.count + 1 }))\n },\n }))\n}\n```\n\nNext, we'll create a factory function that manages the creation and retrieval of counter stores.\nThis allows each tab to have its own independent counter.\n\n```ts\nconst createCounterStoreFactory = (\n counterStores: Map>,\n) => {\n return (counterStoreKey: string) => {\n if (!counterStores.has(counterStoreKey)) {\n counterStores.set(counterStoreKey, createCounterStore())\n }\n return counterStores.get(counterStoreKey)!\n }\n}\n```\n\nNext, we need a way to manage and access these stores throughout our app. We’ll use React’s context\nfor this.\n\n```tsx\nconst CounterStoresContext = createContext(null)\n\nconst CounterStoresProvider = ({ children }) => {\n const [stores] = useState(\n () => new Map>(),\n )\n\n return (\n \n {children}\n \n )\n}\n```\n\nNow, we’ll create a custom hook, `useCounterStore`, that lets us access the correct store for a\ngiven tab.\n\n```tsx\nconst useCounterStore = (\n key: string,\n selector: (state: CounterStore) => U,\n) => {\n const stores = useContext(CounterStoresContext)\n\n if (stores === undefined) {\n throw new Error('useCounterStore must be used within CounterStoresProvider')\n }\n\n const getOrCreateCounterStoreByKey = useCallback(\n (key: string) => createCounterStoreFactory(stores!)(key),\n [stores],\n )\n\n return useStore(getOrCreateCounterStoreByKey(key), selector)\n}\n```\n\nNow, let’s build the Tabs component, where users can switch between tabs and increment each tab’s\ncounter.\n\n```tsx\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"149","text":"function Tabs() {\n const [currentTabIndex, setCurrentTabIndex] = useState(0)\n const counterState = useCounterStore(\n `tab-${currentTabIndex}`,\n (state) => state,\n )\n\n return (\n
\n \n setCurrentTabIndex(0)}\n >\n Tab 1\n \n setCurrentTabIndex(1)}\n >\n Tab 2\n \n setCurrentTabIndex(2)}\n >\n Tab 3\n \n
\n
\n Content of Tab {currentTabIndex + 1}\n

\n \n
\n \n )\n}\n```\n\nFinally, we'll create the `App` component, which renders the tabs and their respective counters.\nThe counter state is managed independently for each tab.\n\n```tsx\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"150","text":"export default function App() {\n return (\n \n \n \n )\n}\n```\n\nHere is what the code should look like:\n\n```tsx\nimport {\n type ReactNode,\n useState,\n useCallback,\n useContext,\n createContext,\n} from 'react'\nimport { createStore, useStore } from 'zustand'\n\ntype CounterState = {\n count: number\n}\n\ntype CounterActions = { increment: () => void }\n\ntype CounterStore = CounterState & CounterActions\n\nconst createCounterStore = () => {\n return createStore()((set) => ({\n count: 0,\n increment: () => {\n set((state) => ({ count: state.count + 1 }))\n },\n }))\n}\n\nconst createCounterStoreFactory = (\n counterStores: Map>,\n) => {\n return (counterStoreKey: string) => {\n if (!counterStores.has(counterStoreKey)) {\n counterStores.set(counterStoreKey, createCounterStore())\n }\n return counterStores.get(counterStoreKey)!\n }\n}\n\nconst CounterStoresContext = createContext\n> | null>(null)\n\nconst CounterStoresProvider = ({ children }: { children: ReactNode }) => {\n const [stores] = useState(\n () => new Map>(),\n )\n\n return (\n \n {children}\n \n )\n}\n\nconst useCounterStore = (\n key: string,\n selector: (state: CounterStore) => U,\n) => {\n const stores = useContext(CounterStoresContext)\n\n if (stores === undefined) {\n throw new Error('useCounterStore must be used within CounterStoresProvider')\n }\n\n const getOrCreateCounterStoreByKey = useCallback(\n (key: string) => createCounterStoreFactory(stores!)(key),\n [stores],\n )\n\n return useStore(getOrCreateCounterStoreByKey(key), selector)\n}\n\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"151","text":"function Tabs() {\n const [currentTabIndex, setCurrentTabIndex] = useState(0)\n const counterState = useCounterStore(\n `tab-${currentTabIndex}`,\n (state) => state,\n )\n\n return (\n
\n \n setCurrentTabIndex(0)}\n >\n Tab 1\n \n setCurrentTabIndex(1)}\n >\n Tab 2\n \n setCurrentTabIndex(2)}\n >\n Tab 3\n \n
\n
\n Content of Tab {currentTabIndex + 1}\n

\n \n
\n \n )\n}\n\nexport default function App() {\n return (\n \n \n \n )\n}\n```\n\n## Troubleshooting\n\nTBD\n","path":"docs/reference/hooks/use-store-with-equality-fn.md","title":"use-store-with-equality-fn.md","source_type":"doc","kind":"doc"} -{"id":"152","text":"---\ntitle: useStore\ndescription: How to use vanilla stores in React\ntag: react\nnav: 25\n---\n\n`useStore` is a React Hook that lets you use a vanilla store in React.\n\n```js\nconst someState = useStore(store, selectorFn)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n- [Reference](#reference)\n- [Usage](#usage)\n - [Use a vanilla store in React](#using-a-global-vanilla-store-in-react)\n - [Using dynamic vanilla stores in React](#using-dynamic-global-vanilla-stores-in-react)\n - [Using scoped (non-global) vanilla store in React](<#using-scoped-(non-global)-vanilla-store-in-react>)\n - [Using dynamic scoped (non-global) vanilla stores in React](<#using-dynamic-scoped-(non-global)-vanilla-stores-in-react>)\n- [Troubleshooting](#troubleshooting)\n\n## Types\n\n### Signature\n\n```ts\nuseStore(store: StoreApi, selectorFn?: (state: T) => U): U\n```\n\n## Reference\n\n### `useStore(store, selectorFn)`\n\n#### Parameters\n\n- `storeApi`: The instance that lets you access to store API utilities.\n- `selectorFn`: A function that lets you return data that is based on current state.\n\n#### Returns\n\n`useStore` returns any data based on current state depending on the selector function. It should\ntake a store, and a selector function as arguments.\n\n## Usage\n\n### Using a global vanilla store in React\n\nFirst, let's set up a store that will hold the position of the dot on the screen. We'll define the\nstore to manage `x` and `y` coordinates and provide an action to update these coordinates.\n\n```tsx\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n}))\n```\n\nNext, we'll create a `MovingDot` component that renders a div representing the dot. This component\nwill use the store to track and update the dot's position.\n\n```tsx\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"153","text":"function MovingDot() {\n const position = useStore(positionStore, (state) => state.position)\n const setPosition = useStore(positionStore, (state) => state.setPosition)\n\n return (\n {\n setPosition({\n x: e.clientX,\n y: e.clientY,\n })\n }}\n style={{\n position: 'relative',\n width: '100vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n```\n\nFinally, we’ll render the `MovingDot` component in our `App` component.\n\n```tsx\nexport default function App() {\n return \n}\n```\n\nHere is what the code should look like:\n\n```tsx\nimport { createStore, useStore } from 'zustand'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n}))\n\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"154","text":"function MovingDot() {\n const position = useStore(positionStore, (state) => state.position)\n const setPosition = useStore(positionStore, (state) => state.setPosition)\n\n return (\n {\n setPosition({\n x: e.clientX,\n y: e.clientY,\n })\n }}\n style={{\n position: 'relative',\n width: '100vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n\nexport default function App() {\n return \n}\n```\n\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"155","text":"### Using dynamic global vanilla stores in React\n\nFirst, we'll create a factory function that generates a store for managing the counter state.\nEach tab will have its own instance of this store.\n\n```ts\ntype CounterState = {\n count: number\n}\n\ntype CounterActions = { increment: () => void }\n\ntype CounterStore = CounterState & CounterActions\n\nconst createCounterStore = () => {\n return createStore()((set) => ({\n count: 0,\n increment: () => {\n set((state) => ({ count: state.count + 1 }))\n },\n }))\n}\n```\n\nNext, we'll create a factory function that manages the creation and retrieval of counter stores.\nThis allows each tab to have its own independent counter.\n\n```ts\nconst defaultCounterStores = new Map<\n string,\n ReturnType\n>()\n\nconst createCounterStoreFactory = (\n counterStores: typeof defaultCounterStores,\n) => {\n return (counterStoreKey: string) => {\n if (!counterStores.has(counterStoreKey)) {\n counterStores.set(counterStoreKey, createCounterStore())\n }\n return counterStores.get(counterStoreKey)!\n }\n}\n\nconst getOrCreateCounterStoreByKey =\n createCounterStoreFactory(defaultCounterStores)\n```\n\nNow, let’s build the Tabs component, where users can switch between tabs and increment each tab’s\ncounter.\n\n```tsx\nconst [currentTabIndex, setCurrentTabIndex] = useState(0)\nconst counterState = useStore(\n getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),\n)\n\nreturn (\n
\n \n setCurrentTabIndex(0)}\n >\n Tab 1\n \n setCurrentTabIndex(1)}\n >\n Tab 2\n \n setCurrentTabIndex(2)}\n >\n Tab 3\n \n
\n
\n Content of Tab {currentTabIndex + 1}\n

\n \n
\n \n)\n```\n\nFinally, we'll create the `App` component, which renders the tabs and their respective counters.\nThe counter state is managed independently for each tab.\n\n```tsx\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"156","text":"export default function App() {\n return \n}\n```\n\nHere is what the code should look like:\n\n```tsx\nimport { useState } from 'react'\nimport { createStore, useStore } from 'zustand'\n\ntype CounterState = {\n count: number\n}\n\ntype CounterActions = { increment: () => void }\n\ntype CounterStore = CounterState & CounterActions\n\nconst createCounterStore = () => {\n return createStore()((set) => ({\n count: 0,\n increment: () => {\n set((state) => ({ count: state.count + 1 }))\n },\n }))\n}\n\nconst defaultCounterStores = new Map<\n string,\n ReturnType\n>()\n\nconst createCounterStoreFactory = (\n counterStores: typeof defaultCounterStores,\n) => {\n return (counterStoreKey: string) => {\n if (!counterStores.has(counterStoreKey)) {\n counterStores.set(counterStoreKey, createCounterStore())\n }\n return counterStores.get(counterStoreKey)!\n }\n}\n\nconst getOrCreateCounterStoreByKey =\n createCounterStoreFactory(defaultCounterStores)\n\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"157","text":"export default function App() {\n const [currentTabIndex, setCurrentTabIndex] = useState(0)\n const counterState = useStore(\n getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`),\n )\n\n return (\n
\n \n setCurrentTabIndex(0)}\n >\n Tab 1\n \n setCurrentTabIndex(1)}\n >\n Tab 2\n \n setCurrentTabIndex(2)}\n >\n Tab 3\n \n
\n
\n Content of Tab {currentTabIndex + 1}\n

\n \n
\n \n )\n}\n```\n\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"158","text":"### Using scoped (non-global) vanilla store in React\n\nFirst, let's set up a store that will hold the position of the dot on the screen. We'll define the\nstore to manage `x` and `y` coordinates and provide an action to update these coordinates.\n\n```tsx\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst createPositionStore = () => {\n return createStore()((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }))\n}\n```\n\nNext, we'll create a context and a provider component to pass down the store through the React\ncomponent tree. This allows each `MovingDot` component to have its own independent state.\n\n```tsx\nconst PositionStoreContext = createContext | null>(null)\n\nfunction PositionStoreProvider({ children }: { children: ReactNode }) {\n const [store] = useState(() => createPositionStore())\n return (\n \n {children}\n \n )\n}\n```\n\nTo simplify accessing the store, we’ll create a React custom hook, `usePositionStore`. This hook\nwill read the store from the context and allow us to select specific parts of the state.\n\n```ts\nfunction usePositionStore(selector: (state: PositionStore) => U) {\n const store = useContext(PositionStoreContext)\n\n if (store === null) {\n throw new Error(\n 'usePositionStore must be used within PositionStoreProvider',\n )\n }\n\n return useStore(store, selector)\n}\n```\n\nNow, let's create the `MovingDot` component, which will render a dot that follows the mouse cursor\nwithin its container.\n\n```tsx\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"159","text":"function MovingDot({ color }: { color: string }) {\n const position = usePositionStore((state) => state.position)\n const setPosition = usePositionStore((state) => state.setPosition)\n\n return (\n {\n setPosition({\n x:\n e.clientX > e.currentTarget.clientWidth\n ? e.clientX - e.currentTarget.clientWidth\n : e.clientX,\n y: e.clientY,\n })\n }}\n style={{\n position: 'relative',\n width: '50vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n```\n\nFinally, we'll bring everything together in the `App` component, where we render two `MovingDot`\ncomponents, each with its own independent state.\n\n```tsx\nexport default function App() {\n return (\n
\n \n \n \n \n \n \n
\n )\n}\n```\n\nHere is what the code should look like:\n\n```tsx\nimport { type ReactNode, useState, createContext, useContext } from 'react'\nimport { createStore, useStore } from 'zustand'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst createPositionStore = () => {\n return createStore()((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }))\n}\n\nconst PositionStoreContext = createContext | null>(null)\n\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"160","text":"function PositionStoreProvider({ children }: { children: ReactNode }) {\n const [store] = useState(() => createPositionStore())\n return (\n \n {children}\n \n )\n}\n\nfunction usePositionStore(selector: (state: PositionStore) => U) {\n const store = useContext(PositionStoreContext)\n\n if (store === null) {\n throw new Error(\n 'usePositionStore must be used within PositionStoreProvider',\n )\n }\n\n return useStore(store, selector)\n}\n\nfunction MovingDot({ color }: { color: string }) {\n const position = usePositionStore((state) => state.position)\n const setPosition = usePositionStore((state) => state.setPosition)\n\n return (\n {\n setPosition({\n x:\n e.clientX > e.currentTarget.clientWidth\n ? e.clientX - e.currentTarget.clientWidth\n : e.clientX,\n y: e.clientY,\n })\n }}\n style={{\n position: 'relative',\n width: '50vw',\n height: '100vh',\n }}\n >\n \n \n )\n}\n\nexport default function App() {\n return (\n
\n \n \n \n \n \n \n
\n )\n}\n```\n\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"161","text":"### Using dynamic scoped (non-global) vanilla stores in React\n\nFirst, we'll create a factory function that generates a store for managing the counter state.\nEach tab will have its own instance of this store.\n\n```ts\nimport { createStore } from 'zustand'\n\ntype CounterState = {\n count: number\n}\n\ntype CounterActions = { increment: () => void }\n\ntype CounterStore = CounterState & CounterActions\n\nconst createCounterStore = () => {\n return createStore()((set) => ({\n count: 0,\n increment: () => {\n set((state) => ({ count: state.count + 1 }))\n },\n }))\n}\n```\n\nNext, we'll create a factory function that manages the creation and retrieval of counter stores.\nThis allows each tab to have its own independent counter.\n\n```ts\nconst createCounterStoreFactory = (\n counterStores: Map>,\n) => {\n return (counterStoreKey: string) => {\n if (!counterStores.has(counterStoreKey)) {\n counterStores.set(counterStoreKey, createCounterStore())\n }\n return counterStores.get(counterStoreKey)!\n }\n}\n```\n\nNext, we need a way to manage and access these stores throughout our app. We’ll use React’s context\nfor this.\n\n```tsx\nconst CounterStoresContext = createContext(null)\n\nconst CounterStoresProvider = ({ children }) => {\n const [stores] = useState(\n () => new Map>(),\n )\n\n return (\n \n {children}\n \n )\n}\n```\n\nNow, we’ll create a custom hook, `useCounterStore`, that lets us access the correct store for a\ngiven tab.\n\n```tsx\nconst useCounterStore = (\n currentTabIndex: number,\n selector: (state: CounterStore) => U,\n) => {\n const stores = useContext(CounterStoresContext)\n\n if (stores === undefined) {\n throw new Error('useCounterStore must be used within CounterStoresProvider')\n }\n\n const getOrCreateCounterStoreByKey = useCallback(\n () => createCounterStoreFactory(stores),\n [stores],\n )\n\n return useStore(getOrCreateCounterStoreByKey(`tab-${currentTabIndex}`))\n}\n```\n\nNow, let’s build the Tabs component, where users can switch between tabs and increment each tab’s\ncounter.\n\n```tsx\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"162","text":"function Tabs() {\n const [currentTabIndex, setCurrentTabIndex] = useState(0)\n const counterState = useCounterStore(\n `tab-${currentTabIndex}`,\n (state) => state,\n )\n\n return (\n
\n \n setCurrentTabIndex(0)}\n >\n Tab 1\n \n setCurrentTabIndex(1)}\n >\n Tab 2\n \n setCurrentTabIndex(2)}\n >\n Tab 3\n \n
\n
\n Content of Tab {currentTabIndex + 1}\n

\n \n
\n \n )\n}\n```\n\nFinally, we'll create the `App` component, which renders the tabs and their respective counters.\nThe counter state is managed independently for each tab.\n\n```tsx\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"163","text":"export default function App() {\n return (\n \n \n \n )\n}\n```\n\nHere is what the code should look like:\n\n```tsx\nimport {\n type ReactNode,\n useState,\n useCallback,\n useContext,\n createContext,\n} from 'react'\nimport { createStore, useStore } from 'zustand'\n\ntype CounterState = {\n count: number\n}\n\ntype CounterActions = { increment: () => void }\n\ntype CounterStore = CounterState & CounterActions\n\nconst createCounterStore = () => {\n return createStore()((set) => ({\n count: 0,\n increment: () => {\n set((state) => ({ count: state.count + 1 }))\n },\n }))\n}\n\nconst createCounterStoreFactory = (\n counterStores: Map>,\n) => {\n return (counterStoreKey: string) => {\n if (!counterStores.has(counterStoreKey)) {\n counterStores.set(counterStoreKey, createCounterStore())\n }\n return counterStores.get(counterStoreKey)!\n }\n}\n\nconst CounterStoresContext = createContext\n> | null>(null)\n\nconst CounterStoresProvider = ({ children }: { children: ReactNode }) => {\n const [stores] = useState(\n () => new Map>(),\n )\n\n return (\n \n {children}\n \n )\n}\n\nconst useCounterStore = (\n key: string,\n selector: (state: CounterStore) => U,\n) => {\n const stores = useContext(CounterStoresContext)\n\n if (stores === undefined) {\n throw new Error('useCounterStore must be used within CounterStoresProvider')\n }\n\n const getOrCreateCounterStoreByKey = useCallback(\n (key: string) => createCounterStoreFactory(stores!)(key),\n [stores],\n )\n\n return useStore(getOrCreateCounterStoreByKey(key), selector)\n}\n\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"164","text":"function Tabs() {\n const [currentTabIndex, setCurrentTabIndex] = useState(0)\n const counterState = useCounterStore(\n `tab-${currentTabIndex}`,\n (state) => state,\n )\n\n return (\n
\n \n setCurrentTabIndex(0)}\n >\n Tab 1\n \n setCurrentTabIndex(1)}\n >\n Tab 2\n \n setCurrentTabIndex(2)}\n >\n Tab 3\n \n
\n
\n Content of Tab {currentTabIndex + 1}\n

\n \n
\n \n )\n}\n\nexport default function App() {\n return (\n \n \n \n )\n}\n```\n\n## Troubleshooting\n\nTBD\n","path":"docs/reference/hooks/use-store.md","title":"use-store.md","source_type":"doc","kind":"doc"} -{"id":"165","text":"---\ntitle: Reference\ndescription: API-first reference for stores, hooks, middlewares, and integrations.\n---\n\n## APIs\n\nCore functions for creating and configuring stores.\n\n- [`create`](./apis/create.md) — Create a store bound to React via hooks.\n- [`createStore`](./apis/create-store.md) — Create a standalone store without React.\n- [`createWithEqualityFn`](./apis/create-with-equality-fn.md) — Like `create`, but with a custom equality function.\n- [`shallow`](./apis/shallow.md) — Utility for shallow comparison of objects and arrays.\n\n## Hooks\n\nReact hooks for reading and subscribing to store state.\n\n- [`useStore`](./hooks/use-store.md) — Access and subscribe to a vanilla store from a React component.\n- [`useStoreWithEqualityFn`](./hooks/use-store-with-equality-fn.md) — Like `useStore`, but with a custom equality function.\n- [`useShallow`](./hooks/use-shallow.md) — Derive a stable reference from a selector using shallow comparison.\n\n## Middlewares\n\nComposable middleware functions for extending store behavior.\n\n- [`persist`](./middlewares/persist.md) — Persist and rehydrate state using `localStorage` or a custom storage engine.\n- [`devtools`](./middlewares/devtools.md) — Connect a store to Redux DevTools for time-travel debugging.\n- [`redux`](./middlewares/redux.md) — Use a reducer and dispatch pattern similar to Redux.\n- [`immer`](./middlewares/immer.md) — Write state updates with mutable syntax using Immer.\n- [`combine`](./middlewares/combine.md) — Combine separate state slices into a single store with inferred types.\n- [`subscribeWithSelector`](./middlewares/subscribe-with-selector.md) — Subscribe to a slice of state with selector and equality support.\n\n","path":"docs/reference/index.md","title":"index.md","source_type":"doc","kind":"doc"} -{"id":"166","text":"## Integrations\n\nIn-depth guides for using Zustand alongside third-party libraries.\n\n- [Persisting store data](./integrations/persisting-store-data.md) — Detailed guide to the `persist` middleware and storage adapters.\n- [Immer middleware](./integrations/immer-middleware.md) — Detailed guide to the `immer` middleware.\n- [Third-party libraries](./integrations/third-party-libraries.md) — Using Zustand with other libraries in the ecosystem.\n\n## Migrations\n\nUpgrade guides between major versions.\n\n- [Migrating to v5](./migrations/migrating-to-v5.md) — How to upgrade from Zustand v4.\n- [Migrating to v4](./migrations/migrating-to-v4.md) — How to upgrade from Zustand v3.\n\n## Previous versions\n\nAPIs that existed in older versions of Zustand and are no longer recommended for new code.\n\n- [createContext (v3)](./previous-versions/zustand-v3-create-context.md) — The `createContext` export from `zustand/context`, deprecated in v4 and removed in v5.\n","path":"docs/reference/index.md","title":"index.md","source_type":"doc","kind":"doc"} -{"id":"167","text":"---\ntitle: Immer middleware\nnav: 35\n---\n\nThe [Immer](https://github.com/immerjs/immer) middleware enables you\nto use immutable state in a more convenient way.\nAlso, with Immer, you can simplify handling\nimmutable data structures in Zustand.\n\n## Installation\n\nIn order to use the Immer middleware in Zustand,\nyou will need to install Immer as a direct dependency.\n\n```bash\nnpm install immer\n```\n\n## Usage\n\n(Notice the extra parentheses after the type parameter as mentioned in the [Advanced Typescript Guide](../../learn/guides/advanced-typescript.md)).\n\nUpdating simple states\n\n```ts\nimport { create } from 'zustand'\nimport { immer } from 'zustand/middleware/immer'\n\ntype State = {\n count: number\n}\n\ntype Actions = {\n increment: (qty: number) => void\n decrement: (qty: number) => void\n}\n\nexport const useCountStore = create()(\n immer((set) => ({\n count: 0,\n increment: (qty: number) =>\n set((state) => {\n state.count += qty\n }),\n decrement: (qty: number) =>\n set((state) => {\n state.count -= qty\n }),\n })),\n)\n```\n\nUpdating complex states\n\n```ts\nimport { create } from 'zustand'\nimport { immer } from 'zustand/middleware/immer'\n\ninterface Todo {\n id: string\n title: string\n done: boolean\n}\n\ntype State = {\n todos: Record\n}\n\ntype Actions = {\n toggleTodo: (todoId: string) => void\n}\n\n","path":"docs/reference/integrations/immer-middleware.md","title":"immer-middleware.md","source_type":"doc","kind":"doc"} -{"id":"168","text":"export const useTodoStore = create()(\n immer((set) => ({\n todos: {\n '82471c5f-4207-4b1d-abcb-b98547e01a3e': {\n id: '82471c5f-4207-4b1d-abcb-b98547e01a3e',\n title: 'Learn Zustand',\n done: false,\n },\n '354ee16c-bfdd-44d3-afa9-e93679bda367': {\n id: '354ee16c-bfdd-44d3-afa9-e93679bda367',\n title: 'Learn Jotai',\n done: false,\n },\n '771c85c5-46ea-4a11-8fed-36cc2c7be344': {\n id: '771c85c5-46ea-4a11-8fed-36cc2c7be344',\n title: 'Learn Valtio',\n done: false,\n },\n '363a4bac-083f-47f7-a0a2-aeeee153a99c': {\n id: '363a4bac-083f-47f7-a0a2-aeeee153a99c',\n title: 'Learn Signals',\n done: false,\n },\n },\n toggleTodo: (todoId: string) =>\n set((state) => {\n state.todos[todoId].done = !state.todos[todoId].done\n }),\n })),\n)\n```\n\n## Gotchas\n\nIn this section you will find some things\nthat you need to keep in mind when using Zustand with Immer.\n\n### My subscriptions aren't being called\n\nIf you are using Immer,\nmake sure you are actually following\n[the rules of Immer](https://immerjs.github.io/immer/pitfalls).\n\nFor example, you have to add `[immerable] = true` for\n[class objects](https://immerjs.github.io/immer/complex-objects) to work.\nIf you don't do this, Immer will still mutate the object,\nbut not as a proxy, so it will also update the current state.\nZustand checks if the state has actually changed,\nso since both the current state and the next state are\nequal (if you don't do it correctly),\nZustand will skip calling the subscriptions.\n\n## Demos\n\n- Basic: https://stackblitz.com/edit/vitejs-vite-3sgc4ejy\n- Advanced: https://stackblitz.com/edit/vitejs-vite-jxxtuyj3\n","path":"docs/reference/integrations/immer-middleware.md","title":"immer-middleware.md","source_type":"doc","kind":"doc"} -{"id":"169","text":"---\ntitle: Persisting store data\nnav: 34\n---\n\nThe Persist middleware enables you to store\nyour Zustand state in a storage\n(e.g., `localStorage`, `AsyncStorage`, `IndexedDB`, etc.),\nthus persisting its data.\n\nNote that this middleware supports both\nsynchronous storages, like `localStorage`,\nand asynchronous storages, like `AsyncStorage`,\nbut using an asynchronous storage does come with a cost.\nSee [Hydration and asynchronous storages](#hydration-and-asynchronous-storages)\nfor more details.\n\n## Simple example\n\n```ts\nimport { create } from 'zustand'\nimport { persist, createJSONStorage } from 'zustand/middleware'\n\nexport const useBearStore = create()(\n persist(\n (set, get) => ({\n bears: 0,\n addABear: () => set({ bears: get().bears + 1 }),\n }),\n {\n name: 'food-storage', // name of the item in the storage (must be unique)\n storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used\n },\n ),\n)\n```\n\n## Typescript simple example\n\n```ts\nimport { create } from 'zustand'\nimport { persist, createJSONStorage } from 'zustand/middleware'\n\ntype BearStore = {\n bears: number\n addABear: () => void\n}\n\nexport const useBearStore = create()(\n persist(\n (set, get) => ({\n bears: 0,\n addABear: () => set({ bears: get().bears + 1 }),\n }),\n {\n name: 'food-storage', // name of the item in the storage (must be unique)\n storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used\n },\n ),\n)\n```\n\n## Options\n\n### `name`\n\nThis is the only required option.\nThe given name is going to be the key\nused to store your Zustand state in the storage,\nso it must be unique.\n\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"170","text":"### `storage`\n\n> Type: `() => StateStorage`\n\nThe `StateStorage` can be imported with:\n\n```ts\nimport { StateStorage } from 'zustand/middleware'\n```\n\n> Default: `createJSONStorage(() => localStorage)`\n\nEnables you to use your own storage. Simply pass a function that returns the storage you want to use. It's recommended to use the [`createJSONStorage`](#createjsonstorage) helper function to create a `storage` object that is compliant with the `StateStorage` interface.\n\nExample:\n\n```ts\nimport { persist, createJSONStorage } from 'zustand/middleware'\n\nexport const useBoundStore = create(\n persist(\n (set, get) => ({\n // ...\n }),\n {\n // ...\n storage: createJSONStorage(() => AsyncStorage),\n },\n ),\n)\n```\n\n### `partialize`\n\n> Type: `(state: Object) => Object`\n\n> Default: `(state) => state`\n\nEnables you to pick some of the state's fields to be stored in the storage.\n\nYou could omit multiple fields using the following:\n\n```ts\nexport const useBoundStore = create(\n persist(\n (set, get) => ({\n foo: 0,\n bar: 1,\n }),\n {\n // ...\n partialize: (state) =>\n Object.fromEntries(\n Object.entries(state).filter(([key]) => !['foo'].includes(key)),\n ),\n },\n ),\n)\n```\n\nOr you could allow only specific fields using the following:\n\n```ts\nexport const useBoundStore = create(\n persist(\n (set, get) => ({\n foo: 0,\n bar: 1,\n }),\n {\n // ...\n partialize: (state) => ({ foo: state.foo }),\n },\n ),\n)\n```\n\n### `onRehydrateStorage`\n\n> Type: `(state: Object) => ((state?: Object, error?: Error) => void) | void`\n\nThis option enables you to pass a listener function\nthat will be called when the storage is hydrated.\n\nExample:\n\n```ts\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"171","text":"export const useBoundStore = create(\n persist(\n (set, get) => ({\n // ...\n }),\n {\n // ...\n onRehydrateStorage: (state) => {\n console.log('hydration starts')\n\n // optional\n return (state, error) => {\n if (error) {\n console.log('an error happened during hydration', error)\n } else {\n console.log('hydration finished')\n }\n }\n },\n },\n ),\n)\n```\n\n### `version`\n\n> Type: `number`\n\n> Default: `0`\n\nIf you want to introduce a breaking change in your storage\n(e.g. renaming a field), you can specify a new version number.\nBy default, if the version in the storage\ndoes not match the version in the code,\nthe stored value won't be used.\nYou can use the [migrate](#migrate) function (see below)\nto handle breaking changes in order to persist previously stored data.\n\n### `migrate`\n\n> Type: `(persistedState: Object, version: number) => Object | Promise`\n\n> Default: `(persistedState) => persistedState`\n\nYou can use this option to handle versions migration.\nThe migrate function takes the persisted state\nand the version number as arguments.\nIt must return a state that is compliant\nto the latest version (the version in the code).\n\nFor instance, if you want to rename a field, you can use the following:\n\n```ts\nexport const useBoundStore = create(\n persist(\n (set, get) => ({\n newField: 0, // let's say this field was named otherwise in version 0\n }),\n {\n // ...\n version: 1, // a migration will be triggered if the version in the storage mismatches this one\n migrate: (persistedState, version) => {\n if (version === 0) {\n // if the stored value is in version 0, we rename the field to the new name\n persistedState.newField = persistedState.oldField\n delete persistedState.oldField\n }\n\n return persistedState\n },\n },\n ),\n)\n```\n\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"172","text":"### `merge`\n\n> Type: `(persistedState: Object, currentState: Object) => Object`\n\n> Default: `(persistedState, currentState) => ({ ...currentState, ...persistedState })`\n\nIn some cases, you might want to use a custom merge function\nto merge the persisted value with the current state.\n\nBy default, the middleware does a shallow merge.\nThe shallow merge might not be enough\nif you have partially persisted nested objects.\nFor instance, if the storage contains the following:\n\n```ts\n{\n foo: {\n bar: 0,\n }\n}\n```\n\nBut your Zustand store contains:\n\n```ts\n{\n foo: {\n bar: 0,\n baz: 1,\n }\n}\n```\n\nThe shallow merge will erase the `baz` field from the `foo` object.\nOne way to fix this would be to give a custom deep merge function:\n\n```ts\nexport const useBoundStore = create(\n persist(\n (set, get) => ({\n foo: {\n bar: 0,\n baz: 1,\n },\n }),\n {\n // ...\n merge: (persistedState, currentState) =>\n deepMerge(currentState, persistedState),\n },\n ),\n)\n```\n\n### `skipHydration`\n\n> Type: `boolean | undefined`\n\n> Default: `undefined`\n\nBy default the store will be hydrated on initialization.\n\nIn some applications you may need to control when the first hydration occurs.\nFor example, in server-rendered apps.\n\nIf you set `skipHydration`, the initial call for hydration isn't called,\nand it is left up to you to manually call `rehydrate()`.\n\n```ts\nexport const useBoundStore = create(\n persist(\n () => ({\n count: 0,\n // ...\n }),\n {\n // ...\n skipHydration: true,\n },\n ),\n)\n```\n\n```tsx\nimport { useBoundStore } from './path-to-store';\n\nexport function StoreConsumer() {\n // hydrate persisted store after on mount\n useEffect(() => {\n useBoundStore.persist.rehydrate();\n }, [])\n\n return (\n //...\n )\n}\n```\n\n## API\n\n> Version: >=3.6.3\n\nThe Persist API enables you to do a number of interactions\nwith the Persist middleware\nfrom inside or outside of a React component.\n\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"173","text":"### `getOptions`\n\n> Type: `() => Partial`\n\n> Returns: Options of the Persist middleware\n\nFor example, it can be used to obtain the storage name:\n\n```ts\nuseBoundStore.persist.getOptions().name\n```\n\n### `setOptions`\n\n> Type: `(newOptions: Partial) => void`\n\nChanges the middleware options.\nNote that the new options will be merged with the current ones.\n\nFor instance, this can be used to change the storage name:\n\n```ts\nuseBoundStore.persist.setOptions({\n name: 'new-name',\n})\n```\n\nOr even to change the storage engine:\n\n```ts\nuseBoundStore.persist.setOptions({\n storage: createJSONStorage(() => sessionStorage),\n})\n```\n\n### `clearStorage`\n\n> Type: `() => void`\n\nClears everything stored under the [name](#name) key.\n\n```ts\nuseBoundStore.persist.clearStorage()\n```\n\n### `rehydrate`\n\n> Type: `() => Promise`\n\nIn some cases, you might want to trigger the rehydration manually.\nThis can be done by calling the `rehydrate` method.\n\n```ts\nawait useBoundStore.persist.rehydrate()\n```\n\n### `hasHydrated`\n\n> Type: `() => boolean`\n\nThis is a non-reactive getter to check\nif the storage has been hydrated\n(note that it updates when calling [`rehydrate`](#rehydrate)).\n\n```ts\nuseBoundStore.persist.hasHydrated()\n```\n\n### `onHydrate`\n\n> Type: `(listener: (state) => void) => () => void`\n\n> Returns: Unsubscribe function\n\nThis listener will be called when the hydration process starts.\n\n```ts\nconst unsub = useBoundStore.persist.onHydrate((state) => {\n console.log('hydration starts')\n})\n\n// later on...\nunsub()\n```\n\n### `onFinishHydration`\n\n> Type: `(listener: (state) => void) => () => void`\n\n> Returns: Unsubscribe function\n\nThis listener will be called when the hydration process ends.\n\n```ts\nconst unsub = useBoundStore.persist.onFinishHydration((state) => {\n console.log('hydration finished')\n})\n\n// later on...\nunsub()\n```\n\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"174","text":"### `createJSONStorage`\n\n> Type: `(getStorage: () => StateStorage, options?: JsonStorageOptions) => StateStorage`\n\n> Returns: `PersistStorage`\n\nThis helper function enables you to create a [`storage`](#storage) object which is useful when you want to use a custom storage engine.\n\n`getStorage` is a function that returns the storage engine with the properties `getItem`, `setItem`, and `removeItem`.\n\n`options` is an optional object that can be used to customize the serialization and deserialization of the data. `options.reviver` is a function that is passed to `JSON.parse` to deserialize the data. `options.replacer` is a function that is passed to `JSON.stringify` to serialize the data.\n\n```ts\nimport { createJSONStorage } from 'zustand/middleware'\n\nconst storage = createJSONStorage(() => sessionStorage, {\n reviver: (key, value) => {\n if (value && value.type === 'date') {\n return new Date(value)\n }\n return value\n },\n replacer: (key, value) => {\n // NOTE: the result of `.toJSON()` is passed to the\n // replacer function as value if is available so\n // a Date is always a `string` at this point\n if (key === 'someDate') return { type: 'date', value }\n return value\n },\n})\n```\n\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"175","text":"## Hydration and asynchronous storages\n\nTo explain what is the \"cost\" of asynchronous storages,\nyou need to understand what is hydration.\n\nIn a nutshell, hydration is a process\nof retrieving persisted state from the storage\nand merging it with the current state.\n\nThe Persist middleware does two kinds of hydration:\nsynchronous and asynchronous.\nIf the given storage is synchronous (e.g., `localStorage`),\nhydration will be done synchronously.\nOn the other hand, if the given storage is asynchronous (e.g., `AsyncStorage`),\nhydration will be done asynchronously (shocking, I know!).\n\nBut what's the catch?\nWith synchronous hydration,\nthe Zustand store will already have been hydrated at its creation.\nIn contrast, with asynchronous hydration,\nthe Zustand store will be hydrated later on, in a microtask.\n\nWhy does it matter?\nAsynchronous hydration can cause some unexpected behaviors.\nFor instance, if you use Zustand in a React app,\nthe store will **not** be hydrated at the initial render.\nIn cases where your app depends on the persisted value at page load,\nyou might want to wait until\nthe store has been hydrated before showing anything.\nFor example, your app might think the user\nis not logged in because it's the default,\nbut in reality the store has not been hydrated yet.\n\nIf your app does depends on the persisted state at page load,\nsee [_How can I check if my store has been hydrated_](#how-can-i-check-if-my-store-has-been-hydrated)\nin the [FAQ](#faq) section below.\n\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"176","text":"### Usage in Next.js\n\nNextJS uses Server Side Rendering, and it will compare the rendered component on the server with the one rendered on client.\nBut since you are using data from browser to change your component, the two renders will differ and Next will throw a warning at you.\n\nThe errors usually are:\n\n- Text content does not match server-rendered HTML\n- Hydration failed because the initial UI does not match what was rendered on the server\n- There was an error while hydrating. Because the error happened outside of a Suspense boundary, the entire root will switch to client rendering\n\nTo solve these errors, create a custom hook so that Zustand waits a little before changing your components.\n\nCreate a file with the following:\n\n```ts\n// useStore.ts\nimport { useState, useEffect } from 'react'\n\nconst useStore = (\n store: (callback: (state: T) => unknown) => unknown,\n callback: (state: T) => F,\n) => {\n const result = store(callback) as F\n const [data, setData] = useState()\n\n useEffect(() => {\n setData(result)\n }, [result])\n\n return data\n}\n\nexport default useStore\n```\n\nNow in your pages, you will use the hook a little bit differently:\n\n```ts\n// useBearStore.ts\n\nimport { create } from 'zustand'\nimport { persist } from 'zustand/middleware'\n\n// the store itself does not need any change\nexport const useBearStore = create(\n persist(\n (set, get) => ({\n bears: 0,\n addABear: () => set({ bears: get().bears + 1 }),\n }),\n {\n name: 'food-storage',\n },\n ),\n)\n```\n\n```ts\n// yourComponent.tsx\n\nimport useStore from './useStore'\nimport { useBearStore } from './stores/useBearStore'\n\nconst bears = useStore(useBearStore, (state) => state.bears)\n```\n\nCredits: [This reply to an issue](https://github.com/pmndrs/zustand/issues/938#issuecomment-1481801942), which points to [this blog post](https://dev.to/abdulsamad/how-to-use-zustands-persist-middleware-in-nextjs-4lb5).\n\n## FAQ\n\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"177","text":"### How can I check if my store has been hydrated\n\nThere are a few different ways to do this.\n\nYou can use the [`onRehydrateStorage`](#onrehydratestorage)\nlistener function to update a field in the store:\n\n```ts\nconst useBoundStore = create(\n persist(\n (set, get) => ({\n // ...\n _hasHydrated: false,\n setHasHydrated: (state) => {\n set({\n _hasHydrated: state\n });\n }\n }),\n {\n // ...\n onRehydrateStorage: (state) => {\n return () => state.setHasHydrated(true)\n }\n }\n )\n);\n\nexport default function App() {\n const hasHydrated = useBoundStore(state => state._hasHydrated);\n\n if (!hasHydrated) {\n return

Loading...

\n }\n\n return (\n // ...\n );\n}\n```\n\nYou can also create a custom `useHydration` hook:\n\n```ts\nconst useBoundStore = create(persist(...))\n\nconst useHydration = () => {\n const [hydrated, setHydrated] = useState(false)\n\n useEffect(() => {\n // Note: This is just in case you want to take into account manual rehydration.\n // You can remove the following line if you don't need it.\n const unsubHydrate = useBoundStore.persist.onHydrate(() => setHydrated(false))\n\n const unsubFinishHydration = useBoundStore.persist.onFinishHydration(() => setHydrated(true))\n\n setHydrated(useBoundStore.persist.hasHydrated())\n\n return () => {\n unsubHydrate()\n unsubFinishHydration()\n }\n }, [])\n\n return hydrated\n}\n```\n\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"178","text":"### How can I use a custom storage engine\n\nIf the storage you want to use does not match the expected API, you can create your own storage:\n\n```ts\nimport { create } from 'zustand'\nimport { persist, createJSONStorage, StateStorage } from 'zustand/middleware'\nimport { get, set, del } from 'idb-keyval' // can use anything: IndexedDB, Ionic Storage, etc.\n\n// Custom storage object\nconst storage: StateStorage = {\n getItem: async (name: string): Promise => {\n console.log(name, 'has been retrieved')\n return (await get(name)) || null\n },\n setItem: async (name: string, value: string): Promise => {\n console.log(name, 'with value', value, 'has been saved')\n await set(name, value)\n },\n removeItem: async (name: string): Promise => {\n console.log(name, 'has been deleted')\n await del(name)\n },\n}\n\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"179","text":"export const useBoundStore = create(\n persist(\n (set, get) => ({\n bears: 0,\n addABear: () => set({ bears: get().bears + 1 }),\n }),\n {\n name: 'food-storage', // unique name\n storage: createJSONStorage(() => storage),\n },\n ),\n)\n```\n\nIf you're using a type that `JSON.stringify()` doesn't support, you'll need to write your own serialization/deserialization code. However, if this is tedious, you can use third-party libraries to serialize and deserialize different types of data.\n\nFor example, [Superjson](https://github.com/blitz-js/superjson) can serialize data along with its type, allowing the data to be parsed back to its original type upon deserialization\n\n```ts\nimport superjson from 'superjson' // can use anything: serialize-javascript, devalue, etc.\nimport { PersistStorage } from 'zustand/middleware'\n\ninterface BearState {\n bear: Map\n fish: Set\n time: Date\n query: RegExp\n}\n\nconst storage: PersistStorage = {\n getItem: (name) => {\n const str = localStorage.getItem(name)\n if (!str) return null\n return superjson.parse(str)\n },\n setItem: (name, value) => {\n localStorage.setItem(name, superjson.stringify(value))\n },\n removeItem: (name) => localStorage.removeItem(name),\n}\n\nconst initialState: BearState = {\n bear: new Map(),\n fish: new Set(),\n time: new Date(),\n query: new RegExp(''),\n}\n\nexport const useBearStore = create()(\n persist(\n (set) => ({\n ...initialState,\n // ...\n }),\n {\n name: 'food-storage',\n storage,\n },\n ),\n)\n```\n\n### How can I rehydrate on storage event\n\nYou can use the Persist API to create your own implementation,\nsimilar to the example below:\n\n```ts\ntype StoreWithPersist = Mutate, [[\"zustand/persist\", unknown]]>\n\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"180","text":"export const withStorageDOMEvents = (store: StoreWithPersist) => {\n const storageEventCallback = (e: StorageEvent) => {\n if (e.key === store.persist.getOptions().name && e.newValue) {\n store.persist.rehydrate()\n }\n }\n\n window.addEventListener('storage', storageEventCallback)\n\n return () => {\n window.removeEventListener('storage', storageEventCallback)\n }\n}\n\nconst useBoundStore = create(persist(...))\nwithStorageDOMEvents(useBoundStore)\n```\n\n### How do I use it with TypeScript\n\nBasic typescript usage doesn't require anything special\nexcept for writing `create()(...)` instead of `create(...)`.\n\n```tsx\nimport { create } from 'zustand'\nimport { persist, createJSONStorage } from 'zustand/middleware'\n\ninterface MyState {\n bears: number\n addABear: () => void\n}\n\nexport const useBearStore = create()(\n persist(\n (set, get) => ({\n bears: 0,\n addABear: () => set({ bears: get().bears + 1 }),\n }),\n {\n name: 'food-storage', // name of item in the storage (must be unique)\n storage: createJSONStorage(() => sessionStorage), // (optional) by default the 'localStorage' is used\n partialize: (state) => ({ bears: state.bears }),\n },\n ),\n)\n```\n\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"181","text":"### How do I use it with Map and Set\n\nIn order to persist object types such as `Map` and `Set`, they will need to be converted to JSON-serializable types such as an `Array` which can be done by defining a custom `storage` engine.\n\nLet's say your state uses `Map` to handle a list of `transactions`,\nthen you can convert the `Map` into an `Array` in the `storage` prop which is shown below:\n\n```ts\n\ninterface BearState {\n .\n .\n .\n transactions: Map\n}\n\n storage: {\n getItem: (name) => {\n const str = localStorage.getItem(name);\n if (!str) return null;\n const existingValue = JSON.parse(str);\n return {\n ...existingValue,\n state: {\n ...existingValue.state,\n transactions: new Map(existingValue.state.transactions),\n }\n }\n },\n setItem: (name, newValue: StorageValue) => {\n // functions cannot be JSON encoded\n const str = JSON.stringify({\n ...newValue,\n state: {\n ...newValue.state,\n transactions: Array.from(newValue.state.transactions.entries()),\n },\n })\n localStorage.setItem(name, str)\n },\n removeItem: (name) => localStorage.removeItem(name),\n },\n```\n","path":"docs/reference/integrations/persisting-store-data.md","title":"persisting-store-data.md","source_type":"doc","kind":"doc"} -{"id":"182","text":"---\ntitle: Third-party Libraries\nnav: 36\n---\n\nZustand provides bear necessities for state management.\nAlthough it is great for most projects,\nsome users wish to extend the library's feature set.\nThis can be done using third-party libraries created by the community.\n\n> Disclaimer: These libraries may have bugs, limited maintenance,\n> or other limitations, and are not officially recommended\n> by pmndrs or the Zustand maintainers.\n> This list aims to provide a good starting point\n> for someone looking to extend Zustand's feature set.\n\n- [@colorfy-software/zfy](https://colorfy-software.gitbook.io/zfy/) — 🧸 Useful helpers for state management in React with Zustand.\n- [@csark0812/zustand-expo-devtools](https://github.com/csark0812/zustand-expo-devtools) — 🧭 Connect Zustand to Redux DevTools in Expo + React Native using the official Expo DevTools plugin system.\n- [@csark0812/zustand-getters](https://github.com/csark0812/zustand-getters) — 🔄 Make JavaScript object getters reactive in Zustand stores — define derived values with `get propertyName()` and they automatically trigger subscription updates when accessed.\n- [@davstack/store](https://www.npmjs.com/package/@davstack/store) — A zustand store factory that auto generates selectors with get/set/use methods, supports inferred types, and makes global / local state management easy.\n- [@dhmk/zustand-lens](https://github.com/dhmk083/dhmk-zustand-lens) — Lens support for Zustand.\n- [@hpkv/zustand-multiplayer](https://github.com/hpkv-io/zustand-multiplayer/tree/main/packages/zustand-multiplayer) — HPKV multiplayer middleware for building realtime collaborative applications\n- [@liveblocks/zustand](https://github.com/liveblocks/liveblocks/tree/main/packages/liveblocks-zustand) — Liveblocks middleware to make your application multiplayer.\n- [@prncss-xyz/zustand-optics](https://github.com/prncss-xyz/zustand-optics) — An adapter for [optics-ts](https://github.com/akheron/optics-ts).\n- [auto-zustand-selectors-hook](https://github.com/Albert-Gao/auto-zustand-selectors-hook) — Automatic generation of Zustand hooks with Typescript support.\n- [derive-zustand](https://github.com/zustandjs/derive-zustand) — A function to create a derived Zustand store from other Zustand stores.\n- [geschichte](https://github.com/BowlingX/geschichte) — Zustand and Immer-based hook to manage query parameters.\n- [leiten-zustand](https://github.com/hecmatyar/leiten-zustand) — Cleans your store from boilerplate for requests and data transformation.\n- [leo-query](https://github.com/steaks/leo-query) — A simple library to connect async queries to Zustand stores.\n- [mobz](https://github.com/2A5F/Mobz) — Zustand-style MobX API.\n- [ngx-zustand](https://github.com/JoaoPauloLousada/ngx-zustand) — A Zustand adapter for Angular.\n- [persist-and-sync](https://github.com/mayank1513/persist-and-sync) — Zustand middleware to easily persist and sync Zustand state between tabs/windows/iframes with same origin.\n- [shared-zustand](https://github.com/Tom-Julux/shared-zustand) — Cross-tab state sharing for Zustand.\n- [simple-zustand-devtools](https://github.com/beerose/simple-zustand-devtools) — 🐻⚛️ Inspect your Zustand store in React DevTools.\n- [solid-zustand](https://github.com/wobsoriano/solid-zustand) — State management in Solid using Zustand.\n- [treeshakable](https://github.com/react18-tools/treeshakable) — A wrapper for library creators to avoid redundant store creation.\n- [use-broadcast-ts](https://github.com/Romainlg29/use-broadcast) — Zustand middleware to share state between tabs.\n- [use-post-message-ts](https://github.com/paulschoen/use-post-message) — Zustand middleware for sharing state between cross-origin iframes via postMessage browser method.\n- [use-zustand](https://github.com/zustandjs/use-zustand) — Another custom hook to use Zustand vanilla store.\n- [vue-zustand](https://github.com/wobsoriano/vue-zustand) — State management solution for Vue based on Zustand.\n- [zoov](https://github.com/InfiniteXyy/zoov) — State managem","path":"docs/reference/integrations/third-party-libraries.md","title":"third-party-libraries.md","source_type":"doc","kind":"doc"} -{"id":"183","text":"e-post-message) — Zustand middleware for sharing state between cross-origin iframes via postMessage browser method.\n- [use-zustand](https://github.com/zustandjs/use-zustand) — Another custom hook to use Zustand vanilla store.\n- [vue-zustand](https://github.com/wobsoriano/vue-zustand) — State management solution for Vue based on Zustand.\n- [zoov](https://github.com/InfiniteXyy/zoov) — State management solution based on Zustand with Module-like API.\n- [zubridge](https://github.com/goosewobbler/zubridge) — Use Zustand in cross-platform apps, seamlessly. Supports Electron & Tauri.\n- [zukeeper](https://github.com/oslabs-beta/Zukeeper) — Native devtools with state and action tracking, diffing, tree display, and time travel\n- [zundo](https://github.com/charkour/zundo) — 🍜 Undo and redo middleware for Zustand, enabling time-travel in your apps.\n- [zustand-ards](https://github.com/ivoilic/zustand-ards) — 💁 Simple opinionated utilities for example alternative selector formats and default shallow hooks\n- [zustand-async-slice](https://github.com/mym0404/zustand-async-slice) — Simple Zustand utility to create Async Slice. TypeScript Fully Supported 🖖\n- [zustand-boilerplate](https://github.com/sagiereder/zustand-boilerplate) — A tool that automatically generates getters, setters and more for your zustand store.\n- [zustand-computed](https://github.com/chrisvander/zustand-computed) — A Zustand middleware to create computed states.\n- [zustand-computed-state](https://github.com/yasintz/zustand-computed-state) — Simple middleware to add computed states.\n- [zustand-constate](https://github.com/ntvinhit/zustand-constate) — Context-based state management based on Zustand and taking ideas from Constate.\n- [zustand-context](https://github.com/fredericoo/zustand-context) — Create a zustand store in React Context, containing an initial value, or use it in your components with isolated, mockable instances.\n- [zustand-create-setter-fn](https://www.npmjs.com/package/zustand-create-setter-fn) — A fully type safe utility for Zustand that allows you to easily update state using React style `setState` functions (framework agnostic, doesn't require React).\n- [zustand-di](https://github.com/charkour/zustand-di) — use react props to init zustand stores\n- [zustand-forms](https://github.com/Conduct/zustand-forms) — Fast, type safe form states as Zustand stores.\n- [zustand-hash-storage](https://github.com/MartinGamesCZ/zustand-hash-storage) — Zustand middleware for saving state into URL hash, b64 encoded (can be configured) and debounce timer.\n- [zustand-injectors](https://github.com/zustandjs/zustand-injectors) — A sweet way to lazy load slices\n- [zustand-interval-persist](https://www.npmjs.com/package/zustand-interval-persist) — An enhancement for zustand that enables automatic saving of the store's state to the specified storage at regular interval.\n- [zustand-lit](https://github.com/ennjin/zustand-lit) — A zustand adapter for lit.js (LitElement)\n- [zustand-middleware-computed-state](https://github.com/cmlarsen/zustand-middleware-computed-state) — A dead simple middleware for adding computed state to Zustand.\n- [zustand-middleware-xstate](https://github.com/biowaffeln/zustand-middleware-xstate) — A middleware for putting XState state machines into a global Zustand store.\n- [zustand-middleware-yjs](https://github.com/joebobmiles/zustand-middleware-yjs) — A middleware for synchronizing Zustand stores with Yjs.\n- [zustand-mmkv-storage](https://github.com/1mehdifaraji/zustand-mmkv-storage) — Fast, lightweight MMKV storage adapter for Zustand persist middleware in React Native.\n- [zustand-multi-persist](https://github.com/mooalot/zustand-multi-persist) — A middleware for persisting and rehydrating state to multiple storage engines.\n- [zustand-mutable](https://github.com/zustandjs/zustand-mutable) — A sweet way to use immer-like mutable updates.\n- [zustand-namespaces](https://github.com/mooalot/zustand-namespaces) — One store to rule them all. Namespaced Zustand st","path":"docs/reference/integrations/third-party-libraries.md","title":"third-party-libraries.md","source_type":"doc","kind":"doc"} -{"id":"184","text":"ative.\n- [zustand-multi-persist](https://github.com/mooalot/zustand-multi-persist) — A middleware for persisting and rehydrating state to multiple storage engines.\n- [zustand-mutable](https://github.com/zustandjs/zustand-mutable) — A sweet way to use immer-like mutable updates.\n- [zustand-namespaces](https://github.com/mooalot/zustand-namespaces) — One store to rule them all. Namespaced Zustand stores.\n- [zustand-persist](https://github.com/roadmanfong/zustand-persist) — A middleware for persisting and rehydrating state.\n- [zustand-pub](https://github.com/AwesomeDevin/zustand-pub) — Cross-Application/Cross-Framework State Management And Sharing based on zustand and zustand-vue for React/Vue.\n- [zustand-querystring](https://github.com/nitedani/zustand-querystring) — A Zustand middleware that syncs the store with the querystring.\n- [zustand-rx](https://github.com/patdx/zustand-rx) — A Zustand middleware enabling you to subscribe to a store as an RxJS Observable.\n- [zustand-saga](https://github.com/Nowsta/zustand-saga) — A Zustand middleware for redux-saga (minus redux).\n- [zustand-slices](https://github.com/zustandjs/zustand-slices) — A slice utility for Zustand.\n- [zustand-store-addons](https://github.com/Diablow/zustand-store-addons) — React state management addons for Zustand.\n- [zustand-sync-tabs](https://github.com/mayank1513/zustand-sync-tabs) — Zustand middleware to easily sync Zustand state between tabs/windows/iframes with same origin.\n- [zustand-utils](https://www.npmjs.com/package/zustand-utils) — Utilities for Zustand — a `createContext` replacement, a devtools wrapper, and a store-updater factory function.\n- [zustand-valtio](https://github.com/zustandjs/zustand-valtio) — A sweet combination of Zustand and Valtio\n- [zustand-vue](https://github.com/AwesomeDevin/zustand-vue) — State management for vue (Vue3 / Vue2) based on zustand.\n- [zustand-x](https://github.com/udecode/zustand-x) — Zustand store factory for a best-in-class developer experience.\n- [zustand-xs](https://github.com/zustandjs/zustand-xs) — XState/store compabile middleware for Zustand\n- [zustand-yjs](https://github.com/tandem-pt/zustand-yjs) — Zustand stores for Yjs structures.\n- [zusteller](https://github.com/timkindberg/zusteller) — Your global state savior. \"Just hooks\" + Zustand.\n- [zustorm](https://github.com/mooalot/zustorm) — A simple and powerful form library for Zustand.\n- [zusty](https://github.com/oslabs-beta/Zusty) — Zustand tool to assist debugging with time travel, action logs, state snapshots, store view, render time metrics and state component tree.\n","path":"docs/reference/integrations/third-party-libraries.md","title":"third-party-libraries.md","source_type":"doc","kind":"doc"} -{"id":"185","text":"---\ntitle: combine\ndescription: How to create a store and get types automatically inferred\nnav: 32\n---\n\n# combine\n\n`combine` middleware lets you create a cohesive state by merging an initial state with a state\ncreator function that adds new state slices and actions. This is really helpful as it automatically\ninfers types, so there’s no need for explicit type definitions.\n\n> [!TIP]\n> This makes state management more straightforward and efficient by making curried version of\n> `create` and `createStore` not necessary for middleware usage.\n\n```js\nconst nextStateCreatorFn = combine(initialState, additionalStateCreatorFn)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n- [Reference](#reference)\n- [Usage](#usage)\n - [Creating a store with inferred types](#creating-a-store-with-inferred-types)\n- [Troubleshooting](#troubleshooting)\n\n## Types\n\n### Signature\n\n```ts\ncombine(initialState: T, additionalStateCreatorFn: StateCreator): StateCreator & U, [], []>\n```\n\n## Reference\n\n### `combine(initialState, additionalStateCreatorFn)`\n\n#### Parameters\n\n- `initialState`: The value you want the state to be initially. It can be a value of any type,\n except a function.\n- `additionalStateCreatorFn`: A function that takes `set` function, `get` function and `store` as\n arguments. Usually, you will return an object with the methods you want to expose.\n\n#### Returns\n\n`combine` returns a state creator function.\n\n## Usage\n\n","path":"docs/reference/middlewares/combine.md","title":"combine","source_type":"doc","kind":"doc"} -{"id":"186","text":"### Creating a store with inferred types\n\nThis example shows you how you can create a store and get types automatically inferred, so you\ndon’t need to define them explicitly.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { combine } from 'zustand/middleware'\n\nconst positionStore = createStore(\n combine({ position: { x: 0, y: 0 } }, (set) => ({\n setPosition: (position) => set({ position }),\n })),\n)\n\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getInitialState(), positionStore.getInitialState())\n\npositionStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n \n\n```\n\n## Troubleshooting\n\nTBD\n","path":"docs/reference/middlewares/combine.md","title":"combine","source_type":"doc","kind":"doc"} -{"id":"187","text":"---\ntitle: devtools\ndescription: How to time-travel debug your store\nnav: 29\n---\n\n# devtools\n\n`devtools` middleware lets you use [Redux DevTools Extension](https://github.com/reduxjs/redux-devtools)\nwithout Redux. Read more about the benefits of using [Redux DevTools for debugging](https://redux.js.org/style-guide/#use-the-redux-devtools-extension-for-debugging).\n\n> [!IMPORTANT]\n> In order to use `devtools` from `zustand/middleware` you need to install\n> `@redux-devtools/extension` library.\n\n```js\nconst nextStateCreatorFn = devtools(stateCreatorFn, devtoolsOptions)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n - [Mutator](#mutator)\n- [Reference](#reference)\n- [Usage](#usage)\n - [Debugging a store](#debugging-a-store)\n - [Debugging a Slices pattern based store](#debugging-a-slices-pattern-based-store)\n - [Filtering actions with actionsDenylist](#filtering-actions-with-actionsdenylist)\n - [Cleanup](#cleanup)\n- [Troubleshooting](#troubleshooting)\n - [Only one store is displayed](#only-one-store-is-displayed)\n - [Action names are labeled as 'anonymous'](#all-action-names-are-labeled-as-'anonymous')\n\n## Types\n\n### Signature\n\n```ts\ndevtools(stateCreatorFn: StateCreator, devtoolsOptions?: DevtoolsOptions): StateCreator\n```\n\n### Mutator\n\n```ts\n;['zustand/devtools', never]\n```\n\n## Reference\n\n### `devtools(stateCreatorFn, devtoolsOptions)`\n\n","path":"docs/reference/middlewares/devtools.md","title":"devtools","source_type":"doc","kind":"doc"} -{"id":"188","text":"#### Parameters\n\n- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.\n Usually, you will return an object with the methods you want to expose.\n- **optional** `devtoolsOptions`: An object to define `Redux Devtools` options.\n - **optional** `name`: A custom identifier for the connection in the Redux DevTools.\n - **optional** `enabled`: Defaults to `true` when is on development mode, and defaults to `false`\n when is on production mode. Enables or disables the Redux DevTools integration\n for this store.\n - **optional** `anonymousActionType`: Defaults to the inferred action type or `anonymous` if\n unavailable. A string to use as the action type for anonymous mutations in the Redux DevTools.\n - **optional** `store`: A custom identifier for the store in the Redux DevTools.\n - **optional** `actionsDenylist`: A string or array of strings (regex patterns) that specify which\n actions should be filtered out from Redux DevTools. This option is passed directly to Redux DevTools\n for filtering. For example, `['secret.*']` will filter out all actions starting with \"secret\".\n\n#### Returns\n\n`devtools` returns a state creator function.\n\n## Usage\n\n### Debugging a store\n\nThis example shows you how you can use `Redux Devtools` to debug a store\n\n```ts\nimport { create, StateCreator } from 'zustand'\nimport { devtools } from 'zustand/middleware'\n\ntype JungleStore = {\n bears: number\n addBear: () => void\n fishes: number\n addFish: () => void\n}\n\nconst useJungleStore = create()(\n devtools((set) => ({\n bears: 0,\n addBear: () =>\n set((state) => ({ bears: state.bears + 1 }), undefined, 'jungle/addBear'),\n fishes: 0,\n addFish: () =>\n set(\n (state) => ({ fishes: state.fishes + 1 }),\n undefined,\n 'jungle/addFish',\n ),\n })),\n)\n```\n\n","path":"docs/reference/middlewares/devtools.md","title":"devtools","source_type":"doc","kind":"doc"} -{"id":"189","text":"### Debugging a Slices pattern based store\n\nThis example shows you how you can use `Redux Devtools` to debug a Slices pattern based store\n\n```ts\nimport { create, StateCreator } from 'zustand'\nimport { devtools } from 'zustand/middleware'\n\ntype BearSlice = {\n bears: number\n addBear: () => void\n}\n\ntype FishSlice = {\n fishes: number\n addFish: () => void\n}\n\ntype JungleStore = BearSlice & FishSlice\n\nconst createBearSlice: StateCreator<\n JungleStore,\n [['zustand/devtools', never]],\n [],\n BearSlice\n> = (set) => ({\n bears: 0,\n addBear: () =>\n set(\n (state) => ({ bears: state.bears + 1 }),\n undefined,\n 'jungle:bear/addBear',\n ),\n})\n\nconst createFishSlice: StateCreator<\n JungleStore,\n [['zustand/devtools', never]],\n [],\n FishSlice\n> = (set) => ({\n fishes: 0,\n addFish: () =>\n set(\n (state) => ({ fishes: state.fishes + 1 }),\n undefined,\n 'jungle:fish/addFish',\n ),\n})\n\nconst useJungleStore = create()(\n devtools((...args) => ({\n ...createBearSlice(...args),\n ...createFishSlice(...args),\n })),\n)\n```\n\n","path":"docs/reference/middlewares/devtools.md","title":"devtools","source_type":"doc","kind":"doc"} -{"id":"190","text":"### Filtering actions with actionsDenylist\n\nYou can filter out specific actions from Redux DevTools using the `actionsDenylist` option. This is useful for hiding internal or sensitive actions from the DevTools timeline.\n\n```ts\nimport { create } from 'zustand'\nimport { devtools } from 'zustand/middleware'\n\ntype Store = {\n user: string | null\n token: string | null\n login: (user: string, token: string) => void\n logout: () => void\n updateData: () => void\n}\n\nconst useStore = create()(\n devtools(\n (set) => ({\n user: null,\n token: null,\n login: (user, token) => set({ user, token }, undefined, 'auth/login'),\n logout: () => set({ user: null, token: null }, undefined, 'auth/logout'),\n updateData: () =>\n set({ user: 'updated' }, undefined, 'internal/updateData'),\n }),\n {\n name: 'AuthStore',\n // Filter out actions matching these regex patterns\n actionsDenylist: ['internal/.*'], // Hides all 'internal/*' actions\n },\n ),\n)\n```\n\nYou can also use a single regex string:\n\n```ts\nconst useStore = create()(\n devtools(\n (set) => ({\n // ... state and actions\n }),\n {\n name: 'MyStore',\n actionsDenylist: 'secret.*', // Hides all actions starting with 'secret'\n },\n ),\n)\n```\n\n> [!NOTE]\n> The `actionsDenylist` option uses regex pattern matching and is handled directly by Redux DevTools Extension.\n> All actions are still sent to DevTools, but matching actions are filtered from the display.\n\n","path":"docs/reference/middlewares/devtools.md","title":"devtools","source_type":"doc","kind":"doc"} -{"id":"191","text":"### Cleanup\n\nWhen a store is no longer needed, you can clean up the Redux DevTools connection by calling the `cleanup` method on the store:\n\n```ts\nimport { create } from 'zustand'\nimport { devtools } from 'zustand/middleware'\n\nconst useStore = create(\n devtools((set) => ({\n count: 0,\n increment: () => set((state) => ({ count: state.count + 1 })),\n })),\n)\n\n// When you're done with the store, clean it up\nuseStore.devtools.cleanup()\n```\n\nThis is particularly useful in applications that wrap store in context or create multiple stores dynamically.\n\n## Troubleshooting\n\n### Only one store is displayed\n\nBy default, `Redux Devtools` only show one store at a time, so in order to see other stores you\nneed to use store selector and choose a different store.\n\n","path":"docs/reference/middlewares/devtools.md","title":"devtools","source_type":"doc","kind":"doc"} -{"id":"192","text":"### All action names are labeled as 'anonymous'\n\nIf an action type name is not provided, it is defaulted to \"anonymous\". You can customize this\ndefault value by providing a `anonymousActionType` parameter:\n\nFor instance the next example doesn't have action type name:\n\n```ts\nimport { create, StateCreator } from 'zustand'\nimport { devtools } from 'zustand/middleware'\n\ntype BearSlice = {\n bears: number\n addBear: () => void\n}\n\ntype FishSlice = {\n fishes: number\n addFish: () => void\n}\n\ntype JungleStore = BearSlice & FishSlice\n\nconst createBearSlice: StateCreator<\n JungleStore,\n [['zustand/devtools', never]],\n [],\n BearSlice\n> = (set) => ({\n bears: 0,\n addBear: () => set((state) => ({ bears: state.bears + 1 })),\n eatFish: () => set((state) => ({ fishes: state.fishes - 1 })),\n})\n\nconst createFishSlice: StateCreator<\n JungleStore,\n [['zustand/devtools', never]],\n [],\n FishSlice\n> = (set) => ({\n fishes: 0,\n addFish: () => set((state) => ({ fishes: state.fishes + 1 })),\n})\n\nconst useJungleStore = create()(\n devtools((...args) => ({\n ...createBearSlice(...args),\n ...createFishSlice(...args),\n })),\n)\n```\n\nIn order to fix the previous example, we need to provide an action type name as the third parameter.\nAdditionally, to preserve the default behavior of the replacement logic, the second parameter\nshould be set to `undefined`.\n\nHere's the fixed previous example\n\n```ts\nimport { create, StateCreator } from 'zustand'\nimport { devtools } from 'zustand/middleware'\n\ntype BearSlice = {\n bears: number\n addBear: () => void\n}\n\ntype FishSlice = {\n fishes: number\n addFish: () => void\n}\n\ntype JungleStore = BearSlice & FishSlice\n\nconst createBearSlice: StateCreator<\n JungleStore,\n [['zustand/devtools', never]],\n [],\n BearSlice\n> = (set) => ({\n bears: 0,\n addBear: () =>\n set((state) => ({ bears: state.bears + 1 }), undefined, 'bear/addBear'),\n})\n\nconst createFishSlice: StateCreator<\n JungleStore,\n [['zustand/devtools', never]],\n [],\n FishSlice\n> = (set) => ({\n fishes: 0,\n addFish: () =>\n set((state) => ({ fishes: state.fishes + 1 }), undefined, 'fish/addFish'),\n})\n\nconst useJungleStore = create()(\n devtools((...args) => ({\n ...createBearSlice(...args),\n ...createFishSlice(...args),\n })),\n)\n```\n\n> [!IMPORTANT]\n> Do not set the second parameter to `true` or `false` unless you want to override the default\n> replacement logic\n","path":"docs/reference/middlewares/devtools.md","title":"devtools","source_type":"doc","kind":"doc"} -{"id":"193","text":"---\ntitle: immer\ndescription: How to perform immutable updates in a store without boilerplate code\nnav: 31\n---\n\n# immer\n\n`immer` middleware lets you perform immutable updates.\n\n> [!IMPORTANT]\n> In order to use `immer` from `zustand/middleware/immer` you need to install\n> `immer` library.\n\n```js\nconst nextStateCreatorFn = immer(stateCreatorFn)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n - [Mutator](#mutator)\n- [Reference](#reference)\n- [Usage](#usage)\n- [Troubleshooting](#troubleshooting)\n\n## Types\n\n### Signature\n\n```ts\nimmer(stateCreatorFn: StateCreator): StateCreator\n```\n\n### Mutator\n\n```ts\n;['zustand/immer', never]\n```\n\n## Reference\n\n### `immer(stateCreatorFn)`\n\n#### Parameters\n\n- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.\n Usually, you will return an object with the methods you want to expose.\n\n#### Returns\n\n`immer` returns a state creator function.\n\n## Usage\n\n","path":"docs/reference/middlewares/immer.md","title":"immer","source_type":"doc","kind":"doc"} -{"id":"194","text":"### Updating state without boilerplate code\n\nIn the next example, we're going to update the `person` object. Since it's a nested object, we need\nto create a copy of the entire object before making the update.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\n\ntype PersonStoreState = {\n person: { firstName: string; lastName: string; email: string }\n}\n\ntype PersonStoreActions = {\n setPerson: (\n nextPerson:\n | PersonStoreState['person']\n | ((person: PersonStoreState['person']) => PersonStoreState['person']),\n ) => void\n}\n\ntype PersonStore = PersonStoreState & PersonStoreActions\n\nconst personStore = createStore()((set) => ({\n person: {\n firstName: 'Barbara',\n lastName: 'Hepworth',\n email: 'bhepworth@sculpture.com',\n },\n setPerson: (nextPerson) =>\n set((state) => ({\n person:\n typeof nextPerson === 'function'\n ? nextPerson(state.person)\n : nextPerson,\n })),\n}))\n\nconst $firstNameInput = document.getElementById(\n 'first-name',\n) as HTMLInputElement\nconst $lastNameInput = document.getElementById('last-name') as HTMLInputElement\nconst $emailInput = document.getElementById('email') as HTMLInputElement\nconst $result = document.getElementById('result') as HTMLDivElement\n\nfunction handleFirstNameChange(event: Event) {\n personStore.getState().setPerson((person) => ({\n ...person,\n firstName: (event.target as any).value,\n }))\n}\n\nfunction handleLastNameChange(event: Event) {\n personStore.getState().setPerson((person) => ({\n ...person,\n lastName: (event.target as any).value,\n }))\n}\n\n","path":"docs/reference/middlewares/immer.md","title":"immer","source_type":"doc","kind":"doc"} -{"id":"195","text":"function handleEmailChange(event: Event) {\n personStore.getState().setPerson((person) => ({\n ...person,\n email: (event.target as any).value,\n }))\n}\n\n$firstNameInput.addEventListener('input', handleFirstNameChange)\n$lastNameInput.addEventListener('input', handleLastNameChange)\n$emailInput.addEventListener('input', handleEmailChange)\n\nconst render: Parameters[0] = (state) => {\n $firstNameInput.value = state.person.firstName\n $lastNameInput.value = state.person.lastName\n $emailInput.value = state.person.email\n\n $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`\n}\n\nrender(personStore.getInitialState(), personStore.getInitialState())\n\npersonStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n\n\n

\n```\n\nTo avoid manually copying the entire object before making updates, we'll use the `immer`\nmiddleware.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { immer } from 'zustand/middleware/immer'\n\ntype PersonStoreState = {\n person: { firstName: string; lastName: string; email: string }\n}\n\ntype PersonStoreActions = {\n setPerson: (\n nextPerson:\n | PersonStoreState['person']\n | ((person: PersonStoreState['person']) => PersonStoreState['person']),\n ) => void\n}\n\ntype PersonStore = PersonStoreState & PersonStoreActions\n\nconst personStore = createStore()(\n immer((set) => ({\n person: {\n firstName: 'Barbara',\n lastName: 'Hepworth',\n email: 'bhepworth@sculpture.com',\n },\n setPerson: (nextPerson) =>\n set((state) => {\n state.person =\n typeof nextPerson === 'function'\n ? nextPerson(state.person)\n : nextPerson\n }),\n })),\n)\n\nconst $firstNameInput = document.getElementById(\n 'first-name',\n) as HTMLInputElement\nconst $lastNameInput = document.getElementById('last-name') as HTMLInputElement\nconst $emailInput = document.getElementById('email') as HTMLInputElement\nconst $result = document.getElementById('result') as HTMLDivElement\n\n","path":"docs/reference/middlewares/immer.md","title":"immer","source_type":"doc","kind":"doc"} -{"id":"196","text":"function handleFirstNameChange(event: Event) {\n personStore.getState().setPerson((person) => {\n person.firstName = (event.target as any).value\n })\n}\n\nfunction handleLastNameChange(event: Event) {\n personStore.getState().setPerson((person) => {\n person.lastName = (event.target as any).value\n })\n}\n\nfunction handleEmailChange(event: Event) {\n personStore.getState().setPerson((person) => {\n person.email = (event.target as any).value\n })\n}\n\n$firstNameInput.addEventListener('input', handleFirstNameChange)\n$lastNameInput.addEventListener('input', handleLastNameChange)\n$emailInput.addEventListener('input', handleEmailChange)\n\nconst render: Parameters[0] = (state) => {\n $firstNameInput.value = state.person.firstName\n $lastNameInput.value = state.person.lastName\n $emailInput.value = state.person.email\n\n $result.innerHTML = `${state.person.firstName} ${state.person.lastName} (${state.person.email})`\n}\n\nrender(personStore.getInitialState(), personStore.getInitialState())\n\npersonStore.subscribe(render)\n```\n\n## Troubleshooting\n\nTBD\n","path":"docs/reference/middlewares/immer.md","title":"immer","source_type":"doc","kind":"doc"} -{"id":"197","text":"---\ntitle: persist\ndescription: How to persist a store\nnav: 28\n---\n\n# persist\n\n`persist` middleware lets you persist a store's state across page reloads or application\nrestarts.\n\n```js\nconst nextStateCreatorFn = persist(stateCreatorFn, persistOptions)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n - [Mutator](#mutator)\n- [Reference](#reference)\n- [Usage](#usage)\n - [Persisting a state](#persisting-a-state)\n - [Persisting a state partially](#persisting-a-state-partially)\n - [Persisting a state with custom storage](#persisting-a-state-with-custom-storage)\n - [Persisting a state through versioning and migrations](#persisting-a-state-through-versioning-and-migrations)\n - [Persisting a state with nested objects](#persisting-a-state-with-nested-objects)\n - [Persisting a state and hydrate it manually](#persisting-a-state-and-hydrate-it-manually)\n- [Troubleshooting](#troubleshooting)\n\n## Types\n\n### Signature\n\n```ts\npersist(stateCreatorFn: StateCreator, persistOptions: PersistOptions): StateCreator\n```\n\n### Mutator\n\n```ts\n;['zustand/persist', U]\n```\n\n## Reference\n\n### `persist(stateCreatorFn, persistOptions)`\n\n","path":"docs/reference/middlewares/persist.md","title":"persist","source_type":"doc","kind":"doc"} -{"id":"198","text":"#### Parameters\n\n- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.\n Usually, you will return an object with the methods you want to expose.\n- `persistOptions`: An object to define storage options.\n - `name`: A unique name of the item for your store in the storage.\n - **optional** `storage`: Defaults to `createJSONStorage(() => localStorage)`.\n - **optional** `partialize`: A function to filter state fields before persisting it.\n - **optional** `onRehydrateStorage`: A function or function returning a function that allows\n custom logic before and after state rehydration.\n - **optional** `version`: A version number for the persisted state. If the stored state version\n doesn't match, it won't be used.\n - **optional** `migrate`: A function to migrate persisted state if the version mismatch occurs.\n - **optional** `merge`: A function for custom logic when merging persisted state with the current\n state during rehydration. Defaults to a shallow merge.\n - **optional** `skipHydration`: Defaults to `false`. If `true`, the middleware won't\n automatically rehydrate the state on initialization. Use `rehydrate` function manually in this\n case. This is useful for server-side rendering (SSR) applications.\n\n#### Returns\n\n`persist` returns a state creator function.\n\n## Usage\n\n","path":"docs/reference/middlewares/persist.md","title":"persist","source_type":"doc","kind":"doc"} -{"id":"199","text":"### Persisting a state\n\nIn this tutorial, we'll create a simple position tracker using vanilla store and the `persist`\nmiddleware. The example tracks the `position` of the mouse as it moves within a container and\nstores the `position` in local storage, so it persists even when the page reloads.\n\nWe start by setting up a vanilla store that holds the position (an object with `x` and `y`\ncoordinates) and an action to update it. We'll also use the `persist` middleware to store the\nposition in `localStorage`.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { persist } from 'zustand/middleware'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()(\n persist(\n (set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }),\n { name: 'position-storage' },\n ),\n)\n```\n\nNext, we'll track the mouse movements inside a div and update the store with the new position.\n\n```ts\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n```\n\nWe want to reflect the position updates on the screen by moving a div element\n(representing the dot) to the new coordinates.\n\n```ts\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere’s the complete code.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { persist } from 'zustand/middleware'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()(\n persist(\n (set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }),\n { name: 'position-storage' },\n ),\n)\n\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n \n\n```\n\n","path":"docs/reference/middlewares/persist.md","title":"persist","source_type":"doc","kind":"doc"} -{"id":"200","text":"### Persisting a state partially\n\nIn this tutorial, we'll create a simple position tracker using vanilla store and the `persist`\nmiddleware. Additionally, we'll show you how to persist only part of the state\n(partial persistence), which can be useful when you don’t want to store the entire state in\n`localStorage`.\n\nWe’ll first create a vanilla store that holds the position state and actions to update it. We'll\nuse the `persist` middleware to persist only the relevant part of the state (in this case, the\ncontext containing the position).\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { persist } from 'zustand/middleware'\n\ntype PositionStoreState = {\n context: {\n position: { x: number; y: number }\n }\n}\n\ntype PositionStoreActions = {\n actions: {\n setPosition: (\n nextPosition: PositionStoreState['context']['position'],\n ) => void\n }\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()(\n persist(\n (set) => ({\n context: {\n position: { x: 0, y: 0 },\n },\n actions: {\n setPosition: (position) => set({ context: { position } }),\n },\n }),\n {\n name: 'position-storage',\n partialize: (state) => ({ context: state.context }),\n },\n ),\n)\n```\n\nNext, we'll track the mouse movements inside a div and update the store with the new position.\n\n```ts\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().actions.setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n```\n\nWe want to reflect the position updates on the screen by moving a div element\n(representing the dot) to the new coordinates.\n\n```ts\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.context.position.x}px, ${state.context.position.y}px)`\n}\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere’s the full code to create a dot that follows your mouse movement inside a container and\npersists the `context` in `localStorage`.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { persist } from 'zustand/middleware'\n\ntype PositionStoreState = {\n context: {\n position: { x: number; y: number }\n }\n}\n\ntype PositionStoreActions = {\n actions: {\n setPosition: (\n nextPosition: PositionStoreState['context']['position'],\n ) => void\n }\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()(\n persist(\n (set) => ({\n context: {\n position: { x: 0, y: 0 },\n },\n actions: {\n setPosition: (position) => set({ context: { position } }),\n },\n }),\n {\n name: 'position-storage',\n partialize: (state) => ({ context: state.context }),\n },\n ),\n)\n\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().actions.setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.context.position.x}px, ${state.context.position.y}px)`\n}\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n \n\n```\n\n","path":"docs/reference/middlewares/persist.md","title":"persist","source_type":"doc","kind":"doc"} -{"id":"201","text":"### Persisting a state with custom storage\n\nIn this mini tutorial, we’ll create a simple position-tracking system using vanilla store, where\nthe position state is persisted in the URL's search parameters. This approach allows state\npersistence directly in the browser's URL, which can be useful for maintaining state across page\nreloads or sharing links with state embedded.\n\nWe need to implement functions to manipulate URL search parameters as if they were a storage\nmechanism. This includes retrieving, setting, and removing parameters.\n\n```ts\nconst getSearchParams = () => {\n return new URL(location.href).searchParams\n}\n\nconst updateSearchParams = (searchParams: URLSearchParams) => {\n window.history.replaceState(\n {},\n '',\n `${location.pathname}?${searchParams.toString()}`,\n )\n}\n\nconst getSearchParam = (key: string) => {\n const searchParams = getSearchParams()\n return searchParams.get(key)\n}\n\nconst updateSearchParam = (key: string, value: string) => {\n const searchParams = getSearchParams()\n searchParams.set(key, value)\n\n updateSearchParams(searchParams)\n}\n\nconst removeSearchParam = (key: string) => {\n const searchParams = getSearchParams()\n searchParams.delete(key)\n\n updateSearchParams(searchParams)\n}\n```\n\nTo use the URL search parameters as storage, we define a `searchParamsStorage` object with\n`getItem`, `setItem`, and `removeItem` methods. These methods map to our custom functions that\nmanipulate search parameters.\n\n```ts\nconst searchParamsStorage = {\n getItem: (key: string) => getSearchParam(key),\n setItem: (key: string, value: string) => updateSearchParam(key, value),\n removeItem: (key: string) => removeSearchParam(key),\n}\n```\n\nNow, we initialize the vanilla store using the `persist` middleware, specifying that we want to use\nour custom storage. Instead of the default `localStorage` or `sessionStorage`, we’ll persist the\nposition data in the URL search parameters.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { persist, createJSONStorage } from 'zustand/middleware'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()(\n persist(\n (set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }),\n {\n name: 'position-storage',\n storage: createJSONStorage(() => searchParamsStorage),\n },\n ),\n)\n```\n\nNext, we'll track the mouse movements inside a div and update the store with the new position.\n\n```ts\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n```\n\nWe want to reflect the position updates on the screen by moving a div element\n(representing the dot) to the new coordinates.\n\n```ts\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere’s the full code to create a dot that follows your mouse movement inside a container and\npersists the position in URL's search parameters.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { persist, createJSONStorage } from 'zustand/middleware'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst getSearchParams = () => {\n return new URL(location.href).searchParams\n}","path":"docs/reference/middlewares/persist.md","title":"persist","source_type":"doc","kind":"doc"} -{"id":"202","text":" from 'zustand/vanilla'\nimport { persist, createJSONStorage } from 'zustand/middleware'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst getSearchParams = () => {\n return new URL(location.href).searchParams\n}\n\nconst updateSearchParams = (searchParams: URLSearchParams) => {\n window.history.replaceState(\n {},\n '',\n `${location.pathname}?${searchParams.toString()}`,\n )\n}\n\nconst getSearchParam = (key: string) => {\n const searchParams = getSearchParams()\n return searchParams.get(key)\n}\n\nconst updateSearchParam = (key: string, value: string) => {\n const searchParams = getSearchParams()\n searchParams.set(key, value)\n\n updateSearchParams(searchParams)\n}\n\nconst removeSearchParam = (key: string) => {\n const searchParams = getSearchParams()\n searchParams.delete(key)\n\n updateSearchParams(searchParams)\n}\n\nconst searchParamsStorage = {\n getItem: (key: string) => getSearchParam(key),\n setItem: (key: string, value: string) => updateSearchParam(key, value),\n removeItem: (key: string) => removeSearchParam(key),\n}\n\nconst positionStore = createStore()(\n persist(\n (set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }),\n {\n name: 'position-storage',\n storage: createJSONStorage(() => searchParamsStorage),\n },\n ),\n)\n\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n \n\n```\n\n","path":"docs/reference/middlewares/persist.md","title":"persist","source_type":"doc","kind":"doc"} -{"id":"203","text":"### Persisting a state through versioning and migrations\n\nIn this tutorial, we’ll explore how to manage state persistence using versioning and migration.\nWe will demonstrate how to evolve your state schema across versions without breaking existing\npersisted data.\n\nBefore moving to versioned state management, we simulate an initial state for `version` 0. This is\ndone by manually setting a `version` 0 state in `localStorage` if it doesn't already exist. The\n`version` 0 state saves the coordinates as `x` and `y` fields.\n\n```ts\n// For tutorial purposes only\nif (!localStorage.getItem('position-storage')) {\n localStorage.setItem(\n 'position-storage',\n JSON.stringify({\n state: { x: 100, y: 100 }, // version 0 structure\n version: 0,\n }),\n )\n}\n```\n\nNext, we use `persist` middleware to handle state persistence. We also add a migration function to\nhandle changes between versions. In this example, we `migrate` the state from `version` 0 (where\n`x` and `y` are separate) to `version` 1, where they are combined into a `position` object.\n\n```ts\nmigrate: (persisted: any, version) => {\n if (version === 0) {\n persisted.position = { x: persisted.x, y: persisted.y }\n delete persisted.x\n delete persisted.y\n }\n\n return persisted\n}\n```\n\nNext, we'll track the mouse movements inside a div and update the store with the new position.\n\n```ts\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n```\n\nWe want to reflect the position updates on the screen by moving a div element\n(representing the dot) to the new coordinates.\n\n```ts\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere’s the complete code.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { persist } from 'zustand/middleware'\n\n// For tutorial purposes only\nif (!localStorage.getItem('position-storage')) {\n localStorage.setItem(\n 'position-storage',\n JSON.stringify({\n state: { x: 100, y: 100 },\n version: 0,\n }),\n )\n}\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()(\n persist(\n (set) => ({\n position: { x: 0, y: 0 }, // version 0: just x: 0, y: 0\n setPosition: (position) => set({ position }),\n }),\n {\n name: 'position-storage',\n version: 1,\n migrate: (persisted: any, version) => {\n if (version === 0) {\n persisted.position = { x: persisted.x, y: persisted.y }\n delete persisted.x\n delete persisted.y\n }\n\n return persisted\n },\n },\n ),\n)\n\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n \n\n```\n\n","path":"docs/reference/middlewares/persist.md","title":"persist","source_type":"doc","kind":"doc"} -{"id":"204","text":"### Persisting a state with nested objects\n\nIn this tutorial, we’ll create a vanilla store that keeps track of a position represented by `x`\nand `y` coordinates. We will also implement persistence using `localStorage` and demonstrate how to\nhandle merging of state with potentially missing fields.\n\nTo simulate an initial state for the tutorial, we will check if our position data exists in\n`localStorage`. If it doesn't, we’ll set it up.\n\n```ts\nif (!localStorage.getItem('position-storage')) {\n localStorage.setItem(\n 'position-storage',\n JSON.stringify({\n state: { position: { y: 100 } }, // missing `x` field\n version: 0,\n }),\n )\n}\n```\n\nNow, we will create the store and configure it to use persistence and deep merging.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { persist } from 'zustand/middleware'\nimport createDeepMerge from '@fastify/deepmerge'\n\nconst deepMerge = createDeepMerge({ all: true })\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()(\n persist(\n (set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }),\n {\n name: 'position-storage',\n merge: (persisted, current) => deepMerge(current, persisted) as never,\n },\n ),\n)\n```\n\nNext, we'll track the mouse movements inside a div and update the store with the new position.\n\n```ts\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n```\n\nWe want to reflect the position updates on the screen by moving a div element\n(representing the dot) to the new coordinates.\n\n```ts\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere’s the complete code.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { persist } from 'zustand/middleware'\nimport createDeepMerge from '@fastify/deepmerge'\n\nconst deepMerge = createDeepMerge({ all: true })\n\n// For tutorial purposes only\nif (!localStorage.getItem('position-storage')) {\n localStorage.setItem(\n 'position-storage',\n JSON.stringify({\n state: { position: { y: 100 } }, // missing `x` field\n version: 0,\n }),\n )\n}\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()(\n persist(\n (set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }),\n {\n name: 'position-storage',\n merge: (persisted, current) => deepMerge(current, persisted) as never,\n },\n ),\n)\n\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n\nconst render: Parameters[0] = (state) => {\n console.log({ state })\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere's the `html` code","path":"docs/reference/middlewares/persist.md","title":"persist","source_type":"doc","kind":"doc"} -{"id":"205","text":"\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n\nconst render: Parameters[0] = (state) => {\n console.log({ state })\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n \n\n```\n\n","path":"docs/reference/middlewares/persist.md","title":"persist","source_type":"doc","kind":"doc"} -{"id":"206","text":"### Persisting a state and hydrate it manually\n\nIn this tutorial, we’ll create a vanilla store that keeps track of a position represented by `x`\nand `y` coordinates. We will also implement persistence using `localStorage` and explore how to\nskip the hydration process and manually trigger rehydration after a delay.\n\nWe start by setting up a vanilla store that holds the position (an object with `x` and `y`\ncoordinates) and an action to update it. Furthermore, we'll also use the `persist` middleware to\nstore the position in `localStorage` but skipping hydration.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { persist } from 'zustand/middleware'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()(\n persist(\n (set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }),\n {\n name: 'position-storage',\n skipHydration: true,\n },\n ),\n)\n```\n\nSince we skipped hydration in the initial setup, we will manually rehydrate the state. Here, we’re\nusing `setTimeout` to simulate a delayed rehydration.\n\n```ts\nsetTimeout(() => {\n positionStore.persist.rehydrate()\n}, 2000)\n```\n\nNext, we'll track the mouse movements inside a div and update the store with the new position.\n\n```ts\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n```\n\nWe want to reflect the position updates on the screen by moving a div element\n(representing the dot) to the new coordinates.\n\n```ts\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere’s the complete code.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { persist } from 'zustand/middleware'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()(\n persist(\n (set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n }),\n {\n name: 'position-storage',\n skipHydration: true,\n },\n ),\n)\n\nconst $dotContainer = document.getElementById('dot-container') as HTMLDivElement\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dotContainer.addEventListener('pointermove', (event) => {\n positionStore.getState().setPosition({\n x: event.clientX,\n y: event.clientY,\n })\n})\n\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nsetTimeout(() => {\n positionStore.persist.rehydrate()\n}, 2000)\n\nrender(positionStore.getState(), positionStore.getState())\n\npositionStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n \n\n```\n\n","path":"docs/reference/middlewares/persist.md","title":"persist","source_type":"doc","kind":"doc"} -{"id":"207","text":"## Troubleshooting\n\nTBD\n","path":"docs/reference/middlewares/persist.md","title":"persist","source_type":"doc","kind":"doc"} -{"id":"208","text":"---\ntitle: redux\ndescription: How to use actions and reducers in a store\nnav: 30\n---\n\n# redux\n\n`redux` middleware lets you update a store through actions and reducers just like redux.\n\n```js\nconst nextStateCreatorFn = redux(reducerFn, initialState)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n - [Mutator](#mutator)\n- [Reference](#reference)\n- [Usage](#usage)\n - [Updating state through actions and reducers](#updating-state-through-actions-and-reducers)\n- [Troubleshooting](#troubleshooting)\n\n## Types\n\n### Signature\n\n```ts\nredux(reducerFn: (state: T, action: A) => T, initialState: T): StateCreator A }, [['zustand/redux', A]], []>\n```\n\n### Mutator\n\n```ts\n;['zustand/redux', A]\n```\n\n## Reference\n\n### `redux(reducerFn, initialState)`\n\n#### Parameters\n\n- `reducerFn`: It should be pure and should take the current state of your application and an action\n object as arguments, and returns the new state resulting from applying the action.\n- `initialState`: The value you want the state to be initially. It can be a value of any type,\n except a function.\n\n#### Returns\n\n`redux` returns a state creator function.\n\n## Usage\n\n","path":"docs/reference/middlewares/redux.md","title":"redux","source_type":"doc","kind":"doc"} -{"id":"209","text":"### Updating state through actions and reducers\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { redux } from 'zustand/middleware'\n\ntype PersonStoreState = {\n firstName: string\n lastName: string\n email: string\n}\n\ntype PersonStoreAction =\n | { type: 'person/setFirstName'; firstName: string }\n | { type: 'person/setLastName'; lastName: string }\n | { type: 'person/setEmail'; email: string }\n\ntype PersonStore = PersonStoreState & {\n dispatch: (action: PersonStoreAction) => PersonStoreAction\n}\n\nconst personStoreReducer = (\n state: PersonStoreState,\n action: PersonStoreAction,\n) => {\n switch (action.type) {\n case 'person/setFirstName': {\n return { ...state, firstName: action.firstName }\n }\n case 'person/setLastName': {\n return { ...state, lastName: action.lastName }\n }\n case 'person/setEmail': {\n return { ...state, email: action.email }\n }\n default: {\n return state\n }\n }\n}\n\nconst personStoreInitialState: PersonStoreState = {\n firstName: 'Barbara',\n lastName: 'Hepworth',\n email: 'bhepworth@sculpture.com',\n}\n\nconst personStore = createStore()(\n redux(personStoreReducer, personStoreInitialState),\n)\n\nconst $firstNameInput = document.getElementById(\n 'first-name',\n) as HTMLInputElement\nconst $lastNameInput = document.getElementById('last-name') as HTMLInputElement\nconst $emailInput = document.getElementById('email') as HTMLInputElement\nconst $result = document.getElementById('result') as HTMLDivElement\n\nfunction handleFirstNameChange(event: Event) {\n personStore.dispatch({\n type: 'person/setFirstName',\n firstName: (event.target as any).value,\n })\n}\n\nfunction handleLastNameChange(event: Event) {\n personStore.dispatch({\n type: 'person/setLastName',\n lastName: (event.target as any).value,\n })\n}\n\n","path":"docs/reference/middlewares/redux.md","title":"redux","source_type":"doc","kind":"doc"} -{"id":"210","text":"function handleEmailChange(event: Event) {\n personStore.dispatch({\n type: 'person/setEmail',\n email: (event.target as any).value,\n })\n}\n\n$firstNameInput.addEventListener('input', handleFirstNameChange)\n$lastNameInput.addEventListener('input', handleLastNameChange)\n$emailInput.addEventListener('input', handleEmailChange)\n\nconst render: Parameters[0] = (person) => {\n $firstNameInput.value = person.firstName\n $lastNameInput.value = person.lastName\n $emailInput.value = person.email\n\n $result.innerHTML = `${person.firstName} ${person.lastName} (${person.email})`\n}\n\nrender(personStore.getInitialState(), personStore.getInitialState())\n\npersonStore.subscribe(render)\n```\n\nHere's the `html` code\n\n```html\n\n\n\n

\n```\n\n## Troubleshooting\n\nTBD\n","path":"docs/reference/middlewares/redux.md","title":"redux","source_type":"doc","kind":"doc"} -{"id":"211","text":"---\ntitle: subscribeWithSelector\ndescription: How to subscribe to granular store updates in a store\nnav: 33\n---\n\n# subscribeWithSelector\n\n`subscribeWithSelector` middleware lets you subscribe to specific data based on current state.\n\n```js\nconst nextStateCreatorFn = subscribeWithSelector(stateCreatorFn)\n```\n\n- [Types](#types)\n - [Signature](#signature)\n - [Mutator](#mutator)\n- [Reference](#reference)\n- [Usage](#usage)\n- [Troubleshooting](#troubleshooting)\n\n## Types\n\n### Signature\n\n```ts\nsubscribeWithSelector(stateCreatorFn: StateCreator): StateCreator\n```\n\n### Mutator\n\n```ts\n;['zustand/subscribeWithSelector', never]\n```\n\n## Reference\n\n### `subscribeWithSelector(stateCreatorFn)`\n\n#### Parameters\n\n- `stateCreatorFn`: A function that takes `set` function, `get` function and `store` as arguments.\n Usually, you will return an object with the methods you want to expose.\n\n#### Returns\n\n`subscribeWithSelector` returns a state creator function.\n\n## Usage\n\n","path":"docs/reference/middlewares/subscribe-with-selector.md","title":"subscribeWithSelector","source_type":"doc","kind":"doc"} -{"id":"212","text":"### Subscribing partial state updates\n\nBy subscribing to partial state updates, you register a callback that fires whenever the store's\npartial state updates. We can use `subscribe` for external state management.\n\n```ts\nimport { createStore } from 'zustand/vanilla'\nimport { subscribeWithSelector } from 'zustand/middleware'\n\ntype PositionStoreState = { position: { x: number; y: number } }\n\ntype PositionStoreActions = {\n setPosition: (nextPosition: PositionStoreState['position']) => void\n}\n\ntype PositionStore = PositionStoreState & PositionStoreActions\n\nconst positionStore = createStore()(\n subscribeWithSelector((set) => ({\n position: { x: 0, y: 0 },\n setPosition: (position) => set({ position }),\n })),\n)\n\nconst $dot = document.getElementById('dot') as HTMLDivElement\n\n$dot.addEventListener('mouseenter', (event) => {\n const parent = event.currentTarget.parentElement\n const parentWidth = parent.clientWidth\n const parentHeight = parent.clientHeight\n\n positionStore.getState().setPosition({\n x: Math.ceil(Math.random() * parentWidth),\n y: Math.ceil(Math.random() * parentHeight),\n })\n})\n\nconst render: Parameters[0] = (state) => {\n $dot.style.transform = `translate(${state.position.x}px, ${state.position.y}px)`\n}\n\nrender(positionStore.getInitialState(), positionStore.getInitialState())\n\npositionStore.subscribe((state) => state.position, render)\n\nconst logger: Parameters[0] = (x) => {\n console.log('new x position', { x })\n}\n\npositionStore.subscribe((state) => state.position.x, logger)\n```\n\nHere's the `html` code\n\n```html\n\n \n\n```\n\n## Troubleshooting\n\nTBD\n","path":"docs/reference/middlewares/subscribe-with-selector.md","title":"subscribeWithSelector","source_type":"doc","kind":"doc"} -{"id":"213","text":"---\ntitle: Migrating to v4\nnav: 38\n---\n\nThe only breaking changes are in types.\nIf you are using Zustand with TypeScript\nor JSDoc type annotations,\nthis guide applies.\nOtherwise, no migration is required.\n\nAlso, it's recommended to first read\nthe new [TypeScript Guide](../../learn/guides/advanced-typescript.md),\nso that the migration is easier to understand.\n\nIn addition to this migration guide,\nyou can also check the\n[diff](https://github.com/pmndrs/zustand/compare/v3.7.2...v4.0.0?short_path=37e5b4c#diff-c21e24854115b390eccde717da83f91feb2d5927a76c1485e5f0fdd0135c2afa)\nof the test files in the Zustand repository from v3 to v4.\n\n## `create`\n\n**Applicable imports**\n\n```ts\nimport create from 'zustand'\nimport create from 'zustand/vanilla'\n```\n\n**Change**\n\n```diff\n- create:\n- < State\n- , StoreSetState = StoreApi[\"set\"]\n- , StoreGetState = StoreApi[\"get\"]\n- , Store = StoreApi\n- >\n- (f: ...) => ...\n+ create:\n+ { (): (f: ...) => ...\n+ , (f: ...) => ...\n+ }\n```\n\n**Migration**\n\nIf you are not passing any type parameters to `create`,\nno migration is required.\n\nIf you are using a \"leaf\" middleware like `combine` or `redux`,\nremove all type parameters from `create`.\n\nElse, replace `create(...)` with `create()(...)`.\n\n","path":"docs/reference/migrations/migrating-to-v4.md","title":"migrating-to-v4.md","source_type":"doc","kind":"doc"} -{"id":"214","text":"## `StateCreator`\n\n**Applicable imports**\n\n```ts\nimport type { StateCreator } from 'zustand'\nimport type { StateCreator } from 'zustand/vanilla'\n```\n\n**Change**\n\n```diff\n- type StateCreator\n- < State\n- , StoreSetState = StoreApi[\"set\"]\n- , StoreGetState = StoreApi[\"get\"]\n- , Store = StoreApi\n- > =\n- ...\n+ type StateCreator\n+ < State\n+ , InMutators extends [StoreMutatorIdentifier, unknown][] = []\n+ , OutMutators extends [StoreMutatorIdentifier, unknown][] = []\n+ , Return = State\n+ > =\n+ ...\n```\n\n**Migration**\n\nIf you are using `StateCreator`,\nyou are likely authoring a middleware\nor using the \"slices\" pattern.\nFor that check the\n[Authoring middlewares and advanced usage](../../learn/guides/advanced-typescript.md#authoring-middlewares-and-advanced-usage)\nand [Common recipes](../../learn/guides/advanced-typescript.md#common-recipes)\nsections of the TypeScript Guide.\n\n## `PartialState`\n\n**Applicable imports**\n\n```ts\nimport type { PartialState } from 'zustand'\nimport type { PartialState } from 'zustand/vanilla'\n```\n\n**Change**\n\n```diff\n- type PartialState\n- < T extends State\n- , K1 extends keyof T = keyof T\n- , K2 extends keyof T = K1\n- , K3 extends keyof T = K2\n- , K4 extends keyof T = K3\n- > =\n- | (Pick | Pick | Pick | Pick | T)\n- | ((state: T) => Pick | Pick | Pick | Pick | T)\n+ type PartialState =\n+ | Partial\n+ | ((state: T) => Partial)\n```\n\n**Migration**\n\nReplace `PartialState` with `PartialState`\nand preferably turn on [`exactOptionalPropertyTypes`](https://www.typescriptlang.org/tsconfig#exactOptionalPropertyTypes)\nin your `tsconfig.json`:\n\n```json\n{\n \"compilerOptions\": {\n \"exactOptionalPropertyTypes\": true\n }\n}\n```\n\nWe're no longer using the trick to disallow `{ foo: undefined }`\nto be assigned to `Partial<{ foo: string }>`.\nInstead, we're relying on the users to turn on `exactOptionalPropertyTypes`.\n\n","path":"docs/reference/migrations/migrating-to-v4.md","title":"migrating-to-v4.md","source_type":"doc","kind":"doc"} -{"id":"215","text":"## `useStore`\n\n**Applicable imports**\n\n```ts\nimport { useStore } from 'zustand'\nimport { useStore } from 'zustand/react'\n```\n\n**Change**\n\n```diff\n- useStore:\n- { (store: StoreApi): State\n- , \n- ( store: StoreApi\n- , selector: StateSelector,\n- , equals?: EqualityChecker\n- ): StateSlice\n- }\n+ useStore:\n+ >\n+ ( store: Store\n+ , selector?: StateSelector,\n+ , equals?: EqualityChecker\n+ )\n+ => StateSlice\n```\n\n**Migration**\n\nIf you are not passing any type parameters to `useStore`,\nno migration is required.\n\nIf you are,\nit's recommended to remove all the type parameters,\nor pass the **store** type instead of the **state** type as the first parameter.\n\n## `UseBoundStore`\n\n**Applicable imports**\n\n```ts\nimport type { UseBoundStore } from 'zustand'\nimport type { UseBoundStore } from 'zustand/react'\n```\n\n**Change**\n\n```diff\n- type UseBoundStore<\n- State,\n- Store = StoreApi\n- > =\n- & { (): T\n- , \n- ( selector: StateSelector\n- , equals?: EqualityChecker\n- ): U\n- }\n- & Store\n+ type UseBoundStore =\n+ & (>\n+ ( selector?: (state: ExtractState) => StateSlice\n+ , equals?: (a: StateSlice, b: StateSlice) => boolean\n+ ) => StateSlice\n+ )\n+ & S\n```\n\n**Migration**\n\nReplace `UseBoundStore` with `UseBoundStore>`,\nand `UseBoundStore` with `UseBoundStore`\n\n## `UseContextStore`\n\n**Applicable imports**\n\n```ts\nimport type { UseContextStore } from 'zustand/context'\n```\n\n**Change**\n\n```diff\n- type UseContextStore\n```\n\n**Migration**\n\nUse `typeof MyContext.useStore` instead\n\n","path":"docs/reference/migrations/migrating-to-v4.md","title":"migrating-to-v4.md","source_type":"doc","kind":"doc"} -{"id":"216","text":"## `createContext`\n\n**Applicable imports**\n\n```ts\nimport createContext from 'zustand/context'\n```\n\n**Change**\n\n```diff\n createContext:\n- >() => ...\n+ () => ...\n```\n\n**Migration**\n\nReplace `createContext()` with `createContext>()`,\nand `createContext()` with `createContext()`.\n\n## `combine`, `devtools`, `subscribeWithSelector`\n\n**Applicable imports**\n\n```ts\nimport { combine } from 'zustand/middleware'\nimport { devtools } from 'zustand/middleware'\nimport { subscribeWithSelector } from 'zustand/middleware'\n```\n\n**Change**\n\n```diff\n- combine:\n- (...) => ...\n+ combine:\n+ (...) => ...\n\n- devtools:\n- (...) => ...\n+ devtools:\n+ (...) => ...\n\n- subscribeWithSelector:\n- (...) => ...\n+ subscribeWithSelector:\n+ (...) => ...\n```\n\n**Migration**\n\nIf you are not passing any type parameters\nto `combine`, `devtools`, or `subscribeWithSelector`,\nno migration is required.\n\nIf you are,\nremove all the type parameters,\nas they are inferred automatically.\n\n","path":"docs/reference/migrations/migrating-to-v4.md","title":"migrating-to-v4.md","source_type":"doc","kind":"doc"} -{"id":"217","text":"## `persist`\n\n**Applicable imports**\n\n```ts\nimport { persist } from 'zustand/middleware'\n```\n\n**Change**\n\n```diff\n- persist:\n- >(...) => ...\n+ persist:\n+ (...) => ...\n```\n\n**Migration**\n\nIf you are passing any type parameters,\nremove them as they are inferred automatically.\n\nNext, if you are passing the `partialize` option,\nthere is no further steps required for migration.\n\nIf you are **not** passing the `partialize` option,\nyou might see some compilation errors.\nIf you do not see any,\nthere is no further migration required.\n\nThe type of partialized state is now `T` instead of `Partial`,\nwhich aligns with the runtime behavior of the default `partialize`,\nwhich is an identity (`s => s`).\n\nIf you see some compilation errors,\nyou have to find and fix the errors yourself,\nbecause they might be indicative of unsound code.\nAlternatively, the workaround will be passing\n`s => s as Partial` to `partialize`.\nIf your partialized state is truly `Partial`,\nyou should not encounter any bugs.\n\nThe runtime behavior has not changed,\nonly the types are now correct.\n\n## `redux`\n\n**Applicable imports**\n\n```ts\nimport { redux } from 'zustand/middleware'\n```\n\n**Change**\n\n```diff\n- redux:\n- (...) => ...\n+ redux:\n+ (...) => ...\n```\n\n**Migration**\n\nIf you are not passing any type parameters to `redux`,\nno migration is required.\n\nIf you are,\nremove all the type parameters,\nand annotate only the second (action) parameter.\nThat is, replace `redux((state, action) => ..., ...)`\nwith `redux((state, action: A) => ..., ...)`.\n","path":"docs/reference/migrations/migrating-to-v4.md","title":"migrating-to-v4.md","source_type":"doc","kind":"doc"} -{"id":"218","text":"---\ntitle: How to Migrate to v5 from v4\nnav: 37\n---\n\n# How to Migrate to v5 from v4\n\nWe highly recommend to update to the latest version of v4, before migrating to v5. It will show all deprecation warnings without breaking your app.\n\n## Changes in v5\n\n- Drop default exports\n- Drop deprecated features\n- Make React 18 the minimum required version\n- Make use-sync-external-store a peer dependency (required for `createWithEqualityFn` and `useStoreWithEqualityFn` in `zustand/traditional`)\n- Make TypeScript 4.5 the minimum required version\n- Drop UMD/SystemJS support\n- Organize entry points in the package.json\n- Drop ES5 support\n- Stricter types when setState's replace flag is set\n- Persist middleware behavioral change\n- Other small improvements (technically breaking changes)\n\n## Migration Guide\n\n### Using custom equality functions such as `shallow`\n\nThe `create` function in v5 does not support customizing equality function.\n\nIf you use custom equality function such as `shallow`,\nthe easiest migration is to use `createWithEqualityFn`.\n\n```js\n// v4\nimport { create } from 'zustand'\nimport { shallow } from 'zustand/shallow'\n\nconst useCountStore = create((set) => ({\n count: 0,\n text: 'hello',\n // ...\n}))\n\nconst Component = () => {\n const { count, text } = useCountStore(\n (state) => ({\n count: state.count,\n text: state.text,\n }),\n shallow,\n )\n // ...\n}\n```\n\nThat can be done with `createWithEqualityFn` in v5:\n\n```bash\nnpm install use-sync-external-store\n```\n\n```js\n// v5\nimport { createWithEqualityFn as create } from 'zustand/traditional'\n\n// The rest is the same as v4\n```\n\nAlternatively, for the `shallow` use case, you can use `useShallow` hook:\n\n```js\n// v5\nimport { create } from 'zustand'\nimport { useShallow } from 'zustand/shallow'\n\nconst useCountStore = create((set) => ({\n count: 0,\n text: 'hello',\n // ...\n}))\n\nconst Component = () => {\n const { count, text } = useCountStore(\n useShallow((state) => ({\n count: state.count,\n text: state.text,\n })),\n )\n // ...\n}\n```\n\n","path":"docs/reference/migrations/migrating-to-v5.md","title":"How to Migrate to v5 from v4","source_type":"doc","kind":"doc"} -{"id":"219","text":"### Requiring stable selector outputs\n\nThere is a behavioral change in v5 to match React default behavior.\nIf a selector returns a new reference, it may cause infinite loops.\n\nFor example, this may cause infinite loops.\n\n```js\n// v4\nconst [searchValue, setSearchValue] = useStore((state) => [\n state.searchValue,\n state.setSearchValue,\n])\n```\n\nThe error message will be something like this:\n\n```plaintext\nUncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.\n```\n\nTo fix it, use the `useShallow` hook, which will return a stable reference.\n\n```js\n// v5\nimport { useShallow } from 'zustand/shallow'\n\nconst [searchValue, setSearchValue] = useStore(\n useShallow((state) => [state.searchValue, state.setSearchValue]),\n)\n```\n\nHere's another example that may cause infinite loops.\n\n```js\n// v4\nconst action = useMainStore((state) => {\n return state.action ?? () => {}\n})\n```\n\nTo fix it, make sure the selector function returns a stable reference.\n\n```js\n// v5\n\nconst FALLBACK_ACTION = () => {}\n\nconst action = useMainStore((state) => {\n return state.action ?? FALLBACK_ACTION\n})\n```\n\nAlternatively, if you need v4 behavior, `createWithEqualityFn` will do.\n\n```js\n// v5\nimport { createWithEqualityFn as create } from 'zustand/traditional'\n```\n\n","path":"docs/reference/migrations/migrating-to-v5.md","title":"How to Migrate to v5 from v4","source_type":"doc","kind":"doc"} -{"id":"220","text":"### Stricter types when setState's replace flag is set (Typescript only)\n\n```diff\n- setState:\n- (partial: T | Partial | ((state: T) => T | Partial), replace?: boolean | undefined) => void;\n+ setState:\n+ (partial: T | Partial | ((state: T) => T | Partial), replace?: false) => void;\n+ (state: T | ((state: T) => T), replace: true) => void;\n```\n\nIf you are not using the `replace` flag, no migration is required.\n\nIf you are using the `replace` flag and it's set to `true`, you must provide a complete state object.\nThis change ensures that `store.setState({}, true)` (which results in an invalid state) is no longer considered valid.\n\n**Examples:**\n\n```ts\n// Partial state update (valid)\nstore.setState({ key: 'value' })\n\n// Complete state replacement (valid)\nstore.setState({ key: 'value' }, true)\n\n// Incomplete state replacement (invalid)\nstore.setState({}, true) // Error\n```\n\n#### Handling Dynamic `replace` Flag\n\nIf the value of the `replace` flag is dynamic and determined at runtime, you might face issues. To handle this, you can use a workaround by annotating the `replace` parameter with the parameters of the `setState` function:\n\n```ts\nconst replaceFlag = Math.random() > 0.5\nconst args = [{ bears: 5 }, replaceFlag] as Parameters<\n typeof useBearStore.setState\n>\nstore.setState(...args)\n```\n\n","path":"docs/reference/migrations/migrating-to-v5.md","title":"How to Migrate to v5 from v4","source_type":"doc","kind":"doc"} -{"id":"221","text":"#### Persist middleware no longer stores item at store creation\n\nPreviously, the `persist` middleware stored the initial state during store creation. This behavior has been removed in v5 (and v4.5.5).\n\nFor example, in the following code, the initial state is stored in the storage.\n\n```js\n// v4\nimport { create } from 'zustand'\nimport { persist } from 'zustand/middleware'\n\nconst useCountStore = create(\n persist(\n () => ({\n count: Math.floor(Math.random() * 1000),\n }),\n {\n name: 'count',\n },\n ),\n)\n```\n\nIn v5, this is no longer the case, and you need to explicitly set the state after store creation.\n\n```js\n// v5\nimport { create } from 'zustand'\nimport { persist } from 'zustand/middleware'\n\nconst useCountStore = create(\n persist(\n () => ({\n count: 0,\n }),\n {\n name: 'count',\n },\n ),\n)\nuseCountStore.setState({\n count: Math.floor(Math.random() * 1000),\n})\n```\n\n## Links\n\n- https://github.com/pmndrs/zustand/pull/2138\n- https://github.com/pmndrs/zustand/pull/2580\n","path":"docs/reference/migrations/migrating-to-v5.md","title":"How to Migrate to v5 from v4","source_type":"doc","kind":"doc"} -{"id":"222","text":"---\ntitle: createContext from zustand/context\nnav: 39\n---\n\nA special `createContext` is provided since v3.5,\nwhich avoids misusing the store hook.\n\n> **Note**: This function is deprecated in v4 and will be removed in v5. See [Migration](#migration).\n\n```jsx\nimport create from 'zustand'\nimport createContext from 'zustand/context'\n\nconst { Provider, useStore } = createContext()\n\nconst createStore = () => create(...)\n\nconst App = () => (\n \n ...\n \n)\n\nconst Component = () => {\n const state = useStore()\n const slice = useStore(selector)\n ...\n```\n\n## createContext usage in real components\n\n```jsx\nimport create from \"zustand\";\nimport createContext from \"zustand/context\";\n\n// Best practice: You can move the below createContext() and createStore to a separate file(store.js) and import the Provider, useStore here/wherever you need.\n\nconst { Provider, useStore } = createContext();\n\nconst createStore = () =>\n create((set) => ({\n bears: 0,\n increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),\n removeAllBears: () => set({ bears: 0 })\n }));\n\nconst Button = () => {\n return (\n {/** store() - This will create a store for each time using the Button component instead of using one store for all components **/}\n \n \n \n );\n};\n\nconst ButtonChild = () => {\n const state = useStore();\n return (\n
\n {state.bears}\n {\n state.increasePopulation();\n }}\n >\n +\n \n
\n );\n};\n\nexport default function App() {\n return (\n
\n
\n );\n}\n```\n\n## createContext usage with initialization from props\n\n```tsx\nimport create from 'zustand'\nimport createContext from 'zustand/context'\n\nconst { Provider, useStore } = createContext()\n\n","path":"docs/reference/previous-versions/zustand-v3-create-context.md","title":"zustand-v3-create-context.md","source_type":"doc","kind":"doc"} -{"id":"223","text":"export default function App({ initialBears }) {\n return (\n \n create((set) => ({\n bears: initialBears,\n increase: () => set((state) => ({ bears: state.bears + 1 })),\n }))\n }\n >\n \n}\n```\n\n### Why zustand over redux?\n\n- Simple and un-opinionated\n- Makes hooks the primary means of consuming state\n- Doesn't wrap your app in context providers\n- [Can inform components transiently (without causing render)](#transient-updates-for-often-occurring-state-changes)\n\n### Why zustand over context?\n\n- Less boilerplate\n- Renders components only on changes\n- Centralized, action-based state management\n\n---\n\n# Recipes\n\n## Fetching everything\n\nYou can, but bear in mind that it will cause the component to update on every state change!\n\n```jsx\nconst state = useBearStore()\n```\n\n","path":"README.md","title":"Recipes","source_type":"doc","kind":"doc"} -{"id":"228","text":"## Selecting multiple state slices\n\nIt detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.\n\n```jsx\nconst nuts = useBearStore((state) => state.nuts)\nconst honey = useBearStore((state) => state.honey)\n```\n\nIf you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can use [useShallow](./docs/guides/prevent-rerenders-with-use-shallow.md) to prevent unnecessary rerenders when the selector output does not change according to shallow equal.\n\n```jsx\nimport { create } from 'zustand'\nimport { useShallow } from 'zustand/react/shallow'\n\nconst useBearStore = create((set) => ({\n nuts: 0,\n honey: 0,\n treats: {},\n // ...\n}))\n\n// Object pick, re-renders the component when either state.nuts or state.honey change\nconst { nuts, honey } = useBearStore(\n useShallow((state) => ({ nuts: state.nuts, honey: state.honey })),\n)\n\n// Array pick, re-renders the component when either state.nuts or state.honey change\nconst [nuts, honey] = useBearStore(\n useShallow((state) => [state.nuts, state.honey]),\n)\n\n// Mapped picks, re-renders the component when state.treats changes in order, count or keys\nconst treats = useBearStore(useShallow((state) => Object.keys(state.treats)))\n```\n\nFor more control over re-rendering, you may provide any custom equality function (this example requires the use of [`createWithEqualityFn`](./docs/migrations/migrating-to-v5.md#using-custom-equality-functions-such-as-shallow)).\n\n```jsx\nconst treats = useBearStore(\n (state) => state.treats,\n (oldTreats, newTreats) => compare(oldTreats, newTreats),\n)\n```\n\n","path":"README.md","title":"Recipes","source_type":"doc","kind":"doc"} -{"id":"229","text":"## Overwriting state\n\nThe `set` function has a second argument, `false` by default. Instead of merging, it will replace the state model. Be careful not to wipe out parts you rely on, like actions.\n\n```jsx\nconst useFishStore = create((set) => ({\n salmon: 1,\n tuna: 2,\n deleteEverything: () => set({}, true), // clears the entire store, actions included\n deleteTuna: () => set(({ tuna, ...rest }) => rest, true),\n}))\n```\n\n## Async actions\n\nJust call `set` when you're ready, zustand doesn't care if your actions are async or not.\n\n```jsx\nconst useFishStore = create((set) => ({\n fishies: {},\n fetch: async (pond) => {\n const response = await fetch(pond)\n set({ fishies: await response.json() })\n },\n}))\n```\n\n## Read from state in actions\n\n`set` allows fn-updates `set(state => result)`, but you still have access to state outside of it through `get`.\n\n```jsx\nconst useSoundStore = create((set, get) => ({\n sound: 'grunt',\n action: () => {\n const sound = get().sound\n ...\n```\n\n## Reading/writing state and reacting to changes outside of components\n\nSometimes you need to access state in a non-reactive way or act upon the store. For these cases, the resulting hook has utility functions attached to its prototype.\n\n:warning: This technique is not recommended for adding state in [React Server Components](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md) (typically in Next.js 13 and above). It can lead to unexpected bugs and privacy issues for your users. For more details, see [#2200](https://github.com/pmndrs/zustand/discussions/2200).\n\n```jsx\nconst useDogStore = create(() => ({ paw: true, snout: true, fur: true }))\n\n// Getting non-reactive fresh state\nconst paw = useDogStore.getState().paw\n// Listening to all changes, fires synchronously on every change\nconst unsub1 = useDogStore.subscribe(console.log)\n// Updating state, will trigger listeners\nuseDogStore.setState({ paw: false })\n// Unsubscribe listeners\nunsub1()\n\n","path":"README.md","title":"Recipes","source_type":"doc","kind":"doc"} -{"id":"230","text":"// You can of course use the hook as you always would\nfunction Component() {\n const paw = useDogStore((state) => state.paw)\n ...\n```\n\n### Using subscribe with selector\n\nIf you need to subscribe with a selector,\n`subscribeWithSelector` middleware will help.\n\nWith this middleware `subscribe` accepts an additional signature:\n\n```ts\nsubscribe(selector, callback, options?: { equalityFn, fireImmediately }): Unsubscribe\n```\n\n```js\nimport { subscribeWithSelector } from 'zustand/middleware'\nconst useDogStore = create(\n subscribeWithSelector(() => ({ paw: true, snout: true, fur: true })),\n)\n\n// Listening to selected changes, in this case when \"paw\" changes\nconst unsub2 = useDogStore.subscribe((state) => state.paw, console.log)\n// Subscribe also exposes the previous value\nconst unsub3 = useDogStore.subscribe(\n (state) => state.paw,\n (paw, previousPaw) => console.log(paw, previousPaw),\n)\n// Subscribe also supports an optional equality function\nconst unsub4 = useDogStore.subscribe(\n (state) => [state.paw, state.fur],\n console.log,\n { equalityFn: shallow },\n)\n// Subscribe and fire immediately\nconst unsub5 = useDogStore.subscribe((state) => state.paw, console.log, {\n fireImmediately: true,\n})\n```\n\n## Using zustand without React\n\nZustand core can be imported and used without the React dependency. The only difference is that the create function does not return a hook, but the API utilities.\n\n```jsx\nimport { createStore } from 'zustand/vanilla'\n\nconst store = createStore((set) => ...)\nconst { getState, setState, subscribe, getInitialState } = store\n\nexport default store\n```\n\nYou can use a vanilla store with `useStore` hook available since v4.\n\n```jsx\nimport { useStore } from 'zustand'\nimport { vanillaStore } from './vanillaStore'\n\nconst useBoundStore = (selector) => useStore(vanillaStore, selector)\n```\n\n:warning: Note that middlewares that modify `set` or `get` are not applied to `getState` and `setState`.\n\n","path":"README.md","title":"Recipes","source_type":"doc","kind":"doc"} -{"id":"231","text":"## Transient updates (for often occurring state-changes)\n\nThe subscribe function allows components to bind to a state-portion without forcing re-render on changes. Best combine it with useEffect for automatic unsubscribe on unmount. This can make a [drastic](https://codesandbox.io/s/peaceful-johnson-txtws) performance impact when you are allowed to mutate the view directly.\n\n```jsx\nconst useScratchStore = create((set) => ({ scratches: 0, ... }))\n\nconst Component = () => {\n // Fetch initial state\n const scratchRef = useRef(useScratchStore.getState().scratches)\n // Connect to the store on mount, disconnect on unmount, catch state-changes in a reference\n useEffect(() => useScratchStore.subscribe(\n state => (scratchRef.current = state.scratches)\n ), [])\n ...\n```\n\n## Sick of reducers and changing nested states? Use Immer!\n\nReducing nested structures is tiresome. Have you tried [immer](https://github.com/mweststrate/immer)?\n\n```jsx\nimport { produce } from 'immer'\n\nconst useLushStore = create((set) => ({\n lush: { forest: { contains: { a: 'bear' } } },\n clearForest: () =>\n set(\n produce((state) => {\n state.lush.forest.contains = null\n }),\n ),\n}))\n\nconst clearForest = useLushStore((state) => state.clearForest)\nclearForest()\n```\n\n[Alternatively, there are some other solutions.](./docs/learn/guides/updating-state.md#with-immer)\n\n## Persist middleware\n\nYou can persist your store's data using any kind of storage.\n\n```jsx\nimport { create } from 'zustand'\nimport { persist, createJSONStorage } from 'zustand/middleware'\n\nconst useFishStore = create(\n persist(\n (set, get) => ({\n fishes: 0,\n addAFish: () => set({ fishes: get().fishes + 1 }),\n }),\n {\n name: 'food-storage', // name of the item in the storage (must be unique)\n storage: createJSONStorage(() => sessionStorage), // (optional) by default, 'localStorage' is used\n },\n ),\n)\n```\n\n[See the full documentation for this middleware.](./docs/reference/integrations/persisting-store-data.md)\n\n","path":"README.md","title":"Recipes","source_type":"doc","kind":"doc"} -{"id":"232","text":"## Immer middleware\n\nImmer is available as middleware too.\n\n```jsx\nimport { create } from 'zustand'\nimport { immer } from 'zustand/middleware/immer'\n\nconst useBeeStore = create(\n immer((set) => ({\n bees: 0,\n addBees: (by) =>\n set((state) => {\n state.bees += by\n }),\n })),\n)\n```\n\n## Can't live without redux-like reducers and action types?\n\n```jsx\nconst types = { increase: 'INCREASE', decrease: 'DECREASE' }\n\nconst reducer = (state, { type, by = 1 }) => {\n switch (type) {\n case types.increase:\n return { grumpiness: state.grumpiness + by }\n case types.decrease:\n return { grumpiness: state.grumpiness - by }\n }\n}\n\nconst useGrumpyStore = create((set) => ({\n grumpiness: 0,\n dispatch: (args) => set((state) => reducer(state, args)),\n}))\n\nconst dispatch = useGrumpyStore((state) => state.dispatch)\ndispatch({ type: types.increase, by: 2 })\n```\n\nOr, just use our redux-middleware. It wires up your main-reducer, sets the initial state, and adds a dispatch function to the state itself and the vanilla API.\n\n```jsx\nimport { redux } from 'zustand/middleware'\n\nconst useGrumpyStore = create(redux(reducer, initialState))\n```\n\n","path":"README.md","title":"Recipes","source_type":"doc","kind":"doc"} -{"id":"233","text":"## Redux devtools\n\nInstall the [Redux DevTools Chrome extension](https://chromewebstore.google.com/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd) to use the devtools middleware.\n\n```jsx\nimport { devtools } from 'zustand/middleware'\n\n// Usage with a plain action store, it will log actions as \"setState\"\nconst usePlainStore = create(devtools((set) => ...))\n// Usage with a redux store, it will log full action types\nconst useReduxStore = create(devtools(redux(reducer, initialState)))\n```\n\nOne redux devtools connection for multiple stores\n\n```jsx\nimport { devtools } from 'zustand/middleware'\n\n// Usage with a plain action store, it will log actions as \"setState\"\nconst usePlainStore1 = create(devtools((set) => ..., { name, store: storeName1 }))\nconst usePlainStore2 = create(devtools((set) => ..., { name, store: storeName2 }))\n// Usage with a redux store, it will log full action types\nconst useReduxStore1 = create(devtools(redux(reducer, initialState)), { name, store: storeName3 })\nconst useReduxStore2 = create(devtools(redux(reducer, initialState)), { name, store: storeName4 })\n```\n\nAssigning different connection names will separate stores in redux devtools. This also helps group different stores into separate redux devtools connections.\n\ndevtools takes the store function as its first argument, optionally you can name the store or configure [serialize](https://github.com/zalmoxisus/redux-devtools-extension/blob/master/docs/API/Arguments.md#serialize) options with a second argument.\n\nName store: `devtools(..., {name: \"MyStore\"})`, which will create a separate instance named \"MyStore\" in the devtools.\n\nSerialize options: `devtools(..., { serialize: { options: true } })`.\n\n","path":"README.md","title":"Recipes","source_type":"doc","kind":"doc"} -{"id":"234","text":"#### Logging Actions\n\ndevtools will only log actions from each separated store unlike in a typical _combined reducers_ redux store. See an approach to combining stores https://github.com/pmndrs/zustand/issues/163\n\nYou can log a specific action type for each `set` function by passing a third parameter:\n\n```jsx\nconst useBearStore = create(devtools((set) => ({\n ...\n eatFish: () => set(\n (prev) => ({ fishes: prev.fishes > 1 ? prev.fishes - 1 : 0 }),\n undefined,\n 'bear/eatFish'\n ),\n ...\n```\n\nYou can also log the action's type along with its payload:\n\n```jsx\n ...\n addFishes: (count) => set(\n (prev) => ({ fishes: prev.fishes + count }),\n undefined,\n { type: 'bear/addFishes', count, }\n ),\n ...\n```\n\nIf an action type is not provided, it is defaulted to \"anonymous\". You can customize this default value by providing an `anonymousActionType` parameter:\n\n```jsx\ndevtools(..., { anonymousActionType: 'unknown', ... })\n```\n\nIf you wish to disable devtools (on production for instance). You can customize this setting by providing the `enabled` parameter:\n\n```jsx\ndevtools(..., { enabled: false, ... })\n```\n\n## React context\n\nThe store created with `create` doesn't require context providers. In some cases, you may want to use contexts for dependency injection or if you want to initialize your store with props from a component. Because the normal store is a hook, passing it as a normal context value may violate the rules of hooks.\n\nThe recommended method available since v4 is to use the vanilla store.\n\n```jsx\nimport { createContext, useContext } from 'react'\nimport { createStore, useStore } from 'zustand'\n\nconst store = createStore(...) // vanilla store without hooks\n\nconst StoreContext = createContext()\n\nconst App = () => (\n \n ...\n \n)\n\nconst Component = () => {\n const store = useContext(StoreContext)\n const slice = useStore(store, selector)\n ...\n```\n\n","path":"README.md","title":"Recipes","source_type":"doc","kind":"doc"} -{"id":"235","text":"## TypeScript Usage\n\nBasic typescript usage doesn't require anything special except for writing `create()(...)` instead of `create(...)`...\n\n```ts\nimport { create } from 'zustand'\nimport { devtools, persist } from 'zustand/middleware'\nimport type {} from '@redux-devtools/extension' // required for devtools typing\n\ninterface BearState {\n bears: number\n increase: (by: number) => void\n}\n\nconst useBearStore = create()(\n devtools(\n persist(\n (set) => ({\n bears: 0,\n increase: (by) => set((state) => ({ bears: state.bears + by })),\n }),\n {\n name: 'bear-storage',\n },\n ),\n ),\n)\n```\n\nA more detailed TypeScript guide is [here](docs/learn/guides/beginner-typescript.md) and [there](docs/learn/guides/advanced-typescript.md).\n\n## Best practices\n\n- You may wonder how to organize your code for better maintenance: [Splitting the store into separate slices](./docs/learn/guides/slices-pattern.md).\n- Recommended usage for this unopinionated library: [Flux inspired practice](./docs/learn/guides/flux-inspired-practice.md).\n- [Calling actions outside a React event handler in pre-React 18](./docs/learn/guides/event-handler-in-pre-react-18.md).\n- [Testing](./docs/learn/guides/testing.md)\n- For more, have a look [in the docs folder](./docs/index.md)\n\n## Third-Party Libraries\n\nSome users may want to extend Zustand's feature set which can be done using third-party libraries made by the community. For information regarding third-party libraries with Zustand, visit [the doc](./docs/reference/integrations/third-party-libraries.md).\n\n## Comparison with other libraries\n\n- [Difference between zustand and other state management libraries for React](https://zustand.docs.pmnd.rs/learn/getting-started/comparison)\n","path":"README.md","title":"Recipes","source_type":"doc","kind":"doc"} -{"id":"236","text":"{\n \"name\": \"zustand\",\n \"description\": \"🐻 Bear necessities for state management in React\",\n \"private\": true,\n \"type\": \"commonjs\",\n \"version\": \"5.0.14\",\n \"main\": \"./index.js\",\n \"types\": \"./index.d.ts\",\n \"typesVersions\": {\n \">=4.5\": {\n \"esm/*\": [\n \"esm/*\"\n ],\n \"*\": [\n \"*\"\n ]\n },\n \"*\": {\n \"esm/*\": [\n \"ts_version_4.5_and_above_is_required.d.ts\"\n ],\n \"*\": [\n \"ts_version_4.5_and_above_is_required.d.ts\"\n ]\n }\n },\n \"exports\": {\n \"./package.json\": \"./package.json\",\n \".\": {\n \"react-native\": {\n \"types\": \"./index.d.ts\",\n \"default\": \"./index.js\"\n },\n \"import\": {\n \"types\": \"./esm/index.d.mts\",\n \"default\": \"./esm/index.mjs\"\n },\n \"default\": {\n \"types\": \"./index.d.ts\",\n \"default\": \"./index.js\"\n }\n },\n \"./*\": {\n \"react-native\": {\n \"types\": \"./*.d.ts\",\n \"default\": \"./*.js\"\n },\n \"import\": {\n \"types\": \"./esm/*.d.mts\",\n \"default\": \"./esm/*.mjs\"\n },\n \"default\": {\n \"types\": \"./*.d.ts\",\n \"default\": \"./*.js\"\n }\n }\n },\n \"files\": [\n \"**\"\n ],\n \"sideEffects\": false,\n \"scripts\": {\n \"prebuild\": \"shx rm -rf dist\",\n \"build\": \"pnpm run prebuild && pnpm run \\\"/^build:.*/\\\" && pnpm run postbuild\",\n \"build-watch\": \"pnpm run \\\"/^build:.*/\\\" --watch\",\n \"build:base\": \"rollup -c\",\n \"build:vanilla\": \"rollup -c --config-vanilla\",\n \"build:react\": \"rollup -c --config-react\",\n \"build:middleware\": \"rollup -c --config-middleware\",\n \"build:middleware:immer\": \"rollup -c --config-middleware_immer\",\n \"build:shallow\": \"rollup -c --config-shallow\",\n \"build:vanilla:shallow\": \"rollup -c --config-vanilla_shallow\",\n \"build:react:shallow\": \"rollup -c --config-react_shallow\",\n \"build:traditional\": \"rollup -c --config-traditional\",\n \"postbuild\": \"pnpm run patch-d-ts && pnpm run copy && pnpm run patch-old-ts && pnpm run patch-esm-ts\",\n \"fix\": \"pnpm run fix:lint && pnpm run fix:format\",\n \"fix:format\": \"prettier . --write\",\n \"fix:lint\": \"eslint . --fix\",\n \"test\": \"pnpm run \\\"/^test:.*/\\\"\",\n \"test:format\": \"prettier . --list-different\",\n \"test:types\": \"tsc --noEmit\",\n \"test:lint\": \"eslint .\",\n \"test:spec\": \"vitest run\",\n \"patch-d-ts\": \"node --input-type=module -e \\\"import { entries } from './rollup.config.mjs'; import shelljs from 'shelljs'; const { find, sed } = shelljs; find('dist/**/*.d.ts').forEach(f => { entries.forEach(({ find, replacement }) => { sed('-i', new RegExp(' from \\\\'' + find.source.slice(0, -1) + '\\\\';$'), ' from \\\\'' + replacement + '\\\\';', f); }); sed('-i', / from '(\\\\.[^']+)\\\\.ts';$/, ' from \\\\'\\\\$1\\\\';', f); });\\\"\",\n \"copy\": \"shx cp -r dist/src/* dist/esm && shx cp -r dist/src/* dist && shx rm -rf dist/src && shx rm -rf dist/{src,tests} && shx cp package.json README.md LICENSE dist && json -I -f dist/package.json -e \\\"this.private=false; this.devDependencies=undefined; this.optionalDependencies=undefined; this.scripts=undefined; this.prettier=undefined;\\\"\",\n \"patch-old-ts\": \"shx touch dist/ts_version_4.5_and_above_is_required.d.ts\",\n \"patch-esm-ts\": \"node -e \\\"require('shelljs').find('dist/esm/**/*.d.ts').forEach(f=>{var f2=f.replace(/\\\\.ts$/,'.mts');require('fs').renameSync(f,f2);require('shelljs').sed('-i',/ from '(\\\\.[^']+)';$/,' from \\\\'\\\\$1.mjs\\\\';',f2);require('shelljs').sed('-i',/^declare module '(\\\\.[^']+)'/,'declare module \\\\'\\\\$1.mjs\\\\'',f2)})\\\"\"\n },\n \"engines\": {\n \"node\": \">=12.20.0\"\n },\n \"prettier\": {\n \"semi\": false,\n \"singleQuote\": true\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/pmndrs/zustand.git\"\n },\n \"keywords\": [\n \"react\",\n \"state\",\n \"manager\",\n \"management\",\n \"redux\",\n \"store\"\n ],\n \"author\": \"Paul Henschel\",\n \"contributors\": [\n \"Jeremy Holcomb (https://github.com/JeremyRH)\",\n \"Daishi Kato (https://github.com/dai-shi)\"\n ],\n \"license\": \"MIT\",\n \"bugs\":","path":"package.json","title":"package.json","source_type":"config","kind":"doc"} -{"id":"237","text":"ote\": true\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/pmndrs/zustand.git\"\n },\n \"keywords\": [\n \"react\",\n \"state\",\n \"manager\",\n \"management\",\n \"redux\",\n \"store\"\n ],\n \"author\": \"Paul Henschel\",\n \"contributors\": [\n \"Jeremy Holcomb (https://github.com/JeremyRH)\",\n \"Daishi Kato (https://github.com/dai-shi)\"\n ],\n \"license\": \"MIT\",\n \"bugs\": {\n \"url\": \"https://github.com/pmndrs/zustand/issues\"\n },\n \"homepage\": \"https://github.com/pmndrs/zustand\",\n \"devDependencies\": {\n \"@eslint/js\": \"9.39.4\",\n \"@redux-devtools/extension\": \"^4.0.0\",\n \"@rollup/plugin-alias\": \"^6.0.0\",\n \"@rollup/plugin-node-resolve\": \"^16.0.3\",\n \"@rollup/plugin-replace\": \"^6.0.3\",\n \"@rollup/plugin-typescript\": \"^12.3.0\",\n \"@testing-library/jest-dom\": \"^6.9.1\",\n \"@testing-library/react\": \"^16.3.2\",\n \"@types/node\": \"^25.9.1\",\n \"@types/react\": \"^19.2.15\",\n \"@types/react-dom\": \"^19.2.3\",\n \"@types/use-sync-external-store\": \"^1.5.0\",\n \"@vitest/coverage-v8\": \"^4.1.7\",\n \"@vitest/eslint-plugin\": \"^1.6.18\",\n \"@vitest/ui\": \"^4.1.7\",\n \"esbuild\": \"^0.28.0\",\n \"eslint\": \"9.39.4\",\n \"eslint-import-resolver-typescript\": \"^4.4.4\",\n \"eslint-plugin-import\": \"^2.32.0\",\n \"eslint-plugin-jest-dom\": \"^5.5.0\",\n \"eslint-plugin-react\": \"^7.37.5\",\n \"eslint-plugin-react-hooks\": \"^7.1.1\",\n \"eslint-plugin-testing-library\": \"^7.16.2\",\n \"immer\": \"^11.1.8\",\n \"jsdom\": \"^29.1.1\",\n \"json\": \"^11.0.0\",\n \"prettier\": \"^3.8.3\",\n \"react\": \"^19.2.6\",\n \"react-dom\": \"^19.2.6\",\n \"redux\": \"^5.0.1\",\n \"rollup\": \"^4.60.4\",\n \"rollup-plugin-esbuild\": \"^6.2.1\",\n \"shelljs\": \"^0.10.0\",\n \"shx\": \"^0.4.0\",\n \"tslib\": \"^2.8.1\",\n \"typescript\": \"^6.0.3\",\n \"typescript-eslint\": \"^8.60.0\",\n \"use-sync-external-store\": \"^1.6.0\",\n \"vitest\": \"^4.1.7\"\n },\n \"peerDependencies\": {\n \"@types/react\": \">=18.0.0\",\n \"immer\": \">=9.0.6\",\n \"react\": \">=18.0.0\",\n \"use-sync-external-store\": \">=1.2.0\"\n },\n \"peerDependenciesMeta\": {\n \"@types/react\": {\n \"optional\": true\n },\n \"immer\": {\n \"optional\": true\n },\n \"react\": {\n \"optional\": true\n },\n \"use-sync-external-store\": {\n \"optional\": true\n }\n },\n \"packageManager\": \"pnpm@11.3.0+sha512.2c403d6594527287672b1f7056343a1f7c3634036a67ffabfcc2b3d7595d843768f8787148d1b57cf7956c90606bbd192857c363af19e96d2d0ec9ec5741d215\"\n}\n","path":"package.json","title":"package.json","source_type":"config","kind":"doc"} -{"id":"238","text":"Source src/index.ts (full):\nexport * from './vanilla.ts'\nexport * from './react.ts'\n","path":"src/index.ts","title":"index.ts","source_type":"src","kind":"source"} -{"id":"239","text":"Source src/middleware/combine.ts (full):\nimport type { StateCreator, StoreMutatorIdentifier } from '../vanilla.ts'\n\ntype Write = Omit & U\n\nexport function combine<\n T extends object,\n U extends object,\n Mps extends [StoreMutatorIdentifier, unknown][] = [],\n Mcs extends [StoreMutatorIdentifier, unknown][] = [],\n>(\n initialState: T,\n create: StateCreator,\n): StateCreator, Mps, Mcs> {\n return (...args) => Object.assign({}, initialState, (create as any)(...args))\n}\n","path":"src/middleware/combine.ts","title":"combine.ts","source_type":"src","kind":"source"} -{"id":"240","text":"Source src/middleware/devtools.ts (full):\nimport type {} from '@redux-devtools/extension'\n\nimport type {\n StateCreator,\n StoreApi,\n StoreMutatorIdentifier,\n} from '../vanilla.ts'\n\ntype Config = Parameters<\n (Window extends { __REDUX_DEVTOOLS_EXTENSION__?: infer T }\n ? T\n : { connect: (param: any) => unknown })['connect']\n>[0]\n\ndeclare module '../vanilla' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface StoreMutators {\n 'zustand/devtools': WithDevtools\n }\n}\n\n// FIXME https://github.com/reduxjs/redux-devtools/issues/1097\ntype Message = {\n type: string\n payload?: any\n state?: any\n}\n\ntype WithDispatch = {\n dispatch: (...args: unknown[]) => void\n dispatchFromDevtools: unknown\n}\n\nconst shouldDispatchFromDevtools = (api: unknown): api is WithDispatch =>\n !!(api as WithDispatch).dispatchFromDevtools &&\n typeof (api as WithDispatch).dispatch === 'function'\n\ntype Cast = T extends U ? T : U\ntype Write = Omit & U\ntype TakeTwo = T extends { length: 0 }\n ? [undefined, undefined]\n : T extends { length: 1 }\n ? [...args0: Cast, arg1: undefined]\n : T extends { length: 0 | 1 }\n ? [...args0: Cast, arg1: undefined]\n : T extends { length: 2 }\n ? T\n : T extends { length: 1 | 2 }\n ? T\n : T extends { length: 0 | 1 | 2 }\n ? T\n : T extends [infer A0, infer A1, ...unknown[]]\n ? [A0, A1]\n : T extends [infer A0, (infer A1)?, ...unknown[]]\n ? [A0, A1?]\n : T extends [(infer A0)?, (infer A1)?, ...unknown[]]\n ? [A0?, A1?]\n : never\n\ntype WithDevtools = Write>\n\ntype Action =\n | string\n | {\n type: string\n [x: string | number | symbol]: unknown\n }\ntype StoreDevtools = S extends {\n setState: {\n // capture both overloads of setState\n (...args: infer Sa1): infer Sr1\n (...args: infer Sa2): infer Sr2\n }\n}\n ? {\n setState(...args: [...args: TakeTwo, action?: Action]): Sr1\n setState(...args: [...args: TakeTwo, action?: Action]): Sr2\n devtools: {\n cleanup: () => void\n }\n }\n : never\n\n","path":"src/middleware/devtools.ts","title":"devtools.ts","source_type":"src","kind":"source"} -{"id":"241","text":"export interface DevtoolsOptions extends Config {\n name?: string\n enabled?: boolean\n anonymousActionType?: string\n store?: string\n}\n\ntype Devtools = <\n T,\n Mps extends [StoreMutatorIdentifier, unknown][] = [],\n Mcs extends [StoreMutatorIdentifier, unknown][] = [],\n U = T,\n>(\n initializer: StateCreator,\n devtoolsOptions?: DevtoolsOptions,\n) => StateCreator\n\ntype DevtoolsImpl = (\n storeInitializer: StateCreator,\n devtoolsOptions?: DevtoolsOptions,\n) => StateCreator\n\n","path":"src/middleware/devtools.ts","title":"devtools.ts","source_type":"src","kind":"source"} -{"id":"242","text":"export type NamedSet = WithDevtools>['setState']\n\ntype Connection = ReturnType<\n NonNullable['connect']\n>\ntype ConnectionName = string | undefined\ntype StoreName = string\ntype StoreInformation = StoreApi\ntype ConnectionInformation = {\n connection: Connection\n stores: Record\n}\n\nconst trackedConnections: Map = new Map()\n\nconst getTrackedConnectionState = (\n name: string | undefined,\n): Record => {\n const api = trackedConnections.get(name)\n if (!api) return {}\n return Object.fromEntries(\n Object.entries(api.stores).map(([key, api]) => [key, api.getState()]),\n )\n}\n\nconst extractConnectionInformation = (\n store: string | undefined,\n extensionConnector: NonNullable<\n (typeof window)['__REDUX_DEVTOOLS_EXTENSION__']\n >,\n options: Omit,\n) => {\n if (store === undefined) {\n return {\n type: 'untracked' as const,\n connection: extensionConnector.connect(options),\n }\n }\n const existingConnection = trackedConnections.get(options.name)\n if (existingConnection) {\n return { type: 'tracked' as const, store, ...existingConnection }\n }\n const newConnection: ConnectionInformation = {\n connection: extensionConnector.connect(options),\n stores: {},\n }\n trackedConnections.set(options.name, newConnection)\n return { type: 'tracked' as const, store, ...newConnection }\n}\n\nconst removeStoreFromTrackedConnections = (\n name: string | undefined,\n store: string | undefined,\n) => {\n if (store === undefined) return\n const connectionInfo = trackedConnections.get(name)\n if (!connectionInfo) return\n delete connectionInfo.stores[store]\n if (Object.keys(connectionInfo.stores).length === 0) {\n trackedConnections.delete(name)\n }\n}\n\n// V8 (Chrome/Edge/Node): \"at ()\"\nconst v8StackLineRe = /.+ (.+) .+/\n// SpiderMonkey (Firefox) / JavaScriptCore (Safari): \"@\"\nconst geckoStackLineRe = /^([^@]+)@/\n\n","path":"src/middleware/devtools.ts","title":"devtools.ts","source_type":"src","kind":"source"} -{"id":"243","text":"function findCallerName(stack: string | undefined) {\n if (!stack) return undefined\n const traceLines = stack.split('\\n')\n const apiSetStateLineIndex = traceLines.findIndex((traceLine) =>\n traceLine.includes('api.setState'),\n )\n if (apiSetStateLineIndex < 0) return undefined\n const callerLine = traceLines[apiSetStateLineIndex + 1]?.trim() || ''\n return (\n v8StackLineRe.exec(callerLine)?.[1] ||\n geckoStackLineRe.exec(callerLine)?.[1]\n )\n}\n\nconst devtoolsImpl: DevtoolsImpl =\n (fn, devtoolsOptions = {}) =>\n (set, get, api) => {\n const { enabled, anonymousActionType, store, ...options } = devtoolsOptions\n\n type S = ReturnType & {\n [store: string]: ReturnType\n }\n type PartialState = Partial | ((s: S) => Partial)\n\n let extensionConnector:\n | (typeof window)['__REDUX_DEVTOOLS_EXTENSION__']\n | false\n try {\n extensionConnector =\n (enabled ?? import.meta.env?.MODE !== 'production') &&\n window.__REDUX_DEVTOOLS_EXTENSION__\n } catch {\n // ignored\n }\n\n if (!extensionConnector) {\n return fn(set, get, api)\n }\n\n const { connection, ...connectionInformation } =\n extractConnectionInformation(store, extensionConnector, options)\n\n let isRecording = true\n api.setState = ((state, replace, nameOrAction: Action) => {\n const r = set(state, replace as any)\n if (!isRecording) return r\n const action: { type: string } =\n nameOrAction === undefined\n ? {\n type:\n anonymousActionType ||\n findCallerName(new Error().stack) ||\n 'anonymous',\n }\n : typeof nameOrAction === 'string'\n ? { type: nameOrAction }\n : nameOrAction\n if (store === undefined) {\n connection?.send(action, get())\n return r\n }\n connection?.send(\n {\n ...action,\n type: `${store}/${action.type}`,\n },\n {\n ...getTrackedConnectionState(options.name),\n [store]: api.getState(),\n },\n )\n return r\n }) as NamedSet\n ;(api as StoreApi & StoreDevtools).devtools = {\n cleanup: () => {\n if (\n connection &&\n typeof (connection as any).unsubscribe === 'function'\n ) {\n ;(connection as any).unsubscribe()\n }\n removeStoreFromTrackedConnections(options.name, store)\n },\n }\n\n const setStateFromDevtools: StoreApi['setState'] = (...a) => {\n const originalIsRecording = isRecording\n isRecording = false\n set(...(a as Parameters))\n isRecording = originalIsRecording\n }\n\n const initialState = fn(api.setState, get, api)\n if (connectionInformation.type === 'untracked') {\n connection?.init(initialState)\n } else {\n connectionInformation.stores[connectionInformation.store] = api\n connection?.init(\n Object.fromEntries(\n Object.entries(connectionInformation.stores).map(([key, store]) => [\n key,\n key === connectionInformation.store\n ? initialState\n : store.getState(),\n ]),\n ),\n )\n }\n\n if (shouldDispatchFromDevtools(api)) {\n let didWarnAboutReservedActionType = false\n const originalDispatch = api.dispatch\n api.dispatch = (...args: any[]) => {\n if (\n import.meta.env?.MODE !== 'production' &&\n args[0].type === '__setState' &&\n !didWarnAboutReservedActionType\n ) {\n console.warn(\n '[zustand devtools middleware] \"__setState\" action type is reserved ' +\n 'to set state from the devtools. Avoid using it.',\n )\n didWarnAboutReservedActionType = true\n }\n originalDispatch(...args)\n }\n }","path":"src/middleware/devtools.ts","title":"devtools.ts","source_type":"src","kind":"source"} -{"id":"244","text":"oduction' &&\n args[0].type === '__setState' &&\n !didWarnAboutReservedActionType\n ) {\n console.warn(\n '[zustand devtools middleware] \"__setState\" action type is reserved ' +\n 'to set state from the devtools. Avoid using it.',\n )\n didWarnAboutReservedActionType = true\n }\n originalDispatch(...args)\n }\n }\n\n ;(\n connection as unknown as {\n // FIXME https://github.com/reduxjs/redux-devtools/issues/1097\n subscribe: (\n listener: (message: Message) => void,\n ) => (() => void) | undefined\n }\n ).subscribe((message) => {\n switch (message.type) {\n case 'ACTION':\n if (typeof message.payload !== 'string') {\n console.error(\n '[zustand devtools middleware] Unsupported action format',\n )\n return\n }\n return parseJsonThen<{ type: unknown; state?: PartialState }>(\n message.payload,\n (action) => {\n if (action.type === '__setState') {\n if (store === undefined) {\n setStateFromDevtools(action.state as PartialState)\n return\n }\n if (Object.keys(action.state as S).length !== 1) {\n console.error(\n `\n [zustand devtools middleware] Unsupported __setState action format.\n When using 'store' option in devtools(), the 'state' should have only one key, which is a value of 'store' that was passed in devtools(),\n and value of this only key should be a state object. Example: { \"type\": \"__setState\", \"state\": { \"abc123Store\": { \"foo\": \"bar\" } } }\n `,\n )\n }\n const stateFromDevtools = (action.state as S)[store]\n if (\n stateFromDevtools === undefined ||\n stateFromDevtools === null\n ) {\n return\n }\n if (\n JSON.stringify(api.getState()) !==\n JSON.stringify(stateFromDevtools)\n ) {\n setStateFromDevtools(stateFromDevtools)\n }\n return\n }\n\n if (shouldDispatchFromDevtools(api)) {\n api.dispatch(action)\n }\n },\n )\n\n case 'DISPATCH':\n switch (message.payload.type) {\n case 'RESET':\n setStateFromDevtools(initialState as S)\n if (store === undefined) {\n return connection?.init(api.getState())\n }\n return connection?.init(getTrackedConnectionState(options.name))\n\n case 'COMMIT':\n if (store === undefined) {\n connection?.init(api.getState())\n return\n }\n return connection?.init(getTrackedConnectionState(options.name))\n\n case 'ROLLBACK':\n return parseJsonThen(message.state, (state) => {\n if (store === undefined) {\n setStateFromDevtools(state)\n connection?.init(api.getState())\n return\n }\n setStateFromDevtools(state[store] as S)\n connection?.init(getTrackedConnectionState(options.name))\n })\n\n case 'JUMP_TO_STATE':\n case 'JUMP_TO_ACTION':\n return parseJsonThen(message.state, (state) => {\n if (store === undefined) {\n setStateFromDevtools(state)\n return\n }\n if (\n JSON.stringify(api.getState()) !==\n JSON.stringify(state[store])\n ) {\n setStateFromDevtools(state[store] as S)\n }\n })","path":"src/middleware/devtools.ts","title":"devtools.ts","source_type":"src","kind":"source"} -{"id":"245","text":"hen(message.state, (state) => {\n if (store === undefined) {\n setStateFromDevtools(state)\n return\n }\n if (\n JSON.stringify(api.getState()) !==\n JSON.stringify(state[store])\n ) {\n setStateFromDevtools(state[store] as S)\n }\n })\n\n case 'IMPORT_STATE': {\n const { nextLiftedState } = message.payload\n const lastComputedState =\n nextLiftedState.computedStates.slice(-1)[0]?.state\n if (!lastComputedState) return\n if (store === undefined) {\n setStateFromDevtools(lastComputedState)\n } else {\n setStateFromDevtools(lastComputedState[store])\n }\n connection?.send(\n null as any, // FIXME no-any\n nextLiftedState,\n )\n return\n }\n\n case 'PAUSE_RECORDING':\n return (isRecording = !isRecording)\n }\n return\n }\n })\n\n return initialState\n }\n","path":"src/middleware/devtools.ts","title":"devtools.ts","source_type":"src","kind":"source"} -{"id":"246","text":"export const devtools = devtoolsImpl as unknown as Devtools\n\nconst parseJsonThen = (stringified: string, fn: (parsed: T) => void) => {\n let parsed: T | undefined\n try {\n parsed = JSON.parse(stringified)\n } catch (e) {\n console.error(\n '[zustand devtools middleware] Could not parse the received json',\n e,\n )\n }\n if (parsed !== undefined) fn(parsed as T)\n}\n","path":"src/middleware/devtools.ts","title":"devtools.ts","source_type":"src","kind":"source"} -{"id":"247","text":"Source src/middleware/immer.ts (full):\nimport { produce } from 'immer'\nimport type { Draft } from 'immer'\nimport type { StateCreator, StoreMutatorIdentifier } from '../vanilla.ts'\n\ntype Immer = <\n T,\n Mps extends [StoreMutatorIdentifier, unknown][] = [],\n Mcs extends [StoreMutatorIdentifier, unknown][] = [],\n U = T,\n>(\n initializer: StateCreator,\n) => StateCreator\n\ndeclare module '../vanilla' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface StoreMutators {\n ['zustand/immer']: WithImmer\n }\n}\n\ntype Write = Omit & U\ntype SkipTwo = T extends { length: 0 }\n ? []\n : T extends { length: 1 }\n ? []\n : T extends { length: 0 | 1 }\n ? []\n : T extends [unknown, unknown, ...infer A]\n ? A\n : T extends [unknown, unknown?, ...infer A]\n ? A\n : T extends [unknown?, unknown?, ...infer A]\n ? A\n : never\n\ntype SetStateType = Exclude any>\n\ntype WithImmer = Write>\n\ntype StoreImmer = S extends {\n setState: infer SetState\n}\n ? SetState extends {\n (...args: infer A1): infer Sr1\n (...args: infer A2): infer Sr2\n }\n ? {\n // Ideally, we would want to infer the `nextStateOrUpdater` `T` type from the\n // `A1` type, but this is infeasible since it is an intersection with\n // a partial type.\n setState(\n nextStateOrUpdater:\n | SetStateType\n | Partial>\n | ((state: Draft>) => void),\n shouldReplace?: false,\n ...args: SkipTwo\n ): Sr1\n setState(\n nextStateOrUpdater:\n | SetStateType\n | ((state: Draft>) => void),\n shouldReplace: true,\n ...args: SkipTwo\n ): Sr2\n }\n : never\n : never\n\ntype ImmerImpl = (\n storeInitializer: StateCreator,\n) => StateCreator\n\nconst immerImpl: ImmerImpl = (initializer) => (set, get, store) => {\n type T = ReturnType\n\n store.setState = (updater, replace, ...args) => {\n const nextState = (\n typeof updater === 'function' ? produce(updater as any) : updater\n ) as ((s: T) => T) | T | Partial\n\n return set(nextState, replace as any, ...args)\n }\n\n return initializer(store.setState, get, store)\n}\n\n","path":"src/middleware/immer.ts","title":"immer.ts","source_type":"src","kind":"source"} -{"id":"248","text":"export const immer = immerImpl as unknown as Immer\n","path":"src/middleware/immer.ts","title":"immer.ts","source_type":"src","kind":"source"} -{"id":"249","text":"Source src/middleware/persist.ts (full):\nimport type {\n StateCreator,\n StoreApi,\n StoreMutatorIdentifier,\n} from '../vanilla.ts'\n\nexport interface StateStorage {\n getItem: (name: string) => string | null | Promise\n setItem: (name: string, value: string) => R\n removeItem: (name: string) => R\n}\n\nexport type StorageValue = {\n state: S\n version?: number\n}\n\nexport interface PersistStorage {\n getItem: (\n name: string,\n ) => StorageValue | null | Promise | null>\n setItem: (name: string, value: StorageValue) => R\n removeItem: (name: string) => R\n}\n\ntype JsonStorageOptions = {\n reviver?: (key: string, value: unknown) => unknown\n replacer?: (key: string, value: unknown) => unknown\n}\n\nexport function createJSONStorage(\n getStorage: () => StateStorage,\n options?: JsonStorageOptions,\n): PersistStorage | undefined {\n let storage: StateStorage | undefined\n try {\n storage = getStorage()\n } catch {\n // prevent error if the storage is not defined (e.g. when server side rendering a page)\n return\n }\n const persistStorage: PersistStorage = {\n getItem: (name) => {\n const parse = (str: string | null) => {\n if (str === null) {\n return null\n }\n return JSON.parse(str, options?.reviver) as StorageValue\n }\n const str = storage.getItem(name) ?? null\n if (str instanceof Promise) {\n return str.then(parse)\n }\n return parse(str)\n },\n setItem: (name, newValue) =>\n storage.setItem(name, JSON.stringify(newValue, options?.replacer)),\n removeItem: (name) => storage.removeItem(name),\n }\n return persistStorage\n}\n\n","path":"src/middleware/persist.ts","title":"persist.ts","source_type":"src","kind":"source"} -{"id":"250","text":"export interface PersistOptions<\n S,\n PersistedState = S,\n PersistReturn = unknown,\n> {\n /** Name of the storage (must be unique) */\n name: string\n /**\n * Use a custom persist storage.\n *\n * Combining `createJSONStorage` helps creating a persist storage\n * with JSON.parse and JSON.stringify.\n *\n * @default createJSONStorage(() => window.localStorage)\n */\n storage?: PersistStorage | undefined\n /**\n * Filter the persisted value.\n *\n * @params state The state's value\n */\n partialize?: (state: S) => PersistedState\n /**\n * A function returning another (optional) function.\n * The main function will be called before the state rehydration.\n * The returned function will be called after the state rehydration or when an error occurred.\n */\n onRehydrateStorage?: (\n state: S,\n ) => ((state?: S, error?: unknown) => void) | void\n /**\n * If the stored state's version mismatch the one specified here, the storage will not be used.\n * This is useful when adding a breaking change to your store.\n */\n version?: number\n /**\n * A function to perform persisted state migration.\n * This function will be called when persisted state versions mismatch with the one specified here.\n */\n migrate?: (\n persistedState: unknown,\n version: number,\n ) => PersistedState | Promise\n /**\n * A function to perform custom hydration merges when combining the stored state with the current one.\n * By default, this function does a shallow merge.\n */\n merge?: (persistedState: unknown, currentState: S) => S\n\n /**\n * An optional boolean that will prevent the persist middleware from triggering hydration on initialization,\n * This allows you to call `rehydrate()` at a specific point in your apps rendering life-cycle.\n *\n * This is useful in SSR application.\n *\n * @default false\n */\n skipHydration?: boolean\n}\n\ntype PersistListener = (state: S) => void\n\ntype StorePersist = S extends {\n getState: () => infer T\n setState: {\n // capture both overloads of setState\n (...args: infer Sa1): infer Sr1\n (...args: infer Sa2): infer Sr2\n }\n}\n ? {\n setState(...args: Sa1): Sr1 | Pr\n setState(...args: Sa2): Sr2 | Pr\n persist: {\n setOptions: (options: Partial>) => void\n clearStorage: () => void\n rehydrate: () => Promise | void\n hasHydrated: () => boolean\n onHydrate: (fn: PersistListener) => () => void\n onFinishHydration: (fn: PersistListener) => () => void\n getOptions: () => Partial>\n }\n }\n : never\n\ntype Thenable = {\n then(\n onFulfilled: (value: Value) => V | Promise | Thenable,\n ): Thenable\n catch(\n onRejected: (reason: Error) => V | Promise | Thenable,\n ): Thenable\n}\n\nconst toThenable =\n (\n","path":"src/middleware/persist.ts","title":"persist.ts","source_type":"src","kind":"source"} -{"id":"251","text":" fn: (input: Input) => Result | Promise | Thenable,\n ) =>\n (input: Input): Thenable => {\n try {\n const result = fn(input)\n if (result instanceof Promise) {\n return result as Thenable\n }\n return {\n then(onFulfilled) {\n return toThenable(onFulfilled)(result as Result)\n },\n catch(_onRejected) {\n return this as Thenable\n },\n }\n } catch (e: any) {\n return {\n then(_onFulfilled) {\n return this as Thenable\n },\n catch(onRejected) {\n return toThenable(onRejected)(e)\n },\n }\n }\n }\n\nconst persistImpl: PersistImpl = (config, baseOptions) => (set, get, api) => {\n type S = ReturnType\n let options = {\n storage: createJSONStorage(() => window.localStorage),\n partialize: (state: S) => state,\n version: 0,\n merge: (persistedState: unknown, currentState: S) => ({\n ...currentState,\n ...(persistedState as object),\n }),\n ...baseOptions,\n }\n\n let hasHydrated = false\n // Counter to track hydration versions and prevent race conditions\n // when multiple rehydrate() calls happen concurrently\n let hydrationVersion = 0\n const hydrationListeners = new Set>()\n const finishHydrationListeners = new Set>()\n let storage = options.storage\n\n if (!storage) {\n return config(\n (...args) => {\n console.warn(\n `[zustand persist middleware] Unable to update item '${options.name}', the given storage is currently unavailable.`,\n )\n set(...(args as Parameters))\n },\n get,\n api,\n )\n }\n\n const setItem = () => {\n const state = options.partialize({ ...get() })\n return (storage as PersistStorage).setItem(options.name, {\n state,\n version: options.version,\n })\n }\n\n const savedSetState = api.setState\n\n api.setState = (state, replace) => {\n savedSetState(state, replace as any)\n return setItem()\n }\n\n const configResult = config(\n (...args) => {\n set(...(args as Parameters))\n return setItem()\n },\n get,\n api,\n )\n\n api.getInitialState = () => configResult\n\n // a workaround to solve the issue of not storing rehydrated state in sync storage\n // the set(state) value would be later overridden with initial state by create()\n // to avoid this, we merge the state from localStorage into the initial state.\n let stateFromStorage: S | undefined\n\n // rehydrate initial state with existing stored state\n const hydrate = () => {\n if (!storage) return\n\n // On the first invocation of 'hydrate', state will not yet be defined (this is\n // true for both the 'asynchronous' and 'synchronous' case). Pass 'configResult'\n // as a backup to 'get()' so listeners and 'onRehydrateStorage' are called with\n // the latest available state.\n\n // Increment version to invalidate any in-flight hydration\n const currentVersion = ++hydrationVersion\n hasHydrated = false\n hydrationListeners.forEach((cb) => cb(get() ?? configResult))\n\n const postRehydrationCallback =\n options.onRehydrateStorage?.(get() ?? configResult) || undefined","path":"src/middleware/persist.ts","title":"persist.ts","source_type":"src","kind":"source"} -{"id":"252","text":"()' so listeners and 'onRehydrateStorage' are called with\n // the latest available state.\n\n // Increment version to invalidate any in-flight hydration\n const currentVersion = ++hydrationVersion\n hasHydrated = false\n hydrationListeners.forEach((cb) => cb(get() ?? configResult))\n\n const postRehydrationCallback =\n options.onRehydrateStorage?.(get() ?? configResult) || undefined\n\n // bind is used to avoid `TypeError: Illegal invocation` error\n return toThenable(storage.getItem.bind(storage))(options.name)\n .then((deserializedStorageValue) => {\n if (deserializedStorageValue) {\n if (\n typeof deserializedStorageValue.version === 'number' &&\n deserializedStorageValue.version !== options.version\n ) {\n if (options.migrate) {\n const migration = options.migrate(\n deserializedStorageValue.state,\n deserializedStorageValue.version,\n )\n if (migration instanceof Promise) {\n return migration.then((result) => [true, result] as const)\n }\n return [true, migration] as const\n }\n console.error(\n `State loaded from storage couldn't be migrated since no migrate function was provided`,\n )\n } else {\n return [false, deserializedStorageValue.state] as const\n }\n }\n return [false, undefined] as const\n })\n .then((migrationResult) => {\n // Abort if a newer hydration has started\n if (currentVersion !== hydrationVersion) {\n return\n }\n const [migrated, migratedState] = migrationResult\n stateFromStorage = options.merge(\n migratedState as S,\n get() ?? configResult,\n )\n\n set(stateFromStorage as S, true)\n if (migrated) {\n return setItem()\n }\n })\n .then(() => {\n // Abort if a newer hydration has started\n if (currentVersion !== hydrationVersion) {\n return\n }\n postRehydrationCallback?.(get(), undefined)\n\n // It's possible that 'postRehydrationCallback' updated the state. To ensure\n // that isn't overwritten when returning 'stateFromStorage' below\n // (synchronous-case only), update 'stateFromStorage' to point to the latest\n // state. In the asynchronous case, 'stateFromStorage' isn't used after this\n // callback, so there's no harm in updating it to match the latest state.\n stateFromStorage = get()\n hasHydrated = true\n finishHydrationListeners.forEach((cb) => cb(stateFromStorage as S))\n })\n .catch((e: Error) => {\n // Abort if a newer hydration has started\n if (currentVersion !== hydrationVersion) {\n return\n }\n postRehydrationCallback?.(undefined, e)\n })\n }\n\n ;(api as StoreApi & StorePersist, S, unknown>).persist = {\n setOptions: (newOptions) => {\n options = {\n ...options,\n ...newOptions,\n }\n\n if (newOptions.storage) {\n storage = newOptions.storage\n }\n },\n clearStorage: () => {\n storage?.removeItem(options.name)\n },\n getOptions: () => options,\n rehydrate: () => hydrate() as Promise,\n hasHydrated: () => hasHydrated,\n onHydrate: (cb) => {\n hydrationListeners.add(cb)\n\n return () => {\n hydrationListeners.delete(cb)\n }\n },\n onFinishHydration: (cb) => {\n finishHydrationListeners.add(cb)\n\n return () => {\n finishHydrationListeners.delete(cb)\n }\n },\n }\n\n if (!options.skipHydration) {\n hydrate()\n }\n\n return stateFromStorage || configResult\n}","path":"src/middleware/persist.ts","title":"persist.ts","source_type":"src","kind":"source"} -{"id":"253","text":"> hasHydrated,\n onHydrate: (cb) => {\n hydrationListeners.add(cb)\n\n return () => {\n hydrationListeners.delete(cb)\n }\n },\n onFinishHydration: (cb) => {\n finishHydrationListeners.add(cb)\n\n return () => {\n finishHydrationListeners.delete(cb)\n }\n },\n }\n\n if (!options.skipHydration) {\n hydrate()\n }\n\n return stateFromStorage || configResult\n}\n\ntype Persist = <\n T,\n Mps extends [StoreMutatorIdentifier, unknown][] = [],\n Mcs extends [StoreMutatorIdentifier, unknown][] = [],\n U = T,\n>(\n initializer: StateCreator,\n options: PersistOptions,\n) => StateCreator\n\ndeclare module '../vanilla' {\n interface StoreMutators {\n 'zustand/persist': WithPersist\n }\n}\n\ntype Write = Omit & U\n\ntype WithPersist = Write>\n\ntype PersistImpl = (\n storeInitializer: StateCreator,\n options: PersistOptions,\n) => StateCreator\n\n","path":"src/middleware/persist.ts","title":"persist.ts","source_type":"src","kind":"source"} -{"id":"254","text":"export const persist = persistImpl as unknown as Persist\n","path":"src/middleware/persist.ts","title":"persist.ts","source_type":"src","kind":"source"} -{"id":"255","text":"Source src/middleware/redux.ts (full):\nimport type { StateCreator, StoreMutatorIdentifier } from '../vanilla.ts'\nimport type { NamedSet } from './devtools.ts'\n\ntype Write = Omit & U\n\ntype Action = { type: string }\n\ntype StoreRedux = {\n dispatch: (a: A) => A\n dispatchFromDevtools: true\n}\n\ntype ReduxState = {\n dispatch: StoreRedux['dispatch']\n}\n\ntype WithRedux = Write>\n\ntype Redux = <\n T,\n A extends Action,\n Cms extends [StoreMutatorIdentifier, unknown][] = [],\n>(\n reducer: (state: T, action: A) => T,\n initialState: T,\n) => StateCreator>, Cms, [['zustand/redux', A]]>\n\ndeclare module '../vanilla' {\n interface StoreMutators {\n 'zustand/redux': WithRedux\n }\n}\n\ntype ReduxImpl = (\n reducer: (state: T, action: A) => T,\n initialState: T,\n) => StateCreator, [], []>\n\nconst reduxImpl: ReduxImpl = (reducer, initial) => (set, _get, api) => {\n type S = typeof initial\n type A = Parameters[1]\n ;(api as any).dispatch = (action: A) => {\n ;(set as NamedSet)((state: S) => reducer(state, action), false, action)\n return action\n }\n ;(api as any).dispatchFromDevtools = true\n\n return { dispatch: (...args) => (api as any).dispatch(...args), ...initial }\n}\nexport const redux = reduxImpl as unknown as Redux\n","path":"src/middleware/redux.ts","title":"redux.ts","source_type":"src","kind":"source"} -{"id":"256","text":"Source src/middleware/ssrSafe.ts (full):\nimport type { StateCreator, StoreMutatorIdentifier } from '../vanilla.ts'\n\n// This is experimental middleware. It will be changed before finalizing it.\n// https://github.com/pmndrs/zustand/discussions/2740\n// TODO Not very happy with the middleware name. Will revisit it later.\nexport function ssrSafe<\n T extends object,\n U extends object,\n Mps extends [StoreMutatorIdentifier, unknown][] = [],\n Mcs extends [StoreMutatorIdentifier, unknown][] = [],\n>(\n config: StateCreator,\n isSSR: boolean = typeof window === 'undefined',\n): StateCreator {\n return (set, get, api) => {\n if (!isSSR) {\n return config(set, get, api)\n }\n const ssrSet = () => {\n throw new Error('Cannot set state of Zustand store in SSR')\n }\n api.setState = ssrSet\n return config(ssrSet as never, get, api)\n }\n}\n","path":"src/middleware/ssrSafe.ts","title":"ssrSafe.ts","source_type":"src","kind":"source"} -{"id":"257","text":"Source src/middleware/subscribeWithSelector.ts (full):\nimport type { StateCreator, StoreMutatorIdentifier } from '../vanilla.ts'\n\ntype SubscribeWithSelector = <\n T,\n Mps extends [StoreMutatorIdentifier, unknown][] = [],\n Mcs extends [StoreMutatorIdentifier, unknown][] = [],\n>(\n initializer: StateCreator<\n T,\n [...Mps, ['zustand/subscribeWithSelector', never]],\n Mcs\n >,\n) => StateCreator\n\ntype Write = Omit & U\n\ntype WithSelectorSubscribe = S extends { getState: () => infer T }\n ? Write>\n : never\n\ndeclare module '../vanilla' {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n interface StoreMutators {\n ['zustand/subscribeWithSelector']: WithSelectorSubscribe\n }\n}\n\ntype StoreSubscribeWithSelector = {\n subscribe: {\n (listener: (selectedState: T, previousSelectedState: T) => void): () => void\n (\n selector: (state: T) => U,\n listener: (selectedState: U, previousSelectedState: U) => void,\n options?: {\n equalityFn?: (a: U, b: U) => boolean\n fireImmediately?: boolean\n },\n ): () => void\n }\n}\n\ntype SubscribeWithSelectorImpl = (\n storeInitializer: StateCreator,\n) => StateCreator\n\nconst subscribeWithSelectorImpl: SubscribeWithSelectorImpl =\n (fn) => (set, get, api) => {\n type S = ReturnType\n type Listener = (state: S, previousState: S) => void\n const origSubscribe = api.subscribe as (listener: Listener) => () => void\n api.subscribe = ((selector: any, optListener: any, options: any) => {\n let listener: Listener = selector // if no selector\n if (optListener) {\n const equalityFn = options?.equalityFn || Object.is\n let currentSlice = selector(api.getState())\n listener = (state) => {\n const nextSlice = selector(state)\n if (!equalityFn(currentSlice, nextSlice)) {\n const previousSlice = currentSlice\n optListener((currentSlice = nextSlice), previousSlice)\n }\n }\n if (options?.fireImmediately) {\n optListener(currentSlice, currentSlice)\n }\n }\n return origSubscribe(listener)\n }) as any\n const initialState = fn(set, get, api)\n return initialState\n }\n","path":"src/middleware/subscribeWithSelector.ts","title":"subscribeWithSelector.ts","source_type":"src","kind":"source"} -{"id":"258","text":"export const subscribeWithSelector =\n subscribeWithSelectorImpl as unknown as SubscribeWithSelector\n","path":"src/middleware/subscribeWithSelector.ts","title":"subscribeWithSelector.ts","source_type":"src","kind":"source"} -{"id":"259","text":"Source src/middleware.ts (full):\nexport { redux } from './middleware/redux.ts'\nexport {\n devtools,\n type DevtoolsOptions,\n type NamedSet,\n} from './middleware/devtools.ts'\nexport { subscribeWithSelector } from './middleware/subscribeWithSelector.ts'\nexport { combine } from './middleware/combine.ts'\nexport {\n persist,\n createJSONStorage,\n type StateStorage,\n type StorageValue,\n type PersistStorage,\n type PersistOptions,\n} from './middleware/persist.ts'\nexport { ssrSafe as unstable_ssrSafe } from './middleware/ssrSafe.ts'\n","path":"src/middleware.ts","title":"middleware.ts","source_type":"src","kind":"source"} -{"id":"260","text":"Source src/react/shallow.ts (full):\nimport React from 'react'\nimport { shallow } from '../vanilla/shallow.ts'\n\nexport function useShallow(selector: (state: S) => U): (state: S) => U {\n const prev = React.useRef(undefined)\n return (state) => {\n const next = selector(state)\n return shallow(prev.current, next)\n ? (prev.current as U)\n : (prev.current = next)\n }\n}\n","path":"src/react/shallow.ts","title":"shallow.ts","source_type":"src","kind":"source"} -{"id":"261","text":"Source src/react.ts (full):\nimport React from 'react'\nimport { createStore } from './vanilla.ts'\nimport type {\n ExtractState,\n Mutate,\n StateCreator,\n StoreApi,\n StoreMutatorIdentifier,\n} from './vanilla.ts'\n\ntype ReadonlyStoreApi = Pick<\n StoreApi,\n 'getState' | 'getInitialState' | 'subscribe'\n>\n\nconst identity = (arg: T): T => arg\nexport function useStore>(\n api: S,\n): ExtractState\n\nexport function useStore, U>(\n api: S,\n selector: (state: ExtractState) => U,\n): U\n\nexport function useStore(\n api: ReadonlyStoreApi,\n selector: (state: TState) => StateSlice = identity as any,\n) {\n const slice = React.useSyncExternalStore(\n api.subscribe,\n React.useCallback(() => selector(api.getState()), [api, selector]),\n React.useCallback(() => selector(api.getInitialState()), [api, selector]),\n )\n React.useDebugValue(slice)\n return slice\n}\n\nexport type UseBoundStore> = {\n (): ExtractState\n (selector: (state: ExtractState) => U): U\n} & S\n\ntype Create = {\n (\n initializer: StateCreator,\n ): UseBoundStore, Mos>>\n (): (\n initializer: StateCreator,\n ) => UseBoundStore, Mos>>\n}\n\nconst createImpl = (createState: StateCreator) => {\n const api = createStore(createState)\n\n const useBoundStore: any = (selector?: any) => useStore(api, selector)\n\n Object.assign(useBoundStore, api)\n\n return useBoundStore\n}\n\nexport const create = ((createState: StateCreator | undefined) =>\n createState ? createImpl(createState) : createImpl) as Create\n","path":"src/react.ts","title":"react.ts","source_type":"src","kind":"source"} -{"id":"262","text":"Source src/shallow.ts (full):\nexport { shallow } from './vanilla/shallow.ts'\nexport { useShallow } from './react/shallow.ts'\n","path":"src/shallow.ts","title":"shallow.ts","source_type":"src","kind":"source"} -{"id":"263","text":"Source src/traditional.ts (full):\nimport React from 'react'\nimport useSyncExternalStoreExports from 'use-sync-external-store/shim/with-selector'\nimport { createStore } from './vanilla.ts'\nimport type {\n ExtractState,\n Mutate,\n StateCreator,\n StoreApi,\n StoreMutatorIdentifier,\n} from './vanilla.ts'\n\nconst { useSyncExternalStoreWithSelector } = useSyncExternalStoreExports\n\ntype ReadonlyStoreApi = Pick<\n StoreApi,\n 'getState' | 'getInitialState' | 'subscribe'\n>\n\nconst identity = (arg: T): T => arg\n\nexport function useStoreWithEqualityFn>(\n api: S,\n): ExtractState\n\nexport function useStoreWithEqualityFn, U>(\n api: S,\n selector: (state: ExtractState) => U,\n equalityFn?: (a: U, b: U) => boolean,\n): U\n\nexport function useStoreWithEqualityFn(\n api: ReadonlyStoreApi,\n selector: (state: TState) => StateSlice = identity as any,\n equalityFn?: (a: StateSlice, b: StateSlice) => boolean,\n) {\n const slice = useSyncExternalStoreWithSelector(\n api.subscribe,\n api.getState,\n api.getInitialState,\n selector,\n equalityFn,\n )\n React.useDebugValue(slice)\n return slice\n}\n\n","path":"src/traditional.ts","title":"traditional.ts","source_type":"src","kind":"source"} -{"id":"264","text":"export type UseBoundStoreWithEqualityFn> = {\n (): ExtractState\n (\n selector: (state: ExtractState) => U,\n equalityFn?: (a: U, b: U) => boolean,\n ): U\n} & S\n\ntype CreateWithEqualityFn = {\n (\n initializer: StateCreator,\n defaultEqualityFn?: (a: U, b: U) => boolean,\n ): UseBoundStoreWithEqualityFn, Mos>>\n (): (\n initializer: StateCreator,\n defaultEqualityFn?: (a: U, b: U) => boolean,\n ) => UseBoundStoreWithEqualityFn, Mos>>\n}\n\nconst createWithEqualityFnImpl = (\n createState: StateCreator,\n defaultEqualityFn?: (a: U, b: U) => boolean,\n) => {\n const api = createStore(createState)\n\n const useBoundStoreWithEqualityFn: any = (\n selector?: any,\n equalityFn = defaultEqualityFn,\n ) => useStoreWithEqualityFn(api, selector, equalityFn)\n\n Object.assign(useBoundStoreWithEqualityFn, api)\n\n return useBoundStoreWithEqualityFn\n}\n\nexport const createWithEqualityFn = ((\n createState: StateCreator | undefined,\n defaultEqualityFn?: (a: U, b: U) => boolean,\n) =>\n createState\n ? createWithEqualityFnImpl(createState, defaultEqualityFn)\n : createWithEqualityFnImpl) as CreateWithEqualityFn\n","path":"src/traditional.ts","title":"traditional.ts","source_type":"src","kind":"source"} -{"id":"265","text":"Source src/types.d.ts (full):\ndeclare interface ImportMeta {\n env?: {\n MODE: string\n }\n}\n","path":"src/types.d.ts","title":"types.d.ts","source_type":"src","kind":"source"} -{"id":"266","text":"Source src/vanilla/shallow.ts (full):\nconst isIterable = (obj: object): obj is Iterable =>\n Symbol.iterator in obj\n\nconst hasIterableEntries = (\n value: Iterable,\n): value is Iterable & {\n entries(): Iterable<[unknown, unknown]>\n} =>\n // HACK: avoid checking entries type\n 'entries' in value\n\nconst compareEntries = (\n valueA: { entries(): Iterable<[unknown, unknown]> },\n valueB: { entries(): Iterable<[unknown, unknown]> },\n) => {\n const mapA = valueA instanceof Map ? valueA : new Map(valueA.entries())\n const mapB = valueB instanceof Map ? valueB : new Map(valueB.entries())\n if (mapA.size !== mapB.size) {\n return false\n }\n for (const [key, value] of mapA) {\n if (!mapB.has(key) || !Object.is(value, mapB.get(key))) {\n return false\n }\n }\n return true\n}\n\n// Ordered iterables\nconst compareIterables = (\n valueA: Iterable,\n valueB: Iterable,\n) => {\n const iteratorA = valueA[Symbol.iterator]()\n const iteratorB = valueB[Symbol.iterator]()\n let nextA = iteratorA.next()\n let nextB = iteratorB.next()\n while (!nextA.done && !nextB.done) {\n if (!Object.is(nextA.value, nextB.value)) {\n return false\n }\n nextA = iteratorA.next()\n nextB = iteratorB.next()\n }\n return !!nextA.done && !!nextB.done\n}\n\nexport function shallow(valueA: T, valueB: T): boolean {\n if (Object.is(valueA, valueB)) {\n return true\n }\n if (\n typeof valueA !== 'object' ||\n valueA === null ||\n typeof valueB !== 'object' ||\n valueB === null\n ) {\n return false\n }\n if (Object.getPrototypeOf(valueA) !== Object.getPrototypeOf(valueB)) {\n return false\n }\n if (isIterable(valueA) && isIterable(valueB)) {\n if (hasIterableEntries(valueA) && hasIterableEntries(valueB)) {\n return compareEntries(valueA, valueB)\n }\n return compareIterables(valueA, valueB)\n }\n // assume plain objects\n return compareEntries(\n { entries: () => Object.entries(valueA) },\n { entries: () => Object.entries(valueB) },\n )\n}\n","path":"src/vanilla/shallow.ts","title":"shallow.ts","source_type":"src","kind":"source"} -{"id":"267","text":"Source src/vanilla.ts (full):\ntype SetStateInternal = {\n _(\n partial: T | Partial | { _(state: T): T | Partial }['_'],\n replace?: false,\n ): void\n _(state: T | { _(state: T): T }['_'], replace: true): void\n}['_']\n\nexport interface StoreApi {\n setState: SetStateInternal\n getState: () => T\n getInitialState: () => T\n subscribe: (listener: (state: T, prevState: T) => void) => () => void\n}\n\nexport type ExtractState = S extends { getState: () => infer T } ? T : never\n\ntype Get = K extends keyof T ? T[K] : F\n\nexport type Mutate = number extends Ms['length' & keyof Ms]\n ? S\n : Ms extends []\n ? S\n : Ms extends [[infer Mi, infer Ma], ...infer Mrs]\n ? Mutate[Mi & StoreMutatorIdentifier], Mrs>\n : never\n\nexport type StateCreator<\n T,\n Mis extends [StoreMutatorIdentifier, unknown][] = [],\n Mos extends [StoreMutatorIdentifier, unknown][] = [],\n U = T,\n> = ((\n setState: Get, Mis>, 'setState', never>,\n getState: Get, Mis>, 'getState', never>,\n store: Mutate, Mis>,\n) => U) & { $$storeMutators?: Mos }\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/no-empty-object-type\nexport interface StoreMutators {}\n","path":"src/vanilla.ts","title":"vanilla.ts","source_type":"src","kind":"source"} -{"id":"268","text":"export type StoreMutatorIdentifier = keyof StoreMutators\n\ntype CreateStore = {\n (\n initializer: StateCreator,\n ): Mutate, Mos>\n\n (): (\n initializer: StateCreator,\n ) => Mutate, Mos>\n}\n\ntype CreateStoreImpl = <\n T,\n Mos extends [StoreMutatorIdentifier, unknown][] = [],\n>(\n initializer: StateCreator,\n) => Mutate, Mos>\n\nconst createStoreImpl: CreateStoreImpl = (createState) => {\n type TState = ReturnType\n type Listener = (state: TState, prevState: TState) => void\n let state: TState\n const listeners: Set = new Set()\n\n const setState: StoreApi['setState'] = (partial, replace) => {\n // TODO: Remove type assertion once https://github.com/microsoft/TypeScript/issues/37663 is resolved\n // https://github.com/microsoft/TypeScript/issues/37663#issuecomment-759728342\n const nextState =\n typeof partial === 'function'\n ? (partial as (state: TState) => TState)(state)\n : partial\n if (!Object.is(nextState, state)) {\n const previousState = state\n state =\n (replace ?? (typeof nextState !== 'object' || nextState === null))\n ? (nextState as TState)\n : Object.assign({}, state, nextState)\n listeners.forEach((listener) => listener(state, previousState))\n }\n }\n\n const getState: StoreApi['getState'] = () => state\n\n const getInitialState: StoreApi['getInitialState'] = () =>\n initialState\n\n const subscribe: StoreApi['subscribe'] = (listener) => {\n listeners.add(listener)\n // Unsubscribe\n return () => listeners.delete(listener)\n }\n\n const api = { setState, getState, getInitialState, subscribe }\n const initialState = (state = createState(setState, getState, api))\n return api as any\n}\n\n","path":"src/vanilla.ts","title":"vanilla.ts","source_type":"src","kind":"source"} -{"id":"269","text":"export const createStore = ((createState) =>\n createState ? createStoreImpl(createState) : createStoreImpl) as CreateStore\n","path":"src/vanilla.ts","title":"vanilla.ts","source_type":"src","kind":"source"} diff --git a/kb/stores/zustand/zustand-kb.rvf b/kb/stores/zustand/zustand-kb.rvf deleted file mode 100644 index ec58907..0000000 Binary files a/kb/stores/zustand/zustand-kb.rvf and /dev/null differ diff --git a/kb/stores/zustand/zustand-kb.rvf.embed.json b/kb/stores/zustand/zustand-kb.rvf.embed.json deleted file mode 100644 index b82b54c..0000000 --- a/kb/stores/zustand/zustand-kb.rvf.embed.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "model": "Xenova/bge-small-en-v1.5", - "pooling": "mean", - "normalize": true, - "queryPrefix": "Represent this sentence for searching relevant passages: ", - "rankScale": 0.6 -} \ No newline at end of file diff --git a/kb/stores/zustand/zustand-kb.rvf.idmap.json b/kb/stores/zustand/zustand-kb.rvf.idmap.json deleted file mode 100644 index 25cff38..0000000 --- a/kb/stores/zustand/zustand-kb.rvf.idmap.json +++ /dev/null @@ -1 +0,0 @@ -{"idToLabel":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":16,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"23":23,"24":24,"25":25,"26":26,"27":27,"28":28,"29":29,"30":30,"31":31,"32":32,"33":33,"34":34,"35":35,"36":36,"37":37,"38":38,"39":39,"40":40,"41":41,"42":42,"43":43,"44":44,"45":45,"46":46,"47":47,"48":48,"49":49,"50":50,"51":51,"52":52,"53":53,"54":54,"55":55,"56":56,"57":57,"58":58,"59":59,"60":60,"61":61,"62":62,"63":63,"64":64,"65":65,"66":66,"67":67,"68":68,"69":69,"70":70,"71":71,"72":72,"73":73,"74":74,"75":75,"76":76,"77":77,"78":78,"79":79,"80":80,"81":81,"82":82,"83":83,"84":84,"85":85,"86":86,"87":87,"88":88,"89":89,"90":90,"91":91,"92":92,"93":93,"94":94,"95":95,"96":96,"97":97,"98":98,"99":99,"100":100,"101":101,"102":102,"103":103,"104":104,"105":105,"106":106,"107":107,"108":108,"109":109,"110":110,"111":111,"112":112,"113":113,"114":114,"115":115,"116":116,"117":117,"118":118,"119":119,"120":120,"121":121,"122":122,"123":123,"124":124,"125":125,"126":126,"127":127,"128":128,"129":129,"130":130,"131":131,"132":132,"133":133,"134":134,"135":135,"136":136,"137":137,"138":138,"139":139,"140":140,"141":141,"142":142,"143":143,"144":144,"145":145,"146":146,"147":147,"148":148,"149":149,"150":150,"151":151,"152":152,"153":153,"154":154,"155":155,"156":156,"157":157,"158":158,"159":159,"160":160,"161":161,"162":162,"163":163,"164":164,"165":165,"166":166,"167":167,"168":168,"169":169,"170":170,"171":171,"172":172,"173":173,"174":174,"175":175,"176":176,"177":177,"178":178,"179":179,"180":180,"181":181,"182":182,"183":183,"184":184,"185":185,"186":186,"187":187,"188":188,"189":189,"190":190,"191":191,"192":192,"193":193,"194":194,"195":195,"196":196,"197":197,"198":198,"199":199,"200":200,"201":201,"202":202,"203":203,"204":204,"205":205,"206":206,"207":207,"208":208,"209":209,"210":210,"211":211,"212":212,"213":213,"214":214,"215":215,"216":216,"217":217,"218":218,"219":219,"220":220,"221":221,"222":222,"223":223,"224":224,"225":225,"226":226,"227":227,"228":228,"229":229,"230":230,"231":231,"232":232,"233":233,"234":234,"235":235,"236":236,"237":237,"238":238,"239":239,"240":240,"241":241,"242":242,"243":243,"244":244,"245":245,"246":246,"247":247,"248":248,"249":249,"250":250,"251":251,"252":252,"253":253,"254":254,"255":255,"256":256,"257":257,"258":258,"259":259,"260":260,"261":261,"262":262,"263":263,"264":264,"265":265,"266":266,"267":267,"268":268,"269":269},"labelToId":{"1":"1","2":"2","3":"3","4":"4","5":"5","6":"6","7":"7","8":"8","9":"9","10":"10","11":"11","12":"12","13":"13","14":"14","15":"15","16":"16","17":"17","18":"18","19":"19","20":"20","21":"21","22":"22","23":"23","24":"24","25":"25","26":"26","27":"27","28":"28","29":"29","30":"30","31":"31","32":"32","33":"33","34":"34","35":"35","36":"36","37":"37","38":"38","39":"39","40":"40","41":"41","42":"42","43":"43","44":"44","45":"45","46":"46","47":"47","48":"48","49":"49","50":"50","51":"51","52":"52","53":"53","54":"54","55":"55","56":"56","57":"57","58":"58","59":"59","60":"60","61":"61","62":"62","63":"63","64":"64","65":"65","66":"66","67":"67","68":"68","69":"69","70":"70","71":"71","72":"72","73":"73","74":"74","75":"75","76":"76","77":"77","78":"78","79":"79","80":"80","81":"81","82":"82","83":"83","84":"84","85":"85","86":"86","87":"87","88":"88","89":"89","90":"90","91":"91","92":"92","93":"93","94":"94","95":"95","96":"96","97":"97","98":"98","99":"99","100":"100","101":"101","102":"102","103":"103","104":"104","105":"105","106":"106","107":"107","108":"108","109":"109","110":"110","111":"111","112":"112","113":"113","114":"114","115":"115","116":"116","117":"117","118":"118","119":"119","120":"120","121":"121","122":"122","123":"123","124":"124","125":"125","126":"126","127":"127","128":"128","129":"129","130":"130","131":"131","132":"132","133":"133","134":"134","135":"135","136":"136","137":"137","138":"138","139":"139","140":"140","141":"141","142":"142","143":"143","144":"144","145":"145","146":"146","147":"147","148":"148","149":"149","150":"150","151":"151","152":"152","153":"153","154":"154","155":"155","156":"156","157":"157","158":"158","159":"159","160":"160","161":"161","162":"162","163":"163","164":"164","165":"165","166":"166","167":"167","168":"168","169":"169","170":"170","171":"171","172":"172","173":"173","174":"174","175":"175","176":"176","177":"177","178":"178","179":"179","180":"180","181":"181","182":"182","183":"183","184":"184","185":"185","186":"186","187":"187","188":"188","189":"189","190":"190","191":"191","192":"192","193":"193","194":"194","195":"195","196":"196","197":"197","198":"198","199":"199","200":"200","201":"201","202":"202","203":"203","204":"204","205":"205","206":"206","207":"207","208":"208","209":"209","210":"210","211":"211","212":"212","213":"213","214":"214","215":"215","216":"216","217":"217","218":"218","219":"219","220":"220","221":"221","222":"222","223":"223","224":"224","225":"225","226":"226","227":"227","228":"228","229":"229","230":"230","231":"231","232":"232","233":"233","234":"234","235":"235","236":"236","237":"237","238":"238","239":"239","240":"240","241":"241","242":"242","243":"243","244":"244","245":"245","246":"246","247":"247","248":"248","249":"249","250":"250","251":"251","252":"252","253":"253","254":"254","255":"255","256":"256","257":"257","258":"258","259":"259","260":"260","261":"261","262":"262","263":"263","264":"264","265":"265","266":"266","267":"267","268":"268","269":"269"},"nextLabel":270} \ No newline at end of file diff --git a/kb/stores/zustand/zustand-primer.md b/kb/stores/zustand/zustand-primer.md deleted file mode 100644 index 64d0338..0000000 --- a/kb/stores/zustand/zustand-primer.md +++ /dev/null @@ -1,108 +0,0 @@ -# Zustand — Human Primer - -## 1. What is zustand - -Zustand is a small, fast, and scalable bearbones state management solution for React. It provides a hooks-first API that is neither boilerplatey nor opinionated, but has enough convention to be explicit and flux-like. It is published to npm and lives in the `pmndrs` organization. - -The library was built specifically to handle common React state pitfalls: the zombie child problem, React concurrency issues, and context loss between mixed renderers. - -## 2. What can it do for you - -- **Create a store with a single hook** — no providers required, no app-wrapping boilerplate. -- **Subscribe with selectors** — manually apply render optimizations by passing selector functions to your hook calls. -- **Work without React** — a vanilla (framework-free) build is available alongside the React-specific one. -- **Layer in middleware** — built-in middleware includes `devtools`, `persist`, `immer`, and `combine`, all usable from `zustand/middleware`. -- **Compose state with slices** — large stores can be split into typed slice creators and merged together. -- **Stay safe under React concurrency** — the library was designed with concurrent rendering in mind. - -Compared to Redux, it does not require your app to be wrapped in context providers. Compared to Valtio, it uses an immutable state model. Compared to Jotai and Recoil, render optimization is manual via selectors rather than automatic via atom dependency tracking. - -## 3. What is it made of (the components) - -The repo contains three components: - -| Component | Role | -|-----------|------| -| **zustand** | The core library — the thing you install and ship. | -| **demo** | A demo application; depends on the core `zustand` component. Also pulls in `@react-three/fiber`, `@react-three/drei`, `@react-three/postprocessing`, `three`, `meshline`, and related packages. | -| **starter** | A starter application; also depends on the core `zustand` component. | - -The demo and starter components are internal development/showcase tools. Only `zustand` itself is the published package. - -The core library is built in several discrete sub-targets: `base`, `vanilla`, `react`, `middleware`, `middleware/immer`, `shallow`, `vanilla/shallow`, `react/shallow`, and `traditional` — each with its own build command. - -## 4. How it works - -You define a store by calling `create` with an initializer function that receives `set` (and optionally `get`). The initializer returns the initial state and any actions: - -```ts -import { create } from 'zustand' - -interface BearState { - bears: number - increase: (by: number) => void -} - -const useBearStore = create()((set) => ({ - bears: 0, - increase: (by) => set((state) => ({ bears: state.bears + by })), -})) -``` - -Components subscribe by calling the hook with a selector. Only the selected slice of state triggers a re-render: - -```ts -const increasePopulation = useBear((state) => state.increasePopulation) -``` - -State updates are immutable — you return a new partial state from `set`, not a mutation. Middleware wraps the initializer and can extend or transform the store. For TypeScript users, the pattern is `create()(...)` — the extra parentheses matter for correct contextual inference. The `combine` middleware can infer state types automatically if you prefer not to annotate explicitly. - -The knowledge base indexes 41 public symbols across the library's entrypoints. - -## 5. How to install and use it - -**Install:** - -```bash -npm install zustand -``` - -**Minimal example:** - -```ts -import { create } from 'zustand' - -const useBearStore = create((set) => ({ - bears: 0, - increase: () => set((state) => ({ bears: state.bears + 1 })), -})) -``` - -**With middleware (TypeScript):** - -```ts -import { create } from 'zustand' -import { devtools, persist } from 'zustand/middleware' - -const useBearStore = create()( - devtools(persist((set) => ({ bears: 0, increase: (by) => set((state) => ({ bears: state.bears + by })) }), { name: 'bearStore' })) -) -``` - -**For contributors building from source**, the repo uses `pnpm`. Key commands: - -- `npm run build` — full build -- `npm run test` — runs format, type, lint, and spec checks -- `npm run fix` — formats and lints code and docs -- `npm run dev` — starts the dev server (demo or starter) - -Documentation lives at `zustand.docs.pmnd.rs` and is based on `pmndrs/docs`. - -## 6. Honest scope and limits - -- **Manual render optimization** — unlike Jotai or Recoil, Zustand does not automatically track dependencies. You are responsible for writing selectors to avoid unnecessary re-renders. -- **Immutable model only** — if you want proxy-based mutable state (like Valtio), Zustand is not that; you must return new state objects from `set`. -- **TypeScript ceremony** — the `create()()` double-call pattern is required for correct type inference; the single-call form exists but loses type safety in certain middleware scenarios. -- **`get` is unsafe at init time** — calling `get` inside the initializer before state is created returns `undefined` at runtime despite what the types suggest; the docs flag this explicitly. -- **No built-in atom dependency graph** — cross-slice reactivity requires you to wire it manually, typically via the slices pattern with `StateCreator`. -- **React is optional but the ecosystem assumes it** — the demo component depends heavily on `@react-three/fiber` and related 3D libraries, which signals the library's primary audience is React developers. diff --git a/kb/stores/zustand/zustand-symbols.json b/kb/stores/zustand/zustand-symbols.json deleted file mode 100644 index 868d1a3..0000000 --- a/kb/stores/zustand/zustand-symbols.json +++ /dev/null @@ -1,477 +0,0 @@ -{ - "target": "zustand", - "metaName": "zustand", - "generated": "2026-07-02T13:45:25.234Z", - "method": "source-scan", - "count": 41, - "byKind": { - "fn": 15, - "const": 12, - "interface": 6, - "type_alias": 8 - }, - "byCrate": { - "examples/demo": 8, - "rollup.config.mjs": 1, - "src/middleware": 14, - "src/react": 1, - "src/react.ts": 3, - "src/traditional.ts": 3, - "src/vanilla": 1, - "src/vanilla.ts": 7, - "tests/test-utils.ts": 3 - }, - "symbols": [ - { - "name": "App", - "kind": "fn", - "signature": "export default function App()", - "module": "examples::demo", - "crate": "examples/demo", - "doc": null, - "file": "examples/demo/src/App.jsx", - "line": 21, - "source": "source-scan" - }, - { - "name": "CodePreview", - "kind": "fn", - "signature": "export default function CodePreview()", - "module": "examples::demo", - "crate": "examples/demo", - "doc": null, - "file": "examples/demo/src/components/CodePreview.jsx", - "line": 15, - "source": "source-scan" - }, - { - "name": "CopyButton", - "kind": "fn", - "signature": "export default function CopyButton({ code, ...props })", - "module": "examples::demo", - "crate": "examples/demo", - "doc": "import { useState, useCallback, useRef } from 'react' import { copyToClipboard } from '../utils/copy-to-clipboard'", - "file": "examples/demo/src/components/CopyButton.jsx", - "line": 8, - "source": "source-scan" - }, - { - "name": "Details", - "kind": "fn", - "signature": "export default function Details()", - "module": "examples::demo", - "crate": "examples/demo", - "doc": null, - "file": "examples/demo/src/components/Details.jsx", - "line": 1, - "source": "source-scan" - }, - { - "name": "Fireflies", - "kind": "fn", - "signature": "export default function Fireflies({ count, colors, radius = 10 })", - "module": "examples::demo", - "crate": "examples/demo", - "doc": null, - "file": "examples/demo/src/components/Fireflies.jsx", - "line": 31, - "source": "source-scan" - }, - { - "name": "Scene", - "kind": "fn", - "signature": "export default function Scene()", - "module": "examples::demo", - "crate": "examples/demo", - "doc": null, - "file": "examples/demo/src/components/Scene.jsx", - "line": 178, - "source": "source-scan" - }, - { - "name": "SnippetLang", - "kind": "fn", - "signature": "export default function SnippetLang({ lang, setLang })", - "module": "examples::demo", - "crate": "examples/demo", - "doc": null, - "file": "examples/demo/src/components/SnippetLang.jsx", - "line": 1, - "source": "source-scan" - }, - { - "name": "copyToClipboard", - "kind": "const", - "signature": "export const copyToClipboard = (str) =>", - "module": "examples::demo", - "crate": "examples/demo", - "doc": null, - "file": "examples/demo/src/utils/copy-to-clipboard.js", - "line": 1, - "source": "source-scan" - }, - { - "name": "entries", - "kind": "const", - "signature": "export const entries = [", - "module": "rollup.config.mjs", - "crate": "rollup.config.mjs", - "doc": null, - "file": "rollup.config.mjs", - "line": 11, - "source": "source-scan" - }, - { - "name": "combine", - "kind": "fn", - "signature": "export function combine<", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/combine.ts", - "line": 5, - "source": "source-scan" - }, - { - "name": "DevtoolsOptions", - "kind": "interface", - "signature": "export interface DevtoolsOptions extends Config", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/devtools.ts", - "line": 84, - "source": "source-scan" - }, - { - "name": "NamedSet", - "kind": "type_alias", - "signature": "export type NamedSet = WithDevtools>['setState']", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/devtools.ts", - "line": 106, - "source": "source-scan" - }, - { - "name": "devtools", - "kind": "const", - "signature": "export const devtools = devtoolsImpl as unknown as Devtools", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/devtools.ts", - "line": 425, - "source": "source-scan" - }, - { - "name": "immer", - "kind": "const", - "signature": "export const immer = immerImpl as unknown as Immer", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/immer.ts", - "line": 88, - "source": "source-scan" - }, - { - "name": "StateStorage", - "kind": "interface", - "signature": "export interface StateStorage", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/persist.ts", - "line": 7, - "source": "source-scan" - }, - { - "name": "StorageValue", - "kind": "type_alias", - "signature": "export type StorageValue =", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/persist.ts", - "line": 13, - "source": "source-scan" - }, - { - "name": "PersistStorage", - "kind": "interface", - "signature": "export interface PersistStorage", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/persist.ts", - "line": 18, - "source": "source-scan" - }, - { - "name": "createJSONStorage", - "kind": "fn", - "signature": "export function createJSONStorage(", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/persist.ts", - "line": 31, - "source": "source-scan" - }, - { - "name": "PersistOptions", - "kind": "interface", - "signature": "export interface PersistOptions<", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/persist.ts", - "line": 63, - "source": "source-scan" - }, - { - "name": "persist", - "kind": "const", - "signature": "export const persist = persistImpl as unknown as Persist", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/persist.ts", - "line": 402, - "source": "source-scan" - }, - { - "name": "redux", - "kind": "const", - "signature": "export const redux = reduxImpl as unknown as Redux", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/redux.ts", - "line": 50, - "source": "source-scan" - }, - { - "name": "ssrSafe", - "kind": "fn", - "signature": "export function ssrSafe<", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/ssrSafe.ts", - "line": 6, - "source": "source-scan" - }, - { - "name": "subscribeWithSelector", - "kind": "const", - "signature": "export const subscribeWithSelector =", - "module": "src::middleware", - "crate": "src/middleware", - "doc": null, - "file": "src/middleware/subscribeWithSelector.ts", - "line": 72, - "source": "source-scan" - }, - { - "name": "useShallow", - "kind": "fn", - "signature": "export function useShallow(selector: (state: S) => U): (state: S) => U", - "module": "src::react", - "crate": "src/react", - "doc": null, - "file": "src/react/shallow.ts", - "line": 4, - "source": "source-scan" - }, - { - "name": "useStore", - "kind": "fn", - "signature": "export function useStore>(", - "module": "src::react.ts", - "crate": "src/react.ts", - "doc": null, - "file": "src/react.ts", - "line": 17, - "source": "source-scan" - }, - { - "name": "UseBoundStore", - "kind": "type_alias", - "signature": "export type UseBoundStore> =", - "module": "src::react.ts", - "crate": "src/react.ts", - "doc": null, - "file": "src/react.ts", - "line": 39, - "source": "source-scan" - }, - { - "name": "create", - "kind": "const", - "signature": "export const create = ((createState: StateCreator | undefined) =>", - "module": "src::react.ts", - "crate": "src/react.ts", - "doc": null, - "file": "src/react.ts", - "line": 63, - "source": "source-scan" - }, - { - "name": "useStoreWithEqualityFn", - "kind": "fn", - "signature": "export function useStoreWithEqualityFn>(", - "module": "src::traditional.ts", - "crate": "src/traditional.ts", - "doc": null, - "file": "src/traditional.ts", - "line": 21, - "source": "source-scan" - }, - { - "name": "UseBoundStoreWithEqualityFn", - "kind": "type_alias", - "signature": "export type UseBoundStoreWithEqualityFn> =", - "module": "src::traditional.ts", - "crate": "src/traditional.ts", - "doc": null, - "file": "src/traditional.ts", - "line": 47, - "source": "source-scan" - }, - { - "name": "createWithEqualityFn", - "kind": "const", - "signature": "export const createWithEqualityFn = ((", - "module": "src::traditional.ts", - "crate": "src/traditional.ts", - "doc": null, - "file": "src/traditional.ts", - "line": 82, - "source": "source-scan" - }, - { - "name": "shallow", - "kind": "fn", - "signature": "export function shallow(valueA: T, valueB: T): boolean", - "module": "src::vanilla", - "crate": "src/vanilla", - "doc": null, - "file": "src/vanilla/shallow.ts", - "line": 48, - "source": "source-scan" - }, - { - "name": "StoreApi", - "kind": "interface", - "signature": "export interface StoreApi", - "module": "src::vanilla.ts", - "crate": "src/vanilla.ts", - "doc": null, - "file": "src/vanilla.ts", - "line": 9, - "source": "source-scan" - }, - { - "name": "ExtractState", - "kind": "type_alias", - "signature": "export type ExtractState = S extends { getState: () => infer T } ? T : never", - "module": "src::vanilla.ts", - "crate": "src/vanilla.ts", - "doc": null, - "file": "src/vanilla.ts", - "line": 16, - "source": "source-scan" - }, - { - "name": "Mutate", - "kind": "type_alias", - "signature": "export type Mutate = number extends Ms['length' & keyof Ms]", - "module": "src::vanilla.ts", - "crate": "src/vanilla.ts", - "doc": null, - "file": "src/vanilla.ts", - "line": 20, - "source": "source-scan" - }, - { - "name": "StateCreator", - "kind": "type_alias", - "signature": "export type StateCreator<", - "module": "src::vanilla.ts", - "crate": "src/vanilla.ts", - "doc": null, - "file": "src/vanilla.ts", - "line": 28, - "source": "source-scan" - }, - { - "name": "StoreMutators", - "kind": "interface", - "signature": "export interface StoreMutators {}", - "module": "src::vanilla.ts", - "crate": "src/vanilla.ts", - "doc": null, - "file": "src/vanilla.ts", - "line": 40, - "source": "source-scan" - }, - { - "name": "StoreMutatorIdentifier", - "kind": "type_alias", - "signature": "export type StoreMutatorIdentifier = keyof StoreMutators", - "module": "src::vanilla.ts", - "crate": "src/vanilla.ts", - "doc": null, - "file": "src/vanilla.ts", - "line": 41, - "source": "source-scan" - }, - { - "name": "createStore", - "kind": "const", - "signature": "export const createStore = ((createState) =>", - "module": "src::vanilla.ts", - "crate": "src/vanilla.ts", - "doc": null, - "file": "src/vanilla.ts", - "line": 99, - "source": "source-scan" - }, - { - "name": "replacer", - "kind": "const", - "signature": "export const replacer = (", - "module": "tests::test-utils.ts", - "crate": "tests/test-utils.ts", - "doc": null, - "file": "tests/test-utils.ts", - "line": 6, - "source": "source-scan" - }, - { - "name": "reviver", - "kind": "const", - "signature": "export const reviver = (key: string, value: ReplacedMap | unknown): unknown =>", - "module": "tests::test-utils.ts", - "crate": "tests/test-utils.ts", - "doc": null, - "file": "tests/test-utils.ts", - "line": 20, - "source": "source-scan" - }, - { - "name": "sleep", - "kind": "fn", - "signature": "export function sleep(ms: number): Promise", - "module": "tests::test-utils.ts", - "crate": "tests/test-utils.ts", - "doc": null, - "file": "tests/test-utils.ts", - "line": 35, - "source": "source-scan" - } - ] -} diff --git a/kb/warm-model-cache.mjs b/kb/warm-model-cache.mjs index fd05d3f..e6141e0 100644 --- a/kb/warm-model-cache.mjs +++ b/kb/warm-model-cache.mjs @@ -1,14 +1,7 @@ #!/usr/bin/env node // warm-model-cache.mjs — make the KB embedder offline-first in hosted builds. // -// Incident 1 (2026-07-16, build 79f135b3): a Hugging Face/CloudFront failure left the Actions -// runner unable to download Xenova/bge-small-en-v1.5; station 1's mandatory real-embedding KB -// build (INV-06/07) correctly refused to fabricate grounding, and the agent burned its whole -// budget discovering that. -// Incident 2 (2026-07-17, run 29557533994 — the make-good): HF answered HTTP 429. GitHub's -// shared runner IPs are RATE-LIMITED by HF, so "wait for HF to recover" is not a fix and the -// actions/cache can never warm itself from HF. The model (MIT, 24 MB) is therefore served from -// THIS repo's own release — github.com is the one origin an Actions runner can always reach. +// Release asset first (sha256-pinned): GitHub-hosted runners are rate-limited by Hugging Face (HTTP 429). // // Source order: local cache (validate only) → our release asset → HF (last resort). // Always VALIDATES by running one real embedding — a partial/corrupt cache must fail here, @@ -18,48 +11,64 @@ import fs from 'node:fs'; import path from 'node:path'; +import crypto from 'node:crypto'; import { execFileSync } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; import { loadTransformers, configureModel, chooseModelCache } from './resolve-deps.mjs'; const MODEL = process.argv[2] || 'Xenova/bge-small-en-v1.5'; const RELEASE_ASSET = 'https://github.com/stuinfla/Repo-Explainer/releases/download/kb-models-v1/bge-small-en-v1.5.tgz'; +// sha256 of that asset. Fail closed: the archive is only unpacked when its digest equals this pin, and an +// EMPTY pin means "not pinned yet", so the release path is skipped (HF is used) rather than trusted blind. +// Set it with: curl -sL | shasum -a 256 +export const RELEASE_SHA256 = '9b0cef3ff1a2a7c94a51e8ca8303d0a57951001ef65785235f83ddca9a64fee1'; -async function fetchFromRelease(cacheRoot) { - if (MODEL !== 'Xenova/bge-small-en-v1.5') return false; // only the standard embedder is mirrored +export const sha256Hex = (buf) => crypto.createHash('sha256').update(buf).digest('hex'); +export const digestMatches = (buf, pin) => /^[0-9a-f]{64}$/.test(pin) && sha256Hex(buf) === pin; + +export async function fetchFromRelease(cacheRoot, { fetchImpl = fetch, pin = RELEASE_SHA256, model = MODEL } = {}) { + if (model !== 'Xenova/bge-small-en-v1.5') return false; // only the standard embedder is mirrored + if (!pin) { console.log('[warm-model-cache] release asset has no sha256 pin — refusing to unpack it; falling through'); return false; } console.log(`[warm-model-cache] fetching from this repo's release (HF-independent): ${RELEASE_ASSET}`); - const res = await fetch(RELEASE_ASSET, { redirect: 'follow', signal: AbortSignal.timeout(120_000) }); + const res = await fetchImpl(RELEASE_ASSET, { redirect: 'follow', signal: AbortSignal.timeout(120_000) }); if (!res.ok) { console.log(`[warm-model-cache] release asset HTTP ${res.status} — falling through`); return false; } + const bytes = Buffer.from(await res.arrayBuffer()); + if (!digestMatches(bytes, pin)) { console.log('[warm-model-cache] release asset sha256 does NOT match the pin — discarded; falling through'); return false; } const tgz = path.join(cacheRoot, 'bge-small-en-v1.5.tgz'); fs.mkdirSync(path.join(cacheRoot, 'Xenova'), { recursive: true }); - fs.writeFileSync(tgz, Buffer.from(await res.arrayBuffer())); + fs.writeFileSync(tgz, bytes); execFileSync('tar', ['xzf', tgz, '-C', path.join(cacheRoot, 'Xenova')]); fs.rmSync(tgz); - return fs.existsSync(path.join(cacheRoot, MODEL, 'onnx', 'model_quantized.onnx')); + return fs.existsSync(path.join(cacheRoot, model, 'onnx', 'model_quantized.onnx')); } -try { - const { T, via } = await loadTransformers(); - const cache = chooseModelCache(MODEL); - let { haveLocalModel } = configureModel(T, cache, MODEL); - console.log(`[warm-model-cache] ${MODEL} — ${haveLocalModel ? 'already cached' : 'not cached'} (${cache}; transformers via ${via})`); +async function main() { + try { + const { T, via } = await loadTransformers(); + const cache = chooseModelCache(); + let { haveLocalModel } = configureModel(T, cache, MODEL); + console.log(`[warm-model-cache] ${MODEL} — ${haveLocalModel ? 'already cached' : 'not cached'} (${cache}; transformers via ${via})`); - if (!haveLocalModel) { - const seeded = await fetchFromRelease(cache).catch((e) => { console.log(`[warm-model-cache] release fetch failed: ${e.message} — falling through`); return false; }); - if (seeded) { - ({ haveLocalModel } = configureModel(T, cache, MODEL)); // re-point: now offline - console.log('[warm-model-cache] seeded from release asset'); - } else { - console.log('[warm-model-cache] last resort: direct HF download (rate-limited from Actions runner IPs — expect this to fail in CI)'); + if (!haveLocalModel) { + const seeded = await fetchFromRelease(cache).catch((e) => { console.log(`[warm-model-cache] release fetch failed: ${e.message} — falling through`); return false; }); + if (seeded) { + ({ haveLocalModel } = configureModel(T, cache, MODEL)); // re-point: now offline + console.log('[warm-model-cache] seeded from release asset'); + } else { + console.log('[warm-model-cache] last resort: direct HF download (rate-limited from Actions runner IPs — expect this to fail in CI)'); + } } - } - const fe = await T.pipeline('feature-extraction', MODEL, { quantized: true }); - const out = await fe('warm-up probe', { pooling: 'mean', normalize: true }); - const dim = out?.data?.length; - if (!dim || dim < 64) throw new Error(`embedding came back with suspicious dimension ${dim}`); - console.log(`[warm-model-cache] OK — real embedding produced (${dim}-dim); KB builds are offline-first from here`); -} catch (e) { - console.error(`[warm-model-cache] FAILED: ${e.message}`); - console.error('[warm-model-cache] no usable local model and no working source (release asset + HF both failed) — the runner preflight will stop the build in seconds with a clear alert instead of burning its budget'); - process.exit(1); + const fe = await T.pipeline('feature-extraction', MODEL, { quantized: true }); + const out = await fe('warm-up probe', { pooling: 'mean', normalize: true }); + const dim = out?.data?.length; + if (!dim || dim < 64) throw new Error(`embedding came back with suspicious dimension ${dim}`); + console.log(`[warm-model-cache] OK — real embedding produced (${dim}-dim); KB builds are offline-first from here`); + } catch (e) { + console.error(`[warm-model-cache] FAILED: ${e.message}`); + console.error('[warm-model-cache] no usable local model and no working source (release asset + HF both failed) — the runner preflight will stop the build in seconds with a clear alert instead of burning its budget'); + process.exit(1); + } } + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) await main(); diff --git a/landing/index.html b/landing/index.html index d7aa4cf..c756f9d 100644 --- a/landing/index.html +++ b/landing/index.html @@ -740,8 +740,8 @@

Private repo you own? Run it in VS Code.

Recommended: run this inside a VS Code / Claude Code session, in a project whose .env already holds your keys — everything is picked up automatically. Private repo: gh auth login first.

- npx explainmyrepo <github-url> --ship-best-effort - diff --git a/landing/netlify/functions/build.js b/landing/netlify/functions/build.js index c2f040d..ad047e8 100644 --- a/landing/netlify/functions/build.js +++ b/landing/netlify/functions/build.js @@ -7,7 +7,8 @@ OWNER's keys and writes progress back to that gist. The client polls /status. Env (Netlify site settings, server-side only — never sent to the browser): - GITHUB_TOKEN PAT with `gist` + `actions:write` on stuinfla/Repo-Explainer + EXPLAINER_GH_TOKEN PAT with `gist` + `actions:write` on stuinfla/Repo-Explainer + (preferred; GITHUB_TOKEN is the fallback name) EMAIL_LEDGER_GIST_ID gist holding ledger.json (per-email counts) [optional] GLOBAL_COUNTER_GIST_ID gist holding counter.json (global monthly cap) [optional] If a meter gist id is missing we FAIL OPEN (allow the build) and log — the metering @@ -30,6 +31,9 @@ function json(statusCode, obj) { }; } +const SEGMENT_RE = /^[A-Za-z0-9_][A-Za-z0-9_.-]*$/; +function isSafeSegment(s) { return typeof s === "string" && SEGMENT_RE.test(s); } + function gh(token) { return { Accept: "application/vnd.github+json", @@ -75,6 +79,7 @@ async function bumpDoor(token, kind) { } catch { /* never block the door on its own tally */ } } +exports.isSafeSegment = isSafeSegment; exports.handler = async function (event) { if (event.httpMethod === "OPTIONS") return json(204, {}); if (event.httpMethod !== "POST") return json(405, { error: "Method not allowed" }); @@ -86,13 +91,21 @@ exports.handler = async function (event) { try { body = JSON.parse(event.body || "{}"); } catch { return json(400, { error: "Invalid JSON body." }); } const url = (body.url || "").toString(); const email = (body.email || "").toString().trim().toLowerCase(); + // The address later reaches SMTP headers and RCPT TO (tools/notify*.mjs): reject anything that is not + // ONE plain address, so a CR/LF can never ride in. Same rule as src/smtp.mjs isSafeAddress. Email is optional. + if (email && !(email.length <= 254 && /^[a-z0-9._%+'-]{1,64}@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/.test(email))) { + return json(400, { error: "That email address doesn't look right. Leave it blank or use a plain address like you@example.com." }); + } - // Accept the full URL or just "owner/name" — first real user's first ask (2026-07-09). + // Accept the full URL or just "owner/name". const match = url.trim().match(/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)/) || url.trim().match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/); if (!match) return json(400, { error: "That doesn't look like a GitHub repo — try owner/name or https://github.com/owner/name." }); const owner = match[1]; const repo = match[2].replace(/\.git$/, ""); + // "../users" matches the character class and the GitHub API normalises repos/../users to /users (a 200 with no + // `private` flag), which would bypass the public-repo check below: a path segment may not start with a dot. + if (!isSafeSegment(owner) || !isSafeSegment(repo)) return json(400, { error: "That doesn't look like a GitHub repo — try owner/name or https://github.com/owner/name." }); const fullName = owner + "/" + repo; // 1) Repo must exist + be reachable by our token (private repos 404 to anon callers). @@ -117,31 +130,13 @@ exports.handler = async function (event) { repoSizeKb = Number(repoMeta.size) || 0; } catch { return json(502, { error: "Couldn't reach GitHub — try again shortly." }); } - // Complexity tiers (size-based; component-count refinement can follow once the pipeline itself - // reports dep-graph size back, but the outer GH Actions job timeout must be fixed BEFORE dispatch, - // so a pre-flight signal is what's available here). Bigger repos get more wall-clock AND more $, - // rather than the same fixed budget regardless of scale. - // - // Floors measured live, THREE times now (2026-07-04, 2026-07-06, 2026-07-10): a first smoke - // test at 15min on `chalk` got killed mid-image-generation; raised small to 25. Then a REAL - // production front-door run on `sindresorhus/p-map` (25min) ALSO got killed, deep in a - // quality-grade refine loop; raised to 30. Then, same night as the credit-outage recovery, - // TWO more real repos (aiki-sh/cli, manjast/agentic-development-playbook) both timed out at - // 30min in the exact same spot — the refine loop's screenshot-vision-grade-fix round trips — - // and BOTH succeeded cleanly on the very next attempt at 40min (matching the existing medium - // tier). Three strikes on the same floor from three independent repos is a pattern, not noise. - // Raised small to match medium's proven-sufficient 40min. Don't lower it again without a real - // measured run to justify it. + // Size-tiered budget, fixed BEFORE dispatch (the outer job timeout cannot change later). Small repos get the + // medium floor: 25 and 30 min were each killed in the refine loop on real builds (see ADR-0011). const tier = repoSizeKb > 200000 ? "large" : repoSizeKb > 20000 ? "medium" : "small"; - const budgetMin = tier === "large" ? 60 : tier === "medium" ? 40 : 40; + const budgetMin = tier === "large" ? 60 : 40; const budgetUsd = tier === "large" ? 18 : tier === "medium" ? 10 : 7; - // GitHub Actions expressions don't support arithmetic the way `fromJSON(x) + 10` implies (learned - // the hard way — it rejects the dispatch outright, a YAML-structure check doesn't catch it since - // it's an expression-syntax error, not a YAML one). Compute the overhead buffer here in - // plain JS instead and pass the already-summed value. +25 (was +10, 2026-07-19): the buffer now - // also covers the runner's post-agent CURE stage (bounded cure agent + one verification grade + - // deploy, ≤20min worst case — see bin/cure.mjs CURE wall constants, pinned by tests/cure.test.mjs) - // so a full-budget build can still be cured instead of SIGKILLed mid-recovery. + // Actions expressions cannot add to an input, so the overhead is summed here: +25 covers the runner's cure + // stage (bin/cure.mjs, <=20 min) so a full-budget build can still be cured instead of SIGKILLed. const timeoutMin = budgetMin + 25; // 2) METERING (before we spend a cent). Fail open if the meter gists aren't configured. @@ -156,7 +151,7 @@ exports.handler = async function (event) { if (ledger && ledger[email] && ledger[email].count >= FREE_PER_EMAIL) { return json(402, { error: "You've used your " + FREE_PER_EMAIL + " free builds — thank you for trying it! " + - "To keep going, run it yourself with your own API keys: npx explainmyrepo --ship-best-effort", + "To keep going, run it yourself with your own API keys: npx explainmyrepo ", }); } } else if (!ledgerId) { @@ -167,7 +162,7 @@ exports.handler = async function (event) { if (counterId) { counter = await readGist(token, counterId, "counter.json"); if (counter && counter.month === month && typeof counter.hardCap === "number" && (counter.builds || 0) >= counter.hardCap) { - return json(503, { error: "We've hit this month's community build limit. It resets next month — or run it yourself: npx explainmyrepo --ship-best-effort" }); + return json(503, { error: "We've hit this month's community build limit. It resets next month — or run it yourself: npx explainmyrepo " }); } } else { console.warn("GLOBAL_COUNTER_GIST_ID not set — global cap disabled (fail-open)."); @@ -175,7 +170,7 @@ exports.handler = async function (event) { // 3) Create the status gist the runner will patch + the browser will poll. const buildId = (globalThis.crypto && globalThis.crypto.randomUUID) ? globalThis.crypto.randomUUID() : String(Date.now()) + Math.random().toString(16).slice(2); - const initial = { buildId, step: 0, totalSteps: 16, stepName: "Queued", status: "queued", repo: fullName, startedAt: nowIso, error: null, result: null }; + const initial = { buildId, stepName: "Queued", status: "queued", repo: fullName, startedAt: nowIso, error: null, result: null }; let gistId; try { const r = await fetch("https://api.github.com/gists", { diff --git a/package-lock.json b/package-lock.json index ba70707..d35d4b8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,56 +1,51 @@ { "name": "explainmyrepo", - "version": "3.0.0", + "version": "3.0.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "explainmyrepo", - "version": "3.0.0", + "version": "3.0.1", "license": "MIT", "dependencies": { - "@ruvector/rvf": "^0.2.2", + "@ruvector/rvf": "^0.4.2", "@xenova/transformers": "^2.17.2", - "playwright": "^1.61.1", - "sharp": "^0.35.3" + "playwright": ">=1.61.1 <1.65.0", + "sharp": "^0.35.5" }, "bin": { "explainmyrepo": "bin/explainmyrepo.mjs" }, + "devDependencies": { + "@claude-flow/aidefence": "^3.1.0" + }, "engines": { "node": ">=18" } }, - "../../.npm-global/lib/node_modules/playwright": { - "version": "1.61.1", - "license": "Apache-2.0", - "dependencies": { - "playwright-core": "1.61.1" - }, - "bin": { - "playwright": "cli.js" - }, + "node_modules/@claude-flow/aidefence": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@claude-flow/aidefence/-/aidefence-3.1.0.tgz", + "integrity": "sha512-q/y8Gyc061DIC4d8ZRIlGYpDQBiK5rOz0r+rLR/AcYEANlLSCk5ao4hoftNNLjWLofKY6tRvPfxa/Fh39Wtc5g==", + "dev": true, + "license": "MIT", "engines": { - "node": ">=18" + "node": ">=18.0.0" }, - "optionalDependencies": { - "fsevents": "2.3.2" - } - }, - "../../.npm-global/lib/node_modules/playwright/node_modules/playwright-core": { - "version": "1.61.1", - "license": "Apache-2.0", - "bin": { - "playwright-core": "cli.js" + "peerDependencies": { + "agentdb": ">=2.0.0-alpha.1" }, - "engines": { - "node": ">=18" + "peerDependenciesMeta": { + "agentdb": { + "optional": true + } } }, "node_modules/@emnapi/runtime": { - "version": "1.11.2", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.2.tgz", - "integrity": "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==", + "version": "1.11.3", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", + "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", "license": "MIT", "optional": true, "dependencies": { @@ -76,9 +71,9 @@ } }, "node_modules/@img/sharp-darwin-arm64": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.3.tgz", - "integrity": "sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz", + "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==", "cpu": [ "arm64" ], @@ -94,13 +89,13 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-darwin-arm64": "1.3.2" + "@img/sharp-libvips-darwin-arm64": "1.3.4" } }, "node_modules/@img/sharp-darwin-x64": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.3.tgz", - "integrity": "sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz", + "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==", "cpu": [ "x64" ], @@ -116,20 +111,20 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-darwin-x64": "1.3.2" + "@img/sharp-libvips-darwin-x64": "1.3.4" } }, "node_modules/@img/sharp-freebsd-wasm32": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.3.tgz", - "integrity": "sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz", + "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==", "license": "Apache-2.0", "optional": true, "os": [ "freebsd" ], "dependencies": { - "@img/sharp-wasm32": "0.35.3" + "@img/sharp-wasm32": "0.35.5" }, "engines": { "node": ">=20.9.0" @@ -139,9 +134,9 @@ } }, "node_modules/@img/sharp-libvips-darwin-arm64": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.2.tgz", - "integrity": "sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz", + "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==", "cpu": [ "arm64" ], @@ -155,9 +150,9 @@ } }, "node_modules/@img/sharp-libvips-darwin-x64": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.2.tgz", - "integrity": "sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz", + "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==", "cpu": [ "x64" ], @@ -171,12 +166,15 @@ } }, "node_modules/@img/sharp-libvips-linux-arm": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.2.tgz", - "integrity": "sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz", + "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==", "cpu": [ "arm" ], + "libc": [ + "glibc" + ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -187,12 +185,15 @@ } }, "node_modules/@img/sharp-libvips-linux-arm64": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.2.tgz", - "integrity": "sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz", + "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==", "cpu": [ "arm64" ], + "libc": [ + "glibc" + ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -203,12 +204,15 @@ } }, "node_modules/@img/sharp-libvips-linux-ppc64": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.2.tgz", - "integrity": "sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz", + "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==", "cpu": [ "ppc64" ], + "libc": [ + "glibc" + ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -219,12 +223,15 @@ } }, "node_modules/@img/sharp-libvips-linux-riscv64": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.2.tgz", - "integrity": "sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz", + "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==", "cpu": [ "riscv64" ], + "libc": [ + "glibc" + ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -235,12 +242,15 @@ } }, "node_modules/@img/sharp-libvips-linux-s390x": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.2.tgz", - "integrity": "sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz", + "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==", "cpu": [ "s390x" ], + "libc": [ + "glibc" + ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -251,12 +261,15 @@ } }, "node_modules/@img/sharp-libvips-linux-x64": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.2.tgz", - "integrity": "sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz", + "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==", "cpu": [ "x64" ], + "libc": [ + "glibc" + ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -267,12 +280,15 @@ } }, "node_modules/@img/sharp-libvips-linuxmusl-arm64": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.2.tgz", - "integrity": "sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz", + "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==", "cpu": [ "arm64" ], + "libc": [ + "musl" + ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -283,12 +299,15 @@ } }, "node_modules/@img/sharp-libvips-linuxmusl-x64": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.2.tgz", - "integrity": "sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz", + "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==", "cpu": [ "x64" ], + "libc": [ + "musl" + ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -299,12 +318,15 @@ } }, "node_modules/@img/sharp-linux-arm": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.3.tgz", - "integrity": "sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz", + "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==", "cpu": [ "arm" ], + "libc": [ + "glibc" + ], "license": "Apache-2.0", "optional": true, "os": [ @@ -317,16 +339,19 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-arm": "1.3.2" + "@img/sharp-libvips-linux-arm": "1.3.4" } }, "node_modules/@img/sharp-linux-arm64": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.3.tgz", - "integrity": "sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz", + "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==", "cpu": [ "arm64" ], + "libc": [ + "glibc" + ], "license": "Apache-2.0", "optional": true, "os": [ @@ -339,16 +364,19 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-arm64": "1.3.2" + "@img/sharp-libvips-linux-arm64": "1.3.4" } }, "node_modules/@img/sharp-linux-ppc64": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.3.tgz", - "integrity": "sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz", + "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==", "cpu": [ "ppc64" ], + "libc": [ + "glibc" + ], "license": "Apache-2.0", "optional": true, "os": [ @@ -361,16 +389,19 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-ppc64": "1.3.2" + "@img/sharp-libvips-linux-ppc64": "1.3.4" } }, "node_modules/@img/sharp-linux-riscv64": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.3.tgz", - "integrity": "sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz", + "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==", "cpu": [ "riscv64" ], + "libc": [ + "glibc" + ], "license": "Apache-2.0", "optional": true, "os": [ @@ -383,16 +414,19 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-riscv64": "1.3.2" + "@img/sharp-libvips-linux-riscv64": "1.3.4" } }, "node_modules/@img/sharp-linux-s390x": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.3.tgz", - "integrity": "sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz", + "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==", "cpu": [ "s390x" ], + "libc": [ + "glibc" + ], "license": "Apache-2.0", "optional": true, "os": [ @@ -405,16 +439,19 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-s390x": "1.3.2" + "@img/sharp-libvips-linux-s390x": "1.3.4" } }, "node_modules/@img/sharp-linux-x64": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.3.tgz", - "integrity": "sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz", + "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==", "cpu": [ "x64" ], + "libc": [ + "glibc" + ], "license": "Apache-2.0", "optional": true, "os": [ @@ -427,16 +464,19 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linux-x64": "1.3.2" + "@img/sharp-libvips-linux-x64": "1.3.4" } }, "node_modules/@img/sharp-linuxmusl-arm64": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.3.tgz", - "integrity": "sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz", + "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==", "cpu": [ "arm64" ], + "libc": [ + "musl" + ], "license": "Apache-2.0", "optional": true, "os": [ @@ -449,16 +489,19 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-arm64": "1.3.2" + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4" } }, "node_modules/@img/sharp-linuxmusl-x64": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.3.tgz", - "integrity": "sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz", + "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==", "cpu": [ "x64" ], + "libc": [ + "musl" + ], "license": "Apache-2.0", "optional": true, "os": [ @@ -471,17 +514,17 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-libvips-linuxmusl-x64": "1.3.2" + "@img/sharp-libvips-linuxmusl-x64": "1.3.4" } }, "node_modules/@img/sharp-wasm32": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.3.tgz", - "integrity": "sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz", + "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==", "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", "optional": true, "dependencies": { - "@emnapi/runtime": "^1.11.1" + "@emnapi/runtime": "^1.11.3" }, "engines": { "node": ">=20.9.0" @@ -491,16 +534,16 @@ } }, "node_modules/@img/sharp-webcontainers-wasm32": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.3.tgz", - "integrity": "sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz", + "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==", "cpu": [ "wasm32" ], "license": "Apache-2.0", "optional": true, "dependencies": { - "@img/sharp-wasm32": "0.35.3" + "@img/sharp-wasm32": "0.35.5" }, "engines": { "node": ">=20.9.0" @@ -510,9 +553,9 @@ } }, "node_modules/@img/sharp-win32-arm64": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.3.tgz", - "integrity": "sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz", + "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==", "cpu": [ "arm64" ], @@ -529,9 +572,9 @@ } }, "node_modules/@img/sharp-win32-ia32": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.3.tgz", - "integrity": "sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz", + "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==", "cpu": [ "ia32" ], @@ -548,9 +591,9 @@ } }, "node_modules/@img/sharp-win32-x64": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.3.tgz", - "integrity": "sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz", + "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==", "cpu": [ "x64" ], @@ -566,76 +609,13 @@ "url": "https://opencollective.com/libvips" } }, - "node_modules/@protobufjs/aspromise": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", - "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/base64": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", - "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/codegen": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", - "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/eventemitter": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", - "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/fetch": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", - "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", - "license": "BSD-3-Clause", - "dependencies": { - "@protobufjs/aspromise": "^1.1.1" - } - }, - "node_modules/@protobufjs/float": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", - "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/inquire": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.2.tgz", - "integrity": "sha512-pa0vFRuws4wkvaXKK1uXZMAwAX4/t8ANaJo45iw/oQHNQ9q5xUzwgFmVJGXiga2BeN+zpX7Vf9vmsiIa2J+MUw==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/path": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", - "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/pool": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", - "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", - "license": "BSD-3-Clause" - }, - "node_modules/@protobufjs/utf8": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.1.tgz", - "integrity": "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==", - "license": "BSD-3-Clause" - }, "node_modules/@ruvector/rvf": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/@ruvector/rvf/-/rvf-0.2.2.tgz", - "integrity": "sha512-wS4b1GtyB53EBK634Vw4I1v7m7fa5q2IBS1PYZP/o9F+w5X59kg+0EPhgph8yqABCim895pL+p1uVvo0Jvu66Q==", + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@ruvector/rvf/-/rvf-0.4.2.tgz", + "integrity": "sha512-hRvBUcdKstAXdH2bqoum0d11bmCiKIxoIa2E+rMxK2aHVQM2f9Gm4/4U2+EXISzwFmdv7ys3dohsA3l/uE2SKA==", "license": "MIT", "dependencies": { - "@ruvector/rvf-node": "^0.1.7" + "@ruvector/rvf-node": "^0.3.1" }, "optionalDependencies": { "@ruvector/rvf-solver": "^0.1.0", @@ -643,115 +623,28 @@ } }, "node_modules/@ruvector/rvf-node": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-node/-/rvf-node-0.1.8.tgz", - "integrity": "sha512-1rbSr9XAiq69wnEPs36FW93ZEfFMYEiI2fANZ0bfQcEH4uNWlwxaZFgKs47PNQPhCgx/cbONpnVsnyX+uOTagw==", + "version": "0.3.2", + "resolved": "https://registry.npmjs.org/@ruvector/rvf-node/-/rvf-node-0.3.2.tgz", + "integrity": "sha512-s/3EqKbnGTEOJ3lmJbB573KzQLmy3LHD0sVzoaqcpzCuLimYvuIwcA6yGBOfu/RyvuY6M55a2Qn2lxwvkpmorA==", "license": "MIT", "engines": { "node": ">= 16" - }, - "optionalDependencies": { - "@ruvector/rvf-node-darwin-arm64": "0.1.7", - "@ruvector/rvf-node-darwin-x64": "0.1.7", - "@ruvector/rvf-node-linux-arm64-gnu": "0.1.7", - "@ruvector/rvf-node-linux-x64-gnu": "0.1.7", - "@ruvector/rvf-node-win32-x64-msvc": "0.1.7" } }, - "node_modules/@ruvector/rvf-node-darwin-arm64": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-darwin-arm64/-/rvf-node-darwin-arm64-0.1.7.tgz", - "integrity": "sha512-vll3WJwDn3oOfy1PB10IG7/f3zBpFiMNHL2/2tdJmeRR8La/rSPJ0ZH5MDIsfleiVtaWzh9bvVCtVkZ6uo2jeg==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@ruvector/rvf-node-darwin-x64": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-darwin-x64/-/rvf-node-darwin-x64-0.1.7.tgz", - "integrity": "sha512-Qi/l2bVuVz5YQ2RcYPYF0LNZVkytiIZHzvWhS71+Tt5GEIrsToauHQIcnJQmDNypvwxO8wYk+EeT2xcHR3ZSQQ==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@ruvector/rvf-node-linux-arm64-gnu": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-linux-arm64-gnu/-/rvf-node-linux-arm64-gnu-0.1.7.tgz", - "integrity": "sha512-oZwrtfs7XqRVaDP6iiw6G52l7+NdP3NbTwR2iM+EP8r8X4e1+p4opwV2Ig+lyT7wAz72wcyOpkzpu1MlbK4NKA==", - "cpu": [ - "arm64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@ruvector/rvf-node-linux-x64-gnu": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-linux-x64-gnu/-/rvf-node-linux-x64-gnu-0.1.7.tgz", - "integrity": "sha512-CRq9nc7dIj8QbcY9sSXvVau7cr1ESh3VnYUPp1IodzZ4SegN0H3oeieF5nUMNYyq+43MkBR4yrEwFgDBZ00QHQ==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@ruvector/rvf-node-win32-x64-msvc": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-node-win32-x64-msvc/-/rvf-node-win32-x64-msvc-0.1.7.tgz", - "integrity": "sha512-sgnoNphOnbD4d3+YyQ83MlGO7sX4kbcDwsFNz7p2mlTaDR8coQXoudSaPrMeMpeUojFUqoxeDvVly/un3jADig==", - "cpu": [ - "x64" - ], - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, "node_modules/@ruvector/rvf-solver": { - "version": "0.1.8", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-solver/-/rvf-solver-0.1.8.tgz", - "integrity": "sha512-YM7L6TvhVoC5w0kUMl8ASback2ka3MesPvuf+lRYSJEcaf6bncPX7YGzcrsheOe4BBwyiyx39vAijVPx1nZkWA==", + "version": "0.1.10", + "resolved": "https://registry.npmjs.org/@ruvector/rvf-solver/-/rvf-solver-0.1.10.tgz", + "integrity": "sha512-fcpzV+L7GOU0r2DLcudgdIWVwQYI3rrlr4kFP8/W3oWe9QALZLfSZaT1i1d76hG9ggLHNEm/ulkvi04jkN0ioQ==", "license": "MIT", "optional": true }, "node_modules/@ruvector/rvf-wasm": { - "version": "0.1.7", - "resolved": "https://registry.npmjs.org/@ruvector/rvf-wasm/-/rvf-wasm-0.1.7.tgz", - "integrity": "sha512-VTGPau9ikQXG9Tvjkjk5ff90ZcCMcwOYv3l6rJ+PL2fH/9EtxM1FWE7H1i7gdhh8dCSqRv4moXOAMSDbJ5oubQ==", + "version": "0.1.11", + "resolved": "https://registry.npmjs.org/@ruvector/rvf-wasm/-/rvf-wasm-0.1.11.tgz", + "integrity": "sha512-8V2lriIWIFPivedH9wJQ2u91fPK+3jbrDLRQ2cQCKYu+I8DA8cKgNcquYiJGf6yS1lkTRCTb0d7kA3f8yPHcWQ==", "license": "MIT", "optional": true }, - "node_modules/@types/long": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/@types/long/-/long-4.0.2.tgz", - "integrity": "sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==", - "license": "MIT" - }, - "node_modules/@types/node": { - "version": "26.1.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.0.tgz", - "integrity": "sha512-O0A1G3xPGy4w7AgQdAQYUlQ+BKk2Oovw8eRpofyp5KdBZULnbe+WqaOVNrm705SHphCiG4XHsACrSmPu1f+Kgw==", - "license": "MIT", - "dependencies": { - "undici-types": "~8.3.0" - } - }, "node_modules/@xenova/transformers": { "version": "2.17.2", "resolved": "https://registry.npmjs.org/@xenova/transformers/-/transformers-2.17.2.tgz", @@ -766,249 +659,6 @@ "onnxruntime-node": "1.14.0" } }, - "node_modules/@xenova/transformers/node_modules/sharp": { - "version": "0.32.6", - "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.32.6.tgz", - "integrity": "sha512-KyLTWwgcR9Oe4d9HwCwNM2l7+J0dUQwn/yf7S0EnTtb0eVS4RxO0eUSvxPtzT4F3SY+C4K6fqdv/DO27sJ/v/w==", - "hasInstallScript": true, - "license": "Apache-2.0", - "dependencies": { - "color": "^4.2.3", - "detect-libc": "^2.0.2", - "node-addon-api": "^6.1.0", - "prebuild-install": "^7.1.1", - "semver": "^7.5.4", - "simple-get": "^4.0.1", - "tar-fs": "^3.0.4", - "tunnel-agent": "^0.6.0" - }, - "engines": { - "node": ">=14.15.0" - }, - "funding": { - "url": "https://opencollective.com/libvips" - } - }, - "node_modules/b4a": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.8.1.tgz", - "integrity": "sha512-aiqre1Nr0B/6DgE2N5vwTc+2/oQZ4Wh1t4NznYY4E00y8LCt6NqdRv81so00oo27D8MVKTpUa/MwUUtBLXCoDw==", - "license": "Apache-2.0", - "peerDependencies": { - "react-native-b4a": "*" - }, - "peerDependenciesMeta": { - "react-native-b4a": { - "optional": true - } - } - }, - "node_modules/bare-events": { - "version": "2.9.1", - "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.1.tgz", - "integrity": "sha512-Z0oHEHAFDZkffN8Qc39zNZjQlMDkPJRyyyZieU1VH7u8c5S+qHZ2S8ixdKIAxEjfHO7FJxXmJWgteOghVanIsg==", - "license": "Apache-2.0", - "peerDependencies": { - "bare-abort-controller": "*" - }, - "peerDependenciesMeta": { - "bare-abort-controller": { - "optional": true - } - } - }, - "node_modules/bare-fs": { - "version": "4.7.4", - "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.7.4.tgz", - "integrity": "sha512-y1kC+ffIx/tPLdTE693uNjHfzTfr+ravR5tvWlMXe25nELbkqV400S71qHDwbkAQ1FVEZobB1NFRzFbCCcyBCQ==", - "license": "Apache-2.0", - "dependencies": { - "bare-events": "^2.5.4", - "bare-path": "^3.0.0", - "bare-stream": "^2.6.4", - "bare-url": "^2.2.2", - "fast-fifo": "^1.3.2" - }, - "engines": { - "bare": ">=1.16.0" - }, - "peerDependencies": { - "bare-buffer": "*" - }, - "peerDependenciesMeta": { - "bare-buffer": { - "optional": true - } - } - }, - "node_modules/bare-path": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.1.tgz", - "integrity": "sha512-JprUlveX3QjApC1cTpsUOiscADftCGVWkzitbHsRqv84hzYwYHw2mbluddsq5TvI8mH/8Ov1f4BiMAdcB0oYnQ==", - "license": "Apache-2.0" - }, - "node_modules/bare-stream": { - "version": "2.13.3", - "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.3.tgz", - "integrity": "sha512-Kc+brLqvEqGkjyfiwJmImAOqLZL7OsoLKuavx+hJjgVV3nLTOjloJyPMFxjUPerGGHrNH0fLU06jjykMLWrERQ==", - "license": "Apache-2.0", - "dependencies": { - "b4a": "^1.8.1", - "streamx": "^2.25.0", - "teex": "^1.0.1" - }, - "peerDependencies": { - "bare-abort-controller": "*", - "bare-buffer": "*", - "bare-events": "*" - }, - "peerDependenciesMeta": { - "bare-abort-controller": { - "optional": true - }, - "bare-buffer": { - "optional": true - }, - "bare-events": { - "optional": true - } - } - }, - "node_modules/bare-url": { - "version": "2.4.5", - "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.4.5.tgz", - "integrity": "sha512-K+y9xF1tN+CdPu4qWwr0QiK1Al07eFPGYK5M2pDXcmHdMdgC/tT/bpmMe1hrmRHaidKLkXrC+cRNYf3XVDUhSQ==", - "license": "Apache-2.0", - "dependencies": { - "bare-path": "^3.0.0" - } - }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "license": "MIT", - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } - }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, - "node_modules/chownr": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", - "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", - "license": "ISC" - }, - "node_modules/color": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/color/-/color-4.2.3.tgz", - "integrity": "sha512-1rXeuUUiGGrykh+CeBdu5Ie7OJwinCgQY0bc7GCRxy5xVHy+moaqkpL/jqQq0MtQOeYcrqEz4abc5f0KtU7W4A==", - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1", - "color-string": "^1.9.0" - }, - "engines": { - "node": ">=12.5.0" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "license": "MIT" - }, - "node_modules/color-string": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/color-string/-/color-string-1.9.1.tgz", - "integrity": "sha512-shrVawQFojnZv6xM40anx4CkoDP+fZsw/ZerEMsW/pyzsRbElpsL/DBVW7q3ExxwusdNXI3lXpuhEZkzs8p5Eg==", - "license": "MIT", - "dependencies": { - "color-name": "^1.0.0", - "simple-swizzle": "^0.2.2" - } - }, - "node_modules/decompress-response": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", - "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", - "license": "MIT", - "dependencies": { - "mimic-response": "^3.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/deep-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "license": "MIT", - "engines": { - "node": ">=4.0.0" - } - }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -1018,167 +668,24 @@ "node": ">=8" } }, - "node_modules/end-of-stream": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", - "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", - "license": "MIT", - "dependencies": { - "once": "^1.4.0" - } - }, - "node_modules/events-universal": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz", - "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==", - "license": "Apache-2.0", - "dependencies": { - "bare-events": "^2.7.0" - } - }, - "node_modules/expand-template": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", - "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", - "license": "(MIT OR WTFPL)", - "engines": { - "node": ">=6" - } - }, - "node_modules/fast-fifo": { - "version": "1.3.2", - "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz", - "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==", - "license": "MIT" - }, "node_modules/flatbuffers": { "version": "1.12.0", "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-1.12.0.tgz", "integrity": "sha512-c7CZADjRcl6j0PlvFy0ZqXQ67qSEZfrVPynmnL+2zPc+NtMvrF8Y0QceMo7QqnSPc7+uWjUIAbvCQ5WIKlMVdQ==", "license": "SEE LICENSE IN LICENSE.txt" }, - "node_modules/fs-constants": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", - "license": "MIT" - }, - "node_modules/github-from-package": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", - "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", - "license": "MIT" - }, "node_modules/guid-typescript": { "version": "1.0.9", "resolved": "https://registry.npmjs.org/guid-typescript/-/guid-typescript-1.0.9.tgz", "integrity": "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==", "license": "ISC" }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "license": "ISC" - }, - "node_modules/is-arrayish": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.3.4.tgz", - "integrity": "sha512-m6UrgzFVUYawGBh1dUsWR5M2Clqic9RVXC/9f8ceNlv2IcO9j9J/z8UoCLPqtsPBFNzEpfR3xftohbfqDx8EQA==", - "license": "MIT" - }, "node_modules/long": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==", "license": "Apache-2.0" }, - "node_modules/mimic-response": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", - "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/mkdirp-classic": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", - "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", - "license": "MIT" - }, - "node_modules/napi-build-utils": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", - "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", - "license": "MIT" - }, - "node_modules/node-abi": { - "version": "3.94.0", - "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.94.0.tgz", - "integrity": "sha512-W5ZNO5KRPB5TkYmGVD9F6YqhsglXJzE6etpbmT+f6EQElhiX/UTG551cnsRGvLG3fyZEg9HwaDmNmj5nwJ4z9g==", - "license": "MIT", - "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/node-addon-api": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-6.1.0.tgz", - "integrity": "sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA==", - "license": "MIT" - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, "node_modules/onnx-proto": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/onnx-proto/-/onnx-proto-4.0.4.tgz", @@ -1230,153 +737,54 @@ "license": "MIT" }, "node_modules/playwright": { - "resolved": "../../.npm-global/lib/node_modules/playwright", - "link": true - }, - "node_modules/prebuild-install": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", - "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", - "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", - "license": "MIT", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "license": "Apache-2.0", "dependencies": { - "detect-libc": "^2.0.0", - "expand-template": "^2.0.3", - "github-from-package": "0.0.0", - "minimist": "^1.2.3", - "mkdirp-classic": "^0.5.3", - "napi-build-utils": "^2.0.0", - "node-abi": "^3.3.0", - "pump": "^3.0.0", - "rc": "^1.2.7", - "simple-get": "^4.0.0", - "tar-fs": "^2.0.0", - "tunnel-agent": "^0.6.0" + "playwright-core": "1.64.1" }, "bin": { - "prebuild-install": "bin.js" + "playwright": "cli.js" }, "engines": { - "node": ">=10" - } - }, - "node_modules/prebuild-install/node_modules/tar-fs": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", - "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", - "license": "MIT", - "dependencies": { - "chownr": "^1.1.1", - "mkdirp-classic": "^0.5.2", - "pump": "^3.0.0", - "tar-stream": "^2.1.4" + "node": ">=20" } }, - "node_modules/prebuild-install/node_modules/tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", - "license": "MIT", - "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" + "node_modules/playwright-core": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" }, "engines": { - "node": ">=6" + "node": ">=20" } }, "node_modules/protobufjs": { - "version": "6.11.6", - "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.11.6.tgz", - "integrity": "sha512-k8BHqgPBOtrlougZZqF2uUk5Z7bN8f0wj+3e8M3hvtSv0NBAz4VBy5f6R5Nxq/l+i7mRFTgNZb2trxqTpHNY/A==", - "hasInstallScript": true, + "version": "8.8.1", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-8.8.1.tgz", + "integrity": "sha512-d9e9179bjXSJdpJ3+R9fP8hzXsnKLyxTjHLG1dUzje8a27pPyXCe6PrcRtgx2rjoM3IZzHd2vAs+6J/BsO1k7Q==", "license": "BSD-3-Clause", "dependencies": { - "@protobufjs/aspromise": "^1.1.2", - "@protobufjs/base64": "^1.1.2", - "@protobufjs/codegen": "^2.0.4", - "@protobufjs/eventemitter": "^1.1.0", - "@protobufjs/fetch": "^1.1.0", - "@protobufjs/float": "^1.0.2", - "@protobufjs/inquire": "^1.1.0", - "@protobufjs/path": "^1.1.2", - "@protobufjs/pool": "^1.1.0", - "@protobufjs/utf8": "^1.1.0", - "@types/long": "^4.0.1", - "@types/node": ">=13.7.0", - "long": "^4.0.0" - }, - "bin": { - "pbjs": "bin/pbjs", - "pbts": "bin/pbts" - } - }, - "node_modules/pump": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", - "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", - "license": "MIT", - "dependencies": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "node_modules/rc": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", - "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", - "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", - "dependencies": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "bin": { - "rc": "cli.js" - } - }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "license": "MIT", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" + "long": "^5.3.2" }, "engines": { - "node": ">= 6" + "node": ">=12.0.0" } }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" + "node_modules/protobufjs/node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" }, "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -1386,9 +794,9 @@ } }, "node_modules/sharp": { - "version": "0.35.3", - "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.3.tgz", - "integrity": "sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q==", + "version": "0.35.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", + "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==", "license": "Apache-2.0", "dependencies": { "@img/colour": "^1.1.0", @@ -1402,31 +810,31 @@ "url": "https://opencollective.com/libvips" }, "optionalDependencies": { - "@img/sharp-darwin-arm64": "0.35.3", - "@img/sharp-darwin-x64": "0.35.3", - "@img/sharp-freebsd-wasm32": "0.35.3", - "@img/sharp-libvips-darwin-arm64": "1.3.2", - "@img/sharp-libvips-darwin-x64": "1.3.2", - "@img/sharp-libvips-linux-arm": "1.3.2", - "@img/sharp-libvips-linux-arm64": "1.3.2", - "@img/sharp-libvips-linux-ppc64": "1.3.2", - "@img/sharp-libvips-linux-riscv64": "1.3.2", - "@img/sharp-libvips-linux-s390x": "1.3.2", - "@img/sharp-libvips-linux-x64": "1.3.2", - "@img/sharp-libvips-linuxmusl-arm64": "1.3.2", - "@img/sharp-libvips-linuxmusl-x64": "1.3.2", - "@img/sharp-linux-arm": "0.35.3", - "@img/sharp-linux-arm64": "0.35.3", - "@img/sharp-linux-ppc64": "0.35.3", - "@img/sharp-linux-riscv64": "0.35.3", - "@img/sharp-linux-s390x": "0.35.3", - "@img/sharp-linux-x64": "0.35.3", - "@img/sharp-linuxmusl-arm64": "0.35.3", - "@img/sharp-linuxmusl-x64": "0.35.3", - "@img/sharp-webcontainers-wasm32": "0.35.3", - "@img/sharp-win32-arm64": "0.35.3", - "@img/sharp-win32-ia32": "0.35.3", - "@img/sharp-win32-x64": "0.35.3" + "@img/sharp-darwin-arm64": "0.35.5", + "@img/sharp-darwin-x64": "0.35.5", + "@img/sharp-freebsd-wasm32": "0.35.5", + "@img/sharp-libvips-darwin-arm64": "1.3.4", + "@img/sharp-libvips-darwin-x64": "1.3.4", + "@img/sharp-libvips-linux-arm": "1.3.4", + "@img/sharp-libvips-linux-arm64": "1.3.4", + "@img/sharp-libvips-linux-ppc64": "1.3.4", + "@img/sharp-libvips-linux-riscv64": "1.3.4", + "@img/sharp-libvips-linux-s390x": "1.3.4", + "@img/sharp-libvips-linux-x64": "1.3.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.3.4", + "@img/sharp-libvips-linuxmusl-x64": "1.3.4", + "@img/sharp-linux-arm": "0.35.5", + "@img/sharp-linux-arm64": "0.35.5", + "@img/sharp-linux-ppc64": "0.35.5", + "@img/sharp-linux-riscv64": "0.35.5", + "@img/sharp-linux-s390x": "0.35.5", + "@img/sharp-linux-x64": "0.35.5", + "@img/sharp-linuxmusl-arm64": "0.35.5", + "@img/sharp-linuxmusl-x64": "0.35.5", + "@img/sharp-webcontainers-wasm32": "0.35.5", + "@img/sharp-win32-arm64": "0.35.5", + "@img/sharp-win32-ia32": "0.35.5", + "@img/sharp-win32-x64": "0.35.5" }, "peerDependenciesMeta": { "@types/node": { @@ -1434,169 +842,12 @@ } } }, - "node_modules/simple-concat": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", - "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/simple-get": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", - "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "decompress-response": "^6.0.0", - "once": "^1.3.1", - "simple-concat": "^1.0.0" - } - }, - "node_modules/simple-swizzle": { - "version": "0.2.4", - "resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.4.tgz", - "integrity": "sha512-nAu1WFPQSMNr2Zn9PGSZK9AGn4t/y97lEm+MXTtUDwfP0ksAIX4nO+6ruD9Jwut4C49SB1Ws+fbXsm/yScWOHw==", - "license": "MIT", - "dependencies": { - "is-arrayish": "^0.3.1" - } - }, - "node_modules/streamx": { - "version": "2.28.0", - "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.0.tgz", - "integrity": "sha512-1Yowhzjf0ivGMrTIkY9hav5TxobO9qIVqUE41fiCGMGgc3CLlf4MY+9AHmZqBWgDTue0fY9zWjYFVyf6Diuobw==", - "license": "MIT", - "dependencies": { - "events-universal": "^1.0.0", - "fast-fifo": "^1.3.2", - "text-decoder": "^1.1.0" - } - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/tar-fs": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.3.tgz", - "integrity": "sha512-/hU4AXnIdZu+Gvl1pk0oI5f5HxWsCJRtY2aFaJdk9VvyL48DWU6iU5WAIPG+wIi1YvWA6eTJvIviP/tMAZZNwQ==", - "license": "MIT", - "dependencies": { - "pump": "^3.0.0", - "tar-stream": "^3.1.5" - }, - "optionalDependencies": { - "bare-fs": "^4.0.1", - "bare-path": "^3.0.0" - } - }, - "node_modules/tar-stream": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.0.tgz", - "integrity": "sha512-ojzvCvVaNp6aOTFmG7jaRD0meowIAuPc3cMMhSgKiVWws1GyHbGd/xvnyuRKcKlMpt3qvxx6r0hreCNITP9hIg==", - "license": "MIT", - "dependencies": { - "b4a": "^1.6.4", - "bare-fs": "^4.5.5", - "fast-fifo": "^1.2.0", - "streamx": "^2.15.0" - } - }, - "node_modules/teex": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz", - "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==", - "license": "MIT", - "dependencies": { - "streamx": "^2.12.5" - } - }, - "node_modules/text-decoder": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz", - "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==", - "license": "Apache-2.0", - "dependencies": { - "b4a": "^1.6.4" - } - }, "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", + "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", "license": "0BSD", "optional": true - }, - "node_modules/tunnel-agent": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", - "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", - "license": "Apache-2.0", - "dependencies": { - "safe-buffer": "^5.0.1" - }, - "engines": { - "node": "*" - } - }, - "node_modules/undici-types": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", - "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", - "license": "MIT" - }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "license": "MIT" - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "license": "ISC" } } } diff --git a/package.json b/package.json index a417ba3..af3cbee 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "explainmyrepo", - "version": "3.0.0", + "version": "3.0.1", "description": "Turn any GitHub repo into a bespoke, art-directed explainer site — for humans and their AI — in one command.", "type": "module", "bin": { @@ -11,7 +11,6 @@ "src/", "tools/", "kb/*.mjs", - "kb/CONTRACT.md", "assets/", "capabilities.json" ], @@ -42,13 +41,22 @@ "access": "public" }, "dependencies": { - "@ruvector/rvf": "^0.2.2", + "@ruvector/rvf": "^0.4.2", "@xenova/transformers": "^2.17.2", - "playwright": "^1.61.1", - "sharp": "^0.35.3" + "playwright": ">=1.61.1 <1.65.0", + "sharp": "^0.35.5" }, "scripts": { "test": "node --test tests/*.test.mjs", + "test:e2e": "node --test tests-e2e/*.test.mjs", + "pull-ratings": "node tools/pull-ratings.mjs", "start": "node bin/explainmyrepo.mjs" + }, + "devDependencies": { + "@claude-flow/aidefence": "^3.1.0" + }, + "overrides": { + "sharp": "$sharp", + "protobufjs": "^8.8.1" } } diff --git a/ruv-explainer-agent-harness-generator/.gitignore b/ruv-explainer-agent-harness-generator/.gitignore deleted file mode 100644 index d3e238c..0000000 --- a/ruv-explainer-agent-harness-generator/.gitignore +++ /dev/null @@ -1,17 +0,0 @@ -# Binaries & bundles are NOT committed here [H] — they ship via GitHub Release. -downloads/*.zip -*.zip -*.rvf -*.rvf.lock -*.embed.json - -# Generated font binaries: drop the real woff2 into assets/fonts/ at build time. -# (kept out of git; see assets/fonts/README.md for the 5 required files) -assets/fonts/*.woff2 - -# Tooling noise -node_modules/ -.vercel/ -.DS_Store -*.log -.vercel diff --git a/ruv-explainer-agent-harness-generator/README.md b/ruv-explainer-agent-harness-generator/README.md deleted file mode 100644 index 79b4849..0000000 --- a/ruv-explainer-agent-harness-generator/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# ruv-explainer-agent-harness-generator - -Foundry/mint-themed **ExplainerSite** for **MetaHarness** -(`ruvnet/agent-harness-generator`). Static single page, **no build, no deps**. - -> The harness is the product. This site teaches a non-technical Claude Code user -> what MetaHarness is and how to use it, and links the drop-in AI half. - -## Status — P2 (site skeleton + design lock) - -The **shell** is built and the **aesthetic is locked**: warm-charcoal + -molten-amber/copper, Big Shoulders Display over IBM Plex Sans/Mono, tactile -pressed-metal depth, **zero cyan** (deliberately unlike the cognitum reference). -All section body copy is **clearly-marked placeholder** — real copy lands in P4 -from the 7-arc draft; graphics G1–G6 land in P5. - -## Files - -| File | Role | -|---|---| -| `index.html` | Single page; 9 collapsible `
` sections (01–07 = 7 arc questions, 08 = use-case gallery, 09 = drop-in). | -| `styles.css` | `:root` foundry tokens, 5 `@font-face` (self-hosted woff2), `prefers-reduced-motion`, responsive. | -| `main.js` | < 6 KB: deep-link section open + dropzone stub (click / keyboard / drag fallback). | -| `vercel.json` | `cleanUrls`, `/assets` immutable cache, woff2 + zip content-type. | -| `favicon.svg` | Hand-authored 'MH' molten stamped coin. | -| `assets/img/` | G1–G6 graphics (see its `README.md`). | -| `assets/fonts/` | 5 self-hosted woff2 (see its `README.md`). | -| `downloads/` | `metaharness-dropin.zip` (the AI half; built P7/P9, gitignored). | - -## Local preview - -Any static server, e.g. `python3 -m http.server` from this directory, then open -`http://localhost:8000`. - -See `../docs/build-plan-metaharness.md` for the full plan and gates. diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/s01.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/s01.svg deleted file mode 100644 index a9a353b..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/s01.svg +++ /dev/null @@ -1,103 +0,0 @@ - - The one-way door: forking ruflo versus generating with MetaHarness - Forking the whole ruflo bundle freezes you and cuts you off from future kernel updates. MetaHarness generates only the pieces you want, branded by you, while still pulling future engine updates. - - - - - - - - - - - - - - - The "one-way door" - Forking the whole bundle vs. generating just the pieces you want - - - - - - BEFORE — fork ruflo - - - - The whole ruflo bundle (one frozen copy) - - - Kernel primitives - MCP, hooks, memory, routing - - - Bundled content - 60+ agents · 30+ skills · 33 plugins - - Kernel and content are fused together — you must take all of it - You fork the ENTIRE thing just to rebrand it - - - - Your frozen fork - A snapshot — never moves again on its own - - - - fork - - - - Future engine updates - never reach your fork - - - - - - - cut off - - - AFTER — generate with MetaHarness - - - - ruflo kernel (lives upstream, keeps improving) - - MCP · hooks · memory · routing · witness — pinned version - - - - MetaHarness generator - picks ONLY the pieces you choose - - - - - - Your branded harness - npx your-name · your agents · your skills - - only the parts you wanted — owned by you - - - generate - - - - Future engine updates - still flow in — re-pin to a newer kernel - - - - - stays connected to the kernel - - - - - Fork = take everything, then it freezes. Generate = take what you need, keep getting updates. - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/s02.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/s02.svg deleted file mode 100644 index 8dc4909..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/s02.svg +++ /dev/null @@ -1,101 +0,0 @@ - - The problem MetaHarness solves: lock-in, host fragmentation, and rebuilt plumbing - A generic AI agent guesses at your repo. Three concrete problems follow: lock-in when you fork a bundle to rebrand it, host fragmentation across different agent runtimes, and reinventing about 80 percent of the same infrastructure on every new project. - - - - - - - - - - The problem - Why a generic agent is not enough — and why three things keep going wrong - - - - Generic AI agent - knows nothing about - YOUR codebase - "...is this a Python repo?" - - - - Your repo - its own layout, build, - tools, conventions - needs an agent that fits - - - - guesses ? ? ? - no project knowledge, no fit - - - Three problems this creates - - - - - 1 · Lock-in - - - You fork a bundled product - just to put your brand on it - - - - - Now you are off the upstream - — no future updates - - Rebranding - shouldn't cost you - every upstream improvement - (the same one-way door) - - - - 2 · Host fragmentation - - Agents now run in many places — - each with its own config rules - - - Claude Code - - Codex - - - Hermes - - pi.dev - - One agent, many hosts - Each host wants different - config files — a rewrite - should target any host, no rewrite - - - - 3 · Rebuilt plumbing - - Every new agent project rebuilds - the same boring infrastructure - - - MCP server setup - - memory namespace - - governance policy - - release signing - - ~80% built by hand, every time - the same plumbing, over and over - - - Lock-in, host fragmentation, and rebuilt plumbing are exactly what MetaHarness is built to remove. - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/s03.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/s03.svg deleted file mode 100644 index a62c1fc..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/s03.svg +++ /dev/null @@ -1,102 +0,0 @@ - - Why now: hosts have multiplied and the plugin marketplace woke up - Two forces make a harness factory worth building now. First, the hosts multiplied — Claude Code, Codex, pi.dev, Hermes, OpenClaw and RVM all gained agent conventions. Second, the plugin marketplace woke up — a scaffolded harness both consumes plugins from the ruflo IPFS registry and can publish its own back. - - - - - - - - - - - - - Why now - Two shifts made a "factory for harnesses" worth building - - - - - 1 · The hosts multiplied - Claude Code used to be the only place. Now there are many. - - - - Then - one host - - - - - Now - six+ hosts - - - - Claude Code - stable - - - Codex CLI - MCP support - - - pi.dev - dev platform - - - Hermes - Nous Research - - - OpenClaw - newer - - - RVM - newer - - - - One generated harness - targets any of them — no rewrite - - - - - - 2 · The marketplace woke up - Plugins are now traded — a harness both takes and gives. - - - - ruflo IPFS plugin registry - the shared marketplace of agent plugins - - - - Your scaffolded harness - a marketplace participant - - - - - consumes - pulls plugins in - - - - - publishes - pushes its own back - - - - Without a generator, every new - participant rebuilds 80% by hand - - - More hosts to target + a live plugin economy = the moment a harness factory pays off. - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/s04.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/s04.svg deleted file mode 100644 index 6f95e1c..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/s04.svg +++ /dev/null @@ -1,166 +0,0 @@ - - The composer pipeline - A GitHub repo, or a blank slate, enters the composer and flows through nine - stages in order — Identity, Hosts, Primitives, Agents, Skills, Plugins, Features, Branding, - Confirm — emerging as a branded, npm-publishable agent harness package. Each stage shows in - plain words what happens there. - - - - - - - - - - - - - - - - - - - - - - - - - HOW IT ACTUALLY WORKS UNDER THE COVERS - The composer pipeline - You answer nine questions, in order. The composer assembles a complete package from your answers. - - - - - A GitHub repo - …or a blank slate. - It never runs your code — it only reads. - - - - Same nine questions, two ways - A friendly picker (the “wizard”), or - the same answers as command-line flags. - - - - - - - - - - - - - 1 - Identity - The name, the package scope, a description, a licence, and who the author is. One screen. - - - - - - - - 2 - Hosts - Tick where it should run — Claude Code, Codex, pi.dev, Hermes, and more. Pick at least one. - - - - - - - - 3 - Primitives - Engine blocks on or off: tool server (always on), automations, memory, routing, marketplace, provenance. All on by default. - - - - - - - - 4 - Agents - Choose helpers from a curated catalogue. It suggests a coder, a reviewer, and a tester to start. - - - - - - - - 5 - Skills - Reusable abilities you bolt on — defaults wire up hooks, memory search, and swarm orchestration. - - - - - - - - 6 - Plugins - Optional add-ons from the shared registry, with live download counts and ratings. None by default. - - - - - - - - 7 - Features - Opt-in extras that change the wiring: teamwork between agents, claims-based access, self-improvement. - - - - - - - - 8 - Branding - “Powered-by” mode or fully independent, plus your own brand wording. - - - - - - - - 9 - Confirm - A summary: every file it will create, the exact engine version it pins to, and a size estimate — before anything is written. - - - - - - - - - - - EMERGES AS - A branded, npm-publishable harness - Your own npx your-name command — a self-contained - package you own and can publish. (See section 05.) - - - - - The composer’s state is one typed answer-object — the picker and the flags build the same thing, so both paths produce the same harness. - - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/s05.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/s05.svg deleted file mode 100644 index 42e43bd..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/s05.svg +++ /dev/null @@ -1,151 +0,0 @@ - - Anatomy of a generated harness - What is literally inside the output package: a repo-aware command-line tool, - a local tool (MCP) server, a project-scoped memory space, skills generated from your file - layout, a default-deny governance policy, and witness-signed releases — all wrapping a - replaceable AI model and pointed at your repository. - - - - - - - - - - - - - - - - - - - - - - - - WHAT “SOLVED” LOOKS LIKE - Anatomy of a generated harness - One self-contained package — say you called it my-bot. Here is what is literally inside it. - - - - THE HARNESS — THE WRAPPER YOU OWN - Everything below is yours, branded as you, and ships in the package. - - - - - - - A repo-aware command-line tool - Your own npx my-bot command, branded as - yours — not as someone else’s tool. It knows - your project, because it was built for it. - - - - - - A local tool server - Its own MCP server registration, running on - your machine. This is how the agents reach - tools — nothing hosted, nothing remote. - - - - - - Project-scoped memory - Its own private memory space, kept separate - from everything else on your machine. What - it learns about your project stays with it. - - - - - - Skills from your file layout - It reads your repo’s file list, manifest and - README to suggest the right agents and skills - — without ever executing your code. - - - - - - A default-deny safety policy - The tool server starts locked down: no - internet, no shell, no writing files — until - you allow each one. Nothing on you didn’t turn on. - - - - - - Witness-signed releases - A signed receipt of exactly what is inside - (an Ed25519 witness manifest), so anyone who - installs it can confirm nothing was swapped. - - - - - - + the agents, skills, plugins, and per-host config files you chose - Copied from the catalogue into the package — your selection, wired up and ready to run. - - - - - - REPLACEABLE SLOT - The AI model — Claude, GPT, or whatever your host brings - The harness wraps the model; it is not the model. Swap the model and everything above still stands. - - - - - - POINTED AT - YOUR repo - The whole harness is - tuned to one codebase - — yours — not a - generic chatbot. - It reads, but never - runs, your code. - - - - aimed at → - - - - - SHIP IT - npm publish - Your users run - npx my-bot init - They never see the - factory underneath - — only your brand. - - - - - - The model is replaceable. The harness is the product. - Nothing here is invented — every piece is what the generator writes into the package, locked down and signed by default. - v0.1.x beta — published and usable; the README badge shows 568 tests passing. - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/s06.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/s06.svg deleted file mode 100644 index 39e89ec..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/s06.svg +++ /dev/null @@ -1,96 +0,0 @@ - - Two ways in, one result - Two implementation paths — the browser Studio and the terminal (npx metaharness) — both produce the same branded harness package that is yours to keep. - - - - - - - - - - - - - - - - Two ways in — same result - Pick the path that fits how you work. Both hand you a .zip (or folder) that is yours to keep. - - - - - Browser Studio - nothing to install - - - - - Open the Studio - ruvnet.github.io - - - - - Pick a tab, - make choices - repo, scratch, skill, verify - - - - - Download .zip - in your browser - - - - - - - - - Terminal - if you live in the command line - - - - Run the command - npx metaharness - - - - - Flags or wizard - --template --host - or --wizard asks you - - - - - Scaffolded folder - written to disk - - - - - - - - - Same branded - package - your own npx my-bot, - yours to keep - - - - - - - - - Then, on your own machine — identical from here: - unzip my-bot.zip   →   cd my-bot   →   npm install   →   edit, then npm publish --provenance - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/s07.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/s07.svg deleted file mode 100644 index 1bef2a0..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/s07.svg +++ /dev/null @@ -1,68 +0,0 @@ - - The fastest start: one command, four questions, your own tool - A three-step flow. Run npx metaharness --wizard, answer a few plain questions (name, template, host, description), and you get your own npx your-name command. The wizard also prints the exact command so you can skip the questions next time. - - - - - - - - - - - - - The fastest start - One command, four questions, a working package — in your own name. - - - - - - 1 - Run the wizard - - npx metaharness --wizard - Nothing to set up. - npx fetches it for you. - - - - - - - 2 - Answer 4 questions - - • - a name - • - a template - • - where it will run (host) - • - a one-line description - - - - - - - 3 - You get your tool - - npx <your-name> - Your brand, your skills, - your own command. - - - - - - - - - Bonus: skip the questions next time - The wizard prints the exact npx metaharness … command it just ran — paste it to repeat in one line. - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/s09.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/s09.svg deleted file mode 100644 index 5e01ce3..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/s09.svg +++ /dev/null @@ -1,104 +0,0 @@ - - The drop-in: one zip, two halves, three steps to wire it in - One download splits into two halves. The For-you half is a written primer to read and watch. The For-your-AI half is a searchable knowledge pack (an .rvf file plus a small MCP server). Wiring the AI half into Claude Code is three steps: unzip the kb folder, add a .mcp.json pointing at it, and paste a verification gate into CLAUDE.md so your AI answers from the real source instead of guessing. - - - - - - - - - - - - - - - - The drop-in — one zip, two halves - One download. Half is for you to read; half is for your AI to search. - - - - - one .zip - metaharness-dropin - - - - - - - - - - For you - A short written primer. - - - read - - watch - - - - - - For your AI - A searchable knowledge pack. - - - kb / .rvf - - MCP server - - - - - wire this half into Claude Code - - - Three steps to wire it in - - - - - - 1 - Unzip the pack - - unzip … → cd kb/ → npm i - Put the kb/ folder by your project. - - - - - - - 2 - Add .mcp.json - - "metaharness-kb": … - Registers the pack as a tool. - - - - - - - 3 - Paste the gate - - into CLAUDE.md - Forces a check before answering. - - - - - - - - - Result: your AI answers from the real source — grounded, with citations — instead of guessing. - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/uc1.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/uc1.svg deleted file mode 100644 index 82db113..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/uc1.svg +++ /dev/null @@ -1,87 +0,0 @@ - - Use case 1 — Turn a repo into an agent that understands it - Problem: a generic chatbot does not know your codebase. You run harness analyze-repo with the scaffold flag. The tool reads the file list, manifest, README and language mix without running your code, and emits a scaffolded harness tuned to that repo, ready to npm install. - - - - - - - - - - - USE CASE 1 - "I have a repo — give me an agent that actually understands it" - - - - Problem - Generic chatbot - It has never seen your - code. Wrong file names, - wrong build steps, - guesses at structure. - - Your GitHub repo - /src /tests - package.json README - - - - - - What you run - - harness analyze-repo . - --scaffold my-bot - Reads file list, manifest, - README and language mix. - - Never runs your code - Build/test commands are - trust: inferred - execution: disabled - - - - - - What it looks like - Recommended set - - - Agents: coder · reviewer - - Skills: memory-search - - MCP tools for your stack - - Review and edit before - you download — it's a - strong starting point. - - - - - - - PAYOFF - A harness - tuned to - your repo - - npm install - Run it — or get - a .zip you own. - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/uc2.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/uc2.svg deleted file mode 100644 index b4b6030..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/uc2.svg +++ /dev/null @@ -1,87 +0,0 @@ - - Use case 2 — Score a repo before you commit to building a harness - Problem: you are unsure a repo is a good candidate or what each run will cost. You run metaharness score and harness genome. The tool reads the repo without running it and prints a report card of fit, build-likelihood, safety and cost per run, plus a ready, needs-work or blocked verdict. You get a go or no-go decision with evidence before scaffolding. - - - - - - - - - - - USE CASE 2 - "Score a repo BEFORE I commit to building a harness for it" - - - - PROBLEM - Should I even - build this? - You don't know if the - repo is a good fit — - or what each agent - run will cost you. - ? ? ? - - - - - - WHAT YOU RUN - - metaharness score <repo> - - harness genome <repo> - Reads the repo — - again, never runs it. - - Deterministic, one-screen - scorecard. No surprises. - - - - - - WHAT IT LOOKS LIKE - Report card - - - Fit8 / 10 - - Build-likelihoodhigh - - Safetyclean - - Cost / run~$0.04 - - - Verdict: - ready - - - - - - - PAYOFF - Go / no-go - with evidence - A clear decision - BEFORE you spend - time scaffolding — - plus a recommended - plan to follow. - ready · needs-work - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/uc3.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/uc3.svg deleted file mode 100644 index a12b84c..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/uc3.svg +++ /dev/null @@ -1,90 +0,0 @@ - - Use case 3 — Spin up a vertical pod from a template - Problem: you want a ready-made multi-agent setup for a known vertical such as support, trading or legal and you do not want to remember flags. You run metaharness with a vertical template, or the dedicated one-command wrapper. The tool scaffolds domain agents with system prompts, skills and per-host settings, all default-deny. You get a working vertical pod such as customer support, paper-by-default quant trading, or drafts-only contract redline. - - - - - - - - - - - USE CASE 3 - "Spin up a support / trading / legal pod from a template" - - - - PROBLEM - Build a whole pod - by hand? - You want a ready-made - multi-agent setup for a - known vertical — and - don't want to remember - a list of flags. - support · trading · legal - - - - - - WHAT YOU RUN - - metaharness --list - …pick a template, then: - - metaharness my-bot - --template vertical:support - …or no flags at all: - - npx @metaharness/support - Wrapper = byte-identical scaffold - - - - - - WHAT IT LOOKS LIKE - Pre-loaded pod - - - Domain agents + prompts - - Skills & commands - - Per-host settings - - All default-deny - - Nothing is allowed until - you explicitly open it. - - - - - - - PAYOFF - A working - vertical pod - - e.g. - • Customer support - • Paper-by-default - quant trading - • Drafts-only - contract redline - - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/uc4.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/uc4.svg deleted file mode 100644 index 2d8b116..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/uc4.svg +++ /dev/null @@ -1,96 +0,0 @@ - - Use case 4 — Check that a colleague's harness .zip is safe to run - Problem: someone hands you a generated harness .zip and you want to vet it before installing. You run harness mcp-scan, harness threat-model and harness verify, or use the Studio Verify tab. The tool statically scans for risky permissions, missing audits, wildcard permissions, unguarded secrets and unpinned deps, and confirms the Ed25519 witness signature, executing nothing. You get a clean, medium or high verdict and a shareable artifact. - - - - - - - - - - - USE CASE 4 - "Check that a .zip a colleague gave me is safe to run" - - - - PROBLEM - An unknown .zip - A colleague hands you - a generated harness. - Installing it could grant - shell, network or file - access you didn't expect. - - harness.zip - Vet it WITHOUT running it. - - - - - - WHAT YOU RUN - - harness mcp-scan <path> - - harness threat-model <path> - - harness verify - "npm audit for agent tools" - Static-only · nothing runs. - Or use the Studio Verify tab. - - - - - - WHAT IT LOOKS LIKE - Scan checklist - - Risky MCP permissions - checked - Missing audit / timeouts - checked - Wildcard permissions - checked - Unguarded secrets - checked - Unpinned deps - checked - - - Ed25519 witness signature - not tampered with - mcp-scan exits 1 on any HIGH finding - - - - - - - PAYOFF - A verdict + - an artifact - - - clean - - medium - - high - - Shareable for PR / - compliance review. - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/uc5.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/uc5.svg deleted file mode 100644 index 022f68f..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/uc5.svg +++ /dev/null @@ -1,95 +0,0 @@ - - Use case 5 — Cut your model bill without losing quality - Problem: you pay frontier prices for work a cheaper model could do. You install the metaharness router and call route on each query. The router sends each request to the cheapest model predicted to clear your quality bar, learned from your own eval logs, with zero native deps. You get same-quality output at lower spend; the DRACO benchmark reports a cheap model delivering frontier-quality research at roughly one-tenth the cost. - - - - - - - - - - - USE CASE 5 - "Cut my model bill without losing quality" - - - - PROBLEM - Frontier prices - for easy work - Every query goes to the - most expensive model — - even the simple ones a - cheaper model handles fine. - - Every request → - frontier model · $$$$ - - - - - - WHAT YOU RUN - - npm i @metaharness/router - …then in your code: - - route(query) - Picks the cheapest model - predicted to clear YOUR - quality bar. - Zero native deps · learns from your eval logs - - - - - - WHAT IT LOOKS LIKE - Smart routing - - - route() - - - - - - cheap - simple Q - - mid - normal Q - - frontier - hard Q - Each request lands where - it's good enough — no higher. - - - - - - - PAYOFF - Same quality, - lower spend - - ~1/10 - the cost - DRACO benchmark: - frontier-quality - research from a - small/cheap model. - diff --git a/ruv-explainer-agent-harness-generator/assets/diagrams/uc6.svg b/ruv-explainer-agent-harness-generator/assets/diagrams/uc6.svg deleted file mode 100644 index 1360ceb..0000000 --- a/ruv-explainer-agent-harness-generator/assets/diagrams/uc6.svg +++ /dev/null @@ -1,95 +0,0 @@ - - Use case 6 — Darwin Mode: the harness quietly improves itself - Darwin Mode is a safe self-improvement loop. The harness changes one of its own settings, tests that change in an isolated sandbox with no internet and no API key, and keeps it only if it measurably helped. The AI model stays frozen; only the wrapper evolves. Run npm run evolve to start; add --no-darwin to opt out. - - - - - - - - - - - - - - USE CASE 6 - "Let the harness quietly improve itself (Darwin Mode)" - - - - Step 1 — Try - Try a small - tweak - The harness changes - one of its own settings - — routing rules, prompt - wording, skill order. - - npm run evolve - starts the loop - - - - - - Step 2 — Test - Test it safely - in a sandbox - The tweak runs inside - an isolated sandbox — - no internet, no API key, - no side effects. - - isolated · read-only - safe gate, always on - - - - - - Step 3 — Keep? - Keep only what - measurably helps - Results are compared - against a real goal. - - improved → keep it - - no change → discard - then loop again - - - - loop · model frozen · only the wrapper evolves - - - - - - - PAYOFF - A harness - that gets - better on - its own - - model frozen - wrapper evolves - Opt out anytime: - --no-darwin - treat as experimental - diff --git a/ruv-explainer-agent-harness-generator/assets/fonts/.gitkeep b/ruv-explainer-agent-harness-generator/assets/fonts/.gitkeep deleted file mode 100644 index ae9ff55..0000000 --- a/ruv-explainer-agent-harness-generator/assets/fonts/.gitkeep +++ /dev/null @@ -1 +0,0 @@ -# 5 self-hosted woff2 fonts land here in P2.3 (BigShouldersDisplay SemiBold/Black, IBMPlexSans Regular/Medium, IBMPlexMono Regular). Zero CDN. Placeholder. diff --git a/ruv-explainer-agent-harness-generator/assets/fonts/README.md b/ruv-explainer-agent-harness-generator/assets/fonts/README.md deleted file mode 100644 index 610e0fc..0000000 --- a/ruv-explainer-agent-harness-generator/assets/fonts/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# assets/fonts/ — self-hosted woff2 (zero CDN) - -`styles.css` declares **5** `@font-face` faces, all loaded from THIS directory -with `font-display: swap`. No CDN, no Google Fonts request at runtime -[Constraint: site is fully self-hosted]. Drop the real `.woff2` files here at -build time (they are gitignored; commit/ship them with the deploy bundle). - -| File (exact name expected by `styles.css`) | Family | Weight | Use | -|---|---|---|---| -| `BigShouldersDisplay-SemiBold.woff2` | Big Shoulders Display | 600 | h3, CTA, brand label | -| `BigShouldersDisplay-Black.woff2` | Big Shoulders Display | 900 | h1/h2 display headings, coin | -| `IBMPlexSans-Regular.woff2` | IBM Plex Sans | 400 | body text | -| `IBMPlexSans-Medium.woff2` | IBM Plex Sans | 500 | emphasis | -| `IBMPlexMono-Regular.woff2` | IBM Plex Mono | 400 | eyebrows, code chips, meta, captions | - -## Sourcing - -Both families are SIL Open Font License (OFL) and free to self-host: -- **Big Shoulders Display** — Google Fonts (OFL). -- **IBM Plex Sans / IBM Plex Mono** — IBM Plex (OFL). - -Get the woff2 either by downloading the families and subsetting to Latin -(e.g. with `fonttools`/`pyftsubset` or `glyphhanger`) to keep each file small, or -by pulling the prebuilt woff2 from a Plex/Fontsource distribution. Subset to the -glyphs actually used (Latin + the few punctuation/arrow glyphs on the page) to -keep total font weight low. - -Filenames must match the table exactly — `styles.css` references them verbatim. diff --git a/ruv-explainer-agent-harness-generator/assets/img/.gitkeep b/ruv-explainer-agent-harness-generator/assets/img/.gitkeep deleted file mode 100644 index bc23f8f..0000000 --- a/ruv-explainer-agent-harness-generator/assets/img/.gitkeep +++ /dev/null @@ -1 +0,0 @@ -# Graphics G1-G6 land here in P5 (hero-stamp, mint-factory-line, cost-curve, darwin-loop, two-halves, og-card). Placeholder. diff --git a/ruv-explainer-agent-harness-generator/assets/img/README.md b/ruv-explainer-agent-harness-generator/assets/img/README.md deleted file mode 100644 index 5434e85..0000000 --- a/ruv-explainer-agent-harness-generator/assets/img/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# assets/img/ — graphics (G1–G6) - -Generated in **P5** (image-generation skill) once the P2 foundry/mint palette is -locked. Every hard concept gets a figure [INV-12]. All art uses the locked -palette — **warm-charcoal + molten-amber/copper, zero cyan** [Constraint K]. - -Palette reference (from `styles.css :root`): -`--bg #16120e` · `--amber #ff9e2c` · `--copper #c2703a` · `--ember #e8531f` · -`--brass #d9a441` · `--ink #f3e8d8`. - -| File | ID | Section | What it shows | Aspect | -|---|---|---|---|---| -| `hero-stamp.png` | **G1** | 01 | The "MH" molten coin / what-it-is hero stamp. | 16:9 | -| `mint-factory-line.png` | **G2** | 02 | Repo → minted-harness assembly line (the factory metaphor). | 16:9 | -| `model-router-cost-curve.png` | **G3** | 04 | `@metaharness/router` "cheapest model that's good enough" cost curve. | 16:9 | -| `darwin-loop.png` | **G4** | 05 | Darwin Mode self-improvement loop: mutate → sandbox-test → keep-if-better. | 16:9 | -| `one-download-two-halves.png` | **G5** | 09 | One download splitting into `for-ai/` + `for-humans/`. | 16:9 | -| `og-card.png` | **G6** | `` | Social share card. | **1200×630** | - -Notes: -- Export PNG (or optimized WebP alongside if added later); keep each ≤ ~250 KB. -- Filenames are referenced by `index.html` / `styles.css` — do not rename without - updating those. diff --git a/ruv-explainer-agent-harness-generator/assets/img/g1.png b/ruv-explainer-agent-harness-generator/assets/img/g1.png deleted file mode 100644 index 8b3e079..0000000 Binary files a/ruv-explainer-agent-harness-generator/assets/img/g1.png and /dev/null differ diff --git a/ruv-explainer-agent-harness-generator/assets/img/g1.prompt.txt b/ruv-explainer-agent-harness-generator/assets/img/g1.prompt.txt deleted file mode 100644 index f19466e..0000000 --- a/ruv-explainer-agent-harness-generator/assets/img/g1.prompt.txt +++ /dev/null @@ -1 +0,0 @@ -Warm, friendly 3D illustration in a cozy artisan foundry / coin-mint aesthetic, deep warm-charcoal background with a soft amber glow. LEFT SIDE: a plain, dull, lifeless grey metal plate stamped with a simple flat folder-and-code-branches icon labeled in large plain text "Your GitHub Repo" — it looks cold, ordinary, matte, forgettable. CENTER: a big friendly stamping press / mint die descending, the moment of transformation, with a soft burst of warm molten light where it touches the metal — labeled simply "Mint It". RIGHT SIDE: the same object reborn as a beautiful glowing circular coin-medallion in molten amber and copper, warm light radiating outward, a small subtle check-mark seal pressed into its surface — labeled in large plain text "Your Custom Agent". A clean left-to-right arrow flow connects the three stages so a complete beginner instantly reads "dull repo turns into a warm, finished, trustworthy agent." Tactile metallic depth, soft rounded shapes, inviting handcrafted warmth — like raw metal being stamped into a glowing keepsake coin. Color palette strictly warm: deep charcoal, amber, copper, honey-gold, soft cream highlights. Absolutely NO cyan, NO blue, NO neon, NO cold sci-fi tech-art, NO circuit boards, NO generic-AI-slop swirls. Minimal composition, lots of breathing room, only three short plain-language labels in a clean friendly sans-serif, no jargon, no extra text, no code. Cinematic soft glow, gentle shadows, premium and approachable. Wide 16:9 hero composition. \ No newline at end of file diff --git a/ruv-explainer-agent-harness-generator/assets/img/g2.png b/ruv-explainer-agent-harness-generator/assets/img/g2.png deleted file mode 100644 index a6297fa..0000000 Binary files a/ruv-explainer-agent-harness-generator/assets/img/g2.png and /dev/null differ diff --git a/ruv-explainer-agent-harness-generator/assets/img/g2.prompt.txt b/ruv-explainer-agent-harness-generator/assets/img/g2.prompt.txt deleted file mode 100644 index 6b0aa48..0000000 --- a/ruv-explainer-agent-harness-generator/assets/img/g2.prompt.txt +++ /dev/null @@ -1,3 +0,0 @@ -A warm, friendly 3D illustration of a small "mint and foundry" assembly line that builds a custom toolkit, read left to right like a simple storybook diagram. On the far LEFT, a single tidy cardboard-and-metal box labeled in large plain letters "YOUR REPO" sits on a conveyor belt and feeds into a rounded, approachable machine. In the MIDDLE, a cozy rounded foundry-machine with a soft glowing amber furnace gently stamps and assembles parts; tiny visible mechanisms and a warm molten-copper glow suggest "a factory making something just for you" — friendly, not industrial-scary. On the RIGHT, the finished result rolls out: one neat, branded toolkit package, an open kit-box holding four clearly separated labeled items, each tagged with a large plain-language word label on a little metal plate: "CLI", "MEMORY", "SKILLS", and "GUARDRAILS". The four items read as distinct friendly objects (a small command bar/terminal chip for CLI, a glowing notebook/memory core for MEMORY, a set of interchangeable tool-bits for SKILLS, and a sturdy shield for GUARDRAILS), assembled together into one tidy package with a subtle ribbon or seal that says "READY". - -STYLE: foundry/mint aesthetic. Deep warm-charcoal background. Molten amber, copper, and soft gold accents with a gentle warm glow and bloom. Tactile metallic depth, soft rounded edges, smooth matte-and-polished surfaces, soft studio rim lighting, gentle ambient occlusion, cozy and inviting like a craft workshop. Approachable, hand-built, premium-but-friendly. NOT cold tech-art, NO cyan or blue neon, NO holographic sci-fi, NO circuit-board clutter, NO generic AI sci-fi slop. Minimal and uncluttered — only the five plain-language labels appear ("YOUR REPO", "CLI", "MEMORY", "SKILLS", "GUARDRAILS"), each large, crisp, perfectly legible, sans-serif, no other text or jargon. Clear left-to-right flow with subtle directional arrows in soft amber so a non-technical viewer instantly understands "a repo goes in, and a custom toolkit comes out." Wide cinematic composition for a website feature image, generous negative space, calm and confident, warm and welcoming. \ No newline at end of file diff --git a/ruv-explainer-agent-harness-generator/assets/img/g3.png b/ruv-explainer-agent-harness-generator/assets/img/g3.png deleted file mode 100644 index c520dae..0000000 Binary files a/ruv-explainer-agent-harness-generator/assets/img/g3.png and /dev/null differ diff --git a/ruv-explainer-agent-harness-generator/assets/img/g3.prompt.txt b/ruv-explainer-agent-harness-generator/assets/img/g3.prompt.txt deleted file mode 100644 index 1303833..0000000 --- a/ruv-explainer-agent-harness-generator/assets/img/g3.prompt.txt +++ /dev/null @@ -1,15 +0,0 @@ -A friendly, simple FLAT 2D vector illustration of a cost BAR CHART, drawn like a clean cozy infographic. Set on a LIGHT warm cream / off-white background (soft #FBF4E9 tone, never dark, never charcoal, never black). The whole image is bright, airy, and inviting with lots of negative space. - -Two side-by-side bars of IDENTICAL WIDTH stand on a single clearly drawn light horizontal baseline. Both bars have soft rounded top corners, gentle flat shading in a warm amber / coral fill (soft copper-amber, like #E8A06B to #E07A5F), and a subtle soft drop shadow on the cream floor. The LEFT bar is TALL and labeled in large clean rounded plain letters "BEFORE" with the symbol "$$$" centered beneath it. The RIGHT bar is MUCH SHORTER (about one-third the height), labeled in the same large clean rounded letters "AFTER" with the symbol "¢" centered beneath it. The dramatic difference in bar heights makes the cost savings instantly obvious at a glance. - -Floating directly ABOVE each bar, at the SAME size and the SAME height, sits ONE identical small green check-circle badge (a simple flat circle with a white checkmark, soft mint-green) — one above BEFORE, one above AFTER — quietly signalling that the quality / result is exactly the SAME in both cases. - -STYLE: soft hand-drawn friendly flat illustration, warm and optimistic, like a modern wellness-app or fintech onboarding graphic. Smooth flat fills, gentle soft shadows, soft rounded shapes, clean rounded sans-serif lettering in a warm muted brown (#6B4A35). Centered, balanced composition with generous breathing room. - -Palette: warm cream background, amber / coral / soft copper bars, one mint-green check badge per bar, muted-brown text. Light, calm, approachable, human. - -Only these words appear: "BEFORE", "AFTER", "$$$", "¢". No other text, no logos, no axis numbers, no clutter. - -STRICTLY AVOID: NO fire, NO fiery embers, NO sparks, NO glowing molten metal, NO metallic ingots, NO 3D rendering, NO glossy reflections, NO dark / moody / charcoal / near-black background, NO neon, NO cyber aesthetic, NO vignette darkening. This must read as a LIGHT, simple, friendly chart — not dramatic, not cold, not premium-tech. - -Concept to convey: "route each task to the cheapest good-enough model — same quality, far less spend." \ No newline at end of file diff --git a/ruv-explainer-agent-harness-generator/assets/img/g4.png b/ruv-explainer-agent-harness-generator/assets/img/g4.png deleted file mode 100644 index 952401b..0000000 Binary files a/ruv-explainer-agent-harness-generator/assets/img/g4.png and /dev/null differ diff --git a/ruv-explainer-agent-harness-generator/assets/img/g4.prompt.txt b/ruv-explainer-agent-harness-generator/assets/img/g4.prompt.txt deleted file mode 100644 index 92b6a6f..0000000 --- a/ruv-explainer-agent-harness-generator/assets/img/g4.prompt.txt +++ /dev/null @@ -1,10 +0,0 @@ -Warm, friendly 3D illustration in a tactile metalworking "foundry" style, on a deep warm-charcoal background (#16120e). A single large, gentle circular arrow loops clockwise in the center of the frame — a soft, rounded, smooth ribbon of molten amber and copper metal (#ff9e2c amber, #c2703a copper) with a soft warm glow, like cooling poured bronze, NOT thin or sharp. The loop feels calm and inviting, not frantic. At the top of the circle the arrowhead curves gently back into the loop, suggesting "it keeps going on its own." Resting warmly inside the loop is one friendly, rounded checkmark (tick) in glowing brass-gold (#d9a441), softly lit with a gentle ember halo (#e8531f) — the checkmark reads as approval and reassurance, "kept because it helped." - -Around the loop, three small evenly-spaced soft glowing nodes suggest the three steps of a gentle cycle: a tiny tool/wrench shape for "try a small tweak," a small rounded enclosure/box shape for "test it safely in a sandbox," and the central checkmark for "keep only what helps." Keep these node icons very simple, large, and unmistakable — friendly pictograms, not busy diagrams. - -Three short, large, plain-English handwritten-clean labels placed clearly around the loop in warm ivory text (#f3e8d8), high contrast and easy to read for a non-technical person: -"try a small tweak" -"test it safely" -"keep what helps" - -Overall mood: warm, friendly, inviting, reassuring, quietly confident — it conveys "it quietly gets better on its own, safely." Tactile metallic depth with soft rounded edges, gentle warm rim-light and a soft amber bloom glow, cozy and human. Minimal and uncluttered with generous negative space, large central focal point, balanced composition. STRICTLY warm palette only: charcoal, amber, copper, ember-orange, brass-gold, ivory. ABSOLUTELY NO cyan, NO blue, NO teal, NO neon green, NO cold colors. NOT cold sci-fi tech-art, NOT generic glowing-circuit AI aesthetic, NOT cluttered, NO dense text, NO code, NO jargon, NO tiny labels, NO photoreal humans. Wide 16:9 composition suitable for a website section header. \ No newline at end of file diff --git a/ruv-explainer-agent-harness-generator/assets/img/g5.png b/ruv-explainer-agent-harness-generator/assets/img/g5.png deleted file mode 100644 index dba8475..0000000 Binary files a/ruv-explainer-agent-harness-generator/assets/img/g5.png and /dev/null differ diff --git a/ruv-explainer-agent-harness-generator/assets/img/g5.prompt.txt b/ruv-explainer-agent-harness-generator/assets/img/g5.prompt.txt deleted file mode 100644 index 15207c1..0000000 --- a/ruv-explainer-agent-harness-generator/assets/img/g5.prompt.txt +++ /dev/null @@ -1,11 +0,0 @@ -Warm, friendly conceptual illustration explaining a simple idea to a non-technical person: ONE download that opens into TWO halves, side by side. A single rounded zip-file package sits at the top center, gently splitting open and unfolding downward into two equal, friendly panels. - -LEFT PANEL labeled "For you" (large, plain, clearly readable hand-lettered-feeling label): a cozy rounded scene of a friendly person calmly reading and watching — a simple smiling figure relaxing with an open book and a small play-button screen, warm and human, approachable. - -RIGHT PANEL labeled "For your AI" (large, plain, clearly readable label): a soft, glowing rounded brain shape that looks gently searchable — warm amber light pulsing inside it, a small friendly magnifying glass hovering near it, soft connection dots, inviting and alive rather than cold or robotic. - -A single gentle line or ribbon connects the one package at top to BOTH panels below, making it obvious that ONE thing becomes TWO halves. Optional tiny tagline feel: "one zip, two halves." - -STYLE — FOUNDRY / MINT aesthetic: deep warm charcoal background (dark brown-black, not pure black, not blue-grey), molten amber and copper accent colors with a soft warm glow, tactile metallic depth like gently poured warm metal, rounded soft shapes, generous padding, lots of breathing room. Cozy, inviting, hand-crafted artisan warmth. Friendly and human-first. - -ABSOLUTELY AVOID: cyan, teal, electric blue, neon, cold sci-fi tech-art, circuit-board clutter, busy wireframes, generic glowing-AI-orb cliché, dense small text, jargon, hexagon grids, matrix code rain. Keep it minimal, large, warm, and instantly understandable by someone who is not technical. Only the two short labels "For you" and "For your AI" as text — clean, large, plain, perfectly legible. Soft glow, warm shadows, professional but cozy. Wide composition. \ No newline at end of file diff --git a/ruv-explainer-agent-harness-generator/assets/img/g6.png b/ruv-explainer-agent-harness-generator/assets/img/g6.png deleted file mode 100644 index 625c026..0000000 Binary files a/ruv-explainer-agent-harness-generator/assets/img/g6.png and /dev/null differ diff --git a/ruv-explainer-agent-harness-generator/assets/img/g6.prompt.txt b/ruv-explainer-agent-harness-generator/assets/img/g6.prompt.txt deleted file mode 100644 index c23f460..0000000 --- a/ruv-explainer-agent-harness-generator/assets/img/g6.prompt.txt +++ /dev/null @@ -1,12 +0,0 @@ -A warm, inviting wide social share card (1200x630 banner composition, designed to feel like an open-graph preview), in a tactile "foundry / mint" aesthetic. - -BACKGROUND: a deep warm-charcoal field (#16120e to #1d1812), softly lit like the inside of a cozy metal workshop — not cold tech-art, not sci-fi. Gentle radial glow of molten amber light (#ff9e2c) blooming from behind the central object, casting a warm copper (#c2703a) ambient haze toward the lower corners. A faint scatter of soft amber bokeh sparks, like embers drifting in a warm forge — sparse, dreamy, never busy. - -CENTERPIECE: a single large, freshly-minted metal coin / commemorative stamp, slightly off-center, catching warm light on its top-left edge. The coin is struck from polished copper and brass (#c2703a / #d9a441) with a molten amber rim that glows like cooling metal (#ff9e2c into #e8531f at the hottest point). Embossed deeply into the face of the coin, in clean bold sans-serif letters, the two big letters "MH" — tactile, raised metal, catching a soft highlight. The coin has real physical depth: beveled edges, gentle reflections, a sense you could pick it up. - -TEXT (must be spelled exactly, crisp and legible, large, plain friendly typography in warm cream ink #f3e8d8): -- Headline, large and confident, set beside or just below the coin: "MetaHarness" -- Subtitle, smaller, warm and approachable, on its own line beneath: "a factory for agent frameworks" -Keep typography minimal and clean — only these two lines of text, no other words, no logos, no UI, no buttons, generous breathing room. - -MOOD & STYLE: warm, friendly, inviting, approachable, hand-made-craft feeling — like the welcoming sign of a small artisan mint or foundry. Cinematic soft glow, shallow tactile depth, premium but cozy. Strictly warm palette: deep warm-charcoal, molten amber, copper, brass, ember-orange, cream ink. ABSOLUTELY NO cyan, NO blue, NO teal, NO neon-purple, NO cold sci-fi tech-grid, NO generic AI-art clutter, NO circuit boards, NO robots. Clean, calm, confident, human. diff --git a/ruv-explainer-agent-harness-generator/downloads/.gitkeep b/ruv-explainer-agent-harness-generator/downloads/.gitkeep deleted file mode 100644 index 31373b6..0000000 --- a/ruv-explainer-agent-harness-generator/downloads/.gitkeep +++ /dev/null @@ -1 +0,0 @@ -# metaharness-dropin.zip (agent-install convenience copy) assembled in P7. Binaries gitignored [H]. Placeholder. diff --git a/ruv-explainer-agent-harness-generator/favicon.svg b/ruv-explainer-agent-harness-generator/favicon.svg deleted file mode 100644 index a5ba04e..0000000 --- a/ruv-explainer-agent-harness-generator/favicon.svg +++ /dev/null @@ -1,34 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - MH - - - MH - - diff --git a/ruv-explainer-agent-harness-generator/index.html b/ruv-explainer-agent-harness-generator/index.html deleted file mode 100644 index d685f24..0000000 --- a/ruv-explainer-agent-harness-generator/index.html +++ /dev/null @@ -1,1922 +0,0 @@ - - - - - - MetaHarness — mint a custom agent harness from any repo - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-

- A plain-language explainer for - ruvnet/agent-harness-generator - by Reuven Cohen - (@ruvnet). - Not affiliated — an independent walkthrough of the open-source project. -

-

- - Updated 2026-06-19 · source @ db65fab · v0.1.3 (latest release tag; the tool self-describes as v0.1.x beta) -

-
-
- - -
- -
- - -
-
-
-
-

ruvnet · agent-harness-generator

-

The harness is
the product.

-

- MetaHarness is a free tool that turns any GitHub repo — or a blank - page — into your own AI assistant: its own name, its own - npx your-name command, the skills it needs, a memory of your - project, and a built-in safety net. It runs on your machine. It never - runs your code. The AI model underneath stays the same — what you - build and own is the wrapper around it. -

-

- An independent explainer for Reuven Cohen’s - (@ruvnet) - agent-harness-generator — built to help you actually adopt and implement his technology. -

- - Get the drop-in → -
- -
-
- - -
-
- - -
- - 01 - -

Why it was built

- Arc 1 — what pushed someone to make this? -
- -
-
-
- - The one-way door: forking ruflo versus generating with MetaHarness - Forking the whole ruflo bundle freezes you and cuts you off from future kernel updates. MetaHarness generates only the pieces you want, branded by you, while still pulling future engine updates. - - - - - - - - - - - - - - - The "one-way door" - Forking the whole bundle vs. generating just the pieces you want - - - - - - BEFORE — fork ruflo - - - - The whole ruflo bundle (one frozen copy) - - - Kernel primitives - MCP, hooks, memory, routing - - - Bundled content - 60+ agents · 30+ skills · 33 plugins - - Kernel and content are fused together — you must take all of it - You fork the ENTIRE thing just to rebrand it - - - - Your frozen fork - A snapshot — never moves again on its own - - - - fork - - - - Future engine updates - never reach your fork - - - - - - - cut off - - - AFTER — generate with MetaHarness - - - - ruflo kernel (lives upstream, keeps improving) - - MCP · hooks · memory · routing · witness — pinned version - - - - MetaHarness generator - picks ONLY the pieces you choose - - - - - - Your branded harness - npx your-name · your agents · your skills - - only the parts you wanted — owned by you - - - generate - - - - Future engine updates - still flow in — re-pin to a newer kernel - - - - - stays connected to the kernel - - - - - Fork = take everything, then it freezes. Generate = take what you need, keep getting updates. - -
The one-way door, drawn out: forking the whole ruflo bundle freezes you and cuts off engine updates (left); MetaHarness generates only the pieces you want, branded by you, and stays connected to the kernel for future updates (right).
-
-
- A dull grey metal plate labelled Your GitHub Repo on the left, a glowing mint press labelled Mint It in the centre, and a warm amber coin labelled Your Custom Agent on the right, connected by an arrow. -
- The core idea in one picture: a plain repo goes in, gets stamped, - and comes out as a finished, branded agent you own. -
-
-

- First, the short version of what it is, so the rest makes - sense. A harness is the wrapper around an AI - model — not the model itself. Underneath you are still talking to - Claude, GPT, or whatever model you use. The harness is the bit that - gives your assistant a name, knows your project, carries a set of - skills, and keeps a safety net around what it is allowed to do. - MetaHarness is a factory that builds those wrappers. - As the project puts it: “It is not another agent framework. - It is a factory for agent frameworks. The model is replaceable. The - harness is the product.” -

-

- So why build a factory instead of just one more assistant? - Because of a trap the makers hit themselves. Their earlier product, - ruflo, came as one big bundle — a small core - engine welded to 60+ pre-made agents, 30+ skills, and 33 plugins, all - fused together. People loved the engine but wanted their own - brand, their own agents, and their own listing. The only way to get - that was to copy (“fork”) the whole bundle — and the - moment you did, you were cut off from every future update to the - engine. That is a one-way door: rebrand once, and you - are frozen in time. -

-

- MetaHarness was built to take the hinges off that door. It - separates the reusable engine from the opinionated content, - so you can take just the engine and generate just the pieces you - actually want — owned and branded by you, and still able to pull - future engine updates. -

- -
-
- - -
- - 02 - -

What problem it solves

- Arc 2 — what pain does this take away? -
- -
-
-
- - The problem MetaHarness solves: lock-in, host fragmentation, and rebuilt plumbing - A generic AI agent guesses at your repo. Three concrete problems follow: lock-in when you fork a bundle to rebrand it, host fragmentation across different agent runtimes, and reinventing about 80 percent of the same infrastructure on every new project. - - - - - - - - - - The problem - Why a generic agent is not enough — and why three things keep going wrong - - - - Generic AI agent - knows nothing about - YOUR codebase - "...is this a Python repo?" - - - - Your repo - its own layout, build, - tools, conventions - needs an agent that fits - - - - guesses ? ? ? - no project knowledge, no fit - - - Three problems this creates - - - - - 1 · Lock-in - - - You fork a bundled product - just to put your brand on it - - - - - Now you are off the upstream - — no future updates - - Rebranding - shouldn't cost you - every upstream improvement - (the same one-way door) - - - - 2 · Host fragmentation - - Agents now run in many places — - each with its own config rules - - - Claude Code - - Codex - - - Hermes - - pi.dev - - One agent, many hosts - Each host wants different - config files — a rewrite - should target any host, no rewrite - - - - 3 · Rebuilt plumbing - - Every new agent project rebuilds - the same boring infrastructure - - - MCP server setup - - memory namespace - - governance policy - - release signing - - ~80% built by hand, every time - the same plumbing, over and over - - - Lock-in, host fragmentation, and rebuilt plumbing are exactly what MetaHarness is built to remove. - -
The three pains, side by side: a generic agent guesses at your repo, then lock-in, host fragmentation, and rebuilding ~80% of the same plumbing follow.
-
-

- There are three everyday headaches it removes: -

-
    -
  1. - Lock-in. As above — copying a bundled product - just to rebrand it means you give up every future update to the part - you actually relied on. You get stuck. -
  2. -
  3. - Too many places to run an assistant. Claude Code - used to be the obvious home for AI agents. Now there are several - — Codex, Hermes, pi.dev and more — and each one wants its - config files set up its way. (Config = the small settings - files that tell a tool how to behave.) Setting the same assistant up - by hand for each place is tedious and easy to get wrong. MetaHarness - writes the right files for whichever places you pick. -
  4. -
  5. - Rebuilding the same plumbing every time. Roughly - 80% of any new agent project is the same unglamorous wiring done over - again: a local tool server, a place to keep memory, the rules for - what is allowed, and a way to sign your release so people can trust - it. MetaHarness generates all of that for you, correctly, in one go. -
  6. -
-

- In plain terms: instead of spending your first week rebuilding - scaffolding, you answer a few questions and get a clean, safe starting - point that is already yours. -

- -
-
- - -
- - 03 - -

Why now

- Arc 3 — why does this make sense at this moment? -
- -
-
-
- - Why now: hosts have multiplied and the plugin marketplace woke up - Two forces make a harness factory worth building now. First, the hosts multiplied — Claude Code, Codex, pi.dev, Hermes, OpenClaw and RVM all gained agent conventions. Second, the plugin marketplace woke up — a scaffolded harness both consumes plugins from the ruflo IPFS registry and can publish its own back. - - - - - - - - - - - - - Why now - Two shifts made a "factory for harnesses" worth building - - - - - 1 · The hosts multiplied - Claude Code used to be the only place. Now there are many. - - - - Then - one host - - - - - Now - six+ hosts - - - - Claude Code - stable - - - Codex CLI - MCP support - - - pi.dev - dev platform - - - Hermes - Nous Research - - - OpenClaw - newer - - - RVM - newer - - - - One generated harness - targets any of them — no rewrite - - - - - - 2 · The marketplace woke up - Plugins are now traded — a harness both takes and gives. - - - - ruflo IPFS plugin registry - the shared marketplace of agent plugins - - - - Your scaffolded harness - a marketplace participant - - - - - consumes - pulls plugins in - - - - - publishes - pushes its own back - - - - Without a generator, every new - participant rebuilds 80% by hand - - - More hosts to target + a live plugin economy = the moment a harness factory pays off. - -
Why now: the hosts multiplied (Claude Code, Codex, pi.dev, Hermes, OpenClaw, RVM) and the plugin marketplace woke up — a generated harness both consumes plugins from the IPFS registry and can publish its own back.
-
-
- A friendly foundry assembly line: a box labelled Your Repo enters a glowing machine and a finished toolkit rolls out holding four labelled parts — CLI, Memory, Skills, and Guardrails. -
- Your repo goes in one end; a tidy, branded toolkit — a command - (CLI), a memory, a set of skills, and guardrails — comes out the - other. -
-
-

- A factory only pays off once there is enough variety for it to - produce. Two things just crossed that line. -

-

- The homes for AI agents multiplied. A year or two ago - you mostly ran assistants in one place. Now Codex, Hermes, pi.dev and - others each have their own way of running agents. A factory that can - target any of them — without you rewriting anything — is - suddenly worth having. -

-

- The plugin marketplace woke up. A - “plugin” is just an add-on capability you can drop into your - assistant. There is now a shared, open registry of these (hosted on - IPFS, a decentralised file network), so a harness you build can both - pull in ready-made plugins and, if you want, - publish its own. Building becomes assembling from parts rather - than carving everything from scratch — which is exactly when an - assembly line earns its keep. -

- -
-
- - -
- - 04 - -

How it solves it

- Arc 4 — how does it actually do the job? -
- -
-
-
- - The composer pipeline - A GitHub repo, or a blank slate, enters the composer and flows through nine - stages in order — Identity, Hosts, Primitives, Agents, Skills, Plugins, Features, Branding, - Confirm — emerging as a branded, npm-publishable agent harness package. Each stage shows in - plain words what happens there. - - - - - - - - - - - - - - - - - - - - - - - - - HOW IT ACTUALLY WORKS UNDER THE COVERS - The composer pipeline - You answer nine questions, in order. The composer assembles a complete package from your answers. - - - - - A GitHub repo - …or a blank slate. - It never runs your code — it only reads. - - - - Same nine questions, two ways - A friendly picker (the “wizard”), or - the same answers as command-line flags. - - - - - - - - - - - - - 1 - Identity - The name, the package scope, a description, a licence, and who the author is. One screen. - - - - - - - - 2 - Hosts - Tick where it should run — Claude Code, Codex, pi.dev, Hermes, and more. Pick at least one. - - - - - - - - 3 - Primitives - Engine blocks on or off: tool server (always on), automations, memory, routing, marketplace, provenance. All on by default. - - - - - - - - 4 - Agents - Choose helpers from a curated catalogue. It suggests a coder, a reviewer, and a tester to start. - - - - - - - - 5 - Skills - Reusable abilities you bolt on — defaults wire up hooks, memory search, and swarm orchestration. - - - - - - - - 6 - Plugins - Optional add-ons from the shared registry, with live download counts and ratings. None by default. - - - - - - - - 7 - Features - Opt-in extras that change the wiring: teamwork between agents, claims-based access, self-improvement. - - - - - - - - 8 - Branding - “Powered-by” mode or fully independent, plus your own brand wording. - - - - - - - - 9 - Confirm - A summary: every file it will create, the exact engine version it pins to, and a size estimate — before anything is written. - - - - - - - - - - - EMERGES AS - A branded, npm-publishable harness - Your own npx your-name command — a self-contained - package you own and can publish. (See section 05.) - - - - - The composer’s state is one typed answer-object — the picker and the flags build the same thing, so both paths produce the same harness. - - -
The composer pipeline: a repo or blank slate enters and flows top-to-bottom through the nine ADR-003 stages — Identity, Hosts, Primitives, Agents, Skills, Plugins, Features, Branding, Confirm — emerging as a branded, npm-publishable harness. It never runs your code.
-
-

- It walks you through a short series of choices — call it the - composer — and then assembles a complete, - self-contained package from your answers. You can answer the questions - in a friendly picker (a “wizard”) or, if you prefer, pass - the same answers as command-line options. Either way you end up at the - same place. The steps, in order, are: -

-
    -
  1. Identity — the name, the package scope, a - description, a licence, and who the author is.
  2. -
  3. Hosts — tick which places you want it to run - (Claude Code, Codex, and so on). Pick at least one.
  4. -
  5. Primitives — switch the engine’s - building blocks on or off: the tool server (always on), automations, - memory, smart routing, the marketplace hook, and signed provenance. - All on by default.
  6. -
  7. Agents — choose helpers from a curated list - (it suggests a coder, a reviewer, and a tester to start).
  8. -
  9. Skills — reusable abilities you can bolt on.
  10. -
  11. Plugins — optional add-ons from the shared - registry (none by default).
  12. -
  13. Features — opt-in extras like teamwork - between agents or self-improvement.
  14. -
  15. Branding — “powered-by” mode or - fully independent, plus your brand wording.
  16. -
  17. Confirm — a clear summary: every file it will - create, the exact engine version it pins to, and a size estimate, - before anything is written.
  18. -
- -

- Two things make this safe and predictable. It never runs your - code — when it looks at a repo it only reads the file - list and a few text files to make suggestions; it does not execute - anything. And the generated tool server starts locked - down (“default-deny”): no internet access, no - shell, no writing to files, until you explicitly allow each - one. Nothing is on that you did not turn on. -

-

- - A note so the numbers add up: the teaching walkthrough on this page - uses seven questions (the 7 stages of understanding, - sections 01–07). The tool’s own composer has the - nine build steps listed just above. They are - different lists for different jobs — don’t worry if the - counts differ. - -

-
-
- - -
- - 05 - -

What “solved” looks like

- Arc 5 — how do you know it worked? -
- -
-
-
- - Anatomy of a generated harness - What is literally inside the output package: a repo-aware command-line tool, - a local tool (MCP) server, a project-scoped memory space, skills generated from your file - layout, a default-deny governance policy, and witness-signed releases — all wrapping a - replaceable AI model and pointed at your repository. - - - - - - - - - - - - - - - - - - - - - - - - WHAT “SOLVED” LOOKS LIKE - Anatomy of a generated harness - One self-contained package — say you called it my-bot. Here is what is literally inside it. - - - - THE HARNESS — THE WRAPPER YOU OWN - Everything below is yours, branded as you, and ships in the package. - - - - - - - A repo-aware command-line tool - Your own npx my-bot command, branded as - yours — not as someone else’s tool. It knows - your project, because it was built for it. - - - - - - A local tool server - Its own MCP server registration, running on - your machine. This is how the agents reach - tools — nothing hosted, nothing remote. - - - - - - Project-scoped memory - Its own private memory space, kept separate - from everything else on your machine. What - it learns about your project stays with it. - - - - - - Skills from your file layout - It reads your repo’s file list, manifest and - README to suggest the right agents and skills - — without ever executing your code. - - - - - - A default-deny safety policy - The tool server starts locked down: no - internet, no shell, no writing files — until - you allow each one. Nothing on you didn’t turn on. - - - - - - Witness-signed releases - A signed receipt of exactly what is inside - (an Ed25519 witness manifest), so anyone who - installs it can confirm nothing was swapped. - - - - - - + the agents, skills, plugins, and per-host config files you chose - Copied from the catalogue into the package — your selection, wired up and ready to run. - - - - - - REPLACEABLE SLOT - The AI model — Claude, GPT, or whatever your host brings - The harness wraps the model; it is not the model. Swap the model and everything above still stands. - - - - - - POINTED AT - YOUR repo - The whole harness is - tuned to one codebase - — yours — not a - generic chatbot. - It reads, but never - runs, your code. - - - - aimed at → - - - - - SHIP IT - npm publish - Your users run - npx my-bot init - They never see the - factory underneath - — only your brand. - - - - - - The model is replaceable. The harness is the product. - Nothing here is invented — every piece is what the generator writes into the package, locked down and signed by default. - v0.1.x beta — published and usable; the README badge shows 568 tests passing. - -
Anatomy of a generated harness: the wrapper you own — repo-aware CLI, local MCP tool server, project-scoped memory, skills inferred from your file layout, default-deny governance, Ed25519 witness-signed releases — wrapping a replaceable model and pointed at your repo. The model is replaceable; the harness is the product.
-
-
- A warm circular loop of molten metal with three steps around it — try a small tweak, test it safely, keep what helps — and a glowing checkmark in the centre. -
- The self-improvement loop: try a small tweak, test it safely, keep - only what helps. It can keep going on its own. -
-
-

- When it has done its job, you have a single, self-contained package - — say you called it my-bot — that includes: -

-
    -
  • Its own npx my-bot command, branded as yours, not as - someone else’s tool.
  • -
  • Its own local tool server, locked down by default.
  • -
  • Its own private memory space, kept separate from everything else.
  • -
  • The agents, skills, plugins, and per-place config files you chose.
  • -
  • A signed receipt of exactly what is inside it - (a cryptographic signature called an Ed25519 witness manifest), so - anyone who installs it can confirm they got precisely what you - shipped — nothing swapped or added.
  • -
-

- You can publish it (npm publish) and your users run - npx my-bot init. They never see the factory underneath - — only your brand. -

-

- And it does not have to stand still. A finished harness can be set to - quietly improve its own settings over time: it tries a - small tweak, tests it safely in a sandbox, and keeps the change only if - it measurably helped. The AI model never changes — only the - wrapper gets a little better. (More on this in the use cases below.) -

- -

- - Honest maturity note: this is v0.1.x beta — - published and usable, but still settling. The README badge shows - 568 tests passing; you may see slightly different - totals in other docs as they catch up, so treat 568 as - “the headline figure,” not gospel. - -

-
-
- - -
- - 06 - -

How to implement it

- Arc 6 — what does the path from idea to package look like? -
- -
-
-
- - Two ways in, one result - Two implementation paths — the browser Studio and the terminal (npx metaharness) — both produce the same branded harness package that is yours to keep. - - - - - - - - - - - - - - - - Two ways in — same result - Pick the path that fits how you work. Both hand you a .zip (or folder) that is yours to keep. - - - - - Browser Studio - nothing to install - - - - - Open the Studio - ruvnet.github.io - - - - - Pick a tab, - make choices - repo, scratch, skill, verify - - - - - Download .zip - in your browser - - - - - - - - - Terminal - if you live in the command line - - - - Run the command - npx metaharness - - - - - Flags or wizard - --template --host - or --wizard asks you - - - - - Scaffolded folder - written to disk - - - - - - - - - Same branded - package - your own npx my-bot, - yours to keep - - - - - - - - - Then, on your own machine — identical from here: - unzip my-bot.zip   →   cd my-bot   →   npm install   →   edit, then npm publish --provenance - -
Two ways in, one result: the in-browser Studio (Download .zip) and the terminal (npx metaharness) both produce the same harness folder that is yours to keep.
-
-

- There are two ways in, and they give the same result — a - .zip (or scaffolded folder) that is yours to keep. -

-

- 1. In your browser, with nothing to install. Open the - Studio at - ruvnet.github.io/agent-harness-generator, - pick a tab (turn a repo into a harness, create one from scratch, add a - skill or agent, or verify a harness), make your choices, and click - Download .zip. Then on your own machine: -

-
unzip my-bot.zip
-cd my-bot
-npm install
-

- The Studio runs entirely in your browser. For analysis it only reads a - repo’s public file list through GitHub’s - API — it never reads your file contents on a server, and there is - no account, no sign-in, and no tracking. -

-

- 2. In your terminal, if you live there. The same - behaviour, from the command line: -

-
npx metaharness my-bot --template vertical:coding --host claude-code
-# or be asked the questions instead:
-npx metaharness --wizard
-

- After scaffolding, the files are yours: open them, delete what you - don’t need, adjust the wording and the routing, and when - you’re happy, ship it with npm publish --provenance - (the --provenance part attaches that signed receipt so - installers can trust it). -

-

- One naming note so nothing trips you up: the published command is - npx metaharness. In some older docs you may see - npx create-agent-harness — that is the - same tool under its internal package name, not a second - product. Lead with metaharness. -

- -
-
- - -
- - 07 - -

How to start

- Arc 7 — what is the single fastest first step? -
- -
-
-
- - The fastest start: one command, four questions, your own tool - A three-step flow. Run npx metaharness --wizard, answer a few plain questions (name, template, host, description), and you get your own npx your-name command. The wizard also prints the exact command so you can skip the questions next time. - - - - - - - - - - - - - The fastest start - One command, four questions, a working package — in your own name. - - - - - - 1 - Run the wizard - - npx metaharness --wizard - Nothing to set up. - npx fetches it for you. - - - - - - - 2 - Answer 4 questions - - • - a name - • - a template - • - where it will run (host) - • - a one-line description - - - - - - - 3 - You get your tool - - npx <your-name> - Your brand, your skills, - your own command. - - - - - - - - - Bonus: skip the questions next time - The wizard prints the exact npx metaharness … command it just ran — paste it to repeat in one line. - -
The fastest start: one command (npx metaharness --wizard), four questions (name, template, host, one-line description), and a working package — with the exact non-interactive command printed so you can skip the questions next time.
-
- - -

- Prefer the terminal? If you’re not sure what to - pick, run the wizard. It asks just four things — - a name, a template, where it will run, and a one-line description — - and then prints the exact npx metaharness … command it would - have run, so you can skip the questions next time: -

-
npx metaharness --wizard
-

- Already know what you want? Jump straight in: -

-
npx metaharness my-bot --template vertical:coding --host claude-code
-cd my-bot && npm install && npx . --help
-

- Want to see what’s on the menu first? npx metaharness - --list shows every template. And once your harness exists, run - harness doctor — a quick health check that confirms - the scaffold is set up correctly before you go further. -

-

- That’s the whole on-ramp: browser Studio or one terminal command, - four questions, a working package. The use cases below show where to take - it next. -

- -
-
- - -
- - 08 - -

Use-case gallery

- Six real situations — the situation → the exact command → what it does → what you get. -
- -
-
-
- Flow: your repo enters analyze-repo (reads file list only, never runs code), out comes a fitted set of agents, skills, and tools as a ready harness or .zip. -
Scenario 1 — repo in, an assistant that actually understands it out (it reads, it never runs).
-
-
- Flow: a repo enters score/genome (read-only), out comes a one-screen report card with fit, build-likelihood, tool safety, cost-per-run, and a ready / needs-work / blocked verdict. -
Scenario 2 — a go / no-go report card before you build, backed by evidence.
-
-
- Flow: pick a vertical template (support, trading, legal), out comes a domain team of purpose-built agents with matching skills and per-host config, locked down by default. -
Scenario 3 — a ready-made domain team from a single template, locked down by default.
-
-
- Flow: a colleague's .zip enters mcp-scan / threat-model / verify (nothing executed), out comes a clean / medium / high verdict, a shareable report, and a confirmed signed receipt. -
Scenario 4 — vet a colleague's harness statically: clean / medium / high, nothing executed.
-
-
- Flow: each request enters the router, which sends it to the cheapest model predicted to clear your quality bar, so you get the same answer quality for a far smaller bill. -
Scenario 5 — route each task to the cheapest model that still clears your quality bar.
-
-
- A simple bar chart on a light cream background: a tall BEFORE bar marked with three dollar signs next to a much shorter AFTER bar marked with a cent sign, each topped by an identical green checkmark to show the quality is the same. -
- Same result, far smaller bill: route each task to the cheapest - model that is still good enough. -
-
-
- Flow (Darwin Mode): the harness changes one of its own settings, tests it safely in a sandbox, and keeps it only if it measurably helped. The model stays frozen; only the wrapper evolves. -
Scenario 6 — Darwin Mode: try a tweak, test it safely, keep only what measurably helps.
-
-

- Every command below is taken straight from the project’s own - docs — nothing here is made up. Pick the one that sounds like you. -

-
- - -
- Scenario 1 -

“I have a repo and want an assistant that actually understands it”

- -
-
The situation
-
You maintain a codebase and want a coding helper tuned to - that project — not a generic chatbot that knows - nothing about your file layout.
-
The exact command
-
-
harness analyze-repo .                    # just look, suggest nothing risky
-harness analyze-repo . --scaffold my-bot  # build the suggested harness
- Or, in the browser: the Studio’s - Repo → Harness tab — paste the GitHub - URL, review the suggestions, click Download .zip. -
-
What it does
-
Reads your file list, your package.json, your - README, and your mix of languages, then recommends a fitting set - of agents, skills, and tools. It never runs your - code; any build or test commands it spots are written - down but switched off (marked - execution: disabled).
-
What you get
-
A ready-to-use harness (or a .zip) with a sensible - starting agent set for your repo — npm install - and you’re running.
-
-
- - -
- Scenario 2 -

“Is this repo even worth building an assistant for — and what will it cost?”

- -
-
The situation
-
Before you commit any time, you want a quick read on whether a - repo is a good candidate, and roughly what each run will cost.
-
The exact command
-
-
npx metaharness score <repo>   # a one-screen report card
-harness genome <repo>          # a fuller pre-build readiness report
-
-
What it does
-
Reads the repo (again, never runs it) and - prints a single screen: how well a harness fits, how likely it is - to build cleanly, how safe the tools look, and the rough cost per - run. genome adds a plain verdict — - ready, needs-work, or blocked.
-
What you get
-
A clear go / no-go decision, backed by evidence, - before you build anything — plus a suggested plan.
-
-
- - -
- Scenario 3 -

“Give me a ready-made team for my industry — support, trading, legal…”

- -
-
The situation
-
You want a pre-built set of agents for a known area and - you’d rather not memorise any options.
-
The exact command
-
-
npx metaharness --list                       # browse every template
-npx metaharness my-bot --template vertical:support
-npx @metaharness/support my-bot              # same thing, zero options to remember
-
-
What it does
-
Builds a harness pre-loaded with that area’s purpose-built - agents (with their instructions written in), plus the matching - skills, commands, and per-place settings — all locked down - by default. The shortcut wrapper produces a byte-for-byte - identical result to the longer command.
-
What you get
-
A working domain team — for example a customer-support - pod, a quant-trading setup that is paper-only until you say - otherwise, or a contract reviewer that only ever drafts, never - sends.
-
-
- - -
- Scenario 4 -

“A colleague sent me a harness — is it safe to run?”

- -
-
The situation
-
Someone hands you a generated .zip and you want to - vet it before installing anything.
-
The exact command
-
The Studio’s Verify tab (checks without - unzipping or running a thing), or from the terminal: -
harness mcp-scan <path>      # like "npm audit" but for agent tools
-harness threat-model <path>  # a shareable review write-up
-harness verify               # confirm the signed receipt is intact
-
-
What it does
-
Statically inspects the harness for risky permissions - (internet, shell, file-writing), missing timeouts, wildcard - rules, exposed secrets, and unpinned dependencies. - mcp-scan stops with an error on any high-severity - finding. verify confirms nobody has tampered with the - signed receipt. Nothing is executed.
-
What you get
-
A clean / medium / high verdict and a shareable report — - in plain terms, “no riskier than any other npm package you - would install” if it passes.
-
-
- - -
- Scenario 5 -

“Cut my model bill without losing quality”

- -
-
The situation
-
You’re paying top-tier prices for work a cheaper model - could handle just as well.
-
The exact command
-
-
npm i @metaharness/router
-# then in your code:
-# route(query) -> the cheapest model predicted to clear your quality bar
-
-
What it does
-
The router sends each request to the cheapest model it expects - to still meet the standard you set — a standard it learns - from your own results. It works out of the box, and you can train - it on your own data for an even better fit.
-
What you get
-
The same quality of answer for less money. The project’s - own benchmark reports a small, cheap model delivering - top-tier-quality research at roughly one-tenth the cost. - Honest caveat: the underlying timing signal is described - as “a diagnostic signal, not a proven early warning — - test it on your own workload before relying on it.”
-
- -
- - -
- Scenario 6 -

“Let the harness quietly improve itself (Darwin Mode)”

- -
-
The situation
-
You want your harness to tune its own settings over time - — without anyone touching the AI model.
-
The exact command
-
-
npm run evolve     # built into every harness; add --no-darwin to switch it off
-
-
What it does
-
It changes one of its own settings, tests that change safely in - a sandbox, and keeps it only if it measurably made - things better. The model stays frozen; only the wrapper evolves. - Safe by default — no internet, no API key, - just careful tuning behind a safety gate.
-
What you get
-
A harness that gets a little better on its own, measured against - a real goal (the project validates this on actual bug-fixing - tasks). Treat it as experimental — you can always opt out - with --no-darwin. (Pictured up in section 05.)
-
-
- -
-
-
- - -
- - 09 - -

Drop-in

- The AI half — one download, drop it into your agent. -
- -
-
-
- - The drop-in: one zip, two halves, three steps to wire it in - One download splits into two halves. The For-you half is a written primer plus a studio folder containing a NotebookLM audio overview (play this first) and a deep-dive report. The For-your-AI half is a searchable knowledge pack (an .rvf file plus a small MCP server). Wiring the AI half into Claude Code is three steps: unzip the kb folder, add a .mcp.json pointing at it, and paste a verification gate into CLAUDE.md so your AI answers from the real source instead of guessing. - - - - - - - - - - - - - - - - The drop-in — one zip, two halves - One download. Half is for you to read; half is for your AI to search. - - - - - one .zip - metaharness-dropin - - - - - - - - - - For you - A primer — plus a studio/ folder to listen & read. - - - - 🎧 audio overview - - 📄 report - - - - - - For your AI - A searchable knowledge pack. - - - kb / .rvf - - MCP server - - - - - wire this half into Claude Code - - - Three steps to wire it in - - - - - - 1 - Unzip the pack - - unzip … → cd kb/ → npm i - Put the kb/ folder by your project. - - - - - - - 2 - Add .mcp.json - - "metaharness-kb": … - Registers the pack as a tool. - - - - - - - 3 - Paste the gate - - into CLAUDE.md - Forces a check before answering. - - - - - - - - - Result: your AI answers from the real source — grounded, with citations — instead of guessing. - -
The drop-in, step by step: one zip splits into for-humans/ (the primer you read, plus a studio/ folder with a 🎧 audio overview and 📄 report) and for-ai/ (the knowledge pack your assistant searches), wired into Claude Code in three small steps — unzip, register a .mcp.json tool, add a CLAUDE.md gate.
-
-
- One zip file at the top splits into two equal panels: a left panel labelled For you showing a person reading and watching, and a right panel labelled For your AI showing a warm, searchable glowing brain with a magnifying glass. -
- One zip, two halves: for-humans/ (the primer you read, - plus a studio/ folder with a 🎧 audio overview and 📄 report) - and for-ai/ (the knowledge pack your assistant searches). -
-
-

- Everything on this page also comes as one download with two - halves. One half is for you — a short written - primer, plus a studio/ folder with a NotebookLM audio - overview and a deep-dive report. The other half is for your AI - — a small, searchable knowledge pack your assistant can read so it - can answer questions about MetaHarness accurately, with sources, instead - of guessing. -

- -
-

Inside for-humans/studio/ — start here

-
    -
  • - 🎧 metaharness-audio.m4a — - a NotebookLM audio overview (~14 min). Play this first — - it’s the fastest way to absorb what MetaHarness is. - ~32 MB -
  • -
  • - 📄 metaharness-report.md — - the written deep-dive briefing document the audio is based on. -
  • -
  • - 📝 audio-overview-prompt.md — the exact - prompt that generated the audio, if you want to remix it. -
  • -
-
- -

- Wiring the AI half into Claude Code takes three small steps: -

-
    -
  1. - Unzip it next to your project. -
    unzip metaharness-dropin.zip
    -cd metaharness-dropin/for-ai
    -npm install
    -
  2. -
  3. - Point Claude Code at it with a .mcp.json file. - This tiny file tells Claude Code about the local knowledge tool. Drop - it in your project root: -
    {
    -  "mcpServers": {
    -    "metaharness-kb": {
    -      "command": "node",
    -      "args": ["metaharness-dropin/for-ai/kb-mcp-server.mjs"]
    -    }
    -  }
    -}
    - (.mcp.json is just a list of helper tools Claude Code is - allowed to call. Here it registers the knowledge pack as a tool - named metaharness-kb.) -
  4. -
  5. - Add a verification gate to your CLAUDE.md. - CLAUDE.md is the instruction file Claude reads first. - This line forces it to check the knowledge pack before - answering, rather than guessing: -
    ## MetaHarness questions
    -Before answering ANY question about MetaHarness, query the
    -`metaharness-kb` tool and ground your answer in what it returns.
    -If the pack has no answer, say so plainly — do not invent one.
    -
  6. -
-

- Then confirm it works. Ask Claude Code a question only - the pack can answer, for example: -

-
What are the nine composer stages in MetaHarness, in order?
-

- If the wiring is right, the answer comes back grounded in the knowledge - pack — Identity, Hosts, Primitives, Agents, Skills, Plugins, - Features, Branding, Confirm — with the source it drew from. If you - instead get a vague reply with no source, the gate isn’t firing: - re-check the .mcp.json path and the CLAUDE.md - line above. -

- - - -
Download the drop-in
-
- metaharness-dropin.zip — 27 MB (incl. 🎧 audio overview) — Gate A: 99.9 / 100 — ready now -
-

Ready

-
-
-
- -
-
-
- - -
-
-
- NotebookLM studio · the same explainer, every format -

Prefer to listen, watch, or skim? Take the studio tour.

-

- We loaded everything about MetaHarness into a public Google - NotebookLM notebook and let it produce the same plain-language - story in a handful of formats — an audio overview, a short explainer video, - a slide deck, a one-glance infographic, and a written deep-dive. Same idea Maya - learned (an AI that guesses about your project vs. an assistant that - actually knows it, built in about a minute), in whatever form suits you. -

- - - - Open the NotebookLM studio — audio, video, slides & more - - -
- - -
-

🎧 Audio overview

-

Listen (~14 min)

-

- Two hosts walk through Maya’s before→after in a friendly - back-and-forth. The fastest way to absorb what MetaHarness is. -

- - -
- - -
-

🎥 Explainer video

-

Watch the short

-

- A narrated explainer that draws the problem, the fix, and the one command - to start — built straight from the notebook. -

- - -
- - -
-

📊 Slide deck

-

Skim the deck

-

- A detailed deck you can page through — the whole MetaHarness story, - one slide at a time, ready to present or share. -

- - -
- - -
-

📈 Infographic

-

See it at a glance

-

- One landscape image: the AI knowledge gap, Maya’s story, and the - 60-second fix — the whole idea in a single look. -

- - MetaHarness infographic: 'Give your AI the home-field advantage.' Shows the AI knowledge gap (a generic assistant guesses and makes errors, while MetaHarness builds a project-aware specialist with zero-trust, read-only analysis), Maya's story from the clean-up tax to a 60-second fix to one shared 'npx maya-shop' command for her whole team, and a 'Ready to start? npx metaharness' call to action. - - -
- - -
-

📄 Deep-dive report

-

Read the briefing

-

- The written briefing document the audio is based on — themes, - architecture, host support, and the honest beta caveats. -

- -
- -
- -

- Built with Google NotebookLM from the same source material as this site · - the notebook is public — - open it to chat with the sources directly. -

-
-
-
- - - - - - - diff --git a/ruv-explainer-agent-harness-generator/kb/.last-built.json b/ruv-explainer-agent-harness-generator/kb/.last-built.json deleted file mode 100644 index 7e33bf5..0000000 --- a/ruv-explainer-agent-harness-generator/kb/.last-built.json +++ /dev/null @@ -1 +0,0 @@ -{"builtAt":"2026-06-19","targetRepoSha":"db65fabee6841434fa8ed36b317346a9ada2d429","version":"v0.1.3"} diff --git a/ruv-explainer-agent-harness-generator/main.js b/ruv-explainer-agent-harness-generator/main.js deleted file mode 100644 index 7429336..0000000 --- a/ruv-explainer-agent-harness-generator/main.js +++ /dev/null @@ -1,91 +0,0 @@ -/* ============================================================================= - MetaHarness ExplainerSite — main.js (P2 shell; target < 6 KB) - Progressive enhancement only. The page is fully usable with JS disabled: - the 9 sections are native
/, so they open/close on their - own. This script adds: - 1. deep-link: open the
a #hash points at, and on nav-click. - 2. dropzone stub: click + keyboard (Enter/Space) + drag-and-drop fallback, - all three paths converge on one handler. The real .zip download href - and file handling wire up in P7/P9. - No dependencies. No build step. - ========================================================================== */ -(function () { - "use strict"; - - /* --- 1. Deep-link a section open ---------------------------------------- */ - function openFromHash() { - var id = (location.hash || "").replace(/^#/, ""); - if (!id) return; - var el = document.getElementById(id); - // Walk up to the enclosing
(the hash may target an inner element). - while (el && el.tagName !== "DETAILS") el = el.parentElement; - if (el && !el.open) el.open = true; - } - window.addEventListener("hashchange", openFromHash); - openFromHash(); - - // Clicking an in-page nav link should also expand its target section. - document.querySelectorAll('a[href^="#"]').forEach(function (a) { - a.addEventListener("click", function () { - var id = a.getAttribute("href").slice(1); - var sec = document.getElementById(id); - while (sec && sec.tagName !== "DETAILS") sec = sec.parentElement; - if (sec && !sec.open) sec.open = true; - }); - }); - - /* --- 2. Dropzone stub (click / keyboard / drag) ------------------------- */ - var dz = document.getElementById("dropzone"); - var status = document.getElementById("dzStatus"); - if (!dz) return; - - // P2 stub target. Swapped for the real GitHub Release / downloads/ href in P9. - var DOWNLOAD_HREF = "downloads/metaharness-dropin.zip"; - - function say(msg) { - if (status) status.textContent = msg; - } - - function activate() { - // P2 behaviour: announce intent. In P9 this becomes a real navigation to - // the published .zip. Kept inert here so the shell ships without a binary. - say("Drop-in not bundled yet — wires up in P7/P9 (" + DOWNLOAD_HREF + ")."); - } - - // Click path. - dz.addEventListener("click", activate); - - // Keyboard path (it is role="button" tabindex="0"). - dz.addEventListener("keydown", function (e) { - if (e.key === "Enter" || e.key === " " || e.key === "Spacebar") { - e.preventDefault(); - activate(); - } - }); - - // Drag path. Prevent the browser from navigating away when a folder is dropped. - ["dragenter", "dragover"].forEach(function (evt) { - dz.addEventListener(evt, function (e) { - e.preventDefault(); - e.stopPropagation(); - dz.classList.add("is-dragover"); - }); - }); - ["dragleave", "dragend"].forEach(function (evt) { - dz.addEventListener(evt, function (e) { - e.preventDefault(); - dz.classList.remove("is-dragover"); - }); - }); - dz.addEventListener("drop", function (e) { - e.preventDefault(); - e.stopPropagation(); - dz.classList.remove("is-dragover"); - var n = (e.dataTransfer && e.dataTransfer.items && e.dataTransfer.items.length) || 0; - say( - n - ? "Caught " + n + " item(s). Repo analysis is a P4+ feature — preview only." - : "Nothing detected. Click or press Enter for the drop-in instead." - ); - }); -})(); diff --git a/ruv-explainer-agent-harness-generator/package.json b/ruv-explainer-agent-harness-generator/package.json deleted file mode 100644 index ffceaed..0000000 --- a/ruv-explainer-agent-harness-generator/package.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "ruv-explainer-agent-harness-generator", - "version": "0.1.0", - "private": true, - "description": "Foundry/mint ExplainerSite for MetaHarness (ruvnet/agent-harness-generator). Static, no build, no deps.", - "license": "MIT", - "homepage": "https://ruv-explainer-agent-harness-generator.vercel.app", - "repository": { - "type": "git", - "url": "https://github.com/stuinfla/ruv-explainer-agent-harness-generator" - }, - "keywords": [ - "metaharness", - "agent-harness-generator", - "ruvnet", - "explainer", - "static-site" - ], - "scripts": {} -} diff --git a/ruv-explainer-agent-harness-generator/robots.txt b/ruv-explainer-agent-harness-generator/robots.txt deleted file mode 100644 index 8cc3497..0000000 --- a/ruv-explainer-agent-harness-generator/robots.txt +++ /dev/null @@ -1,4 +0,0 @@ -User-agent: * -Allow: / - -Sitemap: https://ruv-explainer-agent-harness-generator.vercel.app/sitemap.xml diff --git a/ruv-explainer-agent-harness-generator/studio/audio-overview-prompt.md b/ruv-explainer-agent-harness-generator/studio/audio-overview-prompt.md deleted file mode 100644 index 7da28b9..0000000 --- a/ruv-explainer-agent-harness-generator/studio/audio-overview-prompt.md +++ /dev/null @@ -1,25 +0,0 @@ -# MetaHarness Audio Overview — Optimized Prompt - -**Notebook:** MetaHarness — Explainer -**Notebook ID:** 3cc18f99-ef82-457d-bd80-686238d0685a -**Artifact ID:** 17496280-86f0-40f2-a713-5939924ed24a -**Format:** deep_dive | Length: default -**Audience:** Non-technical Claude Code user (comfortable with npm, not a framework author) - -## Focus Prompt Used - -Open with the felt problem: when you ask a generic AI assistant to change your code, it guesses — invents file names, ignores your project rules, sometimes touches things it shouldn't. Define "harness" in one plain sentence: a harness is a lightweight wrapper around the AI that gives it your project's memory, skills, and guardrails. Then walk Maya's before-and-after: before MetaHarness she spends an hour cleaning up wrong guesses every time; after running npx metaharness on her shop's repo she has npx maya-shop — a project-aware assistant that gets it right the first try and that she can share with her whole team. Close with the exact first command to try right now: npx metaharness. Tone: warm, confident, zero undefined jargon. Audience: a non-technical Claude Code user comfortable with npm. - -## Prompt Design Rationale - -1. **Opens with the felt problem** — "it guesses" is the visceral pain point non-technical users recognize immediately; no jargon required. -2. **One-sentence harness definition** — "a wrapper that gives the AI your project's memory, skills, and guardrails" uses only words the audience already knows. -3. **Maya before→after** — concrete character example from the resonance brief; makes the abstract tangible and emotionally grounded. -4. **Ends with exact first command** — `npx metaharness` removes all ambiguity about what to do next. -5. **Tone guidance** — "warm, confident, zero undefined jargon" prevents the hosts from slipping into tech-speak. - -## Source Files - -- content/agent-harness-generator.canon.md (Source ID: 15cab96b-5192-40ac-b59b-cd177b0fbed7) -- content/agent-harness-generator.resonance.md (Source ID: 978badc7-e54a-425f-b62d-1f33a28224a8) -- .targets/agent-harness-generator/README.md (Source ID: f1001fb8-04c4-4aaa-88e8-e08a5711f53d) diff --git a/ruv-explainer-agent-harness-generator/studio/metaharness-audio.m4a b/ruv-explainer-agent-harness-generator/studio/metaharness-audio.m4a deleted file mode 100644 index b6fc6a1..0000000 Binary files a/ruv-explainer-agent-harness-generator/studio/metaharness-audio.m4a and /dev/null differ diff --git a/ruv-explainer-agent-harness-generator/studio/metaharness-infographic.png b/ruv-explainer-agent-harness-generator/studio/metaharness-infographic.png deleted file mode 100644 index 79936e0..0000000 Binary files a/ruv-explainer-agent-harness-generator/studio/metaharness-infographic.png and /dev/null differ diff --git a/ruv-explainer-agent-harness-generator/studio/metaharness-report.md b/ruv-explainer-agent-harness-generator/studio/metaharness-report.md deleted file mode 100644 index 3acf5c9..0000000 --- a/ruv-explainer-agent-harness-generator/studio/metaharness-report.md +++ /dev/null @@ -1,100 +0,0 @@ -# MetaHarness: Project Analysis and Briefing Document - -## Executive Summary - -MetaHarness is a local-first, client-side factory for AI agent frameworks. Rather than acting as another standalone agent, it generates custom, branded, and npm-publishable "harnesses" from any GitHub repository or blank slate. A harness functions as a specialized wrapper around existing Large Language Models (LLMs) like Claude or GPT, providing them with repo-aware skills, scoped memory, and governance policies. - -The tool aims to solve three primary problems: model and framework lock-in, host fragmentation across various AI platforms, and the constant reinvention of agentic infrastructure. By automating the creation of MCP servers, memory namespaces, and release gates, MetaHarness allows developers to ship repo-tuned agents as versioned dependencies (via `npx`) in under 60 seconds. - -Currently in **v0.1.x beta**, MetaHarness features a Rust-based kernel, supports nine host integrations, and includes "Darwin Mode" for self-evolving configurations. - ---- - -## Key Themes Analysis - -### 1. The "Harness" vs. The Framework -A central tenet of the project is that the model is replaceable while the harness is the product. Most frameworks require developers to build agents; MetaHarness helps repositories ship their own agents. -* **Definition:** A harness is not the AI "brain" but the infrastructure around it—identity, branding, skills, memory, and safety nets. -* **Function:** It turns a generalist AI into a specialist that "knows" a specific project’s file layout, billing rules, and safety constraints. - -### 2. Economic Optimization and Model Routing -MetaHarness emphasizes cost-efficiency through its "Router" and the DRACO benchmark. -* **The Router:** Using `@metaharness/router`, the system routes queries to the cheapest model predicted to meet the required quality bar based on local evaluation logs. -* **DRACO Benchmark:** This internal benchmark demonstrates that a well-harnessed small model can deliver frontier-quality research at approximately **one-tenth the cost** of larger models. - -### 3. Security and "Default-Deny" Governance -The architecture prioritizes security through a strict "default-deny" policy for all generated tools. -* **MCP Safeguards:** Generated MCP servers ship with no network, shell, or file-write access by default. Dangerous actions require explicit approval. -* **Provenance:** Every release is signed with an **Ed25519 witness manifest**, allowing users to verify that a harness has not been tampered with before execution. -* **Static Analysis:** The `metaharness score` and `genome` commands perform deterministic static analysis, meaning they read repository metadata without ever executing the code. - -### 4. Self-Evolution (Darwin Mode) -Newer scaffolds include "Darwin Mode," an experimental feature where the harness improves its own configuration. -* **Mechanism:** The harness mutates its config, tests changes in a sandbox, and retains only those that measurably improve performance against a fitness function. -* **Safety:** This process happens while the underlying model remains frozen, ensuring the "evolution" is limited to the harness's logic and tuning. - ---- - -## Technical Infrastructure and Host Support - -MetaHarness supports nine distinct host environments, allowing a single generated harness to run across multiple platforms. - -| Host | Integration Method | Stability Status | -| :--- | :--- | :--- | -| **Claude Code** | MCP server + hooks + 3-scope settings | Stable | -| **OpenAI Codex** | MCP via config.toml | Stable | -| **pi.dev** | Pi extension via registerTool() | Stable | -| **Hermes** | MCP runtime + thinking scrubbing | Stable | -| **OpenClaw** | workspace skills | Stable | -| **RVM** | Bare-metal microhypervisor | Stable | -| **GitHub Copilot** | MCP via .vscode/mcp.json | New (ADR-032) | -| **OpenCode** | MCP via .opencode/opencode.json | New (ADR-036) | -| **GitHub Actions** | Composite action.yml | New (ADR-033) | - ---- - -## Important Quotes with Context - -> **"It is not another agent framework. It is a factory for agent frameworks. The model is replaceable. The harness is the product."** -* **Context:** This quote defines the project's market position. It emphasizes that MetaHarness provides the "plumbing" (the harness) and treats the AI model as a modular component. - -> **"Every serious repo deserves its own agent."** -* **Context:** The founding philosophy of MetaHarness is that repo-aware CLIs and agents should be standard for any project, providing project-specific memory and governance. - -> **"Default-deny is a feature with a cost."** -* **Context:** Found in the user limits section, this warns developers that while the security is high, they must explicitly spend time allowing specific tools/permissions because the system starts with zero access. - -> **"Stop paying frontier prices for work a $0.10 model does just as well."** -* **Context:** Used to promote the `@metaharness/router`, highlighting the project's focus on breaking the reliance on expensive models for routine tasks. - ---- - -## Use-Case Scenarios - -| Situation | Actionable Command | Outcome | -| :--- | :--- | :--- | -| **Pre-Analysis** | `npx metaharness score ` | A report card on fit, cost per run, and tool safety. | -| **Standard Scaffolding** | `npx metaharness --wizard` | A 4-question interactive setup for a new harness. | -| **Vertical Deployment** | `npx @metaharness/devops my-bot` | A ready-made incident response pod for DevOps. | -| **Integrity Check** | `harness verify` | Confirmation that the witness signature is untampered. | -| **Cost Savings** | `npm i @metaharness/router` | Automated routing to the cheapest capable model. | -| **Ejection** | `harness eject` | Lifting custom agents from a `ruflo` install into a new branded harness. | - ---- - -## Actionable Insights - -1. **Perform "Genome" Scoring Before Scaffolding:** Use `harness genome ` to determine if a repository is ready for an agent. This avoids building harnesses for "needs-work" or "blocked" repositories. -2. **Standardize Team AI with npm:** Organizations should publish their harnesses as private npm packages. This ensures every team member runs the same `npx @org/harness` command, providing a consistent, repo-tuned experience across the organization. -3. **Utilize Darwin Mode for Continuous Tuning:** For complex engineering tasks, enable Darwin Mode to allow the harness to self-refactor its configurations based on real-world bug-fixing performance (validated on SWE-bench Lite). -4. **Enforce Security via MCP-Scan:** Integrate `harness mcp-scan` into CI/CD pipelines. This acts as an "npm audit" for agent tools, flagging shell/network grants and unpinned dependencies before they reach production. -5. **Leverage the Router for High-Volume Tasks:** For projects requiring deep research or high-volume processing, implement the `@metaharness/router` to achieve "frontier-quality" results at one-tenth the cost. - ---- - -## Documented Limits and Constraints - -* **Beta Status:** The project is in v0.1.x beta. Documentation and credibility reconciliation (Issue #4) are ongoing. -* **Documentation Lag:** There are inconsistencies between the code (which supports 9 hosts) and the documentation (which often cites 4 or 6). Similarly, test counts vary between 568 and 605 across different files. -* **Static-Only Analysis:** Analysis is intentionally shallow and read-only. It does not execute code; the output is a "strong starting point" that requires manual prompt and tool tuning. -* **Local-First Architecture:** There is no hosted backend or telemetry. The Studio is 100% client-side (GitHub Pages), and the CLI runs entirely locally. \ No newline at end of file diff --git a/ruv-explainer-agent-harness-generator/styles.css b/ruv-explainer-agent-harness-generator/styles.css deleted file mode 100644 index b7599d5..0000000 --- a/ruv-explainer-agent-harness-generator/styles.css +++ /dev/null @@ -1,702 +0,0 @@ -/* ============================================================================= - MetaHarness ExplainerSite — FOUNDRY / MINT - Aesthetic lock [Constraint K]: deep WARM-charcoal (never blue-black), molten - amber/copper accents, industrial-refined display type (Big Shoulders Display) - over IBM Plex Sans/Mono, generous space, tactile pressed-metal depth. - ZERO CYAN — deliberately NOT the cognitum cool-cyan/phosphor reference. - P2 SHELL: tokens + structure + motion only; section copy is placeholder. - ========================================================================== */ - -/* ---- Self-hosted fonts (zero CDN). woff2 files land in assets/fonts/ ------ */ -@font-face { - font-family: "Big Shoulders Display"; - src: url("assets/fonts/BigShouldersDisplay-SemiBold.woff2") format("woff2"); - font-weight: 600; font-style: normal; font-display: swap; -} -@font-face { - font-family: "Big Shoulders Display"; - src: url("assets/fonts/BigShouldersDisplay-Black.woff2") format("woff2"); - font-weight: 900; font-style: normal; font-display: swap; -} -@font-face { - font-family: "IBM Plex Sans"; - src: url("assets/fonts/IBMPlexSans-Regular.woff2") format("woff2"); - font-weight: 400; font-style: normal; font-display: swap; -} -@font-face { - font-family: "IBM Plex Sans"; - src: url("assets/fonts/IBMPlexSans-Medium.woff2") format("woff2"); - font-weight: 500; font-style: normal; font-display: swap; -} -@font-face { - font-family: "IBM Plex Mono"; - src: url("assets/fonts/IBMPlexMono-Regular.woff2") format("woff2"); - font-weight: 400; font-style: normal; font-display: swap; -} - -/* ---- :root FOUNDRY DESIGN TOKENS [P2.1] ------------------------------------- - Hues are warm (yellow/orange bias). No blue, no cyan, no green anywhere. */ -:root { - /* Warm-charcoal substrate — graphite with an iron-warm cast, not navy */ - --bg: #16120e; /* deepest — page floor */ - --bg-2: #1d1812; /* raised plane */ - --panel: #241d15; /* card body */ - --panel-2: #2c2418; /* card header / inset */ - --ridge: #3a2f1f; /* hairline edges, embossed seams */ - - /* Molten metal accents — amber poured into copper */ - --amber: #ff9e2c; /* primary molten amber */ - --amber-hot: #ffb650; /* highlight / hover lift */ - --copper: #c2703a; /* secondary copper */ - --copper-deep: #8a4a26; /* shadow side of copper */ - --ember: #e8531f; /* hottest stamp / danger-warm */ - --brass: #d9a441; /* tertiary brass for micro-labels */ - - /* Ink — warm off-white, never blue-white */ - --ink: #f3e8d8; /* primary text on dark */ - --ink-2: #d6c5ac; /* secondary text */ - --muted: #9c8b72; /* captions, meta */ - --faint: #6b5e49; /* hairline labels */ - --on-amber: #1a1206; /* text that sits ON molten fills */ - - /* Lines / fills derived from the warm accents */ - --line: rgba(217,164,65,0.14); - --line-strong: rgba(217,164,65,0.30); - --fill-amber: rgba(255,158,44,0.10); - --fill-copper: rgba(194,112,58,0.12); - - /* Tactile depth — pressed-metal shadows + cast glow */ - --shadow: 0 22px 48px -26px rgba(0,0,0,0.82); - --shadow-deep: 0 38px 90px -40px rgba(0,0,0,0.9); - --emboss: inset 0 1px 0 rgba(255,196,120,0.07), - inset 0 -1px 0 rgba(0,0,0,0.45); - --glow-amber: 0 0 0 1px rgba(255,158,44,0.25), - 0 14px 40px -16px rgba(255,158,44,0.32); - - /* Type */ - --display: "Big Shoulders Display", "Arial Narrow", system-ui, sans-serif; - --sans: "IBM Plex Sans", system-ui, -apple-system, sans-serif; - --mono: "IBM Plex Mono", ui-monospace, "SF Mono", Menlo, monospace; - - /* Rhythm */ - --maxw: 1120px; - --gutter: clamp(20px, 5vw, 56px); - --radius: 14px; - --radius-s: 9px; - --ease: cubic-bezier(0.22, 0.61, 0.36, 1); -} - -/* ---- Reset / base --------------------------------------------------------- */ -*, *::before, *::after { box-sizing: border-box; } -html { -webkit-text-size-adjust: 100%; scroll-behavior: smooth; } - -body { - margin: 0; - background: var(--bg); - color: var(--ink); - font-family: var(--sans); - font-size: 16.5px; - line-height: 1.65; - -webkit-font-smoothing: antialiased; - text-rendering: optimizeLegibility; - /* Cast-iron grain: layered warm radials + a faint poured-metal sheen. - No blue/cyan in any stop. */ - background-image: - radial-gradient(1100px 620px at 78% -8%, rgba(255,158,44,0.10), transparent 60%), - radial-gradient(900px 700px at -10% 8%, rgba(194,112,58,0.08), transparent 55%), - linear-gradient(180deg, var(--bg) 0%, var(--bg-2) 100%); - background-attachment: fixed; -} - -img { max-width: 100%; height: auto; display: block; } - -a { - color: var(--amber); - text-decoration: none; - transition: color 0.18s var(--ease); -} -a:hover { color: var(--amber-hot); } -a:focus-visible, -summary:focus-visible, -button:focus-visible, -[tabindex]:focus-visible { - outline: 2px solid var(--amber); - outline-offset: 3px; - border-radius: 4px; -} - -/* ---- Layout --------------------------------------------------------------- */ -.wrap { width: 100%; max-width: var(--maxw); margin: 0 auto; padding: 0 var(--gutter); } - -/* ---- Type system ---------------------------------------------------------- */ -h1, h2, h3, h4 { - font-family: var(--display); - font-weight: 900; - line-height: 0.98; - letter-spacing: 0.005em; - margin: 0 0 0.5em; - text-transform: uppercase; -} -h1 { font-size: clamp(2.8rem, 8vw, 5.6rem); } -h2 { font-size: clamp(1.9rem, 4.4vw, 3rem); } -h3 { font-size: 1.5rem; font-weight: 600; letter-spacing: 0.01em; } -p { margin: 0 0 1rem; max-width: 68ch; color: var(--ink-2); } - -.eyebrow { - font-family: var(--mono); - font-size: 12px; - letter-spacing: 0.36em; - text-transform: uppercase; - color: var(--brass); - font-weight: 400; - margin: 0 0 14px; -} -.mono { font-family: var(--mono); } -.lede { font-size: 1.18rem; color: var(--ink); max-width: 64ch; } -.attrib-lede { - font-size: 0.95rem; line-height: 1.55; color: var(--ink-2); max-width: 64ch; - margin: 0 0 1rem; padding: 11px 16px; border-left: 3px solid var(--brass); - border-radius: 0 8px 8px 0; background: var(--fill-amber); -} -.attrib-lede strong { color: var(--ink); font-weight: 600; } -.attrib-lede a { color: var(--brass); } -.attrib-lede a:hover { color: var(--amber-hot); } -.placeholder { - color: var(--muted); - font-style: italic; - border-left: 2px solid var(--copper-deep); - padding-left: 14px; -} - -/* Lists — comfortable rhythm, warm markers */ -ol, ul { margin: 0 0 1rem; padding-left: 1.4em; max-width: 68ch; color: var(--ink-2); } -li { margin: 0 0 0.55em; } -li::marker { color: var(--copper); } -li strong { color: var(--ink); } - -/* Multi-line command block — a cast-metal plate of commands */ -pre.code-block { - font-family: var(--mono); - font-size: 0.85rem; - line-height: 1.6; - color: var(--amber-hot); - background: var(--bg); - border: 1px solid var(--line-strong); - border-left: 3px solid var(--copper); - border-radius: var(--radius-s); - padding: 16px 18px; - margin: 0 0 1rem; - overflow-x: auto; - box-shadow: var(--emboss); - max-width: 68ch; -} -pre.code-block code { - background: none; border: none; box-shadow: none; padding: 0; - font-size: inherit; color: inherit; white-space: pre; -} - -/* Small honest-note paragraphs at the foot of a section */ -.footnote-note { - margin-top: 18px; - padding: 12px 16px; - border: 1px dashed var(--copper-deep); - border-radius: var(--radius-s); - background: var(--fill-copper); - color: var(--muted); - max-width: 70ch; -} -.footnote-note small { color: var(--muted); line-height: 1.55; } - -/* ---- Studio callout (the 🎧 audio + 📄 report inside the zip) ------------- */ -.studio-note { - margin: 20px 0; padding: 16px 18px; - border: 2px solid var(--amber); - border-radius: var(--radius); - background: linear-gradient(135deg, var(--fill-amber) 0%, var(--panel) 100%); - box-shadow: var(--glow-amber); - max-width: 70ch; -} -.studio-note .studio-lead { - margin: 0 0 8px; font-family: var(--display); - font-weight: 700; font-size: 1.05rem; color: var(--amber-hot); - letter-spacing: 0.01em; -} -.studio-note ul { margin: 0; padding-left: 0; list-style: none; max-width: none; } -.studio-note li { margin: 6px 0; color: var(--ink-2); line-height: 1.5; } -.studio-note li code { color: var(--amber-hot); } -.studio-note .studio-tag { - font-family: var(--mono); font-size: 11px; color: var(--brass); - letter-spacing: 0.04em; -} - -/* Browser Studio on-ramp block — §07 "recommended for beginners" callout */ -.browser-onramp { - margin: 28px 0 32px; - padding: 20px 24px; - border: 2px solid var(--amber); - border-radius: var(--radius); - background: linear-gradient(135deg, var(--fill-amber) 0%, var(--panel) 100%); - box-shadow: var(--glow-amber), var(--emboss); -} -.browser-onramp-label { - display: inline-block; - margin-bottom: 10px; - padding: 3px 12px; - background: linear-gradient(96deg, var(--amber-hot), var(--copper)); - color: var(--on-amber); - font-family: var(--display); - font-weight: 600; - font-size: 0.8rem; - letter-spacing: 0.06em; - text-transform: uppercase; - border-radius: 20px; -} -.browser-onramp-intro { - margin: 0 0 16px; - color: var(--text-2); - line-height: 1.55; -} -.browser-onramp-cta { - display: flex; - flex-direction: column; - gap: 5px; - padding: 14px 22px; - background: linear-gradient(96deg, var(--amber-hot), var(--copper)); - color: var(--on-amber); - font-family: var(--display); - font-weight: 600; - font-size: 1.05rem; - letter-spacing: 0.02em; - text-transform: uppercase; - border-radius: 10px; - box-shadow: var(--glow-amber), var(--emboss); - transition: transform 0.16s var(--ease), filter 0.16s var(--ease); - width: fit-content; - max-width: 100%; -} -.browser-onramp-cta:hover { - transform: translateY(-2px); - filter: brightness(1.07); - color: var(--on-amber); -} -.browser-onramp-url { - font-family: var(--mono); - font-size: 0.78rem; - font-weight: 400; - letter-spacing: 0; - text-transform: none; - opacity: 0.85; -} -.browser-onramp-note { - margin: 14px 0 0; - color: var(--muted); - font-size: 0.9rem; - line-height: 1.55; -} - -/* Inline command chip — looks struck into metal */ -code, .cmd { - font-family: var(--mono); - font-size: 0.86em; - color: var(--amber-hot); - background: var(--fill-amber); - border: 1px solid var(--line-strong); - border-radius: 6px; - padding: 0.12em 0.45em; - box-shadow: var(--emboss); -} - -/* ---- Provenance / attribution banner (Cognitum-style) --------------------- */ -.prov-banner { - border-bottom: 1px solid var(--line); - background: - linear-gradient(180deg, rgba(44,36,24,0.55), rgba(29,24,18,0.45)); - backdrop-filter: blur(6px); - -webkit-backdrop-filter: blur(6px); -} -.prov-banner-inner { - display: flex; flex-wrap: wrap; align-items: center; - justify-content: space-between; gap: 10px 26px; - padding-top: 9px; padding-bottom: 9px; -} -.prov-attr { - margin: 0; max-width: none; - font-family: var(--sans); font-size: 12.5px; line-height: 1.5; - color: var(--muted); letter-spacing: 0.01em; -} -.prov-attr strong { color: var(--ink-2); font-weight: 500; } -.prov-attr a { color: var(--brass); } -.prov-attr a:hover { color: var(--amber-hot); } -.prov-live { - margin: 0; flex: 0 0 auto; - font-family: var(--mono); font-size: 11.5px; letter-spacing: 0.05em; - color: var(--faint); white-space: nowrap; - display: inline-flex; align-items: center; gap: 8px; -} -.prov-live code { - font-size: 0.95em; color: var(--brass); - background: var(--fill-amber); padding: 0.08em 0.4em; -} -.prov-dot { - color: var(--amber); font-size: 9px; - filter: drop-shadow(0 0 4px rgba(255,158,44,0.8)); - animation: prov-pulse 2.6s var(--ease) infinite; -} -@keyframes prov-pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.35; } -} - -/* ---- Header / nav --------------------------------------------------------- */ -.site-head { - position: sticky; top: 0; z-index: 40; - background: rgba(22,18,14,0.78); - backdrop-filter: blur(11px); - -webkit-backdrop-filter: blur(11px); - border-bottom: 1px solid var(--line); -} -.site-head .wrap { - display: flex; align-items: center; justify-content: space-between; - height: 64px; -} -.brand { - display: inline-flex; align-items: center; gap: 12px; - font-family: var(--display); font-weight: 900; font-size: 1.25rem; - letter-spacing: 0.04em; text-transform: uppercase; color: var(--ink); -} -.brand .coin { - width: 30px; height: 30px; border-radius: 50%; - display: grid; place-items: center; - font-family: var(--display); font-weight: 900; font-size: 13px; - color: var(--on-amber); - background: radial-gradient(circle at 34% 28%, var(--amber-hot), var(--copper) 78%, var(--copper-deep)); - box-shadow: var(--glow-amber), var(--emboss); -} -.nav-links { display: flex; gap: 4px; } -.nav-links a { - font-family: var(--mono); font-size: 12px; letter-spacing: 0.05em; - color: var(--muted); padding: 7px 11px; border-radius: 7px; - transition: color 0.18s var(--ease), background 0.18s var(--ease); -} -.nav-links a:hover { color: var(--ink); background: var(--fill-amber); } - -/* ---- Hero ----------------------------------------------------------------- */ -.hero { padding: clamp(64px, 12vw, 132px) 0 clamp(48px, 8vw, 88px); } -.hero h1 { color: var(--ink); } -.hero h1 .molten { - background: linear-gradient(96deg, var(--amber-hot), var(--copper) 60%, var(--ember)); - -webkit-background-clip: text; background-clip: text; color: transparent; -} -.hero .lede { margin-top: 20px; } -.hero .meta-row { - display: flex; gap: 26px; flex-wrap: wrap; margin-top: 34px; - font-family: var(--mono); font-size: 12px; color: var(--faint); - letter-spacing: 0.05em; -} -.hero .meta-row b { color: var(--brass); font-weight: 400; } -.cta { - display: inline-flex; align-items: center; gap: 10px; margin-top: 34px; - font-family: var(--display); font-weight: 600; font-size: 1.05rem; - letter-spacing: 0.03em; text-transform: uppercase; - color: var(--on-amber); - background: linear-gradient(96deg, var(--amber-hot), var(--copper)); - padding: 13px 26px; border-radius: 10px; - box-shadow: var(--glow-amber), var(--emboss); - transition: transform 0.16s var(--ease), filter 0.16s var(--ease); -} -.cta:hover { transform: translateY(-2px); filter: brightness(1.06); color: var(--on-amber); } - -/* Hero two-column layout: copy left, visual right */ -.hero-inner { - display: flex; - align-items: center; - gap: clamp(32px, 5vw, 72px); - flex-wrap: wrap; -} -.hero-copy { - flex: 1 1 320px; - min-width: 0; -} -.hero-visual { - flex: 0 1 480px; - min-width: 0; -} -.hero-figure { - margin: 0; - border: 1px solid var(--ridge); - border-radius: var(--radius); - background: var(--panel-2); - padding: 10px; - box-shadow: - var(--shadow), - 0 0 0 1px rgba(255,158,44,0.10), - 0 20px 60px -20px rgba(255,158,44,0.18); - overflow: hidden; -} -.hero-figure img { - display: block; - width: 100%; - height: auto; - border-radius: calc(var(--radius) - 4px); -} -/* On narrow viewports, visual drops below copy and goes full-width */ -@media (max-width: 700px) { - .hero-inner { flex-direction: column; } - .hero-visual { flex-basis: auto; width: 100%; } -} - -/* ---- Sections (native
) ----------------------------------------- */ -.sections { padding: clamp(32px, 6vw, 64px) 0 clamp(64px, 10vw, 110px); } - -.section { - background: - linear-gradient(180deg, var(--panel) 0%, var(--bg-2) 100%); - border: 1px solid var(--ridge); - border-radius: var(--radius); - box-shadow: var(--shadow), var(--emboss); - margin: 0 0 18px; - overflow: hidden; -} -.section[open] { box-shadow: var(--shadow-deep), var(--emboss); } - -/* The clickable bar — a stamped foundry plate */ -.section > summary { - list-style: none; cursor: pointer; - display: flex; align-items: baseline; gap: 18px; - padding: 26px clamp(20px, 4vw, 34px); - user-select: none; - transition: background 0.2s var(--ease); -} -.section > summary::-webkit-details-marker { display: none; } -.section > summary:hover { background: var(--fill-amber); } - -.section .num { - font-family: var(--mono); font-size: 13px; letter-spacing: 0.22em; - color: var(--copper); flex: 0 0 auto; padding-top: 6px; -} -.section .head-text { flex: 1 1 auto; } -.section .head-text h2 { - margin: 0; color: var(--ink); - font-size: clamp(1.4rem, 3.2vw, 2.05rem); -} -.section .head-text .q { - display: block; font-family: var(--mono); font-size: 12px; - letter-spacing: 0.06em; color: var(--muted); margin-top: 6px; - text-transform: none; -} -/* Chevron that rotates on open */ -.section .chev { - flex: 0 0 auto; width: 26px; height: 26px; align-self: center; - border-radius: 50%; display: grid; place-items: center; - border: 1px solid var(--line-strong); color: var(--amber); - font-size: 13px; line-height: 1; - transition: transform 0.25s var(--ease), background 0.2s var(--ease); -} -.section[open] .chev { transform: rotate(90deg); background: var(--fill-amber); } - -.section .body { - padding: 4px clamp(20px, 4vw, 34px) 32px; - border-top: 1px solid var(--line); - margin-top: 2px; -} -.section .body > *:first-child { margin-top: 18px; } - -/* Figure slot — where G1-G6 land in P5 */ -.figure { - margin: 24px 0; border: 1px solid var(--ridge); border-radius: var(--radius-s); - background: var(--panel-2); padding: 18px; box-shadow: var(--emboss); -} -.figure .slot { - aspect-ratio: 16 / 9; border-radius: 6px; - border: 1px dashed var(--copper-deep); - background: - repeating-linear-gradient(45deg, rgba(217,164,65,0.05) 0 12px, transparent 12px 24px); - display: grid; place-items: center; - color: var(--faint); font-family: var(--mono); font-size: 12px; - letter-spacing: 0.08em; text-align: center; padding: 16px; -} -.figure figcaption { - margin-top: 12px; color: var(--muted); - font-family: var(--mono); font-size: 12px; letter-spacing: 0.03em; -} - -/* Diagram figures: inline SVGs (s01-s07,s09) and SVGs (uc1-uc6). - Force responsive width regardless of any width/height attrs on the SVG root. */ -.figure.diagram { background: var(--bg); } -.figure.diagram > svg, -.figure.diagram > img { - display: block; width: 100%; height: auto; max-width: 100%; - border-radius: 6px; -} -.figure.uc-diagram { margin: 16px 0 4px; padding: 14px; } -.figure.uc-diagram figcaption { margin-top: 10px; } - -/* Use-case + drop-in cards reuse the plate look */ -.grid { - display: grid; gap: 16px; - grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); - margin-top: 18px; -} -.card { - background: var(--panel-2); border: 1px solid var(--ridge); - border-radius: var(--radius-s); padding: 20px; box-shadow: var(--emboss); -} -.card .tag { - font-family: var(--mono); font-size: 11px; letter-spacing: 0.16em; - text-transform: uppercase; color: var(--copper); -} -.card h3 { margin: 8px 0 10px; color: var(--ink); } - -/* Use-case gallery: full scenario cards span the grid for readability */ -.grid.cases { grid-template-columns: 1fr; gap: 18px; } -.case p { max-width: none; } -.case pre.code-block { max-width: none; } -.case dl { margin: 14px 0 0; } -.case dt { - font-family: var(--mono); font-size: 11px; letter-spacing: 0.14em; - text-transform: uppercase; color: var(--brass); margin-top: 14px; -} -.case dt:first-child { margin-top: 0; } -.case dd { margin: 5px 0 0; color: var(--ink-2); } -.case .figure { margin: 18px 0 0; } - -/* ---- Dropzone (the drag-in stub) ----------------------------------------- */ -.dropzone { - margin-top: 22px; border: 2px dashed var(--copper-deep); - border-radius: var(--radius); padding: clamp(28px, 6vw, 52px); - text-align: center; background: var(--fill-copper); - transition: border-color 0.2s var(--ease), background 0.2s var(--ease), - transform 0.2s var(--ease); - cursor: pointer; -} -.dropzone:hover { border-color: var(--copper); background: var(--fill-amber); } -.dropzone.is-dragover { - border-color: var(--amber-hot); background: var(--fill-amber); - transform: scale(1.01); box-shadow: var(--glow-amber); -} -.dropzone .dz-icon { - font-family: var(--display); font-weight: 900; font-size: 2rem; - color: var(--amber); margin-bottom: 8px; -} -.dropzone .dz-hint { - font-family: var(--mono); font-size: 12px; color: var(--muted); - letter-spacing: 0.04em; margin-top: 10px; -} -.dz-status { - margin-top: 14px; font-family: var(--mono); font-size: 12.5px; - color: var(--brass); min-height: 1.2em; -} - -/* ---- NotebookLM Studio (the multi-format companion) ----------------------- */ -.nlm-studio { - margin: 40px 0 8px; - border: 2px solid var(--amber); - border-radius: var(--radius); - background: - radial-gradient(120% 140% at 8% 0%, var(--fill-amber) 0%, transparent 60%), - linear-gradient(180deg, var(--panel-2) 0%, var(--bg-2) 100%); - box-shadow: var(--shadow-deep); - padding: clamp(22px, 4vw, 38px); -} -.nlm-studio .nlm-kicker { - display: inline-block; - font-family: var(--mono); font-size: 12px; letter-spacing: 0.14em; - text-transform: uppercase; color: var(--copper); - margin: 0 0 8px; -} -.nlm-studio h2 { - font-family: var(--display); font-weight: 800; - font-size: clamp(1.5rem, 3.4vw, 2.2rem); line-height: 1.05; - color: var(--ink); margin: 0 0 10px; -} -.nlm-studio .nlm-lead { max-width: 70ch; color: var(--ink-2); } -.nlm-cta { - display: inline-flex; align-items: center; gap: 10px; - margin: 14px 0 8px; padding: 14px 22px; - border-radius: 10px; border: 1px solid var(--amber); - background: linear-gradient(96deg, var(--amber-hot), var(--copper)); - color: #1a120a; font-family: var(--display); font-weight: 800; - font-size: 1.05rem; letter-spacing: 0.01em; text-decoration: none; - box-shadow: var(--glow-amber); - transition: transform 0.15s var(--ease), filter 0.15s var(--ease); -} -.nlm-cta:hover { transform: translateY(-1px); filter: brightness(1.06); color: #160f08; } -.nlm-cta .nlm-cta-play { font-size: 1.2rem; } -.nlm-grid { - display: grid; gap: 14px; margin-top: 24px; - grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); -} -.nlm-card { - border: 1px solid var(--line-strong); border-radius: 12px; - background: linear-gradient(135deg, var(--fill-amber) 0%, var(--panel) 100%); - padding: 16px 18px 18px; display: flex; flex-direction: column; -} -.nlm-card .nlm-card-tag { - font-family: var(--mono); font-size: 11px; letter-spacing: 0.12em; - text-transform: uppercase; color: var(--amber-hot); margin: 0 0 6px; -} -.nlm-card h3 { - font-family: var(--display); font-weight: 700; font-size: 1.15rem; - color: var(--ink); margin: 0 0 6px; -} -.nlm-card p { font-size: 0.92rem; color: var(--ink-2); margin: 0 0 12px; max-width: none; } -.nlm-card .nlm-media { - margin: 0 0 12px; border-radius: 8px; overflow: hidden; - border: 1px solid var(--line-strong); background: var(--bg); -} -.nlm-card .nlm-media img, -.nlm-card .nlm-media video { display: block; width: 100%; height: auto; } -.nlm-card .nlm-actions { margin-top: auto; display: flex; flex-wrap: wrap; gap: 10px 16px; } -.nlm-card .nlm-actions a { - font-family: var(--mono); font-size: 12.5px; letter-spacing: 0.02em; - color: var(--brass); text-decoration: none; border-bottom: 1px solid transparent; -} -.nlm-card .nlm-actions a:hover { color: var(--amber-hot); border-bottom-color: var(--amber-hot); } -.nlm-card audio { width: 100%; margin-top: 2px; } -.nlm-note { - margin-top: 18px; font-family: var(--mono); font-size: 12px; - color: var(--muted); letter-spacing: 0.02em; -} - -/* ---- Footer --------------------------------------------------------------- */ -footer { - border-top: 1px solid var(--line); - padding: 48px 0 72px; - color: var(--faint); - font-family: var(--mono); font-size: 12.5px; letter-spacing: 0.03em; -} -footer a { color: var(--brass); } -footer .prov { margin-top: 10px; color: var(--muted); } - -/* "The whole stack, one link each" footer nav */ -.stack-links { - display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px 22px; - margin-bottom: 16px; padding-bottom: 16px; - border-bottom: 1px solid var(--line); -} -.stack-links .stack-lead { - color: var(--faint); text-transform: uppercase; letter-spacing: 0.12em; -} -.stack-links a { color: var(--brass); } -.stack-links a:hover { color: var(--amber-hot); } - -/* ---- Responsive ----------------------------------------------------------- */ -@media (max-width: 640px) { - body { font-size: 16px; } - .nav-links { display: none; } - .section > summary { gap: 12px; padding: 20px 18px; } - .section .num { padding-top: 4px; } - .hero .meta-row { gap: 16px; } -} - -/* ---- Reduced motion ------------------------------------------------------- */ -@media (prefers-reduced-motion: reduce) { - html { scroll-behavior: auto; } - *, *::before, *::after { - animation-duration: 0.001ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.001ms !important; - scroll-behavior: auto !important; - } - .cta:hover, .dropzone.is-dragover { transform: none; } -} diff --git a/ruv-explainer-agent-harness-generator/vercel.json b/ruv-explainer-agent-harness-generator/vercel.json deleted file mode 100644 index 449f67a..0000000 --- a/ruv-explainer-agent-harness-generator/vercel.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "$schema": "https://openapi.vercel.sh/vercel.json", - "cleanUrls": true, - "trailingSlash": false, - "headers": [ - { - "source": "/assets/(.*)", - "headers": [ - { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" } - ] - }, - { - "source": "/(.*)\\.woff2", - "headers": [ - { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }, - { "key": "Content-Type", "value": "font/woff2" } - ] - }, - { - "source": "/downloads/(.*)\\.zip", - "headers": [ - { "key": "Content-Type", "value": "application/zip" }, - { "key": "Cache-Control", "value": "public, max-age=300" } - ] - } - ] -} diff --git a/ruv-explainer-photonlayer/.gitignore b/ruv-explainer-photonlayer/.gitignore deleted file mode 100644 index 1a36312..0000000 --- a/ruv-explainer-photonlayer/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -node_modules/ -.vercel/ -.DS_Store -*.log -.env -.env.* -.targets/ -# KEEP the drop-in zip (it IS the AI-half deliverable); ignore other download scratch. -downloads/* -!downloads/photonlayer-dropin.zip -.vercel diff --git a/ruv-explainer-photonlayer/README.md b/ruv-explainer-photonlayer/README.md deleted file mode 100644 index d86d4c3..0000000 --- a/ruv-explainer-photonlayer/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# PhotonLayer — Explainer Site - -A plain-English explainer for **[PhotonLayer](https://github.com/ruvnet/PhotonLayer)** by -**Reuven Cohen / [@ruvnet](https://github.com/ruvnet)** — a deterministic optical-AI front -end where a learned phase mask reshapes light so a tiny sensor captures the *answer* instead -of the whole picture, with a signed, reproducible receipt. - -This site is part of the Repo-Primer / ExplainerSite pipeline (ADR-0001, Part II). It is an -independent explainer; all numbers and quotes are grounded in the source repo at the SHA -shown on the page. Nothing is invented. - -## Structure - -``` -ruv-explainer-photonlayer/ -├ index.html # the site — 11 collapsible numbered sections, dual-level visuals -├ styles.css # PRISM / NEAR-BLACK theme (distinct per repo, constraint K) -├ main.js # collapsible sections, smooth nav, live-provenance refresh, copy-to-clip -├ favicon.svg # prism + spectrum mark -├ vercel.json # static hosting config -├ package.json # local dev server -├ robots.txt -└ assets/ - ├ img/ # friendly raster on-ramp illustrations (Gemini-generated) - └ diagrams/ # (reserved) — technical diagrams ship as inline SVG in index.html -``` - -## Run locally - -```bash -npm run dev # serves on http://localhost:4321 -``` - -## Provenance - -- Source: @ `fe86c9fad9a1572ce46e337f118656961bdf4ebb` -- Live demo: -- NotebookLM studio (public — audio · video · slides · infographic · report): -- License (PhotonLayer): MIT © Ruvector -- Updated: 2026-06-19 diff --git a/ruv-explainer-photonlayer/assets/diagrams/README.md b/ruv-explainer-photonlayer/assets/diagrams/README.md deleted file mode 100644 index 68d0225..0000000 --- a/ruv-explainer-photonlayer/assets/diagrams/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# Technical diagrams - -Per ADR-0001 D15(E) and the build brief, the **technical / architectural diagrams ship as -crisp inline SVG authored directly in `index.html`** (57 inline `` figures) — not as -separate raster files. Inline SVG keeps them sharp at any zoom, accessible (each has a -`role="img"` + `aria-label`), themeable with the page's spectrum palette, and true to the -real PhotonLayer architecture (pipeline, optical stack, crate graph, ceiling-break bars, -compression sweep, positioning, etc.). - -The friendly raster on-ramp illustrations live in `../img/` (Gemini-generated). - -This directory is reserved for any future exported/standalone diagram assets. diff --git a/ruv-explainer-photonlayer/assets/img/before-after-camera.png b/ruv-explainer-photonlayer/assets/img/before-after-camera.png deleted file mode 100644 index 0f351e1..0000000 Binary files a/ruv-explainer-photonlayer/assets/img/before-after-camera.png and /dev/null differ diff --git a/ruv-explainer-photonlayer/assets/img/hero-prism.png b/ruv-explainer-photonlayer/assets/img/hero-prism.png deleted file mode 100644 index acc4648..0000000 Binary files a/ruv-explainer-photonlayer/assets/img/hero-prism.png and /dev/null differ diff --git a/ruv-explainer-photonlayer/assets/img/phase-mask-glass.png b/ruv-explainer-photonlayer/assets/img/phase-mask-glass.png deleted file mode 100644 index af5c30c..0000000 Binary files a/ruv-explainer-photonlayer/assets/img/phase-mask-glass.png and /dev/null differ diff --git a/ruv-explainer-photonlayer/assets/img/priya-recycling.png b/ruv-explainer-photonlayer/assets/img/priya-recycling.png deleted file mode 100644 index e2173f3..0000000 Binary files a/ruv-explainer-photonlayer/assets/img/priya-recycling.png and /dev/null differ diff --git a/ruv-explainer-photonlayer/assets/img/receipt-stamp.png b/ruv-explainer-photonlayer/assets/img/receipt-stamp.png deleted file mode 100644 index fde1a06..0000000 Binary files a/ruv-explainer-photonlayer/assets/img/receipt-stamp.png and /dev/null differ diff --git a/ruv-explainer-photonlayer/assets/img/translator-summary.png b/ruv-explainer-photonlayer/assets/img/translator-summary.png deleted file mode 100644 index 789722c..0000000 Binary files a/ruv-explainer-photonlayer/assets/img/translator-summary.png and /dev/null differ diff --git a/ruv-explainer-photonlayer/build-manifest.json b/ruv-explainer-photonlayer/build-manifest.json deleted file mode 100644 index 1c4cd0b..0000000 --- a/ruv-explainer-photonlayer/build-manifest.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "builtAt": "2026-06-19", - "sourceSha": "fe86c9fad9a1572ce46e337f118656961bdf4ebb", - "sourceShaShort": "fe86c9f", - "upstream": "https://github.com/ruvnet/PhotonLayer", - "author": "Reuven Cohen / @ruvnet", - "kb": { - "embedding": "Xenova/bge-small-en-v1.5 (384-dim)", - "gateA": { "tuned": 99.73, "heldout": 100.0 } - } -} diff --git a/ruv-explainer-photonlayer/downloads/photonlayer-dropin.zip b/ruv-explainer-photonlayer/downloads/photonlayer-dropin.zip deleted file mode 100644 index dbffc91..0000000 Binary files a/ruv-explainer-photonlayer/downloads/photonlayer-dropin.zip and /dev/null differ diff --git a/ruv-explainer-photonlayer/favicon.svg b/ruv-explainer-photonlayer/favicon.svg deleted file mode 100644 index f594fcc..0000000 --- a/ruv-explainer-photonlayer/favicon.svg +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ruv-explainer-photonlayer/index.html b/ruv-explainer-photonlayer/index.html deleted file mode 100644 index 1e9aa04..0000000 --- a/ruv-explainer-photonlayer/index.html +++ /dev/null @@ -1,1366 +0,0 @@ - - - - - -PhotonLayer — the lens that captures the answer, not the picture - - - - - - - - - - - - -
- -
- - - - -
-
-
-
- Optical AI · pure Rust · by @ruvnet -

The lens already did the thinking — so all that's left to capture is the answer.

-

PhotonLayer is a deterministic optical-AI front end: a learned piece of smart glass reshapes light so a tiny sensor captures the answer instead of the whole picture.

-

Then it signs a receipt proving exactly what it measured — a result you can re-run, not just a claim. Today it's a faithful software simulator written in Rust; the actual glass is on the roadmap.

-

An independent explainer for Reuven Cohen's (@ruvnet) PhotonLayer — built to help you actually implement his technology.

- - -
- By Reuven Cohen · @ruvnet - Updated · source @ fe86c9f - MIT © Ruvector - github.com/ruvnet/PhotonLayer ↗ - Built with the Ruv-Explainer pipeline ↗ -
-
- -
-
- A beam of plain white light enters a glowing prism and fans into a full rainbow spectrum that resolves into a few clean glowing dots — the answer. -
-

white light in → trained optics → a few numbers out: the answer, shaped by physics

-
-
- -
-
64
sensor pixels, vs 1,024 in a full image (16× fewer)
-
83.3%
single-plane MNIST at 16× compression (gradient-trained)
-
88.8%
2-plane optical cascade, still 16× compression
-
~24s
to reproduce the headline result from clean, deterministically
-
-
-
- -

- - -
-
- - - - - -
- - -
-
- - 01 - - Q1 · What is this? -

A camera that captures the answer, not the picture

-

In one plain sentence, then grounded all the way down to earth.

-
- -
-
-

PhotonLayer is a deterministic optical-AI front end: a learned piece of "smart glass" reshapes incoming light so a tiny sensor captures the answer instead of the whole picture — then signs a receipt proving exactly what it measured.

- -

Here's the everyday version. A normal camera records every pixel of a scene, then a computer reads all of them to decide what it's looking at. That's a lot of data to move, store, and process — and the picture itself can leak (it's a viewable photo of you or your scene).

-

PhotonLayer flips the order. It puts a specially-shaped, trained piece of glass — a phase mask — in front of a small sensor. The glass bends the incoming light so that, by the time light lands on the sensor, the useful information has already been squeezed into just a handful of numbers. A tiny program reads those numbers and gives the answer.

- -

The repo's own analogy: it's like a translator who listens to a whole speech and hands you a one-line summary — you never needed the full transcript to act on it. The "lens" is trained by trial-and-improvement to do that summarizing in the light itself, before anything is digitized.

- - -
-
-
Friendly view
-
A person listens to a long wall of speech and hands over a single tiny summary card — you never needed the full transcript to act.
-
The translator analogy: hear the whole speech, hand back one useful line. PhotonLayer does that summarizing in the light.
-
- -
-
Technical view — the pipeline
-
- - - - - - - - - - - - - - - - - scene - 1024 px - - - - - - - phase - mask - - - - - - propagate - (diffraction) - - - - - - - sensor - 64 px - - - - - - decoder - tiny · 640 MAC - - - - - - "paper" - decision - - - - - ⛓ receipt - BLAKE3 hash of { image · mask · config · output · metrics · build } → re-runnable proof - - - - - - -
-
The real pipeline (README "How it works"): a trained mask + diffraction does analog preprocessing, the sensor records ~64 numbers, a tiny decoder reads the answer, and a BLAKE3 receipt binds every input/output.
-
-
- -
Honest framing the repo insists onToday this is a software simulator written in Rust — the physics, the training, and the receipts are all real and reproducible. Building the actual glass is on the roadmap. So "smart glass" currently means a faithful simulation that runs on your computer or in your browser.
-
-
-
- - -
-
- - 02 - - Q2 · What problem does it solve? -

Every camera-based AI pays the "capture everything, then think" tax

-

Bandwidth, power, storage — and a recoverable image of whatever it looked at.

-
- -
-
-

Today's pattern is always the same: grab the whole picture, then compute on all of it. That single design choice creates four costs you can't avoid.

- - - - - - - - - -
The costWhy it hurts
BandwidthThousands of pixels per frame have to be read off the sensor and moved.
Power & computeA processor chews through every pixel before it can decide anything.
StorageFull frames pile up — more to keep, more to secure.
PrivacyA stored frame is a viewable photo of whatever it saw — a recoverable image of you, your documents, your scene.
- -

PhotonLayer is a proof-of-concept for capture-the-answer sensing: do the first chunk of "figuring out what's in the picture" in the light, so the sensor only ever captures a tiny compressed measurement (e.g. 64 numbers instead of 1,024 pixels), and the stored thing is a measurement, not a viewable photo.

- -
-
-
Friendly view
-
Left: a heavy cluttered camera grabbing a full pixel-dense photo. Right: a small calm sensor behind a prismatic lens capturing just a few bright dots.
-
Left: capture everything, then think — heavy and cluttered. Right: the optics already did the first pass, so only a few bright numbers are left to capture.
-
- -
-
Technical view — where the cost lives
-
- - - - - - - NORMAL CAMERA + AI - - - - read 1024 px - - - - compute 10,240 MACs - - - decision - + full photo - stored ⚠ - - - - - - PHOTONLAYER - - - mask - - read 64 px - - - - compute 640 MACs - - - decision - + measurement - (not a photo) ✓ - -
-
Same decision, but PhotonLayer reads 16× fewer sensor pixels and 16× fewer digital-decoder MACs (640 vs 10,240), and stores a measurement instead of a recoverable photo. Numbers from the README "Measured results" tables.
-
-
-
-
-
- - -
-
- - 03 - - Q3 · Why is that a problem now? -

Cameras-with-AI are everywhere — and "trust me, that's what it measured" no longer cuts it

-

Edge sensing is exploding, privacy rules are tightening, and results need to be provable.

-
- -
-
-

Three pressures collide right now, and the "capture everything, then think" design sits in the worst spot for all three.

-
    -
  • Sensing moved to the edge. Doorbells, conveyor belts, drones, wearables — tiny battery- and bandwidth-limited devices are doing vision. Reading and crunching a full frame per item is exactly the budget they don't have.
  • -
  • Privacy is now a liability, not a footnote. A stored full frame is a recoverable photo. The cheapest way to not leak a picture is to never capture one in the first place — capture a measurement that doesn't look like the scene.
  • -
  • Results need to be provable. As AI makes more real decisions, "the model said so" isn't enough. You need to show exactly what was measured and that it wasn't tampered with — a re-runnable experiment, not a screenshot.
  • -
-

PhotonLayer is the only proof-of-concept in this space that ships with bit-reproducible, signed receipts, so a result is a re-runnable experiment, not a claim. It reproduces a genuine research result — a single-layer ceiling-break to 83.3%, multi-plane 88.8%, all at 16× compression, all deterministic, from clean in ~24–62 seconds — and is unusually candid about exactly what it does and doesn't prove.

- -
-
-
Friendly view
-
A glowing tamper-proof digital receipt with a green checkmark seal and a subtle fingerprint motif, edged with prismatic light.
-
A result you can prove: every run emits a signed receipt — a re-runnable experiment, stamped and tamper-evident.
-
- -
-
Technical view — three forces, one design answer
-
- - - - - - EDGE - tiny power / bandwidth - - PRIVACY - don't store a photo - - PROVABILITY - show what was measured - - - - - - - - Capture the answer - few pixels · measurement, not photo - + signed reproducible receipt - -
-
Edge limits, privacy, and provability all push toward the same answer: capture less, store a measurement not a photo, and prove it with a receipt.
-
-
-
-
-
- - -
-
- - 04 - - Q4 · How does it solve it? -

A trained phase mask does the first transform inside the light

-

"Phase mask," diffraction, sensor, decoder, receipt — each one in plain terms, then exactly.

-
- -
-
-

"Phase mask," in plain terms: a flat piece of optics whose surface is patterned so it nudges different parts of the light wave to arrive slightly early or late — and that pattern is what gets learned for your specific task.

- -
-
-
Friendly view
-
A flat patterned piece of smart glass bends incoming wavefronts of light — some parts arrive slightly early, some late — emerging as gently reshaped glowing waves.
-
The phase mask is patterned glass that bends the light wave: some parts arrive a touch early, some late. Train that pattern and the light arrives pre-sorted.
-
- -
-
Technical view — the optical stack
-
- - - - - - - incoming light - phase mask - propagation - sensor - decoder - - - - - - - - - - +.3π−.7π+.1π−.4π+.6π−.2π - - learned θ(x,y) - - - - - - - - - Fresnel / Fraunhofer / Angular-Spectrum · deterministic FFT - - - - bin → 64 px - - - - nearest-centroid - reads the class - -
-
Accurate to photonlayer-core: a learned phase profile θ(x,y) shifts the wave per region, scalar diffraction propagates it (Fresnel / Fraunhofer / Angular-Spectrum via a deterministic FFT), the sensor bins down to ~64 values, and a tiny decoder reads the class.
-
-
- -

How the mask gets good: trial-and-improvement, then real gradients

-

A random mask already works a bit. To make it actually good at separating your classes, PhotonLayer trains the mask two ways:

-
    -
  • Hill-climbing — try a small tweak, keep it only if accuracy improves. Simple, but it plateaus at an optimizer ceiling (~73%).
  • -
  • Analytic gradient descent — train the mask through a proven adjoint of the diffraction operator (Propagator::backward_into, validated by an exact-adjoint identity and a finite-difference grad-check). This clears the ceiling decisively, to 83.3% single-plane.
  • -
  • Multi-plane cascade — stack phase planes with free-space propagation between them, trained end-to-end through the composed adjoint. Each plane sees a genuinely different field (decorrelated to ~0.04), reaching 88.8% with 2 planes.
  • -
- -
The receiptEvery run hashes every output-determining input — image, mask, config, output frame, metrics, build provenance — into one tamper-evident BLAKE3 digest. Change any one field and verification fails. That's what turns a result into a re-runnable experiment.
-
-
-
- - -
-
- - 05 - - Q5 · What does a solved state look like? -

Fewer pixels, a measurement that isn't a photo, and a receipt you can re-run

-

The before → after, stated as concrete, measured numbers from the repo.

-
- -
-
-

"Solved" isn't abstract here — it's a set of measured numbers you can reproduce.

- -
-
-
Before · normal camera + AI
-

Read 1,024 pixels per frame. Compute 10,240 MACs in the decoder. Store a full, viewable photo. Result is a claim — "trust the model."

-
-
→
-
-
After · PhotonLayer
-

Read 64 pixels (16× fewer). Compute 640 MACs (16× fewer). Store a measurement that doesn't look like the scene. Result ships with a signed, re-runnable receipt.

-
-
- - - - - - - - - -
Measured on real MNIST (16× compression)Sensor pxDecoder MACsAccuracy
Full-image baseline (same tiny decoder)102410,24075.40%
Optical, hill-climbed mask6464073.05%
Optical, gradient-trained (single plane)6464083.30%
Optical, 2-plane cascade6464088.80%
- -
-
-
Friendly view
-
The before-and-after again: a heavy full-photo camera versus a light sensor capturing a few clean bright dots.
-
Same decision, far lighter footprint — and the thing you keep is a measurement, not a recoverable picture.
-
- -
-
Technical view — breaking the ceiling
-
- - - - - - 60708090 - - - - - - - 73.05% - hill-climb - - - 75.40% - full-image - (1024 px) - - - 83.30% - gradient - (64 px) - - - 88.80% - 2-plane - (64 px) - - accuracy - ↑ - -
-
The ceiling-break, exactly as reported: hill-climb plateaus at 73.05%; real gradient training clears it to 83.30% (single plane); a 2-plane cascade reaches 88.80% — all at 16× sensor compression with the same tiny decoder.
-
-
- -
Read this number honestlyThe 83.30% > 75.40% gap is a statement about feature separability under a deliberately weak nearest-centroid decoder, not "optics beat digital." A small CNN on the same 1,024 raw pixels reaches ~99% and beats both. PhotonLayer's win is compression + privacy-by-physics + auditability, not raw accuracy.
-
-
-
- - -
-
- - 06 - - The "oh — that's what it's for" moment -

Priya runs a small recycling line

-

One named, ordinary person. A real before → after. No optics degree required.

-
- -
-
-

Priya runs a small recycling line. A camera over the conveyor belt has to spot which bin each item belongs in. She's not an optics engineer; she just needs the sorter to be fast, cheap, and not a privacy headache — the belt sometimes carries documents and personal items.

- -
-
Friendly view — Priya's sorting line
-
A warm illustration of a small recycling line: a conveyor with a bottle, paper and can, a smart prismatic-lens camera above sorting them into four colored bins.
-
A bottle, a sheet of paper, a can go past. A small smart-lens camera sorts each into one of four bins — without ever keeping a photo of what went by.
-
- -
-
-
Before
-

The camera grabs a full image of every item — thousands of pixels each — and a computer chews through all of them to decide "plastic / paper / metal / glass." That's a lot of data per second, a chunky processor, and a stored photo of everything that went past, including the personal stuff. It works, but it's heavy, power-hungry, and the stored pictures make her lawyer nervous.

-
-
→
-
-
After PhotonLayer
-

Priya's team designs a learned phase mask for exactly this 4-way sort. Now the sensor captures a few numbers per item — a measurement already shaped to separate the four classes that does not look like the item (you can't read a document off it). A tiny decoder reads "paper" off those numbers. Each run also emits a signed receipt, so she can prove to an auditor exactly what was measured.

-
-
- -
-
Technical view — what Priya's measured run actually showed
-
- - - - - - item - - - - - learned - - - - 2×2 sensor · 64× fewer - - - - "paper" - - - accuracy at this 64× reduction: - - - learned 0.988 - - - random 0.738 - - - naïve subsample — lost - - source: photonlayer-core compression-sweep table (2×2 sensor, 64× reduction) - - ⛓ + signed receipt → prove exactly what was measured - -
-
In the repo's own measured sweep, the learned few-pixel front end hits ~99% on a 4-class sort where a random mask gets ~74% and naïve sub-sampling loses the signal entirely. Each run emits a verifiable receipt.
-
- -

The "oh, that's what it's for" line: It's the difference between a camera that photographs the scene and then thinks about it, and one where the lens already did the thinking — so all that's left to capture is the answer.

- -
The honest hedge the repo itself demandsThe high-accuracy numbers come from a noise-free simulation with a deliberately weak decoder — a statement about feature separability, not "optics beat digital." A small CNN on the raw pixels still wins on raw accuracy. Priya's win is compression + privacy-by-physics + auditability, not "more accurate than a normal camera."
-
-
-
- - - - - -
-
- - 08 - - "I already have a camera + AI — why this too?" -

Why this vs. the tools you already have

-

Answered head-on: vs a normal camera+CNN, and vs "an optical neural network."

-
- -
-
- - - - - - - -
You might already use…What PhotonLayer changes
A normal camera + a CNNA normal camera captures the whole scene then computes. PhotonLayer captures far less by doing the first transform in the optics, and stores a measurement that need not look like the scene. The repo's words: "sees enough to decide, but captures far less than a full image."
"An optical neural network"The repo deliberately positions itself as NOT that. Its wedge is "auditable optical compression for task-useful sensing" — narrower and "far more defensible." Multi-layer 97–99% diffractive networks are explicitly out of scope. It doesn't compete on raw accuracy.
Any of the aboveThe one thing nothing else here gives you: bit-reproducible, signed receipts. Every run hashes its inputs/outputs into a tamper-evident digest, so a result is a re-runnable experiment, not a screenshot. That's the stated moat.
- -
-
-
Friendly view
-
The before/after split once more: heavy full-photo camera versus a calm few-dots sensor with a prismatic lens.
-
It's not "a better camera." It's a different deal: capture less, store a measurement not a photo, prove it with a receipt.
-
- -
-
Technical view — the defensible wedge
-
- - - - data captured → less - auditable / provable → more - - camera + CNN - multi-layer optical net - PhotonLayer - compressed + auditable - -
-
PhotonLayer's wedge: it gives up the raw-accuracy race to own the corner nothing else here occupies — heavily compressed and provable.
-
-
-
-
-
- - -
-
- - 09 - - Q · How would you implement it? -

What's actually inside — the four real crates

-

PhotonLayer is Rust crates, not a zip-of-models. Here's the real file-tree, each part in plain English.

-
- -
-
-

One Rust workspace, four crates. This is the actual layout (from the README "Crates" table and Cargo.toml) — annotated so you know what each one is for.

- -
-PhotonLayer/ # one Rust workspace, four crates · MIT © Ruvector -├ crates/ -│ ├ photonlayer-core # the optical simulator: scalar diffraction (Fresnel/ -│ │ # Fraunhofer/angular-spectrum), deterministic FFT, phase -│ │ # mask, sensor, metrics, signed receipts ← the heart -│ ├ photonlayer-bench # the experiments: learned-vs-random masks, the real-MNIST -│ │ # compression benchmark, gradient + cascade training, -│ │ # privacy probe ← the proof -│ ├ photonlayer-wasm # browser build: run the whole thing in your browser, no install -│ └ photonlayer-cli # command-line driver: bench / barcode / edge / privacy-gate / -│ # verify-receipt ← the easy front door -├ examples/ # hello_optics, compression, receipt, propagation_modes … -├ docs/ # ADR-260/261 (core), ADR-263 (FiberGate roadmap) -├ Cargo.toml # workspace · version 0.1.0 · edition 2021 -└ README.md # the dense original — this site is its plain-English handle -
- -

Use it in your own Rust project

-

Add the core crate and call the simulator directly. Re-running yields a bit-identical frame_hash — that's the determinism guarantee.

-
$ cargo add photonlayer-corecopy
-
use photonlayer_core::prelude::*;
-
-let frame = ScalarSimulator.simulate(&img, &mask, &cfg)?;
-// re-run with the same inputs → identical frame.frame_hash
-// build & verify a tamper-evident receipt of exactly what ran:
-let receipt = Receipt::build(&img, &mask, &cfg, &frame);
-assert!(receipt.verify());
- -
-
-
Friendly view — one engine, three ways to drive it
-
- - - ⚙️ - core - - 🧪bench · proof - ⌨️cli · front door - 🌐wasm · no install - - - - - - - -
-
Think of core as the engine and bench / cli / wasm as three ways to put your hands on it — prove it, type at it, or click it in a browser.
-
-
-
Technical view — how the four crates fit together
-
- - - photonlayer-core - the heart · optics + receipts - - photonlayer-benchthe proof / experiments - photonlayer-clithe easy front door - photonlayer-wasmbrowser, no install - - - - - - -
-
core is the engine. bench proves it, cli drives it from a terminal, and wasm runs it in a browser — every front door calls the same deterministic core.
-
-
-
-
-
- - -
-
- - 10 - - Q7 · How do you start? -

Three ways to start — all real, all in the README

-

Pick by how much you want to install: zero, a 30-line tour, or a dependency.

-
- -
-
-
    -
  1. No install — try it in your browser. Open the live demo ↗ — it runs entirely via WASM. Shape light through a mask, watch it compress to a tiny measurement, and verify the deterministic receipt.
  2. -
  3. 30-line local tour. Run the minimal pipeline and see that a re-run is bit-identical: -
    $ cargo run --release --example hello_optics -p photonlayer-corecopy
    -
  4. -
  5. Use it in your own Rust project. cargo add photonlayer-core, then call ScalarSimulator.simulate(&img, &mask, &cfg) — re-running yields a bit-identical frame_hash.
  6. -
-
-
-
Friendly view
-
Light passing through patterned smart glass — the thing you get to play with the moment you open the live demo.
-
The fastest start needs nothing installed: open the live demo and shape light through a mask in your browser.
-
-
-
Technical view — three on-ramps, by how much you install
-
- - - - 0 · BROWSER - live demo (WASM) - no install - - 1 · TOUR - hello_optics - 30-line local run - - 2 · BUILD - cargo add - into your Rust project - - each one re-runs bit-identically · the determinism guarantee - -
-
Pick your on-ramp by how much you want to install — and every one yields a bit-identical re-run.
-
-
- -
If you want the real-data numbersMNIST isn't bundled. Fetch the IDX files into crates/photonlayer-bench/data/mnist/ first (see each test header). Without them, the examples skip cleanly (never panic) and run on synthetic data.
-

Open the repo on GitHub ↗

-
-
-
- - -
-
- - 11 - - Take it with you · a studio to explore, one download to keep -

The NotebookLM studio & the drop-in: watch, listen, read — then take the whole thing

-

A public NotebookLM studio (🎧 audio · 🎬 video · 🖼 slides · 📊 infographic · 📄 report) plus a one-zip drop-in: for-humans/ (primer + studio media) and for-ai/ (a searchable KB you wire into Claude Code in three steps).

-
- -
-
- - -
- -

Generated with Google NotebookLM · grounded in the same source repo

-

A full NotebookLM studio for PhotonLayer

-

Audio overview, an explainer video, a slide deck, an infographic and a written report — all in one place, all built for a curious newcomer. No account, no setup: just open it and explore.

- -
    -
  • 🎧 Audio overview
  • -
  • 🎬 Explainer video
  • -
  • 🖼 Slide deck
  • -
  • 📊 Infographic
  • -
  • 📄 Written report
  • -
-
- - -
-
-

🎬 Explainer video

-

A short, plain-language walkthrough — what PhotonLayer is, the before→after, why it matters, how to start.

- - -
-
-

📊 The whole idea on one page

-

The before→after at a glance: a camera that records every pixel vs. light pre-shaped so a tiny sensor reads only the answer — 16× less data, privacy by physics, a signed receipt.

- PhotonLayer infographic: AI that sees the answer, not the image. Traditional sensing captures everything and thinks later, leaking privacy and burning compute; PhotonLayer uses a learned phase mask to shape light so a tiny sensor captures the answer in a few numbers — 16x less data, 88.8% accuracy, with a signed receipt for trusted audits. - -
-
-

🖼 Slide deck for a newcomer

-

A 12-slide deck that walks the idea from "what is this?" to "how do I try it?" — built for someone seeing optical AI for the first time.

- PhotonLayer slide deck cover: The camera that captures the answer, not the picture — an introduction to PhotonLayer, the deterministic optical-AI front end. - -
-
- - -
-
Friendly view — what you actually get when you unzip it
-
-

This is the real file-tree of the download — every file, in plain English. The studio media is highlighted: play the audio overview first, it's the gentlest way in.

- -
-photonlayer-dropin/ # one zip · two halves · grounded in ruvnet/PhotonLayer @ fe86c9f -├ for-humans/ # read & listen first — no setup needed -│ ├ photonlayer-primer.md # the 7-question plain-English orientation -│ └ studio/ # NotebookLM media — start here -│ ├ 🎧 photonlayer-audio.m4a # AUDIO OVERVIEW — play this FIRST (Priya's story, ~deep-dive) -│ ├ 📊 photonlayer-infographic.png # the whole idea on one page (before→after) -│ ├ 🖼 photonlayer-slides.pdf # newcomer-friendly deck -│ ├ 📄 photonlayer-report.md # the written deep-dive briefing (figures + honest limits) -│ └ audio-overview-prompt.md # the optimized prompt that generated the audio -└ for-ai/ # the searchable knowledge pack — wire into your agent - ├ photonlayer-kb.rvf # single 384-dim bge-small HNSW knowledge base ← the brain - ├ photonlayer-kb.rvf.embed.json # embedder config — REQUIRED so queries use the right model - ├ …passages.jsonl · …ids.json # full passage text + per-id index - ├ ask-kb.mjs · kb-mcp-server.mjs # CLI query + MCP server for Claude Code ← the front doors - └ kb.config.mjs · resolve-deps.mjs · package.json # run `npm i` here -
- -
-

Inside for-humans/studio/ — start here

-
    -
  • 🎧 photonlayer-audio.m4a — a NotebookLM audio overview that walks Priya's recycling-line story end to end. Play this first..m4a
  • -
  • 📊 photonlayer-infographic.png — the whole idea on one landscape page: the before→after of raw camera data vs. pre-shaped light..png
  • -
  • 🖼 photonlayer-slides.pdf — a newcomer-friendly deck: what PhotonLayer is, why it matters, how to start..pdf
  • -
  • 📄 photonlayer-report.md — the written deep-dive: the four crates, the measured results, and the honest limits, all grounded in the repo..md
  • -
-

The explainer video is large, so it lives in the public NotebookLM studio (linked from the zip's README) rather than inside the download.

-
- -
- Download the drop-in zip ↓ - Self-contained · KB passed Gate A (tuned 99.7 / held-out 100). No account, no cloud. -
- -

Three steps to wire the AI half into Claude Code

-
    -
  1. Unzip & install: -
    $ unzip photonlayer-dropin.zip && cd photonlayer-dropin/for-ai && npm installcopy
    -
  2. -
  3. Point Claude Code at it with a .mcp.json in your project root that runs for-ai/kb-mcp-server.mjs.
  4. -
  5. Add a one-line gate to CLAUDE.md: "Before answering anything about PhotonLayer, query the photonlayer-kb tool and ground the answer in what it returns."
  6. -
-

Prefer the terminal? Query it directly, no Claude Code needed:

-
$ node ask-kb.mjs photonlayer "what does PhotonLayer actually do"copy
- -
-
Technical view — how the two halves serve two audiences from one download
-
- - - photonlayer-dropin.zip - one download - - - for-humans/ - primer.md - 🎧 audio overview · 📄 report - → a person reads & listens - - - for-ai/ - photonlayer-kb.rvf + MCP server - ask-kb.mjs - → Claude Code searches it - - - - - - -
-
One zip, two audiences: for-humans/ is a primer plus a studio (🎧 audio + 📄 report) a person reads and listens to; for-ai/ is the same knowledge as a searchable .rvf + MCP server your assistant queries — so it answers from the real source instead of guessing.
-
-
-
-
- - -
-
- - 12 - - In the repo's own words — don't soften them -

Honest limits

-

PhotonLayer is unusually candid about what it does and doesn't prove. So is this page.

-
- -
-
-
-
-
Friendly view — what's real vs. what's a goal
-
- - Proven today ✓ - On the roadmap ◷ - - ✓ deterministic Rust sim - ✓ BLAKE3 receipts - ✓ 16× / 64× compression - ✓ 83.3% ceiling-break - ✓ runs offline - - - ◷ real glass hardware - ◷ noise / quantization - ◷ cross-platform bits - ◷ formal privacy proof - ◷ beating a CNN - - - -
-
The left column is real and reproducible right now; the right column is honest future work the repo names itself.
-
-
-
Technical view — where each claim's confidence comes from
-
- - - real-hardware regime — not yet characterized - - simulation-verified - noise-free scalar diffraction - continuous phase · x86-64 bit-identical - accuracy = feature-separability claim - -
-
Every number on this page lives in the green inner box (simulated, reproducible). The dashed outer box — real glass, sensor noise, fabrication — is explicitly unproven.
-
-
-
It's a simulator, not hardware (yet)"Today this is a software simulator written in Rust … building the actual glass is on the roadmap." Real hardware is expected to degrade the numbers.
-
Not a new accuracy state-of-the-artA single task-trained optical layer + tiny decoder = competitive single-layer optical compression, not SOTA. The gap vs the full-image baseline is feature-separability under a deliberately weak nearest-centroid decoder; a small CNN on the same raw pixels reaches ~99% and beats both.
-
No privacy or security guaranteeIt stores a learned measurement, not the raw image — "a description, not a theorem." The bundled probe measures linear invertibility only; nonlinear (CNN/U-Net) reconstruction is expected to succeed. Never read it as "cannot be reconstructed" or "privacy-preserving."
-
The "16× MAC reduction" counts the digital decoder only(640 vs 10,240). The optical FFT-scale transform is passive in real hardware but not free in this simulator, and is not counted.
-
All figures are noise-free scalar-diffraction simulationwith continuous phase. Robustness to phase quantization, sensor noise, and fabrication error is not yet characterized (a quantization/SNR ablation is on the roadmap).
-
Determinism is verified within runs/builds on x86-64, not yet cross-platformFull Linux/macOS/WASM bit-identity is a design goal, not yet proven — the open obstacle is platform libm transcendentals (sin/cos/atan2) differing by a ULP.
-
MNIST data isn't bundledThe real-data runs need you to fetch the IDX files first; without them the examples skip cleanly and run on synthetic data.
-
-
-
- -
-
-
- - - - - - - diff --git a/ruv-explainer-photonlayer/main.js b/ruv-explainer-photonlayer/main.js deleted file mode 100644 index d57a42a..0000000 --- a/ruv-explainer-photonlayer/main.js +++ /dev/null @@ -1,112 +0,0 @@ -/* PhotonLayer ExplainerSite — interaction layer - - collapsible sections (remember "open" via aria) - - smooth in-page nav + active section highlight - - "expand all / collapse all" control - - provenance line: static by default, live-refreshable if a build manifest exists - No frameworks, no CDN. Progressive-enhancement only. */ -(function () { - "use strict"; - - /* ---- 1. Collapsible
— animate height + scroll into view ------- */ - var allDetails = Array.prototype.slice.call(document.querySelectorAll("details.sec, details.uc")); - - function setExpandLabel() { - var btn = document.getElementById("expand-toggle"); - if (!btn) return; - var anyClosed = allDetails.some(function (d) { return !d.open; }); - btn.textContent = anyClosed ? "Expand all sections" : "Collapse all sections"; - btn.setAttribute("aria-expanded", String(!anyClosed)); - } - - var expandBtn = document.getElementById("expand-toggle"); - if (expandBtn) { - expandBtn.addEventListener("click", function () { - var anyClosed = allDetails.some(function (d) { return !d.open; }); - allDetails.forEach(function (d) { d.open = anyClosed; }); - setExpandLabel(); - }); - } - allDetails.forEach(function (d) { - d.addEventListener("toggle", setExpandLabel); - }); - setExpandLabel(); - - /* ---- 2. Smooth-scroll for in-page nav, open target if collapsed -------- */ - document.querySelectorAll('a[href^="#"]').forEach(function (a) { - a.addEventListener("click", function (e) { - var id = a.getAttribute("href").slice(1); - if (!id) return; - var target = document.getElementById(id); - if (!target) return; - e.preventDefault(); - var det = target.closest("details"); - if (det && !det.open) det.open = true; - if (target.tagName === "DETAILS" && !target.open) target.open = true; - target.scrollIntoView({ behavior: "smooth", block: "start" }); - history.replaceState(null, "", "#" + id); - }); - }); - - /* ---- 3. Active-section highlight in the side rail ---------------------- */ - var navLinks = Array.prototype.slice.call(document.querySelectorAll(".rail a")); - var byId = {}; - navLinks.forEach(function (l) { byId[l.getAttribute("href").slice(1)] = l; }); - var sections = Array.prototype.slice.call(document.querySelectorAll("section[id]")); - if ("IntersectionObserver" in window && sections.length) { - var io = new IntersectionObserver(function (entries) { - entries.forEach(function (en) { - var link = byId[en.target.id]; - if (!link) return; - if (en.isIntersecting) { - navLinks.forEach(function (l) { l.classList.remove("active"); }); - link.classList.add("active"); - } - }); - }, { rootMargin: "-45% 0px -50% 0px", threshold: 0 }); - sections.forEach(function (s) { io.observe(s); }); - } - - /* ---- 4. Live provenance (optional). Static line ships in the HTML; - if a /build-manifest.json is later added, refresh it in place. -- */ - var prov = document.getElementById("prov-live"); - if (prov) { - fetch("/build-manifest.json", { cache: "no-store" }) - .then(function (r) { return r.ok ? r.json() : null; }) - .then(function (m) { - if (!m) return; - // Sanitize: only hex chars for sha, only date-ish chars for date. - var sha = String(m.sourceSha || "").replace(/[^0-9a-fA-F]/g, "").slice(0, 7); - var date = String(m.builtAt || m.updated || "").replace(/[^0-9A-Za-z:\-\s.]/g, ""); - if (!sha) return; - // Build via safe DOM nodes (textContent only) — never innerHTML. - prov.textContent = ""; - prov.appendChild(document.createTextNode("Updated ")); - var t = document.createElement("time"); - t.textContent = date || "—"; - prov.appendChild(t); - prov.appendChild(document.createTextNode(" · source @ ")); - var c = document.createElement("code"); - c.textContent = sha; - prov.appendChild(c); - }) - .catch(function () { /* keep static line */ }); - } - - /* ---- 5. Copy-to-clipboard on command blocks --------------------------- */ - document.querySelectorAll("[data-copy]").forEach(function (el) { - el.addEventListener("click", function () { - var text = el.getAttribute("data-copy"); - if (!navigator.clipboard) return; - navigator.clipboard.writeText(text).then(function () { - var prev = el.getAttribute("data-label") || ""; - el.classList.add("copied"); - var hint = el.querySelector(".copy-hint"); - if (hint) { hint.textContent = "copied ✓"; } - setTimeout(function () { - el.classList.remove("copied"); - if (hint) hint.textContent = "copy"; - }, 1400); - }); - }); - }); -})(); diff --git a/ruv-explainer-photonlayer/package.json b/ruv-explainer-photonlayer/package.json deleted file mode 100644 index 049b32e..0000000 --- a/ruv-explainer-photonlayer/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "ruv-explainer-photonlayer", - "version": "1.0.0", - "private": true, - "description": "Explainer site for PhotonLayer by Reuven Cohen (@ruvnet) — deterministic optical-AI front end.", - "license": "MIT", - "scripts": { - "dev": "python3 -m http.server 4321", - "start": "python3 -m http.server 4321" - } -} diff --git a/ruv-explainer-photonlayer/robots.txt b/ruv-explainer-photonlayer/robots.txt deleted file mode 100644 index c2aa7fd..0000000 --- a/ruv-explainer-photonlayer/robots.txt +++ /dev/null @@ -1,4 +0,0 @@ -User-agent: * -Allow: / - -Sitemap: https://ruv-explainer-photonlayer.vercel.app/sitemap.xml diff --git a/ruv-explainer-photonlayer/studio/audio-overview-prompt.md b/ruv-explainer-photonlayer/studio/audio-overview-prompt.md deleted file mode 100644 index 0437dc2..0000000 --- a/ruv-explainer-photonlayer/studio/audio-overview-prompt.md +++ /dev/null @@ -1,27 +0,0 @@ -# PhotonLayer Audio Overview — Optimized Prompt - -**Notebook:** PhotonLayer — Explainer -**Notebook ID:** d97351e0-542f-4c80-9e56-19cb1dca04f5 -**Audio Artifact ID:** 7f9510fb-3273-4aea-ac61-894513f37a1f -**Report Artifact ID:** 6ed11d55-5365-4b52-a69b-b6ddaf4b87d0 -**Format:** deep_dive | Length: default -**Audience:** Non-technical Claude Code user (comfortable with the terminal, not an optics/ML engineer) - -## Focus Prompt Used - -Open with the felt problem: every camera-based AI captures a full photo of everything it sees, then a computer chews through every pixel to decide what it is — heavy on power, storage, and bandwidth, and it leaves a viewable picture of whatever (or whoever) it looked at sitting around. Define the idea in one plain sentence: PhotonLayer is a deterministic optical-AI front end — a learned piece of smart glass (a phase mask) reshapes incoming light so a tiny sensor captures the answer instead of the whole picture, then signs a receipt proving exactly what it measured. Use the translator analogy: the glass listens to the whole scene and hands the sensor a one-line summary. Then walk Priya, who runs a small recycling line: before PhotonLayer her belt camera grabs a full image of every item and a chunky computer sorts plastic/paper/metal/glass while storing photos of everything including personal documents; after PhotonLayer a learned phase mask squeezes each item into a few numbers that do not look like the item, a tiny decoder reads "paper", and a signed receipt proves what was measured — in the repo's own run a few-pixel learned front end hits about 99 percent where a random mask gets about 74 percent. Be scrupulously honest: today this is a reproducible Rust SIMULATOR, not real glass yet (hardware is on the roadmap); the high accuracy numbers are noise-free simulation with a deliberately weak decoder and are a statement about feature separability, not optics beating digital — a small CNN on raw pixels still wins on raw accuracy. Priya's real win is compression plus privacy-by-physics plus auditability. Close with the exact way to try it right now: open the live browser demo, or run `cargo run --release --example hello_optics -p photonlayer-core`. Tone: warm, confident, zero undefined jargon; define phase mask, propagation, and receipt in plain words the first time each appears. - -## Prompt Design Rationale - -1. **Opens with the felt problem** — "captures a full photo of everything, then chews through every pixel" is the visceral cost (power, storage, a recoverable picture) a non-technical listener feels immediately. -2. **One-sentence definition** — "smart glass that reshapes light so the sensor captures the answer, not the picture, and signs a receipt" uses only everyday words. -3. **Translator analogy** — the repo's own analogy (a translator handing you a one-line summary) makes "analog preprocessing in the light" tangible. -4. **Priya before→after** — the canonical resonance persona; grounds the abstraction in a real recycling-line story with measured numbers (99% learned vs 74% random). -5. **Honest hedges baked in** — simulator-not-hardware, feature-separability-not-optics-beat-digital, privacy-by-physics-not-zero-knowledge — so the audio cannot overclaim (global Rule 9 honesty). -6. **Ends with the exact first step** — live browser demo or one `cargo run` command — removes all ambiguity about what to do next. - -## Source Files - -- content/photonlayer.canon.md (Source ID: 44365632-be50-4752-9081-7a08572fed44) — the resonance brief / content standard -- kb/stores/photonlayer/photonlayer-primer.md (Source ID: ec57e160-cb3d-432c-9328-ac681817f11b) — the 7-stage comprehension-arc primer -- .targets/photonlayer/README.md (Source ID: 2c40fe35-b32c-45d3-9a4d-e6067e125b24) — upstream README (ruvnet) diff --git a/ruv-explainer-photonlayer/studio/photonlayer-infographic.png b/ruv-explainer-photonlayer/studio/photonlayer-infographic.png deleted file mode 100644 index 8fd2340..0000000 Binary files a/ruv-explainer-photonlayer/studio/photonlayer-infographic.png and /dev/null differ diff --git a/ruv-explainer-photonlayer/studio/photonlayer-report.md b/ruv-explainer-photonlayer/studio/photonlayer-report.md deleted file mode 100644 index 728b3b1..0000000 --- a/ruv-explainer-photonlayer/studio/photonlayer-report.md +++ /dev/null @@ -1,100 +0,0 @@ -# PhotonLayer: Auditable Optical Compression and Task-Trained Optics - -## Executive Summary - -PhotonLayer is a deterministic optical-AI front end implemented in pure Rust. It reimagines the traditional imaging pipeline by performing task-specific analog preprocessing directly in the optical domain before light is digitized. By placing a learned "phase mask"—a specially-shaped piece of smart glass—in front of a sensor, the system bends incoming light to compress task-useful information into a small number of sensor pixels. This approach allows a system to "capture the answer" rather than recording a full-resolution image and processing it digitally. - -Currently existing as a high-fidelity software simulator, PhotonLayer achieves significant data reduction, demonstrating a 16× reduction in sensor pixels and digital Multiply-Accumulate (MAC) operations with minimal accuracy loss on benchmarks like MNIST. The system distinguishes itself through a commitment to absolute reproducibility; every execution generates a tamper-evident, BLAKE3-bound cryptographic receipt that proves exactly what was measured and decided. - -## Core Theme Analysis - -### 1. Optical Compression: "The Wedge" -PhotonLayer is explicitly defined not as a general-purpose "optical neural network," but as **auditable optical compression for task-useful sensing**. In a standard imaging system, a camera captures every pixel of a scene, creating a massive data overhead and potential privacy leaks. PhotonLayer "flips the order" by using a learned phase mask to perform a trained analog transform on light. - -The resulting sensor measurement is a compressed summary rather than a viewable photo. This provides four primary benefits: -* **Reduced Capture:** Uses a few sensor pixels instead of a full image. -* **Faster Decisions:** The "heavy lifting" occurs passively in the optics through free-space diffraction. -* **Reduced Leakage:** The sensor records a compressed measurement that does not look like the original scene. -* **Provability:** Every run emits a deterministic receipt. - -### 2. Training Methodologies and "Ceiling Breaking" -The system utilizes two primary methods for training the optical phase masks, moving from simple optimization to advanced analytic gradients: - -* **Hill-Climbing:** A trial-and-improvement method that perturbs the mask and retains changes that improve accuracy. This method typically hits an optimizer ceiling (approx. 73% accuracy on MNIST at 16× compression). -* **Analytic Gradient Descent:** This represents the "headline" achievement of the project. By using a proven adjoint of the diffraction operator (`Propagator::backward_into`), gradients flow back through the optics. This allows for direct training via Adam, breaking the single-mask ceiling to reach **83.30%** accuracy. -* **Multi-Plane Diffractive Cascade:** By stacking multiple phase planes with free-space propagation between them, the system can reach **88.80%** (2 planes) or **89.80%** (3 planes) accuracy while maintaining 16× compression. - -### 3. Determinism and Cryptographic Auditability -The project's primary competitive advantage—its "moat"—is bit-identical reproducibility. PhotonLayer uses a custom scalar Complex type and a hand-rolled FFT with a fixed reduction order to ensure that the same input, mask, and seed produce identical results on x86-64 architectures. - -This determinism enables the generation of **BLAKE3-bound receipts**. These receipts hash the model, configuration, measurement, and decision into a single digest. This transforms a result from a mere claim into a reproducible experiment that can be verified by third parties or auditors. - -## Measured Results: MNIST Optical Compression - -The following table outlines the performance of various configurations against a full-image baseline using a tiny nearest-centroid decoder. - -| Configuration | Sensor Pixels | Decoder Params | Accuracy | Delta vs Baseline | -| :--- | :--- | :--- | :--- | :--- | -| **Full-Image Baseline** | 1024 | 10,240 | 75.40% | — | -| **Optical (Hill-Climb Mask)** | 64 | 640 | 73.05% | -2.35 pp | -| **Optical (Gradient-Trained)** | 64 | 640 | **83.30%** | **+7.90 pp** | -| **Optical (2-Plane Cascade)** | 64 | 640 | **88.80%** | **+13.40 pp** | - -**Note on Accuracy:** The superior performance of the gradient-trained optical system over the baseline (83.30% vs 75.40%) is a statement on **feature separability under a fixed weak decoder**. It indicates that 64 learned optical features are more linearly separable than 1024 raw pixels, rather than a claim that optics outperform all digital methods (as a CNN on the same 1024 pixels reaches ~99%). - -## System Architecture - -### The Four Crates -PhotonLayer is organized as a Rust workspace consisting of four distinct crates: - -| Crate | Functionality | -| :--- | :--- | -| `photonlayer-core` | The optical simulator. Handles scalar diffraction (Fresnel/Fraunhofer), deterministic FFT, phase masks, and BLAKE3 receipts. | -| `photonlayer-bench` | Benchmarks and training. Contains MNIST benchmarks, hill-climb and gradient training logic, and privacy probes. | -| `photonlayer-wasm` | WebAssembly bindings enabling the live browser-based demo and playground. | -| `photonlayer-cli` | Command-line driver for subcommands like `bench`, `barcode`, `edge`, and `verify-receipt`. | - -### The Optical Pipeline -The core pipeline follows a deterministic five-stage chain: -1. **InputImage:** The source scene is converted into an `OpticalField`. -2. **PhaseMask:** A trained pattern of phase shifts is imprinted onto the light. -3. **Propagation:** The field moves through free space via scalar diffraction models. -4. **Capture:** The sensor records intensity, average-pooling the field into a compressed measurement. -5. **Decoder & Receipt:** A tiny digital program interprets the measurement and signs the result. - -## Honest Scope and Limitations - -The documentation emphasizes several critical caveats regarding the current state of the project: -* **Simulator Status:** The project is currently a software simulator. While the physics and training are real, physical hardware implementation is still on the roadmap. -* **Not Absolute SOTA:** The goal is competitive single-layer compression, not setting new state-of-the-art accuracy records for MNIST (where multi-layer CNNs still dominate). -* **Privacy vs. Security:** While PhotonLayer captures "less" information, it offers **no formal privacy or security guarantee**. Linear reconstruction may fail, but nonlinear (CNN-based) reconstruction is expected to succeed. It is "privacy-by-physics," not zero-knowledge. -* **MAC Reduction:** The 16× reduction claim applies only to the **digital decoder**. The optical transform is passive in hardware but consumes compute resources within the simulator. -* **Cross-Platform Determinism:** While bit-identity is verified on x86-64, it is not yet proven across Linux, macOS, and WASM due to variations in platform `libm` transcendentals (sin/cos). - -## Key Quotes with Context - -> **"The camera no longer captures the image. It captures the answer shaped by physics."** -* *Context:* Found in the `photonlayer-core` documentation, this summarizes the fundamental shift from traditional "capture everything" imaging to task-specific "capture the answer" sensing. - -> **"It's like a translator who listens to a whole speech and hands you a one-line summary — you never needed the full transcript to act on it."** -* *Context:* A plain-language analogy used to explain how the phase mask summarizes information in the light itself before digitization. - -> **"Capture less · decide faster · leak less · prove what happened."** -* *Context:* The core mantra of the PhotonLayer project, highlighting the four pillars of its value proposition. - -> **"Hill-climbing converges to an optimizer ceiling (~73%); analytic gradient descent breaks it to 83.30%."** -* *Context:* Highlights the technical breakthrough achieved by implementing a differentiable training head and an adjoint of the diffraction operator. - -## Actionable Insights and Implementation - -### Demonstration Pathways -For those seeking to evaluate the system, the repository provides a "ladder" of runnable examples: -* **Visualizing Compression:** Run `cargo run --example compression` to see a side-by-side ASCII comparison of a 64x64 input and its compressed 8x8 sensor measurement. -* **Verifying Receipts:** Use `cargo run --example receipt` to generate a receipt, verify it passes, tamper with one byte, and watch it fail. -* **Gradient Training:** Run `cargo run --example gradient_training` to reproduce the 83.30% accuracy result in approximately 24 seconds. - -### Roadmap and Future Development -The project outlines a clear path toward physical realization: -1. **Analytic Adjoint Refinement:** Continuing to push the limits of cascaded planes. -2. **FiberGate:** Simulating multimode-fiber transmission-matrix substrates with drift-aware training. -3. **Hardware Bridge:** Developing a DiffuserCam-style lensless camera as the first physical demonstration, preceded by a phase-quantization sweep to prepare for fabrication. \ No newline at end of file diff --git a/ruv-explainer-photonlayer/studio/photonlayer-slides-cover.png b/ruv-explainer-photonlayer/studio/photonlayer-slides-cover.png deleted file mode 100644 index bdc539b..0000000 Binary files a/ruv-explainer-photonlayer/studio/photonlayer-slides-cover.png and /dev/null differ diff --git a/ruv-explainer-photonlayer/studio/photonlayer-slides.pdf b/ruv-explainer-photonlayer/studio/photonlayer-slides.pdf deleted file mode 100644 index d86c4f0..0000000 Binary files a/ruv-explainer-photonlayer/studio/photonlayer-slides.pdf and /dev/null differ diff --git a/ruv-explainer-photonlayer/styles.css b/ruv-explainer-photonlayer/styles.css deleted file mode 100644 index 4a1bf1a..0000000 --- a/ruv-explainer-photonlayer/styles.css +++ /dev/null @@ -1,412 +0,0 @@ -/* ============================================================================= - PhotonLayer ExplainerSite — PRISM / NEAR-BLACK - Aesthetic lock [Constraint K — distinct per repo]: - • Substrate: near-black optical-bench black (#08080d), NOT warm charcoal. - • Accents: the full visible-light SPECTRUM (violet→indigo→blue→cyan→green - →yellow→orange→red) used as a prismatic gradient, never a single hue. - • Motifs: lenses, light rays, prisms, wavefronts, fanned spectra. - • DELIBERATELY NOT the MetaHarness FOUNDRY look (warm charcoal + molten - amber/copper, zero cyan). This site is cool-black with a rainbow edge. - Type: "Space Grotesk" display + "Inter" body + "JetBrains Mono" code, - loaded from Google Fonts with a system fallback so the page renders offline. - ========================================================================== */ - -@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;500;600;700&family=Inter:wght@400;450;500;600&family=JetBrains+Mono:wght@400;500&display=swap'); - -/* ---- Design tokens -------------------------------------------------------- */ -:root { - /* Near-black substrate — true optical-bench black with a faint blue cast */ - --bg: #08080d; /* deepest — page floor */ - --bg-2: #0c0c14; /* raised plane */ - --panel: #11111c; /* card body */ - --panel-2: #161624; /* card header / inset */ - --panel-3: #1d1d2e; /* hover / nested */ - --ridge: #262640; /* hairline edges */ - - /* The spectrum — used as a prismatic gradient + individual band swatches */ - --violet: #a06bff; - --indigo: #6b7bff; - --blue: #4f8cff; - --cyan: #1fd6d6; - --green: #3ee68a; - --yellow: #ffd23e; - --orange: #ff9a3e; - --red: #ff5e62; - --spectrum: linear-gradient(90deg, - var(--violet) 0%, var(--indigo) 16%, var(--blue) 30%, - var(--cyan) 46%, var(--green) 60%, var(--yellow) 74%, - var(--orange) 86%, var(--red) 100%); - --spectrum-soft: linear-gradient(90deg, - rgba(160,107,255,.9), rgba(79,140,255,.9), rgba(31,214,214,.9), - rgba(62,230,138,.9), rgba(255,210,62,.9), rgba(255,94,98,.9)); - - /* Ink — cool off-white, never warm cream */ - --ink: #eef0fb; /* primary text */ - --ink-2: #c3c6dd; /* secondary text */ - --muted: #8b8fab; /* captions, meta */ - --faint: #5a5e7a; /* hairline labels */ - --on-accent: #08080d; /* text ON a bright fill */ - - /* Lines / fills */ - --line: rgba(140,150,210,.12); - --line-strong: rgba(140,150,210,.26); - --glass: rgba(20,22,40,.55); - - /* Depth — cool shadows + prismatic glow */ - --shadow: 0 22px 50px -28px rgba(0,0,0,.85); - --shadow-deep: 0 40px 100px -44px rgba(0,0,0,.92); - --glow-cyan: 0 0 0 1px rgba(31,214,214,.25), 0 16px 44px -18px rgba(31,214,214,.30); - --glow-spec: 0 14px 50px -20px rgba(120,120,255,.35); - - /* Type */ - --display: "Space Grotesk", ui-sans-serif, system-ui, sans-serif; - --sans: "Inter", system-ui, -apple-system, "Segoe UI", sans-serif; - --mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace; - - /* Rhythm */ - --maxw: 1160px; - --gutter: clamp(18px, 5vw, 52px); - --radius: 16px; - --radius-s: 10px; - --ease: cubic-bezier(.22,.61,.36,1); -} - -/* ---- Reset / base --------------------------------------------------------- */ -*, *::before, *::after { box-sizing: border-box; } -html { -webkit-text-size-adjust: 100%; scroll-behavior: smooth; scroll-padding-top: 84px; } - -body { - margin: 0; - background: var(--bg); - color: var(--ink); - font-family: var(--sans); - font-size: 16.5px; - line-height: 1.66; - -webkit-font-smoothing: antialiased; - text-rendering: optimizeLegibility; - /* Optical-bench backdrop: faint prismatic glints + a deep-space gradient. - Cool/rainbow only — NEVER warm amber (that's the other site). */ - background-image: - radial-gradient(900px 540px at 82% -6%, rgba(160,107,255,.10), transparent 60%), - radial-gradient(820px 600px at -8% 4%, rgba(31,214,214,.08), transparent 58%), - radial-gradient(700px 520px at 50% 112%, rgba(255,94,98,.06), transparent 60%), - linear-gradient(180deg, var(--bg) 0%, var(--bg-2) 100%); - background-attachment: fixed; -} - -img { max-width: 100%; height: auto; display: block; } - -a { color: var(--cyan); text-decoration: none; transition: color .18s var(--ease); } -a:hover { color: var(--green); } - -a:focus-visible, summary:focus-visible, button:focus-visible { - outline: 2px solid var(--cyan); - outline-offset: 3px; - border-radius: 4px; -} - -code, pre, kbd { font-family: var(--mono); } - -::selection { background: rgba(31,214,214,.30); color: var(--ink); } - -/* ---- Layout shell --------------------------------------------------------- */ -.wrap { max-width: var(--maxw); margin: 0 auto; padding: 0 var(--gutter); } - -/* Prismatic hairline used as a recurring motif (a "spectrum edge") */ -.spec-line { height: 2px; width: 100%; background: var(--spectrum); border: 0; border-radius: 2px; opacity: .9; } - -/* ---- Top bar -------------------------------------------------------------- */ -.topbar { - position: sticky; top: 0; z-index: 50; - backdrop-filter: blur(14px); - background: linear-gradient(180deg, rgba(8,8,13,.92), rgba(8,8,13,.72)); - border-bottom: 1px solid var(--line); -} -.topbar .wrap { display: flex; align-items: center; gap: 18px; height: 60px; } -.brand { display: flex; align-items: center; gap: 11px; font-family: var(--display); font-weight: 600; letter-spacing: .2px; color: var(--ink); } -.brand .logo { width: 26px; height: 26px; flex: none; } -.brand b { font-weight: 700; } -.brand .tag { font-family: var(--mono); font-size: 11px; color: var(--muted); padding: 2px 7px; border: 1px solid var(--line); border-radius: 20px; } -.topbar nav { margin-left: auto; display: flex; gap: 4px; align-items: center; } -.topbar nav a { color: var(--ink-2); font-size: 14px; font-weight: 500; padding: 7px 11px; border-radius: 8px; } -.topbar nav a:hover { color: var(--ink); background: var(--panel-2); } -.topbar .ghub { border: 1px solid var(--line-strong); } -@media (max-width: 720px) { .topbar nav a.hide-sm { display: none; } } - -/* ---- Hero ----------------------------------------------------------------- */ -.hero { position: relative; padding: clamp(48px, 8vw, 96px) 0 clamp(40px, 6vw, 72px); overflow: hidden; } -.hero .wrap { position: relative; z-index: 2; } -.hero-grid { display: grid; grid-template-columns: 1.06fr .94fr; gap: clamp(28px, 5vw, 60px); align-items: center; } -@media (max-width: 880px) { .hero-grid { grid-template-columns: 1fr; } } - -.eyebrow { - display: inline-flex; align-items: center; gap: 9px; - font-family: var(--mono); font-size: 12px; letter-spacing: .12em; text-transform: uppercase; - color: var(--ink-2); padding: 6px 13px; border-radius: 30px; - border: 1px solid var(--line-strong); - background: var(--glass); -} -.eyebrow .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--spectrum); box-shadow: 0 0 10px rgba(31,214,214,.6); } - -.hero h1 { - font-family: var(--display); font-weight: 700; - font-size: clamp(34px, 5.6vw, 60px); line-height: 1.04; letter-spacing: -.02em; - margin: 20px 0 0; -} -.hero h1 .spec-text { - background: var(--spectrum); -webkit-background-clip: text; background-clip: text; color: transparent; -} -.hero .lede { font-size: clamp(17px, 2.2vw, 21px); color: var(--ink-2); margin: 20px 0 0; max-width: 38ch; } -.hero .sub { font-size: 15.5px; color: var(--muted); margin: 14px 0 0; max-width: 46ch; } -.hero .attrib-lede { - font-size: 14.5px; line-height: 1.5; color: var(--ink-2); margin: 18px 0 0; max-width: 48ch; - padding: 11px 15px 11px 16px; border-left: 3px solid var(--cyan); border-radius: 0 10px 10px 0; - background: var(--glass); -} -.hero .attrib-lede strong { color: var(--ink); } -.hero .attrib-lede a { color: var(--cyan); border-bottom: 1px dotted var(--line-strong); } -.hero .attrib-lede a:hover { color: var(--green); } - -.hero-cta { display: flex; flex-wrap: wrap; gap: 12px; margin-top: 30px; } - -.btn { - display: inline-flex; align-items: center; gap: 9px; - font-family: var(--sans); font-weight: 600; font-size: 15px; - padding: 12px 20px; border-radius: 12px; cursor: pointer; border: 1px solid transparent; - transition: transform .14s var(--ease), box-shadow .18s var(--ease), background .18s var(--ease); -} -.btn-primary { color: var(--on-accent); background: var(--spectrum); box-shadow: var(--glow-spec); } -.btn-primary:hover { transform: translateY(-2px); color: var(--on-accent); } -.btn-ghost { color: var(--ink); background: var(--panel); border-color: var(--line-strong); } -.btn-ghost:hover { color: var(--ink); background: var(--panel-2); transform: translateY(-2px); } - -.hero-figure { position: relative; border-radius: var(--radius); overflow: hidden; border: 1px solid var(--line); box-shadow: var(--shadow-deep); } -.hero-figure img { width: 100%; } -.hero-figure::after { content:""; position:absolute; inset:0; border-radius: var(--radius); box-shadow: inset 0 0 0 1px rgba(160,107,255,.18); pointer-events:none; } -.hero-figcap { font-family: var(--mono); font-size: 11.5px; color: var(--muted); margin-top: 10px; text-align: center; } - -/* Provenance strip */ -.prov { - margin-top: 30px; display: flex; flex-wrap: wrap; gap: 10px 18px; align-items: center; - font-family: var(--mono); font-size: 12.5px; color: var(--muted); - padding: 12px 16px; border: 1px solid var(--line); border-radius: 12px; background: var(--glass); -} -.prov .who { color: var(--ink-2); } -.prov code { color: var(--cyan); } -.prov a { color: var(--ink-2); border-bottom: 1px dotted var(--line-strong); } -.prov a:hover { color: var(--green); } -.prov .pill { padding: 2px 9px; border-radius: 20px; border: 1px solid var(--line-strong); } - -/* ---- Stat band ------------------------------------------------------------ */ -.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 14px; margin-top: 40px; } -@media (max-width: 720px) { .stats { grid-template-columns: repeat(2,1fr); } } -.stat { padding: 18px; border: 1px solid var(--line); border-radius: 14px; background: var(--panel); position: relative; overflow: hidden; } -.stat::before { content:""; position:absolute; left:0; top:0; bottom:0; width:3px; background: var(--spectrum); } -.stat .n { font-family: var(--display); font-weight: 700; font-size: clamp(22px, 3vw, 30px); color: var(--ink); } -.stat .l { font-size: 13px; color: var(--muted); margin-top: 4px; } - -/* ---- Main two-column (rail + content) ------------------------------------ */ -.shell { display: grid; grid-template-columns: 224px 1fr; gap: clamp(24px, 4vw, 52px); padding: clamp(40px,6vw,72px) 0; align-items: start; } -@media (max-width: 980px) { .shell { grid-template-columns: 1fr; } } - -.rail { position: sticky; top: 84px; align-self: start; } -@media (max-width: 980px) { .rail { display: none; } } -.rail .rail-h { font-family: var(--mono); font-size: 11px; letter-spacing: .14em; text-transform: uppercase; color: var(--faint); margin: 0 0 12px 12px; } -.rail a { display: block; color: var(--muted); font-size: 14px; padding: 7px 12px; border-radius: 8px; border-left: 2px solid transparent; line-height: 1.3; } -.rail a:hover { color: var(--ink); background: var(--panel); } -.rail a.active { color: var(--ink); border-left-color: var(--cyan); background: var(--panel); } -.rail a .num { font-family: var(--mono); font-size: 11px; color: var(--faint); margin-right: 7px; } -.rail .expand-btn { margin-top: 16px; width: 100%; font-size: 12.5px; color: var(--ink-2); background: var(--panel); border: 1px solid var(--line); padding: 9px; border-radius: 9px; cursor: pointer; font-family: var(--sans); } -.rail .expand-btn:hover { background: var(--panel-2); color: var(--ink); } - -/* ---- Section (collapsible) ------------------------------------------------ */ -section { scroll-margin-top: 84px; } -.sec { border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); margin-bottom: 20px; overflow: hidden; box-shadow: var(--shadow); } -.sec[open] { box-shadow: var(--shadow), var(--glow-cyan); border-color: var(--line-strong); } -.sec > summary { - list-style: none; cursor: pointer; display: flex; align-items: flex-start; gap: 16px; - padding: 22px clamp(18px,3vw,30px); user-select: none; -} -.sec > summary::-webkit-details-marker { display: none; } -.sec > summary:hover { background: var(--panel-2); } -.sec .s-num { font-family: var(--mono); font-size: 13px; font-weight: 500; color: var(--on-accent); background: var(--spectrum); border-radius: 9px; padding: 6px 10px; flex: none; line-height: 1; margin-top: 3px; } -.sec .s-head { flex: 1; min-width: 0; } -.sec .s-q { font-family: var(--mono); font-size: 11.5px; letter-spacing: .08em; text-transform: uppercase; color: var(--cyan); } -.sec .s-title { font-family: var(--display); font-weight: 600; font-size: clamp(19px, 2.6vw, 25px); line-height: 1.18; margin: 5px 0 0; color: var(--ink); } -.sec .s-sub { font-size: 14.5px; color: var(--muted); margin: 7px 0 0; } -.sec .chev { flex: none; width: 22px; height: 22px; color: var(--muted); transition: transform .22s var(--ease); margin-top: 6px; } -.sec[open] .chev { transform: rotate(180deg); color: var(--cyan); } -.sec .s-body { padding: 4px clamp(18px,3vw,30px) clamp(24px,3vw,32px); } -.sec .s-body > :first-child { margin-top: 0; } - -.sec p { color: var(--ink-2); } -.sec h4 { font-family: var(--display); font-weight: 600; font-size: 17px; color: var(--ink); margin: 26px 0 8px; } -.sec ul, .sec ol { color: var(--ink-2); padding-left: 20px; } -.sec li { margin: 7px 0; } -.sec strong { color: var(--ink); font-weight: 600; } -.sec em { color: var(--ink); font-style: italic; } - -.lead-in { font-size: 17px; color: var(--ink) !important; } - -/* Callouts */ -.note { border-left: 3px solid var(--cyan); background: rgba(31,214,214,.06); padding: 12px 16px; border-radius: 0 10px 10px 0; margin: 18px 0; font-size: 14.5px; color: var(--ink-2); } -.note.warn { border-left-color: var(--orange); background: rgba(255,154,62,.07); } -.note.honest { border-left-color: var(--violet); background: rgba(160,107,255,.07); } -.note .lab { font-family: var(--mono); font-size: 11px; letter-spacing:.08em; text-transform: uppercase; color: var(--cyan); display:block; margin-bottom: 4px; } -.note.warn .lab { color: var(--orange); } -.note.honest .lab { color: var(--violet); } - -/* Dual-visual block: a friendly raster on-ramp + a technical SVG diagram */ -.dual { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; margin: 22px 0; } -@media (max-width: 760px) { .dual { grid-template-columns: 1fr; } } -.vfig { border: 1px solid var(--line); border-radius: 14px; background: var(--bg-2); overflow: hidden; display: flex; flex-direction: column; } -.vfig .vlabel { font-family: var(--mono); font-size: 11px; letter-spacing: .08em; text-transform: uppercase; padding: 9px 14px; border-bottom: 1px solid var(--line); color: var(--muted); display:flex; align-items:center; gap:8px; } -.vfig .vlabel .ic { width: 14px; height: 14px; } -.vfig .vlabel.simple { color: var(--green); } -.vfig .vlabel.tech { color: var(--cyan); } -.vfig .vbody { padding: 0; } -.vfig img { width: 100%; display: block; } -.vfig .svgwrap { padding: 16px; } -.vfig .vcap { font-size: 13px; color: var(--muted); padding: 11px 14px 14px; border-top: 1px solid var(--line); } -.vfig svg { width: 100%; height: auto; display: block; } - -/* Command / code blocks */ -.cmd { position: relative; display: block; font-family: var(--mono); font-size: 13.5px; background: #05050a; border: 1px solid var(--ridge); border-radius: 10px; padding: 14px 48px 14px 16px; color: var(--green); margin: 14px 0; overflow-x: auto; white-space: pre; cursor: copy; } -.cmd .copy-hint { position: absolute; right: 12px; top: 12px; font-size: 10.5px; color: var(--faint); letter-spacing: .04em; text-transform: uppercase; } -.cmd:hover { border-color: var(--line-strong); } -.cmd:hover .copy-hint { color: var(--cyan); } -.cmd .prompt { color: var(--faint); user-select: none; } -.cmd .flag { color: var(--cyan); } -pre.block { font-family: var(--mono); font-size: 13px; line-height: 1.6; background: #05050a; border: 1px solid var(--ridge); border-radius: 12px; padding: 16px; color: var(--ink-2); overflow-x: auto; margin: 16px 0; } -code.inl { font-size: .9em; background: var(--panel-3); padding: 1.5px 6px; border-radius: 5px; color: var(--cyan); border: 1px solid var(--line); } - -/* Tables (before/after, comparison) */ -.tbl { width: 100%; border-collapse: collapse; margin: 18px 0; font-size: 14.5px; border: 1px solid var(--line); border-radius: 12px; overflow: hidden; } -.tbl th, .tbl td { padding: 12px 14px; text-align: left; border-bottom: 1px solid var(--line); } -.tbl thead th { font-family: var(--mono); font-size: 11.5px; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); background: var(--panel-2); } -.tbl tbody tr:last-child td { border-bottom: 0; } -.tbl td.before { color: var(--ink-2); } -.tbl td.after { color: var(--ink); } -.tbl .win { color: var(--green); font-weight: 600; } -.tbl .num { font-family: var(--mono); } - -/* Before → after pair */ -.ba { display: grid; grid-template-columns: 1fr auto 1fr; gap: 16px; align-items: stretch; margin: 20px 0; } -@media (max-width: 720px) { .ba { grid-template-columns: 1fr; } .ba .arrow { transform: rotate(90deg); justify-self: center; } } -.ba .card { border: 1px solid var(--line); border-radius: 14px; padding: 18px; background: var(--bg-2); } -.ba .card.b { border-top: 3px solid var(--red); } -.ba .card.a { border-top: 3px solid var(--green); } -.ba .card h5 { font-family: var(--mono); font-size: 11.5px; letter-spacing: .08em; text-transform: uppercase; margin: 0 0 10px; } -.ba .card.b h5 { color: var(--red); } -.ba .card.a h5 { color: var(--green); } -.ba .card p { font-size: 14px; margin: 0; color: var(--ink-2); } -.ba .arrow { align-self: center; color: var(--cyan); font-size: 26px; } - -/* ---- Use-case gallery ----------------------------------------------------- */ -.gallery-intro { margin-bottom: 18px; } -.uc { border: 1px solid var(--line); border-radius: 14px; background: var(--panel); margin-bottom: 14px; overflow: hidden; } -.uc[open] { border-color: var(--line-strong); box-shadow: var(--glow-cyan); } -.uc > summary { list-style: none; cursor: pointer; display: flex; align-items: center; gap: 14px; padding: 16px 20px; } -.uc > summary::-webkit-details-marker { display: none; } -.uc > summary:hover { background: var(--panel-2); } -.uc .uc-n { font-family: var(--mono); font-size: 12px; color: var(--on-accent); width: 26px; height: 26px; display: grid; place-items: center; border-radius: 8px; flex: none; } -.uc .uc-n.b1 { background: var(--violet); } .uc .uc-n.b2 { background: var(--blue); } -.uc .uc-n.b3 { background: var(--cyan); } .uc .uc-n.b4 { background: var(--green); } -.uc .uc-n.b5 { background: var(--yellow); } .uc .uc-n.b6 { background: var(--orange); } -.uc .uc-n.b7 { background: var(--red); } .uc .uc-n.b8 { background: var(--indigo); } -.uc .uc-t { font-family: var(--display); font-weight: 600; font-size: 16.5px; color: var(--ink); flex: 1; } -.uc .uc-tag { font-family: var(--mono); font-size: 11px; color: var(--muted); padding: 3px 9px; border: 1px solid var(--line); border-radius: 20px; } -@media (max-width: 600px) { .uc .uc-tag { display: none; } } -.uc .chev { width: 18px; height: 18px; color: var(--muted); transition: transform .2s var(--ease); flex: none; } -.uc[open] .chev { transform: rotate(180deg); color: var(--cyan); } -.uc .uc-body { padding: 4px 20px 22px; } -.uc .uc-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-top: 8px; } -@media (max-width: 760px) { .uc .uc-grid { grid-template-columns: 1fr; } } -.uc .uc-meta p { margin: 6px 0; font-size: 14.5px; color: var(--ink-2); } -.uc .uc-meta .k { font-family: var(--mono); font-size: 11px; letter-spacing:.06em; text-transform: uppercase; color: var(--cyan); display:block; } - -/* ---- Drop-in file tree ---------------------------------------------------- */ -.tree { font-family: var(--mono); font-size: 13px; line-height: 1.9; background: #05050a; border: 1px solid var(--ridge); border-radius: 14px; padding: 20px; overflow-x: auto; margin: 18px 0; } -.tree .root { color: var(--ink); font-weight: 500; } -.tree .br { color: var(--faint); } -.tree .f { color: var(--cyan); } -.tree .d { color: var(--violet); } -.tree .cmt { color: var(--muted); } -.tree .heart { color: var(--red); } -.tree .group { color: var(--green); } -/* drop-in smart-zip: studio media highlighted so a downloader can't miss it (D13/V) */ -.tree .studio { color: #ffce54; font-weight: 600; } -.tree .play { color: #ffce54; font-weight: 700; } -.tree-row.hl { display: block; background: rgba(255,206,84,.07); border-left: 3px solid #ffce54; padding: 1px 10px; margin: 1px -10px 1px -13px; border-radius: 0 6px 6px 0; } -.studio-note { margin: 18px 0; padding: 16px 18px; background: rgba(255,206,84,.06); border: 1px solid rgba(255,206,84,.35); border-radius: 14px; } -.studio-note .studio-lead { margin: 0 0 8px; font-weight: 600; color: #ffce54; } -.studio-note ul { margin: 0; padding-left: 20px; } -.studio-note li { margin: 4px 0; color: var(--ink-2); } -.studio-note .tag { font-family: var(--mono); font-size: 11px; color: var(--muted); border: 1px solid var(--ridge); border-radius: 6px; padding: 1px 6px; margin-left: 6px; } -.dl-cta { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; margin: 20px 0; } -.dl-cta .dl-meta { color: var(--muted); font-size: 13px; } - -/* NotebookLM studio hero — prominent public-notebook link */ -.studio-hero { - position: relative; overflow: hidden; - margin: 4px 0 26px; padding: 26px 26px 22px; - border: 1px solid var(--line-strong); border-radius: 18px; - background: - radial-gradient(120% 140% at 8% 0%, rgba(160,107,255,.16), transparent 52%), - radial-gradient(120% 160% at 100% 100%, rgba(31,214,214,.14), transparent 55%), - var(--panel); - box-shadow: var(--shadow); -} -.studio-hero::before { - content: ""; position: absolute; left: 0; top: 0; right: 0; height: 3px; - background: var(--spectrum); -} -.studio-hero-glow { position: absolute; inset: -40% -10% auto auto; width: 320px; height: 320px; - background: radial-gradient(circle, rgba(79,140,255,.18), transparent 65%); filter: blur(8px); pointer-events: none; } -.studio-hero-kicker { position: relative; margin: 0 0 6px; font-family: var(--mono); font-size: 11px; - letter-spacing: .04em; text-transform: uppercase; color: var(--cyan); } -.studio-hero-title { position: relative; margin: 0 0 8px; font-size: clamp(20px, 3.2vw, 28px); color: var(--ink); } -.studio-hero-sub { position: relative; margin: 0 0 18px; max-width: 62ch; color: var(--ink-2); } -.studio-hero-cta { position: relative; display: flex; flex-wrap: wrap; gap: 12px; align-items: center; } -.studio-hero-cta .btn-primary { font-size: 15px; padding: 13px 22px; } -.studio-chips { position: relative; display: flex; flex-wrap: wrap; gap: 8px; margin: 16px 0 0; padding: 0; list-style: none; } -.studio-chips li { font-family: var(--mono); font-size: 12px; color: var(--ink-2); - padding: 5px 11px; border: 1px solid var(--line); border-radius: 20px; background: var(--bg-2); } - -/* studio media embeds (video / slides / infographic) */ -.studio-media { display: grid; gap: 18px; margin: 20px 0 6px; } -.studio-media .sm-card { border: 1px solid var(--line); border-radius: 14px; background: var(--bg-2); padding: 16px 18px; } -.studio-media .sm-card h4 { margin: 0 0 4px; color: var(--ink); display: flex; align-items: center; gap: 8px; } -.studio-media .sm-card p { margin: 0 0 12px; color: var(--muted); font-size: 13px; } -.studio-media video { width: 100%; border-radius: 10px; display: block; background: #000; border: 1px solid var(--ridge); } -.studio-media .sm-infographic img, .studio-media .sm-slides img { width: 100%; border-radius: 10px; display: block; border: 1px solid var(--ridge); margin-bottom: 4px; } -.studio-media .sm-slides a { display: block; transition: transform .15s ease; } -.studio-media .sm-slides a:hover { transform: translateY(-2px); } -.studio-media .sm-actions { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 12px; } - -/* steps */ -.steps { counter-reset: step; list-style: none; padding: 0; margin: 20px 0; } -.steps li { counter-increment: step; position: relative; padding: 14px 16px 14px 56px; border: 1px solid var(--line); border-radius: 12px; margin-bottom: 12px; background: var(--bg-2); } -.steps li::before { content: counter(step); position: absolute; left: 14px; top: 14px; width: 28px; height: 28px; border-radius: 9px; display: grid; place-items: center; font-family: var(--mono); font-weight: 600; font-size: 14px; color: var(--on-accent); background: var(--spectrum); } -.steps li strong { color: var(--ink); } - -/* ---- Footer --------------------------------------------------------------- */ -.footer { border-top: 1px solid var(--line); padding: 44px 0 60px; margin-top: 30px; } -.footer .cols { display: grid; grid-template-columns: 1.4fr 1fr 1fr; gap: 28px; } -@media (max-width: 760px) { .footer .cols { grid-template-columns: 1fr; } } -.footer h6 { font-family: var(--mono); font-size: 11px; letter-spacing: .12em; text-transform: uppercase; color: var(--faint); margin: 0 0 12px; } -.footer a { color: var(--ink-2); display: block; padding: 4px 0; font-size: 14px; } -.footer a:hover { color: var(--green); } -.footer .credit { font-size: 14px; color: var(--muted); line-height: 1.7; } -.footer .credit b { color: var(--ink); } -.footer .fine { font-family: var(--mono); font-size: 11.5px; color: var(--faint); margin-top: 28px; padding-top: 20px; border-top: 1px solid var(--line); } - -/* utility */ -.center { text-align: center; } -.muted { color: var(--muted); } -.kbd { font-family: var(--mono); font-size: .85em; background: var(--panel-2); border: 1px solid var(--line); border-radius: 5px; padding: 1px 6px; } - -/* Reduced motion */ -@media (prefers-reduced-motion: reduce) { - * { scroll-behavior: auto !important; transition: none !important; animation: none !important; } -} diff --git a/ruv-explainer-photonlayer/vercel.json b/ruv-explainer-photonlayer/vercel.json deleted file mode 100644 index d24f6dc..0000000 --- a/ruv-explainer-photonlayer/vercel.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "$schema": "https://openapi.vercel.sh/vercel.json", - "cleanUrls": true, - "trailingSlash": false, - "headers": [ - { - "source": "/assets/(.*)", - "headers": [ - { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" } - ] - }, - { - "source": "/(.*)", - "headers": [ - { "key": "X-Content-Type-Options", "value": "nosniff" }, - { "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" } - ] - } - ] -} diff --git a/ruv-explainer-rufield/.gitignore b/ruv-explainer-rufield/.gitignore deleted file mode 100644 index 44727e3..0000000 --- a/ruv-explainer-rufield/.gitignore +++ /dev/null @@ -1,15 +0,0 @@ -# Binaries & bundles are NOT committed here [Constraint H] — they ship via GitHub Release. -downloads/*.zip -*.zip -*.rvf -*.rvf.lock -*.embed.json - -# Optional self-hosted font binaries (the page falls back to system stacks if absent). -assets/fonts/*.woff2 - -# Tooling noise -node_modules/ -.vercel/ -.DS_Store -*.log diff --git a/ruv-explainer-rufield/README.md b/ruv-explainer-rufield/README.md deleted file mode 100644 index 3a643c2..0000000 --- a/ruv-explainer-rufield/README.md +++ /dev/null @@ -1,56 +0,0 @@ -# ruv-explainer-rufield - -A plain-language **ExplainerSite** for **RuField MFS** (`ruvnet/rufield`) — the open -specification plus working Rust reference build for **camera-free multimodal field -sensing**: turning the invisible WiFi / radar / heat signals already in a room into -privacy-labelled, provenance-signed, fusion-ready facts (*present · sitting · got out -of bed · left*) — with no camera and no microphone. - -- **Source of truth (content):** `content/rufield.canon.md` -- **Upstream repo:** by Reuven Cohen ([@ruvnet](https://github.com/ruvnet)), MIT. -- **Provenance shown on page:** Updated 2026-06-19 · source `@ 509d8ae` · `rufield.mfs.v0.1`. - -## What's here - -Static site — no build, no dependencies, no framework. - -``` -index.html 8 collapsible numbered sections (learning arc) + hero + footer -styles.css FIELD/SIGNAL theme: deep slate-charcoal + signal-violet/magenta -main.js progressive enhancement (deep-link sections, dropzone stub) -favicon.svg a violet field-wave mark -vercel.json static headers (immutable assets, woff2, zip) -package.json metadata only (no scripts) -robots.txt allow all + sitemap pointer -assets/img/ g1–g6 friendly raster art (+ optimized prompts) — gate-E tier -assets/diagrams/ (reserved; technical diagrams are authored INLINE in index.html) -assets/fonts/ optional self-hosted woff2 (system fallbacks ship by default) -downloads/ the drop-in .zip lands here at publish (gitignored) -``` - -## Aesthetic [Constraint K — distinct per repo] - -Deep **slate-charcoal** (cool blue-grey, never warm) with **signal-violet → magenta** -accents and **waveform / field** motifs. Type: **Space Grotesk** over **Inter** / -**JetBrains Mono**. Deliberately unlike the MetaHarness amber/copper foundry site and -unlike the cognitum cyan. - -## Dual-level visuals [D15-E] - -Every section carries **both**: -1. a **precise technical SVG** — authored inline, accurate to the real 7-crate - architecture / pipeline / privacy ladder, labelled and source-cited; and -2. a **simple, friendly illustration** — either a generated raster (g1–g6) or a - friendly inline SVG — that makes the idea approachable. - -## Local preview - -``` -cd ruv-explainer-rufield -python3 -m http.server 8000 -# open http://localhost:8000/ -``` - -## Deploy - -Vercel, git-connected, auto-deploy on push → `ruv-explainer-rufield.vercel.app`. diff --git a/ruv-explainer-rufield/assets/diagrams/.gitkeep b/ruv-explainer-rufield/assets/diagrams/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/ruv-explainer-rufield/assets/fonts/.gitkeep b/ruv-explainer-rufield/assets/fonts/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/ruv-explainer-rufield/assets/img/g1.png b/ruv-explainer-rufield/assets/img/g1.png deleted file mode 100644 index 4d45c34..0000000 Binary files a/ruv-explainer-rufield/assets/img/g1.png and /dev/null differ diff --git a/ruv-explainer-rufield/assets/img/g1.prompt.txt b/ruv-explainer-rufield/assets/img/g1.prompt.txt deleted file mode 100644 index 1532b7d..0000000 --- a/ruv-explainer-rufield/assets/img/g1.prompt.txt +++ /dev/null @@ -1,16 +0,0 @@ -g1.png — HERO (16:9). RuField "the field made visible." -PROMPT: -Soft, warm editorial illustration of a cozy living room at night, viewed in calm -three-quarter perspective. A gentle human silhouette sits relaxed in an armchair -reading. The invisible signals in the air are made visible as soft, glowing -violet-and-magenta waveforms — concentric ripples and flowing sine-wave bands — -rippling gently outward through the whole room and softly wrapping around the -person, like warm aurora light. ABSOLUTELY NO camera, no lens, no surveillance -device anywhere. Deep slate-charcoal background (cool blue-grey #14161f to #0e1018), -NOT warm, NOT amber, NOT orange. Accent glow strictly signal-violet (#a855f7) and -magenta (#e84ef0) with the faintest cool indigo. Inviting, peaceful, human, a -little magical — the feeling of a home gently watching over someone without ever -looking at them. Subtle film grain, soft bloom, generous negative space at the top -for a website headline. High-end, premium, calm. No text. -RATIONALE (gate-E): leads with the human warmth ("home watching over you"), makes -the abstract "field" concrete and friendly, locks the distinct slate+violet palette. diff --git a/ruv-explainer-rufield/assets/img/g2.png b/ruv-explainer-rufield/assets/img/g2.png deleted file mode 100644 index 0aa1a6b..0000000 Binary files a/ruv-explainer-rufield/assets/img/g2.png and /dev/null differ diff --git a/ruv-explainer-rufield/assets/img/g2.prompt.txt b/ruv-explainer-rufield/assets/img/g2.prompt.txt deleted file mode 100644 index 5fe513d..0000000 --- a/ruv-explainer-rufield/assets/img/g2.prompt.txt +++ /dev/null @@ -1,16 +0,0 @@ -g2.png — GROUNDING EXAMPLE: Margaret & Priya (16:9). -PROMPT: -Warm, tender split-scene illustration in soft editorial style. LEFT: an elderly -woman, peaceful and dignified, safe in her own softly-lit bedroom at night, just -getting up from bed — calm and unwatched. RIGHT: in a different home, her adult -daughter sits on a sofa looking with relief at her phone, which shows a simple -reassuring status card reading "Mum is moving normally tonight" with a small calm -green dot. The two rooms are gently connected across the middle by soft flowing -violet-and-magenta signal-waves carrying not pictures but a single gentle glowing -fact. ABSOLUTELY NO camera, no video feed, no image-of-a-person on the phone — -only a friendly status line. Deep slate-charcoal background (cool blue-grey -#14161f), NOT warm/amber. Accent glow signal-violet (#a855f7) and magenta -(#e84ef0). Loving, reassuring, respectful of the elder's privacy; the emotional -core is relief and dignity. Soft bloom, gentle grain. No camera. Minimal extra text. -RATIONALE (gate-E): the named before→after persona; shows "the answer without the -image"; emotionally lands "oh, that's what it's for." diff --git a/ruv-explainer-rufield/assets/img/g3.png b/ruv-explainer-rufield/assets/img/g3.png deleted file mode 100644 index 04e4701..0000000 Binary files a/ruv-explainer-rufield/assets/img/g3.png and /dev/null differ diff --git a/ruv-explainer-rufield/assets/img/g3.prompt.txt b/ruv-explainer-rufield/assets/img/g3.prompt.txt deleted file mode 100644 index 7f1aaee..0000000 --- a/ruv-explainer-rufield/assets/img/g3.prompt.txt +++ /dev/null @@ -1,15 +0,0 @@ -g3.png — FUSION: common sense from many clues (16:9). -PROMPT: -Friendly, approachable flat-with-depth illustration of "three weak guesses becoming -one confident answer." Three small, charming sensor characters stand together like -gentle teammates, each whispering a soft uncertain guess shown as a thin wavy -thread: (1) a little WiFi-wave character emitting concentric ripples, (2) a tiny -rounded radar chip with a soft sonar arc, (3) a small warm thermal dot glowing -gently. Their three soft violet-and-magenta wave-threads flow inward and merge into -ONE bright, confident glowing answer bubble in the center reading "someone is here". -The merge feels like friends nodding in agreement. Deep slate-charcoal background -(cool blue-grey #14161f), NOT warm/amber. Strictly signal-violet (#a855f7) and -magenta (#e84ef0) glows, faint indigo. Warm, simple, a touch playful, very -approachable — like a kids'-book explanation of teamwork. Soft bloom, rounded forms. -RATIONALE (gate-E): turns "sensor fusion / weighted Bayes" into the everyday idea -of combining weak clues into one sure answer; friendly, not technical. diff --git a/ruv-explainer-rufield/assets/img/g4.png b/ruv-explainer-rufield/assets/img/g4.png deleted file mode 100644 index f744b34..0000000 Binary files a/ruv-explainer-rufield/assets/img/g4.png and /dev/null differ diff --git a/ruv-explainer-rufield/assets/img/g4.prompt.txt b/ruv-explainer-rufield/assets/img/g4.prompt.txt deleted file mode 100644 index 7cc62d5..0000000 --- a/ruv-explainer-rufield/assets/img/g4.prompt.txt +++ /dev/null @@ -1,15 +0,0 @@ -g4.png — PRIVACY + PROVENANCE: the guard and the seal (16:9). -PROMPT: -Warm, trustworthy illustration of "sensitive things stay home, and every fact gets -a tamper-proof seal." A cozy little house outline glows softly on the left; inside -it, several glowing data-droplets each wear a small colored privacy badge (a tiny -P-label). A gentle, friendly gatekeeper figure stands at the doorway: the most -sensitive, deeply-colored droplets are kindly held back inside the house, while -only the calm, light "plain-fact" droplets are allowed out — and as each one -leaves, the gatekeeper presses a glowing violet wax-seal "verified" receipt onto -it. One droplet shows a broken seal being gently turned away. Deep slate-charcoal -background (cool blue-grey #14161f), NOT warm/amber. Signal-violet (#a855f7) and -magenta (#e84ef0) accents. The mood is safe, caring, and honest — privacy as -kindness, not as a cold corporate lock. Soft rounded shapes, gentle bloom. -RATIONALE (gate-E): makes "privacy classes P0–P5 + ed25519 provenance receipts" -feel like a caring doorkeeper and a trust-sticker; warm, not corporate. diff --git a/ruv-explainer-rufield/assets/img/g5.png b/ruv-explainer-rufield/assets/img/g5.png deleted file mode 100644 index 68b6113..0000000 Binary files a/ruv-explainer-rufield/assets/img/g5.png and /dev/null differ diff --git a/ruv-explainer-rufield/assets/img/g5.prompt.txt b/ruv-explainer-rufield/assets/img/g5.prompt.txt deleted file mode 100644 index b31c736..0000000 --- a/ruv-explainer-rufield/assets/img/g5.prompt.txt +++ /dev/null @@ -1,14 +0,0 @@ -g5.png — THE DROP-IN: one download, two halves (16:9). -PROMPT: -Inviting, simple illustration of a single friendly parcel/package gently splitting -into two soft-glowing halves. LEFT half labelled feeling "for you": a relaxed -person comfortably reading a friendly illustrated guide. RIGHT half labelled -feeling "for your AI": a gentle, kind glowing brain holding a small magnifying glass -as it happily searches a neat little stack of knowledge cards. The two halves are -joined by soft flowing violet-and-magenta signal-waves so they clearly came from -one package. Deep slate-charcoal background (cool blue-grey #14161f), NOT warm/amber. -Signal-violet (#a855f7) and magenta (#e84ef0) glows. Warm, simple, welcoming, very -low-friction — the feeling of "this is easy, here are your two gifts." Rounded -shapes, soft bloom, plenty of calm space. -RATIONALE (gate-E): mirrors the Cognitum "one download, two halves" on-ramp in a -friendly way; pairs with the precise file-tree SVG that shows the real contents. diff --git a/ruv-explainer-rufield/assets/img/g6.png b/ruv-explainer-rufield/assets/img/g6.png deleted file mode 100644 index 64cbf5a..0000000 Binary files a/ruv-explainer-rufield/assets/img/g6.png and /dev/null differ diff --git a/ruv-explainer-rufield/assets/img/g6.prompt.txt b/ruv-explainer-rufield/assets/img/g6.prompt.txt deleted file mode 100644 index ea0beca..0000000 --- a/ruv-explainer-rufield/assets/img/g6.prompt.txt +++ /dev/null @@ -1,13 +0,0 @@ -g6.png — SOCIAL CARD (16:9, used at 1200x630). -PROMPT: -Minimal, premium social-share hero. A single elegant, glowing violet-and-magenta -waveform — a smooth flowing sine ribbon with concentric field-ripples — sweeps -gracefully across a deep slate-charcoal canvas (cool blue-grey #0e1018 to #14161f), -NOT warm, NOT amber, NOT copper. The waveform feels alive and calm, like a heartbeat -of a quiet room. Generous negative space, cinematic, high-end, restrained. Faint -indigo depth, soft bloom on the wave crest. The overall impression evokes -"the answer a camera would give you — without anyone ever being watched": -quiet, trustworthy, sophisticated. Leave clear open space for an overlaid title. -Strictly signal-violet (#a855f7) + magenta (#e84ef0) on slate. No camera. No text. -RATIONALE (gate-E): distinct premium identity (waveform, not foundry coin), locks -the slate+violet brand for link previews; deliberately unlike any amber/charcoal site. diff --git a/ruv-explainer-rufield/downloads/.gitkeep b/ruv-explainer-rufield/downloads/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/ruv-explainer-rufield/favicon.svg b/ruv-explainer-rufield/favicon.svg deleted file mode 100644 index bbbce7c..0000000 --- a/ruv-explainer-rufield/favicon.svg +++ /dev/null @@ -1,26 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ruv-explainer-rufield/index.html b/ruv-explainer-rufield/index.html deleted file mode 100644 index 39d5efc..0000000 --- a/ruv-explainer-rufield/index.html +++ /dev/null @@ -1,1519 +0,0 @@ - - - - - - RuField MFS — the answer a camera would give you, without anyone being watched - - - - - - - - - - - - - - - - - - - - - - - - -
-
-

- A plain-language explainer for - ruvnet/rufield - by Reuven Cohen - (@ruvnet). - Not affiliated — an independent walkthrough of the open-source project (MIT). -

-

- - Updated 2026-06-19 · source @ 509d8ae · rufield.mfs.v0.1 -

-
-
- - -
- -
- - -
-
-
-

ruvnet · rufield · multimodal field sensing

-

The answer a camera
would give you —
without being watched.

-

- RuField is a free, open standard — plus a working Rust build — - for camera-free room sensing. It takes the invisible - signals already bouncing around a room (your WiFi, a tiny radar chip, a - cheap heat sensor) and turns them into one plain-English stream of facts: - someone is present · they sat down · they got out of bed · - they left the room. No camera. No microphone. A privacy label and a - tamper-proof signature on every single reading. -

- - -
- A cozy living room at night. Soft glowing violet and magenta waveforms ripple gently through the air and wrap around a person reading calmly in an armchair. There is no camera anywhere — the invisible signals in the room are simply made visible as warm light. -
-
-
- - -
-
- - -
- - 01 - -

What it is — and who it’s for

- Start here — the plain-English version, anchored to one real person. -
- -
-
-

- Two words in the name do all the work. Let’s demystify both, then - meet someone it actually helps. -

-

- “Field” = the invisible signals all around - you right now. Your WiFi is constantly bouncing radio waves off - everything in the room. A $10 radar chip sees motion through the air. A - cheap thermal sensor sees body heat. When a person moves — even - slightly — all of these change. That changing pattern is - the “field.” -

-

- “MFS” (Multimodal Field Sensing Specification) - = an agreed-upon format so every one of those different sensors - speaks the same language. Today WiFi, radar, and thermal - each spit out their own incompatible gibberish. RuField is the translator - that turns all of them into one tidy event anyone can read and combine. -

-

- Think of it as “USB for room-sensing.” Before - USB, every device had its own weird plug; USB was just an agreement - on the shape of the plug, and suddenly anything worked with anything. - RuField is one agreed-upon shape so any sensor’s reading drops into - any app. It is not a new gadget and not a new radio — - it sits above the standards you may have heard of (WiFi sensing / - 802.11bf, radar, UWB) and makes their outputs fit together. -

- -

Meet Margaret — the “oh, that’s what it’s for” moment

-

- Margaret is 78 and lives alone. Her daughter Priya worries about - night-time falls and bathroom trips — but Margaret flatly refuses - cameras in her home, and she’s right to. -

- - -

Technical view — the before → after, as the real data flow

-
- - Before and after RuField, shown as the real pipeline - Before RuField, the only ways to know if Margaret is okay are a camera (vetoed) or a panic button she must reach. After RuField, three camera-free sensors feed invisible signals into a fusion engine that emits plain room-state facts; raw signals stay on-device as privacy class P0, breathing is gated as P4 requiring consent, and every fact carries a signed ed25519 receipt before it reaches Priya's app. - - - - The answer, without the image - - - BEFORE — no dignified way to know - - Option A — a camera - Margaret vetoes it · nobody wants one in a bedroom - - Option B — a panic button - Useless if she’s fallen and can’t reach it - - So Priya just worries. - No way to ask “is Mum up and moving normally tonight?” - - - AFTER — the field, fused into facts - - - WiFi CSI - - mmWave radar - - thermal IR - - - - - - - - - - - - RuField fusion engine - weighted Bayes · temporal windows - - - - Plain room-state facts - present · sitting · breathing · in bed · got out of bed · left - each fact: a privacy class + a signed ed25519 receipt - - - - P0 raw - stays on-device - - P4 breathing - needs consent - - P2 facts - verified → app - - - - - Priya’s app - “Mum is moving normally tonight.” - -
- Technical view: three camera-free sensors → the RuField fusion - engine → plain facts. Raw signals (P0) - never leave the house; breathing (P4) is - consent-gated; occupancy facts (P2) are - signed, verified, and only then shown to Priya. (Source: ADR-260 §19; - room_state.toml; rufield-privacy.) -
-
- - -

Friendly view — the same story, in a picture

-
- Left: Margaret, peaceful and dignified, getting up from her bed at night in her own softly-lit room, completely unwatched. Right: in another home, her daughter Priya smiles with relief at her phone, which shows a calm status line reading 'Mum is moving normally tonight' with a small green dot. A soft violet signal-wave links the two rooms, carrying a single reassuring fact — not a picture. There is no camera anywhere. -
- The same thing in plain feeling: Margaret is never watched — there - is no image, ever — yet Priya finally knows her mother is moving - normally tonight. -
-
- -

- Before RuField, Priya’s only real options were a - camera (vetoed) or a panic button Margaret has to remember to wear and - press — useless if she’s fallen and can’t reach it. So - Priya just worried. -

-

- After RuField, a few cheap, camera-free sensors sit in - the corners. RuField fuses their invisible signals into plain facts. - The raw signals never leave Margaret’s house (they’re privacy - class P0, which the system refuses to - transmit by default). A sensitive health reading like breathing - is P4 and stays off unless Margaret - explicitly consents. Every fact carries a signed receipt, so a tampered - “she’s fine” can’t be faked. -

-

- The line that makes it land: it’s how you get - the answer a camera would give you — “is everything okay in - there?” — without anyone ever being watched. -

- -
- - Honest note on this example. v0.1’s room-state - demo runs on a synthetic simulator, and the one - real-signal path (CsiReplayAdapter) is recorded - WiFi replayed from a file — a physically-grounded proxy, - not validated accuracy. The architecture, privacy - enforcement, and provenance are real and working today; the - field-accuracy numbers that would let you trust this with a real - Margaret need the hardware adapters v0.1 deliberately does not yet ship. - (Source: README L13–25; ADR-260 “Honest statement.”) - -
-
-
- - -
- - 02 - -

The problem it solves — and why now

- Why does this need to exist, and why does it matter today? -
- -
-
-

- The useful information — “Grandma got out of bed at 3am and - hasn’t come back” — usually requires a camera, - and a camera in a bedroom or bathroom is a non-starter. RuField gives you - the answer without the image: nobody is ever watched; the - system only knows “a person is here,” never “here is a - picture of them.” -

-

- There’s a second, quieter problem. Every kind of sensor talks a - different language, and every team that wants to combine - them reinvents the same plumbing — calibration, fusion, privacy - rules, anti-spoofing — by hand, badly. WiFi sensing, radar, and - thermal are each “locked into modality-specific silos” with no - common format, which prevents reliable fusion and makes governance - weak. (Source: ADR-260 §4.) -

-

- Why now? Because WiFi sensing is about to be everywhere - — in homes, hospitals, offices. If that’s coming, it needs a - common, privacy-first, provable format the way the early web needed HTTP. - RuField is a bid to be that shared layer, with privacy and - provenance built in from day one rather than bolted on after the - scandal. (Source: ADR-260 §21 decision matrix; §25.) -

- - -

Technical view — three silos vs one common event format

-
- - Modality silos versus one shared RuField event model - Today WiFi, radar and thermal each emit their own incompatible format, so they cannot be fused and governance is weak. RuField defines one common FieldEvent — typed feature, privacy class, and a signed provenance receipt — that every sensor maps into, enabling reliable fusion and consistent privacy and provenance. - - - - - - - From incompatible silos to one shared event - - - TODAY — three silos, no common shape - - WiFi - its own format - - radar - its own format - - thermal - its own format - - - can’t fuse reliably - weak governance · everyone rebuilds the glue - - ✗ - - - - RuField - - - RUFIELD — one common FieldEvent - - WiFi - - radar - - thermal - - UWB · IR · - future - - - - - - - one FieldEvent (the “USB plug” shape) - - typed feature - presence, range… - - privacy class - P0 … P5 - - signed receipt - ed25519 - - - - reliable fusion · consistent privacy & provenance - - - RuField sits ABOVE existing radio standards (802.11bf, UWB, radar) — it makes their outputs fit, it does not replace them. - Source: ADR-260 §1-2, §4-5; README L51-54 - -
- The core idea, precisely: RuField doesn’t build a new sensor — - it defines one common FieldEvent (a typed feature + a - privacy class + a signed receipt) that every modality maps into, which - is what finally makes fusion, privacy, and provenance consistent across - all of them. -
-
- - -

Friendly view — it’s “USB for room-sensing”

-
- - USB-style metaphor: many odd plugs become one shared shape - A friendly illustration. On the left, three sensors each have their own odd-shaped plug that fits nothing. On the right, RuField gives them all one shared rounded plug shape, so any sensor drops neatly into any app — just like USB did for devices. - - Before USB, every plug was weird. Then everything just fit. - - - Before: incompatible plugs - - - WiFi - - - radar - - - heat - - None of them fit the same socket ✗ - - - - - - After RuField: one shared plug - - WiFi - - radar - - heat - - - - - - - - any app - Every sensor drops into any app ✓ - One agreed shape — that’s the whole trick. RuField is the agreement, not a new device. - -
- The same point with no jargon: RuField is an agreement on the shape - of the plug. Once everyone agrees, any sensor’s reading drops - into any app — exactly what USB did for gadgets. -
-
-
-
- - -
- - 03 - -

How it works

- From an invisible wobble in the air to a signed, plain-English fact. -
- -
-
-

- The heart of RuField is one idea you already use every day: - “fusion” just means common sense from many clues. - No single sensor is sure. WiFi thinks someone’s there; - radar agrees; the thermal sensor sees warmth in the same spot. Combine - the three weak guesses and you get one confident answer — exactly - how you use sight, sound, and touch together. (Source: - room_state.toml; ADR-260 §12–13.) -

-

- Here’s the whole journey, stage by stage, from a real signal to a - fact you can trust. -

- - -

Technical view — the real reference pipeline (the 7 crates)

-
- - The RuField reference pipeline across its seven crates - Raw signal enters an adapter (rufield-adapters), which calibrates an empty-room baseline and emits a signed FieldEvent built on rufield-core's data model. A provenance gate (rufield-provenance, is_fusable) admits only events with a verifying ed25519 receipt or an explicit synthetic flag. Admitted events enter the fusion engine (rufield-fusion) which applies room_state.toml rules — weighted Bayes and temporal windows — to infer room-state. A privacy guard (rufield-privacy) caps each inference's privacy class and enforces P0-denied, P4-consent, P5-identity-bound rules before output. rufield-bench scores the whole pipeline against synthetic ground truth; rufield-viewer renders it live in the browser. - - - - - - - - - - Signal → signed FieldEvent → fused, privacy-capped room-state - - - - 1 · Raw signal - WiFi CSI · radar · thermal - a wobble in the air - - - - 2 · Adapter + calibrate - learn empty-room baseline, - emit a SIGNED FieldEvent - rufield-adapters · -core - - - - 3 · Provenance gate - is_fusable(): admit ONLY if - ed25519 verifies (or synthetic) - rufield-provenance - - - - forged / altered? - receipt fails → - never fused ✗ - - - - - - - - admitted events - - - - 4 · Fusion engine — common sense from many clues - rufield-fusion · rules/room_state.toml - - - weighted_bayes - presence · sitting · breathing - - temporal_window - bed_exit · room_transition - - per-rule threshold - + privacy_max cap - - WiFi “maybe” + radar “maybe” + heat “maybe” - - - → one confident inference + confidence score - - - - - - - 5 · Privacy guard — caps + enforces before anything leaves - rufield-privacy · authorize(class, destination, consent, identity) - - P0 raw → network DENIED - - P4 health → needs consent - - P5 identity → bound + logged - - - - - Room-state fact: signed · privacy-capped · ready to read - -
- The real journey: rufield-adapters + -core emit - a signed event → rufield-provenance admits only verified - ones → rufield-fusion applies the - room_state.toml rules (weighted Bayes + temporal windows) - → rufield-privacy caps and gates the result before it - leaves. (rufield-bench scores it; rufield-viewer - renders it.) -
-
- - -

Friendly view — three weak guesses, one confident answer

-
- Three small, friendly sensor characters — a WiFi-wave, a little radar chip, and a warm thermal dot — each whisper an uncertain guess ('maybe movement?', 'echo... something?', 'warm spot... person?'). Their three soft violet and magenta wave-threads flow inward and merge into one bright, confident glowing bubble that reads 'someone is here.' -
- No single sensor is sure. Put their three weak “maybe”s - together — the way you’d trust three friends who all saw the - same thing — and you get one confident answer. That’s - fusion. -
-
-
-
- - -
- - 04 - -

What a solved state looks like

- When it’s working, what do you actually see — and what changed? -
- -
-
-

- A “solved” RuField looks like a calm dashboard you can read at - a glance. The reference build ships a live viewer you can - run today (cargo run -p rufield-viewer) that replays a room - waking up — enter → sit → breathe → sleep → - scratch → bed-exit → leave — tick by tick, in your - browser, with no build step. -

-

- Two things sit on top of every event, and they’re the whole point: - a colour-coded privacy badge (P0 - … P5) and a click-to-inspect - signed receipt (✓/✗). An honest - SYNTHETIC banner tells you the demo’s sensors are - simulated, so you’re never misled. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Before → after: the same night, with and without RuField
The momentBefore RuFieldAfter RuField
Knowing if someone’s up at 3amA camera (vetoed) or a worried phone call“Got out of bed” appears as a plain, signed fact
What’s actually capturedA literal image of a person in a bedroomNo image, ever — only “a person is here”
Where the raw data goesOften streamed to a cloud you don’t controlRaw signal is P0 — refused off-device by default
Health-style readings (breathing)On or off with no clear consent boundaryP4 — off unless explicitly consented
Trusting an “all-clear”No way to tell a real reading from a faked oneEvery fact carries a tamper-proof signature you can verify
- - -

Technical view — the live viewer’s four panels

-
- - The rufield-viewer dashboard layout - A browser dashboard with a SYNTHETIC banner. Top-left: a room-state panel showing live facts. Top-right: an event stream where each event has a colour-coded privacy badge P0 to P5. Bottom-left: a fusion graph showing which signals support each conclusion. Bottom-right: a provenance inspector showing a signed receipt with a checkmark for verified or a cross for unverified events, which are never fused. - - - - - - http://localhost:8088/ - - - - SYNTHETIC — simulated sensors, no hardware - - - - Room-state - ● person present - ● sitting - ● in bed - ● breathing (consented) - ● got out of bed - enter → sit → breathe → sleep → bed-exit → leave - - - - Event stream - - P2 - presence ✓ - P4 - breathing ✓ - P0 - raw frame (kept on-device) - P2 - bed-exit ✓ - ! - unverified event ✗ never fused - - - - - Fusion graph - WiFi - radar - heat - - - - “person present” 0.91 - which signals support each conclusion - - - - Provenance inspector - - ✓ verified - sha256 ✓ · ed25519 sig ✓ · sensor key #03 - - ✗ tampered - one byte changed after signing → rejected - -
- What “solved” looks like on screen: a calm room-state panel, - an event stream where every event wears a privacy badge, a - fusion graph showing which signals backed each conclusion, and a - provenance inspector where a tampered event fails the check and is never - fused. (Source: README L96–152.) -
-
- - -

Friendly view — the kindly gatekeeper and the seal

-
- A cozy glowing house. Inside, several data-droplets each wear a small coloured privacy badge. A gentle gatekeeper at the door kindly keeps the most sensitive droplets inside, while letting only the safe, plain-fact droplets out — pressing a glowing violet wax seal 'verified' onto each one as it leaves. One droplet with a broken seal is gently turned away. -
- The same idea, kindly: the sensitive stuff stays home, and every fact - that does leave gets a wax-seal receipt — break the seal - and it’s turned away. Privacy and proof, by construction. -
-
- -
- - Honest note. The viewer is a read-only - demo — no device management, no fleet console, no controlling real - sensors — and its room-state runs on the synthetic simulator. The - architecture, privacy enforcement, and provenance shown are real; the - accuracy is not yet validated against live hardware. (Source: README - L69, L150–152.) - -
-
-
- - -
- - 05 - -

Why this, vs. what you already have?

- “I’ve got a camera / a motion sensor / a smart-home hub — why do I need this too?” -
- -
-
-

- You may already use a camera, a motion sensor, or a smart-home hub like - Matter. Here’s the honest difference — and why RuField - isn’t “just another thing piled on.” -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
What you have vs. what RuField adds
You might already use…What it gives youWhat RuField adds
A security cameraA literal image — and a privacy problem nobody wants in a bedroomThe answer (“present, got out of bed”) with no image at all, plus a privacy label per fact
A PIR motion sensorOne bit: “something moved”Rich room-state — sitting, sleeping, breathing, bed-exit, room-transition — fused with confidence scores
Matter / a smart-home hubA way for devices to connectMatter is a connectivity layer; it doesn’t define a sensing-event format. RuField is the missing sensing layer that could feed a Matter bridge
WiFi sensing / 802.11bf aloneWiFi-only readings, no privacy or provenance modelOne grammar across WiFi + radar + ultrasound + IR, with privacy classes and signed receipts — RuField sits above 802.11bf, it doesn’t compete with it
- -

- The one-line version: everything you already have either watches - you (cameras), tells you almost nothing (a motion blip), or just connects - devices (Matter). RuField is the privacy-first layer that turns invisible - signals into rich, provable facts — and it’s an open standard, - so it’s not one vendor’s locked box. -

- - -

Technical view — where RuField sits in the stack

-
- - RuField's layer position above radio standards and below applications - A layer stack. At the bottom are the physical radio standards: 802.11bf WiFi sensing, Bluetooth channel sounding, UWB, and radar — RuField sits above these, not replacing them. In the middle, RuField defines the common event, privacy, and provenance layer. Above that, Matter and other connectivity hubs can bridge the events, and applications like an elder-care app consume the plain facts. A side note clarifies RuField is the sensing-event layer the others lack. - - RuField is a new LAYER, not a new device - - - - Your apps — elder-care, security, building analytics - read plain, signed facts — never raw signal, never images - - - - Connectivity hubs (Matter) — move events between devices · do NOT define a sensing event - - - - RuField MFS — the common event, privacy & provenance layer - one FieldEvent format - privacy classes P0–P5 - signed provenance - - - RuField sits ABOVE these — it makes their outputs fit, it does not replace them: - 802.11bfWiFi sensing - BT channelsounding - UWBranging - radarmmWave - - Source: ADR-260 §1, §8, §14; README L51-54 - -
- The positioning, precisely: RuField is a layer above the radio - standards (it makes their outputs fit) and below your apps. Matter moves - events; RuField defines the sensing event Matter lacks. -
-
- - -

Friendly view — three things you have, and the gap RuField fills

-
- - Camera watches you, motion sensor tells you almost nothing, hub just connects - Three friendly cards. A camera card 'watches you'. A motion sensor card 'tells you almost nothing'. A hub card 'just connects devices'. A fourth bright card shows RuField giving rich, private, provable facts — the gap the others leave. - - Each thing you have solves only one piece - - - 📷 - Camera - watches you - great answer, - unwanted in a bedroom - - - 🔅 - Motion sensor - tells you almost nothing - just “something - moved” - - - 🔗 - Smart-home hub - just connects devices - no sensing event - of its own - - - ✨ - RuField - rich · private · provable - the facts, no image, - signed & labelled - -
- Put plainly: the camera watches you, the motion sensor barely tells you - anything, the hub only connects boxes. RuField fills the gap they all - leave — rich facts, no image, private and provable. -
-
-
-
- - -
- - 06 - -

Use-case gallery

- Six real situations — situation → the exact command → what it does → what you get. Each opens to its own diagram. -
- -
-
-

- Every command below is taken straight from the project’s own README - — nothing here is invented. Each scenario maps to something the v0.1 - reference stack actually runs. Click one open to see how it flows. -

-
- - -
- - Scenario 1 -

“Just show me it works” — the benchmark

- -
-
-
- - The benchmark flow - Running cargo run -p rufield-bench runs synthetic sensors through fusion and room-state, scored deterministically against known ground truth, producing a report card of F1 per task, p95 latency, 100% provenance coverage and 0 privacy violations, every number labelled SYNTHETIC. - - - synthetic sensorsknown ground truth - - fusion - - room-state - - - deterministic report card - F1 per task: presence · breathing · bed-exit · room-transition - p95 latency · 100% provenance coverage - 0 privacy violations - every number labelled SYNTHETIC - scored against its own known truth — proves the pipeline is correct, not real-world accuracy - -
Scenario 1 — the whole pipeline scored against known truth, honestly labelled SYNTHETIC.
-
-
-
The situation
-
You’ve heard the pitch and want proof the pipeline is real, not a slide deck.
-
The exact command
-
cargo run -p rufield-bench -- 2026
-
What it does
-
Runs the whole pipeline — synthetic sensors → fusion → room state → scoring — deterministically against known ground truth.
-
What you get
-
A one-screen report card: F1 per task, p95 latency, 100% provenance coverage, 0 privacy violations — every number labelled SYNTHETIC, honestly. (Source: README L76–82, L279–313.)
-
-
-
- - -
- - Scenario 2 -

“Let me watch a room light up” — the live dashboard

- -
-
-
- - The live viewer flow - Running cargo run -p rufield-viewer opens localhost:8088 and replays the enter, sit, breathe, sleep, scratch, bed-exit, leave sequence across WiFi, radar and thermal, showing a room-state panel, a privacy-badged event stream, a fusion graph and click-to-inspect signed receipts, under an amber SYNTHETIC banner. - - - - replay sequence - enter → sit → breathe - → sleep → scratch - → bed-exit → leave - WiFi · radar · thermal, - tick by tick, no build - - - SYNTHETIC — simulated sensors, no hardware - room-state: present · sitting · in bed→ got out of bed - event stream + privacy badge P0–P5click a receipt: ✓ verified / ✗ not - fusion graph — which signals support each conclusion - -
Scenario 2 — a room waking up, live in the browser, every event privacy-badged and receipt-checkable.
-
-
-
The situation
-
You want to see camera-free room intelligence, not read a table.
-
The exact command
-
cargo run -p rufield-viewer
-# then open http://localhost:8088/
-
What it does
-
Replays the enter → sit → breathe → sleep → scratch → bed-exit → leave sequence tick by tick across WiFi/radar/thermal, in your browser, no build step.
-
What you get
-
A live room-state panel, a privacy-badged event stream, the fusion graph, and a click-to-inspect signed receipt per event — under an honest SYNTHETIC banner. (Source: README L84–152.)
-
-
-
- - -
- - Scenario 3 -

“Plug in a real WiFi recording” — the one real-signal path

- -
-
-
- - The real-WiFi replay flow - A real .csi.jsonl WiFi recording is read by CsiReplayAdapter, which calibrates an empty-room baseline and emits one signed FieldEvent per frame with a real sha256 and ed25519 signature, feeding the same fusion engine. The honest caveat: it is replay from an unlabeled file, a CSI-variance proxy, not validated accuracy. - - - real .csi.jsonlcaptured WiFi, from a file - - CsiReplayAdaptercalibrate empty-room baselinesign each frame (sha256+ed25519) - - same fusion engineas the demo - - real inferencesperson_present · breathingfrom REAL WiFi signal - caveat: replay from an unlabeled file → CSI-variance proxy, NOT validated accuracy - -
Scenario 3 — the one path that ingests real WiFi: signed per frame, fused like the demo, honestly framed as a proxy.
-
-
-
The situation
-
You want to feed RuField real captured WiFi, not a simulator.
-
The exact command (Rust)
-
let mut adapter = CsiReplayAdapter::from_jsonl(&recording)?;
-adapter.calibrate("living_room")?;
-while let Some(event) = adapter.next_event()? {
-    fusion.ingest(event);   // RuFieldFusion
-}
-
What it does
-
Reads a real .csi.jsonl recording, learns an empty-room baseline, and emits one signed field event per frame (real sha256 + ed25519) into the same fusion engine. (Source: README L212–244.)
-
What you get
-
Real person_present / breathing inferences from real WiFi. Honest caveat: it’s replay from an unlabeled file, so it’s a CSI-variance proxy, not validated accuracy — the win is “RuField ingests real WiFi and fuses it.” (Source: README L246–254.)
-
-
-
- - -
- - Scenario 4 -

“Prove a reading wasn’t faked” — provenance / anti-spoofing

- -
-
-
- - The provenance gate - is_fusable checks every event's signature. A genuine event with a verifying ed25519 receipt (or an explicit synthetic flag) is admitted to fusion. A forged or altered event fails the check and is never fused; the live viewer flags it with a cross. - - - incoming eventcarries a receipt - - is_fusable()ed25519 verify? - verifies (or synthetic) - forged / altered - ✓ admitted to fusioncan drive a trusted conclusion - ✗ never fusedviewer flags it; a spoofed all-clear can’t hide an emergency - -
Scenario 4 — only a verifying receipt gets into fusion. Tamper with one byte and the event is rejected, never trusted.
-
-
-
The situation
-
A safety system can’t trust an event that might be forged — a spoofed “all clear” could hide a real emergency.
-
The exact command (Rust)
-
rufield_provenance::is_fusable(&event)
-
What it does
-
Checks every event’s signature; an event enters fusion only if it carries a verifying ed25519 receipt or is explicitly flagged synthetic. Tamper with any field after signing and the check fails. (Source: README L363–371; ADR-260 §11, §22.)
-
What you get
-
A hard guarantee that no forged or altered event can drive a trusted conclusion — the viewer flags unverified events ✗ and never fuses them. (Source: README L130–138.)
-
-
-
- - -
- - Scenario 5 -

“Keep the sensitive stuff on the device” — the privacy guard

- -
-
-
- - The privacy guard's six classes - The DefaultPrivacyGuard authorize call enforces policy by class. P0 raw frames and P1 derived features are the most sensitive; P0 is denied from the network by default. P2 occupancy and P3 aggregate facts pass. P4 health inferences like breathing require explicit consent. P5 identity-linked inferences require identity binding plus an audit log. The benchmark reports zero privacy violations. - - Six privacy classes — P0 rawest (most sensitive) to P5 (names a person) - - P0raw frame(raw CSI/radar)DENIED fromnetwork by default - P1derived feature(Doppler, blob)non-identity - P2occupancy/motion(present, bed-exit)passes - P3anon aggregate(room count)passes - P4health inference(breathing, sleep)requiresexplicit consent - P5identity-linked(named person)bind identity+ audit log - You literally can’t ship the sensitive data without an explicit, logged decision — benchmark: 0 privacy violations - -
Scenario 5 — the real six-class ladder (from privacy.rs): P0 raw is denied off-device, P4 health needs consent, P5 identity needs binding + audit.
-
-
-
The situation
-
Raw signals and health inferences must not leak off the device by accident.
-
The exact command (Rust)
-
DefaultPrivacyGuard::default()
-    .authorize(class, destination, consent, identity_bound)
-
What it does
-
Enforces the policy automatically: P0 raw frames are denied from the network by default; P4 health inferences require explicit consent; P5 (names a person) requires identity binding + an audit log. (Source: README L200–209; rufield-privacy/src/lib.rs.)
-
What you get
-
Privacy by construction — you literally can’t ship the sensitive data without an explicit, logged decision; the benchmark reports 0 privacy violations. (Source: README L290, L355–361.)
-
-
-
- - -
- - Scenario 6 -

“Show real sensor data on the same dashboard” — live upstream mode

- -
-
-
- - Live upstream mode - Running the viewer with source live and an upstream URL subscribes to a real FieldEvent stream, verifies each receipt on ingest, and runs only verified events through the identical room-state, privacy and fusion display, with a green LIVE banner when connected or a red DISCONNECTED banner if unreachable. It never silently falls back to fake data under a LIVE banner. - - - real upstream feede.g. RuView sensing server:8080 · real FieldEvents - - verify receipt on ingestonly verified events passno silent fake fallback - - identical displayroom-state · privacy · fusion - ● LIVE (connected) - ● DISCONNECTED - Same panels, now driven by real events — honest banners, never fake data under a LIVE label - -
Scenario 6 — the same dashboard, fed by a real upstream feed; verified-only, with honest LIVE / DISCONNECTED banners.
-
-
-
The situation
-
You have a real RuField feed (e.g. from RuView’s sensing server) and want the same dashboard to display it instead of the simulator.
-
The exact command
-
cargo run -p rufield-viewer -- \
-  --source live --upstream http://127.0.0.1:8080
-
What it does
-
Subscribes to the upstream’s real FieldEvent stream, verifies each receipt on ingest, and runs only verified events through the identical room-state / privacy / fusion display. (Source: README L113–152.)
-
What you get
-
The same panels, now driven by real events — with an honest green LIVE banner when connected, or a red DISCONNECTED banner if unreachable. It never silently falls back to fake data under a LIVE banner. (Source: README L140–152.)
-
-
-
- -
-
-
- - -
- - 07 - -

How to implement — and start in five minutes

- You’ve seen what it does. Here’s the shortest path to running it yourself. -
- -
-
-

- RuField’s reference build is plain Rust — if you have - cargo (Rust’s build tool), you can run the whole thing. - There are exactly two starting moves: watch a room light up, - then see the score. -

- - -

Technical view — clone → run the viewer → run the bench

-
- - The three-step start path - Step one: clone the rufield repo and have cargo ready. Step two: run cargo run -p rufield-viewer and open localhost:8088 to watch a room light up in the browser. Step three: run cargo run -p rufield-bench to see the deterministic, SYNTHETIC-labelled report card. Then optionally wire the drop-in knowledge pack into your AI. - - - Two commands to your first camera-free room - - - - 1 - Clone & have cargo - - git clone github.com/ - ruvnet/rufield - cd rufield - no extra services, no Docker - - - - - - 2 - Watch a room - - cargo run -p rufield-viewer - - open localhost:8088 → it lights up - - - - - - 3 - See the score - - cargo run -p rufield-bench - - report card (SYNTHETIC-labelled) - - - - Optional → wire the drop-in knowledge pack into your AI (Section 08) so it answers from the real source - -
- The whole start: git clone, then two cargo run - commands — one to watch a room light up, one to see the scored - report card. No Docker, no extra services. (Source: README L76–125.) -
-
- -

Copy-paste, in order:

-
# 1. get the reference build
-git clone https://github.com/ruvnet/rufield
-cd rufield
-
-# 2. watch a room wake up, live in your browser
-cargo run -p rufield-viewer
-#    then open http://localhost:8088/
-
-# 3. see the pipeline scored against known truth
-cargo run -p rufield-bench -- 2026
- - -

Friendly view — it really is just two commands

-
- - Two friendly steps: watch, then score - A friendly two-step path. A play button labelled 'watch a room' leads to a smiling room icon lighting up. A chart button labelled 'see the score' leads to a friendly report card with a checkmark. The message: you are five minutes from your first camera-free room. - - Five minutes from here to your first camera-free room - - - - - watch a room - - - - - - it lights up ✓ - - - - - see the score - - - - ✓ - report card - honest numbers - -
- No jargon needed: press play to watch a room light up, then run the score - to see honest, labelled numbers. That’s the start. -
-
-
-
- - -
- - 08 - -

The drop-in

- One download, two halves — copy it in and your AI answers from the real source. -
- -
-
-

- Everything on this page also comes as one download with two - halves. One half is for you — a short written - primer. The other is for your AI — a small, searchable - knowledge pack your assistant can read, so it answers questions about - RuField accurately, with sources, instead of guessing. -

- - -

Technical view — what’s actually inside the zip (every file, in plain English)

-
- - The drop-in zip's real file tree, annotated - An annotated file tree of the rufield drop-in. The top level is rufield-kb, one download with two halves. The for-you (human) half contains rufield-primer.md, the whole tool in plain English, and an optional studio folder with a short video and audio overview. The for-your-AI half contains rufield-kb.big.rvf, the sharp brain for Mac or PC; rufield-kb.small.rvf, the light brain for edge; rufield.passages.jsonl, every doc and all source, searchable; ask-kb.mjs, to ask it from the command line; and kb-mcp-server.mjs, to wire it into Claude Code or Cursor. A README explains what it is and the three-step setup. Below the tree, three steps: unzip into your project as kb, add the two-line .mcp.json, and paste the CLAUDE.md gate. - - - rufield-kb/ — one download, two halves - - - - - ├─ for-you (human) ─────────────── - └─ rufield-primer.md - — the whole tool, in plain English - └─ studio/ (optional) - — short video + audio overview - - - ├─ for-your-AI ───────────────── - ├─ rufield-kb.big.rvf - — the “brain” (sharp; Mac/PC, 768-dim) - ├─ rufield-kb.small.rvf - — the “brain” (light; edge, 384-dim) - ├─ rufield.passages.jsonl - — every doc + all source, searchable - ├─ ask-kb.mjs - — ask it from the command line - └─ kb-mcp-server.mjs - — wire it into Claude Code / Cursor - - └─ README.md - — what it is + the 3-step setup - - - - - Three steps to wire it in - - - 1 - Unzip into your project - unzip … → a kb/ folder - Put kb/ beside your code. - - - 2 - Add a .mcp.json - "rufield-kb": { … } - Registers the pack as a tool. - - - 3 - Paste the gate - into CLAUDE.md - Forces a source check first. - -
- Not an abstract picture — the real contents: two halves - (for-you + for-your-AI), the big and small - .rvf brains, the searchable passages.jsonl, a - CLI (ask-kb.mjs) and an MCP server - (kb-mcp-server.mjs), plus a README. Wired in three steps. -
-
- - -

Friendly view — one parcel, two gifts

-
- A single friendly parcel gently splits into two glowing halves. The left half, labelled 'FOR YOU', shows a person relaxing while reading a friendly illustrated guide. The right half, labelled 'FOR YOUR AI', shows a gentle glowing brain holding a magnifying glass and happily searching a neat stack of knowledge cards. Soft violet signal-waves join the two halves. -
- One parcel, two gifts: for-you/ (the primer you read) and - for-your-AI/ (the knowledge pack your assistant searches). -
-
- -

Wiring the AI half into Claude Code takes three small steps:

-
    -
  1. - Unzip it next to your project. -
    unzip rufield-dropin.zip
    -cd rufield-kb/for-your-AI
    -npm install
    -
  2. -
  3. - Point Claude Code at it with a .mcp.json file. - This tiny file tells Claude Code about the local knowledge tool. Drop it - in your project root: -
    {
    -  "mcpServers": {
    -    "rufield-kb": {
    -      "command": "node",
    -      "args": ["rufield-kb/for-your-AI/kb-mcp-server.mjs"]
    -    }
    -  }
    -}
    - (.mcp.json is just a list of helper tools Claude Code is - allowed to call. Here it registers the knowledge pack as a tool named - rufield-kb.) -
  4. -
  5. - Add a verification gate to your CLAUDE.md. - CLAUDE.md is the instruction file Claude reads first. This - forces it to check the knowledge pack before answering, rather - than guessing: -
    ## RuField questions
    -Before answering ANY question about RuField, query the
    -`rufield-kb` tool and ground your answer in what it returns.
    -If the pack has no answer, say so plainly — do not invent one.
    -
  6. -
-

Then confirm it works. Ask Claude Code something only the pack can answer:

-
What are the privacy classes P0 through P5 in RuField, and which
-ones are denied, consent-gated, or identity-bound?
-

- If the wiring is right, the answer comes back grounded in the pack — - P0 raw (denied off-device), - P4 health (consent), P5 - identity (bound + logged) — with the source it drew from. If - you instead get a vague reply with no source, the gate isn’t firing: - re-check the .mcp.json path and the CLAUDE.md line. -

- - -
- -
Get the drop-in
-
- Click / press Enter to download — or drag a folder here (preview - stub). The real .zip ships via the GitHub Release. -
-

-
- -
- - Honest limits, stated plainly. RuField is - rufield.mfs.v0.1 — an honestly-measured reference - pipeline (data model, provenance, privacy, fusion, benchmark), not a - product you install in your house yet. v0.1 ships - synthetic adapters only; no validated hardware adapter - exists. The one real-signal path is recorded WiFi replay - (a proxy, not validated accuracy). The viewer is read-only. - And RuField explicitly does not claim medical diagnosis - — health-style inferences are gated and must not be read as clinical - claims. (Source: README L13–25, L316–344; ADR-260 §6, §25.) - -
-
-
- -
-
-
- - -
-
- -
- A plain-language explainer for ruvnet/rufield - by Reuven Cohen (@ruvnet) · built with the Ruv-Explainer - dual-half pipeline · not affiliated, MIT-licensed source. -
-
- Honest limits, in one breath: RuField is - rufield.mfs.v0.1, a reference stack — most numbers are - SYNTHETIC (scored against a simulator’s own truth, not - real-world accuracy); the single real-signal path is recorded WiFi - replay, a physically-grounded proxy, not validated accuracy; no - hardware adapter is validated; the viewer is read-only; and it is - not a medical device. The architecture, privacy enforcement, - and provenance are real and working today. - -  ·  Updated 2026-06-19 · source - @ 509d8ae · rufield.mfs.v0.1 - -
-
-
- - - - diff --git a/ruv-explainer-rufield/main.js b/ruv-explainer-rufield/main.js deleted file mode 100644 index bf36a11..0000000 --- a/ruv-explainer-rufield/main.js +++ /dev/null @@ -1,93 +0,0 @@ -/* ============================================================================= - RuField MFS ExplainerSite — main.js (progressive enhancement; < 6 KB) - The page is fully usable with JS disabled: all sections AND the use-case - gallery items are native
/, so they open/close on their own. - This script adds: - 1. deep-link: open the
a #hash points at, and on nav-click. - 2. dropzone stub: click + keyboard (Enter/Space) + drag-and-drop fallback, - all three paths converge on one handler. The real .zip download href - wires up when downloads/rufield-dropin.zip is published. - No dependencies. No build step. - ========================================================================== */ -(function () { - "use strict"; - - /* --- 1. Deep-link a section (or gallery item) open ---------------------- */ - function openFromHash() { - var id = (location.hash || "").replace(/^#/, ""); - if (!id) return; - var el = document.getElementById(id); - // Walk up: open EVERY enclosing
(a gallery item lives inside §06). - while (el) { - if (el.tagName === "DETAILS" && !el.open) el.open = true; - el = el.parentElement; - } - var target = document.getElementById(id); - if (target && target.scrollIntoView) { - target.scrollIntoView({ behavior: "smooth", block: "start" }); - } - } - window.addEventListener("hashchange", openFromHash); - openFromHash(); - - // Clicking an in-page nav link should also expand its target section. - document.querySelectorAll('a[href^="#"]').forEach(function (a) { - a.addEventListener("click", function () { - var id = a.getAttribute("href").slice(1); - var el = document.getElementById(id); - while (el) { - if (el.tagName === "DETAILS" && !el.open) el.open = true; - el = el.parentElement; - } - }); - }); - - /* --- 2. Dropzone stub (click / keyboard / drag) ------------------------- */ - var dz = document.getElementById("dropzone"); - var status = document.getElementById("dzStatus"); - if (!dz) return; - - // Stub target. Swapped for the real GitHub Release / downloads/ href on publish. - var DOWNLOAD_HREF = "downloads/rufield-dropin.zip"; - - function say(msg) { if (status) status.textContent = msg; } - - function activate() { - // Announce intent. Becomes a real navigation to the published .zip on publish. - say("Drop-in pack not bundled yet — ships via the GitHub Release (" + DOWNLOAD_HREF + ")."); - } - - dz.addEventListener("click", activate); - - dz.addEventListener("keydown", function (e) { - if (e.key === "Enter" || e.key === " " || e.key === "Spacebar") { - e.preventDefault(); - activate(); - } - }); - - ["dragenter", "dragover"].forEach(function (evt) { - dz.addEventListener(evt, function (e) { - e.preventDefault(); - e.stopPropagation(); - dz.classList.add("is-dragover"); - }); - }); - ["dragleave", "dragend"].forEach(function (evt) { - dz.addEventListener(evt, function (e) { - e.preventDefault(); - dz.classList.remove("is-dragover"); - }); - }); - dz.addEventListener("drop", function (e) { - e.preventDefault(); - e.stopPropagation(); - dz.classList.remove("is-dragover"); - var n = (e.dataTransfer && e.dataTransfer.items && e.dataTransfer.items.length) || 0; - say( - n - ? "Caught " + n + " item(s). The drop-in is a knowledge pack you copy in — preview only here." - : "Nothing detected. Click or press Enter for the drop-in pack instead." - ); - }); -})(); diff --git a/ruv-explainer-rufield/package.json b/ruv-explainer-rufield/package.json deleted file mode 100644 index 153cce1..0000000 --- a/ruv-explainer-rufield/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "ruv-explainer-rufield", - "version": "0.1.0", - "private": true, - "description": "Slate + signal-violet ExplainerSite for RuField MFS (ruvnet/rufield): camera-free multimodal field sensing — invisible WiFi/radar/heat signals turned into privacy-labelled, provable room-state facts. Static, no build, no deps.", - "license": "MIT", - "homepage": "https://ruv-explainer-rufield.vercel.app", - "repository": { - "type": "git", - "url": "https://github.com/stuinfla/ruv-explainer-rufield" - }, - "keywords": [ - "rufield", - "rufield-mfs", - "ruvnet", - "field-sensing", - "wifi-sensing", - "camera-free", - "explainer", - "static-site" - ], - "scripts": {} -} diff --git a/ruv-explainer-rufield/robots.txt b/ruv-explainer-rufield/robots.txt deleted file mode 100644 index 2541009..0000000 --- a/ruv-explainer-rufield/robots.txt +++ /dev/null @@ -1,4 +0,0 @@ -User-agent: * -Allow: / - -Sitemap: https://ruv-explainer-rufield.vercel.app/sitemap.xml diff --git a/ruv-explainer-rufield/styles.css b/ruv-explainer-rufield/styles.css deleted file mode 100644 index a4b04fe..0000000 --- a/ruv-explainer-rufield/styles.css +++ /dev/null @@ -1,587 +0,0 @@ -/* ============================================================================= - RuField MFS ExplainerSite — FIELD / SIGNAL aesthetic - Aesthetic lock [Constraint K]: DEEP SLATE-CHARCOAL (cool blue-grey, never warm, - never amber/copper) with SIGNAL-VIOLET -> MAGENTA accents and waveform / field - motifs. Deliberately NOT the MetaHarness foundry/mint amber look, and NOT the - cognitum cool-cyan. Type: Space Grotesk display over Inter / JetBrains Mono. - Self-hosted fonts are optional — robust system fallbacks ship if absent. - ========================================================================== */ - -/* ---- Optional self-hosted fonts (zero CDN). Page works without them. ------ */ -@font-face { - font-family: "Space Grotesk"; - src: url("assets/fonts/SpaceGrotesk-Medium.woff2") format("woff2"); - font-weight: 500; font-style: normal; font-display: swap; -} -@font-face { - font-family: "Space Grotesk"; - src: url("assets/fonts/SpaceGrotesk-Bold.woff2") format("woff2"); - font-weight: 700; font-style: normal; font-display: swap; -} -@font-face { - font-family: "Inter"; - src: url("assets/fonts/Inter-Regular.woff2") format("woff2"); - font-weight: 400; font-style: normal; font-display: swap; -} -@font-face { - font-family: "Inter"; - src: url("assets/fonts/Inter-Medium.woff2") format("woff2"); - font-weight: 500; font-style: normal; font-display: swap; -} -@font-face { - font-family: "JetBrains Mono"; - src: url("assets/fonts/JetBrainsMono-Regular.woff2") format("woff2"); - font-weight: 400; font-style: normal; font-display: swap; -} - -/* ---- :root FIELD/SIGNAL DESIGN TOKENS --------------------------------------- - Hues are COOL (blue-grey / indigo bias) with violet+magenta signal accents. - No amber, no copper, no warm-orange, no cyan, no green (except one calm "ok"). */ -:root { - /* Slate-charcoal substrate — graphite with a cool blue-grey cast, not navy, not warm */ - --bg: #0d0f17; /* deepest — page floor */ - --bg-2: #11131c; /* raised plane */ - --panel: #161927; /* card body */ - --panel-2: #1b1f30; /* card header / inset */ - --ridge: #2a3047; /* hairline edges, embossed seams */ - - /* Signal accents — violet poured into magenta */ - --violet: #a855f7; /* primary signal-violet */ - --violet-hot: #c084fc; /* highlight / hover lift */ - --magenta: #e84ef0; /* secondary magenta */ - --magenta-deep:#9d2bc4; /* shadow side of magenta */ - --indigo: #7c5cff; /* tertiary indigo for the field */ - --field: #6f7bd6; /* soft cool field-blue micro-labels */ - --ok: #56d4a0; /* the ONE calm green — "verified / live / ok" only */ - --warn: #f0a85a; /* honest SYNTHETIC banner — used sparingly, not a theme color */ - - /* Ink — cool off-white, never warm-cream */ - --ink: #eef1fb; /* primary text on dark */ - --ink-2: #c4cae2; /* secondary text */ - --muted: #8b92b4; /* captions, meta */ - --faint: #5b6184; /* hairline labels */ - --on-violet: #120a1e; /* text that sits ON violet fills */ - - /* Lines / fills derived from the signal accents */ - --line: rgba(168,85,247,0.14); - --line-strong: rgba(168,85,247,0.30); - --fill-violet: rgba(168,85,247,0.10); - --fill-magenta:rgba(232,78,240,0.10); - - /* Depth — cool shadows + signal glow */ - --shadow: 0 22px 48px -26px rgba(0,0,0,0.85); - --shadow-deep: 0 38px 90px -40px rgba(0,0,0,0.92); - --emboss: inset 0 1px 0 rgba(168,140,255,0.08), - inset 0 -1px 0 rgba(0,0,0,0.5); - --glow-violet: 0 0 0 1px rgba(168,85,247,0.28), - 0 14px 40px -16px rgba(168,85,247,0.40); - - /* Type — distinct from MetaHarness (Big Shoulders) */ - --display: "Space Grotesk", "Avenir Next", system-ui, sans-serif; - --sans: "Inter", system-ui, -apple-system, "Segoe UI", sans-serif; - --mono: "JetBrains Mono", ui-monospace, "SF Mono", Menlo, monospace; - - /* Rhythm */ - --maxw: 1120px; - --gutter: clamp(20px, 5vw, 56px); - --radius: 16px; - --radius-s: 10px; - --ease: cubic-bezier(0.22, 0.61, 0.36, 1); -} - -/* ---- Reset / base --------------------------------------------------------- */ -*, *::before, *::after { box-sizing: border-box; } -html { -webkit-text-size-adjust: 100%; scroll-behavior: smooth; } - -body { - margin: 0; - background: var(--bg); - color: var(--ink); - font-family: var(--sans); - font-size: 16.5px; - line-height: 1.66; - -webkit-font-smoothing: antialiased; - text-rendering: optimizeLegibility; - /* Field grain: layered cool violet/indigo radials + faint signal sheen. - No warm/amber stop anywhere. */ - background-image: - radial-gradient(1100px 640px at 80% -8%, rgba(168,85,247,0.12), transparent 60%), - radial-gradient(900px 720px at -10% 6%, rgba(124,92,255,0.10), transparent 55%), - radial-gradient(700px 520px at 50% 108%, rgba(232,78,240,0.07), transparent 60%), - linear-gradient(180deg, var(--bg) 0%, var(--bg-2) 100%); - background-attachment: fixed; -} - -img { max-width: 100%; height: auto; display: block; } - -a { - color: var(--violet-hot); - text-decoration: none; - transition: color 0.18s var(--ease); -} -a:hover { color: var(--magenta); } -a:focus-visible, -summary:focus-visible, -button:focus-visible, -[tabindex]:focus-visible { - outline: 2px solid var(--violet); - outline-offset: 3px; - border-radius: 4px; -} - -/* ---- Layout --------------------------------------------------------------- */ -.wrap { width: 100%; max-width: var(--maxw); margin: 0 auto; padding: 0 var(--gutter); } - -/* ---- Type system ---------------------------------------------------------- */ -h1, h2, h3, h4 { - font-family: var(--display); - font-weight: 700; - line-height: 1.02; - letter-spacing: -0.012em; - margin: 0 0 0.5em; -} -h1 { font-size: clamp(2.6rem, 7.5vw, 5rem); letter-spacing: -0.02em; } -h2 { font-size: clamp(1.7rem, 4vw, 2.6rem); } -h3 { font-size: 1.42rem; font-weight: 500; letter-spacing: -0.01em; } -p { margin: 0 0 1rem; max-width: 68ch; color: var(--ink-2); } - -.eyebrow { - font-family: var(--mono); - font-size: 12px; - letter-spacing: 0.32em; - text-transform: uppercase; - color: var(--field); - font-weight: 400; - margin: 0 0 14px; -} -.mono { font-family: var(--mono); } -.lede { font-size: 1.2rem; color: var(--ink); max-width: 66ch; } - -/* Lists — comfortable rhythm, violet markers */ -ol, ul { margin: 0 0 1rem; padding-left: 1.4em; max-width: 68ch; color: var(--ink-2); } -li { margin: 0 0 0.55em; } -li::marker { color: var(--violet); } -li strong { color: var(--ink); } - -/* Multi-line command block — a quiet signal plate */ -pre.code-block { - font-family: var(--mono); - font-size: 0.85rem; - line-height: 1.62; - color: var(--violet-hot); - background: #0a0c13; - border: 1px solid var(--line-strong); - border-left: 3px solid var(--magenta); - border-radius: var(--radius-s); - padding: 16px 18px; - margin: 0 0 1rem; - overflow-x: auto; - box-shadow: var(--emboss); - max-width: 72ch; -} -pre.code-block code { - background: none; border: none; box-shadow: none; padding: 0; - font-size: inherit; color: inherit; white-space: pre; -} - -/* Honest-note paragraphs at the foot of a section */ -.footnote-note { - margin-top: 18px; - padding: 13px 16px; - border: 1px dashed var(--magenta-deep); - border-radius: var(--radius-s); - background: var(--fill-magenta); - color: var(--ink-2); - max-width: 72ch; -} -.footnote-note small { color: var(--muted); line-height: 1.58; } -.footnote-note strong { color: var(--ink); } - -/* The honest SYNTHETIC banner — used inside sections where v0.1 is synthetic */ -.synthetic-banner { - display: inline-flex; align-items: center; gap: 9px; - margin: 6px 0 16px; - font-family: var(--mono); font-size: 12px; letter-spacing: 0.05em; - color: #f6d9b3; background: rgba(240,168,90,0.10); - border: 1px solid rgba(240,168,90,0.35); border-radius: 999px; - padding: 6px 14px; -} -.synthetic-banner::before { - content: ""; width: 8px; height: 8px; border-radius: 50%; - background: var(--warn); box-shadow: 0 0 8px rgba(240,168,90,0.8); -} - -/* Inline command chip — struck into slate */ -code, .cmd { - font-family: var(--mono); - font-size: 0.86em; - color: var(--violet-hot); - background: var(--fill-violet); - border: 1px solid var(--line-strong); - border-radius: 6px; - padding: 0.12em 0.45em; - box-shadow: var(--emboss); -} - -/* Privacy-class chips P0..P5 (reused in copy + the privacy section) */ -.pchip { - display: inline-block; font-family: var(--mono); font-size: 0.78em; - font-weight: 500; letter-spacing: 0.04em; - padding: 0.08em 0.5em; border-radius: 6px; border: 1px solid; -} -.pchip.p0 { color:#ff9fb0; border-color:rgba(255,159,176,0.5); background:rgba(255,159,176,0.10); } -.pchip.p1 { color:#f59fe0; border-color:rgba(245,159,224,0.5); background:rgba(245,159,224,0.10); } -.pchip.p2 { color:#c4a0ff; border-color:rgba(196,160,255,0.5); background:rgba(196,160,255,0.10); } -.pchip.p3 { color:#9fb4ff; border-color:rgba(159,180,255,0.5); background:rgba(159,180,255,0.10); } -.pchip.p4 { color:#ffc48a; border-color:rgba(255,196,138,0.5); background:rgba(255,196,138,0.10); } -.pchip.p5 { color:#ff8a8a; border-color:rgba(255,138,138,0.55); background:rgba(255,138,138,0.12); } - -/* ---- Provenance / attribution banner (Cognitum-style) [Constraint Q] ------ */ -.prov-banner { - border-bottom: 1px solid var(--line); - background: linear-gradient(180deg, rgba(27,31,48,0.6), rgba(17,19,28,0.5)); - backdrop-filter: blur(6px); - -webkit-backdrop-filter: blur(6px); -} -.prov-banner-inner { - display: flex; flex-wrap: wrap; align-items: center; - justify-content: space-between; gap: 10px 26px; - padding-top: 9px; padding-bottom: 9px; -} -.prov-attr { - margin: 0; max-width: none; - font-family: var(--sans); font-size: 12.5px; line-height: 1.5; - color: var(--muted); letter-spacing: 0.01em; -} -.prov-attr strong { color: var(--ink-2); font-weight: 500; } -.prov-attr a { color: var(--field); } -.prov-attr a:hover { color: var(--magenta); } -.prov-live { - margin: 0; flex: 0 0 auto; - font-family: var(--mono); font-size: 11.5px; letter-spacing: 0.05em; - color: var(--faint); white-space: nowrap; - display: inline-flex; align-items: center; gap: 8px; -} -.prov-live code { - font-size: 0.95em; color: var(--field); - background: var(--fill-violet); padding: 0.08em 0.4em; -} -.prov-dot { - color: var(--violet); font-size: 9px; - filter: drop-shadow(0 0 4px rgba(168,85,247,0.85)); - animation: prov-pulse 2.6s var(--ease) infinite; -} -@keyframes prov-pulse { - 0%, 100% { opacity: 1; } - 50% { opacity: 0.32; } -} - -/* ---- Header / nav --------------------------------------------------------- */ -.site-head { - position: sticky; top: 0; z-index: 40; - background: rgba(13,15,23,0.78); - backdrop-filter: blur(11px); - -webkit-backdrop-filter: blur(11px); - border-bottom: 1px solid var(--line); -} -.site-head .wrap { - display: flex; align-items: center; justify-content: space-between; - height: 64px; -} -.brand { - display: inline-flex; align-items: center; gap: 12px; - font-family: var(--display); font-weight: 700; font-size: 1.2rem; - letter-spacing: -0.01em; color: var(--ink); -} -.brand .mark { - width: 30px; height: 30px; border-radius: 9px; - display: grid; place-items: center; - background: var(--bg-2); - box-shadow: var(--glow-violet), var(--emboss); -} -.brand .mark svg { width: 30px; height: 30px; display: block; } -.nav-links { display: flex; gap: 4px; } -.nav-links a { - font-family: var(--mono); font-size: 12px; letter-spacing: 0.04em; - color: var(--muted); padding: 7px 11px; border-radius: 7px; - transition: color 0.18s var(--ease), background 0.18s var(--ease); -} -.nav-links a:hover { color: var(--ink); background: var(--fill-violet); } - -/* ---- Hero ----------------------------------------------------------------- */ -.hero { position: relative; padding: clamp(56px, 11vw, 120px) 0 clamp(40px, 7vw, 76px); overflow: hidden; } -.hero h1 { color: var(--ink); } -.hero h1 .signal { - background: linear-gradient(96deg, var(--indigo), var(--violet) 45%, var(--magenta)); - -webkit-background-clip: text; background-clip: text; color: transparent; -} -.hero .lede { margin-top: 20px; } -.hero-figure { - margin: 30px 0 0; border-radius: var(--radius); - border: 1px solid var(--ridge); overflow: hidden; - box-shadow: var(--shadow); position: relative; -} -.hero-figure img { width: 100%; display: block; } -.hero .meta-row { - display: flex; gap: 26px; flex-wrap: wrap; margin-top: 30px; - font-family: var(--mono); font-size: 12px; color: var(--faint); - letter-spacing: 0.04em; -} -.hero .meta-row b { color: var(--field); font-weight: 400; } -.cta { - display: inline-flex; align-items: center; gap: 10px; margin-top: 32px; - font-family: var(--display); font-weight: 700; font-size: 1rem; - letter-spacing: 0.01em; - color: var(--on-violet); - background: linear-gradient(96deg, var(--violet-hot), var(--magenta)); - padding: 13px 26px; border-radius: 11px; - box-shadow: var(--glow-violet), var(--emboss); - transition: transform 0.16s var(--ease), filter 0.16s var(--ease); -} -.cta:hover { transform: translateY(-2px); filter: brightness(1.07); color: var(--on-violet); } -.cta.ghost { - background: transparent; color: var(--violet-hot); - border: 1px solid var(--line-strong); box-shadow: var(--emboss); - margin-left: 12px; -} -.cta.ghost:hover { color: var(--magenta); border-color: var(--magenta); } - -/* ---- Sections (native
) ----------------------------------------- */ -.sections { padding: clamp(30px, 5vw, 56px) 0 clamp(64px, 10vw, 110px); } - -.section { - background: linear-gradient(180deg, var(--panel) 0%, var(--bg-2) 100%); - border: 1px solid var(--ridge); - border-radius: var(--radius); - box-shadow: var(--shadow), var(--emboss); - margin: 0 0 18px; - overflow: hidden; -} -.section[open] { box-shadow: var(--shadow-deep), var(--emboss); } - -/* The clickable bar — a signal plate */ -.section > summary { - list-style: none; cursor: pointer; - display: flex; align-items: baseline; gap: 18px; - padding: 25px clamp(20px, 4vw, 34px); - user-select: none; - transition: background 0.2s var(--ease); -} -.section > summary::-webkit-details-marker { display: none; } -.section > summary:hover { background: var(--fill-violet); } - -.section .num { - font-family: var(--mono); font-size: 13px; letter-spacing: 0.18em; - color: var(--magenta); flex: 0 0 auto; padding-top: 6px; -} -.section .head-text { flex: 1 1 auto; } -.section .head-text h2 { - margin: 0; color: var(--ink); - font-size: clamp(1.32rem, 3vw, 1.95rem); -} -.section .head-text .q { - display: block; font-family: var(--mono); font-size: 12px; - letter-spacing: 0.04em; color: var(--muted); margin-top: 6px; - text-transform: none; -} -/* Chevron that rotates on open */ -.section .chev { - flex: 0 0 auto; width: 26px; height: 26px; align-self: center; - border-radius: 50%; display: grid; place-items: center; - border: 1px solid var(--line-strong); color: var(--violet); - font-size: 13px; line-height: 1; - transition: transform 0.25s var(--ease), background 0.2s var(--ease); -} -.section[open] .chev { transform: rotate(90deg); background: var(--fill-violet); } - -.section .body { - padding: 4px clamp(20px, 4vw, 34px) 32px; - border-top: 1px solid var(--line); - margin-top: 2px; -} -.section .body > *:first-child { margin-top: 18px; } - -/* Two-tier visual label — marks technical SVG vs friendly art */ -.tier { - display: inline-flex; align-items: center; gap: 7px; - font-family: var(--mono); font-size: 10.5px; letter-spacing: 0.14em; - text-transform: uppercase; color: var(--faint); - margin: 26px 0 8px; -} -.tier::before { - content: ""; width: 18px; height: 1px; background: var(--line-strong); -} -.tier.tech { color: var(--violet); } -.tier.simple { color: var(--magenta); } - -/* Figure slots */ -.figure { - margin: 10px 0 4px; border: 1px solid var(--ridge); border-radius: var(--radius-s); - background: var(--panel-2); padding: 16px; box-shadow: var(--emboss); -} -.figure figcaption { - margin-top: 12px; color: var(--muted); - font-family: var(--mono); font-size: 12px; letter-spacing: 0.02em; - line-height: 1.55; -} -/* Diagram figures: inline SVGs + SVGs — force responsive width. */ -.figure.diagram { background: #0a0c13; } -.figure.diagram > svg, -.figure.diagram > img { - display: block; width: 100%; height: auto; max-width: 100%; - border-radius: 7px; -} -.figure.art img { border-radius: 8px; } -.figure.uc-diagram { margin: 14px 0 4px; padding: 13px; } -.figure.uc-diagram figcaption { margin-top: 10px; } - -/* Before -> after comparison table */ -.cmp { - width: 100%; border-collapse: separate; border-spacing: 0; - margin: 16px 0; font-size: 0.95rem; - border: 1px solid var(--ridge); border-radius: var(--radius-s); overflow: hidden; -} -.cmp caption { - text-align: left; font-family: var(--mono); font-size: 11px; - letter-spacing: 0.14em; text-transform: uppercase; color: var(--faint); - padding: 0 0 8px; -} -.cmp th, .cmp td { - text-align: left; padding: 12px 14px; vertical-align: top; - border-bottom: 1px solid var(--line); color: var(--ink-2); -} -.cmp thead th { - font-family: var(--mono); font-size: 11px; letter-spacing: 0.08em; - text-transform: uppercase; color: var(--field); background: var(--panel-2); -} -.cmp tbody tr:last-child td { border-bottom: none; } -.cmp .col-before { color: var(--muted); } -.cmp .col-after { color: var(--ink); } -.cmp .col-after strong { color: var(--violet-hot); } -.cmp td:first-child { - font-weight: 500; color: var(--ink); - background: rgba(168,85,247,0.04); - border-right: 1px solid var(--line); - white-space: nowrap; -} - -/* Use-case cards reuse the plate look */ -.grid { display: grid; gap: 16px; margin-top: 18px; } -.card { - background: var(--panel-2); border: 1px solid var(--ridge); - border-radius: var(--radius-s); padding: 20px 22px; box-shadow: var(--emboss); -} -.card .tag { - font-family: var(--mono); font-size: 11px; letter-spacing: 0.14em; - text-transform: uppercase; color: var(--magenta); -} -.card h3 { margin: 8px 0 10px; color: var(--ink); } - -/* Use-case gallery: nested collapsible items, each its own visual [R] */ -.grid.cases { grid-template-columns: 1fr; gap: 14px; } -.case { - background: var(--panel-2); border: 1px solid var(--ridge); - border-radius: var(--radius-s); box-shadow: var(--emboss); overflow: hidden; -} -.case > summary { - list-style: none; cursor: pointer; - display: flex; align-items: center; gap: 14px; - padding: 18px 20px; user-select: none; - transition: background 0.18s var(--ease); -} -.case > summary::-webkit-details-marker { display: none; } -.case > summary:hover { background: var(--fill-violet); } -.case .uc-tag { - font-family: var(--mono); font-size: 11px; letter-spacing: 0.12em; - text-transform: uppercase; color: var(--magenta); flex: 0 0 auto; -} -.case > summary h3 { margin: 0; flex: 1 1 auto; font-size: 1.12rem; color: var(--ink); } -.case > summary .chev { - flex: 0 0 auto; width: 22px; height: 22px; - border-radius: 50%; display: grid; place-items: center; - border: 1px solid var(--line-strong); color: var(--violet); - font-size: 12px; transition: transform 0.25s var(--ease); -} -.case[open] > summary .chev { transform: rotate(90deg); background: var(--fill-violet); } -.case .uc-body { padding: 2px 20px 22px; border-top: 1px solid var(--line); } -.case .uc-body p { max-width: none; } -.case pre.code-block { max-width: none; } -.case dl { margin: 14px 0 0; } -.case dt { - font-family: var(--mono); font-size: 11px; letter-spacing: 0.12em; - text-transform: uppercase; color: var(--field); margin-top: 14px; -} -.case dt:first-child { margin-top: 0; } -.case dd { margin: 5px 0 0; color: var(--ink-2); } -.case .figure { margin: 16px 0 4px; } - -/* ---- Dropzone (the drag-in stub) ----------------------------------------- */ -.dropzone { - margin-top: 22px; border: 2px dashed var(--magenta-deep); - border-radius: var(--radius); padding: clamp(28px, 6vw, 50px); - text-align: center; background: var(--fill-magenta); - transition: border-color 0.2s var(--ease), background 0.2s var(--ease), - transform 0.2s var(--ease); - cursor: pointer; -} -.dropzone:hover { border-color: var(--magenta); background: var(--fill-violet); } -.dropzone.is-dragover { - border-color: var(--violet-hot); background: var(--fill-violet); - transform: scale(1.01); box-shadow: var(--glow-violet); -} -.dropzone .dz-icon { margin-bottom: 8px; } -.dropzone .dz-icon svg { width: 34px; height: 34px; margin: 0 auto; display: block; } -.dropzone .dz-hint { - font-family: var(--mono); font-size: 12px; color: var(--muted); - letter-spacing: 0.03em; margin-top: 10px; -} -.dz-status { - margin-top: 14px; font-family: var(--mono); font-size: 12.5px; - color: var(--field); min-height: 1.2em; -} - -/* ---- Footer --------------------------------------------------------------- */ -footer { - border-top: 1px solid var(--line); - padding: 48px 0 72px; - color: var(--faint); - font-family: var(--mono); font-size: 12.5px; letter-spacing: 0.02em; -} -footer a { color: var(--field); } -footer .prov { margin-top: 12px; color: var(--muted); line-height: 1.6; max-width: 80ch; } -footer .prov strong { color: var(--ink-2); } - -.stack-links { - display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px 22px; - margin-bottom: 16px; padding-bottom: 16px; - border-bottom: 1px solid var(--line); -} -.stack-links .stack-lead { - color: var(--faint); text-transform: uppercase; letter-spacing: 0.1em; -} -.stack-links a { color: var(--field); } -.stack-links a:hover { color: var(--magenta); } - -/* ---- Responsive ----------------------------------------------------------- */ -@media (max-width: 640px) { - body { font-size: 16px; } - .nav-links { display: none; } - .section > summary { gap: 12px; padding: 20px 18px; } - .section .num { padding-top: 4px; } - .hero .meta-row { gap: 16px; } - .cta.ghost { margin-left: 0; margin-top: 12px; } - .cmp { font-size: 0.88rem; } - .cmp td:first-child { white-space: normal; } -} - -/* ---- Reduced motion ------------------------------------------------------- */ -@media (prefers-reduced-motion: reduce) { - html { scroll-behavior: auto; } - *, *::before, *::after { - animation-duration: 0.001ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.001ms !important; - scroll-behavior: auto !important; - } - .cta:hover, .dropzone.is-dragover { transform: none; } -} diff --git a/ruv-explainer-rufield/vercel.json b/ruv-explainer-rufield/vercel.json deleted file mode 100644 index 449f67a..0000000 --- a/ruv-explainer-rufield/vercel.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "$schema": "https://openapi.vercel.sh/vercel.json", - "cleanUrls": true, - "trailingSlash": false, - "headers": [ - { - "source": "/assets/(.*)", - "headers": [ - { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" } - ] - }, - { - "source": "/(.*)\\.woff2", - "headers": [ - { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" }, - { "key": "Content-Type", "value": "font/woff2" } - ] - }, - { - "source": "/downloads/(.*)\\.zip", - "headers": [ - { "key": "Content-Type", "value": "application/zip" }, - { "key": "Cache-Control", "value": "public, max-age=300" } - ] - } - ] -} diff --git a/ruv-explainer-ruqu/.gitignore b/ruv-explainer-ruqu/.gitignore deleted file mode 100644 index ed85321..0000000 --- a/ruv-explainer-ruqu/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# Tooling noise -node_modules/ -.vercel/ -.DS_Store -*.log - -# Secrets never go in git -.env -.env.* - -# NOTE (recipe v1.3.1): the drop-in zip in downloads/ IS committed so Vercel serves it -# directly behind the .dropzone download button. downloads/ruqu-dropin.zip must NOT be ignored. -.vercel diff --git a/ruv-explainer-ruqu/README.md b/ruv-explainer-ruqu/README.md deleted file mode 100644 index ffa6032..0000000 --- a/ruv-explainer-ruqu/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# ruv-explainer-ruqu - -A plain-language **ExplainerSite** for [**ruvnet/ruqu**](https://github.com/ruvnet/ruqu) — -a pretend quantum computer (a faithful state-vector simulator) written in pure Rust and -compiled to WebAssembly, plus a real-time "is it safe to act?" coherence engine. - -Built as the second target of the **Repo-Primer Pipeline** (ADR-0001, Part II). One page -per repo; this is ruqu's. It is a static site — no build step, no dependencies. - -- **Source of truth:** `content/ruqu.canon.md` -- **Author of ruqu:** Reuven Cohen / [@ruvnet](https://github.com/ruvnet) -- **Provenance:** content grounded in the repo's own READMEs at HEAD - `026d63ef900ab689c863b6b3254f5dce8c068bf6` — no invented features. - Workspace v2.2.3 · `@ruvector/ruqu` v0.2.0 · `@ruvector/ruqu-wasm` v2.0.5. - -## Distinct aesthetic [Constraint K] - -Deep **indigo** substrate, **electric-magenta** + **violet** accents, **cyan** phosphor -highlight; **bloch-sphere / quantum-circuit** motifs. Deliberately NOT the amber/copper -"foundry" look of the MetaHarness site, and not a clone of any prior primer. - -## Dual-level visuals [D12 / gate E] - -Every section carries **both**: - -1. a **technical SVG** in `assets/diagrams/` — precise, labeled, accurate to the real - architecture/process (the tier-2 "how it actually works" diagram), and -2. a **friendly illustration** in `assets/img/` — the approachable tier-1 on-ramp, - generated with the `image-generation` skill (prompts saved as `gN.prompt.txt`). - -That dual-level coverage is the whole advantage over a README. - -## Files - -``` -ruv-explainer-ruqu/ -├ index.html — the site (collapsible numbered sections, learning-arc order) -├ styles.css — quantum/indigo theme tokens + layout -├ main.js — progressive enhancement (deep-link, live provenance) -├ favicon.svg — bloch-sphere mark -├ vercel.json — static hosting config -├ package.json — metadata (no deps, no build) -├ robots.txt -├ assets/ -│ ├ diagrams/ — technical SVGs (s01–s07, qubit, uc1–uc7, diff, dropin) -│ └ img/ — friendly raster art (g1–g8) + gN.prompt.txt -└ downloads/ — the drop-in .zip lands here (gitignored; ships via Release) -``` - -## Run locally - -It's a static site — open `index.html`, or: - -```bash -npx serve . # or: python3 -m http.server -``` - -## Deploy - -Vercel, git-connected, auto-deploy on push. Target host: -`https://ruv-explainer-ruqu.vercel.app`. diff --git a/ruv-explainer-ruqu/assets/diagrams/diff.svg b/ruv-explainer-ruqu/assets/diagrams/diff.svg deleted file mode 100644 index 1cb2d1d..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/diff.svg +++ /dev/null @@ -1,72 +0,0 @@ - - Why ruqu, not the tools you already have - A side-by-side comparison. Python quantum stacks like Qiskit and Cirq are powerful but heavy and cannot drop into a browser. Claude Code is a brilliant generalist but cannot actually run a quantum circuit or check whether your VQE energy is right. ruqu is pure Rust compiled to native and WebAssembly, a 180 KB gzip bundle that runs in a web page or as one npx command, with a SHA-256 witness log and a unique coherence engine. - - - - - - “I already have X — why ruqu too?” - - - - Qiskit / Cirq (Python) - “just use Claude Code” - other simulators - ruqu - - - - WEIGHT & PORTABILITY - - - ✗ Python runtime + big dependency tree - ✗ can’t drop into a browser - - — not a quantum tool; it would guess - the physics - - — vary; most are also Python-based or - server-bound - - ✓ pure Rust, no FFI - ✓ native and wasm32 - ✓ 180 KB gz → in a page - - - - CAN IT ACTUALLY RUN THE MATH? - - - ✓ yes, real simulation - (but heavy to set up and embed) - - ✗ can’t run a circuit - ✗ can’t check your VQE - energy is right - - ✓ usually yes - but no real-time - safety gate - - ✓ real state-vector math - ✓ SHA-256 witness log - reproducible, auditable - - - - THE UNIQUE PIECE - - - None of these ship a real-time “is it safe to act?” monitor for a quantum machine. - The coherence engine’s PERMIT / DEFER / DENY gate is ruv’s original contribution. - - ✓ the coherence engine - exists in no mainstream toolkit - - - - - On your own work: - Before — quantum ideas stay theoretical (tooling too heavy / hardware out of reach). After — you prototype, test, even monitor quantum workloads from a terminal, browser, or Rust app, today, free. - diff --git a/ruv-explainer-ruqu/assets/diagrams/dropin.svg b/ruv-explainer-ruqu/assets/diagrams/dropin.svg deleted file mode 100644 index c49e0bc..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/dropin.svg +++ /dev/null @@ -1,66 +0,0 @@ - - What is actually inside the ruqu drop-in kit - An annotated file tree of the ruqu-dropin.zip download, one folder with two halves. for-humans holds the plain-English primer plus a highlighted studio folder containing a NotebookLM audio overview to play first, a written report, and the prompt that made them. for-ai holds a single ruqu-kb.rvf brain (384-dim bge-small), its idmap and embed sidecars, a passages JSONL of every doc and all source, an ids index, an ask-kb command-line tool, a kb-mcp-server to wire it into Claude Code or Cursor, the kb.config and resolve-deps modules, and a package.json. Plus a README and manifest. Each file is labeled with a plain-English what-this-is. - - - - - - - What’s actually inside the download - ruqu-dropin.zip — one folder, two halves: one for you, one for your AI - - - ruqu-dropin/ - the one download · unzip into your project as kb/ - - - - ├─ for-humans/ - read & listen first — understand the tool - - ├─ ruqu-primer.md - └─ studio/ - - — the whole tool, in plain English (the comprehension arc) - - - - 🎧 ruqu-audio.m4a - 📄 ruqu-report.md - - - — NotebookLM audio overview · play this first (warm, jargon-free) - — the written deep-dive briefing (themes · quotes · honest limits) - - The studio media rides inside the zip — not just on the site. Start with the 🎧 audio overview. - - - - ├─ for-ai/ - point your assistant here so it answers from the real source, not guesses - - ├─ ruqu-kb.rvf - ├─ ruqu-kb.passages.jsonl - ├─ ruqu-kb.ids.json - ├─ ask-kb.mjs - ├─ kb-mcp-server.mjs - ├─ kb.config.mjs - └─ package.json - - - — the “brain” — one 384-dim bge-small vector DB (HNSW), runs anywhere Node 18+ does - — every doc + all source, full text, joined to each hit by id - — per-passage kind + preview index - — ask it a question from the command line - — wire it straight into Claude Code / Cursor (one MCP server) - — routing config + resolve-deps.mjs (portable dep loader) - — two deps; npm i then node ask-kb.mjs ruqu … - - One RVF file [recipe v1.3.1] — 384-dim Xenova/bge-small-en-v1.5: lightest, fastest, passed its answer-quality gate before shipping. - - - - └─ README.md + manifest.json - — what it is + the 3-step setup, plus provenance (date · source SHA · model · gate score) - diff --git a/ruv-explainer-ruqu/assets/diagrams/qubit.svg b/ruv-explainer-ruqu/assets/diagrams/qubit.svg deleted file mode 100644 index 36f8f6a..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/qubit.svg +++ /dev/null @@ -1,37 +0,0 @@ - - A bit versus a qubit, shown on a Bloch sphere - A normal bit is either 0 or 1. A qubit is a blend of both until you look, drawn as an arrow that can point anywhere on a Bloch sphere with 0 at the top pole and 1 at the bottom. That blend is what gives quantum its power and what makes it fragile. - - - - - - - A “qubit,” in one picture - - - A NORMAL BIT - - 0 - or - - 1 - one or the other — always definite - - - A QUBIT (on a Bloch sphere) - - - - - |0⟩ - |1⟩ - - - - the arrow can point - anywhere — a blend of - 0 and 1 until you look - - That blend is what gives quantum its power — and what makes it so fragile. - diff --git a/ruv-explainer-ruqu/assets/diagrams/s01.svg b/ruv-explainer-ruqu/assets/diagrams/s01.svg deleted file mode 100644 index a46d665..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/s01.svg +++ /dev/null @@ -1,64 +0,0 @@ - - Before and after ruqu: teaching a Bell state - Before ruqu, Aisha fights heavy Python installs and cloud credits and half the lab is gone. After ruqu, one npx command runs a real 2-qubit Bell-state simulation with no install, and every student runs the same circuit in their own browser, getting 00 or 11 with 50/50 odds. - - - - - - - - - - - - - - - - Aisha demos a Bell state to her intro-quantum class - Two qubits become “spookily” linked — measure one, you instantly know the other - - - - BEFORE - - Install a heavy Python quantum toolkit - Qiskit/Cirq + big dependency tree, on every laptop - … or sign up for cloud quantum credits that run out - - - Fight dependency errors in the lab - Nothing runs in the students’ own browsers - - - - Half the lab period is gone - … before anything quantum happens - - - - AFTER ruqu - - One command — no install - - npx @ruvector/ruqu simulate --qubits 2 - - - A real state-vector simulation runs - Outcome distribution prints in the terminal: - ~50% “00” · ~50% “11” (Bell signature) - - - - Every student runs the SAME circuit - in their own browser tab via the WASM package - Circuit(2) · h(0) · cnot(0,1) · sim.run - - - - - “Oh — that’s what it’s for.” - A real quantum computer’s behavior, in a browser tab or one terminal command — - so you can touch quantum without owning a quantum computer. The class is doing quantum in 5 minutes. - diff --git a/ruv-explainer-ruqu/assets/diagrams/s02.svg b/ruv-explainer-ruqu/assets/diagrams/s02.svg deleted file mode 100644 index d3b5545..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/s02.svg +++ /dev/null @@ -1,81 +0,0 @@ - - What ruqu actually gives you: three things - ruqu is a pure-Rust quantum simulator compiled to native and WebAssembly. It gives you three things: a state-vector simulator (the imitation quantum computer, ~25 qubits in browser, 32 in native Rust), ready-made algorithms (VQE, Grover, QAOA, surface-code error correction), and a coherence engine that decides PERMIT, DEFER, or DENY before each operation. - - - - - - - One pure-Rust engine → runs in three places, gives you three things - - - - ruqu — one codebase, pure Rust (no Python, no C++) - compiles to native & WebAssembly (wasm32) - - - - in a web page (WASM) - - npx @ruvector/ruqu - - inside a Rust program - - - - - THE THREE THINGS IT GIVES YOU - - - - - - - 1 · State-vector - simulator - The imitation quantum - computer itself — it tracks - every possible state at once. - - ~25 qubits browser / Node - 32 qubits native Rust - Cost doubles with every - qubit — that’s the ceiling. - - - - 2 · Ready-made - algorithms - Call them, don’t build them: - - - VQEchemistry · lowest energy - - Groverfast search - - QAOAoptimization / best split - - Surface codeerror correction - - The standard near-term toolkit. - - - - 3 · Coherence - engine - ruv’s original idea - A classical “nervous system” - that watches the error pattern - and, before each operation, - asks: “is it still safe to act?” - - PERMIT - DEFER - DENY - - Exists in no mainstream - toolkit. Turns a fragile - experiment into a - self-aware machine. - diff --git a/ruv-explainer-ruqu/assets/diagrams/s03.svg b/ruv-explainer-ruqu/assets/diagrams/s03.svg deleted file mode 100644 index 774cd55..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/s03.svg +++ /dev/null @@ -1,52 +0,0 @@ - - Why this is a problem now: real quantum machines are out of reach - Real quantum computers are rare, cost millions, live in fridges colder than space, and make mistakes constantly. So almost nobody gets hands-on time. The way to learn, prototype, or check your math is to simulate: run a faithful imitation on an ordinary computer. - - - - - - - Real quantum hardware is scarce — so you simulate - - - REAL QUANTUM COMPUTERS - - - 🍴Rareonly a handful exist worldwide - - 💰Cost millionscloud time burns real money fast - - ❄Colder than spacelive inside dilution fridges - - ⚡Make mistakes constantlyqubits are fragile — errors everywhere - - - Result: almost nobody gets hands-on time - so how do you learn, prototype, or check your math? - - - - you simulate - - - - Run a faithful imitation - on an ordinary computer - - - A simulator acts EXACTLY like - a real quantum machine — same physics - - - ✓Learn quantum without a lab - ✓Prototype an idea for free - ✓Validate your math before paying - ✓Catch bugs before real hardware time - - - ruqu is that faithful imitation - - A free, faithful simulator lets you learn, prototype, and validate today — - and catch your bugs before you burn money on actual hardware time. - diff --git a/ruv-explainer-ruqu/assets/diagrams/s04.svg b/ruv-explainer-ruqu/assets/diagrams/s04.svg deleted file mode 100644 index 0fd7ec8..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/s04.svg +++ /dev/null @@ -1,88 +0,0 @@ - - How ruqu runs a quantum circuit: from gates to a measured outcome - You describe a circuit as qubits and gates. ruqu builds a state vector that holds every possible state at once, applies each gate as a matrix operation, optionally checks the coherence engine for PERMIT or DEFER or DENY, then measures to collapse the state into a real bitstring with the right probabilities. A SHA-256 witness log records each step so the run is reproducible. - - - - - - - How a circuit actually runs inside ruqu - Using the Bell-state circuit as the worked example - - - - 1 · You describe a circuit - qubits + gates - - - - q0 - q1 - - - H - - - - - - superpose - entangle (CNOT) - - - - 2 · ruqu builds a state vector - one complex number (amplitude) per - possible outcome — every state, at once - - |00⟩ amplitude 0.707 - |01⟩ amplitude 0.000 - |10⟩ amplitude 0.000 - |11⟩ amplitude 0.707 - - 2 qubits → 4 amplitudes. Add a qubit, - the list doubles — that’s the 25/32-qubit wall. - - - - - - - 3 · Each gate = a matrix applied to the vector - H spreads one qubit into a 50/50 blend; CNOT flips - the target when the control is 1 — that links them. - Pure linear algebra. No randomness yet — the math is exact. - - - - 4 · (optional) coherence engine checks: safe to act? - - PERMIT - DEFER - DENY - - A real-time min-cut on the error pattern decides whether to - proceed, wait, or quarantine — before the operation runs. - - - - 5 · Measure → the state collapses to a real bitstring - Now randomness enters: amplitudes become probabilities - (amplitude squared). You get one concrete answer: - - “00” ~50% · “11” ~50% - - - - - 6 · SHA-256 witness log records every step - a hash chain → the run is reproducible and auditable, not hallucinated. - - - - - - - - diff --git a/ruv-explainer-ruqu/assets/diagrams/s05.svg b/ruv-explainer-ruqu/assets/diagrams/s05.svg deleted file mode 100644 index ec85a40..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/s05.svg +++ /dev/null @@ -1,61 +0,0 @@ - - What a solved state looks like - When ruqu is working for you, quantum stops being theoretical. A terminal prints a real Bell-state distribution, every student's browser runs the same circuit, a Rust program returns a ground-state energy, and a health gauge flags trouble a median of four cycles before failure. Quantum ideas you could only read about become things you run. - - - - - - What “solved” looks like — quantum you can actually run - From “I’ve read about this” to “I just ran it” - - - - - A terminal prints a real distribution - - - $ npx @ruvector/ruqu simulate --qubits 2 - 00 █████████████ 0.498 - 01 ░ 0.001 - 10 ░ 0.000 - 11 █████████████ 0.501 - - - - - Every browser runs the same circuit - - - - - 00 - 11 - 50 / 50 - no server, no install - - - - - A Rust program returns a ground-state energy - - let result = VQE::new(...).optimize(); - result.energy → -1.137 Hartree - A working chemistry prototype — with zero hardware. - The core question behind drug & materials design, - answered on your laptop. - - - - A health gauge warns before things break - - - - - PERMIT - DEFER - DENY - - In tests: flagged trouble a median of 4 cycles - before failure (85.7% recall) — vendor-measured. - diff --git a/ruv-explainer-ruqu/assets/diagrams/s06.svg b/ruv-explainer-ruqu/assets/diagrams/s06.svg deleted file mode 100644 index 5b13d9e..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/s06.svg +++ /dev/null @@ -1,75 +0,0 @@ - - How to implement ruqu: three surfaces, the same engine - Pick the surface that fits your job. In the terminal, run npx @ruvector/ruqu with a subcommand. In a web page, npm install @ruvector/ruqu-wasm and build a Circuit. In a Rust program, add the crate and call the algorithms directly. All three drive the same pure-Rust state-vector engine. - - - - - - - Three ways in — pick the one that fits your job - - - - Terminal · CLI - fastest demo, nothing to install - - - npx @ruvector/ruqu \ - simulate --qubits 2 - npx @ruvector/ruqu \ - grover --qubits 3 \ - --target 5 - npx @ruvector/ruqu qaoa \ - --nodes 4 - - Good for: live demos, quick - experiments, teaching. - @ruvector/ruqu v0.2.0 - - - - Web page · WASM - in-page, no backend server - - - npm i @ruvector/ruqu-wasm - const c = new Circuit(2); - c.h(0); - c.cnot(0, 1); - sim.run(c); - state.measureAll(); - // "00" or "11" - - Good for: live widgets, - teaching apps, ~25 qubits. - @ruvector/ruqu-wasm v2.0.5 · 180KB gz - - - - Rust program · crate - full power, up to 32 qubits - - - let h = Hamiltonian:: - from_pauli_strings([..]); - let a = Ansatz::uccsd(..); - VQE::new(h, a) - .optimize(); - // also: SurfaceCode, - // fabric.process_cycle, - // plan_execution(..) - - Good for: chemistry, error - correction, coherence engine. - workspace v2.2.3 - - - - - - - The same pure-Rust state-vector engine - Same physics underneath all three surfaces — you just choose the door. - No Python · no C++ · no install for the CLI / web paths - diff --git a/ruv-explainer-ruqu/assets/diagrams/s07.svg b/ruv-explainer-ruqu/assets/diagrams/s07.svg deleted file mode 100644 index e9c69b8..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/s07.svg +++ /dev/null @@ -1,55 +0,0 @@ - - How to start in 60 seconds - Step one: open a terminal and run npx @ruvector/ruqu simulate --qubits 2, no install. Step two: see the Bell-state distribution print. Step three: drop @ruvector/ruqu-wasm into a web page for an in-browser widget. You are doing quantum in the first minute. - - - - - - - Start in 60 seconds — no install - - - 1 - - Open a terminal, run: - - npx @ruvector/ruqu \ - simulate --qubits 2 - npx fetches it on the fly — - nothing to install first. - No Python. No setup. - - - - - 2 - - Watch quantum happen: - - - 00 █████████ .50 - 01 ░ .00 - 10 ░ .00 - 11 █████████ .50 - - The Bell-state signature, - printed for real. - - - - - 3 - - Want it in a - web page? - - npm i @ruvector/ - ruqu-wasm - Drop it in — an - in-browser widget - your visitors run. - - You’re doing quantum in the first minute — in a terminal or a browser tab. - Then explore the gallery above for search (Grover), optimization (QAOA), chemistry (VQE), and the coherence engine. - diff --git a/ruv-explainer-ruqu/assets/diagrams/uc1.svg b/ruv-explainer-ruqu/assets/diagrams/uc1.svg deleted file mode 100644 index aa65cc8..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/uc1.svg +++ /dev/null @@ -1,58 +0,0 @@ - - Grover's algorithm: amplify the target answer - A flat list of equally-likely items goes through a few quantum amplify rounds. Each round nudges probability toward the target item until it spikes far above the rest. Grover finds the needle in about the square root of N steps instead of N. - - - - - - - Quantum search — amplify the answer until it spikes - npx @ruvector/ruqu grover --qubits 3 --target 5 - - - START · all equal - - - - - - - - item #5 (target) = same as the rest - - - round 1 - - - AMPLIFY · target rises - - - - - - - each round nudges probability up - - - ~√N rounds - - - RESULT · spike on target - - - - - - - measure → lands on #5 with high probability - - - - You get - the found bitstring - + its probability - Grover’s quadratic - speedup — √N vs N - made visible - diff --git a/ruv-explainer-ruqu/assets/diagrams/uc2.svg b/ruv-explainer-ruqu/assets/diagrams/uc2.svg deleted file mode 100644 index 2031329..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/uc2.svg +++ /dev/null @@ -1,60 +0,0 @@ - - QAOA: split a network into two best groups - A 4-node ring graph goes through layers of QAOA, a quantum approximate optimizer, which returns a partition that colors the nodes into two groups and reports the cut value. It gives a hands-on feel for quantum approximate advantage on a classic NP-hard MaxCut problem. - - - - - - Optimization (MaxCut) — find the best way to split a network - npx @ruvector/ruqu qaoa --nodes 4 - - - A 4-node ring - - - - - - - - - which split cuts the most edges? - - - - - QAOA layers - - cost layer (γ) - mixer layer (β) - repeat × p - - tune the angles to push toward a good split - - - - - A two-group split - - - - - - - - - - - - magenta group vs cyan group - - - - You get - a partition + - its cut value - a feel for quantum - approximate advantage - no math PhD needed - diff --git a/ruv-explainer-ruqu/assets/diagrams/uc3.svg b/ruv-explainer-ruqu/assets/diagrams/uc3.svg deleted file mode 100644 index 6a2351e..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/uc3.svg +++ /dev/null @@ -1,53 +0,0 @@ - - VQE: a quantum chemistry prototype in Rust - Build a Hamiltonian from Pauli strings, pick a UCCSD ansatz, then call VQE optimize. A parameterized quantum circuit is tuned step by step until the energy curve settles to its minimum, returning an estimated ground-state energy in Hartrees, with no quantum hardware. - - - - - - - Quantum chemistry — a molecule’s lowest-energy state - Hamiltonian::from_pauli_strings([..]) · Ansatz::uccsd(..) · VQE::new(..).optimize() - - - Your molecule - - - - - - - - encoded as a Hamiltonian - - - - - Parameterized circuit (ansatz) - - - - Rθ - Rθ - Rθ - - tunable angles θ - - - - - Energy settles to its minimum - - - energy - optimizer steps - - - each step lowers the estimate - - - - You get: result.energy - → an estimated ground-state energy (Hartrees) - diff --git a/ruv-explainer-ruqu/assets/diagrams/uc4.svg b/ruv-explainer-ruqu/assets/diagrams/uc4.svg deleted file mode 100644 index 89d36ec..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/uc4.svg +++ /dev/null @@ -1,77 +0,0 @@ - - Surface-code error correction - A clean distance-3 lattice of qubits gets realistic noise injected, scattering red error dots. The code measures tell-tale syndromes, then a minimum-weight perfect-matching decoder pairs them up and corrects them, recovering a clean lattice. You can inspect the before, the detected syndromes, and the recovered state. - - - - - - Error correction — how quantum survives its own mistakes - SurfaceCode::new(distance:3) · apply_noise(.., 0.01) · Decoder::mwpm().correct(..) - - - - 1 · CLEAN lattice (d=3) - - - - - - - - - - - - a logical qubit, encoded - - - - - 2 · NOISE + syndromes - - - - - - - - - - - - - - - - - red = errors · amber = detected syndromes - - - - - 3 · MWPM matches & corrects - - - - - - - - - - - - - - minimum-weight perfect matching pairs syndromes - - - - A before/after you can inspect - ● corrupted state - ◆ detected syndromes - ✓ recovered clean lattice - Learn why quantum machines - need error correction — hands-on. - diff --git a/ruv-explainer-ruqu/assets/diagrams/uc5.svg b/ruv-explainer-ruqu/assets/diagrams/uc5.svg deleted file mode 100644 index 6d80f69..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/uc5.svg +++ /dev/null @@ -1,65 +0,0 @@ - - The coherence engine: a real-time is-it-safe-to-act monitor - Each cycle's syndrome data is fed into fabric.process_cycle. A real-time min-cut over the error pattern decides whether the machine is healthy, borderline, or collapsing, returning PERMIT, DEFER, or DENY before the next operation. Healthy regions keep running while a bad region is quarantined. In tests it flagged trouble a median of four cycles before failure with 85.7 percent recall, at 468 nanosecond P99 latency and 3.8 million decisions per second. - - - - - - The coherence engine — “is it still safe to act?” (ruv’s original idea) - fabric.process_cycle(syndrome_data) → Permit | Defer | Deny - - - 1 · syndrome stream - - - cycle t-2 - cycle t-1 - cycle t (errors↑) - - each cycle = a snapshot - of where errors fired - fed in, cycle by cycle - - - - - 2 · real-time min-cut on the error pattern - - - - - - - - - - min-cut - - - - - - cheapest cut separating healthy from collapsing region - - - - - 3 · decision, before the next op - - PERMIThealthy — keep running - DEFERborderline — wait - DENYcollapsing — quarantine - - healthy regions keep running; a bad region is isolated - - - - Measured (vendor, Apple M2 / specified conditions — indicative, not independently audited): - - ● median 4 cycles’ early warning - ● 85.7% recall - ● 468 ns P99 latency - ● 3.8M decisions / sec - - diff --git a/ruv-explainer-ruqu/assets/diagrams/uc6.svg b/ruv-explainer-ruqu/assets/diagrams/uc6.svg deleted file mode 100644 index 320c74b..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/uc6.svg +++ /dev/null @@ -1,47 +0,0 @@ - - The cost-model planner: pick the right backend automatically - A circuit too big for the obvious track-every-possibility method is handed to plan_execution. A cost model predicts memory, runtime, and fidelity, then routes the circuit to the cheapest viable backend of five: StateVector for exact small jobs, Stabilizer for Clifford-only circuits with millions of qubits, TensorNetwork, Clifford+T, or a real hardware profile. Decompose can split a circuit first. - - - - - - The planner — route a big circuit to the cheapest viable engine - plan_execution(&circuit, &PlannerConfig::default()) · decompose(&circ, 25) - - - - One circuit - too big for the - naive method - would run out of memory - - - - - - cost-model planner - predicts, per backend: - - memory - runtime - fidelity - - - - - - … routes to the cheapest of FIVE backends - - StateVectorexact, small jobs (≤25/32 qubits)★ chosen - StabilizerClifford-only — millions of qubits - TensorNetworklow-entanglement / structured circuits - Clifford+Tnear-Clifford with few T-gates - Hardware profileIBM / IonQ / Rigetti / Braket (sim fallback) - - - - - You get: a feasible run where a naive simulator would have crashed. - Honest note: Clifford+T isn’t in the auto-router yet, and the “millions of qubits” figure is Stabilizer-only (Clifford circuits). - diff --git a/ruv-explainer-ruqu/assets/diagrams/uc7.svg b/ruv-explainer-ruqu/assets/diagrams/uc7.svg deleted file mode 100644 index b48ce81..0000000 --- a/ruv-explainer-ruqu/assets/diagrams/uc7.svg +++ /dev/null @@ -1,48 +0,0 @@ - - In-page quantum: a live widget via WebAssembly, no server - A browser tab loads the @ruvector/ruqu-wasm WebAssembly module. The page builds a Circuit, runs genuine state-vector simulation client-side up to about 25 qubits, and measureAll returns a live result. Your visitors run the quantum simulation themselves with zero server cost. - - - - - - - In-page quantum — a live widget, no backend server - new Circuit(3) · sim.run(circuit) · state.measureAll() - - - - - - A browser tab - your teaching app or website - no install for visitors — - it just loads with the page - npm i @ruvector/ruqu-wasm - 180 KB gz · v2.0.5 - - - - - - WASM module - the pure-Rust state-vector - engine, compiled to wasm32 - genuine simulation, - client-side, ~25 qubits - ~1 GB browser memory at 25 - - - - - - live measurement readout - - 010 - 101 - - each click → a fresh measured outcome - zero server cost - - An interactive quantum widget your visitors run themselves — entirely in their browser. - diff --git a/ruv-explainer-ruqu/assets/img/README.md b/ruv-explainer-ruqu/assets/img/README.md deleted file mode 100644 index acc7778..0000000 --- a/ruv-explainer-ruqu/assets/img/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# Friendly raster art (Tier-1 on-ramp visuals) - -These are the approachable, human-first illustrations for the ruqu ExplainerSite — -the friendly half of the mandated dual-level visuals [D19/E]. The precise, labeled, -architecturally-true diagrams live in `../diagrams/` as crisp inline/`` SVG (Tier-2). - -Generated with the `image-generation` skill (Google Gemini). Aesthetic [Constraint K]: -deep indigo (#13102b / #1b1640) + electric-magenta (#ff3df0) + violet (#8b5cff) + cyan -glow (#39e8ff); bloch-sphere / quantum-circuit motifs. DISTINCT from the MetaHarness -amber/charcoal foundry look. - -| File | Where it lands | Concept | -|------|----------------|---------| -| g1.png | Hero | quantum orb in a laptop — "a quantum computer on your normal machine" | -| g2.png | §01 grounding example | teacher shows a Bell pair in the browser | -| g3.png | §08 gallery — Grover | magnifying glass finds the glowing needle | -| g4.png | §08 gallery — VQE | molecule + energy curve dipping to its minimum | -| g5.png | §08 gallery — coherence | green/amber/red guardian over a quantum chip | -| g6.png | §09 drop-in | the kit splitting into "for you" / "for your AI" | -| g7.png | og:image / social | the ruqu orb, text-free share card | -| g8.png | §differentiation | heavy Python crate vs tiny Rust gear in a browser tab | - -Each `gN.prompt.txt` holds the exact prompt used (auditable / reusable per [D19]). diff --git a/ruv-explainer-ruqu/assets/img/g1.png b/ruv-explainer-ruqu/assets/img/g1.png deleted file mode 100644 index f60104f..0000000 Binary files a/ruv-explainer-ruqu/assets/img/g1.png and /dev/null differ diff --git a/ruv-explainer-ruqu/assets/img/g1.prompt.txt b/ruv-explainer-ruqu/assets/img/g1.prompt.txt deleted file mode 100644 index e7a8490..0000000 --- a/ruv-explainer-ruqu/assets/img/g1.prompt.txt +++ /dev/null @@ -1 +0,0 @@ -g1 — HERO (16:9). Friendly cinematic 3D: a glowing translucent bloch-sphere quantum orb (latitude/longitude lines + small state-vector arrow) floating above an open laptop on a wooden desk; magenta+violet glow, cyan rim-light; faint quantum circuit ribbons trailing from the screen; deep indigo (#13102b) background, soft bokeh; warm, inviting, negative space on the left. Tier-1 friendly on-ramp. diff --git a/ruv-explainer-ruqu/assets/img/g2.png b/ruv-explainer-ruqu/assets/img/g2.png deleted file mode 100644 index a9b6c17..0000000 Binary files a/ruv-explainer-ruqu/assets/img/g2.png and /dev/null differ diff --git a/ruv-explainer-ruqu/assets/img/g2.prompt.txt b/ruv-explainer-ruqu/assets/img/g2.prompt.txt deleted file mode 100644 index 39673bd..0000000 --- a/ruv-explainer-ruqu/assets/img/g2.prompt.txt +++ /dev/null @@ -1 +0,0 @@ -g2 — §01 grounding example (4:3). Inside a browser frame, a teacher gestures to two glowing qubit orbs linked by a magenta thread (a Bell pair); delighted cartoon students watch; 00/11 labels float nearby; magenta/violet glow on deep indigo (#1b1640); warm classroom feel. diff --git a/ruv-explainer-ruqu/assets/img/g3.png b/ruv-explainer-ruqu/assets/img/g3.png deleted file mode 100644 index b3982c8..0000000 Binary files a/ruv-explainer-ruqu/assets/img/g3.png and /dev/null differ diff --git a/ruv-explainer-ruqu/assets/img/g3.prompt.txt b/ruv-explainer-ruqu/assets/img/g3.prompt.txt deleted file mode 100644 index abd5b8b..0000000 --- a/ruv-explainer-ruqu/assets/img/g3.prompt.txt +++ /dev/null @@ -1 +0,0 @@ -g3 — gallery: quantum search (4:3). Glowing magnifying glass over a haystack with one spotlighted glowing needle in electric magenta; violet lens, cyan rim; deep indigo (#13102b); playful, approachable; faint circuit arc behind. diff --git a/ruv-explainer-ruqu/assets/img/g4.png b/ruv-explainer-ruqu/assets/img/g4.png deleted file mode 100644 index a7dbd1e..0000000 Binary files a/ruv-explainer-ruqu/assets/img/g4.png and /dev/null differ diff --git a/ruv-explainer-ruqu/assets/img/g4.prompt.txt b/ruv-explainer-ruqu/assets/img/g4.prompt.txt deleted file mode 100644 index a1475b0..0000000 --- a/ruv-explainer-ruqu/assets/img/g4.prompt.txt +++ /dev/null @@ -1 +0,0 @@ -g4 — gallery: quantum chemistry / VQE (4:3). Small molecule of glowing orbs + bonds above a cyan energy curve dipping to a glowing lowest point marked with a star; magenta/violet orbs; deep indigo (#1b1640); warm, rounded. diff --git a/ruv-explainer-ruqu/assets/img/g5.png b/ruv-explainer-ruqu/assets/img/g5.png deleted file mode 100644 index 6afaad9..0000000 Binary files a/ruv-explainer-ruqu/assets/img/g5.png and /dev/null differ diff --git a/ruv-explainer-ruqu/assets/img/g5.prompt.txt b/ruv-explainer-ruqu/assets/img/g5.prompt.txt deleted file mode 100644 index 20bf6ac..0000000 --- a/ruv-explainer-ruqu/assets/img/g5.prompt.txt +++ /dev/null @@ -1 +0,0 @@ -g5 — gallery: coherence engine monitor (4:3). Rounded traffic-light health gauge (green/amber/red, green brightest) watching over a glowing quantum chip with a bloch orb; magenta/violet accents, cyan chip glow; deep indigo (#13102b); reassuring guardian feel; small heartbeat line. diff --git a/ruv-explainer-ruqu/assets/img/g6.png b/ruv-explainer-ruqu/assets/img/g6.png deleted file mode 100644 index d599f2c..0000000 Binary files a/ruv-explainer-ruqu/assets/img/g6.png and /dev/null differ diff --git a/ruv-explainer-ruqu/assets/img/g6.prompt.txt b/ruv-explainer-ruqu/assets/img/g6.prompt.txt deleted file mode 100644 index 12cff8c..0000000 --- a/ruv-explainer-ruqu/assets/img/g6.prompt.txt +++ /dev/null @@ -1 +0,0 @@ -g6 — §drop-in kit (4:3). Tidy open glowing download box splitting into two halves: left = friendly person icon ('for you'), right = friendly robot/AI icon ('for your AI'); magenta seam; magenta/violet glow, cyan rim; deep indigo (#1b1640); clean, organized, approachable. diff --git a/ruv-explainer-ruqu/assets/img/g7.png b/ruv-explainer-ruqu/assets/img/g7.png deleted file mode 100644 index 20c7916..0000000 Binary files a/ruv-explainer-ruqu/assets/img/g7.png and /dev/null differ diff --git a/ruv-explainer-ruqu/assets/img/g7.prompt.txt b/ruv-explainer-ruqu/assets/img/g7.prompt.txt deleted file mode 100644 index c1b533c..0000000 --- a/ruv-explainer-ruqu/assets/img/g7.prompt.txt +++ /dev/null @@ -1 +0,0 @@ -g7 — social share card / og:image (16:9, text-free). Single luminous bloch-sphere orb (lat/long lines + state arrow) centered, magenta/violet glow, cyan rim, thin radiating circuit lines + gate squares; deep indigo (#13102b) with radial bokeh; premium, inviting. diff --git a/ruv-explainer-ruqu/assets/img/g8.png b/ruv-explainer-ruqu/assets/img/g8.png deleted file mode 100644 index 76693fd..0000000 Binary files a/ruv-explainer-ruqu/assets/img/g8.png and /dev/null differ diff --git a/ruv-explainer-ruqu/assets/img/g8.prompt.txt b/ruv-explainer-ruqu/assets/img/g8.prompt.txt deleted file mode 100644 index a454784..0000000 --- a/ruv-explainer-ruqu/assets/img/g8.prompt.txt +++ /dev/null @@ -1 +0,0 @@ -g8 — 'why this vs what you have' (16:9). Side-by-side: left = heavy crate with tangled cables + python snake, muted/grey-violet (heavy Python stack); right = tiny brilliant glowing Rust gear spinning in a small browser tab, magenta/violet/cyan glow (lightweight Rust-in-browser); deep indigo (#1b1640); playful, approachable. diff --git a/ruv-explainer-ruqu/favicon.svg b/ruv-explainer-ruqu/favicon.svg deleted file mode 100644 index 049a45a..0000000 --- a/ruv-explainer-ruqu/favicon.svg +++ /dev/null @@ -1,25 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/ruv-explainer-ruqu/index.html b/ruv-explainer-ruqu/index.html deleted file mode 100644 index 5b30ac1..0000000 --- a/ruv-explainer-ruqu/index.html +++ /dev/null @@ -1,880 +0,0 @@ - - - - - - ruqu — a pretend quantum computer that runs on your laptop - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
-

- An independent explainer for - Reuven Cohen’s (@ruvnet) - ruqu — built to help you - implement his technology. Part of the - ruvector ecosystem. - Not affiliated — an independent walkthrough of the open-source project. - Built with the Ruv-Explainer Repo-Primer Pipeline ↗ -

-

- - Updated 2026-06-19 · source @ 026d63e · workspace v2.2.3 -

-
-
- - -
- -
- - -
-
-
-
-
-

ruvnet · ruqu · quantum execution engine

-

A quantum computer
on your normal laptop.

-

- ruqu is a tiny, fast program that acts exactly like a - real quantum machine — so you can build and test quantum ideas before the - expensive hardware exists, right in your browser or your terminal. Written in pure - Rust, it runs as npx @ruvector/ruqu or drops straight into a web page. - No Python. No install. -

-

- An independent explainer for - Reuven Cohen’s (@ruvnet) - ruqu — - built to help you implement his technology. -

- - -
-
- A glowing translucent bloch-sphere quantum orb floating above an open laptop on a desk, with quantum-circuit ribbons trailing from the screen — magenta and violet on deep indigo. -
-
- - -
-

- In one sentence: ruqu is a pretend quantum computer that runs on your - normal laptop — a faithful imitation of a real quantum machine, so you can - learn, prototype, and check your quantum ideas today, for free, without owning (or - renting) million-dollar hardware. -

-
-
-
- - -
-
- - -
- - 01 - -

“Oh — that’s what it’s for.”

- Start here — one concrete, relatable example before anything else -
- -
-
-

- Meet Aisha. She teaches an undergrad “intro to quantum - computing” class and is not a quantum physicist herself. She uses - Claude Code to prepare her demos. Today she wants to show the famous - Bell state: two qubits that become “spookily” linked, so - measuring one instantly tells you the other. -

-

- First, what’s a “qubit”? A normal bit is either 0 or 1. A - qubit (a quantum bit) can be a blend of both at once — - until you look. That blend is what gives quantum its power, and what makes it so fragile: -

- -
-
- Technical · precise SVG - A diagram contrasting a normal bit (0 or 1) with a qubit drawn as an arrow on a Bloch sphere, pointing anywhere between the 0 pole at top and the 1 pole at bottom. -
The mechanics. A qubit’s state is an arrow on a Bloch sphere — not just 0 or 1, but any blend, until measured.
-
-
- Friendly · the on-ramp - A warm illustration: inside a browser window, a teacher gestures to two glowing orbs linked by a magenta thread — a Bell pair — while delighted students watch. Labels 00 and 11 float nearby. -
The feeling. Aisha shows her class two glowing qubits that are linked — a “Bell pair” — running live in the browser.
-
-
- -

Before ruqu: to demo a Bell state live, Aisha would normally have to - install a heavy Python quantum toolkit, fight dependency errors on the classroom laptops, - or sign her class up for cloud quantum credits that run out. Half the lab period is gone - before anything quantum happens — and nothing runs in the students’ own browsers.

- -

After ruqu: she types one command — no install — and a real - state-vector simulation runs, printing the outcome (roughly 50% “00” and 50% - “11”, the Bell-state signature). For the web lab she drops the - @ruvector/ruqu-wasm package into a page; in about ten lines, every student - watches the same circuit run in their own browser tab. The - whole class is doing quantum in the first five minutes.

- -
# In a terminal — nothing to install:
-npx @ruvector/ruqu simulate --qubits 2
-# → prints ~50% "00" and ~50% "11" (the Bell signature)
-
-# In a web page — every student runs it themselves:
-const circuit = new Circuit(2);
-circuit.h(0);          // put qubit 0 into a 50/50 blend
-circuit.cnot(0, 1);    // link (entangle) the two qubits
-sim.run(circuit);      state.measureAll();  // → "00" or "11"
- -
- Technical · before → after - A before-and-after diagram. Before ruqu: heavy Python installs, dependency errors, cloud credits, and half the lab period gone. After ruqu: one npx command runs a real Bell-state simulation, and every student runs the same circuit in their own browser, getting 00 or 11 with 50/50 odds. -
The whole arc on one canvas. Heavy setup and lost lab time on the left; one command, a real distribution, and every student’s browser on the right.
-
- -
The “oh, that’s what it’s for” line: - it’s a real quantum computer’s behavior, in a browser tab or one terminal - command — so you can actually touch quantum without owning a quantum computer.
-
-
- - -
- - 02 - -

What ruqu actually is

- Past the “quantum execution intelligence engine” pitch — in plain terms -
- -
-
-

The repo’s own headline calls ruqu “a quantum execution intelligence - engine … a layered operating stack that decides how, where, and whether to run - quantum workloads.” True — but it means nothing to a normal person. - Here’s the down-to-earth version:

-
    -
  • A “quantum computer” is a radically different kind of - computer that, for certain problems (designing a drug molecule, finding the best route, - cracking a search), can try a huge number of possibilities at once. The catch: - real ones are rare, cost millions, live in fridges colder than space, and make mistakes - constantly.
  • -
  • The problem: almost nobody can get hands-on time on one. So how do - you learn quantum, prototype an idea, or check your math? You simulate — - run a faithful imitation on an ordinary computer.
  • -
  • ruqu is that faithful imitation, written from scratch in - Rust (a fast, safe language) with “no Python, no C++, no - heavyweight dependencies.” Because it’s also compiled to - WebAssembly, the same simulator runs in three places with zero - install: in a web page, from your terminal with one npx command, or inside - a Rust program.
  • -
- -

It gives you three things:

- -
-
- Technical · the architecture - A diagram: one pure-Rust engine compiles to native and WebAssembly, running in a web page, via npx, or inside Rust. It gives three things: a state-vector simulator (about 25 qubits in browser, 32 in native Rust), ready-made algorithms (VQE, Grover, QAOA, surface-code error correction), and a coherence engine returning PERMIT, DEFER, or DENY. -
One engine, three surfaces, three gifts: the simulator, the ready-made algorithms, and the coherence engine.
-
-
- Friendly · the on-ramp - A friendly illustration of a glowing quantum orb floating above an open laptop with circuit ribbons — a quantum computer's behavior on a normal machine. -
The picture to hold onto: a real quantum machine’s behavior, living inside your ordinary laptop.
-
-
- -
    -
  1. A state-vector simulator — the imitation quantum computer itself - (up to ~25 qubits in a browser/terminal, up to 32 in native Rust).
  2. -
  3. Ready-made quantum algorithms you can just call — VQE - (chemistry / find a molecule’s lowest energy), Grover (fast search), - QAOA (optimization), and surface-code error correction.
  4. -
  5. A novel “coherence engine” — a classical nervous - system that watches a quantum machine’s error pattern in real time and says - PERMIT / DEFER / DENY before each operation: “is it still safe to - act, or is this thing about to fall apart?”
  6. -
-
-
- - -
- - 03 - -

Why this matters — and why now

- The stakes: what it does, why you care, why you need it -
- -
-
-

What does it actually do? It pretends to be a quantum computer on your - normal machine, accurately — so you can run quantum programs, test quantum algorithms, - and study quantum error correction without owning (or renting) real quantum hardware.

-

Why do you care? Because real quantum machines are scarce, costly, and - noisy. A faithful free simulator lets you learn, prototype, and validate today — and - catch your bugs before you burn money on actual hardware time.

-

Why do you need it? The popular alternatives are heavy Python stacks - (Qiskit, Cirq) that pull in big dependency trees and don’t run cleanly in a browser - or as a one-line terminal command. ruqu is pure Rust → WebAssembly: tiny, fast, - embeddable, and runnable with no Python install and no setup.

-

Why is it important? It also ships ruv’s original idea — - the coherence engine — a real-time “is it safe to act?” - monitor that turns a quantum computer “from a fragile experiment into a self-aware - machine,” the missing piece for running long, trustworthy quantum jobs.

- -
-
- Technical · the gap & the fix - A diagram: real quantum computers are rare, cost millions, live colder than space, and make mistakes constantly — so almost nobody gets hands-on time. The fix: run a faithful imitation on an ordinary computer, which lets you learn, prototype, validate, and catch bugs before paying. ruqu is that imitation. -
Why simulation, not hardware. Four reasons real machines are out of reach — and why a faithful imitation is the practical answer today.
-
-
- Friendly · the on-ramp - A playful comparison: a heavy crate with a tangled python snake (heavy Python stack) versus a tiny glowing Rust gear spinning happily in a browser tab (lightweight Rust-in-browser). -
The trade in one glance: a heavy Python stack versus a tiny Rust engine that runs right in a browser tab.
-
-
-
-
- - -
- - 04 - -

How it works

- From the gates you write to a measured outcome — the real pipeline -
- -
-
-

You describe a circuit as qubits and gates. ruqu builds a - state vector — one number (an “amplitude”) for every - possible outcome, so it tracks every state at once. Each gate is applied as a - matrix operation (pure linear algebra, exact). Then you measure, which - collapses that vector into one real bitstring with the right probabilities. A SHA-256 - witness log records each step, so the run is reproducible — not - hallucinated.

-

This is also where the 25/32-qubit ceiling comes from: every qubit you - add doubles the size of the state vector. Two qubits need 4 amplitudes; ten need - 1,024; twenty-five need over 33 million. That doubling is the real, honest limit.

- -
-
- Technical · the real process - A six-step diagram of how a circuit runs inside ruqu, using the Bell-state circuit: (1) you describe a circuit with an H gate on qubit 0 and a CNOT from 0 to 1; (2) ruqu builds a state vector with amplitudes on the 00 and 11 outcomes; (3) each gate is applied as a matrix; (4) optionally the coherence engine checks PERMIT, DEFER, or DENY; (5) measurement collapses the state to a real bitstring, 00 or 11 at about 50/50; (6) a SHA-256 witness log records every step. -
Accurate to the engine. The exact path a Bell-state circuit takes — superpose, entangle, build the state vector, (optionally) gate-check, measure, and witness-log.
-
-
- Friendly · the on-ramp - A friendly illustration of a traffic-light-style health gauge (green, amber, red) acting as a guardian over a glowing quantum chip with a bloch-sphere orb, with a small heartbeat line. -
Step 4, made friendly: a little guardian watching the machine’s health and giving it a green, amber, or red light before each move.
-
-
-
-
- - -
- - 05 - -

What a “solved” state looks like

- From “I’ve read about this” to “I just ran it” -
- -
-
-

When ruqu is working for you, quantum stops being theoretical. A terminal prints a real - Bell-state distribution. Every student’s browser runs the same circuit. A Rust - program hands you a molecule’s ground-state energy. And a health gauge flags trouble - a median of four cycles before failure. Quantum ideas you could only read - about become things you run.

- -
-
- Technical · the real outputs - Four solved-state tiles: a terminal printing a real Bell distribution (00 about 0.498, 11 about 0.501); a browser running the same circuit and getting 00 or 11 at 50/50 with no server; a Rust program returning result.energy of about -1.137 Hartree; and a health gauge with a sparkline and PERMIT/DEFER/DENY flagging trouble a median of four cycles before failure at 85.7 percent recall. -
Real artifacts, not promises: a printed distribution, a browser result, a returned energy, and an early-warning signal.
-
-
- Friendly · the on-ramp - A friendly illustration of a small molecule made of glowing orbs above a cyan energy curve that dips to a starred lowest point labeled ground state. -
One result, made friendly: a molecule settling into its lowest-energy “ground state” — the core question behind drug and materials design.
-
-
- -
Honest note on the numbers: the coherence-engine figures - (median 4-cycle early warning, 85.7% recall, 468 ns P99, 3.8M decisions/sec) are - vendor-measured on an Apple M2 under specified conditions — indicative, - not independently audited.
-
-
- - -
- - 06 - -

How you’d implement it

- Three doors into the same engine — pick the one that fits your job -
- -
-
-

There’s no “setup” ceremony. Pick the surface that fits what you’re - doing — all three drive the same pure-Rust state-vector engine.

- -
-
- Technical · the three surfaces - A diagram of three ways to use ruqu, all converging on the same pure-Rust state-vector engine. Terminal CLI: npx @ruvector/ruqu with simulate, grover, or qaoa subcommands (v0.2.0). Web page WASM: npm install @ruvector/ruqu-wasm, build a Circuit, run it, measureAll (v2.0.5, 180KB gzip). Rust crate: build a Hamiltonian, pick an ansatz, call VQE optimize, or use SurfaceCode, process_cycle, plan_execution (workspace v2.2.3). -
Real code paths. The actual commands and calls for each surface — CLI, in-browser WASM, and the Rust crate — all hitting one engine.
-
-
- Friendly · the on-ramp - A friendly illustration of a glowing magnifying glass over a haystack with one spotlighted glowing needle — quantum search. -
What “just call it” feels like: one command (grover) finds the needle — you don’t build the algorithm, you call it.
-
-
- -
# Terminal — fastest, nothing installed:
-npx @ruvector/ruqu grover --qubits 3 --target 5
-
-# Web page — an in-browser widget, no server:
-npm i @ruvector/ruqu-wasm
-const c = new Circuit(3); /* … */ sim.run(c); state.measureAll();
-
-# Rust — full power (chemistry, error correction, coherence):
-let h = Hamiltonian::from_pauli_strings([/* … */]);
-let result = VQE::new(h, Ansatz::uccsd(/* … */)).optimize();
-
-
- - -
- - 07 - -

How to start — in 60 seconds

- No install. One command. You’re doing quantum in the first minute. -
- -
-
-
- Technical · the 3 steps - A three-step start diagram. Step 1: open a terminal and run npx @ruvector/ruqu simulate --qubits 2 — npx fetches it on the fly, no install. Step 2: watch the Bell-state distribution print, about 50 percent 00 and 50 percent 11. Step 3: to put it in a web page, npm install @ruvector/ruqu-wasm and drop in an in-browser widget. -
The literal path. Open a terminal, run one command, watch quantum happen — then optionally drop it into a web page.
-
- -
-
-
1
-

Run one command

-

Open a terminal: npx @ruvector/ruqu simulate --qubits 2. npx fetches it on the fly — nothing to install first.

-
-
-
2
-

Watch quantum happen

-

It prints the Bell-state distribution — roughly 50% “00” and 50% “11”. That’s a real simulation, for real.

-
-
-
3
-

Put it in a page

-

Want it in a website or teaching app? npm i @ruvector/ruqu-wasm and drop in an in-browser widget your visitors run.

-
-
- -

From here, explore the use-case gallery below — search (Grover), optimization - (QAOA), chemistry (VQE), error correction, and the coherence engine — each with its - own command and its own picture.

-
-
- - -
- - 08 - -

Use-case gallery

- Seven real things you can do — each opens to its own visual, concept, and command -
- -
-
-

Each card is a full scenario: the situation, the exact command, what it - does, and what you get — with its own diagram. Open any of them.

- - -
- - 1 - Quantum search in the terminal - CLI · Grover - - -
-
-
Situation
You want to show how a quantum computer finds a “needle in a haystack” faster than checking items one by one.
-
Command
npx @ruvector/ruqu grover --qubits 3 --target 5
-
What it does
Runs Grover’s algorithm (amplitude amplification) on the WASM state-vector simulator to home in on the target in about √N steps instead of N.
-
What you get
The found bitstring and the probability it landed on the right answer — Grover’s quadratic speedup, made visible.
-
-
- Technical · how the amplification works - A diagram of Grover's algorithm: a flat list of equal items goes through amplify rounds that raise the target item's probability, until measurement spikes on the target after about the square root of N rounds. -
Flat list → “amplify the answer” rounds → a probability spike on the target.
-
-
-
- - -
- - 2 - Optimization toy problem (MaxCut), no math PhD - CLI · QAOA - - -
-
-
Situation
You have a network and want the best way to split it into two groups — a classic NP-hard problem.
-
Command
npx @ruvector/ruqu qaoa --nodes 4
-
What it does
Runs QAOA (a quantum approximate optimizer) on a 4-node ring to find a good split.
-
What you get
A partition and its cut value — a hands-on feel for “quantum approximate advantage” on combinatorial problems.
-
-
- Technical · QAOA layers - A diagram: a 4-node ring graph goes through QAOA cost and mixer layers and returns a two-group coloring (magenta vs cyan) with the cut edges highlighted, plus the cut value. -
Ring graph → QAOA cost/mixer layers → a colored two-group split.
-
-
-
- - -
- - 3 - A quantum chemistry prototype in Rust - Rust · VQE - - -
-
-
Situation
You want a molecule’s lowest-energy (“ground”) state — the core question behind drug and materials design — but have no quantum hardware.
-
Command (Rust)
Build a Hamiltonian::from_pauli_strings([…]), pick the Ansatz::uccsd(…), then VQE::new(…).optimize().
-
What it does
Runs the Variational Quantum Eigensolver, the standard near-term quantum-chemistry algorithm, entirely on the simulator.
-
What you get
An estimated ground-state energy in Hartrees (result.energy) — a working chemistry prototype with zero hardware.
-
-
- Technical · how VQE settles - A diagram: a molecule is encoded as a Hamiltonian, fed into a parameterized circuit (ansatz) with tunable angles, and an optimizer lowers the energy step by step until it settles to a minimum — returning result.energy in Hartrees. -
Molecule → parameterized circuit → energy curve settling to its minimum.
-
-
-
- - -
- - 4 - How quantum survives its own mistakes - Rust · error correction - - -
-
-
Situation
You’re learning why quantum machines need error correction and how a “surface code” fixes errors.
-
Command (Rust)
SurfaceCode::new(distance: 3), inject noise with apply_noise(…, error_rate: 0.01), then Decoder::mwpm().correct(…).
-
What it does
Encodes a logical qubit, scatters realistic errors, measures the tell-tale “syndromes,” and corrects them with minimum-weight perfect matching.
-
What you get
A before/after you can inspect — corrupted state → detected syndromes → recovered state.
-
-
- Technical · encode, detect, correct - A diagram of surface-code error correction: a clean distance-3 lattice, then noise injects red error dots and amber syndrome flags, then minimum-weight perfect matching pairs the syndromes and corrects them, recovering a clean lattice. -
Clean lattice → red error dots + syndromes → matched-and-corrected lattice.
-
-
-
- - -
- - 5 - A real-time “is it safe to act?” health monitor - Rust · coherence engine - - -
-
-
Situation
You’re running a long quantum job and want to catch a structural breakdown before it wipes out your progress.
-
Command (Rust)
Feed each cycle’s syndrome_data into fabric.process_cycle(…); read back Permit / Defer / Deny.
-
What it does
ruv’s original coherence engine runs a real-time min-cut on the error pattern and decides whether the machine is healthy, borderline, or collapsing.
-
What you get
An early-warning signal — in tests it flagged trouble a median of 4 cycles before failure with 85.7% recall — so healthy regions keep running while a bad region is quarantined.
-
-
- Technical · the decision pipeline - A diagram of the coherence engine: each cycle's syndrome stream is fed into a real-time min-cut over the error pattern, which returns PERMIT (healthy, keep running), DEFER (borderline, wait), or DENY (collapsing, quarantine) before the next operation. Measured stats: median 4 cycles early warning, 85.7 percent recall, 468 nanosecond P99 latency, 3.8 million decisions per second. -
Syndrome stream → real-time min-cut → PERMIT / DEFER / DENY, with the vendor-measured numbers.
-
-
Why this is the headline. No mainstream toolkit ships a real-time safety gate like this — it’s ruv’s original contribution and the piece that makes ruqu more than “just another simulator.”
-
-
- - -
- - 6 - Pick the right engine automatically for a bigger circuit - Rust · planner - - -
-
-
Situation
Your circuit is too big for the obvious “track every possibility” method, but you don’t know which technique to use.
-
Command (Rust)
plan_execution(&circuit, &PlannerConfig::default()) — or decompose(&circ, 25) to split it.
-
What it does
A cost-model planner predicts memory/runtime/fidelity and routes the circuit to the best of five backends (StateVector, Stabilizer for Clifford-only circuits with millions of qubits, TensorNetwork, Clifford+T, or hardware profiles).
-
What you get
A feasible run where a naive simulator would have run out of memory.
-
-
- Technical · the routing decision - A diagram: a circuit too big for the naive method is handed to a cost-model planner that predicts memory, runtime, and fidelity, then routes to the cheapest of five backends — StateVector (chosen for small exact jobs), Stabilizer (Clifford-only, millions of qubits), TensorNetwork, Clifford+T, or a hardware profile. Honest note: Clifford+T is not in the auto-router yet. -
One circuit → planner predicts cost → the cheapest viable backend is chosen.
-
-
-
- - -
- - 7 - In-page quantum for a website or teaching app - JS · WASM widget - - -
-
-
Situation
You want a live quantum demo embedded in a web page with no backend server.
-
Command (JS)
npm install @ruvector/ruqu-wasm, then new Circuit(3) … sim.run(circuit) … state.measureAll().
-
What it does
Runs genuine state-vector simulation client-side via WebAssembly (up to ~25 qubits; ~1 GB browser memory at 25).
-
What you get
An interactive quantum widget your visitors run themselves, zero server cost.
-
-
- Technical · the in-browser path - A diagram: a browser tab loads the @ruvector/ruqu-wasm WebAssembly module — the pure-Rust state-vector engine compiled to wasm32 — which runs genuine simulation client-side up to about 25 qubits and returns a live measurement readout, with zero server cost. -
Browser tab → WASM module → a live measurement readout, no server.
-
-
-
-
-
- - -
- - ⚛ - -

“I already have X — why ruqu too?”

- Qiskit/Cirq? Claude Code? Another simulator? Here’s the honest difference. -
- -
-
-
    -
  • vs Python quantum stacks (Qiskit / Cirq): powerful but heavy — a - Python runtime plus a large dependency tree, awkward to embed and impossible to drop - straight into a browser. ruqu is pure Rust with no FFI that compiles to - native and wasm32: a 180 KB-gzip WASM bundle that runs in a web - page or as npx @ruvector/ruqu. Same physics, far less weight, runs - where Python can’t.
  • -
  • vs “just use Claude Code”: Claude Code is a brilliant - generalist, but it can’t run a quantum circuit or check whether your VQE - energy is right — it would guess. ruqu is the actual engine it can call: real - state-vector math, real algorithms, and a cryptographic witness log - (SHA-256 hash chain) so results are reproducible and auditable, not hallucinated. The repo - even ships ruqu as a Claude-Code agent harness so your assistant can drive it - directly.
  • -
  • vs other simulators generally: the differentiator is the - coherence engine — “ruQu is not a simulator… it - decides how, where, and whether to run quantum workloads.” The real-time - PERMIT/DEFER/DENY safety gate (468 ns P99, 3.8M decisions/sec — measured) is - ruv’s original contribution and exists in no mainstream toolkit.
  • -
- -
- Technical · side-by-side & before→after on your own work - A comparison table of Qiskit/Cirq, Claude Code, other simulators, and ruqu across weight and portability, whether they can actually run the math, and the unique piece. ruqu is pure Rust, native and wasm32, 180KB gzip, with a SHA-256 witness log and the coherence engine. Footer: before ruqu, quantum ideas stay theoretical; after, you prototype, test, and even monitor quantum workloads from a terminal, browser, or Rust app, today, free. -
The head-to-head, plus your own before→after. What changes when ruqu is in your toolbox — lighter, runnable everywhere, reproducible, and uniquely able to monitor a quantum machine’s health.
-
-
-
- - -
- - 09 - -

The drop-in kit

- One download, two halves — one for you, one for your AI assistant -
- -
-
-

Want your AI assistant (in Claude Code or Cursor) to answer questions about ruqu from the - real source instead of guessing? Grab the drop-in kit. It’s one folder with - two clearly-labeled halves: a plain-English primer for you, and a - queryable knowledge base for your AI.

- -
-
- Technical · the ACTUAL file tree - An annotated file tree of the ruqu-dropin.zip download. Root: ruqu-dropin, unzip into your project as kb. for-humans half: ruqu-primer.md (the whole tool in plain English) and a highlighted studio folder holding ruqu-audio.m4a (a NotebookLM audio overview to play first), ruqu-report.md (the written briefing), and the prompt that made them. for-ai half: ruqu-kb.rvf (the single 384-dim bge-small brain), ruqu-kb.passages.jsonl (every doc and all source, full text), ruqu-kb.ids.json (the id index), ask-kb.mjs (ask it from the command line), kb-mcp-server.mjs (wire it into Claude Code or Cursor), kb.config.mjs and package.json. Plus a README and manifest with the build's provenance. -
Exactly what’s inside. Every file, with a plain-English “what this is” — the real contents, not an abstract picture. Note the highlighted studio/: a 🎧 audio overview (play first) and a 📄 report ride inside the zip.
-
-
- Friendly · the on-ramp - A friendly illustration of a glowing download box splitting into two halves: a 'for you' half with a person icon and a 'for your AI' half with a robot icon. -
The idea in one picture: one tidy download that opens into a half for you and a half for your AI.
-
-
- -
-
-
1
-

Unzip into your project

-

Drop the folder in as kb/. You now have for-humans/ and for-ai/ side by side.

-
-
-
2
-

Add the 2-line .mcp.json

-

In for-ai/ run npm i (two deps, Node 18+), then point a 2-line .mcp.json at the bundled kb-mcp-server.mjs so your assistant can query the single ruqu-kb.rvf brain.

-
-
-
3
-

Paste the CLAUDE.md gate

-

Tell your AI to answer ruqu questions from the KB. Confirm it works with a real query — e.g. “How does the coherence engine decide PERMIT vs DENY?”

-
-
- - - -
Download the drop-in kit
-
ruqu-dropin.zip — single 384-dim brain + the 🎧 studio audio overview & 📄 report inside — Gate A: 99.3 tuned / 100 held-out — ready now
-

Ready

-
- - -
- -

Generated with Google NotebookLM · grounded in the same source repo

-

A full NotebookLM studio for ruqu

-

Audio overview, an explainer video, a slide deck, an infographic and a written report — all in one place, all built for a curious newcomer with no quantum hardware. No account, no setup: just open it and explore.

- -
    -
  • 🎧 Audio overview
  • -
  • 🎬 Explainer video
  • -
  • 📊 Slide deck
  • -
  • 📈 Infographic
  • -
  • 📄 Written report
  • -
-
- -
-
🎧 Audio overview — a warm, jargon-free deep-dive on ruqu (NotebookLM). Play it right here, or find it in the zip at for-humans/studio/.
- - -
- - - - -
Listen first. Inside the zip, for-humans/studio/ - holds the 🎧 NotebookLM audio overview above (play it first — a warm, - jargon-free deep-dive) and a 📄 written report. The - for-ai/ half is one runnable folder: a single ruqu-kb.rvf brain - (384-dim bge-small), the full passages, the CLI, and the MCP server — it - cleared its answer-quality gate (tuned 99.3 / held-out 100, both ≥95) before shipping.
-
-
- - -
- - ⚠ - -

Honest limits

- What ruqu does not do, stated plainly -
- -
-
-
    -
  • It is a simulator, not a quantum computer. Validation is - simulation-only; “hardware behavior may differ.” The hardware adapters - (IBM/IonQ/Rigetti/Braket) are profiles with local-simulation fallback, not a finished - end-to-end pipeline (roadmap v0.5, “Planned”).
  • -
  • Qubit ceilings are real. Exact state-vector simulation tops out around - 25 qubits in browser/Node (≈1 GB memory at 25) and - 32 in native Rust — cost doubles with every qubit. The Stabilizer - backend reaches “millions” of qubits only for restricted - (Clifford-only) circuits.
  • -
  • Versions are early / mixed. The coherence engine is at roadmap - v0.3–0.4 (“v1.0 production-ready with hardware validation” still Planned); - the CLI is @ruvector/ruqu v0.2.0; @ruvector/ruqu-wasm is v2.0.5; - the Rust workspace is v2.2.3 — read the version that matches what you install.
  • -
  • Some pieces aren’t wired together yet. The repo openly lists gaps: - “no end-to-end pipeline” (modules run independently), Clifford+T not yet in the - auto-router, greedy (not optimal) min-cut partitioning, and no fidelity-aware stitching at - partition boundaries.
  • -
  • ruqu-exotic is explicitly experimental. Its - quantum-inspired AI hybrids (memory decay, interference search, reasoning error - correction) are research, not production guarantees.
  • -
  • The benchmark numbers are vendor-measured (Apple M2 / specified - conditions), not independently audited — treat them as indicative.
  • -
-
Bottom line: ruqu is a genuinely useful, faithful simulator with a unique - real-time safety engine — and an early-stage, partly-unwired project. - Both are true. Use it for learning, prototyping, and validation today; don’t mistake - it for finished hardware tooling.
-
-
- -
-
-
- - -
-
- -

- An independent, plain-language explainer for ruvnet/ruqu, - created by Reuven Cohen (@ruvnet). - Built with the Ruv-Explainer Repo-Primer Pipeline ↗ - — an open project for turning dense repos into friendly explainers. - Not affiliated with or endorsed by the author. -

-

- Updated 2026-06-19 · source @ 026d63e · workspace v2.2.3 - (@ruvector/ruqu v0.2.0 · @ruvector/ruqu-wasm v2.0.5). - Content grounded in the repo’s own READMEs at HEAD — no invented features. -

-
-
- - - - diff --git a/ruv-explainer-ruqu/main.js b/ruv-explainer-ruqu/main.js deleted file mode 100644 index 916c147..0000000 --- a/ruv-explainer-ruqu/main.js +++ /dev/null @@ -1,74 +0,0 @@ -/* ============================================================================= - ruqu ExplainerSite — main.js - Progressive enhancement only. The page is fully usable with JS disabled: - every section and gallery item is a native
/, so they - open/close on their own. This script adds: - 1. deep-link: open the
a #hash points at, and on nav-click. - 2. live provenance: best-effort fetch of /kb/.last-built.json to refresh - the "Updated … · source @sha" line if a real build manifest is present. - Silent no-op if the file is absent (the static fallback already shows - the build this page was authored against). - No dependencies. No build step. - ========================================================================== */ -(function () { - "use strict"; - - /* --- 1. Deep-link a section open ---------------------------------------- */ - function openFromHash() { - var id = (location.hash || "").replace(/^#/, ""); - if (!id) return; - var el = document.getElementById(id); - while (el && el.tagName !== "DETAILS") el = el.parentElement; // walk up to the
- if (el && !el.open) el.open = true; - } - window.addEventListener("hashchange", openFromHash); - openFromHash(); - - // Clicking an in-page nav link should also expand its target section. - document.querySelectorAll('a[href^="#"]').forEach(function (a) { - a.addEventListener("click", function () { - var id = a.getAttribute("href").slice(1); - var sec = document.getElementById(id); - while (sec && sec.tagName !== "DETAILS") sec = sec.parentElement; - if (sec && !sec.open) sec.open = true; - }); - }); - - /* --- 2. Live provenance (best-effort, optional) -------------------------- */ - // If a real build manifest ships at /kb/.last-built.json, update the provenance - // line so a visitor can verify they're looking at the current build. Absent => - // keep the authored static line. Never throws on the page. - fetch("/kb/.last-built.json", { cache: "no-store" }) - .then(function (r) { return r.ok ? r.json() : null; }) - .then(function (m) { - if (!m) return; - // Sanitize: keep only safe chars (hex sha, ISO date, version string). - var sha = (m.sha || m.head || "").toString().replace(/[^0-9a-fA-F]/g, "").slice(0, 7); - var date = (m.date || m.builtAt || "").toString().replace(/[^0-9-]/g, "").slice(0, 10); - var version = (m.version || "").toString().replace(/[^0-9A-Za-z.\-_ ]/g, "").slice(0, 40); - if (!sha && !date) return; - var live = document.querySelector(".prov-live"); - if (!live) return; - - // Build the line with safe DOM nodes only (no innerHTML, no markup injection). - while (live.firstChild) live.removeChild(live.firstChild); - var dot = document.createElement("span"); - dot.className = "prov-dot"; - dot.setAttribute("aria-hidden", "true"); - dot.textContent = "●"; - live.appendChild(dot); - - var parts = []; - if (date) parts.push(document.createTextNode(" Updated " + date)); - if (sha) { - if (parts.length) parts.push(document.createTextNode(" · source ")); - else parts.push(document.createTextNode(" source ")); - var codeEl = document.createElement("code"); - codeEl.textContent = "@ " + sha; - parts.push(codeEl); - } - if (version) parts.push(document.createTextNode(" · " + version)); - parts.forEach(function (n) { live.appendChild(n); }); - }) - .catch(function () { /* offline / absent manifest — keep static line */ }); -})(); diff --git a/ruv-explainer-ruqu/package.json b/ruv-explainer-ruqu/package.json deleted file mode 100644 index b395ef0..0000000 --- a/ruv-explainer-ruqu/package.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "name": "ruv-explainer-ruqu", - "version": "0.1.0", - "private": true, - "description": "Plain-language ExplainerSite for ruqu (ruvnet/ruqu): a faithful quantum-computer simulator in pure Rust → WebAssembly, with a real-time coherence engine. Static, no build, no deps.", - "license": "MIT", - "homepage": "https://ruv-explainer-ruqu.vercel.app", - "repository": { - "type": "git", - "url": "https://github.com/stuinfla/ruv-explainer-ruqu" - }, - "keywords": [ - "ruqu", - "ruvnet", - "quantum-simulator", - "state-vector", - "webassembly", - "coherence-engine", - "explainer", - "static-site" - ], - "scripts": {} -} diff --git a/ruv-explainer-ruqu/robots.txt b/ruv-explainer-ruqu/robots.txt deleted file mode 100644 index e985292..0000000 --- a/ruv-explainer-ruqu/robots.txt +++ /dev/null @@ -1,4 +0,0 @@ -User-agent: * -Allow: / - -Sitemap: https://ruv-explainer-ruqu.vercel.app/sitemap.xml diff --git a/ruv-explainer-ruqu/studio/audio-overview-prompt.md b/ruv-explainer-ruqu/studio/audio-overview-prompt.md deleted file mode 100644 index 2249004..0000000 --- a/ruv-explainer-ruqu/studio/audio-overview-prompt.md +++ /dev/null @@ -1,50 +0,0 @@ -# ruqu Audio Overview — Optimized Prompt - -**Notebook:** ruqu — Explainer -**Notebook ID:** 994580f7-b28d-4c02-9346-8829220af63a -**Audio Artifact ID:** ce8b045a-0ecf-4411-bb35-6397cd83bbac -**Report Artifact ID:** a63a133b-7bc2-4db4-b239-f4b68e299257 -**Format:** deep_dive | Length: default -**Audience:** A curious developer or student, comfortable with npm, who is NOT a quantum physicist. - -## Focus Prompt Used - -Open with the felt problem: a teacher (Aisha) wants to demo a real quantum "Bell state" to her -class but has no quantum computer, and installing heavy Python quantum toolkits fails on classroom -laptops. Then define the core idea in one plain sentence: ruqu is a pretend quantum computer written -in pure Rust that runs on a normal laptop or right inside a browser tab, so you can build and test -real quantum algorithms with NO quantum hardware. Explain a qubit simply (a bit that can be a blend -of 0 and 1 until you look). Name the three things ruqu gives you in plain words: (1) a state-vector -simulator (the imitation quantum computer itself, exact answers up to ~25 qubits in a browser, ~32 -in Rust), (2) ready-made quantum algorithms you just call (VQE for chemistry, Grover for fast -search, QAOA for optimization, surface-code error correction), and (3) ruv's original "coherence -engine" that watches a quantum machine in real time and says PERMIT / DEFER / DENY before each step. -Contrast with heavy Python stacks (Qiskit/Cirq): ruqu is tiny, fast, pure Rust to WebAssembly, no -Python, runs where Python can't. Be honest: it is a SIMULATOR, not real quantum hardware; qubit -counts are capped because cost doubles per qubit. End with the exact first command to try right now: -`npx @ruvector/ruqu simulate --qubits 2`. Tone: warm, vivid, zero undefined jargon. - -## Prompt Design Rationale - -1. **Opens with a felt, concrete scenario** (Aisha + the failed Python install) — the audience feels - the pain instantly, no jargon required. This is the resonance canon's grounding example. -2. **One-sentence plain definition** — "a pretend quantum computer that runs on your normal laptop" - collapses the ethereal "quantum execution intelligence engine" into words anyone understands. -3. **Defines "qubit" inline** — the single most important term, in one friendly clause. -4. **Names the three deliverables in plain words** — simulator / ready-made algorithms / coherence - engine — so the listener leaves knowing exactly what they get. -5. **Differentiation built in** (vs Qiskit/Cirq Python) — answers "why this and not what I have." -6. **Honesty baked in** (it's a simulator, qubit ceilings are real) — never oversells. -7. **Ends with the exact first command** — `npx @ruvector/ruqu simulate --qubits 2` — removes all - ambiguity about what to do next. -8. **Tone + audience pinned** — "warm, vivid, zero undefined jargon … not a quantum physicist" keeps - the hosts out of tech-speak. - -## Source Files (added to the notebook) - -- `content/ruqu.canon.md` — Resonance Canon (grounded content standard) · Source ID 3ac41182-5c86-4e8a-89fd-66028eaf4251 -- `kb/stores/ruqu/ruqu-primer.md` — Top-Down Primer (7-arc comprehension) · Source ID ee68cd7d-8127-4cc7-8be9-d458e29018d0 -- `.targets/ruqu/README.md` — upstream README @026d63ef · Source ID a58b3648-2c95-45ef-ada5-eba7db556143 - -Provenance: content grounded in the ruqu repo at HEAD `026d63ef900ab689c863b6b3254f5dce8c068bf6`. -Author of ruqu: Reuven Cohen / @ruvnet · . diff --git a/ruv-explainer-ruqu/studio/ruqu-infographic.png b/ruv-explainer-ruqu/studio/ruqu-infographic.png deleted file mode 100644 index bfcada9..0000000 Binary files a/ruv-explainer-ruqu/studio/ruqu-infographic.png and /dev/null differ diff --git a/ruv-explainer-ruqu/studio/ruqu-report.md b/ruv-explainer-ruqu/studio/ruqu-report.md deleted file mode 100644 index 364cfea..0000000 --- a/ruv-explainer-ruqu/studio/ruqu-report.md +++ /dev/null @@ -1,97 +0,0 @@ -# ruqu: High-Performance Quantum Computing Toolkit for Rust and WebAssembly - -## Executive Summary - -**ruqu** is an advanced, dependency-light quantum computing toolkit developed in pure Rust, designed to provide high-performance quantum circuit simulation and algorithm execution across native and web environments. By leveraging WebAssembly (WASM), ruqu enables complex quantum simulations—traditionally reserved for heavy Python-based stacks or expensive hardware—to run directly in browsers or via a one-line terminal command. - -The toolkit functions as a "pretend quantum computer" that executes on standard hardware, offering an exact state-vector simulation of up to 32 qubits (native) or 25 qubits (browser). Beyond simulation, ruqu distinguishes itself through a novel "coherence engine" that acts as a classical nervous system for quantum machines, assessing real-time stability to mitigate errors. Its "batteries-included" approach provides production-ready implementations of VQE, Grover’s search, QAOA, and surface-code error correction, making it a comprehensive solution for research, education, and prototype development in the Noisy Intermediate-Scale Quantum (NISQ) era. - ---- - -## Core System Architecture - -The ruqu ecosystem is structured as a Rust workspace comprising five primary crates, each serving a distinct role in the quantum execution stack. - -### The Five Crates of ruqu - -| Crate | Primary Function | Key Features | -| :--- | :--- | :--- | -| **ruqu-core** | State-vector circuit simulator | SIMD acceleration (AVX2/NEON), multi-threading (Rayon), 5 simulation backends, and noise models. | -| **ruqu-algorithms** | Production quantum algorithms | Implementations for VQE (chemistry), Grover’s (search), QAOA (optimization), and Surface Code (error correction). | -| **ruqu-wasm** | WebAssembly bindings | Enables 25-qubit simulations in JavaScript/TypeScript/Node.js with zero native dependencies. | -| **ruQu** | Coherence engine | A "quantum execution intelligence engine" using dynamic min-cut for real-time coherence assessment. | -| **ruqu-exotic** | Experimental AI hybrids | Quantum-classical hybrid tools including memory decay, interference search, and swarm interference. | - ---- - -## Detailed Analysis of Key Themes - -### 1. High-Performance Simulation & Automation -The toolkit is built for speed and portability. Unlike traditional quantum toolkits that rely on Python or C++ FFI (Foreign Function Interface), ruqu's pure Rust implementation ensures memory safety and easy embedding. - -* **SIMD Acceleration:** Uses vectorized kernels to achieve a 2–4× speedup. -* **Cost-Model Planner:** Rather than manual backend selection, ruqu's intelligence layer inspects circuit parameters (qubit count, gate mix, T-count) and auto-routes the workload to the most efficient backend (e.g., StateVector for small exact circuits, Stabilizer for millions of Clifford-only qubits). -* **Mixed Precision:** Allows users to alternate between f32 and f64 precision to balance speed and accuracy. - -### 2. The Coherence Engine (ruQu) -Described as a "nervous system for quantum machines," the ruQu crate represents the toolkit’s most innovative contribution. It monitors the health of a quantum operation in real time. -* **Dynamic Min-Cut:** Analyzes error patterns to make PERMIT, DEFER, or DENY decisions for each operation. -* **Latency:** Operates with a 468 ns P99 latency, capable of 3.8 million decisions per second. -* **Predictive Safety:** In testing, it flagged structural breakdowns a median of 4 cycles before failure with 85.7% recall. - -### 3. "Batteries-Included" Algorithms -ruqu provides ready-to-use implementations of industry-standard quantum algorithms: -* **VQE (Variational Quantum Eigensolver):** Used for finding ground-state energies in quantum chemistry. -* **QAOA (Quantum Approximate Optimization Algorithm):** Targeted at combinatorial optimization, such as MaxCut problems. -* **Grover’s Search:** Provides a quadratic speedup for unstructured search tasks. -* **Surface Code:** A distance-3 simulation for studying quantum error correction (QEC) via syndrome decoding and noise injection. - -### 4. Accessibility via WebAssembly and CLI -One of ruqu's primary goals is removing the barrier to entry for quantum computing. -* **Zero Install:** Using `npx @ruvector/ruqu`, users can run simulations from any terminal. -* **Browser-Native:** The `ruqu-wasm` package allows for the creation of interactive quantum widgets or educational tools that run entirely client-side, avoiding the need for backend servers or cloud credits. - ---- - -## Technical Specifications and Limits - -While powerful, ruqu is governed by the mathematical realities of classical simulation. - -* **State-Vector Limits:** Exact simulation is limited by memory. Each additional qubit doubles the memory requirement. - * **Native Rust:** Up to 32 qubits. - * **Browser/WASM:** Up to 25 qubits (~1 GB RAM). -* **Stabilizer Backend:** Can handle millions of qubits, but only for Clifford-only circuits (Gottesman–Knill theorem). -* **Noise Modeling:** Supports depolarizing, amplitude damping, phase damping, thermal relaxation, and custom Kraus operators. -* **OpenQASM 3.0:** Supports exporting circuits to standard OpenQASM 3.0 for interoperability with other quantum tools. - ---- - -## Important Quotes and Context - -> **"ruqu is a pretend quantum computer that runs on your normal laptop — a tiny, fast program that acts exactly like a real quantum machine so you can build and test quantum ideas before the expensive hardware exists."** -*Context: A high-level explanation designed for non-technical users to understand the value proposition of a simulator versus physical hardware.* - -> **"The coherence engine turns a quantum computer 'from a fragile experiment into a self-aware machine' which is exactly the missing piece for running long, trustworthy quantum jobs."** -*Context: Describing the strategic importance of the ruQu crate in moving beyond simple simulation toward managed quantum execution.* - -> **"No Python, no C++, no heavyweight dependencies."** -*Context: Emphasizing the portability and ease of use compared to industry-standard tools like Qiskit or Cirq, which require complex environments.* - -> **"Is it still safe to act, or is this thing about to fall apart?"** -*Context: The fundamental question the coherence engine answers through its real-time PERMIT / DEFER / DENY light system.* - ---- - -## Actionable Insights for Implementation - -### Deployment Pathways -1. **For Rapid Prototyping:** Use `npx @ruvector/ruqu simulate --qubits 4` to immediately validate a circuit without any local installation. -2. **For Web Integration:** Use the `@ruvector/ruqu-wasm` package to build client-side educational tools or demos that require no server-side quantum processing. -3. **For High-Performance Research:** Integrate `ruqu-core` directly into Rust projects to utilize SIMD acceleration and Rayon-based multi-threading for circuits up to 32 qubits. -4. **For Error Mitigation Studies:** Utilize the `SurfaceCode` implementation in `ruqu-algorithms` to test syndrome decoding against realistic noise models (depolarizing/damping). - -### Maturity and Versioning Note -Users should be aware of the varied maturity levels across the workspace: -* **Rust Workspace:** v2.2.3 -* **CLI (@ruvector/ruqu):** v0.2.0 -* **Status:** The coherence engine is currently in v0.3–0.4, with full hardware validation (v1.0) listed as a planned roadmap item. The `ruqu-exotic` crate remains explicitly experimental for research purposes. \ No newline at end of file diff --git a/ruv-explainer-ruqu/studio/ruqu-slides.pdf b/ruv-explainer-ruqu/studio/ruqu-slides.pdf deleted file mode 100644 index 99785b7..0000000 Binary files a/ruv-explainer-ruqu/studio/ruqu-slides.pdf and /dev/null differ diff --git a/ruv-explainer-ruqu/styles.css b/ruv-explainer-ruqu/styles.css deleted file mode 100644 index ac401bc..0000000 --- a/ruv-explainer-ruqu/styles.css +++ /dev/null @@ -1,487 +0,0 @@ -/* ============================================================================= - ruqu ExplainerSite — QUANTUM / BLOCH aesthetic - Aesthetic lock [Constraint K]: DEEP INDIGO substrate (never warm-charcoal), - ELECTRIC-MAGENTA + VIOLET accents with a cyan phosphor highlight, bloch-sphere - and quantum-circuit motifs. Geometric humanist sans (Space Grotesk) over Inter, - JetBrains Mono for code. Deliberately NOT the amber/copper foundry MetaHarness - look and NOT a clone of any prior site. Zero amber, zero warm-charcoal. - ========================================================================== */ - -/* ---- Fonts: system stack + optional self-hosted (graceful, zero hard CDN dep) */ -:root { - /* --- Indigo substrate: blue-violet bias, never warm --- */ - --bg: #0e0a22; /* deepest — page floor */ - --bg-2: #13102b; /* raised plane */ - --panel: #1a1540; /* card body */ - --panel-2: #211a4a; /* card header / inset */ - --inset: #100c26; /* code wells */ - --ridge: #34295e; /* hairline edges */ - - /* --- Quantum accents: magenta poured into violet, cyan phosphor highlight --- */ - --magenta: #ff3df0; /* primary electric magenta */ - --magenta-hi: #ff7bf6; /* hover lift / highlight */ - --violet: #8b5cff; /* secondary violet */ - --violet-deep:#5b3fd6; /* shadow side of violet */ - --cyan: #39e8ff; /* phosphor highlight / cyan glow */ - --cyan-soft: #7df0ff; - --good: #5cffaa; /* PERMIT green */ - --warn: #ffd96b; /* DEFER amber (only as a SIGNAL token, not the theme) */ - --bad: #ff8fa3; /* DENY red */ - - /* --- Ink: cool off-white, lavender-tinted --- */ - --ink: #f3eefb; - --ink-2: #cdc2ee; - --muted: #9a8fc4; - --faint: #6f6498; - --on-mag: #14081f; /* text that sits ON magenta fills */ - - --line: rgba(139,92,255,0.16); - --line-strong: rgba(139,92,255,0.34); - --fill-mag: rgba(255,61,240,0.10); - --fill-violet: rgba(139,92,255,0.12); - --fill-cyan: rgba(57,232,255,0.10); - - /* --- Depth: soft outer shadow + magenta/violet cast glow --- */ - --shadow: 0 22px 52px -28px rgba(0,0,0,0.86); - --shadow-deep: 0 40px 96px -42px rgba(0,0,0,0.92); - --inner: inset 0 1px 0 rgba(180,150,255,0.08), inset 0 -1px 0 rgba(0,0,0,0.5); - --glow-mag: 0 0 0 1px rgba(255,61,240,0.30), 0 16px 44px -18px rgba(255,61,240,0.38); - --glow-cyan: 0 0 0 1px rgba(57,232,255,0.28), 0 14px 40px -18px rgba(57,232,255,0.30); - - --display: "Space Grotesk", "Inter", system-ui, -apple-system, sans-serif; - --sans: "Inter", system-ui, -apple-system, "Segoe UI", sans-serif; - --mono: "JetBrains Mono", "IBM Plex Mono", ui-monospace, "SF Mono", Menlo, monospace; - - --maxw: 1140px; - --gutter: clamp(20px, 5vw, 56px); - --radius: 16px; - --radius-s: 10px; - --ease: cubic-bezier(0.22, 0.61, 0.36, 1); -} - -/* ---- Reset / base --------------------------------------------------------- */ -*, *::before, *::after { box-sizing: border-box; } -html { -webkit-text-size-adjust: 100%; scroll-behavior: smooth; } - -body { - margin: 0; - background: var(--bg); - color: var(--ink); - font-family: var(--sans); - font-size: 16.5px; - line-height: 1.66; - -webkit-font-smoothing: antialiased; - text-rendering: optimizeLegibility; - /* Quantum-field glow: layered magenta/violet/cyan radials over deep indigo */ - background-image: - radial-gradient(1100px 640px at 80% -10%, rgba(255,61,240,0.12), transparent 60%), - radial-gradient(900px 720px at -8% 6%, rgba(139,92,255,0.13), transparent 55%), - radial-gradient(700px 500px at 50% 120%, rgba(57,232,255,0.07), transparent 60%), - linear-gradient(180deg, var(--bg) 0%, var(--bg-2) 100%); - background-attachment: fixed; -} - -img, svg { max-width: 100%; height: auto; display: block; } - -a { color: var(--magenta); text-decoration: none; transition: color 0.18s var(--ease); } -a:hover { color: var(--magenta-hi); } -a:focus-visible, summary:focus-visible, button:focus-visible, [tabindex]:focus-visible { - outline: 2px solid var(--cyan); outline-offset: 3px; border-radius: 4px; -} - -.wrap { width: 100%; max-width: var(--maxw); margin: 0 auto; padding: 0 var(--gutter); } - -/* ---- Type system ---------------------------------------------------------- */ -h1, h2, h3, h4 { - font-family: var(--display); - font-weight: 700; - line-height: 1.04; - letter-spacing: -0.01em; - margin: 0 0 0.5em; -} -h1 { font-size: clamp(2.5rem, 7vw, 4.8rem); letter-spacing: -0.02em; } -h2 { font-size: clamp(1.7rem, 4vw, 2.6rem); } -h3 { font-size: 1.35rem; font-weight: 600; } -p { margin: 0 0 1rem; max-width: 70ch; color: var(--ink-2); } - -.eyebrow { - font-family: var(--mono); font-size: 12px; letter-spacing: 0.32em; - text-transform: uppercase; color: var(--cyan); font-weight: 500; margin: 0 0 14px; -} -.mono { font-family: var(--mono); } -.lede { font-size: 1.2rem; color: var(--ink); max-width: 66ch; } - -ol, ul { margin: 0 0 1rem; padding-left: 1.4em; max-width: 70ch; color: var(--ink-2); } -li { margin: 0 0 0.55em; } -li::marker { color: var(--magenta); } -li strong, p strong { color: var(--ink); } -em { color: var(--ink); font-style: italic; } - -/* Multi-line command block — a glowing terminal well */ -pre.code-block { - font-family: var(--mono); font-size: 0.84rem; line-height: 1.6; - color: var(--cyan-soft); background: var(--inset); - border: 1px solid var(--line-strong); border-left: 3px solid var(--magenta); - border-radius: var(--radius-s); padding: 16px 18px; margin: 0 0 1rem; - overflow-x: auto; box-shadow: var(--inner); max-width: 72ch; -} -pre.code-block code { background: none; border: none; box-shadow: none; padding: 0; font-size: inherit; color: inherit; white-space: pre; } -pre.code-block .c { color: var(--faint); } /* comment */ -pre.code-block .k { color: var(--magenta-hi); } /* key/keyword */ - -/* Inline command chip */ -code, .cmd { - font-family: var(--mono); font-size: 0.85em; color: var(--cyan-soft); - background: var(--fill-cyan); border: 1px solid var(--line-strong); - border-radius: 6px; padding: 0.12em 0.45em; -} - -/* honest-note / callout */ -.note { - margin-top: 18px; padding: 13px 16px; - border: 1px dashed var(--violet-deep); border-radius: var(--radius-s); - background: var(--fill-violet); color: var(--muted); max-width: 74ch; -} -.note strong { color: var(--ink-2); } -.note.warm { border-color: var(--magenta); background: var(--fill-mag); } - -/* takeaway line */ -.oh { - margin: 22px 0 4px; padding: 16px 20px; border-radius: var(--radius-s); - background: linear-gradient(96deg, var(--fill-mag), var(--fill-violet)); - border: 1px solid var(--line-strong); color: var(--ink); - font-size: 1.05rem; max-width: none; -} -.oh strong { color: var(--magenta-hi); } - -/* ---- Provenance / attribution banner -------------------------------------- */ -.prov-banner { - border-bottom: 1px solid var(--line); - background: linear-gradient(180deg, rgba(33,26,74,0.6), rgba(19,16,43,0.5)); - backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px); -} -.prov-banner-inner { - display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; - gap: 10px 26px; padding-top: 9px; padding-bottom: 9px; -} -.prov-attr { margin: 0; max-width: none; font-size: 12.5px; line-height: 1.5; color: var(--muted); } -.prov-attr strong { color: var(--ink-2); font-weight: 600; } -.prov-attr a { color: var(--cyan); } -.prov-attr a:hover { color: var(--magenta-hi); } -.prov-live { - margin: 0; flex: 0 0 auto; font-family: var(--mono); font-size: 11.5px; - letter-spacing: 0.04em; color: var(--faint); white-space: nowrap; - display: inline-flex; align-items: center; gap: 8px; -} -.prov-live code { font-size: 0.95em; color: var(--cyan); background: var(--fill-cyan); padding: 0.08em 0.4em; } -.prov-dot { color: var(--magenta); font-size: 9px; filter: drop-shadow(0 0 5px rgba(255,61,240,0.9)); animation: prov-pulse 2.6s var(--ease) infinite; } -@keyframes prov-pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.32; } } - -/* ---- Header / nav --------------------------------------------------------- */ -.site-head { - position: sticky; top: 0; z-index: 40; - background: rgba(14,10,34,0.8); - backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); - border-bottom: 1px solid var(--line); -} -.site-head .wrap { display: flex; align-items: center; justify-content: space-between; height: 64px; } -.brand { - display: inline-flex; align-items: center; gap: 12px; - font-family: var(--display); font-weight: 700; font-size: 1.25rem; - letter-spacing: 0.01em; color: var(--ink); -} -.brand .orb { width: 30px; height: 30px; display: block; } -.nav-links { display: flex; gap: 4px; } -.nav-links a { - font-family: var(--mono); font-size: 12px; letter-spacing: 0.04em; color: var(--muted); - padding: 7px 11px; border-radius: 7px; transition: color 0.18s var(--ease), background 0.18s var(--ease); -} -.nav-links a:hover { color: var(--ink); background: var(--fill-mag); } - -/* ---- Hero ----------------------------------------------------------------- */ -.hero { padding: clamp(56px, 11vw, 116px) 0 clamp(40px, 7vw, 76px); position: relative; } -.hero-grid { display: grid; grid-template-columns: 1.05fr 0.95fr; gap: clamp(24px, 5vw, 56px); align-items: center; } -.hero h1 { color: var(--ink); } -.hero h1 .grad { - background: linear-gradient(96deg, var(--magenta-hi), var(--violet) 55%, var(--cyan)); - -webkit-background-clip: text; background-clip: text; color: transparent; -} -.hero .lede { margin-top: 20px; } -.attrib-lede { - margin: 22px 0 0; max-width: 64ch; font-size: 1.02rem; line-height: 1.55; - color: var(--ink-2); padding: 14px 18px; - border-left: 3px solid var(--magenta); - background: linear-gradient(96deg, rgba(255,61,240,0.08), rgba(57,232,255,0.05) 80%); - border-radius: 0 var(--radius-s, 8px) var(--radius-s, 8px) 0; -} -.attrib-lede strong { color: var(--ink); } -.attrib-lede a { color: var(--cyan); } -.attrib-lede a:hover { color: var(--magenta-hi); } -.hero .meta-row { - display: flex; gap: 22px; flex-wrap: wrap; margin-top: 30px; - font-family: var(--mono); font-size: 12px; color: var(--faint); letter-spacing: 0.04em; -} -.hero .meta-row b { color: var(--cyan); font-weight: 500; } -.hero-art { - border-radius: var(--radius); overflow: hidden; - border: 1px solid var(--ridge); box-shadow: var(--shadow), var(--glow-mag); -} -.hero-art img { width: 100%; display: block; } -.cta-row { display: flex; flex-wrap: wrap; gap: 14px; margin-top: 32px; } -.cta { - display: inline-flex; align-items: center; gap: 10px; - font-family: var(--display); font-weight: 600; font-size: 1.02rem; letter-spacing: 0.01em; - color: var(--on-mag); - background: linear-gradient(96deg, var(--magenta-hi), var(--violet)); - padding: 13px 26px; border-radius: 11px; box-shadow: var(--glow-mag); - transition: transform 0.16s var(--ease), filter 0.16s var(--ease); -} -.cta:hover { transform: translateY(-2px); filter: brightness(1.07); color: var(--on-mag); } -.cta.ghost { background: transparent; color: var(--cyan); border: 1px solid var(--line-strong); box-shadow: none; } -.cta.ghost:hover { color: var(--magenta-hi); border-color: var(--magenta); background: var(--fill-mag); } - -/* one-plain-sentence band */ -.plainband { - margin-top: clamp(36px, 6vw, 64px); padding: clamp(22px, 4vw, 34px); - border-radius: var(--radius); border: 1px solid var(--line-strong); - background: linear-gradient(120deg, var(--fill-violet), var(--fill-mag)); - box-shadow: var(--inner); -} -.plainband p { margin: 0; max-width: none; font-size: clamp(1.15rem, 2.4vw, 1.5rem); color: var(--ink); line-height: 1.42; } -.plainband .q { color: var(--magenta-hi); font-weight: 600; } - -/* ---- Sections (native
) ----------------------------------------- */ -.sections { padding: clamp(30px, 6vw, 60px) 0 clamp(60px, 10vw, 104px); } -.section { - background: linear-gradient(180deg, var(--panel) 0%, var(--bg-2) 100%); - border: 1px solid var(--ridge); border-radius: var(--radius); - box-shadow: var(--shadow), var(--inner); margin: 0 0 18px; overflow: hidden; -} -.section[open] { box-shadow: var(--shadow-deep), var(--inner); border-color: var(--line-strong); } -.section > summary { - list-style: none; cursor: pointer; display: flex; align-items: baseline; gap: 18px; - padding: 24px clamp(20px, 4vw, 34px); user-select: none; transition: background 0.2s var(--ease); -} -.section > summary::-webkit-details-marker { display: none; } -.section > summary:hover { background: var(--fill-mag); } -.section .num { - font-family: var(--mono); font-size: 13px; letter-spacing: 0.18em; color: var(--cyan); - flex: 0 0 auto; padding-top: 6px; -} -.section .head-text { flex: 1 1 auto; } -.section .head-text h2 { margin: 0; color: var(--ink); font-size: clamp(1.3rem, 3vw, 1.95rem); } -.section .head-text .q { display: block; font-family: var(--mono); font-size: 12px; letter-spacing: 0.04em; color: var(--muted); margin-top: 6px; } -.section .chev { - flex: 0 0 auto; width: 26px; height: 26px; align-self: center; border-radius: 50%; - display: grid; place-items: center; border: 1px solid var(--line-strong); color: var(--magenta); - font-size: 13px; line-height: 1; transition: transform 0.25s var(--ease), background 0.2s var(--ease); -} -.section[open] .chev { transform: rotate(90deg); background: var(--fill-mag); } -.section .body { padding: 4px clamp(20px, 4vw, 34px) 32px; border-top: 1px solid var(--line); margin-top: 2px; } -.section .body > *:first-child { margin-top: 18px; } - -/* ---- Dual-visual figures -------------------------------------------------- */ -/* A dual-level block: technical SVG + friendly illustration, side by side on wide screens. */ -.dual { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; margin: 24px 0; } -.dual.stack { grid-template-columns: 1fr; } -@media (max-width: 820px) { .dual { grid-template-columns: 1fr; } } - -.figure { - margin: 0; border: 1px solid var(--ridge); border-radius: var(--radius-s); - background: var(--inset); padding: 14px; box-shadow: var(--inner); -} -.figure .tier { - display: inline-flex; align-items: center; gap: 7px; margin-bottom: 10px; - font-family: var(--mono); font-size: 10.5px; letter-spacing: 0.14em; text-transform: uppercase; -} -.figure .tier.tech { color: var(--cyan); } -.figure .tier.tech::before { content: ""; width: 8px; height: 8px; border-radius: 2px; background: var(--cyan); display: inline-block; } -.figure .tier.friendly { color: var(--magenta-hi); } -.figure .tier.friendly::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: var(--magenta); display: inline-block; } -.figure > svg, .figure > img { width: 100%; height: auto; border-radius: 7px; display: block; } -.figure figcaption { margin-top: 11px; color: var(--muted); font-size: 12.5px; line-height: 1.5; } -.figure figcaption b { color: var(--ink-2); } - -/* full-width single figure */ -.figure.wide { margin: 24px 0; } - -/* ---- Cards / use-case gallery -------------------------------------------- */ -.grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); margin-top: 18px; } - -/* gallery items are themselves collapsible
*/ -.case { - background: linear-gradient(180deg, var(--panel-2), var(--bg-2)); - border: 1px solid var(--ridge); border-radius: var(--radius-s); - overflow: hidden; margin: 0 0 14px; box-shadow: var(--inner); -} -.case[open] { border-color: var(--line-strong); } -.case > summary { - list-style: none; cursor: pointer; display: flex; align-items: center; gap: 14px; - padding: 16px 20px; user-select: none; transition: background 0.18s var(--ease); -} -.case > summary::-webkit-details-marker { display: none; } -.case > summary:hover { background: var(--fill-violet); } -.case .uc-num { - font-family: var(--mono); font-size: 12px; color: var(--on-mag); flex: 0 0 auto; - width: 28px; height: 28px; border-radius: 8px; display: grid; place-items: center; font-weight: 700; - background: linear-gradient(120deg, var(--magenta-hi), var(--violet)); -} -.case .uc-title { flex: 1 1 auto; font-family: var(--display); font-weight: 600; font-size: 1.12rem; color: var(--ink); } -.case .uc-kind { font-family: var(--mono); font-size: 10.5px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--cyan); flex: 0 0 auto; } -.case .chev { flex: 0 0 auto; width: 24px; height: 24px; border-radius: 50%; display: grid; place-items: center; border: 1px solid var(--line-strong); color: var(--magenta); font-size: 12px; transition: transform 0.25s var(--ease); } -.case[open] .chev { transform: rotate(90deg); background: var(--fill-mag); } -.case .uc-body { padding: 2px 20px 22px; border-top: 1px solid var(--line); } -.case .uc-body > *:first-child { margin-top: 16px; } -.case dl { margin: 14px 0 0; } -.case dt { font-family: var(--mono); font-size: 11px; letter-spacing: 0.13em; text-transform: uppercase; color: var(--cyan); margin-top: 14px; } -.case dt:first-child { margin-top: 0; } -.case dd { margin: 5px 0 0; color: var(--ink-2); } -.case dd code { font-size: 0.92em; } -.case .figure { margin-top: 18px; } - -/* ---- Drop-in steps -------------------------------------------------------- */ -.steps { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; margin: 22px 0; } -@media (max-width: 720px) { .steps { grid-template-columns: 1fr; } } -.step { background: var(--panel-2); border: 1px solid var(--ridge); border-radius: var(--radius-s); padding: 18px; box-shadow: var(--inner); } -.step .n { - font-family: var(--display); font-weight: 700; font-size: 1rem; color: var(--on-mag); - width: 30px; height: 30px; border-radius: 9px; display: grid; place-items: center; margin-bottom: 12px; - background: linear-gradient(120deg, var(--magenta-hi), var(--violet)); -} -.step h4 { font-family: var(--display); font-size: 1.02rem; margin: 0 0 8px; color: var(--ink); } -.step p { margin: 0; font-size: 0.94rem; } -.step code { font-size: 0.84em; } - -/* ---- Footer --------------------------------------------------------------- */ -footer { border-top: 1px solid var(--line); padding: 46px 0 72px; color: var(--faint); font-family: var(--mono); font-size: 12.5px; letter-spacing: 0.02em; } -footer a { color: var(--cyan); } -footer .prov { margin-top: 10px; color: var(--muted); } -.stack-links { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px 22px; margin-bottom: 16px; padding-bottom: 16px; border-bottom: 1px solid var(--line); } -.stack-links .stack-lead { color: var(--faint); text-transform: uppercase; letter-spacing: 0.1em; } -.stack-links a { color: var(--cyan); } -.stack-links a:hover { color: var(--magenta-hi); } - -/* ---- Responsive ----------------------------------------------------------- */ -@media (max-width: 900px) { .hero-grid { grid-template-columns: 1fr; } .hero-art { order: -1; } } -@media (max-width: 640px) { - body { font-size: 16px; } - .nav-links { display: none; } - .section > summary { gap: 12px; padding: 18px; } - .section .num { padding-top: 4px; } - .hero .meta-row { gap: 14px; } -} - -/* ---- Drop-in download dropzone -------------------------------------------- */ -.dropzone { - display: block; margin: 24px 0 8px; text-decoration: none; - border: 2px dashed var(--line-strong); border-radius: var(--radius); - padding: clamp(26px, 5vw, 46px); text-align: center; - background: var(--fill-violet); color: var(--ink); - transition: border-color 0.2s var(--ease), background 0.2s var(--ease), - transform 0.2s var(--ease), box-shadow 0.2s var(--ease); - cursor: pointer; -} -.dropzone:hover, .dropzone:focus-visible { - border-color: var(--magenta); background: var(--fill-mag); - box-shadow: var(--glow-mag); outline: none; -} -.dropzone.is-dragover { - border-color: var(--cyan); background: var(--fill-cyan); - transform: scale(1.01); box-shadow: var(--glow-cyan); -} -.dropzone .dz-icon { - font-family: var(--display); font-weight: 700; font-size: 2rem; - color: var(--cyan); margin-bottom: 6px; line-height: 1; -} -.dropzone strong { color: var(--ink); font-size: 1.05rem; } -.dropzone .dz-hint { - font-family: var(--mono); font-size: 12px; color: var(--muted); - letter-spacing: 0.02em; margin-top: 10px; -} -.dropzone .dz-status { - margin-top: 12px; font-family: var(--mono); font-size: 12.5px; - color: var(--cyan-soft); min-height: 1.2em; -} - -/* ---- Studio audio player -------------------------------------------------- */ -.studio-player { - margin: 22px 0 8px; padding: 18px 20px; border-radius: var(--radius); - background: var(--fill-cyan); border: 1px solid var(--cyan); - box-shadow: var(--inner); -} -.studio-player figcaption { - color: var(--ink-2); font-size: 13.5px; line-height: 1.5; margin-bottom: 12px; -} -.studio-player audio { width: 100%; display: block; border-radius: 8px; } -.studio-player .studio-links { - margin-top: 12px; font-size: 13px; color: var(--muted); -} -.studio-player .studio-links a { color: var(--cyan-soft); } - -/* ---- Studio hero (public NotebookLM) -------------------------------------- */ -.studio-hero { - position: relative; overflow: hidden; - margin: 26px 0 18px; padding: 26px 26px 22px; - border-radius: var(--radius); border: 1px solid var(--line-strong); - background: - radial-gradient(120% 140% at 12% 0%, rgba(255,61,240,0.14), transparent 55%), - radial-gradient(120% 140% at 92% 100%, rgba(57,232,255,0.12), transparent 55%), - linear-gradient(180deg, var(--bg-2) 0%, var(--inset) 100%); - box-shadow: var(--shadow), var(--glow-mag); -} -.studio-hero-glow { - position: absolute; inset: -40% 30% auto -10%; height: 200px; - background: radial-gradient(closest-side, rgba(139,92,255,0.35), transparent); - filter: blur(28px); pointer-events: none; -} -.studio-hero-kicker { - position: relative; margin: 0 0 6px; font-family: var(--mono); - font-size: 11.5px; letter-spacing: 0.06em; text-transform: uppercase; color: var(--cyan); -} -.studio-hero-title { - position: relative; margin: 0 0 8px; font-size: 1.45rem; line-height: 1.2; color: var(--ink); -} -.studio-hero-sub { - position: relative; margin: 0 0 16px; max-width: 62ch; color: var(--ink-2); font-size: 0.98rem; -} -.studio-hero-cta { position: relative; margin: 0 0 14px; } -.studio-chips { - position: relative; list-style: none; margin: 0; padding: 0; - display: flex; flex-wrap: wrap; gap: 8px; -} -.studio-chips li { - font-size: 12.5px; color: var(--ink-2); - padding: 5px 11px; border-radius: 999px; - border: 1px solid var(--line-strong); background: var(--inset); -} - -/* ---- Studio media gallery (video · slides · infographic) ------------------ */ -.studio-gallery { - display: grid; gap: 16px; margin: 18px 0 8px; - grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); -} -.studio-card { - margin: 0; padding: 14px; border-radius: var(--radius-s); - background: var(--bg-2); border: 1px solid var(--line-strong); - box-shadow: var(--inner); -} -.studio-card figcaption { - color: var(--ink-2); font-size: 13px; line-height: 1.5; margin-bottom: 10px; -} -.studio-card video { width: 100%; display: block; border-radius: 8px; background: #000; } -.studio-card img { width: 100%; display: block; border-radius: 8px; } -.studio-thumb { - display: flex; flex-direction: column; align-items: center; justify-content: center; - gap: 8px; min-height: 120px; text-align: center; color: var(--cyan-soft); - border: 1px dashed var(--line-strong); border-radius: 8px; padding: 18px; - font-size: 13.5px; transition: border-color 0.18s var(--ease), color 0.18s var(--ease); -} -.studio-thumb:hover { color: var(--magenta-hi); border-color: var(--magenta); } -.studio-thumb-ic { font-size: 30px; } - -/* ---- Reduced motion ------------------------------------------------------- */ -@media (prefers-reduced-motion: reduce) { - html { scroll-behavior: auto; } - *, *::before, *::after { animation-duration: 0.001ms !important; animation-iteration-count: 1 !important; transition-duration: 0.001ms !important; } - .cta:hover { transform: none; } -} diff --git a/ruv-explainer-ruqu/vercel.json b/ruv-explainer-ruqu/vercel.json deleted file mode 100644 index 3583afa..0000000 --- a/ruv-explainer-ruqu/vercel.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "$schema": "https://openapi.vercel.sh/vercel.json", - "cleanUrls": true, - "trailingSlash": false, - "headers": [ - { - "source": "/assets/(.*)", - "headers": [ - { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" } - ] - }, - { - "source": "/(.*)\\.svg", - "headers": [ - { "key": "Content-Type", "value": "image/svg+xml" } - ] - }, - { - "source": "/downloads/(.*)\\.zip", - "headers": [ - { "key": "Content-Type", "value": "application/zip" }, - { "key": "Cache-Control", "value": "public, max-age=300" } - ] - }, - { - "source": "/studio/(.*)\\.m4a", - "headers": [ - { "key": "Content-Type", "value": "audio/mp4" }, - { "key": "Cache-Control", "value": "public, max-age=86400" } - ] - }, - { - "source": "/studio/(.*)\\.md", - "headers": [ - { "key": "Content-Type", "value": "text/markdown; charset=utf-8" } - ] - } - ] -} diff --git a/ruv-explainer-ruvn/.gitignore b/ruv-explainer-ruvn/.gitignore deleted file mode 100644 index 595ac3f..0000000 --- a/ruv-explainer-ruvn/.gitignore +++ /dev/null @@ -1,28 +0,0 @@ -# Secrets — NEVER commit -.env -.env.* -*.key -*.pem -*.p12 -memory.db -*.db - -# Build targets / upstream clones / deploy state -.targets/ -.vercel -.vercel/ -node_modules/ - -# KEEP the drop-in zip — it is served directly from the site (downloads/ruvn-dropin.zip), -# and the NotebookLM studio media rides INSIDE that zip. Do NOT gitignore downloads/*.zip here. - -# Optional self-hosted fonts dropped in at build time (kept out of git). -assets/fonts/*.woff2 - -# studio/ holds local full-res NotebookLM masters (download staging only). The SERVED copies -# live in assets/studio/ and the zip embeds from kb/stores/. Don't commit duplicate binaries. -studio/ - -# Tooling noise -.DS_Store -*.log diff --git a/ruv-explainer-ruvn/assets/diagrams/README.md b/ruv-explainer-ruvn/assets/diagrams/README.md deleted file mode 100644 index 1961f0d..0000000 --- a/ruv-explainer-ruvn/assets/diagrams/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# assets/diagrams - -The precise **technical diagrams** for this explainer are authored as **crisp inline SVG** -directly in `index.html` (one per numbered section, in each `
`), -per ADR-0001 Part II gate (E): *"ARCHITECTURAL / explanatory diagrams — authored as crisp SVG, -not AI raster."* Authoring them inline keeps them styleable, zoomable, accessible -(``/`<desc>` + `role="img"`), and zero-request. - -This folder is reserved for any standalone `.svg` exports of those diagrams if they are ever -needed outside the page (e.g. for the NotebookLM human half or social cards). - -The **friendly raster on-ramp** illustrations live in `../img/` (g-*.png). diff --git a/ruv-explainer-ruvn/assets/img/g-before-after.png b/ruv-explainer-ruvn/assets/img/g-before-after.png deleted file mode 100644 index bc255c7..0000000 Binary files a/ruv-explainer-ruvn/assets/img/g-before-after.png and /dev/null differ diff --git a/ruv-explainer-ruvn/assets/img/g-dropin.png b/ruv-explainer-ruvn/assets/img/g-dropin.png deleted file mode 100644 index 08357f4..0000000 Binary files a/ruv-explainer-ruvn/assets/img/g-dropin.png and /dev/null differ diff --git a/ruv-explainer-ruvn/assets/img/g-grades.png b/ruv-explainer-ruvn/assets/img/g-grades.png deleted file mode 100644 index 18e4f0f..0000000 Binary files a/ruv-explainer-ruvn/assets/img/g-grades.png and /dev/null differ diff --git a/ruv-explainer-ruvn/assets/img/g-hero.png b/ruv-explainer-ruvn/assets/img/g-hero.png deleted file mode 100644 index b713cf5..0000000 Binary files a/ruv-explainer-ruvn/assets/img/g-hero.png and /dev/null differ diff --git a/ruv-explainer-ruvn/assets/img/g-persona.png b/ruv-explainer-ruvn/assets/img/g-persona.png deleted file mode 100644 index 9d12da8..0000000 Binary files a/ruv-explainer-ruvn/assets/img/g-persona.png and /dev/null differ diff --git a/ruv-explainer-ruvn/assets/img/g-pipeline.png b/ruv-explainer-ruvn/assets/img/g-pipeline.png deleted file mode 100644 index f661231..0000000 Binary files a/ruv-explainer-ruvn/assets/img/g-pipeline.png and /dev/null differ diff --git a/ruv-explainer-ruvn/favicon.svg b/ruv-explainer-ruvn/favicon.svg deleted file mode 100644 index bf84a68..0000000 --- a/ruv-explainer-ruvn/favicon.svg +++ /dev/null @@ -1,25 +0,0 @@ -<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" role="img" aria-label="ruvn — graded evidence stamp"> - <!-- Hand-authored DOSSIER mark: a warm paper square with a forest-green - grade-A rubber stamp and an oxblood casefile corner. Deliberately NOT - the MetaHarness molten-amber 'MH' coin. --> - <defs> - <linearGradient id="paper" x1="0" y1="0" x2="0" y2="1"> - <stop offset="0%" stop-color="#fbf6ea"/> - <stop offset="100%" stop-color="#efe5d2"/> - </linearGradient> - </defs> - <!-- paper field --> - <rect width="32" height="32" rx="6" fill="url(#paper)" stroke="#d8c9a8" stroke-width="1"/> - <!-- oxblood casefile spine on the left edge --> - <rect x="0" y="0" width="4" height="32" rx="2" fill="#9e2b25"/> - <!-- dog-eared corner --> - <path d="M24 4 L28 4 L28 8 Z" fill="#e3d2ad"/> - <!-- forest-green 'A' grade stamp, rotated like a struck stamp --> - <g transform="rotate(-8 18 18)"> - <rect x="9" y="9" width="18" height="16" rx="3" fill="none" stroke="#3f6b3a" stroke-width="2"/> - <text x="18" y="22.5" text-anchor="middle" font-family="Georgia, 'Times New Roman', serif" - font-weight="800" font-size="14" fill="#3f6b3a">A</text> - </g> - <!-- tiny green check --> - <path d="M22.5 11.5 l1.6 1.6 l3-3.4" fill="none" stroke="#3f6b3a" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/> -</svg> diff --git a/ruv-explainer-ruvn/index.html b/ruv-explainer-ruvn/index.html deleted file mode 100644 index 8e6743f..0000000 --- a/ruv-explainer-ruvn/index.html +++ /dev/null @@ -1,1354 +0,0 @@ -<!doctype html> -<html lang="en"> -<head> - <meta charset="utf-8" /> - <meta name="viewport" content="width=device-width, initial-scale=1" /> - <title>ruvn — the AI research assistant that grades its sources and hands you a cited dossier - - - - - - - - - - - - - - - - - - -
- -
- -
- - -
-
-
-

ruvnet · ruvn · an evidence-grading research agent

-

Stop trusting the
confident paragraph.
Get a graded dossier.

-

- ruvn is a free AI research assistant that turns a question into a - graded, cited evidence dossier. It searches the web, gives every source a - letter grade for trustworthiness, writes its answer using only the - trustworthy ones, tries to prove itself wrong, and hands you a report where - every single claim has a receipt. It runs inside the AI you already have - — npm i -g @ruvnet/ruvn — and adds no model of its own. -

-

- An independent explainer for Reuven Cohen’s - (@ruvnet) ruvn - — built to help you actually adopt and implement his technology. -

- - -
-
- Case File - An open paper evidence dossier on a warm wooden desk, with source clippings paperclipped to the pages, each wearing a small rubber-stamp letter grade A, B, C or D, and a magnifying glass resting on top. -
What ruvn gives you back: an evidence dossier where every source carries a grade and every claim can be checked.
-
-
-
- - -
-
- Provenance - Original tool by Reuven Cohen / @ruvnet - Source: github.com/ruvnet/ruvn - Updated 2026-06-19 · source @ruvnet/ruvn v0.1.1 @ 5b5dd72 - This page explains, and credits, ruv’s work — it is not the tool itself. - Built with the Ruv-Explainer pipeline -
-
- - -
-
- - -
- - 01 - -

Meet Dr. Priya — the “oh, that’s what it’s for” story

- One real person, one real before → after. -
- -
-
-

Start here

-

- Dr. Priya runs a small wellness studio. She’s heard clients - ask about “40 Hz light-and-sound therapy” for focus and sleep, and - she wants to know whether there’s real evidence before she says - anything to anyone. She is not a scientist and she does not have time to read forty - browser tabs. She already uses Claude Code — mostly for her booking - spreadsheets — so the AI is right there on her laptop. -

- -

Before ruvn. She asks her normal AI chatbot, - “Does 40 Hz light therapy actually help with sleep?” It hands - her one smooth, confident paragraph. It sounds authoritative. But she has no - idea whether that confidence came from a 2024 clinical trial or from a - supplement-seller’s blog — they’re blended together with no labels. - She can’t tell what to trust, can’t cite anything to a client, and - can’t tell what’s hype. She’s stuck with a paragraph she can’t - stand behind.

- -

After ruvn. She installs it once - (npm i -g @ruvnet/ruvn, then ruvn init) and asks Claude Code - to run the ruvn research pipeline on the same question. Now it splits her question into - precise sub-questions, goes and finds the sources, grades each one A/B/C/D, - writes the findings using only the A’s and B’s, then - tries to prove each statement wrong and deletes anything it can’t back up, - and finally hands her a dossier where every claim has a numbered citation and - every source shows its grade. She gets a TL;DR, a cited body, and a graded - bibliography. She can see the strong claims rest on a graded-A 2024 paper and the weak - ones were thrown out. Now she can honestly tell a client, “here’s what the - good evidence says, and here’s what it doesn’t.”

- -
- The line that makes it click - It’s the difference between an AI that hands you a confident paragraph you - can’t check, and one that hands you a graded, cited dossier you can. -
- - -

Technical view — the same question, two very different paths

-
- - Before and after ruvn: one blended paragraph versus a six-stage graded pipeline - Before ruvn, sources of every quality are blended into one unlabeled confident paragraph. After ruvn, the same question passes through scout, web-searcher, source-grader, synthesizer, fact-checker and citer, producing a dossier where every claim is cited and every source is graded A to D. - - - - - - - - - - The same question: “Does 40 Hz light therapy help sleep?” - - - - BEFORE — a plain AI chat - - - Sources of every quality, mixed together - 2024 trial - forum post - seller blog - no labels · no grades · you can’t tell them apart - - - - One confident paragraph - sounds sure either way - “trust me” - nothing to cite, nothing to check - Result: a paragraph Priya can’t stand behind - - - AFTER — the ruvn pipeline - - - scout — split into precise sub-questions - web-searcher — collect raw sources - source-grader — stamp each A / B / C / D - synthesizer — write from A & B only - fact-checker — disprove & delete unsupported - citer — attach a receipt to every claim - - - - A graded, cited dossier - TL;DR · cited body · graded bibliography - every claim has a receipt; weak sources thrown out - - The clever part: each helper only sees what the one before it produced — - so good information is forced through a grading gate and a fact-checking gate before it reaches you. - A confident paragraph you can’t check → a graded dossier you can. - -
The whole idea in one diagram: a plain chat blends every source into one unlabeled paragraph (left); ruvn forces the same question through six checkpoints — grade, then write from the good ones only, then fact-check, then cite — and returns a dossier you can audit (right).
-
- - -

Friendly view — what it feels like for Priya

-
- A relieved wellness-studio owner at a cozy desk holding a tidy cited report with letter-grade tabs, while a chaotic pile of browser tabs and sticky-note question marks fades away behind her. -
- Before: forty tabs, sticky notes, and a nagging “can I actually trust this?” - After: one tidy report she can hand to a client, with grades she can point to. Same - AI, same laptop — ruvn just made it show its work. -
-
- -
- Honest framing - ruvn was built for exactly this kind of question — it was made for the - ruv-neural gamma-entrainment (40 Hz) research project — but - the repo is explicit that “it works for any research question.” The - medical framing is the origin story, not a limit. And ruvn is a research tool: - it grades and cites evidence; it does not give medical advice or make - efficacy claims. -
-
-
- - -
- - 02 - -

What problem it solves — the “confident blend” trap

- What does it actually do? Why do I care? -
- -
-
-

- When you ask a normal AI chatbot to “research” something, it blends good - sources and bad sources into one confident paragraph — and you - can’t tell which parts came from a peer-reviewed paper and which came from a - random forum post. It sounds sure of itself either way. That’s the trap. - The repo puts it bluntly: “Most ‘ask an AI’ research blends good - and bad sources into one confident answer. ruvn refuses to.” -

-

So, plainly:

-
    -
  • What does it actually do? It does disciplined research for - you — finds sources, grades them, writes only from the trustworthy ones, - fact-checks itself, and gives you a cited report instead of a confident guess.
  • -
  • Why do I care? Because a confident-but-wrong answer is the most - expensive kind. ruvn makes the AI show its work — you can see - which claim came from which source, and how good that source is, at a glance. No more - “trust me.”
  • -
  • Why do I need it? Because the AI you already use doesn’t grade - its sources by default — it just answers. ruvn bolts a - grading-and-verification discipline onto the AI you already have, so - “research” stops meaning “plausible paragraph” and starts - meaning “evidence you can check.”
  • -
  • Why is it important? Because the output is auditable. - Every claim has a citation; every source has a grade. You — or a colleague, or a - skeptic — can re-check it. That’s the difference between a vibe and a - dossier.
  • -
- - -

Technical view — why a single blended answer hides the problem

-
- - The confident-blend trap, and how grading + citation undoes it - A plain AI flattens a strong paper, a weak blog and an unsourced forum post into one unlabeled paragraph, so a reader cannot trace any claim. ruvn keeps each source separate, grades it, and attaches the grade and a citation to every claim, making the output auditable. - - - - - Why “one confident paragraph” is the trap - - - 2024 clinical trialstrong · would be grade A - a tidy summarybackground only · grade C - unsourced forum postdiscard · grade D - - - - - - - PLAIN AI - one paragraph - grades flattened away - you can’t trace any claim - the D quietly counts as much as the A - - - - - - - RUVN — keep them separate, graded, cited - [A] kept · used in the answer, with a citation - - [C] background only — not evidence in the answer - - [D] discarded — never reaches you - - The difference: ruvn never lets the weak sources hide inside the strong ones. - - Plain AI: “trust me” — you can’t check it, can’t cite it, can’t tell hype from evidence. - ruvn: every claim carries a citation; every source carries a grade. - Auditable, not just plausible. - -
The trap, drawn out: a plain AI flattens a grade-A paper, a grade-C summary, and a grade-D forum post into one paragraph where the weak source secretly counts as much as the strong one. ruvn keeps them separate, grades each, and only lets the good ones into the answer — with a citation.
-
- - -

Friendly view — from “trust me” to a checkable case file

-
- On the left, a single grey blurry paragraph with a big question mark and the words trust me. On the right, the same content reorganized into a neat case file with numbered citation tags and green A and B grade stamps, joined by an arrow labelled transformation, verified. -
- Left: a confident grey blur you’re asked to trust. Right: the same content as a - tidy case file — numbered citations, graded sources, checkable. That arrow in the - middle is the whole product. -
-
-
-
- - -
- - 03 - -

The grading rubric — how a source earns its way into your answer

- A, B, C, D — and only A and B are allowed in. -
- -
-
-

- Here is the rule the whole tool turns on. The source-grader opens each - source and stamps it A, B, C, or D for how much you can trust it. The - synthesizer is then only allowed to write from the A and B - sources — the C’s and D’s are not allowed in. And the - fact-checker holds the bar higher still: a claim must be backed by - one grade-A source or two grade-B sources, or it gets stripped out. -

- - - - - - - - - - - -
GradeWhat it meansAllowed in the answer?
APrimary source (a real paper, an official doc), under ~2 years old, on-topic✓  Yes
BReputable secondary source (major outlet, named expert), under ~5 years✓  Yes
CTertiary (Wikipedia, a summary) — background only, not evidence✗  No
DDiscarded (forum post, unsourced claim, dead link)✗  No
- -
- The whole point in one line - The synthesizer is only allowed to use A and B. The fact-checker then - keeps a claim only if it has one A or two B’s behind it. Everything - else is background or gone. -
- - -

Technical view — the grading gate and the evidence threshold

-
- - The grading gate: sources sorted A to D, only A and B pass to the writer, and a claim survives only with one A or two B sources - Every collected source is graded A, B, C or D. A and B pass the first gate into the synthesizer; C and D are blocked. Then the fact-checker applies a second gate: a claim is kept only if backed by one grade-A source or two grade-B sources, otherwise it is deleted. - - - - - - Two gates a source must clear - - - COLLECTED - A · primary paper - B · reputable outlet - C · summary - D · forum post - - - - GATE 1 · grade - - - - - - - - - synthesizer - writes from A & B only - - - C/D blocked - (C = background; D = gone) - - - - - GATE 2 · verify - - - Claim KEPT - backed by 1×A  or  2×B - … then a citation is attached - - - Claim DELETED - can’t meet the threshold → stripped out - - - - - A source can be trusted (gate 1) and a claim can still be cut (gate 2). - Gate 1 decides which sources are allowed in. Gate 2 decides which claims have enough backing to survive. - Two independent checks — that’s why the output is hard to fool. - source: src/agents/source-grader.ts · synthesizer.ts · fact-checker.ts - -
The grading gate, exactly as the agents enforce it: Gate 1 (the grader) only lets A and B sources reach the writer; Gate 2 (the fact-checker) keeps a claim only if it has one grade-A or two grade-B sources behind it, then a citation is attached. Two separate checks, so weak evidence can’t sneak through on either.
-
- - -

Friendly view — the four grade stamps

-
- Four rubber-stamp letter grades on cream paper: A and B stamped in green with checkmarks and the words used in answer; C and D stamped in oxblood red with crosses and the words not used. -
- Green stamps get used; red stamps don’t. A and B are the evidence your answer is - built from; C is background only; D is thrown out. That’s the entire rubric on - one piece of paper. -
-
-
-
- - -
- - 04 - -

How it works — six specialist helpers, in a line

- A research process with checkpoints, not a single answer. -
- -
-
-

- ruvn is a research process with checkpoints, not a single answer. It runs - six specialist helpers in a line, and — this is the clever part — - each helper only sees what the one before it produced, never the raw mess. - So information is forced to pass through a grading gate and a fact-checking gate - before it ever reaches you. In plain words: -

-
    -
  1. scout — breaks your big question into 3–7 precise little - questions. “What exactly do we need to find out?”
  2. -
  3. web-searcher — goes and finds raw sources for each little - question; doesn’t judge yet, just collects. “Go find the sources.”
  4. -
  5. source-grader — opens each source and stamps it A, B, C, or D - for how much you can trust it. “Which of these can we actually trust?”
  6. -
  7. synthesizer — writes the findings using only the A and - B sources. The C’s and D’s are not allowed in. “Summarize — - but only from the good stuff.”
  8. -
  9. fact-checker — goes back and tries to disprove every - claim; anything it can’t support gets deleted. “Try to prove each - statement wrong, and cut what fails.”
  10. -
  11. citer — final pass: attaches a numbered citation to - every claim and builds the bibliography with the grades shown. - “No claim ships without a receipt.”
  12. -
-

- What you get back: a Markdown dossier — a TL;DR up top, a body where - every sentence is cited, and a bibliography with a letter grade next to each source. -

- - -

Technical view — the pipeline, its hand-off contract, and the model tier of each agent

-
- - The six-agent ruvn pipeline with its strict hand-off contract - Six agents run in order: scout, web-searcher, source-grader, synthesizer, fact-checker, citer. Each agent receives only the previous agent's structured output, not the raw web. The grader and writer enforce the A/B gate; the fact-checker enforces the evidence threshold; the citer attaches citations. Five agents run on the sonnet tier; web-searcher runs on the cheaper haiku tier. - - - - - The pipeline — each helper only sees the one before it - Your question enters at the left; a graded, cited dossier leaves at the right. - - - - your - question - - - - - - 1 · scout - split into 3–7 - sub-questions - sonnet - - - 2 · web-searcher - collect raw sources - (no judging yet) - haiku · cheaper tier - - - 3 · source-grader - stamp each - A / B / C / D - sonnet - - - 4 · synthesizer - write from - A & B only - sonnet - - - 5 · fact-checker - disprove & - delete unsupported - sonnet - - - 6 · citer - cite every - claim - sonnet - - - - - - - - - - - - The hand-off contract - Each agent receives ONLY the previous agent’s structured output — never the raw web, never the raw mess. - - - - - - - - What leaves the pipeline - - A Markdown dossier - - ▸ a TL;DR up top - ▸ a body where every sentence is cited - ▸ a bibliography with a grade beside each source - - - Because each helper is fed a clean, structured hand-off, the grade and verify gates can’t be bypassed. - source: src/agents/scout.ts · web-searcher.ts · source-grader.ts · synthesizer.ts · fact-checker.ts · citer.ts - Tiers from each agent’s TIER field: five run on sonnet; web-searcher runs on the cheaper haiku tier. - -
The real pipeline, with the detail a README buries: six named agents in a fixed order; the strict hand-off contract (each only sees the previous agent’s structured output, never the raw web); the two forced gates (grade, then verify); the model tier each agent runs on; and the exact shape of the dossier that comes out.
-
- - -

Friendly view — six little helpers passing the folder down the line

-
- Six friendly little paper-character helpers in a line on a worktable, passing a manila folder hand to hand: a scout with a spyglass, a searcher with a net of papers, a grader with a stamp, a synthesizer with a pen, a fact-checker with a red reject stamp, and a citer attaching numbered tags. -
- Picture six little specialists at a worktable, passing one folder down the line. Each - only ever sees the folder the helper before them handed over — so by the time it - reaches you, it has been searched, graded, written, fact-checked, and tagged. -
-
-
-
- - -
- - 05 - -

What “solved” looks like — the dossier on your screen

- The exact thing you can hand a skeptic. -
- -
-
-

- “Done” isn’t a chat reply — it’s a file. ruvn returns a - ready-to-paste Markdown dossier with three parts you can actually point at: a - TL;DR at the top, a cited body where every sentence - carries a numbered receipt, and a graded bibliography where every source - shows its A/B/C tag. The citer’s own rule is blunt: “the dossier must NOT - contain any claim without a citation.” -

- - -

Technical view — the anatomy of the dossier ruvn writes

-
- - Anatomy of a ruvn dossier: TL;DR, a cited body, and a graded bibliography - A sample Markdown dossier showing a TL;DR block, a body where every sentence ends in a numbered citation, and a bibliography listing each source with its letter grade. Callouts point to the citation on each claim and the grade on each source. - - - - - What lands in your folder: a Markdown dossier - - - - - research-dossier.md - - - - - ## TL;DR - - - - - ## Findings - - [1] - - [2] - - [3] - - [1] - - - ## Sources - - A - [1] Nature, 2024 clinical trial — primary, on-topic - B - [2] Major outlet review — reputable secondary - A - [3] Official guideline doc — primary - D - — forum post, discarded · not cited in the body - - - - - every claim - ends in a receipt - - - every source - shows its grade - - - the D never made - it into the answer - - A skeptic can re-check it line by line. That’s the difference between a vibe and a dossier. - -
The solved state, concretely: a TL;DR, a body where every sentence ends in a numbered citation, and a bibliography where every source wears its grade. The grade-D forum post is listed but was never allowed into the answer — you can see exactly what was used and what was thrown out.
-
- - -

Friendly view — the finished case file on the desk

-
- An open evidence dossier on a warm desk with source clippings clipped in, each wearing a letter grade, and a magnifying glass on top, representing the finished, checkable research result. -
- This is what “solved” feels like: a tidy case file you can open, where the - strong sources are clipped in and graded, and the magnifying glass is right there if you - want to check any one of them yourself. -
-
-
-
- - -
- - 06 - -

“I already have Claude Code — why do I need ruvn too?”

- The discipline layer, not another brain. -
- -
-
-

- You almost certainly already have the AI host — Claude Code, Codex, Copilot. - So let’s answer this head-on. -

-

- Claude Code is the brilliant generalist brain. Out of the box, when - you say “research X,” it gives you one confident blended answer — it does - not, by default, grade each source, refuse to use the weak ones, - adversarially fact-check itself, and attach a citation to every claim. ruvn is the - discipline layer that makes it do all of that, every time, in a fixed - order. -

-

- And it doesn’t replace your AI — it rides inside it. ruvn ships - no model of its own; the kernel “makes no model calls — your host provides - the model.” You keep your same AI, your same login, your same bill. ruvn just - adds the six-agent research pipeline and the grading rubric on top. -

- -

Before → after on your own question

- - - - - - - - - - - -
 Plain AI chatWith ruvn
SourcesBlended, unlabeledEach graded A/B/C/D source-grader
What the answer is built fromWhatever it foundA & B sources only synthesizer
Self-checkingNone by defaultAdversarial fact-check; unsupported claims deleted fact-checker
CitationsSometimes, inconsistentlyEvery claim cited or it doesn’t ship citer
What you can hand a skeptic“Trust me”An auditable dossier
- - -

Technical view — ruvn is a thin discipline layer on the host you already run

-
- - ruvn adds a research pipeline and grading rubric on top of your existing AI host, without replacing the model - Your AI host provides the model and the web-search tool. ruvn sits on top as a configuration layer: six agent prompts and the A/B/C/D rubric. The kernel makes no model calls of its own. You keep the same login and bill; ruvn only adds the discipline. - - - - - ruvn rides inside the AI you already have - - - - YOUR AI HOST — Claude Code / Codex / Copilot … - the model (the brain)your login, your bill — unchanged - web-search toolWebFetch / WebSearch — the host’s - your files & memoryalready on your machine - - - - + ruvn — the discipline layer (config only, no model) - 6 agent prompts, in orderscout → … → citer - the A/B/C/D rubricgrade gate + evidence threshold - - - - - ruvn calls down into the host for the brain and the search — it never brings its own model. - Not another thing piled on. The same AI — now forced to grade, verify, and cite. - “the kernel makes no model calls — your host provides the model.” (README) - -
Why it’s not redundant with the AI you already pay for: ruvn ships no model. Your host still provides the brain, the web search, and your files. ruvn is a thin configuration layer — six agent prompts plus the grading rubric — that calls down into your host and forces the grade-verify-cite discipline every time.
-
- - -

Friendly view — same content, before and after the discipline

-
- A grey blurry trust-me paragraph on the left transforming via an arrow into a tidy verified case file with numbered citations and green grade stamps on the right. -
- The same AI, the same question — just run through ruvn’s discipline. The left - is what you get for free; the right is what ruvn turns it into. -
-
-
-
- - -
- - 07 - -

Use-case gallery — six real ways people use it

- Open each card for its own picture, command, and result. -
- -
-
-

- Every card below runs the same six-agent pipeline - (scout → web-searcher → source-grader → synthesizer → - fact-checker → citer). The variety is in the question and the audience — - not the machinery. Each opens to its own diagram. -

- - -
-
- - -
- - 08 - -

How to implement it — three commands

- Now that you know why, here’s how. -
- -
-
-

Straight from the repo. Install once, wire it into your host, confirm it loaded:

-
# installs the `ruvn` command -npm i -g @ruvnet/ruvn -# wires the harness into Claude Code (.claude/ settings + plugin) -ruvn init -# health check — confirms the kernel + host adapter load -ruvn doctor -# or one-off, no install: -npx @ruvnet/ruvn init
-

- Then, in Claude Code, ask it to run the research pipeline on your question — the - agents and the grading rubric in CLAUDE.md are now available to it. -

- -

Want to prove it against a live model first?

-

- Set an OpenRouter key and run the validation — it exercises all 6 agents on a real - sample question, and each must return a sensible, on-task answer. -

-
export OPENROUTER_API_KEY=sk-or-... -npm run validate:openrouter
- -

What’s actually inside (the pieces you get)

-
    -
  • 6 agent definitions — each a plain prompt + model tier you can read - and tweak (src/agents/*.ts). scout / grader / synth / fact-check / citer run on - the sonnet tier; web-searcher runs on the cheaper haiku tier.
  • -
  • A tiny CLI — init, doctor, --version - (bin/cli.js).
  • -
  • Host config for 9 hosts — the .claude/, .codex/, - .vscode/, .opencode/, .openclaw/, .github/, - plus AGENTS.md / SYSTEM.md / trust.json / - cli-config.yaml / rvm.manifest.toml.
  • -
  • A real smoke test — boots the kernel + host adapter so a broken - install fails loudly (__tests__/smoke.test.ts).
  • -
- - -

Technical view — what each command does to your project

-
- - The install and boot sequence: install the CLI, init wires host config, doctor verifies the adapter loads - Step one installs the ruvn command globally. Step two, ruvn init, writes host configuration files such as .claude settings and the CLAUDE.md gate into your project. Step three, ruvn doctor, loads the kernel and host adapter to confirm everything is wired before you run it. - - Three commands, three concrete effects - - - 1 · npm i -g @ruvnet/ruvn - Adds the global ruvn - command to your machine. - Nothing touched in your repo yet — - just the tool itself. - - - 2 · ruvn init - Writes host config into - your project: - .claude/settings.json - CLAUDE.md (the gate) - + the agents & rubric - - - 3 · ruvn doctor - Loads the kernel + host - adapter and checks it. - ✓ green → ready to run - a broken install fails loudly, - not silently. - - - - After step 3: ask Claude Code to run the ruvn pipeline on your question — the rubric is already loaded. - source: README.md install steps · bin/cli.js - -
Each command, demystified: install adds the CLI; ruvn init writes the host config and the CLAUDE.md gate into your project; ruvn doctor boots the adapter to confirm it loaded. Then you just ask your AI to run the pipeline.
-
- - -

Friendly view — the six helpers are now on call

-
- Six friendly paper-character helpers ready at a worktable, representing the ruvn pipeline now installed and available inside your AI host. -
- After three commands, the six little helpers are on call inside the AI you already use. - Ask for research, and they line up — scout, search, grade, write, fact-check, cite. -
-
-
-
- - -
- - 🎧 - -

The NotebookLM studio — listen, watch, skim, or open the whole thing

- A full media pack: audio, video, slides, an infographic & a report. -
- -
-
-

- We fed ruvn’s own primer, README, and CLAUDE.md into NotebookLM and - had it build a whole media pack — each piece tuned for a newcomer: - the same plain-language story (a confident, unsourced AI paragraph → a - graded, cited dossier you can actually defend) told as audio, video, slides, an - infographic, and a written report. Start wherever you like — or open the live - notebook and explore the sources yourself. -

- - -
- -
-

Open the NotebookLM studio — audio, video, slides & more

-

The live, public notebook: every artifact below plus the source documents they were built from. Free, no sign-up to view.

-
- ▶  Open the studio → -
- - -
-
- -
-

Audio overview — play this first

-

A warm two-host conversation: the confident-blend trap, how grading + citation fix it, and how to start.

-
-
- - -
- -
-

Written report — the briefing doc

-

A skimmable deep-dive: the six-agent pipeline (with model tiers), the A/B/C/D rubric, scope, and honest limits.

-
- Read the report → -
-
- - -
-
-

Video overview

-

A short animated explainer: the before→after, in motion.

- - -

Tip: also playable in the public notebook above.

-
- -
-

Slide deck

-

A detailed deck you can flip through — or hand to a colleague.

-
- - Cover of the ruvn slide deck: Stop Trusting, Start Verifying — how ruvn turns any question into a graded, cited evidence dossier. - -
- -

PDF rides inside the drop-in zip too.

-
- - -
-

Infographic — the whole story on one sheet

-

From AI “vibes” to graded evidence: before→after, the A/B/C/D rubric, and the three commands to start. Tap to open full-size.

-
- - ruvn infographic: From AI vibes to graded evidence. Before — standard AI blends a real study with random forum posts into one unverified paragraph. After — a graded dossier with primary and expert sources (Grade A/B), a TL;DR, and verified, cited synthesis. The A/B/C/D standard: A/B primaries used for synthesis, C (Wikipedia) for context only, D (forums, dead links) discarded. It rides inside tools you already use like Claude Code, is honest early beta, and starts in three steps: npm i -g @ruvnet/ruvn, ruvn init, ask your question. - -
- -
-
- -
- Made with NotebookLM - Every piece is generated from ruvn’s own primer, README, and CLAUDE.md, then checked - against the source. The audio, report, slides (PDF) and infographic also ride inside - the drop-in zip (for-humans/studio/); the full video and the live notebook are - linked from the zip’s README to keep the download light — see the file-tree below. -
-
-
- - -
- - 09 - -

The drop-in — one download, two halves

- What’s actually inside the zip. -
- -
-
-

- Beyond installing the tool, there’s a drop-in knowledge bundle: one - kb/ folder with two halves — one for you to read, one for - your AI to query against the real source. Here’s the actual file tree, every - file with a plain-English note on what it is: -

- - - - -

The 3-step drop-in

-
    -
  1. Listen first (optional): open for-humans/studio/ and play - 🎧 ruvn-audio-overview.m4a — a friendly two-host walkthrough - of the whole tool. Prefer reading? Open 📄 ruvn-report.md.
  2. -
  3. Unzip for-ai/ into your project, then npm i (two deps) and ask the - brain a question: node ask-kb.mjs ruvn "how does the source-grader decide A vs B?"
  4. -
  5. Wire it into your AI host: add the 2-line .mcp.json pointing at - kb-mcp-server.mjs, and paste the CLAUDE.md gate — now your AI - answers from the real ruvn source, not from guesses.
  6. -
- -
- Confirm it works - After wiring it in, ask: “Using the kb tool, how does ruvn’s source-grader - decide an A vs a B?” — a correct, grounded answer that quotes the rubric - means the drop-in is live. (The whole bundle is self-contained: the - for-humans/studio/ audio + report ride inside the zip, not just on this page.) -
- - -

Friendly view — the bundle dropping into your laptop

-
- A small kb folder being dropped into an open laptop, splitting into two labeled halves: a printed primer booklet for humans on the left, and a glowing brain-file for your AI on the right. -
- One small folder, two halves: a primer booklet you read, and a queryable - “brain” your AI answers from. Drop it in, wire two lines, and the AI - stops guessing about ruvn and starts quoting the real source. -
-
- - -
-

⇩  Download the drop-in Smart Zip

-

Click or press Enter. Self-contained: the for-humans/studio/ audio overview + report ride inside.

-

-
-
-
- - -
- - 10 - -

Honest limits — what ruvn is not

- Stated plainly, not hidden. -
- -
-
-
    -
  • Early beta — v0.1.1. This is a young, small package.
  • -
  • It’s a research tool, not an oracle. It grades and cites - evidence; it does not give medical advice or make efficacy claims. Its - output is “a starting dossier to verify, not a conclusion.”
  • -
  • It needs a host with web access. ruvn ships no model of its own - — the kernel makes no model calls; your AI host provides the brain and the web-search - tool. No host, no run.
  • -
  • Quality is bounded by what’s findable and by the grader’s judgment. - Grades are assigned by an AI applying the A/B/C/D rubric — solid, but not a human - peer-reviewer. Treat the dossier as a strong first pass to verify.
  • -
  • Domain DNA. It was built for the gamma-entrainment / ruv-neural project, - so its built-in examples and validation tasks are 40 Hz-flavored. The pipeline - is general; the examples just smell of its origin.
  • -
  • “Signed session bundles” is the sibling tool’s job. That - phrase in the one-liner belongs to ruv-neural (the closed-loop OS that - runs / measures / signs protocols); ruvn is the research front-end. Don’t - oversell ruvn as the protocol-signer.
  • -
-
- In one line - ruvn makes research auditable — it does not make it infallible. It hands you a - strong, checkable first pass; the checking is still yours to do. -
-
-
- -
-
-
- - -
-
-

- ruvn is created by Reuven Cohen (@ruvnet). Source & license: - github.com/ruvnet/ruvn - — package @ruvnet/ruvn. - This explainer is an independent, plain-language guide to ruv’s work — it is not the - tool itself, and every claim on it is grounded in the real repository. -

-

- Updated 2026-06-19 · source @ruvnet/ruvn v0.1.1 @ 5b5dd72 · - built with the Ruv-Explainer Repo-Primer Pipeline (ADR-0001). -

-
-
- - - - diff --git a/ruv-explainer-ruvn/kb/.last-built.json b/ruv-explainer-ruvn/kb/.last-built.json deleted file mode 100644 index d887bf4..0000000 --- a/ruv-explainer-ruvn/kb/.last-built.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "builtAt": "2026-06-19", - "version": "v0.1.1", - "targetRepoSha": "5b5dd7247bd9e0f61bdce2fee6730692b9606977", - "embedder": "Xenova/bge-small-en-v1.5", - "dim": 384, - "gateA": { "score": 99.7, "heldout": 99.8, "passed": true, "date": "2026-06-19" } -} diff --git a/ruv-explainer-ruvn/main.js b/ruv-explainer-ruvn/main.js deleted file mode 100644 index c7e7cfc..0000000 --- a/ruv-explainer-ruvn/main.js +++ /dev/null @@ -1,88 +0,0 @@ -/* ============================================================================= - ruvn ExplainerSite — main.js (progressive enhancement only; < 6 KB) - The page is fully usable with JS disabled: all sections and gallery cards - are native
/. This script adds, on top: - 1. deep-link: open the
a #hash points at, and on nav-click. - 2. drop-in stub: click / keyboard / drag-and-drop converge on one handler; - the real .zip href wires up when the Drop-in Smart Zip is published. - No dependencies. No build step. - ========================================================================== */ -(function () { - "use strict"; - - /* --- 1. Deep-link a section open ---------------------------------------- */ - function openFromHash() { - var id = (location.hash || "").replace(/^#/, ""); - if (!id) return; - var el = document.getElementById(id); - while (el && el.tagName !== "DETAILS") el = el.parentElement; - if (el && !el.open) el.open = true; - if (el && el.scrollIntoView) el.scrollIntoView({ behavior: "smooth", block: "start" }); - } - window.addEventListener("hashchange", openFromHash); - openFromHash(); - - // Clicking an in-page nav link should also expand its target section. - document.querySelectorAll('a[href^="#"]').forEach(function (a) { - a.addEventListener("click", function () { - var id = a.getAttribute("href").slice(1); - var sec = document.getElementById(id); - while (sec && sec.tagName !== "DETAILS") sec = sec.parentElement; - if (sec && !sec.open) sec.open = true; - }); - }); - - /* --- 2. Drop-in stub (click / keyboard / drag) -------------------------- */ - var dz = document.getElementById("dropzone"); - var status = document.getElementById("dzStatus"); - if (!dz) return; - - // The drop-in Smart Zip ships alongside the site under downloads/. - var DOWNLOAD_HREF = "downloads/ruvn-dropin.zip"; - - function say(msg) { if (status) status.textContent = msg; } - - function activate() { - say("Downloading ruvn-dropin.zip … (unzip → cd for-ai → npm i → node ask-kb.mjs ruvn \"what does ruvn do\")"); - var a = document.createElement("a"); - a.href = DOWNLOAD_HREF; - a.download = "ruvn-dropin.zip"; - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - } - - dz.addEventListener("click", activate); - - dz.addEventListener("keydown", function (e) { - if (e.key === "Enter" || e.key === " " || e.key === "Spacebar") { - e.preventDefault(); - activate(); - } - }); - - ["dragenter", "dragover"].forEach(function (evt) { - dz.addEventListener(evt, function (e) { - e.preventDefault(); - e.stopPropagation(); - dz.classList.add("is-dragover"); - }); - }); - ["dragleave", "dragend"].forEach(function (evt) { - dz.addEventListener(evt, function (e) { - e.preventDefault(); - dz.classList.remove("is-dragover"); - }); - }); - dz.addEventListener("drop", function (e) { - e.preventDefault(); - e.stopPropagation(); - dz.classList.remove("is-dragover"); - var n = (e.dataTransfer && e.dataTransfer.items && e.dataTransfer.items.length) || 0; - say( - n - ? "Caught " + n + " item(s). The drop-in is a download, not an upload — click or press Enter to get it." - : "Nothing detected. Click or press Enter to get the drop-in instead." - ); - }); -})(); diff --git a/ruv-explainer-ruvn/package.json b/ruv-explainer-ruvn/package.json deleted file mode 100644 index 542569c..0000000 --- a/ruv-explainer-ruvn/package.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "name": "ruv-explainer-ruvn", - "version": "0.1.0", - "private": true, - "description": "Dossier / warm-paper ExplainerSite for ruvn (ruvnet/ruvn) — an AI research assistant that grades sources and builds cited evidence dossiers. Static, no build, no deps.", - "license": "MIT", - "homepage": "https://ruvn-explainer.vercel.app", - "repository": { - "type": "git", - "url": "https://github.com/stuinfla/ruvn-explainer" - }, - "keywords": [ - "ruvn", - "ruvnet", - "research-agent", - "evidence-grading", - "explainer", - "static-site" - ], - "scripts": {} -} diff --git a/ruv-explainer-ruvn/robots.txt b/ruv-explainer-ruvn/robots.txt deleted file mode 100644 index 20b437e..0000000 --- a/ruv-explainer-ruvn/robots.txt +++ /dev/null @@ -1,4 +0,0 @@ -User-agent: * -Allow: / - -Sitemap: https://ruvn-explainer.vercel.app/sitemap.xml diff --git a/ruv-explainer-ruvn/sitemap.xml b/ruv-explainer-ruvn/sitemap.xml deleted file mode 100644 index 8df892d..0000000 --- a/ruv-explainer-ruvn/sitemap.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - https://ruvn-explainer.vercel.app/ - 2026-06-19 - weekly - 1.0 - - diff --git a/ruv-explainer-ruvn/styles.css b/ruv-explainer-ruvn/styles.css deleted file mode 100644 index 585730c..0000000 --- a/ruv-explainer-ruvn/styles.css +++ /dev/null @@ -1,629 +0,0 @@ -/* ============================================================================= - ruvn ExplainerSite — DOSSIER / WARM PAPER & INK (editorial) - Aesthetic lock [Constraint K]: WARM CREAM PAPER substrate (never dark), - sepia/oak INK type, oxblood-red & forest-green GRADE STAMPS, manila tabs, - paperclip + ruled-margin casefile motifs. Deliberately NOT the dark - amber/charcoal MetaHarness "foundry" look and NOT any cyan/phosphor theme. - Editorial serif display (Spectral) over a humanist sans (Source Sans 3) - with a typewriter mono (Spline Sans Mono) for stamps & commands. - Static, no build, no JS dependency for core function. - ========================================================================== */ - -/* ---- Fonts: Google Fonts CDN (display swap). No build step. --------------- - Self-host later by dropping woff2 into assets/fonts/ and swapping these. */ -@import url("https://fonts.googleapis.com/css2?family=Spectral:ital,wght@0,400;0,600;0,800;1,400&family=Source+Sans+3:wght@400;500;600;700&family=Spline+Sans+Mono:wght@400;500;600&display=swap"); - -/* ---- :root — DOSSIER DESIGN TOKENS ---------------------------------------- - Hues are warm paper + ink. Two stamp accents only: oxblood + forest. */ -:root { - /* Paper substrate — warm cream, aging toward manila at the edges */ - --paper: #f4ecdc; /* page floor — warm cream */ - --paper-2: #efe5d2; /* raised plane */ - --card: #fbf6ea; /* card body — brighter sheet */ - --card-2: #f0e7d4; /* card header / inset */ - --manila: #e3d2ad; /* folder tab / manila accent */ - --rule: #d8c9a8; /* hairline edges, ruled margins */ - - /* Ink — warm oak-brown, never pure black */ - --ink: #3a2f25; /* primary text */ - --ink-2: #5a4a39; /* secondary text */ - --muted: #84715a; /* captions, meta */ - --faint: #a8966f; /* hairline labels */ - - /* Stamp accents — the only saturated colours on the page */ - --oxblood: #9e2b25; /* primary stamp / reject / margin rule */ - --oxblood-dk: #7a201c; /* pressed shadow side */ - --forest: #3f6b3a; /* approve / grade A & B */ - --forest-dk: #2f5230; /* pressed shadow side */ - --brass: #b07d35; /* tertiary — paperclips, micro-labels */ - --on-stamp: #fbf6ea; /* text that sits ON a filled stamp */ - - /* Lines / fills derived from ink + stamps */ - --line: rgba(58,47,37,0.14); - --line-strong: rgba(58,47,37,0.26); - --fill-ox: rgba(158,43,37,0.08); - --fill-forest: rgba(63,107,58,0.10); - - /* Depth — soft paper shadow + the red margin spine */ - --shadow: 0 16px 36px -22px rgba(58,40,20,0.45); - --shadow-deep: 0 30px 70px -34px rgba(58,40,20,0.5); - --emboss: inset 0 1px 0 rgba(255,251,240,0.7), - inset 0 -1px 0 rgba(120,95,55,0.12); - - /* Type */ - --display: "Spectral", Georgia, "Times New Roman", serif; - --sans: "Source Sans 3", system-ui, -apple-system, "Segoe UI", sans-serif; - --mono: "Spline Sans Mono", ui-monospace, "SF Mono", Menlo, monospace; - - /* Rhythm */ - --maxw: 1120px; - --gutter: clamp(20px, 5vw, 56px); - --radius: 10px; - --radius-s: 6px; - --ease: cubic-bezier(0.22, 0.61, 0.36, 1); -} - -/* ---- Reset / base --------------------------------------------------------- */ -*, *::before, *::after { box-sizing: border-box; } -html { -webkit-text-size-adjust: 100%; scroll-behavior: smooth; } - -body { - margin: 0; - background: var(--paper); - color: var(--ink); - font-family: var(--sans); - font-size: 17px; - line-height: 1.66; - -webkit-font-smoothing: antialiased; - text-rendering: optimizeLegibility; - /* Paper grain: faint warm radials + a hair of fibre noise via gradients. */ - background-image: - radial-gradient(1100px 560px at 82% -6%, rgba(176,125,53,0.07), transparent 60%), - radial-gradient(900px 640px at -8% 6%, rgba(158,43,37,0.045), transparent 55%), - linear-gradient(180deg, var(--paper) 0%, var(--paper-2) 100%); - background-attachment: fixed; -} - -img { max-width: 100%; height: auto; display: block; } - -a { - color: var(--oxblood); - text-decoration: none; - border-bottom: 1px solid rgba(158,43,37,0.35); - transition: color 0.18s var(--ease), border-color 0.18s var(--ease); -} -a:hover { color: var(--oxblood-dk); border-color: var(--oxblood); } -a:focus-visible, -summary:focus-visible, -.dz:focus-visible { - outline: 2.5px solid var(--brass); - outline-offset: 3px; - border-radius: var(--radius-s); -} - -code, kbd, .mono { font-family: var(--mono); } - -.wrap { max-width: var(--maxw); margin: 0 auto; padding: 0 var(--gutter); } - -/* ============================================================================= - TOP BAR — manila folder tab strip - ========================================================================== */ -.topbar { - position: sticky; top: 0; z-index: 40; - background: linear-gradient(180deg, var(--manila), #dcc8a0); - border-bottom: 2px solid var(--oxblood); - box-shadow: 0 2px 0 rgba(120,32,28,0.25), var(--shadow); -} -.topbar .wrap { - display: flex; align-items: center; gap: 14px; - height: 56px; -} -.brandmark { - display: inline-flex; align-items: center; gap: 10px; - font-family: var(--display); font-weight: 800; font-size: 19px; - color: var(--ink); border: 0; letter-spacing: 0.2px; -} -.brandmark img { width: 26px; height: 26px; } -.brandmark .dot { color: var(--oxblood); } -.topbar nav { - margin-left: auto; display: flex; gap: 6px; flex-wrap: wrap; -} -.topbar nav a { - font-family: var(--mono); font-size: 12.5px; font-weight: 500; - color: var(--ink-2); border: 0; padding: 5px 9px; border-radius: 6px; - letter-spacing: 0.3px; -} -.topbar nav a:hover { color: var(--oxblood); background: rgba(255,251,240,0.5); } -@media (max-width: 760px) { - .topbar nav { display: none; } -} - -/* ============================================================================= - HERO - ========================================================================== */ -.hero { - position: relative; - padding: clamp(48px, 8vw, 92px) 0 clamp(30px, 5vw, 52px); - border-bottom: 1px dashed var(--rule); -} -.hero .wrap { display: grid; grid-template-columns: 1.15fr 0.85fr; gap: clamp(24px, 4vw, 52px); align-items: center; } -@media (max-width: 900px) { .hero .wrap { grid-template-columns: 1fr; } } - -.eyebrow { - font-family: var(--mono); font-size: 12.5px; font-weight: 500; - letter-spacing: 1.5px; text-transform: uppercase; color: var(--muted); - margin: 0 0 14px; -} -.hero h1 { - font-family: var(--display); font-weight: 800; - font-size: clamp(36px, 6.2vw, 62px); line-height: 1.04; - letter-spacing: -0.5px; margin: 0 0 18px; color: var(--ink); -} -.hero h1 .stamp-word { - position: relative; color: var(--oxblood); white-space: nowrap; -} -.hero h1 .stamp-word::after { - content: ""; position: absolute; left: -6px; right: -6px; top: -4px; bottom: -2px; - border: 2.5px solid var(--oxblood); border-radius: 7px; - transform: rotate(-1.4deg); opacity: 0.55; pointer-events: none; -} -.lede { font-size: 19px; line-height: 1.62; color: var(--ink-2); margin: 0 0 22px; max-width: 60ch; } -.lede em { font-style: italic; color: var(--ink); } -.lede code { - background: var(--fill-forest); color: var(--forest-dk); - padding: 1px 6px; border-radius: 5px; font-size: 0.88em; - border: 1px solid rgba(63,107,58,0.25); -} - -.attrib-lede { - font-size: 15px; line-height: 1.58; color: var(--ink-2); margin: 0 0 22px; max-width: 60ch; - padding: 12px 16px; border-left: 3px solid var(--oxblood); border-radius: 0 7px 7px 0; - background: var(--card-2); -} -.attrib-lede strong { color: var(--ink); font-weight: 600; } -.attrib-lede a { color: var(--oxblood); border-bottom: 1px dotted var(--rule); } - -.meta-row { - display: flex; flex-wrap: wrap; gap: 8px 10px; margin: 0 0 26px; -} -.meta-row span { - font-family: var(--mono); font-size: 11.5px; color: var(--muted); - border: 1px solid var(--rule); background: var(--card); - padding: 5px 10px; border-radius: 5px; letter-spacing: 0.3px; -} -.meta-row b { color: var(--ink); font-weight: 600; } - -.cta-row { display: flex; flex-wrap: wrap; gap: 12px; align-items: center; } -.cta { - display: inline-flex; align-items: center; gap: 8px; - font-family: var(--sans); font-weight: 600; font-size: 15.5px; - color: var(--on-stamp); background: var(--oxblood); border: 0; - padding: 12px 22px; border-radius: 8px; - box-shadow: var(--shadow), inset 0 1px 0 rgba(255,255,255,0.18); - transition: transform 0.16s var(--ease), background 0.16s var(--ease); -} -.cta:hover { background: var(--oxblood-dk); color: var(--on-stamp); transform: translateY(-2px); border-color: transparent; } -.cta.ghost { - background: transparent; color: var(--ink); border: 1.5px solid var(--rule); - box-shadow: none; -} -.cta.ghost:hover { border-color: var(--oxblood); color: var(--oxblood); background: var(--fill-ox); transform: translateY(-2px); } - -.hero-art { - position: relative; border-radius: var(--radius); - border: 1px solid var(--rule); - box-shadow: var(--shadow-deep); - overflow: hidden; background: var(--card); - transform: rotate(-0.6deg); -} -.hero-art img { width: 100%; } -.hero-art figcaption { - font-family: var(--mono); font-size: 11px; color: var(--muted); - padding: 8px 12px; border-top: 1px solid var(--rule); - background: var(--card-2); -} - -/* "FILE STAMP" corner badge */ -.file-stamp { - position: absolute; top: 14px; right: 14px; z-index: 2; - font-family: var(--mono); font-size: 10.5px; font-weight: 600; - letter-spacing: 1px; text-transform: uppercase; - color: var(--oxblood); border: 2px solid var(--oxblood); - padding: 5px 9px; border-radius: 5px; transform: rotate(6deg); - background: rgba(251,246,234,0.7); opacity: 0.92; -} - -/* ============================================================================= - PROVENANCE BAR - ========================================================================== */ -.provenance { - background: var(--card-2); border-bottom: 1px dashed var(--rule); -} -.provenance .wrap { - display: flex; flex-wrap: wrap; gap: 8px 22px; align-items: center; - padding-top: 14px; padding-bottom: 14px; - font-family: var(--mono); font-size: 12.5px; color: var(--ink-2); -} -.provenance .pv-label { - color: var(--oxblood); font-weight: 600; letter-spacing: 0.5px; - text-transform: uppercase; font-size: 11px; -} -.provenance b { color: var(--ink); font-weight: 600; } -.provenance a { border-bottom-style: dotted; } -.provenance .sha { background: var(--paper); padding: 2px 7px; border-radius: 5px; border: 1px solid var(--rule); } - -/* ============================================================================= - SECTIONS — numbered casefile entries (
) - ========================================================================== */ -.sections { padding: clamp(28px, 5vw, 56px) 0 24px; } - -.section { - background: var(--card); - border: 1px solid var(--rule); - border-left: 4px solid var(--oxblood); /* the red casefile spine */ - border-radius: var(--radius); - box-shadow: var(--shadow); - margin: 0 0 22px; - overflow: hidden; -} -.section[open] { box-shadow: var(--shadow-deep); } - -.section > summary { - display: flex; align-items: center; gap: 16px; - padding: 20px clamp(18px, 3vw, 28px); - cursor: pointer; list-style: none; user-select: none; - background: - linear-gradient(180deg, var(--card) 0%, var(--card-2) 100%); - transition: background 0.18s var(--ease); -} -.section > summary::-webkit-details-marker { display: none; } -.section > summary:hover { background: var(--card-2); } - -.num { - font-family: var(--display); font-weight: 800; font-size: 30px; - color: var(--oxblood); line-height: 1; min-width: 50px; - border-right: 1px solid var(--rule); padding-right: 14px; - font-variant-numeric: tabular-nums; -} -.head-text { flex: 1; min-width: 0; } -.head-text h2 { - font-family: var(--display); font-weight: 600; font-size: clamp(20px, 3vw, 26px); - margin: 0; color: var(--ink); letter-spacing: -0.2px; line-height: 1.18; -} -.head-text .q { - display: block; font-family: var(--mono); font-size: 12px; color: var(--muted); - margin-top: 4px; letter-spacing: 0.2px; -} -.chev { - font-family: var(--display); font-size: 28px; color: var(--faint); - transition: transform 0.22s var(--ease); transform: rotate(90deg); -} -.section[open] > summary .chev { transform: rotate(-90deg); color: var(--oxblood); } - -.body { - padding: 4px clamp(18px, 3vw, 28px) 30px; - border-top: 1px dashed var(--rule); -} -.body > p:first-child { margin-top: 20px; } -.body p { margin: 0 0 16px; max-width: 72ch; } -.body ul, .body ol { margin: 0 0 18px; padding-left: 22px; max-width: 72ch; } -.body li { margin: 0 0 9px; } -.body strong { color: var(--ink); font-weight: 700; } -.body em { color: var(--ink-2); } -.body h3 { - font-family: var(--display); font-weight: 600; font-size: 19px; - color: var(--ink); margin: 28px 0 12px; -} -.body code { - font-family: var(--mono); font-size: 0.86em; - background: var(--paper); padding: 1px 6px; border-radius: 5px; - border: 1px solid var(--rule); color: var(--ink); -} - -/* Callout — a paperclipped margin note */ -.note { - position: relative; - background: var(--fill-forest); - border: 1px solid rgba(63,107,58,0.28); - border-left: 3px solid var(--forest); - border-radius: var(--radius-s); - padding: 14px 16px 14px 18px; margin: 18px 0 20px; - font-size: 15.5px; color: var(--ink-2); -} -.note.warn { background: var(--fill-ox); border-color: rgba(158,43,37,0.3); border-left-color: var(--oxblood); } -.note .note-k { - display: block; font-family: var(--mono); font-size: 11px; font-weight: 600; - letter-spacing: 0.8px; text-transform: uppercase; color: var(--forest-dk); - margin-bottom: 4px; -} -.note.warn .note-k { color: var(--oxblood-dk); } - -/* ============================================================================= - FIGURES — technical SVG diagrams + friendly raster - ========================================================================== */ -.figure { margin: 26px 0 8px; } -.figure svg { display: block; width: 100%; height: auto; } -.figure.diagram { - border: 1px solid var(--rule); border-radius: var(--radius); - background: var(--card); padding: 8px; box-shadow: var(--shadow); - overflow: hidden; -} -.figure img { - border: 1px solid var(--rule); border-radius: var(--radius); - box-shadow: var(--shadow); width: 100%; -} -.figure figcaption { - font-size: 13.5px; color: var(--muted); line-height: 1.5; - margin-top: 10px; max-width: 80ch; - padding-left: 14px; border-left: 2px solid var(--rule); -} -/* tier tag above each figure */ -.fig-tier { - display: inline-flex; align-items: center; gap: 7px; - font-family: var(--mono); font-size: 10.5px; font-weight: 600; - letter-spacing: 1px; text-transform: uppercase; - color: var(--muted); margin: 4px 0 8px; -} -.fig-tier::before { - content: ""; width: 8px; height: 8px; border-radius: 2px; background: var(--brass); -} -.fig-tier.tech::before { background: var(--oxblood); } -.fig-tier.friendly::before { background: var(--forest); } - -/* two-up figure row */ -.fig-grid { - display: grid; grid-template-columns: 1fr 1fr; gap: 22px; align-items: start; -} -@media (max-width: 820px) { .fig-grid { grid-template-columns: 1fr; } } - -/* ============================================================================= - GRADE PILLS / TABLE - ========================================================================== */ -table.grades { - width: 100%; border-collapse: collapse; margin: 22px 0 10px; - font-size: 15px; background: var(--card); border-radius: var(--radius); - overflow: hidden; box-shadow: var(--shadow); border: 1px solid var(--rule); -} -table.grades th, table.grades td { - text-align: left; padding: 12px 14px; border-bottom: 1px solid var(--rule); - vertical-align: middle; -} -table.grades thead th { - background: var(--card-2); font-family: var(--mono); font-size: 11.5px; - letter-spacing: 0.6px; text-transform: uppercase; color: var(--muted); -} -table.grades tr:last-child td { border-bottom: 0; } -.gp { - display: inline-flex; align-items: center; justify-content: center; - width: 30px; height: 30px; border-radius: 6px; - font-family: var(--mono); font-weight: 600; font-size: 15px; - border: 2px solid; transform: rotate(-2deg); -} -.gp.a, .gp.b { color: var(--forest-dk); border-color: var(--forest); background: var(--fill-forest); } -.gp.c, .gp.d { color: var(--oxblood-dk); border-color: var(--oxblood); background: var(--fill-ox); } -.yes { color: var(--forest-dk); font-weight: 600; } -.no { color: var(--oxblood-dk); font-weight: 600; } - -/* before/after comparison table */ -table.compare { - width: 100%; border-collapse: collapse; margin: 22px 0 10px; - font-size: 15px; background: var(--card); border-radius: var(--radius); - overflow: hidden; box-shadow: var(--shadow); border: 1px solid var(--rule); -} -table.compare th, table.compare td { - padding: 12px 14px; border-bottom: 1px solid var(--rule); text-align: left; - vertical-align: top; -} -table.compare thead th { background: var(--card-2); font-family: var(--display); font-size: 16px; } -table.compare thead th:nth-child(2) { color: var(--oxblood); } -table.compare thead th:nth-child(3) { color: var(--forest-dk); } -table.compare td:first-child { font-weight: 600; color: var(--ink); width: 26%; } -table.compare tr:last-child td { border-bottom: 0; } -table.compare td:nth-child(2) { color: var(--ink-2); } -table.compare td:nth-child(3) { background: var(--fill-forest); } - -/* ============================================================================= - USE-CASE GALLERY (nested collapsibles) - ========================================================================== */ -.gallery { margin: 22px 0 6px; } -.uc { - background: var(--paper); border: 1px solid var(--rule); - border-left: 3px solid var(--brass); - border-radius: var(--radius-s); margin: 0 0 14px; overflow: hidden; -} -.uc[open] { border-left-color: var(--oxblood); } -.uc > summary { - display: flex; align-items: center; gap: 13px; - padding: 14px 16px; cursor: pointer; list-style: none; user-select: none; -} -.uc > summary::-webkit-details-marker { display: none; } -.uc > summary:hover { background: var(--card-2); } -.uc .uc-num { - font-family: var(--mono); font-weight: 600; font-size: 13px; - color: var(--on-stamp); background: var(--brass); - width: 26px; height: 26px; border-radius: 5px; - display: inline-flex; align-items: center; justify-content: center; - flex: 0 0 auto; -} -.uc[open] .uc-num { background: var(--oxblood); } -.uc .uc-title { font-family: var(--display); font-weight: 600; font-size: 17.5px; color: var(--ink); flex: 1; line-height: 1.25; } -.uc .uc-chev { font-family: var(--display); font-size: 22px; color: var(--faint); transition: transform 0.2s var(--ease); transform: rotate(90deg); } -.uc[open] .uc-chev { transform: rotate(-90deg); color: var(--oxblood); } -.uc .uc-body { padding: 2px 16px 20px; border-top: 1px dashed var(--rule); } -.uc .uc-body p { margin: 14px 0; } -.uc .uc-meta { - display: grid; gap: 10px; margin: 14px 0; -} -.uc .uc-meta .row { - display: grid; grid-template-columns: 110px 1fr; gap: 10px; align-items: start; - font-size: 15px; -} -.uc .uc-meta .row .k { - font-family: var(--mono); font-size: 11px; font-weight: 600; - letter-spacing: 0.6px; text-transform: uppercase; color: var(--oxblood); - padding-top: 2px; -} -@media (max-width: 560px) { .uc .uc-meta .row { grid-template-columns: 1fr; gap: 2px; } } - -/* command block */ -.cmd { - font-family: var(--mono); font-size: 13.5px; line-height: 1.7; - background: #efe6d2; color: var(--ink); - border: 1px solid var(--rule); border-radius: var(--radius-s); - padding: 14px 16px; margin: 14px 0; overflow-x: auto; - box-shadow: var(--emboss); -} -.cmd .c { color: var(--muted); } /* comment */ -.cmd .p { color: var(--oxblood); } /* prompt sigil */ -.cmd .k { color: var(--forest-dk); font-weight: 600; } /* keyword */ - -/* ============================================================================= - FILE-TREE (drop-in §) — cognitum style, annotated - ========================================================================== */ -.filetree { - font-family: var(--mono); font-size: 13.5px; line-height: 1.9; - background: var(--card); border: 1px solid var(--rule); - border-radius: var(--radius); padding: 18px 18px; margin: 20px 0 10px; - box-shadow: var(--shadow); overflow-x: auto; -} -.filetree .ft-row { display: grid; grid-template-columns: minmax(230px, auto) 1fr; gap: 16px; align-items: baseline; padding: 1px 0; } -.filetree .ft-tree { color: var(--ink); white-space: pre; } -.filetree .ft-name { color: var(--oxblood-dk); font-weight: 600; } -.filetree .ft-name.human { color: var(--forest-dk); } -.filetree .ft-desc { color: var(--ink-2); font-family: var(--sans); font-size: 13.5px; } -.filetree .ft-head { color: var(--muted); font-weight: 600; padding: 8px 0 2px; } -.filetree .ft-head.first { padding-top: 2px; } -/* HIGHLIGHT the NotebookLM studio media so a downloader cannot miss it (D13/V). */ -.filetree .ft-badge { - font-family: var(--sans); font-size: 11px; font-weight: 700; letter-spacing: .04em; - text-transform: uppercase; color: var(--on-stamp); background: var(--forest); - border-radius: 4px; padding: 1px 7px; margin-left: 6px; vertical-align: middle; -} -.filetree .ft-row.ft-hi { - background: var(--fill-forest); border-left: 3px solid var(--forest); - border-radius: 4px; margin: 2px 0; padding: 3px 6px 3px 4px; -} -.filetree .ft-row.ft-hi .ft-name.human { color: var(--forest-dk); font-weight: 700; } -.filetree .ft-row.ft-hi .ft-desc { color: var(--ink); } -@media (max-width: 640px) { .filetree .ft-row { grid-template-columns: 1fr; gap: 1px; } .filetree .ft-desc { padding-bottom: 8px; } } - -/* steps */ -.steps { counter-reset: step; list-style: none; padding: 0; margin: 22px 0 10px; display: grid; gap: 12px; } -.steps li { - counter-increment: step; position: relative; - background: var(--card); border: 1px solid var(--rule); - border-radius: var(--radius-s); padding: 14px 16px 14px 56px; -} -.steps li::before { - content: counter(step); position: absolute; left: 14px; top: 13px; - width: 28px; height: 28px; border-radius: 6px; - background: var(--oxblood); color: var(--on-stamp); - font-family: var(--mono); font-weight: 600; font-size: 14px; - display: inline-flex; align-items: center; justify-content: center; -} -.steps li b { color: var(--ink); } -.steps li code { font-family: var(--mono); font-size: 0.88em; background: var(--paper); border: 1px solid var(--rule); padding: 1px 6px; border-radius: 5px; } - -/* dropzone */ -.dz { - margin: 22px 0 6px; padding: 26px; text-align: center; - border: 2px dashed var(--brass); border-radius: var(--radius); - background: var(--fill-forest); cursor: pointer; - transition: border-color 0.18s var(--ease), background 0.18s var(--ease), transform 0.18s var(--ease); -} -.dz:hover, .dz.is-dragover { border-color: var(--oxblood); background: var(--fill-ox); transform: translateY(-2px); } -.dz .dz-title { font-family: var(--display); font-weight: 600; font-size: 19px; color: var(--ink); margin: 0 0 6px; } -.dz .dz-sub { font-size: 14.5px; color: var(--muted); margin: 0; } -.dz .dz-status { font-family: var(--mono); font-size: 12px; color: var(--oxblood); margin-top: 10px; min-height: 1em; } - -/* ============================================================================= - FOOTER - ========================================================================== */ -.foot { - margin-top: 40px; border-top: 2px solid var(--oxblood); - background: var(--card-2); -} -.foot .wrap { padding: 30px 0 40px; display: grid; gap: 14px; } -.foot .credit { font-size: 15px; color: var(--ink-2); max-width: 70ch; } -.foot .credit b { color: var(--ink); } -.foot .fine { font-family: var(--mono); font-size: 12px; color: var(--muted); } -.foot a { border-bottom-style: dotted; } - -/* utilities */ -.kicker { - display: inline-block; font-family: var(--mono); font-size: 11px; font-weight: 600; - letter-spacing: 1px; text-transform: uppercase; color: var(--oxblood); - background: var(--fill-ox); border: 1px solid rgba(158,43,37,0.25); - padding: 3px 9px; border-radius: 5px; margin: 0 0 10px; -} -.visually-hidden { - position: absolute !important; width: 1px; height: 1px; padding: 0; margin: -1px; - overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; -} - -@media (prefers-reduced-motion: reduce) { - * { scroll-behavior: auto !important; transition: none !important; } -} - -/* ===================== STUDIO SECTION (NotebookLM audio + report) ===================== */ -.studio-section > summary .num { font-size: 22px; } -.studio-card { - background: var(--card); border: 1px solid var(--rule); border-left: 4px solid var(--forest); - border-radius: var(--radius); padding: 18px 18px 16px; margin: 18px 0 6px; box-shadow: var(--shadow); -} -.studio-row { display: flex; align-items: center; gap: 14px; padding: 8px 0; } -.studio-ico { font-size: 26px; line-height: 1; flex: 0 0 auto; } -.studio-meta { flex: 1 1 auto; min-width: 0; } -.studio-t { margin: 0 0 2px; font-family: var(--display); font-size: 17px; font-weight: 700; color: var(--ink); } -.studio-d { margin: 0; font-size: 14px; color: var(--ink-2); } -.studio-audio { width: 100%; margin: 6px 0 10px; } -.studio-cta { flex: 0 0 auto; white-space: nowrap; } -@media (max-width: 560px) { .studio-row { flex-wrap: wrap; } .studio-cta { width: 100%; text-align: center; } } - -/* PUBLIC NOTEBOOK callout — the hero link of the studio (open the whole NotebookLM). */ -.nb-open { - display: flex; align-items: center; gap: 16px; flex-wrap: wrap; - margin: 6px 0 20px; padding: 18px 20px; - background: var(--fill-ox); border: 1px solid rgba(158,43,37,0.28); - border-left: 5px solid var(--oxblood); border-radius: var(--radius); - box-shadow: var(--shadow); -} -.nb-open .nb-ico { font-size: 30px; line-height: 1; flex: 0 0 auto; } -.nb-open .nb-meta { flex: 1 1 260px; min-width: 0; } -.nb-open .nb-t { margin: 0 0 3px; font-family: var(--display); font-size: 19px; font-weight: 700; color: var(--ink); } -.nb-open .nb-d { margin: 0; font-size: 14px; color: var(--ink-2); } -.nb-open .nb-cta { - flex: 0 0 auto; white-space: nowrap; - background: var(--oxblood); color: var(--on-stamp); - border: 1px solid var(--oxblood-dk); border-radius: var(--radius-s); - padding: 11px 18px; font-family: var(--display); font-weight: 700; font-size: 15.5px; - text-decoration: none; box-shadow: var(--shadow); - transition: background 0.16s var(--ease), transform 0.16s var(--ease); -} -.nb-open .nb-cta:hover { background: var(--oxblood-dk); transform: translateY(-2px); } -@media (max-width: 560px) { .nb-open .nb-cta { width: 100%; text-align: center; } } - -/* MEDIA GRID — video / slides / infographic cards, casefile look. */ -.studio-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin: 6px 0 4px; } -@media (max-width: 720px) { .studio-grid { grid-template-columns: 1fr; } } -.studio-media { - background: var(--card); border: 1px solid var(--rule); border-left: 4px solid var(--forest); - border-radius: var(--radius); padding: 14px 16px 16px; box-shadow: var(--shadow); - display: flex; flex-direction: column; -} -.studio-media .sm-head { display: flex; align-items: baseline; gap: 8px; margin: 0 0 8px; } -.studio-media .sm-ico { font-size: 20px; } -.studio-media .sm-t { margin: 0; font-family: var(--display); font-size: 16px; font-weight: 700; color: var(--ink); } -.studio-media .sm-d { margin: 0 0 12px; font-size: 13.5px; color: var(--ink-2); } -.studio-media video, -.studio-media .sm-frame img { - width: 100%; border-radius: var(--radius-s); border: 1px solid var(--rule); - background: var(--paper-2); display: block; -} -.studio-media .sm-frame { margin: 0 0 12px; } -.studio-media .sm-frame img { transition: transform 0.18s var(--ease); } -.studio-media .sm-frame a:hover img { transform: scale(1.012); } -.studio-media .sm-actions { margin-top: auto; display: flex; gap: 10px; flex-wrap: wrap; } -.studio-media .sm-actions .cta { flex: 1 1 auto; text-align: center; white-space: nowrap; } -.studio-media .sm-note { margin: 8px 0 0; font-family: var(--mono); font-size: 11.5px; color: var(--muted); } -.studio-media.span2 { grid-column: 1 / -1; } diff --git a/ruv-explainer-ruvn/vercel.json b/ruv-explainer-ruvn/vercel.json deleted file mode 100644 index 72d1881..0000000 --- a/ruv-explainer-ruvn/vercel.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "$schema": "https://openapi.vercel.sh/vercel.json", - "cleanUrls": true, - "trailingSlash": false, - "headers": [ - { - "source": "/assets/(.*)", - "headers": [ - { "key": "Cache-Control", "value": "public, max-age=31536000, immutable" } - ] - }, - { - "source": "/(.*)\\.svg", - "headers": [ - { "key": "Content-Type", "value": "image/svg+xml" } - ] - }, - { - "source": "/(.*)\\.m4a", - "headers": [ - { "key": "Content-Type", "value": "audio/mp4" } - ] - }, - { - "source": "/(.*)\\.mp4", - "headers": [ - { "key": "Content-Type", "value": "video/mp4" } - ] - }, - { - "source": "/downloads/(.*)\\.zip", - "headers": [ - { "key": "Content-Type", "value": "application/zip" }, - { "key": "Cache-Control", "value": "public, max-age=300" } - ] - } - ] -} diff --git a/scripts/gen-tools-contract.mjs b/scripts/gen-tools-contract.mjs new file mode 100644 index 0000000..90be06f --- /dev/null +++ b/scripts/gen-tools-contract.mjs @@ -0,0 +1,56 @@ +#!/usr/bin/env node +// gen-tools-contract.mjs — regenerate skills/explainmyrepo/TOOLS-CONTRACT.md from the leading `//` header block of every tools/*.mjs. +// +// Usage: node scripts/gen-tools-contract.mjs write the file +// node scripts/gen-tools-contract.mjs --check exit 1 if the committed file differs +// Deterministic: tools sorted by file name, no date stamp. tests/review-p8-tools-contract.test.mjs runs generate() +// in memory and compares it with the committed file, so a tool header edited without regenerating fails CI. + +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +export const OUT_REL = 'skills/explainmyrepo/TOOLS-CONTRACT.md'; + +const INTRO = `# TOOLS CONTRACT — the pipeline's toolbox, from each tool's own header + +GENERATED by \`node scripts/gen-tools-contract.mjs\` from the leading \`//\` comment block of every tools/*.mjs. Do not edit by hand: edit the tool's header, then regenerate. A test (tests/review-p8-tools-contract.test.mjs) fails when this file and the headers disagree. Read THIS instead of tool source; open source only if this is ambiguous. For which station runs which tool on which door, see src/stations.mjs and tools/CONTRACT.md. +`; + +/** The leading `//` block of a source file (after an optional shebang), with the comment markers removed. */ +export function headerOf(source) { + const lines = source.split('\n'); + let i = 0; + if (lines[0] && lines[0].startsWith('#!')) i = 1; + const out = []; + for (; i < lines.length && lines[i].startsWith('//'); i++) out.push(lines[i].replace(/^\/\/ ?/, '').replace(/\s+$/, '')); + while (out.length && out[out.length - 1] === '') out.pop(); + return out.join('\n'); +} + +export function toolFiles(root = ROOT) { + return fs.readdirSync(path.join(root, 'tools')).filter((f) => f.endsWith('.mjs')).sort(); +} + +export function generate(root = ROOT) { + const parts = [INTRO]; + for (const f of toolFiles(root)) { + const header = headerOf(fs.readFileSync(path.join(root, 'tools', f), 'utf8')); + if (!header) throw new Error(`tools/${f} has no leading // header block`); + parts.push(`## tools/${f}\n${header}\n`); + } + return parts.join('\n'); +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const out = path.join(ROOT, OUT_REL); + const next = generate(); + if (process.argv.includes('--check')) { + const cur = fs.existsSync(out) ? fs.readFileSync(out, 'utf8') : ''; + if (cur !== next) { console.error(`${OUT_REL} is out of date; run: node scripts/gen-tools-contract.mjs`); process.exit(1); } + } else { + fs.writeFileSync(out, next); + console.error(`wrote ${OUT_REL} (${next.split('\n').length} lines, ${toolFiles().length} tools)`); + } +} diff --git a/skills/explainmyrepo/SKILL.md b/skills/explainmyrepo/SKILL.md index 29c4be6..10d4201 100644 --- a/skills/explainmyrepo/SKILL.md +++ b/skills/explainmyrepo/SKILL.md @@ -9,8 +9,9 @@ description: >- deeply via a real RVF knowledge base, conceives a one-of-a-kind visual metaphor, authors the content along a comprehension arc grounded in the KB, generates feeling (raster) + structure (SVG) imagery, assembles one page, - grades it on real pixels to the exemplar-anchored bar (mean >= 90, min >= 85, six operator-YES) with a surgical refine - loop, ships a downloadable AI knowledge pack, and deploys to a live URL. Do + grades it on real pixels against the exemplar bar (mean >= 90, min >= 85, six operator-YES) with a surgical refine + loop (a below-bar page still ships, with its weakest axis disclosed), ships a downloadable AI knowledge pack, and + deploys to a live URL. Do NOT use for generic "build me a website" requests with no repo to explain. --- @@ -29,10 +30,12 @@ email. You never let a tool think, and a tool never decides "good enough." > bar, it is **not done and not acceptable.** Every station below exists to serve > that one sentence. -Authoritative sources (read them if anything here is ambiguous): -`docs/adr/0005-skill-based-explainer-recipe.md` (the decision), -`tools/CONTRACT.md` (the tool law), `docs/ddd/explainmyrepo-recipe-domain.md` -(the domain model). Where they conflict, **ADR-0005 governs.** +Authoritative sources (read them if anything here is ambiguous): `tools/CONTRACT.md` (the tool law and the +slot shapes), `skills/explainmyrepo/TOOLS-CONTRACT.md` (every tool's own header: flags, env, gotchas), +`src/stations.mjs` (the station order and which door runs what), and the newest ADRs 0011-0016 in `docs/adr/`. +`docs/adr/0005-skill-based-explainer-recipe.md` is the founding record and +`docs/ddd/explainmyrepo-recipe-domain.md` the historical domain model; where they conflict with the code or a newer ADR, +**the code and the newer ADR govern.** --- @@ -50,12 +53,13 @@ Authoritative sources (read them if anything here is ambiguous): writes a placeholder, default asset, stub, or `TODO` to limp past a failure. You read the **exit code first**, then the JSON. A failed cue stops the build with an honest reason — never a stack trace, never a silent green. -4. **Never ship below the exemplar bar (INV-05).** "Done" = on BOTH mobile (390px) and desktop - (1440px) the scorecard's **mean ≥ 90 AND min axis ≥ 85 AND all six operator questions YES** - (anchored to the owner's own example sites — a literal "95 on every axis" is unreachable by an - honest grader; a build that clears this bar is **reported as a normalized 95**). The two pre-ship - eyes (vision model + you) agree, the page is live (200 unauthenticated), and the AI pack ships. - Below the bar: **refine, or flag honestly.** Never ship slop and call it done. +4. **Aim for the exemplar bar, and never lie about where you landed (INV-05).** The target the refine + loop climbs to is, on BOTH mobile (390px) and desktop (1440px), **mean ≥ 90 AND min axis ≥ 85 AND all + six operator questions YES** (anchored to the owner's own example sites — a literal "95 on every axis" + is unreachable by an honest grader; every page reports its honest mean). The + page must be live (200 unauthenticated) and the AI pack must ship. **Delivery is gated only on + integrity (ADR-0011), not on the score:** a page below the bar still ships, with its weakest axis + named to the requester. Refine, or flag honestly. Never ship slop and call it done. 5. **The submitted repo IS the identity (INV-21).** You build an explainer of the EXACT repo the human submitted — nothing else, ever. If it cannot be cloned (private, deleted, typo) or its clone is broken, STOP with an honest, actionable reason ("we @@ -97,26 +101,31 @@ After every tool call: **check the exit code (0 ⇔ ok), then parse stdout.** If forward on a failed cue. Secrets (GitHub token, OpenAI key, deploy token, SMTP creds) come from the **environment**, never from `build.json`. -### Tool roster (14 pure tools) - -| Station | Tool | Fills slot | -|---|---|---| -| 0–1 | `clone-repo` | `repo` (+ `buildId`) | -| 1 | `build-kb` | `understanding`, `kb` | -| 4 | `generate-image` | `visuals.hero` / `visuals.sections[]` (one rung per call) | -| 4 | `make-diagrams` | `visuals.architectureDiagram` / `.flowDiagram` / `.bigIdeaDiagram` / `.insightDiagram` | -| 5 | `make-favicon` | `brand.favicon` | -| 5 | `make-social-card` | `brand.socialCard` | -| 6 | `assemble-page` | `page` (+ SEO/social ``, sitemap/robots/llms.txt) | -| 6 | `make-pack` | `pack` | -| 7 | `quality-grade` | `quality` (two scorecards) | -| 8 | `deploy` | `publish.liveUrl` / `.http200` | -| 8 | `publish-repo` | `publish.explainerRepoUrl` / `.ownerInvited` | -| 8 | `repo-seo` | `publish.repoTopics` / `.repoDescription` / `.sourceRepoSeoSuggested` | -| 8b | `readme-enhance` | `readmePr` (optional, PR-only) | -| 9 | `notify` | `notify` | - -`concept` (Station 2) and `content` (Station 3) have **no tool** — you fill them +### Tool roster + +The station order, and which door runs each station, is `src/stations.mjs`. **You are the HOSTED door**: +the table below is exactly the stations of that file whose doors include `hosted`, in the order you meet them. +The harness, not you, does the clone, the concept tournament, the notify email and the advisory claims check. +The stations that run on the local door only (`make-ask`, `publish-repo`, `repo-seo`, `readme-enhance`, +`make-overview` and its `redeploy` / `republish`) are not yours: never run them. + +| Station | Tool | Fills slot | Who runs it | +|---|---|---|---| +| 0–1 | `tools/clone-repo.mjs` | `repo` (+ `buildId`) | the harness already did it for you | +| 1 | `tools/build-kb.mjs` | `understanding`, `kb` | you | +| 2 | `tools/concept-tournament.mjs` | `concept` (seeds it) | the harness, BEFORE you start; advisory | +| 3 | `tools/check-claims.mjs` | `claims` | the harness, AFTER you finish; advisory | +| 4 | `tools/generate-image.mjs` | `visuals.hero` / `visuals.sections[]` (one call, all rungs) | you | +| 4 | `tools/make-favicon.mjs` | `brand.favicon` | you | +| 4 | `tools/make-social-card.mjs` | `brand.socialCard` (required; a missing or unreadable card stops the build) | you | +| 4 | `tools/make-diagrams.mjs` | `visuals.architectureDiagram` / `.flowDiagram` / `.bigIdeaDiagram` / `.insightDiagram` / `.heroAnim` | you | +| 6 | `tools/assemble-page.mjs` | `page` (+ SEO/social ``, sitemap/robots/llms.txt) | you | +| 6 | `tools/make-pack.mjs` | `pack` | you | +| 7 | `tools/quality-grade.mjs` | `quality` (two scorecards) | you | +| 8 | `tools/deploy.mjs` | `publish.liveUrl` / `.http200` and the below-bar disclosure | you | +| 9 | `tools/notify.mjs` | `notify` | the runner sends it, not you | + +`concept` (Station 2, when no tournament ran) and `content` (Station 3) have **no tool** — you fill them directly. So does the **primer** (Station 1). That is the judgment that is yours. The KB engine has direct CLIs you call yourself for **reading + grounding** (not @@ -143,11 +152,11 @@ tools — they are how the brain thinks): `node kb/ask-kb.mjs "question" ## The stations (run them in order; each cue fails loud) -Critical path: **S1 → S2 → S3 → S4(slowest visual) → S6 → S7(may loop) → S8 → S9.** +Critical path: **S1 → S2 → S3 → S4(slowest visual) → S6 → S7(may loop) → S8.** Parallelize off-path (see "Parallelism" at the end): raster rungs fire together; -the SVGs are authored during S3; favicon + social card start the moment the hero -returns; the AI pack builds as soon as S1's KB exists; the README PR (S8b) is -optional and quarantined. +the diagram rows are authored during S3; favicon + social card start the moment the hero +returns; the AI pack builds as soon as S1's KB exists. Optional, local-door-only extras +(README outreach, the video overview) never sit on the path. ### Station 0 — VALIDATE - **Do:** Confirm the repo URL is reachable (supports private + the owner's own @@ -159,12 +168,12 @@ optional and quarantined. ### Station 1 — UNDERSTAND (read the repo deeply; this is where grounding is earned) 1. **Clone** (the `clone-repo` call above leaves the working tree at `/repo/`). -2. **Register the target** in `kb/kb.config.mjs` with an **explicit `embed` block** - (`Xenova/bge-small-en-v1.5`, 384-dim) and its `repoDir` pointing at the clone. - This is required: on the bare MiniLM default, `build-kb.mjs` writes - `-kb.small.rvf`, which the Station-6 pack builder globs for `-kb.rvf` - and **cannot find**. The `build-kb` tool **fails loud** if the target is - unregistered or writes a `.small.rvf`. +2. **Register the target** in `kb/kb.config.mjs` (`kb:register` in the station table) with an + **`embed` block** (model + dimension; registered targets use `Xenova/bge-small-en-v1.5`, 384-dim) and its + `repoDir` pointing at the clone. `kb/build-kb.mjs` **refuses a target with no `embed` block** (there is no + default embedder), writes `-kb.rvf`, and records the model it used in `-kb.rvf.embed.json`; + that sidecar, not this document, is what governs queries and what `kb/index-primer.mjs` checks (it throws + if the sidecar is missing or names a different model than `ids.json`). 3. **Build the KB + structured indexes:** `node tools/build-kb.mjs `. This runs the real engine: `kb/build-kb.mjs` (the RVF store, local embeddings, self-reconciling) **plus** `extract-symbols.mjs`, `dep-graph.mjs`, @@ -181,7 +190,7 @@ optional and quarantined. `kb/stores//-primer.md` — a natural-language top-down orientation (what it is / its concepts / how each works / maturity / where the docs are / how to use it end-to-end). This is a **hard prerequisite of Station 6**: - `kb/make-dropin.mjs` line 79 `must()`s it and throws `missing: -primer.md` + `tools/make-pack.mjs` fails with `missing required input: …-primer.md` if absent. Never let a tool fake it. 6. **Index the authored primer:** `node kb/index-primer.mjs ` (a write/index step — it consumes the primer you wrote; it does not create it). @@ -210,51 +219,33 @@ failure). The brief, grounded in what the KB revealed: - **`metaphor`** — a visual metaphor that genuinely fits this repo (PhotonLayer → prism; ruvn → evidence dossier; ruqu → Bloch-sphere orb). A stranger should nod. -- **`palette`** — colours that fit the metaphor. These are the **design-system - expression knobs**; `assemble-page` compiles them into the page's per-repo theme +- **`palette`** — colours that fit the metaphor, as an **object of knobs** (`{ "accent": "#…", "bg": "#…", … }`), + never prose: `assemble-page` reads it as an object and **fails loud** otherwise. These are the + **design-system expression knobs**; `assemble-page` compiles them into the page's per-repo theme layer over the shared `assets/design-system/design-system.css` skeleton. This — the palette + type knobs you set here — **is** the page's "theme.css": the invariants (responsive, accessible, the required sections) live in the shared - skeleton; the **expression** is what you set in `concept`. -- **`typePersonality`** — a display + body + mono pairing that carries the - metaphor's voice. -- **`layoutRhythm`** — the ordered section archetypes (the page's cadence). + skeleton; the **expression** is what you set in `concept`. (The concept tournament already emits + this object shape, so a tournament winner renders as is.) +- **`typePersonality`** — an object (`{ "display", "sans", "mono", … }`): a display + body + mono pairing + that carries the metaphor's voice. - **`heroConcept`** — the single emotional opening-image idea. - - **THE HERO PROMPT MUST *BE* THE METAPHOR** (2026-07-12, learned the hard way). When you author - `visuals.hero.prompt` in S4, it renders **`concept.metaphor`, literally and concretely** — the - metaphor is not decoration you invent and then discard. ternlight authored a genuinely good one - ("a maritime signal lamp flashing exactly three states — −1, 0, +1 — across dark water") and then - shipped a hero of *generic glowing dots in space*: the stock embedding-space cliché, connected to - nothing. The reader's verdict was exact — **"I don't know what the lights are meant to be"** — and - they were right: the lights meant nothing, because the image had abandoned the idea. If a stranger - cannot look at the hero and get the ONE idea, the hero has failed, however pretty it is. Never - reach for a generic "abstract glowing network / constellation / neural mesh" — that is the tell - that you stopped thinking. + - **THE HERO PROMPT MUST *BE* THE METAPHOR.** `visuals.hero.prompt` renders `concept.metaphor` literally and + concretely; a generic glowing network or constellation is the tell that you stopped thinking (ADR-0008). - **`copyVoice`** — the tone/register for all authored text. - **`tagline`** — the one line baked into the social card + `og:description`. -- **THREE DIRECTIONS, THEN A VERDICT (2026-07-13 — anti-sameness is a design step, not a hope).** - A single concept pass converges on the house style (dark editorial, cream serif, warm inserts — - the wall proves it). So author **THREE genuinely divergent art directions** before choosing: - different metaphor FAMILY (mechanical / spatial / document / organic / optical…), different - palette temperature, different layout rhythm. For each, one line of "why it fits THIS repo." - Then judge for repo-fit and commit to ONE. Two hard rules on the verdict: - 1. **The house look is never the default.** Dark-editorial-with-serif may WIN, but only by - argument from this repo's own domain — never because it's what the last build did. - 2. **NEVER open another build's `build.json` or page for creative direction.** The exemplar - bar (INV-05) is a QUALITY bar, not a style guide — imitating a prior build's concept is how - the wall became one page in seven costumes. Record the two rejected directions (one line - each) in `concept.rejectedDirections` so the choice is auditable. +- **THREE DIRECTIONS, THEN A VERDICT.** Author three genuinely divergent art directions (different metaphor + family, palette temperature and layout rhythm, one line each on why it fits THIS repo), then commit to ONE. + The house look never wins by default, and never open another build's `build.json` or page for direction + (the exemplar bar is a quality bar, not a style guide). Record the two rejected directions in + `concept.rejectedDirections`. - **Cue:** the brief is **specific to THIS repo** and the **metaphor genuinely fits**. A generic brief is a failure **here**, not at the gate. ### Station 2b — THE STORY SPEC (do this BEFORE authoring a single section) -**Write the thesis and the arc FIRST, then write sections to serve them.** The failure this -prevents (2026-07-12, cost a whole night): the page was authored section-by-section from repo -facts, so it opened INSIDE THE MACHINE — multiplication counts, tokenizers, WASM — for a reader -who has never heard of any of it. Three independent judges, shown three competing story angles, -were unanimous on the cause: **"you cannot rescue an insider-ordered story with better sentences."** -No amount of rewriting fixed it, because the defect was the ORDER, not the words. +**Write the thesis and the arc FIRST, then write sections to serve them.** An insider-ordered story cannot be +rescued by better sentences (ADR-0006). Write into `concept.story` before Station 3: - **`thesis`** — ONE plain sentence a stranger understands, that the whole page proves. Zero jargon. @@ -287,9 +278,7 @@ forms. **Never show a low-level detail before the high-level frame that makes it legible.** **THE COMPREHENSION LADDER (ADR-0006 v1.2.0 — altitude control).** The reader is a **curious -FIFTEEN-YEAR-OLD** (superseding "a smart developer from a different domain", 2026-09-17: the owner -scored two shipped pages 6.5/10 — *"it still feels like it's asking me to geek out versus bringing it -back to my level ... the whole point of this is to explain it like somebody is 15"*). They have never +FIFTEEN-YEAR-OLD** (ADR-0006 D8; this replaced "a smart developer from a different domain"). They have never built software. After rungs 1–4 they must be able to say, in their own words: what this is, what it would do FOR THEM, why the trick is clever, and roughly how it works. @@ -318,12 +307,9 @@ problem it kills. `howItWorks` may descend ONE technical level (terms still defi what the experience looks like. Grounding (INV-06) supplies the FACTS, not the VOCABULARY: translate insider terms; cite the passage, don't parrot its jargon. -**SHOW, THEN SAY (2026-07-13 — the reader's verdict on a text-heavy page: "their README is -better than this").** No section may run more than ~120 visible words before a visual, a code -block, a real artifact, or a structural element carries the next beat. When a mechanism takes -more words than that to explain, the words are describing a diagram you haven't drawn yet — -draw it, label it, and cut the prose to what the diagram can't say. The page must beat the -repo's own README on scannability or it has no reason to exist. +**SHOW, THEN SAY.** No section runs more than about 120 visible words before a visual, a code block, a real +artifact or a structural element carries the next beat; the page must beat the repo's own README on +scannability. Author all eight sections: @@ -341,9 +327,9 @@ Author all eight sections: **Grounding is non-negotiable (INV-06).** Every claim must be traceable to a KB passage retrieved via `node kb/ask-kb.mjs "…"`. Record `content.citations` as `{ claim, passageId }`. **No invented capabilities, no "lorem", no "TODO", no -placeholder text.** As you author `howItWorks`, the **ASCII for the architecture + -flow diagrams falls out naturally** — capture it now so S4 can convert it in -parallel. +placeholder text.** As you author `howItWorks`, capture the architecture and flow as +`visuals.architectureDiagram.rows` / `visuals.flowDiagram.rows` (and `bigIdeaDiagram` / `insightDiagram` +rows): short concept-card labels, never ASCII art. `make-diagrams` draws them in S4. - **Cue:** all arc questions answered, zero placeholder text, every claim traceable to a KB source. A4 specifically: the page explicitly answers **"how is this useful @@ -351,11 +337,8 @@ parallel. ### Station 4 — VISUALIZE (feeling = raster, structure = SVG) -- **THE IMAGE CONTRACT (INV-22, 2026-07-13 — every image must teach, or it must not exist.)** - Born from a real verdict on a shipped page: a warm, competent photo of a man pointing at a - laptop scored 91 at the gate and the owner correctly called it "generic drivel — what am I - supposed to take away from this?" The gate measured beauty; nobody measured payload. Rules, - in force for every raster on the page: +- **THE IMAGE CONTRACT (INV-22, ADR-0008 — every image must teach, or it must not exist).** Rules, in force + for every raster on the page: 1. **Every raster brief MUST carry a `takeaway:` line** — the one sentence a stranger should be able to say about THIS repo after looking at the finished image (not the caption — the pixels). No stateable takeaway → the image is decoration → do not generate it; give the @@ -364,11 +347,9 @@ parallel. DIFFERENT repo's page, it fails. A person at a laptop passes the swap test for every repo on earth — which is exactly why it is banned. 3. **BANNED imagery (the AI-slop list — these have all shipped and all read as slop).** - **NO ROOMS, NO PROPS, NO PEOPLE (ADR-0008 v1.1.0, 2026-09-17):** desks, offices, cafes, windows, + **NO ROOMS, NO PROPS, NO PEOPLE (ADR-0008 v1.1.0):** desks, offices, cafes, windows, plants, coffee cups, notebooks, pens, books, stray phones, sticky notes as set dressing, hands. - Two consecutive builds shipped a desk-and-plant "problem" scene that the grader capped at B5=55 - (*"a generic desk/plant/binder scene does not teach a discernible fact ... could ship unchanged on - many software or office-product pages"*). Compose from the SUBJECT ITSELF — the screens, artifacts + Compose from the SUBJECT ITSELF — the screens, artifacts and objects the repo is about — filling the frame. Also banned: person at a laptop/desk/screen · hands typing · generic office or cafe scenes · glowing abstract networks/particles · fake UI floating on a fake device · concerned-developer @@ -394,76 +375,52 @@ parallel. - **Raster rungs (emotional) — `generate-image`, ONE call, no rung argument:** the tool reads every declared rung (`visuals.hero` + `visuals.sections[]`) from `build.json` itself and generates all of them internally with bounded - concurrency (2026-07-10: firing multiple separate `generate-image` processes — - one per rung — is WRONG; the tool has no per-rung CLI argument, and doing this - produced redundant concurrent processes racing on the same output files, papered - over by shell-level `sleep`-polling. Call it once and let it finish). Covers the + concurrency (never one process per rung: there is no per-rung CLI argument). Covers the **hero (1536×1024)**, the **problem (1024×1024)**, and the **use-case scenario - (1024×1024)** at quality `xhigh` (2026-09-17: on Images 2.5 an `xhigh` hero measured - 28.1s, and was clearly sharper with legible on-screen text than `gpt-image-2` at `medium`; - see the QUALITY comment in `tools/generate-image.mjs`). Valid sizes: `1024×1024`, + (1024×1024)** at quality `xhigh` (see the QUALITY comment in `tools/generate-image.mjs`). Valid sizes: `1024×1024`, `1024×1536`, `1536×1024`, `auto` (the DALL·E-3 `1792×1024` is rejected — never use it). -- **STRUCTURAL RUNGS ARE BESPOKE, AUTHORED, ANIMATED SVG (INV-23, 2026-07-13 — rails on - truth, never on form).** The old path funneled every diagram through one renderer and the - owner's verdict on the result was exact: "four different versions of the same process map." - A vertical pill-stack is a LIST wearing a costume; an information shape must dictate its - form. New contract — YOU author each diagram as a standalone SVG file (same output paths: - `assets/big-idea.svg`, `assets/insight.svg`, `assets/architecture.svg`, `assets/flow.svg`): - 1. **Pick each diagram's ARCHETYPE from the menu and declare it** as `data-archetype` on the - root `` AND in `visuals..archetype`: `journey` (something travels and - transforms, left→right) · `containment` (boxes within boxes, layers) · `field` (a - population of many small things, a few highlighted) · `fan` (one radiating to many) · - `tree` (hierarchy) · `exchange` (two sides, a broker between). **No two diagrams on one - page may share an archetype** — the gate fails repetition. - **WIDTH-BUDGET EVERY LABEL (2026-07-15, autonomous-wealth-builder + agentic-kit hero - collisions — both from unmeasured text)**: before writing any , compute its budget — - monospace ≈ 0.62 × font-size per char, bold sans ≈ 0.55 — and verify the string fits its - container at the DESKTOP COLUMN scale (~45% of natural size), not just the full-size stage. - Two same-lane labels need ≥12px gap at column scale. Style micro-labels lowercase with - letter-spacing (caps-styled words like DISK/AGENT trip the INV-20 acronym gate). - 2. **The flow diagram must SHOW the thesis motion, not name stages.** For a repo whose trick - is spatial ("the key never leaves the vault"), the invariant must be VISIBLE: the request - dot travels the full journey while the key glyph stays pulsing inside the vault boundary. - If a stranger can't see the trick happen, it's a list of stages — rejected. - 3. **Animate INSIDE the SVG** (CSS keyframes / SMIL in a `