Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

Reposition around repo-native markdown graph: rewrite README + web landing page

anirudhkumar-nanonetsf9fd1f55b026
diff --git a/README.md b/README.md
index 149c3254..3a6ada64 100644
--- a/README.md
+++ b/README.md
@@ -1,420 +1,34 @@
# Context Graph Engine
-> Turn any docs into a structured **context graph** that AI agents read from before doing work — and contribute their learnings back to, so the graph gets smarter every time it's used.
+**31% fewer tool calls, 23% less cost, 17% lower latency.** That's what your agent gets from reading the repo's context graph before it starts working.
-Dumping docs into a vector store gives you a bag of chunks. It doesn't give you *structure* an agent can reason over, and there's no clean way for an agent to send back what it learned mid-task. The Context Graph Engine fixes both:
-
-- **Ingest** any docs → a graph of **entities** (concepts, systems, people, APIs…) connected by typed **relationships**, grounded in the original source passages.
-- **Read** the graph before a task → get a compact, structured context bundle (entities + relationships + supporting sources), ready to drop into a prompt.
-- **Contribute** learnings back → new facts are deduplicated and merged into existing knowledge; repeated observations **reinforce** confidence. The graph compounds over time.
-
-Access it four ways: a **web UI** (your team's knowledge as a living, citable graph — see below), a **library**, a **CLI**, or an **MCP server** that any agent (Claude Code, Cursor, …) can plug into.
-
-> **Benchmark:** on a real 344-file repo, giving the agent the graph up front cut tool calls **31%**, cost **23%**, and latency **17%** vs. exploring cold — same model, same tools, only difference is the graph bundle.
-
----
-
-## Install
-
-**One line, runs locally, no API keys required:**
-
-```bash
-curl -fsSL https://raw.githubusercontent.com/NanoNets/context-graph-engine/main/install.sh | sh
-```
-
-This puts `context-graph`, `context-graph-mcp`, and `context-graph-web` on your PATH. Requires git and Node ≥ 20.
-
-Or straight from GitHub with npm (also works as a library / dev dependency):
-
-```bash
-npm install -g github:NanoNets/context-graph-engine
-```
-
-## Try it in 60 seconds — the web UI
-
-```bash
-context-graph-web
-# → http://localhost:4680
-```
-
-Open the page, drop a folder of `.pdf` / `.md` / `.txt` files on the **“Add documents”** dropzone, and watch it become a knowledge graph. Then ask questions: answers come back with numbered citations, and every fact wears a **provenance receipt** — how many times it's been observed, how confident the graph is, and which sources say so. Use **“Add a fact”** to record something the docs don't capture, and watch the graph reinforce in real time.
-
-Everything runs on your machine (the server binds to localhost only). Set `OPENROUTER_API_KEY` to upgrade to LLM-written answers and cloud extraction; without it, retrieval and the graph stay fully local.
-
-Running it for your whole team? One `docker compose up` gives everyone the same graph at one URL — see [Team sharing](#team-sharing).
-
-### Or run everything at once — `context-graph serve`
-
-```bash
-context-graph serve
-# → web UI http://localhost:4680
-# MCP (HTTP) http://localhost:4680/mcp
-```
-
-One process runs the web UI, the MCP server (over HTTP), and the folder watcher on a single port over **one shared engine** — the supported way to run the whole thing at once, with no separate `watch` daemon to babysit. Open the UI, click **Connect a folder**, tick **Keep watching**, and that folder is ingested and watched live; it's remembered, so the next `serve` resumes it. Prefer the command line? Pass folders directly: `context-graph serve ./sample-docs`.
-
-### Runs locally by default — keys are optional
-
-Out of the box the engine needs **no accounts and no cloud calls**:
-
-- **Embeddings** run **in-process** via a small ONNX model (transformers.js) — downloaded and cached on first use.
-- **Extraction** uses a local **[Ollama](https://ollama.com)** model. Install Ollama and pull one:
- ```bash
- ollama pull llama3.2
- ```
-
-Want higher-quality cloud models instead? Set a key and the engine uses it **automatically** (local remains the fallback):
-
-```bash
-export OPENROUTER_API_KEY=sk-or-... # cloud extraction via OpenRouter
-export OPENAI_API_KEY=sk-... # cloud embeddings (optional; local otherwise)
-```
-
-Force local even when keys are present with `CONTEXT_GRAPH_LOCAL=1`.
-
----
-
-## Quickstart (library)
-
-```ts
-import { ContextGraphEngine } from "context-graph-engine";
-
-const engine = new ContextGraphEngine(); // persists to ./.context-graph/graph.db
-
-// 1. Ingest docs — builds the graph.
-await engine.ingest(myMarkdownDocs, { title: "Onboarding" });
-await engine.ingestFile("./docs/architecture.md");
-
-// 2. Read before doing work.
-const ctx = await engine.read("how does authentication work?");
-console.log(ctx.prompt); // inject this string into your agent
-console.log(ctx.nodes); // structured entities
-console.log(ctx.edges); // structured relationships
-
-// 3. Contribute what an agent learned.
-await engine.contribute(
- "The auth service rotates tokens every 15 minutes.",
- { agentId: "code-reviewer" },
-);
-```
-
-Run the full working demo (set `OPENROUTER_API_KEY`, or run a local Ollama):
-
-```bash
-npm run example
-```
-
----
-
-## CLI
-
-```bash
-# Ingest documents (Markdown, text, and PDFs — PDFs are parsed automatically)
-context-graph ingest ./docs/*.md ./handbook.pdf
-context-graph ingest-dir ./docs # a whole folder, recursively
-echo "some notes" | context-graph ingest-text --title "Notes"
-
-# Keep the graph evolving as a folder changes (see "Auto-watch")
-context-graph watch ./docs # register + watch; re-run with no args to resume
-context-graph ingest-dir ./docs --watch # ingest now, register for watching
-context-graph watch-status # list registered folders
-context-graph unwatch ./docs
-
-# Ingest a code repository — as summaries, not raw code (see "Code repositories")
-context-graph repo .
-
-# Ingest GitHub pull requests (title, description, review discussion) via the gh CLI
-context-graph ingest-prs --state merged --limit 50
-
-# Wire the graph into Claude Code (see "Claude Code hooks")
-context-graph install-hooks
-
-# Visualize the graph (interactive HTML; also --format json|mermaid)
-context-graph export --out graph.html && open graph.html
-
-# Read the graph
-context-graph query "how does billing retry failed charges?"
-context-graph query "billing" --json # full structured bundle
-
-# Contribute a learning
-context-graph contribute "Dunning worker retries 3x then marks past_due" --agent me
-
-# Inspect
-context-graph stats
-
-# Point at a specific graph file
-context-graph --db ./team-graph.db query "auth"
-
-# Team sharing — git mode (see "Team sharing" below)
-context-graph sync # pull teammates' graph.jsonl, re-merge, write it back
-context-graph push # write the graph to a committable graph.jsonl
-context-graph pull # import + re-merge a teammate's graph.jsonl
-```
-
----
-
-## MCP server
-
-Expose the graph to any MCP client so agents can `context_read` and `context_contribute` directly — the same "shared skill / durable memory" model as tools like ByteRover.
-
-Add to your Claude Code / MCP client config:
-
-```json
-{
- "mcpServers": {
- "context-graph": {
- "command": "context-graph-mcp",
- "env": {
- "CONTEXT_GRAPH_DB": "/absolute/path/to/team-graph.db"
- }
- }
- }
-}
-```
-
-Or, if you're running `context-graph serve`, point any MCP client at its HTTP endpoint instead of spawning a process:
-
-```json
-{
- "mcpServers": {
- "context-graph": { "type": "http", "url": "http://localhost:4680/mcp" }
- }
-}
-```
-
-When the server is exposed beyond localhost, add `"headers": { "Authorization": "Bearer <access-token>" }` — the same token the web UI prints.
-
-The API-key env vars are optional — add `OPENROUTER_API_KEY` (and optionally `OPENAI_API_KEY` for embeddings) only if you want cloud models instead of the local defaults.
-
-Tools exposed:
-
-| Tool | What it does |
-|------|--------------|
-| `context_read` | Read relevant context for a query before working |
-| `context_contribute` | Write a learning back into the shared graph |
-| `context_ingest` | Ingest a document (raw text) into the graph |
-| `context_ingest_file` | Ingest files from disk, including **PDFs** (parsed automatically) |
-| `context_ingest_dir` | Ingest a whole **directory** of docs (PDF/MD/TXT by default; pass `extensions` to widen), recursively |
-| `context_ingest_repo` | Ingest a **code repository** as per-file prose summaries (never raw code); incremental across runs |
-| `context_watch_dir` | Connect a folder for **auto-watching**: ingest it now and re-ingest files as they change (see "Auto-watch") |
-| `context_unwatch_dir` | Disconnect a watched folder (its knowledge stays in the graph) |
-| `context_watch_status` | List connected folders and the ingest queue |
-| `context_export` | Write the graph to an interactive **HTML** visualization |
-| `context_sync` | Team sharing (git mode): import + re-merge the shared `graph.jsonl`, then write it back |
-| `context_stats` | Report how much the graph currently holds |
-
-A natural agent workflow: **read context → do the task → contribute what you learned.**
-
----
-
-## Code repositories
-
-`context-graph repo <dir>` (or the `context_ingest_repo` MCP tool) ingests a codebase — but deliberately **never feeds raw source code to the entity extractor**. Running LLM extraction over thousands of code chunks is the most expensive way to compute what `grep` and tree-sitter give agents for free, and it fills the graph with noisy, duplicated symbol entities. (Every serious code-context system — aider, Cursor, Sourcegraph, Claude Code — derives code *structure* statically, and uses LLMs only for prose.)
-
-Instead, repo ingestion:
-
-1. Walks the repo for code files (`.ts`, `.py`, `.go`, … — `node_modules`/`dist`/etc. and files over 1 MB are skipped).
-2. Writes **one LLM prose summary per file**: purpose, key exports, dependencies, design decisions.
-3. Groups summaries into one document per top-level directory and ingests those through the normal pipeline — so the graph gains *module-level* entities ("the chunker is paragraph-aware", "the CLI requires the GitHub CLI for PR ingestion") with provenance, not ten thousand function names.
-
-It is **incremental**: summaries are cached by content hash in `repo-summaries.json` next to the db, so re-running after edits only re-summarizes changed files, and a changed file's module document *replaces* its predecessor rather than piling up stale duplicates. An unchanged repo re-ingests with **zero** LLM calls.
-
-The same replace-on-change behavior now applies to every file ingest: re-ingesting a modified doc replaces the old version instead of leaving both in the graph.
-
-For a ~30-file repo expect ~30 small summary calls on first run; the graph stays module-scale (a handful of documents) rather than chunk-soup-scale. Agents should still read raw code with their own tools — the graph holds what code can't say: intent, decisions, and gotchas.
-
-## Auto-watch — an evolving graph
-
-Connect a folder once and the graph tracks it: files you add or edit are re-ingested automatically, so the graph evolves with your notes instead of freezing at ingest time.
-
-```bash
-context-graph watch ~/notes # catch up on the folder, then watch it live
-# … later, in a fresh shell — no args needed, registered folders resume:
-context-graph watch
-```
-
-How it behaves:
-
-- **Debounced and cheap.** Saves are coalesced (~1.5 s quiet time per file) and unchanged files are skipped by content hash, so a daemon restart over a big unchanged folder costs zero LLM calls. Edited files *replace* their old document rather than piling up copies.
-- **Append-only.** Deleting a file never removes knowledge already learned from it — the graph is a memory, not a mirror. The deletion is logged and nothing else happens.
-- **Same rules as `ingest-dir`.** Default extensions `.pdf .md .markdown .txt` (override with `--ext`), dot-dirs / `node_modules` / files over 1 MB are ignored.
-- **Registered folders** live in `watched-dirs.json` next to the db (machine-local — it never rides the git-synced graph). `ingest-dir --watch` registers while ingesting; `watch-status` / `unwatch` manage the list.
-- **One watcher per db.** Run a single `watch` daemon per graph; MCP sessions and the web UI can read concurrently while it runs.
-
-Elsewhere: the `context_watch_dir` MCP tool connects a folder for the life of the agent session (set `CONTEXT_GRAPH_AUTOWATCH=1` on the MCP server to auto-resume registered folders), and `CONTEXT_GRAPH_WATCH=1` does the same for `context-graph-web` — the UI picks up growth live.
-
-## Claude Code hooks
-
-`context-graph install-hooks` wires the graph into Claude Code via `.claude/settings.json` (merges with what's already there):
-
-- **SessionStart** — every new session begins with relevant graph context (conventions, decisions, gotchas) auto-injected, plus a reminder that `context_contribute` exists.
-- **Stop** — when the agent finishes, it's nudged once to record any durable learnings from the session before ending. Pass `--no-stop` to skip this hook if you find the nudge too chatty.
-
-Both hooks stay silent when there's no graph yet, so installing them in a fresh project is harmless. Combined with the MCP server this closes the loop: sessions **start** with team knowledge and **end** by adding to it.
-
-## GitHub pull requests
-
-PR descriptions and review threads are where decisions actually get written down. `context-graph ingest-prs` pulls them into the graph via the [GitHub CLI](https://cli.github.com) (no extra auth needed if `gh` is logged in):
-
-```bash
-context-graph ingest-prs # merged PRs of the current repo (default 50)
-context-graph ingest-prs -R owner/name -n 100 --state all
-```
-
-Each PR becomes one document (title, description, review discussion) with source `pr:owner/name#123`. Re-runs are cheap: unchanged PRs are skipped by hash, edited ones replace their old version.
-
----
-
-## Team sharing
-
-A solo graph is one SQLite file. To share one across a team, pick a mode. All three keep the local-first default intact (team sync is **opt-in**).
-
-### The easy mode — one shared server (recommended)
-
-This is how nearly every self-hosted team tool works (Vaultwarden, Outline, BookStack): one instance, one URL, everyone's browser. No sync to configure, contributions land in the same graph instantly, and there is exactly one copy of the truth.
-
-```bash
-docker compose up -d
-cat ./data/share-link.txt # the share link, with access token
-```
-
-The graph persists to `./data/graph.db`. Ingest documents two ways: click **Choose a folder…** in the UI to upload a folder straight from your computer (works for remote teammates), or drop files into `./docs` on the server and ingest the mounted `/docs` path. When exposed beyond localhost the API requires an access token. It's generated once, saved to `./data/share-link.txt` (and printed to `docker compose logs`), and **stays stable across restarts** so shared links keep working. Pin your own with `CONTEXT_GRAPH_WEB_TOKEN`.
-
-No server to put it on? Run it on any machine and share it over [Tailscale](https://tailscale.com) without opening a port to the internet:
-
-```bash
-context-graph-web &
-tailscale serve localhost:4680 # private HTTPS URL, visible only to your tailnet
-```
-
-### Git mode — sync separate graphs, no server at all
-
-Prefer no shared server? Each teammate keeps their own local graph and git moves the knowledge around. This relies on the graph's **conflict-free merge**: observations are a grow-only counter and free-text fields are last-writer-wins, so re-importing the same facts never double-counts and merge order never changes the result.
-
-Commit the graph to your repo as a human-diffable file and let git move it around.
-
-```bash
-# You: capture the merged graph and commit it
-context-graph sync
-git add .context-graph/graph.jsonl && git commit -m "sync context graph" && git push
-
-# A teammate: get the latest and converge their local graph
-git pull
-context-graph sync
-```
-
-`sync` imports the committed `.context-graph/graph.jsonl`, re-merges it into the local graph, and writes the merged result back. It's idempotent (safe to run repeatedly) and commutative (order-independent), so two teammates' additions always converge. The repo's `.gitignore` keeps the local SQLite replica private while tracking `graph.jsonl`. Best for teams already living in git who want no servers and offline-friendly sharing; the only friction is the occasional merge conflict on the file, resolved by re-running `sync`.
-
-> Both modes assume one embedding model per graph (see the note under *How it works*). Imports across mismatched embedding dimensions keep the facts but drop the incompatible vectors, and warn you to re-ingest sources to re-embed.
-
----
-
-## How the graph gets smarter over time
-
-Every entity and relationship carries a `confidence` score and an `observations` count.
-
-- **Dedup on write.** When new knowledge comes in, each entity is matched against existing nodes by exact name/alias **and** embedding similarity (cosine ≥ `mergeThreshold`). A match is *merged*, not duplicated.
-- **Reinforcement.** Each observation is recorded under the id of the document/contribution that made it, so `observations` is a grow-only counter and `confidence` is *derived* from it (seen-often facts rise toward 1.0; one-offs stay low). Because the counter merges by taking the max per source, re-importing the same records is a no-op — reinforcement survives team sync without double-counting.
-- **Provenance.** Every node/edge tracks which documents and agents contributed to it.
-- **Grounding.** Source passages are kept as retrievable evidence and returned alongside the structured graph.
-
-This is what makes contributions compound: the tenth agent to confirm a fact strengthens it rather than cluttering the graph.
-
----
+The graph is a folder of plain markdown files in the repo — one per system, API, or concept, linked to each other. It stays in sync with the code through git, so anyone who clones the repo has it, no setup.
## How it works
-```
- ingest / contribute read
- ┌──────────────────────────┐ ┌────────────────────────┐
- │ text → chunk → embed │ │ query → embed │
- │ → extract (LLM) │ │ → semantic match nodes │
- │ → MERGE (dedup + │───────────▶│ → expand 1 hop (edges) │
- │ reinforce) │ graph │ → gather source chunks │
- └──────────────────────────┘ (SQLite) │ → render context bundle│
- └────────────────────────┘
-```
-
-- **Storage** — SQLite (via `better-sqlite3`) by default, or swap in your own `GraphStore`.
-- **Extraction** — local **Ollama** (`llama3.2` by default) using structured JSON output; automatically upgrades to **OpenRouter** (`openai/gpt-4o-mini` by default, any tool-calling model) if `OPENROUTER_API_KEY` is set.
-- **Embeddings** — local **in-process** model (`Xenova/all-MiniLM-L6-v2`, 384-dim) by default; automatically upgrades to **OpenAI** (`text-embedding-3-small`) if `OPENAI_API_KEY` is set.
-- **Retrieval** — semantic match over entities + one-hop graph expansion + supporting source passages.
-
-> Note: embeddings from different models aren't comparable, so pick local **or** cloud for a given database and stick with it — don't switch providers mid-graph.
-
----
-
-## Configuration
-
-Everything is configurable via constructor options, environment variables, or defaults (in that order):
-
-```ts
-new ContextGraphEngine({
- dbPath: "./.context-graph/graph.db", // CONTEXT_GRAPH_DB
- // Cloud (used automatically when set):
- openrouterApiKey: process.env.OPENROUTER_API_KEY,
- openrouterModel: "openai/gpt-4o-mini", // CONTEXT_GRAPH_OPENROUTER_MODEL
- openaiApiKey: process.env.OPENAI_API_KEY, // optional, embeddings only
- embeddingModel: "text-embedding-3-small", // CONTEXT_GRAPH_EMBEDDING_MODEL
- // Local (the zero-key fallback):
- forceLocal: false, // CONTEXT_GRAPH_LOCAL=1 forces local
- localEmbeddingModel: "Xenova/all-MiniLM-L6-v2",// CONTEXT_GRAPH_LOCAL_EMBEDDING_MODEL
- ollamaModel: "llama3.2", // CONTEXT_GRAPH_OLLAMA_MODEL
- ollamaBaseUrl: "http://localhost:11434", // CONTEXT_GRAPH_OLLAMA_URL
- chunkSize: 1200,
- chunkOverlap: 200,
- mergeThreshold: 0.86, // higher = stricter dedup
-});
-```
+- Edit code, regenerate the graph, commit both together.
+- Someone clones the repo — they've got the graph, nothing to set up.
+- Their agent reads it before doing work.
-### Bring your own components
+No database, no server, no embeddings. The graph is just files in git, so git is the sync. And when a change moves something around, you see it in the graph diff right next to the code, in the same PR.
-The engine depends only on small interfaces, so you can replace any piece:
+## Setup
-```ts
-import { ContextGraphEngine, type Embedder, type Extractor, type GraphStore, type Summarizer } from "context-graph-engine";
-
-new ContextGraphEngine({
- store: myCustomStore, // e.g. Postgres/pgvector
- embedder: myCustomEmbedder, // any embedding model
- extractor: myCustomExtractor, // any LLM, or a rules-based extractor
- summarizer: myCustomSummarizer // code-file summaries for ingestRepo
-});
-```
-
-This is exactly how the test suite runs the whole pipeline offline with fake providers.
-
----
-
-## API reference (essentials)
+```bash
+# in your repo
+context-graph init # builds .context/ from your code
+git add .context && git commit
-```ts
-class ContextGraphEngine {
- ingest(text: string, opts?: { title?; source? }): Promise<IngestResult>;
- ingestFile(path: string, opts?): Promise<IngestResult>; // .pdf parsed automatically
- ingestDir(dir: string, opts?): Promise<IngestResult[]>; // recursive; PDF/MD/TXT
- ingestRepo(dir: string, opts?): Promise<RepoIngestResult>; // code → per-file summaries, incremental
- read(query: string, opts?: { maxNodes?; maxChunks?; expand? }): Promise<ContextBundle>;
- contribute(learning: string, opts?: { agentId?; source? }): Promise<ContributeResult>;
- exportGraph(): GraphExport; // -> toHtml / toMermaid
- stats(): GraphStats;
- close(): void;
-}
+# keep it honest — fails CI if the graph is stale
+context-graph check
```
-A `ContextBundle` contains `{ query, nodes, edges, chunks, prompt }` — use `prompt` for a ready-made context block, or the structured arrays to build your own.
-
----
+That's it. Anyone who clones the repo gets `.context/` for free. Point your agent at it and it reads the graph before working.
-## Development
+## The proof
-```bash
-npm install
-npm run build # compile to dist/
-npm run cli -- stats # run the CLI from source
-npm run mcp # run the MCP server from source
-```
+Same model, same tools, same tasks. The only difference is whether the agent got the graph first. On a real 344-file repo it cut tool calls 31%, cost 23%, and latency 17%. The graph isn't magic — it's just that reading a few linked files beats rediscovering the codebase from scratch every single time.
-## License
+## Runs locally
-MIT
+Everything runs on your machine. No accounts, no cloud calls, no keys. Building the graph uses a local model (Ollama); if you'd rather use a cloud model for better summaries, set a key and it'll use it. Local stays the default.
diff --git a/src/web/ui.html b/src/web/ui.html
index e50bf3ee..80bbec8b 100644
--- a/src/web/ui.html
+++ b/src/web/ui.html
@@ -3,7 +3,7 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
-<title>Context Graph — your team's living knowledge ledger</title>
+<title>Context Graph — read the graph before you work</title>
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ccircle cx='9' cy='9' r='4' fill='%232E6B4E'/%3E%3Ccircle cx='24' cy='13' r='3' fill='%231C2422'/%3E%3Ccircle cx='14' cy='24' r='3' fill='%231C2422'/%3E%3Cpath d='M12 11l9 2M11 12l3 9M23 16l-8 7' stroke='%239AA79F' stroke-width='1.5'/%3E%3C/svg%3E" />
<style>
:root {
@@ -16,1479 +16,179 @@
--verdant: #2e6b4e;
--verdant-deep: #1f4f38;
--verdant-soft: #e2ede4;
- --amber: #a9762b;
- --amber-soft: #f3ead8;
--serif: "Charter", "Iowan Old Style", "Palatino", Georgia, serif;
--sans: system-ui, -apple-system, "Segoe UI", sans-serif;
--mono: ui-monospace, "SF Mono", SFMono-Regular, Menlo, Consolas, monospace;
- /* spacing — 4px base */
--s1: 4px; --s2: 8px; --s3: 12px; --s4: 16px;
--s5: 24px; --s6: 32px; --s7: 48px; --s8: 64px;
- /* type roles */
- --fs-label: 11px;
- --fs-meta: 12px;
- --fs-ui: 13.5px;
- --fs-body: 15px;
- --fs-read: 17px;
- --fs-title: 20px;
- --fs-display: 26px;
- /* shape & elevation */
--r-sm: 4px; --r-md: 6px; --r-lg: 10px;
--shadow-1: 0 1px 3px rgba(28,36,34,.06);
- --shadow-2: 0 6px 24px rgba(28,36,34,.10);
- /* motion */
- --dur-fast: 160ms; --dur-med: 320ms; --dur-slow: 600ms;
--ease-out: cubic-bezier(.22,.7,.3,1);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
- html, body { height: 100%; }
body {
font-family: var(--sans);
background: var(--paper);
color: var(--ink);
- font-size: var(--fs-body);
+ font-size: 15px;
line-height: 1.5;
+ -webkit-font-smoothing: antialiased;
}
- button, input, textarea { font: inherit; color: inherit; }
- :focus-visible { outline: 2px solid var(--verdant); outline-offset: 2px; }
+ @keyframes rise { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
+ .rise { animation: rise 480ms var(--ease-out) both; animation-delay: calc(var(--i, 0) * 70ms); }
+ @media (prefers-reduced-motion: reduce) { .rise { animation: none; } }
- /* ---------- motion primitives ---------- */
- @keyframes rise { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }
- .rise { animation: rise var(--dur-med) var(--ease-out) both; animation-delay: calc(var(--i, 0) * 45ms); }
- @keyframes shimmer { to { background-position: -200% 0; } }
- @keyframes spin { to { transform: rotate(360deg); } }
+ code { font-family: var(--mono); }
- /* ---------- app state ---------- */
- /* Until boot resolves the state, both halves stay unmounted — no flash. */
- #onboarding { display: none; }
- body.is-empty #onboarding { display: block; }
- #ask-section, #library { display: none; }
- body.is-ready #ask-section { display: block; }
- body.is-ready #library { display: block; }
-
- /* ---------- header ---------- */
+ /* ---------- masthead ---------- */
.masthead {
display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap;
padding: 14px 22px 12px;
border-bottom: 1px solid var(--line);
background: var(--panel);
}
- .wordmark { font-family: var(--sans); font-weight: 700; font-size: 15px; letter-spacing: .14em; text-transform: uppercase; }
+ .wordmark { font-weight: 700; font-size: 15px; letter-spacing: .14em; text-transform: uppercase; }
.wordmark .dot { color: var(--verdant); }
.tagline { font-family: var(--serif); font-style: italic; color: var(--ink-soft); font-size: 14.5px; }
- .masthead-right { margin-left: auto; display: flex; align-items: baseline; gap: var(--s2); }
- .stat { font-family: var(--mono); font-size: var(--fs-meta); color: var(--ink-soft); }
- .stat b { color: var(--ink); font-size: 14px; font-weight: 600; }
- .stat-sep { color: var(--ink-faint); font-family: var(--mono); font-size: var(--fs-meta); }
- .provider-badge {
- font-family: var(--mono); font-size: var(--fs-label); padding: 3px 9px;
- border: 1px solid var(--line); border-radius: 999px; color: var(--ink-soft);
- background: var(--paper); margin-left: var(--s3);
- }
- .provider-badge.cloud { border-color: var(--verdant); color: var(--verdant-deep); background: var(--verdant-soft); }
- .provider-badge:not(.cloud) { cursor: pointer; }
-
- /* ---------- layout ---------- */
- .frame {
- display: grid;
- grid-template-columns: minmax(400px, 500px) 1fr;
- height: calc(100vh - 49px);
- }
- .desk {
- overflow-y: auto;
- padding: var(--s5) var(--s5) var(--s8);
- border-right: 1px solid var(--line);
- }
- .desk > section { margin-bottom: var(--s6); }
- .atlas { position: relative; background: var(--panel); }
- #graph { position: absolute; inset: 0; }
-
- /* ---------- onboarding hero ---------- */
- .hero h1 { font-family: var(--serif); font-size: var(--fs-display); font-weight: 600; margin: var(--s4) 0 var(--s3); }
- .hero-sub { color: var(--ink-soft); font-size: var(--fs-body); line-height: 1.55; margin-bottom: var(--s5); max-width: 46ch; }
- .steps { list-style: none; margin-bottom: var(--s5); display: flex; flex-direction: column; gap: var(--s2); }
- .steps li { display: flex; gap: var(--s3); align-items: center; font-size: var(--fs-ui); color: var(--ink-soft); }
- .steps li b { color: var(--ink); }
- .steps .num {
- font-family: var(--mono); font-size: var(--fs-label); font-weight: 700;
- color: var(--verdant-deep); background: var(--verdant-soft); border-radius: 50%;
- width: 20px; height: 20px; flex: none;
- display: inline-flex; align-items: center; justify-content: center;
- }
- .dropzone {
- display: flex; flex-direction: column; gap: var(--s1); align-items: center; justify-content: center;
- width: 100%; padding: var(--s6) var(--s4);
- border: 1.5px dashed var(--ink-faint); border-radius: var(--r-lg);
- background: var(--panel); cursor: pointer; text-align: center;
- transition: border-color var(--dur-fast), background var(--dur-fast), transform var(--dur-fast);
- }
- .dropzone:hover, .dropzone.drag { border-color: var(--verdant); background: var(--verdant-soft); }
- .dropzone.drag { transform: scale(1.01); }
- .dropzone:disabled { opacity: .55; cursor: default; }
- .dz-main { font-family: var(--serif); font-size: var(--fs-title); color: var(--ink); }
- .dz-sub { font-family: var(--mono); font-size: var(--fs-meta); color: var(--ink-soft); }
- /* compact variant inside the library drawer */
- #ingest-panel .dropzone { padding: var(--s4); }
- #ingest-panel .dz-main { font-size: var(--fs-body); }
-
- #ingest-controls .picker-row { margin-top: var(--s3); }
-
- /* ---------- ingest progress ---------- */
- #ingest-progress { margin-top: var(--s3); }
- .progress-track { height: 3px; background: var(--line); border-radius: 2px; overflow: hidden; }
- .progress-track i { display: block; height: 100%; width: 0; background: var(--verdant); transition: width var(--dur-med) var(--ease-out); }
- #progress-rows { margin-top: var(--s2); font-family: var(--mono); font-size: var(--fs-meta); color: var(--ink-soft); }
- .progress-row { display: flex; gap: var(--s2); align-items: center; padding: 2px 0; min-width: 0; }
- .progress-row > span:last-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .progress-row .icon { width: 12px; flex: none; text-align: center; }
- .progress-row.ok .icon { color: var(--verdant); }
- .progress-row.err { color: #a03b2e; }
- .spinner {
- display: inline-block; width: 10px; height: 10px;
- border: 1.5px solid var(--line); border-top-color: var(--verdant);
- border-radius: 50%; animation: spin .7s linear infinite;
- }
-
- /* ---------- ask ---------- */
- .ask-label {
- font-size: var(--fs-label); letter-spacing: .12em; text-transform: uppercase;
- color: var(--ink-faint); font-weight: 600; margin-bottom: var(--s2);
- }
- .ask-row { display: flex; gap: var(--s2); }
- .ask-input {
- flex: 1;
- font-family: var(--serif); font-size: var(--fs-read);
- padding: 11px 14px;
- border: 1px solid var(--line); border-radius: var(--r-md);
- background: var(--panel);
- min-width: 0;
- }
- .ask-input::placeholder { color: var(--ink-faint); font-style: italic; }
- .btn {
- padding: 10px 18px; border-radius: var(--r-md); border: 1px solid var(--verdant-deep);
- background: var(--verdant); color: #fff; font-weight: 600; font-size: 14px;
- cursor: pointer;
- transition: background var(--dur-fast), transform var(--dur-fast), box-shadow var(--dur-fast), border-color var(--dur-fast);
- }
- .btn:hover { background: var(--verdant-deep); transform: translateY(-1px); box-shadow: var(--shadow-1); }
- .btn:active { transform: none; box-shadow: none; }
- .btn:disabled { opacity: .55; cursor: default; transform: none; box-shadow: none; }
- .btn.quiet { background: var(--panel); color: var(--ink); border-color: var(--line); font-weight: 500; }
- .btn.quiet:hover { background: var(--panel); border-color: var(--ink-faint); }
- .linklike { background: none; border: none; color: var(--verdant-deep); cursor: pointer; font-size: var(--fs-ui); padding: var(--s1) 0; }
- .linklike:hover { text-decoration: underline; }
+ /* ---------- page ---------- */
+ .page { max-width: 760px; margin: 0 auto; padding: var(--s8) var(--s5) var(--s8); }
+ section { margin-bottom: var(--s8); }
- .local-note {
- display: flex; gap: var(--s3); align-items: flex-start;
- margin-top: var(--s3); padding: 9px 12px; border-radius: var(--r-md);
- background: var(--amber-soft); border: 1px solid #e5d7ba;
- font-size: 13px; color: #6d5426;
+ /* ---------- hero ---------- */
+ .hero h1 {
+ font-family: var(--serif); font-weight: 600; letter-spacing: -0.01em;
+ font-size: clamp(30px, 6vw, 46px); line-height: 1.12; margin-bottom: var(--s5);
}
- .local-note code { font-family: var(--mono); font-size: 12px; }
- .note-close { background: none; border: none; cursor: pointer; color: #6d5426; font-size: 15px; line-height: 1.3; padding: 0; flex: none; }
+ .hero-sub { color: var(--ink-soft); font-size: 18px; line-height: 1.6; max-width: 56ch; }
+ .hero-sub b { color: var(--ink); font-weight: 600; }
- /* ---------- answer ---------- */
- .answer-card {
- margin-top: var(--s4); background: var(--panel);
- border: 1px solid var(--line); border-radius: var(--r-lg);
- padding: var(--s4) var(--s5);
- box-shadow: var(--shadow-1);
- }
- .answer-q {
- font-family: var(--mono); font-size: var(--fs-meta); color: var(--ink-faint);
- margin-bottom: var(--s3); word-break: break-word;
- }
- .answer-body { font-family: var(--serif); font-size: var(--fs-read); line-height: 1.65; }
- .answer-body p + p { margin-top: var(--s3); }
- .answer-body ul { margin: var(--s2) 0 var(--s2) 22px; }
- .answer-body .cite {
- font-family: var(--mono); font-size: 10.5px; font-style: normal;
- background: var(--verdant-soft); color: var(--verdant-deep);
- border-radius: var(--r-sm); padding: 1px 5px; margin: 0 1px;
- cursor: pointer; vertical-align: super; line-height: 1;
- border: none;
- transition: background var(--dur-fast), color var(--dur-fast);
- }
- .answer-body .cite:hover { background: var(--verdant); color: #fff; }
- .thinking { font-family: var(--serif); font-style: italic; color: var(--ink-soft); }
-
- #answer-skeleton .skel-bar {
- height: 13px; border-radius: var(--r-sm); margin: var(--s3) 0;
- background: linear-gradient(90deg, #e8ede7 25%, #f4f7f3 45%, #e8ede7 65%);
- background-size: 200% 100%;
- animation: shimmer 1.1s linear infinite;
- }
-
- /* ---------- the receipt (signature element) ---------- */
- .receipt {
- display: inline-flex; align-items: center; gap: 7px;
- font-family: var(--mono); font-size: var(--fs-label); color: var(--ink-soft);
- border: 1px solid var(--line); border-radius: var(--r-sm);
- padding: 2px 8px 2px 6px; background: var(--panel);
- white-space: nowrap;
- }
- .receipt .meter {
- width: 34px; height: 5px; border-radius: 3px; background: #e4e9e3;
- overflow: hidden; flex: none;
- }
- .receipt .meter i { display: block; height: 100%; background: var(--verdant); border-radius: 3px; }
- .receipt.low .meter i { background: var(--amber); }
- .receipt .pct { color: var(--ink); font-weight: 600; }
-
- #receipt-legend {
- display: flex; gap: var(--s3); align-items: center; flex-wrap: wrap;
- margin-top: var(--s3); padding: var(--s3) var(--s4);
- background: var(--verdant-soft); border: 1px solid #cfe0d2; border-radius: var(--r-md);
- font-size: var(--fs-ui); color: var(--ink-soft);
- }
- #receipt-legend .legend-text { flex: 1; min-width: 200px; }
- #receipt-legend .linklike { font-family: var(--mono); font-size: var(--fs-meta); flex: none; }
-
- /* ---------- evidence tabs ---------- */
- #evidence-tabs {
- display: flex; gap: var(--s4);
- border-bottom: 1px solid var(--line);
- margin: var(--s5) 0 var(--s3);
- }
- .tab {
- background: none; border: none; cursor: pointer;
- font-size: var(--fs-label); letter-spacing: .12em; text-transform: uppercase; font-weight: 600;
- color: var(--ink-faint);
- padding: var(--s2) 2px; position: relative;
- transition: color var(--dur-fast);
- }
- .tab .count { font-family: var(--mono); letter-spacing: 0; margin-left: 4px; color: inherit; font-weight: 500; }
- .tab::after {
- content: ""; position: absolute; left: 0; right: 0; bottom: -1px; height: 2px;
- background: var(--verdant); transform: scaleX(0);
- transition: transform var(--dur-fast) var(--ease-out);
+ /* ---------- metric tiles ---------- */
+ .metrics { display: grid; grid-template-columns: repeat(3, 1fr); gap: var(--s3); margin-top: var(--s6); }
+ .metric {
+ background: var(--panel); border: 1px solid var(--line); border-radius: var(--r-lg);
+ padding: var(--s4) var(--s4) var(--s3); box-shadow: var(--shadow-1);
}
- .tab:hover { color: var(--ink); }
- .tab.active { color: var(--ink); }
- .tab.active::after { transform: scaleX(1); }
+ .metric .n { font-family: var(--serif); font-weight: 600; font-size: 34px; color: var(--verdant-deep); line-height: 1; }
+ .metric .l { font-family: var(--mono); font-size: 11.5px; color: var(--ink-soft); margin-top: var(--s2); text-transform: uppercase; letter-spacing: .06em; }
- /* ---------- ledger sections ---------- */
- .ledger-head {
- display: flex; align-items: baseline; justify-content: space-between;
- margin: 0 0 var(--s3);
+ /* ---------- steps ---------- */
+ h2.head {
+ font-size: 12px; letter-spacing: .12em; text-transform: uppercase;
+ color: var(--ink-faint); font-weight: 700; margin-bottom: var(--s5);
border-bottom: 1px solid var(--line); padding-bottom: var(--s2);
}
- .ledger-head h2 {
- font-size: var(--fs-label); letter-spacing: .12em; text-transform: uppercase;
- color: var(--ink-faint); font-weight: 600;
- }
- .ledger-head .count { font-family: var(--mono); font-size: var(--fs-label); color: var(--ink-faint); }
-
- .fact {
- display: flex; flex-direction: column; gap: 5px;
- padding: 11px 2px; border-bottom: 1px solid var(--line);
- }
- .fact-top { display: flex; align-items: baseline; gap: var(--s2); flex-wrap: wrap; }
- .fact-name { font-family: var(--serif); font-size: 15.5px; font-weight: 700; cursor: pointer; }
- .fact-name:hover { color: var(--verdant-deep); text-decoration: underline; }
- .fact-type { font-family: var(--mono); font-size: 10.5px; color: var(--ink-faint); text-transform: lowercase; }
- .fact-via { font-family: var(--mono); font-size: 10px; color: var(--verdant-deep); background: var(--verdant-soft); border-radius: 3px; padding: 1px 5px; }
- .fact-via.expanded { color: var(--ink-soft); background: var(--paper); }
- .fact-summary { font-family: var(--serif); font-size: 14px; color: var(--ink-soft); line-height: 1.5; }
-
- .edge-line { font-family: var(--mono); font-size: var(--fs-meta); color: var(--ink-soft); padding: 6px 2px; border-bottom: 1px solid var(--line); }
- .edge-line b { color: var(--ink); font-weight: 600; }
- .edge-line .rel { color: var(--verdant-deep); }
-
- .source {
- padding: var(--s3) 2px; border-bottom: 1px solid var(--line);
- }
- .source.flash { background: var(--verdant-soft); transition: background 1.2s; }
- .source-top { display: flex; align-items: baseline; gap: var(--s2); margin-bottom: 5px; }
- .source-num { font-family: var(--mono); font-size: var(--fs-label); font-weight: 700; color: var(--verdant-deep); }
- .source-title { font-size: 13px; font-weight: 600; }
- .source-text {
- font-family: var(--serif); font-size: 13.5px; color: var(--ink-soft); line-height: 1.55;
- max-height: 88px; overflow: hidden; position: relative;
- }
- .source.open .source-text { max-height: none; }
- .source-more { font-size: var(--fs-meta); color: var(--verdant-deep); background: none; border: none; cursor: pointer; padding: 2px 0; }
-
- /* ---------- library drawers ---------- */
- details.grow { margin-bottom: var(--s3); border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--panel); }
- details.grow summary {
- cursor: pointer; padding: var(--s3) var(--s4); font-weight: 600; font-size: var(--fs-ui);
- list-style: none; display: flex; align-items: center; gap: var(--s2);
- }
- details.grow summary::-webkit-details-marker { display: none; }
- details.grow summary::before { content: "+"; font-family: var(--mono); color: var(--verdant); font-weight: 700; }
- details.grow[open] summary::before { content: "–"; }
- details.grow .grow-body { padding: 2px var(--s4) var(--s4); }
- .grow-hint { font-size: 12.5px; color: var(--ink-soft); margin-bottom: var(--s3); }
- textarea.teach {
- width: 100%; min-height: 74px; resize: vertical;
- font-family: var(--serif); font-size: 15px; padding: 10px 12px;
- border: 1px solid var(--line); border-radius: var(--r-md); background: var(--paper);
- margin-bottom: var(--s2);
- }
- input.dir {
- width: 100%; font-family: var(--mono); font-size: 13px; padding: 9px 12px;
- border: 1px solid var(--line); border-radius: var(--r-md); background: var(--paper);
- margin-bottom: var(--s2);
- }
- .grow-status { font-family: var(--mono); font-size: var(--fs-meta); margin-top: var(--s3); color: var(--ink-soft); white-space: pre-wrap; word-break: break-word; }
- .grow-status:empty { margin-top: 0; }
- .grow-status.ok { color: var(--verdant-deep); }
- .grow-status.err { color: #a03b2e; }
- .picker-row { display: flex; flex-wrap: wrap; gap: var(--s2); }
- details.server-path { margin-top: var(--s3); border-top: 1px solid var(--line); padding-top: 10px; }
- details.server-path summary { cursor: pointer; font-size: 12.5px; color: var(--ink-faint); list-style: none; }
- details.server-path summary::-webkit-details-marker { display: none; }
- details.server-path summary::before { content: "›"; margin-right: 6px; color: var(--verdant); }
- details.server-path[open] summary::before { content: "⌄"; }
- details.server-path .grow-hint code { font-family: var(--mono); font-size: 11.5px; }
- details.server-path[open] { padding-bottom: var(--s1); }
- details.server-path > *:not(summary) { margin-top: var(--s2); }
- .watch-opt {
- display: flex; align-items: center; gap: 7px; font-size: 12.5px; color: var(--ink-soft);
- cursor: pointer; user-select: none;
+ .steps { list-style: none; display: flex; flex-direction: column; gap: var(--s5); }
+ .steps li { display: flex; gap: var(--s4); align-items: flex-start; }
+ .steps .num {
+ font-family: var(--mono); font-size: 12px; font-weight: 700;
+ color: var(--verdant-deep); background: var(--verdant-soft); border-radius: 50%;
+ width: 26px; height: 26px; flex: none;
+ display: inline-flex; align-items: center; justify-content: center; margin-top: 2px;
}
- .watch-opt input { accent-color: var(--verdant); }
+ .steps .body { font-size: 16px; color: var(--ink-soft); line-height: 1.55; }
+ .steps .body b { color: var(--ink); font-weight: 600; }
- .sync-pill {
- display: flex; align-items: center; gap: 8px; margin-top: var(--s3);
- padding: 8px 12px; border: 1px solid var(--verdant); border-radius: var(--r-sm);
- background: var(--verdant-soft); font-size: 12.5px; color: var(--ink-soft);
- }
- .sync-pill .dot {
- width: 8px; height: 8px; border-radius: 50%; background: var(--verdant); flex: none;
- animation: sync-pulse 2s ease-in-out infinite;
+ /* ---------- code block ---------- */
+ pre {
+ background: var(--ink); color: #e7ede8; border-radius: var(--r-lg);
+ padding: var(--s5); overflow-x: auto; font-family: var(--mono); font-size: 13.5px; line-height: 1.7;
}
- .sync-pill #folder-sync-text { flex: 1; min-width: 0; }
- .sync-pill .btn { padding: 3px 10px; font-size: 12px; }
- @keyframes sync-pulse { 0%, 100% { opacity: 1; } 50% { opacity: .35; } }
+ pre .c { color: #7f9686; } /* comment */
+ .after { color: var(--ink-soft); font-size: 15px; margin-top: var(--s4); line-height: 1.6; }
+ .after code { background: var(--verdant-soft); color: var(--verdant-deep); border-radius: var(--r-sm); padding: 1px 5px; font-size: 13px; }
- .doc-row {
- display: flex; gap: var(--s2); align-items: baseline; padding: 7px 4px;
- border-bottom: 1px solid var(--line); font-size: 13px; border-radius: var(--r-sm);
- transition: background var(--dur-fast);
- }
- .doc-row:hover { background: var(--verdant-soft); }
- .doc-row .t { font-weight: 600; flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
- .doc-row .d { font-family: var(--mono); font-size: var(--fs-label); color: var(--ink-faint); flex: none; }
+ /* ---------- prose ---------- */
+ .prose { font-size: 16px; color: var(--ink-soft); line-height: 1.65; max-width: 62ch; }
+ .prose + .prose { margin-top: var(--s3); }
+ .prose b { color: var(--ink); font-weight: 600; }
- /* ---------- graph panel chrome ---------- */
- .atlas-legend {
- position: absolute; top: 14px; left: 16px; z-index: 5;
- font-family: var(--mono); font-size: var(--fs-label); color: var(--ink-soft);
- background: color-mix(in srgb, var(--panel) 88%, transparent);
- border: 1px solid var(--line); border-radius: var(--r-md); padding: var(--s2) var(--s3);
- display: flex; gap: 14px; align-items: center;
+ footer {
+ border-top: 1px solid var(--line); padding: var(--s5) 0 0;
+ color: var(--ink-faint); font-size: 13px;
}
- .atlas-legend .swatch { display: inline-block; width: 9px; height: 9px; border-radius: 50%; margin-right: 5px; vertical-align: -1px; }
- #node-card {
- position: absolute; bottom: 16px; left: 16px; right: 16px; z-index: 5;
- max-width: 440px;
- background: var(--panel); border: 1px solid var(--line); border-radius: var(--r-lg);
- padding: 14px 16px; box-shadow: var(--shadow-2);
- visibility: hidden; opacity: 0; transform: translateY(6px) scale(.98);
- transition: opacity var(--dur-fast) var(--ease-out), transform var(--dur-fast) var(--ease-out), visibility var(--dur-fast);
- }
- #node-card.show { visibility: visible; opacity: 1; transform: none; }
- #node-card .close { position: absolute; top: 8px; right: 10px; background: none; border: none; cursor: pointer; color: var(--ink-faint); font-size: 15px; }
- #node-card h3 { font-family: var(--serif); font-size: 17px; margin-bottom: 2px; }
- #node-card .nc-type { font-family: var(--mono); font-size: var(--fs-label); color: var(--ink-faint); margin-bottom: 7px; }
- #node-card .nc-summary { font-family: var(--serif); font-size: 14px; color: var(--ink-soft); line-height: 1.5; margin-bottom: 9px; }
- #node-card .nc-prov { font-family: var(--mono); font-size: var(--fs-label); color: var(--ink-faint); margin-top: var(--s2); }
- .atlas-empty {
- position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
- z-index: 4; text-align: center; padding: 40px;
- }
- .atlas-empty .inner { max-width: 360px; }
- .atlas-empty h3 { font-family: var(--serif); font-size: var(--fs-title); margin-bottom: var(--s2); }
- .atlas-empty p { color: var(--ink-soft); font-size: 14px; }
- .hidden { display: none !important; }
-
- @media (max-width: 900px) {
- .frame { grid-template-columns: 1fr; grid-template-rows: auto 420px; height: auto; }
- .desk { border-right: none; border-bottom: 1px solid var(--line); }
- .atlas { height: 420px; }
- }
- @media (prefers-reduced-motion: reduce) {
- * { transition: none !important; animation: none !important; }
- .rise { opacity: 1 !important; transform: none !important; }
- #answer-skeleton .skel-bar { background: #e8ede7; }
- #node-card { visibility: hidden; opacity: 1; transform: none; }
- #node-card.show { visibility: visible; }
+ @media (max-width: 560px) {
+ .metrics { grid-template-columns: 1fr; }
+ .page { padding: var(--s6) var(--s4) var(--s7); }
}
-
- /* ---------- access-token gate ---------- */
- .token-overlay {
- position: fixed; inset: 0; z-index: 1000;
- display: none; align-items: center; justify-content: center;
- background: rgba(28, 36, 34, .55); padding: 20px;
- }
- .token-overlay.open { display: flex; }
- .token-card {
- width: 100%; max-width: 440px;
- background: var(--panel); border: 1px solid var(--line); border-radius: var(--r-lg);
- padding: 24px 24px 20px; box-shadow: 0 12px 40px rgba(28, 36, 34, .25);
- }
- .token-card h2 {
- font-family: var(--serif); font-size: var(--fs-title); font-weight: 600; margin-bottom: var(--s2);
- }
- .token-card p { font-size: 14px; color: var(--ink-soft); margin-bottom: 14px; }
- .token-card p code {
- font-family: var(--mono); font-size: var(--fs-meta);
- background: var(--paper); border: 1px solid var(--line);
- border-radius: var(--r-sm); padding: 1px 5px; color: var(--ink);
- }
- .token-input {
- width: 100%; padding: 11px 13px; font-family: var(--mono); font-size: 13px;
- border: 1px solid var(--line); border-radius: var(--r-md); background: var(--panel);
- }
- .token-input:focus { border-color: var(--verdant); }
- .token-hint { font-size: 12.5px; color: var(--ink-faint); margin: 10px 0 0; }
- .token-hint code { font-family: var(--mono); font-size: 11.5px; }
- .token-err { color: var(--amber); font-size: 13px; margin-top: 10px; min-height: 0; }
- .token-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 18px; }
</style>
</head>
<body>
-<div class="token-overlay" id="token-overlay" role="dialog" aria-modal="true" aria-labelledby="token-title">
- <div class="token-card">
- <h2 id="token-title">This graph is protected</h2>
- <p>Paste the <b>access token</b> or the <b>share link</b> you were given.</p>
- <input class="token-input" id="token-input" type="text"
- placeholder="token, or http://…/#token=…" autocomplete="off" spellcheck="false" />
- <div class="token-err" id="token-err"></div>
- <p class="token-hint">
- Where to find it: open <code>./data/share-link.txt</code> next to the server,
- or run <code>docker compose logs | grep token</code>.
- </p>
- <div class="token-actions">
- <button class="btn quiet" id="token-cancel" type="button">Cancel</button>
- <button class="btn" id="token-submit" type="button">Unlock</button>
- </div>
- </div>
-</div>
-
<header class="masthead">
<span class="wordmark">Context<span class="dot">·</span>Graph</span>
- <span class="tagline">a living ledger of what your team knows</span>
- <div class="masthead-right">
- <span class="stat"><b id="stat-nodes">–</b> facts</span>
- <span class="stat-sep">·</span>
- <span class="stat"><b id="stat-edges">–</b> connections</span>
- <span class="stat-sep">·</span>
- <span class="stat"><b id="stat-docs">–</b> documents</span>
- <span class="provider-badge" id="provider-badge">…</span>
- </div>
+ <span class="tagline">read the graph before you work</span>
</header>
-<div class="frame">
- <main class="desk">
-
- <!-- Onboarding hero — shown while the graph is empty -->
- <section id="onboarding" class="hero rise" style="--i:1">
- <h1>Start your ledger</h1>
- <p class="hero-sub">Add documents and Context Graph turns them into a map of facts —
- every answer cited, every fact carrying a receipt that shows how well-attested it is.
- <em>Agents that read the graph before a task explore 31% less.</em></p>
- <ol class="steps">
- <li><span class="num">1</span><span><b>Add documents</b> — PDFs, markdown, or plain text.</span></li>
- <li><span class="num">2</span><span><b>Ask a question</b> — get a written answer with numbered citations.</span></li>
- <li><span class="num">3</span><span><b>Check the receipts</b> — every fact shows its confidence and sources.</span></li>
- </ol>
- <div id="onboarding-controls-slot">
- <div id="ingest-controls">
- <button class="dropzone" id="dropzone" type="button">
- <span class="dz-main">Drop files here, or click to choose</span>
- <span class="dz-sub">.pdf · .md · .txt — files stay on your machine</span>
- </button>
- <input type="file" id="files-input" multiple accept=".pdf,.md,.markdown,.txt" hidden />
- <input type="file" id="folder-input" webkitdirectory multiple hidden />
- <div class="picker-row">
- <button class="btn quiet" id="choose-folder-btn" type="button" title="The folder keeps syncing while this tab is open">Connect a folder…</button>
- </div>
- <div id="folder-sync" class="sync-pill hidden">
- <span class="dot"></span>
- <span id="folder-sync-text"></span>
- <button class="btn quiet" id="folder-sync-stop" type="button">Stop</button>
- </div>
- <details class="server-path">
- <summary>Ingest a path on the server</summary>
- <p class="grow-hint">Reads a file or folder from the server's own disk — in Docker, that's the mounted <code>/docs</code>.</p>
- <input class="dir" id="ingest-input" placeholder="/path/to/docs or /path/to/file.md" />
- <label class="watch-opt"><input type="checkbox" id="watch-check" /> Keep watching — future changes are ingested automatically</label>
- <button class="btn quiet" id="ingest-btn" type="button">Ingest server path</button>
- </details>
- <div id="ingest-progress" class="hidden">
- <div class="progress-track"><i id="progress-fill"></i></div>
- <div id="progress-rows"></div>
- </div>
- <div class="grow-status" id="ingest-status"></div>
- </div>
- </div>
- </section>
-
- <!-- Ask — the hero once documents exist -->
- <section id="ask-section" class="rise" style="--i:1">
- <div class="ask-label">Ask your documents</div>
- <form class="ask-row" id="ask-form">
- <input class="ask-input" id="ask-input" placeholder="How do we deploy to staging?" autocomplete="off" />
- <button class="btn" id="ask-btn" type="submit">Ask</button>
- </form>
- <div class="local-note hidden" id="local-note">
- <span>Local mode — search and the map work now. For written answers and adding new
- documents, run a free local model (<code>ollama pull llama3.2</code>) or set
- <code>OPENROUTER_API_KEY</code>.</span>
- <button class="note-close" id="local-note-close" type="button" aria-label="Dismiss">×</button>
- </div>
- </section>
-
- <section id="answer-wrap" class="hidden">
- <div class="answer-card">
- <div class="answer-q" id="answer-q"></div>
- <div id="answer-skeleton" class="hidden">
- <span class="thinking">Consulting the graph…</span>
- <div class="skel-bar" style="width:92%"></div>
- <div class="skel-bar" style="width:78%"></div>
- <div class="skel-bar" style="width:60%"></div>
- </div>
- <div class="answer-body" id="answer-body"></div>
- </div>
-
- <div id="receipt-legend" class="hidden">
- <span id="legend-sample"></span>
- <span class="legend-text">The receipt: how confident the graph is (87%), how many
- times the fact was observed (×4), and in how many sources (2). Seen often = trusted more.</span>
- <button class="linklike" id="legend-dismiss" type="button">got it ×</button>
- </div>
-
- <div id="evidence" class="hidden">
- <nav id="evidence-tabs">
- <button type="button" class="tab active" data-tab="sources">Sources <span class="count" id="sources-count"></span></button>
- <button type="button" class="tab" data-tab="facts">Facts <span class="count" id="facts-count"></span></button>
- <button type="button" class="tab" data-tab="edges" id="tab-btn-edges">Connections <span class="count" id="edges-count"></span></button>
- </nav>
- <div class="tab-panel" id="tab-sources"><div id="sources"></div></div>
- <div class="tab-panel hidden" id="tab-facts"><div id="facts"></div></div>
- <div class="tab-panel hidden" id="tab-edges"><div id="edges"></div></div>
- </div>
- </section>
-
- <!-- Library — documents + ways to add knowledge -->
- <section id="library" class="rise" style="--i:2">
- <div class="ledger-head"><h2>Library</h2><span class="count" id="docs-count"></span></div>
-
- <details class="grow" id="ingest-panel">
- <summary>Add documents</summary>
- <div class="grow-body" id="ingest-panel-body">
- <p class="grow-hint">Every file becomes facts and connections — watch the map grow on the right.</p>
- </div>
- </details>
-
- <details class="grow" id="teach-panel">
- <summary>Add a fact</summary>
- <div class="grow-body">
- <p class="grow-hint">Know something the documents don't say? Write it in one sentence —
- “Postgres failovers page the on-call via #incidents, not email.” The graph will
- remember it, and who said so.</p>
- <textarea class="teach" id="teach-input" placeholder="What did you learn?"></textarea>
- <button class="btn quiet" id="teach-btn" type="button">Save fact</button>
- <div class="grow-status" id="teach-status"></div>
- </div>
- </details>
-
- <div id="docs"></div>
- <button class="linklike hidden" id="docs-toggle" type="button">Show all</button>
- </section>
- </main>
-
- <section class="atlas">
- <div class="atlas-legend">
- <span><span class="swatch" style="background:#2e6b4e"></span>used in this answer</span>
- <span><span class="swatch" style="background:#b8c2ba"></span>everything else</span>
- </div>
- <div id="graph"></div>
- <div class="atlas-empty hidden" id="atlas-empty">
- <div class="inner">
- <h3>Your knowledge map draws itself here.</h3>
- <p>As documents are added, each fact becomes a node; each relationship, a line.</p>
- </div>
- </div>
- <div id="node-card">
- <button class="close" id="node-card-close" aria-label="Close">×</button>
- <h3 id="nc-name"></h3>
- <div class="nc-type" id="nc-type"></div>
- <div class="nc-summary" id="nc-summary"></div>
- <span class="receipt" id="nc-receipt"></span>
- <div class="nc-prov" id="nc-prov"></div>
+<main class="page">
+
+ <section class="hero rise" style="--i:0">
+ <h1>31% fewer tool calls.<br>23% less cost.<br>17% lower latency.</h1>
+ <p class="hero-sub">That's what your agent gets from reading the repo's context graph before it
+ starts working. The graph is a folder of plain markdown files in the repo — one per system,
+ API, or concept, linked to each other. It stays in sync with the code through git, so
+ <b>anyone who clones the repo has it, no setup.</b></p>
+ <div class="metrics">
+ <div class="metric"><div class="n">&minus;31%</div><div class="l">tool calls</div></div>
+ <div class="metric"><div class="n">&minus;23%</div><div class="l">cost</div></div>
+ <div class="metric"><div class="n">&minus;17%</div><div class="l">latency</div></div>
</div>
</section>
-</div>
-
-<script src="https://unpkg.com/[email protected]/standalone/umd/vis-network.min.js" integrity="sha384-yxKDWWf0wwdUj/gPeuL11czrnKFQROnLgY8ll7En9NYoXibgg3C6NK/UDHNtUgWJ" crossorigin="anonymous"></script>
-<script>
-"use strict";
-const $ = (id) => document.getElementById(id);
-const REDUCED = matchMedia("(prefers-reduced-motion: reduce)");
-
-/* ---------- access token (shared/team deployments) ---------- */
-// A share link carries #token=… in the URL fragment — fragments are never
-// sent to the server, so the token stays out of proxy/access logs. Accept
-// either a bare token or a whole pasted link and pull the token out of it.
-function extractToken(raw) {
- const s = (raw || "").trim();
- if (!s) return "";
- // Full share link: token lives in the #token=… fragment.
- const hash = s.includes("#") ? s.slice(s.indexOf("#") + 1) : "";
- const fromHash = new URLSearchParams(hash).get("token");
- return (fromHash || s).trim();
-}
-
-(function pickUpToken() {
- const frag = new URLSearchParams(location.hash.replace(/^#/, ""));
- const t = frag.get("token");
- if (t) {
- localStorage.setItem("cg-token", t.trim());
- history.replaceState(null, "", location.pathname + location.search);
- }
-})();
-
-// In-page token modal — a Promise that resolves with the entered token (already
-// normalized) or null if the user cancels. Replaces the browser's window.prompt.
-function askForToken(message) {
- const overlay = $("token-overlay");
- const input = $("token-input");
- const err = $("token-err");
- err.textContent = message || "";
- input.value = "";
- overlay.classList.add("open");
- input.focus();
- return new Promise((resolve) => {
- const close = (value) => {
- overlay.classList.remove("open");
- $("token-submit").onclick = null;
- $("token-cancel").onclick = null;
- input.onkeydown = null;
- overlay.onmousedown = null;
- resolve(value);
- };
- const submit = () => {
- const token = extractToken(input.value);
- if (!token) { err.textContent = "Enter a token or share link."; return; }
- close(token);
- };
- $("token-submit").onclick = submit;
- $("token-cancel").onclick = () => close(null);
- input.onkeydown = (e) => {
- if (e.key === "Enter") submit();
- else if (e.key === "Escape") close(null);
- };
- // Click on the backdrop (not the card) cancels.
- overlay.onmousedown = (e) => { if (e.target === overlay) close(null); };
- });
-}
-
-async function api(path, opts = {}) {
- const headers = { ...(opts.headers || {}) };
- const token = localStorage.getItem("cg-token");
- if (token) headers["authorization"] = "Bearer " + token;
- const r = await fetch(path, { ...opts, headers });
- if (r.status === 401) {
- const wrong = Boolean(token); // had a token that the server rejected
- const t = await askForToken(wrong ? "That token was rejected. Try again." : "");
- if (t) {
- localStorage.setItem("cg-token", t);
- return api(path, opts);
- }
- throw new Error("access token required");
- }
- return r;
-}
-const esc = (s) => String(s ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
-
-const MODEL_HINT = "Adding facts needs a model: run Ollama locally (ollama pull llama3.2) or set OPENROUTER_API_KEY.";
-
-const COLOR_BASE = { background: "#b8c2ba", border: "#93a098" };
-const COLOR_HIT = { background: "#2e6b4e", border: "#1f4f38" };
-const COLOR_EXPANDED = { background: "#7fa98f", border: "#2e6b4e" };
-const COLOR_FRESH = { background: "#3f8f66", border: "#1f4f38" };
-
-let network = null;
-let nodesDs = null;
-let edgesDs = null;
-let prevObs = new Map(); // node id -> observations, for "what just got smarter" diffing
-let highlighted = new Set();
-let ingestBusy = false;
-
-/* ---------- app state: empty (onboarding) vs ready (ask) ---------- */
-let appState = "";
-function setAppState(stats) {
- const forcedReady = new URLSearchParams(location.search).get("q");
- const ready = (stats && stats.documents > 0) || Boolean(forcedReady);
- const next = ready ? "is-ready" : "is-empty";
- if (next === appState) return;
- appState = next;
- document.body.classList.remove("is-ready", "is-empty");
- document.body.classList.add(next);
- // The ingest controls exist once; they live in the hero while the graph is
- // empty and move into the Library drawer once it isn't.
- const controls = $("ingest-controls");
- if (ready) {
- $("ingest-panel-body").appendChild(controls);
- if (ingestBusy) {
- // Mid-ingest flip: keep the progress visible in its new home.
- $("ingest-panel").open = true;
- } else {
- $("ask-input").focus();
- }
- } else {
- $("onboarding-controls-slot").appendChild(controls);
- }
-}
-
-/* ---------- motion helpers ---------- */
-// Stagger-reveal freshly rendered children (they're new DOM nodes each render,
-// so the animation replays). Skipped entirely under reduced motion.
-function stagger(el, cap = 10) {
- if (REDUCED.matches) return;
- Array.from(el.children).forEach((c, i) => {
- c.style.setProperty("--i", String(Math.min(i, cap)));
- c.classList.add("rise");
- });
-}
-
-/* ---------- receipts ---------- */
-function receiptHtml(confidence, observations, sourceCount) {
- const pct = Math.round(confidence * 100);
- const low = pct < 55;
- const src = sourceCount != null ? ` · ${sourceCount} source${sourceCount === 1 ? "" : "s"}` : "";
- const across = sourceCount != null ? ` across ${sourceCount} source${sourceCount === 1 ? "" : "s"}` : "";
- return `<span class="receipt${low ? " low" : ""}" title="confidence ${pct}% — observed ${observations} time${observations === 1 ? "" : "s"}${esc(across)}; repeated observations raise confidence">` +
- `<span class="meter"><i style="width:${pct}%"></i></span>` +
- `<span class="pct">${pct}%</span><span>×${observations}${esc(src)}</span></span>`;
-}
-
-function maybeShowReceiptLegend() {
- if (localStorage.getItem("cg-receipt-legend")) return;
- $("receipt-legend").classList.remove("hidden");
-}
-$("legend-dismiss").addEventListener("click", () => {
- localStorage.setItem("cg-receipt-legend", "1");
- $("receipt-legend").classList.add("hidden");
-});
-
-/* ---------- stats + provider ---------- */
-async function refreshStats() {
- const s = await (await api("/api/stats")).json();
- $("stat-nodes").textContent = s.nodes;
- $("stat-edges").textContent = s.edges;
- $("stat-docs").textContent = s.documents;
- const badge = $("provider-badge");
- if (s.provider.canSynthesize) {
- badge.textContent = "answers: " + s.provider.model;
- badge.classList.add("cloud");
- } else {
- badge.textContent = "local mode";
- if (!localStorage.getItem("cg-local-note-off")) $("local-note").classList.remove("hidden");
- }
- setAppState(s);
- return s;
-}
-$("local-note-close").addEventListener("click", () => {
- localStorage.setItem("cg-local-note-off", "1");
- $("local-note").classList.add("hidden");
-});
-$("provider-badge").addEventListener("click", () => {
- // In local mode the badge re-opens the dismissed explainer.
- if ($("provider-badge").classList.contains("cloud")) return;
- localStorage.removeItem("cg-local-note-off");
- $("local-note").classList.remove("hidden");
-});
-
-/* ---------- graph ---------- */
-function nodeVisual(n) {
- return {
- id: n.id,
- label: n.name,
- title: `${n.name} — ${n.type}\n${n.summary}\n×${n.observations} observations · ${Math.round(n.confidence * 100)}% confidence`,
- size: 9 + Math.min(n.observations, 10) * 1.8,
- color: highlighted.has(n.id) ? COLOR_HIT : COLOR_BASE,
- _data: n,
- };
-}
-
-async function refreshGraph({ diff = false } = {}) {
- const g = await (await api("/api/graph")).json();
- $("atlas-empty").classList.toggle("hidden", g.nodes.length > 0);
-
- const freshIds = [];
- if (diff) {
- for (const n of g.nodes) {
- const before = prevObs.get(n.id);
- if (before === undefined || n.observations > before) freshIds.push(n.id);
- }
- }
- prevObs = new Map(g.nodes.map((n) => [n.id, n.observations]));
-
- const nodes = g.nodes.map(nodeVisual);
- const edges = g.edges.map((e, i) => ({
- id: "e" + i,
- from: e.sourceId,
- to: e.targetId,
- title: `${e.relation}${e.description ? " — " + e.description : ""}\n×${e.observations} · ${Math.round(e.confidence * 100)}%`,
- width: 1 + Math.min(e.observations - 1, 4) * 0.6,
- }));
-
- if (!network) {
- nodesDs = new vis.DataSet(nodes);
- edgesDs = new vis.DataSet(edges);
- network = new vis.Network($("graph"), { nodes: nodesDs, edges: edgesDs }, {
- nodes: {
- shape: "dot",
- font: { face: "system-ui", size: 12, color: "#1c2422" },
- borderWidth: 1.5,
- },
- edges: {
- color: { color: "#c9d1c9", highlight: "#2e6b4e", hover: "#8b968f" },
- arrows: { to: { enabled: true, scaleFactor: 0.5 } },
- smooth: { type: "continuous" },
- },
- interaction: { hover: true, tooltipDelay: 120 },
- physics: {
- solver: "forceAtlas2Based",
- forceAtlas2Based: { gravitationalConstant: -42, springLength: 110, damping: 0.5 },
- stabilization: { iterations: 180 },
- },
- });
- network.on("click", (params) => {
- if (params.nodes.length) showNodeCard(params.nodes[0]);
- else hideNodeCard();
- });
- } else {
- // Update in place so the layout doesn't reshuffle under the user.
- const existing = new Set(nodesDs.getIds());
- for (const n of nodes) existing.has(n.id) ? nodesDs.update(n) : nodesDs.add(n);
- edgesDs.clear();
- edgesDs.add(edges);
- }
-
- if (freshIds.length) pulseFresh(freshIds);
- return g;
-}
-
-function pulseFresh(ids) {
- nodesDs.update(ids.map((id) => ({ id, color: COLOR_FRESH, borderWidth: 3 })));
- if (network) network.fit({ nodes: ids, animation: REDUCED.matches ? false : { duration: 600 }, maxZoomLevel: 1.2 });
- setTimeout(() => {
- nodesDs.update(ids.map((id) => ({
- id,
- color: highlighted.has(id) ? COLOR_HIT : COLOR_BASE,
- borderWidth: 1.5,
- })));
- }, 2600);
-}
-
-function highlightRetrieval(bundle) {
- highlighted = new Set(bundle.nodes.map((n) => n.id));
- const semantic = new Set(bundle.nodes.filter((n) => n.via === "semantic").map((n) => n.id));
- nodesDs.update(nodesDs.getIds().map((id) => ({
- id,
- color: semantic.has(id) ? COLOR_HIT : highlighted.has(id) ? COLOR_EXPANDED : COLOR_BASE,
- opacity: highlighted.has(id) ? 1 : 0.35,
- })));
- if (highlighted.size && network) {
- network.fit({ nodes: [...highlighted], animation: REDUCED.matches ? false : { duration: 700 }, maxZoomLevel: 1.1 });
- }
-}
-
-function focusNode(id) {
- if (!network) return;
- network.focus(id, { scale: 1.3, animation: REDUCED.matches ? false : { duration: 500 } });
- network.selectNodes([id]);
- showNodeCard(id);
-}
-
-function showNodeCard(id) {
- const v = nodesDs.get(id);
- if (!v || !v._data) return;
- const n = v._data;
- $("nc-name").textContent = n.name;
- $("nc-type").textContent = n.type;
- $("nc-summary").textContent = n.summary;
- $("nc-receipt").outerHTML = receiptHtml(n.confidence, n.observations).replace('class="receipt', 'id="nc-receipt" class="receipt');
- $("nc-prov").textContent = "";
- $("node-card").classList.add("show");
-}
-function hideNodeCard() { $("node-card").classList.remove("show"); }
-$("node-card-close").addEventListener("click", hideNodeCard);
-
-/* ---------- evidence tabs ---------- */
-function activateTab(name) {
- document.querySelectorAll("#evidence-tabs .tab").forEach((b) =>
- b.classList.toggle("active", b.dataset.tab === name));
- ["sources", "facts", "edges"].forEach((t) =>
- $("tab-" + t).classList.toggle("hidden", t !== name));
-}
-document.querySelectorAll("#evidence-tabs .tab").forEach((b) =>
- b.addEventListener("click", () => activateTab(b.dataset.tab)));
-/* ---------- ask ---------- */
-function renderAnswerText(text, sourceCount) {
- // Minimal, safe rendering: escape first, then paragraphs, bullets, bold, [n] citations.
- const lines = esc(text).split(/\n/);
- let html = "", inList = false;
- const flushList = () => { if (inList) { html += "</ul>"; inList = false; } };
- let para = [];
- const flushPara = () => {
- if (para.length) { html += "<p>" + para.join("<br>") + "</p>"; para = []; }
- };
- for (const raw of lines) {
- const line = raw.trim();
- if (!line) { flushPara(); flushList(); continue; }
- if (/^[-*•]\s+/.test(line)) {
- flushPara();
- if (!inList) { html += "<ul>"; inList = true; }
- html += "<li>" + line.replace(/^[-*•]\s+/, "") + "</li>";
- } else {
- flushList();
- para.push(line);
- }
- }
- flushPara(); flushList();
- html = html.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
- html = html.replace(/\[(\d+)\]/g, (m, d) => {
- const i = Number(d);
- return i >= 1 && i <= sourceCount ? `<button class="cite" data-src="${i}">${i}</button>` : m;
- });
- return html;
-}
-
-function renderBundle(bundle) {
- const facts = $("facts");
- facts.innerHTML = bundle.nodes.map((n) => `
- <div class="fact">
- <div class="fact-top">
- <span class="fact-name" data-node="${esc(n.id)}">${esc(n.name)}</span>
- <span class="fact-type">${esc(n.type)}</span>
- <span class="fact-via${n.via === "expanded" ? " expanded" : ""}">${n.via === "semantic" ? "matched" : "connected"}</span>
- ${receiptHtml(n.confidence, n.observations, n.provenance.length)}
- </div>
- <div class="fact-summary">${esc(n.summary)}</div>
- </div>`).join("");
- $("facts-count").textContent = bundle.nodes.length;
- facts.querySelectorAll(".fact-name").forEach((el) =>
- el.addEventListener("click", () => focusNode(el.dataset.node)));
-
- const byId = new Map(bundle.nodes.map((n) => [n.id, n.name]));
- const edgeRows = bundle.edges
- .filter((e) => byId.has(e.sourceId) && byId.has(e.targetId))
- .slice(0, 10)
- .map((e) => `<div class="edge-line"><b>${esc(byId.get(e.sourceId))}</b> <span class="rel">—${esc(e.relation)}→</span> <b>${esc(byId.get(e.targetId))}</b></div>`);
- $("edges").innerHTML = edgeRows.join("");
- $("edges-count").textContent = edgeRows.length;
- $("tab-btn-edges").classList.toggle("hidden", !edgeRows.length);
-
- $("sources").innerHTML = bundle.chunks.map((c, i) => `
- <div class="source" id="source-${i + 1}">
- <div class="source-top">
- <span class="source-num">[${i + 1}]</span>
- <span class="source-title">${esc(c.documentTitle)}</span>
- </div>
- <div class="source-text">${esc(c.text)}</div>
- <button class="source-more" type="button">show more</button>
- </div>`).join("");
- $("sources-count").textContent = bundle.chunks.length;
- $("sources").querySelectorAll(".source-more").forEach((btn) =>
- btn.addEventListener("click", () => {
- const card = btn.closest(".source");
- card.classList.toggle("open");
- btn.textContent = card.classList.contains("open") ? "show less" : "show more";
- }));
-
- activateTab("sources");
- // Cascade the evidence in after the prose (see stagger()).
- stagger($("sources"));
- stagger($("facts"));
- stagger($("edges"));
-}
-
-$("ask-form").addEventListener("submit", async (ev) => {
- ev.preventDefault();
- const q = $("ask-input").value.trim();
- if (!q) return;
- const btn = $("ask-btn");
- btn.disabled = true;
- $("answer-wrap").classList.remove("hidden");
- $("answer-q").textContent = "Q · " + q;
- $("answer-body").innerHTML = "";
- $("answer-skeleton").classList.remove("hidden");
- $("evidence").classList.add("hidden");
- $("facts").innerHTML = ""; $("edges").innerHTML = ""; $("sources").innerHTML = "";
- try {
- const r = await api("/api/ask", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ question: q }),
- });
- const data = await r.json();
- if (data.error) throw new Error(data.error);
- const { answer, bundle } = data;
- $("answer-skeleton").classList.add("hidden");
- const hasEvidence = bundle.nodes.length > 0 || bundle.chunks.length > 0;
- if (!hasEvidence) {
- $("answer-body").innerHTML = '<p class="thinking">Nothing in your documents answers this yet. <button class="linklike" id="no-results-add" type="button">Add the documents</button> that would — then ask again.</p>';
- const add = $("no-results-add");
- if (add) add.addEventListener("click", () => {
- $("ingest-panel").open = true;
- $("ingest-panel").scrollIntoView({ behavior: REDUCED.matches ? "auto" : "smooth", block: "center" });
- });
- } else if (answer) {
- $("answer-body").innerHTML = renderAnswerText(answer, bundle.chunks.length);
- $("answer-body").querySelectorAll(".cite").forEach((el) =>
- el.addEventListener("click", () => {
- activateTab("sources");
- const card = $("source-" + el.dataset.src);
- if (!card) return;
- card.scrollIntoView({ behavior: REDUCED.matches ? "auto" : "smooth", block: "center" });
- card.classList.add("flash");
- setTimeout(() => card.classList.remove("flash"), 1400);
- }));
- } else {
- $("answer-body").innerHTML = '<p class="thinking">Local mode — here is everything your documents hold on this, with receipts. For a written answer, run Ollama or set OPENROUTER_API_KEY.</p>';
- }
- stagger($("answer-body"), 4);
- $("evidence").classList.toggle("hidden", !hasEvidence);
- renderBundle(bundle);
- highlightRetrieval(bundle);
- if (hasEvidence) maybeShowReceiptLegend();
- } catch (e) {
- $("answer-skeleton").classList.add("hidden");
- $("answer-body").innerHTML = '<p class="thinking">Something went wrong: ' + esc(e.message) + "</p>";
- } finally {
- btn.disabled = false;
- }
-});
-
-/* ---------- teach ---------- */
-$("teach-btn").addEventListener("click", async () => {
- const learning = $("teach-input").value.trim();
- const status = $("teach-status");
- if (!learning) return;
- $("teach-btn").disabled = true;
- status.className = "grow-status";
- status.textContent = "Extracting entities and folding them in…";
- try {
- const r = await api("/api/contribute", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ learning }),
- });
- const data = await r.json();
- if (data.error) throw new Error(data.error);
- status.className = "grow-status ok";
- status.textContent =
- `✓ saved — ${data.nodesCreated} new fact${data.nodesCreated === 1 ? "" : "s"}, ` +
- `${data.nodesUpdated} reinforced, ${data.edgesCreated + data.edgesUpdated} connections touched`;
- $("teach-input").value = "";
- await refreshStats();
- await refreshGraph({ diff: true });
- await refreshDocs();
- } catch (e) {
- status.className = "grow-status err";
- status.textContent = "Could not save: " + e.message + "\n" + MODEL_HINT;
- } finally {
- $("teach-btn").disabled = false;
- }
-});
-
-/* ---------- ingest progress (shared by server-path and upload) ---------- */
-let progressItems = [];
-function progressShow() {
- progressItems = [];
- $("progress-fill").style.width = "0%";
- $("progress-rows").innerHTML = "";
- $("ingest-progress").classList.remove("hidden");
-}
-function renderProgress(frac) {
- if (frac != null) $("progress-fill").style.width = Math.round(frac * 100) + "%";
- $("progress-rows").innerHTML = progressItems.slice(-4).map((it) => `
- <div class="progress-row ${it.state}">
- <span class="icon">${it.state === "busy" ? '<span class="spinner"></span>' : it.state === "ok" ? "✓" : "✗"}</span>
- <span>${esc(it.name)}${it.msg ? " — " + esc(it.msg) : ""}</span>
- </div>`).join("");
-}
-function progressFile(index, total, name) {
- for (const it of progressItems) if (it.state === "busy") it.state = "ok";
- progressItems.push({ name, state: "busy" });
- renderProgress(total ? index / total : 0);
-}
-function progressFail(msg) {
- const last = progressItems[progressItems.length - 1];
- if (last) { last.state = "err"; last.msg = msg; }
- renderProgress(null);
-}
-function progressDone() {
- for (const it of progressItems) if (it.state === "busy") it.state = "ok";
- renderProgress(1);
-}
-
-function setIngestControlsDisabled(disabled) {
- ingestBusy = disabled;
- [$("dropzone"), $("choose-folder-btn"), $("ingest-btn")].forEach((b) => { b.disabled = disabled; });
-}
-
-/* ---------- ingest a path on the server ---------- */
-$("ingest-btn").addEventListener("click", async () => {
- const dir = $("ingest-input").value.trim();
- const status = $("ingest-status");
- if (!dir) return;
- setIngestControlsDisabled(true);
- status.className = "grow-status";
- status.textContent = "Scanning " + dir + " …";
- progressShow();
- try {
- const r = await api("/api/ingest-dir", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ dir, watch: $("watch-check").checked }),
- });
- if (!r.ok) {
- const err = await r.json().catch(() => ({}));
- throw new Error(err.error || r.statusText);
- }
- const reader = r.body.getReader();
- const decoder = new TextDecoder();
- let buf = "";
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buf += decoder.decode(value, { stream: true });
- let nl;
- while ((nl = buf.indexOf("\n")) >= 0) {
- const line = buf.slice(0, nl); buf = buf.slice(nl + 1);
- if (!line.trim()) continue;
- const ev = JSON.parse(line);
- if (ev.type === "progress") {
- status.textContent = "";
- progressFile(ev.index, ev.total, ev.file.split("/").pop());
- // Grow the graph live between files.
- refreshGraph({ diff: true }).catch(() => {});
- refreshStats().catch(() => {});
- } else if (ev.type === "done") {
- progressDone();
- const fresh = ev.results.filter((x) => !x.skipped);
- const skipped = ev.results.length - fresh.length;
- const nodes = fresh.reduce((a, x) => a + x.nodesCreated + x.nodesUpdated, 0);
- status.className = "grow-status ok";
- status.textContent =
- `✓ ${fresh.length} document${fresh.length === 1 ? "" : "s"} added` +
- (skipped ? ` (${skipped} already known, skipped)` : "") +
- `, ${nodes} facts written or reinforced` +
- (ev.watching ? " — now watching this folder for changes" : "");
- } else if (ev.type === "error") {
- throw new Error(ev.error);
- }
- }
- }
- await refreshStats();
- await refreshGraph({ diff: true });
- await refreshDocs();
- } catch (e) {
- progressFail(e.message);
- status.className = "grow-status err";
- status.textContent = "Could not add documents: " + e.message + "\n" + MODEL_HINT;
- } finally {
- setIngestControlsDisabled(false);
- }
-});
-
-/* ---------- browser upload (dropzone / pickers → server ingest) ---------- */
-const UPLOAD_ACCEPT = /\.(pdf|md|markdown|txt)$/i;
-
-// Base64-encode file bytes in chunks (fromCharCode.apply chokes on huge arrays).
-// The relative path (from a folder pick or live sync) keys the document on the
-// server, so same-named files in different subfolders stay distinct.
-async function fileToPayload(file) {
- const relPath = file._relPath || file.webkitRelativePath || undefined;
- if (/\.pdf$/i.test(file.name)) {
- const bytes = new Uint8Array(await file.arrayBuffer());
- let binary = "";
- for (let i = 0; i < bytes.length; i += 0x8000) {
- binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
- }
- return { name: file.name, relPath, dataBase64: btoa(binary) };
- }
- return { name: file.name, relPath, text: await file.text() };
-}
-
-$("dropzone").addEventListener("click", () => $("files-input").click());
-$("dropzone").addEventListener("dragover", (e) => {
- e.preventDefault();
- if (!ingestBusy) $("dropzone").classList.add("drag");
-});
-$("dropzone").addEventListener("dragleave", () => $("dropzone").classList.remove("drag"));
-$("dropzone").addEventListener("drop", (e) => {
- e.preventDefault();
- $("dropzone").classList.remove("drag");
- if (ingestBusy) return;
- uploadFiles(Array.from(e.dataTransfer.files || []), "files");
-});
-$("choose-folder-btn").addEventListener("click", async () => {
- // Chromium: keep a handle to the picked folder and live-sync it while the
- // tab is open. Elsewhere: fall back to the classic one-shot folder upload.
- if (!window.showDirectoryPicker) return $("folder-input").click();
- try {
- const handle = await showDirectoryPicker({ mode: "read" });
- await startFolderSync(handle);
- } catch (e) {
- if (e.name !== "AbortError") {
- $("ingest-status").className = "grow-status err";
- $("ingest-status").textContent = "Could not open the folder: " + e.message;
- }
- }
-});
-$("files-input").addEventListener("change", (e) => uploadPicked(e, "files"));
-$("folder-input").addEventListener("change", (e) => uploadPicked(e, "folder"));
-
-function uploadPicked(e, kind) {
- const all = Array.from(e.target.files || []);
- e.target.value = ""; // let the user re-pick the same selection later
- uploadFiles(all, kind);
-}
-
-async function uploadFiles(all, kind) {
- const files = all.filter((f) => UPLOAD_ACCEPT.test(f.name));
- const status = $("ingest-status");
- if (!files.length) {
- status.className = "grow-status err";
- status.textContent = all.length
- ? `No .pdf, .md, or .txt files in that ${kind === "folder" ? "folder" : "selection"}.`
- : `No ${kind === "folder" ? "folder" : "files"} selected.`;
- return;
- }
- setIngestControlsDisabled(true);
- status.className = "grow-status";
- status.textContent = "";
- progressShow();
- let ok = 0, skipped = 0, failed = 0, nodes = 0;
- try {
- for (let i = 0; i < files.length; i++) {
- const f = files[i];
- progressFile(i, files.length, f.name);
- try {
- const r = await api("/api/ingest-upload", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(await fileToPayload(f)),
- });
- if (!r.ok) {
- const er = await r.json().catch(() => ({}));
- throw new Error(er.error || r.statusText);
- }
- const data = await r.json();
- if (data.result && !data.result.skipped) {
- ok++;
- nodes += (data.result.nodesCreated || 0) + (data.result.nodesUpdated || 0);
- } else {
- skipped++;
- }
- // Grow the graph live between files, like the server-folder ingest.
- refreshGraph({ diff: true }).catch(() => {});
- refreshStats().catch(() => {});
- } catch (err) {
- failed++;
- progressFail(err.message);
- }
- }
- progressDone();
- status.className = failed ? "grow-status err" : "grow-status ok";
- status.textContent =
- `✓ ${ok} document${ok === 1 ? "" : "s"} added` +
- (skipped ? ` (${skipped} already known, skipped)` : "") +
- (failed ? `, ${failed} failed` : "") +
- `, ${nodes} facts written or reinforced` +
- (failed ? "\n" + MODEL_HINT : "");
- await refreshStats();
- await refreshGraph({ diff: true });
- await refreshDocs();
- } finally {
- setIngestControlsDisabled(false);
- }
-}
-
-/* ---------- live folder sync (File System Access API, Chromium) ----------
- The picked folder's handle stays with the page: every few seconds it is
- re-scanned and files whose size/mtime moved are re-uploaded, so the graph
- keeps evolving while the tab is open. Deletions are ignored on purpose —
- the graph is append-only. */
-const SYNC_INTERVAL_MS = 5000;
-const SYNC_SKIP = new Set(["node_modules", "dist", "build", "out", "target", "vendor", "coverage", "__pycache__", "venv"]);
-const SYNC_MAX_BYTES = 1_000_000;
-let folderSync = null; // { handle, name, state: Map<rel, sig>, timer, busy }
-
-async function collectFolderFiles(handle, name) {
- const files = [];
- const state = new Map();
- async function walk(dir, prefix) {
- for await (const entry of dir.values()) {
- if (entry.name.startsWith(".") || SYNC_SKIP.has(entry.name)) continue;
- if (entry.kind === "directory") {
- await walk(entry, prefix + entry.name + "/");
- } else if (UPLOAD_ACCEPT.test(entry.name)) {
- const f = await entry.getFile();
- if (f.size > SYNC_MAX_BYTES) continue;
- const rel = prefix + entry.name;
- state.set(rel, f.size + ":" + f.lastModified);
- f._relPath = name + "/" + rel;
- f._rel = rel;
- files.push(f);
- }
- }
- }
- await walk(handle, "");
- return { files, state };
-}
+ <section class="rise" style="--i:1">
+ <h2 class="head">How it works</h2>
+ <ol class="steps">
+ <li>
+ <span class="num">1</span>
+ <span class="body"><b>Point it at your repo.</b> It builds <code>.context/</code> — one
+ markdown file per system, API, or concept, linked together. The files are the nodes, the
+ links are the edges. That's the whole graph.</span>
+ </li>
+ <li>
+ <span class="num">2</span>
+ <span class="body"><b>Commit it.</b> The graph is just files in git, so git is the sync.
+ Anyone who clones the repo has it, and CI keeps it fresh — when a change moves something,
+ you see it in the graph diff right next to the code, in the same PR.</span>
+ </li>
+ <li>
+ <span class="num">3</span>
+ <span class="body"><b>Your agent reads it before doing work</b> — so it starts knowing the
+ codebase instead of rediscovering it from scratch every time.</span>
+ </li>
+ </ol>
+ </section>
-function renderSyncPill(msg) {
- $("folder-sync-text").textContent = msg;
- $("folder-sync").classList.remove("hidden");
-}
+ <section class="rise" style="--i:2">
+ <h2 class="head">Setup</h2>
+<pre><span class="c"># in your repo</span>
+context-graph init <span class="c"># builds .context/ from your code</span>
+git add .context &amp;&amp; git commit
-async function startFolderSync(handle) {
- stopFolderSync();
- const session = { handle, name: handle.name, state: new Map(), timer: null, busy: false };
- folderSync = session;
- renderSyncPill(`Scanning “${handle.name}”…`);
- const { files, state } = await collectFolderFiles(handle, handle.name);
- session.state = state;
- await uploadFiles(files, "folder"); // the usual progress UI for the first sweep
- if (folderSync !== session) return; // stopped or replaced mid-sweep
- session.timer = setInterval(syncTick, SYNC_INTERVAL_MS);
- renderSyncPill(`Watching “${handle.name}” — ${state.size} files. Edits sync while this tab is open.`);
-}
+<span class="c"># keep it honest — fails CI if the graph is stale</span>
+context-graph check</pre>
+ <p class="after">That's it. Anyone who clones the repo gets <code>.context/</code> for free.
+ Point your agent at it and it reads the graph before working.</p>
+ </section>
-function stopFolderSync() {
- if (!folderSync) return;
- clearInterval(folderSync.timer);
- folderSync = null;
- $("folder-sync").classList.add("hidden");
-}
-$("folder-sync-stop").addEventListener("click", stopFolderSync);
+ <section class="rise" style="--i:3">
+ <h2 class="head">The proof</h2>
+ <p class="prose">Same model, same tools, same tasks. The only difference is whether the agent
+ got the graph first. On a real 344-file repo it cut tool calls 31%, cost 23%, and latency 17%.</p>
+ <p class="prose">The graph isn't magic — it's just that reading a few linked files beats
+ rediscovering the codebase from scratch every single time.</p>
+ </section>
-async function syncTick() {
- const session = folderSync;
- if (!session || session.busy || ingestBusy) return;
- session.busy = true;
- try {
- const { files, state } = await collectFolderFiles(session.handle, session.name);
- const changed = files.filter((f) => session.state.get(f._rel) !== state.get(f._rel));
- session.state = state; // forgets deleted entries too — harmless, append-only
- let synced = 0;
- for (const f of changed) {
- if (folderSync !== session) return; // stopped mid-batch
- const r = await api("/api/ingest-upload", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify(await fileToPayload(f)),
- });
- if (r.ok) {
- const data = await r.json();
- if (data.result && !data.result.skipped) synced++;
- }
- }
- if (synced && folderSync === session) {
- refreshStats().catch(() => {});
- refreshGraph({ diff: true }).catch(() => {});
- refreshDocs().catch(() => {});
- const at = new Date().toLocaleTimeString();
- renderSyncPill(`Watching “${session.name}” — synced ${synced} change${synced === 1 ? "" : "s"} at ${at}.`);
- }
- } catch (e) {
- // Permission revoked or the folder went away — stop cleanly, not noisily.
- if (folderSync === session) {
- clearInterval(session.timer);
- folderSync = null;
- renderSyncPill(`Sync stopped: ${e.message}`);
- }
- return;
- }
- session.busy = false;
-}
+ <section class="rise" style="--i:4">
+ <h2 class="head">Runs locally</h2>
+ <p class="prose">Everything runs on your machine. No accounts, no cloud calls, no keys. Building
+ the graph uses a local model (Ollama); if you'd rather use a cloud model for better summaries,
+ set a key and it'll use it. Local stays the default.</p>
+ </section>
-/* ---------- documents ---------- */
-const DOCS_PREVIEW = 10;
-let docsExpanded = false;
-let docsCache = [];
-function renderDocs() {
- const shown = docsExpanded ? docsCache : docsCache.slice(0, DOCS_PREVIEW);
- $("docs").innerHTML = shown.map((d) => `
- <div class="doc-row">
- <span class="t" title="${esc(d.source)}">${esc(d.title)}</span>
- <span class="d">${esc((d.createdAt || "").slice(0, 10))}</span>
- </div>`).join("");
- const toggle = $("docs-toggle");
- toggle.classList.toggle("hidden", docsCache.length <= DOCS_PREVIEW);
- toggle.textContent = docsExpanded ? "Show fewer" : `Show all ${docsCache.length}`;
-}
-$("docs-toggle").addEventListener("click", () => {
- docsExpanded = !docsExpanded;
- renderDocs();
-});
-async function refreshDocs() {
- docsCache = await (await api("/api/documents")).json();
- $("docs-count").textContent = docsCache.length;
- renderDocs();
- if (docsCache.length && !$("ask-input").value) {
- const t = docsCache[0].title.length > 42 ? docsCache[0].title.slice(0, 42) + "…" : docsCache[0].title;
- $("ask-input").placeholder = `What does “${t}” cover?`;
- }
-}
+ <footer>Context&middot;Graph &mdash; a context graph that lives in your repo.</footer>
-/* ---------- boot ---------- */
-(async function boot() {
- $("legend-sample").innerHTML = receiptHtml(0.87, 4, 2);
- try {
- await refreshStats();
- if (typeof vis === "undefined") {
- $("graph").innerHTML = '<p style="padding:40px;color:#5c6862;font-family:var(--serif)">The graph view needs internet access once (vis-network CDN). Everything else works offline.</p>';
- } else {
- await refreshGraph();
- }
- await refreshDocs();
- } catch (e) {
- console.error(e);
- // Stats unavailable (e.g. token prompt cancelled) — default to the ask
- // layout so the page still works once access is sorted out.
- if (!appState) setAppState({ documents: 1 });
- }
- // Shareable question links: /?q=how+do+we+deploy auto-asks on load.
- const q = new URLSearchParams(location.search).get("q");
- if (q) {
- $("ask-input").value = q;
- $("ask-form").requestSubmit();
- }
-})();
+</main>
-/* ---------- live updates ----------
- When the server runs with an auto-watcher (CONTEXT_GRAPH_WATCH=1), the graph
- grows on its own as watched folders change. A cheap stats poll notices and
- refreshes the heavier graph/docs views only when the counts actually moved. */
-let liveCounts = null;
-setInterval(async () => {
- try {
- const s = await refreshStats();
- const counts = `${s.documents}|${s.nodes}|${s.edges}|${s.chunks}`;
- if (liveCounts !== null && counts !== liveCounts) {
- refreshGraph({ diff: true }).catch(() => {});
- refreshDocs().catch(() => {});
- }
- liveCounts = counts;
- } catch {
- /* offline or token prompt pending — try again next tick */
- }
-}, 10_000);
-</script>
</body>
</html>