Skip to content

The open-source app everyone uses to manage agents at work

[codex] Add LLM Wiki plugin package to master (#5716)

Dotta508355b8fcc5
diff --git a/Dockerfile b/Dockerfile
index 95c452c95f..e367910e5e 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -34,6 +34,7 @@ COPY packages/adapters/pi-local/package.json packages/adapters/pi-local/
COPY packages/plugins/sdk/package.json packages/plugins/sdk/
COPY --parents packages/plugins/sandbox-providers/./*/package.json packages/plugins/sandbox-providers/
COPY packages/plugins/paperclip-plugin-fake-sandbox/package.json packages/plugins/paperclip-plugin-fake-sandbox/
+COPY packages/plugins/plugin-llm-wiki/package.json packages/plugins/plugin-llm-wiki/
COPY patches/ patches/
RUN pnpm install --frozen-lockfile
diff --git a/packages/plugins/plugin-llm-wiki/.gitignore b/packages/plugins/plugin-llm-wiki/.gitignore
new file mode 100644
index 0000000000..d9e2126a32
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/.gitignore
@@ -0,0 +1,4 @@
+dist
+node_modules
+.paperclip-sdk
+screenshots
diff --git a/packages/plugins/plugin-llm-wiki/README.md b/packages/plugins/plugin-llm-wiki/README.md
new file mode 100644
index 0000000000..6e0aabd416
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/README.md
@@ -0,0 +1,160 @@
+# LLM Wiki
+
+Local-file LLM Wiki plugin for source ingestion, wiki browsing, query, lint, and maintenance workflows.
+
+## Scope
+
+This package is the standalone home for LLM Wiki behavior. Wiki-specific routes,
+UI, prompts, tools, local-folder templates, migrations, fixtures, and tests live
+here rather than in Paperclip core.
+
+The alpha surface includes:
+
+- manifest-declared Wiki page, sidebar entry, and settings page
+- trusted local folder declaration for `raw/`, `wiki/`, `AGENTS.md`, `IDEA.md`, `wiki/index.md`, and `wiki/log.md`
+- plugin database namespace migration for wiki instances, sources, pages, operations, query sessions, and resource bindings
+- managed `Wiki Maintainer` agent, managed `LLM Wiki` project, and paused managed routines for wiki update processing, lint, and index refresh
+- plugin-operation issue creation using `surfaceVisibility: "plugin_operation"`
+- local source capture into `raw/` with metadata rows in the plugin DB namespace
+- opt-in company-scoped Paperclip event ingestion controls for issues, comments, and documents; event ingestion is disabled by default and routes captured raw provenance into the default space only
+- manual Paperclip project/root issue distillation and bounded backfill actions with explicit work items, operation issues, source caps, and estimated cost recording
+- Paperclip-derived distillation (cursor windows, manual `distill-now`, backfill) always writes into the default wiki space in Phase 1; non-default spaces remain on manual / raw-file ingest until per-space Paperclip ingestion profiles ship
+- Paperclip-derived distillation maintains `wiki/projects/<slug>/standup.md` as the executive current-state view for each represented project, alongside durable `wiki/projects/<slug>/index.md` knowledge pages
+- wiki page writes with plugin path validation, atomic local-folder writes, metadata/revision rows, backlink extraction, and optional stale-hash protection
+- wiki tools for search/read/write/propose patch/source/log/index/backlinks workflows
+
+## Phase 5 Security Gate
+
+Paperclip-derived text ingestion stays limited to issue titles/descriptions, issue comments, and issue documents.
+
+- Issue attachments/assets are **metadata-only** in Phase 5.
+- Issue work products are **metadata-only** in Phase 5.
+- The wiki must not fetch `/api/assets/:id/content`, dereference work-product `url` fields, or store those capability-bearing links in source bundles/snapshots.
+
+The accepted policy lives in [doc/plans/2026-05-06-llm-wiki-paperclip-asset-security-gate.md](../../../doc/plans/2026-05-06-llm-wiki-paperclip-asset-security-gate.md).
+
+## Development
+
+```bash
+pnpm install
+pnpm dev # watch builds
+pnpm dev:ui # local dev server with hot-reload events
+pnpm test
+```
+
+From the Paperclip repo root:
+
+```bash
+pnpm --filter @paperclipai/plugin-llm-wiki typecheck
+pnpm --filter @paperclipai/plugin-llm-wiki test
+pnpm --filter @paperclipai/plugin-llm-wiki build
+```
+
+## Alpha Verification
+
+Run these commands from the Paperclip repo root before handing off alpha plugin
+changes:
+
+```bash
+pnpm --filter @paperclipai/plugin-llm-wiki typecheck
+pnpm --filter @paperclipai/plugin-llm-wiki test
+pnpm --filter @paperclipai/plugin-llm-wiki build
+```
+
+The focused Vitest suite covers:
+
+- standalone package boundaries and package-local harness dependencies
+- required local folder bootstrap writes
+- raw source capture plus ingest metadata persistence
+- hidden plugin-operation issue creation for ingest/query/file-as-page workflows
+- disabled and enabled Paperclip event ingestion paths
+- managed routine declarations, manual distill/backfill work items, source cap handling, and backfill project/date scoping
+- atomic page writes, metadata/revision rows, backlinks, and stale-hash refusal
+- query session creation, run-id recording, stream event forwarding, and completion updates
+- filing a streamed query answer back into the wiki through a hidden operation
+
+Remaining alpha gaps:
+
+- Browser screenshot capture is maintained separately under `tests/screenshots`;
+ generated `screenshots/` outputs are local artifacts and are ignored by git.
+- Host-level plugin install and live agent invocation still need Paperclip
+ server/runtime smoke coverage when preparing a release candidate.
+
+
+
+## Install Into Paperclip
+
+```bash
+curl -X POST http://127.0.0.1:3100/api/plugins/install \
+ -H "Content-Type: application/json" \
+ -d '{"packageName":"/Users/dotta/paperclip/.paperclip/worktrees/PAP-3179-design-a-llm-wiki-plugin/packages/plugins/plugin-llm-wiki","isLocalPath":true}'
+```
+
+## Build Options
+
+- `pnpm build` uses esbuild presets from `@paperclipai/plugin-sdk/bundlers`.
+- `pnpm build:rollup` uses rollup presets from the same SDK.
+
+After changing manifest-loaded assets such as skills, agent instructions, or
+templates, recompile the local plugin before re-enabling it:
+
+```bash
+pnpm --filter @paperclipai/plugin-llm-wiki build
+```
+
+The package-local `dist/` directory is ignored by git, but local Paperclip
+installs load the compiled `dist/manifest.js` and `dist/worker.js` files at
+runtime. If activation failed before the rebuild, re-enable the plugin or
+restart the Paperclip dev server so the host imports the fresh bundle.
+
+## Local File Layout
+
+```text
+<configured-wiki-root>/
+ AGENTS.md
+ IDEA.md
+ .gitignore
+ raw/
+ .gitkeep
+ wiki/
+ index.md
+ log.md
+ sources/
+ .gitkeep
+ projects/
+ .gitkeep
+ <project-slug>/
+ index.md
+ standup.md
+ decisions.md
+ history.md
+ entities/
+ .gitkeep
+ concepts/
+ .gitkeep
+ synthesis/
+ .gitkeep
+```
+
+Use the settings page or `bootstrap-root` action to configure the folder and
+write the starter files. The plugin uses Paperclip's local folder API for path
+containment, symlink checks, read/write validation, and atomic writes.
+
+Bootstrap preserves existing files rather than overwriting operator edits. The
+default first-install skeleton is copied from the vanilla LLM Wiki layout, with
+`CLAUDE.md` renamed to `AGENTS.md` and Paperclip project overviews, standups,
+decisions, and history kept together under `wiki/projects/<slug>/`.
+
+## Managed Agent Instructions
+
+Plugin-managed agent instruction bundles live under:
+
+```text
+agents/<agent-key>/AGENTS.md
+```
+
+For this plugin the Wiki Maintainer source bundle is `agents/wiki-maintainer/AGENTS.md`.
+Any additional files in that folder are installed as sibling instruction files
+for the managed agent. The settings health check reports drift from these
+defaults, and resetting the managed agent asks for confirmation before replacing
+customized instructions.
diff --git a/packages/plugins/plugin-llm-wiki/agents/wiki-maintainer/AGENTS.md b/packages/plugins/plugin-llm-wiki/agents/wiki-maintainer/AGENTS.md
new file mode 100644
index 0000000000..3c8b6e88f1
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/agents/wiki-maintainer/AGENTS.md
@@ -0,0 +1,65 @@
+# LLM Wiki Maintainer
+
+You are the maintainer of this personal wiki. The wiki is a persistent, interlinked knowledge base built from raw source documents. You read sources, extract knowledge, and integrate it into evolving wiki pages. The user curates sources, directs analysis, and asks questions; you handle the bookkeeping.
+
+## Wiki Root
+
+The wiki root folder is:
+
+`{{localFolders.wiki-root.path}}`
+
+The wiki's default operating schema is:
+
+`{{localFolders.wiki-root.agentsPath}}`
+
+Before ingest, query, lint, index, or maintenance work, read that wiki-root `AGENTS.md` file. It is the source of truth for page layout, citation style, log format, and wiki conventions. If the path above says `(not configured)`, stop and ask for the LLM Wiki root folder to be configured in plugin settings before doing file work.
+
+## Identity
+
+- You maintain the LLM Wiki, not the application codebase.
+- You keep raw source material in `raw/` immutable.
+- You keep Paperclip project operating summaries current in `wiki/projects/<project-slug>/standup.md`.
+- You create and update durable wiki pages under `wiki/`.
+- You keep `wiki/index.md` and `wiki/log.md` accurate after changes.
+- You cite wiki pages and raw sources in answers.
+
+## Operating Loop
+
+1. Resolve the configured wiki root folder and the target space named in the operation issue.
+2. Read the target space's `AGENTS.md`.
+3. Read the target space's `wiki/index.md` and recent `wiki/log.md` entries before choosing files.
+4. Pick the right operation skill (see below) and follow it.
+5. Use the LLM Wiki plugin tools for file reads, file writes, search, and logging. Always pass the operation issue's `wikiId` and `spaceSlug` arguments.
+6. Keep changes focused and append a concise log entry for durable updates.
+
+All operation paths are relative to the target space root. Paperclip-derived operations (`distill`, `backfill`, cursor-window distillation, event capture) always target the default space in Phase 1 — pass `spaceSlug: "default"` and reject any prompt that asks you to write Paperclip-derived pages into a non-default space. Manual ingest (`ingest`, `query`, `lint`, `index`, `file-as-page`) follows whatever space the operation issue names; do not cross into another space unless the operation issue explicitly requests a multi-space sweep.
+
+For Paperclip-derived project work, maintain two layers:
+
+- `wiki/projects/<project-slug>/standup.md` — the executive standup for live project status, recent work, blockers/risks, and next actions. Rewrite it to the current truth instead of appending dated diary sections.
+- `wiki/projects/<project-slug>/index.md` and optional `wiki/projects/<project-slug>/decisions.md` / `history.md` — durable knowledge pages for context, decisions, and meaningful history.
+
+Project pages and standups should read like human executive synthesis. Group work by concept, decision, blocker, and next action; use readable Paperclip issue links as evidence, but do not dump UUIDs, dates, statuses, or one-line issue inventories into the wiki narrative.
+
+## Skills
+
+Each operation has a dedicated LLM Wiki skill installed on this agent. Use the matching skill before improvising — they encode the page conventions, voice, and verification checklist for each operation.
+
+- `wiki-ingest` — a captured `raw/` source needs to become durable wiki pages.
+- `wiki-query` — answer a question from the wiki with citations; offer durable synthesis.
+- `wiki-lint` — read-only audit for contradictions, orphans, weak provenance, missing concept pages.
+- `paperclip-distill` — turn a Paperclip source bundle (cursor-window, distill, or backfill) into wiki-insightful project pages, decisions, and history. Replaces the stiff, datestamp-heavy templated output.
+- `index-refresh` — keep `wiki/index.md` accurate and scannable.
+
+The operation issue's `originKind` (`plugin:llm-wiki:operation:<type>`) tells you which skill to load:
+
+| `operationType` | Skill |
+| --------------------- | ---------------------------------------------- |
+| `ingest` | `wiki-ingest` |
+| `query` | `wiki-query` |
+| `lint` | `wiki-lint` |
+| `distill`, `backfill` | `paperclip-distill` |
+| `index` | `index-refresh` |
+| `file-as-page` | `wiki-query` (filing synthesis from an answer) |
+
+If a skill conflicts with this file, follow this file for identity. If a skill conflicts with the wiki-root `AGENTS.md`, follow that for page structure and voice.
diff --git a/packages/plugins/plugin-llm-wiki/esbuild.config.mjs b/packages/plugins/plugin-llm-wiki/esbuild.config.mjs
new file mode 100644
index 0000000000..b5cfd36ed9
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/esbuild.config.mjs
@@ -0,0 +1,17 @@
+import esbuild from "esbuild";
+import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
+
+const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
+const watch = process.argv.includes("--watch");
+
+const workerCtx = await esbuild.context(presets.esbuild.worker);
+const manifestCtx = await esbuild.context(presets.esbuild.manifest);
+const uiCtx = await esbuild.context(presets.esbuild.ui);
+
+if (watch) {
+ await Promise.all([workerCtx.watch(), manifestCtx.watch(), uiCtx.watch()]);
+ console.log("esbuild watch mode enabled for worker, manifest, and ui");
+} else {
+ await Promise.all([workerCtx.rebuild(), manifestCtx.rebuild(), uiCtx.rebuild()]);
+ await Promise.all([workerCtx.dispose(), manifestCtx.dispose(), uiCtx.dispose()]);
+}
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/.gitignore b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/.gitignore
new file mode 100644
index 0000000000..ef42c26de5
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/.gitignore
@@ -0,0 +1,3 @@
+.DS_Store
+.obsidian/workspace*
+.obsidian/cache
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/AGENTS.md b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/AGENTS.md
new file mode 100644
index 0000000000..3c2aa2739a
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/AGENTS.md
@@ -0,0 +1,137 @@
+# AGENTS.md — LLM Wiki Schema
+
+You are the maintainer of this personal wiki. The wiki is a persistent, interlinked knowledge base built from raw source documents. You read sources, extract knowledge, and integrate it into evolving wiki pages. The user curates sources, directs analysis, and asks questions; you handle the bookkeeping.
+
+The underlying pattern is described in `IDEA.md` (Karpathy's "LLM Wiki" gist). Read it if you need the philosophy; this file is the operational schema.
+
+## Layout
+
+```
+.
+├── AGENTS.md # this file — your operating instructions
+├── IDEA.md # the pattern this wiki follows
+├── raw/ # immutable source documents (you read, never write)
+└── wiki/ # generated, owned by you
+ ├── index.md # catalog of all pages
+ ├── log.md # append-only timeline of operations
+ ├── sources/ # one summary page per source
+ ├── projects/ # Paperclip project overviews, standups, decisions, and history
+ │ └── <slug>/
+ │ ├── index.md
+ │ ├── standup.md
+ │ ├── decisions.md
+ │ └── history.md
+ ├── entities/ # people, organizations, products, places
+ ├── concepts/ # ideas, frameworks, definitions
+ └── synthesis/ # cross-cutting analysis, comparisons, theses
+```
+
+The subdirectories under `wiki/` are conventional, not enforced. Add new categories (e.g. `wiki/papers/`) as the domain demands — and update this file when you do.
+
+Paperclip project material lives only under `wiki/projects/<project-slug>/`. Do not create a top-level `projects/` directory.
+
+- `wiki/projects/<project-slug>/standup.md` is the executive-level project standup. It answers where the project stands today, what changed recently, current blockers/risks, and the next concrete actions.
+- `wiki/projects/<project-slug>/index.md` is the durable knowledge page. It explains what the project is, why it exists, decisions made, history, and long-lived context.
+- Keep the two linked. A standup should link to the durable project page, and the durable project page should point at the current standup for live status.
+- Update `standup.md` whenever Paperclip project, issue, plan, comment, blocker, approval, or status history materially changes the project's current state. Do not append endless dated sections; rewrite it as today's concise status.
+- Project writing should be editorial and concept-grouped. Do not dump issue queues, UUIDs, raw metadata, or date-heavy ledgers into project pages. Reference Paperclip tasks with human issue links where useful, but make headings and paragraphs explain the concepts, decisions, completed work, next work, and blockers in plain executive language.
+
+## Page conventions
+
+- **Filename:** kebab-case, `.md`. Treat filenames as stable; do not rename without updating backlinks.
+- **Frontmatter:** YAML at the top of every wiki page.
+ ```yaml
+ ---
+ title: Human-readable title
+ type: source | project | entity | concept | synthesis
+ tags: [tag-a, tag-b]
+ sources: [raw/doc.pdf] # for source pages and synthesis pages
+ created: YYYY-MM-DD
+ updated: YYYY-MM-DD
+ ---
+ ```
+- **Cross-links:** Obsidian-style `[[wiki/entities/some-page]]` (or `[[some-page]]` when unambiguous). When you mention a concept or entity that has — or should have — its own page, link it.
+- **Citations:** cite the source inline whenever a claim comes from one: `(see [[wiki/sources/some-slug]])`.
+- **Voice:** terse, factual, neutral. The wiki is reference material, not narrative.
+
+## Operations
+
+### Ingest
+
+Triggered when the user drops a file in `raw/` and asks to process it (or just says "ingest").
+
+1. Read the source end to end.
+2. Briefly discuss key takeaways with the user before writing — confirm what to emphasize.
+3. Create `wiki/sources/<slug>.md`: a summary page (~300–800 words) covering the source's main claims, structure, and notable quotes or data.
+4. Update or create relevant pages in `entities/`, `concepts/`, `synthesis/`. A typical ingest touches 5–15 pages.
+5. Add any new pages to `wiki/index.md`.
+6. Append a log entry:
+ ```
+ ## [YYYY-MM-DD] ingest | <source title>
+ - source: raw/<filename>
+ - new pages: [[...]], [[...]]
+ - updated pages: [[...]], [[...]]
+ - notes: <one-line synthesis, contradiction flagged, or open question>
+ ```
+
+When new information contradicts an existing page, do **not** silently overwrite. Flag the contradiction on the page (a `> ⚠ contradicted by [[...]] (YYYY-MM-DD)` callout) and note it in the log.
+
+### Project updates
+
+Triggered when Paperclip project, issue, plan, comment, blocker, or status history is distilled into the wiki.
+
+1. Create or update `wiki/projects/<project-slug>/standup.md` first. Every Paperclip project represented in the wiki must have one. Keep stable sections for executive readout, what changed, decisions, blockers/risks, next actions, and links.
+2. Create or update `wiki/projects/<project-slug>/index.md` as the durable project overview. Keep stable sections for overview, current direction, workstreams, decisions, open risks/blockers, and references.
+3. Use `wiki/projects/<project-slug>/decisions.md` for accepted/rejected plans, architectural decisions, approval outcomes, and reversals when a project has enough decision history to warrant a separate page.
+4. Use `wiki/projects/<project-slug>/history.md` for compact narrative history of meaningful project movement. Group by phase or concept; do not mirror every issue comment.
+5. Always cite Paperclip source material with readable links to issue identifiers, document keys, issue documents, approvals, and raw/source pages. Do not put UUIDs in prose unless the UUID itself is the subject.
+6. Update `wiki/index.md` under Projects and append a `project` log entry to `wiki/log.md`.
+
+### Query
+
+The user asks a question. You:
+
+1. Read `wiki/index.md` to find candidate pages.
+2. Read those pages; follow links as needed.
+3. Answer with citations back to wiki pages, and ultimately to raw sources.
+4. If the answer is substantial (a comparison, analysis, new synthesis), offer to file it under `wiki/synthesis/` so the work compounds rather than disappearing into chat history.
+
+If the wiki lacks what the question needs, say so plainly and suggest sources to ingest or web searches to run.
+
+### Lint
+
+On request ("lint", "health check"), scan for:
+
+- contradictions across pages
+- claims a newer source has superseded
+- orphan pages (not linked from `index.md` or any other page)
+- concepts mentioned in multiple places but lacking a dedicated page
+- broken `[[wiki-links]]`
+- gaps where a web search or new source would help
+
+Report findings as a checklist and ask the user which to act on.
+
+## index.md format
+
+A catalog organized by category. Each line: `- [[path]] — one-line summary`. Keep it scannable; this is your primary navigation aid before opening pages.
+
+## log.md format
+
+Append new entries to the bottom. Every entry header follows:
+
+```
+## [YYYY-MM-DD] <op> | <subject>
+```
+
+so `grep "^## \[" wiki/log.md | tail -10` always returns recent activity. Operations: `ingest`, `query`, `lint`, `setup`, `refactor`.
+
+## Customization
+
+This schema is intentionally generic. As the wiki's domain becomes clear, evolve it:
+
+- add domain-specific page types and subdirectories
+- adjust frontmatter fields
+- specify preferred output formats for queries (Marp slides, charts, tables)
+- record workflow preferences (one-at-a-time vs batch ingest, level of human supervision)
+
+When you and the user agree on a convention, **write it into this file**. The schema is the wiki's source of truth for how the wiki is built.
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/IDEA.md b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/IDEA.md
new file mode 100644
index 0000000000..35ef071290
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/IDEA.md
@@ -0,0 +1,75 @@
+# LLM Wiki
+
+A pattern for building personal knowledge bases using LLMs.
+
+This is an idea file, it is designed to be copy pasted to your own LLM Agent (e.g. OpenAI Codex, Claude Code, OpenCode / Pi, or etc.). Its goal is to communicate the high level idea, but your agent will build out the specifics in collaboration with you.
+
+## The core idea
+
+Most people's experience with LLMs and documents looks like RAG: you upload a collection of files, the LLM retrieves relevant chunks at query time, and generates an answer. This works, but the LLM is rediscovering knowledge from scratch on every question. There's no accumulation. Ask a subtle question that requires synthesizing five documents, and the LLM has to find and piece together the relevant fragments every time. Nothing is built up. NotebookLM, ChatGPT file uploads, and most RAG systems work this way.
+
+The idea here is different. Instead of just retrieving from raw documents at query time, the LLM **incrementally builds and maintains a persistent wiki** — a structured, interlinked collection of markdown files that sits between you and the raw sources. When you add a new source, the LLM doesn't just index it for later retrieval. It reads it, extracts the key information, and integrates it into the existing wiki — updating entity pages, revising topic summaries, noting where new data contradicts old claims, strengthening or challenging the evolving synthesis. The knowledge is compiled once and then *kept current*, not re-derived on every query.
+
+This is the key difference: **the wiki is a persistent, compounding artifact.** The cross-references are already there. The contradictions have already been flagged. The synthesis already reflects everything you've read. The wiki keeps getting richer with every source you add and every question you ask.
+
+You never (or rarely) write the wiki yourself — the LLM writes and maintains all of it. You're in charge of sourcing, exploration, and asking the right questions. The LLM does all the grunt work — the summarizing, cross-referencing, filing, and bookkeeping that makes a knowledge base actually useful over time. In practice, I have the LLM agent open on one side and Obsidian open on the other. The LLM makes edits based on our conversation, and I browse the results in real time — following links, checking the graph view, reading the updated pages. Obsidian is the IDE; the LLM is the programmer; the wiki is the codebase.
+
+This can apply to a lot of different contexts. A few examples:
+
+- **Personal**: tracking your own goals, health, psychology, self-improvement — filing journal entries, articles, podcast notes, and building up a structured picture of yourself over time.
+- **Research**: going deep on a topic over weeks or months — reading papers, articles, reports, and incrementally building a comprehensive wiki with an evolving thesis.
+- **Reading a book**: filing each chapter as you go, building out pages for characters, themes, plot threads, and how they connect. By the end you have a rich companion wiki. Think of fan wikis like [Tolkien Gateway](https://tolkiengateway.net/wiki/Main_Page) — thousands of interlinked pages covering characters, places, events, languages, built by a community of volunteers over years. You could build something like that personally as you read, with the LLM doing all the cross-referencing and maintenance.
+- **Business/team**: an internal wiki maintained by LLMs, fed by Slack threads, meeting transcripts, project documents, customer calls. Possibly with humans in the loop reviewing updates. The wiki stays current because the LLM does the maintenance that no one on the team wants to do.
+- **Competitive analysis, due diligence, trip planning, course notes, hobby deep-dives** — anything where you're accumulating knowledge over time and want it organized rather than scattered.
+
+## Architecture
+
+There are three layers:
+
+**Raw sources** — your curated collection of source documents. Articles, papers, images, data files. These are immutable — the LLM reads from them but never modifies them. This is your source of truth.
+
+**The wiki** — a directory of LLM-generated markdown files. Summaries, entity pages, concept pages, comparisons, an overview, a synthesis. The LLM owns this layer entirely. It creates pages, updates them when new sources arrive, maintains cross-references, and keeps everything consistent. You read it; the LLM writes it.
+
+**The schema** — a document (e.g. AGENTS.md for Paperclip agents) that tells the LLM how the wiki is structured, what the conventions are, and what workflows to follow when ingesting sources, answering questions, or maintaining the wiki. This is the key configuration file — it's what makes the LLM a disciplined wiki maintainer rather than a generic chatbot. You and the LLM co-evolve this over time as you figure out what works for your domain.
+
+## Operations
+
+**Ingest.** You drop a new source into the raw collection and tell the LLM to process it. An example flow: the LLM reads the source, discusses key takeaways with you, writes a summary page in the wiki, updates the index, updates relevant entity and concept pages across the wiki, and appends an entry to the log. A single source might touch 10-15 wiki pages. Personally I prefer to ingest sources one at a time and stay involved — I read the summaries, check the updates, and guide the LLM on what to emphasize. But you could also batch-ingest many sources at once with less supervision. It's up to you to develop the workflow that fits your style and document it in the schema for future sessions.
+
+**Query.** You ask questions against the wiki. The LLM searches for relevant pages, reads them, and synthesizes an answer with citations. Answers can take different forms depending on the question — a markdown page, a comparison table, a slide deck (Marp), a chart (matplotlib), a canvas. The important insight: **good answers can be filed back into the wiki as new pages.** A comparison you asked for, an analysis, a connection you discovered — these are valuable and shouldn't disappear into chat history. This way your explorations compound in the knowledge base just like ingested sources do.
+
+**Lint.** Periodically, ask the LLM to health-check the wiki. Look for: contradictions between pages, stale claims that newer sources have superseded, orphan pages with no inbound links, important concepts mentioned but lacking their own page, missing cross-references, data gaps that could be filled with a web search. The LLM is good at suggesting new questions to investigate and new sources to look for. This keeps the wiki healthy as it grows.
+
+## Indexing and logging
+
+Two special files help the LLM (and you) navigate the wiki as it grows. They serve different purposes:
+
+**index.md** is content-oriented. It's a catalog of everything in the wiki — each page listed with a link, a one-line summary, and optionally metadata like date or source count. Organized by category (entities, concepts, sources, etc.). The LLM updates it on every ingest. When answering a query, the LLM reads the index first to find relevant pages, then drills into them. This works surprisingly well at moderate scale (~100 sources, ~hundreds of pages) and avoids the need for embedding-based RAG infrastructure.
+
+**log.md** is chronological. It's an append-only record of what happened and when — ingests, queries, lint passes. A useful tip: if each entry starts with a consistent prefix (e.g. `## [2026-04-02] ingest | Article Title`), the log becomes parseable with simple unix tools — `grep "^## \[" log.md | tail -5` gives you the last 5 entries. The log gives you a timeline of the wiki's evolution and helps the LLM understand what's been done recently.
+
+## Optional: CLI tools
+
+At some point you may want to build small tools that help the LLM operate on the wiki more efficiently. A search engine over the wiki pages is the most obvious one — at small scale the index file is enough, but as the wiki grows you want proper search. [qmd](https://github.com/tobi/qmd) is a good option: it's a local search engine for markdown files with hybrid BM25/vector search and LLM re-ranking, all on-device. It has both a CLI (so the LLM can shell out to it) and an MCP server (so the LLM can use it as a native tool). You could also build something simpler yourself — the LLM can help you vibe-code a naive search script as the need arises.
+
+## Tips and tricks
+
+- **Obsidian Web Clipper** is a browser extension that converts web articles to markdown. Very useful for quickly getting sources into your raw collection.
+- **Download images locally.** In Obsidian Settings → Files and links, set "Attachment folder path" to a fixed directory (e.g. `raw/assets/`). Then in Settings → Hotkeys, search for "Download" to find "Download attachments for current file" and bind it to a hotkey (e.g. Ctrl+Shift+D). After clipping an article, hit the hotkey and all images get downloaded to local disk. This is optional but useful — it lets the LLM view and reference images directly instead of relying on URLs that may break. Note that LLMs can't natively read markdown with inline images in one pass — the workaround is to have the LLM read the text first, then view some or all of the referenced images separately to gain additional context. It's a bit clunky but works well enough.
+- **Obsidian's graph view** is the best way to see the shape of your wiki — what's connected to what, which pages are hubs, which are orphans.
+- **Marp** is a markdown-based slide deck format. Obsidian has a plugin for it. Useful for generating presentations directly from wiki content.
+- **Dataview** is an Obsidian plugin that runs queries over page frontmatter. If your LLM adds YAML frontmatter to wiki pages (tags, dates, source counts), Dataview can generate dynamic tables and lists.
+- The wiki is just a git repo of markdown files. You get version history, branching, and collaboration for free.
+
+## Why this works
+
+The tedious part of maintaining a knowledge base is not the reading or the thinking — it's the bookkeeping. Updating cross-references, keeping summaries current, noting when new data contradicts old claims, maintaining consistency across dozens of pages. Humans abandon wikis because the maintenance burden grows faster than the value. LLMs don't get bored, don't forget to update a cross-reference, and can touch 15 files in one pass. The wiki stays maintained because the cost of maintenance is near zero.
+
+The human's job is to curate sources, direct the analysis, ask good questions, and think about what it all means. The LLM's job is everything else.
+
+The idea is related in spirit to Vannevar Bush's Memex (1945) — a personal, curated knowledge store with associative trails between documents. Bush's vision was closer to this than to what the web became: private, actively curated, with the connections between documents as valuable as the documents themselves. The part he couldn't solve was who does the maintenance. The LLM handles that.
+
+
+## Note
+
+This document is intentionally abstract. It describes the idea, not a specific implementation. The exact directory structure, the schema conventions, the page formats, the tooling — all of that will depend on your domain, your preferences, and your LLM of choice. Everything mentioned above is optional and modular — pick what's useful, ignore what isn't. For example: your sources might be text-only, so you don't need image handling at all. Your wiki might be small enough that the index file is all you need, no search engine required. You might not care about slide decks and just want markdown pages. You might want a completely different set of output formats. The right way to use this is to share it with your LLM agent and work together to instantiate a version that fits your needs. The document's only job is to communicate the pattern. Your LLM can figure out the rest.
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/raw/.gitkeep b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/raw/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/raw/plugin-boundaries.md b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/raw/plugin-boundaries.md
new file mode 100644
index 0000000000..89d8a8d984
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/raw/plugin-boundaries.md
@@ -0,0 +1,3 @@
+# Raw Source
+
+LLM Wiki code must live in the standalone plugin package.
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/areas/knowledge.md b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/areas/knowledge.md
new file mode 100644
index 0000000000..46462345bf
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/areas/knowledge.md
@@ -0,0 +1,3 @@
+# Knowledge
+
+The wiki stores durable knowledge as local markdown files.
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/concepts/.gitkeep b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/concepts/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/concepts/plugin-boundaries.md b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/concepts/plugin-boundaries.md
new file mode 100644
index 0000000000..595ee78cf1
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/concepts/plugin-boundaries.md
@@ -0,0 +1,3 @@
+# Plugin Boundaries
+
+LLM Wiki routes, prompts, UI, tools, and migrations belong inside the plugin.
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/entities/.gitkeep b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/entities/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/index.md b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/index.md
new file mode 100644
index 0000000000..54f1f8a304
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/index.md
@@ -0,0 +1,23 @@
+# Index
+
+Catalog of durable wiki pages and linked project standups. Updated on every ingest or Paperclip distill.
+
+## Sources
+
+_(none yet)_
+
+## Projects
+
+_(none yet)_
+
+## Entities
+
+_(none yet)_
+
+## Concepts
+
+_(none yet)_
+
+## Synthesis
+
+_(none yet)_
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/log.md b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/log.md
new file mode 100644
index 0000000000..6b101ab13a
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/log.md
@@ -0,0 +1,10 @@
+# Log
+
+Append-only chronological record of wiki operations.
+
+## [2026-05-03] setup | wiki initialized
+- created `AGENTS.md` (schema)
+- created `raw/` for source documents
+- created `wiki/` skeleton: `index.md`, `log.md`, `sources/`, `projects/`, `entities/`, `concepts/`, `synthesis/`
+- created `wiki/projects/` for Paperclip project overviews and standups
+- pattern reference: `IDEA.md` (Karpathy "LLM Wiki" gist, https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f)
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/projects/.gitkeep b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/projects/.gitkeep
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/projects/.gitkeep
@@ -0,0 +1 @@
+
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/sources/.gitkeep b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/sources/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/synthesis/.gitkeep b/packages/plugins/plugin-llm-wiki/fixtures/basic-root/wiki/synthesis/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/plugins/plugin-llm-wiki/migrations/001_llm_wiki.sql b/packages/plugins/plugin-llm-wiki/migrations/001_llm_wiki.sql
new file mode 100644
index 0000000000..01d5067cdc
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/migrations/001_llm_wiki.sql
@@ -0,0 +1,101 @@
+CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_instances (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL,
+ root_folder_key text NOT NULL DEFAULT 'wiki-root',
+ configured_root_path text,
+ schema_version integer NOT NULL DEFAULT 1,
+ settings jsonb NOT NULL DEFAULT '{}'::jsonb,
+ managed_agent_key text,
+ managed_project_key text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (company_id, wiki_id)
+);
+
+CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_sources (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL,
+ source_type text NOT NULL,
+ title text,
+ url text,
+ raw_path text NOT NULL,
+ content_hash text NOT NULL,
+ status text NOT NULL DEFAULT 'captured',
+ metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_pages (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL,
+ path text NOT NULL,
+ title text,
+ page_type text,
+ frontmatter jsonb NOT NULL DEFAULT '{}'::jsonb,
+ source_refs jsonb NOT NULL DEFAULT '[]'::jsonb,
+ backlinks jsonb NOT NULL DEFAULT '[]'::jsonb,
+ content_hash text,
+ current_revision_id uuid,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (company_id, wiki_id, path)
+);
+
+CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_page_revisions (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL,
+ page_id uuid REFERENCES plugin_llm_wiki_8f50da974f.wiki_pages(id) ON DELETE CASCADE,
+ operation_id uuid,
+ path text NOT NULL,
+ content_hash text NOT NULL,
+ summary text,
+ metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_operations (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL,
+ operation_type text NOT NULL,
+ status text NOT NULL,
+ hidden_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
+ project_id uuid REFERENCES public.projects(id) ON DELETE SET NULL,
+ run_ids jsonb NOT NULL DEFAULT '[]'::jsonb,
+ cost_cents integer NOT NULL DEFAULT 0,
+ warnings jsonb NOT NULL DEFAULT '[]'::jsonb,
+ affected_pages jsonb NOT NULL DEFAULT '[]'::jsonb,
+ metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_query_sessions (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL,
+ hidden_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
+ agent_session_id text,
+ status text NOT NULL DEFAULT 'active',
+ filed_outputs jsonb NOT NULL DEFAULT '[]'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE TABLE plugin_llm_wiki_8f50da974f.wiki_resource_bindings (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL,
+ resource_kind text NOT NULL,
+ resource_key text NOT NULL,
+ resolved_id uuid,
+ metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (company_id, wiki_id, resource_kind, resource_key)
+);
diff --git a/packages/plugins/plugin-llm-wiki/migrations/002_paperclip_distillation.sql b/packages/plugins/plugin-llm-wiki/migrations/002_paperclip_distillation.sql
new file mode 100644
index 0000000000..aa8c269bb5
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/migrations/002_paperclip_distillation.sql
@@ -0,0 +1,88 @@
+CREATE TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL,
+ source_scope text NOT NULL,
+ scope_key text NOT NULL,
+ project_id uuid REFERENCES public.projects(id) ON DELETE CASCADE,
+ root_issue_id uuid REFERENCES public.issues(id) ON DELETE CASCADE,
+ source_kind text NOT NULL DEFAULT 'paperclip_issue_history',
+ last_processed_at timestamptz,
+ last_observed_at timestamptz,
+ pending_event_count integer NOT NULL DEFAULT 0,
+ last_successful_run_id uuid,
+ last_source_hash text,
+ metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (company_id, wiki_id, source_scope, scope_key, source_kind)
+);
+
+CREATE TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL,
+ work_item_kind text NOT NULL,
+ status text NOT NULL DEFAULT 'pending',
+ priority text NOT NULL DEFAULT 'medium',
+ project_id uuid REFERENCES public.projects(id) ON DELETE CASCADE,
+ root_issue_id uuid REFERENCES public.issues(id) ON DELETE CASCADE,
+ requested_by_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
+ idempotency_key text,
+ metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (company_id, wiki_id, idempotency_key)
+);
+
+CREATE TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_runs (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL,
+ cursor_id uuid REFERENCES plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors(id) ON DELETE SET NULL,
+ work_item_id uuid REFERENCES plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items(id) ON DELETE SET NULL,
+ project_id uuid REFERENCES public.projects(id) ON DELETE SET NULL,
+ root_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
+ source_window_start timestamptz,
+ source_window_end timestamptz,
+ source_hash text,
+ status text NOT NULL,
+ operation_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
+ retry_count integer NOT NULL DEFAULT 0,
+ cost_cents integer NOT NULL DEFAULT 0,
+ warnings jsonb NOT NULL DEFAULT '[]'::jsonb,
+ metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE TABLE plugin_llm_wiki_8f50da974f.paperclip_source_snapshots (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL,
+ distillation_run_id uuid REFERENCES plugin_llm_wiki_8f50da974f.paperclip_distillation_runs(id) ON DELETE CASCADE,
+ project_id uuid REFERENCES public.projects(id) ON DELETE SET NULL,
+ root_issue_id uuid REFERENCES public.issues(id) ON DELETE SET NULL,
+ source_hash text NOT NULL,
+ max_characters integer NOT NULL,
+ clipped boolean NOT NULL DEFAULT false,
+ source_refs jsonb NOT NULL DEFAULT '[]'::jsonb,
+ bundle_markdown text NOT NULL,
+ metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL,
+ project_id uuid REFERENCES public.projects(id) ON DELETE CASCADE,
+ root_issue_id uuid REFERENCES public.issues(id) ON DELETE CASCADE,
+ page_path text NOT NULL,
+ last_applied_source_hash text,
+ last_distillation_run_id uuid REFERENCES plugin_llm_wiki_8f50da974f.paperclip_distillation_runs(id) ON DELETE SET NULL,
+ metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (company_id, wiki_id, page_path)
+);
diff --git a/packages/plugins/plugin-llm-wiki/migrations/003_spaces.sql b/packages/plugins/plugin-llm-wiki/migrations/003_spaces.sql
new file mode 100644
index 0000000000..e9c4a0fd20
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/migrations/003_spaces.sql
@@ -0,0 +1,236 @@
+CREATE TABLE IF NOT EXISTS plugin_llm_wiki_8f50da974f.wiki_spaces (
+ id uuid PRIMARY KEY,
+ company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
+ wiki_id text NOT NULL DEFAULT 'default',
+ slug text NOT NULL,
+ display_name text NOT NULL,
+ space_type text NOT NULL DEFAULT 'local_folder',
+ folder_mode text NOT NULL DEFAULT 'managed_subfolder',
+ root_folder_key text NOT NULL DEFAULT 'wiki-root',
+ path_prefix text,
+ configured_root_path text,
+ access_scope text NOT NULL DEFAULT 'shared',
+ owner_user_id text,
+ owner_agent_id uuid REFERENCES public.agents(id) ON DELETE SET NULL,
+ team_key text,
+ settings jsonb NOT NULL DEFAULT '{}'::jsonb,
+ status text NOT NULL DEFAULT 'active',
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ UNIQUE (company_id, wiki_id, slug)
+);
+
+CREATE INDEX IF NOT EXISTS wiki_spaces_company_status_idx
+ ON plugin_llm_wiki_8f50da974f.wiki_spaces (company_id, wiki_id, status);
+
+WITH wiki_pairs AS (
+ SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.wiki_instances
+ UNION
+ SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.wiki_sources
+ UNION
+ SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.wiki_pages
+ UNION
+ SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.wiki_page_revisions
+ UNION
+ SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.wiki_operations
+ UNION
+ SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.wiki_query_sessions
+ UNION
+ SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors
+ UNION
+ SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items
+ UNION
+ SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.paperclip_distillation_runs
+ UNION
+ SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.paperclip_source_snapshots
+ UNION
+ SELECT company_id, wiki_id FROM plugin_llm_wiki_8f50da974f.paperclip_page_bindings
+)
+INSERT INTO plugin_llm_wiki_8f50da974f.wiki_spaces
+ (id, company_id, wiki_id, slug, display_name, space_type, folder_mode, root_folder_key, path_prefix, access_scope, status)
+SELECT (
+ substr(md5(company_id::text || ':' || wiki_id || ':default'), 1, 8) || '-' ||
+ substr(md5(company_id::text || ':' || wiki_id || ':default'), 9, 4) || '-' ||
+ '4' || substr(md5(company_id::text || ':' || wiki_id || ':default'), 14, 3) || '-' ||
+ '8' || substr(md5(company_id::text || ':' || wiki_id || ':default'), 18, 3) || '-' ||
+ substr(md5(company_id::text || ':' || wiki_id || ':default'), 21, 12)
+ )::uuid,
+ company_id,
+ wiki_id,
+ 'default',
+ 'default',
+ 'local_folder',
+ 'managed_subfolder',
+ 'wiki-root',
+ NULL,
+ 'shared',
+ 'active'
+FROM wiki_pairs
+ON CONFLICT (company_id, wiki_id, slug) DO NOTHING;
+
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_sources ADD COLUMN IF NOT EXISTS space_id uuid;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages ADD COLUMN IF NOT EXISTS space_id uuid;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_page_revisions ADD COLUMN IF NOT EXISTS space_id uuid;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_operations ADD COLUMN IF NOT EXISTS space_id uuid;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_query_sessions ADD COLUMN IF NOT EXISTS space_id uuid;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors ADD COLUMN IF NOT EXISTS space_id uuid;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items ADD COLUMN IF NOT EXISTS space_id uuid;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_runs ADD COLUMN IF NOT EXISTS space_id uuid;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_source_snapshots ADD COLUMN IF NOT EXISTS space_id uuid;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings ADD COLUMN IF NOT EXISTS space_id uuid;
+
+UPDATE plugin_llm_wiki_8f50da974f.wiki_sources t
+SET space_id = s.id
+FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
+WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
+
+UPDATE plugin_llm_wiki_8f50da974f.wiki_pages t
+SET space_id = s.id
+FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
+WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
+
+UPDATE plugin_llm_wiki_8f50da974f.wiki_page_revisions t
+SET space_id = s.id
+FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
+WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
+
+UPDATE plugin_llm_wiki_8f50da974f.wiki_operations t
+SET space_id = s.id
+FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
+WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
+
+UPDATE plugin_llm_wiki_8f50da974f.wiki_query_sessions t
+SET space_id = s.id
+FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
+WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
+
+UPDATE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors t
+SET space_id = s.id
+FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
+WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
+
+UPDATE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items t
+SET space_id = s.id
+FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
+WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
+
+UPDATE plugin_llm_wiki_8f50da974f.paperclip_distillation_runs t
+SET space_id = s.id
+FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
+WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
+
+UPDATE plugin_llm_wiki_8f50da974f.paperclip_source_snapshots t
+SET space_id = s.id
+FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
+WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
+
+UPDATE plugin_llm_wiki_8f50da974f.paperclip_page_bindings t
+SET space_id = s.id
+FROM plugin_llm_wiki_8f50da974f.wiki_spaces s
+WHERE t.company_id = s.company_id AND t.wiki_id = s.wiki_id AND s.slug = 'default' AND t.space_id IS NULL;
+
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_sources ALTER COLUMN space_id SET NOT NULL;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages ALTER COLUMN space_id SET NOT NULL;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_page_revisions ALTER COLUMN space_id SET NOT NULL;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_operations ALTER COLUMN space_id SET NOT NULL;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_query_sessions ALTER COLUMN space_id SET NOT NULL;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors ALTER COLUMN space_id SET NOT NULL;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items ALTER COLUMN space_id SET NOT NULL;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_runs ALTER COLUMN space_id SET NOT NULL;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_source_snapshots ALTER COLUMN space_id SET NOT NULL;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings ALTER COLUMN space_id SET NOT NULL;
+
+DO $$
+DECLARE
+ target record;
+ constraint_name text;
+BEGIN
+ FOR target IN
+ SELECT * FROM (VALUES
+ ('wiki_pages', ARRAY['company_id', 'wiki_id', 'path']::text[]),
+ ('paperclip_distillation_cursors', ARRAY['company_id', 'wiki_id', 'source_scope', 'scope_key', 'source_kind']::text[]),
+ ('paperclip_distillation_work_items', ARRAY['company_id', 'wiki_id', 'idempotency_key']::text[]),
+ ('paperclip_page_bindings', ARRAY['company_id', 'wiki_id', 'page_path']::text[])
+ ) AS targets(table_name, column_names)
+ LOOP
+ FOR constraint_name IN
+ SELECT c.conname
+ FROM pg_constraint c
+ JOIN pg_class t ON t.oid = c.conrelid
+ JOIN pg_namespace n ON n.oid = t.relnamespace
+ WHERE n.nspname = 'plugin_llm_wiki_8f50da974f'
+ AND t.relname = target.table_name
+ AND c.contype = 'u'
+ AND (
+ SELECT array_agg(a.attname ORDER BY constraint_columns.ordinality)::text[]
+ FROM unnest(c.conkey) WITH ORDINALITY AS constraint_columns(attnum, ordinality)
+ JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = constraint_columns.attnum
+ ) = target.column_names
+ LOOP
+ EXECUTE format('ALTER TABLE %I.%I DROP CONSTRAINT %I', 'plugin_llm_wiki_8f50da974f', target.table_name, constraint_name);
+ END LOOP;
+ END LOOP;
+END $$;
+
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages
+ DROP CONSTRAINT IF EXISTS wiki_pages_company_wiki_space_path_key;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages
+ ADD CONSTRAINT wiki_pages_company_wiki_space_path_key UNIQUE (company_id, wiki_id, space_id, path);
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors
+ DROP CONSTRAINT IF EXISTS distillation_cursors_company_wiki_space_scope_key;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors
+ ADD CONSTRAINT distillation_cursors_company_wiki_space_scope_key UNIQUE (company_id, wiki_id, space_id, source_scope, scope_key, source_kind);
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items
+ DROP CONSTRAINT IF EXISTS distillation_work_items_company_wiki_space_idempotency_key;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items
+ ADD CONSTRAINT distillation_work_items_company_wiki_space_idempotency_key UNIQUE (company_id, wiki_id, space_id, idempotency_key);
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings
+ DROP CONSTRAINT IF EXISTS page_bindings_company_wiki_space_page_path_key;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings
+ ADD CONSTRAINT page_bindings_company_wiki_space_page_path_key UNIQUE (company_id, wiki_id, space_id, page_path);
+
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_sources
+ DROP CONSTRAINT IF EXISTS wiki_sources_space_id_fk;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_sources
+ ADD CONSTRAINT wiki_sources_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages
+ DROP CONSTRAINT IF EXISTS wiki_pages_space_id_fk;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_pages
+ ADD CONSTRAINT wiki_pages_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_page_revisions
+ DROP CONSTRAINT IF EXISTS wiki_page_revisions_space_id_fk;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_page_revisions
+ ADD CONSTRAINT wiki_page_revisions_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_operations
+ DROP CONSTRAINT IF EXISTS wiki_operations_space_id_fk;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_operations
+ ADD CONSTRAINT wiki_operations_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_query_sessions
+ DROP CONSTRAINT IF EXISTS wiki_query_sessions_space_id_fk;
+ALTER TABLE plugin_llm_wiki_8f50da974f.wiki_query_sessions
+ ADD CONSTRAINT wiki_query_sessions_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors
+ DROP CONSTRAINT IF EXISTS paperclip_distillation_cursors_space_id_fk;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_cursors
+ ADD CONSTRAINT paperclip_distillation_cursors_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items
+ DROP CONSTRAINT IF EXISTS paperclip_distillation_work_items_space_id_fk;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_work_items
+ ADD CONSTRAINT paperclip_distillation_work_items_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_runs
+ DROP CONSTRAINT IF EXISTS paperclip_distillation_runs_space_id_fk;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_distillation_runs
+ ADD CONSTRAINT paperclip_distillation_runs_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_source_snapshots
+ DROP CONSTRAINT IF EXISTS paperclip_source_snapshots_space_id_fk;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_source_snapshots
+ ADD CONSTRAINT paperclip_source_snapshots_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings
+ DROP CONSTRAINT IF EXISTS paperclip_page_bindings_space_id_fk;
+ALTER TABLE plugin_llm_wiki_8f50da974f.paperclip_page_bindings
+ ADD CONSTRAINT paperclip_page_bindings_space_id_fk FOREIGN KEY (space_id) REFERENCES plugin_llm_wiki_8f50da974f.wiki_spaces(id) ON DELETE CASCADE;
+
+CREATE INDEX IF NOT EXISTS wiki_sources_space_idx ON plugin_llm_wiki_8f50da974f.wiki_sources (company_id, wiki_id, space_id, created_at DESC);
+CREATE INDEX IF NOT EXISTS wiki_operations_space_idx ON plugin_llm_wiki_8f50da974f.wiki_operations (company_id, wiki_id, space_id, created_at DESC);
+CREATE INDEX IF NOT EXISTS wiki_query_sessions_space_idx ON plugin_llm_wiki_8f50da974f.wiki_query_sessions (company_id, wiki_id, space_id, updated_at DESC);
+CREATE INDEX IF NOT EXISTS distillation_runs_space_idx ON plugin_llm_wiki_8f50da974f.paperclip_distillation_runs (company_id, wiki_id, space_id, created_at DESC);
diff --git a/packages/plugins/plugin-llm-wiki/package.json b/packages/plugins/plugin-llm-wiki/package.json
new file mode 100644
index 0000000000..4461c84527
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/package.json
@@ -0,0 +1,47 @@
+{
+ "name": "@paperclipai/plugin-llm-wiki",
+ "version": "0.1.0",
+ "type": "module",
+ "private": true,
+ "description": "Local-file LLM Wiki plugin for source ingestion, wiki browsing, query, lint, and maintenance workflows.",
+ "scripts": {
+ "prebuild": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps",
+ "build": "node ./esbuild.config.mjs",
+ "build:rollup": "rollup -c",
+ "dev": "node ./esbuild.config.mjs --watch",
+ "dev:ui": "paperclip-plugin-dev-server --root . --ui-dir dist/ui --port 4177",
+ "test": "vitest run --config ./vitest.config.ts",
+ "typecheck": "pnpm --filter @paperclipai/plugin-sdk ensure-build-deps && tsc --noEmit"
+ },
+ "paperclipPlugin": {
+ "manifest": "./dist/manifest.js",
+ "worker": "./dist/worker.js",
+ "ui": "./dist/ui/"
+ },
+ "keywords": [
+ "paperclip",
+ "plugin",
+ "automation",
+ "wiki",
+ "knowledge"
+ ],
+ "author": "Paperclip",
+ "license": "MIT",
+ "devDependencies": {
+ "@paperclipai/plugin-sdk": "workspace:*",
+ "@rollup/plugin-node-resolve": "^16.0.1",
+ "@rollup/plugin-typescript": "^12.1.2",
+ "@types/node": "^24.6.0",
+ "@types/react": "^19.0.8",
+ "@types/react-dom": "^19.0.3",
+ "esbuild": "^0.27.3",
+ "react-dom": "^19.0.0",
+ "rollup": "^4.38.0",
+ "tslib": "^2.8.1",
+ "typescript": "^5.7.3",
+ "vitest": "^3.0.5"
+ },
+ "peerDependencies": {
+ "react": ">=18"
+ }
+}
diff --git a/packages/plugins/plugin-llm-wiki/rollup.config.mjs b/packages/plugins/plugin-llm-wiki/rollup.config.mjs
new file mode 100644
index 0000000000..ccee40a744
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/rollup.config.mjs
@@ -0,0 +1,28 @@
+import { nodeResolve } from "@rollup/plugin-node-resolve";
+import typescript from "@rollup/plugin-typescript";
+import { createPluginBundlerPresets } from "@paperclipai/plugin-sdk/bundlers";
+
+const presets = createPluginBundlerPresets({ uiEntry: "src/ui/index.tsx" });
+
+function withPlugins(config) {
+ if (!config) return null;
+ return {
+ ...config,
+ plugins: [
+ nodeResolve({
+ extensions: [".ts", ".tsx", ".js", ".jsx", ".mjs"],
+ }),
+ typescript({
+ tsconfig: "./tsconfig.json",
+ declaration: false,
+ declarationMap: false,
+ }),
+ ],
+ };
+}
+
+export default [
+ withPlugins(presets.rollup.manifest),
+ withPlugins(presets.rollup.worker),
+ withPlugins(presets.rollup.ui),
+].filter(Boolean);
diff --git a/packages/plugins/plugin-llm-wiki/skills/README.md b/packages/plugins/plugin-llm-wiki/skills/README.md
new file mode 100644
index 0000000000..cacfe3ca4d
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/skills/README.md
@@ -0,0 +1,34 @@
+# LLM Wiki Maintainer Skills
+
+This folder is the plugin-level source for LLM Wiki managed company skills. Paperclip installs these skills into the company skill library and syncs them onto the Wiki Maintainer agent. The Wiki Maintainer's identity and operating loop live in `agents/wiki-maintainer/AGENTS.md`; the wiki-root `AGENTS.md` remains the wiki schema for page layout, citation style, and log format.
+
+Each skill is an isolated SKILL.md describing one job — when to invoke it, the inputs that must be true before starting, the steps, and the durable output the operation must leave behind.
+
+## Skill registry
+
+| Skill | When to invoke |
+|---|---|
+| [`wiki-maintainer`](./wiki-maintainer/SKILL.md) | General LLM Wiki maintenance and tool-use guidance shared by the operation skills. |
+| [`wiki-ingest`](./wiki-ingest/SKILL.md) | A new file landed in `raw/` and the operation issue says "ingest" — turn the source into durable wiki pages. |
+| [`wiki-query`](./wiki-query/SKILL.md) | The user asked the wiki a question; answer with citations and offer to file durable synthesis back into `wiki/`. |
+| [`wiki-lint`](./wiki-lint/SKILL.md) | A lint or health-check operation — audit for contradictions, orphan pages, weak provenance, broken links, missing concept pages. |
+| [`paperclip-distill`](./paperclip-distill/SKILL.md) | Cursor-window, distill, or backfill operation on Paperclip activity — write a wiki-insightful project page, decisions log, and history note. |
+| [`index-refresh`](./index-refresh/SKILL.md) | Refresh `wiki/index.md` so each entry has a tight, scannable summary; flag drift between the index and recent log activity. |
+
+## Layering
+
+```
+AGENTS.md (wiki root) ← schema for the wiki itself: page conventions, frontmatter, voice
+ agents/wiki-maintainer/AGENTS.md ← agent identity and operating loop
+ skills/<skill>/SKILL.md ← plugin-managed company skills installed onto the maintainer
+```
+
+When a skill conflicts with the wiki-root `AGENTS.md`, the wiki schema wins for page format/voice and the skill wins for operation flow. When a skill conflicts with the agent's `AGENTS.md`, the agent file wins for identity and the skill wins for the operation procedure.
+
+## Skill conventions
+
+- Front matter has `name` (kebab-case) and `description` (one or two sentences with the trigger condition).
+- Each skill names the input it expects (e.g. an operation issue with `originKind` ending in `:ingest`, a captured `raw/` path, a Paperclip source bundle).
+- Each skill ends with a verification checklist — what must be true before the operation issue is closed `done`.
+- Skills cite the wiki-plugin tools they rely on (`wiki_search`, `wiki_read_page`, `wiki_write_page`, `wiki_read_source`, `wiki_list_sources`).
+- Skills do not duplicate the page conventions from the wiki root `AGENTS.md`. They reference it instead.
diff --git a/packages/plugins/plugin-llm-wiki/skills/index-refresh/SKILL.md b/packages/plugins/plugin-llm-wiki/skills/index-refresh/SKILL.md
new file mode 100644
index 0000000000..e0380e67f3
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/skills/index-refresh/SKILL.md
@@ -0,0 +1,65 @@
+---
+name: index-refresh
+description: Use when an operation issue is an index refresh — typically the hourly index-refresh routine. Rebuild `wiki/index.md` so each entry has a tight, scannable one-line summary and the catalog tracks the actual contents of `wiki/`. Resolve drift between the index and recent log activity, but do not edit page content.
+---
+
+# Index Refresh
+
+Keep `wiki/index.md` accurate and scannable. The index is the maintainer's first stop for navigation — its quality determines how cheap every subsequent operation becomes.
+
+## Inputs
+
+- An operation issue with `operationType: "index"` (or the `index-refresh` routine title).
+- The operation issue's target `wikiId`, `spaceSlug`, and space root. Refresh only that space unless the issue explicitly says this is a multi-space sweep.
+
+## Workflow
+
+1. **Read the target space's `wiki/index.md`** as it currently stands.
+2. **Walk the target space's `wiki/`.** `wiki/projects/<slug>/standup.md` entries are current-state companions for durable `wiki/projects/<slug>/index.md` pages; index them only as links attached to the matching project entry. Walk `wiki/` by category (`sources/`, `projects/`, `entities/`, `concepts/`, `synthesis/`, plus any custom subdirectories the wiki schema added).
+3. **Read the target space's last ~50 entries of `wiki/log.md`** to spot pages that were created or substantially changed but never made it to the index.
+4. **Per category, produce sorted entries** of the form:
+ ```
+ - [[<path>]] — <one-line summary>
+ ```
+ The summary is one factual sentence pulled from the page's first paragraph or its title. **No status, no datestamps in the index** — those belong in the page itself or in the log.
+5. **Drop entries whose page no longer exists.** Note the deletion in the log:
+ ```
+ ## [YYYY-MM-DD] index-refresh | reconciled
+ - removed: [[wiki/old-page]] (page deleted)
+ - added: [[wiki/new-page]] — <summary>
+ ```
+6. **Add entries for pages that exist on disk but were missing from the index.** Skip `wiki/log.md` and `wiki/index.md` themselves. For standalone `wiki/projects/<slug>/standup.md` without a matching durable project page, add it under Projects and flag it for later durable-page distillation.
+7. **Write project entries editorially.** The Projects section should group work by the project's concept and purpose, not by issue ids, dates, statuses, UUIDs, or source metadata. Link task identifiers only as supporting evidence.
+8. **Preserve custom categories.** If the wiki has added e.g. `wiki/papers/` or `wiki/runbooks/`, keep its index section. Do not collapse to the default five categories.
+9. **Append a log entry** with counts:
+ ```
+ ## [YYYY-MM-DD] index-refresh | added=N removed=M
+ - operation issue: <issue identifier>
+ ```
+ If the index was already accurate, the log entry says `added=0 removed=0` — still write it so future audits can see the run happened.
+
+## What this skill does NOT do
+
+- Does not change page content.
+- Does not resolve contradictions, fix broken links, or fill concept gaps. Those go to the next `wiki-lint` run.
+- Does not write summaries that are not already supported by the page itself. If a page lacks a clear first paragraph to summarise, flag it for `wiki-lint`.
+
+## Voice
+
+- Index entries are one factual line per page, present tense.
+- No emojis, no statuses, no dates in `wiki/index.md`. Dates live in the log.
+
+## Verification
+
+Before closing the operation issue:
+
+- [ ] `wiki/index.md` matches the actual contents of `wiki/` — no missing pages, no dangling entries.
+- [ ] Project entries include current `wiki/projects/<slug>/standup.md` links when standups exist.
+- [ ] Each index line has the form `- [[path]] — <summary>`.
+- [ ] Custom category sections are preserved.
+- [ ] `wiki/log.md` has the index-refresh entry with counts (even if the counts are zero).
+- [ ] No page bodies were modified. No file under `raw/` was modified.
+
+## Tools
+
+`wiki_search`, `wiki_read_page`, `wiki_write_page` (for `wiki/index.md` and `wiki/log.md` only). Always include the operation issue's `wikiId` and `spaceSlug`.
diff --git a/packages/plugins/plugin-llm-wiki/skills/paperclip-distill/SKILL.md b/packages/plugins/plugin-llm-wiki/skills/paperclip-distill/SKILL.md
new file mode 100644
index 0000000000..fa7b8d60d5
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/skills/paperclip-distill/SKILL.md
@@ -0,0 +1,125 @@
+---
+name: paperclip-distill
+description: Use when an operation issue is a Paperclip cursor-window, distill, or backfill — `operationType: "distill"` or `"backfill"` and the body references a Paperclip source bundle for a project or root issue. Turn raw Paperclip activity into a wiki-insightful project page, decisions log, and history note. This skill exists specifically to replace the stiff, datestamp-heavy templated output that the deterministic distiller produces.
+---
+
+# Paperclip Distill
+
+Distill Paperclip project, issue, comment, and document activity into durable wiki pages. The success criterion is **wiki-insightful, not procedural**: a reader who has never seen Paperclip should learn what the project is, what was decided, what is at risk, and what the current state is — without scanning a list of `## [YYYY-MM-DD]` headers.
+
+## When this skill is needed
+
+- Cursor-window distillation: the routine fed you a bounded source bundle of recent Paperclip activity for one project or root issue.
+- Backfill: the user asked to seed the wiki with the historical activity of a project or root issue. Source window may be wide.
+- Manual `distill-paperclip-now` request from the UI.
+
+If the operation issue is `operationType: "ingest"` (raw file) or `operationType: "query"`, this is the wrong skill — use `wiki-ingest` or `wiki-query`.
+
+## Destination space
+
+In Phase 1, every Paperclip distill, backfill, and cursor-window operation writes into the
+default wiki space. The operation issue should always carry `spaceSlug: "default"`. If an
+operation issue passes any other slug, stop and surface the mismatch in a comment — do not
+write Paperclip-derived pages into a non-default space.
+
+This rule is destination-only. The Paperclip source scope (which projects, root issues,
+comments, documents are read) is set elsewhere in the operation issue and is independent of
+the destination.
+
+## Inputs
+
+- A Paperclip source bundle (issue list, comment refs, document refs, source hash, cursor window).
+- An existing or planned `wiki/projects/<slug>/standup.md` page path.
+- An existing or planned `wiki/projects/<slug>/index.md` page path.
+- The operation issue's target `wikiId`, `spaceSlug`, space root, and the target space's `AGENTS.md` for page conventions.
+- The current `wiki/projects/<slug>/standup.md`, `wiki/projects/<slug>/index.md`, `decisions.md`, and `history.md` if they already exist (so you write a *patch*, not a rewrite).
+
+## Paperclip Asset Gate
+
+Do not treat Paperclip assets/attachments or issue work products as source text for this skill.
+
+- Allowed Paperclip body text: issue descriptions, comment bodies, document bodies.
+- Assets/attachments are metadata-only until a separate approved extraction policy exists.
+- Work products are metadata-only until a separate approved extraction policy exists.
+- Never fetch `/api/assets/:id/content`.
+- Never dereference a work-product `url`, preview URL, artifact URL, or other linked destination from this skill.
+- If an operator asks for attachment/work-product content distillation, stop and point them at the Phase 5 asset/work-product security gate policy instead of improvising.
+
+## Anti-patterns to avoid
+
+The deterministic templating this skill replaces produced these failure modes — do not reproduce them:
+
+1. **Datestamp-as-section-header.** Lines like `## [2026-04-15] paperclip-distill | proposed` belong in `wiki/log.md`, not in the project page. The project page is durable knowledge; the log is the audit trail.
+2. **Procedural status lists.** `Issue mix: 3 todo, 5 in_progress, 2 done` tells the reader nothing they could not read off Paperclip directly. State *what is happening and why it matters*, then cite the issues that constitute the evidence.
+3. **One-line-per-issue dumps.** A page that is mostly `- PAP-1234: title (in_progress, updated 2026-...)` is an issue list, not a wiki page. Group issues by what they are *about* (a decision, a risk, a workstream) and cite multiple issues per bullet when they share a story.
+4. **Mechanical "Current as of" timestamps everywhere.** One `current_as_of` in frontmatter is enough.
+5. **No interpretation.** "Active issues: PAP-A, PAP-B, PAP-C" is bookkeeping. "The team is concentrating on the schema migration ([PAP-A], [PAP-B]) and has parked the index work pending capacity ([PAP-C])." is wiki-insightful.
+6. **Opaque identifiers in prose.** UUIDs, cursor ids, source hashes, run ids, and raw metadata belong in logs or frontmatter when needed, not in executive-facing project narrative.
+
+## Workflow
+
+1. **Read the bundle in full.** Don't sample. Read every issue title, every comment, every document key the bundle includes. Note: which issues are decisions, which are risks/blockers, which are recently completed, which are inflight.
+2. **Read the existing project page** (if any) so you write a patch, not a rewrite. The "Decisions" section in particular accumulates over time — never wipe accepted decisions; supersede them with `> ⚠ reversed by ...` callouts when something later overrides them.
+3. **Read the target space's `AGENTS.md`** for page conventions: filename style, YAML frontmatter shape, link style, voice. Always pass the operation issue's `wikiId` and `spaceSlug` to LLM Wiki tools.
+4. **Write `wiki/projects/<slug>/standup.md` first.** Every Paperclip project represented in the wiki must have this file. It is the executive standup: where the project stands today, what changed recently, what is blocked or risky, and what happens next. Use stable sections, in this order:
+ - Frontmatter (`type: project-standup`, `project: <slug>`, `current_as_of: YYYY-MM-DD`, `sources`).
+ - **Executive Readout** — one short paragraph that explains the current project posture in plain language.
+ - **What Changed** — the meaningful work completed or advanced since the last window. Group by concept; cite issues/comments/documents only as evidence.
+ - **Decisions** — accepted/rejected/reversed decisions that changed the project direction. Omit when none exist.
+ - **Blockers / Risks** — current blockers and risks with named owner or next action when the source provides one.
+ - **Next Actions** — concrete next actions and owners inferred from Paperclip issues, not vague aspirations.
+ - **Links** — durable wiki project page and relevant Paperclip project/issues/documents.
+ Rewrite the standup to today's state. Do not append endless dated sections; the audit trail belongs in `wiki/log.md` and Paperclip comments.
+5. **Write `wiki/projects/<slug>/index.md`** with these stable sections, in this order:
+ - Frontmatter (`type: project`, `current_as_of: YYYY-MM-DD`, `tags`, `sources`).
+ - **Overview** — 2–4 sentences saying what the project is and why it exists. Use the project description if it exists; otherwise synthesise it from the root issue.
+ - **Current Direction** — narrative paragraph naming the active workstreams, the immediate next concrete deliverable, and the stance on risks. Cite 2–4 issues, do not list 20.
+ - **Workstreams** — a short, grouped list. Each line is a workstream or idea, not an issue.
+ - **Decisions** — accepted and reversed decisions with one paragraph each. Each decision cites the issue / approval / comment that ratified it. Format: `### Decision — short title` then a paragraph; never a bare bullet list.
+ - **Open Risks / Blockers** — what could derail the project, with the issue ref that surfaces it. Skip this section when the bundle has no risk signal — do not pad with `_(none)_`.
+ - **References** — readable links to the current standup and supporting Paperclip tasks/documents. Keep hashes and cursor ids out of the narrative.
+6. **Optionally write `wiki/projects/<slug>/decisions.md`** when the project has accumulated more decisions than the project page can carry without becoming a wall of text. Each decision is a `## ` section with: short title, accepted/reversed/superseded status, one-paragraph rationale, citing the source. *Do not* duplicate decisions already on the project page — link instead.
+7. **Optionally write `wiki/projects/<slug>/history.md`** for a compact narrative timeline of meaningful project changes. **Not** an issue dump — group by phase ("Discovery", "Architecture", "Build", "Stabilisation"), not by date. Each phase is a paragraph that cites the 2–4 issues that defined it.
+8. **Refresh `wiki/index.md`** under the `## Projects` section — one line per durable project page with a one-sentence summary of the project's purpose, plus a link to the current `wiki/projects/<slug>/standup.md` when present.
+9. **Append `wiki/log.md`** entry — this is where the datestamp belongs:
+ ```
+ ## [YYYY-MM-DD] paperclip-distill | <project name>
+ - standup: wiki/projects/<slug>/standup.md
+ - page: wiki/projects/<slug>/index.md
+ - source hash: `<hash>`
+ - cursor window: <start> → <end>
+ - notes: <one line on what changed in this distill, e.g. "decisions section grew with PAP-X reversal", "low-signal window, no page changes">
+ ```
+10. **Surface bundle warnings** (clipped sources, low signal, stale hash). Bundle warnings → `human_review_required: true` on the patch. Do not paper over them.
+
+## Voice
+
+- Past-tense for completed work, present-tense for current state, future-tense only with citation ("the team plans to … per [[…]]").
+- Cite Paperclip source refs inline using their issue identifier (e.g. `PAP-3179`), not opaque UUIDs.
+- Use issue links as evidence, not as the shape of the page. Headings and paragraphs should be organized by concepts, workstreams, decisions, and blockers.
+- Wiki voice: terse, factual, neutral. No "the team is excited to" or "this initiative aims to".
+- Headings are about *content*, not metadata. `## Schema migration` not `## Active Issues`.
+
+## When the bundle has no signal
+
+If the bundle has no durable signal — no decisions, no risk, no completed work, only routine status churn — do **not** write a project page. Instead:
+
+- Append a `paperclip-distill | low-signal skip` log entry naming the cursor window.
+- Close the operation issue with a one-line "no durable change in this window" comment.
+- Do not bump the source hash on a binding that has no proposed page.
+
+## Verification
+
+Before closing the operation issue:
+
+- [ ] The project page reads as wiki content, not as a Paperclip status report. A reader new to the company should understand what the project is.
+- [ ] `wiki/projects/<slug>/standup.md` exists for the represented project and reads as an executive current-state update, not a raw issue dump.
+- [ ] Decisions section names decisions, not issues — every decision has a one-paragraph rationale and a citation.
+- [ ] The page contains exactly one `current_as_of` (in frontmatter), zero `## [YYYY-MM-DD]` headings (those go to the log).
+- [ ] Bundle warnings (clipped, low signal, stale hash) are surfaced; the patch carries `human_review_required: true` when the deployment is authenticated/public.
+- [ ] `wiki/index.md` and `wiki/log.md` are updated.
+- [ ] No file under `raw/` was modified.
+
+## Tools
+
+`wiki_search`, `wiki_read_page`, `wiki_write_page`, `wiki_list_sources`, `wiki_read_source`. Always include the operation issue's `wikiId` and `spaceSlug`. The Paperclip source bundle arrives as part of the operation context — you do not need to assemble it.
diff --git a/packages/plugins/plugin-llm-wiki/skills/wiki-ingest/SKILL.md b/packages/plugins/plugin-llm-wiki/skills/wiki-ingest/SKILL.md
new file mode 100644
index 0000000000..3422af806b
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/skills/wiki-ingest/SKILL.md
@@ -0,0 +1,57 @@
+---
+name: wiki-ingest
+description: Use when an operation issue asks you to ingest a captured source from `raw/` into the LLM Wiki, or when the user explicitly says "ingest <slug>". The issue body will name a file under `raw/` (e.g. `raw/karpathy-llm-wiki.md`) and ask for durable wiki pages. Do not invoke this skill for Paperclip activity bundles — those use `paperclip-distill` instead.
+---
+
+# Wiki Ingest
+
+Turn one source document into durable, interlinked wiki knowledge.
+
+## Inputs
+
+- An operation issue with `operationType: "ingest"` assigned to you.
+- A `raw/` path mentioned in the issue body (always treat `raw/` as immutable).
+- The operation issue's target `wikiId`, `spaceSlug`, and space root (otherwise stop and surface the missing config to the requester).
+
+## Workflow
+
+1. **Read context first.**
+ - Read the target space's `AGENTS.md` for page conventions (filenames, frontmatter, voice, citation style).
+ - Read the target space's `wiki/index.md` to see what already exists.
+ - Read the target space's last ~20 entries of `wiki/log.md` to avoid re-ingesting a source or re-resolving a contradiction someone else already filed.
+2. **Read the source end to end** with `wiki_read_source`, passing the operation issue's `wikiId` and `spaceSlug`. Do not skim. Note the source's structure, claims, dates, and anything that contradicts existing pages.
+3. **Plan, then confirm — but only if the user is in the loop.** If the operation came from a routine (no live user), proceed. If a user is asking interactively, summarise the 3–5 takeaways you intend to file and ask which to emphasise before writing.
+4. **Write the source page** at `wiki/sources/<slug>.md` — ~300–800 words, frontmatter per the wiki schema, neutral voice, key claims with quoted excerpts where they carry weight. The source page is the canonical citation target for everything else this skill writes.
+5. **Update or create downstream pages** in `entities/`, `concepts/`, and `synthesis/`. A typical ingest touches 5–15 pages; resist creating pages for ideas that only appear once.
+6. **Wire the cross-links.** Every claim that comes from the source cites it as `(see [[wiki/sources/<slug>]])`. Every entity / concept mentioned by name on more than one page links to its dedicated page.
+7. **Flag contradictions; do not silently overwrite.** When new material disagrees with an existing page, append a `> ⚠ contradicted by [[wiki/sources/<slug>]] (YYYY-MM-DD)` callout to the older page and note the conflict in the log.
+8. **Refresh `wiki/index.md`** with one-line summaries for any new pages.
+9. **Append a log entry** in `wiki/log.md`:
+ ```
+ ## [YYYY-MM-DD] ingest | <source title>
+ - source: raw/<filename>
+ - new pages: [[...]], [[...]]
+ - updated pages: [[...]], [[...]]
+ - notes: <one-line synthesis or open question>
+ ```
+
+## Voice
+
+- Terse, factual, neutral. Reference material, not narrative.
+- No "Today I learned" or "This is interesting because" framing.
+- Quote the source verbatim when paraphrasing would lose precision.
+
+## Verification
+
+Before closing the operation issue:
+
+- [ ] Source page exists at `wiki/sources/<slug>.md` with valid frontmatter and a `sources:` field pointing to the raw path.
+- [ ] Every new or updated page links back to the source page or a downstream page that does.
+- [ ] `wiki/index.md` lists every new page under the right category with a one-line summary.
+- [ ] `wiki/log.md` has the ingest entry with the exact filename heading format (so `grep "^## \[" wiki/log.md` keeps working).
+- [ ] Any contradiction between the new source and an older page is annotated, not silently overwritten.
+- [ ] No file under `raw/` was modified.
+
+## Tools
+
+`wiki_list_sources`, `wiki_read_source`, `wiki_search`, `wiki_read_page`, `wiki_write_page`. Always include the operation issue's `wikiId` and `spaceSlug`.
diff --git a/packages/plugins/plugin-llm-wiki/skills/wiki-lint/SKILL.md b/packages/plugins/plugin-llm-wiki/skills/wiki-lint/SKILL.md
new file mode 100644
index 0000000000..acaa02557f
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/skills/wiki-lint/SKILL.md
@@ -0,0 +1,57 @@
+---
+name: wiki-lint
+description: Use when an operation issue is a lint or health-check (`operationType: "lint"`) — typically the nightly lint routine or a manual "Run lint" from the UI. Audit the wiki for contradictions, orphans, weak provenance, broken links, and missing concept pages, and return a triage list — do not auto-fix.
+---
+
+# Wiki Lint
+
+Audit, do not edit. Return findings the maintainer (human or agent) can triage.
+
+## Inputs
+
+- An operation issue with `operationType: "lint"`.
+- The operation issue's target `wikiId`, `spaceSlug`, and space root. Lint only that space unless the issue explicitly says this is a multi-space sweep.
+
+## Workflow
+
+1. **Walk the target space's `wiki/index.md` and wiki tree** with `wiki_search` and `wiki_read_page`, always passing the operation issue's `wikiId` and `spaceSlug`. Build a mental map of: pages that exist, pages referenced from `index.md`, pages referenced from other pages, and raw sources.
+2. **Check for the seven recurring issues**, in this order:
+ 1. **Contradictions** — two pages making incompatible claims about the same entity, decision, or status. Flag both pages, name the conflicting claims, and quote evidence.
+ 2. **Stale claims** — a page asserts X, but a newer source under `raw/` has superseded it. Flag the older page; never overwrite.
+ 3. **Orphan pages** — a `wiki/` page is not linked from `index.md` and not referenced from any other wiki page. Either it should be linked, removed, or merged.
+ 4. **Concept gaps** — a term appears on three or more pages but has no dedicated `wiki/concepts/<slug>.md`. Recommend creating one.
+ 5. **Broken `[[wiki-links]]`** — a link target file does not exist.
+ 6. **Weak provenance** — a non-trivial claim is uncited or cites only the wiki itself in a circle. The original source ref should be findable.
+ 7. **Index / log drift** — pages exist that are not in `index.md`, or `index.md` lists pages that no longer exist. Recent operations in `wiki/log.md` that did not produce a corresponding page change.
+3. **Return a triage list**, grouped by severity:
+ - **critical**: contradictions, broken links to active pages, fabricated citations.
+ - **medium**: stale claims, weak provenance, large concept gaps.
+ - **low**: orphans, log drift, small index gaps.
+ Each item has: file path, evidence (a 1–2 line quote), suggested fix, and the operation that should follow up (`ingest`, `paperclip-distill`, `index-refresh`, manual review).
+4. **Do not write to `wiki/`.** Lint is read-only by design — the maintainer or the routine that follows decides which findings to act on.
+5. **Append a log entry** describing the run:
+ ```
+ ## [YYYY-MM-DD] lint | <N findings, M critical>
+ - operation issue: <issue identifier>
+ - critical: <count>
+ - medium: <count>
+ - low: <count>
+ ```
+
+## Voice
+
+- Lead with the count by severity.
+- Each finding is one bullet. Resist commentary.
+- When in doubt about severity, say so and surface it as medium with a "verify" note.
+
+## Verification
+
+Before closing the operation issue:
+
+- [ ] Findings are grouped by severity with file paths, evidence, and suggested fix per item.
+- [ ] No files under `raw/` were modified. No files under `wiki/` were modified except `wiki/log.md`.
+- [ ] If the run found nothing, the issue is closed with "no findings" and the log entry still exists so future audits can see this run happened.
+
+## Tools
+
+`wiki_search`, `wiki_read_page`, `wiki_list_sources`, `wiki_read_source`, `wiki_write_page` (only `wiki/log.md`). Always include the operation issue's `wikiId` and `spaceSlug`.
diff --git a/packages/plugins/plugin-llm-wiki/skills/wiki-maintainer/SKILL.md b/packages/plugins/plugin-llm-wiki/skills/wiki-maintainer/SKILL.md
new file mode 100644
index 0000000000..de701b764a
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/skills/wiki-maintainer/SKILL.md
@@ -0,0 +1,12 @@
+---
+name: "LLM Wiki Maintainer"
+description: "Use the LLM Wiki plugin tools to maintain a cited local company wiki."
+---
+
+# LLM Wiki Maintainer
+
+Use this skill when maintaining the company LLM Wiki, answering questions from it, ingesting durable source material, refreshing the index, or linting wiki structure.
+
+Before changing wiki files, resolve the configured wiki root, read its AGENTS.md, inspect wiki/index.md and recent wiki/log.md entries, then use the LLM Wiki plugin tools for source reads, page writes, patch proposals, backlinks, and logging.
+
+Keep raw sources immutable, cite wiki pages and raw paths, update wiki/index.md when page navigation changes, and append a concise wiki/log.md entry for durable updates. For Paperclip project work, keep `wiki/projects/<project-slug>/standup.md` current as the executive status view and use `wiki/projects/<project-slug>/index.md` for durable project knowledge. Write project material as concept-grouped executive synthesis, not issue-id lists or metadata dumps.
diff --git a/packages/plugins/plugin-llm-wiki/skills/wiki-query/SKILL.md b/packages/plugins/plugin-llm-wiki/skills/wiki-query/SKILL.md
new file mode 100644
index 0000000000..ccb2855a7f
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/skills/wiki-query/SKILL.md
@@ -0,0 +1,44 @@
+---
+name: wiki-query
+description: Use when an operation issue asks you to answer a question from the LLM Wiki — `operationType: "query"` and a question in the issue body. Answer with citations to wiki pages and raw sources, and offer to file durable synthesis back into `wiki/synthesis/` so the work compounds instead of disappearing into a chat thread.
+---
+
+# Wiki Query
+
+Answer a question from what the wiki actually contains, with citations.
+
+## Inputs
+
+- An operation issue with `operationType: "query"` and the question in the body.
+- The operation issue's target `wikiId`, `spaceSlug`, and space root.
+
+## Workflow
+
+1. **Open the target space's `wiki/index.md` first** — it is the navigation aid. Identify candidate pages.
+2. **Read the candidate pages** end to end with `wiki_read_page`, always passing the operation issue's `wikiId` and `spaceSlug`. Follow `[[wiki-links]]` to neighbouring pages when the question spans entities or concepts.
+3. **Inspect raw sources** when a wiki page's claim feels thin. The wiki points to `raw/` precisely so you can verify before answering. Use `wiki_read_source`.
+4. **Answer the question** in the operation issue thread. Structure:
+ - Direct answer first, in 1–4 sentences.
+ - Then the supporting facts as bullet points, each with an inline citation: `(see [[wiki/concepts/managed-resources]])` or `(see raw/<filename>)`.
+ - If you needed to read a raw source the wiki did not summarise, name that as a gap.
+5. **Decide whether the answer is durable.** If the question forced you to do real synthesis (a comparison, a tradeoff, a definition of something that isn't already a page), offer to file it under `wiki/synthesis/<slug>.md`. Do not write the synthesis page silently — it is opt-in. If the user accepts, write the page, link it from `wiki/index.md`, and append a `query | filed synthesis` log entry.
+6. **When the wiki cannot answer**, say so plainly. Suggest a source the user should ingest, a Paperclip project that would help if distilled, or a web lookup. Never bluff.
+
+## Voice
+
+- Lead with the answer.
+- Cite as you go, not in a footnote block at the end.
+- Use the wiki's terse, factual voice. The query response is itself a candidate for filing into `wiki/synthesis/`.
+
+## Verification
+
+Before closing the operation issue:
+
+- [ ] Every claim in the answer cites a wiki page or raw source.
+- [ ] If the wiki was insufficient, that is stated directly with a concrete next step (ingest source X, distill project Y, web search Z).
+- [ ] If you wrote a synthesis page, `wiki/index.md` lists it and `wiki/log.md` has a `query | filed synthesis` entry.
+- [ ] No file under `raw/` was modified.
+
+## Tools
+
+`wiki_search`, `wiki_read_page`, `wiki_list_sources`, `wiki_read_source`, `wiki_write_page` (only when filing synthesis). Always include the operation issue's `wikiId` and `spaceSlug`.
diff --git a/packages/plugins/plugin-llm-wiki/src/manifest.ts b/packages/plugins/plugin-llm-wiki/src/manifest.ts
new file mode 100644
index 0000000000..de611ae6ad
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/src/manifest.ts
@@ -0,0 +1,601 @@
+import { readFileSync } from "node:fs";
+import type { PaperclipPluginManifestV1 } from "@paperclipai/plugin-sdk";
+import { DEFAULT_AGENT_INSTRUCTION_FILES, DEFAULT_AGENT_INSTRUCTIONS } from "./templates.js";
+
+export const PLUGIN_ID = "paperclipai.plugin-llm-wiki";
+export const WIKI_ROOT_FOLDER_KEY = "wiki-root";
+export const WIKI_MAINTAINER_AGENT_KEY = "wiki-maintainer";
+export const WIKI_MAINTAINER_SKILL_KEY = "wiki-maintainer";
+export const WIKI_INGEST_SKILL_KEY = "wiki-ingest";
+export const WIKI_QUERY_SKILL_KEY = "wiki-query";
+export const WIKI_LINT_SKILL_KEY = "wiki-lint";
+export const PAPERCLIP_DISTILL_SKILL_KEY = "paperclip-distill";
+export const INDEX_REFRESH_SKILL_KEY = "index-refresh";
+export const WIKI_PROJECT_KEY = "llm-wiki";
+export const CURSOR_WINDOW_ROUTINE_KEY = "cursor-window-processing";
+export const NIGHTLY_LINT_ROUTINE_KEY = "nightly-wiki-lint";
+export const INDEX_REFRESH_ROUTINE_KEY = "index-refresh";
+export const DEFAULT_MAX_SOURCE_BYTES = 250000;
+export const DEFAULT_MAX_PAPERCLIP_ISSUE_SOURCE_CHARS = 12000;
+export const DEFAULT_MAX_PAPERCLIP_CURSOR_WINDOW_CHARS = 60000;
+export const DEFAULT_MAX_PAPERCLIP_ROUTINE_RUN_CHARS = 120000;
+export const DEFAULT_PAPERCLIP_COST_CENTS_PER_1K_CHARS = 1;
+export const WIKI_MAINTENANCE_ROUTINE_KEYS = [
+ CURSOR_WINDOW_ROUTINE_KEY,
+ NIGHTLY_LINT_ROUTINE_KEY,
+ INDEX_REFRESH_ROUTINE_KEY,
+] as const;
+export const WIKI_MANAGED_SKILL_KEYS = [
+ WIKI_MAINTAINER_SKILL_KEY,
+ WIKI_INGEST_SKILL_KEY,
+ WIKI_QUERY_SKILL_KEY,
+ WIKI_LINT_SKILL_KEY,
+ PAPERCLIP_DISTILL_SKILL_KEY,
+ INDEX_REFRESH_SKILL_KEY,
+] as const;
+
+function canonicalSkillKey(skillKey: string) {
+ return `plugin/paperclipai-plugin-llm-wiki/${skillKey}`;
+}
+
+function skillMarkdown(skillKey: (typeof WIKI_MANAGED_SKILL_KEYS)[number]) {
+ return readFileSync(new URL(`../skills/${skillKey}/SKILL.md`, import.meta.url), "utf8");
+}
+
+export const WIKI_MAINTAINER_SKILL_CANONICAL_KEY = canonicalSkillKey(WIKI_MAINTAINER_SKILL_KEY);
+export const WIKI_MANAGED_SKILL_CANONICAL_KEYS = WIKI_MANAGED_SKILL_KEYS.map(canonicalSkillKey);
+
+const CURSOR_WINDOW_ROUTINE_DESCRIPTION = `Process bounded Paperclip issue-history windows into the LLM Wiki.
+
+Run procedure:
+Target space: default (slug: default). Paperclip-derived indexing currently writes only into the default space, so this routine never sweeps other spaces. Per-space Paperclip ingestion profiles are a later phase; until they ship, treat any prompt to operate on a non-default space here as a bug and stop.
+1. Resolve the configured wiki root, then read the default space AGENTS.md, wiki/index.md, and the recent entries in wiki/log.md.
+2. Review recent Paperclip issue, comment, and document activity for non-plugin-operation work. Skip LLM Wiki operation issues so routine output does not feed back into itself.
+3. Synthesize Paperclip project state into wiki/projects/<slug>/standup.md for the executive current-state view, then durable project or root-issue knowledge into focused pages under wiki/projects/<slug>/index.md, wiki/concepts/, or wiki/synthesis/. Keep transient run logs out of durable pages unless they change the project's state or decisions.
+4. Write project material as concept-grouped executive synthesis. Link readable issue identifiers when useful, but do not turn project pages into issue-ID lists, UUID dumps, date ledgers, or metadata reports. Always pass wikiId \`default\` and spaceSlug \`default\` to LLM Wiki tools.
+5. Refresh wiki/index.md and append a short wiki/log.md entry listing the source window, affected pages, skipped windows, warnings, and any follow-up issue needed.
+6. If there is no new durable signal, record that in wiki/log.md and close the routine issue with a concise note.`;
+
+const NIGHTLY_LINT_ROUTINE_DESCRIPTION = `Lint the LLM Wiki for structure, provenance, and stale synthesis.
+
+Run procedure:
+Target space: default (slug: default). Paperclip-derived indexing currently writes only into the default space, so this routine never sweeps other spaces. Per-space Paperclip ingestion profiles are a later phase; until they ship, treat any prompt to operate on a non-default space here as a bug and stop.
+1. Resolve the configured wiki root, then read the default space AGENTS.md, wiki/index.md, wiki/log.md, and the current page list.
+2. Check for orphan pages, missing backlinks, stale source provenance, weak citations, duplicate concepts, contradictory claims, and index/log drift.
+3. Inspect the relevant wiki pages and raw sources before changing content. Do not invent missing provenance.
+4. Apply low-risk fixes directly: refresh backlinks, repair index entries, add missing source links, and append a wiki/log.md lint entry. Always pass wikiId \`default\` and spaceSlug \`default\` to LLM Wiki tools.
+5. For ambiguous contradictions or major rewrites, leave the pages unchanged and create or comment a follow-up Paperclip issue with the exact files and evidence.
+6. Close the routine issue with counts by severity, files changed, and unresolved findings.`;
+
+const INDEX_REFRESH_ROUTINE_DESCRIPTION = `Refresh the LLM Wiki navigation and change log.
+
+Run procedure:
+Target space: default (slug: default). Paperclip-derived indexing currently writes only into the default space, so this routine never sweeps other spaces. Per-space Paperclip ingestion profiles are a later phase; until they ship, treat any prompt to operate on a non-default space here as a bug and stop.
+1. Resolve the configured wiki root, then read the default space AGENTS.md, wiki/index.md, wiki/log.md, and the current page list.
+2. Rebuild wiki/index.md so it lists current wiki pages by category with concise summaries and valid wikilinks, and attaches wiki/projects/<slug>/standup.md links to matching project entries.
+3. Verify recently changed wiki pages and project standups are present in the index and that removed or renamed pages no longer appear.
+4. Do not rewrite content pages unless a broken title or link prevents the index from being accurate. Always pass wikiId \`default\` and spaceSlug \`default\` to LLM Wiki tools.
+5. Append a wiki/log.md entry with the index refresh time, page counts by category, and any unresolved indexing problems.
+6. Close the routine issue with the index changes and any follow-up needed.`;
+
+const manifest: PaperclipPluginManifestV1 = {
+ id: PLUGIN_ID,
+ apiVersion: 1,
+ version: "0.1.0",
+ displayName: "LLM Wiki",
+ description: "Local-file LLM Wiki plugin for source ingestion, wiki browsing, query, lint, and maintenance workflows.",
+ author: "Paperclip",
+ categories: ["automation", "ui"],
+ capabilities: [
+ "events.subscribe",
+ "api.routes.register",
+ "database.namespace.migrate",
+ "database.namespace.read",
+ "database.namespace.write",
+ "companies.read",
+ "projects.read",
+ "projects.managed",
+ "skills.managed",
+ "issues.read",
+ "issue.subtree.read",
+ "issues.create",
+ "issues.update",
+ "issues.wakeup",
+ "issues.orchestration.read",
+ "issue.comments.read",
+ "issue.comments.create",
+ "issue.documents.read",
+ "issue.documents.write",
+ "agents.read",
+ "agents.managed",
+ "agent.sessions.create",
+ "agent.sessions.list",
+ "agent.sessions.send",
+ "agent.sessions.close",
+ "routines.managed",
+ "local.folders",
+ "agent.tools.register",
+ "metrics.write",
+ "activity.log.write",
+ "plugin.state.read",
+ "plugin.state.write",
+ "ui.sidebar.register",
+ "ui.page.register"
+ ],
+ entrypoints: {
+ worker: "./dist/worker.js",
+ ui: "./dist/ui"
+ },
+ database: {
+ namespaceSlug: "llm_wiki",
+ migrationsDir: "migrations",
+ coreReadTables: ["companies", "issues", "projects", "agents"]
+ },
+ localFolders: [
+ {
+ folderKey: WIKI_ROOT_FOLDER_KEY,
+ displayName: "Wiki root",
+ description: "Company-scoped local folder that stores raw sources, wiki pages, Paperclip project standups under wiki/projects/, AGENTS.md, IDEA.md, wiki/index.md, and wiki/log.md.",
+ access: "readWrite",
+ requiredDirectories: [
+ "raw",
+ "wiki",
+ "wiki/sources",
+ "wiki/projects",
+ "wiki/entities",
+ "wiki/concepts",
+ "wiki/synthesis"
+ ],
+ requiredFiles: ["AGENTS.md", "IDEA.md", "wiki/index.md", "wiki/log.md"]
+ }
+ ],
+ agents: [
+ {
+ agentKey: WIKI_MAINTAINER_AGENT_KEY,
+ displayName: "Wiki Maintainer",
+ role: "knowledge-maintainer",
+ title: "LLM Wiki Maintainer",
+ icon: "book-open",
+ capabilities: "Ingests source material, maintains local wiki pages, answers cited questions, and runs wiki lint/maintenance through plugin tools.",
+ adapterType: "claude_local",
+ adapterPreference: ["claude_local", "codex_local", "gemini_local", "opencode_local", "cursor", "pi_local"],
+ adapterConfig: {
+ dangerouslySkipPermissions: false,
+ dangerouslyBypassApprovalsAndSandbox: false,
+ sandbox: true,
+ paperclipSkillSync: {
+ desiredSkills: WIKI_MANAGED_SKILL_CANONICAL_KEYS
+ }
+ },
+ runtimeConfig: {
+ modelProfiles: {
+ cheap: {
+ purpose: "classification, lint planning, index maintenance"
+ }
+ }
+ },
+ permissions: {
+ pluginTools: [PLUGIN_ID]
+ },
+ status: "paused",
+ budgetMonthlyCents: 0,
+ instructions: {
+ entryFile: "AGENTS.md",
+ content: DEFAULT_AGENT_INSTRUCTIONS,
+ files: DEFAULT_AGENT_INSTRUCTION_FILES,
+ assetPath: "agents/wiki-maintainer"
+ }
+ }
+ ],
+ projects: [
+ {
+ projectKey: WIKI_PROJECT_KEY,
+ displayName: "LLM Wiki",
+ description: "Plugin-managed inspection area for LLM Wiki ingest, query, lint, and maintenance operation issues.",
+ status: "in_progress",
+ color: "#2563eb"
+ }
+ ],
+ skills: [
+ {
+ skillKey: WIKI_MAINTAINER_SKILL_KEY,
+ displayName: "LLM Wiki Maintainer",
+ slug: "llm-wiki-maintainer",
+ description: "Use the LLM Wiki plugin tools to maintain a cited local company wiki.",
+ markdown: skillMarkdown(WIKI_MAINTAINER_SKILL_KEY)
+ },
+ {
+ skillKey: WIKI_INGEST_SKILL_KEY,
+ displayName: "Wiki Ingest",
+ slug: WIKI_INGEST_SKILL_KEY,
+ description: "Turn captured raw source material into cited durable LLM Wiki pages.",
+ markdown: skillMarkdown(WIKI_INGEST_SKILL_KEY)
+ },
+ {
+ skillKey: WIKI_QUERY_SKILL_KEY,
+ displayName: "Wiki Query",
+ slug: WIKI_QUERY_SKILL_KEY,
+ description: "Answer questions from the LLM Wiki with citations and optional durable synthesis.",
+ markdown: skillMarkdown(WIKI_QUERY_SKILL_KEY)
+ },
+ {
+ skillKey: WIKI_LINT_SKILL_KEY,
+ displayName: "Wiki Lint",
+ slug: WIKI_LINT_SKILL_KEY,
+ description: "Audit the LLM Wiki for contradictions, orphan pages, weak provenance, broken links, and missing concepts.",
+ markdown: skillMarkdown(WIKI_LINT_SKILL_KEY)
+ },
+ {
+ skillKey: PAPERCLIP_DISTILL_SKILL_KEY,
+ displayName: "Paperclip Distill",
+ slug: PAPERCLIP_DISTILL_SKILL_KEY,
+ description: "Turn Paperclip cursor-window, distill, or backfill source bundles into wiki-insightful project knowledge.",
+ markdown: skillMarkdown(PAPERCLIP_DISTILL_SKILL_KEY)
+ },
+ {
+ skillKey: INDEX_REFRESH_SKILL_KEY,
+ displayName: "Index Refresh",
+ slug: INDEX_REFRESH_SKILL_KEY,
+ description: "Refresh wiki/index.md so it accurately catalogs current wiki pages.",
+ markdown: skillMarkdown(INDEX_REFRESH_SKILL_KEY)
+ }
+ ],
+ routines: [
+ {
+ routineKey: CURSOR_WINDOW_ROUTINE_KEY,
+ title: "Process LLM Wiki updates",
+ description: CURSOR_WINDOW_ROUTINE_DESCRIPTION,
+ status: "paused",
+ priority: "low",
+ assigneeRef: { resourceKind: "agent", resourceKey: WIKI_MAINTAINER_AGENT_KEY },
+ projectRef: { resourceKind: "project", resourceKey: WIKI_PROJECT_KEY },
+ concurrencyPolicy: "skip_if_active",
+ catchUpPolicy: "skip_missed",
+ triggers: [
+ {
+ kind: "schedule",
+ label: "Every 6 hours",
+ enabled: false,
+ cronExpression: "0 */6 * * *",
+ timezone: "UTC",
+ signingMode: null,
+ replayWindowSec: null
+ }
+ ],
+ issueTemplate: {
+ surfaceVisibility: "plugin_operation",
+ originId: "routine:cursor-window-processing",
+ billingCode: "plugin-llm-wiki:distillation"
+ }
+ },
+ {
+ routineKey: NIGHTLY_LINT_ROUTINE_KEY,
+ title: "Run LLM Wiki lint",
+ description: NIGHTLY_LINT_ROUTINE_DESCRIPTION,
+ status: "paused",
+ priority: "low",
+ assigneeRef: { resourceKind: "agent", resourceKey: WIKI_MAINTAINER_AGENT_KEY },
+ projectRef: { resourceKind: "project", resourceKey: WIKI_PROJECT_KEY },
+ concurrencyPolicy: "skip_if_active",
+ catchUpPolicy: "skip_missed",
+ triggers: [
+ {
+ kind: "schedule",
+ label: "Nightly",
+ enabled: false,
+ cronExpression: "0 3 * * *",
+ timezone: "UTC",
+ signingMode: null,
+ replayWindowSec: null
+ }
+ ],
+ issueTemplate: {
+ surfaceVisibility: "plugin_operation",
+ originId: "routine:nightly-wiki-lint",
+ billingCode: "plugin-llm-wiki:maintenance"
+ }
+ },
+ {
+ routineKey: INDEX_REFRESH_ROUTINE_KEY,
+ title: "Refresh LLM Wiki index",
+ description: INDEX_REFRESH_ROUTINE_DESCRIPTION,
+ status: "paused",
+ priority: "low",
+ assigneeRef: { resourceKind: "agent", resourceKey: WIKI_MAINTAINER_AGENT_KEY },
+ projectRef: { resourceKind: "project", resourceKey: WIKI_PROJECT_KEY },
+ concurrencyPolicy: "skip_if_active",
+ catchUpPolicy: "skip_missed",
+ triggers: [
+ {
+ kind: "schedule",
+ label: "Hourly",
+ enabled: false,
+ cronExpression: "0 * * * *",
+ timezone: "UTC",
+ signingMode: null,
+ replayWindowSec: null
+ }
+ ],
+ issueTemplate: {
+ surfaceVisibility: "plugin_operation",
+ originId: "routine:index-refresh",
+ billingCode: "plugin-llm-wiki:maintenance"
+ }
+ }
+ ],
+ tools: [
+ {
+ name: "wiki_search",
+ displayName: "Search Wiki",
+ description: "Search indexed wiki page and source metadata for one wiki space. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
+ parametersSchema: {
+ type: "object",
+ properties: {
+ companyId: { type: "string" },
+ wikiId: { type: "string" },
+ spaceSlug: { type: "string" },
+ query: { type: "string" },
+ limit: { type: "number" }
+ },
+ required: ["companyId", "wikiId", "query"]
+ }
+ },
+ {
+ name: "wiki_read_page",
+ displayName: "Read Wiki Page",
+ description: "Read a markdown wiki page from one wiki space. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
+ parametersSchema: {
+ type: "object",
+ properties: {
+ companyId: { type: "string" },
+ wikiId: { type: "string" },
+ spaceSlug: { type: "string" },
+ path: { type: "string" }
+ },
+ required: ["companyId", "wikiId", "path"]
+ }
+ },
+ {
+ name: "wiki_write_page",
+ displayName: "Write Wiki Page",
+ description: "Atomically write a markdown wiki page in one wiki space after plugin path validation and optional hash conflict checks. Operation agents should pass the issue's spaceSlug; omitting it uses the default space. Protected control files such as AGENTS.md and IDEA.md are excluded from agent-tool writes.",
+ parametersSchema: {
+ type: "object",
+ properties: {
+ companyId: { type: "string" },
+ wikiId: { type: "string" },
+ spaceSlug: { type: "string" },
+ path: { type: "string" },
+ contents: { type: "string" },
+ expectedHash: { type: "string" },
+ summary: { type: "string" }
+ },
+ required: ["companyId", "wikiId", "path", "contents"]
+ }
+ },
+ {
+ name: "wiki_propose_patch",
+ displayName: "Propose Wiki Patch",
+ description: "Return a structured proposed page write for one wiki space without changing files. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
+ parametersSchema: {
+ type: "object",
+ properties: {
+ companyId: { type: "string" },
+ wikiId: { type: "string" },
+ spaceSlug: { type: "string" },
+ path: { type: "string" },
+ contents: { type: "string" },
+ summary: { type: "string" }
+ },
+ required: ["companyId", "wikiId", "path", "contents"]
+ }
+ },
+ {
+ name: "wiki_list_sources",
+ displayName: "List Wiki Sources",
+ description: "Return captured raw source metadata from one wiki space. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
+ parametersSchema: {
+ type: "object",
+ properties: {
+ companyId: { type: "string" },
+ wikiId: { type: "string" },
+ spaceSlug: { type: "string" },
+ limit: { type: "number" }
+ },
+ required: ["companyId", "wikiId"]
+ }
+ },
+ {
+ name: "wiki_read_source",
+ displayName: "Read Wiki Source",
+ description: "Read a captured raw source from one wiki space. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
+ parametersSchema: {
+ type: "object",
+ properties: {
+ companyId: { type: "string" },
+ wikiId: { type: "string" },
+ spaceSlug: { type: "string" },
+ rawPath: { type: "string" }
+ },
+ required: ["companyId", "wikiId", "rawPath"]
+ }
+ },
+ {
+ name: "wiki_append_log",
+ displayName: "Append Wiki Log",
+ description: "Append a maintenance note to one wiki space's wiki/log.md. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
+ parametersSchema: {
+ type: "object",
+ properties: {
+ companyId: { type: "string" },
+ wikiId: { type: "string" },
+ spaceSlug: { type: "string" },
+ entry: { type: "string" }
+ },
+ required: ["companyId", "wikiId", "entry"]
+ }
+ },
+ {
+ name: "wiki_update_index",
+ displayName: "Update Wiki Index",
+ description: "Atomically replace one wiki space's wiki/index.md with optional hash conflict checks. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
+ parametersSchema: {
+ type: "object",
+ properties: {
+ companyId: { type: "string" },
+ wikiId: { type: "string" },
+ spaceSlug: { type: "string" },
+ contents: { type: "string" },
+ expectedHash: { type: "string" }
+ },
+ required: ["companyId", "wikiId", "contents"]
+ }
+ },
+ {
+ name: "wiki_list_backlinks",
+ displayName: "List Wiki Backlinks",
+ description: "Return indexed backlinks for a wiki page in one wiki space. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
+ parametersSchema: {
+ type: "object",
+ properties: {
+ companyId: { type: "string" },
+ wikiId: { type: "string" },
+ spaceSlug: { type: "string" },
+ path: { type: "string" }
+ },
+ required: ["companyId", "wikiId", "path"]
+ }
+ },
+ {
+ name: "wiki_list_pages",
+ displayName: "List Wiki Pages",
+ description: "Return the known page index from one wiki space's plugin metadata. Operation agents should pass the issue's spaceSlug; omitting it uses the default space.",
+ parametersSchema: {
+ type: "object",
+ properties: {
+ companyId: { type: "string" },
+ wikiId: { type: "string" },
+ spaceSlug: { type: "string" }
+ },
+ required: ["companyId", "wikiId"]
+ }
+ }
+ ],
+ apiRoutes: [
+ {
+ routeKey: "overview",
+ method: "GET",
+ path: "/overview",
+ auth: "board-or-agent",
+ capability: "api.routes.register",
+ companyResolution: { from: "query", key: "companyId" }
+ },
+ {
+ routeKey: "bootstrap",
+ method: "POST",
+ path: "/bootstrap",
+ auth: "board",
+ capability: "api.routes.register",
+ companyResolution: { from: "body", key: "companyId" }
+ },
+ {
+ routeKey: "capture-source",
+ method: "POST",
+ path: "/sources",
+ auth: "board-or-agent",
+ capability: "api.routes.register",
+ companyResolution: { from: "body", key: "companyId" }
+ },
+ {
+ routeKey: "spaces",
+ method: "GET",
+ path: "/spaces",
+ auth: "board-or-agent",
+ capability: "api.routes.register",
+ companyResolution: { from: "query", key: "companyId" }
+ },
+ {
+ routeKey: "create-space",
+ method: "POST",
+ path: "/spaces",
+ auth: "board",
+ capability: "api.routes.register",
+ companyResolution: { from: "body", key: "companyId" }
+ },
+ {
+ routeKey: "update-space",
+ method: "PATCH",
+ path: "/spaces/:spaceSlug",
+ auth: "board",
+ capability: "api.routes.register",
+ companyResolution: { from: "body", key: "companyId" }
+ },
+ {
+ routeKey: "bootstrap-space",
+ method: "POST",
+ path: "/spaces/:spaceSlug/bootstrap",
+ auth: "board",
+ capability: "api.routes.register",
+ companyResolution: { from: "body", key: "companyId" }
+ },
+ {
+ routeKey: "archive-space",
+ method: "POST",
+ path: "/spaces/:spaceSlug/archive",
+ auth: "board",
+ capability: "api.routes.register",
+ companyResolution: { from: "body", key: "companyId" }
+ },
+ {
+ routeKey: "operations",
+ method: "GET",
+ path: "/operations",
+ auth: "board-or-agent",
+ capability: "api.routes.register",
+ companyResolution: { from: "query", key: "companyId" }
+ },
+ {
+ routeKey: "start-query",
+ method: "POST",
+ path: "/query-sessions",
+ auth: "board",
+ capability: "api.routes.register",
+ companyResolution: { from: "body", key: "companyId" }
+ },
+ {
+ routeKey: "file-as-page",
+ method: "POST",
+ path: "/file-as-page",
+ auth: "board",
+ capability: "api.routes.register",
+ companyResolution: { from: "body", key: "companyId" }
+ }
+ ],
+ ui: {
+ slots: [
+ {
+ type: "sidebar",
+ id: "wiki-sidebar",
+ displayName: "Wiki",
+ exportName: "SidebarLink",
+ order: 35
+ },
+ {
+ type: "page",
+ id: "wiki-page",
+ displayName: "Wiki",
+ exportName: "WikiPage",
+ routePath: "wiki"
+ },
+ {
+ type: "routeSidebar",
+ id: "wiki-route-sidebar",
+ displayName: "Wiki",
+ exportName: "WikiRouteSidebar",
+ routePath: "wiki"
+ }
+ ]
+ }
+};
+
+export default manifest;
diff --git a/packages/plugins/plugin-llm-wiki/src/templates.ts b/packages/plugins/plugin-llm-wiki/src/templates.ts
new file mode 100644
index 0000000000..c07bf6f693
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/src/templates.ts
@@ -0,0 +1,73 @@
+import { readdirSync, readFileSync, statSync } from "node:fs";
+
+export const REQUIRED_WIKI_DIRECTORIES = [
+ "raw",
+ "wiki",
+ "wiki/sources",
+ "wiki/projects",
+ "wiki/entities",
+ "wiki/concepts",
+ "wiki/synthesis",
+] as const;
+
+export const REQUIRED_WIKI_FILES = ["AGENTS.md", "IDEA.md", "wiki/index.md", "wiki/log.md"] as const;
+export const KARPATHY_LLM_WIKI_GIST_URL = "https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f";
+
+function templateFile(path: string): string {
+ return readFileSync(new URL(`../templates/${path}`, import.meta.url), "utf8");
+}
+
+function agentInstructionFiles(agentKey: string): Record<string, string> {
+ const root = new URL(`../agents/${agentKey}/`, import.meta.url);
+ const files: Record<string, string> = {};
+
+ function walk(relativeDir: string) {
+ const dirUrl = new URL(relativeDir ? `${relativeDir}/` : "./", root);
+ for (const entry of readdirSync(dirUrl)) {
+ if (entry === ".DS_Store") continue;
+ const relativePath = relativeDir ? `${relativeDir}/${entry}` : entry;
+ const entryUrl = new URL(relativePath, root);
+ const stat = statSync(entryUrl);
+ if (stat.isDirectory()) {
+ walk(relativePath);
+ } else if (stat.isFile()) {
+ files[relativePath] = readFileSync(entryUrl, "utf8");
+ }
+ }
+ }
+
+ walk("");
+ return Object.fromEntries(Object.entries(files).sort(([left], [right]) => left.localeCompare(right)));
+}
+
+export const DEFAULT_WIKI_SCHEMA = templateFile("AGENTS.md");
+export const DEFAULT_AGENT_INSTRUCTION_FILES = agentInstructionFiles("wiki-maintainer");
+export const DEFAULT_AGENT_INSTRUCTIONS = DEFAULT_AGENT_INSTRUCTION_FILES["AGENTS.md"] ?? "";
+export const DEFAULT_IDEA = templateFile("IDEA.md");
+export const DEFAULT_INDEX = templateFile("wiki/index.md");
+export const DEFAULT_LOG = templateFile("wiki/log.md");
+export const DEFAULT_GITIGNORE = templateFile(".gitignore");
+
+export const QUERY_PROMPT = `Answer from the LLM Wiki using the installed wiki-query skill.
+
+Read the target space's wiki/index.md first, inspect relevant pages and raw/source references in that same space, cite the wiki page paths and raw source paths used, and say when the wiki does not contain enough evidence. Useful durable synthesis should be filed back into wiki/synthesis/ inside that same space. Always pass the operation issue's wikiId and spaceSlug to LLM Wiki tools.
+`;
+
+export const LINT_PROMPT = `Lint the LLM Wiki using the installed wiki-lint skill.
+
+Audit the target space only for contradictions, stale claims, orphan pages, missing backlinks, weak provenance, and wiki/index.md / wiki/log.md drift. Also look for important concepts mentioned without pages and answers that should have been filed back into wiki/. Return findings grouped by severity with concrete file paths, evidence, and suggested fixes — do not auto-apply edits. Always pass the operation issue's wikiId and spaceSlug to LLM Wiki tools.
+`;
+
+export const BOOTSTRAP_FILES: ReadonlyArray<{ path: string; contents: string }> = [
+ { path: ".gitignore", contents: DEFAULT_GITIGNORE },
+ { path: "AGENTS.md", contents: DEFAULT_WIKI_SCHEMA },
+ { path: "IDEA.md", contents: DEFAULT_IDEA },
+ { path: "wiki/index.md", contents: DEFAULT_INDEX },
+ { path: "wiki/log.md", contents: DEFAULT_LOG },
+ { path: "raw/.gitkeep", contents: "" },
+ { path: "wiki/sources/.gitkeep", contents: "" },
+ { path: "wiki/projects/.gitkeep", contents: "" },
+ { path: "wiki/entities/.gitkeep", contents: "" },
+ { path: "wiki/concepts/.gitkeep", contents: "" },
+ { path: "wiki/synthesis/.gitkeep", contents: "" },
+];
diff --git a/packages/plugins/plugin-llm-wiki/src/ui/app.tsx b/packages/plugins/plugin-llm-wiki/src/ui/app.tsx
new file mode 100644
index 0000000000..8110e827bc
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/src/ui/app.tsx
@@ -0,0 +1,7120 @@
+import {
+ AssigneePicker,
+ FileTree,
+ IssuesList as PluginIssuesList,
+ ManagedRoutinesList as PluginManagedRoutinesList,
+ MarkdownBlock,
+ MarkdownEditor,
+ ProjectPicker,
+ usePluginAction,
+ usePluginData,
+ usePluginStream,
+ usePluginToast,
+ useHostLocation,
+ useHostNavigation,
+ type FileTreeNode,
+ type ManagedRoutinesListItem,
+ type PluginPageProps,
+ type PluginRouteSidebarProps,
+ type PluginSettingsPageProps,
+ type PluginSidebarProps,
+} from "@paperclipai/plugin-sdk/ui";
+import { useCallback, useEffect, useMemo, useRef, useState, type AnchorHTMLAttributes, type CSSProperties, type ReactElement, type ReactNode } from "react";
+import { readIngestOperationIssueId, uploadIssueAttachmentFile } from "./issue-attachments.js";
+
+// ---------------------------------------------------------------------------
+// Shared design tokens — copied from the UX wireframe shared.css so the plugin
+// looks identical inside the host whether or not host theme tokens are
+// available at runtime.
+// ---------------------------------------------------------------------------
+
+const tokens = {
+ border: "var(--border, oklch(0.269 0 0))",
+ card: "var(--card, oklch(0.205 0 0))",
+ bg: "var(--background, oklch(0.145 0 0))",
+ fg: "var(--foreground, oklch(0.985 0 0))",
+ muted: "var(--muted-foreground, oklch(0.708 0 0))",
+ accent: "var(--accent, oklch(0.269 0 0))",
+ primary: "var(--primary, oklch(0.985 0 0))",
+ primaryFg: "var(--primary-foreground, oklch(0.205 0 0))",
+ destructive: "var(--destructive, oklch(0.637 0.237 25.331))",
+ pluginBg: "oklch(0.3 0.06 70)",
+ pluginFg: "oklch(0.92 0.08 80)",
+ pluginBorder: "oklch(0.55 0.15 70)",
+ hiddenOpBg: "oklch(0.27 0.04 280)",
+ hiddenOpFg: "oklch(0.85 0.08 280)",
+ hiddenOpBorder: "oklch(0.45 0.1 280)",
+ callout: { bg: "oklch(0.2 0.04 250)", fg: "oklch(0.85 0.08 250)", border: "oklch(0.4 0.1 250)" },
+ statusDone: "oklch(0.65 0.16 145)",
+ statusRunning: "oklch(0.7 0.13 200)",
+ statusBlocked: "oklch(0.6 0.21 25)",
+ statusInProgress: "oklch(0.58 0.18 280)",
+ statusTodo: "oklch(0.6 0.17 250)",
+ statusPaused: "oklch(0.72 0.15 70)",
+};
+
+type Tone = "todo" | "in_progress" | "in_review" | "done" | "blocked" | "running" | "paused" | "failed" | "queued" | "default";
+
+const toneStyles: Record<Tone, CSSProperties> = {
+ default: { background: "var(--secondary, oklch(0.269 0 0))", color: tokens.fg, border: `1px solid ${tokens.border}` },
+ todo: { background: "oklch(0.27 0.06 250)", color: "oklch(0.85 0.1 250)" },
+ in_progress: { background: "oklch(0.27 0.06 280)", color: "oklch(0.85 0.1 280)" },
+ in_review: { background: "oklch(0.27 0.07 305)", color: "oklch(0.85 0.1 305)" },
+ done: { background: "oklch(0.27 0.06 145)", color: "oklch(0.85 0.1 145)" },
+ blocked: { background: "oklch(0.27 0.08 25)", color: "oklch(0.82 0.13 25)" },
+ running: { background: "oklch(0.27 0.06 200)", color: "oklch(0.83 0.11 200)" },
+ paused: { background: "oklch(0.27 0.07 70)", color: "oklch(0.85 0.1 70)" },
+ failed: { background: "oklch(0.27 0.08 25)", color: "oklch(0.82 0.13 25)" },
+ queued: { background: "oklch(0.27 0.06 250)", color: "oklch(0.85 0.1 250)" },
+};
+
+const fontStack = `ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif`;
+const mobileMediaQuery = "(max-width: 767px)";
+const PLUGIN_ID = "paperclipai.plugin-llm-wiki";
+const WIKI_SIDEBAR_NAV_STATE_KEY = "paperclipWikiSidebarTreePath";
+const ROUTE_SIDEBAR_EXPANDED_STORAGE_PREFIX = `${PLUGIN_ID}:route-sidebar-expanded:v2`;
+const WIKI_TOC_STICKY_TOP = 88;
+const WIKI_SPACE_PREFETCH_LIMIT = 8;
+const DEFAULT_ROUTE_SIDEBAR_EXPANDED_PATHS = [
+ "wiki",
+ "wiki/sources",
+ "wiki/projects",
+ "wiki/entities",
+ "wiki/concepts",
+ "wiki/synthesis",
+] as const;
+
+// ---------------------------------------------------------------------------
+// Shared types coming back from the worker.
+// ---------------------------------------------------------------------------
+
+type FolderStatus = {
+ configured: boolean;
+ path: string | null;
+ realPath: string | null;
+ access: "read" | "readWrite";
+ readable: boolean;
+ writable: boolean;
+ requiredDirectories: string[];
+ requiredFiles: string[];
+ missingDirectories: string[];
+ missingFiles: string[];
+ healthy: boolean;
+ problems: { code: string; message: string; path?: string }[];
+ checkedAt: string;
+};
+
+type ManagedAgent = {
+ status: string;
+ source?: "managed" | "selected";
+ agentId?: string | null;
+ resourceKey?: string | null;
+ details?: { name?: string; status?: string; adapterType?: string | null; icon?: string | null; urlKey?: string | null } | null;
+ defaultDrift?: { entryFile: string; changedFiles: string[] } | null;
+};
+
+type ManagedProject = {
+ status: string;
+ source?: "managed" | "selected";
+ projectId?: string | null;
+ resourceKey?: string | null;
+ details?: { name?: string; status?: string; color?: string | null } | null;
+};
+
+type ManagedRoutine = {
+ status: string;
+ routineId?: string | null;
+ resourceKey?: string | null;
+ missingRefs?: Array<{ pluginKey?: string; resourceKind: string; resourceKey: string }>;
+ defaultDrift?: {
+ changedFields: string[];
+ defaultTitle?: string | null;
+ defaultDescription?: string | null;
+ } | null;
+ routine?: {
+ id?: string;
+ title?: string;
+ status?: string;
+ assigneeAgentId?: string | null;
+ projectId?: string | null;
+ lastTriggeredAt?: string | null;
+ lastEnqueuedAt?: string | null;
+ managedByPlugin?: {
+ pluginDisplayName?: string;
+ resourceKey?: string;
+ } | null;
+ } | null;
+ details?: {
+ title?: string;
+ status?: string;
+ cronExpression?: string | null;
+ enabled?: boolean;
+ nextRunAt?: string | null;
+ lastRunAt?: string | null;
+ assigneeAgentId?: string | null;
+ } | null;
+};
+
+type ManagedSkill = {
+ status: string;
+ skillId?: string | null;
+ resourceKey?: string | null;
+ defaultDrift?: { changedFiles: string[] } | null;
+ skill?: {
+ id?: string;
+ name?: string;
+ key?: string;
+ description?: string | null;
+ } | null;
+ details?: {
+ name?: string;
+ key?: string;
+ description?: string | null;
+ } | null;
+};
+
+type OverviewData = {
+ status: "ok";
+ checkedAt: string;
+ wikiId: string;
+ folder: FolderStatus;
+ managedAgent: ManagedAgent;
+ managedProject: ManagedProject;
+ managedSkills: ManagedSkill[];
+ operationCount: number;
+ eventIngestion: EventIngestionSettings;
+ capabilities: string[];
+ prompts: { query: string; lint: string };
+};
+
+type EventIngestionSettings = {
+ enabled: boolean;
+ sources: {
+ issues: boolean;
+ comments: boolean;
+ documents: boolean;
+ };
+ wikiId: string;
+ maxCharacters: number;
+};
+
+type WikiEventIngestionSource = "issues" | "comments" | "documents";
+
+type PaperclipIngestionSourceScope =
+ | { kind: "active_projects"; limit: number; statuses?: Array<"in_progress" | "todo" | "done"> }
+ | { kind: "selected_projects"; projectIds: string[] }
+ | { kind: "root_issues"; issueIds: string[] }
+ | { kind: "company_all"; requiresBoardConfirmation: true };
+
+type PaperclipIngestionProfile = {
+ version: 1;
+ enabled: boolean;
+ sourceScopes: PaperclipIngestionSourceScope[];
+ sourceKinds: {
+ issues: boolean;
+ comments: boolean;
+ documents: boolean;
+ attachments: "off" | "metadata_only";
+ workProducts: "off" | "metadata_only";
+ };
+ cursor: {
+ maxWindowCharacters: number;
+ maxCharactersPerSource: number;
+ minSourceAgeMinutes: number;
+ maxWindowsPerRun: number;
+ staleAfterHours: number;
+ };
+ backfill: {
+ defaultStartAt?: string | null;
+ defaultEndAt?: string | null;
+ requireManualQueue: boolean;
+ };
+};
+
+type PaperclipIngestionProfileData = {
+ wikiId: string;
+ space: Pick<WikiSpace, "id" | "slug" | "displayName" | "accessScope" | "status">;
+ profile: PaperclipIngestionProfile;
+ effectiveState: "enabled" | "disabled" | "policy_blocked" | "pending_approval" | "enabled_no_scopes";
+ policyBlocks: string[];
+ historicalPageCount: number;
+ overlapCount: number;
+};
+
+type SettingsData = {
+ folder: FolderStatus;
+ managedAgent: ManagedAgent;
+ managedProject: ManagedProject;
+ managedRoutine?: ManagedRoutine;
+ managedRoutines?: ManagedRoutine[];
+ managedSkills?: ManagedSkill[];
+ distillationPolicy?: {
+ autoApplyAllowed: boolean;
+ autoApplyRestriction: string | null;
+ deploymentMode: "local_trusted" | "authenticated" | null;
+ deploymentExposure: "private" | "public" | null;
+ };
+ eventIngestion: EventIngestionSettings;
+ agentOptions: Array<{ id: string; name: string; status?: string | null; adapterType?: string | null; icon?: string | null; urlKey?: string | null }>;
+ projectOptions: Array<{ id: string; name: string; status?: string | null; color?: string | null }>;
+ capabilities: string[];
+};
+
+type WikiSpace = {
+ id: string;
+ companyId: string;
+ wikiId: string;
+ slug: string;
+ displayName: string;
+ spaceType: string;
+ folderMode: string;
+ rootFolderKey: string;
+ pathPrefix: string | null;
+ configuredRootPath: string | null;
+ accessScope: string;
+ ownerUserId: string | null;
+ ownerAgentId: string | null;
+ teamKey: string | null;
+ settings: Record<string, unknown>;
+ status: string;
+ createdAt: string | null;
+ updatedAt: string | null;
+};
+
+type WikiSpacesData = {
+ spaces: WikiSpace[];
+};
+
+type WikiSpaceWithFolderStatus = WikiSpace & {
+ relativeRoot: string;
+ folder: FolderStatus;
+};
+
+const DEFAULT_SPACE_SLUG = "default";
+
+type WikiPageRow = {
+ path: string;
+ title: string | null;
+ pageType: string | null;
+ backlinkCount: number;
+ sourceCount: number;
+ contentHash: string | null;
+ updatedAt: string;
+};
+
+type WikiSourceRow = {
+ rawPath: string;
+ title: string | null;
+ sourceType: string;
+ url: string | null;
+ status: string;
+ createdAt: string;
+};
+
+type PagesData = {
+ pages: WikiPageRow[];
+ sources: WikiSourceRow[];
+};
+
+type PageContentData = {
+ wikiId: string;
+ path: string;
+ contents: string;
+ title: string | null;
+ pageType: string | null;
+ backlinks: string[];
+ sourceRefs: Array<Record<string, unknown> | string>;
+ updatedAt: string | null;
+ hash: string;
+};
+
+type WikiOperationRow = {
+ id: string;
+ operationType: string;
+ status: string;
+ hiddenIssueId: string | null;
+ hiddenIssueIdentifier: string | null;
+ hiddenIssueTitle: string | null;
+ hiddenIssueStatus: string | null;
+ projectId: string | null;
+ runIds: unknown[];
+ costCents: number;
+ warnings: unknown[];
+ affectedPages: unknown[];
+ metadata?: Record<string, unknown>;
+ createdAt: string;
+ updatedAt: string;
+};
+
+type OperationsData = {
+ operations: WikiOperationRow[];
+};
+
+type TemplateData = {
+ path: string;
+ contents: string;
+ hash: string | null;
+ exists: boolean;
+};
+
+type WikiFrontmatterValue = string | string[];
+
+type WikiFrontmatterProperty = {
+ key: string;
+ value: WikiFrontmatterValue;
+};
+
+type ParsedWikiMarkdown = {
+ body: string;
+ frontmatter: WikiFrontmatterProperty[];
+};
+
+type WikiTocHeading = {
+ id: string;
+ text: string;
+ level: number;
+};
+
+// ---------------------------------------------------------------------------
+// Small presentational primitives.
+// ---------------------------------------------------------------------------
+
+function Badge({ children, tone = "default", style }: { children: ReactNode; tone?: Tone; style?: CSSProperties }) {
+ return (
+ <span style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 4,
+ padding: "2px 8px",
+ borderRadius: 999,
+ fontSize: 11,
+ fontWeight: 500,
+ whiteSpace: "nowrap",
+ ...toneStyles[tone],
+ ...style,
+ }}>{children}</span>
+ );
+}
+
+function HiddenOpBadge() {
+ return (
+ <span style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 4,
+ padding: "2px 8px",
+ borderRadius: 999,
+ fontSize: 11,
+ fontWeight: 500,
+ background: tokens.hiddenOpBg,
+ color: tokens.hiddenOpFg,
+ border: `1px solid ${tokens.hiddenOpBorder}`,
+ }}>📖 wiki task</span>
+ );
+}
+
+function StatusIcon({ status }: { status: string }) {
+ const map: Record<string, { color: string; filled?: boolean; pulse?: boolean }> = {
+ done: { color: tokens.statusDone, filled: true },
+ in_progress: { color: tokens.statusInProgress },
+ running: { color: tokens.statusRunning, pulse: true },
+ queued: { color: tokens.statusTodo },
+ todo: { color: tokens.statusTodo },
+ blocked: { color: tokens.statusBlocked },
+ failed: { color: tokens.statusBlocked },
+ paused: { color: tokens.statusPaused },
+ };
+ const tone = map[status] ?? { color: tokens.muted };
+ return (
+ <span style={{
+ width: 12,
+ height: 12,
+ flexShrink: 0,
+ borderRadius: "50%",
+ border: `2px solid ${tone.color}`,
+ background: tone.filled ? tone.color : "transparent",
+ animation: tone.pulse ? "pcWikiPulse 1.6s infinite" : undefined,
+ }} aria-hidden />
+ );
+}
+
+function Card({ children, style }: { children: ReactNode; style?: CSSProperties }) {
+ return (
+ <section style={{
+ background: tokens.card,
+ border: `1px solid ${tokens.border}`,
+ borderRadius: 8,
+ overflow: "hidden",
+ minWidth: 0,
+ ...style,
+ }}>{children}</section>
+ );
+}
+
+function CardHeader({ title, right, badges }: { title: ReactNode; right?: ReactNode; badges?: ReactNode }) {
+ return (
+ <div style={{
+ padding: "12px 16px",
+ borderBottom: `1px solid ${tokens.border}`,
+ display: "flex",
+ alignItems: "center",
+ flexWrap: "wrap",
+ gap: 12,
+ minWidth: 0,
+ }}>
+ <h3 style={{ margin: 0, fontSize: 14, fontWeight: 600, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis" }}>{title}</h3>
+ {badges}
+ {right ? <div style={{ marginLeft: "auto", minWidth: 0, maxWidth: "100%" }}>{right}</div> : null}
+ </div>
+ );
+}
+
+function CardBody({ children, padding = 16 }: { children: ReactNode; padding?: number | string }) {
+ return <div style={{ padding }}>{children}</div>;
+}
+
+const unfilledSurfaceStyle: CSSProperties = {
+ background: "transparent",
+};
+
+function PropRow({ label, value }: { label: ReactNode; value: ReactNode }) {
+ return (
+ <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", flexWrap: "wrap", padding: "4px 0", fontSize: 13, gap: 12, minWidth: 0 }}>
+ <span style={{ color: tokens.muted, fontSize: 12, flexShrink: 0 }}>{label}</span>
+ <span style={{ flex: "1 1 160px", minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "normal", overflowWrap: "anywhere", textAlign: "right" }}>{value}</span>
+ </div>
+ );
+}
+
+function Tiny({ children, style }: { children: ReactNode; style?: CSSProperties }) {
+ return <div style={{ fontSize: 11, color: tokens.muted, ...style }}>{children}</div>;
+}
+
+function Mono({ children, style }: { children: ReactNode; style?: CSSProperties }) {
+ return <span style={{ fontFamily: "ui-monospace, SFMono-Regular, monospace", fontSize: 12, overflowWrap: "anywhere", wordBreak: "break-word", ...style }}>{children}</span>;
+}
+
+type ButtonVariant = "primary" | "default" | "ghost" | "destructive";
+type ButtonSize = "sm" | "md";
+
+function Button({
+ variant = "default",
+ size = "md",
+ disabled,
+ loading,
+ onClick,
+ children,
+ type = "button",
+ style,
+ title,
+}: {
+ variant?: ButtonVariant;
+ size?: ButtonSize;
+ disabled?: boolean;
+ loading?: boolean;
+ onClick?: () => void;
+ children: ReactNode;
+ type?: "button" | "submit";
+ style?: CSSProperties;
+ title?: string;
+}) {
+ const palette: Record<ButtonVariant, CSSProperties> = {
+ primary: {
+ background: tokens.primary,
+ color: tokens.primaryFg,
+ border: `1px solid transparent`,
+ },
+ default: {
+ background: tokens.card,
+ color: tokens.fg,
+ border: `1px solid ${tokens.border}`,
+ },
+ ghost: {
+ background: "transparent",
+ color: tokens.fg,
+ border: `1px solid transparent`,
+ },
+ destructive: {
+ background: "transparent",
+ color: "oklch(0.7 0.2 25)",
+ border: `1px solid oklch(0.5 0.18 25)`,
+ },
+ };
+ return (
+ <button
+ type={type}
+ title={title}
+ disabled={disabled || loading}
+ onClick={onClick}
+ style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 6,
+ padding: size === "sm" ? "3px 8px" : "6px 12px",
+ borderRadius: 6,
+ fontSize: size === "sm" ? 11 : 13,
+ fontWeight: 500,
+ cursor: disabled || loading ? "not-allowed" : "pointer",
+ opacity: disabled || loading ? 0.5 : 1,
+ fontFamily: fontStack,
+ minWidth: 0,
+ whiteSpace: "nowrap",
+ ...palette[variant],
+ ...style,
+ }}
+ >{children}</button>
+ );
+}
+
+function TextInput(props: React.InputHTMLAttributes<HTMLInputElement>) {
+ return (
+ <input
+ {...props}
+ style={{
+ background: "oklch(0.2 0 0)",
+ border: `1px solid ${tokens.border}`,
+ borderRadius: 6,
+ padding: "6px 10px",
+ fontSize: 13,
+ color: tokens.fg,
+ width: "100%",
+ boxSizing: "border-box",
+ minWidth: 0,
+ fontFamily: fontStack,
+ ...props.style,
+ }}
+ />
+ );
+}
+
+function TextArea(props: React.TextareaHTMLAttributes<HTMLTextAreaElement>) {
+ return (
+ <textarea
+ {...props}
+ style={{
+ background: "oklch(0.2 0 0)",
+ border: `1px solid ${tokens.border}`,
+ borderRadius: 6,
+ padding: "6px 10px",
+ fontSize: 13,
+ color: tokens.fg,
+ width: "100%",
+ boxSizing: "border-box",
+ minWidth: 0,
+ minHeight: 96,
+ fontFamily: fontStack,
+ resize: "vertical",
+ ...props.style,
+ }}
+ />
+ );
+}
+
+type AutosaveStatus = "idle" | "dirty" | "saving" | "saved" | "error";
+
+function AutosaveStatusLabel({ status, error }: { status: AutosaveStatus; error: string | null }) {
+ if (status === "saving") return <Tiny>Saving…</Tiny>;
+ if (status === "saved") return <Tiny>Saved</Tiny>;
+ if (status === "dirty") return <Tiny>Unsaved changes</Tiny>;
+ if (status === "error") return <Tiny style={{ color: "oklch(0.7 0.2 25)" }}>{error ?? "Autosave failed"}</Tiny>;
+ return <Tiny>Autosave on</Tiny>;
+}
+
+function AutosaveMarkdownEditor({
+ value,
+ placeholder,
+ minHeight,
+ resetKey,
+ onSave,
+ onStatusChange,
+}: {
+ value: string;
+ placeholder?: string;
+ minHeight?: number;
+ resetKey: string;
+ onSave: (value: string) => Promise<void>;
+ onStatusChange?: (status: AutosaveStatus) => void;
+}) {
+ const [draft, setDraft] = useState(value);
+ const [lastSaved, setLastSaved] = useState(value);
+ const [status, setStatus] = useState<AutosaveStatus>("idle");
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ setDraft(value);
+ setLastSaved(value);
+ setStatus("idle");
+ setError(null);
+ onStatusChange?.("idle");
+ }, [onStatusChange, resetKey, value]);
+
+ useEffect(() => {
+ if (draft === lastSaved) return;
+ setStatus("dirty");
+ setError(null);
+ onStatusChange?.("dirty");
+ const timeout = window.setTimeout(async () => {
+ setStatus("saving");
+ onStatusChange?.("saving");
+ try {
+ await onSave(draft);
+ setLastSaved(draft);
+ setStatus("saved");
+ onStatusChange?.("saved");
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ setError(message);
+ setStatus("error");
+ onStatusChange?.("error");
+ }
+ }, 800);
+ return () => window.clearTimeout(timeout);
+ }, [draft, lastSaved, onSave, onStatusChange]);
+
+ return (
+ <div style={{ display: "grid", gap: 6, minWidth: 0 }}>
+ <MarkdownEditor
+ value={draft}
+ onChange={setDraft}
+ placeholder={placeholder}
+ bordered
+ contentClassName="min-h-[260px]"
+ className="pc-wiki-markdown-editor"
+ />
+ <style>{`
+ .pc-wiki-markdown-editor .mdxeditor-root-contenteditable {
+ min-height: ${minHeight ?? 260}px;
+ }
+ `}</style>
+ <AutosaveStatusLabel status={status} error={error} />
+ </div>
+ );
+}
+
+function Callout({ children, tone = "info" }: { children: ReactNode; tone?: "info" | "warn" | "danger" }) {
+ const palette = tone === "danger"
+ ? { bg: "oklch(0.22 0.06 25)", fg: "oklch(0.85 0.12 25)", border: "oklch(0.45 0.12 25)" }
+ : tone === "warn"
+ ? { bg: "oklch(0.22 0.06 70)", fg: "oklch(0.85 0.1 70)", border: "oklch(0.45 0.12 70)" }
+ : tokens.callout;
+ return (
+ <div style={{
+ background: palette.bg,
+ color: palette.fg,
+ border: `1px solid ${palette.border}`,
+ borderRadius: 8,
+ padding: "12px 14px",
+ fontSize: 13,
+ lineHeight: 1.55,
+ }}>{children}</div>
+ );
+}
+
+function Divider() {
+ return <div style={{ height: 1, background: tokens.border, margin: "16px 0" }} />;
+}
+
+// ---------------------------------------------------------------------------
+// Hooks
+// ---------------------------------------------------------------------------
+
+function useMediaQuery(query: string): boolean {
+ const getSnapshot = () => {
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return false;
+ return window.matchMedia(query).matches;
+ };
+ const [matches, setMatches] = useState(getSnapshot);
+
+ useEffect(() => {
+ if (typeof window === "undefined" || typeof window.matchMedia !== "function") return;
+ const mediaQuery = window.matchMedia(query);
+ const handleChange = (event: MediaQueryListEvent) => setMatches(event.matches);
+ setMatches(mediaQuery.matches);
+ mediaQuery.addEventListener("change", handleChange);
+ return () => mediaQuery.removeEventListener("change", handleChange);
+ }, [query]);
+
+ return matches;
+}
+
+function useIsMobileLayout(): boolean {
+ return useMediaQuery(mobileMediaQuery);
+}
+
+function useOverview(companyId: string | null) {
+ const params = useMemo(() => companyId ? { companyId } : undefined, [companyId]);
+ return usePluginData<OverviewData>("overview", params);
+}
+
+function useSettings(companyId: string | null) {
+ const params = useMemo(() => companyId ? { companyId } : undefined, [companyId]);
+ return usePluginData<SettingsData>("settings", params);
+}
+
+function usePages(companyId: string | null, opts: { includeRaw?: boolean; spaceSlug?: string | null } = {}) {
+ const params = useMemo(() => {
+ if (!companyId) return undefined;
+ const next: Record<string, unknown> = { companyId, includeRaw: opts.includeRaw ?? true };
+ if (opts.spaceSlug && opts.spaceSlug !== DEFAULT_SPACE_SLUG) next.spaceSlug = opts.spaceSlug;
+ else if (opts.spaceSlug === DEFAULT_SPACE_SLUG) next.spaceSlug = DEFAULT_SPACE_SLUG;
+ return next;
+ }, [companyId, opts.includeRaw, opts.spaceSlug]);
+ return usePluginData<PagesData>("pages", params);
+}
+
+function useSpaces(companyId: string | null) {
+ const params = useMemo(() => companyId ? { companyId } : undefined, [companyId]);
+ return usePluginData<WikiSpacesData>("spaces", params);
+}
+
+function useSpaceFolderStatus(companyId: string | null, spaceSlug: string | null) {
+ const params = useMemo(() => {
+ if (!companyId || !spaceSlug) return undefined;
+ return { companyId, spaceSlug };
+ }, [companyId, spaceSlug]);
+ return usePluginData<WikiSpaceWithFolderStatus>("space", params);
+}
+
+function usePaperclipIngestionProfile(companyId: string | null, spaceSlug: string | null) {
+ const params = useMemo(() => {
+ if (!companyId || !spaceSlug) return undefined;
+ return { companyId, spaceSlug };
+ }, [companyId, spaceSlug]);
+ return usePluginData<PaperclipIngestionProfileData>("paperclip-ingestion-profile", params);
+}
+
+function usePageContent(companyId: string | null, path: string | null, spaceSlug?: string | null) {
+ const params = useMemo(() => {
+ if (!companyId || !path) return undefined;
+ const next: Record<string, unknown> = { companyId, path };
+ if (spaceSlug) next.spaceSlug = spaceSlug;
+ return next;
+ }, [companyId, path, spaceSlug]);
+ return usePluginData<PageContentData>("page-content", params);
+}
+
+function useOperations(companyId: string | null, filter: { operationType?: string | null; status?: string | null; spaceSlug?: string | null } = {}) {
+ const params = useMemo(() => {
+ if (!companyId) return undefined;
+ return {
+ companyId,
+ operationType: filter.operationType ?? null,
+ status: filter.status ?? null,
+ spaceSlug: filter.spaceSlug ?? null,
+ };
+ }, [companyId, filter.operationType, filter.status, filter.spaceSlug]);
+ return usePluginData<OperationsData>("operations", params);
+}
+
+function useTemplate(companyId: string | null, path: string) {
+ const params = useMemo(() => {
+ if (!companyId) return undefined;
+ return { companyId, path };
+ }, [companyId, path]);
+ return usePluginData<TemplateData>("template", params);
+}
+
+type DistillationCursor = {
+ id: string;
+ sourceScope: string;
+ scopeKey: string;
+ projectId: string | null;
+ projectName: string | null;
+ projectColor: string | null;
+ rootIssueId: string | null;
+ rootIssueIdentifier: string | null;
+ rootIssueTitle: string | null;
+ lastProcessedAt: string | null;
+ lastObservedAt: string | null;
+ pendingEventCount: number;
+ lastSourceHash: string | null;
+ lastSuccessfulRunId: string | null;
+};
+
+type DistillationRun = {
+ id: string;
+ cursorId: string | null;
+ workItemId: string | null;
+ projectId: string | null;
+ projectName: string | null;
+ rootIssueId: string | null;
+ rootIssueIdentifier: string | null;
+ sourceWindowStart: string | null;
+ sourceWindowEnd: string | null;
+ sourceHash: string | null;
+ status: string;
+ costCents: number;
+ retryCount: number;
+ warnings: string[];
+ metadata: Record<string, unknown>;
+ operationIssueId: string | null;
+ operationIssueIdentifier: string | null;
+ operationIssueTitle: string | null;
+ affectedPagePaths: string[];
+ createdAt: string;
+ updatedAt: string;
+};
+
+type DistillationWorkItem = {
+ id: string;
+ workItemKind: string;
+ status: string;
+ priority: string;
+ projectId: string | null;
+ rootIssueId: string | null;
+ metadata: Record<string, unknown>;
+ createdAt: string;
+ updatedAt: string;
+};
+
+type DistillationPageBinding = {
+ id: string;
+ pagePath: string;
+ projectId: string | null;
+ projectName: string | null;
+ rootIssueId: string | null;
+ lastAppliedSourceHash: string | null;
+ lastDistillationRunId: string | null;
+ lastRunStatus: string | null;
+ lastRunCompletedAt: string | null;
+ lastRunSourceWindowEnd: string | null;
+ lastRunSourceHash: string | null;
+ metadata: Record<string, unknown>;
+ updatedAt: string;
+};
+
+type DistillationOverviewData = {
+ cursors: DistillationCursor[];
+ runs: DistillationRun[];
+ workItems: DistillationWorkItem[];
+ pageBindings: DistillationPageBinding[];
+ reviewWorkItems: DistillationWorkItem[];
+ counts: {
+ cursors: number;
+ runningRuns: number;
+ failedRuns24h: number;
+ reviewRequired: number;
+ };
+};
+
+function useDistillationOverview(companyId: string | null) {
+ const params = useMemo(() => (companyId ? { companyId } : undefined), [companyId]);
+ return usePluginData<DistillationOverviewData>("distillation-overview", params);
+}
+
+type DistillationProvenanceData = {
+ binding: DistillationPageBinding | null;
+ runs: DistillationRun[];
+ snapshot: {
+ id: string;
+ distillationRunId: string;
+ sourceHash: string;
+ maxCharacters: number;
+ clipped: boolean;
+ sourceRefs: Array<Record<string, unknown> | string>;
+ metadata: Record<string, unknown>;
+ createdAt: string;
+ } | null;
+ cursor: DistillationCursor | null;
+};
+
+function useDistillationProvenance(companyId: string | null, pagePath: string | null) {
+ const params = useMemo(() => {
+ if (!companyId || !pagePath) return undefined;
+ return { companyId, pagePath };
+ }, [companyId, pagePath]);
+ return usePluginData<DistillationProvenanceData>("distillation-page-provenance", params);
+}
+
+function stripYamlInlineComment(value: string): string {
+ let quote: "'" | "\"" | null = null;
+ for (let i = 0; i < value.length; i++) {
+ const char = value[i];
+ const previous = value[i - 1];
+ if ((char === "'" || char === "\"") && previous !== "\\") {
+ quote = quote === char ? null : quote ?? char;
+ }
+ if (char === "#" && quote === null && (i === 0 || /\s/.test(previous ?? ""))) {
+ return value.slice(0, i).trimEnd();
+ }
+ }
+ return value.trim();
+}
+
+function unquoteYamlScalar(value: string): string {
+ const trimmed = stripYamlInlineComment(value).trim();
+ if (trimmed.length >= 2) {
+ const first = trimmed[0];
+ const last = trimmed[trimmed.length - 1];
+ if ((first === "\"" && last === "\"") || (first === "'" && last === "'")) {
+ return trimmed.slice(1, -1);
+ }
+ }
+ return trimmed;
+}
+
+function parseYamlInlineArray(value: string): string[] | null {
+ const trimmed = stripYamlInlineComment(value).trim();
+ if (!trimmed.startsWith("[") || !trimmed.endsWith("]")) return null;
+ const body = trimmed.slice(1, -1).trim();
+ if (!body) return [];
+
+ const items: string[] = [];
+ let current = "";
+ let quote: "'" | "\"" | null = null;
+ for (let i = 0; i < body.length; i++) {
+ const char = body[i];
+ const previous = body[i - 1];
+ if ((char === "'" || char === "\"") && previous !== "\\") {
+ quote = quote === char ? null : quote ?? char;
+ current += char;
+ continue;
+ }
+ if (char === "," && quote === null) {
+ const item = unquoteYamlScalar(current);
+ if (item) items.push(item);
+ current = "";
+ continue;
+ }
+ current += char;
+ }
+
+ const item = unquoteYamlScalar(current);
+ if (item) items.push(item);
+ return items;
+}
+
+function parseFrontmatterValue(rawValue: string, followingList: string[]): WikiFrontmatterValue {
+ const inlineArray = parseYamlInlineArray(rawValue);
+ if (inlineArray) return inlineArray;
+ if (!rawValue.trim() && followingList.length > 0) return followingList;
+ return unquoteYamlScalar(rawValue);
+}
+
+function parseWikiFrontmatterBlock(block: string): WikiFrontmatterProperty[] {
+ const lines = block.replace(/\r\n/g, "\n").split("\n");
+ const properties: WikiFrontmatterProperty[] = [];
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ if (!line.trim() || line.trimStart().startsWith("#")) continue;
+ if (/^\s+-\s+/.test(line)) continue;
+
+ const match = line.match(/^([A-Za-z0-9_-]+):(?:\s*(.*))?$/);
+ if (!match) continue;
+
+ const key = match[1];
+ const rawValue = match[2] ?? "";
+ const followingList: string[] = [];
+ let cursor = i + 1;
+ while (cursor < lines.length) {
+ const listMatch = lines[cursor]?.match(/^\s+-\s+(.+)$/);
+ if (!listMatch) break;
+ followingList.push(unquoteYamlScalar(listMatch[1] ?? ""));
+ cursor += 1;
+ }
+ if (!rawValue.trim() && followingList.length > 0) i = cursor - 1;
+
+ const value = parseFrontmatterValue(rawValue, followingList);
+ if (Array.isArray(value) ? value.length > 0 : value.length > 0) {
+ properties.push({ key, value });
+ }
+ }
+
+ return properties;
+}
+
+function parseWikiMarkdown(contents: string): ParsedWikiMarkdown {
+ const normalized = contents.replace(/^\uFEFF/, "").replace(/\r\n/g, "\n");
+ if (!normalized.startsWith("---\n")) {
+ return { body: contents, frontmatter: [] };
+ }
+
+ const closingMatch = normalized.slice(4).match(/\n(?:---|\.\.\.)[ \t]*(?:\n|$)/);
+ if (!closingMatch || closingMatch.index == null) {
+ return { body: contents, frontmatter: [] };
+ }
+
+ const frontmatterBlock = normalized.slice(4, closingMatch.index + 4);
+ const bodyStart = 4 + closingMatch.index + closingMatch[0].length;
+ return {
+ body: normalized.slice(bodyStart).replace(/^\n+/, ""),
+ frontmatter: parseWikiFrontmatterBlock(frontmatterBlock),
+ };
+}
+
+function stripMarkdownHeadingSyntax(text: string): string {
+ return text
+ .replace(/\\([\\`*_{}\[\]()#+\-.!|>])/g, "$1")
+ .replace(/!\[([^\]]*)\]\([^)]+\)/g, "$1")
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
+ .replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, "$2")
+ .replace(/\[\[([^\]]+)\]\]/g, "$1")
+ .replace(/`([^`]+)`/g, "$1")
+ .replace(/[*_~]+/g, "")
+ .replace(/<[^>]+>/g, "")
+ .trim();
+}
+
+function slugifyWikiHeading(text: string): string {
+ const slug = stripMarkdownHeadingSyntax(text)
+ .toLowerCase()
+ .replace(/&[a-z0-9#]+;/g, "")
+ .replace(/[^a-z0-9\s-]/g, "")
+ .trim()
+ .replace(/\s+/g, "-")
+ .replace(/-+/g, "-");
+ return slug || "section";
+}
+
+function extractWikiTocHeadings(markdownBody: string): WikiTocHeading[] {
+ const lines = markdownBody.replace(/\r\n/g, "\n").split("\n");
+ const headings: WikiTocHeading[] = [];
+ const usedIds = new Map<string, number>();
+ let fenced = false;
+
+ for (const line of lines) {
+ if (/^\s*(```|~~~)/.test(line)) {
+ fenced = !fenced;
+ continue;
+ }
+ if (fenced) continue;
+
+ const match = line.match(/^\s{0,3}(#{2,4})\s+(.+?)\s*#*\s*$/);
+ if (!match) continue;
+
+ const text = stripMarkdownHeadingSyntax(match[2] ?? "");
+ if (!text) continue;
+
+ const baseId = slugifyWikiHeading(text);
+ const count = usedIds.get(baseId) ?? 0;
+ usedIds.set(baseId, count + 1);
+ headings.push({
+ id: count === 0 ? baseId : `${baseId}-${count + 1}`,
+ text,
+ level: match[1]?.length ?? 2,
+ });
+ }
+
+ return headings;
+}
+
+// ---------------------------------------------------------------------------
+// Sidebar entry and settings page.
+// ---------------------------------------------------------------------------
+
+// Stroke-2, 16×16 lucide-react icons inlined here because plugin bundles
+// cannot import `lucide-react` directly (host-only dep). Path data tracks the
+// upstream lucide source 1:1 — keep them in sync if upstream changes.
+
+type LucideIconProps = { size?: number };
+
+function makeLucideIcon(paths: ReactNode) {
+ return function LucideIcon({ size = 16 }: LucideIconProps) {
+ return (
+ <svg
+ aria-hidden="true"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ style={{ width: size, height: size, display: "block" }}
+ >
+ {paths}
+ </svg>
+ );
+ };
+}
+
+const BookOpenIcon = makeLucideIcon(
+ <>
+ <path d="M12 7v14" />
+ <path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" />
+ </>,
+);
+
+const DownloadCloudIcon = makeLucideIcon(
+ <>
+ <path d="M12 13v8l-4-4" />
+ <path d="m12 21 4-4" />
+ <path d="M4.393 15.269A7 7 0 1 1 15.71 8.071" />
+ </>,
+);
+
+const MessageSquareTextIcon = makeLucideIcon(
+ <>
+ <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
+ <path d="M13 8H7" />
+ <path d="M17 12H7" />
+ </>,
+);
+
+const ListChecksIcon = makeLucideIcon(
+ <>
+ <path d="m3 17 2 2 4-4" />
+ <path d="m3 7 2 2 4-4" />
+ <path d="M13 6h8" />
+ <path d="M13 12h8" />
+ <path d="M13 18h8" />
+ </>,
+);
+
+const HistoryIcon = makeLucideIcon(
+ <>
+ <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
+ <path d="M3 3v5h5" />
+ <path d="M12 7v5l4 2" />
+ </>,
+);
+
+const SlidersHorizontalIcon = makeLucideIcon(
+ <>
+ <line x1="21" x2="14" y1="4" y2="4" />
+ <line x1="10" x2="3" y1="4" y2="4" />
+ <line x1="21" x2="12" y1="12" y2="12" />
+ <line x1="8" x2="3" y1="12" y2="12" />
+ <line x1="21" x2="16" y1="20" y2="20" />
+ <line x1="12" x2="3" y1="20" y2="20" />
+ <line x1="14" x2="14" y1="2" y2="6" />
+ <line x1="8" x2="8" y1="10" y2="14" />
+ <line x1="16" x2="16" y1="18" y2="22" />
+ </>,
+);
+
+const FolderOpenIcon = makeLucideIcon(
+ <>
+ <path d="M6 14h.01" />
+ <path d="M3 6h5l2 2h11v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
+ </>,
+);
+
+const ActivityIcon = makeLucideIcon(
+ <path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.5.5 0 0 1-.96 0L9.24 3.18a.5.5 0 0 0-.96 0l-2.35 8.36A2 2 0 0 1 4 13H2" />,
+);
+
+const InfoIcon = makeLucideIcon(
+ <>
+ <circle cx="12" cy="12" r="10" />
+ <path d="M12 16v-4" />
+ <path d="M12 8h.01" />
+ </>,
+);
+
+const SparklesIcon = makeLucideIcon(
+ <>
+ <path d="m12 3-1.9 5.8a2 2 0 0 1-1.3 1.3L3 12l5.8 1.9a2 2 0 0 1 1.3 1.3L12 21l1.9-5.8a2 2 0 0 1 1.3-1.3L21 12l-5.8-1.9a2 2 0 0 1-1.3-1.3z" />
+ <path d="M5 3v4" />
+ <path d="M19 17v4" />
+ <path d="M3 5h4" />
+ <path d="M17 19h4" />
+ </>,
+);
+
+const RefreshIcon = makeLucideIcon(
+ <>
+ <path d="M3 12a9 9 0 0 1 15-6.7L21 8" />
+ <path d="M21 3v5h-5" />
+ <path d="M21 12a9 9 0 0 1-15 6.7L3 16" />
+ <path d="M3 21v-5h5" />
+ </>,
+);
+
+const ExternalLinkIcon = makeLucideIcon(
+ <>
+ <path d="M15 3h6v6" />
+ <path d="M10 14 21 3" />
+ <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
+ </>,
+);
+
+const ClockIcon = makeLucideIcon(
+ <>
+ <circle cx="12" cy="12" r="10" />
+ <path d="M12 6v6l4 2" />
+ </>,
+);
+
+const AlertTriangleIcon = makeLucideIcon(
+ <>
+ <path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3z" />
+ <path d="M12 9v4" />
+ <path d="M12 17h.01" />
+ </>,
+);
+
+const XIcon = makeLucideIcon(
+ <>
+ <path d="M18 6 6 18" />
+ <path d="m6 6 12 12" />
+ </>,
+);
+
+const ChevronLeftIcon = makeLucideIcon(<path d="m15 18-6-6 6-6" />);
+
+const ChevronRightIcon = makeLucideIcon(<path d="m9 6 6 6-6 6" />);
+
+const ChevronDownIcon = makeLucideIcon(<path d="m6 9 6 6 6-6" />);
+
+const PlusIcon = makeLucideIcon(
+ <>
+ <path d="M12 5v14" />
+ <path d="M5 12h14" />
+ </>,
+);
+
+const PlusCircleIcon = makeLucideIcon(
+ <>
+ <circle cx="12" cy="12" r="9" />
+ <path d="M12 8v8" />
+ <path d="M8 12h8" />
+ </>,
+);
+
+const FolderIcon = makeLucideIcon(<path d="M3 7h6l2 2h10v10H3z" />);
+
+const MoreHorizontalIcon = makeLucideIcon(
+ <>
+ <circle cx="6" cy="12" r="1" />
+ <circle cx="12" cy="12" r="1" />
+ <circle cx="18" cy="12" r="1" />
+ </>,
+);
+
+const ArchiveIcon = makeLucideIcon(
+ <>
+ <path d="M3 6h18v4H3z" />
+ <path d="M5 10v10h14V10" />
+ <path d="M10 14h4" />
+ </>,
+);
+
+const PencilIcon = makeLucideIcon(
+ <>
+ <path d="M12 20h9" />
+ <path d="M16.5 3.5a2.121 2.121 0 1 1 3 3L7 19l-4 1 1-4z" />
+ </>,
+);
+
+export function SidebarLink({ context }: PluginSidebarProps) {
+ const hostNavigation = useHostNavigation();
+ return (
+ <a
+ {...hostNavigation.linkProps("/wiki")}
+ className="flex items-center gap-2.5 px-3 py-2 text-[13px] font-medium text-foreground/80 transition-colors hover:bg-accent/50 hover:text-foreground"
+ style={{ textDecoration: "none" }}
+ >
+ <span aria-hidden="true" className="shrink-0">
+ <BookOpenIcon />
+ </span>
+ <span className="flex-1 truncate">Wiki</span>
+ </a>
+ );
+}
+
+export function SettingsPage({ context }: PluginSettingsPageProps) {
+ const isMobile = useIsMobileLayout();
+ return (
+ <main style={{ padding: isMobile ? 16 : 24, maxWidth: isMobile ? "none" : 1040, minWidth: 0, fontFamily: fontStack, color: tokens.fg }}>
+ <SettingsBody context={context} />
+ </main>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Main wiki page: section shell for Pages / Ask / Ingest / Lint / History /
+// Settings. Wiki navigation uses path segments so pages can be deep-linked as
+// `/:companyPrefix/wiki/page/path/to/file`. Legacy query-param links are still
+// accepted as a compatibility fallback.
+// ---------------------------------------------------------------------------
+
+type SectionKey = "browse" | "ingest" | "query" | "lint" | "history" | "settings";
+
+const SECTIONS: ReadonlyArray<{
+ key: SectionKey;
+ label: string;
+ Icon: (props: LucideIconProps) => ReactElement;
+ description: string;
+}> = [
+ { key: "browse", label: "Wiki", Icon: BookOpenIcon, description: "Open wiki pages and raw sources from the sidebar." },
+ { key: "query", label: "Ask", Icon: MessageSquareTextIcon, description: "Ask the Wiki Maintainer agent a cited question against the local wiki." },
+ { key: "ingest", label: "Add Content", Icon: PlusCircleIcon, description: "Capture a new source into the active space and queue an ingest operation." },
+ { key: "lint", label: "Lint", Icon: ListChecksIcon, description: "Run structural checks for orphan pages, missing backlinks, and stale provenance." },
+ { key: "history", label: "History", Icon: HistoryIcon, description: "Inspect recent LLM Wiki operation issues." },
+ { key: "settings", label: "Settings", Icon: SlidersHorizontalIcon, description: "Folder, agent, project, and routine configuration scoped to this company." },
+];
+
+const TOP_TOOL_KEYS: ReadonlySet<SectionKey> = new Set<SectionKey>(["query", "ingest"]);
+const BOTTOM_TOOL_KEYS: ReadonlySet<SectionKey> = new Set<SectionKey>(["history", "settings"]);
+const TOP_TOOL_SECTIONS = SECTIONS.filter((section) => TOP_TOOL_KEYS.has(section.key));
+const BOTTOM_TOOL_SECTIONS = SECTIONS.filter((section) => BOTTOM_TOOL_KEYS.has(section.key));
+const SECTION_KEYS: ReadonlySet<SectionKey> = new Set(SECTIONS.map((s) => s.key));
+const LEGACY_SECTION_ALIASES: Readonly<Partial<Record<string, SectionKey>>> = {
+ operations: "history",
+};
+
+function isSectionKey(value: string | null | undefined): value is SectionKey {
+ return typeof value === "string" && SECTION_KEYS.has(value as SectionKey);
+}
+
+function normalizeSectionKey(value: string | null | undefined): SectionKey | null {
+ if (typeof value !== "string") return null;
+ return LEGACY_SECTION_ALIASES[value] ?? (isSectionKey(value) ? value : null);
+}
+
+function readSectionFromSearch(search: string): SectionKey {
+ const params = new URLSearchParams(search);
+ const raw = params.get("section");
+ return normalizeSectionKey(raw) ?? "browse";
+}
+
+function decodeRouteSegment(segment: string): string {
+ try {
+ return decodeURIComponent(segment);
+ } catch {
+ return segment;
+ }
+}
+
+function readWikiRouteSegments(pathname: string): string[] {
+ const segments = pathname.split("/").filter(Boolean);
+ const wikiIndex = segments.findIndex((segment) => decodeRouteSegment(segment).toLowerCase() === "wiki");
+ if (wikiIndex === -1) return [];
+ return segments.slice(wikiIndex + 1).map(decodeRouteSegment);
+}
+
+// Strip an optional `spaces/<slug>` prefix from the wiki route segments.
+// Returns the active space slug (defaults to "default") and the remaining segments
+// after that prefix so existing section/page parsing keeps working unchanged.
+function readWikiSpaceContext(pathname: string): { spaceSlug: string; rest: string[] } {
+ const segments = readWikiRouteSegments(pathname);
+ if (segments[0] === "spaces" && typeof segments[1] === "string" && segments[1].length > 0) {
+ return { spaceSlug: segments[1], rest: segments.slice(2) };
+ }
+ return { spaceSlug: DEFAULT_SPACE_SLUG, rest: segments };
+}
+
+function readActiveSpaceSlugFromLocation(pathname: string): string {
+ return readWikiSpaceContext(pathname).spaceSlug;
+}
+
+function readSectionFromLocation(pathname: string, search: string): SectionKey {
+ const [firstSegment] = readWikiSpaceContext(pathname).rest;
+ if (firstSegment === "page") return "browse";
+ return normalizeSectionKey(firstSegment) ?? readSectionFromSearch(search);
+}
+
+function readSettingsSectionFromLocation(pathname: string): SettingsSectionKey {
+ const [firstSegment, secondSegment] = readWikiSpaceContext(pathname).rest;
+ if (firstSegment !== "settings") return "root";
+ if (secondSegment === "maintainer" || secondSegment === "project") return "root";
+ return SETTINGS_SECTIONS.some((section) => section.key === secondSegment)
+ ? secondSegment as SettingsSectionKey
+ : "root";
+}
+
+function readSettingsSpaceSlugFromLocation(pathname: string): string | null {
+ const segs = readWikiSpaceContext(pathname).rest;
+ if (segs[0] !== "settings" || segs[1] !== "spaces") return null;
+ const slug = segs[2];
+ return typeof slug === "string" && slug.length > 0 ? slug : null;
+}
+
+function buildSpacePrefix(spaceSlug: string): string {
+ return spaceSlug && spaceSlug !== DEFAULT_SPACE_SLUG
+ ? `/wiki/spaces/${encodeURIComponent(spaceSlug)}`
+ : `/wiki`;
+}
+
+function buildSectionHref(section: SectionKey, spaceSlug: string = DEFAULT_SPACE_SLUG): string {
+ const prefix = buildSpacePrefix(spaceSlug);
+ return section === "browse" ? prefix : `${prefix}/${section}`;
+}
+
+function buildSettingsSectionHref(settingsSection: SettingsSectionKey | "spaces", spaceSlug: string = DEFAULT_SPACE_SLUG, slug?: string): string {
+ const prefix = buildSpacePrefix(spaceSlug);
+ if (settingsSection === "spaces" && slug) {
+ return `${prefix}/settings/spaces/${encodeURIComponent(slug)}`;
+ }
+ if (settingsSection === "root") return `${prefix}/settings`;
+ return `${prefix}/settings/${settingsSection}`;
+}
+
+function readSelectedTreePathFromSearch(search: string): string | null {
+ const params = new URLSearchParams(search);
+ const raw = params.get("page")?.trim();
+ return raw || null;
+}
+
+function readSelectedTreePathFromLocation(pathname: string, search: string): string | null {
+ const [firstSegment, ...rest] = readWikiSpaceContext(pathname).rest;
+ if (firstSegment === "page") {
+ return treePathFromRouteSegments(rest);
+ }
+ return readSelectedTreePathFromSearch(search);
+}
+
+function buildPageHref(treePath: string, spaceSlug: string = DEFAULT_SPACE_SLUG): string {
+ const prefix = buildSpacePrefix(spaceSlug);
+ const encodedPath = routeSegmentsFromTreePath(treePath).map((segment) => encodeURIComponent(segment)).join("/");
+ return encodedPath ? `${prefix}/page/${encodedPath}` : prefix;
+}
+
+function wikiSidebarNavigationState(treePath: string): Record<typeof WIKI_SIDEBAR_NAV_STATE_KEY, string> {
+ return { [WIKI_SIDEBAR_NAV_STATE_KEY]: treePath };
+}
+
+function readSidebarSelectedPathFromNavigationState(state: unknown): string | null {
+ if (!state || typeof state !== "object") return null;
+ const value = (state as Record<string, unknown>)[WIKI_SIDEBAR_NAV_STATE_KEY];
+ return typeof value === "string" && value.trim() ? value : null;
+}
+
+function routeSidebarExpandedStorageKey(companyId: string | null | undefined): string {
+ return `${ROUTE_SIDEBAR_EXPANDED_STORAGE_PREFIX}:${companyId ?? "global"}`;
+}
+
+function readRouteSidebarExpandedPaths(storageKey: string): Set<string> {
+ if (typeof window === "undefined") return new Set(DEFAULT_ROUTE_SIDEBAR_EXPANDED_PATHS);
+
+ try {
+ const raw = window.localStorage.getItem(storageKey);
+ if (raw === null) return new Set(DEFAULT_ROUTE_SIDEBAR_EXPANDED_PATHS);
+ const parsed = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return new Set(DEFAULT_ROUTE_SIDEBAR_EXPANDED_PATHS);
+ return new Set(parsed.filter((value): value is string => typeof value === "string" && value.trim().length > 0));
+ } catch {
+ return new Set(DEFAULT_ROUTE_SIDEBAR_EXPANDED_PATHS);
+ }
+}
+
+function writeRouteSidebarExpandedPaths(storageKey: string, paths: ReadonlySet<string>): void {
+ if (typeof window === "undefined") return;
+
+ try {
+ window.localStorage.setItem(storageKey, JSON.stringify([...paths].sort()));
+ } catch {
+ // Ignore storage failures; the tree still works for the current render.
+ }
+}
+
+const ROOT_WIKI_LINK_PAGES = new Set(["WIKI.md", "AGENTS.md", "IDEA.md", "index.md", "log.md"]);
+
+function splitWikiLinkTarget(target: string): { path: string; fragment: string | null } | null {
+ const trimmed = target.trim();
+ if (!trimmed || /^[a-z][a-z\d+.-]*:/i.test(trimmed) || trimmed.startsWith("//")) return null;
+
+ const hashIndex = trimmed.indexOf("#");
+ const rawPath = (hashIndex >= 0 ? trimmed.slice(0, hashIndex) : trimmed)
+ .trim()
+ .replace(/^\/+/, "");
+ if (
+ !rawPath ||
+ rawPath.includes("\\") ||
+ rawPath.split("/").some((segment) => !segment || segment === "." || segment === "..")
+ ) {
+ return null;
+ }
+
+ const fragment = hashIndex >= 0 ? trimmed.slice(hashIndex + 1).trim() || null : null;
+ return { path: rawPath, fragment };
+}
+
+function withMarkdownExtension(path: string): string {
+ return path.toLowerCase().endsWith(".md") ? path : `${path}.md`;
+}
+
+function normalizeWikiLinkPagePath(target: string): { path: string; fragment: string | null } | null {
+ const parsed = splitWikiLinkTarget(target);
+ if (!parsed) return null;
+
+ let path = withMarkdownExtension(parsed.path);
+ if (!path.startsWith("wiki/") && !path.startsWith("raw/") && !ROOT_WIKI_LINK_PAGES.has(path)) {
+ path = `wiki/${path}`;
+ }
+
+ return { path, fragment: parsed.fragment };
+}
+
+function buildWikiLinkHref(target: string, resolveHref: (to: string) => string): string | null {
+ const normalized = normalizeWikiLinkPagePath(target);
+ if (!normalized) return null;
+
+ const href = resolveHref(buildPageHref(normalized.path));
+ return normalized.fragment ? `${href}#${encodeURIComponent(normalized.fragment)}` : href;
+}
+
+function routeSegmentsFromTreePath(treePath: string): string[] {
+ return treePath.split("/").filter(Boolean);
+}
+
+function treePathFromRouteSegments(segments: string[]): string | null {
+ if (segments.length === 0) return null;
+ const [firstSegment, ...rest] = segments;
+ if (firstSegment === "templates") {
+ const templatePath = rest.join("/").trim();
+ return templatePath || null;
+ }
+ const routePath = segments.join("/").trim();
+ return routePath || null;
+}
+
+function firstSelectableTreePath(data: PagesData | null | undefined): string | null {
+ const firstPage = data?.pages.find((p) => p.path !== "wiki/index.md" && p.path !== "index.md") ?? data?.pages[0] ?? null;
+ if (firstPage) return firstPage.path;
+ const firstSource = data?.sources[0] ?? null;
+ if (firstSource) return firstSource.rawPath;
+ return TEMPLATE_PATHS[0] ?? null;
+}
+
+function contentPathFromTreePath(treePath: string | null): string | null {
+ return treePath;
+}
+
+function isEditableWikiPagePath(path: string): boolean {
+ return path === "WIKI.md"
+ || path === "AGENTS.md"
+ || path === "IDEA.md"
+ || path === "index.md"
+ || path === "log.md"
+ || path.startsWith("wiki/");
+}
+
+export function WikiPage({ context }: PluginPageProps) {
+ const { pathname, search } = useHostLocation();
+ const isMobile = useIsMobileLayout();
+ const section = useMemo(() => readSectionFromLocation(pathname, search), [pathname, search]);
+ const settingsSection = useMemo(() => readSettingsSectionFromLocation(pathname), [pathname]);
+ const activeSpaceSlug = useMemo(() => readActiveSpaceSlugFromLocation(pathname), [pathname]);
+ const settingsSpaceSlug = useMemo(() => readSettingsSpaceSlugFromLocation(pathname), [pathname]);
+ const overview = useOverview(context.companyId);
+ const [isDragActive, setIsDragActive] = useState(false);
+ const [stagedFiles, setStagedFiles] = useState<StagedIngestFile[]>([]);
+ const [isIngestModalOpen, setIsIngestModalOpen] = useState(false);
+
+ const resetDragState = useCallback(() => {
+ setIsDragActive(false);
+ }, []);
+
+ const stageFiles = useCallback((files: File[]) => {
+ if (files.length === 0) return;
+ const now = Date.now();
+ setStagedFiles((current) => [
+ ...current,
+ ...files.map((file, index) => ({
+ id: `${now}-${index}-${file.name}-${file.size}-${file.lastModified}`,
+ file,
+ })),
+ ]);
+ setIsIngestModalOpen(true);
+ }, []);
+
+ const handleDragEnter = useCallback((event: React.DragEvent<HTMLElement>) => {
+ if (!isFileDrag(event)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ setIsDragActive(true);
+ }, []);
+
+ const handleDragOver = useCallback((event: React.DragEvent<HTMLElement>) => {
+ if (!isFileDrag(event)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ event.dataTransfer.dropEffect = "copy";
+ setIsDragActive(true);
+ }, []);
+
+ const handleDragLeave = useCallback((event: React.DragEvent<HTMLElement>) => {
+ if (!isFileDrag(event)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const relatedTarget = event.relatedTarget;
+ if (relatedTarget instanceof Node && event.currentTarget.contains(relatedTarget)) return;
+ resetDragState();
+ }, [resetDragState]);
+
+ const handleDrop = useCallback((event: React.DragEvent<HTMLElement>) => {
+ if (!isFileDrag(event)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ resetDragState();
+ stageFiles(Array.from(event.dataTransfer.files ?? []));
+ }, [resetDragState, stageFiles]);
+
+ useEffect(() => {
+ if (!isDragActive) return;
+ const handleWindowDragLeave = (event: DragEvent) => {
+ const leftViewport =
+ event.clientX <= 0 ||
+ event.clientY <= 0 ||
+ event.clientX >= window.innerWidth ||
+ event.clientY >= window.innerHeight;
+ if (leftViewport) resetDragState();
+ };
+ const handleVisibilityChange = () => {
+ if (document.visibilityState !== "visible") resetDragState();
+ };
+ window.addEventListener("dragend", resetDragState);
+ window.addEventListener("drop", resetDragState);
+ window.addEventListener("blur", resetDragState);
+ window.addEventListener("dragleave", handleWindowDragLeave);
+ document.addEventListener("visibilitychange", handleVisibilityChange);
+ return () => {
+ window.removeEventListener("dragend", resetDragState);
+ window.removeEventListener("drop", resetDragState);
+ window.removeEventListener("blur", resetDragState);
+ window.removeEventListener("dragleave", handleWindowDragLeave);
+ document.removeEventListener("visibilitychange", handleVisibilityChange);
+ };
+ }, [isDragActive, resetDragState]);
+
+ if (!context.companyId) {
+ return <main style={{ ...shellStyle, height: isMobile ? "auto" : "100%", minHeight: isMobile ? "auto" : 600 }}>Choose a company to open the LLM Wiki.</main>;
+ }
+
+ return (
+ <main
+ style={{ ...shellStyle, position: "relative", height: isMobile ? "auto" : "100%", minHeight: isMobile ? "auto" : 600 }}
+ onDragEnter={handleDragEnter}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ >
+ <style>{`@keyframes pcWikiPulse { 0%,100% { opacity:1 } 50% { opacity:0.45 } }`}</style>
+ <section style={{ flex: 1, minHeight: isMobile ? "auto" : 0, overflow: isMobile ? "visible" : "hidden", display: "flex" }}>
+ {overview.error ? (
+ <div style={{ padding: 24, flex: 1 }}>
+ <Callout tone="danger">LLM Wiki bridge error: {overview.error.message}</Callout>
+ </div>
+ ) : !overview.data ? (
+ <div style={{ padding: 24, flex: 1, color: tokens.muted, fontSize: 13 }}>Loading wiki…</div>
+ ) : !overview.data.folder.healthy ? (
+ <UnconfiguredFolder context={context} folder={overview.data.folder} refresh={overview.refresh} />
+ ) : section === "browse" ? (
+ <BrowseTab context={context} />
+ ) : section === "ingest" ? (
+ <IngestTab context={context} refreshOverview={overview.refresh} />
+ ) : section === "query" ? (
+ <QueryTab context={context} overview={overview.data} />
+ ) : section === "lint" ? (
+ <SettingsTab context={context} initialSection="lint" />
+ ) : section === "history" ? (
+ <HistoryTab context={context} overview={overview.data} />
+ ) : (
+ <SettingsTab context={context} initialSection={settingsSection} />
+ )}
+ </section>
+ {isDragActive ? <WikiPageDropOverlay onClose={resetDragState} /> : null}
+ {isIngestModalOpen ? (
+ <IngestFilesModal
+ companyId={context.companyId}
+ files={stagedFiles}
+ initialSpaceSlug={activeSpaceSlug}
+ onAddFiles={stageFiles}
+ onRemoveFile={(id) => setStagedFiles((current) => current.filter((item) => item.id !== id))}
+ onClose={() => {
+ setIsIngestModalOpen(false);
+ setStagedFiles([]);
+ }}
+ onIngested={() => {
+ overview.refresh();
+ if (typeof window !== "undefined") {
+ window.dispatchEvent(new CustomEvent("pc-wiki-ingest-queued"));
+ }
+ }}
+ />
+ ) : null}
+ </main>
+ );
+}
+
+type StagedIngestFile = {
+ id: string;
+ file: File;
+};
+
+function isFileDrag(event: React.DragEvent<HTMLElement>): boolean {
+ return Array.from(event.dataTransfer?.types ?? []).includes("Files");
+}
+
+function WikiPageDropOverlay({ onClose }: { onClose: () => void }) {
+ return (
+ <div
+ data-testid="llm-wiki-page-drop-overlay"
+ style={{
+ position: "fixed",
+ inset: 0,
+ zIndex: 1000,
+ pointerEvents: "auto",
+ display: "grid",
+ placeItems: "center",
+ padding: 24,
+ background: "color-mix(in oklab, var(--background, oklch(0.145 0 0)) 72%, transparent)",
+ backdropFilter: "blur(3px)",
+ }}
+ >
+ <button
+ type="button"
+ aria-label="Close ingest drop overlay"
+ title="Close"
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ onClose();
+ }}
+ style={{
+ position: "absolute",
+ top: 16,
+ right: 16,
+ width: 34,
+ height: 34,
+ borderRadius: 8,
+ border: `1px solid ${tokens.border}`,
+ background: "color-mix(in oklab, var(--card, oklch(0.205 0 0)) 90%, transparent)",
+ color: tokens.fg,
+ display: "inline-grid",
+ placeItems: "center",
+ cursor: "pointer",
+ boxShadow: "0 10px 30px rgba(0,0,0,0.28)",
+ }}
+ >
+ <XIcon size={16} />
+ </button>
+ <div style={{
+ width: "min(520px, 100%)",
+ borderRadius: 8,
+ border: `1.5px dashed ${tokens.pluginBorder}`,
+ background: "color-mix(in oklab, var(--card, oklch(0.205 0 0)) 92%, transparent)",
+ color: tokens.fg,
+ padding: "28px 24px",
+ textAlign: "center",
+ boxShadow: "0 20px 60px rgba(0,0,0,0.35)",
+ }}>
+ <div style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 44, height: 44, borderRadius: 8, background: tokens.pluginBg, color: tokens.pluginFg, marginBottom: 12 }}>
+ <DownloadCloudIcon size={24} />
+ </div>
+ <div style={{ fontSize: 18, fontWeight: 650, marginBottom: 6 }}>Drop to ingest into LLM Wiki</div>
+ <Tiny>Files will be staged for review before the wiki maintainer queues ingest operations.</Tiny>
+ </div>
+ </div>
+ );
+}
+
+function IngestFilesModal({
+ companyId,
+ files,
+ onAddFiles,
+ onRemoveFile,
+ onClose,
+ onIngested,
+ initialSpaceSlug,
+}: {
+ companyId: string;
+ files: StagedIngestFile[];
+ onAddFiles: (files: File[]) => void;
+ onRemoveFile: (id: string) => void;
+ onClose: () => void;
+ onIngested: () => void;
+ initialSpaceSlug: string;
+}) {
+ const ingest = usePluginAction("ingest-source");
+ const toast = usePluginToast();
+ const spacesQuery = useSpaces(companyId);
+ const spaces = useMemo(() => {
+ const list = spacesQuery.data?.spaces ?? [];
+ return [...list].sort(compareSpaces);
+ }, [spacesQuery.data]);
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [errorMsg, setErrorMsg] = useState<string | null>(null);
+ const [targetSpaceSlug, setTargetSpaceSlug] = useState(initialSpaceSlug || DEFAULT_SPACE_SLUG);
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const [createOpen, setCreateOpen] = useState(false);
+ const targetSpace = useMemo(() => spaces.find((s) => s.slug === targetSpaceSlug) ?? null, [spaces, targetSpaceSlug]);
+
+ const requestClose = useCallback(() => {
+ if (!busy) onClose();
+ }, [busy, onClose]);
+
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key !== "Escape" || busy) return;
+ event.preventDefault();
+ onClose();
+ };
+ window.addEventListener("keydown", handleKeyDown);
+ return () => window.removeEventListener("keydown", handleKeyDown);
+ }, [busy, onClose]);
+
+ async function confirm() {
+ if (busy || files.length === 0) return;
+ setBusy(true);
+ setErrorMsg(null);
+ try {
+ for (const item of files) {
+ const contents = await item.file.text();
+ const result = await ingest({
+ companyId,
+ spaceSlug: targetSpaceSlug,
+ sourceType: "file",
+ title: item.file.name,
+ url: null,
+ contents,
+ metadata: {
+ fileName: item.file.name,
+ fileSize: item.file.size,
+ fileType: item.file.type || null,
+ lastModified: item.file.lastModified,
+ },
+ });
+ await uploadIssueAttachmentFile({
+ companyId,
+ issueId: readIngestOperationIssueId(result),
+ file: item.file,
+ });
+ }
+ const count = files.length;
+ const spaceLabel = targetSpace?.displayName ?? targetSpaceSlug;
+ toast({ tone: "success", title: `Files queued for ingest into ${spaceLabel}`, body: `${count} ${count === 1 ? "file" : "files"} captured into raw sources and attached to ingest tasks.` });
+ onIngested();
+ onClose();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ setErrorMsg(message);
+ toast({ tone: "error", title: "File ingest failed", body: message });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="llm-wiki-ingest-modal-title"
+ data-testid="llm-wiki-ingest-modal"
+ onMouseDown={(event) => {
+ if (event.currentTarget === event.target) requestClose();
+ }}
+ style={{
+ position: "fixed",
+ inset: 0,
+ zIndex: 1010,
+ display: "grid",
+ placeItems: "center",
+ padding: 18,
+ background: "rgba(0,0,0,0.52)",
+ }}
+ >
+ <div style={{
+ width: "min(680px, 100%)",
+ maxHeight: "min(720px, calc(100vh - 36px))",
+ overflow: "auto",
+ background: tokens.card,
+ color: tokens.fg,
+ border: `1px solid ${tokens.border}`,
+ borderRadius: 8,
+ boxShadow: "0 24px 80px rgba(0,0,0,0.45)",
+ }}>
+ <div style={{ padding: "16px 18px", borderBottom: `1px solid ${tokens.border}`, display: "flex", gap: 12, alignItems: "flex-start" }}>
+ <div style={{ width: 34, height: 34, borderRadius: 8, background: tokens.pluginBg, color: tokens.pluginFg, display: "grid", placeItems: "center", flexShrink: 0 }}>
+ <DownloadCloudIcon size={18} />
+ </div>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <h2 id="llm-wiki-ingest-modal-title" style={{ margin: 0, fontSize: 16, fontWeight: 650 }}>Ingest files into {targetSpace?.displayName ?? targetSpaceSlug}</h2>
+ <Tiny style={{ marginTop: 4 }}>
+ Review the staged files, switch the destination space if needed, then queue them as LLM
+ Wiki ingest operations. This is manual file ingest - Paperclip-derived distillation always
+ routes to the default space regardless of the destination picked here.
+ </Tiny>
+ </div>
+ <Button size="sm" variant="ghost" onClick={requestClose} disabled={busy} title="Close ingest modal">Close</Button>
+ </div>
+ <div style={{ padding: 18, display: "grid", gap: 14 }}>
+ <SpacePicker
+ spaces={spaces}
+ activeSpaceSlug={targetSpaceSlug}
+ loading={spacesQuery.loading}
+ error={spacesQuery.error?.message ?? null}
+ isOpen={pickerOpen}
+ onToggle={() => setPickerOpen((v) => !v)}
+ onClose={() => setPickerOpen(false)}
+ onSelect={(slug) => {
+ setPickerOpen(false);
+ setTargetSpaceSlug(slug);
+ }}
+ onCreate={() => {
+ setPickerOpen(false);
+ setCreateOpen(true);
+ }}
+ />
+ <div style={{ display: "flex", gap: 8, flexWrap: "wrap", alignItems: "center" }}>
+ <Badge tone="running">{files.length} staged</Badge>
+ <Button size="sm" onClick={() => inputRef.current?.click()} disabled={busy}>Add files</Button>
+ <input
+ ref={inputRef}
+ type="file"
+ multiple
+ style={{ display: "none" }}
+ onChange={(event) => {
+ onAddFiles(Array.from(event.currentTarget.files ?? []));
+ event.currentTarget.value = "";
+ }}
+ />
+ </div>
+ <div style={{ border: `1px solid ${tokens.border}`, borderRadius: 8, overflow: "hidden" }}>
+ {files.length === 0 ? (
+ <div style={{ padding: 16 }}><Tiny>No files staged.</Tiny></div>
+ ) : files.map((item) => (
+ <div key={item.id} style={{ display: "flex", gap: 10, alignItems: "center", padding: "10px 12px", borderBottom: `1px solid ${tokens.border}`, minWidth: 0 }}>
+ <div style={{ flex: "1 1 auto", minWidth: 0 }}>
+ <strong style={{ display: "block", fontSize: 13, overflowWrap: "anywhere" }}>{item.file.name}</strong>
+ <Tiny>{formatFileSize(item.file.size)}{item.file.type ? ` · ${item.file.type}` : ""}</Tiny>
+ </div>
+ <Button size="sm" variant="ghost" onClick={() => onRemoveFile(item.id)} disabled={busy}>Remove</Button>
+ </div>
+ ))}
+ </div>
+ {errorMsg ? <Callout tone="danger">{errorMsg}</Callout> : null}
+ <Callout>
+ Confirming captures each file into <Mono>{targetSpaceSlug}/raw/</Mono>, attaches the original file to the ingest task, and initiates a task for the Wiki Maintainer to process.
+ </Callout>
+ <div style={{ display: "flex", gap: 8, justifyContent: "flex-end", flexWrap: "wrap" }}>
+ <Button variant="ghost" onClick={requestClose} disabled={busy}>Cancel</Button>
+ <Button variant="primary" onClick={confirm} disabled={files.length === 0} loading={busy}>Capture & ingest into {targetSpace?.displayName ?? targetSpaceSlug}</Button>
+ </div>
+ </div>
+ </div>
+ {createOpen ? (
+ <CreateSpaceModal
+ companyId={companyId}
+ existingSlugs={new Set(spaces.map((s) => s.slug))}
+ onClose={() => setCreateOpen(false)}
+ onCreated={(space) => {
+ setCreateOpen(false);
+ spacesQuery.refresh();
+ setTargetSpaceSlug(space.slug);
+ }}
+ />
+ ) : null}
+ </div>
+ );
+}
+
+function formatFileSize(bytes: number): string {
+ if (!Number.isFinite(bytes) || bytes < 0) return "Unknown size";
+ if (bytes < 1024) return `${bytes} B`;
+ const kib = bytes / 1024;
+ if (kib < 1024) return `${kib.toFixed(kib >= 10 ? 0 : 1)} KB`;
+ const mib = kib / 1024;
+ return `${mib.toFixed(mib >= 10 ? 0 : 1)} MB`;
+}
+
+// ---------------------------------------------------------------------------
+// Wiki route sidebar — replaces the company sidebar while the user is on a
+// `/wiki` route. Mirrors the shell of the host's CompanySettingsSidebar so
+// users see a familiar takeover.
+// ---------------------------------------------------------------------------
+
+// ---------------------------------------------------------------------------
+// Create-space modal — opened from the sidebar `+` icon and also reachable
+// from the edit-space settings sub-nav. Disables the "Cloud" type and the
+// "Existing absolute path" folder source per the PAP-3640 security review.
+// ---------------------------------------------------------------------------
+
+function slugify(input: string): string {
+ return input
+ .toLowerCase()
+ .normalize("NFKD")
+ .replace(/[\u0300-\u036f]/g, "")
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "")
+ .slice(0, 40);
+}
+
+const SLUG_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?$/;
+
+function CreateSpaceModal({
+ companyId,
+ existingSlugs,
+ onClose,
+ onCreated,
+}: {
+ companyId: string;
+ existingSlugs: ReadonlySet<string>;
+ onClose: () => void;
+ onCreated: (space: WikiSpace) => void;
+}) {
+ const create = usePluginAction("create-space");
+ const toast = usePluginToast();
+ const [displayName, setDisplayName] = useState("");
+ const [slug, setSlug] = useState("");
+ const [slugDirty, setSlugDirty] = useState(false);
+ const [folderMode, setFolderMode] = useState<"managed_subfolder" | "existing_local_folder">("managed_subfolder");
+ const [accessScope, setAccessScope] = useState<"shared" | "personal" | "team">("shared");
+ const [busy, setBusy] = useState(false);
+ const [errorMsg, setErrorMsg] = useState<string | null>(null);
+ const isMobile = useIsMobileLayout();
+
+ useEffect(() => {
+ const handler = (event: KeyboardEvent) => { if (event.key === "Escape" && !busy) onClose(); };
+ document.addEventListener("keydown", handler);
+ return () => document.removeEventListener("keydown", handler);
+ }, [busy, onClose]);
+
+ const effectiveSlug = slug.trim() || (slugDirty ? "" : slugify(displayName));
+
+ const slugError = (() => {
+ if (!effectiveSlug) return null;
+ if (effectiveSlug === DEFAULT_SPACE_SLUG) return "Slug 'default' is reserved.";
+ if (!SLUG_PATTERN.test(effectiveSlug)) return "Use 2-40 chars: lowercase letters, numbers, hyphens.";
+ if (existingSlugs.has(effectiveSlug)) return "A space with this slug already exists.";
+ return null;
+ })();
+
+ const canSubmit = displayName.trim().length > 0 && effectiveSlug.length > 0 && !slugError && !busy;
+
+ async function submit() {
+ if (!canSubmit) return;
+ setBusy(true);
+ setErrorMsg(null);
+ try {
+ const result = await create({
+ companyId,
+ slug: effectiveSlug,
+ displayName: displayName.trim(),
+ folderMode,
+ accessScope,
+ }) as { status: "created"; space: WikiSpace };
+ toast({ tone: "success", title: "Space created", body: `${result.space.displayName} is ready for ingest.` });
+ onCreated(result.space);
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ setErrorMsg(msg);
+ toast({ tone: "error", title: "Could not create space", body: msg });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ const previewName = displayName.trim() || "your-space";
+
+ return (
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="create-space-modal-title"
+ style={{
+ position: "fixed",
+ inset: 0,
+ zIndex: 200,
+ display: "grid",
+ placeItems: isMobile ? "end" : "center",
+ padding: isMobile ? 0 : 18,
+ background: "rgba(0,0,0,0.52)",
+ }}
+ onClick={(event) => {
+ if (event.target === event.currentTarget && !busy) onClose();
+ }}
+ >
+ <div
+ style={{
+ width: isMobile ? "100%" : "min(560px, 100%)",
+ maxHeight: isMobile ? "92vh" : "min(760px, calc(100vh - 36px))",
+ overflow: "auto",
+ background: tokens.card,
+ color: tokens.fg,
+ border: `1px solid ${tokens.border}`,
+ borderRadius: isMobile ? "12px 12px 0 0" : 8,
+ boxShadow: "0 24px 80px rgba(0,0,0,0.45)",
+ fontFamily: fontStack,
+ }}
+ >
+ <div style={{ padding: "16px 20px", borderBottom: `1px solid ${tokens.border}`, display: "flex", alignItems: "flex-start", gap: 12 }}>
+ <div style={{ width: 34, height: 34, borderRadius: 8, background: tokens.pluginBg, color: tokens.pluginFg, display: "grid", placeItems: "center", flexShrink: 0 }}>
+ <FolderIcon size={18} />
+ </div>
+ <div style={{ flex: 1, minWidth: 0 }}>
+ <h2 id="create-space-modal-title" style={{ margin: 0, fontSize: 17, fontWeight: 650 }}>Create a shared space</h2>
+ <Tiny style={{ marginTop: 4 }}>
+ Spaces partition wiki pages, sources, and manual ingest into separate slug-prefixed folders
+ under the wiki root. Paperclip distillation and event capture always write into the
+ default space and skip new spaces created here - per-space Paperclip routing is a later
+ phase.
+ </Tiny>
+ </div>
+ <Button size="sm" variant="ghost" onClick={onClose} disabled={busy} title="Close">Close</Button>
+ </div>
+ <div style={{ padding: 20, display: "grid", gap: 16 }}>
+ <FormField label="Display name">
+ <TextInput
+ value={displayName}
+ autoFocus
+ onChange={(event) => {
+ setDisplayName(event.target.value);
+ if (!slugDirty) setSlug("");
+ }}
+ placeholder="Team research"
+ maxLength={120}
+ />
+ </FormField>
+ <FormField
+ label="Slug"
+ help={slugError ?? `Stored as the URL segment and the on-disk folder. Defaults to ${slugify(displayName) || "auto-derived from display name"}.`}
+ tone={slugError ? "danger" : "muted"}
+ >
+ <TextInput
+ value={slug || (slugDirty ? "" : slugify(displayName))}
+ onChange={(event) => {
+ setSlugDirty(true);
+ setSlug(event.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ""));
+ }}
+ placeholder="team-research"
+ style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace" }}
+ />
+ </FormField>
+ <FormField label="Type">
+ <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
+ <SegmentedOption selected label="Folder" onClick={() => undefined} />
+ <SegmentedOption disabled label="Cloud" suffix="Coming soon" onClick={() => undefined} />
+ </div>
+ </FormField>
+ <FormField label="Folder source" help="New managed folders create a slug-scoped subfolder under your wiki root. Existing folders must already live under the same wiki root.">
+ <div style={{ display: "grid", gap: 8 }}>
+ <FolderModeRow
+ checked={folderMode === "managed_subfolder"}
+ onSelect={() => setFolderMode("managed_subfolder")}
+ label="New managed folder"
+ help={`Creates spaces/${previewName.replace(/\s+/g, "-").toLowerCase()}/ under the configured wiki root with the standard skeleton.`}
+ />
+ <FolderModeRow
+ checked={folderMode === "existing_local_folder"}
+ onSelect={() => setFolderMode("existing_local_folder")}
+ label="Existing folder under wiki root"
+ help="Re-use a sub-folder you've already created inside the wiki root. The folder path is stored in the space settings."
+ />
+ <FolderModeRow
+ disabled
+ checked={false}
+ onSelect={() => undefined}
+ label="Existing absolute path"
+ help="Pending host capability — security review (PAP-3640) gates this until host-managed dynamic local-folder bindings ship."
+ suffix="Disabled"
+ />
+ </div>
+ </FormField>
+ <FormField label="Access scope" help="Access scope is metadata only. It does not currently enforce who can read or write the space, and it does not change which Paperclip sources reach the space.">
+ <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr 1fr", gap: 8 }}>
+ <ScopeTile
+ selected={accessScope === "shared"}
+ onSelect={() => setAccessScope("shared")}
+ label="Shared"
+ help="Visible to everyone in this company."
+ />
+ <ScopeTile
+ selected={accessScope === "personal"}
+ onSelect={() => setAccessScope("personal")}
+ label="Personal"
+ help="Future scope — stored only."
+ tag="Future"
+ />
+ <ScopeTile
+ selected={accessScope === "team"}
+ onSelect={() => setAccessScope("team")}
+ label="Team"
+ help="Future scope — stored only."
+ tag="Future"
+ />
+ </div>
+ </FormField>
+ {errorMsg ? <Callout tone="danger">{errorMsg}</Callout> : null}
+ </div>
+ <div style={{
+ padding: "12px 20px",
+ borderTop: `1px solid ${tokens.border}`,
+ display: "flex",
+ gap: 8,
+ justifyContent: isMobile ? "stretch" : "flex-end",
+ flexWrap: "wrap",
+ position: isMobile ? "sticky" : "static",
+ bottom: 0,
+ background: tokens.card,
+ }}>
+ <Button variant="ghost" onClick={onClose} disabled={busy} style={{ flex: isMobile ? 1 : undefined }}>Cancel</Button>
+ <Button variant="primary" onClick={submit} disabled={!canSubmit} loading={busy} style={{ flex: isMobile ? 1 : undefined }}>Create space</Button>
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function FormField({ label, help, tone = "muted", children }: { label: ReactNode; help?: ReactNode; tone?: "muted" | "danger"; children: ReactNode }) {
+ return (
+ <div style={{ display: "grid", gap: 6 }}>
+ <label style={{ fontSize: 12, fontWeight: 600, color: tokens.fg }}>{label}</label>
+ {children}
+ {help ? (
+ <span style={{ fontSize: 11, color: tone === "danger" ? "oklch(0.78 0.18 25)" : tokens.muted, lineHeight: 1.4 }}>{help}</span>
+ ) : null}
+ </div>
+ );
+}
+
+function SegmentedOption({ label, selected, disabled, suffix, onClick }: { label: string; selected?: boolean; disabled?: boolean; suffix?: string; onClick: () => void }) {
+ return (
+ <button
+ type="button"
+ onClick={disabled ? undefined : onClick}
+ disabled={disabled}
+ aria-pressed={selected}
+ aria-disabled={disabled}
+ style={{
+ padding: "8px 14px",
+ borderRadius: 6,
+ border: `1px solid ${selected ? tokens.border : tokens.border}`,
+ background: selected ? tokens.accent : "transparent",
+ color: disabled ? tokens.muted : tokens.fg,
+ fontSize: 13,
+ fontWeight: 600,
+ cursor: disabled ? "not-allowed" : "pointer",
+ opacity: disabled ? 0.6 : 1,
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 6,
+ fontFamily: fontStack,
+ }}
+ >
+ <span>{label}</span>
+ {suffix ? (
+ <span style={{
+ fontSize: 10,
+ fontWeight: 500,
+ padding: "1px 6px",
+ borderRadius: 3,
+ border: `1px dashed ${tokens.border}`,
+ color: tokens.muted,
+ }}>{suffix}</span>
+ ) : null}
+ </button>
+ );
+}
+
+function FolderModeRow({ checked, onSelect, label, help, disabled, suffix }: { checked: boolean; onSelect: () => void; label: string; help: string; disabled?: boolean; suffix?: string }) {
+ return (
+ <button
+ type="button"
+ onClick={disabled ? undefined : onSelect}
+ disabled={disabled}
+ style={{
+ display: "flex",
+ alignItems: "flex-start",
+ gap: 10,
+ padding: "10px 12px",
+ borderRadius: 8,
+ border: `1px solid ${checked ? tokens.fg : tokens.border}`,
+ background: "transparent",
+ color: tokens.fg,
+ textAlign: "left",
+ cursor: disabled ? "not-allowed" : "pointer",
+ opacity: disabled ? 0.55 : 1,
+ fontFamily: fontStack,
+ }}
+ >
+ <span
+ aria-hidden="true"
+ style={{
+ width: 14,
+ height: 14,
+ borderRadius: 7,
+ border: `2px solid ${checked ? tokens.fg : tokens.muted}`,
+ flexShrink: 0,
+ marginTop: 2,
+ background: checked ? tokens.fg : "transparent",
+ }}
+ />
+ <div style={{ display: "grid", gap: 2, flex: 1, minWidth: 0 }}>
+ <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
+ <span style={{ fontSize: 13, fontWeight: 600 }}>{label}</span>
+ {suffix ? <Badge tone="default" style={{ fontSize: 10 }}>{suffix}</Badge> : null}
+ </div>
+ <span style={{ fontSize: 11, color: tokens.muted, lineHeight: 1.4 }}>{help}</span>
+ </div>
+ </button>
+ );
+}
+
+function ScopeTile({ selected, onSelect, label, help, tag }: { selected: boolean; onSelect: () => void; label: string; help: string; tag?: string }) {
+ return (
+ <button
+ type="button"
+ onClick={onSelect}
+ style={{
+ padding: "10px 12px",
+ borderRadius: 8,
+ border: `1px solid ${selected ? tokens.fg : tokens.border}`,
+ background: selected ? tokens.accent : "transparent",
+ color: tokens.fg,
+ textAlign: "left",
+ display: "grid",
+ gap: 4,
+ cursor: "pointer",
+ fontFamily: fontStack,
+ }}
+ >
+ <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
+ <span style={{ fontSize: 13, fontWeight: 600 }}>{label}</span>
+ {tag ? <Badge tone="default" style={{ fontSize: 10 }}>{tag}</Badge> : null}
+ </div>
+ <span style={{ fontSize: 11, color: tokens.muted, lineHeight: 1.4 }}>{help}</span>
+ </button>
+ );
+}
+
+function compareSpaces(a: WikiSpace, b: WikiSpace): number {
+ if (a.slug === DEFAULT_SPACE_SLUG && b.slug !== DEFAULT_SPACE_SLUG) return -1;
+ if (b.slug === DEFAULT_SPACE_SLUG && a.slug !== DEFAULT_SPACE_SLUG) return 1;
+ return a.displayName.localeCompare(b.displayName, undefined, { sensitivity: "base" });
+}
+
+function activeWikiSpaces(spaces: WikiSpace[]): WikiSpace[] {
+ return spaces.filter((space) => space.status !== "archived");
+}
+
+function spaceTreeKey(spaceSlug: string, path: string): string {
+ return `${spaceSlug}::${path}`;
+}
+
+function SpacePageContentWarmup({ companyId, path, spaceSlug }: { companyId: string | null; path: string; spaceSlug: string }) {
+ usePageContent(companyId, path, spaceSlug);
+ return null;
+}
+
+function SpacePagesWarmup({ companyId, spaceSlug }: { companyId: string | null; spaceSlug: string }) {
+ const pages = usePages(companyId, { includeRaw: true, spaceSlug });
+ const selectedTreePath = firstSelectableTreePath(pages.data);
+ const selected = contentPathFromTreePath(selectedTreePath);
+ return selected ? <SpacePageContentWarmup companyId={companyId} path={selected} spaceSlug={spaceSlug} /> : null;
+}
+
+export function WikiRouteSidebar({ context }: PluginRouteSidebarProps) {
+ const hostNavigation = useHostNavigation();
+ const { pathname, search, state } = useHostLocation();
+ const activeSection = useMemo(() => readSectionFromLocation(pathname, search), [pathname, search]);
+ const activeSpaceSlug = useMemo(() => readActiveSpaceSlugFromLocation(pathname), [pathname]);
+ const companyName = context.companyPrefix ?? "Company";
+ const spacesQuery = useSpaces(context.companyId);
+ const spaces = useMemo(() => {
+ const list = spacesQuery.data?.spaces ?? [];
+ if (list.length === 0) return list;
+ return activeWikiSpaces(list).sort(compareSpaces);
+ }, [spacesQuery.data]);
+ const pages = usePages(context.companyId, { includeRaw: true, spaceSlug: activeSpaceSlug });
+ const activeSpaceNodes = useMemo(
+ () => buildBrowseTree(pages.data?.pages ?? [], pages.data?.sources ?? []),
+ [pages.data],
+ );
+ const warmupSpaces = useMemo(() => {
+ const active = spaces.find((space) => space.slug === activeSpaceSlug);
+ const rest = spaces.filter((space) => space.slug !== activeSpaceSlug);
+ return (active ? [active, ...rest] : rest).slice(0, WIKI_SPACE_PREFETCH_LIMIT);
+ }, [spaces, activeSpaceSlug]);
+ const storageKey = useMemo(() => routeSidebarExpandedStorageKey(context.companyId), [context.companyId]);
+ const [expandedRaw, setExpandedRaw] = useState<Set<string>>(() => readRouteSidebarExpandedPaths(storageKey));
+ const [selectedTreePath, setSelectedTreePath] = useState<string | null>(null);
+ const [spaceCollapse, setSpaceCollapse] = useState<Set<string>>(new Set());
+ const [createOpen, setCreateOpen] = useState(false);
+ const [openMenuFor, setOpenMenuFor] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (activeSection !== "browse") return;
+ const sidebarSelectedPath = readSidebarSelectedPathFromNavigationState(state);
+ if (sidebarSelectedPath === null) return;
+ setSelectedTreePath(sidebarSelectedPath);
+ }, [activeSection, state]);
+
+ useEffect(() => {
+ setExpandedRaw(readRouteSidebarExpandedPaths(storageKey));
+ }, [storageKey]);
+
+ useEffect(() => {
+ writeRouteSidebarExpandedPaths(storageKey, expandedRaw);
+ }, [expandedRaw, storageKey]);
+
+ useEffect(() => {
+ const ancestors = expandedAncestors(selectedTreePath);
+ if (ancestors.length === 0) return;
+ const slug = activeSpaceSlug;
+ setExpandedRaw((current) => {
+ const next = new Set(current);
+ let changed = false;
+ for (const ancestor of ancestors) {
+ const key = spaceTreeKey(slug, ancestor);
+ if (next.has(key)) continue;
+ next.add(key);
+ changed = true;
+ }
+ return changed ? next : current;
+ });
+ }, [selectedTreePath, activeSpaceSlug]);
+
+ // Project the per-space-prefixed expanded paths down to the active space's
+ // bare paths so FileTree (which is space-agnostic) can read them directly.
+ // Legacy entries written before this change have no `slug::` prefix and are
+ // treated as belonging to the default space.
+ const expandedForActiveSpace = useMemo(() => {
+ const next = new Set<string>();
+ const prefix = `${activeSpaceSlug}::`;
+ for (const entry of expandedRaw) {
+ if (entry.startsWith(prefix)) {
+ next.add(entry.slice(prefix.length));
+ } else if (!entry.includes("::") && activeSpaceSlug === DEFAULT_SPACE_SLUG) {
+ next.add(entry);
+ }
+ }
+ return next;
+ }, [expandedRaw, activeSpaceSlug]);
+
+ const handleToggleDir = (dirPath: string) => {
+ const key = spaceTreeKey(activeSpaceSlug, dirPath);
+ setExpandedRaw((current) => {
+ const next = new Set(current);
+ // For the default space, legacy un-prefixed entries also need to be
+ // removed so that the projection (which falls through legacy keys to
+ // default) does not leave a "ghost" expansion after a collapse click.
+ if (next.has(key)) {
+ next.delete(key);
+ if (activeSpaceSlug === DEFAULT_SPACE_SLUG) next.delete(dirPath);
+ } else if (activeSpaceSlug === DEFAULT_SPACE_SLUG && next.has(dirPath)) {
+ next.delete(dirPath);
+ } else {
+ next.add(key);
+ }
+ return next;
+ });
+ };
+
+ const toggleSpaceCollapse = (slug: string) => {
+ setSpaceCollapse((current) => {
+ const next = new Set(current);
+ if (next.has(slug)) next.delete(slug);
+ else next.add(slug);
+ return next;
+ });
+ };
+
+ const renderToolLink = ({ key, label, Icon }: (typeof SECTIONS)[number]) => {
+ const isLegacyLintSettingsActive = key === "settings" && activeSection === "lint";
+ const isActive = key === activeSection || isLegacyLintSettingsActive;
+ return (
+ <a
+ key={key}
+ {...hostNavigation.linkProps(buildSectionHref(key, activeSpaceSlug))}
+ aria-current={isActive ? "page" : undefined}
+ className={[
+ "flex items-center gap-2.5 rounded-md px-2 py-1.5 text-[13px] font-medium transition-colors",
+ isActive && !isLegacyLintSettingsActive
+ ? "bg-accent text-foreground"
+ : isActive
+ ? "text-foreground"
+ : "text-foreground/80 hover:bg-accent/50 hover:text-foreground",
+ ].join(" ")}
+ style={{ textDecoration: "none" }}
+ >
+ <span aria-hidden="true" className="shrink-0">
+ <Icon />
+ </span>
+ <span className="flex-1 truncate">{label}</span>
+ </a>
+ );
+ };
+
+ return (
+ <aside className="w-full h-full min-h-0 border-r border-border bg-background flex flex-col">
+ {warmupSpaces.map((space) => (
+ <SpacePagesWarmup key={space.slug} companyId={context.companyId} spaceSlug={space.slug} />
+ ))}
+ <div className="flex flex-col gap-1 px-3 py-3 shrink-0">
+ <a
+ {...hostNavigation.linkProps("/dashboard")}
+ className="flex items-center gap-1.5 rounded-md px-2 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent/50 hover:text-foreground"
+ style={{ textDecoration: "none" }}
+ >
+ <span aria-hidden="true" className="shrink-0">
+ <ChevronLeftIcon size={14} />
+ </span>
+ <span className="truncate">{companyName}</span>
+ </a>
+ </div>
+ <div className="flex-1 min-h-0 overflow-y-auto border-t border-border px-3 py-3">
+ <nav aria-label="Wiki primary" className="mb-3">
+ <div className="flex flex-col gap-0.5">
+ {TOP_TOOL_SECTIONS.map(renderToolLink)}
+ </div>
+ </nav>
+ <div className="mb-1 flex items-center gap-1 px-2 text-[11px] font-semibold uppercase tracking-normal text-muted-foreground" style={{ height: 24 }}>
+ <span
+ className="flex-1 truncate"
+ title="Destination spaces. Browsing and manual ingest happen in the active space; Paperclip distillation always writes into the default space in Phase 1."
+ >
+ Shared Spaces
+ </span>
+ <button
+ type="button"
+ aria-label="Create space"
+ title="Create space"
+ onClick={() => setCreateOpen(true)}
+ style={{
+ width: 22,
+ height: 22,
+ display: "inline-flex",
+ alignItems: "center",
+ justifyContent: "center",
+ border: "none",
+ background: "transparent",
+ color: tokens.muted,
+ borderRadius: 4,
+ cursor: "pointer",
+ }}
+ >
+ <PlusIcon size={14} />
+ </button>
+ </div>
+ {spacesQuery.error ? (
+ <div style={{ padding: "6px 8px", fontSize: 11, color: tokens.statusBlocked }}>
+ Failed to load spaces: {spacesQuery.error.message}
+ </div>
+ ) : null}
+ {spaces.length === 0 && spacesQuery.loading ? (
+ <Tiny style={{ padding: "6px 8px" }}>Loading spaces…</Tiny>
+ ) : null}
+ <div style={{ display: "flex", flexDirection: "column" }}>
+ {spaces.map((space) => {
+ const isActiveSpace = space.slug === activeSpaceSlug;
+ const collapsed = spaceCollapse.has(space.slug);
+ const showTree = isActiveSpace && !collapsed;
+ return (
+ <div key={space.slug} style={{ position: "relative" }}>
+ <SpaceRow
+ space={space}
+ active={isActiveSpace}
+ expanded={showTree}
+ hostNavigation={hostNavigation}
+ onToggleCollapse={() => {
+ if (!isActiveSpace) {
+ setSpaceCollapse((current) => {
+ if (!current.has(space.slug)) return current;
+ const next = new Set(current);
+ next.delete(space.slug);
+ return next;
+ });
+ hostNavigation.navigate(buildSectionHref("browse", space.slug));
+ } else {
+ toggleSpaceCollapse(space.slug);
+ }
+ }}
+ onMenuToggle={() => setOpenMenuFor((curr) => curr === space.slug ? null : space.slug)}
+ menuOpen={openMenuFor === space.slug}
+ onMenuClose={() => setOpenMenuFor(null)}
+ onArchived={(slug) => {
+ spacesQuery.refresh();
+ setOpenMenuFor(null);
+ setSpaceCollapse((current) => {
+ if (!current.has(slug)) return current;
+ const next = new Set(current);
+ next.delete(slug);
+ return next;
+ });
+ if (activeSpaceSlug === slug) {
+ hostNavigation.navigate(buildSectionHref("browse", DEFAULT_SPACE_SLUG));
+ }
+ }}
+ activeSpaceSlug={activeSpaceSlug}
+ companyId={context.companyId}
+ />
+ {showTree ? (
+ <div style={{ paddingLeft: 18, marginTop: 2, marginBottom: 6 }}>
+ <FileTree
+ nodes={activeSpaceNodes}
+ selectedFile={selectedTreePath}
+ expandedPaths={expandedForActiveSpace}
+ onSelectFile={(path) => {
+ setSelectedTreePath(path);
+ hostNavigation.navigate(buildPageHref(path, space.slug), { state: wikiSidebarNavigationState(path) });
+ }}
+ onToggleDir={handleToggleDir}
+ wrapLabels={false}
+ loading={pages.loading}
+ error={pages.error ? { message: pages.error.message } : null}
+ empty={{ title: "No pages yet", description: "Add content to populate this space." }}
+ ariaLabel={`Wiki pages in ${space.displayName}`}
+ />
+ </div>
+ ) : null}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ <nav
+ aria-label="Wiki secondary"
+ className="shrink-0 border-t border-border px-3 py-3"
+ >
+ <div className="flex flex-col gap-0.5">
+ {BOTTOM_TOOL_SECTIONS.map(renderToolLink)}
+ </div>
+ </nav>
+ {createOpen && context.companyId ? (
+ <CreateSpaceModal
+ companyId={context.companyId}
+ existingSlugs={new Set(spaces.map((s) => s.slug))}
+ onClose={() => setCreateOpen(false)}
+ onCreated={(space) => {
+ setCreateOpen(false);
+ spacesQuery.refresh();
+ hostNavigation.navigate(buildSectionHref("browse", space.slug));
+ }}
+ />
+ ) : null}
+ </aside>
+ );
+}
+
+function SpaceRow({
+ space,
+ active,
+ expanded,
+ hostNavigation,
+ onToggleCollapse,
+ onMenuToggle,
+ menuOpen,
+ onMenuClose,
+ onArchived,
+ activeSpaceSlug,
+ companyId,
+}: {
+ space: WikiSpace;
+ active: boolean;
+ expanded: boolean;
+ hostNavigation: ReturnType<typeof useHostNavigation>;
+ onToggleCollapse: () => void;
+ onMenuToggle: () => void;
+ menuOpen: boolean;
+ onMenuClose: () => void;
+ onArchived: (slug: string) => void;
+ activeSpaceSlug: string;
+ companyId: string | null;
+}) {
+ const [hover, setHover] = useState(false);
+ const isDefault = space.slug === DEFAULT_SPACE_SLUG;
+ return (
+ <div
+ role="button"
+ tabIndex={0}
+ aria-expanded={expanded}
+ aria-label={`${expanded ? "Collapse" : active ? "Expand" : "Open"} ${space.displayName} space`}
+ onMouseEnter={() => setHover(true)}
+ onMouseLeave={() => setHover(false)}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ padding: "6px 8px",
+ borderRadius: 6,
+ cursor: "pointer",
+ background: active ? tokens.accent : "transparent",
+ position: "relative",
+ }}
+ onClick={onToggleCollapse}
+ onKeyDown={(event) => {
+ if (event.target !== event.currentTarget) return;
+ if (event.key !== "Enter" && event.key !== " ") return;
+ event.preventDefault();
+ onToggleCollapse();
+ }}
+ >
+ <span aria-hidden="true" style={{ color: tokens.muted, display: "flex", flexShrink: 0, transform: expanded ? "rotate(0)" : "rotate(0)" }}>
+ {expanded ? <ChevronDownIcon size={14} /> : <ChevronRightIcon size={14} />}
+ </span>
+ <span aria-hidden="true" style={{ color: tokens.muted, display: "flex", flexShrink: 0 }}>
+ <FolderIcon size={16} />
+ </span>
+ <span style={{ flex: 1, fontSize: 13, fontWeight: 600, color: tokens.fg, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
+ {space.displayName}
+ </span>
+ {space.accessScope === "personal" ? (
+ <Badge tone="default" style={{ height: 18, padding: "0 6px", fontSize: 10 }}>personal</Badge>
+ ) : space.accessScope === "team" ? (
+ <Badge tone="default" style={{ height: 18, padding: "0 6px", fontSize: 10 }}>team</Badge>
+ ) : null}
+ <button
+ type="button"
+ aria-label={`${space.displayName} space menu`}
+ title="Space menu"
+ onClick={(event) => {
+ event.stopPropagation();
+ onMenuToggle();
+ }}
+ style={{
+ opacity: hover || menuOpen ? 1 : 0,
+ transition: "opacity 80ms ease",
+ width: 22,
+ height: 22,
+ display: "inline-flex",
+ alignItems: "center",
+ justifyContent: "center",
+ border: "none",
+ background: "transparent",
+ color: tokens.fg,
+ borderRadius: 4,
+ cursor: "pointer",
+ }}
+ >
+ <MoreHorizontalIcon size={14} />
+ </button>
+ {menuOpen ? (
+ <SpaceRowMenu
+ space={space}
+ isDefault={isDefault}
+ hostNavigation={hostNavigation}
+ activeSpaceSlug={activeSpaceSlug}
+ companyId={companyId}
+ onClose={onMenuClose}
+ onArchived={onArchived}
+ />
+ ) : null}
+ </div>
+ );
+}
+
+function SpaceRowMenu({
+ space,
+ isDefault,
+ hostNavigation,
+ activeSpaceSlug,
+ companyId,
+ onClose,
+ onArchived,
+}: {
+ space: WikiSpace;
+ isDefault: boolean;
+ hostNavigation: ReturnType<typeof useHostNavigation>;
+ activeSpaceSlug: string;
+ companyId: string | null;
+ onClose: () => void;
+ onArchived: (slug: string) => void;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const archive = usePluginAction("archive-space");
+ const bootstrap = usePluginAction("bootstrap-space");
+ const toast = usePluginToast();
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ const handler = (event: MouseEvent) => {
+ if (!ref.current) return;
+ if (event.target instanceof Node && ref.current.contains(event.target)) return;
+ onClose();
+ };
+ const keyHandler = (event: KeyboardEvent) => {
+ if (event.key === "Escape") onClose();
+ };
+ document.addEventListener("mousedown", handler);
+ document.addEventListener("keydown", keyHandler);
+ return () => {
+ document.removeEventListener("mousedown", handler);
+ document.removeEventListener("keydown", keyHandler);
+ };
+ }, [onClose]);
+
+ const handleArchive = async () => {
+ if (!companyId || isDefault || busy) return;
+ if (typeof window !== "undefined" && !window.confirm(`Archive ${space.displayName}? Pages remain on disk; you can restore later through the plugin API or by un-archiving from the database.`)) {
+ return;
+ }
+ setBusy(true);
+ try {
+ await archive({ companyId, spaceSlug: space.slug });
+ toast({ tone: "success", title: "Space archived", body: `${space.displayName} hidden from sidebar.` });
+ onArchived(space.slug);
+ } catch (err) {
+ toast({ tone: "error", title: "Archive failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const handleRefresh = async () => {
+ if (!companyId || busy) return;
+ setBusy(true);
+ try {
+ await bootstrap({ companyId, spaceSlug: space.slug });
+ toast({ tone: "success", title: "Space refreshed", body: `${space.displayName} index re-bootstrapped.` });
+ onClose();
+ } catch (err) {
+ toast({ tone: "error", title: "Refresh failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <div
+ ref={ref}
+ role="menu"
+ onClick={(event) => event.stopPropagation()}
+ style={{
+ position: "absolute",
+ top: "calc(100% + 4px)",
+ right: 0,
+ zIndex: 30,
+ minWidth: 220,
+ background: tokens.card,
+ border: `1px solid ${tokens.border}`,
+ borderRadius: 8,
+ boxShadow: "0 12px 36px rgba(0,0,0,0.45)",
+ padding: 4,
+ }}
+ >
+ <SpaceMenuItem
+ label="Edit space"
+ Icon={PencilIcon}
+ onClick={() => {
+ onClose();
+ hostNavigation.navigate(buildSettingsSectionHref("spaces", activeSpaceSlug, space.slug));
+ }}
+ />
+ <SpaceMenuItem
+ label="Refresh index"
+ Icon={RefreshIcon}
+ onClick={handleRefresh}
+ disabled={busy}
+ />
+ <SpaceMenuItem
+ label="Open ingest"
+ Icon={PlusCircleIcon}
+ onClick={() => {
+ onClose();
+ hostNavigation.navigate(buildSectionHref("ingest", space.slug));
+ }}
+ />
+ <SpaceMenuDivider />
+ <SpaceMenuItem
+ label={isDefault ? "Archive space (default cannot be archived)" : "Archive space…"}
+ Icon={ArchiveIcon}
+ onClick={handleArchive}
+ disabled={isDefault || busy}
+ destructive
+ />
+ </div>
+ );
+}
+
+function SpaceMenuItem({
+ label,
+ Icon,
+ onClick,
+ disabled,
+ destructive,
+}: {
+ label: string;
+ Icon: (props: LucideIconProps) => ReactElement;
+ onClick: () => void;
+ disabled?: boolean;
+ destructive?: boolean;
+}) {
+ return (
+ <button
+ type="button"
+ role="menuitem"
+ onClick={onClick}
+ disabled={disabled}
+ style={{
+ width: "100%",
+ display: "flex",
+ alignItems: "center",
+ gap: 10,
+ padding: "7px 10px",
+ background: "transparent",
+ border: "none",
+ cursor: disabled ? "not-allowed" : "pointer",
+ color: destructive ? "oklch(0.7 0.2 25)" : tokens.fg,
+ opacity: disabled ? 0.5 : 1,
+ fontSize: 13,
+ textAlign: "left",
+ borderRadius: 4,
+ fontFamily: fontStack,
+ }}
+ onMouseEnter={(event) => {
+ if (disabled) return;
+ event.currentTarget.style.background = tokens.accent;
+ }}
+ onMouseLeave={(event) => {
+ event.currentTarget.style.background = "transparent";
+ }}
+ >
+ <span aria-hidden="true" style={{ display: "flex", color: destructive ? "oklch(0.7 0.2 25)" : tokens.muted }}>
+ <Icon size={14} />
+ </span>
+ <span style={{ flex: 1 }}>{label}</span>
+ </button>
+ );
+}
+
+function SpaceMenuDivider() {
+ return <div style={{ height: 1, background: tokens.border, margin: "4px 0" }} />;
+}
+
+const shellStyle: CSSProperties = {
+ display: "flex",
+ flexDirection: "column",
+ height: "100%",
+ minHeight: 600,
+ background: tokens.bg,
+ color: tokens.fg,
+ fontFamily: fontStack,
+ fontSize: 14,
+};
+
+// ---------------------------------------------------------------------------
+// Pre-flight: prompt for folder before any tab can be useful.
+// ---------------------------------------------------------------------------
+
+function UnconfiguredFolder({ context, folder, refresh }: { context: { companyId: string | null }; folder?: FolderStatus; refresh: () => void }) {
+ const bootstrap = usePluginAction("bootstrap-root");
+ const toast = usePluginToast();
+ const isMobile = useIsMobileLayout();
+ const [path, setPath] = useState(folder?.path ?? "");
+ const [busy, setBusy] = useState(false);
+ const [errorMsg, setErrorMsg] = useState<string | null>(null);
+ const configuredButUnhealthy = Boolean(folder?.configured);
+
+ useEffect(() => {
+ setPath(folder?.path ?? "");
+ }, [folder?.path]);
+
+ async function submit() {
+ if (!context.companyId || !path.trim()) return;
+ setBusy(true);
+ setErrorMsg(null);
+ try {
+ const result = await bootstrap({ companyId: context.companyId, path: path.trim() });
+ const written = (result as { writtenFiles?: string[] }).writtenFiles ?? [];
+ toast({ tone: "success", title: "Wiki root configured", body: written.length ? `Created ${written.length} bootstrap file(s).` : "Existing files preserved." });
+ refresh();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ setErrorMsg(message);
+ toast({ tone: "error", title: "Could not configure wiki root", body: message });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <div style={{ flex: 1, padding: isMobile ? 16 : 28, display: "grid", placeItems: "start", overflow: isMobile ? "visible" : "auto", minWidth: 0 }}>
+ <Card style={{ maxWidth: 720, width: "100%" }}>
+ <CardHeader title={configuredButUnhealthy ? "Repair wiki root folder" : "Choose a wiki root folder"} />
+ <CardBody>
+ <Tiny style={{ marginBottom: 12 }}>
+ {configuredButUnhealthy
+ ? "The configured wiki root is not ready. Update the path or repair it to recreate required baseline files."
+ : "Pick an absolute path on this machine. The plugin creates "}
+ {!configuredButUnhealthy ? <><Mono>raw/</Mono>, <Mono>wiki/</Mono>, <Mono>AGENTS.md</Mono>, <Mono>IDEA.md</Mono>, <Mono>wiki/index.md</Mono>, and <Mono>wiki/log.md</Mono> if they don't already exist.</> : null}
+ </Tiny>
+ {folder?.problems?.length ? (
+ <Callout tone="danger">
+ <div style={{ display: "grid", gap: 6 }}>
+ {folder.problems.map((problem, index) => (
+ <div key={`${problem.code}:${problem.path ?? index}`}>
+ {problem.message}{problem.path ? <> <Mono>{problem.path}</Mono></> : null}
+ </div>
+ ))}
+ </div>
+ </Callout>
+ ) : null}
+ <div style={{ display: "grid", gap: 12 }}>
+ {folder ? <FolderHealthChecklist folder={folder} /> : null}
+ <FolderPathPicker
+ value={path}
+ onChange={setPath}
+ onApply={submit}
+ applyLabel={configuredButUnhealthy ? "Repair & bootstrap" : "Configure & bootstrap"}
+ busy={busy}
+ disabled={!path.trim()}
+ />
+ <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
+ <Button variant="ghost" onClick={() => refresh()}>I already configured it</Button>
+ </div>
+ {errorMsg ? <Callout tone="danger">{errorMsg}</Callout> : null}
+ </div>
+ </CardBody>
+ </Card>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Browse tab: selected page detail. The route sidebar owns the file tree.
+// ---------------------------------------------------------------------------
+
+const TEMPLATE_PATHS = ["AGENTS.md", "IDEA.md"] as const;
+const BASELINE_DIRECTORIES = ["raw", "wiki", "wiki/sources", "wiki/projects", "wiki/entities", "wiki/concepts", "wiki/synthesis"] as const;
+const BASELINE_FILES = [...TEMPLATE_PATHS, "wiki/index.md", "wiki/log.md"] as const;
+const BASELINE_TREE_ORDER = new Map<string, number>([
+ ["AGENTS.md", 0],
+ ["IDEA.md", 1],
+ ["raw", 2],
+ ["wiki", 3],
+ ["wiki/index.md", 0],
+ ["wiki/log.md", 1],
+ ["wiki/sources", 2],
+ ["wiki/projects", 3],
+ ["wiki/entities", 4],
+ ["wiki/concepts", 5],
+ ["wiki/synthesis", 6],
+]);
+
+function basename(path: string): string {
+ return path.split("/").pop() ?? path;
+}
+
+function dirname(path: string): string {
+ const idx = path.lastIndexOf("/");
+ return idx === -1 ? "" : path.slice(0, idx);
+}
+
+function ensureDir(roots: FileTreeNode[], dirPath: string): FileTreeNode {
+ const segments = dirPath.split("/").filter(Boolean);
+ let parentChildren = roots;
+ let currentPath = "";
+ let currentNode: FileTreeNode | null = null;
+ for (const segment of segments) {
+ currentPath = currentPath ? `${currentPath}/${segment}` : segment;
+ let next = parentChildren.find((c) => c.kind === "dir" && c.path === currentPath);
+ if (!next) {
+ next = { name: segment, path: currentPath, kind: "dir", children: [] };
+ parentChildren.push(next);
+ }
+ parentChildren = next.children;
+ currentNode = next;
+ }
+ if (!currentNode) {
+ throw new Error(`ensureDir called with empty path`);
+ }
+ return currentNode;
+}
+
+function pageDisplayName(path: string, title: string | null): string {
+ const trimmed = title?.trim();
+ return trimmed ? trimmed : basename(path);
+}
+
+function treeDisplayName(path: string, title: string | null): string {
+ return (BASELINE_FILES as readonly string[]).includes(path) ? basename(path) : pageDisplayName(path, title);
+}
+
+function buildBrowseTree(
+ pages: WikiPageRow[],
+ sources: WikiSourceRow[],
+): FileTreeNode[] {
+ const roots: FileTreeNode[] = [];
+ const seenPaths = new Set<string>();
+
+ for (const dirPath of BASELINE_DIRECTORIES) {
+ ensureDir(roots, dirPath);
+ }
+
+ if (sources.length > 0) {
+ const rawDir = ensureDir(roots, "raw");
+ for (const source of sources) {
+ seenPaths.add(source.rawPath);
+ const node: FileTreeNode = {
+ name: pageDisplayName(source.rawPath, source.title),
+ path: source.rawPath,
+ kind: "file",
+ children: [],
+ };
+ rawDir.children.push(node);
+ }
+ }
+
+ for (const page of pages) {
+ seenPaths.add(page.path);
+ const parentDir = dirname(page.path);
+ const file: FileTreeNode = {
+ name: treeDisplayName(page.path, page.title),
+ path: page.path,
+ kind: "file",
+ children: [],
+ };
+ if (parentDir) {
+ ensureDir(roots, parentDir).children.push(file);
+ } else {
+ roots.push(file);
+ }
+ }
+
+ // Add the baseline files using their real wiki-root paths so the browser
+ // mirrors the on-disk default layout even before metadata has been indexed.
+ for (const path of BASELINE_FILES) {
+ if (seenPaths.has(path)) continue;
+ const parentDir = dirname(path);
+ const node = {
+ name: basename(path),
+ path,
+ kind: "file" as const,
+ children: [],
+ action: path,
+ };
+ seenPaths.add(path);
+ if (parentDir) {
+ ensureDir(roots, parentDir).children.push(node);
+ continue;
+ }
+ roots.push({
+ ...node,
+ name: path,
+ });
+ }
+
+ function sortNodes(nodes: FileTreeNode[]) {
+ nodes.sort((a, b) => {
+ const orderA = BASELINE_TREE_ORDER.get(a.path);
+ const orderB = BASELINE_TREE_ORDER.get(b.path);
+ if (orderA != null || orderB != null) return (orderA ?? Number.MAX_SAFE_INTEGER) - (orderB ?? Number.MAX_SAFE_INTEGER);
+ if (a.kind !== b.kind) return a.kind === "dir" ? -1 : 1;
+ return a.name.localeCompare(b.name);
+ });
+ for (const node of nodes) {
+ if (node.kind === "dir") sortNodes(node.children);
+ }
+ }
+ sortNodes(roots);
+
+ return roots;
+}
+
+function expandedAncestors(path: string | null): string[] {
+ if (!path) return [];
+ const out: string[] = [];
+ const segments = path.split("/").filter(Boolean);
+ let current = "";
+ for (let i = 0; i < segments.length - 1; i++) {
+ current = current ? `${current}/${segments[i]}` : segments[i];
+ out.push(current);
+ }
+ return out;
+}
+
+function BrowseTab({ context }: { context: { companyId: string | null } }) {
+ const { pathname, search } = useHostLocation();
+ const activeSpaceSlug = useMemo(() => readActiveSpaceSlugFromLocation(pathname), [pathname]);
+ const pages = usePages(context.companyId, { includeRaw: true, spaceSlug: activeSpaceSlug });
+ const isMobile = useIsMobileLayout();
+ const selectedTreePath = readSelectedTreePathFromLocation(pathname, search) ?? firstSelectableTreePath(pages.data);
+ const selected = contentPathFromTreePath(selectedTreePath);
+
+ return (
+ <div style={{ flex: 1, minWidth: 0, overflow: isMobile ? "visible" : "auto" }}>
+ {pages.loading && !selected ? (
+ <div style={{ padding: isMobile ? 16 : 28, color: tokens.muted, fontSize: 13 }}>Loading pages…</div>
+ ) : pages.error && !selected ? (
+ <div style={{ padding: isMobile ? 16 : 28 }}><Callout tone="danger">Failed to load pages: {pages.error.message}</Callout></div>
+ ) : (
+ <PageDetail context={context} path={selected} spaceSlug={activeSpaceSlug} />
+ )}
+ </div>
+ );
+}
+
+function PageDetail({ context, path, spaceSlug }: { context: { companyId: string | null }; path: string | null; spaceSlug?: string }) {
+ const content = usePageContent(context.companyId, path, spaceSlug ?? null);
+ const writePage = usePluginAction("write-page");
+ const toast = usePluginToast();
+ const hostNavigation = useHostNavigation();
+ const isMobile = useIsMobileLayout();
+ const markdownBodyRef = useRef<HTMLDivElement | null>(null);
+ const [editing, setEditing] = useState(false);
+ const [savedHash, setSavedHash] = useState<string | null>(null);
+ const [provenanceOpen, setProvenanceOpen] = useState(false);
+ const [tocOpen, setTocOpen] = useState(true);
+ const [activeTocId, setActiveTocId] = useState<string | null>(null);
+ const parsedMarkdown = useMemo(() => parseWikiMarkdown(content.data?.contents ?? ""), [content.data?.contents]);
+ const tocHeadings = useMemo(() => extractWikiTocHeadings(parsedMarkdown.body), [parsedMarkdown.body]);
+
+ useEffect(() => {
+ setEditing(false);
+ setSavedHash(null);
+ setTocOpen(true);
+ setActiveTocId(null);
+ }, [path]);
+
+ useEffect(() => {
+ if (!content.data || editing) return;
+ const root = markdownBodyRef.current;
+ if (!root) return;
+ const renderedHeadings = Array.from(root.querySelectorAll("h2, h3, h4"));
+ tocHeadings.forEach((heading, index) => {
+ const element = renderedHeadings[index];
+ if (element instanceof HTMLElement) {
+ element.id = heading.id;
+ }
+ });
+ }, [content.data, editing, tocHeadings]);
+
+ useEffect(() => {
+ if (!content.data || editing || tocHeadings.length === 0) return;
+ const root = markdownBodyRef.current;
+ if (!root) return;
+
+ const scrollParent = findScrollableAncestor(root);
+ const updateActiveHeading = () => {
+ const containerTop = scrollParent instanceof HTMLElement ? scrollParent.getBoundingClientRect().top : 0;
+ const activationY = containerTop + 96;
+ let activeId = tocHeadings[0]?.id ?? null;
+
+ for (const heading of tocHeadings) {
+ const element = root.ownerDocument.getElementById(heading.id);
+ if (!(element instanceof HTMLElement)) continue;
+ if (!root.contains(element)) continue;
+ if (element.getBoundingClientRect().top <= activationY) {
+ activeId = heading.id;
+ } else {
+ break;
+ }
+ }
+
+ setActiveTocId(activeId);
+ };
+
+ updateActiveHeading();
+ scrollParent.addEventListener("scroll", updateActiveHeading, { passive: true });
+ window.addEventListener("resize", updateActiveHeading);
+ return () => {
+ scrollParent.removeEventListener("scroll", updateActiveHeading);
+ window.removeEventListener("resize", updateActiveHeading);
+ };
+ }, [content.data, editing, tocHeadings]);
+
+ const editable = path ? isEditableWikiPagePath(path) : false;
+ const resolveWikiLinkHref = useCallback(
+ (target: string) => buildWikiLinkHref(target, hostNavigation.resolveHref),
+ [hostNavigation.resolveHref],
+ );
+ const handleTocClick = useCallback((event: React.MouseEvent<HTMLAnchorElement>, id: string) => {
+ const root = markdownBodyRef.current;
+ const target = root?.ownerDocument.getElementById(id);
+ if (!(target instanceof HTMLElement)) return;
+ if (root && !root.contains(target)) return;
+ event.preventDefault();
+ setActiveTocId(id);
+ target.scrollIntoView({ block: "start", behavior: "smooth" });
+ if (typeof window !== "undefined") {
+ window.history.replaceState(window.history.state, "", `${window.location.pathname}${window.location.search}#${id}`);
+ }
+ }, []);
+ const savePageContents = useCallback(async (nextContents: string) => {
+ if (!context.companyId || !content.data || !editable || !path) return;
+ const result = await writePage({
+ companyId: context.companyId,
+ wikiId: content.data.wikiId,
+ spaceSlug: spaceSlug ?? null,
+ path,
+ contents: nextContents,
+ expectedHash: savedHash ?? content.data.hash,
+ summary: `Edited ${path} from the LLM Wiki page`,
+ }) as { hash?: string };
+ if (typeof result.hash === "string") setSavedHash(result.hash);
+ }, [context.companyId, content.data, editable, path, savedHash, writePage, spaceSlug]);
+
+ if (!path) return <div style={{ padding: isMobile ? 16 : 28, color: tokens.muted, fontSize: 13 }}>Pick a page from the tree.</div>;
+ if (content.loading) return <div style={{ padding: isMobile ? 16 : 28, color: tokens.muted, fontSize: 13 }}>Loading {path}…</div>;
+ if (content.error && path.startsWith("raw/")) {
+ return (
+ <div style={{ padding: isMobile ? 16 : 28, display: "grid", gap: 12 }}>
+ <Callout tone="warn">
+ The captured source <Mono>{path}</Mono> is indexed but no longer exists in the configured wiki folder. Refresh the wiki or re-ingest the source to restore it.
+ </Callout>
+ <Tiny>{content.error.message}</Tiny>
+ </div>
+ );
+ }
+ if (content.error) return <div style={{ padding: isMobile ? 16 : 28 }}><Callout tone="danger">Failed to read {path}: {content.error.message}</Callout></div>;
+ if (!content.data) return <div style={{ padding: isMobile ? 16 : 28, color: tokens.muted, fontSize: 13 }}>No content for {path}.</div>;
+ const { contents, title, sourceRefs, updatedAt, hash } = content.data;
+ const visibleFrontmatter = parsedMarkdown.frontmatter.filter((property) => property.key.toLowerCase() !== "title");
+ const displayTitle = (BASELINE_FILES as readonly string[]).includes(path) ? basename(path) : title ?? basename(path);
+ const folderPath = dirname(path);
+
+ const isDistilledProjectPage = path.startsWith("wiki/projects/");
+ const showToc = !editing && tocHeadings.length > 0;
+ const displaySourceRefs = sourceRefs
+ .map((ref, index) => ({
+ id: sourceRefIdentity(ref, index),
+ label: formatSourceRef(ref, index),
+ hasDisplayText: typeof ref === "string" || readSourceRefField(ref, "title") !== null,
+ }))
+ .filter((ref) => ref.hasDisplayText);
+
+ return (
+ <article style={{ padding: isMobile ? "16px" : "24px 28px", display: "grid", gap: isMobile ? 12 : 14, minWidth: 0 }}>
+ <header style={{ display: "grid", gap: 8, minWidth: 0 }}>
+ <div style={{ display: "flex", alignItems: "flex-start", gap: 12, flexWrap: "wrap", minWidth: 0 }}>
+ <div style={{ flex: "1 1 260px", minWidth: 0 }}>
+ {folderPath ? <Tiny style={{ display: "block", marginBottom: 6 }}><Mono>{folderPath}</Mono></Tiny> : null}
+ <h1 style={{ margin: 0, fontSize: isMobile ? 20 : 22, overflowWrap: "anywhere" }}>{displayTitle}</h1>
+ </div>
+ <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
+ {isDistilledProjectPage ? (
+ <Button size="sm" variant="ghost" onClick={() => setProvenanceOpen(true)} title="Show source provenance and freshness">
+ <InfoIcon size={12} /> Provenance
+ </Button>
+ ) : null}
+ {editable && !editing ? (
+ <Button size="sm" onClick={() => { setSavedHash(hash); setEditing(true); }}>Edit page</Button>
+ ) : editable ? (
+ <Button size="sm" variant="ghost" onClick={() => { setEditing(false); content.refresh(); }}>Done</Button>
+ ) : (
+ <Badge>read-only source</Badge>
+ )}
+ </div>
+ </div>
+ <Tiny>Updated {updatedAt ? formatTime(updatedAt) : "—"}</Tiny>
+ </header>
+ {isDistilledProjectPage && path ? (
+ <FreshnessChip companyId={context.companyId} pagePath={path} companyPrefix={(context as { companyPrefix?: string | null }).companyPrefix ?? null} />
+ ) : null}
+ {editing ? (
+ <>
+ <AutosaveMarkdownEditor
+ key={`${path}:${hash}`}
+ resetKey={`${path}:${hash}`}
+ value={contents}
+ placeholder={`Edit ${path}`}
+ minHeight={isMobile ? 260 : 420}
+ onSave={async (nextContents) => {
+ await savePageContents(nextContents);
+ toast({ tone: "success", title: `${path} saved` });
+ }}
+ />
+ </>
+ ) : (
+ <div
+ data-testid="llm-wiki-page-content-layout"
+ style={{
+ display: "grid",
+ gridTemplateColumns: showToc && !isMobile ? `minmax(0, 1fr) ${tocOpen ? "minmax(180px, 240px)" : "36px"}` : "minmax(0, 1fr)",
+ gap: showToc && !isMobile ? (tocOpen ? 24 : 10) : 0,
+ alignItems: "start",
+ minWidth: 0,
+ }}
+ >
+ <div style={{ display: "grid", gap: isMobile ? 12 : 14, minWidth: 0 }}>
+ <div ref={markdownBodyRef} style={{ minWidth: 0, fontSize: 13, lineHeight: 1.65 }}>
+ <FrontmatterProperties properties={visibleFrontmatter} />
+ <MarkdownBlock
+ content={parsedMarkdown.body}
+ enableWikiLinks
+ resolveWikiLinkHref={resolveWikiLinkHref}
+ />
+ {displaySourceRefs.length > 0 ? (
+ <section aria-label="Paperclip source refs" style={{ marginTop: 16, display: "grid", gap: 6 }}>
+ <Tiny style={{ fontWeight: 650 }}>Paperclip source refs</Tiny>
+ <ul style={{ margin: 0, paddingLeft: 18, color: tokens.muted, fontSize: 12, lineHeight: 1.5 }}>
+ {displaySourceRefs.map((ref) => (
+ <li key={ref.id}>{ref.label}</li>
+ ))}
+ </ul>
+ </section>
+ ) : null}
+ </div>
+ </div>
+ {showToc ? (
+ <OnThisPagePane
+ headings={tocHeadings}
+ activeHeadingId={activeTocId}
+ open={tocOpen}
+ onToggle={() => setTocOpen((current) => !current)}
+ onHeadingClick={handleTocClick}
+ mobile={isMobile}
+ />
+ ) : null}
+ </div>
+ )}
+ {provenanceOpen && path ? (
+ <ProvenanceDrawer
+ companyId={context.companyId}
+ pagePath={path}
+ onClose={() => setProvenanceOpen(false)}
+ />
+ ) : null}
+ </article>
+ );
+}
+
+function findScrollableAncestor(element: HTMLElement): HTMLElement | Window {
+ let current: HTMLElement | null = element.parentElement;
+ while (current && current !== document.body && current !== document.documentElement) {
+ const style = window.getComputedStyle(current);
+ const overflowY = style.overflowY;
+ if ((overflowY === "auto" || overflowY === "scroll") && current.scrollHeight > current.clientHeight) {
+ return current;
+ }
+ current = current.parentElement;
+ }
+ return window;
+}
+
+function OnThisPagePane({
+ headings,
+ activeHeadingId,
+ open,
+ onToggle,
+ onHeadingClick,
+ mobile,
+}: {
+ headings: WikiTocHeading[];
+ activeHeadingId: string | null;
+ open: boolean;
+ onToggle: () => void;
+ onHeadingClick: (event: React.MouseEvent<HTMLAnchorElement>, id: string) => void;
+ mobile: boolean;
+}) {
+ const contentId = "llm-wiki-on-this-page";
+ const currentHeadingId = activeHeadingId ?? headings[0]?.id ?? null;
+ const shellRef = useRef<HTMLElement | null>(null);
+ const [fixedFrame, setFixedFrame] = useState<{ left: number; top: number; width: number } | null>(null);
+
+ useEffect(() => {
+ if (mobile) {
+ setFixedFrame(null);
+ return;
+ }
+ const shell = shellRef.current;
+ if (!shell) return;
+
+ let animationFrame = 0;
+ const updateFrame = () => {
+ cancelAnimationFrame(animationFrame);
+ animationFrame = requestAnimationFrame(() => {
+ const rect = shell.getBoundingClientRect();
+ const top = Math.max(WIKI_TOC_STICKY_TOP, rect.top);
+ setFixedFrame((current) => {
+ if (
+ current &&
+ Math.abs(current.left - rect.left) < 0.5 &&
+ Math.abs(current.top - top) < 0.5 &&
+ Math.abs(current.width - rect.width) < 0.5
+ ) {
+ return current;
+ }
+ return { left: rect.left, top, width: rect.width };
+ });
+ });
+ };
+
+ updateFrame();
+ const resizeObserver = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(updateFrame);
+ resizeObserver?.observe(shell);
+ window.addEventListener("resize", updateFrame);
+ window.addEventListener("scroll", updateFrame, true);
+ return () => {
+ cancelAnimationFrame(animationFrame);
+ resizeObserver?.disconnect();
+ window.removeEventListener("resize", updateFrame);
+ window.removeEventListener("scroll", updateFrame, true);
+ };
+ }, [mobile, open]);
+
+ const paneStyle: CSSProperties = mobile ? {} : fixedFrame ? {
+ position: "fixed",
+ top: fixedFrame.top,
+ left: fixedFrame.left,
+ width: fixedFrame.width,
+ maxHeight: `calc(100vh - ${fixedFrame.top + 16}px)`,
+ overflowY: "auto",
+ zIndex: 2,
+ } : {
+ position: "sticky",
+ top: WIKI_TOC_STICKY_TOP,
+ };
+
+ return (
+ <aside
+ ref={shellRef}
+ aria-label="On this page"
+ style={{
+ order: mobile ? -1 : 0,
+ minWidth: 0,
+ minHeight: mobile ? undefined : open ? 120 : 24,
+ alignSelf: "start",
+ }}
+ >
+ <div style={{
+ ...paneStyle,
+ borderLeft: open ? `1px solid ${tokens.border}` : 0,
+ paddingLeft: open ? 10 : 0,
+ }}>
+ <button
+ type="button"
+ aria-label={open ? "Collapse on this page" : "Expand on this page"}
+ aria-expanded={open}
+ aria-controls={contentId}
+ onClick={onToggle}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: open ? "space-between" : "center",
+ gap: 10,
+ width: "100%",
+ border: 0,
+ background: "transparent",
+ color: tokens.fg,
+ padding: open ? "0 0 8px" : "0",
+ fontFamily: fontStack,
+ fontSize: 12,
+ fontWeight: 650,
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ {open ? <span>On this page</span> : null}
+ <span aria-hidden="true" style={{ color: tokens.muted, transform: open ? "rotate(90deg)" : "rotate(0deg)", transition: "transform 120ms ease" }}>
+ <ChevronLeftIcon size={13} />
+ </span>
+ </button>
+ {open ? (
+ <nav id={contentId} style={{ display: "grid", gap: 2 }}>
+ {headings.map((heading) => {
+ const active = heading.id === currentHeadingId;
+ return (
+ <a
+ key={heading.id}
+ href={`#${heading.id}`}
+ aria-current={active ? "location" : undefined}
+ onClick={(event) => onHeadingClick(event, heading.id)}
+ style={{
+ display: "block",
+ padding: `3px 0 3px ${Math.max(0, heading.level - 2) * 12}px`,
+ color: active ? tokens.fg : tokens.muted,
+ fontSize: 12,
+ fontWeight: active ? 700 : 450,
+ lineHeight: 1.35,
+ textDecoration: "none",
+ overflowWrap: "anywhere",
+ }}
+ >
+ {heading.text}
+ </a>
+ );
+ })}
+ </nav>
+ ) : null}
+ </div>
+ </aside>
+ );
+}
+
+function FreshnessChip({ companyId, pagePath, companyPrefix }: { companyId: string | null; pagePath: string; companyPrefix: string | null }) {
+ const provenance = useDistillationProvenance(companyId, pagePath);
+ const binding = provenance.data?.binding ?? null;
+ const cursor = provenance.data?.cursor ?? null;
+
+ if (provenance.loading && !provenance.data) {
+ return <FreshnessChipShell tone="info" icon={<ClockIcon size={14} />}>Checking distillation cursor…</FreshnessChipShell>;
+ }
+ if (!binding) return null;
+
+ const lastEnd = binding.lastRunSourceWindowEnd ?? binding.lastRunCompletedAt;
+ const status = binding.lastRunStatus ?? "unknown";
+ const sourceCount = (() => {
+ const meta = binding.metadata as Record<string, unknown>;
+ const refs = Array.isArray(meta.sourceRefs) ? meta.sourceRefs.length : null;
+ return refs;
+ })();
+ const isStale = (() => {
+ if (status === "failed" || status === "refused_cost_cap") return true;
+ if (!lastEnd) return true;
+ const diff = Date.now() - Date.parse(lastEnd);
+ return Number.isFinite(diff) ? diff > 72 * 60 * 60 * 1000 : true;
+ })();
+ const isFailed = status === "failed" || status === "refused_cost_cap";
+ const isRunning = status === "running";
+
+ const tone: "info" | "warn" | "danger" | "running" = isFailed ? "danger" : isStale ? "warn" : isRunning ? "running" : "info";
+ const projectLink = cursor && cursor.projectId && companyPrefix ? `/${companyPrefix}/projects/${cursor.projectId}` : null;
+
+ return (
+ <FreshnessChipShell
+ tone={tone}
+ icon={isFailed ? <AlertTriangleIcon size={14} /> : isRunning ? <ActivityIcon size={14} /> : <ClockIcon size={14} />}
+ >
+ <span><strong>Current as of {lastEnd ? formatTimestamp(lastEnd) : "—"}.</strong>
+ {sourceCount ? ` ${sourceCount} sources in this window. ` : " "}
+ Cursor at <Mono>{lastEnd ?? "—"}</Mono>.
+ </span>
+ {projectLink ? (
+ <a href={projectLink} style={{ marginLeft: 8, color: "inherit", textDecoration: "underline" }}>
+ Open Paperclip for live state →
+ </a>
+ ) : null}
+ </FreshnessChipShell>
+ );
+}
+
+function FreshnessChipShell({ tone, icon, children }: { tone: "info" | "warn" | "danger" | "running"; icon: ReactNode; children: ReactNode }) {
+ const palette = tone === "danger"
+ ? { bg: "oklch(0.22 0.06 25)", fg: "oklch(0.85 0.12 25)", border: "oklch(0.45 0.12 25)" }
+ : tone === "warn"
+ ? { bg: "oklch(0.22 0.06 70)", fg: "oklch(0.85 0.1 70)", border: "oklch(0.45 0.12 70)" }
+ : tone === "running"
+ ? { bg: "oklch(0.22 0.06 200)", fg: "oklch(0.85 0.11 200)", border: "oklch(0.45 0.12 200)" }
+ : tokens.callout;
+ return (
+ <div style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 8,
+ padding: "8px 12px",
+ borderRadius: 999,
+ background: palette.bg,
+ color: palette.fg,
+ border: `1px solid ${palette.border}`,
+ fontSize: 12.5,
+ lineHeight: 1.5,
+ flexWrap: "wrap",
+ }}>
+ {icon}
+ <div style={{ display: "flex", alignItems: "center", gap: 4, flexWrap: "wrap" }}>
+ {children}
+ </div>
+ </div>
+ );
+}
+
+function readSourceRefField(ref: Record<string, unknown>, field: string): string | null {
+ const value = ref[field];
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
+}
+
+function sourceRefIdentity(ref: Record<string, unknown> | string, fallbackIndex: number): string {
+ if (typeof ref === "string") return ref;
+ const issueIdentifier = readSourceRefField(ref, "issueIdentifier");
+ const issueId = readSourceRefField(ref, "issueId");
+ const commentId = readSourceRefField(ref, "commentId");
+ const documentKey = readSourceRefField(ref, "documentKey");
+ const documentId = readSourceRefField(ref, "documentId");
+ const kind = readSourceRefField(ref, "kind");
+ const parts = [kind, issueIdentifier ?? issueId, commentId, documentKey ?? documentId].filter(Boolean);
+ return parts.length > 0 ? parts.join(":") : `source-ref-${fallbackIndex}`;
+}
+
+function formatSourceRef(ref: Record<string, unknown> | string, fallbackIndex: number): string {
+ if (typeof ref === "string") return ref;
+
+ const kind = readSourceRefField(ref, "kind");
+ const issue = readSourceRefField(ref, "issueIdentifier") ?? readSourceRefField(ref, "issueId");
+ const title = readSourceRefField(ref, "title");
+ const commentId = readSourceRefField(ref, "commentId");
+ const documentKey = readSourceRefField(ref, "documentKey");
+ const documentId = readSourceRefField(ref, "documentId");
+
+ const primary = issue ?? sourceRefIdentity(ref, fallbackIndex);
+ const suffix = kind === "comment" && commentId
+ ? ` comment ${commentId.slice(0, 8)}`
+ : kind === "document" && (documentKey || documentId)
+ ? ` document ${documentKey ?? documentId?.slice(0, 8)}`
+ : kind ? ` ${kind}` : "";
+ return title ? `${primary}${suffix} - ${title}` : `${primary}${suffix}`;
+}
+
+function ProvenanceDrawer({ companyId, pagePath, onClose }: { companyId: string | null; pagePath: string; onClose: () => void }) {
+ const isMobile = useIsMobileLayout();
+ const provenance = useDistillationProvenance(companyId, pagePath);
+ const data = provenance.data;
+ const binding = data?.binding ?? null;
+ const cursor = data?.cursor ?? null;
+ const snapshot = data?.snapshot ?? null;
+ const runs = data?.runs ?? [];
+
+ return (
+ <div
+ onClick={onClose}
+ style={{
+ position: "fixed",
+ inset: 0,
+ background: "oklch(0 0 0 / 0.55)",
+ zIndex: 50,
+ display: "flex",
+ justifyContent: isMobile ? "stretch" : "flex-end",
+ alignItems: isMobile ? "flex-end" : "stretch",
+ }}
+ >
+ <div
+ onClick={(event) => event.stopPropagation()}
+ style={{
+ background: tokens.bg,
+ borderLeft: isMobile ? undefined : `1px solid ${tokens.border}`,
+ borderTop: isMobile ? `1px solid ${tokens.border}` : undefined,
+ width: isMobile ? "100%" : 420,
+ maxWidth: "100%",
+ maxHeight: isMobile ? "85vh" : "100vh",
+ display: "flex",
+ flexDirection: "column",
+ }}
+ >
+ <div style={{ padding: "14px 18px", borderBottom: `1px solid ${tokens.border}`, display: "flex", alignItems: "center", gap: 10 }}>
+ <InfoIcon size={16} />
+ <strong style={{ fontSize: 14, flex: 1 }}>Provenance</strong>
+ <Button variant="ghost" size="sm" onClick={onClose}>
+ <XIcon size={14} />
+ </Button>
+ </div>
+ <div style={{ overflow: "auto", flex: 1, padding: 18, display: "flex", flexDirection: "column", gap: 14 }}>
+ {provenance.loading && !data ? <Tiny>Loading provenance…</Tiny> : null}
+ {!binding && !provenance.loading ? <Callout>This page is not currently bound to a distillation cursor. It may be hand-authored or pre-distillation.</Callout> : null}
+ {binding ? (
+ <Card>
+ <CardBody padding={14}>
+ <PropRow label="Page path" value={<Mono>{binding.pagePath}</Mono>} />
+ <PropRow label="Source hash" value={<Mono>{binding.lastRunSourceHash?.slice(0, 16) ?? "—"}…</Mono>} />
+ <PropRow label="Cursor end" value={<Mono>{binding.lastRunSourceWindowEnd ? formatTimestamp(binding.lastRunSourceWindowEnd) : "—"}</Mono>} />
+ <PropRow label="Last run status" value={<Badge tone={runStatusTone(binding.lastRunStatus ?? "")}>{binding.lastRunStatus ?? "—"}</Badge>} />
+ <PropRow label="Project" value={binding.projectName ?? "—"} />
+ <PropRow label="Updated" value={formatTimestamp(binding.updatedAt)} />
+ </CardBody>
+ </Card>
+ ) : null}
+ {cursor ? (
+ <Card>
+ <CardHeader title="Cursor" />
+ <CardBody padding={14}>
+ <PropRow label="Scope" value={cursor.sourceScope} />
+ <PropRow label="Pending events" value={String(cursor.pendingEventCount)} />
+ <PropRow label="Last observed" value={formatTimestamp(cursor.lastObservedAt)} />
+ <PropRow label="Last processed" value={formatTimestamp(cursor.lastProcessedAt)} />
+ </CardBody>
+ </Card>
+ ) : null}
+ {snapshot ? (
+ <Card>
+ <CardHeader title="Sources in this window" />
+ <CardBody padding={14}>
+ <Tiny style={{ marginBottom: 8 }}>{snapshot.sourceRefs.length} ref{snapshot.sourceRefs.length === 1 ? "" : "s"}{snapshot.clipped ? " · clipped" : ""}</Tiny>
+ <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12, color: tokens.muted, lineHeight: 1.5 }}>
+ {snapshot.sourceRefs.slice(0, 8).map((ref, index) => {
+ const obj = typeof ref === "object" && ref ? ref as Record<string, unknown> : null;
+ const id = obj && typeof obj.id === "string" ? obj.id : typeof ref === "string" ? ref : `ref-${index}`;
+ const kind = obj && typeof obj.kind === "string" ? obj.kind : null;
+ const title = obj && typeof obj.title === "string" ? obj.title : null;
+ return (
+ <li key={`${id}-${index}`} style={{ marginBottom: 4 }}>
+ <Mono>{id}</Mono>
+ {kind ? ` · ${kind}` : ""}
+ {title ? ` · ${title}` : ""}
+ </li>
+ );
+ })}
+ </ul>
+ {snapshot.sourceRefs.length > 8 ? <Tiny style={{ marginTop: 6 }}>{`+${snapshot.sourceRefs.length - 8} more`}</Tiny> : null}
+ </CardBody>
+ </Card>
+ ) : null}
+ {runs.length > 0 ? (
+ <Card>
+ <CardHeader title="Operations affecting this page" />
+ <CardBody padding={0}>
+ <ul style={{ margin: 0, padding: 0, listStyle: "none" }}>
+ {runs.slice(0, 8).map((run) => (
+ <li key={run.id} style={{ padding: "10px 14px", borderBottom: `1px solid ${tokens.border}`, display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
+ <Mono style={{ fontSize: 12 }}>{run.operationIssueIdentifier ?? `op-${run.id.slice(0, 6)}`}</Mono>
+ <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
+ <Tiny>{formatTimestamp(run.updatedAt)}</Tiny>
+ <Mono style={{ fontSize: 11 }}>{formatCostCents(run.costCents)}</Mono>
+ <Badge tone={runStatusTone(run.status)}>{runStatusLabel(run.status)}</Badge>
+ </div>
+ </li>
+ ))}
+ </ul>
+ </CardBody>
+ </Card>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function FrontmatterProperties({ properties }: { properties: WikiFrontmatterProperty[] }) {
+ if (properties.length === 0) return null;
+
+ return (
+ <details
+ open
+ style={{
+ marginBottom: 20,
+ paddingBottom: 16,
+ borderBottom: `1px solid ${tokens.border}`,
+ }}
+ >
+ <summary
+ style={{
+ cursor: "pointer",
+ color: tokens.fg,
+ fontSize: 13,
+ fontWeight: 650,
+ listStylePosition: "outside",
+ marginBottom: 10,
+ }}
+ >
+ Properties
+ </summary>
+ <dl style={{ display: "grid", gap: 8, margin: 0, maxWidth: 720 }}>
+ {properties.map((property) => (
+ <div
+ key={property.key}
+ style={{
+ display: "grid",
+ gridTemplateColumns: "minmax(96px, 0.32fr) minmax(0, 1fr)",
+ gap: 12,
+ alignItems: "baseline",
+ minWidth: 0,
+ }}
+ >
+ <dt style={{ color: tokens.muted, fontSize: 12, minWidth: 0, overflowWrap: "anywhere" }}>{property.key}</dt>
+ <dd style={{ margin: 0, minWidth: 0 }}>
+ <FrontmatterValue value={property.value} />
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </details>
+ );
+}
+
+function FrontmatterValue({ value }: { value: WikiFrontmatterValue }) {
+ if (Array.isArray(value)) {
+ return (
+ <span style={{ display: "flex", flexWrap: "wrap", gap: 6, minWidth: 0 }}>
+ {value.map((item) => (
+ <span
+ key={item}
+ style={{
+ display: "inline-flex",
+ alignItems: "center",
+ minWidth: 0,
+ maxWidth: "100%",
+ padding: "1px 7px",
+ borderRadius: 999,
+ background: "var(--secondary, oklch(0.269 0 0))",
+ color: tokens.fg,
+ fontSize: 12,
+ lineHeight: 1.5,
+ overflowWrap: "anywhere",
+ }}
+ >
+ {item}
+ </span>
+ ))}
+ </span>
+ );
+ }
+
+ return (
+ <span style={{ color: tokens.fg, fontSize: 13, overflowWrap: "anywhere" }}>
+ {value}
+ </span>
+ );
+}
+
+function Row({ primary, secondary, right }: { primary: ReactNode; secondary?: ReactNode; right?: ReactNode }) {
+ return (
+ <div style={{
+ display: "flex",
+ alignItems: "center",
+ flexWrap: "wrap",
+ gap: 12,
+ padding: "8px 12px",
+ borderBottom: `1px solid ${tokens.border}`,
+ fontSize: 13,
+ minWidth: 0,
+ }}>
+ <div style={{ flex: "1 1 220px", minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "normal", overflowWrap: "anywhere" }}>{primary}</div>
+ {secondary ? <div style={{ flex: "0 1 auto", minWidth: 0, color: tokens.muted, fontSize: 12, overflowWrap: "anywhere" }}>{secondary}</div> : null}
+ {right ? <div style={{ marginLeft: "auto", minWidth: 0, display: "flex", gap: 6, alignItems: "center", justifyContent: "flex-end", flexWrap: "wrap" }}>{right}</div> : null}
+ </div>
+ );
+}
+
+function formatTime(iso: string | null | undefined): string {
+ if (!iso) return "—";
+ try {
+ const date = new Date(iso);
+ if (Number.isNaN(date.getTime())) return iso;
+ const diffMs = Date.now() - date.getTime();
+ const minutes = Math.floor(diffMs / 60000);
+ if (minutes < 1) return "just now";
+ if (minutes < 60) return `${minutes}m ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.floor(hours / 24);
+ if (days < 30) return `${days}d ago`;
+ return date.toLocaleDateString();
+ } catch {
+ return iso;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Ingest tab.
+// ---------------------------------------------------------------------------
+
+function IngestTab({ context, refreshOverview }: { context: { companyId: string | null }; refreshOverview: () => void }) {
+ const { pathname } = useHostLocation();
+ const activeSpaceSlug = useMemo(() => readActiveSpaceSlugFromLocation(pathname), [pathname]);
+ const spacesQuery = useSpaces(context.companyId);
+ const spaces = useMemo(() => {
+ const list = spacesQuery.data?.spaces ?? [];
+ return activeWikiSpaces(list).sort(compareSpaces);
+ }, [spacesQuery.data]);
+ const ingest = usePluginAction("ingest-source");
+ const toast = usePluginToast();
+ const hostNavigation = useHostNavigation();
+ const isMobile = useIsMobileLayout();
+ const [url, setUrl] = useState("");
+ const [pasted, setPasted] = useState("");
+ const [title, setTitle] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [errorMsg, setErrorMsg] = useState<string | null>(null);
+ const [spaceMenuOpen, setSpaceMenuOpen] = useState(false);
+ const [createOpen, setCreateOpen] = useState(false);
+
+ const activeSpace = useMemo(() => {
+ return spaces.find((space) => space.slug === activeSpaceSlug)
+ ?? spaces.find((space) => space.slug === DEFAULT_SPACE_SLUG)
+ ?? null;
+ }, [spaces, activeSpaceSlug]);
+
+ const canSubmit = !!context.companyId && (pasted.trim().length > 0 || url.trim().length > 0) && !busy;
+
+ useEffect(() => {
+ const refresh = () => refreshOverview();
+ window.addEventListener("pc-wiki-ingest-queued", refresh);
+ return () => window.removeEventListener("pc-wiki-ingest-queued", refresh);
+ }, [refreshOverview]);
+
+ async function submit() {
+ if (!context.companyId) return;
+ setBusy(true);
+ setErrorMsg(null);
+ try {
+ let contents = pasted.trim();
+ let sourceType: "url" | "text" = "text";
+ let resolvedTitle = title.trim();
+ if (url.trim()) {
+ sourceType = "url";
+ contents = pasted.trim() || `Captured URL: ${url.trim()}\n\n_Plugin needs to fetch the URL — placeholder body for the alpha._`;
+ resolvedTitle = resolvedTitle || url.trim();
+ } else {
+ resolvedTitle = resolvedTitle || pasted.split("\n", 1)[0]?.slice(0, 80) || "Pasted source";
+ }
+ await ingest({
+ companyId: context.companyId,
+ spaceSlug: activeSpaceSlug,
+ sourceType,
+ url: url.trim() || null,
+ title: resolvedTitle,
+ contents,
+ });
+ const spaceLabel = activeSpace?.displayName ?? activeSpaceSlug;
+ toast({ tone: "success", title: `Source captured into ${spaceLabel}`, body: `Operation issue created. Check History to inspect.` });
+ setUrl("");
+ setPasted("");
+ setTitle("");
+ refreshOverview();
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ setErrorMsg(message);
+ toast({ tone: "error", title: "Ingest failed", body: message });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ const spaceLabel = activeSpace?.displayName ?? activeSpaceSlug;
+
+ return (
+ <div style={{ flex: 1, minHeight: isMobile ? "auto" : 0, minWidth: 0, overflow: isMobile ? "visible" : "auto" }}>
+ <div style={{
+ padding: isMobile ? "16px" : "24px 28px",
+ maxWidth: 920,
+ minWidth: 0,
+ }}>
+ <div style={{ marginBottom: 4, fontSize: 11, fontWeight: 600, letterSpacing: "0.04em", textTransform: "uppercase", color: tokens.muted }}>Add Content</div>
+ <h2 style={{ margin: "0 0 6px", fontSize: 18, fontWeight: 650 }}>Capture into <span style={{ color: tokens.fg }}>{spaceLabel}</span></h2>
+ <Tiny style={{ marginBottom: 18 }}>
+ Each capture queues an ingest operation scoped to <Mono>{activeSpaceSlug}</Mono>. Files land in that space's <Mono>raw/</Mono> folder and the Wiki Maintainer proposes a patch.
+ </Tiny>
+ <div style={{ display: "grid", gap: 14, marginBottom: 18 }}>
+ <SpacePicker
+ spaces={spaces}
+ activeSpaceSlug={activeSpaceSlug}
+ loading={spacesQuery.loading}
+ error={spacesQuery.error?.message ?? null}
+ isOpen={spaceMenuOpen}
+ onToggle={() => setSpaceMenuOpen((v) => !v)}
+ onClose={() => setSpaceMenuOpen(false)}
+ onSelect={(slug) => {
+ setSpaceMenuOpen(false);
+ hostNavigation.navigate(buildSectionHref("ingest", slug));
+ }}
+ onCreate={() => {
+ setSpaceMenuOpen(false);
+ setCreateOpen(true);
+ }}
+ />
+ <div>
+ <label style={{ fontSize: 11, color: tokens.muted, display: "block", marginBottom: 6 }}>Drop files anywhere on this page</label>
+ <div style={{
+ minHeight: isMobile ? 180 : 230,
+ border: `1.5px dashed ${tokens.pluginBorder}`,
+ borderRadius: 8,
+ padding: isMobile ? 20 : 30,
+ display: "flex",
+ flexDirection: "column",
+ justifyContent: "center",
+ alignItems: "center",
+ gap: 10,
+ textAlign: "center",
+ color: tokens.muted,
+ background: tokens.pluginBg,
+ }}>
+ <div style={{ display: "inline-flex", alignItems: "center", justifyContent: "center", width: 46, height: 46, borderRadius: 8, background: tokens.card, color: tokens.pluginFg, border: `1px solid ${tokens.pluginBorder}` }}>
+ <DownloadCloudIcon size={24} />
+ </div>
+ <div style={{ fontSize: 16, fontWeight: 650, color: tokens.fg }}>Drop source files here</div>
+ <Tiny>Review staged files before queueing maintainer tasks.</Tiny>
+ </div>
+ </div>
+ <div data-testid="llm-wiki-ingest-manual-separator" aria-hidden="true" style={{ display: "flex", alignItems: "center", gap: 12, color: tokens.muted, fontSize: 11, fontWeight: 650, textTransform: "uppercase", letterSpacing: "0.04em" }}>
+ <span style={{ height: 1, flex: 1, background: tokens.border }} />
+ <span>or</span>
+ <span style={{ height: 1, flex: 1, background: tokens.border }} />
+ </div>
+ <div>
+ <label style={{ fontSize: 11, color: tokens.muted, display: "block", marginBottom: 4 }}>Source title (optional)</label>
+ <TextInput value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. Karpathy LLM Wiki gist" />
+ </div>
+ <div>
+ <label style={{ fontSize: 11, color: tokens.muted, display: "block", marginBottom: 4 }}>URL</label>
+ <TextInput value={url} onChange={(e) => setUrl(e.target.value)} placeholder="https://example.com/article" />
+ </div>
+ <div>
+ <label style={{ fontSize: 11, color: tokens.muted, display: "block", marginBottom: 4 }}>Paste markdown / text</label>
+ <TextArea value={pasted} onChange={(e) => setPasted(e.target.value)} placeholder="Paste source content…" rows={8} />
+ </div>
+ </div>
+ <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
+ <Button variant="primary" onClick={submit} disabled={!canSubmit} loading={busy}>+ Capture & ingest</Button>
+ </div>
+ {errorMsg ? <div style={{ marginTop: 14 }}><Callout tone="danger">{errorMsg}</Callout></div> : null}
+ </div>
+ {createOpen && context.companyId ? (
+ <CreateSpaceModal
+ companyId={context.companyId}
+ existingSlugs={new Set(spaces.map((s) => s.slug))}
+ onClose={() => setCreateOpen(false)}
+ onCreated={(space) => {
+ setCreateOpen(false);
+ spacesQuery.refresh();
+ hostNavigation.navigate(buildSectionHref("ingest", space.slug));
+ }}
+ />
+ ) : null}
+ </div>
+ );
+}
+
+function SpacePicker({
+ spaces,
+ activeSpaceSlug,
+ loading,
+ error,
+ isOpen,
+ onToggle,
+ onClose,
+ onSelect,
+ onCreate,
+}: {
+ spaces: WikiSpace[];
+ activeSpaceSlug: string;
+ loading: boolean;
+ error: string | null;
+ isOpen: boolean;
+ onToggle: () => void;
+ onClose: () => void;
+ onSelect: (slug: string) => void;
+ onCreate: () => void;
+}) {
+ const ref = useRef<HTMLDivElement>(null);
+ const active = spaces.find((s) => s.slug === activeSpaceSlug);
+ useEffect(() => {
+ if (!isOpen) return;
+ const handler = (event: MouseEvent) => {
+ if (!ref.current) return;
+ if (event.target instanceof Node && ref.current.contains(event.target)) return;
+ onClose();
+ };
+ document.addEventListener("mousedown", handler);
+ return () => document.removeEventListener("mousedown", handler);
+ }, [isOpen, onClose]);
+ return (
+ <div ref={ref} style={{ position: "relative" }}>
+ <label style={{ fontSize: 11, color: tokens.muted, display: "block", marginBottom: 4 }}>Space</label>
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-haspopup="listbox"
+ aria-expanded={isOpen}
+ style={{
+ width: "100%",
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ background: "oklch(0.2 0 0)",
+ border: `1px solid ${tokens.border}`,
+ borderRadius: 6,
+ padding: "8px 10px",
+ color: tokens.fg,
+ fontFamily: fontStack,
+ fontSize: 13,
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <FolderIcon size={14} />
+ <span style={{ flex: 1, fontWeight: 600 }}>{active?.displayName ?? activeSpaceSlug}</span>
+ {active ? (
+ <Badge tone="default" style={{ fontSize: 10, padding: "0 6px" }}>{active.accessScope}</Badge>
+ ) : null}
+ <ChevronDownIcon size={14} />
+ </button>
+ <div style={{ marginTop: 6, fontSize: 11, color: tokens.muted, lineHeight: 1.4 }}>
+ Defaults to the space you opened. Switching now re-routes the page so deep links carry the destination.
+ </div>
+ {isOpen ? (
+ <div
+ role="listbox"
+ style={{
+ position: "absolute",
+ top: "calc(100% + 4px)",
+ left: 0,
+ right: 0,
+ zIndex: 25,
+ background: tokens.card,
+ border: `1px solid ${tokens.border}`,
+ borderRadius: 8,
+ boxShadow: "0 16px 40px rgba(0,0,0,0.45)",
+ padding: 4,
+ maxHeight: 320,
+ overflowY: "auto",
+ }}
+ >
+ {error ? <div style={{ padding: 10, fontSize: 12, color: tokens.statusBlocked }}>{error}</div> : null}
+ {loading ? <div style={{ padding: 10 }}><Tiny>Loading spaces…</Tiny></div> : null}
+ {spaces.map((space) => (
+ <button
+ key={space.slug}
+ type="button"
+ role="option"
+ aria-selected={space.slug === activeSpaceSlug}
+ onClick={() => onSelect(space.slug)}
+ style={{
+ width: "100%",
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ padding: "8px 10px",
+ background: space.slug === activeSpaceSlug ? tokens.accent : "transparent",
+ border: "none",
+ borderRadius: 6,
+ color: tokens.fg,
+ fontSize: 13,
+ fontFamily: fontStack,
+ cursor: "pointer",
+ textAlign: "left",
+ }}
+ >
+ <FolderIcon size={14} />
+ <span style={{ flex: 1, fontWeight: 600 }}>{space.displayName}</span>
+ <span style={{ fontSize: 10, color: tokens.muted, fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace" }}>{space.slug}</span>
+ </button>
+ ))}
+ <SpaceMenuDivider />
+ <button
+ type="button"
+ onClick={onCreate}
+ style={{
+ width: "100%",
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ padding: "8px 10px",
+ background: "transparent",
+ border: "none",
+ borderRadius: 6,
+ color: "oklch(0.78 0.13 250)",
+ fontSize: 13,
+ fontFamily: fontStack,
+ cursor: "pointer",
+ textAlign: "left",
+ fontWeight: 600,
+ }}
+ >
+ <PlusIcon size={14} />
+ <span>New shared space…</span>
+ </button>
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+function OperationCard({ op }: { op: WikiOperationRow }) {
+ return (
+ <Card>
+ <div style={{ padding: "12px 14px" }}>
+ <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap", minWidth: 0 }}>
+ <StatusIcon status={op.status} />
+ <strong style={{ flex: "1 1 180px", minWidth: 0, fontSize: 13, overflowWrap: "anywhere" }}>{op.hiddenIssueTitle ?? `LLM Wiki ${op.operationType}`}</strong>
+ <Badge tone={statusTone(op.status)} style={{ marginLeft: "auto" }}>{op.status}</Badge>
+ </div>
+ <Tiny style={{ marginTop: 4 }}>
+ {op.operationType.toUpperCase()} · started {formatTime(op.createdAt)} · op-{op.id.slice(0, 6)}
+ {op.hiddenIssueIdentifier ? <> · <Mono>{op.hiddenIssueIdentifier}</Mono></> : null}
+ </Tiny>
+ {Array.isArray(op.warnings) && op.warnings.length > 0 ? (
+ <Tiny style={{ marginTop: 4, color: tokens.statusBlocked }}>
+ {op.warnings.length} warning{op.warnings.length === 1 ? "" : "s"}
+ </Tiny>
+ ) : null}
+ </div>
+ </Card>
+ );
+}
+
+function statusTone(status: string): Tone {
+ if (status === "done") return "done";
+ if (status === "running" || status === "in_progress") return "running";
+ if (status === "blocked" || status === "failed") return "failed";
+ if (status === "queued" || status === "todo") return "todo";
+ if (status === "paused") return "paused";
+ return "default";
+}
+
+// ---------------------------------------------------------------------------
+// Ask tab.
+// ---------------------------------------------------------------------------
+
+type QueryThreadEntry = {
+ id: string;
+ prompt: string;
+ operationId: string | null;
+ querySessionId: string | null;
+ hiddenIssueIdentifier: string | null;
+ channel: string | null;
+ status: "queued" | "running" | "done" | "error";
+ createdAt: string;
+ answer: string;
+ errorMessage?: string;
+};
+
+type QueryStreamEvent = {
+ type: string;
+ operationId?: string;
+ querySessionId?: string;
+ message?: string | null;
+ payload?: Record<string, unknown> | null;
+ eventType?: string;
+ stream?: string | null;
+ answer?: string;
+};
+
+function QueryTab({ context, overview }: { context: { companyId: string | null }; overview: OverviewData }) {
+ const startQuery = usePluginAction("start-query");
+ const fileAsPage = usePluginAction("file-as-page");
+ const toast = usePluginToast();
+ const { pathname } = useHostLocation();
+ const activeSpaceSlug = useMemo(() => readActiveSpaceSlugFromLocation(pathname), [pathname]);
+ const isMobile = useIsMobileLayout();
+ const [thread, setThread] = useState<QueryThreadEntry[]>([]);
+ const [prompt, setPrompt] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [filePath, setFilePath] = useState("wiki/concepts/new-page.md");
+ const [fileBody, setFileBody] = useState("");
+ const [filing, setFiling] = useState<string | null>(null);
+ const fileSource = useMemo(() => {
+ for (let i = thread.length - 1; i >= 0; i -= 1) {
+ const entry = thread[i];
+ if (entry.answer.trim()) return entry;
+ }
+ return null;
+ }, [thread]);
+
+ const activeEntry = useMemo(() => {
+ for (let i = thread.length - 1; i >= 0; i -= 1) {
+ const entry = thread[i];
+ if (entry.status === "running" || entry.status === "queued") return entry;
+ }
+ return null;
+ }, [thread]);
+
+ const stream = usePluginStream<QueryStreamEvent>(activeEntry?.channel ?? "llm-wiki:idle", {
+ companyId: context.companyId ?? undefined,
+ });
+
+ useEffect(() => {
+ if (!activeEntry || !stream.lastEvent) return;
+ const event = stream.lastEvent;
+ setThread((prev) => prev.map((entry) => {
+ if (entry.id !== activeEntry.id) return entry;
+ if (event.type === "agent.event" && event.eventType === "chunk" && event.message && event.stream !== "stderr") {
+ return { ...entry, answer: entry.answer + event.message, status: "running" };
+ }
+ if (event.type === "query.done") {
+ return { ...entry, status: "done", answer: event.answer ?? entry.answer };
+ }
+ if (event.type === "query.error") {
+ return { ...entry, status: "error", errorMessage: event.message ?? "agent session error" };
+ }
+ return entry;
+ }));
+ if (event.type === "query.done" && event.answer && !fileBody.trim()) {
+ setFileBody(event.answer);
+ }
+ }, [fileBody, stream.lastEvent, activeEntry?.id]);
+
+ async function send() {
+ if (!context.companyId || !prompt.trim()) return;
+ setBusy(true);
+ const entryId = `q-${Date.now()}`;
+ setThread((prev) => [...prev, {
+ id: entryId,
+ prompt: prompt.trim(),
+ operationId: null,
+ querySessionId: null,
+ hiddenIssueIdentifier: null,
+ channel: null,
+ status: "queued",
+ createdAt: new Date().toISOString(),
+ answer: "",
+ }]);
+ try {
+ const res = await startQuery({ companyId: context.companyId, spaceSlug: activeSpaceSlug, question: prompt.trim() });
+ const result = res as {
+ operationId: string;
+ querySessionId?: string;
+ channel?: string;
+ issue?: { identifier?: string | null };
+ };
+ setThread((prev) => prev.map((entry) =>
+ entry.id === entryId ? {
+ ...entry,
+ operationId: result.operationId,
+ querySessionId: result.querySessionId ?? result.operationId,
+ hiddenIssueIdentifier: result.issue?.identifier ?? null,
+ channel: result.channel ?? `llm-wiki:query:${result.operationId}`,
+ status: "running",
+ } : entry,
+ ));
+ setPrompt("");
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ setThread((prev) => prev.map((entry) =>
+ entry.id === entryId ? { ...entry, status: "error", errorMessage: message } : entry,
+ ));
+ toast({ tone: "error", title: "Ask failed", body: message });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function fileAnswer(entry?: QueryThreadEntry) {
+ const source = entry ?? fileSource;
+ const answer = fileBody.trim() || source?.answer.trim() || "";
+ if (!context.companyId || !filePath.trim() || !answer) return;
+ setFiling(source?.id ?? "manual");
+ try {
+ await fileAsPage({
+ companyId: context.companyId,
+ wikiId: overview.wikiId,
+ spaceSlug: activeSpaceSlug,
+ path: filePath.trim(),
+ question: source?.prompt,
+ answer,
+ querySessionId: source?.querySessionId,
+ });
+ toast({ tone: "success", title: "Answer filed", body: `Wrote ${filePath.trim()} and recorded a file-as-page task.` });
+ setFileBody("");
+ } catch (err) {
+ const message = err instanceof Error ? err.message : String(err);
+ toast({ tone: "error", title: "Could not file answer", body: message });
+ } finally {
+ setFiling(null);
+ }
+ }
+
+ return (
+ <div style={{ display: "flex", flexDirection: isMobile ? "column" : "row", flex: 1, minHeight: isMobile ? "auto" : 0, minWidth: 0 }}>
+ <div style={{ flex: 1, padding: isMobile ? "16px" : "24px 28px", overflow: isMobile ? "visible" : "auto", minWidth: 0 }}>
+ {thread.length === 0 ? (
+ <Callout>
+ Ask the wiki anything. Each question initiates a task assigned to the Wiki Maintainer. The answer streams below; you can promote useful answers into a wiki page.
+ </Callout>
+ ) : null}
+ <div style={{ display: "grid", gap: 22, marginTop: 18 }}>
+ {thread.map((entry) => (
+ <div key={entry.id}>
+ <Tiny style={{ marginBottom: 4 }}>You · {formatTime(entry.createdAt)}</Tiny>
+ <div style={{ background: tokens.card, border: `1px solid ${tokens.border}`, padding: "10px 12px", borderRadius: 8, fontSize: 13 }}>{entry.prompt}</div>
+ <Tiny style={{ marginTop: 8 }}>
+ Wiki Maintainer · {entry.status}
+ {entry.hiddenIssueIdentifier ? <> · <Mono>{entry.hiddenIssueIdentifier}</Mono></> : null}
+ </Tiny>
+ {entry.status === "error" ? (
+ <div style={{ marginTop: 6 }}><Callout tone="danger">{entry.errorMessage}</Callout></div>
+ ) : (
+ <pre style={{
+ margin: "8px 0 0",
+ whiteSpace: "pre-wrap",
+ wordBreak: "break-word",
+ fontFamily: "ui-sans-serif, system-ui, sans-serif",
+ fontSize: 13,
+ lineHeight: 1.65,
+ color: tokens.fg,
+ }}>{entry.answer || (entry.status === "running" ? "Streaming…" : "")}</pre>
+ )}
+ {entry.answer.trim() && entry.status === "done" ? (
+ <div style={{ marginTop: 10, border: `1px dashed ${tokens.border}`, borderRadius: 8, padding: "10px 12px" }}>
+ <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
+ <strong style={{ fontSize: 13 }}>📑 File this answer as a wiki page?</strong>
+ <Tiny style={{ marginLeft: isMobile ? 0 : "auto", width: isMobile ? "100%" : undefined }}>Path: <Mono>{filePath}</Mono></Tiny>
+ </div>
+ <div style={{ display: "flex", gap: 6, marginTop: 8, alignItems: "center", flexWrap: "wrap" }}>
+ <TextInput value={filePath} onChange={(e) => setFilePath(e.target.value)} style={{ maxWidth: isMobile ? "none" : 360 }} />
+ <Button size="sm" variant="primary" onClick={() => fileAnswer(entry)} disabled={!filePath.trim()} loading={filing === entry.id}>Accept &amp; file</Button>
+ </div>
+ </div>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ <div style={{ borderTop: `1px solid ${tokens.border}`, paddingTop: 14, marginTop: 22 }}>
+ <TextArea value={prompt} onChange={(e) => setPrompt(e.target.value)} placeholder="Ask the wiki…" rows={3} />
+ <div style={{ display: "flex", gap: 6, marginTop: 8, alignItems: "center", flexWrap: "wrap" }}>
+ <Button variant="primary" size="sm" onClick={send} disabled={!prompt.trim()} loading={busy}>Send (⌘↵)</Button>
+ <Badge>Cite: wiki + raw</Badge>
+ <Badge>Max steps: 6</Badge>
+ <Tiny style={{ marginLeft: "auto" }}>Streamed via agent session · maintainer task</Tiny>
+ </div>
+ </div>
+ </div>
+ <aside style={{
+ width: isMobile ? "auto" : 320,
+ borderLeft: isMobile ? "none" : `1px solid ${tokens.border}`,
+ borderTop: isMobile ? `1px solid ${tokens.border}` : "none",
+ padding: isMobile ? "16px" : "18px 20px",
+ overflow: isMobile ? "visible" : "auto",
+ minWidth: 0,
+ }}>
+ <Tiny style={{ marginBottom: 8 }}>SESSION</Tiny>
+ <PropRow label="Wiki" value={overview.wikiId} />
+ <PropRow label="Project" value={overview.managedProject.details?.name ?? overview.managedProject.status} />
+ <PropRow label="Agent" value={overview.managedAgent.details?.name ?? overview.managedAgent.status} />
+ <PropRow label="Operations" value={overview.operationCount} />
+ <PropRow label="Stream" value={stream.connected ? "live" : stream.connecting ? "connecting…" : "idle"} />
+ <Divider />
+ <Tiny style={{ marginBottom: 8 }}>ASK PROMPT</Tiny>
+ <pre style={{ margin: 0, whiteSpace: "pre-wrap", fontFamily: "ui-monospace, monospace", fontSize: 12, color: tokens.muted }}>{overview.prompts.query}</pre>
+ </aside>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Lint tab.
+// ---------------------------------------------------------------------------
+
+function LintTab({ context, overview, refreshOverview }: { context: { companyId: string | null }; overview: OverviewData; refreshOverview: () => void }) {
+ const isMobile = useIsMobileLayout();
+ return (
+ <div style={{ flex: 1, minHeight: isMobile ? "auto" : 0, overflow: isMobile ? "visible" : "auto", padding: isMobile ? "16px" : "24px 28px", display: "grid", gap: isMobile ? 14 : 18, minWidth: 0 }}>
+ <LintPanelContent context={context} overview={overview} refreshOverview={refreshOverview} />
+ </div>
+ );
+}
+
+function SettingsLintPanel({ context }: { context: { companyId: string | null } }) {
+ const overview = useOverview(context.companyId);
+
+ if (overview.error) {
+ return <SettingsPanel title="Lint" badge={<HiddenOpBadge />} description="Run structural checks for orphan pages, missing backlinks, and stale provenance.">
+ <Callout tone="danger">LLM Wiki bridge error: {overview.error.message}</Callout>
+ </SettingsPanel>;
+ }
+
+ if (!overview.data) {
+ return <SettingsPanel title="Lint" badge={<HiddenOpBadge />} description="Run structural checks for orphan pages, missing backlinks, and stale provenance.">
+ <Tiny>Loading lint controls…</Tiny>
+ </SettingsPanel>;
+ }
+
+ return (
+ <SettingsPanel
+ title="Lint"
+ badge={<HiddenOpBadge />}
+ description="Run structural checks for orphan pages, missing backlinks, and stale provenance."
+ >
+ <LintPanelContent context={context} overview={overview.data} refreshOverview={overview.refresh} showHeading={false} />
+ </SettingsPanel>
+ );
+}
+
+function LintPanelContent({
+ context,
+ overview,
+ refreshOverview,
+ showHeading = true,
+}: {
+ context: { companyId: string | null };
+ overview: OverviewData;
+ refreshOverview: () => void;
+ showHeading?: boolean;
+}) {
+ const create = usePluginAction("create-operation");
+ const { pathname } = useHostLocation();
+ const activeSpaceSlug = useMemo(() => readActiveSpaceSlugFromLocation(pathname), [pathname]);
+ const operations = useOperations(context.companyId, { operationType: "lint", spaceSlug: activeSpaceSlug });
+ const toast = usePluginToast();
+ const isMobile = useIsMobileLayout();
+ const [busy, setBusy] = useState(false);
+
+ async function runLint() {
+ if (!context.companyId) return;
+ setBusy(true);
+ try {
+ await create({
+ companyId: context.companyId,
+ spaceSlug: activeSpaceSlug,
+ operationType: "lint",
+ title: `Run LLM Wiki lint · ${activeSpaceSlug}`,
+ prompt: overview.prompts.lint,
+ });
+ toast({ tone: "success", title: "Lint queued", body: "Lint runs as a Wiki Maintainer task. Findings will appear here once the run completes." });
+ operations.refresh();
+ refreshOverview();
+ } catch (err) {
+ toast({ tone: "error", title: "Could not run lint", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ const recent = operations.data?.operations ?? [];
+ const latestDone = recent.find((op) => op.status === "done");
+ const findings = Array.isArray(latestDone?.warnings) ? (latestDone!.warnings as Record<string, unknown>[]) : [];
+ const counts = aggregateLintFindings(findings);
+
+ return (
+ <div style={{ display: "grid", gap: isMobile ? 14 : 18, minWidth: 0 }}>
+ <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
+ {showHeading ? <h2 style={{ margin: 0, fontSize: 16, fontWeight: 600 }}>Lint</h2> : null}
+ <Badge style={unfilledSurfaceStyle}>{recent.length} run{recent.length === 1 ? "" : "s"}</Badge>
+ <Button variant="primary" size="sm" onClick={runLint} loading={busy} style={{ marginLeft: isMobile ? 0 : "auto" }}>▶ Run lint now</Button>
+ </div>
+ <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gap: 12 }}>
+ <StatCard label="Findings" value={String(counts.total)} hint={latestDone ? `last run ${formatTime(latestDone.createdAt)}` : "no runs yet"} />
+ <StatCard label="Critical" value={String(counts.critical)} hint="contradictions / conflict" tone={counts.critical > 0 ? "danger" : undefined} />
+ <StatCard label="Orphans" value={String(counts.orphan)} hint="no inbound backlinks" />
+ <StatCard label="Stale" value={String(counts.stale)} hint="provenance > 30d" />
+ <StatCard label="Index drift" value={String(counts.index)} hint="wiki/index.md / wiki/log.md" />
+ </div>
+ <Card style={unfilledSurfaceStyle}>
+ <CardHeader title="Findings" badges={<HiddenOpBadge />} right={<Tiny>Lint runs as a Wiki Maintainer task. Critical findings can optionally open visible follow-up issues — toggle in Settings → Lint policy.</Tiny>} />
+ <CardBody padding={0}>
+ {findings.length === 0 ? (
+ <div style={{ padding: 16, color: tokens.muted, fontSize: 13 }}>
+ {latestDone ? "Latest lint run reported no findings." : "No completed lint runs yet. Use ▶ Run lint now to start one."}
+ </div>
+ ) : findings.map((f, idx) => {
+ const severityTone: Tone = f.severity === "critical" ? "failed" : f.severity === "orphan" ? "paused" : "default";
+ return (
+ <Row
+ key={idx}
+ primary={
+ <span>
+ <Badge tone={severityTone} style={severityTone === "default" ? unfilledSurfaceStyle : undefined}>
+ {String(f.severity ?? "info")}
+ </Badge>
+ <span style={{ marginLeft: 8 }}>{String(f.message ?? f.title ?? "(no description)")}</span>
+ </span>
+ }
+ secondary={f.path ? <Mono>{String(f.path)}</Mono> : null}
+ />
+ );
+ })}
+ </CardBody>
+ </Card>
+ <Card style={unfilledSurfaceStyle}>
+ <CardHeader title="Recent lint runs" />
+ <CardBody padding={0}>
+ {recent.length === 0 ? <div style={{ padding: 12, color: tokens.muted, fontSize: 13 }}>No lint runs yet.</div> : recent.map((op) => (
+ <Row
+ key={op.id}
+ primary={<><Mono>op-{op.id.slice(0, 6)}</Mono> {op.hiddenIssueTitle ?? "Wiki lint"}</>}
+ secondary={formatTime(op.createdAt)}
+ right={<Badge tone={statusTone(op.status)}>{op.status}</Badge>}
+ />
+ ))}
+ </CardBody>
+ </Card>
+ </div>
+ );
+}
+
+function StatCard({ label, value, hint, tone }: { label: string; value: string; hint?: string; tone?: "danger" | "warn" }) {
+ const palette = tone === "danger" ? { color: "oklch(0.7 0.2 25)" } : tone === "warn" ? { color: "oklch(0.85 0.1 70)" } : { color: tokens.fg };
+ return (
+ <Card style={{ ...unfilledSurfaceStyle, padding: 14 }}>
+ <Tiny>{label.toUpperCase()}</Tiny>
+ <div style={{ fontSize: 22, fontWeight: 700, marginTop: 4, ...palette }}>{value}</div>
+ {hint ? <Tiny style={{ marginTop: 2 }}>{hint}</Tiny> : null}
+ </Card>
+ );
+}
+
+function aggregateLintFindings(findings: Record<string, unknown>[]): { total: number; critical: number; orphan: number; stale: number; index: number } {
+ const counts = { total: findings.length, critical: 0, orphan: 0, stale: 0, index: 0 };
+ for (const f of findings) {
+ const sev = String(f.severity ?? "");
+ if (sev === "critical") counts.critical += 1;
+ else if (sev === "orphan") counts.orphan += 1;
+ else if (sev === "stale") counts.stale += 1;
+ else if (sev === "index") counts.index += 1;
+ }
+ return counts;
+}
+
+// ---------------------------------------------------------------------------
+// History tab: native Paperclip issue table for recent LLM Wiki operation
+// issues. Each plugin run is represented by an issue, so the standard issue
+// history view is the right surface here.
+// ---------------------------------------------------------------------------
+
+function formatCostCents(cents: number): string {
+ if (!Number.isFinite(cents) || cents <= 0) return "$0.00";
+ return `$${(cents / 100).toFixed(2)}`;
+}
+
+function formatTimestamp(value: string | null | undefined): string {
+ if (!value) return "—";
+ const ms = Date.parse(value);
+ if (!Number.isFinite(ms)) return "—";
+ return new Date(ms).toLocaleString(undefined, { month: "short", day: "2-digit", hour: "2-digit", minute: "2-digit" });
+}
+
+function runStatusTone(status: string): Tone {
+ if (status === "running") return "running";
+ if (status === "succeeded" || status === "completed" || status === "done") return "done";
+ if (status === "failed" || status === "refused_cost_cap") return "failed";
+ if (status === "review_required") return "in_review";
+ if (status === "paused") return "paused";
+ if (status === "source_ready" || status === "queued") return "queued";
+ return "default";
+}
+
+function runStatusLabel(status: string): string {
+ switch (status) {
+ case "review_required":
+ return "review required";
+ case "refused_cost_cap":
+ return "cost capped";
+ case "source_ready":
+ return "source ready";
+ default:
+ return status.replace(/_/g, " ");
+ }
+}
+
+function HistoryTab({ context, overview }: { context: { companyId: string | null; companyPrefix?: string | null }; overview: OverviewData }) {
+ const isMobile = useIsMobileLayout();
+ const projectId = overview.managedProject.projectId;
+ const originKindPrefix = `plugin:${PLUGIN_ID}:operation`;
+
+ if (!context.companyId) {
+ return <div style={{ padding: isMobile ? 16 : 24, flex: 1 }}><Callout>Choose a company to view LLM Wiki history.</Callout></div>;
+ }
+
+ if (!projectId) {
+ return (
+ <div style={{ padding: isMobile ? 16 : 24, flex: 1 }}>
+ <Callout tone="warn">The LLM Wiki operations project is not resolved yet. Reconcile the managed project in Settings, then history will show its issues here.</Callout>
+ </div>
+ );
+ }
+
+ return (
+ <div style={{ flex: 1, minHeight: isMobile ? "auto" : 0, overflow: isMobile ? "visible" : "auto", padding: isMobile ? 12 : 0, minWidth: 0 }}>
+ <PluginIssuesList
+ companyId={context.companyId}
+ projectId={projectId}
+ filters={{ originKindPrefix }}
+ viewStateKey="paperclip:llm-wiki-history-issues-view"
+ searchWithinLoadedIssues
+ />
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Settings (tab) and the standalone host SettingsPage share this body.
+// ---------------------------------------------------------------------------
+
+function SettingsTab({ context, initialSection = "root" }: { context: { companyId: string | null; companyPrefix?: string | null }; initialSection?: SettingsSectionKey }) {
+ const isMobile = useIsMobileLayout();
+ return (
+ <div style={{ flex: 1, minHeight: isMobile ? "auto" : 0, overflow: isMobile ? "visible" : "auto", padding: isMobile ? "16px" : "24px 28px", minWidth: 0 }}>
+ <SettingsBody context={context} initialSection={initialSection} />
+ </div>
+ );
+}
+
+const ROUTINE_FALLBACKS: Record<string, { title: string; cron: string }> = {
+ "cursor-window-processing": { title: "Process LLM Wiki updates", cron: "0 */6 * * *" },
+ "nightly-wiki-lint": { title: "Run LLM Wiki lint", cron: "0 3 * * *" },
+ "index-refresh": { title: "Refresh LLM Wiki index", cron: "0 * * * *" },
+};
+
+const MANAGED_SKILL_LABELS: Record<string, string> = {
+ "wiki-maintainer": "LLM Wiki Maintainer",
+ "wiki-ingest": "Wiki Ingest",
+ "wiki-query": "Wiki Query",
+ "wiki-lint": "Wiki Lint",
+ "paperclip-distill": "Paperclip Distill",
+ "index-refresh": "Index Refresh",
+};
+
+function routineFallbackFor(routine: ManagedRoutine) {
+ const key = routine.resourceKey?.split(":").pop() ?? "";
+ return ROUTINE_FALLBACKS[key] ?? { title: routine.resourceKey ?? "Managed routine", cron: "—" };
+}
+
+function managedRoutineStatus(routine: ManagedRoutine) {
+ return routine.routine?.status ?? routine.details?.status ?? (routine.routineId ? "paused" : "missing");
+}
+
+type RoutineHealthItem = {
+ label: string;
+ ok: boolean;
+ detail: string;
+};
+
+function routineResourceKey(routine: ManagedRoutine) {
+ return routine.resourceKey?.split(":").pop() ?? "";
+}
+
+function managedAgentIsReady(resource: ManagedAgent) {
+ return resource.source === "managed" && Boolean(resource.agentId);
+}
+
+function managedProjectIsReady(resource: ManagedProject) {
+ return resource.source === "managed" && Boolean(resource.projectId);
+}
+
+function managedSkillIsReady(resource: ManagedSkill) {
+ return resource.status !== "missing" && Boolean(resource.skillId);
+}
+
+function managedResourceKey(resourceKey?: string | null) {
+ return resourceKey?.split(":").pop() ?? "";
+}
+
+function skillLabel(resource: ManagedSkill) {
+ const declaredLabel = MANAGED_SKILL_LABELS[managedResourceKey(resource.resourceKey)];
+ return declaredLabel ?? resource.details?.name ?? resource.skill?.name ?? "Managed skill";
+}
+
+function buildAgentHealthItems(managedAgent: ManagedAgent): RoutineHealthItem[] {
+ const agentName = managedAgent.details?.name ?? "Wiki Maintainer";
+ return [{
+ label: agentName,
+ ok: managedAgentIsReady(managedAgent) && !managedAgent.defaultDrift?.changedFiles.length,
+ detail: managedAgent.source === "managed"
+ ? managedAgent.defaultDrift?.changedFiles.length
+ ? `The Wiki Maintainer instructions differ from the plugin default: ${managedAgent.defaultDrift.changedFiles.join(", ")}.`
+ : "The plugin-managed Wiki Maintainer exists with current default instructions."
+ : "The settings page is using a selected maintainer instead of the plugin-managed Wiki Maintainer.",
+ }];
+}
+
+function buildProjectHealthItems(managedProject: ManagedProject): RoutineHealthItem[] {
+ const projectName = managedProject.details?.name ?? "LLM Wiki";
+ return [{
+ label: projectName,
+ ok: managedProjectIsReady(managedProject),
+ detail: managedProject.source === "managed"
+ ? "The plugin-managed LLM Wiki project exists."
+ : "The settings page is using a selected project instead of the plugin-managed LLM Wiki project.",
+ }];
+}
+
+function buildSkillHealthItems(skills: ManagedSkill[]): RoutineHealthItem[] {
+ if (skills.length === 0) {
+ return [{
+ label: "Managed skill",
+ ok: false,
+ detail: "No plugin-managed skills are installed in the company skill library.",
+ }];
+ }
+ return skills.map((skill) => ({
+ label: skillLabel(skill),
+ ok: managedSkillIsReady(skill) && !skill.defaultDrift?.changedFiles.length,
+ detail: managedSkillIsReady(skill)
+ ? skill.defaultDrift?.changedFiles.length
+ ? `${skillLabel(skill)} differs from the plugin default: ${skill.defaultDrift.changedFiles.join(", ")}.`
+ : `${skillLabel(skill)} is installed in the company skill library.`
+ : `${skillLabel(skill)} is not installed in the company skill library.`,
+ }));
+}
+
+function buildRoutineHealthItems(
+ routines: ManagedRoutine[],
+ managedAgent: ManagedAgent,
+ managedProject: ManagedProject,
+): RoutineHealthItem[] {
+ const routineByKey = new Map(routines.map((routine) => [routineResourceKey(routine), routine]));
+ const expectedAgentId = managedAgent.source === "managed" ? managedAgent.agentId ?? null : null;
+ const expectedProjectId = managedProject.source === "managed" ? managedProject.projectId ?? null : null;
+ const items: RoutineHealthItem[] = [];
+
+ for (const [key, fallback] of Object.entries(ROUTINE_FALLBACKS)) {
+ const routine = routineByKey.get(key);
+ const routineAgentId = routine?.routine?.assigneeAgentId ?? null;
+ const routineProjectId = routine?.routine?.projectId ?? null;
+ const missingRefs = routine?.missingRefs ?? [];
+ const missing = !routine?.routineId || !routine.routine;
+ const wrongAgent = Boolean(expectedAgentId && routineAgentId && routineAgentId !== expectedAgentId);
+ const wrongProject = Boolean(expectedProjectId && routineProjectId && routineProjectId !== expectedProjectId);
+ const missingAgent = Boolean(expectedAgentId && !routineAgentId);
+ const missingProject = Boolean(expectedProjectId && !routineProjectId);
+ const blockedByManagedResources = !expectedAgentId || !expectedProjectId;
+ const ok = Boolean(routine && !missing && missingRefs.length === 0 && !wrongAgent && !wrongProject && !missingAgent && !missingProject && !blockedByManagedResources);
+ let detail = `${fallback.title} is installed with the Wiki Maintainer and LLM Wiki project.`;
+ if (missing) {
+ detail = `${fallback.title} is not installed.`;
+ } else if (missingRefs.length > 0) {
+ detail = `${fallback.title} cannot resolve ${missingRefs.map((ref) => `${ref.resourceKind}:${ref.resourceKey}`).join(", ")}.`;
+ } else if (blockedByManagedResources) {
+ detail = `${fallback.title} cannot be validated until the managed agent and project are restored.`;
+ } else if (wrongAgent || missingAgent) {
+ detail = `${fallback.title} is not assigned to the Wiki Maintainer.`;
+ } else if (wrongProject || missingProject) {
+ detail = `${fallback.title} is not attached to the LLM Wiki project.`;
+ }
+ items.push({ label: fallback.title, ok, detail });
+ }
+
+ return items;
+}
+
+function RoutineHealthChecklist({ items }: { items: RoutineHealthItem[] }) {
+ return (
+ <ManagedResourceHealthChecklist
+ items={items}
+ ariaLabel="Wiki routines health checklist"
+ heading="Routine health"
+ />
+ );
+}
+
+function ManagedResourceHealthChecklist({
+ items,
+ ariaLabel,
+ heading,
+}: {
+ items: RoutineHealthItem[];
+ ariaLabel: string;
+ heading: string;
+}) {
+ return (
+ <div style={{ display: "grid", gap: 8 }} aria-label={ariaLabel}>
+ <div style={{ fontSize: 12, fontWeight: 650, color: tokens.muted }}>{heading}</div>
+ <div role="list" style={{ position: "relative", display: "grid", gap: 0, padding: "2px 0" }}>
+ {items.length > 1 ? (
+ <span
+ aria-hidden
+ style={{
+ position: "absolute",
+ left: 8,
+ top: 12,
+ bottom: 12,
+ width: 1,
+ background: "oklch(0.38 0.09 145)",
+ }}
+ />
+ ) : null}
+ {items.map((item) => (
+ <div
+ key={item.label}
+ role="listitem"
+ title={item.detail}
+ style={{
+ display: "grid",
+ gridTemplateColumns: "18px minmax(0, 1fr)",
+ alignItems: "center",
+ gap: 10,
+ padding: "7px 0",
+ minWidth: 0,
+ }}
+ >
+ <span style={{ display: "inline-flex", justifyContent: "center", position: "relative", zIndex: 1, background: tokens.bg }}>
+ <StatusIcon status={item.ok ? "done" : "blocked"} />
+ </span>
+ <span style={{ fontSize: 13, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: item.ok ? tokens.fg : "oklch(0.85 0.1 70)" }}>
+ {item.label}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function SkillHealthChecklist({ items }: { items: RoutineHealthItem[] }) {
+ return (
+ <ManagedResourceHealthChecklist
+ items={items}
+ ariaLabel="Wiki skills health checklist"
+ heading="Skill health"
+ />
+ );
+}
+
+type SettingsSectionKey = "root" | "spaces" | "distillation" | "routines" | "lint" | "events";
+
+const SETTINGS_SECTIONS: ReadonlyArray<{
+ key: SettingsSectionKey;
+ label: string;
+ description: string;
+}> = [
+ { key: "root", label: "Setup", description: "" },
+ { key: "spaces", label: "Spaces", description: "Destination spaces - folders, slugs, and folder health. Per-space Paperclip indexing is not configurable yet." },
+ { key: "distillation", label: "Distillation", description: "Paperclip -> default space. Cursors, caps, and routines for the company-wide distillation pipeline." },
+ { key: "routines", label: "Managed Routines", description: "Scheduled wiki maintenance." },
+ { key: "lint", label: "Lint", description: "Run checks and review wiki health findings." },
+ { key: "events", label: "Ingestion Settings", description: "Paperclip event capture into the default space (issues, comments, documents)." },
+];
+
+function SettingsSectionButton({
+ section,
+ active,
+ onSelect,
+}: {
+ section: (typeof SETTINGS_SECTIONS)[number];
+ active: boolean;
+ onSelect: () => void;
+}) {
+ return (
+ <button
+ type="button"
+ aria-current={active ? "page" : undefined}
+ onClick={onSelect}
+ style={{
+ width: "100%",
+ border: `1px solid ${active ? tokens.border : "transparent"}`,
+ borderRadius: 6,
+ background: "transparent",
+ color: active ? tokens.fg : tokens.muted,
+ cursor: "pointer",
+ display: "grid",
+ gap: 2,
+ padding: "8px 10px",
+ textAlign: "left",
+ fontFamily: fontStack,
+ }}
+ >
+ <span style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.3 }}>{section.label}</span>
+ {section.description ? (
+ <span style={{ fontSize: 11, lineHeight: 1.35, overflowWrap: "anywhere" }}>{section.description}</span>
+ ) : null}
+ </button>
+ );
+}
+
+function SettingsPanel({
+ title,
+ badge,
+ description,
+ children,
+}: {
+ title: ReactNode;
+ badge?: ReactNode;
+ description?: ReactNode;
+ children: ReactNode;
+}) {
+ return (
+ <section style={{ display: "grid", gap: 14, minWidth: 0 }}>
+ <header style={{ display: "grid", gap: 6, minWidth: 0 }}>
+ <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap", minWidth: 0 }}>
+ <h2 style={{ margin: 0, fontSize: 17, fontWeight: 650, overflowWrap: "anywhere" }}>{title}</h2>
+ {badge}
+ </div>
+ {description ? <Tiny>{description}</Tiny> : null}
+ </header>
+ <div style={{ minWidth: 0 }}>{children}</div>
+ </section>
+ );
+}
+
+function SetupSection({ title, children, separated = false }: { title: ReactNode; children: ReactNode; separated?: boolean }) {
+ return (
+ <section style={{ display: "grid", gap: 12, minWidth: 0, paddingTop: separated ? 22 : 0, borderTop: separated ? `1px solid ${tokens.border}` : "none" }}>
+ <h2 style={{ margin: 0, fontSize: 16, fontWeight: 650 }}>{title}</h2>
+ <div style={{ minWidth: 0 }}>{children}</div>
+ </section>
+ );
+}
+
+type PathPlatform = "mac" | "windows" | "linux";
+
+const PATH_PLATFORM_LABELS: Record<PathPlatform, string> = {
+ mac: "macOS",
+ windows: "Windows",
+ linux: "Linux",
+};
+
+const PATH_PLATFORM_STEPS: Record<PathPlatform, string[]> = {
+ mac: [
+ "Open Finder and navigate to the folder.",
+ "Control-click the folder.",
+ "Hold Option, choose Copy as Pathname, then paste it here.",
+ ],
+ windows: [
+ "Open File Explorer and navigate to the folder.",
+ "Click the address bar to reveal the full path.",
+ "Copy the path and paste it here.",
+ ],
+ linux: [
+ "Open a terminal in the directory.",
+ "Run pwd to print the full path.",
+ "Copy the output and paste it here.",
+ ],
+};
+
+function detectPathPlatform(): PathPlatform {
+ if (typeof navigator === "undefined") return "mac";
+ const agent = navigator.userAgent.toLowerCase();
+ if (agent.includes("win")) return "windows";
+ if (agent.includes("linux")) return "linux";
+ return "mac";
+}
+
+function PathInstructionsDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
+ const [platform, setPlatform] = useState<PathPlatform>(detectPathPlatform);
+
+ useEffect(() => {
+ if (!open) return;
+ function handleKeyDown(event: KeyboardEvent) {
+ if (event.key === "Escape") onClose();
+ }
+ document.addEventListener("keydown", handleKeyDown);
+ return () => document.removeEventListener("keydown", handleKeyDown);
+ }, [onClose, open]);
+
+ if (!open) return null;
+
+ return (
+ <div
+ role="presentation"
+ onClick={onClose}
+ style={{
+ position: "fixed",
+ inset: 0,
+ zIndex: 50,
+ background: "rgba(0, 0, 0, 0.48)",
+ display: "grid",
+ placeItems: "center",
+ padding: 18,
+ }}
+ >
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="wiki-path-help-title"
+ onClick={(event) => event.stopPropagation()}
+ style={{
+ width: "min(460px, 100%)",
+ border: `1px solid ${tokens.border}`,
+ borderRadius: 8,
+ background: tokens.card,
+ color: tokens.fg,
+ boxShadow: "0 24px 70px rgba(0, 0, 0, 0.45)",
+ padding: 18,
+ display: "grid",
+ gap: 14,
+ }}
+ >
+ <div style={{ display: "flex", justifyContent: "space-between", gap: 12, alignItems: "start" }}>
+ <div style={{ display: "grid", gap: 4 }}>
+ <h3 id="wiki-path-help-title" style={{ margin: 0, fontSize: 15, fontWeight: 650 }}>Get a full folder path</h3>
+ <Tiny>Paste an absolute path such as <Mono>/Users/you/company-wiki</Mono>.</Tiny>
+ </div>
+ <Button size="sm" variant="ghost" onClick={onClose} title="Close path help">Close</Button>
+ </div>
+ <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 4, border: `1px solid ${tokens.border}`, borderRadius: 7, padding: 3 }}>
+ {(Object.keys(PATH_PLATFORM_LABELS) as PathPlatform[]).map((key) => (
+ <button
+ key={key}
+ type="button"
+ onClick={() => setPlatform(key)}
+ style={{
+ border: 0,
+ borderRadius: 5,
+ background: key === platform ? tokens.accent : "transparent",
+ color: key === platform ? tokens.fg : tokens.muted,
+ padding: "6px 8px",
+ cursor: "pointer",
+ fontSize: 12,
+ fontFamily: fontStack,
+ }}
+ >
+ {PATH_PLATFORM_LABELS[key]}
+ </button>
+ ))}
+ </div>
+ <ol style={{ margin: 0, paddingLeft: 20, display: "grid", gap: 8, fontSize: 13, lineHeight: 1.45 }}>
+ {PATH_PLATFORM_STEPS[platform].map((step) => <li key={step}>{step}</li>)}
+ </ol>
+ </div>
+ </div>
+ );
+}
+
+function FolderPathPicker({
+ value,
+ onChange,
+ onApply,
+ applyLabel,
+ busy,
+ disabled,
+ onRefresh,
+}: {
+ value: string;
+ onChange: (value: string) => void;
+ onApply: () => void;
+ applyLabel: string;
+ busy?: boolean;
+ disabled?: boolean;
+ onRefresh?: () => void;
+}) {
+ const [helpOpen, setHelpOpen] = useState(false);
+
+ return (
+ <div style={{
+ border: `1px solid ${tokens.border}`,
+ borderRadius: 8,
+ background: "oklch(0.18 0 0)",
+ overflow: "hidden",
+ minWidth: 0,
+ }}>
+ <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderBottom: `1px solid ${tokens.border}` }}>
+ <span aria-hidden style={{
+ width: 28,
+ height: 28,
+ borderRadius: 7,
+ display: "inline-flex",
+ alignItems: "center",
+ justifyContent: "center",
+ background: tokens.accent,
+ color: tokens.pluginFg,
+ flexShrink: 0,
+ }}>
+ <FolderOpenIcon />
+ </span>
+ <div style={{ display: "grid", gap: 2, minWidth: 0 }}>
+ <span style={{ fontSize: 13, fontWeight: 650 }}>Local wiki folder</span>
+ <Tiny>Absolute path on this machine</Tiny>
+ </div>
+ </div>
+ <div style={{ display: "flex", gap: 8, padding: 12, alignItems: "center", flexWrap: "wrap" }}>
+ <TextInput
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ placeholder="/absolute/path/to/wiki-root"
+ style={{ flex: "1 1 320px", fontFamily: "ui-monospace, SFMono-Regular, monospace" }}
+ />
+ <Button size="sm" onClick={() => setHelpOpen(true)}><FolderOpenIcon size={13} /> Choose</Button>
+ <Button variant="primary" size="sm" onClick={onApply} loading={busy} disabled={disabled || !value.trim()}>{applyLabel}</Button>
+ {onRefresh ? <Button size="sm" variant="ghost" onClick={onRefresh}>Run health check</Button> : null}
+ </div>
+ <PathInstructionsDialog open={helpOpen} onClose={() => setHelpOpen(false)} />
+ </div>
+ );
+}
+
+type FolderHealthItem = {
+ label: string;
+ ok: boolean;
+};
+
+function folderHealthItems(folder: FolderStatus): FolderHealthItem[] {
+ return [
+ { label: "Path configured", ok: folder.configured },
+ { label: "Readable", ok: folder.readable },
+ { label: folder.access === "readWrite" ? "Writable" : "Read-only access", ok: folder.access === "read" || folder.writable },
+ { label: "Baseline files", ok: folder.missingFiles.length === 0 },
+ { label: "Wiki folders", ok: folder.missingDirectories.length === 0 },
+ ];
+}
+
+function FolderHealthChecklist({ folder }: { folder: FolderStatus }) {
+ const items = folderHealthItems(folder);
+ return (
+ <div style={{ display: "grid", gap: 8 }} aria-label="Wiki root health checklist">
+ <div style={{ fontSize: 12, fontWeight: 650, color: tokens.muted }}>Health check</div>
+ <div role="list" style={{ position: "relative", display: "grid", gap: 0, padding: "2px 0" }}>
+ {items.length > 1 ? (
+ <span
+ aria-hidden
+ style={{
+ position: "absolute",
+ left: 8,
+ top: 12,
+ bottom: 12,
+ width: 1,
+ background: "oklch(0.38 0.09 145)",
+ }}
+ />
+ ) : null}
+ {items.map((item) => (
+ <div
+ key={item.label}
+ role="listitem"
+ style={{
+ display: "grid",
+ gridTemplateColumns: "18px minmax(0, 1fr)",
+ alignItems: "center",
+ gap: 10,
+ padding: "7px 0",
+ minWidth: 0,
+ }}
+ >
+ <span style={{ display: "inline-flex", justifyContent: "center", position: "relative", zIndex: 1, background: tokens.bg }}>
+ <StatusIcon status={item.ok ? "done" : "blocked"} />
+ </span>
+ <span style={{ fontSize: 13, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: item.ok ? tokens.fg : "oklch(0.85 0.1 70)" }}>
+ {item.label}
+ </span>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+type MaintainerAgentOption = SettingsData["agentOptions"][number];
+type ProjectOption = SettingsData["projectOptions"][number];
+
+function agentStatusLabel(status?: string | null) {
+ if (!status) return "unknown";
+ return status.replace(/_/g, " ");
+}
+
+function projectStatusLabel(status?: string | null) {
+ if (!status) return "unknown";
+ return status.replace(/_/g, " ");
+}
+
+function adapterTypeLabel(adapterType?: string | null) {
+ if (!adapterType) return "unknown adapter";
+ return adapterType.replace(/_/g, " ");
+}
+
+function agentAvatarGlyph(icon?: string | null, name?: string | null) {
+ if (icon === "book-open") return "📖";
+ return (name?.trim().charAt(0) || "A").toUpperCase();
+}
+
+function AgentAvatar({ agent, size = 30 }: { agent: Pick<MaintainerAgentOption, "name" | "icon">; size?: number }) {
+ return (
+ <span
+ aria-hidden
+ style={{
+ width: size,
+ height: size,
+ borderRadius: "50%",
+ display: "inline-flex",
+ alignItems: "center",
+ justifyContent: "center",
+ flexShrink: 0,
+ border: `1px solid ${tokens.border}`,
+ background: tokens.accent,
+ color: tokens.fg,
+ fontSize: size > 28 ? 14 : 12,
+ fontWeight: 700,
+ }}
+ >
+ {agentAvatarGlyph(agent.icon, agent.name)}
+ </span>
+ );
+}
+
+function AgentOptionLabel({ agent, muted = false }: { agent: MaintainerAgentOption; muted?: boolean }) {
+ return (
+ <span style={{ display: "flex", alignItems: "center", gap: 8, minWidth: 0 }}>
+ <AgentAvatar agent={agent} />
+ <span style={{ display: "grid", gap: 1, minWidth: 0 }}>
+ <span style={{ fontSize: 13, fontWeight: 600, color: muted ? tokens.muted : tokens.fg, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
+ {agent.name}
+ </span>
+ <span style={{ fontSize: 11, color: tokens.muted, textTransform: "capitalize" }}>
+ {agentStatusLabel(agent.status)} · {adapterTypeLabel(agent.adapterType)}
+ </span>
+ </span>
+ </span>
+ );
+}
+
+function MaintainerAgentLink({
+ agent,
+ hrefProps,
+}: {
+ agent: MaintainerAgentOption;
+ hrefProps?: Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "style">;
+}) {
+ return (
+ <a
+ {...hrefProps}
+ style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: 8,
+ maxWidth: "100%",
+ color: tokens.fg,
+ textDecoration: "none",
+ }}
+ >
+ <AgentAvatar agent={agent} />
+ <span style={{ display: "grid", gap: 1, minWidth: 0, textAlign: "left" }}>
+ <span style={{ fontSize: 13, fontWeight: 650, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
+ Resolve agent wiki maintainer
+ </span>
+ <span style={{ fontSize: 11, color: tokens.muted, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
+ {agent.name} · {agentStatusLabel(agent.status)} · {adapterTypeLabel(agent.adapterType)}
+ </span>
+ </span>
+ </a>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Distillation settings panel (configured + unconfigured states).
+// Source filters / cursor windows / model lanes / auto-apply / backfill.
+// Most controls render the current state; persistence is wired through
+// existing managed-routine and plugin-action endpoints.
+// ---------------------------------------------------------------------------
+
+function DistillationSettingsPanel({ context, settings }: { context: { companyId: string | null }; settings: SettingsData }) {
+ const overview = useDistillationOverview(context.companyId);
+ const distillNow = usePluginAction("distill-paperclip-now");
+ const enableActiveProjects = usePluginAction("enable-paperclip-distillation-active-projects");
+ const queueBackfill = usePluginAction("backfill-paperclip-distillation");
+ const toast = usePluginToast();
+ const isMobile = useIsMobileLayout();
+ const [busy, setBusy] = useState<string | null>(null);
+ const data = overview.data;
+ const cursors = data?.cursors ?? [];
+ const counts = data?.counts ?? { cursors: 0, runningRuns: 0, failedRuns24h: 0, reviewRequired: 0 };
+ const isConfigured = cursors.length > 0;
+ const autoApplyRestriction = settings.distillationPolicy?.autoApplyRestriction ?? null;
+ const [useCheapPath, setUseCheapPath] = useState(true);
+
+ const projectsCovered = useMemo(() => {
+ const set = new Set<string>();
+ for (const cursor of cursors) {
+ if (cursor.projectId) set.add(cursor.projectId);
+ }
+ return set.size;
+ }, [cursors]);
+
+ async function runDistillNow() {
+ if (!context.companyId) return;
+ if (cursors.length === 0) {
+ toast({ tone: "warn", title: "Distill now needs at least one cursor" });
+ return;
+ }
+ setBusy("distill-now");
+ try {
+ await distillNow({
+ companyId: context.companyId,
+ useCheapModelProfile: useCheapPath,
+ idempotencyKey: `manual:company:${Date.now()}`,
+ });
+ toast({
+ tone: "success",
+ title: "Distill now queued",
+ body: "Wiki Maintainer will scan changed projects in the company and write into the default wiki space.",
+ });
+ overview.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Distill now failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ async function enableForActiveProjects() {
+ if (!context.companyId) return;
+ setBusy("enable-active-projects");
+ try {
+ const result = await enableActiveProjects({ companyId: context.companyId, limit: 3 }) as {
+ selectedProjects?: Array<{ name?: string | null }>;
+ };
+ const count = result.selectedProjects?.length ?? 0;
+ toast({
+ tone: count > 0 ? "success" : "warn",
+ title: count > 0 ? "Distillation enabled" : "No active projects found",
+ body: count > 0
+ ? `${count} active project${count === 1 ? "" : "s"} added to the distillation cursor set.`
+ : "Create or resume a project, then enable distillation again.",
+ });
+ overview.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Enable distillation failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ async function runBackfill() {
+ if (!context.companyId || cursors.length === 0) return;
+ const target = cursors.find((cursor) => cursor.projectId) ?? cursors[0];
+ if (!target.projectId && !target.rootIssueId) {
+ toast({ tone: "warn", title: "Backfill needs a project or root issue scope" });
+ return;
+ }
+ setBusy("backfill");
+ try {
+ await queueBackfill({
+ companyId: context.companyId,
+ projectId: target.projectId ?? undefined,
+ rootIssueId: target.rootIssueId ?? undefined,
+ useCheapModelProfile: useCheapPath,
+ });
+ toast({ tone: "success", title: "Backfill queued", body: target.projectName ?? target.rootIssueIdentifier ?? "Selected scope" });
+ overview.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Backfill failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setBusy(null);
+ }
+ }
+
+ if (overview.loading && !data) {
+ return <Tiny>Loading distillation overview…</Tiny>;
+ }
+
+ if (!isConfigured) {
+ return (
+ <div style={{ display: "grid", gap: 16, maxWidth: 720 }}>
+ <Card>
+ <CardBody padding={isMobile ? 18 : 26}>
+ <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", gap: 12 }}>
+ <SparklesIcon size={36} />
+ <div>
+ <h3 style={{ margin: 0, fontSize: 17, fontWeight: 650 }}>Distillation is off</h3>
+ <Tiny style={{ marginTop: 6, fontSize: 13, color: tokens.fg, lineHeight: 1.55, maxWidth: 540 }}>
+ When enabled, the Wiki Maintainer reads Paperclip issues, comments, and documents for this
+ company and keeps <Mono>wiki/projects/&lt;slug&gt;/standup.md</Mono> plus <Mono>wiki/projects/&lt;slug&gt;/index.md</Mono> pages in the
+ <strong> default wiki space</strong>. Pages stay marked stale until a cursor window succeeds -
+ they never imply live state.
+ </Tiny>
+ <Tiny style={{ marginTop: 6, fontSize: 13, color: tokens.fg, lineHeight: 1.55, maxWidth: 540 }}>
+ Other spaces do not receive Paperclip-derived pages yet. They stay on manual and raw-file
+ ingest until per-space Paperclip ingestion profiles ship.
+ </Tiny>
+ </div>
+ <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
+ <Button variant="primary" size="md" onClick={enableForActiveProjects} loading={busy === "enable-active-projects"}>
+ <SparklesIcon size={14} /> Enable for active projects
+ </Button>
+ <Button variant="default" size="md" onClick={() => overview.refresh()}>Configure manually</Button>
+ </div>
+ <Tiny>Suggested defaults: 3 active projects in the default space · all-section auto-apply where allowed · routines paused for 24h.</Tiny>
+ </div>
+ </CardBody>
+ </Card>
+
+ <div style={{ display: "grid", gap: 12, gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr" }}>
+ <Card>
+ <CardHeader title="What gets created" />
+ <CardBody padding={14}>
+ <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12.5, color: tokens.muted, lineHeight: 1.5 }}>
+ <li>Project overviews at <Mono>wiki/projects/&lt;slug&gt;/index.md</Mono></li>
+ <li>Executive standups at <Mono>wiki/projects/&lt;slug&gt;/standup.md</Mono></li>
+ <li>Decisions and history under <Mono>wiki/projects/&lt;slug&gt;/</Mono></li>
+ <li>Source bundles cached under <Mono>raw/distill/</Mono></li>
+ </ul>
+ </CardBody>
+ </Card>
+ <Card>
+ <CardHeader title="What it never does" />
+ <CardBody padding={14}>
+ <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12.5, color: tokens.muted, lineHeight: 1.5 }}>
+ <li>Read across companies — strict per-company isolation.</li>
+ <li>Re-distill its own plugin operation issues.</li>
+ <li>Auto-apply patches when source hashes drift.</li>
+ </ul>
+ </CardBody>
+ </Card>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div style={{ display: "grid", gap: 16, minWidth: 0 }}>
+ {autoApplyRestriction ? (
+ <Callout tone="warn">
+ {autoApplyRestriction} The plugin ignores auto-apply requests from config and manual distill actions on this instance.
+ </Callout>
+ ) : null}
+ <Callout>
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
+ <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
+ <InfoIcon size={16} />
+ <strong style={{ fontSize: 13 }}>Active for {projectsCovered} project{projectsCovered === 1 ? "" : "s"} · {counts.cursors} cursor{counts.cursors === 1 ? "" : "s"} catching up · default space</strong>
+ </div>
+ <div style={{ display: "flex", gap: 8 }}>
+ <Button variant="ghost" size="sm" onClick={() => overview.refresh()}><RefreshIcon size={12} /> Refresh</Button>
+ <Button variant="primary" size="sm" onClick={runDistillNow} loading={busy === "distill-now"}><SparklesIcon size={12} /> Distill now</Button>
+ </div>
+ </div>
+ <Tiny style={{ marginTop: 6 }}>
+ Distillation runs on the assigned Wiki Maintainer agent and writes only into the default
+ space. Use the cheap path option when the agent exposes a cheap model profile.
+ </Tiny>
+ </Callout>
+
+ <Card>
+ <CardHeader title="Source filters" />
+ <CardBody padding={14}>
+ <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 16 }}>
+ <fieldset style={{ border: 0, padding: 0, margin: 0, display: "grid", gap: 6 }}>
+ <legend style={{ fontSize: 12, color: tokens.muted, marginBottom: 4 }}>Issue scope</legend>
+ <CheckboxRow label="Active projects" defaultChecked help="Cursors are created for projects with recent activity." />
+ <CheckboxRow label="Root issues marked distillable" defaultChecked />
+ <CheckboxRow label="All company issues" help="May create large source windows." />
+ <Tiny>
+ These filters narrow the Paperclip source scope. The destination is always the default
+ wiki space in Phase 1.
+ </Tiny>
+ <Tiny>Plugin-operation issues are always excluded to prevent feedback loops.</Tiny>
+ </fieldset>
+ <fieldset style={{ border: 0, padding: 0, margin: 0, display: "grid", gap: 6 }}>
+ <legend style={{ fontSize: 12, color: tokens.muted, marginBottom: 4 }}>Source kinds</legend>
+ <CheckboxRow label="Issue title + description" defaultChecked locked />
+ <CheckboxRow label="Comments (ranked, clipped)" defaultChecked />
+ <CheckboxRow label="Documents (plan, spec, report)" defaultChecked />
+ <CheckboxRow label="Work products / attachments" suffix="coming soon" />
+ <Tiny>Heartbeats and hidden documents are never included.</Tiny>
+ </fieldset>
+ </div>
+ </CardBody>
+ </Card>
+
+ <Card>
+ <CardHeader title="Cursor windows" />
+ <CardBody padding={14}>
+ <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 16 }}>
+ <SettingField label="Max source characters per project" hint="Source bundles above this size are clipped and the page warns 'source clipped'.">
+ <TextInput defaultValue="48000" />
+ </SettingField>
+ <SettingField label="Min source age before processing" hint="Debounces a hot project so a flurry of comments collapses into one cursor window.">
+ <SelectInput defaultValue="15" options={[["5", "5 min"], ["15", "15 min"], ["30", "30 min"], ["60", "1 hour"]]} />
+ </SettingField>
+ <SettingField label="Max cursor windows per routine run" hint="Routine runs that hit this cap split the remainder into the next routine fire.">
+ <TextInput defaultValue="6" />
+ </SettingField>
+ <SettingField label="Stale window threshold" hint="After this, project pages render a 'Stale' badge until a successful run advances the cursor.">
+ <SelectInput defaultValue="72" options={[["24", "24 h"], ["48", "48 h"], ["72", "72 h"], ["168", "7 days"]]} />
+ </SettingField>
+ </div>
+ </CardBody>
+ </Card>
+
+ <Card>
+ <CardHeader title="Agent execution" />
+ <CardBody padding={14}>
+ <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "1fr 1fr", gap: 16 }}>
+ <SettingField label="Assigned maintainer" hint="Model selection comes from the agent adapter and its runtime config. The plugin does not choose Claude/Codex/Gemini models here.">
+ <div style={{ minHeight: 34, display: "flex", alignItems: "center", border: `1px solid ${tokens.border}`, borderRadius: 6, padding: "6px 10px", fontSize: 13 }}>
+ {settings.managedAgent.details
+ ? `${settings.managedAgent.details.name} · ${adapterTypeLabel(settings.managedAgent.details.adapterType)}`
+ : "No maintainer agent resolved"}
+ </div>
+ </SettingField>
+ <SettingField label="Cheap path" hint="When enabled, manual distill and backfill operation issues request assigneeAdapterOverrides.modelProfile = cheap.">
+ <CheckboxRow
+ label="Request the assigned agent's cheap model profile for distillation tasks"
+ checked={useCheapPath}
+ onChange={setUseCheapPath}
+ />
+ </SettingField>
+ </div>
+ </CardBody>
+ </Card>
+
+ <Card>
+ <CardHeader title="Auto-apply policy" />
+ <CardBody padding={14}>
+ <div style={{ display: "grid", gap: 8 }}>
+ <RadioRow name="autoapply" value="never" label="Never — every patch goes to review-required." />
+ <RadioRow name="autoapply" value="status" label="Executive-status sections only — standup, current direction, and risks." />
+ <RadioRow name="autoapply" value="all" label="All sections — apply when source hash matches and confidence ≥ 0.8 (default)." defaultChecked />
+ <Tiny>Stale-hash collisions always fall through to review, regardless of policy.</Tiny>
+ </div>
+ </CardBody>
+ </Card>
+
+ <Card>
+ <CardHeader
+ title="Backfill"
+ right={<Button variant="default" size="sm" onClick={runBackfill} loading={busy === "backfill"}>Queue backfill</Button>}
+ />
+ <CardBody padding={14}>
+ <Tiny style={{ marginBottom: 6 }}>Backfills replay a bounded source window for a single scope so newly-enabled projects can catch up to fresh state.</Tiny>
+ <div style={{ display: "grid", gap: 8, fontSize: 13 }}>
+ <PropRow label="Default scope" value={cursors.find((c) => c.projectName)?.projectName ?? cursors[0]?.scopeKey ?? "—"} />
+ <PropRow label="Cursors active" value={String(counts.cursors)} />
+ <PropRow label="Runs in flight" value={String(counts.runningRuns)} />
+ <PropRow label="Failed (24h)" value={String(counts.failedRuns24h)} />
+ <PropRow label="Review queue" value={String(counts.reviewRequired)} />
+ </div>
+ </CardBody>
+ </Card>
+
+ <Tiny>
+ Active cursors:&nbsp;
+ {cursors.slice(0, 6).map((cursor, idx) => (
+ <span key={cursor.id}>
+ {idx > 0 ? " · " : ""}
+ {cursor.projectName ?? cursor.rootIssueIdentifier ?? cursor.scopeKey}
+ </span>
+ ))}
+ {cursors.length > 6 ? <span>{` +${cursors.length - 6} more`}</span> : null}
+ </Tiny>
+ </div>
+ );
+}
+
+function SettingField({ label, hint, children }: { label: ReactNode; hint?: ReactNode; children: ReactNode }) {
+ return (
+ <div style={{ display: "grid", gap: 6, minWidth: 0 }}>
+ <label style={{ fontSize: 12, color: tokens.muted }}>{label}</label>
+ {children}
+ {hint ? <Tiny>{hint}</Tiny> : null}
+ </div>
+ );
+}
+
+function CheckboxRow({
+ label,
+ help,
+ defaultChecked,
+ checked,
+ onChange,
+ locked,
+ suffix,
+}: {
+ label: string;
+ help?: string;
+ defaultChecked?: boolean;
+ checked?: boolean;
+ onChange?: (checked: boolean) => void;
+ locked?: boolean;
+ suffix?: string;
+}) {
+ return (
+ <label style={{ display: "flex", alignItems: "flex-start", gap: 8, fontSize: 13 }}>
+ <input
+ type="checkbox"
+ defaultChecked={checked === undefined ? defaultChecked : undefined}
+ checked={checked}
+ disabled={locked}
+ onChange={(event) => onChange?.(event.currentTarget.checked)}
+ />
+ <span>
+ {label}
+ {suffix ? <span style={{ marginLeft: 6, fontSize: 11, color: tokens.muted }}>({suffix})</span> : null}
+ {help ? <Tiny style={{ display: "block", marginTop: 2 }}>{help}</Tiny> : null}
+ </span>
+ </label>
+ );
+}
+
+function RadioRow({ name, value, label, defaultChecked }: { name: string; value: string; label: string; defaultChecked?: boolean }) {
+ return (
+ <label style={{ display: "flex", alignItems: "flex-start", gap: 8, fontSize: 13 }}>
+ <input type="radio" name={name} value={value} defaultChecked={defaultChecked} />
+ <span>{label}</span>
+ </label>
+ );
+}
+
+function SelectInput({ defaultValue, options }: { defaultValue: string; options: ReadonlyArray<readonly [string, string]> }) {
+ return (
+ <select
+ defaultValue={defaultValue}
+ style={{
+ background: "oklch(0.2 0 0)",
+ color: tokens.fg,
+ border: `1px solid ${tokens.border}`,
+ borderRadius: 6,
+ padding: "6px 10px",
+ fontSize: 13,
+ }}
+ >
+ {options.map(([value, label]) => <option key={value} value={value}>{label}</option>)}
+ </select>
+ );
+}
+
+function SettingsBody({ context, initialSection = "root" }: { context: { companyId: string | null; companyPrefix?: string | null }; initialSection?: SettingsSectionKey }) {
+ const settings = useSettings(context.companyId);
+ const hostNavigation = useHostNavigation();
+ const { pathname } = useHostLocation();
+ const isMobile = useIsMobileLayout();
+ const bootstrap = usePluginAction("bootstrap-root");
+ const updateEventIngestion = usePluginAction("update-event-ingestion-settings");
+ const resetAgent = usePluginAction("reset-managed-agent");
+ const resetProject = usePluginAction("reset-managed-project");
+ const resetRoutine = usePluginAction("reset-managed-routine");
+ const reconcileAgent = usePluginAction("reconcile-managed-agent");
+ const reconcileProject = usePluginAction("reconcile-managed-project");
+ const selectAgent = usePluginAction("select-managed-agent");
+ const selectProject = usePluginAction("select-managed-project");
+ const resetSkills = usePluginAction("reset-managed-skills");
+ const reconcileRoutines = usePluginAction("reconcile-managed-routines");
+ const updateRoutineStatus = usePluginAction("update-managed-routine-status");
+ const runManagedRoutine = usePluginAction("run-managed-routine");
+ const toast = usePluginToast();
+
+ const [folderPath, setFolderPath] = useState("");
+ const [folderBusy, setFolderBusy] = useState(false);
+ const [agentBusy, setAgentBusy] = useState(false);
+ const [projectBusy, setProjectBusy] = useState(false);
+ const [selectedAgentId, setSelectedAgentId] = useState("");
+ const [selectedProjectId, setSelectedProjectId] = useState("");
+ const [routineBusyKey, setRoutineBusyKey] = useState<string | null>(null);
+ const [routineRepairBusy, setRoutineRepairBusy] = useState(false);
+ const [skillBusy, setSkillBusy] = useState(false);
+ const [allRepairBusy, setAllRepairBusy] = useState(false);
+ const [eventPolicy, setEventPolicy] = useState<EventIngestionSettings | null>(null);
+ const [eventPolicyBusy, setEventPolicyBusy] = useState(false);
+ const [activeSettingsSection, setActiveSettingsSection] = useState<SettingsSectionKey>(initialSection);
+
+ useEffect(() => {
+ if (settings.data?.folder.path && !folderPath) setFolderPath(settings.data.folder.path);
+ }, [settings.data?.folder.path, folderPath]);
+ useEffect(() => { if (settings.data?.managedAgent.agentId) setSelectedAgentId(settings.data.managedAgent.agentId); }, [settings.data?.managedAgent.agentId]);
+ useEffect(() => { if (settings.data?.managedProject.projectId) setSelectedProjectId(settings.data.managedProject.projectId); }, [settings.data?.managedProject.projectId]);
+ useEffect(() => {
+ if (settings.data?.eventIngestion && eventPolicy === null) setEventPolicy(settings.data.eventIngestion);
+ }, [settings.data?.eventIngestion, eventPolicy]);
+ useEffect(() => {
+ setActiveSettingsSection(initialSection);
+ }, [initialSection]);
+
+ if (!context.companyId) return <Callout>Choose a company to view LLM Wiki settings.</Callout>;
+ if (settings.loading) return <Tiny>Loading settings…</Tiny>;
+ if (settings.error) return <Callout tone="danger">{settings.error.message}</Callout>;
+ if (!settings.data) return <Tiny>No settings available.</Tiny>;
+
+ const data = settings.data;
+ const maintainerFallbackAgent: MaintainerAgentOption | null = data.managedAgent.agentId
+ ? {
+ id: data.managedAgent.agentId,
+ name: data.managedAgent.details?.name ?? "Wiki Maintainer",
+ status: data.managedAgent.details?.status ?? data.managedAgent.status,
+ adapterType: data.managedAgent.details?.adapterType ?? null,
+ icon: data.managedAgent.details?.icon ?? "book-open",
+ urlKey: data.managedAgent.details?.urlKey ?? null,
+ }
+ : null;
+ const maintainerAgentOptions = maintainerFallbackAgent && !data.agentOptions.some((agent) => agent.id === maintainerFallbackAgent.id)
+ ? [maintainerFallbackAgent, ...data.agentOptions]
+ : data.agentOptions;
+ const effectiveSelectedAgentId = selectedAgentId || data.managedAgent.agentId || "";
+ const currentMaintainerAgent = maintainerAgentOptions.find((agent) => agent.id === effectiveSelectedAgentId) ?? maintainerFallbackAgent;
+ const savedCustomMaintainer = data.managedAgent.source === "selected";
+ const selectingDifferentMaintainer = Boolean(
+ data.managedAgent.source === "managed" &&
+ data.managedAgent.agentId &&
+ effectiveSelectedAgentId &&
+ effectiveSelectedAgentId !== data.managedAgent.agentId,
+ );
+ const showMaintainerWarning = savedCustomMaintainer || selectingDifferentMaintainer;
+ const maintainerPendingApproval = currentMaintainerAgent?.status === "pending_approval" || data.managedAgent.details?.status === "pending_approval";
+ const agentLink = currentMaintainerAgent?.id
+ ? `/agents/${currentMaintainerAgent.id}`
+ : null;
+ const projectLink = data.managedProject.projectId
+ ? `/projects/${data.managedProject.projectId}`
+ : null;
+ const managedRoutines = data.managedRoutines ?? (data.managedRoutine ? [data.managedRoutine] : []);
+ const agentHealthItems = buildAgentHealthItems(data.managedAgent);
+ const agentHealthWarnings = agentHealthItems.filter((item) => !item.ok);
+ const routineHealthItems = buildRoutineHealthItems(managedRoutines, data.managedAgent, data.managedProject);
+ const routineHealthWarnings = routineHealthItems.filter((item) => !item.ok);
+ const projectHealthItems = buildProjectHealthItems(data.managedProject);
+ const projectHealthWarnings = projectHealthItems.filter((item) => !item.ok);
+ const managedSkills = data.managedSkills ?? [];
+ const skillHealthItems = buildSkillHealthItems(managedSkills);
+ const skillHealthWarnings = skillHealthItems.filter((item) => !item.ok);
+ const configurationErrors = [
+ ...(!data.folder.healthy ? ["Wiki root folder"] : []),
+ ...(agentHealthWarnings.length > 0 ? ["Managed agents"] : []),
+ ...(skillHealthWarnings.length > 0 ? ["Managed skills"] : []),
+ ...(projectHealthWarnings.length > 0 ? ["Managed projects"] : []),
+ ...(routineHealthWarnings.length > 0 ? ["Managed routines"] : []),
+ ];
+ const hasConfigurationErrors = configurationErrors.length > 0;
+ const projectFallbackOption: ProjectOption | null = data.managedProject.projectId
+ ? {
+ id: data.managedProject.projectId,
+ name: data.managedProject.details?.name ?? "Current project",
+ status: data.managedProject.details?.status ?? data.managedProject.status,
+ color: data.managedProject.details?.color ?? null,
+ }
+ : null;
+ const projectOptions = projectFallbackOption && !data.projectOptions.some((project) => project.id === projectFallbackOption.id)
+ ? [projectFallbackOption, ...data.projectOptions]
+ : data.projectOptions;
+ const effectiveSelectedProjectId = selectedProjectId || data.managedProject.projectId || "";
+ const currentProjectOption = projectOptions.find((project) => project.id === effectiveSelectedProjectId) ?? projectFallbackOption;
+ const currentEventPolicy = eventPolicy ?? data.eventIngestion;
+ const managedRoutineItems: ManagedRoutinesListItem[] = managedRoutines.map((routine) => {
+ const fallback = routineFallbackFor(routine);
+ const key = routine.resourceKey ?? routine.routineId ?? fallback.title;
+ const status = managedRoutineStatus(routine);
+ const assigneeAgentId = routine.routine?.assigneeAgentId ?? routine.details?.assigneeAgentId ?? null;
+
+ return {
+ key,
+ title: routine.routine?.title ?? routine.details?.title ?? fallback.title,
+ status: status === "missing" || status === "missing_refs" ? "paused" : status,
+ routineId: routine.routineId ?? routine.routine?.id ?? null,
+ href: routine.routineId ? `/routines/${routine.routineId}` : null,
+ resourceKey: routine.resourceKey ?? null,
+ projectId: routine.routine?.projectId ?? null,
+ assigneeAgentId,
+ cronExpression: routine.details?.cronExpression ?? fallback.cron,
+ lastRunAt: routine.routine?.lastTriggeredAt ?? routine.details?.lastRunAt ?? null,
+ managedByPluginDisplayName: routine.routine?.managedByPlugin?.pluginDisplayName ?? "LLM Wiki",
+ missingRefs: routine.missingRefs?.map((ref) => ({
+ resourceKind: ref.resourceKind,
+ resourceKey: ref.resourceKey,
+ })),
+ defaultDrift: routine.defaultDrift
+ ? {
+ changedFields: routine.defaultDrift.changedFields,
+ defaultTitle: routine.defaultDrift.defaultTitle ?? null,
+ defaultDescription: routine.defaultDrift.defaultDescription ?? null,
+ }
+ : null,
+ };
+ });
+ const routineDefaultDriftItems = managedRoutineItems.filter((routine) => routine.defaultDrift?.changedFields.length);
+ const agentDefaultDrift = data.managedAgent.defaultDrift;
+ const activeSpaceSlug = readActiveSpaceSlugFromLocation(pathname);
+
+ function routineBusyKeyFor(prefix: string) {
+ const marker = `${prefix}:`;
+ return routineBusyKey?.startsWith(marker) ? routineBusyKey.slice(marker.length) : null;
+ }
+
+ async function changeFolder() {
+ if (!context.companyId || !folderPath.trim()) return;
+ setFolderBusy(true);
+ try {
+ await bootstrap({ companyId: context.companyId, path: folderPath.trim() });
+ toast({ tone: "success", title: "Folder updated" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Folder update failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setFolderBusy(false);
+ }
+ }
+
+ async function chooseAgent() {
+ const agentId = selectedAgentId || data.managedAgent.agentId;
+ if (!context.companyId || !agentId) return;
+ setAgentBusy(true);
+ try {
+ await selectAgent({ companyId: context.companyId, agentId });
+ toast({ tone: "success", title: "Maintainer agent selected" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Agent selection failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setAgentBusy(false);
+ }
+ }
+
+ async function chooseProject() {
+ const projectId = effectiveSelectedProjectId;
+ if (!context.companyId || !projectId) return;
+ setProjectBusy(true);
+ try {
+ await selectProject({ companyId: context.companyId, projectId });
+ toast({ tone: "success", title: "Project selected" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Project selection failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setProjectBusy(false);
+ }
+ }
+
+ async function saveEventPolicy() {
+ if (!context.companyId || !eventPolicy) return;
+ setEventPolicyBusy(true);
+ try {
+ const next = await updateEventIngestion({ companyId: context.companyId, ...eventPolicy }) as EventIngestionSettings;
+ setEventPolicy(next);
+ toast({ tone: "success", title: "Event ingestion controls saved" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Could not save event controls", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setEventPolicyBusy(false);
+ }
+ }
+
+ async function repairManagedRoutines() {
+ if (!context.companyId) return;
+ setRoutineRepairBusy(true);
+ try {
+ await reconcileRoutines({ companyId: context.companyId });
+ toast({ tone: "success", title: "Routines fixed" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Routine repair failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setRoutineRepairBusy(false);
+ }
+ }
+
+ async function resyncManagedSkills() {
+ if (!context.companyId) return;
+ setSkillBusy(true);
+ try {
+ await resetSkills({ companyId: context.companyId });
+ toast({ tone: "success", title: "Skills synced" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Skill sync failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setSkillBusy(false);
+ }
+ }
+
+ async function fixAllConfigurationErrors() {
+ if (!context.companyId || !hasConfigurationErrors) return;
+ const confirmed = typeof window === "undefined" || window.confirm(
+ "Fix all detected LLM Wiki configuration errors? This may recreate missing wiki baseline files and restore plugin-managed agents, projects, routines, and skills to their current defaults.",
+ );
+ if (!confirmed) return;
+
+ setAllRepairBusy(true);
+ try {
+ if (!data.folder.healthy) {
+ const path = folderPath.trim() || data.folder.path?.trim() || "";
+ if (!path && !data.folder.configured) {
+ throw new Error("Choose a wiki root folder path before fixing all configuration errors.");
+ }
+ await bootstrap(path ? { companyId: context.companyId, path } : { companyId: context.companyId });
+ }
+
+ if (skillHealthWarnings.length > 0) {
+ await resetSkills({ companyId: context.companyId });
+ }
+
+ const shouldResetAgent =
+ data.managedAgent.source !== "managed" ||
+ !managedAgentIsReady(data.managedAgent) ||
+ Boolean(data.managedAgent.defaultDrift?.changedFiles.length);
+ const shouldResetProject =
+ data.managedProject.source !== "managed" ||
+ !managedProjectIsReady(data.managedProject);
+
+ if (shouldResetAgent) {
+ await resetAgent({ companyId: context.companyId });
+ } else if (routineHealthWarnings.length > 0) {
+ await reconcileAgent({ companyId: context.companyId });
+ }
+
+ if (shouldResetProject) {
+ await resetProject({ companyId: context.companyId });
+ } else if (routineHealthWarnings.length > 0) {
+ await reconcileProject({ companyId: context.companyId });
+ }
+
+ if (routineHealthWarnings.length > 0) {
+ await reconcileRoutines({ companyId: context.companyId });
+ }
+
+ toast({ tone: "success", title: "Configuration errors fixed" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Fix all failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setAllRepairBusy(false);
+ }
+ }
+
+ async function toggleManagedRoutine(routine: ManagedRoutinesListItem, enabled: boolean) {
+ if (!context.companyId || !routine.resourceKey) return;
+ if (!enabled && !routine.assigneeAgentId) {
+ toast({ tone: "warn", title: "Default agent required", body: "Set a default maintainer before enabling this routine." });
+ return;
+ }
+ setRoutineBusyKey(`status:${routine.key}`);
+ try {
+ await updateRoutineStatus({ companyId: context.companyId, routineKey: routine.resourceKey, status: enabled ? "paused" : "active" });
+ toast({ tone: "success", title: enabled ? "Routine paused" : "Routine enabled" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Routine update failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setRoutineBusyKey(null);
+ }
+ }
+
+ async function runManagedRoutineNow(routine: ManagedRoutinesListItem) {
+ if (!context.companyId || !routine.resourceKey) return;
+ const assigneeAgentId = routine.assigneeAgentId ?? data.managedAgent.agentId ?? null;
+ const projectId = routine.projectId ?? data.managedProject.projectId ?? null;
+ if (!assigneeAgentId) {
+ toast({ tone: "warn", title: "Default agent required", body: "Set a default maintainer before running this routine." });
+ return;
+ }
+
+ setRoutineBusyKey(`run:${routine.key}`);
+ try {
+ await runManagedRoutine({
+ companyId: context.companyId,
+ routineKey: routine.resourceKey,
+ assigneeAgentId,
+ projectId,
+ });
+ toast({ tone: "success", title: "Routine run started" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Routine run failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setRoutineBusyKey(null);
+ }
+ }
+
+ async function resetManagedRoutineToDefaults(routine: ManagedRoutinesListItem) {
+ if (!context.companyId || !routine.resourceKey) return;
+ const changedFields = routine.defaultDrift?.changedFields ?? [];
+ const fieldList = changedFields.length > 0 ? changedFields.join(", ") : "managed defaults";
+ const confirmed = typeof window === "undefined" || window.confirm(
+ `Update "${routine.title}" to the current LLM Wiki plugin defaults? This replaces ${fieldList}. Cancel to keep the current custom routine text.`,
+ );
+ if (!confirmed) return;
+
+ const assigneeAgentId = routine.assigneeAgentId ?? data.managedAgent.agentId ?? null;
+ const projectId = routine.projectId ?? data.managedProject.projectId ?? null;
+ setRoutineBusyKey(`reset:${routine.key}`);
+ try {
+ await resetRoutine({
+ companyId: context.companyId,
+ routineKey: routine.resourceKey,
+ assigneeAgentId,
+ projectId,
+ });
+ toast({ tone: "success", title: "Routine defaults updated" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Routine reset failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setRoutineBusyKey(null);
+ }
+ }
+
+ async function resetManagedAgentToDefaults() {
+ if (!context.companyId) return;
+ const changedFiles = agentDefaultDrift?.changedFiles ?? [];
+ const fileList = changedFiles.length > 0 ? changedFiles.join(", ") : "managed instructions and defaults";
+ const confirmed = typeof window === "undefined" || window.confirm(
+ `Update the Wiki Maintainer to the current LLM Wiki plugin defaults? This replaces ${fileList}. Cancel to keep the current custom instructions.`,
+ );
+ if (!confirmed) return;
+
+ setAgentBusy(true);
+ try {
+ await resetAgent({ companyId: context.companyId });
+ toast({ tone: "success", title: "Agent reset to plugin defaults" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Reset failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setAgentBusy(false);
+ }
+ }
+
+ const activeSettingsConfig =
+ SETTINGS_SECTIONS.find((section) => section.key === activeSettingsSection) ?? SETTINGS_SECTIONS[0];
+
+ return (
+ <div style={{
+ display: "flex",
+ flexDirection: isMobile ? "column" : "row",
+ gap: isMobile ? 16 : 24,
+ maxWidth: isMobile ? "none" : 1040,
+ minWidth: 0,
+ }}>
+ <aside style={{
+ width: isMobile ? "auto" : 230,
+ flexShrink: 0,
+ borderRight: isMobile ? "none" : `1px solid ${tokens.border}`,
+ borderBottom: isMobile ? `1px solid ${tokens.border}` : "none",
+ paddingRight: isMobile ? 0 : 16,
+ paddingBottom: isMobile ? 12 : 0,
+ }}>
+ <nav aria-label="LLM Wiki settings sections" style={{
+ display: "flex",
+ flexDirection: isMobile ? "row" : "column",
+ gap: 4,
+ overflowX: isMobile ? "auto" : "visible",
+ paddingBottom: isMobile ? 2 : 0,
+ }}>
+ {SETTINGS_SECTIONS.map((section) => (
+ <div key={section.key} style={{ minWidth: isMobile ? 190 : 0 }}>
+ <SettingsSectionButton
+ section={section}
+ active={activeSettingsSection === section.key}
+ onSelect={() => {
+ setActiveSettingsSection(section.key);
+ hostNavigation.navigate(buildSettingsSectionHref(section.key, activeSpaceSlug));
+ }}
+ />
+ </div>
+ ))}
+ </nav>
+ </aside>
+
+ <div style={{ flex: 1, minWidth: 0 }}>
+ {hasConfigurationErrors ? (
+ <div style={{ marginBottom: 18 }}>
+ <Callout tone="warn">
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
+ <div style={{ display: "grid", gap: 4, minWidth: 0 }}>
+ <strong>configuration errors detected, fix them all?</strong>
+ <Tiny>
+ {configurationErrors.join(", ")} {configurationErrors.length === 1 ? "needs" : "need"} attention.
+ </Tiny>
+ </div>
+ <Button size="sm" variant="primary" onClick={fixAllConfigurationErrors} loading={allRepairBusy}>
+ Fix them all
+ </Button>
+ </div>
+ </Callout>
+ </div>
+ ) : null}
+ {activeSettingsSection === "root" ? (
+ <section style={{ display: "grid", gap: 22, minWidth: 0 }}>
+ <h1 style={{ margin: 0, fontSize: isMobile ? 20 : 22, fontWeight: 700 }}>Setup</h1>
+ <SetupSection title="Base Folder">
+ <div style={{ display: "grid", gap: 12 }}>
+ <FolderPathPicker
+ value={folderPath}
+ onChange={setFolderPath}
+ onApply={changeFolder}
+ applyLabel="Apply path"
+ busy={folderBusy}
+ disabled={!folderPath.trim()}
+ onRefresh={() => settings.refresh()}
+ />
+ <FolderHealthChecklist folder={data.folder} />
+ {data.folder.problems.length > 0 ? (
+ <Callout tone="warn">{data.folder.problems.length} folder issue(s): {data.folder.problems.map((p) => p.message).join("; ")}</Callout>
+ ) : null}
+ </div>
+ </SetupSection>
+ <SetupSection title="Managed Agents" separated>
+ <div style={{ display: "grid", gap: 14, maxWidth: isMobile ? "none" : 620, minWidth: 0 }}>
+ <ManagedResourceHealthChecklist
+ items={agentHealthItems}
+ ariaLabel="Wiki agents health checklist"
+ heading="Agent health"
+ />
+ {agentHealthWarnings.length > 0 ? (
+ <Callout tone="warn">
+ <div style={{ display: "grid", gap: 8 }}>
+ <div>{agentHealthWarnings.length} agent issue(s) need attention.</div>
+ <ul style={{ margin: 0, paddingLeft: 18 }}>
+ {agentHealthWarnings.map((item) => <li key={item.label}>{item.detail}</li>)}
+ </ul>
+ </div>
+ </Callout>
+ ) : null}
+ <div style={{ display: "grid", gap: 8 }}>
+ <label style={{ fontSize: 12, color: tokens.muted }}>Maintainer</label>
+ <fieldset
+ disabled={agentBusy}
+ style={{ border: 0, margin: 0, minWidth: 0, padding: 0 }}
+ >
+ <AssigneePicker
+ companyId={context.companyId}
+ value={effectiveSelectedAgentId ? `agent:${effectiveSelectedAgentId}` : ""}
+ includeUsers={false}
+ placeholder="Select maintainer"
+ noneLabel="No maintainer"
+ searchPlaceholder="Search agents..."
+ emptyMessage="No agents found."
+ onChange={(_value, selection) => {
+ setSelectedAgentId(selection.assigneeAgentId ?? "");
+ }}
+ />
+ </fieldset>
+ <Tiny>
+ Adapter: {adapterTypeLabel(currentMaintainerAgent?.adapterType ?? data.managedAgent.details?.adapterType ?? null)}
+ </Tiny>
+ {maintainerPendingApproval ? (
+ <Callout tone="warn">
+ The Wiki Maintainer is pending approval. Approve the agent before relying on wiki ingest, query, lint, or scheduled maintenance tasks.
+ </Callout>
+ ) : null}
+ {showMaintainerWarning ? (
+ <Callout tone="warn">
+ This is not the Paperclip-provided Wiki Maintainer. Plugin operations and routines may miss the recommended wiki role, tools, and default instructions.
+ </Callout>
+ ) : null}
+ {agentDefaultDrift?.changedFiles.length ? (
+ <Callout tone="warn">
+ Wiki Maintainer instruction defaults changed: {agentDefaultDrift.changedFiles.join(", ")}. Reset only if you want to replace current custom instructions with the plugin template.
+ </Callout>
+ ) : null}
+ <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
+ <Button
+ size="sm"
+ variant="primary"
+ onClick={chooseAgent}
+ loading={agentBusy}
+ disabled={!effectiveSelectedAgentId || effectiveSelectedAgentId === data.managedAgent.agentId}
+ >
+ Save maintainer
+ </Button>
+ {agentLink ? <Button size="sm" onClick={() => hostNavigation.navigate(agentLink)}>Open agent ↗</Button> : null}
+ <Button size="sm" variant="ghost" onClick={async () => {
+ if (!context.companyId) return;
+ setAgentBusy(true);
+ try {
+ await reconcileAgent({ companyId: context.companyId });
+ toast({ tone: "success", title: "Agent reconciled" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Reconcile failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setAgentBusy(false);
+ }
+ }} loading={agentBusy}>Repair</Button>
+ <Button size="sm" variant="ghost" onClick={resetManagedAgentToDefaults} loading={agentBusy}>Reset to defaults</Button>
+ </div>
+ </div>
+ </div>
+ </SetupSection>
+ <SetupSection title="Managed Skills" separated>
+ <div style={{ display: "grid", gap: 12, maxWidth: isMobile ? "none" : 620, minWidth: 0 }}>
+ <SkillHealthChecklist items={skillHealthItems} />
+ {skillHealthWarnings.length > 0 ? (
+ <Callout tone="warn">
+ <div style={{ display: "grid", gap: 8 }}>
+ <div>{skillHealthWarnings.length} skill issue(s) need attention.</div>
+ <ul style={{ margin: 0, paddingLeft: 18 }}>
+ {skillHealthWarnings.map((item) => <li key={item.label}>{item.detail}</li>)}
+ </ul>
+ <div>
+ <Button size="sm" variant="primary" onClick={resyncManagedSkills} loading={skillBusy}>Re-sync skills</Button>
+ </div>
+ </div>
+ </Callout>
+ ) : (
+ <Callout>
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
+ <span>LLM Wiki skills are installed in the company skill library.</span>
+ <Button size="sm" variant="ghost" onClick={resyncManagedSkills} loading={skillBusy}>Re-sync skills</Button>
+ </div>
+ </Callout>
+ )}
+ </div>
+ </SetupSection>
+ <SetupSection title="Managed Projects" separated>
+ <div style={{ display: "grid", gap: 10, maxWidth: isMobile ? "none" : 620, minWidth: 0 }}>
+ <ManagedResourceHealthChecklist
+ items={projectHealthItems}
+ ariaLabel="Wiki projects health checklist"
+ heading="Project health"
+ />
+ {projectHealthWarnings.length > 0 ? (
+ <Callout tone="warn">
+ <div style={{ display: "grid", gap: 8 }}>
+ <div>{projectHealthWarnings.length} project issue(s) need attention.</div>
+ <ul style={{ margin: 0, paddingLeft: 18 }}>
+ {projectHealthWarnings.map((item) => <li key={item.label}>{item.detail}</li>)}
+ </ul>
+ </div>
+ </Callout>
+ ) : null}
+ <div style={{ display: "grid", gap: 8 }}>
+ <label style={{ fontSize: 12, color: tokens.muted }}>Use existing project</label>
+ <fieldset
+ disabled={projectBusy}
+ style={{ border: 0, margin: 0, minWidth: 0, padding: 0 }}
+ >
+ <ProjectPicker
+ companyId={context.companyId}
+ value={effectiveSelectedProjectId}
+ includeArchived
+ placeholder="Project"
+ noneLabel="No project"
+ searchPlaceholder="Search projects..."
+ emptyMessage="No projects found."
+ onChange={setSelectedProjectId}
+ />
+ </fieldset>
+ <Tiny>
+ Status: {projectStatusLabel(currentProjectOption?.status ?? data.managedProject.details?.status ?? data.managedProject.status)}
+ </Tiny>
+ <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
+ <Button size="sm" variant="primary" onClick={chooseProject} loading={projectBusy} disabled={!effectiveSelectedProjectId}>Save project</Button>
+ {projectLink ? <Button size="sm" onClick={() => hostNavigation.navigate(projectLink)}>Open project ↗</Button> : null}
+ <Button size="sm" variant="ghost" onClick={async () => {
+ if (!context.companyId) return;
+ setProjectBusy(true);
+ try {
+ await reconcileProject({ companyId: context.companyId });
+ toast({ tone: "success", title: "Project reconciled" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Reconcile failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setProjectBusy(false);
+ }
+ }} loading={projectBusy}>Repair / reconcile</Button>
+ <Button size="sm" variant="ghost" onClick={async () => {
+ if (!context.companyId) return;
+ setProjectBusy(true);
+ try {
+ await resetProject({ companyId: context.companyId });
+ toast({ tone: "success", title: "Project reset to plugin defaults" });
+ settings.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Reset failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setProjectBusy(false);
+ }
+ }} loading={projectBusy}>↺ Reset to plugin defaults</Button>
+ </div>
+ </div>
+ </div>
+ </SetupSection>
+ <SetupSection title="Managed Routines" separated>
+ <div style={{ display: "grid", gap: 12, maxWidth: isMobile ? "none" : 620, minWidth: 0 }}>
+ <RoutineHealthChecklist items={routineHealthItems} />
+ {routineHealthWarnings.length > 0 ? (
+ <Callout tone="warn">
+ <div style={{ display: "grid", gap: 8 }}>
+ <div>{routineHealthWarnings.length} routine issue(s) need attention.</div>
+ <ul style={{ margin: 0, paddingLeft: 18 }}>
+ {routineHealthWarnings.map((item) => <li key={item.label}>{item.detail}</li>)}
+ </ul>
+ <div>
+ <Button size="sm" variant="primary" onClick={repairManagedRoutines} loading={routineRepairBusy}>Fix routines</Button>
+ </div>
+ </div>
+ </Callout>
+ ) : routineDefaultDriftItems.length > 0 ? (
+ <Callout tone="warn">
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
+ <span>{routineDefaultDriftItems.length} routine default update{routineDefaultDriftItems.length === 1 ? "" : "s"} available.</span>
+ <Button size="sm" variant="primary" onClick={() => {
+ setActiveSettingsSection("routines");
+ hostNavigation.navigate(buildSettingsSectionHref("routines", activeSpaceSlug));
+ }}>Review defaults</Button>
+ </div>
+ </Callout>
+ ) : (
+ <Tiny>Managed routines are installed with the Wiki Maintainer and LLM Wiki project.</Tiny>
+ )}
+ </div>
+ </SetupSection>
+ </section>
+ ) : activeSettingsSection === "distillation" ? (
+ <SettingsPanel
+ title="Distillation"
+ badge={<Badge tone="default">Default space only</Badge>}
+ description="Read Paperclip issues, comments, and documents for this company and write project pages into the default wiki space. Assets/attachments and work products stay metadata-only in Phase 5 and are excluded from source-text extraction. Other spaces cannot be selected as a destination yet - that lands with per-space Paperclip ingestion profiles."
+ >
+ <DistillationSettingsPanel context={context} settings={data} />
+ </SettingsPanel>
+ ) : activeSettingsSection === "routines" ? (
+ <SettingsPanel title="Managed Routines" description={activeSettingsConfig.description}>
+ <div style={{ display: "grid", gap: 12 }}>
+ {routineDefaultDriftItems.length > 0 ? (
+ <Callout tone="warn">
+ <div style={{ display: "grid", gap: 6 }}>
+ <strong>Routine defaults changed.</strong>
+ <span>
+ Review rows marked with changed defaults. Reset a row to update it to the current LLM Wiki instructions, or leave it unchanged to keep custom routine text.
+ </span>
+ </div>
+ </Callout>
+ ) : null}
+ {routineHealthWarnings.length > 0 ? (
+ <Callout tone="warn">
+ <div style={{ display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
+ <div style={{ display: "grid", gap: 6, minWidth: 0 }}>
+ <strong>Routine setup needs repair.</strong>
+ <ul style={{ margin: 0, paddingLeft: 18 }}>
+ {routineHealthWarnings.map((item) => <li key={item.label}>{item.detail}</li>)}
+ </ul>
+ </div>
+ <Button size="sm" variant="primary" onClick={repairManagedRoutines} loading={routineRepairBusy}>Fix routines</Button>
+ </div>
+ </Callout>
+ ) : (
+ <Callout>
+ <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, flexWrap: "wrap" }}>
+ <span>Managed routines are installed with the Wiki Maintainer and LLM Wiki project.</span>
+ <Button size="sm" disabled>Routines valid</Button>
+ </div>
+ </Callout>
+ )}
+ <PluginManagedRoutinesList
+ routines={managedRoutineItems}
+ agents={maintainerAgentOptions}
+ projects={projectOptions}
+ pluginDisplayName="LLM Wiki"
+ runningRoutineKey={routineBusyKeyFor("run")}
+ statusMutationRoutineKey={routineBusyKeyFor("status")}
+ resettingRoutineKey={routineBusyKeyFor("reset")}
+ onRunNow={runManagedRoutineNow}
+ onToggleEnabled={toggleManagedRoutine}
+ onReset={resetManagedRoutineToDefaults}
+ />
+ </div>
+ </SettingsPanel>
+ ) : activeSettingsSection === "lint" ? (
+ <SettingsLintPanel context={context} />
+ ) : activeSettingsSection === "spaces" ? (
+ <SpacesSettingsPanel context={context} description={activeSettingsConfig.description} />
+ ) : activeSettingsSection === "events" ? (
+ <SettingsPanel
+ title="Paperclip event ingestion"
+ badge={<Badge tone={currentEventPolicy.enabled ? "running" : "default"}>{currentEventPolicy.enabled ? "enabled" : "off by default"}</Badge>}
+ description={activeSettingsConfig.description}
+ >
+ <Tiny style={{ marginBottom: 10 }}>
+ Company-scoped Paperclip events can advance default-space cursors. Enable only the first-party text sources this wiki should observe for default-space distillation.
+ </Tiny>
+ <div style={{ display: "grid", gap: 10 }}>
+ <label style={{ display: "flex", gap: 8, alignItems: "center", fontSize: 13 }}>
+ <input
+ type="checkbox"
+ checked={currentEventPolicy.enabled}
+ onChange={(event) => setEventPolicy({ ...currentEventPolicy, enabled: event.currentTarget.checked })}
+ />
+ Enable event ingestion for this company
+ </label>
+ <div style={{ display: "grid", gap: 8, paddingLeft: isMobile ? 0 : 22 }}>
+ {([
+ ["issues", "Issues", "Capture issue title and description when issue events fire."],
+ ["comments", "Comments", "Capture comment body when comment-created events fire."],
+ ["documents", "Documents", "Capture document body when document-created or document-updated events fire."],
+ ] as const).map(([key, label, help]) => (
+ <label key={key} style={{ display: "grid", gridTemplateColumns: "auto 1fr", columnGap: 8, rowGap: 2, alignItems: "start", fontSize: 13 }}>
+ <input
+ type="checkbox"
+ checked={currentEventPolicy.sources[key]}
+ onChange={(event) => setEventPolicy({
+ ...currentEventPolicy,
+ sources: { ...currentEventPolicy.sources, [key]: event.currentTarget.checked },
+ })}
+ />
+ <span>
+ {label}
+ <Tiny style={{ display: "block" }}>{help}</Tiny>
+ </span>
+ </label>
+ ))}
+ </div>
+ <div style={{ display: "grid", gap: 6, maxWidth: isMobile ? "none" : 220 }}>
+ <label style={{ fontSize: 12, color: tokens.muted }}>Max characters per captured event</label>
+ <TextInput
+ value={String(currentEventPolicy.maxCharacters)}
+ onChange={(event) => {
+ const parsed = Number(event.currentTarget.value);
+ setEventPolicy({ ...currentEventPolicy, maxCharacters: Number.isFinite(parsed) ? parsed : currentEventPolicy.maxCharacters });
+ }}
+ />
+ </div>
+ <Callout tone="warn">
+ Event ingestion records selected Paperclip issue, comment, and document activity for the default wiki space. Assets/attachments and work products are excluded here: Phase 5 allows metadata-only references later, not blob reads or linked-content fetches. It never reads across companies or creates non-default space cursors.
+ </Callout>
+ <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
+ <Button size="sm" variant="primary" onClick={saveEventPolicy} loading={eventPolicyBusy}>Save controls</Button>
+ <Button size="sm" variant="ghost" onClick={() => setEventPolicy(data.eventIngestion)}>Revert</Button>
+ </div>
+ </div>
+ </SettingsPanel>
+ ) : null}
+ </div>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Spaces settings — list of spaces with sub-nav and a per-space edit panel.
+// Reachable via /wiki/settings/spaces or /wiki/settings/spaces/<slug>.
+// ---------------------------------------------------------------------------
+
+function SpacesSettingsPanel({ context, description }: { context: { companyId: string | null; companyPrefix?: string | null }; description: string }) {
+ const { pathname } = useHostLocation();
+ const hostNavigation = useHostNavigation();
+ const activeSpaceSlug = useMemo(() => readActiveSpaceSlugFromLocation(pathname), [pathname]);
+ const editingSlug = useMemo(() => readSettingsSpaceSlugFromLocation(pathname), [pathname]);
+ const isMobile = useIsMobileLayout();
+ const spacesQuery = useSpaces(context.companyId);
+ const spaces = useMemo(() => {
+ const list = spacesQuery.data?.spaces ?? [];
+ return activeWikiSpaces(list).sort(compareSpaces);
+ }, [spacesQuery.data]);
+ const [createOpen, setCreateOpen] = useState(false);
+
+ const focusedSpace = useMemo(() => {
+ if (editingSlug) return spaces.find((s) => s.slug === editingSlug) ?? null;
+ return spaces.find((s) => s.slug === activeSpaceSlug) ?? spaces.find((s) => s.slug === DEFAULT_SPACE_SLUG) ?? spaces[0] ?? null;
+ }, [editingSlug, spaces, activeSpaceSlug]);
+
+ return (
+ <SettingsPanel title="Shared spaces" description={description}>
+ <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : "220px 1fr", gap: 18, alignItems: "flex-start" }}>
+ <aside style={{ display: "grid", gap: 4, minWidth: 0 }}>
+ {spaces.map((space) => {
+ const active = focusedSpace?.slug === space.slug;
+ return (
+ <button
+ key={space.slug}
+ type="button"
+ onClick={() => hostNavigation.navigate(buildSettingsSectionHref("spaces", activeSpaceSlug, space.slug))}
+ style={{
+ textAlign: "left",
+ background: active ? tokens.accent : "transparent",
+ border: `1px solid ${active ? tokens.border : "transparent"}`,
+ borderRadius: 6,
+ padding: "8px 10px",
+ color: tokens.fg,
+ cursor: "pointer",
+ fontFamily: fontStack,
+ display: "grid",
+ gap: 2,
+ }}
+ >
+ <span style={{ fontSize: 13, fontWeight: 600 }}>{space.displayName}</span>
+ <span style={{ fontSize: 11, color: tokens.muted, fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace" }}>{space.slug}</span>
+ </button>
+ );
+ })}
+ <button
+ type="button"
+ onClick={() => setCreateOpen(true)}
+ style={{
+ textAlign: "left",
+ background: "transparent",
+ border: `1px dashed ${tokens.border}`,
+ borderRadius: 6,
+ padding: "8px 10px",
+ color: "oklch(0.78 0.13 250)",
+ cursor: "pointer",
+ fontFamily: fontStack,
+ display: "flex",
+ alignItems: "center",
+ gap: 8,
+ fontSize: 13,
+ fontWeight: 600,
+ marginTop: 6,
+ }}
+ >
+ <PlusIcon size={14} />
+ Add space…
+ </button>
+ </aside>
+ <div style={{ minWidth: 0, display: "grid", gap: 14 }}>
+ {spacesQuery.loading && spaces.length === 0 ? <Tiny>Loading spaces…</Tiny> : null}
+ {spacesQuery.error ? <Callout tone="danger">Failed to load spaces: {spacesQuery.error.message}</Callout> : null}
+ {focusedSpace ? (
+ <SpaceEditCard
+ space={focusedSpace}
+ companyId={context.companyId}
+ isOnlySpace={spaces.length === 1}
+ refresh={spacesQuery.refresh}
+ onArchived={() => {
+ hostNavigation.navigate(buildSettingsSectionHref("spaces", activeSpaceSlug));
+ }}
+ />
+ ) : (
+ <Callout>Pick a space from the list, or create one with the “Add space…” button.</Callout>
+ )}
+ </div>
+ </div>
+ {createOpen && context.companyId ? (
+ <CreateSpaceModal
+ companyId={context.companyId}
+ existingSlugs={new Set(spaces.map((s) => s.slug))}
+ onClose={() => setCreateOpen(false)}
+ onCreated={(space) => {
+ setCreateOpen(false);
+ spacesQuery.refresh();
+ hostNavigation.navigate(buildSettingsSectionHref("spaces", activeSpaceSlug, space.slug));
+ }}
+ />
+ ) : null}
+ </SettingsPanel>
+ );
+}
+
+function SpaceEditCard({
+ space,
+ companyId,
+ isOnlySpace,
+ refresh,
+ onArchived,
+}: {
+ space: WikiSpace;
+ companyId: string | null;
+ isOnlySpace: boolean;
+ refresh: () => void;
+ onArchived: () => void;
+}) {
+ const updateSpace = usePluginAction("update-space");
+ const archiveSpace = usePluginAction("archive-space");
+ const bootstrapSpace = usePluginAction("bootstrap-space");
+ const folderStatusQuery = useSpaceFolderStatus(companyId, space.slug);
+ const toast = usePluginToast();
+ const isDefault = space.slug === DEFAULT_SPACE_SLUG;
+ const [displayName, setDisplayName] = useState(space.displayName);
+ const [busy, setBusy] = useState(false);
+ const [folderBusy, setFolderBusy] = useState(false);
+ const [archiveBusy, setArchiveBusy] = useState(false);
+
+ useEffect(() => {
+ setDisplayName(space.displayName);
+ }, [space.slug, space.displayName]);
+
+ const folder = folderStatusQuery.data?.folder ?? null;
+ const relativeRoot = folderStatusQuery.data?.relativeRoot ?? "";
+ const settingsRecord = (space.settings ?? {}) as Record<string, unknown>;
+ const folderModeLabel = space.folderMode === "managed_subfolder"
+ ? "New managed folder (under wiki root)"
+ : space.folderMode === "existing_local_folder"
+ ? "Existing folder under wiki root"
+ : space.folderMode;
+
+ async function saveName() {
+ if (!companyId || displayName.trim().length === 0 || displayName.trim() === space.displayName) return;
+ setBusy(true);
+ try {
+ await updateSpace({ companyId, spaceSlug: space.slug, displayName: displayName.trim() });
+ toast({ tone: "success", title: "Display name updated" });
+ refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Update failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function recreateBaseline() {
+ if (!companyId || folderBusy) return;
+ setFolderBusy(true);
+ try {
+ await bootstrapSpace({ companyId, spaceSlug: space.slug });
+ toast({ tone: "success", title: "Baseline restored", body: `Re-created the standard skeleton for ${space.displayName}.` });
+ folderStatusQuery.refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Bootstrap failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setFolderBusy(false);
+ }
+ }
+
+ async function archive() {
+ if (!companyId || isDefault || isOnlySpace || archiveBusy) return;
+ if (typeof window !== "undefined" && !window.confirm(`Archive ${space.displayName}? Pages stay on disk; you can restore later through the plugin API or by un-archiving from the database.`)) {
+ return;
+ }
+ setArchiveBusy(true);
+ try {
+ await archiveSpace({ companyId, spaceSlug: space.slug });
+ toast({ tone: "success", title: "Space archived", body: `${space.displayName} hidden from the sidebar.` });
+ refresh();
+ onArchived();
+ } catch (err) {
+ toast({ tone: "error", title: "Archive failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setArchiveBusy(false);
+ }
+ }
+
+ return (
+ <div style={{ display: "grid", gap: 12 }}>
+ <Card>
+ <CardHeader
+ title={
+ <span style={{ display: "flex", alignItems: "center", gap: 8 }}>
+ <FolderIcon size={16} />
+ <span>{space.displayName}</span>
+ <Badge tone="default" style={{ fontSize: 10 }}>{space.slug}</Badge>
+ <Badge tone={space.status === "active" ? "running" : "default"} style={{ fontSize: 10 }}>{space.status}</Badge>
+ </span>
+ }
+ right={
+ <span style={{ fontSize: 11, color: tokens.muted }}>
+ {space.spaceType} · {space.accessScope}
+ </span>
+ }
+ />
+ <CardBody>
+ <Tiny>
+ Stored under <Mono>{relativeRoot || (isDefault ? "(wiki root)" : `spaces/${space.slug}/`)}</Mono> within the configured wiki root.
+ </Tiny>
+ </CardBody>
+ </Card>
+
+ <Card>
+ <CardHeader title="Identity" />
+ <CardBody>
+ <div style={{ display: "grid", gap: 12 }}>
+ <FormField label="Display name">
+ <TextInput value={displayName} onChange={(event) => setDisplayName(event.target.value)} maxLength={120} />
+ </FormField>
+ <FormField label="Slug" help="Slug is locked once a space has indexed pages. Contact platform team to migrate.">
+ <TextInput value={space.slug} disabled style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", opacity: 0.7 }} />
+ </FormField>
+ <FormField label="Type" help="(Cloud connectors coming soon)">
+ <TextInput value={space.spaceType === "managed" ? "Folder" : space.spaceType} disabled style={{ opacity: 0.7 }} />
+ </FormField>
+ <div>
+ <Button variant="primary" size="sm" onClick={saveName} disabled={busy || displayName.trim() === space.displayName} loading={busy}>Save name</Button>
+ </div>
+ </div>
+ </CardBody>
+ </Card>
+
+ <Card>
+ <CardHeader title="Folder source & health" />
+ <CardBody>
+ <div style={{ display: "grid", gap: 12 }}>
+ <FormField label="Mode">
+ <TextInput value={folderModeLabel} disabled style={{ opacity: 0.7 }} />
+ </FormField>
+ <FormField label="Path">
+ <TextInput value={folder?.path ?? folder?.realPath ?? relativeRoot ?? "(unconfigured)"} disabled style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", opacity: 0.7 }} />
+ </FormField>
+ {folderStatusQuery.loading ? <Tiny>Loading folder status…</Tiny> : null}
+ {folderStatusQuery.error ? <Callout tone="danger">{folderStatusQuery.error.message}</Callout> : null}
+ {folder ? <SpaceFolderHealthChecklist folder={folder} /> : null}
+ <div>
+ <Button size="sm" onClick={recreateBaseline} loading={folderBusy}>Recreate baseline</Button>
+ </div>
+ </div>
+ </CardBody>
+ </Card>
+
+ <PaperclipIngestionSpaceCard companyId={companyId} space={space} refresh={refresh} />
+
+ <Card style={{ opacity: 0.56 }}>
+ <CardHeader title="Access" />
+ <CardBody>
+ <div aria-disabled="true" style={{ display: "grid", gap: 10 }}>
+ <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
+ <Badge tone="default" style={{ fontSize: 10 }}>{space.accessScope}</Badge>
+ <Badge tone="default" style={{ fontSize: 10 }}>Coming soon</Badge>
+ </div>
+ <Tiny>
+ Access scope is stored as metadata only. <Mono>shared</Mono>, <Mono>team</Mono>, and{" "}
+ <Mono>personal</Mono> are saved on the space record but do not currently enforce
+ read/write permissions, and they do not change which Paperclip sources reach this space.
+ </Tiny>
+ <FormField label="Owner user id">
+ <TextInput value={(settingsRecord.ownerUserHint as string | undefined) ?? space.ownerUserId ?? ""} disabled style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace" }} />
+ </FormField>
+ <FormField label="Owner team key">
+ <TextInput value={space.teamKey ?? ""} disabled style={{ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace" }} />
+ </FormField>
+ </div>
+ </CardBody>
+ </Card>
+
+ <Card style={{ borderColor: "oklch(0.5 0.18 25)" }}>
+ <CardHeader
+ title={<span style={{ color: "oklch(0.78 0.18 25)" }}>Danger zone</span>}
+ />
+ <CardBody>
+ <div style={{ display: "grid", gap: 8 }}>
+ <Tiny>
+ {isDefault
+ ? "The default space cannot be archived because new operations and tools fall back to it."
+ : isOnlySpace
+ ? "This is the only space in the company. Create another before archiving this one."
+ : "Archiving hides the space from the sidebar and pauses scheduled lint/index. Pages remain on disk."}
+ </Tiny>
+ <div>
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={archive}
+ disabled={isDefault || isOnlySpace || archiveBusy}
+ loading={archiveBusy}
+ title={isDefault ? "Default space cannot be archived" : isOnlySpace ? "At least one space must remain" : undefined}
+ >
+ Archive this space
+ </Button>
+ </div>
+ </div>
+ </CardBody>
+ </Card>
+ </div>
+ );
+}
+
+function paperclipIngestionStateBadge(data: PaperclipIngestionProfileData | null): { tone: Tone; label: string } {
+ if (!data) return { tone: "default", label: "Loading" };
+ if (data.effectiveState === "policy_blocked") return { tone: "blocked", label: "Locked" };
+ if (data.effectiveState === "pending_approval") return { tone: "queued", label: "Pending approval" };
+ if (data.effectiveState === "enabled_no_scopes") return { tone: "failed", label: "Misconfigured" };
+ if (data.effectiveState === "enabled") return { tone: "running", label: `On · ${data.profile.sourceScopes.length} source${data.profile.sourceScopes.length === 1 ? "" : "s"}` };
+ return { tone: "default", label: data.historicalPageCount > 0 ? `Off · ${data.historicalPageCount} historical pages` : "Off" };
+}
+
+function PaperclipIngestionSpaceCard({ companyId, space, refresh }: { companyId: string | null; space: WikiSpace; refresh: () => void }) {
+ const profileQuery = usePaperclipIngestionProfile(companyId, space.slug);
+ const updateProfile = usePluginAction("update-paperclip-ingestion-profile");
+ const toast = usePluginToast();
+ const data = profileQuery.data ?? null;
+ const [draft, setDraft] = useState<PaperclipIngestionProfile | null>(null);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ setDraft(data?.profile ?? null);
+ }, [data?.space.slug, data?.profile]);
+
+ const badge = paperclipIngestionStateBadge(data);
+ const locked = data?.effectiveState === "policy_blocked";
+ const sourceScope = draft?.sourceScopes[0];
+ const activeProjectLimit = sourceScope?.kind === "active_projects" ? sourceScope.limit : 3;
+ const canSave = Boolean(companyId && draft && !busy && !locked);
+ const emptyScopes = Boolean(draft?.enabled && draft.sourceScopes.length === 0);
+
+ function patchDraft(patch: Partial<PaperclipIngestionProfile>) {
+ setDraft((current) => current ? { ...current, ...patch } : current);
+ }
+
+ function setSourceKind(key: WikiEventIngestionSource, value: boolean) {
+ setDraft((current) => current
+ ? { ...current, sourceKinds: { ...current.sourceKinds, [key]: value } }
+ : current);
+ }
+
+ function setActiveProjectsLimit(value: number) {
+ setDraft((current) => current
+ ? {
+ ...current,
+ sourceScopes: [{ kind: "active_projects", limit: Math.max(1, Math.floor(value || 1)) }],
+ }
+ : current);
+ }
+
+ async function save() {
+ if (!companyId || !draft || locked) return;
+ setBusy(true);
+ try {
+ await updateProfile({ companyId, spaceSlug: space.slug, profile: draft });
+ toast({ tone: "success", title: "Paperclip ingestion profile saved", body: `${space.displayName} will use the selected Paperclip sources.` });
+ profileQuery.refresh();
+ refresh();
+ } catch (err) {
+ toast({ tone: "error", title: "Profile save failed", body: err instanceof Error ? err.message : String(err) });
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <Card>
+ <CardHeader
+ title={<span>Paperclip → {space.displayName}</span>}
+ right={<Badge tone={badge.tone} style={{ fontSize: 10 }}>{badge.label}</Badge>}
+ />
+ <CardBody>
+ <div style={{ display: "grid", gap: 12 }}>
+ {profileQuery.loading && !data ? <Tiny>Loading Paperclip ingestion profile…</Tiny> : null}
+ {profileQuery.error ? <Callout tone="danger">{profileQuery.error.message}</Callout> : null}
+ {locked ? (
+ <Callout tone="warn">
+ Locked — host permissions pending. Paperclip ingestion stays disabled on team and personal spaces until LLM Wiki enforces read/write permissions for non-shared spaces.
+ </Callout>
+ ) : null}
+ {data && data.historicalPageCount > 0 && data.effectiveState === "disabled" ? (
+ <Callout>
+ Off · {data.historicalPageCount} historical Paperclip page{data.historicalPageCount === 1 ? "" : "s"} still in this space. Disabling stops new observations but does not delete prior wiki pages.
+ </Callout>
+ ) : null}
+ {data && data.overlapCount > 0 ? (
+ <Callout>
+ {data.overlapCount} source overlap{data.overlapCount === 1 ? "" : "s"} with another enabled space. Duplicate destinations are allowed, but they are explicit.
+ </Callout>
+ ) : null}
+ {emptyScopes ? <Callout tone="warn">Pick at least one source scope before saving.</Callout> : null}
+ {draft ? (
+ <>
+ <label style={{ display: "flex", gap: 8, alignItems: "flex-start", fontSize: 13 }}>
+ <input
+ type="checkbox"
+ checked={draft.enabled}
+ disabled={locked || busy}
+ onChange={(event) => patchDraft({
+ enabled: event.currentTarget.checked,
+ sourceScopes: event.currentTarget.checked && draft.sourceScopes.length === 0
+ ? [{ kind: "active_projects", limit: activeProjectLimit }]
+ : draft.sourceScopes,
+ })}
+ />
+ <span>
+ Enable Paperclip ingestion for this destination space
+ <Tiny style={{ display: "block" }}>Future Paperclip issue, comment, and document events can advance cursors in {space.displayName}. Existing pages are preserved when this is turned off.</Tiny>
+ </span>
+ </label>
+ <div style={{ display: "grid", gap: 8 }}>
+ <strong style={{ fontSize: 13 }}>Source scope</strong>
+ <label style={{ display: "grid", gap: 6, maxWidth: 260 }}>
+ <Tiny>Recently active projects (auto)</Tiny>
+ <TextInput
+ value={String(activeProjectLimit)}
+ disabled={locked || busy}
+ onChange={(event) => setActiveProjectsLimit(Number(event.currentTarget.value))}
+ />
+ </label>
+ <Tiny>Specific projects, issue trees, and company-wide ingestion use the same profile API; this first editor keeps the default auto-scope path visible and capped.</Tiny>
+ </div>
+ <div style={{ display: "grid", gap: 8 }}>
+ <strong style={{ fontSize: 13 }}>Source kinds</strong>
+ {([
+ ["issues", "Issues"],
+ ["comments", "Comments"],
+ ["documents", "Documents"],
+ ] as const).map(([key, label]) => (
+ <label key={key} style={{ display: "flex", gap: 8, alignItems: "center", fontSize: 13 }}>
+ <input
+ type="checkbox"
+ checked={draft.sourceKinds[key]}
+ disabled={locked || busy}
+ onChange={(event) => setSourceKind(key, event.currentTarget.checked)}
+ />
+ {label}
+ </label>
+ ))}
+ <Tiny>Attachments — locked, metadata only; no file contents. Future extraction needs separate review.</Tiny>
+ <Tiny>Work products — locked, metadata only; no artifact contents.</Tiny>
+ </div>
+ <div style={{ display: "grid", gap: 8 }}>
+ <strong style={{ fontSize: 13 }}>Caps</strong>
+ <Tiny>
+ Defaults: {draft.cursor.maxWindowCharacters.toLocaleString()} chars/window · {draft.cursor.maxCharactersPerSource.toLocaleString()} chars/source.
+ </Tiny>
+ </div>
+ <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
+ <Button size="sm" variant="primary" onClick={save} loading={busy} disabled={!canSave || emptyScopes}>Save Paperclip profile</Button>
+ <Button size="sm" variant="ghost" onClick={() => setDraft(data?.profile ?? null)} disabled={busy}>Revert</Button>
+ </div>
+ </>
+ ) : null}
+ </div>
+ </CardBody>
+ </Card>
+ );
+}
+
+function SpaceFolderHealthChecklist({ folder }: { folder: FolderStatus }) {
+ const items = [
+ { key: "readable", label: "Folder readable", ok: folder.readable },
+ { key: "writable", label: "Folder writable", ok: folder.writable },
+ ...folder.requiredDirectories.map((dir) => ({
+ key: `dir-${dir}`,
+ label: `${dir}/ present`,
+ ok: !folder.missingDirectories.includes(dir),
+ })),
+ ...folder.requiredFiles.map((file) => ({
+ key: `file-${file}`,
+ label: `${file} present`,
+ ok: !folder.missingFiles.includes(file),
+ })),
+ ];
+
+ return (
+ <div role="list" aria-label="Space folder health checklist" style={{ position: "relative", display: "grid", gap: 0, padding: "2px 0" }}>
+ {items.length > 1 ? (
+ <span
+ aria-hidden
+ style={{
+ position: "absolute",
+ left: 8,
+ top: 12,
+ bottom: 12,
+ width: 1,
+ background: "oklch(0.38 0.09 145)",
+ }}
+ />
+ ) : null}
+ {items.map((item) => (
+ <div
+ key={item.key}
+ role="listitem"
+ style={{
+ display: "grid",
+ gridTemplateColumns: "18px minmax(0, 1fr)",
+ alignItems: "center",
+ gap: 10,
+ padding: "7px 0",
+ minWidth: 0,
+ }}
+ >
+ <span style={{ display: "inline-flex", justifyContent: "center", position: "relative", zIndex: 1, background: tokens.bg }}>
+ <StatusIcon status={item.ok ? "done" : "blocked"} />
+ </span>
+ <span style={{ fontSize: 13, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: item.ok ? tokens.fg : "oklch(0.85 0.1 70)" }}>
+ {item.label}
+ </span>
+ </div>
+ ))}
+ </div>
+ );
+}
diff --git a/packages/plugins/plugin-llm-wiki/src/ui/index.tsx b/packages/plugins/plugin-llm-wiki/src/ui/index.tsx
new file mode 100644
index 0000000000..f8f8bf1f20
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/src/ui/index.tsx
@@ -0,0 +1 @@
+export { SidebarLink, SettingsPage, WikiPage, WikiRouteSidebar } from "./app.js";
diff --git a/packages/plugins/plugin-llm-wiki/src/ui/issue-attachments.ts b/packages/plugins/plugin-llm-wiki/src/ui/issue-attachments.ts
new file mode 100644
index 0000000000..7e399bc707
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/src/ui/issue-attachments.ts
@@ -0,0 +1,49 @@
+type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
+
+export type IngestSourceActionResult = {
+ operation?: {
+ issue?: {
+ id?: unknown;
+ } | null;
+ } | null;
+};
+
+export function readIngestOperationIssueId(result: unknown): string {
+ const issueId = (result as IngestSourceActionResult | null)?.operation?.issue?.id;
+ if (typeof issueId === "string" && issueId.trim()) return issueId;
+ throw new Error("Ingest operation did not return an issue id; the dropped file could not be attached.");
+}
+
+async function readUploadError(response: Response): Promise<string> {
+ const body = await response.json().catch(() => null);
+ if (body && typeof body === "object") {
+ const error = (body as { error?: unknown; message?: unknown }).error;
+ if (typeof error === "string" && error.trim()) return error;
+ const message = (body as { error?: unknown; message?: unknown }).message;
+ if (typeof message === "string" && message.trim()) return message;
+ }
+ return `Attachment upload failed with HTTP ${response.status}.`;
+}
+
+export async function uploadIssueAttachmentFile(input: {
+ companyId: string;
+ issueId: string;
+ file: File;
+ fetchImpl?: FetchLike;
+}): Promise<unknown> {
+ const fetchImpl = input.fetchImpl ?? fetch;
+ const form = new FormData();
+ form.append("file", input.file);
+ const response = await fetchImpl(
+ `/api/companies/${encodeURIComponent(input.companyId)}/issues/${encodeURIComponent(input.issueId)}/attachments`,
+ {
+ method: "POST",
+ credentials: "include",
+ body: form,
+ },
+ );
+ if (!response.ok) {
+ throw new Error(await readUploadError(response));
+ }
+ return response.json();
+}
diff --git a/packages/plugins/plugin-llm-wiki/src/wiki.ts b/packages/plugins/plugin-llm-wiki/src/wiki.ts
new file mode 100644
index 0000000000..a1eddeac5a
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/src/wiki.ts
@@ -0,0 +1 @@
+export * from "./wiki/core.js";
diff --git a/packages/plugins/plugin-llm-wiki/src/wiki/core.ts b/packages/plugins/plugin-llm-wiki/src/wiki/core.ts
new file mode 100644
index 0000000000..5583dad76a
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/src/wiki/core.ts
@@ -0,0 +1,4976 @@
+import { createHash, randomUUID } from "node:crypto";
+import type { Agent, AgentSessionEvent, Issue, IssueComment, PluginContext, PluginEvent, PluginLocalFolderEntry, Project, ToolResult } from "@paperclipai/plugin-sdk";
+import type { IssueDocument, PluginIssueOriginKind, PluginManagedRoutineResolution, PluginManagedSkillResolution } from "@paperclipai/plugin-sdk/types";
+import {
+ DEFAULT_MAX_SOURCE_BYTES,
+ DEFAULT_MAX_PAPERCLIP_CURSOR_WINDOW_CHARS,
+ DEFAULT_MAX_PAPERCLIP_ISSUE_SOURCE_CHARS,
+ DEFAULT_MAX_PAPERCLIP_ROUTINE_RUN_CHARS,
+ DEFAULT_PAPERCLIP_COST_CENTS_PER_1K_CHARS,
+ PLUGIN_ID,
+ WIKI_MAINTAINER_AGENT_KEY,
+ WIKI_MANAGED_SKILL_KEYS,
+ WIKI_MAINTENANCE_ROUTINE_KEYS,
+ WIKI_PROJECT_KEY,
+ WIKI_ROOT_FOLDER_KEY,
+} from "../manifest.js";
+import {
+ BOOTSTRAP_FILES,
+ LINT_PROMPT,
+ QUERY_PROMPT,
+ REQUIRED_WIKI_DIRECTORIES,
+ REQUIRED_WIKI_FILES,
+} from "../templates.js";
+
+export const DEFAULT_WIKI_ID = "default";
+export const DEFAULT_SPACE_SLUG = "default";
+export const OPERATION_ORIGIN_KIND = `plugin:${PLUGIN_ID}:operation` as PluginIssueOriginKind;
+const EVENT_INGESTION_STATE_NAMESPACE = "llm-wiki";
+const EVENT_INGESTION_STATE_KEY = "event-ingestion";
+const EVENT_INGESTION_DEDUP_NAMESPACE = "llm-wiki-event-ingestion";
+const MAX_EVENT_SOURCE_CHARS = 20000;
+const MAX_PAPERCLIP_INGESTION_PROFILE_SOURCE_COUNT = 3;
+const MAX_PAPERCLIP_DISTILLATION_FAN_OUT = 25;
+const MAX_PAPERCLIP_PROFILE_SELECTED_PROJECTS = 25;
+const MAX_PAPERCLIP_PROFILE_ROOT_ISSUES = 25;
+const PROTECTED_WIKI_CONTROL_FILES = new Set(["AGENTS.md", "IDEA.md"]);
+export const PUBLIC_DISTILLATION_AUTO_APPLY_RESTRICTION =
+ "Authenticated/public deployments always require manual review before wiki writes.";
+
+export type WikiEventIngestionSource = "issues" | "comments" | "documents";
+export type PaperclipDistillationScope = "company" | "project" | "root_issue";
+export type PaperclipDistillationWorkItemKind = "manual" | "retry" | "backfill" | "priority_override" | "review_patch";
+
+export type WikiEventIngestionSettings = {
+ enabled: boolean;
+ sources: Record<WikiEventIngestionSource, boolean>;
+ wikiId: string;
+ maxCharacters: number;
+};
+
+export type PaperclipIngestionSourceScope =
+ | { kind: "active_projects"; limit: number; statuses?: Array<"in_progress" | "todo" | "done"> }
+ | { kind: "selected_projects"; projectIds: string[] }
+ | { kind: "root_issues"; issueIds: string[] }
+ | { kind: "company_all"; requiresBoardConfirmation: true };
+
+export type PaperclipIngestionProfileV1 = {
+ version: 1;
+ enabled: boolean;
+ sourceScopes: PaperclipIngestionSourceScope[];
+ sourceKinds: Record<WikiEventIngestionSource, boolean> & {
+ attachments: "off" | "metadata_only";
+ workProducts: "off" | "metadata_only";
+ };
+ cursor: {
+ maxWindowCharacters: number;
+ maxCharactersPerSource: number;
+ minSourceAgeMinutes: number;
+ maxWindowsPerRun: number;
+ staleAfterHours: number;
+ };
+ backfill: {
+ defaultStartAt?: string | null;
+ defaultEndAt?: string | null;
+ requireManualQueue: boolean;
+ };
+};
+
+export type PaperclipIngestionProfileEffectiveState =
+ | "enabled"
+ | "disabled"
+ | "policy_blocked"
+ | "pending_approval"
+ | "enabled_no_scopes";
+
+export type PaperclipIngestionProfileRead = {
+ wikiId: string;
+ space: Pick<WikiSpace, "id" | "slug" | "displayName" | "accessScope" | "status">;
+ profile: PaperclipIngestionProfileV1;
+ effectiveState: PaperclipIngestionProfileEffectiveState;
+ policyBlocks: string[];
+ historicalPageCount: number;
+ overlapCount: number;
+};
+
+export type DistillationAutoApplyRestriction = {
+ autoApplyAllowed: boolean;
+ autoApplyRestriction: string | null;
+ deploymentMode: "local_trusted" | "authenticated" | null;
+ deploymentExposure: "private" | "public" | null;
+};
+
+type PaperclipIngestionPolicyPurpose =
+ | "profile_read"
+ | "profile_update"
+ | "candidate_search"
+ | "queue"
+ | "execute"
+ | "event_routing";
+
+type PaperclipIngestionPolicyDecision =
+ | { allowed: true; space: WikiSpace }
+ | { allowed: false; space: WikiSpace; reason: "restricted_space" | "archived_space" | "profile_disabled" | "profile_empty"; message: string };
+
+type PaperclipIngestionCandidatesInput = SpaceInput & {
+ query?: string | null;
+};
+
+export type EnableActiveProjectDistillationResult = {
+ wikiId: string;
+ spaceSlug: string;
+ selectedProjects: Array<{
+ id: string;
+ name: string;
+ status: string;
+ observedAt: string | null;
+ cursorId: string;
+ }>;
+ eventIngestion: WikiEventIngestionSettings;
+};
+
+export const DEFAULT_EVENT_INGESTION_SETTINGS: WikiEventIngestionSettings = {
+ enabled: false,
+ sources: {
+ issues: false,
+ comments: false,
+ documents: false,
+ },
+ wikiId: DEFAULT_WIKI_ID,
+ maxCharacters: 12000,
+};
+
+export type WikiOverview = {
+ status: "ok";
+ checkedAt: string;
+ wikiId: string;
+ defaultSpace: WikiSpace;
+ folder: Awaited<ReturnType<PluginContext["localFolders"]["status"]>>;
+ managedAgent: WikiAgentResource;
+ managedProject: WikiProjectResource;
+ managedSkills: WikiSkillResource[];
+ operationCount: number;
+ eventIngestion: WikiEventIngestionSettings;
+ capabilities: readonly string[];
+ prompts: {
+ query: string;
+ lint: string;
+ };
+};
+
+export type WikiAgentResource = {
+ status: "missing" | "resolved" | "created" | "relinked" | "reset";
+ source: "managed" | "selected";
+ agentId: string | null;
+ resourceKey: string;
+ agent: Agent | null;
+ details: { name: string; status: string; adapterType: string | null; icon?: string | null; urlKey?: string | null } | null;
+ defaultDrift?: { entryFile: string; changedFiles: string[] } | null;
+};
+
+export type WikiProjectResource = {
+ status: "missing" | "resolved" | "created" | "relinked" | "reset";
+ source: "managed" | "selected";
+ projectId: string | null;
+ resourceKey: string;
+ project: Project | null;
+ details: { name: string; status: string; color: string | null } | null;
+};
+
+export type WikiSkillResource = {
+ status: "missing" | "resolved" | "created" | "relinked" | "reset";
+ skillId: string | null;
+ resourceKey: string;
+ skill: PluginManagedSkillResolution["skill"];
+ details: { name: string; key: string; description: string | null } | null;
+ defaultDrift?: { changedFiles: string[] } | null;
+};
+
+export type WikiResourceOption = {
+ id: string;
+ name: string;
+ status?: string | null;
+ adapterType?: string | null;
+ color?: string | null;
+ icon?: string | null;
+ urlKey?: string | null;
+};
+
+export type WikiSpace = {
+ id: string;
+ companyId: string;
+ wikiId: string;
+ slug: string;
+ displayName: string;
+ spaceType: string;
+ folderMode: string;
+ rootFolderKey: string;
+ pathPrefix: string | null;
+ configuredRootPath: string | null;
+ accessScope: string;
+ ownerUserId: string | null;
+ ownerAgentId: string | null;
+ teamKey: string | null;
+ settings: Record<string, unknown>;
+ status: "active" | "archived" | string;
+ createdAt: string | null;
+ updatedAt: string | null;
+};
+
+export type WikiSpaceWithFolderStatus = WikiSpace & {
+ relativeRoot: string;
+ folder: Awaited<ReturnType<PluginContext["localFolders"]["status"]>>;
+};
+
+type BootstrapInput = {
+ companyId: string;
+ path?: string | null;
+};
+
+type SpaceInput = {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+};
+
+type CreateSpaceInput = {
+ companyId: string;
+ wikiId?: string | null;
+ slug?: string | null;
+ displayName?: string | null;
+ folderMode?: "managed_subfolder" | "existing_local_folder" | null;
+ accessScope?: "shared" | "personal" | "team" | null;
+ settings?: Record<string, unknown> | null;
+};
+
+type UpdateSpaceInput = SpaceInput & {
+ displayName?: string | null;
+ settings?: Record<string, unknown> | null;
+ status?: "active" | "archived" | null;
+};
+
+type OperationInput = {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ operationType: "ingest" | "query" | "lint" | "file-as-page" | "index" | "distill" | "backfill";
+ title?: string | null;
+ prompt?: string | null;
+ useCheapModelProfile?: boolean;
+};
+
+type OperationSpaceContext = {
+ wikiId: string;
+ space: WikiSpace;
+ operationType: OperationInput["operationType"];
+ operationId: string;
+ prompt?: string | null;
+};
+
+type QuerySessionInput = {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ question: string;
+ title?: string | null;
+};
+
+type CaptureSourceInput = {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ sourceType?: string | null;
+ title?: string | null;
+ url?: string | null;
+ contents: string;
+ rawPath?: string | null;
+ metadata?: Record<string, unknown> | null;
+};
+
+type PaperclipSourceBundleInput = {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ projectId?: string | null;
+ rootIssueId?: string | null;
+ maxCharacters?: number | null;
+ maxCharactersPerSource?: number | null;
+ backfillStartAt?: string | null;
+ backfillEndAt?: string | null;
+ routineRun?: boolean;
+ includeComments?: boolean;
+ includeDocuments?: boolean;
+ workItemId?: string | null;
+ operationIssueId?: string | null;
+};
+
+type PaperclipSourceRef = {
+ kind: "issue" | "comment" | "document";
+ issueId: string;
+ issueIdentifier: string | null;
+ projectId: string | null;
+ title?: string | null;
+ commentId?: string;
+ documentId?: string;
+ documentKey?: string;
+ updatedAt?: string;
+ createdAt?: string;
+ redactionStatus?: "suppressed_sensitive_content";
+ redactionReasons?: string[];
+};
+
+type PaperclipSourceBundle = {
+ markdown: string;
+ sourceRefs: PaperclipSourceRef[];
+ sourceHash: string;
+ sourceWindowStart: string | null;
+ sourceWindowEnd: string | null;
+ clipped: boolean;
+ warnings: string[];
+};
+
+type PaperclipDistillationRunInput = PaperclipSourceBundleInput;
+
+type PaperclipDistillationOutcomeInput = {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ runId: string;
+ cursorId?: string | null;
+ status: "succeeded" | "failed" | "review_required";
+ sourceHash?: string | null;
+ sourceWindowEnd?: string | null;
+ warning?: string | null;
+ costCents?: number | null;
+ retryCount?: number | null;
+};
+
+type PaperclipDistillationWorkItemInput = {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ kind: PaperclipDistillationWorkItemKind;
+ projectId?: string | null;
+ rootIssueId?: string | null;
+ requestedByIssueId?: string | null;
+ priority?: "critical" | "high" | "medium" | "low" | null;
+ idempotencyKey?: string | null;
+ metadata?: Record<string, unknown> | null;
+};
+
+type PaperclipProjectPageDistillationInput = PaperclipSourceBundleInput & {
+ autoApply?: boolean;
+ expectedProjectPageHash?: string | null;
+ includeSupportingPages?: boolean;
+};
+
+type WritePageInput = {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ path: string;
+ contents: string;
+ expectedHash?: string | null;
+ summary?: string | null;
+ sourceRefs?: unknown;
+ operationId?: string | null;
+ writer?: "agent_tool" | "board_ui" | "plugin_internal";
+};
+
+type FileQueryAnswerInput = {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ querySessionId?: string | null;
+ question?: string | null;
+ answer?: string | null;
+ path: string;
+ title?: string | null;
+ contents?: string | null;
+ expectedHash?: string | null;
+};
+
+type ToolParams = Record<string, unknown>;
+type WikiResourceKind = "agent" | "project";
+type PaperclipDistillationPatchOperation =
+ | "standup_update"
+ | "project_page_distill"
+ | "decision_distill"
+ | "history_distill"
+ | "index_refresh"
+ | "log_append";
+type PaperclipDistillationPatch = {
+ pagePath: string;
+ operationType: PaperclipDistillationPatchOperation;
+ currentHash: string | null;
+ proposedHash: string;
+ proposedContents: string;
+ sourceHash: string;
+ sourceRefs: PaperclipSourceRef[];
+ cursorWindow: {
+ start: string | null;
+ end: string | null;
+ };
+ confidence: "high" | "medium" | "low";
+ warnings: string[];
+ humanReviewRequired: boolean;
+};
+type PaperclipEventIngestResult =
+ | { status: "skipped"; reason: "disabled" | "source_disabled" | "unsupported_event" | "missing_issue" | "missing_comment" | "missing_document" | "plugin_operation" | "already_ingested" }
+ | { status: "recorded"; sourceKind: WikiEventIngestionSource; sourceId: string; cursorId: string; issueId: string };
+
+type WikiResourceBinding = {
+ resolvedId: string | null;
+ metadata: Record<string, unknown>;
+};
+
+function stringField(value: unknown): string | null {
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
+}
+
+function requireString(value: unknown, name: string): string {
+ const field = stringField(value);
+ if (!field) throw new Error(`${name} is required`);
+ return field;
+}
+
+function normalizeWikiId(value: unknown): string {
+ return stringField(value) ?? DEFAULT_WIKI_ID;
+}
+
+export function normalizeSpaceSlug(value: unknown): string {
+ const raw = stringField(value) ?? DEFAULT_SPACE_SLUG;
+ const normalized = raw
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "");
+ if (!normalized) throw new Error("spaceSlug is required");
+ if (normalized.length > 64) throw new Error("spaceSlug must be 64 characters or fewer");
+ return normalized;
+}
+
+async function requirePaperclipIngestionPolicy(
+ ctx: PluginContext,
+ input: { companyId: string; wikiId: string; spaceSlug?: string | null },
+ purpose: PaperclipIngestionPolicyPurpose,
+ options: { requireEnabledProfile?: boolean } = {},
+): Promise<WikiSpace> {
+ const space = await resolveSpace(ctx, {
+ companyId: input.companyId,
+ wikiId: input.wikiId,
+ spaceSlug: input.spaceSlug,
+ });
+ const profile = await profileForSpace(ctx, input.companyId, space);
+ const decision = evaluatePaperclipProfilePolicy({
+ space,
+ profile,
+ purpose,
+ requireEnabledProfile: options.requireEnabledProfile,
+ });
+ if (!decision.allowed) throw new Error(decision.message);
+ return decision.space;
+}
+
+function assertPaperclipSourceScopePayload(input: { projectId?: string | null; rootIssueId?: string | null }) {
+ if (input.projectId && input.rootIssueId) {
+ throw new Error("Paperclip source scope must specify either projectId or rootIssueId, not both.");
+ }
+}
+
+function assertRequestedCharacterLimit(name: string, value: unknown, max: number) {
+ if (value == null) return;
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 1) {
+ throw new Error(`${name} must be a positive number.`);
+ }
+ if (Math.floor(value) > max) {
+ throw new Error(`${name} exceeds the hard Paperclip ingestion cap of ${max} characters.`);
+ }
+}
+
+function stableSpaceId(input: { companyId: string; wikiId: string; slug: string }): string {
+ const hex = createHash("md5")
+ .update(`${input.companyId}:${input.wikiId}:${input.slug}`)
+ .digest("hex");
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-4${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
+}
+
+function normalizeLimit(value: unknown, fallback: number, max: number): number {
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
+ return Math.max(1, Math.min(max, Math.floor(value)));
+}
+
+function contentHash(contents: string): string {
+ return createHash("sha256").update(contents, "utf8").digest("hex");
+}
+
+function byteLength(contents: string): number {
+ return Buffer.byteLength(contents, "utf8");
+}
+
+function slugify(value: string): string {
+ const slug = value
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "");
+ return slug || "source";
+}
+
+function jsonParam(value: unknown): string {
+ return JSON.stringify(value ?? {});
+}
+
+function jsonArrayParam(value: unknown): string {
+ return JSON.stringify(Array.isArray(value) ? value : []);
+}
+
+function isoString(value: unknown): string | null {
+ if (value instanceof Date) return value.toISOString();
+ if (typeof value === "string" && value.trim().length > 0) {
+ const parsed = new Date(value);
+ return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
+ }
+ return null;
+}
+
+function normalizeBoolean(value: unknown, fallback: boolean): boolean {
+ return typeof value === "boolean" ? value : fallback;
+}
+
+function normalizeMaxSourceBytes(value: unknown): number {
+ if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_MAX_SOURCE_BYTES;
+ return Math.max(1, Math.floor(value));
+}
+
+function normalizeBundleLimit(value: unknown, fallback: number): number {
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
+ return Math.max(1000, Math.floor(value));
+}
+
+function normalizeCostRate(value: unknown): number {
+ if (typeof value !== "number" || !Number.isFinite(value)) return DEFAULT_PAPERCLIP_COST_CENTS_PER_1K_CHARS;
+ return Math.max(0, value);
+}
+
+type PaperclipDistillationLimits = {
+ maxCharacters: number;
+ maxCharactersPerSource: number;
+ maxRoutineRunCharacters: number;
+ costCentsPerThousandSourceCharacters: number;
+};
+
+const DISTILLATION_REDACTED_VALUE = "***REDACTED***";
+const DISTILLATION_JSON_SECRET_FIELD_TEXT_RE =
+ /((?:"|')?(?:api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)(?:"|')?\s*:\s*(?:"|'))[^"'`\r\n]+((?:"|'))/gi;
+const DISTILLATION_ESCAPED_JSON_SECRET_FIELD_TEXT_RE =
+ /((?:\\")?(?:api[-_]?key|access[-_]?token|auth(?:_?token)?|authorization|bearer|secret|passwd|password|credential|jwt|private[-_]?key|cookie|connectionstring)(?:\\")?\s*:\s*(?:\\"))[^\\\r\n]+((?:\\"))/gi;
+const DISTILLATION_ENV_SECRET_ASSIGNMENT_RE =
+ /(\b[A-Za-z0-9_]*(?:TOKEN|KEY|SECRET|PASSWORD|PASSWD|AUTHORIZATION|JWT)[A-Za-z0-9_]*\s*=\s*)[^\s"'`]+/gi;
+const DISTILLATION_AUTHORIZATION_BEARER_RE = /(\bAuthorization\s*:\s*Bearer\s+)[^\s"'`]+/gi;
+const DISTILLATION_OPENAI_KEY_RE = /\bsk-[A-Za-z0-9_-]{12,}\b/g;
+const DISTILLATION_GITHUB_TOKEN_RE = /\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g;
+const DISTILLATION_JWT_RE =
+ /\b[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]{8,})?\b/g;
+const DISTILLATION_CONNECTION_STRING_RE =
+ /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqps?):\/\/[^\s"'`]+/gi;
+const DISTILLATION_PRIVATE_KEY_BLOCK_RE =
+ /-----BEGIN(?:[A-Z ]+)?PRIVATE KEY-----[\s\S]*?-----END(?:[A-Z ]+)?PRIVATE KEY-----/gi;
+const DISTILLATION_PRIVATE_KEY_BLOCK_TEST_RE =
+ /-----BEGIN(?:[A-Z ]+)?PRIVATE KEY-----[\s\S]*?-----END(?:[A-Z ]+)?PRIVATE KEY-----/i;
+
+type DistillationSourceProtectionResult = {
+ body: string;
+ warning: string | null;
+ refPatch: Pick<PaperclipSourceRef, "redactionStatus" | "redactionReasons">;
+};
+
+function redactDistillationSensitiveText(input: string): string {
+ return input
+ .replace(DISTILLATION_PRIVATE_KEY_BLOCK_RE, DISTILLATION_REDACTED_VALUE)
+ .replace(DISTILLATION_JSON_SECRET_FIELD_TEXT_RE, `$1${DISTILLATION_REDACTED_VALUE}$2`)
+ .replace(DISTILLATION_ESCAPED_JSON_SECRET_FIELD_TEXT_RE, `$1${DISTILLATION_REDACTED_VALUE}$2`)
+ .replace(DISTILLATION_ENV_SECRET_ASSIGNMENT_RE, `$1${DISTILLATION_REDACTED_VALUE}`)
+ .replace(DISTILLATION_AUTHORIZATION_BEARER_RE, `$1${DISTILLATION_REDACTED_VALUE}`)
+ .replace(DISTILLATION_CONNECTION_STRING_RE, DISTILLATION_REDACTED_VALUE)
+ .replace(DISTILLATION_OPENAI_KEY_RE, DISTILLATION_REDACTED_VALUE)
+ .replace(DISTILLATION_GITHUB_TOKEN_RE, DISTILLATION_REDACTED_VALUE)
+ .replace(DISTILLATION_JWT_RE, DISTILLATION_REDACTED_VALUE);
+}
+
+function protectDistillationSourceBody(input: {
+ issue: Issue;
+ sourceKind: "comment" | "document";
+ sourceId: string;
+ body: string;
+}): DistillationSourceProtectionResult {
+ const redactedBody = redactDistillationSensitiveText(input.body);
+ const reasons = [
+ DISTILLATION_PRIVATE_KEY_BLOCK_TEST_RE.test(input.body) ? "private_key_block" : null,
+ redactedBody !== input.body ? "secret_like_token" : null,
+ ].filter((reason): reason is string => Boolean(reason));
+ if (reasons.length === 0) {
+ return {
+ body: input.body,
+ warning: null,
+ refPatch: {},
+ };
+ }
+
+ return {
+ body: [
+ `[Suppressed by LLM Wiki distillation security policy for this ${input.sourceKind}.]`,
+ "",
+ `- Source ID: ${input.sourceId}`,
+ `- Redaction reasons: ${reasons.join(", ")}`,
+ "- Review the original Paperclip source directly if a human needs the unredacted material.",
+ ].join("\n"),
+ warning: `Suppressed ${input.sourceKind} content for ${sourceTitleForIssue(input.issue)} / ${input.sourceId}: ${reasons.join(", ")}.`,
+ refPatch: {
+ redactionStatus: "suppressed_sensitive_content",
+ redactionReasons: reasons,
+ },
+ };
+}
+
+async function resolvePaperclipDistillationLimits(
+ ctx: PluginContext,
+ input: Pick<PaperclipSourceBundleInput, "maxCharacters" | "maxCharactersPerSource" | "routineRun">,
+): Promise<PaperclipDistillationLimits> {
+ assertRequestedCharacterLimit("maxCharacters", input.maxCharacters, DEFAULT_MAX_PAPERCLIP_CURSOR_WINDOW_CHARS);
+ assertRequestedCharacterLimit("maxCharactersPerSource", input.maxCharactersPerSource, DEFAULT_MAX_PAPERCLIP_ISSUE_SOURCE_CHARS);
+ const config = await ctx.config.get() as Record<string, unknown>;
+ const maxCharactersPerSource = Math.min(
+ normalizeBundleLimit(input.maxCharactersPerSource, DEFAULT_MAX_PAPERCLIP_ISSUE_SOURCE_CHARS),
+ normalizeBundleLimit(config.maxPaperclipIssueSourceCharacters, DEFAULT_MAX_PAPERCLIP_ISSUE_SOURCE_CHARS),
+ );
+ const cursorWindowCap = normalizeBundleLimit(
+ config.maxPaperclipCursorWindowCharacters,
+ DEFAULT_MAX_PAPERCLIP_CURSOR_WINDOW_CHARS,
+ );
+ const routineRunCap = normalizeBundleLimit(
+ config.maxPaperclipRoutineRunCharacters,
+ DEFAULT_MAX_PAPERCLIP_ROUTINE_RUN_CHARS,
+ );
+ const requestedMaxCharacters = normalizeBundleLimit(input.maxCharacters, cursorWindowCap);
+ const hardCharacterCap = input.routineRun ? Math.min(cursorWindowCap, routineRunCap) : cursorWindowCap;
+ return {
+ maxCharacters: Math.min(requestedMaxCharacters, hardCharacterCap),
+ maxCharactersPerSource,
+ maxRoutineRunCharacters: routineRunCap,
+ costCentsPerThousandSourceCharacters: normalizeCostRate(config.paperclipCostCentsPerThousandSourceCharacters),
+ };
+}
+
+async function resolvePaperclipDistillationLimitsForSpace(
+ ctx: PluginContext,
+ input: Pick<PaperclipSourceBundleInput, "companyId" | "maxCharacters" | "maxCharactersPerSource" | "routineRun"> & { space: WikiSpace },
+): Promise<PaperclipDistillationLimits> {
+ const [base, profile] = await Promise.all([
+ resolvePaperclipDistillationLimits(ctx, input),
+ profileForSpace(ctx, input.companyId, input.space),
+ ]);
+ return {
+ ...base,
+ maxCharacters: Math.min(base.maxCharacters, profile.cursor.maxWindowCharacters),
+ maxCharactersPerSource: Math.min(base.maxCharactersPerSource, profile.cursor.maxCharactersPerSource),
+ };
+}
+
+function estimateSourceCostCents(characters: number, costCentsPerThousandSourceCharacters: number): number {
+ if (characters <= 0 || costCentsPerThousandSourceCharacters <= 0) return 0;
+ return Math.ceil((characters / 1000) * costCentsPerThousandSourceCharacters);
+}
+
+async function assertSourceWithinConfiguredLimit(ctx: PluginContext, contents: string) {
+ const config = await ctx.config.get();
+ const maxSourceBytes = normalizeMaxSourceBytes(config.maxSourceBytes);
+ const sourceBytes = byteLength(contents);
+ if (sourceBytes > maxSourceBytes) {
+ throw new Error(`Source content is ${sourceBytes} bytes, which exceeds the configured LLM Wiki source limit of ${maxSourceBytes} bytes.`);
+ }
+}
+
+function normalizeEventIngestionSettings(value: unknown): WikiEventIngestionSettings {
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
+ return { ...DEFAULT_EVENT_INGESTION_SETTINGS, sources: { ...DEFAULT_EVENT_INGESTION_SETTINGS.sources } };
+ }
+ const record = value as Record<string, unknown>;
+ const sources = record.sources && typeof record.sources === "object" && !Array.isArray(record.sources)
+ ? record.sources as Record<string, unknown>
+ : {};
+ const maxCharacters = typeof record.maxCharacters === "number" && Number.isFinite(record.maxCharacters)
+ ? Math.max(1000, Math.min(MAX_EVENT_SOURCE_CHARS, Math.floor(record.maxCharacters)))
+ : DEFAULT_EVENT_INGESTION_SETTINGS.maxCharacters;
+ return {
+ enabled: normalizeBoolean(record.enabled, DEFAULT_EVENT_INGESTION_SETTINGS.enabled),
+ sources: {
+ issues: normalizeBoolean(sources.issues, DEFAULT_EVENT_INGESTION_SETTINGS.sources.issues),
+ comments: normalizeBoolean(sources.comments, DEFAULT_EVENT_INGESTION_SETTINGS.sources.comments),
+ documents: normalizeBoolean(sources.documents, DEFAULT_EVENT_INGESTION_SETTINGS.sources.documents),
+ },
+ wikiId: normalizeWikiId(record.wikiId),
+ maxCharacters,
+ };
+}
+
+function defaultPaperclipIngestionProfile(input: {
+ space: Pick<WikiSpace, "slug">;
+ legacySettings?: WikiEventIngestionSettings | null;
+}): PaperclipIngestionProfileV1 {
+ const legacy = input.space.slug === DEFAULT_SPACE_SLUG ? input.legacySettings : null;
+ return {
+ version: 1,
+ enabled: legacy?.enabled ?? false,
+ sourceScopes: legacy?.enabled ? [{ kind: "company_all", requiresBoardConfirmation: true }] : [],
+ sourceKinds: {
+ issues: legacy?.sources.issues ?? true,
+ comments: legacy?.sources.comments ?? true,
+ documents: legacy?.sources.documents ?? true,
+ attachments: "off",
+ workProducts: "off",
+ },
+ cursor: {
+ maxWindowCharacters: DEFAULT_MAX_PAPERCLIP_CURSOR_WINDOW_CHARS,
+ maxCharactersPerSource: DEFAULT_MAX_PAPERCLIP_ISSUE_SOURCE_CHARS,
+ minSourceAgeMinutes: 15,
+ maxWindowsPerRun: 6,
+ staleAfterHours: 72,
+ },
+ backfill: {
+ defaultStartAt: null,
+ defaultEndAt: null,
+ requireManualQueue: true,
+ },
+ };
+}
+
+function stringArray(value: unknown): string[] {
+ if (!Array.isArray(value)) return [];
+ return [...new Set(value.map((item) => stringField(item)).filter((item): item is string => Boolean(item)))];
+}
+
+function normalizePaperclipIngestionSourceScope(value: unknown): PaperclipIngestionSourceScope | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const record = value as Record<string, unknown>;
+ const kind = stringField(record.kind);
+ if (kind === "active_projects") {
+ const statuses = Array.isArray(record.statuses)
+ ? record.statuses.filter((status): status is "in_progress" | "todo" | "done" =>
+ status === "in_progress" || status === "todo" || status === "done")
+ : undefined;
+ return {
+ kind,
+ limit: normalizeLimit(record.limit, 3, MAX_PAPERCLIP_PROFILE_SELECTED_PROJECTS),
+ ...(statuses && statuses.length > 0 ? { statuses: [...new Set(statuses)] } : {}),
+ };
+ }
+ if (kind === "selected_projects") {
+ return { kind, projectIds: stringArray(record.projectIds).slice(0, MAX_PAPERCLIP_PROFILE_SELECTED_PROJECTS) };
+ }
+ if (kind === "root_issues") {
+ return { kind, issueIds: stringArray(record.issueIds).slice(0, MAX_PAPERCLIP_PROFILE_ROOT_ISSUES) };
+ }
+ if (kind === "company_all") {
+ return { kind, requiresBoardConfirmation: true };
+ }
+ return null;
+}
+
+function normalizePaperclipIngestionProfile(
+ value: unknown,
+ input: { space: Pick<WikiSpace, "slug">; legacySettings?: WikiEventIngestionSettings | null },
+): PaperclipIngestionProfileV1 {
+ const fallback = defaultPaperclipIngestionProfile(input);
+ if (!value || typeof value !== "object" || Array.isArray(value)) return fallback;
+ const record = value as Record<string, unknown>;
+ const sourceKinds = record.sourceKinds && typeof record.sourceKinds === "object" && !Array.isArray(record.sourceKinds)
+ ? record.sourceKinds as Record<string, unknown>
+ : {};
+ const cursor = record.cursor && typeof record.cursor === "object" && !Array.isArray(record.cursor)
+ ? record.cursor as Record<string, unknown>
+ : {};
+ const backfill = record.backfill && typeof record.backfill === "object" && !Array.isArray(record.backfill)
+ ? record.backfill as Record<string, unknown>
+ : {};
+ return {
+ version: 1,
+ enabled: normalizeBoolean(record.enabled, fallback.enabled),
+ sourceScopes: Array.isArray(record.sourceScopes)
+ ? record.sourceScopes.map(normalizePaperclipIngestionSourceScope).filter((scope): scope is PaperclipIngestionSourceScope => Boolean(scope))
+ : fallback.sourceScopes,
+ sourceKinds: {
+ issues: normalizeBoolean(sourceKinds.issues, fallback.sourceKinds.issues),
+ comments: normalizeBoolean(sourceKinds.comments, fallback.sourceKinds.comments),
+ documents: normalizeBoolean(sourceKinds.documents, fallback.sourceKinds.documents),
+ attachments: sourceKinds.attachments === "metadata_only" ? "metadata_only" : "off",
+ workProducts: sourceKinds.workProducts === "metadata_only" ? "metadata_only" : "off",
+ },
+ cursor: {
+ maxWindowCharacters: normalizeLimit(cursor.maxWindowCharacters, fallback.cursor.maxWindowCharacters, DEFAULT_MAX_PAPERCLIP_CURSOR_WINDOW_CHARS),
+ maxCharactersPerSource: normalizeLimit(cursor.maxCharactersPerSource, fallback.cursor.maxCharactersPerSource, DEFAULT_MAX_PAPERCLIP_ISSUE_SOURCE_CHARS),
+ minSourceAgeMinutes: normalizeLimit(cursor.minSourceAgeMinutes, fallback.cursor.minSourceAgeMinutes, 24 * 60),
+ maxWindowsPerRun: normalizeLimit(cursor.maxWindowsPerRun, fallback.cursor.maxWindowsPerRun, 25),
+ staleAfterHours: normalizeLimit(cursor.staleAfterHours, fallback.cursor.staleAfterHours, 24 * 30),
+ },
+ backfill: {
+ defaultStartAt: isoString(backfill.defaultStartAt),
+ defaultEndAt: isoString(backfill.defaultEndAt),
+ requireManualQueue: normalizeBoolean(backfill.requireManualQueue, fallback.backfill.requireManualQueue),
+ },
+ };
+}
+
+async function profileForSpace(ctx: PluginContext, companyId: string, space: WikiSpace): Promise<PaperclipIngestionProfileV1> {
+ const legacySettings = space.slug === DEFAULT_SPACE_SLUG ? await getEventIngestionSettings(ctx, companyId) : null;
+ return normalizePaperclipIngestionProfile(space.settings.paperclipIngestion, { space, legacySettings });
+}
+
+function eventIngestionStateKey(companyId: string) {
+ return {
+ scopeKind: "company" as const,
+ scopeId: companyId,
+ namespace: EVENT_INGESTION_STATE_NAMESPACE,
+ stateKey: EVENT_INGESTION_STATE_KEY,
+ };
+}
+
+function eventIngestionDedupKey(companyId: string, wikiId: string, spaceId: string, sourceKind: WikiEventIngestionSource, sourceId: string) {
+ return {
+ scopeKind: "company" as const,
+ scopeId: companyId,
+ namespace: EVENT_INGESTION_DEDUP_NAMESPACE,
+ stateKey: `${wikiId}:${spaceId}:${sourceKind}:${sourceId}`,
+ };
+}
+
+export async function getEventIngestionSettings(ctx: PluginContext, companyId: string): Promise<WikiEventIngestionSettings> {
+ return normalizeEventIngestionSettings(await ctx.state.get(eventIngestionStateKey(companyId)));
+}
+
+function evaluatePaperclipProfilePolicy(input: {
+ space: WikiSpace;
+ profile?: PaperclipIngestionProfileV1 | null;
+ purpose: PaperclipIngestionPolicyPurpose;
+ requireEnabledProfile?: boolean;
+}): PaperclipIngestionPolicyDecision {
+ const { space, profile, purpose } = input;
+ if (space.status !== "active") {
+ return {
+ allowed: false,
+ space,
+ reason: "archived_space",
+ message: `Paperclip ingestion policy denied ${purpose}: space "${space.slug}" is ${space.status}.`,
+ };
+ }
+ if (space.accessScope !== "shared") {
+ return {
+ allowed: false,
+ space,
+ reason: "restricted_space",
+ message: `Paperclip ingestion policy denied ${purpose}: ${space.accessScope} spaces cannot ingest Paperclip sources until host permissions are enforced.`,
+ };
+ }
+ if (input.requireEnabledProfile && space.slug !== DEFAULT_SPACE_SLUG && !profile?.enabled) {
+ return {
+ allowed: false,
+ space,
+ reason: "profile_disabled",
+ message: `Paperclip ingestion policy denied ${purpose}: Paperclip ingestion is not enabled for space "${space.slug}".`,
+ };
+ }
+ if (input.requireEnabledProfile && space.slug !== DEFAULT_SPACE_SLUG && profile?.enabled && profile.sourceScopes.length === 0) {
+ return {
+ allowed: false,
+ space,
+ reason: "profile_empty",
+ message: `Paperclip ingestion policy denied ${purpose}: space "${space.slug}" has no source scopes configured.`,
+ };
+ }
+ return { allowed: true, space };
+}
+
+export async function getPaperclipIngestionProfile(
+ ctx: PluginContext,
+ input: { companyId: string; wikiId?: string | null; spaceSlug?: string | null },
+): Promise<PaperclipIngestionProfileRead> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const profile = await profileForSpace(ctx, input.companyId, space);
+ const policy = evaluatePaperclipProfilePolicy({ space, profile, purpose: "profile_read" });
+ const historicalPageCount = await countPaperclipHistoricalPages(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceId: space.id,
+ });
+ const overlapCount = await countPaperclipProfileOverlaps(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ space,
+ profile,
+ });
+ const effectiveState: PaperclipIngestionProfileEffectiveState = !policy.allowed
+ ? "policy_blocked"
+ : profile.enabled && profile.sourceScopes.length === 0
+ ? "enabled_no_scopes"
+ : profile.enabled
+ ? "enabled"
+ : "disabled";
+ return {
+ wikiId,
+ space: {
+ id: space.id,
+ slug: space.slug,
+ displayName: space.displayName,
+ accessScope: space.accessScope,
+ status: space.status,
+ },
+ profile,
+ effectiveState,
+ policyBlocks: policy.allowed ? [] : [policy.message],
+ historicalPageCount,
+ overlapCount,
+ };
+}
+
+async function countPaperclipHistoricalPages(ctx: PluginContext, input: { companyId: string; wikiId: string; spaceId: string }): Promise<number> {
+ const rows = await ctx.db.query<{ count: string | number }>(
+ `SELECT count(*)::text AS count
+ FROM ${pageBindingTable(ctx)}
+ WHERE company_id = $1 AND wiki_id = $2 AND space_id = $3`,
+ [input.companyId, input.wikiId, input.spaceId],
+ );
+ return Number(rows[0]?.count ?? 0) || 0;
+}
+
+function scopeIdentity(scope: PaperclipIngestionSourceScope): string[] {
+ if (scope.kind === "active_projects") return [`active_projects:${scope.limit}`];
+ if (scope.kind === "selected_projects") return scope.projectIds.map((id) => `project:${id}`);
+ if (scope.kind === "root_issues") return scope.issueIds.map((id) => `root_issue:${id}`);
+ return ["company_all"];
+}
+
+async function countPaperclipProfileOverlaps(ctx: PluginContext, input: {
+ companyId: string;
+ wikiId: string;
+ space: WikiSpace;
+ profile: PaperclipIngestionProfileV1;
+}): Promise<number> {
+ if (!input.profile.enabled || input.profile.sourceScopes.length === 0) return 0;
+ const own = new Set(input.profile.sourceScopes.flatMap(scopeIdentity));
+ if (own.size === 0) return 0;
+ const { spaces } = await listSpaces(ctx, { companyId: input.companyId, wikiId: input.wikiId });
+ let overlaps = 0;
+ for (const space of spaces) {
+ if (space.id === input.space.id) continue;
+ const profile = await profileForSpace(ctx, input.companyId, space);
+ if (!profile.enabled) continue;
+ for (const key of profile.sourceScopes.flatMap(scopeIdentity)) {
+ if (own.has(key)) overlaps += 1;
+ }
+ }
+ return overlaps;
+}
+
+async function validatePaperclipIngestionProfile(ctx: PluginContext, input: {
+ companyId: string;
+ space: WikiSpace;
+ profile: PaperclipIngestionProfileV1;
+}) {
+ const policy = evaluatePaperclipProfilePolicy({
+ space: input.space,
+ profile: input.profile,
+ purpose: "profile_update",
+ requireEnabledProfile: input.profile.enabled && input.space.slug !== DEFAULT_SPACE_SLUG,
+ });
+ if (!policy.allowed) throw new Error(policy.message);
+ if (input.profile.enabled && input.profile.sourceScopes.length === 0) {
+ throw new Error("Paperclip ingestion profile must include at least one source scope before it can be enabled.");
+ }
+ if (input.profile.sourceScopes.length > MAX_PAPERCLIP_INGESTION_PROFILE_SOURCE_COUNT) {
+ throw new Error(`Paperclip ingestion profile sources exceed the hard cap of ${MAX_PAPERCLIP_INGESTION_PROFILE_SOURCE_COUNT}.`);
+ }
+ for (const scope of input.profile.sourceScopes) {
+ if (scope.kind === "company_all" && input.space.slug !== DEFAULT_SPACE_SLUG) {
+ throw new Error("Everything in the company is only available on the default wiki space.");
+ }
+ if (scope.kind === "selected_projects") {
+ if (scope.projectIds.length > MAX_PAPERCLIP_PROFILE_SELECTED_PROJECTS) {
+ throw new Error(`selected_projects exceeds the hard cap of ${MAX_PAPERCLIP_PROFILE_SELECTED_PROJECTS}.`);
+ }
+ for (const projectId of scope.projectIds) {
+ const project = await ctx.projects.get(projectId, input.companyId);
+ if (!project) throw new Error(`Project belongs to another company or does not exist: ${projectId}`);
+ }
+ }
+ if (scope.kind === "root_issues") {
+ if (scope.issueIds.length > MAX_PAPERCLIP_PROFILE_ROOT_ISSUES) {
+ throw new Error(`root_issues exceeds the hard cap of ${MAX_PAPERCLIP_PROFILE_ROOT_ISSUES}.`);
+ }
+ for (const issueId of scope.issueIds) {
+ const issue = await ctx.issues.get(issueId, input.companyId);
+ if (!issue) throw new Error(`Issue belongs to another company or does not exist: ${issueId}`);
+ }
+ }
+ }
+}
+
+export async function updatePaperclipIngestionProfile(ctx: PluginContext, input: {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ profile: unknown;
+}): Promise<PaperclipIngestionProfileRead> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const current = await profileForSpace(ctx, input.companyId, space);
+ const profile = normalizePaperclipIngestionProfile(input.profile, { space, legacySettings: space.slug === DEFAULT_SPACE_SLUG ? await getEventIngestionSettings(ctx, input.companyId) : null });
+ await validatePaperclipIngestionProfile(ctx, { companyId: input.companyId, space, profile });
+ await updateSpace(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceSlug: space.slug,
+ settings: { paperclipIngestion: profile },
+ });
+ if (space.slug === DEFAULT_SPACE_SLUG) {
+ await ctx.state.set(eventIngestionStateKey(input.companyId), {
+ enabled: profile.enabled,
+ wikiId,
+ maxCharacters: profile.cursor.maxCharactersPerSource,
+ sources: {
+ issues: profile.sourceKinds.issues,
+ comments: profile.sourceKinds.comments,
+ documents: profile.sourceKinds.documents,
+ },
+ });
+ }
+ await ctx.activity.log({
+ companyId: input.companyId,
+ message: `Updated Paperclip ingestion profile for ${space.displayName}`,
+ entityType: "llm_wiki_space",
+ entityId: space.id,
+ metadata: {
+ type: "plugin.llm_wiki.paperclip_ingestion_profile_updated",
+ wikiId,
+ spaceSlug: space.slug,
+ beforeEnabled: current.enabled,
+ afterEnabled: profile.enabled,
+ sourceScopeKinds: profile.sourceScopes.map((scope) => scope.kind),
+ sourceKinds: profile.sourceKinds,
+ cursor: profile.cursor,
+ },
+ });
+ return getPaperclipIngestionProfile(ctx, { companyId: input.companyId, wikiId, spaceSlug: space.slug });
+}
+
+export async function listPaperclipIngestionCandidates(ctx: PluginContext, input: PaperclipIngestionCandidatesInput): Promise<{
+ projects: Array<{ id: string; name: string; status: string; updatedAt: string | null }>;
+ rootIssues: Array<{ id: string; identifier: string | null; title: string; status: string; projectId: string | null }>;
+}> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ await requirePaperclipIngestionPolicy(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug }, "candidate_search");
+ const query = stringField(input.query)?.toLowerCase() ?? "";
+ const projects = (await ctx.projects.list({ companyId: input.companyId, limit: 200 }))
+ .filter((project) => !project.archivedAt)
+ .filter((project) => !query || project.name.toLowerCase().includes(query))
+ .slice(0, 50)
+ .map((project) => ({
+ id: project.id,
+ name: project.name,
+ status: project.status,
+ updatedAt: isoString(project.updatedAt),
+ }));
+ const issues = (await ctx.issues.list({
+ companyId: input.companyId,
+ includePluginOperations: false,
+ limit: 200,
+ }))
+ .filter((issue) => !issue.parentId)
+ .filter((issue) => !query || issue.title.toLowerCase().includes(query) || issue.identifier?.toLowerCase().includes(query))
+ .slice(0, 50)
+ .map((issue) => ({
+ id: issue.id,
+ identifier: issue.identifier ?? null,
+ title: issue.title,
+ status: issue.status,
+ projectId: issue.projectId ?? null,
+ }));
+ return { projects, rootIssues: issues };
+}
+
+export async function updateEventIngestionSettings(
+ ctx: PluginContext,
+ input: { companyId: string; settings: Partial<WikiEventIngestionSettings> & { sources?: Partial<Record<WikiEventIngestionSource, boolean>> } },
+): Promise<WikiEventIngestionSettings> {
+ await requirePaperclipIngestionPolicy(ctx, {
+ companyId: input.companyId,
+ wikiId: normalizeWikiId(input.settings.wikiId),
+ spaceSlug: DEFAULT_SPACE_SLUG,
+ }, "profile_update");
+ const sourceKeys = Object.keys(input.settings.sources ?? {});
+ if (sourceKeys.length > MAX_PAPERCLIP_INGESTION_PROFILE_SOURCE_COUNT) {
+ throw new Error(`Paperclip ingestion profile sources exceed the hard cap of ${MAX_PAPERCLIP_INGESTION_PROFILE_SOURCE_COUNT}.`);
+ }
+ assertRequestedCharacterLimit("maxCharacters", input.settings.maxCharacters, MAX_EVENT_SOURCE_CHARS);
+ const current = await getEventIngestionSettings(ctx, input.companyId);
+ const next = normalizeEventIngestionSettings({
+ ...current,
+ ...input.settings,
+ sources: {
+ ...current.sources,
+ ...(input.settings.sources ?? {}),
+ },
+ });
+ await ctx.state.set(eventIngestionStateKey(input.companyId), next);
+ const defaultSpace = await ensureDefaultSpace(ctx, { companyId: input.companyId, wikiId: next.wikiId });
+ const profile = normalizePaperclipIngestionProfile(
+ {
+ ...defaultPaperclipIngestionProfile({ space: defaultSpace, legacySettings: next }),
+ enabled: next.enabled,
+ sourceKinds: {
+ issues: next.sources.issues,
+ comments: next.sources.comments,
+ documents: next.sources.documents,
+ attachments: "off",
+ workProducts: "off",
+ },
+ cursor: {
+ ...defaultPaperclipIngestionProfile({ space: defaultSpace, legacySettings: next }).cursor,
+ maxCharactersPerSource: next.maxCharacters,
+ },
+ },
+ { space: defaultSpace, legacySettings: next },
+ );
+ await updateSpace(ctx, {
+ companyId: input.companyId,
+ wikiId: next.wikiId,
+ spaceSlug: DEFAULT_SPACE_SLUG,
+ settings: { paperclipIngestion: profile },
+ });
+ return next;
+}
+
+function assertWikiPath(path: string, options: { allowMetadata?: boolean } = {}): string {
+ const trimmed = path.trim().replace(/^\/+/, "");
+ if (
+ !trimmed ||
+ trimmed.includes("\\") ||
+ trimmed.split("/").some((segment) => segment === "" || segment === "." || segment === "..")
+ ) {
+ throw new Error(`Invalid wiki path: ${path}`);
+ }
+ if (
+ trimmed !== ".gitignore" &&
+ trimmed !== "WIKI.md" &&
+ trimmed !== "AGENTS.md" &&
+ trimmed !== "IDEA.md" &&
+ trimmed !== "index.md" &&
+ trimmed !== "log.md" &&
+ !trimmed.startsWith("raw/") &&
+ !trimmed.startsWith("wiki/") &&
+ !(options.allowMetadata && trimmed.startsWith(".paperclip/"))
+ ) {
+ throw new Error(`Wiki path must stay inside AGENTS.md, IDEA.md, raw/, or wiki/: ${path}`);
+ }
+ return trimmed;
+}
+
+function assertPagePath(path: string): string {
+ const normalized = assertWikiPath(path);
+ if (normalized !== "index.md" && normalized !== "log.md" && normalized !== "WIKI.md" && normalized !== "AGENTS.md" && normalized !== "IDEA.md" && !normalized.startsWith("wiki/")) {
+ throw new Error(`Wiki page writes must target AGENTS.md, IDEA.md, or wiki/: ${path}`);
+ }
+ if (!normalized.endsWith(".md")) {
+ throw new Error(`Wiki page path must be a markdown file: ${path}`);
+ }
+ return normalized;
+}
+
+function assertPageWriteAllowed(path: string, writer: WritePageInput["writer"] = "agent_tool"): void {
+ if (writer !== "board_ui" && PROTECTED_WIKI_CONTROL_FILES.has(path)) {
+ throw new Error(`Refusing to overwrite protected wiki control file ${path}; board-managed edits must use the wiki UI.`);
+ }
+}
+
+function assertRawPath(path: string): string {
+ const normalized = assertWikiPath(path);
+ if (!normalized.startsWith("raw/")) {
+ throw new Error(`Source path must stay inside raw/: ${path}`);
+ }
+ return normalized;
+}
+
+function tableName(namespace: string, table: string): string {
+ return `${namespace}.${table}`;
+}
+
+function spaceTable(ctx: PluginContext): string {
+ return tableName(ctx.db.namespace, "wiki_spaces");
+}
+
+function bindingTable(ctx: PluginContext): string {
+ return tableName(ctx.db.namespace, "wiki_resource_bindings");
+}
+
+function distillationCursorTable(ctx: PluginContext): string {
+ return tableName(ctx.db.namespace, "paperclip_distillation_cursors");
+}
+
+function distillationRunTable(ctx: PluginContext): string {
+ return tableName(ctx.db.namespace, "paperclip_distillation_runs");
+}
+
+function sourceSnapshotTable(ctx: PluginContext): string {
+ return tableName(ctx.db.namespace, "paperclip_source_snapshots");
+}
+
+function distillationWorkItemTable(ctx: PluginContext): string {
+ return tableName(ctx.db.namespace, "paperclip_distillation_work_items");
+}
+
+function pageBindingTable(ctx: PluginContext): string {
+ return tableName(ctx.db.namespace, "paperclip_page_bindings");
+}
+
+function parseBindingMetadata(value: unknown): Record<string, unknown> {
+ if (value && typeof value === "object" && !Array.isArray(value)) return value as Record<string, unknown>;
+ if (typeof value === "string") {
+ try {
+ const parsed = JSON.parse(value);
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : {};
+ } catch {
+ return {};
+ }
+ }
+ return {};
+}
+
+function parseJsonObject(value: unknown): Record<string, unknown> {
+ if (value && typeof value === "object" && !Array.isArray(value)) return value as Record<string, unknown>;
+ if (typeof value === "string") {
+ try {
+ const parsed = JSON.parse(value);
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed as Record<string, unknown> : {};
+ } catch {
+ return {};
+ }
+ }
+ return {};
+}
+
+type WikiSpaceRow = {
+ id: string;
+ company_id: string;
+ wiki_id: string;
+ slug: string;
+ display_name: string;
+ space_type: string;
+ folder_mode: string;
+ root_folder_key: string;
+ path_prefix: string | null;
+ configured_root_path: string | null;
+ access_scope: string;
+ owner_user_id: string | null;
+ owner_agent_id: string | null;
+ team_key: string | null;
+ settings: unknown;
+ status: string;
+ created_at: string | null;
+ updated_at: string | null;
+};
+
+function wikiSpaceFromRow(row: WikiSpaceRow): WikiSpace {
+ return {
+ id: row.id,
+ companyId: row.company_id,
+ wikiId: row.wiki_id,
+ slug: row.slug,
+ displayName: row.display_name,
+ spaceType: row.space_type,
+ folderMode: row.folder_mode,
+ rootFolderKey: row.root_folder_key,
+ pathPrefix: row.path_prefix,
+ configuredRootPath: row.configured_root_path,
+ accessScope: row.access_scope,
+ ownerUserId: row.owner_user_id,
+ ownerAgentId: row.owner_agent_id,
+ teamKey: row.team_key,
+ settings: parseJsonObject(row.settings),
+ status: row.status,
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ };
+}
+
+function fallbackDefaultSpace(input: { companyId: string; wikiId: string }): WikiSpace {
+ return {
+ id: stableSpaceId({ companyId: input.companyId, wikiId: input.wikiId, slug: DEFAULT_SPACE_SLUG }),
+ companyId: input.companyId,
+ wikiId: input.wikiId,
+ slug: DEFAULT_SPACE_SLUG,
+ displayName: DEFAULT_SPACE_SLUG,
+ spaceType: "local_folder",
+ folderMode: "managed_subfolder",
+ rootFolderKey: WIKI_ROOT_FOLDER_KEY,
+ pathPrefix: null,
+ configuredRootPath: null,
+ accessScope: "shared",
+ ownerUserId: null,
+ ownerAgentId: null,
+ teamKey: null,
+ settings: {},
+ status: "active",
+ createdAt: null,
+ updatedAt: null,
+ };
+}
+
+export async function ensureDefaultSpace(ctx: PluginContext, input: { companyId: string; wikiId?: string | null }): Promise<WikiSpace> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const id = stableSpaceId({ companyId: input.companyId, wikiId, slug: DEFAULT_SPACE_SLUG });
+ await ctx.db.execute(
+ `INSERT INTO ${spaceTable(ctx)} AS wiki_spaces
+ (id, company_id, wiki_id, slug, display_name, space_type, folder_mode, root_folder_key, path_prefix, access_scope, status, settings)
+ VALUES ($1, $2, $3, 'default', 'default', 'local_folder', 'managed_subfolder', $4, NULL, 'shared', 'active', '{}'::jsonb)
+ ON CONFLICT (company_id, wiki_id, slug)
+ DO UPDATE SET updated_at = wiki_spaces.updated_at`,
+ [id, input.companyId, wikiId, WIKI_ROOT_FOLDER_KEY],
+ );
+ const rows = await ctx.db.query<WikiSpaceRow>(
+ `SELECT id, company_id, wiki_id, slug, display_name, space_type, folder_mode, root_folder_key,
+ path_prefix, configured_root_path, access_scope, owner_user_id, owner_agent_id, team_key,
+ settings, status, created_at::text AS created_at, updated_at::text AS updated_at
+ FROM ${spaceTable(ctx)}
+ WHERE company_id = $1 AND wiki_id = $2 AND slug = 'default'
+ LIMIT 1`,
+ [input.companyId, wikiId],
+ );
+ return rows[0] ? wikiSpaceFromRow(rows[0]) : fallbackDefaultSpace({ companyId: input.companyId, wikiId });
+}
+
+export async function resolveSpace(ctx: PluginContext, input: SpaceInput): Promise<WikiSpace> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const slug = normalizeSpaceSlug(input.spaceSlug);
+ if (slug === DEFAULT_SPACE_SLUG) {
+ return ensureDefaultSpace(ctx, { companyId: input.companyId, wikiId });
+ }
+ const rows = await ctx.db.query<WikiSpaceRow>(
+ `SELECT id, company_id, wiki_id, slug, display_name, space_type, folder_mode, root_folder_key,
+ path_prefix, configured_root_path, access_scope, owner_user_id, owner_agent_id, team_key,
+ settings, status, created_at::text AS created_at, updated_at::text AS updated_at
+ FROM ${spaceTable(ctx)}
+ WHERE company_id = $1 AND wiki_id = $2 AND slug = $3 AND status <> 'archived'
+ LIMIT 1`,
+ [input.companyId, wikiId, slug],
+ );
+ if (!rows[0]) throw new Error(`LLM Wiki space not found: ${slug}`);
+ return wikiSpaceFromRow(rows[0]);
+}
+
+async function resolveSpaceAnyStatus(ctx: PluginContext, input: SpaceInput): Promise<WikiSpace> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const slug = normalizeSpaceSlug(input.spaceSlug);
+ if (slug === DEFAULT_SPACE_SLUG) {
+ return ensureDefaultSpace(ctx, { companyId: input.companyId, wikiId });
+ }
+ const rows = await ctx.db.query<WikiSpaceRow>(
+ `SELECT id, company_id, wiki_id, slug, display_name, space_type, folder_mode, root_folder_key,
+ path_prefix, configured_root_path, access_scope, owner_user_id, owner_agent_id, team_key,
+ settings, status, created_at::text AS created_at, updated_at::text AS updated_at
+ FROM ${spaceTable(ctx)}
+ WHERE company_id = $1 AND wiki_id = $2 AND slug = $3
+ LIMIT 1`,
+ [input.companyId, wikiId, slug],
+ );
+ if (!rows[0]) throw new Error(`LLM Wiki space not found: ${slug}`);
+ return wikiSpaceFromRow(rows[0]);
+}
+
+export async function listSpaces(ctx: PluginContext, input: { companyId: string; wikiId?: string | null }): Promise<{ spaces: WikiSpace[] }> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ await ensureDefaultSpace(ctx, { companyId: input.companyId, wikiId });
+ const rows = await ctx.db.query<WikiSpaceRow>(
+ `SELECT id, company_id, wiki_id, slug, display_name, space_type, folder_mode, root_folder_key,
+ path_prefix, configured_root_path, access_scope, owner_user_id, owner_agent_id, team_key,
+ settings, status, created_at::text AS created_at, updated_at::text AS updated_at
+ FROM ${spaceTable(ctx)}
+ WHERE company_id = $1 AND wiki_id = $2 AND status <> 'archived'
+ ORDER BY CASE WHEN slug = 'default' THEN 0 ELSE 1 END, display_name, slug`,
+ [input.companyId, wikiId],
+ );
+ const spaces = rows.length > 0 ? rows.map(wikiSpaceFromRow) : [fallbackDefaultSpace({ companyId: input.companyId, wikiId })];
+ return { spaces };
+}
+
+export async function createSpace(ctx: PluginContext, input: CreateSpaceInput): Promise<{ status: "created"; space: WikiSpace }> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const displayName = stringField(input.displayName) ?? stringField(input.slug) ?? "New space";
+ const slug = normalizeSpaceSlug(input.slug ?? displayName);
+ if (slug === DEFAULT_SPACE_SLUG) {
+ return { status: "created", space: await ensureDefaultSpace(ctx, { companyId: input.companyId, wikiId }) };
+ }
+ const folderMode = input.folderMode ?? "managed_subfolder";
+ if (folderMode !== "managed_subfolder") {
+ throw new Error("Only managed_subfolder spaces are supported until dynamic local folder bindings are available.");
+ }
+ const accessScope = input.accessScope ?? "shared";
+ const id = randomUUID();
+ const pathPrefix = `spaces/${slug}`;
+ await ctx.db.execute(
+ `INSERT INTO ${spaceTable(ctx)}
+ (id, company_id, wiki_id, slug, display_name, space_type, folder_mode, root_folder_key, path_prefix, access_scope, settings, status)
+ VALUES ($1, $2, $3, $4, $5, 'local_folder', $6, $7, $8, $9, $10::jsonb, 'active')`,
+ [
+ id,
+ input.companyId,
+ wikiId,
+ slug,
+ displayName,
+ folderMode,
+ WIKI_ROOT_FOLDER_KEY,
+ pathPrefix,
+ accessScope,
+ jsonParam(input.settings ?? {}),
+ ],
+ );
+ const space: WikiSpace = {
+ id,
+ companyId: input.companyId,
+ wikiId,
+ slug,
+ displayName,
+ spaceType: "local_folder",
+ folderMode,
+ rootFolderKey: WIKI_ROOT_FOLDER_KEY,
+ pathPrefix,
+ configuredRootPath: null,
+ accessScope,
+ ownerUserId: null,
+ ownerAgentId: null,
+ teamKey: null,
+ settings: input.settings ?? {},
+ status: "active",
+ createdAt: null,
+ updatedAt: null,
+ };
+ await bootstrapSpaceFiles(ctx, input.companyId, space);
+ await upsertWikiInstance(ctx, { companyId: input.companyId, wikiId });
+ return { status: "created", space };
+}
+
+export async function updateSpace(ctx: PluginContext, input: UpdateSpaceInput): Promise<{ status: "ok"; space: WikiSpace }> {
+ const nextStatus = input.status ?? null;
+ if (nextStatus !== null && nextStatus !== "active" && nextStatus !== "archived") {
+ throw new Error("LLM Wiki space status must be active or archived.");
+ }
+ const space = nextStatus === "active" ? await resolveSpaceAnyStatus(ctx, input) : await resolveSpace(ctx, input);
+ const nextDisplayName = stringField(input.displayName);
+ if (space.slug === DEFAULT_SPACE_SLUG && nextStatus === "archived") {
+ throw new Error("The default LLM Wiki space cannot be archived.");
+ }
+ await ctx.db.execute(
+ `UPDATE ${spaceTable(ctx)}
+ SET display_name = COALESCE($4, display_name),
+ settings = CASE WHEN $5::jsonb IS NULL THEN settings ELSE settings || $5::jsonb END,
+ status = COALESCE($6, status),
+ updated_at = now()
+ WHERE company_id = $1 AND wiki_id = $2 AND slug = $3`,
+ [
+ input.companyId,
+ space.wikiId,
+ space.slug,
+ nextDisplayName,
+ input.settings ? jsonParam(input.settings) : null,
+ nextStatus ?? null,
+ ],
+ );
+ if (nextStatus === "archived") {
+ return {
+ status: "ok",
+ space: {
+ ...space,
+ displayName: nextDisplayName ?? space.displayName,
+ settings: input.settings ? { ...space.settings, ...input.settings } : space.settings,
+ status: "archived",
+ },
+ };
+ }
+ return { status: "ok", space: await resolveSpace(ctx, { companyId: input.companyId, wikiId: space.wikiId, spaceSlug: space.slug }) };
+}
+
+export async function archiveSpace(ctx: PluginContext, input: SpaceInput): Promise<{ status: "archived"; space: WikiSpace }> {
+ const space = await resolveSpace(ctx, input);
+ if (space.slug === DEFAULT_SPACE_SLUG) throw new Error("The default LLM Wiki space cannot be archived.");
+ await ctx.db.execute(
+ `UPDATE ${spaceTable(ctx)}
+ SET status = 'archived', updated_at = now()
+ WHERE company_id = $1 AND wiki_id = $2 AND slug = $3`,
+ [input.companyId, space.wikiId, space.slug],
+ );
+ return { status: "archived", space: { ...space, status: "archived" } };
+}
+
+export function spaceRelativePath(space: Pick<WikiSpace, "pathPrefix">, path: string): string {
+ const normalized = path.replace(/^\/+/, "");
+ return space.pathPrefix ? `${space.pathPrefix}/${normalized}` : normalized;
+}
+
+function logicalPathFromSpacePath(space: Pick<WikiSpace, "pathPrefix">, path: string): string {
+ if (!space.pathPrefix) return path;
+ const prefix = `${space.pathPrefix}/`;
+ return path.startsWith(prefix) ? path.slice(prefix.length) : path;
+}
+
+export async function spaceFolderStatus(ctx: PluginContext, input: SpaceInput): Promise<WikiSpaceWithFolderStatus> {
+ const space = await resolveSpace(ctx, input);
+ const folder = await ctx.localFolders.status(input.companyId, WIKI_ROOT_FOLDER_KEY);
+ return {
+ ...space,
+ relativeRoot: space.pathPrefix ?? ".",
+ folder,
+ };
+}
+
+async function getResourceBinding(
+ ctx: PluginContext,
+ input: { companyId: string; wikiId: string; resourceKind: WikiResourceKind; resourceKey: string },
+): Promise<WikiResourceBinding | null> {
+ const rows = await ctx.db.query<{ resolved_id: string | null; metadata: unknown }>(
+ `SELECT resolved_id, metadata
+ FROM ${bindingTable(ctx)}
+ WHERE company_id = $1
+ AND wiki_id = $2
+ AND resource_kind = $3
+ AND resource_key = $4
+ LIMIT 1`,
+ [input.companyId, input.wikiId, input.resourceKind, input.resourceKey],
+ );
+ const row = rows[0];
+ return row ? { resolvedId: row.resolved_id, metadata: parseBindingMetadata(row.metadata) } : null;
+}
+
+async function upsertResourceBinding(
+ ctx: PluginContext,
+ input: { companyId: string; wikiId: string; resourceKind: WikiResourceKind; resourceKey: string; resolvedId: string; metadata?: Record<string, unknown> },
+) {
+ await ctx.db.execute(
+ `INSERT INTO ${bindingTable(ctx)} AS wiki_resource_bindings
+ (id, company_id, wiki_id, resource_kind, resource_key, resolved_id, metadata)
+ VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb)
+ ON CONFLICT (company_id, wiki_id, resource_kind, resource_key)
+ DO UPDATE SET resolved_id = EXCLUDED.resolved_id,
+ metadata = EXCLUDED.metadata,
+ updated_at = now()`,
+ [
+ randomUUID(),
+ input.companyId,
+ input.wikiId,
+ input.resourceKind,
+ input.resourceKey,
+ input.resolvedId,
+ jsonParam(input.metadata ?? {}),
+ ],
+ );
+}
+
+function agentDetails(agent: Agent | null): WikiAgentResource["details"] {
+ return agent
+ ? { name: agent.name, status: agent.status, adapterType: agent.adapterType ?? null, icon: agent.icon ?? null, urlKey: agent.urlKey ?? null }
+ : null;
+}
+
+function projectDetails(project: Project | null): WikiProjectResource["details"] {
+ return project ? { name: project.name, status: project.status, color: project.color ?? null } : null;
+}
+
+function skillDetails(skill: PluginManagedSkillResolution["skill"]): WikiSkillResource["details"] {
+ return skill
+ ? { name: skill.name, key: skill.key, description: skill.description ?? null }
+ : null;
+}
+
+function agentResource(input: {
+ status: WikiAgentResource["status"];
+ source: WikiAgentResource["source"];
+ agent: Agent | null;
+ defaultDrift?: WikiAgentResource["defaultDrift"];
+}): WikiAgentResource {
+ return {
+ status: input.status,
+ source: input.source,
+ agentId: input.agent?.id ?? null,
+ resourceKey: `${PLUGIN_ID}:agent:${WIKI_MAINTAINER_AGENT_KEY}`,
+ agent: input.agent,
+ details: agentDetails(input.agent),
+ defaultDrift: input.defaultDrift ?? null,
+ };
+}
+
+function projectResource(input: {
+ status: WikiProjectResource["status"];
+ source: WikiProjectResource["source"];
+ project: Project | null;
+}): WikiProjectResource {
+ return {
+ status: input.status,
+ source: input.source,
+ projectId: input.project?.id ?? null,
+ resourceKey: `${PLUGIN_ID}:project:${WIKI_PROJECT_KEY}`,
+ project: input.project,
+ details: projectDetails(input.project),
+ };
+}
+
+function skillResource(resolved: PluginManagedSkillResolution): WikiSkillResource {
+ return {
+ status: resolved.status,
+ skillId: resolved.skillId,
+ resourceKey: resolved.resourceKey,
+ skill: resolved.skill,
+ details: skillDetails(resolved.skill),
+ defaultDrift: resolved.defaultDrift ?? null,
+ };
+}
+
+async function resolveSelectedAgent(ctx: PluginContext, companyId: string, binding: WikiResourceBinding | null) {
+ if (!binding?.resolvedId) return null;
+ const agent = await ctx.agents.get(binding.resolvedId, companyId);
+ return agent && agent.status !== "terminated" ? agent : null;
+}
+
+async function resolveSelectedProject(ctx: PluginContext, companyId: string, binding: WikiResourceBinding | null) {
+ if (!binding?.resolvedId) return null;
+ return ctx.projects.get(binding.resolvedId, companyId);
+}
+
+function inferTitle(path: string, contents: string): string {
+ const heading = contents.match(/^#\s+(.+)$/m)?.[1]?.trim();
+ if (heading) return heading;
+ const filename = path.split("/").pop()?.replace(/\.md$/i, "") ?? path;
+ return filename.replace(/[-_]+/g, " ");
+}
+
+function inferPageType(path: string): string | null {
+ if (/^wiki\/projects\/[^/]+\/standup\.md$/.test(path)) return "project-standup";
+ const match = path.match(/^wiki\/([^/]+)\//);
+ return match?.[1] ?? (path === "index.md" || path === "wiki/index.md" ? "index" : path === "log.md" || path === "wiki/log.md" ? "log" : null);
+}
+
+function extractWikiLinks(contents: string): string[] {
+ const links = new Set<string>();
+ const markdownLinkPattern = /\[[^\]]+\]\(([^)]+)\)/g;
+ for (const match of contents.matchAll(markdownLinkPattern)) {
+ const target = match[1]?.split("#")[0]?.trim();
+ if (target && (target.startsWith("wiki/") || target === "index.md" || target === "log.md" || target === "AGENTS.md" || target === "IDEA.md")) {
+ links.add(target);
+ }
+ }
+ const wikiTokenPattern = /\bwiki\/[A-Za-z0-9._/-]+\.md\b/g;
+ for (const match of contents.matchAll(wikiTokenPattern)) {
+ links.add(match[0]);
+ }
+ return [...links].sort();
+}
+
+async function readCurrentWithHash(
+ ctx: PluginContext,
+ companyId: string,
+ path: string,
+ space: Pick<WikiSpace, "pathPrefix">,
+): Promise<{ contents: string | null; hash: string | null }> {
+ try {
+ const contents = await ctx.localFolders.readText(companyId, WIKI_ROOT_FOLDER_KEY, spaceRelativePath(space, path));
+ return { contents, hash: contentHash(contents) };
+ } catch {
+ return { contents: null, hash: null };
+ }
+}
+
+async function filterReadableRows<T>(
+ ctx: PluginContext,
+ companyId: string,
+ space: Pick<WikiSpace, "pathPrefix">,
+ rows: T[],
+ pathForRow: (row: T) => string,
+): Promise<T[]> {
+ const checks: Array<T | null> = await Promise.all(rows.map(async (row): Promise<T | null> => {
+ try {
+ await ctx.localFolders.readText(companyId, WIKI_ROOT_FOLDER_KEY, spaceRelativePath(space, pathForRow(row)));
+ return row;
+ } catch {
+ return null;
+ }
+ }));
+ return checks.filter((row): row is T => row != null);
+}
+
+async function listLocalFiles(ctx: PluginContext, input: { companyId: string; space: Pick<WikiSpace, "pathPrefix">; relativePath: "wiki" | "raw" }): Promise<PluginLocalFolderEntry[]> {
+ try {
+ const relativePath = spaceRelativePath(input.space, input.relativePath);
+ const listing = await ctx.localFolders.list(input.companyId, WIKI_ROOT_FOLDER_KEY, {
+ relativePath,
+ recursive: true,
+ maxEntries: LOCAL_BROWSE_FILE_LIMIT,
+ });
+ return listing.entries
+ .filter((entry) => entry.kind === "file")
+ .map((entry) => ({ ...entry, path: logicalPathFromSpacePath(input.space, entry.path) }));
+ } catch {
+ return [];
+ }
+}
+
+function mergeLocalPageRows(pages: WikiPageRow[], entries: PluginLocalFolderEntry[]): WikiPageRow[] {
+ const byPath = new Map(pages.map((page) => [page.path, page]));
+ for (const entry of entries) {
+ if (!entry.path.endsWith(".md") || byPath.has(entry.path)) continue;
+ byPath.set(entry.path, {
+ path: entry.path,
+ title: null,
+ pageType: inferPageType(entry.path),
+ backlinkCount: 0,
+ sourceCount: 0,
+ contentHash: null,
+ updatedAt: entry.modifiedAt ?? new Date(0).toISOString(),
+ });
+ }
+ return [...byPath.values()].sort((a, b) => a.path.localeCompare(b.path));
+}
+
+function mergeLocalSourceRows(sources: WikiSourceRow[], entries: PluginLocalFolderEntry[]): WikiSourceRow[] {
+ const byPath = new Map(sources.map((source) => [source.rawPath, source]));
+ for (const entry of entries) {
+ if (!entry.path.endsWith(".md") || byPath.has(entry.path)) continue;
+ byPath.set(entry.path, {
+ rawPath: entry.path,
+ title: null,
+ sourceType: "local_file",
+ url: null,
+ status: "present",
+ createdAt: entry.modifiedAt ?? new Date(0).toISOString(),
+ });
+ }
+ return [...byPath.values()].sort((a, b) => a.rawPath.localeCompare(b.rawPath));
+}
+
+function assertExpectedHash(expectedHash: string | null | undefined, currentHash: string | null, path: string): void {
+ if (expectedHash && currentHash && expectedHash !== currentHash) {
+ throw new Error(`Refusing to overwrite ${path}: expected hash ${expectedHash} but current hash is ${currentHash}`);
+ }
+}
+
+async function upsertWikiInstance(ctx: PluginContext, input: { companyId: string; wikiId: string; rootPath?: string | null }) {
+ await ctx.db.execute(
+ `INSERT INTO ${tableName(ctx.db.namespace, "wiki_instances")} AS wiki_instances
+ (id, company_id, wiki_id, root_folder_key, configured_root_path, schema_version, settings, managed_agent_key, managed_project_key)
+ VALUES ($1, $2, $3, $4, $5, 1, '{}'::jsonb, $6, $7)
+ ON CONFLICT (company_id, wiki_id)
+ DO UPDATE SET configured_root_path = COALESCE(EXCLUDED.configured_root_path, wiki_instances.configured_root_path),
+ managed_agent_key = EXCLUDED.managed_agent_key,
+ managed_project_key = EXCLUDED.managed_project_key,
+ updated_at = now()`,
+ [
+ randomUUID(),
+ input.companyId,
+ input.wikiId,
+ WIKI_ROOT_FOLDER_KEY,
+ input.rootPath ?? null,
+ WIKI_MAINTAINER_AGENT_KEY,
+ WIKI_PROJECT_KEY,
+ ],
+ );
+}
+
+async function upsertPageMetadata(ctx: PluginContext, input: {
+ companyId: string;
+ wikiId: string;
+ spaceId: string;
+ path: string;
+ contents: string;
+ summary?: string | null;
+ sourceRefs?: unknown;
+ operationId?: string | null;
+}) {
+ const pageId = randomUUID();
+ const revisionId = randomUUID();
+ const hash = contentHash(input.contents);
+ const title = inferTitle(input.path, input.contents);
+ const pageType = inferPageType(input.path);
+ const backlinks = extractWikiLinks(input.contents);
+ const sourceRefs = Array.isArray(input.sourceRefs) ? input.sourceRefs : [];
+
+ await ctx.db.execute(
+ `INSERT INTO ${tableName(ctx.db.namespace, "wiki_pages")}
+ (id, company_id, wiki_id, space_id, path, title, page_type, frontmatter, source_refs, backlinks, content_hash, current_revision_id)
+ VALUES ($1, $2, $3, $11, $4, $5, $6, '{}'::jsonb, $7::jsonb, $8::jsonb, $9, $10)
+ ON CONFLICT (company_id, wiki_id, space_id, path)
+ DO UPDATE SET title = EXCLUDED.title,
+ page_type = EXCLUDED.page_type,
+ source_refs = EXCLUDED.source_refs,
+ backlinks = EXCLUDED.backlinks,
+ content_hash = EXCLUDED.content_hash,
+ current_revision_id = EXCLUDED.current_revision_id,
+ updated_at = now()`,
+ [
+ pageId,
+ input.companyId,
+ input.wikiId,
+ input.path,
+ title,
+ pageType,
+ jsonParam(sourceRefs),
+ jsonParam(backlinks),
+ hash,
+ revisionId,
+ input.spaceId,
+ ],
+ );
+
+ await ctx.db.execute(
+ `INSERT INTO ${tableName(ctx.db.namespace, "wiki_page_revisions")}
+ (id, company_id, wiki_id, space_id, page_id, operation_id, path, content_hash, summary, metadata)
+ VALUES ($1, $2, $3, $8, (SELECT id FROM ${tableName(ctx.db.namespace, "wiki_pages")} WHERE company_id = $2 AND wiki_id = $3 AND space_id = $8 AND path = $4), $7, $4, $5, $6, '{}'::jsonb)`,
+ [revisionId, input.companyId, input.wikiId, input.path, hash, input.summary ?? null, input.operationId ?? null, input.spaceId],
+ );
+
+ return { title, pageType, backlinks, hash, revisionId };
+}
+
+export async function writeWikiPage(ctx: PluginContext, input: WritePageInput) {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const path = assertPagePath(input.path);
+ assertPageWriteAllowed(path, input.writer);
+ const current = await readCurrentWithHash(ctx, input.companyId, path, space);
+ assertExpectedHash(input.expectedHash, current.hash, path);
+ await ctx.localFolders.writeTextAtomic(input.companyId, WIKI_ROOT_FOLDER_KEY, spaceRelativePath(space, path), input.contents);
+ const metadata = await upsertPageMetadata(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceId: space.id,
+ path,
+ contents: input.contents,
+ summary: input.summary,
+ sourceRefs: input.sourceRefs,
+ operationId: input.operationId,
+ });
+ await upsertWikiInstance(ctx, { companyId: input.companyId, wikiId });
+ return { status: "ok", wikiId, spaceSlug: space.slug, path, previousHash: current.hash, ...metadata };
+}
+
+export async function captureWikiSource(ctx: PluginContext, input: CaptureSourceInput) {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const title = stringField(input.title) ?? "Untitled source";
+ await assertSourceWithinConfiguredLimit(ctx, input.contents);
+ const hash = contentHash(input.contents);
+ const rawPath = input.rawPath
+ ? assertRawPath(input.rawPath)
+ : assertRawPath(`raw/${new Date().toISOString().slice(0, 10)}-${slugify(title)}-${hash.slice(0, 8)}.md`);
+ await ctx.localFolders.writeTextAtomic(input.companyId, WIKI_ROOT_FOLDER_KEY, spaceRelativePath(space, rawPath), input.contents);
+ await upsertWikiInstance(ctx, { companyId: input.companyId, wikiId });
+ const sourceId = randomUUID();
+ await ctx.db.execute(
+ `INSERT INTO ${tableName(ctx.db.namespace, "wiki_sources")}
+ (id, company_id, wiki_id, space_id, source_type, title, url, raw_path, content_hash, status, metadata)
+ VALUES ($1, $2, $3, $10, $4, $5, $6, $7, $8, 'captured', $9::jsonb)`,
+ [
+ sourceId,
+ input.companyId,
+ wikiId,
+ stringField(input.sourceType) ?? "text",
+ title,
+ stringField(input.url),
+ rawPath,
+ hash,
+ jsonParam(input.metadata ?? {}),
+ space.id,
+ ],
+ );
+ return { status: "ok", sourceId, wikiId, spaceSlug: space.slug, rawPath, hash, title };
+}
+
+export async function getOverview(ctx: PluginContext, companyId: string): Promise<WikiOverview> {
+ const [defaultSpace, folder, managedAgent, managedProject, managedSkills] = await Promise.all([
+ ensureDefaultSpace(ctx, { companyId, wikiId: DEFAULT_WIKI_ID }),
+ ctx.localFolders.status(companyId, WIKI_ROOT_FOLDER_KEY),
+ resolveWikiAgentResource(ctx, companyId),
+ resolveWikiProjectResource(ctx, companyId),
+ resolveWikiSkillResources(ctx, companyId),
+ ]);
+ const operationRows = await ctx.db.query<{ count: string }>(
+ `SELECT count(*)::text AS count FROM ${tableName(ctx.db.namespace, "wiki_operations")} WHERE company_id = $1`,
+ [companyId],
+ );
+ const operationCount = Number(operationRows[0]?.count ?? 0);
+ const eventIngestion = await getEventIngestionSettings(ctx, companyId);
+ return {
+ status: "ok",
+ checkedAt: new Date().toISOString(),
+ wikiId: DEFAULT_WIKI_ID,
+ defaultSpace,
+ folder,
+ managedAgent,
+ managedProject,
+ managedSkills,
+ operationCount,
+ eventIngestion,
+ capabilities: ctx.manifest.capabilities,
+ prompts: {
+ query: QUERY_PROMPT,
+ lint: LINT_PROMPT,
+ },
+ };
+}
+
+export async function resolveWikiAgentResource(
+ ctx: PluginContext,
+ companyId: string,
+ options: { reconcileMissing?: boolean } = {},
+): Promise<WikiAgentResource> {
+ const wikiId = DEFAULT_WIKI_ID;
+ const binding = await getResourceBinding(ctx, {
+ companyId,
+ wikiId,
+ resourceKind: "agent",
+ resourceKey: WIKI_MAINTAINER_AGENT_KEY,
+ });
+ const selectedAgent = await resolveSelectedAgent(ctx, companyId, binding);
+ if (selectedAgent) {
+ const source = binding?.metadata.source === "managed-default" ? "managed" : "selected";
+ const managedResolution = source === "managed"
+ ? await ctx.agents.managed.get(WIKI_MAINTAINER_AGENT_KEY, companyId)
+ : null;
+ return agentResource({
+ status: "resolved",
+ source,
+ agent: selectedAgent,
+ defaultDrift: managedResolution?.defaultDrift ?? null,
+ });
+ }
+ if (binding?.resolvedId && !options.reconcileMissing) {
+ return agentResource({ status: "missing", source: "selected", agent: null });
+ }
+
+ const resolved = options.reconcileMissing
+ ? await ctx.agents.managed.reconcile(WIKI_MAINTAINER_AGENT_KEY, companyId)
+ : await ctx.agents.managed.get(WIKI_MAINTAINER_AGENT_KEY, companyId);
+ if (resolved.agentId && options.reconcileMissing) {
+ await upsertResourceBinding(ctx, {
+ companyId,
+ wikiId,
+ resourceKind: "agent",
+ resourceKey: WIKI_MAINTAINER_AGENT_KEY,
+ resolvedId: resolved.agentId,
+ metadata: { source: "managed-default", updatedBy: "resolve" },
+ });
+ }
+ return agentResource({ status: resolved.status, source: "managed", agent: resolved.agent, defaultDrift: resolved.defaultDrift ?? null });
+}
+
+export async function resolveWikiProjectResource(
+ ctx: PluginContext,
+ companyId: string,
+ options: { reconcileMissing?: boolean } = {},
+): Promise<WikiProjectResource> {
+ const wikiId = DEFAULT_WIKI_ID;
+ const binding = await getResourceBinding(ctx, {
+ companyId,
+ wikiId,
+ resourceKind: "project",
+ resourceKey: WIKI_PROJECT_KEY,
+ });
+ const selectedProject = await resolveSelectedProject(ctx, companyId, binding);
+ if (selectedProject) {
+ return projectResource({
+ status: "resolved",
+ source: binding?.metadata.source === "managed-default" ? "managed" : "selected",
+ project: selectedProject,
+ });
+ }
+ if (binding?.resolvedId && !options.reconcileMissing) {
+ return projectResource({ status: "missing", source: "selected", project: null });
+ }
+
+ const resolved = options.reconcileMissing
+ ? await ctx.projects.managed.reconcile(WIKI_PROJECT_KEY, companyId)
+ : await ctx.projects.managed.get(WIKI_PROJECT_KEY, companyId);
+ if (resolved.projectId && options.reconcileMissing) {
+ await upsertResourceBinding(ctx, {
+ companyId,
+ wikiId,
+ resourceKind: "project",
+ resourceKey: WIKI_PROJECT_KEY,
+ resolvedId: resolved.projectId,
+ metadata: { source: "managed-default", updatedBy: "resolve" },
+ });
+ }
+ return projectResource({ status: resolved.status, source: "managed", project: resolved.project });
+}
+
+export async function resolveWikiSkillResources(
+ ctx: PluginContext,
+ companyId: string,
+ options: { reconcileMissing?: boolean } = {},
+): Promise<WikiSkillResource[]> {
+ return Promise.all(
+ WIKI_MANAGED_SKILL_KEYS.map(async (skillKey) => {
+ const resolved = options.reconcileMissing
+ ? await ctx.skills.managed.reconcile(skillKey, companyId)
+ : await ctx.skills.managed.get(skillKey, companyId);
+ return skillResource(resolved);
+ }),
+ );
+}
+
+export async function reconcileWikiAgentResource(ctx: PluginContext, companyId: string): Promise<WikiAgentResource> {
+ const resolved = await ctx.agents.managed.reconcile(WIKI_MAINTAINER_AGENT_KEY, companyId);
+ if (resolved.agentId) {
+ await upsertResourceBinding(ctx, {
+ companyId,
+ wikiId: DEFAULT_WIKI_ID,
+ resourceKind: "agent",
+ resourceKey: WIKI_MAINTAINER_AGENT_KEY,
+ resolvedId: resolved.agentId,
+ metadata: { source: "managed-default", updatedBy: "reconcile" },
+ });
+ }
+ return agentResource({ status: resolved.status, source: "managed", agent: resolved.agent, defaultDrift: resolved.defaultDrift ?? null });
+}
+
+export async function resetWikiAgentResource(ctx: PluginContext, companyId: string): Promise<WikiAgentResource> {
+ const resolved = await ctx.agents.managed.reset(WIKI_MAINTAINER_AGENT_KEY, companyId);
+ if (resolved.agentId) {
+ await upsertResourceBinding(ctx, {
+ companyId,
+ wikiId: DEFAULT_WIKI_ID,
+ resourceKind: "agent",
+ resourceKey: WIKI_MAINTAINER_AGENT_KEY,
+ resolvedId: resolved.agentId,
+ metadata: { source: "managed-default", updatedBy: "reset" },
+ });
+ }
+ return agentResource({ status: resolved.status, source: "managed", agent: resolved.agent, defaultDrift: resolved.defaultDrift ?? null });
+}
+
+export async function selectWikiAgentResource(ctx: PluginContext, input: { companyId: string; agentId: string }): Promise<WikiAgentResource> {
+ const agent = await ctx.agents.get(input.agentId, input.companyId);
+ if (!agent || agent.status === "terminated") {
+ throw new Error("Selected Wiki Maintainer agent was not found or is terminated.");
+ }
+ await upsertResourceBinding(ctx, {
+ companyId: input.companyId,
+ wikiId: DEFAULT_WIKI_ID,
+ resourceKind: "agent",
+ resourceKey: WIKI_MAINTAINER_AGENT_KEY,
+ resolvedId: agent.id,
+ metadata: { source: "selected-existing", updatedBy: "settings" },
+ });
+ return agentResource({ status: "resolved", source: "selected", agent });
+}
+
+export async function reconcileWikiProjectResource(ctx: PluginContext, companyId: string): Promise<WikiProjectResource> {
+ const resolved = await ctx.projects.managed.reconcile(WIKI_PROJECT_KEY, companyId);
+ if (resolved.projectId) {
+ await upsertResourceBinding(ctx, {
+ companyId,
+ wikiId: DEFAULT_WIKI_ID,
+ resourceKind: "project",
+ resourceKey: WIKI_PROJECT_KEY,
+ resolvedId: resolved.projectId,
+ metadata: { source: "managed-default", updatedBy: "reconcile" },
+ });
+ }
+ return projectResource({ status: resolved.status, source: "managed", project: resolved.project });
+}
+
+export async function resetWikiProjectResource(ctx: PluginContext, companyId: string): Promise<WikiProjectResource> {
+ const resolved = await ctx.projects.managed.reset(WIKI_PROJECT_KEY, companyId);
+ if (resolved.projectId) {
+ await upsertResourceBinding(ctx, {
+ companyId,
+ wikiId: DEFAULT_WIKI_ID,
+ resourceKind: "project",
+ resourceKey: WIKI_PROJECT_KEY,
+ resolvedId: resolved.projectId,
+ metadata: { source: "managed-default", updatedBy: "reset" },
+ });
+ }
+ return projectResource({ status: resolved.status, source: "managed", project: resolved.project });
+}
+
+export async function reconcileWikiSkillResources(ctx: PluginContext, companyId: string): Promise<WikiSkillResource[]> {
+ return resolveWikiSkillResources(ctx, companyId, { reconcileMissing: true });
+}
+
+export async function resetWikiSkillResources(ctx: PluginContext, companyId: string): Promise<WikiSkillResource[]> {
+ return Promise.all(
+ WIKI_MANAGED_SKILL_KEYS.map(async (skillKey) => {
+ return skillResource(await ctx.skills.managed.reset(skillKey, companyId));
+ }),
+ );
+}
+
+export async function reconcileWikiRoutineResources(
+ ctx: PluginContext,
+ companyId: string,
+): Promise<{
+ managedAgent: WikiAgentResource;
+ managedProject: WikiProjectResource;
+ managedRoutines: PluginManagedRoutineResolution[];
+}> {
+ const [managedAgent, managedProject] = await Promise.all([
+ reconcileWikiAgentResource(ctx, companyId),
+ reconcileWikiProjectResource(ctx, companyId),
+ ]);
+
+ const managedRoutines = await Promise.all(
+ WIKI_MAINTENANCE_ROUTINE_KEYS.map((routineKey) =>
+ ctx.routines.managed.reconcile(routineKey, companyId, {
+ assigneeAgentId: managedAgent.agentId,
+ projectId: managedProject.projectId,
+ })),
+ );
+
+ return { managedAgent, managedProject, managedRoutines };
+}
+
+export async function selectWikiProjectResource(ctx: PluginContext, input: { companyId: string; projectId: string }): Promise<WikiProjectResource> {
+ const project = await ctx.projects.get(input.projectId, input.companyId);
+ if (!project) {
+ throw new Error("Selected LLM Wiki project was not found.");
+ }
+ await upsertResourceBinding(ctx, {
+ companyId: input.companyId,
+ wikiId: DEFAULT_WIKI_ID,
+ resourceKind: "project",
+ resourceKey: WIKI_PROJECT_KEY,
+ resolvedId: project.id,
+ metadata: { source: "selected-existing", updatedBy: "settings" },
+ });
+ return projectResource({ status: "resolved", source: "selected", project });
+}
+
+export async function listWikiAgentOptions(ctx: PluginContext, companyId: string): Promise<WikiResourceOption[]> {
+ const agents = await ctx.agents.list({ companyId, limit: 200 });
+ return agents
+ .filter((agent) => agent.status !== "terminated")
+ .map((agent) => ({
+ id: agent.id,
+ name: agent.name,
+ status: agent.status,
+ adapterType: agent.adapterType ?? null,
+ icon: agent.icon ?? null,
+ urlKey: agent.urlKey ?? null,
+ }));
+}
+
+export async function listWikiProjectOptions(ctx: PluginContext, companyId: string): Promise<WikiResourceOption[]> {
+ const projects = await ctx.projects.list({ companyId, limit: 200 });
+ return projects.map((project) => ({ id: project.id, name: project.name, status: project.status, color: project.color ?? null }));
+}
+
+export async function bootstrapWikiRoot(ctx: PluginContext, input: BootstrapInput) {
+ const wikiId = DEFAULT_WIKI_ID;
+ const defaultSpace = await ensureDefaultSpace(ctx, { companyId: input.companyId, wikiId });
+ const configureFolder = (path: string) => ctx.localFolders.configure({
+ companyId: input.companyId,
+ folderKey: WIKI_ROOT_FOLDER_KEY,
+ path,
+ access: "readWrite",
+ requiredDirectories: [...REQUIRED_WIKI_DIRECTORIES],
+ requiredFiles: [...REQUIRED_WIKI_FILES],
+ });
+ const currentFolder = input.path
+ ? null
+ : await ctx.localFolders.status(input.companyId, WIKI_ROOT_FOLDER_KEY);
+ const folder = input.path
+ ? await configureFolder(input.path)
+ : currentFolder?.configured && currentFolder.path
+ ? await configureFolder(currentFolder.path)
+ : currentFolder ?? await ctx.localFolders.status(input.companyId, WIKI_ROOT_FOLDER_KEY);
+
+ const writtenFiles: string[] = [];
+ const preservedFiles: string[] = [];
+ for (const file of BOOTSTRAP_FILES) {
+ const path = assertWikiPath(file.path, { allowMetadata: true });
+ try {
+ await ctx.localFolders.readText(input.companyId, WIKI_ROOT_FOLDER_KEY, path);
+ preservedFiles.push(path);
+ continue;
+ } catch {
+ // Missing files are initialized below. Existing files are intentionally preserved.
+ }
+ await ctx.localFolders.writeTextAtomic(input.companyId, WIKI_ROOT_FOLDER_KEY, file.path, file.contents);
+ writtenFiles.push(path);
+ }
+
+ await upsertWikiInstance(ctx, { companyId: input.companyId, wikiId, rootPath: folder.path });
+ const managedSkills = await reconcileWikiSkillResources(ctx, input.companyId);
+ const [managedAgent, managedProject] = await Promise.all([
+ reconcileWikiAgentResource(ctx, input.companyId),
+ reconcileWikiProjectResource(ctx, input.companyId),
+ ]);
+ await ctx.state.set(
+ {
+ scopeKind: "company",
+ scopeId: input.companyId,
+ namespace: "llm-wiki",
+ stateKey: "last-bootstrap",
+ },
+ { at: new Date().toISOString(), path: folder.path },
+ );
+
+ return {
+ status: "ok",
+ folder,
+ wikiId,
+ space: defaultSpace,
+ managedAgent,
+ managedProject,
+ managedSkills,
+ writtenFiles,
+ preservedFiles,
+ };
+}
+
+export async function bootstrapSpace(ctx: PluginContext, input: SpaceInput) {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const { writtenFiles, preservedFiles } = await bootstrapSpaceFiles(ctx, input.companyId, space);
+ await upsertWikiInstance(ctx, { companyId: input.companyId, wikiId });
+ return {
+ status: "ok",
+ wikiId,
+ space,
+ writtenFiles,
+ preservedFiles,
+ };
+}
+
+async function bootstrapSpaceFiles(ctx: PluginContext, companyId: string, space: WikiSpace) {
+ const writtenFiles: string[] = [];
+ const preservedFiles: string[] = [];
+ for (const file of BOOTSTRAP_FILES) {
+ const path = assertWikiPath(file.path, { allowMetadata: true });
+ const physicalPath = spaceRelativePath(space, path);
+ try {
+ await ctx.localFolders.readText(companyId, WIKI_ROOT_FOLDER_KEY, physicalPath);
+ preservedFiles.push(path);
+ continue;
+ } catch {
+ // Missing files are initialized below. Existing files are intentionally preserved.
+ }
+ await ctx.localFolders.writeTextAtomic(companyId, WIKI_ROOT_FOLDER_KEY, physicalPath, file.contents);
+ writtenFiles.push(path);
+ }
+ return { writtenFiles, preservedFiles };
+}
+
+function operationSpaceRoot(space: WikiSpace): string {
+ return space.pathPrefix ? `${space.rootFolderKey}/${space.pathPrefix}` : `${space.rootFolderKey} root`;
+}
+
+function operationBillingContext(wikiId: string, space: WikiSpace): string {
+ return space.slug === DEFAULT_SPACE_SLUG
+ ? `plugin-llm-wiki:${wikiId} (space ${space.slug})`
+ : `plugin-llm-wiki:${wikiId}:${space.slug}`;
+}
+
+function operationBillingCode(wikiId: string, space: WikiSpace): string {
+ return space.slug === DEFAULT_SPACE_SLUG ? `plugin-llm-wiki:${wikiId}` : `plugin-llm-wiki:${wikiId}:${space.slug}`;
+}
+
+function operationIssueOriginId(input: { wikiId: string; space: WikiSpace; operationId: string }): string {
+ return input.space.slug === DEFAULT_SPACE_SLUG
+ ? `wiki:${input.wikiId}:operation:${input.operationId}`
+ : `wiki:${input.wikiId}:space:${input.space.slug}:operation:${input.operationId}`;
+}
+
+function operationTitleWithSpace(title: string, space: WikiSpace): string {
+ return `${title} [space: ${space.displayName} / ${space.slug}]`;
+}
+
+function operationPromptWithSpaceContext(input: OperationSpaceContext): string {
+ const paperclipDerived = input.operationType === "distill" || input.operationType === "backfill";
+ return [
+ `Plugin operation: ${input.operationType}`,
+ `Wiki ID: ${input.wikiId}`,
+ `Space: ${input.space.displayName} (${input.space.slug})`,
+ `Space root: ${operationSpaceRoot(input.space)}`,
+ `Billing context: ${operationBillingContext(input.wikiId, input.space)}`,
+ "",
+ "Space isolation requirement:",
+ `- Pass wikiId \`${input.wikiId}\` and spaceSlug \`${input.space.slug}\` on every LLM Wiki tool call.`,
+ "- Treat all paths in the prompt as relative to this space root.",
+ paperclipDerived
+ ? "- Paperclip-derived distill/backfill operations are default-space-only in Phase 1. Stop and comment if asked to write Paperclip-derived pages into a non-default space."
+ : "- Manual ingest, query, lint, index, and file-as-page operations follow the named destination space. Do not cross into another space unless the operation explicitly asks for a multi-space sweep.",
+ "",
+ input.prompt ?? "Created by the LLM Wiki plugin.",
+ ].join("\n");
+}
+
+function operationMetadata(input: OperationSpaceContext) {
+ return {
+ operationType: input.operationType,
+ operationId: input.operationId,
+ wikiId: input.wikiId,
+ spaceId: input.space.id,
+ spaceSlug: input.space.slug,
+ spaceName: input.space.displayName,
+ spaceRootFolderKey: input.space.rootFolderKey,
+ spacePathPrefix: input.space.pathPrefix,
+ spaceRoot: operationSpaceRoot(input.space),
+ };
+}
+
+export async function createOperationIssue(ctx: PluginContext, input: OperationInput) {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = input.operationType === "distill" || input.operationType === "backfill"
+ ? await requirePaperclipIngestionPolicy(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug }, "queue", { requireEnabledProfile: true })
+ : await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const managedAgent = await resolveWikiAgentResource(ctx, input.companyId, { reconcileMissing: true });
+ const managedProject = await resolveWikiProjectResource(ctx, input.companyId, { reconcileMissing: true });
+ const operationId = randomUUID();
+ const title = operationTitleWithSpace(input.title ?? `LLM Wiki ${input.operationType}`, space);
+ const originId = operationIssueOriginId({ wikiId, space, operationId });
+ const operationContext = { wikiId, space, operationType: input.operationType, operationId, prompt: input.prompt };
+ const assignableAgentId =
+ managedAgent.agent &&
+ managedAgent.agent.status !== "pending_approval" &&
+ managedAgent.agent.status !== "terminated"
+ ? managedAgent.agent.id
+ : undefined;
+ const issue = await ctx.issues.create({
+ companyId: input.companyId,
+ projectId: managedProject.projectId ?? undefined,
+ title,
+ description: operationPromptWithSpaceContext(operationContext),
+ status: "todo",
+ priority: input.operationType === "query" ? "medium" : "low",
+ assigneeAgentId: assignableAgentId,
+ assigneeAdapterOverrides: input.useCheapModelProfile ? { modelProfile: "cheap" } : null,
+ billingCode: operationBillingCode(wikiId, space),
+ surfaceVisibility: "plugin_operation",
+ originKind: `${OPERATION_ORIGIN_KIND}:${input.operationType}` as PluginIssueOriginKind,
+ originId,
+ });
+
+ await ctx.db.execute(
+ `INSERT INTO ${tableName(ctx.db.namespace, "wiki_operations")}
+ (id, company_id, wiki_id, space_id, operation_type, status, hidden_issue_id, project_id, run_ids, cost_cents, warnings, metadata)
+ VALUES ($1, $2, $3, $8, $4, $5, $6, $7, '[]'::jsonb, 0, '[]'::jsonb, $9::jsonb)`,
+ [
+ operationId,
+ input.companyId,
+ wikiId,
+ input.operationType,
+ "queued",
+ issue.id,
+ issue.projectId ?? null,
+ space.id,
+ jsonParam({
+ ...operationMetadata(operationContext),
+ issueOriginId: originId,
+ billingCode: operationBillingCode(wikiId, space),
+ }),
+ ],
+ );
+
+ return { operationId, wikiId, spaceSlug: space.slug, issue };
+}
+
+function isLlmWikiOperationIssue(issue: Issue): boolean {
+ return typeof issue.originKind === "string" && issue.originKind.startsWith(OPERATION_ORIGIN_KIND);
+}
+
+function paperclipDistillationScope(input: { projectId?: string | null; rootIssueId?: string | null }): PaperclipDistillationScope {
+ if (input.rootIssueId) return "root_issue";
+ if (input.projectId) return "project";
+ return "company";
+}
+
+function paperclipCursorScopeMetadata(input: { projectId?: string | null; rootIssueId?: string | null }) {
+ const sourceScope = paperclipDistillationScope(input);
+ const projectId = sourceScope === "project" ? input.projectId ?? null : null;
+ const rootIssueId = sourceScope === "root_issue" ? input.rootIssueId ?? null : null;
+ return {
+ sourceScope,
+ scopeKey: rootIssueId ?? projectId ?? "company",
+ projectId,
+ rootIssueId,
+ };
+}
+
+async function upsertPaperclipDistillationCursor(ctx: PluginContext, input: {
+ companyId: string;
+ wikiId: string;
+ spaceId: string;
+ projectId?: string | null;
+ rootIssueId?: string | null;
+ observedAt?: string | null;
+ metadata?: Record<string, unknown>;
+}): Promise<string> {
+ const cursorId = randomUUID();
+ const scope = paperclipCursorScopeMetadata(input);
+ await ctx.db.execute(
+ `INSERT INTO ${distillationCursorTable(ctx)} AS paperclip_distillation_cursors
+ (id, company_id, wiki_id, space_id, source_scope, scope_key, project_id, root_issue_id, source_kind, last_observed_at, pending_event_count, metadata)
+ VALUES ($1, $2, $3, $11, $4, $5, $6, $7, 'paperclip_issue_history', $8::timestamptz, $9, $10::jsonb)
+ ON CONFLICT (company_id, wiki_id, space_id, source_scope, scope_key, source_kind)
+ DO UPDATE SET last_observed_at = GREATEST(
+ COALESCE(paperclip_distillation_cursors.last_observed_at, EXCLUDED.last_observed_at),
+ COALESCE(EXCLUDED.last_observed_at, paperclip_distillation_cursors.last_observed_at)
+ ),
+ pending_event_count = paperclip_distillation_cursors.pending_event_count + EXCLUDED.pending_event_count,
+ metadata = paperclip_distillation_cursors.metadata || EXCLUDED.metadata,
+ updated_at = now()`,
+ [
+ cursorId,
+ input.companyId,
+ input.wikiId,
+ scope.sourceScope,
+ scope.scopeKey,
+ scope.projectId,
+ scope.rootIssueId,
+ input.observedAt ?? null,
+ input.observedAt ? 1 : 0,
+ jsonParam(input.metadata ?? {}),
+ input.spaceId,
+ ],
+ );
+ const rows = await ctx.db.query<{ id: string }>(
+ `SELECT id
+ FROM ${distillationCursorTable(ctx)}
+ WHERE company_id = $1
+ AND wiki_id = $2
+ AND space_id = $3
+ AND source_scope = $4
+ AND scope_key = $5
+ AND source_kind = 'paperclip_issue_history'
+ LIMIT 1`,
+ [input.companyId, input.wikiId, input.spaceId, scope.sourceScope, scope.scopeKey],
+ );
+ return rows[0]?.id ?? cursorId;
+}
+
+function isActiveDistillationProject(project: Project): boolean {
+ if (project.status !== "in_progress") return false;
+ if (project.archivedAt) return false;
+ if (project.managedByPlugin?.pluginKey === PLUGIN_ID) return false;
+ if (project.managedByPlugin?.resourceKey === WIKI_PROJECT_KEY) return false;
+ return true;
+}
+
+function projectActivityTimestamp(project: Project): string {
+ return isoString(project.updatedAt) ?? new Date().toISOString();
+}
+
+export async function enableActiveProjectDistillation(ctx: PluginContext, input: {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ limit?: number | null;
+}): Promise<EnableActiveProjectDistillationResult> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await requirePaperclipIngestionPolicy(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug }, "candidate_search", { requireEnabledProfile: true });
+ if (typeof input.limit === "number" && Number.isFinite(input.limit) && Math.floor(input.limit) > MAX_PAPERCLIP_DISTILLATION_FAN_OUT) {
+ throw new Error(`Paperclip ingestion fan-out exceeds the hard cap of ${MAX_PAPERCLIP_DISTILLATION_FAN_OUT} enabled profiles.`);
+ }
+ const limit = normalizeLimit(input.limit ?? 3, 3, 25);
+ const projects = await ctx.projects.list({ companyId: input.companyId, limit: 200 });
+ const activeProjects = projects
+ .filter(isActiveDistillationProject)
+ .sort((a, b) => projectActivityTimestamp(b).localeCompare(projectActivityTimestamp(a)))
+ .slice(0, limit);
+
+ const selectedProjects: EnableActiveProjectDistillationResult["selectedProjects"] = [];
+ for (const project of activeProjects) {
+ const observedAt = projectActivityTimestamp(project);
+ const cursorId = await upsertPaperclipDistillationCursor(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceId: space.id,
+ projectId: project.id,
+ rootIssueId: null,
+ observedAt,
+ metadata: {
+ configuredBy: "enable-active-projects",
+ projectName: project.name,
+ projectStatus: project.status,
+ },
+ });
+ selectedProjects.push({
+ id: project.id,
+ name: project.name,
+ status: project.status,
+ observedAt,
+ cursorId,
+ });
+ }
+
+ const eventIngestion = await updateEventIngestionSettings(ctx, {
+ companyId: input.companyId,
+ settings: {
+ enabled: true,
+ wikiId,
+ sources: {
+ issues: true,
+ comments: true,
+ documents: true,
+ },
+ },
+ });
+
+ return {
+ wikiId,
+ spaceSlug: space.slug,
+ selectedProjects,
+ eventIngestion,
+ };
+}
+
+function appendBoundedSection(input: {
+ lines: string[];
+ title: string;
+ body: string;
+ refs: PaperclipSourceRef[];
+ ref: PaperclipSourceRef;
+ remaining: { value: number };
+ perSourceLimit: number;
+ warnings: string[];
+}) {
+ if (input.remaining.value <= 0) {
+ input.warnings.push(`Skipped ${input.title}: source bundle character limit reached.`);
+ return;
+ }
+ const boundedBody = input.body.length > input.perSourceLimit
+ ? `${input.body.slice(0, input.perSourceLimit)}\n\n[Clipped at ${input.perSourceLimit} characters for this source.]`
+ : input.body;
+ const section = [`## ${input.title}`, "", boundedBody.trim() || "_No content._", ""].join("\n");
+ const clippedSection = section.length > input.remaining.value
+ ? `${section.slice(0, input.remaining.value)}\n\n[Source bundle clipped at configured limit.]\n`
+ : section;
+ input.lines.push(clippedSection);
+ input.refs.push(input.ref);
+ if (boundedBody.length !== input.body.length || clippedSection.length !== section.length) {
+ input.warnings.push(`Clipped ${input.title}.`);
+ }
+ input.remaining.value -= clippedSection.length;
+}
+
+function issueSortKey(issue: Issue): string {
+ return `${issue.identifier ?? ""}:${issue.title}:${issue.id}`;
+}
+
+function sourceRefUpdatedAt(ref: PaperclipSourceRef): string | null {
+ return ref.updatedAt ?? ref.createdAt ?? null;
+}
+
+function issueInBackfillWindow(issue: Issue, input: Pick<PaperclipSourceBundleInput, "backfillStartAt" | "backfillEndAt">): boolean {
+ const issueUpdatedAt = isoString(issue.updatedAt);
+ if (!issueUpdatedAt) return true;
+ const startAt = isoString(input.backfillStartAt);
+ const endAt = isoString(input.backfillEndAt);
+ if (startAt && issueUpdatedAt < startAt) return false;
+ if (endAt && issueUpdatedAt > endAt) return false;
+ return true;
+}
+
+async function listPaperclipBundleIssues(ctx: PluginContext, input: PaperclipSourceBundleInput): Promise<Issue[]> {
+ const filterAndSort = (issues: Issue[]) =>
+ issues
+ .filter((issue) => !isLlmWikiOperationIssue(issue))
+ .filter((issue) => issueInBackfillWindow(issue, input))
+ .sort((a, b) => issueSortKey(a).localeCompare(issueSortKey(b)));
+
+ if (input.rootIssueId) {
+ const subtree = await ctx.issues.getSubtree(input.rootIssueId, input.companyId, {
+ includeRoot: true,
+ includeRelations: true,
+ includeDocuments: true,
+ includeAssignees: true,
+ });
+ return filterAndSort(subtree.issues);
+ }
+
+ const issues = await ctx.issues.list({
+ companyId: input.companyId,
+ projectId: input.projectId ?? undefined,
+ includePluginOperations: false,
+ limit: 500,
+ });
+ return filterAndSort(issues);
+}
+
+export async function assemblePaperclipSourceBundle(ctx: PluginContext, input: PaperclipSourceBundleInput): Promise<PaperclipSourceBundle> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ assertPaperclipSourceScopePayload(input);
+ const space = await requirePaperclipIngestionPolicy(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug }, "execute", { requireEnabledProfile: true });
+ const limits = await resolvePaperclipDistillationLimitsForSpace(ctx, { ...input, space });
+ const maxCharacters = limits.maxCharacters;
+ const perSourceLimit = limits.maxCharactersPerSource;
+ const includeComments = input.includeComments !== false;
+ const includeDocuments = input.includeDocuments !== false;
+ const issues = await listPaperclipBundleIssues(ctx, input);
+ const scope = paperclipCursorScopeMetadata(input);
+ const sourceRefs: PaperclipSourceRef[] = [];
+ const warnings: string[] = [];
+ const lines = [
+ `# Paperclip source bundle`,
+ "",
+ "## Bundle Metadata",
+ "",
+ `- Company ID: ${input.companyId}`,
+ `- Wiki ID: ${wikiId}`,
+ `- Space: ${space.displayName} (${space.slug})`,
+ `- Source scope: ${scope.sourceScope}`,
+ scope.projectId ? `- Project ID: ${scope.projectId}` : null,
+ scope.rootIssueId ? `- Root issue ID: ${scope.rootIssueId}` : null,
+ input.backfillStartAt ? `- Backfill start: ${isoString(input.backfillStartAt) ?? input.backfillStartAt}` : null,
+ input.backfillEndAt ? `- Backfill end: ${isoString(input.backfillEndAt) ?? input.backfillEndAt}` : null,
+ `- Issue count: ${issues.length}`,
+ `- Source caps: ${maxCharacters} characters per window; ${perSourceLimit} characters per source`,
+ "",
+ ].filter((line): line is string => line !== null);
+ const remaining = { value: maxCharacters - lines.join("\n").length };
+
+ for (const issue of issues) {
+ const issueBody = [
+ `- Issue ID: ${issue.id}`,
+ issue.identifier ? `- Identifier: ${issue.identifier}` : null,
+ `- Status: ${issue.status}`,
+ `- Priority: ${issue.priority}`,
+ issue.parentId ? `- Parent issue ID: ${issue.parentId}` : null,
+ issue.projectId ? `- Project ID: ${issue.projectId}` : null,
+ `- Updated at: ${isoString(issue.updatedAt) ?? "unknown"}`,
+ "",
+ issue.description?.trim() ? issue.description.trim() : "_No issue description._",
+ ].filter((line): line is string => line !== null).join("\n");
+ appendBoundedSection({
+ lines,
+ title: `Issue: ${sourceTitleForIssue(issue)}`,
+ body: issueBody,
+ refs: sourceRefs,
+ ref: {
+ kind: "issue",
+ issueId: issue.id,
+ issueIdentifier: issue.identifier ?? null,
+ projectId: issue.projectId ?? null,
+ title: issue.title,
+ updatedAt: isoString(issue.updatedAt) ?? undefined,
+ },
+ remaining,
+ perSourceLimit,
+ warnings,
+ });
+
+ if (includeDocuments && remaining.value > 0) {
+ const documentSummaries = await ctx.issues.documents.list(issue.id, input.companyId);
+ for (const summary of [...documentSummaries].sort((a, b) => a.key.localeCompare(b.key))) {
+ const document = await ctx.issues.documents.get(issue.id, summary.key, input.companyId);
+ if (!document) continue;
+ const protectedDocument = protectDistillationSourceBody({
+ issue,
+ sourceKind: "document",
+ sourceId: document.key,
+ body: document.body,
+ });
+ if (protectedDocument.warning) warnings.push(protectedDocument.warning);
+ appendBoundedSection({
+ lines,
+ title: `Document: ${sourceTitleForIssue(issue)} / ${document.key}`,
+ body: [
+ `- Issue ID: ${issue.id}`,
+ issue.identifier ? `- Issue identifier: ${issue.identifier}` : null,
+ `- Document ID: ${document.id}`,
+ `- Document key: ${document.key}`,
+ `- Revision: ${document.latestRevisionNumber}`,
+ `- Updated at: ${isoString(document.updatedAt) ?? "unknown"}`,
+ "",
+ protectedDocument.body,
+ ].filter((line): line is string => line !== null).join("\n"),
+ refs: sourceRefs,
+ ref: {
+ kind: "document",
+ issueId: issue.id,
+ issueIdentifier: issue.identifier ?? null,
+ projectId: issue.projectId ?? null,
+ documentId: document.id,
+ documentKey: document.key,
+ updatedAt: isoString(document.updatedAt) ?? undefined,
+ ...protectedDocument.refPatch,
+ },
+ remaining,
+ perSourceLimit,
+ warnings,
+ });
+ }
+ }
+
+ if (includeComments && remaining.value > 0) {
+ const comments = await ctx.issues.listComments(issue.id, input.companyId);
+ for (const comment of [...comments].sort((a, b) => (isoString(a.createdAt) ?? "").localeCompare(isoString(b.createdAt) ?? ""))) {
+ const protectedComment = protectDistillationSourceBody({
+ issue,
+ sourceKind: "comment",
+ sourceId: comment.id,
+ body: comment.body,
+ });
+ if (protectedComment.warning) warnings.push(protectedComment.warning);
+ appendBoundedSection({
+ lines,
+ title: `Comment: ${sourceTitleForIssue(issue)} / ${comment.id}`,
+ body: [
+ `- Issue ID: ${issue.id}`,
+ issue.identifier ? `- Issue identifier: ${issue.identifier}` : null,
+ `- Comment ID: ${comment.id}`,
+ `- Created at: ${isoString(comment.createdAt) ?? "unknown"}`,
+ "",
+ protectedComment.body,
+ ].filter((line): line is string => line !== null).join("\n"),
+ refs: sourceRefs,
+ ref: {
+ kind: "comment",
+ issueId: issue.id,
+ issueIdentifier: issue.identifier ?? null,
+ projectId: issue.projectId ?? null,
+ commentId: comment.id,
+ createdAt: isoString(comment.createdAt) ?? undefined,
+ ...protectedComment.refPatch,
+ },
+ remaining,
+ perSourceLimit,
+ warnings,
+ });
+ }
+ }
+ }
+
+ const markdown = lines.join("\n").slice(0, maxCharacters);
+ const sourceDates = sourceRefs.map(sourceRefUpdatedAt).filter((date): date is string => Boolean(date)).sort();
+ return {
+ markdown,
+ sourceRefs,
+ sourceHash: contentHash(markdown),
+ sourceWindowStart: sourceDates[0] ?? null,
+ sourceWindowEnd: sourceDates[sourceDates.length - 1] ?? null,
+ clipped: warnings.some((warning) => warning.includes("Clipped") || warning.includes("Skipped")) || lines.join("\n").length > maxCharacters,
+ warnings,
+ };
+}
+
+export async function createPaperclipDistillationRun(ctx: PluginContext, input: PaperclipDistillationRunInput) {
+ const wikiId = normalizeWikiId(input.wikiId);
+ assertPaperclipSourceScopePayload(input);
+ const space = await requirePaperclipIngestionPolicy(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug }, "execute", { requireEnabledProfile: true });
+ const scope = paperclipCursorScopeMetadata(input);
+ const limits = await resolvePaperclipDistillationLimitsForSpace(ctx, { ...input, space });
+ const cursorId = await upsertPaperclipDistillationCursor(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceId: space.id,
+ projectId: scope.projectId,
+ rootIssueId: scope.rootIssueId,
+ metadata: { source: "source-bundle" },
+ });
+ const bundle = await assemblePaperclipSourceBundle(ctx, input);
+ const estimatedCostCents = estimateSourceCostCents(
+ bundle.markdown.length,
+ limits.costCentsPerThousandSourceCharacters,
+ );
+ const runId = randomUUID();
+ const snapshotId = randomUUID();
+
+ await ctx.db.execute(
+ `INSERT INTO ${distillationRunTable(ctx)}
+ (id, company_id, wiki_id, space_id, cursor_id, work_item_id, project_id, root_issue_id, source_window_start, source_window_end, source_hash, status, operation_issue_id, retry_count, cost_cents, warnings, metadata)
+ VALUES ($1, $2, $3, $15, $4, $5, $6, $7, $8::timestamptz, $9::timestamptz, $10, 'source_ready', $11, 0, $12, $13::jsonb, $14::jsonb)`,
+ [
+ runId,
+ input.companyId,
+ wikiId,
+ cursorId,
+ input.workItemId ?? null,
+ scope.projectId,
+ scope.rootIssueId,
+ bundle.sourceWindowStart,
+ bundle.sourceWindowEnd,
+ bundle.sourceHash,
+ input.operationIssueId ?? null,
+ estimatedCostCents,
+ jsonArrayParam(bundle.warnings),
+ jsonParam({
+ spaceSlug: space.slug,
+ sourceScope: scope.sourceScope,
+ limits,
+ backfillStartAt: isoString(input.backfillStartAt),
+ backfillEndAt: isoString(input.backfillEndAt),
+ }),
+ space.id,
+ ],
+ );
+ await ctx.db.execute(
+ `INSERT INTO ${sourceSnapshotTable(ctx)}
+ (id, company_id, wiki_id, space_id, distillation_run_id, project_id, root_issue_id, source_hash, max_characters, clipped, source_refs, bundle_markdown, metadata)
+ VALUES ($1, $2, $3, $13, $4, $5, $6, $7, $8, $9, $10::jsonb, $11, $12::jsonb)`,
+ [
+ snapshotId,
+ input.companyId,
+ wikiId,
+ runId,
+ scope.projectId,
+ scope.rootIssueId,
+ bundle.sourceHash,
+ limits.maxCharacters,
+ bundle.clipped,
+ jsonParam(bundle.sourceRefs),
+ bundle.markdown,
+ jsonParam({
+ spaceSlug: space.slug,
+ sourceScope: scope.sourceScope,
+ estimatedCostCents,
+ backfillStartAt: isoString(input.backfillStartAt),
+ backfillEndAt: isoString(input.backfillEndAt),
+ }),
+ space.id,
+ ],
+ );
+
+ return { status: "source_ready" as const, wikiId, spaceSlug: space.slug, cursorId, runId, snapshotId, bundle, estimatedCostCents };
+}
+
+export async function recordPaperclipDistillationOutcome(ctx: PluginContext, input: PaperclipDistillationOutcomeInput) {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await requirePaperclipIngestionPolicy(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug }, "execute", { requireEnabledProfile: true });
+ const warnings = input.warning ? [input.warning] : [];
+ await ctx.db.execute(
+ `UPDATE ${distillationRunTable(ctx)}
+ SET status = $4,
+ warnings = CASE WHEN $5::jsonb = '[]'::jsonb THEN warnings ELSE warnings || $5::jsonb END,
+ cost_cents = CASE WHEN $6::integer IS NULL THEN cost_cents ELSE $6::integer END,
+ retry_count = CASE WHEN $7::integer IS NULL THEN retry_count ELSE $7::integer END,
+ updated_at = now()
+ WHERE company_id = $1
+ AND wiki_id = $2
+ AND space_id = $8
+ AND id = $3`,
+ [
+ input.companyId,
+ wikiId,
+ input.runId,
+ input.status,
+ jsonArrayParam(warnings),
+ input.costCents ?? null,
+ input.retryCount ?? null,
+ space.id,
+ ],
+ );
+
+ if (input.status === "succeeded" && input.cursorId && input.sourceHash && input.sourceWindowEnd) {
+ await ctx.db.execute(
+ `UPDATE ${distillationCursorTable(ctx)}
+ SET last_processed_at = $4::timestamptz,
+ last_successful_run_id = $3,
+ last_source_hash = $5,
+ pending_event_count = 0,
+ updated_at = now()
+ WHERE company_id = $1
+ AND wiki_id = $2
+ AND space_id = $7
+ AND id = $6`,
+ [input.companyId, wikiId, input.runId, input.sourceWindowEnd, input.sourceHash, input.cursorId, space.id],
+ );
+ }
+
+ return {
+ status: input.status,
+ cursorAdvanced: input.status === "succeeded" && Boolean(input.cursorId && input.sourceHash && input.sourceWindowEnd),
+ };
+}
+
+export async function createPaperclipDistillationWorkItem(ctx: PluginContext, input: PaperclipDistillationWorkItemInput) {
+ const wikiId = normalizeWikiId(input.wikiId);
+ assertPaperclipSourceScopePayload(input);
+ const space = await requirePaperclipIngestionPolicy(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug }, "queue", { requireEnabledProfile: true });
+ const itemId = randomUUID();
+ const scope = paperclipCursorScopeMetadata(input);
+ if (input.kind === "backfill" && !scope.projectId && !scope.rootIssueId) {
+ throw new Error("Backfill work items must target a projectId or rootIssueId; whole-company backfill is not allowed.");
+ }
+ await ctx.db.execute(
+ `INSERT INTO ${distillationWorkItemTable(ctx)} AS paperclip_distillation_work_items
+ (id, company_id, wiki_id, space_id, work_item_kind, status, priority, project_id, root_issue_id, requested_by_issue_id, idempotency_key, metadata)
+ VALUES ($1, $2, $3, $11, $4, 'pending', $5, $6, $7, $8, $9, $10::jsonb)
+ ON CONFLICT (company_id, wiki_id, space_id, idempotency_key)
+ DO UPDATE SET priority = EXCLUDED.priority,
+ metadata = paperclip_distillation_work_items.metadata || EXCLUDED.metadata,
+ updated_at = now()`,
+ [
+ itemId,
+ input.companyId,
+ wikiId,
+ input.kind,
+ input.priority ?? "medium",
+ scope.projectId,
+ scope.rootIssueId,
+ input.requestedByIssueId ?? null,
+ input.idempotencyKey ?? null,
+ jsonParam({
+ spaceSlug: space.slug,
+ sourceScope: scope.sourceScope,
+ ...(input.metadata ?? {}),
+ }),
+ space.id,
+ ],
+ );
+ return { status: "pending", workItemId: itemId, wikiId, spaceSlug: space.slug, kind: input.kind, sourceScope: scope.sourceScope };
+}
+
+function sourceRefLabel(ref: PaperclipSourceRef): string {
+ const issue = ref.issueIdentifier ? issueReference(ref.issueIdentifier) : (ref.title ?? "Paperclip source");
+ if (ref.kind === "document") return `${issue} document:${ref.documentKey ?? "unknown"}`;
+ if (ref.kind === "comment") return `${issue} comment`;
+ return issue;
+}
+
+function sourceRefMarkdown(ref: PaperclipSourceRef): string {
+ const metadata = [
+ ref.redactionStatus ? `redaction=${ref.redactionStatus}` : null,
+ ref.redactionReasons?.length ? `redaction_reasons=${ref.redactionReasons.join("|")}` : null,
+ ].filter((part): part is string => Boolean(part)).join(", ");
+ return `- ${sourceRefLabel(ref)}${metadata ? ` (${metadata})` : ""}`;
+}
+
+function issueSourceRef(issue: Issue): PaperclipSourceRef {
+ return {
+ kind: "issue",
+ issueId: issue.id,
+ issueIdentifier: issue.identifier ?? null,
+ projectId: issue.projectId ?? null,
+ title: issue.title,
+ updatedAt: isoString(issue.updatedAt) ?? undefined,
+ };
+}
+
+function projectPageSlug(input: { project: Project | null; rootIssue: Issue | null }): string {
+ return slugify(input.project?.name ?? input.rootIssue?.title ?? "paperclip-project");
+}
+
+function issueDescription(issue: Issue): string {
+ return issue.description?.trim() ?? "";
+}
+
+function issueReference(identifier: string): string {
+ const prefix = identifier.match(/^([A-Z]+)-\d+$/)?.[1];
+ return prefix ? `[${identifier}](/${prefix}/issues/${identifier})` : identifier;
+}
+
+function issueReferenceFor(issue: Issue): string {
+ return issue.identifier ? issueReference(issue.identifier) : "source issue";
+}
+
+function issueConcept(issue: Issue): string {
+ const title = issue.title
+ .replace(/^\s*(implement|add|update|fix|ship|write|create|publish|review|validate|investigate|design|refactor|support|make)\s+/i, "")
+ .replace(/\s+/g, " ")
+ .trim();
+ const words = title.split(" ").filter(Boolean).slice(0, 5).join(" ");
+ return words || issue.title;
+}
+
+function issueNarrative(issue: Issue, maxLength = 260): string {
+ const details = issueDescription(issue);
+ return excerpt(details || issue.title, maxLength);
+}
+
+function conceptBullet(issue: Issue): string {
+ return `- **${issueConcept(issue)}.** ${issueNarrative(issue)} (${issueReferenceFor(issue)})`;
+}
+
+function excerpt(value: string, maxLength = 240): string {
+ const normalized = value.replace(/\s+/g, " ").trim();
+ if (normalized.length <= maxLength) return normalized;
+ return `${normalized.slice(0, maxLength - 1).trimEnd()}...`;
+}
+
+function hasDecisionSignal(value: string): boolean {
+ return /\b(accepted|approved|rejected|reversed|decided|decision|plan|proposal|approach|architecture|tradeoff)\b/i.test(value);
+}
+
+function hasRiskSignal(value: string): boolean {
+ return /\b(blocked|blocker|risk|warning|stale|conflict|failed|failure|regression)\b/i.test(value);
+}
+
+function hasDurableSignal(bundle: PaperclipSourceBundle, issues: Issue[]): boolean {
+ if (bundle.sourceRefs.some((ref) => ref.kind === "document" || ref.kind === "comment")) return true;
+ if (issues.some((issue) => issue.status !== "todo" || issueDescription(issue).length > 0)) return true;
+ return /\b(decision|approved|implemented|completed|blocked|risk|artifact|plan|handoff|merged|fixed)\b/i.test(bundle.markdown);
+}
+
+function standupPageContents(input: {
+ project: Project | null;
+ rootIssue: Issue | null;
+ issues: Issue[];
+ bundle: PaperclipSourceBundle;
+ pagePath: string;
+ durablePagePath: string;
+}): string {
+ const currentAsOf = input.bundle.sourceWindowEnd ?? new Date().toISOString();
+ const title = input.project?.name ?? input.rootIssue?.title ?? "Paperclip Project";
+ const activeIssues = input.issues.filter((issue) => !["done", "cancelled"].includes(issue.status));
+ const recentlyChanged = [...input.issues]
+ .sort((a, b) => (isoString(b.updatedAt) ?? "").localeCompare(isoString(a.updatedAt) ?? ""))
+ .slice(0, 6);
+ const completedIssues = recentlyChanged.filter((issue) => issue.status === "done");
+ const advancedIssues = recentlyChanged.filter((issue) => issue.status !== "done" && issue.status !== "cancelled");
+ const decisionIssues = input.issues.filter((issue) => hasDecisionSignal(`${issue.title}\n${issueDescription(issue)}`)).slice(0, 6);
+ const riskIssues = input.issues.filter((issue) => issue.status === "blocked" || hasRiskSignal(`${issue.title}\n${issueDescription(issue)}`)).slice(0, 6);
+ const nextActionIssues = activeIssues.slice(0, 6);
+ const lead = activeIssues[0] ?? recentlyChanged[0] ?? null;
+
+ return [
+ "---",
+ `title: ${JSON.stringify(`${title} Standup`)}`,
+ "type: project-standup",
+ `project: ${JSON.stringify(projectPageSlug(input))}`,
+ `current_as_of: ${JSON.stringify(currentAsOf)}`,
+ "sources: []",
+ "---",
+ "",
+ `# ${title} Standup`,
+ "",
+ "## Executive Readout",
+ "",
+ lead
+ ? `The current center of gravity is **${issueConcept(lead)}** (${issueReferenceFor(lead)}). ${input.bundle.clipped ? "The source window was clipped, so treat this as a bounded readout rather than the full live state." : "This is a high-level readout of the meaningful Paperclip work in the current source window."}`
+ : "No meaningful project movement was present in this source window.",
+ "",
+ "## What Changed",
+ "",
+ ...(completedIssues.length
+ ? completedIssues.map(conceptBullet)
+ : advancedIssues.length
+ ? advancedIssues.map(conceptBullet)
+ : ["- No material completed or advanced work was identified in this source window."]),
+ "",
+ "## Decisions",
+ "",
+ ...(decisionIssues.length
+ ? decisionIssues.map(conceptBullet)
+ : ["- No decision changed the project direction in this source window."]),
+ "",
+ "## Blockers / Risks",
+ "",
+ ...(riskIssues.length
+ ? riskIssues.map(conceptBullet)
+ : ["- No active blocker or material risk surfaced in this source window."]),
+ "",
+ "## Next Actions",
+ "",
+ ...(nextActionIssues.length
+ ? nextActionIssues.map((issue) => `- **${issueConcept(issue)}.** Continue the work represented by ${issueReferenceFor(issue)}; focus on the next concrete deliverable rather than routine status churn.`)
+ : ["- No next action inferred from this source window."]),
+ "",
+ "## Links",
+ "",
+ `- Durable project overview: [[${input.durablePagePath}]]`,
+ ...input.bundle.sourceRefs.slice(0, 12).map(sourceRefMarkdown),
+ "",
+ ].filter((line): line is string => line !== null).join("\n");
+}
+
+function projectPageContents(input: {
+ project: Project | null;
+ rootIssue: Issue | null;
+ issues: Issue[];
+ bundle: PaperclipSourceBundle;
+ pagePath: string;
+}): string {
+ const currentAsOf = input.bundle.sourceWindowEnd ?? new Date().toISOString();
+ const title = input.project?.name ?? input.rootIssue?.title ?? "Paperclip Project";
+ const description = input.project?.description?.trim() || input.rootIssue?.description?.trim() || "";
+ const activeIssues = input.issues.filter((issue) => !["done", "cancelled"].includes(issue.status));
+ const recentIssues = [...input.issues]
+ .sort((a, b) => (isoString(b.updatedAt) ?? "").localeCompare(isoString(a.updatedAt) ?? ""))
+ .slice(0, 8);
+ const decisionIssues = input.issues.filter((issue) => hasDecisionSignal(`${issue.title}\n${issueDescription(issue)}`)).slice(0, 8);
+ const riskIssues = input.issues.filter((issue) => issue.status === "blocked" || hasRiskSignal(`${issue.title}\n${issueDescription(issue)}`)).slice(0, 8);
+
+ return [
+ "---",
+ `title: ${JSON.stringify(title)}`,
+ "type: project",
+ `current_as_of: ${JSON.stringify(currentAsOf)}`,
+ "sources: []",
+ "---",
+ "",
+ `# ${title}`,
+ "",
+ "## Overview",
+ "",
+ description ? excerpt(description, 700) : `This page synthesizes Paperclip issue history into a stable project brief for ${title}.`,
+ "",
+ "## Current Direction",
+ "",
+ activeIssues.length
+ ? `Work is currently organized around ${activeIssues.slice(0, 3).map((issue) => `**${issueConcept(issue)}** (${issueReferenceFor(issue)})`).join(", ")}. The useful project view is the concept being advanced, not the raw issue queue.`
+ : "The current source window does not show active project work.",
+ input.bundle.clipped ? "\nThe source window was clipped, so verify Paperclip before treating this as complete state." : null,
+ "",
+ "## Workstreams",
+ "",
+ ...(recentIssues.length
+ ? recentIssues.map(conceptBullet)
+ : ["- No meaningful workstream signal was identified in this source window."]),
+ "",
+ "## Decisions",
+ "",
+ ...(decisionIssues.length
+ ? decisionIssues.map(conceptBullet)
+ : ["- No durable decision signal was identified in this source window."]),
+ "",
+ "## Open Risks / Blockers",
+ "",
+ ...(riskIssues.length
+ ? riskIssues.map(conceptBullet)
+ : ["- No open risks or blockers identified in this source window."]),
+ "",
+ "## References",
+ "",
+ `- Current standup: [[${input.pagePath.replace(/\/index\.md$/, "/standup.md")}]]`,
+ ...input.bundle.sourceRefs.slice(0, 12).map(sourceRefMarkdown),
+ "",
+ ].filter((line): line is string => line !== null).join("\n");
+}
+
+function decisionsPageContents(input: { project: Project | null; rootIssue: Issue | null; issues: Issue[]; bundle: PaperclipSourceBundle }): string {
+ const title = input.project?.name ?? input.rootIssue?.title ?? "Paperclip Project";
+ const decisionIssues = input.issues.filter((issue) => hasDecisionSignal(`${issue.title}\n${issueDescription(issue)}`));
+ return [
+ `# ${title} Decisions`,
+ "",
+ "Durable project decisions grouped by concept. Use this as an editorial memory of why the project changed direction, not as an issue log.",
+ "",
+ ...(decisionIssues.length
+ ? decisionIssues.map((issue) => [
+ `## ${issueConcept(issue)}`,
+ "",
+ issueDescription(issue) ? excerpt(issueDescription(issue), 900) : "_No decision details beyond the issue title._",
+ "",
+ `Source: ${issueReferenceFor(issue)}`,
+ "",
+ ].join("\n"))
+ : ["No durable decisions identified in this source window.", ""]),
+ "## References",
+ "",
+ ...input.bundle.sourceRefs.slice(0, 40).map(sourceRefMarkdown),
+ "",
+ ].join("\n");
+}
+
+function historyPageContents(input: { project: Project | null; rootIssue: Issue | null; issues: Issue[]; bundle: PaperclipSourceBundle }): string {
+ const title = input.project?.name ?? input.rootIssue?.title ?? "Paperclip Project";
+ const timeline = [...input.issues]
+ .sort((a, b) => (isoString(a.updatedAt) ?? "").localeCompare(isoString(b.updatedAt) ?? ""))
+ .slice(-30);
+ return [
+ `# ${title} History`,
+ "",
+ "Narrative history of meaningful project movement. Group by what changed in the work, not by dates or metadata.",
+ "",
+ "## Meaningful Project Movement",
+ "",
+ ...(timeline.length
+ ? timeline.map(conceptBullet)
+ : ["- No source issues in this window."]),
+ "",
+ "## References",
+ "",
+ ...input.bundle.sourceRefs.slice(0, 40).map(sourceRefMarkdown),
+ "",
+ ].join("\n");
+}
+
+function updateProjectIndexContents(current: string | null, input: { pagePath: string; standupPath: string; title: string }): string {
+ const base = current?.trimEnd() || "# Index\n\n## Sources\n\n_(none yet)_\n\n## Projects\n\n_(none yet)_\n\n## Entities\n\n_(none yet)_\n\n## Concepts\n\n_(none yet)_\n\n## Synthesis\n\n_(none yet)_";
+ const entry = `- [[${input.pagePath}]] — ${input.title} project overview. Current executive standup: [[${input.standupPath}]].`;
+ const projectsMatch = base.match(/(^## Projects\n)([\s\S]*?)(?=^## |\s*$)/m);
+ if (!projectsMatch || projectsMatch.index == null) {
+ return `${base}\n\n## Projects\n\n${entry}\n`;
+ }
+ const start = projectsMatch.index + projectsMatch[1].length;
+ const end = start + projectsMatch[2].length;
+ const existingLines = projectsMatch[2]
+ .split("\n")
+ .map((line) => line.trimEnd())
+ .filter((line) => line.trim() && line.trim() !== "_(none yet)_" && !line.includes(input.pagePath) && !line.includes(input.standupPath));
+ const nextLines = [...existingLines, entry].sort((a, b) => a.localeCompare(b));
+ return `${base.slice(0, start)}${nextLines.join("\n")}\n\n${base.slice(end).replace(/^\n+/, "")}`.trimEnd() + "\n";
+}
+
+function appendProjectLogContents(current: string | null, input: { standupPath: string; pagePath: string; runId: string; sourceHash: string; status: string; warnings: string[] }): string {
+ const base = current?.trimEnd() || "# Log\n\nAppend-only chronological record of wiki operations.";
+ const warningLines = input.warnings.length
+ ? input.warnings.map((warning) => `- warning: ${warning}`)
+ : ["- warnings: none"];
+ const entry = [
+ `## [${new Date().toISOString().slice(0, 10)}] paperclip-distill | ${input.status}`,
+ `- standup: \`${input.standupPath}\``,
+ `- page: \`${input.pagePath}\``,
+ `- run: \`${input.runId}\``,
+ `- source hash: \`${input.sourceHash}\``,
+ ...warningLines,
+ ].join("\n");
+ return `${base}\n\n${entry}\n`;
+}
+
+function patchForPage(input: {
+ path: string;
+ operationType: PaperclipDistillationPatchOperation;
+ currentHash: string | null;
+ contents: string;
+ bundle: PaperclipSourceBundle;
+ confidence: "high" | "medium" | "low";
+ warnings: string[];
+ humanReviewRequired: boolean;
+}): PaperclipDistillationPatch {
+ return {
+ pagePath: input.path,
+ operationType: input.operationType,
+ currentHash: input.currentHash,
+ proposedHash: contentHash(input.contents),
+ proposedContents: input.contents,
+ sourceHash: input.bundle.sourceHash,
+ sourceRefs: input.bundle.sourceRefs,
+ cursorWindow: {
+ start: input.bundle.sourceWindowStart,
+ end: input.bundle.sourceWindowEnd,
+ },
+ confidence: input.confidence,
+ warnings: input.warnings,
+ humanReviewRequired: input.humanReviewRequired,
+ };
+}
+
+async function readPageBinding(ctx: PluginContext, input: { companyId: string; wikiId: string; spaceId: string; pagePath: string }) {
+ const rows = await ctx.db.query<{ last_applied_source_hash: string | null }>(
+ `SELECT last_applied_source_hash
+ FROM ${pageBindingTable(ctx)}
+ WHERE company_id = $1
+ AND wiki_id = $2
+ AND space_id = $3
+ AND page_path = $4
+ LIMIT 1`,
+ [input.companyId, input.wikiId, input.spaceId, input.pagePath],
+ );
+ return rows[0] ?? null;
+}
+
+async function upsertPageBinding(ctx: PluginContext, input: {
+ companyId: string;
+ wikiId: string;
+ spaceId: string;
+ spaceSlug: string;
+ projectId: string | null;
+ rootIssueId: string | null;
+ pagePath: string;
+ sourceHash: string;
+ runId: string;
+ metadata?: Record<string, unknown>;
+}) {
+ await ctx.db.execute(
+ `INSERT INTO ${pageBindingTable(ctx)} AS paperclip_page_bindings
+ (id, company_id, wiki_id, space_id, project_id, root_issue_id, page_path, last_applied_source_hash, last_distillation_run_id, metadata)
+ VALUES ($1, $2, $3, $10, $4, $5, $6, $7, $8, $9::jsonb)
+ ON CONFLICT (company_id, wiki_id, space_id, page_path)
+ DO UPDATE SET last_applied_source_hash = EXCLUDED.last_applied_source_hash,
+ last_distillation_run_id = EXCLUDED.last_distillation_run_id,
+ metadata = paperclip_page_bindings.metadata || EXCLUDED.metadata,
+ updated_at = now()`,
+ [
+ randomUUID(),
+ input.companyId,
+ input.wikiId,
+ input.projectId,
+ input.rootIssueId,
+ input.pagePath,
+ input.sourceHash,
+ input.runId,
+ jsonParam({ spaceSlug: input.spaceSlug, ...(input.metadata ?? {}) }),
+ input.spaceId,
+ ],
+ );
+}
+
+async function autoApplyEnabled(ctx: PluginContext, requested: boolean | undefined): Promise<boolean> {
+ if (getDistillationAutoApplyRestriction().autoApplyRestriction) {
+ return false;
+ }
+ const config = await ctx.config.get();
+ const configured = (config as { autoApplyIngestPatches?: unknown }).autoApplyIngestPatches !== false;
+ return configured && requested !== false;
+}
+
+export function getDistillationAutoApplyRestriction(): DistillationAutoApplyRestriction {
+ const rawMode = process.env.PAPERCLIP_DEPLOYMENT_MODE;
+ const rawExposure = process.env.PAPERCLIP_DEPLOYMENT_EXPOSURE;
+ const deploymentMode =
+ rawMode === "local_trusted" || rawMode === "authenticated" ? rawMode : null;
+ const deploymentExposure =
+ rawExposure === "private" || rawExposure === "public" ? rawExposure : null;
+ const blocked = deploymentMode === "authenticated" && deploymentExposure === "public";
+ return {
+ autoApplyAllowed: !blocked,
+ autoApplyRestriction: blocked ? PUBLIC_DISTILLATION_AUTO_APPLY_RESTRICTION : null,
+ deploymentMode,
+ deploymentExposure,
+ };
+}
+
+export async function distillPaperclipProjectPage(ctx: PluginContext, input: PaperclipProjectPageDistillationInput) {
+ if (!input.projectId && !input.rootIssueId) {
+ throw new Error("projectId or rootIssueId is required");
+ }
+ const wikiId = normalizeWikiId(input.wikiId);
+ assertPaperclipSourceScopePayload(input);
+ const space = await requirePaperclipIngestionPolicy(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug }, "execute", { requireEnabledProfile: true });
+ const scope = paperclipCursorScopeMetadata(input);
+ const issues = await listPaperclipBundleIssues(ctx, input);
+ const project = scope.projectId ? await ctx.projects.get(scope.projectId, input.companyId) : null;
+ const rootIssue = scope.rootIssueId ? await ctx.issues.get(scope.rootIssueId, input.companyId) : null;
+ const slug = projectPageSlug({ project, rootIssue });
+ const projectDir = `wiki/projects/${slug}`;
+ const standupPath = assertPagePath(`${projectDir}/standup.md`);
+ const pagePath = assertPagePath(`${projectDir}/index.md`);
+ const run = await createPaperclipDistillationRun(ctx, input);
+ const bundle = run.bundle;
+ const current = await readCurrentWithHash(ctx, input.companyId, pagePath, space);
+ assertExpectedHash(input.expectedProjectPageHash, current.hash, pagePath);
+
+ if (!hasDurableSignal(bundle, issues)) {
+ await recordPaperclipDistillationOutcome(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceSlug: space.slug,
+ runId: run.runId,
+ cursorId: run.cursorId,
+ status: "succeeded",
+ sourceHash: bundle.sourceHash,
+ sourceWindowEnd: bundle.sourceWindowEnd,
+ warning: "Skipped low-signal Paperclip source window.",
+ });
+ return {
+ status: "skipped",
+ reason: "low_signal",
+ wikiId,
+ runId: run.runId,
+ cursorId: run.cursorId,
+ sourceHash: bundle.sourceHash,
+ warnings: ["Skipped low-signal Paperclip source window."],
+ patches: [] as PaperclipDistillationPatch[],
+ };
+ }
+
+ const existingBinding = await readPageBinding(ctx, { companyId: input.companyId, wikiId, spaceId: space.id, pagePath });
+ if (existingBinding?.last_applied_source_hash === bundle.sourceHash) {
+ await recordPaperclipDistillationOutcome(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceSlug: space.slug,
+ runId: run.runId,
+ cursorId: run.cursorId,
+ status: "succeeded",
+ sourceHash: bundle.sourceHash,
+ sourceWindowEnd: bundle.sourceWindowEnd,
+ warning: "Skipped unchanged Paperclip source hash.",
+ });
+ return {
+ status: "skipped",
+ reason: "unchanged_source",
+ wikiId,
+ runId: run.runId,
+ cursorId: run.cursorId,
+ sourceHash: bundle.sourceHash,
+ warnings: ["Skipped unchanged Paperclip source hash."],
+ patches: [] as PaperclipDistillationPatch[],
+ };
+ }
+
+ const warnings = [...bundle.warnings];
+ const confidence: "high" | "medium" | "low" = bundle.clipped ? "medium" : "high";
+ const reviewRequired = bundle.clipped || warnings.length > 0;
+ const title = project?.name ?? rootIssue?.title ?? "Paperclip Project";
+ const standupCurrent = await readCurrentWithHash(ctx, input.companyId, standupPath, space);
+ const standupContents = standupPageContents({ project, rootIssue, issues, bundle, pagePath: standupPath, durablePagePath: pagePath });
+ const projectContents = projectPageContents({ project, rootIssue, issues, bundle, pagePath });
+ const indexCurrent = await readCurrentWithHash(ctx, input.companyId, "wiki/index.md", space);
+ const logCurrent = await readCurrentWithHash(ctx, input.companyId, "wiki/log.md", space);
+ const indexContents = updateProjectIndexContents(indexCurrent.contents, {
+ pagePath,
+ standupPath,
+ title,
+ });
+ const logContents = appendProjectLogContents(logCurrent.contents, {
+ standupPath,
+ pagePath,
+ runId: run.runId,
+ sourceHash: bundle.sourceHash,
+ status: "proposed",
+ warnings,
+ });
+ const patches: PaperclipDistillationPatch[] = [
+ patchForPage({ path: standupPath, operationType: "standup_update", currentHash: standupCurrent.hash, contents: standupContents, bundle, confidence, warnings, humanReviewRequired: reviewRequired }),
+ patchForPage({ path: pagePath, operationType: "project_page_distill", currentHash: current.hash, contents: projectContents, bundle, confidence, warnings, humanReviewRequired: reviewRequired }),
+ patchForPage({ path: "wiki/index.md", operationType: "index_refresh", currentHash: indexCurrent.hash, contents: indexContents, bundle, confidence: "high", warnings: [], humanReviewRequired: false }),
+ patchForPage({ path: "wiki/log.md", operationType: "log_append", currentHash: logCurrent.hash, contents: logContents, bundle, confidence: "high", warnings: [], humanReviewRequired: false }),
+ ];
+
+ if (input.includeSupportingPages !== false) {
+ const hasDecisions = issues.some((issue) => hasDecisionSignal(`${issue.title}\n${issueDescription(issue)}`));
+ if (hasDecisions) {
+ const decisionsPath = assertPagePath(`${projectDir}/decisions.md`);
+ const decisionsCurrent = await readCurrentWithHash(ctx, input.companyId, decisionsPath, space);
+ patches.push(patchForPage({
+ path: decisionsPath,
+ operationType: "decision_distill",
+ currentHash: decisionsCurrent.hash,
+ contents: decisionsPageContents({ project, rootIssue, issues, bundle }),
+ bundle,
+ confidence,
+ warnings,
+ humanReviewRequired: reviewRequired,
+ }));
+ }
+ const historyPath = assertPagePath(`${projectDir}/history.md`);
+ const historyCurrent = await readCurrentWithHash(ctx, input.companyId, historyPath, space);
+ patches.push(patchForPage({
+ path: historyPath,
+ operationType: "history_distill",
+ currentHash: historyCurrent.hash,
+ contents: historyPageContents({ project, rootIssue, issues, bundle }),
+ bundle,
+ confidence,
+ warnings,
+ humanReviewRequired: reviewRequired,
+ }));
+ }
+
+ const autoApplyRestriction = getDistillationAutoApplyRestriction();
+ const canAutoApply = await autoApplyEnabled(ctx, input.autoApply);
+ if (!canAutoApply || reviewRequired) {
+ const autoApplyWarning =
+ autoApplyRestriction.autoApplyRestriction
+ ?? "Auto-apply policy disabled; proposed patches require review.";
+ await recordPaperclipDistillationOutcome(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceSlug: space.slug,
+ runId: run.runId,
+ cursorId: run.cursorId,
+ status: "review_required",
+ sourceHash: bundle.sourceHash,
+ sourceWindowEnd: bundle.sourceWindowEnd,
+ warning: canAutoApply ? "Human review required by patch warnings." : autoApplyWarning,
+ });
+ return {
+ status: "review_required",
+ wikiId,
+ runId: run.runId,
+ cursorId: run.cursorId,
+ sourceHash: bundle.sourceHash,
+ patches,
+ appliedPages: [] as string[],
+ warnings: canAutoApply ? warnings : [autoApplyWarning, ...warnings],
+ };
+ }
+
+ const appliedPages: string[] = [];
+ for (const patch of patches) {
+ await writeWikiPage(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceSlug: space.slug,
+ path: patch.pagePath,
+ contents: patch.proposedContents,
+ expectedHash: patch.currentHash,
+ summary: `Paperclip distillation ${patch.operationType} from ${bundle.sourceHash}`,
+ sourceRefs: patch.sourceRefs,
+ });
+ await upsertPageBinding(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceId: space.id,
+ spaceSlug: space.slug,
+ projectId: scope.projectId,
+ rootIssueId: scope.rootIssueId,
+ pagePath: patch.pagePath,
+ sourceHash: bundle.sourceHash,
+ runId: run.runId,
+ metadata: { operationType: patch.operationType },
+ });
+ appliedPages.push(patch.pagePath);
+ }
+ await recordPaperclipDistillationOutcome(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceSlug: space.slug,
+ runId: run.runId,
+ cursorId: run.cursorId,
+ status: "succeeded",
+ sourceHash: bundle.sourceHash,
+ sourceWindowEnd: bundle.sourceWindowEnd,
+ });
+
+ return {
+ status: "applied",
+ wikiId,
+ runId: run.runId,
+ cursorId: run.cursorId,
+ sourceHash: bundle.sourceHash,
+ patches,
+ appliedPages,
+ warnings,
+ };
+}
+
+function truncateEventSource(contents: string, maxCharacters: number): string {
+ if (contents.length <= maxCharacters) return contents;
+ return `${contents.slice(0, maxCharacters)}\n\n[Truncated by LLM Wiki event ingestion policy at ${maxCharacters} characters.]\n`;
+}
+
+function eventPayload(event: PluginEvent): Record<string, unknown> {
+ return event.payload && typeof event.payload === "object" && !Array.isArray(event.payload)
+ ? event.payload as Record<string, unknown>
+ : {};
+}
+
+function sourceTitleForIssue(issue: Issue): string {
+ return issue.identifier ? `${issue.identifier} ${issue.title}` : issue.title;
+}
+
+function rawPathForPaperclipEvent(input: {
+ sourceKind: WikiEventIngestionSource;
+ issue: Issue;
+ label: string;
+ contents: string;
+ event: PluginEvent;
+}): string {
+ const identifier = input.issue.identifier ?? input.issue.id.slice(0, 8);
+ const eventDate = input.event.occurredAt.slice(0, 10);
+ return assertRawPath(`raw/paperclip/${input.sourceKind}/${eventDate}-${slugify(identifier)}-${slugify(input.label)}-${contentHash(input.contents).slice(0, 8)}.md`);
+}
+
+function formatIssueEventSource(issue: Issue, event: PluginEvent, maxCharacters: number): string {
+ return truncateEventSource([
+ `# Paperclip issue: ${sourceTitleForIssue(issue)}`,
+ "",
+ "## Provenance",
+ "",
+ `- Company ID: ${issue.companyId}`,
+ `- Issue ID: ${issue.id}`,
+ issue.identifier ? `- Issue identifier: ${issue.identifier}` : null,
+ `- Event type: ${event.eventType}`,
+ `- Event ID: ${event.eventId}`,
+ `- Event occurred at: ${event.occurredAt}`,
+ `- Status: ${issue.status}`,
+ `- Priority: ${issue.priority}`,
+ "",
+ "## Issue",
+ "",
+ issue.description?.trim() ? issue.description.trim() : "_No issue description._",
+ ].filter((line): line is string => line !== null).join("\n"), maxCharacters);
+}
+
+function formatCommentEventSource(issue: Issue, comment: IssueComment, event: PluginEvent, maxCharacters: number): string {
+ return truncateEventSource([
+ `# Paperclip comment on ${sourceTitleForIssue(issue)}`,
+ "",
+ "## Provenance",
+ "",
+ `- Company ID: ${issue.companyId}`,
+ `- Issue ID: ${issue.id}`,
+ issue.identifier ? `- Issue identifier: ${issue.identifier}` : null,
+ `- Comment ID: ${comment.id}`,
+ `- Event type: ${event.eventType}`,
+ `- Event ID: ${event.eventId}`,
+ `- Event occurred at: ${event.occurredAt}`,
+ "",
+ "## Comment",
+ "",
+ comment.body,
+ ].filter((line): line is string => line !== null).join("\n"), maxCharacters);
+}
+
+function formatDocumentEventSource(issue: Issue, document: IssueDocument, event: PluginEvent, maxCharacters: number): string {
+ return truncateEventSource([
+ `# Paperclip document: ${document.title ?? document.key}`,
+ "",
+ "## Provenance",
+ "",
+ `- Company ID: ${issue.companyId}`,
+ `- Issue ID: ${issue.id}`,
+ issue.identifier ? `- Issue identifier: ${issue.identifier}` : null,
+ `- Document ID: ${document.id}`,
+ `- Document key: ${document.key}`,
+ `- Event type: ${event.eventType}`,
+ `- Event ID: ${event.eventId}`,
+ `- Event occurred at: ${event.occurredAt}`,
+ `- Format: ${document.format}`,
+ `- Revision: ${document.latestRevisionNumber}`,
+ "",
+ "## Document",
+ "",
+ document.body,
+ ].filter((line): line is string => line !== null).join("\n"), maxCharacters);
+}
+
+async function recordPaperclipCursorObservation(ctx: PluginContext, input: {
+ companyId: string;
+ wikiId: string;
+ space: WikiSpace;
+ sourceKind: WikiEventIngestionSource;
+ sourceId: string;
+ issue: Issue;
+ event: PluginEvent;
+}): Promise<Extract<PaperclipEventIngestResult, { status: "recorded" }>> {
+ const cursorId = await upsertPaperclipDistillationCursor(ctx, {
+ companyId: input.companyId,
+ wikiId: input.wikiId,
+ spaceId: input.space.id,
+ projectId: input.issue.projectId ?? null,
+ rootIssueId: null,
+ observedAt: input.event.occurredAt,
+ metadata: {
+ lastEventId: input.event.eventId,
+ lastEventType: input.event.eventType,
+ lastSourceKind: input.sourceKind,
+ lastSourceId: input.sourceId,
+ lastIssueId: input.issue.id,
+ lastIssueIdentifier: input.issue.identifier ?? null,
+ },
+ });
+ await ctx.state.set(eventIngestionDedupKey(input.companyId, input.wikiId, input.space.id, input.sourceKind, input.sourceId), {
+ eventId: input.event.eventId,
+ cursorId,
+ issueId: input.issue.id,
+ spaceSlug: input.space.slug,
+ observedAt: new Date().toISOString(),
+ });
+ return {
+ status: "recorded",
+ sourceKind: input.sourceKind,
+ sourceId: input.sourceId,
+ cursorId,
+ issueId: input.issue.id,
+ };
+}
+
+async function paperclipProfileIncludesIssue(ctx: PluginContext, input: {
+ companyId: string;
+ issue: Issue;
+ profile: PaperclipIngestionProfileV1;
+}): Promise<boolean> {
+ for (const scope of input.profile.sourceScopes) {
+ if (scope.kind === "company_all") return true;
+ if (scope.kind === "selected_projects" && input.issue.projectId && scope.projectIds.includes(input.issue.projectId)) {
+ return true;
+ }
+ if (scope.kind === "active_projects" && input.issue.projectId) {
+ const project = await ctx.projects.get(input.issue.projectId, input.companyId);
+ const statuses = scope.statuses ?? ["in_progress"];
+ if (project && statuses.includes(project.status as "in_progress" | "todo" | "done") && isActiveDistillationProject(project)) {
+ return true;
+ }
+ }
+ if (scope.kind === "root_issues") {
+ for (const rootIssueId of scope.issueIds) {
+ if (input.issue.id === rootIssueId) return true;
+ const subtree = await ctx.issues.getSubtree(rootIssueId, input.companyId, { includeRoot: true });
+ if (subtree.issues.some((issue) => issue.id === input.issue.id)) return true;
+ }
+ }
+ }
+ return false;
+}
+
+async function routePaperclipCursorObservation(ctx: PluginContext, input: {
+ companyId: string;
+ sourceKind: WikiEventIngestionSource;
+ sourceId: string;
+ issue: Issue;
+ event: PluginEvent;
+}): Promise<PaperclipEventIngestResult> {
+ const { spaces } = await listSpaces(ctx, { companyId: input.companyId, wikiId: DEFAULT_WIKI_ID });
+ const recorded: Array<Extract<PaperclipEventIngestResult, { status: "recorded" }>> = [];
+ let eligibleProfileCount = 0;
+ for (const space of spaces) {
+ const profile = await profileForSpace(ctx, input.companyId, space);
+ if (!profile.enabled) continue;
+ const policy = evaluatePaperclipProfilePolicy({ space, profile, purpose: "event_routing", requireEnabledProfile: true });
+ if (!policy.allowed) continue;
+ if (!profile.sourceKinds[input.sourceKind]) continue;
+ if (!(await paperclipProfileIncludesIssue(ctx, { companyId: input.companyId, issue: input.issue, profile }))) continue;
+ eligibleProfileCount += 1;
+ if (eligibleProfileCount > MAX_PAPERCLIP_DISTILLATION_FAN_OUT) {
+ throw new Error(`Paperclip ingestion fan-out exceeds the hard cap of ${MAX_PAPERCLIP_DISTILLATION_FAN_OUT} enabled profiles.`);
+ }
+ if (await ctx.state.get(eventIngestionDedupKey(input.companyId, space.wikiId, space.id, input.sourceKind, input.sourceId))) {
+ continue;
+ }
+ recorded.push(await recordPaperclipCursorObservation(ctx, {
+ ...input,
+ wikiId: space.wikiId,
+ space,
+ }));
+ }
+ return recorded[0] ?? { status: "skipped", reason: "source_disabled" };
+}
+
+export async function handlePaperclipEventIngestion(ctx: PluginContext, event: PluginEvent): Promise<PaperclipEventIngestResult> {
+ const companyId = event.companyId;
+
+ const issueId = stringField(event.entityId);
+ if (!issueId) return { status: "skipped", reason: "unsupported_event" };
+ const issue = await ctx.issues.get(issueId, companyId);
+ if (!issue) return { status: "skipped", reason: "missing_issue" };
+ if (isLlmWikiOperationIssue(issue)) return { status: "skipped", reason: "plugin_operation" };
+
+ const payload = eventPayload(event);
+ if (event.eventType === "issue.created" || event.eventType === "issue.updated") {
+ const sourceId = `${event.eventType}:${issue.id}:${event.eventId}`;
+ return routePaperclipCursorObservation(ctx, {
+ companyId,
+ sourceKind: "issues",
+ sourceId,
+ issue,
+ event,
+ });
+ }
+
+ if (event.eventType === "issue.comment.created") {
+ const commentId = stringField(payload.commentId);
+ if (!commentId) return { status: "skipped", reason: "missing_comment" };
+ const sourceId = `comment:${commentId}`;
+ return routePaperclipCursorObservation(ctx, {
+ companyId,
+ sourceKind: "comments",
+ sourceId,
+ issue,
+ event,
+ });
+ }
+
+ if (event.eventType === "issue.document.created" || event.eventType === "issue.document.updated") {
+ const documentKey = stringField(payload.key) ?? stringField(payload.documentKey);
+ if (!documentKey) return { status: "skipped", reason: "missing_document" };
+ const revision = stringField(payload.revisionId) ?? stringField(payload.latestRevisionId) ?? stringField(payload.revisionNumber) ?? event.eventId;
+ const sourceId = `document:${issue.id}:${documentKey}:revision:${revision}`;
+ return routePaperclipCursorObservation(ctx, {
+ companyId,
+ sourceKind: "documents",
+ sourceId,
+ issue,
+ event,
+ });
+ }
+
+ return { status: "skipped", reason: "unsupported_event" };
+}
+
+function queryStreamChannel(operationId: string): string {
+ return `llm-wiki:query:${operationId}`;
+}
+
+function buildQueryPrompt(input: { companyId: string; wikiId: string; space: WikiSpace; question: string }): string {
+ return [
+ QUERY_PROMPT,
+ `Company ID: ${input.companyId}`,
+ `Wiki ID: ${input.wikiId}`,
+ `Space: ${input.space.displayName} (${input.space.slug})`,
+ `Space root: ${operationSpaceRoot(input.space)}`,
+ `Tool arguments: always pass wikiId \`${input.wikiId}\` and spaceSlug \`${input.space.slug}\`.`,
+ "Use the LLM Wiki plugin tools against that space only. Read wiki/index.md first with wiki_read_page, then use wiki_search, wiki_read_page, wiki_list_sources, and wiki_read_source as needed.",
+ "Cite the wiki page paths and raw source paths you used. If the wiki does not contain enough evidence, say that directly.",
+ `Question: ${input.question}`,
+ ].join("\n\n");
+}
+
+async function markOperation(ctx: PluginContext, input: {
+ companyId: string;
+ operationId: string;
+ status: string;
+ runId?: string | null;
+ warning?: string | null;
+ affectedPages?: unknown[] | null;
+ metadata?: Record<string, unknown> | null;
+}) {
+ await ctx.db.execute(
+ `UPDATE ${tableName(ctx.db.namespace, "wiki_operations")}
+ SET status = $3,
+ run_ids = CASE WHEN $4::jsonb = '[]'::jsonb THEN run_ids ELSE run_ids || $4::jsonb END,
+ warnings = CASE WHEN $5::jsonb = '[]'::jsonb THEN warnings ELSE warnings || $5::jsonb END,
+ affected_pages = CASE WHEN $6::jsonb = '[]'::jsonb THEN affected_pages ELSE $6::jsonb END,
+ metadata = metadata || $7::jsonb,
+ updated_at = now()
+ WHERE company_id = $1 AND id = $2`,
+ [
+ input.companyId,
+ input.operationId,
+ input.status,
+ jsonArrayParam(input.runId ? [input.runId] : []),
+ jsonArrayParam(input.warning ? [input.warning] : []),
+ jsonArrayParam(input.affectedPages ?? []),
+ jsonParam(input.metadata ?? {}),
+ ],
+ );
+}
+
+function isTerminalSessionEvent(event: AgentSessionEvent): boolean {
+ return event.eventType === "done" || event.eventType === "error";
+}
+
+export async function startWikiQuerySession(ctx: PluginContext, input: QuerySessionInput) {
+ const question = requireString(input.question, "question");
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const operation = await createOperationIssue(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceSlug: space.slug,
+ operationType: "query",
+ title: input.title ?? `Query LLM Wiki: ${question.slice(0, 72)}`,
+ prompt: question,
+ });
+ const agentId = operation.issue.assigneeAgentId;
+ const channel = queryStreamChannel(operation.operationId);
+
+ if (!agentId) {
+ const warning = "No configured Wiki Maintainer agent is available for this company.";
+ await markOperation(ctx, {
+ companyId: input.companyId,
+ operationId: operation.operationId,
+ status: "blocked",
+ warning,
+ });
+ await ctx.issues.update(operation.issue.id, { status: "blocked" }, input.companyId);
+ await ctx.issues.createComment(operation.issue.id, warning, input.companyId);
+ throw new Error(warning);
+ }
+
+ const agent = await ctx.agents.get(agentId, input.companyId);
+ if (!agent || agent.status === "paused" || agent.status === "terminated" || agent.status === "pending_approval") {
+ const warning = agent
+ ? `Wiki Maintainer agent is not invokable while status is ${agent.status}.`
+ : "Wiki Maintainer agent could not be loaded.";
+ await markOperation(ctx, {
+ companyId: input.companyId,
+ operationId: operation.operationId,
+ status: "blocked",
+ warning,
+ });
+ await ctx.issues.update(operation.issue.id, { status: "blocked" }, input.companyId);
+ await ctx.issues.createComment(operation.issue.id, warning, input.companyId);
+ throw new Error(warning);
+ }
+
+ const session = await ctx.agents.sessions.create(agentId, input.companyId, {
+ taskKey: `plugin:${PLUGIN_ID}:session:wiki:${wikiId}:query:${operation.operationId}`,
+ reason: "LLM Wiki query session",
+ });
+ await ctx.db.execute(
+ `INSERT INTO ${tableName(ctx.db.namespace, "wiki_query_sessions")}
+ (id, company_id, wiki_id, space_id, hidden_issue_id, agent_session_id, status, filed_outputs)
+ VALUES ($1, $2, $3, $6, $4, $5, 'active', '[]'::jsonb)`,
+ [operation.operationId, input.companyId, wikiId, operation.issue.id, session.sessionId, space.id],
+ );
+
+ const prompt = buildQueryPrompt({ companyId: input.companyId, wikiId, space, question });
+ ctx.streams.open(channel, input.companyId);
+ ctx.streams.emit(channel, {
+ type: "query.started",
+ operationId: operation.operationId,
+ querySessionId: operation.operationId,
+ issueId: operation.issue.id,
+ sessionId: session.sessionId,
+ question,
+ });
+
+ let answer = "";
+ const sendResult = await ctx.agents.sessions.sendMessage(session.sessionId, input.companyId, {
+ prompt,
+ reason: "LLM Wiki query",
+ onEvent: (event) => {
+ if (event.eventType === "chunk" && event.stream !== "stderr" && event.message) {
+ answer += event.message;
+ }
+ ctx.streams.emit(channel, {
+ type: "agent.event",
+ operationId: operation.operationId,
+ querySessionId: operation.operationId,
+ eventType: event.eventType,
+ stream: event.stream,
+ message: event.message,
+ payload: event.payload,
+ runId: event.runId,
+ seq: event.seq,
+ });
+ if (isTerminalSessionEvent(event)) {
+ const finalStatus = event.eventType === "done" ? "done" : "failed";
+ ctx.streams.emit(channel, {
+ type: event.eventType === "done" ? "query.done" : "query.error",
+ operationId: operation.operationId,
+ querySessionId: operation.operationId,
+ issueId: operation.issue.id,
+ sessionId: session.sessionId,
+ runId: event.runId,
+ answer,
+ message: event.message,
+ });
+ ctx.streams.close(channel);
+ void markOperation(ctx, {
+ companyId: input.companyId,
+ operationId: operation.operationId,
+ status: finalStatus,
+ runId: event.runId,
+ warning: event.eventType === "error" ? event.message : null,
+ metadata: { answerLength: answer.length },
+ });
+ void ctx.db.execute(
+ `UPDATE ${tableName(ctx.db.namespace, "wiki_query_sessions")}
+ SET status = $3,
+ updated_at = now()
+ WHERE company_id = $1 AND id = $2`,
+ [input.companyId, operation.operationId, finalStatus === "done" ? "completed" : "failed"],
+ );
+ void ctx.issues.createComment(
+ operation.issue.id,
+ event.eventType === "done"
+ ? `Query completed.\n\n${answer.trim() || "_No answer text was streamed._"}`
+ : `Query failed: ${event.message ?? "agent session ended with an error"}`,
+ input.companyId,
+ );
+ void ctx.issues.update(
+ operation.issue.id,
+ { status: event.eventType === "done" ? "done" : "blocked", originRunId: event.runId },
+ input.companyId,
+ );
+ }
+ },
+ });
+
+ await markOperation(ctx, {
+ companyId: input.companyId,
+ operationId: operation.operationId,
+ status: "running",
+ runId: sendResult.runId,
+ });
+ await ctx.issues.update(operation.issue.id, { originRunId: sendResult.runId }, input.companyId);
+
+ return {
+ status: "running",
+ wikiId,
+ spaceSlug: space.slug,
+ operationId: operation.operationId,
+ querySessionId: operation.operationId,
+ issue: operation.issue,
+ sessionId: session.sessionId,
+ runId: sendResult.runId,
+ channel,
+ };
+}
+
+export async function fileQueryAnswerAsPage(ctx: PluginContext, input: FileQueryAnswerInput) {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const path = assertPagePath(input.path);
+ const title = stringField(input.title) ?? inferTitle(path, input.contents ?? input.answer ?? "");
+ const answer = stringField(input.answer);
+ const contents = stringField(input.contents) ?? [
+ `# ${title}`,
+ "",
+ input.question ? `> Filed from query: ${input.question}` : null,
+ "",
+ answer ?? "",
+ ].filter((line): line is string => line !== null).join("\n").trimEnd() + "\n";
+ const operation = await createOperationIssue(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceSlug: space.slug,
+ operationType: "file-as-page",
+ title: `File LLM Wiki answer as ${path}`,
+ prompt: input.question ?? answer ?? `Write ${path}`,
+ });
+ const result = await writeWikiPage(ctx, {
+ companyId: input.companyId,
+ wikiId,
+ spaceSlug: space.slug,
+ path,
+ contents,
+ expectedHash: stringField(input.expectedHash),
+ summary: `Filed query answer as ${path}`,
+ sourceRefs: input.querySessionId ? [{ querySessionId: input.querySessionId }] : [],
+ operationId: operation.operationId,
+ });
+ const affectedPage = {
+ path,
+ title: result.title,
+ pageType: result.pageType,
+ revisionId: result.revisionId,
+ };
+ await markOperation(ctx, {
+ companyId: input.companyId,
+ operationId: operation.operationId,
+ status: "done",
+ affectedPages: [affectedPage],
+ metadata: { querySessionId: input.querySessionId ?? null },
+ });
+ await ctx.issues.update(operation.issue.id, { status: "done" }, input.companyId);
+ await ctx.issues.createComment(
+ operation.issue.id,
+ `Filed query answer as \`${path}\`.`,
+ input.companyId,
+ );
+
+ if (input.querySessionId) {
+ await ctx.db.execute(
+ `UPDATE ${tableName(ctx.db.namespace, "wiki_query_sessions")}
+ SET filed_outputs = filed_outputs || $3::jsonb,
+ updated_at = now()
+ WHERE company_id = $1 AND id = $2`,
+ [input.companyId, input.querySessionId, jsonArrayParam([affectedPage])],
+ );
+ }
+
+ return {
+ status: "ok",
+ wikiId,
+ spaceSlug: space.slug,
+ path,
+ operationId: operation.operationId,
+ issue: operation.issue,
+ page: affectedPage,
+ };
+}
+
+export async function registerWikiTools(ctx: PluginContext) {
+ ctx.tools.register("wiki_search", {
+ displayName: "Search Wiki",
+ description: "Search indexed wiki page and source metadata.",
+ parametersSchema: ctx.manifest.tools?.find((tool) => tool.name === "wiki_search")?.parametersSchema ?? { type: "object" },
+ }, async (params: unknown): Promise<ToolResult> => {
+ const input = params as ToolParams;
+ const companyId = requireString(input.companyId, "companyId");
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId, wikiId, spaceSlug: input.spaceSlug as string | null | undefined });
+ const query = requireString(input.query, "query");
+ const limit = normalizeLimit(input.limit, 20, 50);
+ const rows = await ctx.db.query<{ kind: string; path: string; title: string | null; match_text: string | null }>(
+ `SELECT 'page' AS kind, path, title, page_type AS match_text
+ FROM ${tableName(ctx.db.namespace, "wiki_pages")}
+ WHERE company_id = $1 AND wiki_id = $2 AND space_id = $5 AND (lower(path) LIKE lower($3) OR lower(coalesce(title, '')) LIKE lower($3))
+ UNION ALL
+ SELECT 'source' AS kind, raw_path AS path, title, source_type AS match_text
+ FROM ${tableName(ctx.db.namespace, "wiki_sources")}
+ WHERE company_id = $1 AND wiki_id = $2 AND space_id = $5 AND (lower(raw_path) LIKE lower($3) OR lower(coalesce(title, '')) LIKE lower($3) OR lower(coalesce(url, '')) LIKE lower($3))
+ ORDER BY kind, path
+ LIMIT $4`,
+ [companyId, wikiId, `%${query}%`, limit, space.id],
+ );
+ return {
+ content: rows.length ? rows.map((row) => `${row.kind}: ${row.path}${row.title ? ` - ${row.title}` : ""}`).join("\n") : "No wiki matches found.",
+ data: { companyId, wikiId, spaceSlug: space.slug, query, results: rows },
+ };
+ });
+
+ ctx.tools.register("wiki_read_page", {
+ displayName: "Read Wiki Page",
+ description: "Read a markdown wiki page from the configured local wiki root.",
+ parametersSchema: ctx.manifest.tools?.find((tool) => tool.name === "wiki_read_page")?.parametersSchema ?? { type: "object" },
+ }, async (params: unknown): Promise<ToolResult> => {
+ const input = params as ToolParams;
+ const companyId = requireString(input.companyId, "companyId");
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId, wikiId, spaceSlug: input.spaceSlug as string | null | undefined });
+ const path = assertPagePath(requireString(input.path, "path"));
+ const contents = await ctx.localFolders.readText(companyId, WIKI_ROOT_FOLDER_KEY, spaceRelativePath(space, path));
+ return { content: contents, data: { companyId, wikiId, spaceSlug: space.slug, path, hash: contentHash(contents) } };
+ });
+
+ ctx.tools.register("wiki_write_page", {
+ displayName: "Write Wiki Page",
+ description: "Atomically write a markdown wiki page after plugin path validation.",
+ parametersSchema: ctx.manifest.tools?.find((tool) => tool.name === "wiki_write_page")?.parametersSchema ?? { type: "object" },
+ }, async (params: unknown): Promise<ToolResult> => {
+ const input = params as ToolParams;
+ const result = await writeWikiPage(ctx, {
+ companyId: requireString(input.companyId, "companyId"),
+ wikiId: stringField(input.wikiId),
+ spaceSlug: stringField(input.spaceSlug),
+ path: requireString(input.path, "path"),
+ contents: requireString(input.contents, "contents"),
+ expectedHash: stringField(input.expectedHash),
+ summary: stringField(input.summary),
+ sourceRefs: input.sourceRefs,
+ });
+ return { content: `Wrote ${result.path}`, data: result };
+ });
+
+ ctx.tools.register("wiki_propose_patch", {
+ displayName: "Propose Wiki Patch",
+ description: "Return a structured proposed page write without changing files.",
+ parametersSchema: ctx.manifest.tools?.find((tool) => tool.name === "wiki_propose_patch")?.parametersSchema ?? { type: "object" },
+ }, async (params: unknown): Promise<ToolResult> => {
+ const input = params as ToolParams;
+ const companyId = requireString(input.companyId, "companyId");
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId, wikiId, spaceSlug: input.spaceSlug as string | null | undefined });
+ const path = assertPagePath(requireString(input.path, "path"));
+ const contents = requireString(input.contents, "contents");
+ const current = await readCurrentWithHash(ctx, companyId, path, space);
+ return {
+ content: `Proposed patch for ${path}`,
+ data: {
+ companyId,
+ wikiId,
+ spaceSlug: space.slug,
+ path,
+ summary: stringField(input.summary),
+ currentHash: current.hash,
+ proposedHash: contentHash(contents),
+ proposedContents: contents,
+ },
+ };
+ });
+
+ ctx.tools.register("wiki_list_sources", {
+ displayName: "List Wiki Sources",
+ description: "Return captured raw source metadata from the plugin index.",
+ parametersSchema: ctx.manifest.tools?.find((tool) => tool.name === "wiki_list_sources")?.parametersSchema ?? { type: "object" },
+ }, async (params: unknown): Promise<ToolResult> => {
+ const input = params as ToolParams;
+ const companyId = requireString(input.companyId, "companyId");
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId, wikiId, spaceSlug: input.spaceSlug as string | null | undefined });
+ const limit = normalizeLimit(input.limit, 50, 200);
+ const rows = await ctx.db.query<{ raw_path: string; title: string | null; source_type: string; url: string | null; content_hash: string }>(
+ `SELECT raw_path, title, source_type, url, content_hash
+ FROM ${tableName(ctx.db.namespace, "wiki_sources")}
+ WHERE company_id = $1 AND wiki_id = $2 AND space_id = $4
+ ORDER BY created_at DESC
+ LIMIT $3`,
+ [companyId, wikiId, limit, space.id],
+ );
+ return {
+ content: rows.length ? rows.map((row) => `${row.raw_path}${row.title ? ` - ${row.title}` : ""}`).join("\n") : "No sources captured yet.",
+ data: { companyId, wikiId, spaceSlug: space.slug, sources: rows },
+ };
+ });
+
+ ctx.tools.register("wiki_read_source", {
+ displayName: "Read Wiki Source",
+ description: "Read a captured raw source from the configured local wiki root.",
+ parametersSchema: ctx.manifest.tools?.find((tool) => tool.name === "wiki_read_source")?.parametersSchema ?? { type: "object" },
+ }, async (params: unknown): Promise<ToolResult> => {
+ const input = params as ToolParams;
+ const companyId = requireString(input.companyId, "companyId");
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId, wikiId, spaceSlug: input.spaceSlug as string | null | undefined });
+ const rawPath = assertRawPath(requireString(input.rawPath, "rawPath"));
+ const contents = await ctx.localFolders.readText(companyId, WIKI_ROOT_FOLDER_KEY, spaceRelativePath(space, rawPath));
+ return { content: contents, data: { companyId, wikiId, spaceSlug: space.slug, rawPath, hash: contentHash(contents) } };
+ });
+
+ ctx.tools.register("wiki_append_log", {
+ displayName: "Append Wiki Log",
+ description: "Append a maintenance note to wiki/log.md.",
+ parametersSchema: ctx.manifest.tools?.find((tool) => tool.name === "wiki_append_log")?.parametersSchema ?? { type: "object" },
+ }, async (params: unknown): Promise<ToolResult> => {
+ const input = params as ToolParams;
+ const companyId = requireString(input.companyId, "companyId");
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId, wikiId, spaceSlug: input.spaceSlug as string | null | undefined });
+ const entry = requireString(input.entry, "entry");
+ let current = "";
+ try {
+ current = await ctx.localFolders.readText(companyId, WIKI_ROOT_FOLDER_KEY, spaceRelativePath(space, "wiki/log.md"));
+ } catch {
+ current = "# Log\n\nAppend-only chronological record of wiki operations.\n";
+ }
+ const next = `${current.trimEnd()}\n\n- ${new Date().toISOString()} ${entry}\n`;
+ await ctx.localFolders.writeTextAtomic(companyId, WIKI_ROOT_FOLDER_KEY, spaceRelativePath(space, "wiki/log.md"), next);
+ await upsertPageMetadata(ctx, {
+ companyId,
+ wikiId,
+ spaceId: space.id,
+ path: "wiki/log.md",
+ contents: next,
+ summary: "Append log entry",
+ });
+ return { content: "Appended log entry", data: { companyId, wikiId, spaceSlug: space.slug, hash: contentHash(next) } };
+ });
+
+ ctx.tools.register("wiki_update_index", {
+ displayName: "Update Wiki Index",
+ description: "Atomically replace wiki/index.md with optional hash conflict checks.",
+ parametersSchema: ctx.manifest.tools?.find((tool) => tool.name === "wiki_update_index")?.parametersSchema ?? { type: "object" },
+ }, async (params: unknown): Promise<ToolResult> => {
+ const input = params as ToolParams;
+ const result = await writeWikiPage(ctx, {
+ companyId: requireString(input.companyId, "companyId"),
+ wikiId: stringField(input.wikiId),
+ spaceSlug: stringField(input.spaceSlug),
+ path: "wiki/index.md",
+ contents: requireString(input.contents, "contents"),
+ expectedHash: stringField(input.expectedHash),
+ summary: "Update index",
+ });
+ return { content: "Updated wiki/index.md", data: result };
+ });
+
+ ctx.tools.register("wiki_list_backlinks", {
+ displayName: "List Wiki Backlinks",
+ description: "Return indexed backlinks for a wiki page.",
+ parametersSchema: ctx.manifest.tools?.find((tool) => tool.name === "wiki_list_backlinks")?.parametersSchema ?? { type: "object" },
+ }, async (params: unknown): Promise<ToolResult> => {
+ const input = params as ToolParams;
+ const companyId = requireString(input.companyId, "companyId");
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId, wikiId, spaceSlug: input.spaceSlug as string | null | undefined });
+ const path = assertPagePath(requireString(input.path, "path"));
+ const rows = await ctx.db.query<{ path: string; title: string | null }>(
+ `SELECT path, title
+ FROM ${tableName(ctx.db.namespace, "wiki_pages")}
+ WHERE company_id = $1 AND wiki_id = $2 AND space_id = $4 AND backlinks ? $3
+ ORDER BY path
+ LIMIT 200`,
+ [companyId, wikiId, path, space.id],
+ );
+ return {
+ content: rows.length ? rows.map((row) => `${row.path}${row.title ? ` - ${row.title}` : ""}`).join("\n") : "No backlinks indexed.",
+ data: { companyId, wikiId, spaceSlug: space.slug, path, backlinks: rows },
+ };
+ });
+
+ ctx.tools.register("wiki_list_pages", {
+ displayName: "List Wiki Pages",
+ description: "Return the known page index from plugin metadata.",
+ parametersSchema: ctx.manifest.tools?.find((tool) => tool.name === "wiki_list_pages")?.parametersSchema ?? { type: "object" },
+ }, async (params: unknown): Promise<ToolResult> => {
+ const input = params as ToolParams;
+ const companyId = requireString(input.companyId, "companyId");
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId, wikiId, spaceSlug: input.spaceSlug as string | null | undefined });
+ const rows = await ctx.db.query<{ path: string; title: string | null; page_type: string | null }>(
+ `SELECT path, title, page_type FROM ${tableName(ctx.db.namespace, "wiki_pages")} WHERE company_id = $1 AND wiki_id = $2 AND space_id = $3 ORDER BY path LIMIT 200`,
+ [companyId, wikiId, space.id],
+ );
+ return {
+ content: rows.length ? rows.map((row) => `${row.path}${row.title ? ` - ${row.title}` : ""}`).join("\n") : "No pages indexed yet.",
+ data: { companyId, wikiId, spaceSlug: space.slug, pages: rows },
+ };
+ });
+}
+
+export function readCompanyIdFromParams(params: Record<string, unknown>): string {
+ return requireString(params.companyId, "companyId");
+}
+
+const TEMPLATE_FILES = ["AGENTS.md", "IDEA.md"] as const;
+type WikiTemplateFile = (typeof TEMPLATE_FILES)[number];
+
+function isTemplateFile(value: string): value is WikiTemplateFile {
+ return (TEMPLATE_FILES as readonly string[]).includes(value);
+}
+
+export type WikiPageRow = {
+ path: string;
+ title: string | null;
+ pageType: string | null;
+ backlinkCount: number;
+ sourceCount: number;
+ contentHash: string | null;
+ updatedAt: string;
+};
+
+export type WikiSourceRow = {
+ rawPath: string;
+ title: string | null;
+ sourceType: string;
+ url: string | null;
+ status: string;
+ createdAt: string;
+};
+
+const LOCAL_BROWSE_FILE_LIMIT = 2000;
+
+export type WikiOperationRow = {
+ id: string;
+ operationType: string;
+ status: string;
+ hiddenIssueId: string | null;
+ hiddenIssueIdentifier: string | null;
+ hiddenIssueTitle: string | null;
+ hiddenIssueStatus: string | null;
+ projectId: string | null;
+ runIds: unknown[];
+ costCents: number;
+ warnings: unknown[];
+ affectedPages: unknown[];
+ metadata: Record<string, unknown>;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export async function listPages(ctx: PluginContext, input: {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ pageType?: string | null;
+ includeRaw?: boolean;
+ limit?: number | null;
+}): Promise<{ pages: WikiPageRow[]; sources: WikiSourceRow[] }> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const limit = normalizeLimit(input.limit, 500, LOCAL_BROWSE_FILE_LIMIT);
+ const params: unknown[] = [input.companyId, wikiId, space.id];
+ let pageFilter = "";
+ if (input.pageType) {
+ params.push(input.pageType);
+ pageFilter = ` AND page_type = $${params.length}`;
+ }
+ params.push(limit);
+ const limitIndex = params.length;
+ const pageRows = await ctx.db.query<{
+ path: string;
+ title: string | null;
+ page_type: string | null;
+ backlinks: unknown;
+ source_refs: unknown;
+ content_hash: string | null;
+ updated_at: string;
+ }>(
+ `SELECT path, title, page_type, backlinks, source_refs, content_hash, updated_at::text AS updated_at
+ FROM ${tableName(ctx.db.namespace, "wiki_pages")}
+ WHERE company_id = $1 AND wiki_id = $2 AND space_id = $3${pageFilter}
+ ORDER BY path
+ LIMIT $${limitIndex}`,
+ params,
+ );
+ const readablePageRows = await filterReadableRows(ctx, input.companyId, space, pageRows, (row) => row.path);
+ const pages: WikiPageRow[] = readablePageRows.map((row) => ({
+ path: row.path,
+ title: row.title,
+ pageType: row.page_type,
+ backlinkCount: Array.isArray(row.backlinks) ? row.backlinks.length : 0,
+ sourceCount: Array.isArray(row.source_refs) ? row.source_refs.length : 0,
+ contentHash: row.content_hash,
+ updatedAt: row.updated_at,
+ }));
+ let pagesWithLocalFiles = pages;
+ if (!input.pageType) {
+ const wikiFiles = await listLocalFiles(ctx, { companyId: input.companyId, space, relativePath: "wiki" });
+ pagesWithLocalFiles = mergeLocalPageRows(pages, wikiFiles);
+ }
+
+ let sources: WikiSourceRow[] = [];
+ if (input.includeRaw) {
+ sources = (await listSources(ctx, { companyId: input.companyId, wikiId, spaceSlug: space.slug, limit, onlyReadable: true })).sources;
+ sources = mergeLocalSourceRows(sources, await listLocalFiles(ctx, { companyId: input.companyId, space, relativePath: "raw" }));
+ }
+ return { pages: pagesWithLocalFiles, sources };
+}
+
+export async function listSources(ctx: PluginContext, input: {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ limit?: number | null;
+ onlyReadable?: boolean;
+}): Promise<{ sources: WikiSourceRow[] }> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const limit = normalizeLimit(input.limit, 500, LOCAL_BROWSE_FILE_LIMIT);
+ const rows = await ctx.db.query<{ raw_path: string; title: string | null; source_type: string; url: string | null; status: string; created_at: string }>(
+ `SELECT raw_path, title, source_type, url, status, created_at::text AS created_at
+ FROM ${tableName(ctx.db.namespace, "wiki_sources")}
+ WHERE company_id = $1 AND wiki_id = $2 AND space_id = $4
+ ORDER BY created_at DESC
+ LIMIT $3`,
+ [input.companyId, wikiId, limit, space.id],
+ );
+ const sourceRows = input.onlyReadable
+ ? await filterReadableRows(ctx, input.companyId, space, rows, (row) => row.raw_path)
+ : rows;
+ return {
+ sources: sourceRows.map((row) => ({
+ rawPath: row.raw_path,
+ title: row.title,
+ sourceType: row.source_type,
+ url: row.url,
+ status: row.status,
+ createdAt: row.created_at,
+ })),
+ };
+}
+
+export async function readWikiPage(ctx: PluginContext, input: { companyId: string; wikiId?: string | null; spaceSlug?: string | null; path: string }) {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const path = assertWikiPath(input.path);
+ const contents = await ctx.localFolders.readText(input.companyId, WIKI_ROOT_FOLDER_KEY, spaceRelativePath(space, path));
+ const meta = await ctx.db.query<{ title: string | null; page_type: string | null; backlinks: unknown; source_refs: unknown; updated_at: string }>(
+ `SELECT title, page_type, backlinks, source_refs, updated_at::text AS updated_at
+ FROM ${tableName(ctx.db.namespace, "wiki_pages")}
+ WHERE company_id = $1 AND wiki_id = $2 AND space_id = $4 AND path = $3
+ LIMIT 1`,
+ [input.companyId, wikiId, path, space.id],
+ );
+ const row = meta[0] ?? null;
+ return {
+ wikiId,
+ spaceSlug: space.slug,
+ path,
+ contents,
+ title: row?.title ?? inferTitle(path, contents),
+ pageType: row?.page_type ?? inferPageType(path),
+ backlinks: Array.isArray(row?.backlinks) ? row?.backlinks : [],
+ sourceRefs: Array.isArray(row?.source_refs) ? row?.source_refs : [],
+ updatedAt: row?.updated_at ?? null,
+ hash: contentHash(contents),
+ };
+}
+
+export async function readTemplate(ctx: PluginContext, input: { companyId: string; path: string }) {
+ if (!isTemplateFile(input.path)) {
+ throw new Error(`template path must be one of ${TEMPLATE_FILES.join(", ")}`);
+ }
+ try {
+ const contents = await ctx.localFolders.readText(input.companyId, WIKI_ROOT_FOLDER_KEY, input.path);
+ return { path: input.path, contents, hash: contentHash(contents), exists: true };
+ } catch (error) {
+ return { path: input.path, contents: "", hash: null, exists: false, error: error instanceof Error ? error.message : String(error) };
+ }
+}
+
+export async function writeTemplate(ctx: PluginContext, input: { companyId: string; path: string; contents: string }) {
+ if (!isTemplateFile(input.path)) {
+ throw new Error(`template path must be one of ${TEMPLATE_FILES.join(", ")}`);
+ }
+ await ctx.localFolders.writeTextAtomic(input.companyId, WIKI_ROOT_FOLDER_KEY, input.path, input.contents);
+ return { status: "ok", path: input.path, hash: contentHash(input.contents) };
+}
+
+export type DistillationCursorRow = {
+ id: string;
+ sourceScope: string;
+ scopeKey: string;
+ projectId: string | null;
+ projectName: string | null;
+ projectColor: string | null;
+ rootIssueId: string | null;
+ rootIssueIdentifier: string | null;
+ rootIssueTitle: string | null;
+ lastProcessedAt: string | null;
+ lastObservedAt: string | null;
+ pendingEventCount: number;
+ lastSourceHash: string | null;
+ lastSuccessfulRunId: string | null;
+};
+
+export type DistillationRunRow = {
+ id: string;
+ cursorId: string | null;
+ workItemId: string | null;
+ projectId: string | null;
+ projectName: string | null;
+ rootIssueId: string | null;
+ rootIssueIdentifier: string | null;
+ sourceWindowStart: string | null;
+ sourceWindowEnd: string | null;
+ sourceHash: string | null;
+ status: string;
+ costCents: number;
+ retryCount: number;
+ warnings: string[];
+ metadata: Record<string, unknown>;
+ operationIssueId: string | null;
+ operationIssueIdentifier: string | null;
+ operationIssueTitle: string | null;
+ affectedPagePaths: string[];
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type DistillationWorkItemRow = {
+ id: string;
+ workItemKind: string;
+ status: string;
+ priority: string;
+ projectId: string | null;
+ rootIssueId: string | null;
+ metadata: Record<string, unknown>;
+ createdAt: string;
+ updatedAt: string;
+};
+
+export type DistillationPageBindingRow = {
+ id: string;
+ pagePath: string;
+ projectId: string | null;
+ projectName: string | null;
+ rootIssueId: string | null;
+ lastAppliedSourceHash: string | null;
+ lastDistillationRunId: string | null;
+ lastRunStatus: string | null;
+ lastRunCompletedAt: string | null;
+ lastRunSourceWindowEnd: string | null;
+ lastRunSourceHash: string | null;
+ metadata: Record<string, unknown>;
+ updatedAt: string;
+};
+
+export type DistillationSourceSnapshotRow = {
+ id: string;
+ distillationRunId: string;
+ sourceHash: string;
+ maxCharacters: number;
+ clipped: boolean;
+ sourceRefs: unknown[];
+ metadata: Record<string, unknown>;
+ createdAt: string;
+};
+
+export type DistillationOverview = {
+ cursors: DistillationCursorRow[];
+ runs: DistillationRunRow[];
+ workItems: DistillationWorkItemRow[];
+ pageBindings: DistillationPageBindingRow[];
+ reviewWorkItems: DistillationWorkItemRow[];
+ counts: {
+ cursors: number;
+ runningRuns: number;
+ failedRuns24h: number;
+ reviewRequired: number;
+ };
+};
+
+function jsonObject(value: unknown): Record<string, unknown> {
+ return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
+}
+
+function jsonArray(value: unknown): unknown[] {
+ return Array.isArray(value) ? value : [];
+}
+
+function affectedPagePathsFromRunMetadata(metadata: Record<string, unknown>, fallbackBindings: DistillationPageBindingRow[], runId: string): string[] {
+ const explicit = jsonArray(metadata.affectedPages ?? metadata.pagePaths ?? metadata.affected_pages)
+ .map((entry) => {
+ if (typeof entry === "string") return entry;
+ if (entry && typeof entry === "object") {
+ const path = (entry as Record<string, unknown>).path;
+ return typeof path === "string" ? path : null;
+ }
+ return null;
+ })
+ .filter((value): value is string => Boolean(value));
+ if (explicit.length > 0) return Array.from(new Set(explicit));
+ const bindings = fallbackBindings
+ .filter((binding) => binding.lastDistillationRunId === runId)
+ .map((binding) => binding.pagePath);
+ return Array.from(new Set(bindings));
+}
+
+export async function getDistillationOverview(ctx: PluginContext, input: {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ limit?: number | null;
+}): Promise<DistillationOverview> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const runLimit = normalizeLimit(input.limit ?? 25, 25, 200);
+ const cursorRows = await ctx.db.query<{
+ id: string;
+ source_scope: string;
+ scope_key: string;
+ project_id: string | null;
+ project_name: string | null;
+ project_color: string | null;
+ root_issue_id: string | null;
+ root_issue_identifier: string | null;
+ root_issue_title: string | null;
+ last_processed_at: string | null;
+ last_observed_at: string | null;
+ pending_event_count: number;
+ last_source_hash: string | null;
+ last_successful_run_id: string | null;
+ }>(
+ `SELECT cursor.id,
+ cursor.source_scope,
+ cursor.scope_key,
+ cursor.project_id,
+ project.name AS project_name,
+ project.color AS project_color,
+ cursor.root_issue_id,
+ issue.identifier AS root_issue_identifier,
+ issue.title AS root_issue_title,
+ cursor.last_processed_at::text AS last_processed_at,
+ cursor.last_observed_at::text AS last_observed_at,
+ cursor.pending_event_count,
+ cursor.last_source_hash,
+ cursor.last_successful_run_id
+ FROM ${distillationCursorTable(ctx)} cursor
+ LEFT JOIN public.projects project ON project.id = cursor.project_id
+ LEFT JOIN public.issues issue ON issue.id = cursor.root_issue_id
+ WHERE cursor.company_id = $1 AND cursor.wiki_id = $2 AND cursor.space_id = $3
+ ORDER BY cursor.updated_at DESC
+ LIMIT 200`,
+ [input.companyId, wikiId, space.id],
+ );
+
+ const runRows = await ctx.db.query<{
+ id: string;
+ cursor_id: string | null;
+ work_item_id: string | null;
+ project_id: string | null;
+ project_name: string | null;
+ root_issue_id: string | null;
+ root_issue_identifier: string | null;
+ source_window_start: string | null;
+ source_window_end: string | null;
+ source_hash: string | null;
+ status: string;
+ cost_cents: number;
+ retry_count: number;
+ warnings: unknown;
+ metadata: unknown;
+ operation_issue_id: string | null;
+ operation_issue_identifier: string | null;
+ operation_issue_title: string | null;
+ created_at: string;
+ updated_at: string;
+ }>(
+ `SELECT run.id,
+ run.cursor_id,
+ run.work_item_id,
+ run.project_id,
+ project.name AS project_name,
+ run.root_issue_id,
+ root_issue.identifier AS root_issue_identifier,
+ run.source_window_start::text AS source_window_start,
+ run.source_window_end::text AS source_window_end,
+ run.source_hash,
+ run.status,
+ run.cost_cents,
+ run.retry_count,
+ run.warnings,
+ run.metadata,
+ run.operation_issue_id,
+ op_issue.identifier AS operation_issue_identifier,
+ op_issue.title AS operation_issue_title,
+ run.created_at::text AS created_at,
+ run.updated_at::text AS updated_at
+ FROM ${distillationRunTable(ctx)} run
+ LEFT JOIN public.projects project ON project.id = run.project_id
+ LEFT JOIN public.issues root_issue ON root_issue.id = run.root_issue_id
+ LEFT JOIN public.issues op_issue ON op_issue.id = run.operation_issue_id
+ WHERE run.company_id = $1 AND run.wiki_id = $2 AND run.space_id = $4
+ ORDER BY run.created_at DESC
+ LIMIT $3`,
+ [input.companyId, wikiId, runLimit, space.id],
+ );
+
+ const workItemRows = await ctx.db.query<{
+ id: string;
+ work_item_kind: string;
+ status: string;
+ priority: string;
+ project_id: string | null;
+ root_issue_id: string | null;
+ metadata: unknown;
+ created_at: string;
+ updated_at: string;
+ }>(
+ `SELECT id, work_item_kind, status, priority, project_id, root_issue_id, metadata,
+ created_at::text AS created_at, updated_at::text AS updated_at
+ FROM ${distillationWorkItemTable(ctx)}
+ WHERE company_id = $1 AND wiki_id = $2 AND space_id = $3 AND status IN ('pending', 'review_required', 'in_progress', 'failed')
+ ORDER BY created_at DESC
+ LIMIT 100`,
+ [input.companyId, wikiId, space.id],
+ );
+
+ const bindingRows = await ctx.db.query<{
+ id: string;
+ page_path: string;
+ project_id: string | null;
+ project_name: string | null;
+ root_issue_id: string | null;
+ last_applied_source_hash: string | null;
+ last_distillation_run_id: string | null;
+ last_run_status: string | null;
+ last_run_completed_at: string | null;
+ last_run_source_window_end: string | null;
+ last_run_source_hash: string | null;
+ metadata: unknown;
+ updated_at: string;
+ }>(
+ `SELECT binding.id,
+ binding.page_path,
+ binding.project_id,
+ project.name AS project_name,
+ binding.root_issue_id,
+ binding.last_applied_source_hash,
+ binding.last_distillation_run_id,
+ run.status::text AS last_run_status,
+ run.updated_at::text AS last_run_completed_at,
+ run.source_window_end::text AS last_run_source_window_end,
+ run.source_hash AS last_run_source_hash,
+ binding.metadata,
+ binding.updated_at::text AS updated_at
+ FROM ${pageBindingTable(ctx)} binding
+ LEFT JOIN public.projects project ON project.id = binding.project_id
+ LEFT JOIN ${distillationRunTable(ctx)} run ON run.id = binding.last_distillation_run_id
+ WHERE binding.company_id = $1 AND binding.wiki_id = $2 AND binding.space_id = $3
+ ORDER BY binding.updated_at DESC
+ LIMIT 200`,
+ [input.companyId, wikiId, space.id],
+ );
+
+ const cursors: DistillationCursorRow[] = cursorRows.map((row) => ({
+ id: row.id,
+ sourceScope: row.source_scope,
+ scopeKey: row.scope_key,
+ projectId: row.project_id,
+ projectName: row.project_name,
+ projectColor: row.project_color,
+ rootIssueId: row.root_issue_id,
+ rootIssueIdentifier: row.root_issue_identifier,
+ rootIssueTitle: row.root_issue_title,
+ lastProcessedAt: row.last_processed_at,
+ lastObservedAt: row.last_observed_at,
+ pendingEventCount: Number(row.pending_event_count ?? 0),
+ lastSourceHash: row.last_source_hash,
+ lastSuccessfulRunId: row.last_successful_run_id,
+ }));
+
+ const pageBindings: DistillationPageBindingRow[] = bindingRows.map((row) => ({
+ id: row.id,
+ pagePath: row.page_path,
+ projectId: row.project_id,
+ projectName: row.project_name,
+ rootIssueId: row.root_issue_id,
+ lastAppliedSourceHash: row.last_applied_source_hash,
+ lastDistillationRunId: row.last_distillation_run_id,
+ lastRunStatus: row.last_run_status,
+ lastRunCompletedAt: row.last_run_completed_at,
+ lastRunSourceWindowEnd: row.last_run_source_window_end,
+ lastRunSourceHash: row.last_run_source_hash,
+ metadata: jsonObject(row.metadata),
+ updatedAt: row.updated_at,
+ }));
+
+ const runs: DistillationRunRow[] = runRows.map((row) => {
+ const metadata = jsonObject(row.metadata);
+ return {
+ id: row.id,
+ cursorId: row.cursor_id,
+ workItemId: row.work_item_id,
+ projectId: row.project_id,
+ projectName: row.project_name,
+ rootIssueId: row.root_issue_id,
+ rootIssueIdentifier: row.root_issue_identifier,
+ sourceWindowStart: row.source_window_start,
+ sourceWindowEnd: row.source_window_end,
+ sourceHash: row.source_hash,
+ status: row.status,
+ costCents: Number(row.cost_cents ?? 0),
+ retryCount: Number(row.retry_count ?? 0),
+ warnings: jsonArray(row.warnings).map((entry) => (typeof entry === "string" ? entry : JSON.stringify(entry))),
+ metadata,
+ operationIssueId: row.operation_issue_id,
+ operationIssueIdentifier: row.operation_issue_identifier,
+ operationIssueTitle: row.operation_issue_title,
+ affectedPagePaths: affectedPagePathsFromRunMetadata(metadata, pageBindings, row.id),
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ };
+ });
+
+ const workItems: DistillationWorkItemRow[] = workItemRows.map((row) => ({
+ id: row.id,
+ workItemKind: row.work_item_kind,
+ status: row.status,
+ priority: row.priority,
+ projectId: row.project_id,
+ rootIssueId: row.root_issue_id,
+ metadata: jsonObject(row.metadata),
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ }));
+
+ const reviewWorkItems = workItems.filter((item) => item.status === "review_required" || item.workItemKind === "review");
+ const failedSince = Date.now() - 24 * 60 * 60 * 1000;
+ const failedRuns24h = runs.filter((run) => {
+ if (run.status !== "failed" && run.status !== "refused_cost_cap") return false;
+ const updatedAt = run.updatedAt ? Date.parse(run.updatedAt) : Number.NaN;
+ return Number.isFinite(updatedAt) ? updatedAt >= failedSince : true;
+ }).length;
+
+ return {
+ cursors,
+ runs,
+ workItems,
+ pageBindings,
+ reviewWorkItems,
+ counts: {
+ cursors: cursors.length,
+ runningRuns: runs.filter((run) => run.status === "running").length,
+ failedRuns24h,
+ reviewRequired: reviewWorkItems.length,
+ },
+ };
+}
+
+export async function getDistillationPageProvenance(ctx: PluginContext, input: {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ pagePath: string;
+}): Promise<{
+ binding: DistillationPageBindingRow | null;
+ runs: DistillationRunRow[];
+ snapshot: DistillationSourceSnapshotRow | null;
+ cursor: DistillationCursorRow | null;
+}> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const overview = await getDistillationOverview(ctx, { companyId: input.companyId, wikiId, spaceSlug: space.slug });
+ const binding = overview.pageBindings.find((row) => row.pagePath === input.pagePath) ?? null;
+ if (!binding) {
+ return { binding: null, runs: [], snapshot: null, cursor: null };
+ }
+ const relatedRuns = overview.runs.filter((run) => {
+ if (binding.lastDistillationRunId === run.id) return true;
+ if (binding.projectId && run.projectId === binding.projectId) return true;
+ if (binding.rootIssueId && run.rootIssueId === binding.rootIssueId) return true;
+ return run.affectedPagePaths.includes(binding.pagePath);
+ });
+ const cursor = overview.cursors.find((row) => {
+ if (binding.rootIssueId && row.rootIssueId === binding.rootIssueId) return true;
+ if (binding.projectId && row.projectId === binding.projectId) return true;
+ return false;
+ }) ?? null;
+
+ let snapshot: DistillationSourceSnapshotRow | null = null;
+ if (binding.lastDistillationRunId) {
+ const snapshotRows = await ctx.db.query<{
+ id: string;
+ distillation_run_id: string;
+ source_hash: string;
+ max_characters: number;
+ clipped: boolean;
+ source_refs: unknown;
+ metadata: unknown;
+ created_at: string;
+ }>(
+ `SELECT id, distillation_run_id, source_hash, max_characters, clipped, source_refs, metadata, created_at::text AS created_at
+ FROM ${sourceSnapshotTable(ctx)}
+ WHERE company_id = $1 AND wiki_id = $2 AND space_id = $4 AND distillation_run_id = $3
+ ORDER BY created_at DESC
+ LIMIT 1`,
+ [input.companyId, wikiId, binding.lastDistillationRunId, space.id],
+ );
+ if (snapshotRows[0]) {
+ const row = snapshotRows[0];
+ snapshot = {
+ id: row.id,
+ distillationRunId: row.distillation_run_id,
+ sourceHash: row.source_hash,
+ maxCharacters: Number(row.max_characters ?? 0),
+ clipped: Boolean(row.clipped),
+ sourceRefs: jsonArray(row.source_refs),
+ metadata: jsonObject(row.metadata),
+ createdAt: row.created_at,
+ };
+ }
+ }
+
+ return { binding, runs: relatedRuns, snapshot, cursor };
+}
+
+export async function listOperations(ctx: PluginContext, input: {
+ companyId: string;
+ wikiId?: string | null;
+ spaceSlug?: string | null;
+ operationType?: string | null;
+ status?: string | null;
+ limit?: number | null;
+}): Promise<{ operations: WikiOperationRow[] }> {
+ const wikiId = normalizeWikiId(input.wikiId);
+ const space = await resolveSpace(ctx, { companyId: input.companyId, wikiId, spaceSlug: input.spaceSlug });
+ const limit = normalizeLimit(input.limit, 50, 500);
+ const params: unknown[] = [input.companyId, wikiId, space.id];
+ const filters: string[] = [];
+ if (input.operationType && input.operationType !== "all") {
+ params.push(input.operationType);
+ filters.push(`op.operation_type = $${params.length}`);
+ }
+ if (input.status && input.status !== "all") {
+ params.push(input.status);
+ filters.push(`op.status = $${params.length}`);
+ }
+ params.push(limit);
+ const filterSql = filters.length ? ` AND ${filters.join(" AND ")}` : "";
+ const rows = await ctx.db.query<{
+ id: string;
+ operation_type: string;
+ status: string;
+ hidden_issue_id: string | null;
+ hidden_issue_identifier: string | null;
+ hidden_issue_title: string | null;
+ hidden_issue_status: string | null;
+ project_id: string | null;
+ run_ids: unknown;
+ cost_cents: number;
+ warnings: unknown;
+ affected_pages: unknown;
+ metadata: unknown;
+ created_at: string;
+ updated_at: string;
+ }>(
+ `SELECT op.id, op.operation_type, op.status, op.hidden_issue_id, op.project_id,
+ op.run_ids, op.cost_cents, op.warnings, op.affected_pages, op.metadata,
+ op.created_at::text AS created_at, op.updated_at::text AS updated_at,
+ issue.identifier AS hidden_issue_identifier,
+ issue.title AS hidden_issue_title,
+ issue.status::text AS hidden_issue_status
+ FROM ${tableName(ctx.db.namespace, "wiki_operations")} op
+ LEFT JOIN public.issues issue ON issue.id = op.hidden_issue_id
+ WHERE op.company_id = $1 AND op.wiki_id = $2 AND op.space_id = $3${filterSql}
+ ORDER BY op.created_at DESC
+ LIMIT $${params.length}`,
+ params,
+ );
+ return {
+ operations: rows.map((row) => ({
+ id: row.id,
+ operationType: row.operation_type,
+ status: row.status,
+ hiddenIssueId: row.hidden_issue_id,
+ hiddenIssueIdentifier: row.hidden_issue_identifier,
+ hiddenIssueTitle: row.hidden_issue_title,
+ hiddenIssueStatus: row.hidden_issue_status,
+ projectId: row.project_id,
+ runIds: Array.isArray(row.run_ids) ? row.run_ids : [],
+ costCents: Number(row.cost_cents ?? 0),
+ warnings: Array.isArray(row.warnings) ? row.warnings : [],
+ affectedPages: Array.isArray(row.affected_pages) ? row.affected_pages : [],
+ metadata: jsonObject(row.metadata),
+ createdAt: row.created_at,
+ updatedAt: row.updated_at,
+ })),
+ };
+}
diff --git a/packages/plugins/plugin-llm-wiki/src/worker.ts b/packages/plugins/plugin-llm-wiki/src/worker.ts
new file mode 100644
index 0000000000..0335b31b6e
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/src/worker.ts
@@ -0,0 +1,1081 @@
+import {
+ definePlugin,
+ runWorker,
+ type PluginApiRequestInput,
+ type PluginContext,
+ type PluginManagedRoutineDeclaration,
+ type PluginManagedRoutineResolution,
+} from "@paperclipai/plugin-sdk";
+import {
+ PAPERCLIP_DISTILL_SKILL_KEY,
+ WIKI_MAINTENANCE_ROUTINE_KEYS,
+ WIKI_ROOT_FOLDER_KEY,
+} from "./manifest.js";
+import {
+ bootstrapWikiRoot,
+ bootstrapSpace,
+ assemblePaperclipSourceBundle,
+ archiveSpace,
+ captureWikiSource,
+ createSpace,
+ createPaperclipDistillationRun,
+ createPaperclipDistillationWorkItem,
+ createOperationIssue,
+ distillPaperclipProjectPage,
+ enableActiveProjectDistillation,
+ fileQueryAnswerAsPage,
+ getDistillationOverview,
+ getDistillationPageProvenance,
+ getDistillationAutoApplyRestriction,
+ getEventIngestionSettings,
+ listPaperclipIngestionCandidates,
+ getPaperclipIngestionProfile,
+ getOverview,
+ listSpaces,
+ handlePaperclipEventIngestion,
+ listWikiAgentOptions,
+ listWikiProjectOptions,
+ listOperations,
+ listPages,
+ listSources,
+ readCompanyIdFromParams,
+ readTemplate,
+ readWikiPage,
+ recordPaperclipDistillationOutcome,
+ reconcileWikiAgentResource,
+ reconcileWikiProjectResource,
+ reconcileWikiRoutineResources,
+ reconcileWikiSkillResources,
+ registerWikiTools,
+ resetWikiSkillResources,
+ resetWikiAgentResource,
+ resetWikiProjectResource,
+ selectWikiAgentResource,
+ selectWikiProjectResource,
+ startWikiQuerySession,
+ spaceFolderStatus,
+ updateEventIngestionSettings,
+ updatePaperclipIngestionProfile,
+ updateSpace,
+ writeTemplate,
+ writeWikiPage,
+} from "./wiki.js";
+
+function stringField(value: unknown): string | null {
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
+}
+
+function routineKeyField(value: unknown): (typeof WIKI_MAINTENANCE_ROUTINE_KEYS)[number] {
+ const routineKey = stringField(value);
+ if (!routineKey) {
+ throw new Error(`routineKey is required; valid values: ${WIKI_MAINTENANCE_ROUTINE_KEYS.join(", ")}`);
+ }
+ if (!WIKI_MAINTENANCE_ROUTINE_KEYS.includes(routineKey as (typeof WIKI_MAINTENANCE_ROUTINE_KEYS)[number])) {
+ throw new Error(`Unknown managed routine: ${routineKey}`);
+ }
+ return routineKey as (typeof WIKI_MAINTENANCE_ROUTINE_KEYS)[number];
+}
+
+function routineOverridesFromParams(params: Record<string, unknown>) {
+ const overrides: { assigneeAgentId?: string; projectId?: string } = {};
+ const assigneeAgentId = stringField(params.assigneeAgentId);
+ const projectId = stringField(params.projectId);
+ if (assigneeAgentId) overrides.assigneeAgentId = assigneeAgentId;
+ if (projectId) overrides.projectId = projectId;
+ return overrides;
+}
+
+let activeContext: PluginContext | null = null;
+const PAPERCLIP_EVENT_INGESTION_EVENTS = [
+ "issue.created",
+ "issue.updated",
+ "issue.comment.created",
+ "issue.document.created",
+ "issue.document.updated",
+] as const;
+
+type ManagedRoutineDefaultDrift = {
+ changedFields: string[];
+ defaultTitle: string;
+ defaultDescription: string | null;
+};
+
+type ManagedRoutineSettingsResolution = PluginManagedRoutineResolution & {
+ defaultDrift: ManagedRoutineDefaultDrift | null;
+};
+
+function requireContext(): PluginContext {
+ if (!activeContext) throw new Error("LLM Wiki plugin has not been set up");
+ return activeContext;
+}
+
+function normalizeRoutineTemplateText(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const normalized = value.replace(/\r\n/g, "\n").trim();
+ return normalized.length > 0 ? normalized : null;
+}
+
+function manualDistillScopeLabel(input: { projectId?: string | null; rootIssueId?: string | null }) {
+ if (input.rootIssueId) return "selected root issue";
+ if (input.projectId) return "selected project";
+ return "company-wide stale cursor scan";
+}
+
+function buildManualDistillPrompt(input: { companyId: string; projectId?: string | null; rootIssueId?: string | null }) {
+ const scopeLabel = manualDistillScopeLabel(input);
+ return [
+ "Manual LLM Wiki distillation requested outside recurring cadence.",
+ "",
+ "Prompt source: LLM Wiki plugin action `distill-paperclip-now` (`packages/plugins/plugin-llm-wiki/src/worker.ts`).",
+ `Required skill: use the installed \`${PAPERCLIP_DISTILL_SKILL_KEY}\` skill before changing wiki files.`,
+ "",
+ "Scope:",
+ `- Company ID: ${input.companyId}`,
+ `- Requested scope: ${scopeLabel}`,
+ input.projectId ? `- Source project ID: ${input.projectId}` : null,
+ input.rootIssueId ? `- Source root issue ID: ${input.rootIssueId}` : null,
+ !input.projectId && !input.rootIssueId
+ ? "- Do not hardcode a single project. Find non-plugin Paperclip issues/comments/documents that changed in any project after the last processed cursor and are old enough for the stale/debounce threshold."
+ : null,
+ "",
+ "Process:",
+ "1. Read the wiki root AGENTS.md, wiki/index.md, and recent wiki/log.md entries.",
+ "2. Assemble bounded Paperclip source bundles for every eligible project or root issue, excluding LLM Wiki plugin-operation issues.",
+ "3. Turn durable signal into project standups, wiki-insightful project pages, decisions, history, index, and log updates per the paperclip-distill skill.",
+ "4. Surface clipped, low-signal, stale-hash, or source-window warnings instead of hiding them.",
+ ].filter((line): line is string => line !== null).join("\n");
+}
+
+function withManagedRoutineDefaultDrift(
+ routine: PluginManagedRoutineResolution,
+ declaration: PluginManagedRoutineDeclaration | undefined,
+): ManagedRoutineSettingsResolution {
+ if (!routine.routine || !declaration) {
+ return { ...routine, defaultDrift: null };
+ }
+
+ const changedFields: string[] = [];
+ if (normalizeRoutineTemplateText(routine.routine.title) !== normalizeRoutineTemplateText(declaration.title)) {
+ changedFields.push("title");
+ }
+ if (normalizeRoutineTemplateText(routine.routine.description) !== normalizeRoutineTemplateText(declaration.description ?? null)) {
+ changedFields.push("description");
+ }
+ if (routine.routine.priority !== (declaration.priority ?? "medium")) {
+ changedFields.push("priority");
+ }
+ if (routine.routine.concurrencyPolicy !== (declaration.concurrencyPolicy ?? "coalesce_if_active")) {
+ changedFields.push("concurrency policy");
+ }
+ if (routine.routine.catchUpPolicy !== (declaration.catchUpPolicy ?? "skip_missed")) {
+ changedFields.push("catch-up policy");
+ }
+
+ return {
+ ...routine,
+ defaultDrift: changedFields.length > 0
+ ? {
+ changedFields,
+ defaultTitle: declaration.title,
+ defaultDescription: declaration.description ?? null,
+ }
+ : null,
+ };
+}
+
+const plugin = definePlugin({
+ async setup(ctx) {
+ activeContext = ctx;
+ await registerWikiTools(ctx);
+
+ for (const eventName of PAPERCLIP_EVENT_INGESTION_EVENTS) {
+ ctx.events.on(eventName, async (event) => {
+ const result = await handlePaperclipEventIngestion(ctx, event);
+ if (result.status === "recorded") {
+ ctx.logger.info("LLM Wiki recorded Paperclip event for cursor discovery", {
+ eventType: event.eventType,
+ companyId: event.companyId,
+ sourceKind: result.sourceKind,
+ sourceId: result.sourceId,
+ cursorId: result.cursorId,
+ });
+ }
+ });
+ }
+
+ ctx.data.register("overview", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ return getOverview(ctx, companyId);
+ });
+
+ ctx.data.register("health", async (params) => {
+ const companyId = stringField(params.companyId);
+ return companyId
+ ? getOverview(ctx, companyId)
+ : { status: "ok", checkedAt: new Date().toISOString(), message: "LLM Wiki worker is running" };
+ });
+
+ ctx.actions.register("bootstrap-root", async (params) => {
+ return bootstrapWikiRoot(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ path: stringField(params.path),
+ });
+ });
+
+ ctx.data.register("spaces", async (params) => {
+ return listSpaces(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ });
+ });
+
+ ctx.data.register("space", async (params) => {
+ return spaceFolderStatus(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ });
+ });
+
+ ctx.actions.register("create-space", async (params) => {
+ return createSpace(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ slug: stringField(params.slug),
+ displayName: stringField(params.displayName),
+ folderMode: stringField(params.folderMode) as "managed_subfolder" | "existing_local_folder" | null,
+ accessScope: stringField(params.accessScope) as "shared" | "personal" | "team" | null,
+ settings: typeof params.settings === "object" && params.settings != null ? params.settings as Record<string, unknown> : null,
+ });
+ });
+
+ ctx.actions.register("update-space", async (params) => {
+ return updateSpace(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ displayName: stringField(params.displayName),
+ status: stringField(params.status) as "active" | "archived" | null,
+ settings: typeof params.settings === "object" && params.settings != null ? params.settings as Record<string, unknown> : null,
+ });
+ });
+
+ ctx.actions.register("bootstrap-space", async (params) => {
+ return bootstrapSpace(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ });
+ });
+
+ ctx.actions.register("archive-space", async (params) => {
+ return archiveSpace(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ });
+ });
+
+ ctx.actions.register("create-operation", async (params) => {
+ const operationType = stringField(params.operationType);
+ if (
+ operationType !== "ingest" &&
+ operationType !== "query" &&
+ operationType !== "lint" &&
+ operationType !== "file-as-page" &&
+ operationType !== "index" &&
+ operationType !== "distill" &&
+ operationType !== "backfill"
+ ) {
+ throw new Error("operationType must be ingest, query, lint, file-as-page, index, distill, or backfill");
+ }
+ return createOperationIssue(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ operationType,
+ title: stringField(params.title),
+ prompt: stringField(params.prompt),
+ useCheapModelProfile: params.useCheapModelProfile === true,
+ });
+ });
+
+ ctx.actions.register("capture-source", async (params) => {
+ return captureWikiSource(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ sourceType: stringField(params.sourceType),
+ title: stringField(params.title),
+ url: stringField(params.url),
+ contents: typeof params.contents === "string" ? params.contents : "",
+ rawPath: stringField(params.rawPath),
+ metadata: typeof params.metadata === "object" && params.metadata != null ? params.metadata as Record<string, unknown> : null,
+ });
+ });
+
+ ctx.actions.register("write-page", async (params) => {
+ return writeWikiPage(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ path: stringField(params.path) ?? "",
+ contents: typeof params.contents === "string" ? params.contents : "",
+ expectedHash: stringField(params.expectedHash),
+ summary: stringField(params.summary),
+ sourceRefs: params.sourceRefs,
+ writer: "board_ui",
+ });
+ });
+
+ ctx.actions.register("write-template", async (params) => {
+ return writeTemplate(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ path: stringField(params.path) ?? "",
+ contents: typeof params.contents === "string" ? params.contents : "",
+ });
+ });
+
+ ctx.actions.register("update-event-ingestion-settings", async (params) => {
+ const requestedSources = typeof params.sources === "object" && params.sources != null && !Array.isArray(params.sources)
+ ? params.sources as Record<string, unknown>
+ : null;
+ const sources: { issues?: boolean; comments?: boolean; documents?: boolean } = {};
+ if (requestedSources && Object.prototype.hasOwnProperty.call(requestedSources, "issues")) {
+ sources.issues = requestedSources.issues === true;
+ }
+ if (requestedSources && Object.prototype.hasOwnProperty.call(requestedSources, "comments")) {
+ sources.comments = requestedSources.comments === true;
+ }
+ if (requestedSources && Object.prototype.hasOwnProperty.call(requestedSources, "documents")) {
+ sources.documents = requestedSources.documents === true;
+ }
+ const settings: {
+ enabled?: boolean;
+ wikiId?: string;
+ maxCharacters?: number;
+ sources?: typeof sources;
+ } = {
+ wikiId: stringField(params.wikiId) ?? undefined,
+ maxCharacters: typeof params.maxCharacters === "number" ? params.maxCharacters : undefined,
+ };
+ if (typeof params.enabled === "boolean") {
+ settings.enabled = params.enabled;
+ }
+ if (Object.keys(sources).length > 0) {
+ settings.sources = sources;
+ }
+ return updateEventIngestionSettings(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ settings,
+ });
+ });
+
+ ctx.data.register("paperclip-ingestion-profile", async (params) => {
+ return getPaperclipIngestionProfile(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ });
+ });
+
+ ctx.data.register("paperclip-ingestion-candidates", async (params) => {
+ return listPaperclipIngestionCandidates(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ query: stringField(params.query),
+ });
+ });
+
+ ctx.actions.register("update-paperclip-ingestion-profile", async (params) => {
+ return updatePaperclipIngestionProfile(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ profile: params.profile,
+ });
+ });
+
+ ctx.actions.register("queue-paperclip-ingestion-backfill", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ const sourceScope = typeof params.sourceScope === "object" && params.sourceScope != null && !Array.isArray(params.sourceScope)
+ ? params.sourceScope as Record<string, unknown>
+ : {};
+ const sourceScopeKind = stringField(sourceScope.kind);
+ const projectIds = Array.isArray(sourceScope.projectIds) ? sourceScope.projectIds.map(stringField).filter((id): id is string => Boolean(id)) : [];
+ const issueIds = Array.isArray(sourceScope.issueIds) ? sourceScope.issueIds.map(stringField).filter((id): id is string => Boolean(id)) : [];
+ const scopes = sourceScopeKind === "selected_projects"
+ ? projectIds.map((projectId) => ({ projectId, rootIssueId: null as string | null }))
+ : sourceScopeKind === "root_issues"
+ ? issueIds.map((rootIssueId) => ({ projectId: null as string | null, rootIssueId }))
+ : [];
+ if (scopes.length === 0) {
+ return {
+ status: "refused_policy",
+ wikiId: stringField(params.wikiId) ?? "default",
+ spaceSlug: stringField(params.spaceSlug) ?? "default",
+ warnings: ["Backfill requires a selected project or root issue scope in Phase 4."],
+ };
+ }
+ const backfillStartAt = stringField(params.backfillStartAt);
+ const backfillEndAt = stringField(params.backfillEndAt);
+ const wikiId = stringField(params.wikiId);
+ const spaceSlug = stringField(params.spaceSlug);
+ const requestedByIssueId = stringField(params.requestedByIssueId);
+ const idempotencyKey = stringField(params.idempotencyKey);
+ const queued: Array<{ workItemId: string; issueId: string; projectId: string | null; rootIssueId: string | null }> = [];
+ for (const scope of scopes) {
+ const idempotencyScope = scope.rootIssueId ? `root:${scope.rootIssueId}` : `project:${scope.projectId}`;
+ const workItem = await createPaperclipDistillationWorkItem(ctx, {
+ companyId,
+ wikiId,
+ spaceSlug,
+ kind: "backfill",
+ projectId: scope.projectId,
+ rootIssueId: scope.rootIssueId,
+ requestedByIssueId,
+ priority: "low",
+ idempotencyKey: idempotencyKey && scopes.length === 1
+ ? idempotencyKey
+ : `${idempotencyKey ?? "profile-backfill"}:${idempotencyScope}:${backfillStartAt ?? "begin"}:${backfillEndAt ?? "now"}`,
+ metadata: { backfillStartAt, backfillEndAt, requestedFrom: "queue-paperclip-ingestion-backfill" },
+ });
+ const operation = await createOperationIssue(ctx, {
+ companyId,
+ wikiId,
+ spaceSlug,
+ operationType: "backfill",
+ title: scope.rootIssueId ? "Backfill Paperclip root issue wiki history" : "Backfill Paperclip project wiki history",
+ useCheapModelProfile: params.useCheapModelProfile === true,
+ prompt: [
+ "Backfill LLM Wiki distillation was queued from a per-space Paperclip ingestion profile.",
+ scope.projectId ? `Project ID: ${scope.projectId}` : null,
+ scope.rootIssueId ? `Root issue ID: ${scope.rootIssueId}` : null,
+ backfillStartAt ? `Start: ${backfillStartAt}` : null,
+ backfillEndAt ? `End: ${backfillEndAt}` : null,
+ "Process this bounded window through the profile destination space only.",
+ ].filter(Boolean).join("\n"),
+ });
+ queued.push({
+ workItemId: workItem.workItemId,
+ issueId: operation.issue.id,
+ projectId: scope.projectId,
+ rootIssueId: scope.rootIssueId,
+ });
+ }
+ const primary = queued[0];
+ return {
+ status: "queued",
+ wikiId: stringField(params.wikiId) ?? "default",
+ spaceSlug: stringField(params.spaceSlug) ?? "default",
+ workItemId: primary?.workItemId ?? null,
+ issueId: primary?.issueId ?? null,
+ workItems: queued,
+ warnings: [],
+ };
+ });
+
+ ctx.actions.register("ingest-source", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ const wikiId = stringField(params.wikiId);
+ const spaceSlug = stringField(params.spaceSlug);
+ const sourceType = stringField(params.sourceType) ?? "text";
+ const title = stringField(params.title) ?? sourceType.toUpperCase();
+ const contents = typeof params.contents === "string" ? params.contents : "";
+ const url = stringField(params.url);
+ const captured = await captureWikiSource(ctx, {
+ companyId,
+ wikiId,
+ spaceSlug,
+ sourceType,
+ title,
+ url,
+ contents,
+ rawPath: stringField(params.rawPath),
+ metadata: typeof params.metadata === "object" && params.metadata != null ? params.metadata as Record<string, unknown> : null,
+ });
+ const op = await createOperationIssue(ctx, {
+ companyId,
+ wikiId,
+ spaceSlug,
+ operationType: "ingest",
+ title: `Ingest ${sourceType}: ${title}`,
+ prompt: [
+ `Ingest a captured source from raw/${captured.rawPath.replace(/^raw\//, "")}.`,
+ url ? `Source URL: ${url}` : null,
+ "Follow the installed wiki-ingest skill: read the raw file end to end, summarise into wiki/sources/<slug>.md, update related entity/concept/synthesis pages, refresh wiki/index.md, and append wiki/log.md.",
+ ].filter(Boolean).join("\n"),
+ });
+ return { status: "ok", source: captured, operation: op };
+ });
+
+ ctx.actions.register("assemble-paperclip-source-bundle", async (params) => {
+ return assemblePaperclipSourceBundle(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ projectId: stringField(params.projectId),
+ rootIssueId: stringField(params.rootIssueId),
+ maxCharacters: typeof params.maxCharacters === "number" ? params.maxCharacters : null,
+ maxCharactersPerSource: typeof params.maxCharactersPerSource === "number" ? params.maxCharactersPerSource : null,
+ backfillStartAt: stringField(params.backfillStartAt),
+ backfillEndAt: stringField(params.backfillEndAt),
+ routineRun: params.routineRun === true,
+ includeComments: params.includeComments !== false,
+ includeDocuments: params.includeDocuments !== false,
+ });
+ });
+
+ ctx.actions.register("create-paperclip-distillation-run", async (params) => {
+ return createPaperclipDistillationRun(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ projectId: stringField(params.projectId),
+ rootIssueId: stringField(params.rootIssueId),
+ maxCharacters: typeof params.maxCharacters === "number" ? params.maxCharacters : null,
+ maxCharactersPerSource: typeof params.maxCharactersPerSource === "number" ? params.maxCharactersPerSource : null,
+ backfillStartAt: stringField(params.backfillStartAt),
+ backfillEndAt: stringField(params.backfillEndAt),
+ routineRun: params.routineRun === true,
+ includeComments: params.includeComments !== false,
+ includeDocuments: params.includeDocuments !== false,
+ workItemId: stringField(params.workItemId),
+ operationIssueId: stringField(params.operationIssueId),
+ });
+ });
+
+ ctx.actions.register("record-paperclip-distillation-outcome", async (params) => {
+ const status = stringField(params.status);
+ if (status !== "succeeded" && status !== "failed" && status !== "review_required") {
+ throw new Error("status must be succeeded, failed, or review_required");
+ }
+ const runId = stringField(params.runId);
+ if (!runId) throw new Error("runId is required");
+ return recordPaperclipDistillationOutcome(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ runId,
+ cursorId: stringField(params.cursorId),
+ status,
+ sourceHash: stringField(params.sourceHash),
+ sourceWindowEnd: stringField(params.sourceWindowEnd),
+ warning: stringField(params.warning),
+ costCents: typeof params.costCents === "number" ? params.costCents : null,
+ retryCount: typeof params.retryCount === "number" ? params.retryCount : null,
+ });
+ });
+
+ ctx.actions.register("distill-paperclip-project-page", async (params) => {
+ return distillPaperclipProjectPage(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ projectId: stringField(params.projectId),
+ rootIssueId: stringField(params.rootIssueId),
+ maxCharacters: typeof params.maxCharacters === "number" ? params.maxCharacters : null,
+ maxCharactersPerSource: typeof params.maxCharactersPerSource === "number" ? params.maxCharactersPerSource : null,
+ backfillStartAt: stringField(params.backfillStartAt),
+ backfillEndAt: stringField(params.backfillEndAt),
+ routineRun: params.routineRun === true,
+ includeComments: params.includeComments !== false,
+ includeDocuments: params.includeDocuments !== false,
+ workItemId: stringField(params.workItemId),
+ operationIssueId: stringField(params.operationIssueId),
+ autoApply: params.autoApply === true ? true : params.autoApply === false ? false : undefined,
+ expectedProjectPageHash: stringField(params.expectedProjectPageHash),
+ includeSupportingPages: params.includeSupportingPages !== false,
+ });
+ });
+
+ ctx.actions.register("distill-paperclip-now", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ const spaceSlug = stringField(params.spaceSlug);
+ const projectId = stringField(params.projectId);
+ const rootIssueId = stringField(params.rootIssueId);
+ const idempotencyScope = rootIssueId ? `root:${rootIssueId}` : projectId ? `project:${projectId}` : "company";
+ const workItem = await createPaperclipDistillationWorkItem(ctx, {
+ companyId,
+ wikiId: stringField(params.wikiId),
+ spaceSlug,
+ kind: "manual",
+ projectId,
+ rootIssueId,
+ requestedByIssueId: stringField(params.requestedByIssueId),
+ priority: "medium",
+ idempotencyKey: stringField(params.idempotencyKey) ?? `manual:${idempotencyScope}`,
+ metadata: { requestedFrom: "distill-paperclip-now" },
+ });
+ const operation = await createOperationIssue(ctx, {
+ companyId,
+ wikiId: stringField(params.wikiId),
+ spaceSlug,
+ operationType: "distill",
+ title: rootIssueId
+ ? "Distill Paperclip root issue into wiki"
+ : projectId
+ ? "Distill Paperclip project into wiki"
+ : "Distill Paperclip changes into wiki",
+ useCheapModelProfile: params.useCheapModelProfile === true,
+ prompt: buildManualDistillPrompt({ companyId, projectId, rootIssueId }),
+ });
+ return { status: "queued", workItem, operation };
+ });
+
+ ctx.actions.register("enable-paperclip-distillation-active-projects", async (params) => {
+ return enableActiveProjectDistillation(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ limit: typeof params.limit === "number" ? params.limit : null,
+ });
+ });
+
+ ctx.actions.register("backfill-paperclip-distillation", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ const spaceSlug = stringField(params.spaceSlug);
+ const projectId = stringField(params.projectId);
+ const rootIssueId = stringField(params.rootIssueId);
+ if (!projectId && !rootIssueId) throw new Error("projectId or rootIssueId is required");
+ const backfillStartAt = stringField(params.backfillStartAt);
+ const backfillEndAt = stringField(params.backfillEndAt);
+ const idempotencyScope = rootIssueId ? `root:${rootIssueId}` : `project:${projectId}`;
+ const workItem = await createPaperclipDistillationWorkItem(ctx, {
+ companyId,
+ wikiId: stringField(params.wikiId),
+ spaceSlug,
+ kind: "backfill",
+ projectId,
+ rootIssueId,
+ requestedByIssueId: stringField(params.requestedByIssueId),
+ priority: "low",
+ idempotencyKey: stringField(params.idempotencyKey) ?? `backfill:${idempotencyScope}:${backfillStartAt ?? "begin"}:${backfillEndAt ?? "now"}`,
+ metadata: { backfillStartAt, backfillEndAt, requestedFrom: "backfill-paperclip-distillation" },
+ });
+ const operation = await createOperationIssue(ctx, {
+ companyId,
+ wikiId: stringField(params.wikiId),
+ spaceSlug,
+ operationType: "backfill",
+ title: rootIssueId ? "Backfill Paperclip root issue wiki history" : "Backfill Paperclip project wiki history",
+ useCheapModelProfile: params.useCheapModelProfile === true,
+ prompt: [
+ "Backfill LLM Wiki distillation requested for a bounded Paperclip source window.",
+ projectId ? `Project ID: ${projectId}` : null,
+ rootIssueId ? `Root issue ID: ${rootIssueId}` : null,
+ backfillStartAt ? `Start: ${backfillStartAt}` : null,
+ backfillEndAt ? `End: ${backfillEndAt}` : null,
+ "Do not process whole-company history; stay within the selected project/root issue and date window.",
+ ].filter(Boolean).join("\n"),
+ });
+ const result = await distillPaperclipProjectPage(ctx, {
+ companyId,
+ wikiId: stringField(params.wikiId),
+ spaceSlug,
+ projectId,
+ rootIssueId,
+ maxCharacters: typeof params.maxCharacters === "number" ? params.maxCharacters : null,
+ maxCharactersPerSource: typeof params.maxCharactersPerSource === "number" ? params.maxCharactersPerSource : null,
+ backfillStartAt,
+ backfillEndAt,
+ routineRun: params.routineRun === true,
+ includeComments: params.includeComments !== false,
+ includeDocuments: params.includeDocuments !== false,
+ autoApply: params.autoApply === true ? true : params.autoApply === false ? false : undefined,
+ expectedProjectPageHash: stringField(params.expectedProjectPageHash),
+ includeSupportingPages: params.includeSupportingPages !== false,
+ workItemId: workItem.workItemId,
+ operationIssueId: operation.issue.id,
+ });
+ return { ...result, workItem, operation };
+ });
+
+ ctx.actions.register("create-paperclip-distillation-work-item", async (params) => {
+ const kind = stringField(params.kind);
+ if (
+ kind !== "manual" &&
+ kind !== "retry" &&
+ kind !== "backfill" &&
+ kind !== "priority_override" &&
+ kind !== "review_patch"
+ ) {
+ throw new Error("kind must be manual, retry, backfill, priority_override, or review_patch");
+ }
+ const priority = stringField(params.priority);
+ if (priority && priority !== "critical" && priority !== "high" && priority !== "medium" && priority !== "low") {
+ throw new Error("priority must be critical, high, medium, or low");
+ }
+ return createPaperclipDistillationWorkItem(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ kind,
+ projectId: stringField(params.projectId),
+ rootIssueId: stringField(params.rootIssueId),
+ requestedByIssueId: stringField(params.requestedByIssueId),
+ priority: priority as "critical" | "high" | "medium" | "low" | null,
+ idempotencyKey: stringField(params.idempotencyKey),
+ metadata: typeof params.metadata === "object" && params.metadata != null ? params.metadata as Record<string, unknown> : null,
+ });
+ });
+
+ ctx.actions.register("file-as-page", async (params) => {
+ return fileQueryAnswerAsPage(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ querySessionId: stringField(params.querySessionId),
+ question: stringField(params.question),
+ answer: stringField(params.answer),
+ path: stringField(params.path) ?? "",
+ title: stringField(params.title),
+ contents: stringField(params.contents),
+ expectedHash: stringField(params.expectedHash),
+ });
+ });
+
+ ctx.actions.register("start-query", async (params) => {
+ return startWikiQuerySession(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ question: stringField(params.question) ?? "",
+ title: stringField(params.title),
+ });
+ });
+
+ ctx.actions.register("reset-managed-agent", async (params) => {
+ return resetWikiAgentResource(ctx, readCompanyIdFromParams(params));
+ });
+
+ ctx.actions.register("reset-managed-project", async (params) => {
+ return resetWikiProjectResource(ctx, readCompanyIdFromParams(params));
+ });
+
+ ctx.actions.register("reconcile-managed-agent", async (params) => {
+ return reconcileWikiAgentResource(ctx, readCompanyIdFromParams(params));
+ });
+
+ ctx.actions.register("reconcile-managed-project", async (params) => {
+ return reconcileWikiProjectResource(ctx, readCompanyIdFromParams(params));
+ });
+
+ ctx.actions.register("reconcile-managed-skills", async (params) => {
+ return { managedSkills: await reconcileWikiSkillResources(ctx, readCompanyIdFromParams(params)) };
+ });
+
+ ctx.actions.register("reset-managed-skills", async (params) => {
+ return { managedSkills: await resetWikiSkillResources(ctx, readCompanyIdFromParams(params)) };
+ });
+
+ ctx.actions.register("select-managed-agent", async (params) => {
+ const agentId = stringField(params.agentId);
+ if (!agentId) throw new Error("agentId is required");
+ return selectWikiAgentResource(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ agentId,
+ });
+ });
+
+ ctx.actions.register("select-managed-project", async (params) => {
+ const projectId = stringField(params.projectId);
+ if (!projectId) throw new Error("projectId is required");
+ return selectWikiProjectResource(ctx, {
+ companyId: readCompanyIdFromParams(params),
+ projectId,
+ });
+ });
+
+ ctx.actions.register("reset-managed-routine", async (params) => {
+ return ctx.routines.managed.reset(
+ routineKeyField(params.routineKey),
+ readCompanyIdFromParams(params),
+ routineOverridesFromParams(params),
+ );
+ });
+
+ ctx.actions.register("reconcile-managed-routine", async (params) => {
+ return ctx.routines.managed.reconcile(
+ routineKeyField(params.routineKey),
+ readCompanyIdFromParams(params),
+ routineOverridesFromParams(params),
+ );
+ });
+
+ ctx.actions.register("reconcile-managed-routines", async (params) => {
+ return reconcileWikiRoutineResources(ctx, readCompanyIdFromParams(params));
+ });
+
+ ctx.actions.register("update-managed-routine-status", async (params) => {
+ const status = stringField(params.status);
+ if (!status) throw new Error("status is required");
+ return ctx.routines.managed.update(routineKeyField(params.routineKey), readCompanyIdFromParams(params), {
+ status,
+ });
+ });
+
+ ctx.actions.register("run-managed-routine", async (params) => {
+ return ctx.routines.managed.run(
+ routineKeyField(params.routineKey),
+ readCompanyIdFromParams(params),
+ routineOverridesFromParams(params),
+ );
+ });
+
+ ctx.data.register("pages", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ return listPages(ctx, {
+ companyId,
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ pageType: stringField(params.pageType),
+ includeRaw: params.includeRaw === true || params.includeRaw === "true",
+ limit: typeof params.limit === "number" ? params.limit : null,
+ });
+ });
+
+ ctx.data.register("sources", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ return listSources(ctx, { companyId, wikiId: stringField(params.wikiId), spaceSlug: stringField(params.spaceSlug), limit: typeof params.limit === "number" ? params.limit : null });
+ });
+
+ ctx.data.register("page-content", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ const path = stringField(params.path);
+ if (!path) throw new Error("path is required");
+ return readWikiPage(ctx, { companyId, wikiId: stringField(params.wikiId), spaceSlug: stringField(params.spaceSlug), path });
+ });
+
+ ctx.data.register("template", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ const path = stringField(params.path) ?? "AGENTS.md";
+ return readTemplate(ctx, { companyId, path });
+ });
+
+ ctx.data.register("operations", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ return listOperations(ctx, {
+ companyId,
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ operationType: stringField(params.operationType),
+ status: stringField(params.status),
+ limit: typeof params.limit === "number" ? params.limit : null,
+ });
+ });
+
+ ctx.data.register("distillation-overview", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ return getDistillationOverview(ctx, {
+ companyId,
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ limit: typeof params.limit === "number" ? params.limit : null,
+ });
+ });
+
+ ctx.data.register("distillation-page-provenance", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ const pagePath = stringField(params.pagePath);
+ if (!pagePath) {
+ return { binding: null, runs: [], snapshot: null, cursor: null };
+ }
+ return getDistillationPageProvenance(ctx, {
+ companyId,
+ wikiId: stringField(params.wikiId),
+ spaceSlug: stringField(params.spaceSlug),
+ pagePath,
+ });
+ });
+
+ ctx.data.register("settings", async (params) => {
+ const companyId = readCompanyIdFromParams(params);
+ const folder = await ctx.localFolders.status(companyId, WIKI_ROOT_FOLDER_KEY);
+ const overview = await getOverview(ctx, companyId);
+ const managedRoutines = await Promise.all(
+ WIKI_MAINTENANCE_ROUTINE_KEYS.map((routineKey) => ctx.routines.managed.get(routineKey, companyId)),
+ );
+ const managedRoutinesWithDefaultDrift = managedRoutines.map((routine) =>
+ withManagedRoutineDefaultDrift(
+ routine,
+ ctx.manifest.routines?.find((declaration) => declaration.routineKey === routine.resourceKey),
+ ),
+ );
+ return {
+ folder,
+ spaces: await listSpaces(ctx, { companyId }),
+ managedAgent: overview.managedAgent,
+ managedProject: overview.managedProject,
+ managedSkills: overview.managedSkills,
+ managedRoutine: managedRoutinesWithDefaultDrift[0],
+ managedRoutines: managedRoutinesWithDefaultDrift,
+ distillationPolicy: getDistillationAutoApplyRestriction(),
+ eventIngestion: await getEventIngestionSettings(ctx, companyId),
+ agentOptions: await listWikiAgentOptions(ctx, companyId),
+ projectOptions: await listWikiProjectOptions(ctx, companyId),
+ capabilities: ctx.manifest.capabilities,
+ };
+ });
+ },
+
+ async onApiRequest(input: PluginApiRequestInput) {
+ const ctx = requireContext();
+ if (input.routeKey === "overview") {
+ return { body: await getOverview(ctx, input.companyId) };
+ }
+
+ if (input.routeKey === "bootstrap") {
+ const body = input.body as Record<string, unknown> | null;
+ return {
+ status: 201,
+ body: await bootstrapWikiRoot(ctx, {
+ companyId: input.companyId,
+ path: stringField(body?.path),
+ }),
+ };
+ }
+
+ if (input.routeKey === "spaces") {
+ return {
+ body: await listSpaces(ctx, {
+ companyId: input.companyId,
+ wikiId: stringField(input.query.wikiId),
+ }),
+ };
+ }
+
+ if (input.routeKey === "create-space") {
+ const body = input.body as Record<string, unknown> | null;
+ return {
+ status: 201,
+ body: await createSpace(ctx, {
+ companyId: input.companyId,
+ wikiId: stringField(body?.wikiId),
+ slug: stringField(body?.slug),
+ displayName: stringField(body?.displayName),
+ folderMode: stringField(body?.folderMode) as "managed_subfolder" | "existing_local_folder" | null,
+ accessScope: stringField(body?.accessScope) as "shared" | "personal" | "team" | null,
+ settings: typeof body?.settings === "object" && body.settings != null ? body.settings as Record<string, unknown> : null,
+ }),
+ };
+ }
+
+ if (input.routeKey === "update-space") {
+ const body = input.body as Record<string, unknown> | null;
+ return {
+ body: await updateSpace(ctx, {
+ companyId: input.companyId,
+ wikiId: stringField(body?.wikiId),
+ spaceSlug: input.params.spaceSlug,
+ displayName: stringField(body?.displayName),
+ status: stringField(body?.status) as "active" | "archived" | null,
+ settings: typeof body?.settings === "object" && body.settings != null ? body.settings as Record<string, unknown> : null,
+ }),
+ };
+ }
+
+ if (input.routeKey === "bootstrap-space") {
+ const body = input.body as Record<string, unknown> | null;
+ return {
+ status: 201,
+ body: await bootstrapSpace(ctx, {
+ companyId: input.companyId,
+ wikiId: stringField(body?.wikiId),
+ spaceSlug: input.params.spaceSlug,
+ }),
+ };
+ }
+
+ if (input.routeKey === "archive-space") {
+ const body = input.body as Record<string, unknown> | null;
+ return {
+ body: await archiveSpace(ctx, {
+ companyId: input.companyId,
+ wikiId: stringField(body?.wikiId),
+ spaceSlug: input.params.spaceSlug,
+ }),
+ };
+ }
+
+ if (input.routeKey === "capture-source") {
+ const body = input.body as Record<string, unknown> | null;
+ return {
+ status: 201,
+ body: await captureWikiSource(ctx, {
+ companyId: input.companyId,
+ wikiId: stringField(body?.wikiId),
+ spaceSlug: stringField(body?.spaceSlug),
+ sourceType: stringField(body?.sourceType),
+ title: stringField(body?.title),
+ url: stringField(body?.url),
+ contents: typeof body?.contents === "string" ? body.contents : "",
+ rawPath: stringField(body?.rawPath),
+ metadata: typeof body?.metadata === "object" && body.metadata != null ? body.metadata as Record<string, unknown> : null,
+ }),
+ };
+ }
+
+ if (input.routeKey === "operations") {
+ return {
+ body: await listOperations(ctx, {
+ companyId: input.companyId,
+ wikiId: stringField(input.query.wikiId),
+ spaceSlug: stringField(input.query.spaceSlug),
+ operationType: stringField(input.query.operationType),
+ status: stringField(input.query.status),
+ limit: typeof input.query.limit === "string" ? Number(input.query.limit) : null,
+ }),
+ };
+ }
+
+ if (input.routeKey === "start-query") {
+ const body = input.body as Record<string, unknown> | null;
+ return {
+ status: 201,
+ body: await startWikiQuerySession(ctx, {
+ companyId: input.companyId,
+ wikiId: stringField(body?.wikiId),
+ spaceSlug: stringField(body?.spaceSlug),
+ question: stringField(body?.question) ?? "",
+ title: stringField(body?.title),
+ }),
+ };
+ }
+
+ if (input.routeKey === "file-as-page") {
+ const body = input.body as Record<string, unknown> | null;
+ return {
+ status: 201,
+ body: await fileQueryAnswerAsPage(ctx, {
+ companyId: input.companyId,
+ wikiId: stringField(body?.wikiId),
+ spaceSlug: stringField(body?.spaceSlug),
+ querySessionId: stringField(body?.querySessionId),
+ question: stringField(body?.question),
+ answer: stringField(body?.answer),
+ path: stringField(body?.path) ?? "",
+ title: stringField(body?.title),
+ contents: stringField(body?.contents),
+ expectedHash: stringField(body?.expectedHash),
+ }),
+ };
+ }
+
+ return { status: 404, body: { error: `Unknown LLM Wiki route: ${input.routeKey}` } };
+ },
+
+ async onHealth() {
+ return {
+ status: "ok",
+ message: "LLM Wiki plugin worker is running",
+ details: {
+ surfaces: ["page", "sidebar", "settings", "tools", "database", "local-folder"],
+ },
+ };
+ }
+});
+
+export default plugin;
+runWorker(plugin, import.meta.url);
diff --git a/packages/plugins/plugin-llm-wiki/templates/.gitignore b/packages/plugins/plugin-llm-wiki/templates/.gitignore
new file mode 100644
index 0000000000..ef42c26de5
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/templates/.gitignore
@@ -0,0 +1,3 @@
+.DS_Store
+.obsidian/workspace*
+.obsidian/cache
diff --git a/packages/plugins/plugin-llm-wiki/templates/AGENTS.md b/packages/plugins/plugin-llm-wiki/templates/AGENTS.md
new file mode 100644
index 0000000000..3c2aa2739a
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/templates/AGENTS.md
@@ -0,0 +1,137 @@
+# AGENTS.md — LLM Wiki Schema
+
+You are the maintainer of this personal wiki. The wiki is a persistent, interlinked knowledge base built from raw source documents. You read sources, extract knowledge, and integrate it into evolving wiki pages. The user curates sources, directs analysis, and asks questions; you handle the bookkeeping.
+
+The underlying pattern is described in `IDEA.md` (Karpathy's "LLM Wiki" gist). Read it if you need the philosophy; this file is the operational schema.
+
+## Layout
+
+```
+.
+├── AGENTS.md # this file — your operating instructions
+├── IDEA.md # the pattern this wiki follows
+├── raw/ # immutable source documents (you read, never write)
+└── wiki/ # generated, owned by you
+ ├── index.md # catalog of all pages
+ ├── log.md # append-only timeline of operations
+ ├── sources/ # one summary page per source
+ ├── projects/ # Paperclip project overviews, standups, decisions, and history
+ │ └── <slug>/
+ │ ├── index.md
+ │ ├── standup.md
+ │ ├── decisions.md
+ │ └── history.md
+ ├── entities/ # people, organizations, products, places
+ ├── concepts/ # ideas, frameworks, definitions
+ └── synthesis/ # cross-cutting analysis, comparisons, theses
+```
+
+The subdirectories under `wiki/` are conventional, not enforced. Add new categories (e.g. `wiki/papers/`) as the domain demands — and update this file when you do.
+
+Paperclip project material lives only under `wiki/projects/<project-slug>/`. Do not create a top-level `projects/` directory.
+
+- `wiki/projects/<project-slug>/standup.md` is the executive-level project standup. It answers where the project stands today, what changed recently, current blockers/risks, and the next concrete actions.
+- `wiki/projects/<project-slug>/index.md` is the durable knowledge page. It explains what the project is, why it exists, decisions made, history, and long-lived context.
+- Keep the two linked. A standup should link to the durable project page, and the durable project page should point at the current standup for live status.
+- Update `standup.md` whenever Paperclip project, issue, plan, comment, blocker, approval, or status history materially changes the project's current state. Do not append endless dated sections; rewrite it as today's concise status.
+- Project writing should be editorial and concept-grouped. Do not dump issue queues, UUIDs, raw metadata, or date-heavy ledgers into project pages. Reference Paperclip tasks with human issue links where useful, but make headings and paragraphs explain the concepts, decisions, completed work, next work, and blockers in plain executive language.
+
+## Page conventions
+
+- **Filename:** kebab-case, `.md`. Treat filenames as stable; do not rename without updating backlinks.
+- **Frontmatter:** YAML at the top of every wiki page.
+ ```yaml
+ ---
+ title: Human-readable title
+ type: source | project | entity | concept | synthesis
+ tags: [tag-a, tag-b]
+ sources: [raw/doc.pdf] # for source pages and synthesis pages
+ created: YYYY-MM-DD
+ updated: YYYY-MM-DD
+ ---
+ ```
+- **Cross-links:** Obsidian-style `[[wiki/entities/some-page]]` (or `[[some-page]]` when unambiguous). When you mention a concept or entity that has — or should have — its own page, link it.
+- **Citations:** cite the source inline whenever a claim comes from one: `(see [[wiki/sources/some-slug]])`.
+- **Voice:** terse, factual, neutral. The wiki is reference material, not narrative.
+
+## Operations
+
+### Ingest
+
+Triggered when the user drops a file in `raw/` and asks to process it (or just says "ingest").
+
+1. Read the source end to end.
+2. Briefly discuss key takeaways with the user before writing — confirm what to emphasize.
+3. Create `wiki/sources/<slug>.md`: a summary page (~300–800 words) covering the source's main claims, structure, and notable quotes or data.
+4. Update or create relevant pages in `entities/`, `concepts/`, `synthesis/`. A typical ingest touches 5–15 pages.
+5. Add any new pages to `wiki/index.md`.
+6. Append a log entry:
+ ```
+ ## [YYYY-MM-DD] ingest | <source title>
+ - source: raw/<filename>
+ - new pages: [[...]], [[...]]
+ - updated pages: [[...]], [[...]]
+ - notes: <one-line synthesis, contradiction flagged, or open question>
+ ```
+
+When new information contradicts an existing page, do **not** silently overwrite. Flag the contradiction on the page (a `> ⚠ contradicted by [[...]] (YYYY-MM-DD)` callout) and note it in the log.
+
+### Project updates
+
+Triggered when Paperclip project, issue, plan, comment, blocker, or status history is distilled into the wiki.
+
+1. Create or update `wiki/projects/<project-slug>/standup.md` first. Every Paperclip project represented in the wiki must have one. Keep stable sections for executive readout, what changed, decisions, blockers/risks, next actions, and links.
+2. Create or update `wiki/projects/<project-slug>/index.md` as the durable project overview. Keep stable sections for overview, current direction, workstreams, decisions, open risks/blockers, and references.
+3. Use `wiki/projects/<project-slug>/decisions.md` for accepted/rejected plans, architectural decisions, approval outcomes, and reversals when a project has enough decision history to warrant a separate page.
+4. Use `wiki/projects/<project-slug>/history.md` for compact narrative history of meaningful project movement. Group by phase or concept; do not mirror every issue comment.
+5. Always cite Paperclip source material with readable links to issue identifiers, document keys, issue documents, approvals, and raw/source pages. Do not put UUIDs in prose unless the UUID itself is the subject.
+6. Update `wiki/index.md` under Projects and append a `project` log entry to `wiki/log.md`.
+
+### Query
+
+The user asks a question. You:
+
+1. Read `wiki/index.md` to find candidate pages.
+2. Read those pages; follow links as needed.
+3. Answer with citations back to wiki pages, and ultimately to raw sources.
+4. If the answer is substantial (a comparison, analysis, new synthesis), offer to file it under `wiki/synthesis/` so the work compounds rather than disappearing into chat history.
+
+If the wiki lacks what the question needs, say so plainly and suggest sources to ingest or web searches to run.
+
+### Lint
+
+On request ("lint", "health check"), scan for:
+
+- contradictions across pages
+- claims a newer source has superseded
+- orphan pages (not linked from `index.md` or any other page)
+- concepts mentioned in multiple places but lacking a dedicated page
+- broken `[[wiki-links]]`
+- gaps where a web search or new source would help
+
+Report findings as a checklist and ask the user which to act on.
+
+## index.md format
+
+A catalog organized by category. Each line: `- [[path]] — one-line summary`. Keep it scannable; this is your primary navigation aid before opening pages.
+
+## log.md format
+
+Append new entries to the bottom. Every entry header follows:
+
+```
+## [YYYY-MM-DD] <op> | <subject>
+```
+
+so `grep "^## \[" wiki/log.md | tail -10` always returns recent activity. Operations: `ingest`, `query`, `lint`, `setup`, `refactor`.
+
+## Customization
+
+This schema is intentionally generic. As the wiki's domain becomes clear, evolve it:
+
+- add domain-specific page types and subdirectories
+- adjust frontmatter fields
+- specify preferred output formats for queries (Marp slides, charts, tables)
+- record workflow preferences (one-at-a-time vs batch ingest, level of human supervision)
+
+When you and the user agree on a convention, **write it into this file**. The schema is the wiki's source of truth for how the wiki is built.
diff --git a/packages/plugins/plugin-llm-wiki/templates/IDEA.md b/packages/plugins/plugin-llm-wiki/templates/IDEA.md
new file mode 100644
index 0000000000..35ef071290
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/templates/IDEA.md
@@ -0,0 +1,75 @@
+# LLM Wiki
+
+A pattern for building personal knowledge bases using LLMs.
+
+This is an idea file, it is designed to be copy pasted to your own LLM Agent (e.g. OpenAI Codex, Claude Code, OpenCode / Pi, or etc.). Its goal is to communicate the high level idea, but your agent will build out the specifics in collaboration with you.
+
+## The core idea
+
+Most people's experience with LLMs and documents looks like RAG: you upload a collection of files, the LLM retrieves relevant chunks at query time, and generates an answer. This works, but the LLM is rediscovering knowledge from scratch on every question. There's no accumulation. Ask a subtle question that requires synthesizing five documents, and the LLM has to find and piece together the relevant fragments every time. Nothing is built up. NotebookLM, ChatGPT file uploads, and most RAG systems work this way.
+
+The idea here is different. Instead of just retrieving from raw documents at query time, the LLM **incrementally builds and maintains a persistent wiki** — a structured, interlinked collection of markdown files that sits between you and the raw sources. When you add a new source, the LLM doesn't just index it for later retrieval. It reads it, extracts the key information, and integrates it into the existing wiki — updating entity pages, revising topic summaries, noting where new data contradicts old claims, strengthening or challenging the evolving synthesis. The knowledge is compiled once and then *kept current*, not re-derived on every query.
+
+This is the key difference: **the wiki is a persistent, compounding artifact.** The cross-references are already there. The contradictions have already been flagged. The synthesis already reflects everything you've read. The wiki keeps getting richer with every source you add and every question you ask.
+
+You never (or rarely) write the wiki yourself — the LLM writes and maintains all of it. You're in charge of sourcing, exploration, and asking the right questions. The LLM does all the grunt work — the summarizing, cross-referencing, filing, and bookkeeping that makes a knowledge base actually useful over time. In practice, I have the LLM agent open on one side and Obsidian open on the other. The LLM makes edits based on our conversation, and I browse the results in real time — following links, checking the graph view, reading the updated pages. Obsidian is the IDE; the LLM is the programmer; the wiki is the codebase.
+
+This can apply to a lot of different contexts. A few examples:
+
+- **Personal**: tracking your own goals, health, psychology, self-improvement — filing journal entries, articles, podcast notes, and building up a structured picture of yourself over time.
+- **Research**: going deep on a topic over weeks or months — reading papers, articles, reports, and incrementally building a comprehensive wiki with an evolving thesis.
+- **Reading a book**: filing each chapter as you go, building out pages for characters, themes, plot threads, and how they connect. By the end you have a rich companion wiki. Think of fan wikis like [Tolkien Gateway](https://tolkiengateway.net/wiki/Main_Page) — thousands of interlinked pages covering characters, places, events, languages, built by a community of volunteers over years. You could build something like that personally as you read, with the LLM doing all the cross-referencing and maintenance.
+- **Business/team**: an internal wiki maintained by LLMs, fed by Slack threads, meeting transcripts, project documents, customer calls. Possibly with humans in the loop reviewing updates. The wiki stays current because the LLM does the maintenance that no one on the team wants to do.
+- **Competitive analysis, due diligence, trip planning, course notes, hobby deep-dives** — anything where you're accumulating knowledge over time and want it organized rather than scattered.
+
+## Architecture
+
+There are three layers:
+
+**Raw sources** — your curated collection of source documents. Articles, papers, images, data files. These are immutable — the LLM reads from them but never modifies them. This is your source of truth.
+
+**The wiki** — a directory of LLM-generated markdown files. Summaries, entity pages, concept pages, comparisons, an overview, a synthesis. The LLM owns this layer entirely. It creates pages, updates them when new sources arrive, maintains cross-references, and keeps everything consistent. You read it; the LLM writes it.
+
+**The schema** — a document (e.g. AGENTS.md for Paperclip agents) that tells the LLM how the wiki is structured, what the conventions are, and what workflows to follow when ingesting sources, answering questions, or maintaining the wiki. This is the key configuration file — it's what makes the LLM a disciplined wiki maintainer rather than a generic chatbot. You and the LLM co-evolve this over time as you figure out what works for your domain.
+
+## Operations
+
+**Ingest.** You drop a new source into the raw collection and tell the LLM to process it. An example flow: the LLM reads the source, discusses key takeaways with you, writes a summary page in the wiki, updates the index, updates relevant entity and concept pages across the wiki, and appends an entry to the log. A single source might touch 10-15 wiki pages. Personally I prefer to ingest sources one at a time and stay involved — I read the summaries, check the updates, and guide the LLM on what to emphasize. But you could also batch-ingest many sources at once with less supervision. It's up to you to develop the workflow that fits your style and document it in the schema for future sessions.
+
+**Query.** You ask questions against the wiki. The LLM searches for relevant pages, reads them, and synthesizes an answer with citations. Answers can take different forms depending on the question — a markdown page, a comparison table, a slide deck (Marp), a chart (matplotlib), a canvas. The important insight: **good answers can be filed back into the wiki as new pages.** A comparison you asked for, an analysis, a connection you discovered — these are valuable and shouldn't disappear into chat history. This way your explorations compound in the knowledge base just like ingested sources do.
+
+**Lint.** Periodically, ask the LLM to health-check the wiki. Look for: contradictions between pages, stale claims that newer sources have superseded, orphan pages with no inbound links, important concepts mentioned but lacking their own page, missing cross-references, data gaps that could be filled with a web search. The LLM is good at suggesting new questions to investigate and new sources to look for. This keeps the wiki healthy as it grows.
+
+## Indexing and logging
+
+Two special files help the LLM (and you) navigate the wiki as it grows. They serve different purposes:
+
+**index.md** is content-oriented. It's a catalog of everything in the wiki — each page listed with a link, a one-line summary, and optionally metadata like date or source count. Organized by category (entities, concepts, sources, etc.). The LLM updates it on every ingest. When answering a query, the LLM reads the index first to find relevant pages, then drills into them. This works surprisingly well at moderate scale (~100 sources, ~hundreds of pages) and avoids the need for embedding-based RAG infrastructure.
+
+**log.md** is chronological. It's an append-only record of what happened and when — ingests, queries, lint passes. A useful tip: if each entry starts with a consistent prefix (e.g. `## [2026-04-02] ingest | Article Title`), the log becomes parseable with simple unix tools — `grep "^## \[" log.md | tail -5` gives you the last 5 entries. The log gives you a timeline of the wiki's evolution and helps the LLM understand what's been done recently.
+
+## Optional: CLI tools
+
+At some point you may want to build small tools that help the LLM operate on the wiki more efficiently. A search engine over the wiki pages is the most obvious one — at small scale the index file is enough, but as the wiki grows you want proper search. [qmd](https://github.com/tobi/qmd) is a good option: it's a local search engine for markdown files with hybrid BM25/vector search and LLM re-ranking, all on-device. It has both a CLI (so the LLM can shell out to it) and an MCP server (so the LLM can use it as a native tool). You could also build something simpler yourself — the LLM can help you vibe-code a naive search script as the need arises.
+
+## Tips and tricks
+
+- **Obsidian Web Clipper** is a browser extension that converts web articles to markdown. Very useful for quickly getting sources into your raw collection.
+- **Download images locally.** In Obsidian Settings → Files and links, set "Attachment folder path" to a fixed directory (e.g. `raw/assets/`). Then in Settings → Hotkeys, search for "Download" to find "Download attachments for current file" and bind it to a hotkey (e.g. Ctrl+Shift+D). After clipping an article, hit the hotkey and all images get downloaded to local disk. This is optional but useful — it lets the LLM view and reference images directly instead of relying on URLs that may break. Note that LLMs can't natively read markdown with inline images in one pass — the workaround is to have the LLM read the text first, then view some or all of the referenced images separately to gain additional context. It's a bit clunky but works well enough.
+- **Obsidian's graph view** is the best way to see the shape of your wiki — what's connected to what, which pages are hubs, which are orphans.
+- **Marp** is a markdown-based slide deck format. Obsidian has a plugin for it. Useful for generating presentations directly from wiki content.
+- **Dataview** is an Obsidian plugin that runs queries over page frontmatter. If your LLM adds YAML frontmatter to wiki pages (tags, dates, source counts), Dataview can generate dynamic tables and lists.
+- The wiki is just a git repo of markdown files. You get version history, branching, and collaboration for free.
+
+## Why this works
+
+The tedious part of maintaining a knowledge base is not the reading or the thinking — it's the bookkeeping. Updating cross-references, keeping summaries current, noting when new data contradicts old claims, maintaining consistency across dozens of pages. Humans abandon wikis because the maintenance burden grows faster than the value. LLMs don't get bored, don't forget to update a cross-reference, and can touch 15 files in one pass. The wiki stays maintained because the cost of maintenance is near zero.
+
+The human's job is to curate sources, direct the analysis, ask good questions, and think about what it all means. The LLM's job is everything else.
+
+The idea is related in spirit to Vannevar Bush's Memex (1945) — a personal, curated knowledge store with associative trails between documents. Bush's vision was closer to this than to what the web became: private, actively curated, with the connections between documents as valuable as the documents themselves. The part he couldn't solve was who does the maintenance. The LLM handles that.
+
+
+## Note
+
+This document is intentionally abstract. It describes the idea, not a specific implementation. The exact directory structure, the schema conventions, the page formats, the tooling — all of that will depend on your domain, your preferences, and your LLM of choice. Everything mentioned above is optional and modular — pick what's useful, ignore what isn't. For example: your sources might be text-only, so you don't need image handling at all. Your wiki might be small enough that the index file is all you need, no search engine required. You might not care about slide decks and just want markdown pages. You might want a completely different set of output formats. The right way to use this is to share it with your LLM agent and work together to instantiate a version that fits your needs. The document's only job is to communicate the pattern. Your LLM can figure out the rest.
diff --git a/packages/plugins/plugin-llm-wiki/templates/raw/.gitkeep b/packages/plugins/plugin-llm-wiki/templates/raw/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/plugins/plugin-llm-wiki/templates/wiki/concepts/.gitkeep b/packages/plugins/plugin-llm-wiki/templates/wiki/concepts/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/plugins/plugin-llm-wiki/templates/wiki/entities/.gitkeep b/packages/plugins/plugin-llm-wiki/templates/wiki/entities/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/plugins/plugin-llm-wiki/templates/wiki/index.md b/packages/plugins/plugin-llm-wiki/templates/wiki/index.md
new file mode 100644
index 0000000000..54f1f8a304
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/templates/wiki/index.md
@@ -0,0 +1,23 @@
+# Index
+
+Catalog of durable wiki pages and linked project standups. Updated on every ingest or Paperclip distill.
+
+## Sources
+
+_(none yet)_
+
+## Projects
+
+_(none yet)_
+
+## Entities
+
+_(none yet)_
+
+## Concepts
+
+_(none yet)_
+
+## Synthesis
+
+_(none yet)_
diff --git a/packages/plugins/plugin-llm-wiki/templates/wiki/log.md b/packages/plugins/plugin-llm-wiki/templates/wiki/log.md
new file mode 100644
index 0000000000..6b101ab13a
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/templates/wiki/log.md
@@ -0,0 +1,10 @@
+# Log
+
+Append-only chronological record of wiki operations.
+
+## [2026-05-03] setup | wiki initialized
+- created `AGENTS.md` (schema)
+- created `raw/` for source documents
+- created `wiki/` skeleton: `index.md`, `log.md`, `sources/`, `projects/`, `entities/`, `concepts/`, `synthesis/`
+- created `wiki/projects/` for Paperclip project overviews and standups
+- pattern reference: `IDEA.md` (Karpathy "LLM Wiki" gist, https://gist.github.com/karpathy/442a6bf555914893e9891c11519de94f)
diff --git a/packages/plugins/plugin-llm-wiki/templates/wiki/projects/.gitkeep b/packages/plugins/plugin-llm-wiki/templates/wiki/projects/.gitkeep
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/templates/wiki/projects/.gitkeep
@@ -0,0 +1 @@
+
diff --git a/packages/plugins/plugin-llm-wiki/templates/wiki/sources/.gitkeep b/packages/plugins/plugin-llm-wiki/templates/wiki/sources/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/plugins/plugin-llm-wiki/templates/wiki/synthesis/.gitkeep b/packages/plugins/plugin-llm-wiki/templates/wiki/synthesis/.gitkeep
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/packages/plugins/plugin-llm-wiki/tests/issue-attachments.spec.ts b/packages/plugins/plugin-llm-wiki/tests/issue-attachments.spec.ts
new file mode 100644
index 0000000000..776348fad6
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/tests/issue-attachments.spec.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vitest";
+import { readIngestOperationIssueId, uploadIssueAttachmentFile } from "../src/ui/issue-attachments.js";
+
+describe("LLM Wiki issue attachment uploads", () => {
+ it("reads the ingest operation issue id from the action result", () => {
+ expect(readIngestOperationIssueId({
+ operation: {
+ issue: {
+ id: "issue-1",
+ },
+ },
+ })).toBe("issue-1");
+ });
+
+ it("rejects an ingest result that cannot identify the created issue", () => {
+ expect(() => readIngestOperationIssueId({ operation: { issue: null } }))
+ .toThrow("did not return an issue id");
+ });
+
+ it("uploads the original file to the created ingest task", async () => {
+ const file = new File(["hello"], "source notes.md", { type: "text/markdown" });
+ const calls: Array<{ input: string; init: RequestInit }> = [];
+ const fetchImpl = async (input: string, init: RequestInit) => {
+ calls.push({ input, init });
+ return new Response(JSON.stringify({ id: "attachment-1" }), {
+ status: 201,
+ headers: { "Content-Type": "application/json" },
+ });
+ };
+
+ await expect(uploadIssueAttachmentFile({
+ companyId: "company 1",
+ issueId: "issue/1",
+ file,
+ fetchImpl,
+ })).resolves.toEqual({ id: "attachment-1" });
+
+ expect(calls).toHaveLength(1);
+ expect(calls[0]?.input).toBe("/api/companies/company%201/issues/issue%2F1/attachments");
+ expect(calls[0]?.init.method).toBe("POST");
+ expect(calls[0]?.init.credentials).toBe("include");
+ const body = calls[0]?.init.body;
+ expect(body).toBeInstanceOf(FormData);
+ expect((body as FormData).get("file")).toBe(file);
+ });
+
+ it("surfaces server upload errors", async () => {
+ const fetchImpl = async () => new Response(JSON.stringify({ error: "Attachment exceeds 10 bytes" }), {
+ status: 422,
+ headers: { "Content-Type": "application/json" },
+ });
+
+ await expect(uploadIssueAttachmentFile({
+ companyId: "company-1",
+ issueId: "issue-1",
+ file: new File(["hello"], "source.txt"),
+ fetchImpl,
+ })).rejects.toThrow("Attachment exceeds 10 bytes");
+ });
+});
diff --git a/packages/plugins/plugin-llm-wiki/tests/plugin.spec.ts b/packages/plugins/plugin-llm-wiki/tests/plugin.spec.ts
new file mode 100644
index 0000000000..69dbf26b35
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/tests/plugin.spec.ts
@@ -0,0 +1,3746 @@
+import { readFileSync } from "node:fs";
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { createTestHarness } from "@paperclipai/plugin-sdk/testing";
+import type { Agent, Issue, PluginManagedRoutineResolution, Project } from "@paperclipai/plugin-sdk";
+import manifest, {
+ CURSOR_WINDOW_ROUTINE_KEY,
+ INDEX_REFRESH_ROUTINE_KEY,
+ NIGHTLY_LINT_ROUTINE_KEY,
+ PAPERCLIP_DISTILL_SKILL_KEY,
+ WIKI_MAINTAINER_AGENT_KEY,
+ WIKI_MAINTAINER_SKILL_CANONICAL_KEY,
+ WIKI_MAINTAINER_SKILL_KEY,
+ WIKI_MANAGED_SKILL_CANONICAL_KEYS,
+ WIKI_MANAGED_SKILL_KEYS,
+ WIKI_MAINTENANCE_ROUTINE_KEYS,
+ WIKI_PROJECT_KEY,
+} from "../src/manifest.js";
+import {
+ DEFAULT_AGENT_INSTRUCTION_FILES,
+ DEFAULT_AGENT_INSTRUCTIONS,
+ DEFAULT_IDEA,
+ DEFAULT_INDEX,
+ DEFAULT_LOG,
+ DEFAULT_WIKI_SCHEMA,
+ KARPATHY_LLM_WIKI_GIST_URL,
+ LINT_PROMPT,
+ QUERY_PROMPT,
+} from "../src/templates.js";
+import { SettingsPage, SidebarLink, WikiPage, WikiRouteSidebar } from "../src/ui/index.js";
+import plugin from "../src/worker.js";
+import { OPERATION_ORIGIN_KIND, type WikiSkillResource } from "../src/wiki.js";
+
+const COMPANY_ID = "11111111-1111-4111-8111-111111111111";
+const OTHER_COMPANY_ID = "99999999-9999-4999-8999-999999999999";
+const ORIGINAL_DEPLOYMENT_MODE = process.env.PAPERCLIP_DEPLOYMENT_MODE;
+const ORIGINAL_DEPLOYMENT_EXPOSURE = process.env.PAPERCLIP_DEPLOYMENT_EXPOSURE;
+type TestBridgeGlobal = typeof globalThis & {
+ __paperclipPluginBridge__?: {
+ sdkUi?: Record<string, unknown>;
+ };
+};
+const packageJson = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as {
+ dependencies?: Record<string, string>;
+ devDependencies?: Record<string, string>;
+ peerDependencies?: Record<string, string>;
+};
+const DEFAULT_MANAGED_SKILL = {
+ status: "resolved",
+ skillId: "skill-1",
+ resourceKey: WIKI_MAINTAINER_SKILL_KEY,
+ details: {
+ name: "LLM Wiki Maintainer",
+ key: WIKI_MAINTAINER_SKILL_CANONICAL_KEY,
+ description: "Use the LLM Wiki plugin tools to maintain a cited local company wiki.",
+ },
+ skill: {
+ id: "skill-1",
+ name: "LLM Wiki Maintainer",
+ key: WIKI_MAINTAINER_SKILL_CANONICAL_KEY,
+ description: "Use the LLM Wiki plugin tools to maintain a cited local company wiki.",
+ },
+};
+const DEFAULT_MANAGED_SKILLS = WIKI_MANAGED_SKILL_KEYS.map((skillKey, index) => ({
+ status: "resolved",
+ skillId: `skill-${index + 1}`,
+ resourceKey: skillKey,
+ details: skillKey === WIKI_MAINTAINER_SKILL_KEY
+ ? DEFAULT_MANAGED_SKILL.details
+ : {
+ name: skillKey.split("-").map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" "),
+ key: WIKI_MANAGED_SKILL_CANONICAL_KEYS[index],
+ description: null,
+ },
+ skill: skillKey === WIKI_MAINTAINER_SKILL_KEY
+ ? DEFAULT_MANAGED_SKILL.skill
+ : {
+ id: `skill-${index + 1}`,
+ name: skillKey.split("-").map((part) => `${part[0]?.toUpperCase() ?? ""}${part.slice(1)}`).join(" "),
+ key: WIKI_MANAGED_SKILL_CANONICAL_KEYS[index],
+ description: null,
+ },
+}));
+
+let mockPathname = "/PAP/wiki";
+let mockSearch = "";
+let mockAutoSelectFile: string | null = null;
+let mockNavigatedTo: string | null = null;
+let mockOverviewFolder: Record<string, unknown> | null = null;
+let mockSettingsFolder: Record<string, unknown> | null = null;
+let mockSettingsManagedAgent: Record<string, unknown> | null = null;
+let mockSettingsManagedRoutines: Array<Record<string, unknown>> = [];
+let mockSettingsManagedSkills: Array<Record<string, unknown>> = [];
+let mockDistillationOverviewData: Record<string, unknown> | null = null;
+let mockPageContentsByPath: Record<string, string> = {};
+let mockPageMetadataByPath: Record<string, {
+ backlinks?: string[];
+ sourceRefs?: Array<Record<string, unknown> | string>;
+}> = {};
+
+beforeEach(() => {
+ if (ORIGINAL_DEPLOYMENT_MODE == null) {
+ delete process.env.PAPERCLIP_DEPLOYMENT_MODE;
+ } else {
+ process.env.PAPERCLIP_DEPLOYMENT_MODE = ORIGINAL_DEPLOYMENT_MODE;
+ }
+ if (ORIGINAL_DEPLOYMENT_EXPOSURE == null) {
+ delete process.env.PAPERCLIP_DEPLOYMENT_EXPOSURE;
+ } else {
+ process.env.PAPERCLIP_DEPLOYMENT_EXPOSURE = ORIGINAL_DEPLOYMENT_EXPOSURE;
+ }
+ mockPathname = "/PAP/wiki";
+ mockSearch = "";
+ mockAutoSelectFile = null;
+ mockNavigatedTo = null;
+ mockOverviewFolder = null;
+ mockSettingsFolder = null;
+ mockSettingsManagedAgent = null;
+ mockSettingsManagedRoutines = [];
+ mockSettingsManagedSkills = [];
+ mockDistillationOverviewData = null;
+ mockPageContentsByPath = {};
+ mockPageMetadataByPath = {};
+ (globalThis as TestBridgeGlobal).__paperclipPluginBridge__ = {
+ sdkUi: {
+ usePluginData: (key: string, params?: Record<string, unknown>) => {
+ if (key === "overview") {
+ return {
+ data: {
+ status: "ok",
+ checkedAt: new Date().toISOString(),
+ wikiId: "default",
+ folder: mockOverviewFolder ?? {
+ configured: true,
+ path: "/tmp/company-wiki",
+ realPath: "/tmp/company-wiki",
+ access: "readWrite",
+ readable: true,
+ writable: true,
+ requiredDirectories: [],
+ requiredFiles: [],
+ missingDirectories: [],
+ missingFiles: [],
+ healthy: true,
+ problems: [],
+ checkedAt: new Date().toISOString(),
+ },
+ managedAgent: { status: "resolved", source: "managed", agentId: "agent-1", resourceKey: "wiki-maintainer", details: { name: "Wiki Maintainer", status: "idle", adapterType: "claude_local", icon: "book-open", urlKey: "wiki-maintainer" } },
+ managedProject: { status: "resolved", projectId: "project-1", details: { name: "LLM Wiki", status: "in_progress" } },
+ managedSkills: DEFAULT_MANAGED_SKILLS,
+ operationCount: 0,
+ eventIngestion: {
+ enabled: false,
+ sources: { issues: false, comments: false, documents: false },
+ wikiId: "default",
+ maxCharacters: 12000,
+ },
+ capabilities: [],
+ prompts: { query: QUERY_PROMPT, lint: LINT_PROMPT },
+ },
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ }
+ if (key === "spaces") {
+ return {
+ data: {
+ spaces: [
+ {
+ id: "space-default",
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ slug: "default",
+ displayName: "default",
+ spaceType: "managed",
+ folderMode: "managed_subfolder",
+ rootFolderKey: "wiki-root",
+ pathPrefix: null,
+ configuredRootPath: null,
+ accessScope: "shared",
+ ownerUserId: null,
+ ownerAgentId: null,
+ teamKey: null,
+ settings: {},
+ status: "active",
+ createdAt: null,
+ updatedAt: null,
+ },
+ ],
+ },
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ }
+ if (key === "pages") {
+ return {
+ data: {
+ pages: [
+ {
+ path: "wiki/concepts/sidebar-navigation.md",
+ title: "Sidebar navigation",
+ pageType: "concepts",
+ backlinkCount: 0,
+ sourceCount: 0,
+ contentHash: "abc123",
+ updatedAt: new Date().toISOString(),
+ },
+ ],
+ sources: [
+ {
+ rawPath: "raw/sidebar-notes.md",
+ title: "Sidebar notes",
+ sourceType: "text",
+ url: null,
+ status: "captured",
+ createdAt: new Date().toISOString(),
+ },
+ ],
+ },
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ }
+ if (key === "settings") {
+ return {
+ data: {
+ status: "ok",
+ checkedAt: new Date().toISOString(),
+ wikiId: "default",
+ folder: mockSettingsFolder ?? {
+ configured: true,
+ path: "/tmp/company-wiki",
+ realPath: "/tmp/company-wiki",
+ access: "readWrite",
+ readable: true,
+ writable: true,
+ requiredDirectories: [],
+ requiredFiles: [],
+ missingDirectories: [],
+ missingFiles: [],
+ healthy: true,
+ problems: [],
+ checkedAt: new Date().toISOString(),
+ },
+ managedAgent: mockSettingsManagedAgent ?? { status: "resolved", source: "managed", agentId: "agent-1", resourceKey: "wiki-maintainer", details: { name: "Wiki Maintainer", status: "idle", adapterType: "claude_local", icon: "book-open", urlKey: "wiki-maintainer" } },
+ managedProject: { status: "resolved", source: "managed", projectId: "project-1", resourceKey: "llm-wiki", details: { name: "LLM Wiki", status: "in_progress" } },
+ managedSkills: mockSettingsManagedSkills.length > 0 ? mockSettingsManagedSkills : DEFAULT_MANAGED_SKILLS,
+ managedRoutines: mockSettingsManagedRoutines,
+ managedRoutine: mockSettingsManagedRoutines[0] ?? null,
+ eventIngestion: {
+ enabled: false,
+ sources: { issues: false, comments: false, documents: false },
+ wikiId: "default",
+ maxCharacters: 12000,
+ },
+ agentOptions: [{ id: "agent-1", name: "Wiki Maintainer", status: "idle", icon: "book-open", urlKey: "wiki-maintainer" }],
+ projectOptions: [{ id: "project-1", name: "LLM Wiki", status: "in_progress", color: "#2563eb" }],
+ capabilities: [],
+ },
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ }
+ if (key === "space") {
+ return {
+ data: {
+ id: "space-default",
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ slug: "default",
+ displayName: "default",
+ spaceType: "managed",
+ folderMode: "managed_subfolder",
+ rootFolderKey: "wiki-root",
+ pathPrefix: null,
+ configuredRootPath: null,
+ accessScope: "shared",
+ ownerUserId: null,
+ ownerAgentId: null,
+ teamKey: null,
+ settings: {},
+ status: "active",
+ createdAt: null,
+ updatedAt: null,
+ relativeRoot: "",
+ folder: {
+ configured: true,
+ path: "/tmp/company-wiki",
+ realPath: "/tmp/company-wiki",
+ access: "readWrite",
+ readable: true,
+ writable: true,
+ requiredDirectories: ["raw", "wiki"],
+ requiredFiles: ["AGENTS.md"],
+ missingDirectories: [],
+ missingFiles: [],
+ healthy: true,
+ problems: [],
+ checkedAt: new Date().toISOString(),
+ },
+ },
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ }
+ if (key === "distillation-overview") {
+ return {
+ data: mockDistillationOverviewData,
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ }
+ if (key === "page-content") {
+ const path = typeof params?.path === "string" ? params.path : "wiki/index.md";
+ const contents = mockPageContentsByPath[path] ?? (path === "AGENTS.md"
+ ? DEFAULT_AGENT_INSTRUCTIONS
+ : path === "IDEA.md"
+ ? DEFAULT_IDEA
+ : `# ${path}\n`);
+ return {
+ data: {
+ wikiId: "default",
+ path,
+ contents,
+ title: path === "AGENTS.md" ? "LLM Wiki Maintainer" : path.replace(/\.md$/, ""),
+ pageType: path === "AGENTS.md" ? null : "index",
+ backlinks: mockPageMetadataByPath[path]?.backlinks ?? [],
+ sourceRefs: mockPageMetadataByPath[path]?.sourceRefs ?? [],
+ updatedAt: null,
+ hash: "abc123",
+ },
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ }
+ return { data: null, loading: false, error: null, refresh: () => undefined };
+ },
+ usePluginAction: () => async () => ({}),
+ usePluginToast: () => () => null,
+ useHostNavigation: () => ({
+ resolveHref: (to: string) => `/PAP${to.startsWith("/") ? to : `/${to}`}`,
+ navigate: (to: string) => { mockNavigatedTo = to; },
+ linkProps: (to: string) => ({
+ href: `/PAP${to.startsWith("/") ? to : `/${to}`}`,
+ onClick: () => undefined,
+ }),
+ }),
+ useHostLocation: () => ({
+ pathname: mockPathname,
+ search: mockSearch,
+ hash: "",
+ }),
+ FileTree: (props: {
+ nodes: Array<{ name: string; path: string; kind: string; children?: Array<{ name: string; path: string; kind: string }> }>;
+ selectedFile?: string | null;
+ ariaLabel?: string;
+ wrapLabels?: boolean;
+ fileBadges?: Record<string, unknown>;
+ onSelectFile?: (path: string) => void;
+ }) => {
+ if (mockAutoSelectFile) props.onSelectFile?.(mockAutoSelectFile);
+ return createElement(
+ "div",
+ {
+ role: "tree",
+ "aria-label": props.ariaLabel,
+ "data-selected-file": props.selectedFile ?? "",
+ "data-wrap-labels": String(props.wrapLabels),
+ "data-has-file-badges": String(Boolean(props.fileBadges && Object.keys(props.fileBadges).length > 0)),
+ },
+ props.nodes.map((node) => createElement("div", { key: node.path }, node.name)),
+ );
+ },
+ IssuesList: (props: {
+ projectId?: string | null;
+ filters?: { originKindPrefix?: string };
+ }) => createElement(
+ "div",
+ { "data-testid": "plugin-issues-list" },
+ `Issues table · ${props.projectId ?? "no-project"} · ${props.filters?.originKindPrefix ?? "no-origin-filter"}`,
+ ),
+ MarkdownBlock: ({ content }: { content: string }) => createElement("div", { "data-testid": "markdown-block" }, content),
+ MarkdownEditor: ({ value, onChange }: { value: string; onChange: (value: string) => void }) => createElement("textarea", {
+ "data-testid": "markdown-editor",
+ value,
+ onChange: (event: { currentTarget: { value: string } }) => onChange(event.currentTarget.value),
+ }),
+ AssigneePicker: (props: {
+ value: string;
+ placeholder?: string;
+ onChange: (value: string, selection: { assigneeAgentId: string | null; assigneeUserId: string | null }) => void;
+ }) => createElement(
+ "button",
+ {
+ type: "button",
+ "data-testid": "assignee-picker",
+ onClick: () => props.onChange("agent:agent-1", { assigneeAgentId: "agent-1", assigneeUserId: null }),
+ },
+ props.value === "agent:agent-1" ? "Wiki Maintainer" : (props.placeholder ?? "Select assignee"),
+ ),
+ ProjectPicker: (props: {
+ value: string;
+ placeholder?: string;
+ onChange: (projectId: string) => void;
+ }) => createElement(
+ "button",
+ {
+ type: "button",
+ "data-testid": "project-picker",
+ onClick: () => props.onChange("project-1"),
+ },
+ props.value === "project-1" ? "LLM Wiki" : (props.placeholder ?? "Project"),
+ ),
+ ManagedRoutinesList: (props: {
+ routines: Array<{
+ key: string;
+ title: string;
+ href?: string | null;
+ projectId?: string | null;
+ assigneeAgentId?: string | null;
+ defaultDrift?: { changedFields: string[] } | null;
+ }>;
+ agents?: Array<{ id: string; name: string }>;
+ projects?: Array<{ id: string; name: string }>;
+ onReset?: (routine: { key: string; title: string }) => void;
+ }) => createElement(
+ "div",
+ { "data-testid": "managed-routines-list" },
+ props.routines.map((routine) => {
+ const agent = props.agents?.find((item) => item.id === routine.assigneeAgentId);
+ const project = props.projects?.find((item) => item.id === routine.projectId);
+ return createElement(
+ "div",
+ { key: routine.key },
+ createElement("span", null, routine.title),
+ createElement("button", null, "Run now"),
+ createElement("button", { role: "switch" }, "On"),
+ routine.href ? createElement("a", { href: `/PAP${routine.href}` }, "Configure") : null,
+ routine.defaultDrift?.changedFields.length
+ ? createElement("span", null, `Plugin defaults changed: ${routine.defaultDrift.changedFields.join(", ")}`)
+ : null,
+ routine.defaultDrift?.changedFields.length && props.onReset
+ ? createElement("button", null, "Reset")
+ : null,
+ createElement("span", null, `${project?.name ?? "No project"} · ${agent?.name ?? "No default agent"}`),
+ );
+ }),
+ ),
+ },
+ };
+});
+
+afterEach(() => {
+ if (ORIGINAL_DEPLOYMENT_MODE == null) {
+ delete process.env.PAPERCLIP_DEPLOYMENT_MODE;
+ } else {
+ process.env.PAPERCLIP_DEPLOYMENT_MODE = ORIGINAL_DEPLOYMENT_MODE;
+ }
+ if (ORIGINAL_DEPLOYMENT_EXPOSURE == null) {
+ delete process.env.PAPERCLIP_DEPLOYMENT_EXPOSURE;
+ } else {
+ process.env.PAPERCLIP_DEPLOYMENT_EXPOSURE = ORIGINAL_DEPLOYMENT_EXPOSURE;
+ }
+ delete (globalThis as TestBridgeGlobal).__paperclipPluginBridge__;
+});
+
+function wikiMaintainerAgent(): Agent {
+ const now = new Date();
+ return {
+ id: "22222222-2222-4222-8222-222222222222",
+ companyId: COMPANY_ID,
+ name: "Wiki Maintainer",
+ urlKey: "wiki-maintainer",
+ role: "general",
+ title: "LLM Wiki Maintainer",
+ icon: "book-open",
+ status: "idle",
+ reportsTo: null,
+ capabilities: "Maintains the wiki",
+ adapterType: "claude_local",
+ adapterConfig: {},
+ runtimeConfig: {},
+ budgetMonthlyCents: 0,
+ spentMonthlyCents: 0,
+ pauseReason: null,
+ pausedAt: null,
+ permissions: { canCreateAgents: false },
+ lastHeartbeatAt: null,
+ metadata: {
+ paperclipManagedResource: {
+ pluginKey: manifest.id,
+ resourceKind: "agent",
+ resourceKey: "wiki-maintainer",
+ },
+ },
+ createdAt: now,
+ updatedAt: now,
+ };
+}
+
+function existingAgent(): Agent {
+ return {
+ ...wikiMaintainerAgent(),
+ id: "44444444-4444-4444-8444-444444444444",
+ name: "Existing Knowledge Agent",
+ urlKey: "existing-knowledge-agent",
+ title: "Knowledge Agent",
+ metadata: {},
+ };
+}
+
+function existingProject(): Project {
+ const now = new Date();
+ return {
+ id: "55555555-5555-4555-8555-555555555555",
+ companyId: COMPANY_ID,
+ urlKey: "existing-wiki-project",
+ goalId: null,
+ goalIds: [],
+ goals: [],
+ name: "Existing Wiki Project",
+ description: "Existing project selected for wiki operations.",
+ status: "in_progress",
+ leadAgentId: null,
+ targetDate: null,
+ color: "#0f766e",
+ env: null,
+ pauseReason: null,
+ pausedAt: null,
+ executionWorkspacePolicy: null,
+ codebase: {
+ workspaceId: null,
+ repoUrl: null,
+ repoRef: null,
+ defaultRef: null,
+ repoName: null,
+ localFolder: null,
+ managedFolder: "/tmp/existing-wiki-project",
+ effectiveLocalFolder: "/tmp/existing-wiki-project",
+ origin: "managed_checkout",
+ },
+ workspaces: [],
+ primaryWorkspace: null,
+ managedByPlugin: null,
+ archivedAt: null,
+ createdAt: now,
+ updatedAt: now,
+ };
+}
+
+function paperclipIssue(overrides: Partial<Issue> = {}): Issue {
+ const now = new Date();
+ return {
+ id: "66666666-6666-4666-8666-666666666666",
+ companyId: COMPANY_ID,
+ projectId: null,
+ projectWorkspaceId: null,
+ goalId: null,
+ parentId: null,
+ title: "Design event ingestion controls",
+ description: "Decide which Paperclip issues, comments, and documents can be ingested into the wiki.",
+ status: "todo",
+ workMode: "standard",
+ priority: "medium",
+ assigneeAgentId: null,
+ assigneeUserId: null,
+ checkoutRunId: null,
+ executionRunId: null,
+ executionAgentNameKey: null,
+ executionLockedAt: null,
+ createdByAgentId: null,
+ createdByUserId: null,
+ issueNumber: 3204,
+ identifier: "PAP-3204",
+ originId: null,
+ originRunId: null,
+ originFingerprint: null,
+ requestDepth: 0,
+ billingCode: null,
+ assigneeAdapterOverrides: null,
+ executionPolicy: null,
+ executionState: null,
+ executionWorkspaceId: null,
+ executionWorkspacePreference: null,
+ executionWorkspaceSettings: null,
+ startedAt: null,
+ completedAt: null,
+ cancelledAt: null,
+ hiddenAt: null,
+ createdAt: now,
+ updatedAt: now,
+ ...overrides,
+ };
+}
+
+function wikiSpaceRow(space: Record<string, unknown>) {
+ return {
+ id: space.id,
+ company_id: space.companyId ?? COMPANY_ID,
+ wiki_id: space.wikiId ?? "default",
+ slug: space.slug,
+ display_name: space.displayName,
+ space_type: space.spaceType ?? "local_folder",
+ folder_mode: space.folderMode ?? "managed_subfolder",
+ root_folder_key: space.rootFolderKey ?? "wiki-root",
+ path_prefix: space.pathPrefix ?? `spaces/${space.slug}`,
+ configured_root_path: space.configuredRootPath ?? null,
+ access_scope: space.accessScope ?? "shared",
+ owner_user_id: space.ownerUserId ?? null,
+ owner_agent_id: space.ownerAgentId ?? null,
+ team_key: space.teamKey ?? null,
+ settings: space.settings ?? {},
+ status: space.status ?? "active",
+ created_at: space.createdAt ?? null,
+ updated_at: space.updatedAt ?? null,
+ };
+}
+
+function defaultWikiSpaceRow() {
+ return wikiSpaceRow({
+ id: "77777777-7777-4777-8777-7777777777d0",
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ slug: "default",
+ displayName: "default",
+ pathPrefix: null,
+ accessScope: "shared",
+ settings: {},
+ });
+}
+
+function mockPersistedWikiSpace(harness: ReturnType<typeof createTestHarness>, space: Record<string, unknown>) {
+ const row = wikiSpaceRow(space);
+ const originalQuery = harness.ctx.db.query.bind(harness.ctx.db);
+ harness.ctx.db.query = async <T,>(sql: string, params?: unknown[]) => {
+ if (sql.includes("wiki_spaces") && params?.[2] === row.slug) {
+ return [row] as T[];
+ }
+ if (sql.includes("wiki_spaces") && sql.includes("ORDER BY CASE WHEN slug = 'default'")) {
+ return [defaultWikiSpaceRow(), row] as T[];
+ }
+ return originalQuery<T>(sql, params);
+ };
+}
+
+describe("LLM Wiki plugin scaffold", () => {
+ it("declares standalone plugin surfaces without core wiki coupling", () => {
+ expect(manifest.id).toBe("paperclipai.plugin-llm-wiki");
+ expect(manifest.entrypoints.worker).toBe("./dist/worker.js");
+ expect(manifest.entrypoints.ui).toBe("./dist/ui");
+ expect(manifest.database?.namespaceSlug).toBe("llm_wiki");
+ expect(manifest.localFolders?.[0]?.requiredDirectories).toContain("wiki/projects");
+ expect(manifest.localFolders?.[0]?.requiredDirectories).not.toContain("projects");
+ expect(manifest.localFolders?.[0]?.requiredFiles).toEqual([
+ "AGENTS.md",
+ "IDEA.md",
+ "wiki/index.md",
+ "wiki/log.md",
+ ]);
+ expect(manifest.agents?.[0]?.agentKey).toBe("wiki-maintainer");
+ expect(manifest.agents?.[0]?.adapterType).toBe("claude_local");
+ expect(manifest.agents?.[0]?.adapterConfig).toMatchObject({
+ dangerouslySkipPermissions: false,
+ dangerouslyBypassApprovalsAndSandbox: false,
+ sandbox: true,
+ });
+ expect(manifest.agents?.[0]?.instructions?.entryFile).toBe("AGENTS.md");
+ expect(manifest.agents?.[0]?.instructions?.content).toContain("You are the maintainer of this personal wiki");
+ expect(manifest.agents?.[0]?.instructions?.files?.["AGENTS.md"]).toContain("{{localFolders.wiki-root.path}}");
+ expect(manifest.agents?.[0]?.instructions?.assetPath).toBe("agents/wiki-maintainer");
+ expect(manifest.projects?.[0]?.projectKey).toBe("llm-wiki");
+ expect(manifest.routines?.map((routine) => routine.routineKey)).toEqual([
+ CURSOR_WINDOW_ROUTINE_KEY,
+ NIGHTLY_LINT_ROUTINE_KEY,
+ INDEX_REFRESH_ROUTINE_KEY,
+ ]);
+ expect(manifest.routines).toEqual(
+ WIKI_MAINTENANCE_ROUTINE_KEYS.map((routineKey) => expect.objectContaining({
+ routineKey,
+ assigneeRef: { resourceKind: "agent", resourceKey: WIKI_MAINTAINER_AGENT_KEY },
+ projectRef: { resourceKind: "project", resourceKey: WIKI_PROJECT_KEY },
+ concurrencyPolicy: "skip_if_active",
+ catchUpPolicy: "skip_missed",
+ issueTemplate: expect.objectContaining({
+ surfaceVisibility: "plugin_operation",
+ billingCode: expect.stringMatching(/^plugin-llm-wiki:/),
+ }),
+ })),
+ );
+ for (const routine of manifest.routines ?? []) {
+ expect(routine.description).toContain("Run procedure:");
+ expect(routine.description).toContain("Target space: default (slug: default)");
+ expect(routine.description).toContain("spaceSlug `default`");
+ expect(routine.description).toContain("AGENTS.md");
+ expect(routine.description).toContain("wiki/log.md");
+ }
+ expect(manifest.tools?.map((tool) => tool.name)).toEqual([
+ "wiki_search",
+ "wiki_read_page",
+ "wiki_write_page",
+ "wiki_propose_patch",
+ "wiki_list_sources",
+ "wiki_read_source",
+ "wiki_append_log",
+ "wiki_update_index",
+ "wiki_list_backlinks",
+ "wiki_list_pages",
+ ]);
+ expect(manifest.ui?.slots?.map((slot) => slot.type)).toEqual([
+ "sidebar",
+ "page",
+ "routeSidebar",
+ ]);
+ expect(manifest.capabilities).not.toContain("instance.settings.register");
+ expect(manifest.instanceConfigSchema).toBeUndefined();
+ const routeSidebarSlot = manifest.ui?.slots?.find((slot) => slot.type === "routeSidebar");
+ expect(routeSidebarSlot).toMatchObject({
+ id: "wiki-route-sidebar",
+ exportName: "WikiRouteSidebar",
+ routePath: "wiki",
+ });
+ expect(packageJson.dependencies).toBeUndefined();
+ expect(packageJson.devDependencies?.react).toBeUndefined();
+ expect(packageJson.devDependencies?.["react-dom"]).toBeDefined();
+ expect(packageJson.devDependencies?.["@types/react-dom"]).toBeDefined();
+ expect(packageJson.peerDependencies?.react).toBe(">=18");
+ });
+
+ it("renders a host-aligned sidebar link with an open-book icon", () => {
+ const markup = renderToStaticMarkup(createElement(SidebarLink, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain('href="/PAP/wiki"');
+ expect(markup).toContain("gap-2.5 px-3 py-2 text-[13px] font-medium");
+ expect(markup).toContain("hover:bg-accent/50 hover:text-foreground");
+ expect(markup).toContain("<svg");
+ expect(markup).toContain("M12 7v14");
+ expect(markup).not.toContain("Wiki plugin");
+ expect(markup).not.toContain("border-radius:999");
+ expect(markup).not.toContain("📖");
+ });
+
+ it("ships Karpathy-pattern schema and workflow prompts by default", () => {
+ expect(DEFAULT_WIKI_SCHEMA).toContain("You are the maintainer of this personal wiki");
+ expect(DEFAULT_WIKI_SCHEMA).toContain("raw/");
+ expect(DEFAULT_WIKI_SCHEMA).toContain("wiki/projects/<project-slug>/standup.md");
+ expect(DEFAULT_WIKI_SCHEMA).toContain("wiki/projects/<project-slug>/index.md");
+ expect(DEFAULT_WIKI_SCHEMA).toContain("Do not create a top-level `projects/` directory");
+ expect(DEFAULT_WIKI_SCHEMA).not.toContain("\n├── projects/");
+ expect(DEFAULT_WIKI_SCHEMA).toContain("wiki/");
+ expect(DEFAULT_WIKI_SCHEMA).toContain("AGENTS.md");
+ expect(DEFAULT_IDEA).toContain("persistent, compounding artifact");
+ expect(DEFAULT_AGENT_INSTRUCTIONS).toContain("You are the maintainer of this personal wiki");
+ expect(DEFAULT_AGENT_INSTRUCTIONS).toContain("ingest, query, lint, index, or maintenance work");
+ expect(DEFAULT_AGENT_INSTRUCTIONS).toContain("dedicated LLM Wiki skill installed on this agent");
+ expect(DEFAULT_AGENT_INSTRUCTIONS).not.toContain("skills/<name>/SKILL.md");
+ expect(DEFAULT_AGENT_INSTRUCTION_FILES["skills/wiki-ingest/SKILL.md"]).toBeUndefined();
+ expect(manifest.skills?.map((skill) => skill.skillKey)).toEqual([...WIKI_MANAGED_SKILL_KEYS]);
+ expect(manifest.agents?.[0]?.adapterConfig?.paperclipSkillSync).toEqual({
+ desiredSkills: WIKI_MANAGED_SKILL_CANONICAL_KEYS,
+ });
+ expect(QUERY_PROMPT).toContain("wiki-query skill");
+ expect(QUERY_PROMPT).not.toContain("skills/wiki-query/SKILL.md");
+ expect(QUERY_PROMPT).toContain("filed back into wiki/");
+ expect(LINT_PROMPT).toContain("wiki-lint skill");
+ expect(LINT_PROMPT).not.toContain("skills/wiki-lint/SKILL.md");
+ expect(LINT_PROMPT).toContain("severity");
+ });
+
+ it("renders the route-scoped Wiki sidebar with tool actions, page navigation, and a back link", () => {
+ const markup = renderToStaticMarkup(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain('href="/PAP/dashboard"');
+ expect(markup).toContain("PAP");
+ expect(markup).toContain('href="/PAP/wiki/query"');
+ expect(markup).not.toContain('href="/PAP/wiki/lint"');
+ expect(markup).toContain('href="/PAP/wiki/history"');
+ expect(markup).toContain('href="/PAP/wiki/settings"');
+ expect(markup).not.toContain('href="/PAP/wiki/operations"');
+ // Add Content reuses the legacy /wiki/ingest route so deep links still work.
+ expect(markup).toContain('href="/PAP/wiki/ingest"');
+ expect(markup).toContain('aria-label="Wiki primary"');
+ expect(markup).toContain('aria-label="Wiki secondary"');
+ for (const label of ["Ask", "Add Content", "History", "Settings", "Shared Spaces", "default", "raw", "wiki", "AGENTS.md", "IDEA.md"]) {
+ expect(markup).toContain(label);
+ }
+ expect(markup).not.toContain(">Lint</span>");
+ expect(markup).not.toContain(">Ingest</span>");
+ expect(markup).not.toContain(">Operations</span>");
+ expect(markup).not.toContain('text-sm font-bold text-foreground">Wiki');
+ expect(markup).not.toContain("Browse");
+ expect(markup).not.toContain(">Query<");
+ expect(markup).toContain('role="tree"');
+ expect(markup).toContain('data-selected-file=""');
+ expect(markup).toContain('data-wrap-labels="false"');
+ expect(markup).toContain('data-has-file-badges="false"');
+ });
+
+ it("routes legacy Wiki operations URLs to the History issue table", () => {
+ mockPathname = "/PAP/wiki/operations";
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Issues table · project-1 · plugin:paperclipai.plugin-llm-wiki:operation");
+ expect(markup).not.toContain("Recent runs");
+ expect(markup).not.toContain(">Operations</h2>");
+ });
+
+ it("loads AGENTS.md from the Wiki page and exposes an edit affordance", () => {
+ mockPathname = "/PAP/wiki/page/templates/AGENTS.md";
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("AGENTS");
+ expect(markup).toContain(">AGENTS.md</h1>");
+ expect(markup).not.toContain(">LLM Wiki Maintainer</h1>");
+ expect(markup).toContain("You are the maintainer of this personal wiki");
+ expect(markup).toContain("wiki-root `AGENTS.md`");
+ expect(markup).toContain("Edit page");
+ expect(markup).toContain("Updated —");
+ expect(markup).not.toContain("0 backlinks");
+ expect(markup).not.toContain("0 sources");
+ expect(markup).not.toContain("abc123");
+ expect(markup).not.toContain("+ Ingest");
+ expect(markup).not.toContain("Folder healthy");
+ });
+
+ it("does not render page footer sources and backlinks", () => {
+ mockPathname = "/PAP/wiki/page/wiki/projects/control-plane/index.md";
+ mockPageContentsByPath["wiki/projects/control-plane/index.md"] = "# Control plane\n\nCurrent project state.";
+ mockPageMetadataByPath["wiki/projects/control-plane/index.md"] = {
+ backlinks: ["wiki/backlinks/hidden-footer-link.md"],
+ sourceRefs: [{ kind: "issue", issueIdentifier: "PAP-FOOTER-1" }],
+ };
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Current project state.");
+ expect(markup).not.toContain(">Sources</");
+ expect(markup).not.toContain(">Backlinks</");
+ expect(markup).not.toContain("PAP-FOOTER-1");
+ expect(markup).not.toContain("hidden-footer-link");
+ });
+
+ it("renders YAML frontmatter as foldable properties without duplicating title", () => {
+ mockPathname = "/PAP/wiki/page/wiki/concepts/sidebar-navigation.md";
+ mockPageContentsByPath["wiki/concepts/sidebar-navigation.md"] = `---
+title: Sidebar navigation
+type: concept
+tags: [paperclip, wiki]
+sources:
+ - raw/sidebar-notes.md
+created: 2026-05-04
+updated: 2026-05-04
+---
+# Sidebar navigation
+
+Route sidebar state stays attached to the selected wiki page.
+`;
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("<summary");
+ expect(markup).toContain("Properties");
+ expect(markup).toContain(">type</dt>");
+ expect(markup).toContain("concept");
+ expect(markup).toContain(">tags</dt>");
+ expect(markup).toContain("paperclip");
+ expect(markup).toContain("wiki");
+ expect(markup).toContain(">sources</dt>");
+ expect(markup).toContain("raw/sidebar-notes.md");
+ expect(markup).toContain("Route sidebar state");
+ expect(markup).not.toContain("title: Sidebar navigation");
+ expect(markup).not.toContain("title</dt>");
+ expect(markup).not.toContain("---");
+ });
+
+ it("renders a foldable on-this-page pane from wiki page headings", () => {
+ mockPathname = "/PAP/wiki/page/wiki/concepts/sidebar-navigation.md";
+ mockPageContentsByPath["wiki/concepts/sidebar-navigation.md"] = `# Sidebar navigation
+
+## Why it matters
+
+Route sidebar state stays attached to the selected wiki page.
+
+### Deep link behavior
+
+Wiki links preserve normal browser navigation.
+
+\`\`\`md
+## Ignored code heading
+\`\`\`
+
+## Why it matters
+
+Duplicate headings receive stable suffixes.
+`;
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain('aria-label="On this page"');
+ expect(markup).toContain('aria-expanded="true"');
+ expect(markup).toContain('aria-current="location"');
+ expect(markup).toContain('href="#why-it-matters"');
+ expect(markup).toContain('href="#deep-link-behavior"');
+ expect(markup).toContain('href="#why-it-matters-2"');
+ expect(markup).not.toContain('href="#ignored-code-heading"');
+ const tocMarkup = markup.slice(
+ markup.indexOf('aria-label="On this page"'),
+ markup.indexOf("</aside>", markup.indexOf('aria-label="On this page"')),
+ );
+ expect(tocMarkup).toContain("position:sticky");
+ expect(tocMarkup).toContain("top:88px");
+ expect(tocMarkup).not.toContain("background:color-mix");
+ expect(tocMarkup).not.toContain("border-radius");
+ });
+
+ it("shows folder repair instead of reading pages when the wiki root is stale", () => {
+ mockPathname = "/PAP/wiki/page/AGENTS.md";
+ mockOverviewFolder = {
+ configured: true,
+ path: "/tmp/deleted-wiki-root",
+ realPath: null,
+ access: "readWrite",
+ readable: false,
+ writable: false,
+ requiredDirectories: ["raw", "wiki"],
+ requiredFiles: ["AGENTS.md"],
+ missingDirectories: ["raw", "wiki"],
+ missingFiles: ["AGENTS.md"],
+ healthy: false,
+ problems: [
+ { code: "missing", message: "Configured local folder cannot be inspected.", path: "/tmp/deleted-wiki-root" },
+ ],
+ checkedAt: new Date().toISOString(),
+ };
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Repair wiki root folder");
+ expect(markup).toContain("/tmp/deleted-wiki-root");
+ expect(markup).toContain("Configured local folder cannot be inspected.");
+ expect(markup).toContain("Repair &amp; bootstrap");
+ expect(markup).not.toContain("Failed to read AGENTS.md");
+ expect(markup).not.toContain(">AGENTS.md</h1>");
+ });
+
+ it("serializes root template pages as regular path segments", () => {
+ mockAutoSelectFile = "AGENTS.md";
+ renderToStaticMarkup(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(mockNavigatedTo).toBe("/wiki/page/AGENTS.md");
+ });
+
+ it("highlights Settings for legacy lint links after lint moved under Settings", () => {
+ mockPathname = "/PAP/wiki/lint";
+ const markup = renderToStaticMarkup(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).not.toContain('href="/PAP/wiki/lint"');
+ const settingsAnchor = markup.match(/<a[^>]*href="\/PAP\/wiki\/settings"[^>]*>/);
+ expect(settingsAnchor?.[0]).toContain('aria-current="page"');
+ expect(settingsAnchor?.[0]).toContain("text-foreground");
+ expect(settingsAnchor?.[0]).not.toContain("bg-accent");
+ const askAnchor = markup.match(/<a[^>]*href="\/PAP\/wiki\/query"[^>]*>/);
+ expect(askAnchor?.[0]).not.toContain('aria-current="page"');
+ });
+
+ it("renders the maintainer settings without plugin metadata or inline AGENTS.md editing", () => {
+ mockPathname = "/PAP/wiki/settings/maintainer";
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Wiki Maintainer");
+ expect(markup).toContain("Adapter: claude local");
+ expect(markup).toContain("Maintainer");
+ expect(markup).toContain("Repair");
+ expect(markup).toContain("Reset to defaults");
+ expect(markup).not.toContain("Provided maintainer");
+ expect(markup).not.toContain("Managed by LLM Wiki");
+ expect(markup).not.toContain("Suggested default");
+ expect(markup).not.toContain("AGENT INSTRUCTIONS");
+ expect(markup).not.toContain("Stable key");
+ expect(markup).not.toContain("Plugin managed default");
+ });
+
+ it("recommends approval when the wiki maintainer is pending board approval", () => {
+ mockPathname = "/PAP/wiki/settings/maintainer";
+ mockSettingsManagedAgent = {
+ status: "created",
+ source: "managed",
+ agentId: "agent-1",
+ resourceKey: "wiki-maintainer",
+ details: { name: "Wiki Maintainer", status: "pending_approval", adapterType: "claude_local", icon: "book-open", urlKey: "wiki-maintainer" },
+ };
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("pending approval");
+ expect(markup).toContain("Approve the agent");
+ expect(markup).toContain("Adapter: claude local");
+ });
+
+ it("renders root settings as a compact health checklist with the shared path picker", () => {
+ mockPathname = "/PAP/wiki/settings";
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain(">Setup</");
+ expect(markup).toContain("Base Folder");
+ expect(markup).toContain("Managed Agents");
+ expect(markup).toContain("Managed Skills");
+ expect(markup).toContain("Managed Projects");
+ expect(markup).toContain("Managed Routines");
+ expect(markup.indexOf(">Managed Agents</h2>")).toBeLessThan(markup.indexOf(">Managed Skills</h2>"));
+ expect(markup.indexOf(">Managed Skills</h2>")).toBeLessThan(markup.indexOf(">Managed Projects</h2>"));
+ expect(markup.indexOf(">Managed Projects</h2>")).toBeLessThan(markup.indexOf(">Managed Routines</h2>"));
+ expect(markup).toContain("Adapter: claude local");
+ expect(markup).toContain("Status: in progress");
+ expect(markup).toContain("Wiki root health checklist");
+ expect(markup).toContain("Health check");
+ expect(markup).toContain("Wiki agents health checklist");
+ expect(markup).toContain("Wiki routines health checklist");
+ expect(markup).toContain("Wiki skills health checklist");
+ expect(markup).toContain("Wiki projects health checklist");
+ const routineChecklistStart = markup.indexOf('aria-label="Wiki routines health checklist"');
+ const routineChecklist = markup.slice(routineChecklistStart);
+ expect(routineChecklist).toContain("left:8px");
+ expect(routineChecklist).toContain("background:oklch(0.38 0.09 145)");
+ expect(routineChecklist).toContain("Process LLM Wiki updates");
+ expect(routineChecklist).toContain("Run LLM Wiki lint");
+ expect(routineChecklist).toContain("Refresh LLM Wiki index");
+ expect(routineChecklist).not.toContain("Wiki Maintainer");
+ expect(routineChecklist).not.toContain("LLM Wiki project");
+ const skillChecklistStart = markup.indexOf('aria-label="Wiki skills health checklist"');
+ const skillChecklist = markup.slice(skillChecklistStart, markup.indexOf('aria-label="Wiki projects health checklist"'));
+ expect(skillChecklist).toContain("left:8px");
+ expect(skillChecklist).toContain("background:oklch(0.38 0.09 145)");
+ for (const headline of ["Path configured", "Readable", "Writable", "Baseline files", "Wiki folders"]) {
+ expect(markup).toContain(headline);
+ }
+ expect(markup).toContain("Local wiki folder");
+ expect(markup).toContain("Choose");
+ expect(markup).toContain("Apply path");
+ expect(markup).not.toContain("AGENTS.md, IDEA.md");
+ expect(markup).not.toContain("Ready</span>");
+ expect(markup).not.toContain("Needs attention</span>");
+ expect(markup).not.toContain("wiki/sources/");
+ expect(markup).not.toContain("wiki/entities/");
+ expect(markup).not.toContain("Wiki root folder");
+ expect(markup).not.toContain("Provided maintainer");
+ expect(markup).not.toContain(">Project</span>");
+ expect(markup).toContain("Ingestion Settings");
+ });
+
+ it("shows a top-level fix-all banner when settings configuration has errors", () => {
+ mockPathname = "/PAP/wiki/settings";
+ mockSettingsFolder = {
+ configured: true,
+ path: "/tmp/company-wiki",
+ realPath: "/tmp/company-wiki",
+ access: "readWrite",
+ readable: true,
+ writable: true,
+ requiredDirectories: ["raw", "wiki"],
+ requiredFiles: ["AGENTS.md"],
+ missingDirectories: ["raw"],
+ missingFiles: ["AGENTS.md"],
+ healthy: false,
+ problems: [
+ { code: "missing_directory", message: "Required directory is missing.", path: "raw" },
+ { code: "missing_file", message: "Required file is missing.", path: "AGENTS.md" },
+ ],
+ checkedAt: new Date().toISOString(),
+ };
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("configuration errors detected, fix them all?");
+ expect(markup).toContain("Wiki root folder");
+ expect(markup).toContain("Managed routines");
+ expect(markup).toContain("need attention.");
+ expect(markup).toContain("Fix them all");
+ expect(markup.indexOf("configuration errors detected")).toBeLessThan(markup.indexOf(">Base Folder</"));
+ });
+
+ it("shows missing managed skills in setup health with a re-sync action", () => {
+ mockPathname = "/PAP/wiki/settings";
+ mockSettingsManagedSkills = [{
+ status: "missing",
+ skillId: null,
+ resourceKey: WIKI_MAINTAINER_SKILL_KEY,
+ details: {
+ name: "LLM Wiki Maintainer",
+ key: WIKI_MAINTAINER_SKILL_CANONICAL_KEY,
+ description: null,
+ },
+ }];
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Managed Skills");
+ expect(markup).toContain("skill issue(s) need attention");
+ expect(markup).toContain("LLM Wiki Maintainer is not installed in the company skill library.");
+ expect(markup).toContain("Re-sync skills");
+ });
+
+ it("shows managed skill default drift in setup health", () => {
+ mockPathname = "/PAP/wiki/settings";
+ mockSettingsManagedSkills = [{
+ status: "resolved",
+ skillId: "skill-1",
+ resourceKey: WIKI_MAINTAINER_SKILL_KEY,
+ defaultDrift: { changedFiles: ["SKILL.md"] },
+ details: {
+ name: "LLM Wiki Maintainer",
+ key: WIKI_MAINTAINER_SKILL_CANONICAL_KEY,
+ description: null,
+ },
+ }];
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("skill issue(s) need attention");
+ expect(markup).toContain("LLM Wiki Maintainer differs from the plugin default: SKILL.md.");
+ expect(markup).toContain("Re-sync skills");
+ });
+
+ it("renders host settings directly as the Setup page without an extra plugin heading", () => {
+ const markup = renderToStaticMarkup(createElement(SettingsPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain(">Setup</h1>");
+ expect(markup).toContain("Base Folder");
+ expect(markup).not.toContain("LLM Wiki Settings");
+ expect(markup).not.toContain("These settings live inside the plugin");
+ });
+
+ it("renders project settings as a project picker without managed-resource metadata", () => {
+ mockPathname = "/PAP/wiki/settings/project";
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Use existing project");
+ expect(markup).toContain("LLM Wiki");
+ expect(markup).toContain("Save project");
+ expect(markup).toContain("Open project");
+ expect(markup).toContain("Repair / reconcile");
+ expect(markup).toContain("Reset to plugin defaults");
+ expect(markup).not.toContain("Managed by LLM Wiki");
+ expect(markup).not.toContain("Operations project binding");
+ expect(markup).not.toContain("Stable key");
+ expect(markup).not.toContain("Resolved project");
+ expect(markup).toContain("Status: in progress");
+ expect(markup).not.toContain("Plugin managed default");
+ });
+
+ it("renders space settings with health line styling and disabled access controls", () => {
+ mockPathname = "/PAP/wiki/settings/spaces/default";
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Space folder health checklist");
+ expect(markup).toContain("left:8px");
+ expect(markup).toContain("background:oklch(0.38 0.09 145)");
+ expect(markup).toContain("Folder readable");
+ expect(markup).toContain("raw/ present");
+ expect(markup).toContain("Access");
+ expect(markup).toContain("Coming soon");
+ expect(markup).not.toContain("Future enforcement");
+ expect(markup).not.toContain("stored only");
+ expect(markup).not.toContain("Permissions are stored but not enforced");
+ });
+
+ it("renders distillation settings with assigned-agent model selection and cheap path without budget controls", () => {
+ mockPathname = "/PAP/wiki/settings/distillation";
+ mockDistillationOverviewData = {
+ counts: { cursors: 1, runningRuns: 0, failedRuns24h: 0, reviewRequired: 0 },
+ cursors: [{
+ id: "cursor-1",
+ projectId: "project-1",
+ rootIssueId: null,
+ projectName: "Existing Wiki Project",
+ rootIssueIdentifier: null,
+ sourceScope: "project",
+ scopeKey: "project-1",
+ }],
+ runs: [],
+ };
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Agent execution");
+ expect(markup).toContain("Assigned maintainer");
+ expect(markup).toContain("Wiki Maintainer · claude local");
+ expect(markup).toContain("Cheap path");
+ expect(markup).toContain("assigneeAdapterOverrides.modelProfile = cheap");
+ expect(markup).toContain("All sections — apply when source hash matches and confidence");
+ expect(markup).not.toContain("Per-task budget");
+ expect(markup).not.toContain("Project total budget");
+ expect(markup).not.toContain("/task");
+ expect(markup).not.toContain("Model lanes");
+ expect(markup).not.toContain("Claude Haiku");
+ expect(markup).not.toContain("Daily plugin cap");
+ expect(markup).not.toContain("Monthly plugin cap");
+ });
+
+ it("renders managed routines as normal routine rows with run, toggle, and configure controls", () => {
+ mockPathname = "/PAP/wiki/settings/routines";
+ mockSettingsManagedRoutines = [{
+ status: "resolved",
+ routineId: "routine-1",
+ resourceKey: "nightly-wiki-lint",
+ routine: {
+ id: "routine-1",
+ title: "Run LLM Wiki lint",
+ status: "active",
+ assigneeAgentId: "agent-1",
+ projectId: "project-1",
+ lastTriggeredAt: "2026-05-03T12:00:00Z",
+ managedByPlugin: { pluginDisplayName: "LLM Wiki", resourceKey: "nightly-wiki-lint" },
+ },
+ details: { cronExpression: "0 3 * * *" },
+ }];
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Run LLM Wiki lint");
+ expect(markup).toContain("Run now");
+ expect(markup).toContain("Configure");
+ expect(markup).toContain("role=\"switch\"");
+ expect(markup).toContain("LLM Wiki · Wiki Maintainer");
+ expect(markup).toContain("href=\"/PAP/routines/routine-1\"");
+ });
+
+ it("alerts when managed routine defaults changed and offers a reset path", () => {
+ mockPathname = "/PAP/wiki/settings/routines";
+ mockSettingsManagedRoutines = [{
+ status: "resolved",
+ routineId: "routine-1",
+ resourceKey: "nightly-wiki-lint",
+ defaultDrift: {
+ changedFields: ["description"],
+ defaultTitle: "Run LLM Wiki lint",
+ defaultDescription: "Updated instructions",
+ },
+ routine: {
+ id: "routine-1",
+ title: "Run LLM Wiki lint",
+ status: "active",
+ assigneeAgentId: "agent-1",
+ projectId: "project-1",
+ managedByPlugin: { pluginDisplayName: "LLM Wiki", resourceKey: "nightly-wiki-lint" },
+ },
+ details: { cronExpression: "0 3 * * *" },
+ }];
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Routine defaults changed");
+ expect(markup).toContain("Plugin defaults changed: description");
+ expect(markup).toContain(">Reset</button>");
+ });
+
+ it("shows managed agent instruction drift in the setup health check", () => {
+ mockPathname = "/PAP/wiki/settings";
+ mockSettingsManagedAgent = {
+ status: "resolved",
+ source: "managed",
+ agentId: "agent-1",
+ resourceKey: "wiki-maintainer",
+ defaultDrift: { entryFile: "AGENTS.md", changedFiles: ["AGENTS.md"] },
+ details: { name: "Wiki Maintainer", status: "idle", adapterType: "claude_local", icon: "book-open", urlKey: "wiki-maintainer" },
+ };
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Wiki Maintainer instructions differ from the plugin default: AGENTS.md.");
+ expect(markup).toContain("Wiki Maintainer instruction defaults changed: AGENTS.md");
+ });
+
+ it("shows one routine repair warning instead of per-routine reconcile controls", () => {
+ mockPathname = "/PAP/wiki/settings/routines";
+ mockSettingsManagedRoutines = [{
+ status: "resolved",
+ routineId: "routine-1",
+ resourceKey: "nightly-wiki-lint",
+ routine: {
+ id: "routine-1",
+ title: "Run LLM Wiki lint",
+ status: "active",
+ assigneeAgentId: "other-agent",
+ projectId: "project-1",
+ managedByPlugin: { pluginDisplayName: "LLM Wiki", resourceKey: "nightly-wiki-lint" },
+ },
+ details: { cronExpression: "0 3 * * *" },
+ }];
+
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Routine setup needs repair");
+ expect(markup).toContain("Fix routines");
+ expect(markup).toContain("not assigned to the Wiki Maintainer");
+ expect(markup).not.toContain("Plugin-managed routine defaults can be reconciled from here");
+ expect(markup).not.toContain(">Reconcile</button>");
+ expect(markup).not.toContain(">Reset</button>");
+ });
+
+ it("renders legacy lint routes inside the Wiki settings section", () => {
+ mockPathname = "/PAP/wiki/lint";
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("Run lint now");
+ expect(markup).toContain("Recent lint runs");
+ expect(markup).toContain("LLM Wiki settings sections");
+ });
+
+ it("does not expose IDEA.md pattern editing as a settings section", () => {
+ mockPathname = "/PAP/wiki/settings";
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("LLM Wiki settings sections");
+ expect(markup).not.toContain(">Pattern</span>");
+ expect(markup).not.toContain("Pattern · IDEA.md");
+ expect(markup).not.toContain("IDEA.md skeleton reference");
+ });
+
+ it("does not expose plugin capabilities as a settings section", () => {
+ mockPathname = "/PAP/wiki/settings";
+ const markup = renderToStaticMarkup(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+
+ expect(markup).toContain("LLM Wiki settings sections");
+ expect(markup).not.toContain("Plugin capabilities");
+ expect(markup).not.toContain("api.routes.register");
+ });
+
+ it("reconciles managed maintenance routines through stable agent and project refs", async () => {
+ const harness = createTestHarness({ manifest });
+ const writes: Array<{ path: string; contents: string }> = [];
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push({ path: relativePath, contents });
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+
+ const missing = await harness.performAction<PluginManagedRoutineResolution>("reconcile-managed-routine", {
+ companyId: COMPANY_ID,
+ routineKey: NIGHTLY_LINT_ROUTINE_KEY,
+ });
+ expect(missing.status).toBe("missing_refs");
+ expect(missing.missingRefs).toEqual([
+ expect.objectContaining({ resourceKind: "agent", resourceKey: WIKI_MAINTAINER_AGENT_KEY }),
+ expect.objectContaining({ resourceKind: "project", resourceKey: WIKI_PROJECT_KEY }),
+ ]);
+
+ await harness.performAction("bootstrap-root", { companyId: COMPANY_ID, path: "/tmp/company-wiki" });
+ const reconciled = await Promise.all(
+ WIKI_MAINTENANCE_ROUTINE_KEYS.map((routineKey) =>
+ harness.performAction<PluginManagedRoutineResolution>("reconcile-managed-routine", {
+ companyId: COMPANY_ID,
+ routineKey,
+ })),
+ );
+
+ expect(reconciled.map((routine) => routine.resourceKey)).toEqual([...WIKI_MAINTENANCE_ROUTINE_KEYS]);
+ expect(reconciled).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ resourceKey: NIGHTLY_LINT_ROUTINE_KEY,
+ routine: expect.objectContaining({
+ projectId: expect.any(String),
+ assigneeAgentId: expect.any(String),
+ managedByPlugin: expect.objectContaining({
+ defaultsJson: expect.objectContaining({
+ issueTemplate: expect.objectContaining({ surfaceVisibility: "plugin_operation" }),
+ }),
+ }),
+ }),
+ }),
+ expect.objectContaining({ resourceKey: INDEX_REFRESH_ROUTINE_KEY, routineId: expect.any(String) }),
+ ]),
+ );
+ });
+
+ it("requires an explicit managed routine key for single-routine actions", async () => {
+ const harness = createTestHarness({ manifest });
+ await plugin.definition.setup(harness.ctx);
+
+ await expect(harness.performAction("reconcile-managed-routine", {
+ companyId: COMPANY_ID,
+ })).rejects.toThrow("routineKey is required");
+ });
+
+ it("repairs all managed maintenance routines through one action", async () => {
+ const harness = createTestHarness({ manifest });
+ await plugin.definition.setup(harness.ctx);
+ await harness.performAction("bootstrap-root", { companyId: COMPANY_ID, path: "/tmp/company-wiki" });
+
+ const repaired = await harness.performAction<{
+ managedRoutines: PluginManagedRoutineResolution[];
+ }>("reconcile-managed-routines", { companyId: COMPANY_ID });
+
+ expect(repaired.managedRoutines).toHaveLength(WIKI_MAINTENANCE_ROUTINE_KEYS.length);
+ expect(repaired.managedRoutines.map((routine) => routine.resourceKey)).toEqual([...WIKI_MAINTENANCE_ROUTINE_KEYS]);
+ for (const routine of repaired.managedRoutines) {
+ expect(routine.routine).toEqual(expect.objectContaining({
+ assigneeAgentId: expect.any(String),
+ projectId: expect.any(String),
+ }));
+ expect(routine.missingRefs).toEqual([]);
+ }
+ });
+
+ it("installs and resets managed company skills through setup actions", async () => {
+ const harness = createTestHarness({ manifest });
+ await plugin.definition.setup(harness.ctx);
+
+ const before = await harness.getData<{ managedSkills: WikiSkillResource[] }>("settings", {
+ companyId: COMPANY_ID,
+ });
+ expect(before.managedSkills.map((skill) => skill.resourceKey)).toEqual([...WIKI_MANAGED_SKILL_KEYS]);
+ expect(before.managedSkills[0]).toMatchObject({
+ status: "missing",
+ skillId: null,
+ });
+
+ const repaired = await harness.performAction<{
+ managedSkills: WikiSkillResource[];
+ }>("reconcile-managed-skills", { companyId: COMPANY_ID });
+ expect(repaired.managedSkills).toHaveLength(WIKI_MANAGED_SKILL_KEYS.length);
+ expect(repaired.managedSkills[0]).toMatchObject({
+ status: "created",
+ skillId: expect.any(String),
+ resourceKey: WIKI_MAINTAINER_SKILL_KEY,
+ details: {
+ name: "LLM Wiki Maintainer",
+ key: WIKI_MAINTAINER_SKILL_CANONICAL_KEY,
+ },
+ });
+
+ const resolved = await harness.getData<{ managedSkills: WikiSkillResource[] }>("settings", {
+ companyId: COMPANY_ID,
+ });
+ expect(resolved.managedSkills[0]).toMatchObject({
+ status: "resolved",
+ resourceKey: WIKI_MAINTAINER_SKILL_KEY,
+ details: { key: WIKI_MAINTAINER_SKILL_CANONICAL_KEY },
+ });
+
+ const reset = await harness.performAction<{
+ managedSkills: WikiSkillResource[];
+ }>("reset-managed-skills", { companyId: COMPANY_ID });
+ expect(reset.managedSkills[0]).toMatchObject({
+ status: "reset",
+ skillId: expect.any(String),
+ resourceKey: WIKI_MAINTAINER_SKILL_KEY,
+ });
+ });
+
+ it("registers worker data, actions, and tools", async () => {
+ const harness = createTestHarness({ manifest });
+ await plugin.definition.setup(harness.ctx);
+
+ const overview = await harness.getData<{ status: string; operationCount: number; eventIngestion: { enabled: boolean } }>("overview", {
+ companyId: COMPANY_ID,
+ });
+ expect(overview.status).toBe("ok");
+ expect(overview.operationCount).toBe(0);
+ expect(overview.eventIngestion.enabled).toBe(false);
+
+ const pages = await harness.executeTool<{ content?: string }>("wiki_list_pages", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ });
+ expect(pages.content).toBe("No pages indexed yet.");
+ });
+
+ it("filters stale page and raw source rows out of browse data", async () => {
+ const harness = createTestHarness({ manifest });
+ const files = new Map<string, string>([
+ ["wiki/concepts/live.md", "# Live Page\n"],
+ ["raw/live-source.md", "# Live Source\n"],
+ ]);
+ const now = new Date().toISOString();
+ harness.ctx.localFolders.readText = async (_companyId, _folderKey, relativePath) => {
+ const contents = files.get(relativePath);
+ if (contents == null) throw new Error(`missing ${relativePath}`);
+ return contents;
+ };
+ harness.ctx.db.query = async <T = Record<string, unknown>>(sql: string, params?: unknown[]) => {
+ harness.dbQueries.push({ sql, params });
+ if (sql.includes("wiki_pages")) {
+ return [
+ {
+ path: "wiki/concepts/live.md",
+ title: "Live Page",
+ page_type: "concepts",
+ backlinks: [],
+ source_refs: [],
+ content_hash: "live",
+ updated_at: now,
+ },
+ {
+ path: "wiki/concepts/stale.md",
+ title: "Stale Page",
+ page_type: "concepts",
+ backlinks: [],
+ source_refs: [],
+ content_hash: "stale",
+ updated_at: now,
+ },
+ ] as T[];
+ }
+ if (sql.includes("wiki_sources")) {
+ return [
+ {
+ raw_path: "raw/missing-source.md",
+ title: "Missing Source",
+ source_type: "text",
+ url: null,
+ status: "captured",
+ created_at: now,
+ },
+ {
+ raw_path: "raw/live-source.md",
+ title: "Live Source",
+ source_type: "text",
+ url: null,
+ status: "captured",
+ created_at: now,
+ },
+ ] as T[];
+ }
+ return [];
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.getData<{
+ pages: Array<{ path: string }>;
+ sources: Array<{ rawPath: string }>;
+ }>("pages", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ includeRaw: true,
+ });
+
+ expect(result.pages.map((page) => page.path)).toEqual(["wiki/concepts/live.md"]);
+ expect(result.sources.map((source) => source.rawPath)).toEqual(["raw/live-source.md"]);
+ });
+
+ it("includes local wiki files in browse data before metadata is indexed", async () => {
+ const harness = createTestHarness({ manifest });
+ const modifiedAt = new Date().toISOString();
+ harness.ctx.localFolders.list = async (_companyId, folderKey, options) => ({
+ folderKey,
+ relativePath: options?.relativePath ?? null,
+ truncated: false,
+ entries: options?.relativePath === "wiki"
+ ? [
+ { path: "wiki/concepts/agent-memory-layer.md", name: "agent-memory-layer.md", kind: "file", size: 12, modifiedAt },
+ { path: "wiki/entities/paperclip.md", name: "paperclip.md", kind: "file", size: 10, modifiedAt },
+ { path: "wiki/projects/llm-wiki/standup.md", name: "standup.md", kind: "file", size: 16, modifiedAt },
+ ]
+ : [
+ { path: "raw/2026-04-09-thomas-gieselmann-fundraising-call.md", name: "2026-04-09-thomas-gieselmann-fundraising-call.md", kind: "file", size: 14, modifiedAt },
+ ],
+ });
+ harness.ctx.db.query = async <T = Record<string, unknown>>(sql: string, params?: unknown[]) => {
+ harness.dbQueries.push({ sql, params });
+ return [] as T[];
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.getData<{
+ pages: Array<{ path: string; title: string | null }>;
+ sources: Array<{ rawPath: string; title: string | null }>;
+ }>("pages", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ includeRaw: true,
+ });
+
+ expect(result.pages).toEqual([
+ expect.objectContaining({ path: "wiki/concepts/agent-memory-layer.md", title: null }),
+ expect.objectContaining({ path: "wiki/entities/paperclip.md", title: null }),
+ expect.objectContaining({ path: "wiki/projects/llm-wiki/standup.md", title: null }),
+ ]);
+ expect(result.sources).toEqual([
+ expect.objectContaining({ rawPath: "raw/2026-04-09-thomas-gieselmann-fundraising-call.md", title: null }),
+ ]);
+ });
+
+ it("does not ingest Paperclip events until operator controls enable them", async () => {
+ const harness = createTestHarness({ manifest });
+ const issue = paperclipIssue();
+ harness.seed({ issues: [issue] });
+ const writes: Array<{ path: string; contents: string }> = [];
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push({ path: relativePath, contents });
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ await harness.emit("issue.created", { identifier: issue.identifier }, {
+ companyId: COMPANY_ID,
+ entityId: issue.id,
+ entityType: "issue",
+ eventId: "event-disabled-issue-created",
+ });
+
+ expect(writes).toHaveLength(0);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_sources"))).toBe(false);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_operations"))).toBe(false);
+ });
+
+ it("records enabled Paperclip issue events as cursor observations without creating ingest operations", async () => {
+ const harness = createTestHarness({ manifest });
+ const issue = paperclipIssue();
+ harness.seed({ issues: [issue] });
+ const writes: Array<{ path: string; contents: string }> = [];
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push({ path: relativePath, contents });
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const policy = await harness.performAction<{ enabled: boolean; sources: { issues: boolean; comments: boolean; documents: boolean } }>(
+ "update-event-ingestion-settings",
+ {
+ companyId: COMPANY_ID,
+ enabled: true,
+ sources: { issues: true, comments: false, documents: false },
+ },
+ );
+ expect(policy).toMatchObject({ enabled: true, sources: { issues: true, comments: false, documents: false } });
+
+ await harness.emit("issue.created", { identifier: issue.identifier }, {
+ companyId: COMPANY_ID,
+ entityId: issue.id,
+ entityType: "issue",
+ eventId: "event-enabled-issue-created",
+ });
+
+ expect(writes).toHaveLength(0);
+ const operations = await harness.ctx.issues.list({
+ companyId: COMPANY_ID,
+ originKindPrefix: String(OPERATION_ORIGIN_KIND),
+ });
+ expect(operations).toHaveLength(0);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_sources"))).toBe(false);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_operations"))).toBe(false);
+ const cursorUpsert = harness.dbExecutes.find((execute) => execute.sql.includes("paperclip_distillation_cursors"));
+ expect(cursorUpsert?.params).toEqual(expect.arrayContaining([
+ COMPANY_ID,
+ "default",
+ "company",
+ null,
+ null,
+ ]));
+ });
+
+ it("preserves Paperclip event ingestion sources when only enabled changes", async () => {
+ const harness = createTestHarness({ manifest });
+
+ await plugin.definition.setup(harness.ctx);
+ await harness.performAction("update-event-ingestion-settings", {
+ companyId: COMPANY_ID,
+ enabled: true,
+ sources: { issues: true, comments: true, documents: true },
+ });
+
+ const disabled = await harness.performAction<{
+ enabled: boolean;
+ sources: { issues: boolean; comments: boolean; documents: boolean };
+ }>("update-event-ingestion-settings", {
+ companyId: COMPANY_ID,
+ enabled: false,
+ });
+ expect(disabled).toMatchObject({
+ enabled: false,
+ sources: { issues: true, comments: true, documents: true },
+ });
+
+ const reenabled = await harness.performAction<{
+ enabled: boolean;
+ sources: { issues: boolean; comments: boolean; documents: boolean };
+ }>("update-event-ingestion-settings", {
+ companyId: COMPANY_ID,
+ enabled: true,
+ });
+ expect(reenabled).toMatchObject({
+ enabled: true,
+ sources: { issues: true, comments: true, documents: true },
+ });
+ });
+
+ it("keeps Paperclip event cursor observations company scoped and ignores plugin-operation issues", async () => {
+ const harness = createTestHarness({ manifest });
+ const visibleIssue = paperclipIssue({ projectId: "77777777-7777-4777-8777-777777777777" });
+ const otherCompanyIssue = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777778",
+ companyId: OTHER_COMPANY_ID,
+ projectId: "77777777-7777-4777-8777-777777777779",
+ identifier: "PAP-9999",
+ });
+ const operationIssue = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777780",
+ originKind: `${OPERATION_ORIGIN_KIND}:ingest`,
+ });
+ harness.seed({ issues: [visibleIssue, otherCompanyIssue, operationIssue] });
+
+ await plugin.definition.setup(harness.ctx);
+ await harness.performAction("update-event-ingestion-settings", {
+ companyId: COMPANY_ID,
+ enabled: true,
+ sources: { issues: true, comments: true, documents: true },
+ });
+
+ await harness.emit("issue.updated", {}, {
+ companyId: COMPANY_ID,
+ entityId: visibleIssue.id,
+ entityType: "issue",
+ eventId: "event-visible",
+ });
+ await harness.emit("issue.updated", {}, {
+ companyId: OTHER_COMPANY_ID,
+ entityId: otherCompanyIssue.id,
+ entityType: "issue",
+ eventId: "event-other-company",
+ });
+ await harness.emit("issue.updated", {}, {
+ companyId: COMPANY_ID,
+ entityId: operationIssue.id,
+ entityType: "issue",
+ eventId: "event-plugin-operation",
+ });
+
+ const cursorWrites = harness.dbExecutes.filter((execute) => execute.sql.includes("paperclip_distillation_cursors"));
+ expect(cursorWrites).toHaveLength(1);
+ expect(cursorWrites[0].params).toEqual(expect.arrayContaining([
+ COMPANY_ID,
+ "default",
+ "project",
+ visibleIssue.projectId,
+ ]));
+ });
+
+ it("routes Paperclip issue, comment, and document event cursors only to the default space", async () => {
+ const harness = createTestHarness({ manifest });
+ const issue = paperclipIssue({ projectId: "77777777-7777-4777-8777-777777777777" });
+ harness.seed({ issues: [issue] });
+
+ await plugin.definition.setup(harness.ctx);
+ const created = await harness.performAction<{
+ space: { id: string; slug: string };
+ }>("create-space", {
+ companyId: COMPANY_ID,
+ displayName: "Team Research",
+ });
+ await harness.performAction("update-event-ingestion-settings", {
+ companyId: COMPANY_ID,
+ enabled: true,
+ sources: { issues: true, comments: true, documents: true },
+ });
+
+ await harness.emit("issue.created", {}, {
+ companyId: COMPANY_ID,
+ entityId: issue.id,
+ entityType: "issue",
+ eventId: "event-default-issue-created",
+ });
+ await harness.emit("issue.comment.created", { commentId: "comment-1" }, {
+ companyId: COMPANY_ID,
+ entityId: issue.id,
+ entityType: "issue",
+ eventId: "event-default-comment-created",
+ });
+ await harness.emit("issue.document.updated", { key: "plan", revisionId: "revision-1" }, {
+ companyId: COMPANY_ID,
+ entityId: issue.id,
+ entityType: "issue",
+ eventId: "event-default-document-updated",
+ });
+
+ const cursorWrites = harness.dbExecutes.filter((execute) => execute.sql.includes("paperclip_distillation_cursors"));
+ expect(cursorWrites).toHaveLength(3);
+ expect(cursorWrites.every((execute) => execute.params?.[10] !== created.space.id)).toBe(true);
+ expect(cursorWrites.map((execute) => execute.params?.[2])).toEqual(["default", "default", "default"]);
+ expect(String(cursorWrites[0].params?.[9])).toContain('"lastSourceKind":"issues"');
+ expect(String(cursorWrites[1].params?.[9])).toContain('"lastSourceKind":"comments"');
+ expect(String(cursorWrites[2].params?.[9])).toContain('"lastSourceKind":"documents"');
+ });
+
+ it("routes Paperclip events into an explicitly enabled shared non-default space", async () => {
+ const harness = createTestHarness({ manifest });
+ const project = existingProject();
+ const issue = paperclipIssue({ projectId: project.id });
+ harness.seed({ projects: [project], issues: [issue] });
+
+ await plugin.definition.setup(harness.ctx);
+ const created = await harness.performAction<{
+ space: { id: string; slug: string };
+ }>("create-space", {
+ companyId: COMPANY_ID,
+ displayName: "Engineering Wiki",
+ accessScope: "shared",
+ });
+ mockPersistedWikiSpace(harness, created.space as unknown as Record<string, unknown>);
+ const enabledProfile = {
+ version: 1,
+ enabled: true,
+ sourceScopes: [{ kind: "selected_projects", projectIds: [project.id] }],
+ sourceKinds: { issues: true, comments: true, documents: true, attachments: "off", workProducts: "off" },
+ cursor: { maxWindowCharacters: 60000, maxCharactersPerSource: 12000, minSourceAgeMinutes: 15, maxWindowsPerRun: 6, staleAfterHours: 72 },
+ backfill: { requireManualQueue: true },
+ };
+ await harness.performAction("update-paperclip-ingestion-profile", {
+ companyId: COMPANY_ID,
+ spaceSlug: created.space.slug,
+ profile: enabledProfile,
+ });
+ mockPersistedWikiSpace(harness, { ...(created.space as unknown as Record<string, unknown>), settings: { paperclipIngestion: enabledProfile } });
+
+ await harness.emit("issue.created", {}, {
+ companyId: COMPANY_ID,
+ entityId: issue.id,
+ entityType: "issue",
+ eventId: "event-non-default-enabled",
+ });
+
+ const cursorWrites = harness.dbExecutes.filter((execute) => execute.sql.includes("paperclip_distillation_cursors"));
+ expect(cursorWrites.some((execute) => execute.params?.[10] === created.space.id)).toBe(true);
+ });
+
+ it("stops new non-default observations after the per-space profile is disabled", async () => {
+ const harness = createTestHarness({ manifest });
+ const project = existingProject();
+ const issue = paperclipIssue({ projectId: project.id });
+ harness.seed({ projects: [project], issues: [issue] });
+
+ await plugin.definition.setup(harness.ctx);
+ const created = await harness.performAction<{
+ space: { id: string; slug: string };
+ }>("create-space", {
+ companyId: COMPANY_ID,
+ displayName: "Support Wiki",
+ accessScope: "shared",
+ });
+ mockPersistedWikiSpace(harness, created.space as unknown as Record<string, unknown>);
+ const enabledProfile = {
+ version: 1,
+ enabled: true,
+ sourceScopes: [{ kind: "selected_projects", projectIds: [project.id] }],
+ sourceKinds: { issues: true, comments: false, documents: false, attachments: "off", workProducts: "off" },
+ cursor: { maxWindowCharacters: 60000, maxCharactersPerSource: 12000, minSourceAgeMinutes: 15, maxWindowsPerRun: 6, staleAfterHours: 72 },
+ backfill: { requireManualQueue: true },
+ };
+ await harness.performAction("update-paperclip-ingestion-profile", {
+ companyId: COMPANY_ID,
+ spaceSlug: created.space.slug,
+ profile: enabledProfile,
+ });
+ mockPersistedWikiSpace(harness, { ...(created.space as unknown as Record<string, unknown>), settings: { paperclipIngestion: enabledProfile } });
+ await harness.emit("issue.created", {}, {
+ companyId: COMPANY_ID,
+ entityId: issue.id,
+ entityType: "issue",
+ eventId: "event-before-disable",
+ });
+ await harness.performAction("update-paperclip-ingestion-profile", {
+ companyId: COMPANY_ID,
+ spaceSlug: created.space.slug,
+ profile: { ...enabledProfile, enabled: false },
+ });
+ mockPersistedWikiSpace(harness, { ...(created.space as unknown as Record<string, unknown>), settings: { paperclipIngestion: { ...enabledProfile, enabled: false } } });
+ await harness.emit("issue.updated", {}, {
+ companyId: COMPANY_ID,
+ entityId: issue.id,
+ entityType: "issue",
+ eventId: "event-after-disable",
+ });
+
+ const nonDefaultCursorWrites = harness.dbExecutes.filter((execute) =>
+ execute.sql.includes("paperclip_distillation_cursors") && execute.params?.[10] === created.space.id);
+ expect(nonDefaultCursorWrites).toHaveLength(1);
+ });
+
+ it("assembles deterministic Paperclip source bundles with issue, document, and comment provenance", async () => {
+ const harness = createTestHarness({ manifest });
+ const root = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777781",
+ identifier: "PAP-4000",
+ title: "Root distillation issue",
+ projectId: "77777777-7777-4777-8777-777777777777",
+ updatedAt: new Date("2026-05-01T10:00:00Z"),
+ });
+ const child = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777782",
+ identifier: "PAP-4001",
+ title: "Child source issue",
+ parentId: root.id,
+ projectId: root.projectId,
+ description: "Child issue has a decision and implementation notes.",
+ updatedAt: new Date("2026-05-02T10:00:00Z"),
+ });
+ harness.seed({
+ issues: [root, child],
+ issueComments: [{
+ id: "77777777-7777-4777-8777-777777777783",
+ companyId: COMPANY_ID,
+ issueId: child.id,
+ authorType: "user",
+ authorAgentId: null,
+ authorUserId: null,
+ body: "Comment evidence for the source bundle.",
+ presentation: null,
+ metadata: null,
+ createdAt: new Date("2026-05-03T10:00:00Z"),
+ updatedAt: new Date("2026-05-03T10:00:00Z"),
+ }],
+ });
+
+ await plugin.definition.setup(harness.ctx);
+ await harness.ctx.issues.documents.upsert({
+ companyId: COMPANY_ID,
+ issueId: child.id,
+ key: "plan",
+ title: "Plan",
+ body: "Document evidence for the source bundle.",
+ });
+
+ const first = await harness.performAction<{
+ markdown: string;
+ sourceRefs: Array<{ kind: string; issueIdentifier: string | null; documentKey?: string; commentId?: string }>;
+ sourceHash: string;
+ sourceWindowEnd: string | null;
+ }>("assemble-paperclip-source-bundle", {
+ companyId: COMPANY_ID,
+ rootIssueId: root.id,
+ maxCharacters: 20000,
+ });
+ const second = await harness.performAction<typeof first>("assemble-paperclip-source-bundle", {
+ companyId: COMPANY_ID,
+ rootIssueId: root.id,
+ maxCharacters: 20000,
+ });
+
+ expect(second.sourceHash).toBe(first.sourceHash);
+ expect(first.markdown).toContain("Root distillation issue");
+ expect(first.markdown).toContain("Child issue has a decision");
+ expect(first.markdown).toContain("Document evidence for the source bundle.");
+ expect(first.markdown).toContain("Comment evidence for the source bundle.");
+ expect(first.sourceRefs).toEqual(expect.arrayContaining([
+ expect.objectContaining({ kind: "issue", issueIdentifier: "PAP-4001" }),
+ expect.objectContaining({ kind: "document", documentKey: "plan" }),
+ expect.objectContaining({ kind: "comment", commentId: "77777777-7777-4777-8777-777777777783" }),
+ ]));
+ expect(first.sourceWindowEnd).toEqual(expect.any(String));
+ });
+
+ it("suppresses secret-like comment and document bodies before storing distillation snapshots", async () => {
+ const harness = createTestHarness({ manifest });
+ const issue = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777784",
+ identifier: "PAP-4002",
+ title: "Sensitive source issue",
+ projectId: "77777777-7777-4777-8777-777777777777",
+ description: "Keep the project page current without copying credential material into the wiki.",
+ updatedAt: new Date("2026-05-04T10:00:00Z"),
+ });
+ harness.seed({
+ issues: [issue],
+ issueComments: [{
+ id: "77777777-7777-4777-8777-777777777785",
+ companyId: COMPANY_ID,
+ issueId: issue.id,
+ authorType: "user",
+ authorAgentId: null,
+ authorUserId: null,
+ body: "Authorization: Bearer ghp_supersecretcommenttoken1234567890",
+ presentation: null,
+ metadata: null,
+ createdAt: new Date("2026-05-04T11:00:00Z"),
+ updatedAt: new Date("2026-05-04T11:00:00Z"),
+ }],
+ });
+
+ await plugin.definition.setup(harness.ctx);
+ await harness.ctx.issues.documents.upsert({
+ companyId: COMPANY_ID,
+ issueId: issue.id,
+ key: "plan",
+ title: "Plan",
+ body: "OPENAI_API_KEY=sk-supersecretdocumentvalue1234567890",
+ });
+
+ const run = await harness.performAction<{
+ bundle: {
+ markdown: string;
+ warnings: string[];
+ sourceRefs: Array<Record<string, unknown>>;
+ };
+ }>("create-paperclip-distillation-run", {
+ companyId: COMPANY_ID,
+ projectId: issue.projectId,
+ maxCharacters: 20000,
+ });
+
+ expect(run.bundle.markdown).toContain("Suppressed by LLM Wiki distillation security policy");
+ expect(run.bundle.markdown).not.toContain("ghp_supersecretcommenttoken1234567890");
+ expect(run.bundle.markdown).not.toContain("sk-supersecretdocumentvalue1234567890");
+ expect(run.bundle.warnings).toEqual(expect.arrayContaining([
+ expect.stringContaining("Suppressed comment content"),
+ expect.stringContaining("Suppressed document content"),
+ ]));
+ expect(run.bundle.sourceRefs).toEqual(expect.arrayContaining([
+ expect.objectContaining({ kind: "comment", redactionStatus: "suppressed_sensitive_content" }),
+ expect.objectContaining({ kind: "document", redactionStatus: "suppressed_sensitive_content" }),
+ ]));
+
+ const snapshotInsert = harness.dbExecutes.find((execute) => execute.sql.includes("paperclip_source_snapshots"));
+ const storedSourceRefs = String(snapshotInsert?.params?.[9] ?? "");
+ const storedMarkdown = String(snapshotInsert?.params?.[10] ?? "");
+ expect(storedSourceRefs).toContain("suppressed_sensitive_content");
+ expect(storedMarkdown).toContain("Suppressed by LLM Wiki distillation security policy");
+ expect(storedMarkdown).not.toContain("ghp_supersecretcommenttoken1234567890");
+ expect(storedMarkdown).not.toContain("sk-supersecretdocumentvalue1234567890");
+ });
+
+ it("creates source snapshots and only advances cursors after successful distillation outcomes", async () => {
+ const harness = createTestHarness({ manifest });
+ const issue = paperclipIssue({
+ projectId: "77777777-7777-4777-8777-777777777777",
+ updatedAt: new Date("2026-05-02T10:00:00Z"),
+ });
+ harness.seed({ issues: [issue] });
+ await plugin.definition.setup(harness.ctx);
+
+ const run = await harness.performAction<{
+ runId: string;
+ cursorId: string;
+ snapshotId: string;
+ bundle: { sourceHash: string; sourceWindowEnd: string };
+ }>("create-paperclip-distillation-run", {
+ companyId: COMPANY_ID,
+ projectId: issue.projectId,
+ });
+ expect(run.snapshotId).toEqual(expect.any(String));
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("paperclip_source_snapshots"))).toBe(true);
+
+ const failed = await harness.performAction<{ cursorAdvanced: boolean }>("record-paperclip-distillation-outcome", {
+ companyId: COMPANY_ID,
+ runId: run.runId,
+ cursorId: run.cursorId,
+ status: "failed",
+ sourceHash: run.bundle.sourceHash,
+ sourceWindowEnd: run.bundle.sourceWindowEnd,
+ warning: "writer failed",
+ });
+ expect(failed.cursorAdvanced).toBe(false);
+ const cursorUpdatesAfterFailure = harness.dbExecutes.filter((execute) =>
+ execute.sql.trim().startsWith("UPDATE") && execute.sql.includes("paperclip_distillation_cursors"));
+ expect(cursorUpdatesAfterFailure).toHaveLength(0);
+
+ const succeeded = await harness.performAction<{ cursorAdvanced: boolean }>("record-paperclip-distillation-outcome", {
+ companyId: COMPANY_ID,
+ runId: run.runId,
+ cursorId: run.cursorId,
+ status: "succeeded",
+ sourceHash: run.bundle.sourceHash,
+ sourceWindowEnd: run.bundle.sourceWindowEnd,
+ });
+ expect(succeeded.cursorAdvanced).toBe(true);
+ const cursorSuccessUpdate = harness.dbExecutes.find((execute) =>
+ execute.sql.trim().startsWith("UPDATE") && execute.sql.includes("paperclip_distillation_cursors"));
+ expect(cursorSuccessUpdate?.params).toEqual(expect.arrayContaining([
+ COMPANY_ID,
+ "default",
+ run.runId,
+ run.bundle.sourceWindowEnd,
+ run.bundle.sourceHash,
+ run.cursorId,
+ ]));
+ });
+
+ it("uses the existing distillation cursor id after an upsert conflict", async () => {
+ const harness = createTestHarness({ manifest });
+ const project = existingProject();
+ const issue = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777800",
+ identifier: "PAP-4099",
+ title: "Existing cursor target",
+ projectId: project.id,
+ status: "in_progress",
+ });
+ const existingCursorId = "77777777-7777-4777-8777-777777777899";
+ const originalQuery = harness.ctx.db.query.bind(harness.ctx.db);
+ harness.ctx.db.query = async <T,>(sql: string, params?: unknown[]) => {
+ if (sql.includes("SELECT id") && sql.includes("paperclip_distillation_cursors")) {
+ return [{ id: existingCursorId }] as T[];
+ }
+ return originalQuery<T>(sql, params);
+ };
+ harness.seed({ projects: [project], issues: [issue] });
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.performAction<{ cursorId: string }>("create-paperclip-distillation-run", {
+ companyId: COMPANY_ID,
+ projectId: project.id,
+ });
+
+ expect(result.cursorId).toBe(existingCursorId);
+ const runInsert = harness.dbExecutes.find((execute) =>
+ execute.sql.includes("paperclip_distillation_runs") && execute.sql.includes("'source_ready'"));
+ expect(runInsert?.params?.[3]).toBe(existingCursorId);
+ });
+
+ it("creates explicit distillation work items for manual, retry, and backfill lanes", async () => {
+ const harness = createTestHarness({ manifest });
+ await plugin.definition.setup(harness.ctx);
+
+ await harness.performAction("create-paperclip-distillation-work-item", {
+ companyId: COMPANY_ID,
+ kind: "manual",
+ projectId: "77777777-7777-4777-8777-777777777777",
+ idempotencyKey: "manual:project:77777777-7777-4777-8777-777777777777",
+ });
+ await harness.performAction("create-paperclip-distillation-work-item", {
+ companyId: COMPANY_ID,
+ kind: "retry",
+ rootIssueId: "77777777-7777-4777-8777-777777777781",
+ priority: "high",
+ idempotencyKey: "retry:run:1",
+ });
+ await harness.performAction("create-paperclip-distillation-work-item", {
+ companyId: COMPANY_ID,
+ kind: "backfill",
+ projectId: "77777777-7777-4777-8777-777777777777",
+ priority: "low",
+ metadata: { window: "last-30-days" },
+ idempotencyKey: "backfill:last-30-days",
+ });
+
+ const workItemWrites = harness.dbExecutes.filter((execute) => execute.sql.includes("paperclip_distillation_work_items"));
+ expect(workItemWrites).toHaveLength(3);
+ expect(workItemWrites.map((write) => write.params?.[3])).toEqual(["manual", "retry", "backfill"]);
+ expect(String(workItemWrites[0].params?.[9])).toContain('"sourceScope":"project"');
+ expect(String(workItemWrites[1].params?.[9])).toContain('"sourceScope":"root_issue"');
+ expect(String(workItemWrites[2].params?.[9])).toContain('"sourceScope":"project"');
+
+ await expect(harness.performAction("create-paperclip-distillation-work-item", {
+ companyId: COMPANY_ID,
+ kind: "backfill",
+ idempotencyKey: "backfill:company",
+ })).rejects.toThrow("whole-company backfill is not allowed");
+ });
+
+ it("records estimated Paperclip distillation cost without refusing on legacy cost config", async () => {
+ const harness = createTestHarness({
+ manifest,
+ config: {
+ maxPaperclipRoutineRunCostCents: 1,
+ maxPaperclipDistillationTaskCostCents: 1,
+ maxPaperclipDistillationProjectCostCents: 1,
+ paperclipCostCentsPerThousandSourceCharacters: 100,
+ },
+ });
+ const project = existingProject();
+ const issue = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777795",
+ identifier: "PAP-4104",
+ title: "Large source bundle",
+ description: `Accepted plan. ${"Detailed implementation note. ".repeat(160)}`,
+ projectId: project.id,
+ status: "in_progress",
+ });
+ harness.seed({ projects: [project], issues: [issue] });
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.performAction<{
+ status: string;
+ estimatedCostCents: number;
+ snapshotId: string | null;
+ }>("create-paperclip-distillation-run", {
+ companyId: COMPANY_ID,
+ projectId: project.id,
+ routineRun: true,
+ });
+
+ expect(result.status).toBe("source_ready");
+ expect(result.estimatedCostCents).toBeGreaterThan(1);
+ expect(result.snapshotId).toEqual(expect.any(String));
+ const readyRun = harness.dbExecutes.find((execute) =>
+ execute.sql.includes("paperclip_distillation_runs") && execute.sql.includes("'source_ready'"));
+ expect(readyRun?.params).toEqual(expect.arrayContaining([
+ COMPANY_ID,
+ "default",
+ expect.any(String),
+ expect.any(String),
+ null,
+ project.id,
+ ]));
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("paperclip_source_snapshots"))).toBe(true);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("refused_cost_cap"))).toBe(false);
+ });
+
+ it("queues visible manual distill operation issues for a company-wide stale cursor scan", async () => {
+ const harness = createTestHarness({ manifest });
+ const project = existingProject();
+ const issue = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777796",
+ identifier: "PAP-4105",
+ title: "Manual distillation target",
+ description: "Implemented enough evidence to manually distill into the wiki.",
+ status: "done",
+ projectId: project.id,
+ });
+ harness.seed({ agents: [wikiMaintainerAgent()], projects: [project], issues: [issue] });
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.performAction<{
+ status: string;
+ operation: { issue: { originKind: string; billingCode: string | null; assigneeAgentId: string | null; assigneeAdapterOverrides: { modelProfile?: string } | null; description: string | null } };
+ workItem: { kind: string; workItemId: string };
+ }>("distill-paperclip-now", {
+ companyId: COMPANY_ID,
+ autoApply: false,
+ useCheapModelProfile: true,
+ includeSupportingPages: false,
+ });
+
+ expect(result.status).toBe("queued");
+ expect(result.workItem.kind).toBe("manual");
+ expect(result.operation.issue.originKind).toBe(`${OPERATION_ORIGIN_KIND}:distill`);
+ expect(result.operation.issue.billingCode).toBe("plugin-llm-wiki:default");
+ expect(result.operation.issue.assigneeAgentId).toBe(wikiMaintainerAgent().id);
+ expect(result.operation.issue.assigneeAdapterOverrides).toEqual({ modelProfile: "cheap" });
+ expect(result.operation.issue.description).toContain("Prompt source: LLM Wiki plugin action `distill-paperclip-now`");
+ expect(result.operation.issue.description).toContain(`Required skill: use the installed \`${PAPERCLIP_DISTILL_SKILL_KEY}\` skill`);
+ expect(result.operation.issue.description).toContain("Do not hardcode a single project");
+ expect(result.operation.issue.description).not.toContain(`Source project ID: ${project.id}`);
+ const workItemInsert = harness.dbExecutes.find((execute) =>
+ execute.sql.includes("paperclip_distillation_work_items") && execute.params?.[3] === "manual");
+ expect(workItemInsert?.params).toEqual(expect.arrayContaining([
+ COMPANY_ID,
+ "default",
+ "manual",
+ "medium",
+ null,
+ null,
+ ]));
+ const runInsert = harness.dbExecutes.find((execute) =>
+ execute.sql.includes("paperclip_distillation_runs") && execute.sql.includes("operation_issue_id"));
+ expect(runInsert).toBeUndefined();
+ });
+
+ it("enables distillation cursors for the most recently active non-plugin projects", async () => {
+ const harness = createTestHarness({ manifest });
+ const recentProject = {
+ ...existingProject(),
+ id: "77777777-7777-4777-8777-777777777801",
+ name: "Recent Active Project",
+ status: "in_progress" as const,
+ updatedAt: new Date("2026-05-04T18:00:00Z"),
+ };
+ const olderProject = {
+ ...existingProject(),
+ id: "77777777-7777-4777-8777-777777777802",
+ name: "Older Active Project",
+ status: "in_progress" as const,
+ updatedAt: new Date("2026-05-03T18:00:00Z"),
+ };
+ const overflowProject = {
+ ...existingProject(),
+ id: "77777777-7777-4777-8777-777777777803",
+ name: "Overflow Active Project",
+ status: "in_progress" as const,
+ updatedAt: new Date("2026-05-02T18:00:00Z"),
+ };
+ const completedProject = {
+ ...existingProject(),
+ id: "77777777-7777-4777-8777-777777777804",
+ name: "Completed Project",
+ status: "completed" as const,
+ updatedAt: new Date("2026-05-04T19:00:00Z"),
+ };
+ const pluginProject = {
+ ...existingProject(),
+ id: "77777777-7777-4777-8777-777777777805",
+ name: "LLM Wiki",
+ status: "in_progress" as const,
+ updatedAt: new Date("2026-05-04T20:00:00Z"),
+ managedByPlugin: {
+ id: "77777777-7777-4777-8777-777777777806",
+ pluginId: "plugin-instance-1",
+ pluginKey: manifest.id,
+ pluginDisplayName: manifest.displayName,
+ resourceKind: "project" as const,
+ resourceKey: WIKI_PROJECT_KEY,
+ defaultsJson: {},
+ createdAt: new Date("2026-05-04T00:00:00Z"),
+ updatedAt: new Date("2026-05-04T00:00:00Z"),
+ },
+ };
+ harness.seed({ projects: [recentProject, olderProject, overflowProject, completedProject, pluginProject] });
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.performAction<{
+ selectedProjects: Array<{ id: string; observedAt: string | null }>;
+ eventIngestion: { enabled: boolean; sources: { issues: boolean; comments: boolean; documents: boolean } };
+ }>("enable-paperclip-distillation-active-projects", {
+ companyId: COMPANY_ID,
+ limit: 2,
+ });
+
+ expect(result.selectedProjects.map((project) => project.id)).toEqual([recentProject.id, olderProject.id]);
+ expect(result.eventIngestion).toMatchObject({
+ enabled: true,
+ sources: { issues: true, comments: true, documents: true },
+ });
+ const cursorWrites = harness.dbExecutes.filter((execute) => execute.sql.includes("paperclip_distillation_cursors"));
+ expect(cursorWrites).toHaveLength(2);
+ expect(cursorWrites.map((execute) => execute.params?.[5])).toEqual([recentProject.id, olderProject.id]);
+ expect(cursorWrites.map((execute) => execute.params?.[8])).toEqual([1, 1]);
+ expect(String(cursorWrites[0]?.params?.[9])).toContain('"configuredBy":"enable-active-projects"');
+ });
+
+ it("backfills only the selected Paperclip project and date window", async () => {
+ const harness = createTestHarness({ manifest });
+ const project = existingProject();
+ const inWindow = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777797",
+ identifier: "PAP-4106",
+ title: "Backfill in-window decision",
+ description: "Accepted historical decision that should appear in the backfill page.",
+ status: "done",
+ projectId: project.id,
+ updatedAt: new Date("2026-04-15T12:00:00Z"),
+ });
+ const outOfWindow = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777798",
+ identifier: "PAP-4107",
+ title: "Backfill out-of-window decision",
+ description: "This old decision must not be included in the selected date window.",
+ status: "done",
+ projectId: project.id,
+ updatedAt: new Date("2026-03-01T12:00:00Z"),
+ });
+ const otherProject = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777799",
+ identifier: "PAP-4108",
+ title: "Other project decision",
+ description: "This issue belongs to a different project and must not be included.",
+ status: "done",
+ projectId: "88888888-8888-4888-8888-888888888888",
+ updatedAt: new Date("2026-04-16T12:00:00Z"),
+ });
+ harness.seed({ agents: [wikiMaintainerAgent()], projects: [project], issues: [inWindow, outOfWindow, otherProject] });
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.performAction<{
+ status: string;
+ patches: Array<{ operationType: string; proposedContents: string }>;
+ workItem: { kind: string };
+ operation: { issue: { originKind: string } };
+ }>("backfill-paperclip-distillation", {
+ companyId: COMPANY_ID,
+ projectId: project.id,
+ backfillStartAt: "2026-04-01T00:00:00Z",
+ backfillEndAt: "2026-04-30T23:59:59Z",
+ autoApply: false,
+ includeSupportingPages: false,
+ });
+
+ expect(result.status).toBe("review_required");
+ expect(result.workItem.kind).toBe("backfill");
+ expect(result.operation.issue.originKind).toBe(`${OPERATION_ORIGIN_KIND}:backfill`);
+ const projectPatch = result.patches.find((patch) => patch.operationType === "project_page_distill");
+ expect(projectPatch?.proposedContents).toContain("PAP-4106");
+ expect(projectPatch?.proposedContents).not.toContain("PAP-4107");
+ expect(projectPatch?.proposedContents).not.toContain("PAP-4108");
+ const workItemInsert = harness.dbExecutes.find((execute) =>
+ execute.sql.includes("paperclip_distillation_work_items") && execute.params?.[3] === "backfill");
+ expect(String(workItemInsert?.params?.[9])).toContain('"backfillStartAt":"2026-04-01T00:00:00Z"');
+ });
+
+ it("generates review-required Paperclip project page patches with provenance, index, and log updates", async () => {
+ const harness = createTestHarness({ manifest });
+ const project = existingProject();
+ const issue = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777791",
+ identifier: "PAP-4100",
+ title: "Approved project page distillation plan",
+ description: "Accepted plan: write stable project overview sections with source provenance.",
+ status: "in_progress",
+ projectId: project.id,
+ updatedAt: new Date("2026-05-03T10:00:00Z"),
+ });
+ const files = new Map<string, string>([
+ ["wiki/index.md", DEFAULT_INDEX],
+ ["wiki/log.md", DEFAULT_LOG],
+ ]);
+ const writes: Array<{ path: string; contents: string }> = [];
+ harness.seed({ projects: [project], issues: [issue] });
+ harness.ctx.localFolders.readText = async (_companyId, _folderKey, relativePath) => {
+ const contents = files.get(relativePath);
+ if (contents == null) throw new Error(`missing ${relativePath}`);
+ return contents;
+ };
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push({ path: relativePath, contents });
+ files.set(relativePath, contents);
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.performAction<{
+ status: string;
+ patches: Array<{ pagePath: string; operationType: string; currentHash: string | null; proposedContents: string; sourceRefs: Array<{ issueIdentifier: string | null }> }>;
+ warnings: string[];
+ }>("distill-paperclip-project-page", {
+ companyId: COMPANY_ID,
+ projectId: project.id,
+ autoApply: false,
+ maxCharacters: 20000,
+ includeSupportingPages: false,
+ });
+
+ expect(result.status).toBe("review_required");
+ expect(writes).toHaveLength(0);
+ expect(result.patches.map((patch) => patch.operationType)).toEqual([
+ "standup_update",
+ "project_page_distill",
+ "index_refresh",
+ "log_append",
+ ]);
+ const standupPatch = result.patches[0];
+ expect(standupPatch.pagePath).toBe("wiki/projects/existing-wiki-project/standup.md");
+ expect(standupPatch.proposedContents).toContain("## Executive Readout");
+ expect(standupPatch.proposedContents).toContain("## What Changed");
+ const projectPatch = result.patches[1];
+ expect(projectPatch.currentHash).toBeNull();
+ expect(projectPatch.pagePath).toBe("wiki/projects/existing-wiki-project/index.md");
+ expect(projectPatch.proposedContents).toContain("## Workstreams");
+ expect(projectPatch.proposedContents).toContain("PAP-4100");
+ expect(projectPatch.sourceRefs).toEqual([expect.objectContaining({ issueIdentifier: "PAP-4100" })]);
+ expect(result.patches[2].proposedContents).toContain("[[wiki/projects/existing-wiki-project/index.md]]");
+ expect(result.patches[2].proposedContents).toContain("[[wiki/projects/existing-wiki-project/standup.md]]");
+ expect(result.patches[3].proposedContents).toContain("paperclip-distill | proposed");
+ expect(result.warnings).toContain("Auto-apply policy disabled; proposed patches require review.");
+ });
+
+ it("keeps suppressed secret-like source content out of generated wiki patches", async () => {
+ const harness = createTestHarness({ manifest });
+ const project = existingProject();
+ const issue = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777796",
+ identifier: "PAP-4104",
+ title: "Distill sanitized provenance",
+ description: "Publish enough project state for a reviewable project page without leaking credentials.",
+ status: "in_progress",
+ projectId: project.id,
+ updatedAt: new Date("2026-05-04T10:00:00Z"),
+ });
+ const files = new Map<string, string>([
+ ["wiki/index.md", DEFAULT_INDEX],
+ ["wiki/log.md", DEFAULT_LOG],
+ ]);
+ harness.seed({
+ projects: [project],
+ issues: [issue],
+ issueComments: [{
+ id: "77777777-7777-4777-8777-777777777797",
+ companyId: COMPANY_ID,
+ issueId: issue.id,
+ authorType: "user",
+ authorAgentId: null,
+ authorUserId: null,
+ body: "Authorization: Bearer ghp_patchsecretcommenttoken1234567890",
+ presentation: null,
+ metadata: null,
+ createdAt: new Date("2026-05-04T11:00:00Z"),
+ updatedAt: new Date("2026-05-04T11:00:00Z"),
+ }],
+ });
+ harness.ctx.localFolders.readText = async (_companyId, _folderKey, relativePath) => {
+ const contents = files.get(relativePath);
+ if (contents == null) throw new Error(`missing ${relativePath}`);
+ return contents;
+ };
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ files.set(relativePath, contents);
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ await harness.ctx.issues.documents.upsert({
+ companyId: COMPANY_ID,
+ issueId: issue.id,
+ key: "plan",
+ title: "Plan",
+ body: "OPENAI_API_KEY=sk-patchsecretdocumentvalue1234567890",
+ });
+
+ const result = await harness.performAction<{
+ status: string;
+ patches: Array<{ operationType: string; proposedContents: string }>;
+ }>("distill-paperclip-project-page", {
+ companyId: COMPANY_ID,
+ projectId: project.id,
+ maxCharacters: 20000,
+ includeSupportingPages: false,
+ });
+
+ expect(result.status).toBe("review_required");
+ const combinedPatchContents = result.patches.map((patch) => patch.proposedContents).join("\n");
+ expect(combinedPatchContents).toContain("redaction=suppressed_sensitive_content");
+ expect(combinedPatchContents).toContain("redaction_reasons=secret_like_token");
+ expect(combinedPatchContents).not.toContain("ghp_patchsecretcommenttoken1234567890");
+ expect(combinedPatchContents).not.toContain("sk-patchsecretdocumentvalue1234567890");
+ });
+
+ it("auto-applies Paperclip project page patches by default when policy allows and records page bindings", async () => {
+ const harness = createTestHarness({ manifest });
+ const project = existingProject();
+ const issue = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777792",
+ identifier: "PAP-4101",
+ title: "Implement project page writer",
+ description: "Implementation completed enough to publish the generated project page.",
+ status: "done",
+ projectId: project.id,
+ updatedAt: new Date("2026-05-04T10:00:00Z"),
+ });
+ const files = new Map<string, string>([
+ ["wiki/index.md", DEFAULT_INDEX],
+ ["wiki/log.md", DEFAULT_LOG],
+ ]);
+ harness.seed({ projects: [project], issues: [issue] });
+ harness.ctx.localFolders.readText = async (_companyId, _folderKey, relativePath) => {
+ const contents = files.get(relativePath);
+ if (contents == null) throw new Error(`missing ${relativePath}`);
+ return contents;
+ };
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ files.set(relativePath, contents);
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.performAction<{
+ status: string;
+ appliedPages: string[];
+ patches: Array<{ pagePath: string; sourceHash: string }>;
+ }>("distill-paperclip-project-page", {
+ companyId: COMPANY_ID,
+ projectId: project.id,
+ autoApply: true,
+ maxCharacters: 20000,
+ includeSupportingPages: false,
+ });
+
+ expect(result.status).toBe("applied");
+ expect(result.appliedPages).toEqual([
+ "wiki/projects/existing-wiki-project/standup.md",
+ "wiki/projects/existing-wiki-project/index.md",
+ "wiki/index.md",
+ "wiki/log.md",
+ ]);
+ expect(files.get("wiki/projects/existing-wiki-project/standup.md")).toContain("## Executive Readout");
+ expect(files.get("wiki/projects/existing-wiki-project/index.md")).toContain("## Current Direction");
+ expect(files.get("wiki/projects/existing-wiki-project/index.md")).toContain("## References");
+ expect(files.get("wiki/index.md")).toContain("wiki/projects/existing-wiki-project/index.md");
+ expect(files.get("wiki/log.md")).toContain("paperclip-distill | proposed");
+ const bindingWrites = harness.dbExecutes.filter((execute) => execute.sql.includes("paperclip_page_bindings"));
+ expect(bindingWrites).toHaveLength(4);
+ expect(bindingWrites[0].params).toEqual(expect.arrayContaining([
+ COMPANY_ID,
+ "default",
+ project.id,
+ null,
+ "wiki/projects/existing-wiki-project/standup.md",
+ result.patches[0].sourceHash,
+ ]));
+ });
+
+ it("refuses auto-apply Paperclip project page patches in authenticated/public deployments", async () => {
+ process.env.PAPERCLIP_DEPLOYMENT_MODE = "authenticated";
+ process.env.PAPERCLIP_DEPLOYMENT_EXPOSURE = "public";
+ const harness = createTestHarness({ manifest, config: { autoApplyIngestPatches: true } });
+ const project = existingProject();
+ const issue = paperclipIssue({
+ id: "77777777-7777-4777-8777-77777777779a",
+ identifier: "PAP-4101",
+ title: "Implement project page writer",
+ description: "Implementation completed enough to publish the generated project page.",
+ status: "done",
+ projectId: project.id,
+ updatedAt: new Date("2026-05-04T10:00:00Z"),
+ });
+ const files = new Map<string, string>([
+ ["wiki/index.md", DEFAULT_INDEX],
+ ["wiki/log.md", DEFAULT_LOG],
+ ]);
+ const writes: string[] = [];
+ harness.seed({ projects: [project], issues: [issue] });
+ harness.ctx.localFolders.readText = async (_companyId, _folderKey, relativePath) => {
+ const contents = files.get(relativePath);
+ if (contents == null) throw new Error(`missing ${relativePath}`);
+ return contents;
+ };
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push(relativePath);
+ files.set(relativePath, contents);
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.performAction<{
+ status: string;
+ appliedPages: string[];
+ warnings: string[];
+ }>("distill-paperclip-project-page", {
+ companyId: COMPANY_ID,
+ projectId: project.id,
+ autoApply: true,
+ maxCharacters: 20000,
+ includeSupportingPages: false,
+ });
+
+ expect(result.status).toBe("review_required");
+ expect(result.appliedPages).toEqual([]);
+ expect(writes).toHaveLength(0);
+ expect(result.warnings).toContain(
+ "Authenticated/public deployments always require manual review before wiki writes.",
+ );
+ });
+
+ it("refuses stale project page hashes before writing generated Paperclip pages", async () => {
+ const harness = createTestHarness({ manifest, config: { autoApplyIngestPatches: true } });
+ const project = existingProject();
+ const issue = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777793",
+ identifier: "PAP-4102",
+ title: "Publish project page",
+ description: "Ready to publish.",
+ status: "done",
+ projectId: project.id,
+ });
+ const files = new Map<string, string>([
+ ["wiki/projects/existing-wiki-project/index.md", "# Existing\n"],
+ ["wiki/index.md", DEFAULT_INDEX],
+ ["wiki/log.md", DEFAULT_LOG],
+ ]);
+ const writes: string[] = [];
+ harness.seed({ projects: [project], issues: [issue] });
+ harness.ctx.localFolders.readText = async (_companyId, _folderKey, relativePath) => {
+ const contents = files.get(relativePath);
+ if (contents == null) throw new Error(`missing ${relativePath}`);
+ return contents;
+ };
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push(relativePath);
+ files.set(relativePath, contents);
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ await expect(harness.performAction("distill-paperclip-project-page", {
+ companyId: COMPANY_ID,
+ projectId: project.id,
+ autoApply: true,
+ expectedProjectPageHash: "stale",
+ includeSupportingPages: false,
+ })).rejects.toThrow("Refusing to overwrite");
+ expect(writes).toHaveLength(0);
+ });
+
+ it("skips low-signal Paperclip source windows without proposing wiki writes", async () => {
+ const harness = createTestHarness({ manifest });
+ const project = existingProject();
+ const issue = paperclipIssue({
+ id: "77777777-7777-4777-8777-777777777794",
+ identifier: "PAP-4103",
+ title: "Routine heartbeat",
+ description: "",
+ status: "todo",
+ projectId: project.id,
+ });
+ const writes: string[] = [];
+ harness.seed({ projects: [project], issues: [issue] });
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push(relativePath);
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.performAction<{ status: string; reason: string; patches: unknown[] }>("distill-paperclip-project-page", {
+ companyId: COMPANY_ID,
+ projectId: project.id,
+ maxCharacters: 20000,
+ });
+
+ expect(result.status).toBe("skipped");
+ expect(result.reason).toBe("low_signal");
+ expect(result.patches).toEqual([]);
+ expect(writes).toHaveLength(0);
+ });
+
+ it("bootstraps required local wiki files through the local folder API", async () => {
+ const harness = createTestHarness({ manifest });
+ const writes: Array<{ path: string; contents: string }> = [];
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push({ path: relativePath, contents });
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.performAction<{ writtenFiles: string[]; managedSkills: WikiSkillResource[] }>("bootstrap-root", {
+ companyId: COMPANY_ID,
+ path: "/tmp/company-wiki",
+ });
+
+ expect(result.writtenFiles).toContain("AGENTS.md");
+ expect(result.writtenFiles).toContain("IDEA.md");
+ expect(result.managedSkills[0]).toMatchObject({
+ status: "created",
+ resourceKey: WIKI_MAINTAINER_SKILL_KEY,
+ details: { key: WIKI_MAINTAINER_SKILL_CANONICAL_KEY },
+ });
+ expect(writes.map((write) => write.path)).toEqual([
+ ".gitignore",
+ "AGENTS.md",
+ "IDEA.md",
+ "wiki/index.md",
+ "wiki/log.md",
+ "raw/.gitkeep",
+ "wiki/sources/.gitkeep",
+ "wiki/projects/.gitkeep",
+ "wiki/entities/.gitkeep",
+ "wiki/concepts/.gitkeep",
+ "wiki/synthesis/.gitkeep",
+ ]);
+ expect(writes.find((write) => write.path === "AGENTS.md")?.contents).toContain("LLM Wiki Schema");
+ expect(writes.find((write) => write.path === "AGENTS.md")?.contents).toContain("wiki/projects/<project-slug>/index.md");
+ expect(writes.find((write) => write.path === "AGENTS.md")?.contents).toContain("wiki/projects/<project-slug>/standup.md");
+ });
+
+ it("creates a managed space with an immediately readable baseline skeleton", async () => {
+ const harness = createTestHarness({ manifest });
+ const files = new Map<string, string>();
+ harness.ctx.localFolders.readText = async (_companyId, _folderKey, relativePath) => {
+ const value = files.get(relativePath);
+ if (value == null) throw new Error(`missing ${relativePath}`);
+ return value;
+ };
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ files.set(relativePath, contents);
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const created = await harness.performAction<{
+ space: { slug: string; pathPrefix: string | null };
+ }>("create-space", {
+ companyId: COMPANY_ID,
+ displayName: "QA Space",
+ });
+
+ expect(created.space).toMatchObject({
+ slug: "qa-space",
+ pathPrefix: "spaces/qa-space",
+ });
+ await expect(harness.ctx.localFolders.readText(
+ COMPANY_ID,
+ "wiki-root",
+ "spaces/qa-space/AGENTS.md",
+ )).resolves.toContain("LLM Wiki Schema");
+ expect(files.get("spaces/qa-space/IDEA.md")).toBe(DEFAULT_IDEA);
+ expect(files.has("spaces/qa-space/raw/.gitkeep")).toBe(true);
+ expect(files.has("spaces/qa-space/projects/.gitkeep")).toBe(false);
+ expect(files.has("spaces/qa-space/wiki/projects/.gitkeep")).toBe(true);
+ expect(files.has("spaces/qa-space/wiki/index.md")).toBe(true);
+ });
+
+ it("prevents the default space from being archived through update-space", async () => {
+ const harness = createTestHarness({ manifest });
+ await plugin.definition.setup(harness.ctx);
+
+ await expect(harness.performAction("update-space", {
+ companyId: COMPANY_ID,
+ spaceSlug: "default",
+ status: "archived",
+ })).rejects.toThrow("The default LLM Wiki space cannot be archived.");
+ const defaultSpaceInsert = harness.dbExecutes.find((execute) =>
+ execute.sql.includes("INSERT INTO") && execute.sql.includes("wiki_spaces"));
+ expect(defaultSpaceInsert?.params?.[0]).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-8[0-9a-f]{3}-[0-9a-f]{12}$/);
+ expect(harness.dbExecutes.some((execute) =>
+ execute.sql.includes("UPDATE") &&
+ execute.sql.includes("wiki_spaces") &&
+ execute.params?.includes("archived"))).toBe(false);
+ });
+
+ it("archives a non-default space through update-space without re-resolving it as active", async () => {
+ const harness = createTestHarness({ manifest });
+ const spaceRow = wikiSpaceRow({
+ id: "77777777-7777-4777-8777-7777777777b1",
+ slug: "qa-space",
+ displayName: "QA Space",
+ pathPrefix: "spaces/qa-space",
+ status: "active",
+ settings: { owner: "qa" },
+ });
+ let archived = false;
+ const originalQuery = harness.ctx.db.query.bind(harness.ctx.db);
+ harness.ctx.db.query = async <T,>(sql: string, params?: unknown[]) => {
+ harness.dbQueries.push({ sql, params });
+ if (sql.includes("wiki_spaces") && params?.[2] === "qa-space") {
+ return archived && sql.includes("status <> 'archived'") ? [] as T[] : [spaceRow] as T[];
+ }
+ return originalQuery<T>(sql, params);
+ };
+ const originalExecute = harness.ctx.db.execute.bind(harness.ctx.db);
+ harness.ctx.db.execute = async (sql: string, params?: unknown[]) => {
+ if (sql.includes("UPDATE") && sql.includes("wiki_spaces") && params?.includes("archived")) archived = true;
+ return originalExecute(sql, params);
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const updated = await harness.performAction<{
+ status: string;
+ space: { slug: string; displayName: string; status: string; settings: Record<string, unknown> };
+ }>("update-space", {
+ companyId: COMPANY_ID,
+ spaceSlug: "qa-space",
+ displayName: "Archived QA",
+ settings: { archivedBy: "test" },
+ status: "archived",
+ });
+
+ expect(updated.status).toBe("ok");
+ expect(updated.space).toMatchObject({
+ slug: "qa-space",
+ displayName: "Archived QA",
+ status: "archived",
+ settings: { owner: "qa", archivedBy: "test" },
+ });
+ expect(archived).toBe(true);
+ });
+
+ it("restores an archived non-default space through update-space", async () => {
+ const harness = createTestHarness({ manifest });
+ const spaceRow = wikiSpaceRow({
+ id: "77777777-7777-4777-8777-7777777777b2",
+ slug: "qa-space",
+ displayName: "QA Space",
+ pathPrefix: "spaces/qa-space",
+ status: "archived",
+ });
+ let restored = false;
+ const originalQuery = harness.ctx.db.query.bind(harness.ctx.db);
+ harness.ctx.db.query = async <T,>(sql: string, params?: unknown[]) => {
+ harness.dbQueries.push({ sql, params });
+ if (sql.includes("wiki_spaces") && params?.[2] === "qa-space") {
+ if (!restored && sql.includes("status <> 'archived'")) return [] as T[];
+ return [{
+ ...spaceRow,
+ status: restored ? "active" : "archived",
+ }] as T[];
+ }
+ return originalQuery<T>(sql, params);
+ };
+ const originalExecute = harness.ctx.db.execute.bind(harness.ctx.db);
+ harness.ctx.db.execute = async (sql: string, params?: unknown[]) => {
+ if (sql.includes("UPDATE") && sql.includes("wiki_spaces") && params?.includes("active")) restored = true;
+ return originalExecute(sql, params);
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const updated = await harness.performAction<{
+ status: string;
+ space: { slug: string; status: string };
+ }>("update-space", {
+ companyId: COMPANY_ID,
+ spaceSlug: "qa-space",
+ status: "active",
+ });
+
+ expect(updated.status).toBe("ok");
+ expect(updated.space).toMatchObject({
+ slug: "qa-space",
+ status: "active",
+ });
+ expect(restored).toBe(true);
+ });
+
+ it("rejects unknown space statuses through update-space", async () => {
+ const harness = createTestHarness({ manifest });
+ await plugin.definition.setup(harness.ctx);
+
+ await expect(harness.performAction("update-space", {
+ companyId: COMPANY_ID,
+ spaceSlug: "default",
+ status: "suspended",
+ })).rejects.toThrow("LLM Wiki space status must be active or archived.");
+ expect(harness.dbExecutes.some((execute) =>
+ execute.sql.includes("UPDATE") &&
+ execute.sql.includes("wiki_spaces") &&
+ execute.params?.includes("suspended"))).toBe(false);
+ });
+
+ it("omits archived spaces from the spaces data API", async () => {
+ const harness = createTestHarness({ manifest });
+ const activeRow = wikiSpaceRow({
+ id: "77777777-7777-4777-8777-7777777777a1",
+ slug: "team-research",
+ displayName: "Team Research",
+ pathPrefix: "spaces/team-research",
+ status: "active",
+ });
+ const archivedRow = wikiSpaceRow({
+ id: "77777777-7777-4777-8777-7777777777a2",
+ slug: "qa-team-lock",
+ displayName: "QA Team Lock",
+ pathPrefix: "spaces/qa-team-lock",
+ status: "archived",
+ });
+ harness.ctx.db.query = async <T,>(sql: string, params?: unknown[]) => {
+ harness.dbQueries.push({ sql, params });
+ if (sql.includes("wiki_spaces") && sql.includes("ORDER BY CASE WHEN slug = 'default'")) {
+ const rows = [defaultWikiSpaceRow(), activeRow];
+ if (!sql.includes("status <> 'archived'")) rows.push(archivedRow);
+ return rows as T[];
+ }
+ if (sql.includes("wiki_spaces") && sql.includes("slug = 'default'")) {
+ return [defaultWikiSpaceRow()] as T[];
+ }
+ return [] as T[];
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.getData<{ spaces: Array<{ slug: string }> }>("spaces", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ });
+
+ expect(result.spaces.map((space) => space.slug)).toEqual(["default", "team-research"]);
+ expect(harness.dbQueries.some((query) => query.sql.includes("status <> 'archived'"))).toBe(true);
+ });
+
+ it("captures raw sources into local files and plugin metadata", async () => {
+ const harness = createTestHarness({ manifest });
+ const writes: Array<{ path: string; contents: string }> = [];
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push({ path: relativePath, contents });
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.performAction<{ rawPath: string; hash: string }>("capture-source", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ title: "Plugin Boundaries",
+ contents: "# Plugin Boundaries\n\nKeep wiki logic in the plugin.",
+ });
+
+ expect(result.rawPath).toMatch(/^raw\/\d{4}-\d{2}-\d{2}-plugin-boundaries-/);
+ expect(result.hash).toHaveLength(64);
+ expect(writes[0]).toMatchObject({ path: result.rawPath });
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_sources"))).toBe(true);
+ });
+
+ it("preserves manual source ingest for non-default spaces while refusing Paperclip distillation there", async () => {
+ const harness = createTestHarness({ manifest });
+ const writes: Array<{ path: string; contents: string }> = [];
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push({ path: relativePath, contents });
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+ harness.seed({
+ agents: [wikiMaintainerAgent()],
+ projects: [existingProject()],
+ });
+ const spaces = new Map<string, Record<string, unknown>>();
+ const originalQuery = harness.ctx.db.query.bind(harness.ctx.db);
+ harness.ctx.db.query = async <T,>(sql: string, params?: unknown[]) => {
+ if (sql.includes("wiki_spaces")) {
+ const slug = typeof params?.[2] === "string" ? params[2] : null;
+ if (slug && spaces.has(slug)) return [spaces.get(slug)] as T[];
+ }
+ return originalQuery<T>(sql, params);
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const created = await harness.performAction<{
+ space: { id: string; companyId: string; wikiId: string; slug: string; displayName: string; pathPrefix: string | null };
+ }>("create-space", {
+ companyId: COMPANY_ID,
+ displayName: "Team Research",
+ });
+ spaces.set(created.space.slug, {
+ id: created.space.id,
+ company_id: created.space.companyId,
+ wiki_id: created.space.wikiId,
+ slug: created.space.slug,
+ display_name: created.space.displayName,
+ space_type: "local_folder",
+ folder_mode: "managed_subfolder",
+ root_folder_key: "wiki-root",
+ path_prefix: created.space.pathPrefix,
+ configured_root_path: null,
+ access_scope: "shared",
+ owner_user_id: null,
+ owner_agent_id: null,
+ team_key: null,
+ settings: {},
+ status: "active",
+ created_at: null,
+ updated_at: null,
+ });
+
+ const source = await harness.performAction<{ rawPath: string; spaceSlug: string }>("capture-source", {
+ companyId: COMPANY_ID,
+ spaceSlug: created.space.slug,
+ title: "Team notes",
+ contents: "# Team notes\n\nManual source ingest still belongs to the selected space.",
+ });
+
+ expect(source.spaceSlug).toBe(created.space.slug);
+ expect(writes.map((write) => write.path)).toContain(`spaces/${created.space.slug}/${source.rawPath}`);
+ await expect(harness.performAction("distill-paperclip-now", {
+ companyId: COMPANY_ID,
+ spaceSlug: created.space.slug,
+ projectId: existingProject().id,
+ })).rejects.toThrow("Paperclip ingestion policy denied queue");
+ });
+
+ it("fails closed for direct Paperclip ingestion actions against restricted spaces", async () => {
+ const harness = createTestHarness({ manifest });
+ harness.seed({
+ agents: [wikiMaintainerAgent()],
+ projects: [existingProject()],
+ });
+
+ await plugin.definition.setup(harness.ctx);
+ const created = await harness.performAction<{
+ space: { slug: string; accessScope: string };
+ }>("create-space", {
+ companyId: COMPANY_ID,
+ displayName: "Private Notes",
+ accessScope: "personal",
+ });
+
+ expect(created.space.accessScope).toBe("personal");
+ const originalQuery = harness.ctx.db.query.bind(harness.ctx.db);
+ harness.ctx.db.query = async <T,>(sql: string, params?: unknown[]) => {
+ if (sql.includes("wiki_spaces") && params?.[2] === created.space.slug) {
+ return [{
+ id: "77777777-7777-4777-8777-7777777777b2",
+ company_id: COMPANY_ID,
+ wiki_id: "default",
+ slug: created.space.slug,
+ display_name: "Private Notes",
+ space_type: "local_folder",
+ folder_mode: "managed_subfolder",
+ root_folder_key: "wiki-root",
+ path_prefix: `spaces/${created.space.slug}`,
+ configured_root_path: null,
+ access_scope: "personal",
+ owner_user_id: null,
+ owner_agent_id: null,
+ team_key: null,
+ settings: {},
+ status: "active",
+ created_at: null,
+ updated_at: null,
+ }] as T[];
+ }
+ return originalQuery<T>(sql, params);
+ };
+ await expect(harness.performAction("distill-paperclip-now", {
+ companyId: COMPANY_ID,
+ spaceSlug: created.space.slug,
+ projectId: existingProject().id,
+ })).rejects.toThrow("Paperclip ingestion policy denied queue");
+
+ const operations = await harness.ctx.issues.list({
+ companyId: COMPANY_ID,
+ originKindPrefix: String(OPERATION_ORIGIN_KIND),
+ });
+ expect(operations).toHaveLength(0);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("paperclip_distillation_work_items"))).toBe(false);
+ });
+
+ it("re-checks Paperclip ingestion policy at execution time for queued work", async () => {
+ const harness = createTestHarness({ manifest });
+ const project = existingProject();
+ const issue = paperclipIssue({
+ id: "77777777-7777-4777-8777-7777777777b0",
+ identifier: "PAP-4111",
+ title: "Queued distillation source",
+ description: "Accepted queued work should not run after policy changes.",
+ projectId: project.id,
+ status: "done",
+ });
+ harness.seed({ agents: [wikiMaintainerAgent()], projects: [project], issues: [issue] });
+
+ await plugin.definition.setup(harness.ctx);
+ const queued = await harness.performAction<{ status: string }>("distill-paperclip-now", {
+ companyId: COMPANY_ID,
+ projectId: project.id,
+ });
+ expect(queued.status).toBe("queued");
+
+ const originalQuery = harness.ctx.db.query.bind(harness.ctx.db);
+ harness.ctx.db.query = async <T,>(sql: string, params?: unknown[]) => {
+ if (sql.includes("wiki_spaces") && sql.includes("slug = 'default'")) {
+ return [{
+ id: "77777777-7777-4777-8777-7777777777b1",
+ company_id: COMPANY_ID,
+ wiki_id: "default",
+ slug: "default",
+ display_name: "default",
+ space_type: "local_folder",
+ folder_mode: "managed_subfolder",
+ root_folder_key: "wiki-root",
+ path_prefix: null,
+ configured_root_path: null,
+ access_scope: "personal",
+ owner_user_id: null,
+ owner_agent_id: null,
+ team_key: null,
+ settings: {},
+ status: "active",
+ created_at: null,
+ updated_at: null,
+ }] as T[];
+ }
+ return originalQuery<T>(sql, params);
+ };
+
+ await expect(harness.performAction("create-paperclip-distillation-run", {
+ companyId: COMPANY_ID,
+ projectId: project.id,
+ })).rejects.toThrow("personal spaces cannot ingest Paperclip sources");
+ expect(harness.dbExecutes.some((execute) =>
+ execute.sql.includes("paperclip_distillation_runs") && execute.sql.includes("'source_ready'"))).toBe(false);
+ });
+
+ it("queues Paperclip ingestion backfills for every selected project scope", async () => {
+ const harness = createTestHarness({ manifest });
+ await plugin.definition.setup(harness.ctx);
+
+ const queued = await harness.performAction<{
+ status: string;
+ workItemId: string;
+ issueId: string;
+ workItems: Array<{ workItemId: string; issueId: string; projectId: string | null; rootIssueId: string | null }>;
+ }>("queue-paperclip-ingestion-backfill", {
+ companyId: COMPANY_ID,
+ sourceScope: {
+ kind: "selected_projects",
+ projectIds: [
+ "77777777-7777-4777-8777-7777777777a1",
+ "77777777-7777-4777-8777-7777777777a2",
+ ],
+ },
+ backfillStartAt: "2026-05-01T00:00:00.000Z",
+ backfillEndAt: "2026-05-02T00:00:00.000Z",
+ });
+
+ expect(queued.status).toBe("queued");
+ expect(queued.workItems).toHaveLength(2);
+ expect(queued.workItemId).toBe(queued.workItems[0]?.workItemId);
+ expect(queued.issueId).toBe(queued.workItems[0]?.issueId);
+ expect(queued.workItems.map((item) => item.projectId)).toEqual([
+ "77777777-7777-4777-8777-7777777777a1",
+ "77777777-7777-4777-8777-7777777777a2",
+ ]);
+ expect(harness.dbExecutes.filter((execute) => execute.sql.includes("paperclip_distillation_work_items"))).toHaveLength(2);
+ });
+
+ it("rejects oversized Paperclip ingestion profile and source-scope payloads", async () => {
+ const harness = createTestHarness({ manifest });
+
+ await plugin.definition.setup(harness.ctx);
+ await expect(harness.performAction("update-event-ingestion-settings", {
+ companyId: COMPANY_ID,
+ enabled: true,
+ maxCharacters: 20001,
+ sources: { issues: true },
+ })).rejects.toThrow("maxCharacters exceeds the hard Paperclip ingestion cap");
+
+ await expect(harness.performAction("enable-paperclip-distillation-active-projects", {
+ companyId: COMPANY_ID,
+ limit: 26,
+ })).rejects.toThrow("fan-out exceeds the hard cap");
+
+ await expect(harness.performAction("assemble-paperclip-source-bundle", {
+ companyId: COMPANY_ID,
+ projectId: "77777777-7777-4777-8777-777777777777",
+ rootIssueId: "77777777-7777-4777-8777-777777777778",
+ })).rejects.toThrow("either projectId or rootIssueId");
+
+ await expect(harness.performAction("assemble-paperclip-source-bundle", {
+ companyId: COMPANY_ID,
+ projectId: "77777777-7777-4777-8777-777777777777",
+ maxCharacters: 60001,
+ })).rejects.toThrow("maxCharacters exceeds the hard Paperclip ingestion cap");
+ });
+
+ it("keeps default-space files at the root and isolates managed spaces under slug prefixes", async () => {
+ const harness = createTestHarness({ manifest });
+ const files = new Map<string, string>();
+ const writes: Array<{ path: string; contents: string }> = [];
+ harness.ctx.localFolders.readText = async (_companyId, _folderKey, relativePath) => {
+ const value = files.get(relativePath);
+ if (value == null) throw new Error(`missing ${relativePath}`);
+ return value;
+ };
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push({ path: relativePath, contents });
+ files.set(relativePath, contents);
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+ const spaces = new Map<string, Record<string, unknown>>();
+ const originalQuery = harness.ctx.db.query.bind(harness.ctx.db);
+ harness.ctx.db.query = async <T,>(sql: string, params?: unknown[]) => {
+ if (sql.includes("wiki_spaces")) {
+ const slug = typeof params?.[2] === "string" ? params[2] : null;
+ if (slug && spaces.has(slug)) return [spaces.get(slug)] as T[];
+ }
+ return originalQuery<T>(sql, params);
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const created = await harness.performAction<{
+ space: { id: string; companyId: string; wikiId: string; slug: string; displayName: string; pathPrefix: string | null };
+ }>("create-space", {
+ companyId: COMPANY_ID,
+ displayName: "Research Space",
+ });
+ spaces.set(created.space.slug, {
+ id: created.space.id,
+ company_id: created.space.companyId,
+ wiki_id: created.space.wikiId,
+ slug: created.space.slug,
+ display_name: created.space.displayName,
+ space_type: "local_folder",
+ folder_mode: "managed_subfolder",
+ root_folder_key: "wiki-root",
+ path_prefix: created.space.pathPrefix,
+ configured_root_path: null,
+ access_scope: "shared",
+ owner_user_id: null,
+ owner_agent_id: null,
+ team_key: null,
+ settings: {},
+ status: "active",
+ created_at: null,
+ updated_at: null,
+ });
+ await harness.performAction("bootstrap-space", {
+ companyId: COMPANY_ID,
+ spaceSlug: created.space.slug,
+ });
+ await harness.performAction("write-page", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ path: "wiki/concepts/shared.md",
+ contents: "# Default Shared\n",
+ });
+ await harness.performAction("write-page", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ spaceSlug: created.space.slug,
+ path: "wiki/concepts/shared.md",
+ contents: "# Space Shared\n",
+ });
+ await harness.performAction("capture-source", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ rawPath: "raw/shared.md",
+ title: "Shared Source",
+ contents: "# Default Raw\n",
+ });
+ await harness.performAction("capture-source", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ spaceSlug: created.space.slug,
+ rawPath: "raw/shared.md",
+ title: "Shared Source",
+ contents: "# Space Raw\n",
+ });
+
+ expect(created.space).toMatchObject({
+ slug: "research-space",
+ pathPrefix: "spaces/research-space",
+ });
+ expect(files.get("wiki/concepts/shared.md")).toBe("# Default Shared\n");
+ expect(files.get("spaces/research-space/wiki/concepts/shared.md")).toBe("# Space Shared\n");
+ expect(files.get("raw/shared.md")).toBe("# Default Raw\n");
+ expect(files.get("spaces/research-space/raw/shared.md")).toBe("# Space Raw\n");
+ expect(writes.map((write) => write.path)).not.toContain("spaces/default/wiki/concepts/shared.md");
+
+ const pageWrites = harness.dbExecutes.filter((execute) => execute.sql.includes("wiki_pages"));
+ const sourceWrites = harness.dbExecutes.filter((execute) => execute.sql.includes("wiki_sources"));
+ expect(pageWrites.every((write) => write.sql.includes("space_id"))).toBe(true);
+ expect(sourceWrites.every((write) => write.sql.includes("space_id"))).toBe(true);
+ });
+
+ it("ingests source metadata and creates a hidden plugin-operation issue", async () => {
+ const harness = createTestHarness({ manifest });
+ harness.seed({ agents: [wikiMaintainerAgent()] });
+ const writes: Array<{ path: string; contents: string }> = [];
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push({ path: relativePath, contents });
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const result = await harness.performAction<{
+ source: { rawPath: string; title: string; hash: string };
+ operation: { operationId: string; issue: { originKind: string; originId: string | null; billingCode: string | null; assigneeAgentId: string | null } };
+ }>("ingest-source", {
+ companyId: COMPANY_ID,
+ wikiId: "engineering",
+ sourceType: "url",
+ title: "Standalone Plugin Notes",
+ url: "https://example.test/wiki",
+ contents: "# Standalone Plugin Notes\n\nKeep wiki behavior in the plugin package.",
+ rawPath: "raw/standalone-plugin-notes.md",
+ metadata: { importedBy: "alpha-verification" },
+ });
+
+ expect(result.source.rawPath).toBe("raw/standalone-plugin-notes.md");
+ expect(result.source.title).toBe("Standalone Plugin Notes");
+ expect(result.source.hash).toHaveLength(64);
+ expect(writes).toEqual([
+ expect.objectContaining({
+ path: "raw/standalone-plugin-notes.md",
+ contents: expect.stringContaining("Keep wiki behavior in the plugin package."),
+ }),
+ ]);
+ expect(result.operation.issue.originKind).toBe(`${OPERATION_ORIGIN_KIND}:ingest`);
+ expect(result.operation.issue.originId).toBe(`wiki:engineering:operation:${result.operation.operationId}`);
+ expect(result.operation.issue.billingCode).toBe("plugin-llm-wiki:engineering");
+ expect(result.operation.issue.assigneeAgentId).toBe(wikiMaintainerAgent().id);
+
+ const sourceInsert = harness.dbExecutes.find((execute) => execute.sql.includes("wiki_sources"));
+ expect(sourceInsert?.params).toEqual(expect.arrayContaining([
+ COMPANY_ID,
+ "engineering",
+ "url",
+ "Standalone Plugin Notes",
+ "https://example.test/wiki",
+ "raw/standalone-plugin-notes.md",
+ JSON.stringify({ importedBy: "alpha-verification" }),
+ ]));
+ const operationInsert = harness.dbExecutes.find((execute) => execute.sql.includes("wiki_operations"));
+ expect(operationInsert?.params).toEqual(expect.arrayContaining([
+ result.operation.operationId,
+ COMPANY_ID,
+ "engineering",
+ "ingest",
+ "queued",
+ ]));
+ });
+
+ it("rejects oversized source capture before raw writes or operation creation", async () => {
+ const harness = createTestHarness({ manifest, config: { maxSourceBytes: 16 } });
+ harness.seed({ agents: [wikiMaintainerAgent()] });
+ const writes: Array<{ path: string; contents: string }> = [];
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push({ path: relativePath, contents });
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ await expect(harness.performAction("ingest-source", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ sourceType: "text",
+ title: "Oversized source",
+ contents: "x".repeat(17),
+ })).rejects.toThrow("exceeds the configured LLM Wiki source limit");
+
+ expect(writes).toHaveLength(0);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_sources"))).toBe(false);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_operations"))).toBe(false);
+ const operations = await harness.ctx.issues.list({
+ companyId: COMPANY_ID,
+ originKindPrefix: String(OPERATION_ORIGIN_KIND),
+ });
+ expect(operations).toHaveLength(0);
+ });
+
+ it("writes pages atomically, records metadata, and rejects stale hashes", async () => {
+ const harness = createTestHarness({ manifest });
+ const files = new Map<string, string>([
+ ["wiki/concepts/plugin-boundaries.md", "# Old Title\n"],
+ ]);
+ harness.ctx.localFolders.readText = async (_companyId, _folderKey, relativePath) => {
+ const value = files.get(relativePath);
+ if (value == null) throw new Error("missing");
+ return value;
+ };
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ files.set(relativePath, contents);
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+ const staleWrite = harness.executeTool("wiki_write_page", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ path: "wiki/concepts/plugin-boundaries.md",
+ contents: "# New Title\n",
+ expectedHash: "stale",
+ });
+ await expect(staleWrite).rejects.toThrow("Refusing to overwrite");
+
+ const result = await harness.executeTool<{ data?: { hash: string } }>("wiki_write_page", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ path: "wiki/concepts/plugin-boundaries.md",
+ contents: "# Plugin Boundaries\n\nSee [Knowledge](wiki/areas/knowledge.md).",
+ });
+
+ expect(result.data?.hash).toHaveLength(64);
+ expect(files.get("wiki/concepts/plugin-boundaries.md")).toContain("Plugin Boundaries");
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_pages"))).toBe(true);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_page_revisions"))).toBe(true);
+ });
+
+ it("blocks agent-tool writes to AGENTS.md but allows explicit board edits", async () => {
+ const harness = createTestHarness({ manifest });
+ const files = new Map<string, string>([
+ ["AGENTS.md", "# LLM Wiki Maintainer\n\nOriginal instructions.\n"],
+ ]);
+ harness.ctx.localFolders.readText = async (_companyId, _folderKey, relativePath) => {
+ const value = files.get(relativePath);
+ if (value == null) throw new Error("missing");
+ return value;
+ };
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ files.set(relativePath, contents);
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+
+ await plugin.definition.setup(harness.ctx);
+
+ await expect(harness.executeTool("wiki_write_page", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ path: "AGENTS.md",
+ contents: "# LLM Wiki Maintainer\n\nCompromised instructions.\n",
+ })).rejects.toThrow("Refusing to overwrite protected wiki control file AGENTS.md");
+
+ const result = await harness.performAction<{ hash: string }>("write-page", {
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ path: "AGENTS.md",
+ contents: "# LLM Wiki Maintainer\n\nBoard-updated instructions.\n",
+ });
+
+ expect(result.hash).toHaveLength(64);
+ expect(files.get("AGENTS.md")).toContain("Board-updated instructions.");
+ });
+
+ it("creates plugin-operation issues for LLM workflows", async () => {
+ const harness = createTestHarness({ manifest });
+ harness.seed({ agents: [wikiMaintainerAgent()] });
+ await plugin.definition.setup(harness.ctx);
+
+ const result = await harness.performAction<{ issue: { originKind: string; billingCode: string | null } }>(
+ "create-operation",
+ {
+ companyId: COMPANY_ID,
+ operationType: "query",
+ title: "Ask the wiki about plugin boundaries",
+ prompt: "Which files own wiki behavior?",
+ },
+ );
+
+ expect(result.issue.originKind).toBe(`${OPERATION_ORIGIN_KIND}:query`);
+ expect(result.issue.billingCode).toBe("plugin-llm-wiki:default");
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_resource_bindings"))).toBe(true);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_operations"))).toBe(true);
+ });
+
+ it("stamps resolved space context into hidden operation issues and operation metadata", async () => {
+ const harness = createTestHarness({ manifest });
+ harness.seed({ agents: [wikiMaintainerAgent()] });
+ const spaces = new Map<string, Record<string, unknown>>();
+ const originalQuery = harness.ctx.db.query.bind(harness.ctx.db);
+ harness.ctx.db.query = async <T,>(sql: string, params?: unknown[]) => {
+ if (sql.includes("wiki_spaces")) {
+ const slug = typeof params?.[2] === "string" ? params[2] : null;
+ if (slug && spaces.has(slug)) return [spaces.get(slug)] as T[];
+ }
+ return originalQuery<T>(sql, params);
+ };
+ await plugin.definition.setup(harness.ctx);
+
+ const created = await harness.performAction<{
+ space: { id: string; companyId: string; wikiId: string; slug: string; displayName: string; pathPrefix: string | null };
+ }>("create-space", {
+ companyId: COMPANY_ID,
+ displayName: "Research Space",
+ });
+ spaces.set(created.space.slug, {
+ id: created.space.id,
+ company_id: created.space.companyId,
+ wiki_id: created.space.wikiId,
+ slug: created.space.slug,
+ display_name: created.space.displayName,
+ space_type: "local_folder",
+ folder_mode: "managed_subfolder",
+ root_folder_key: "wiki-root",
+ path_prefix: created.space.pathPrefix,
+ configured_root_path: null,
+ access_scope: "shared",
+ owner_user_id: null,
+ owner_agent_id: null,
+ team_key: null,
+ settings: {},
+ status: "active",
+ created_at: null,
+ updated_at: null,
+ });
+
+ const result = await harness.performAction<{
+ operationId: string;
+ issue: { title: string; description: string | null; billingCode: string | null; originId: string | null };
+ }>("create-operation", {
+ companyId: COMPANY_ID,
+ operationType: "lint",
+ title: "Run LLM Wiki lint",
+ prompt: "Audit wiki structure.",
+ spaceSlug: created.space.slug,
+ });
+
+ expect(result.issue.title).toBe("Run LLM Wiki lint [space: Research Space / research-space]");
+ expect(result.issue.description).toContain("Space: Research Space (research-space)");
+ expect(result.issue.description).toContain("Space root: wiki-root/spaces/research-space");
+ expect(result.issue.description).toContain("Pass wikiId `default` and spaceSlug `research-space`");
+ expect(result.issue.description).toContain("Manual ingest, query, lint, index, and file-as-page operations follow the named destination space");
+ expect(result.issue.billingCode).toBe("plugin-llm-wiki:default:research-space");
+ expect(result.issue.originId).toBe(`wiki:default:space:research-space:operation:${result.operationId}`);
+ const operationInsert = harness.dbExecutes.find((execute) =>
+ execute.sql.includes("wiki_operations") && execute.params?.[0] === result.operationId);
+ const metadata = JSON.parse(String(operationInsert?.params?.[8]));
+ expect(metadata).toMatchObject({
+ operationType: "lint",
+ operationId: result.operationId,
+ wikiId: "default",
+ spaceId: created.space.id,
+ spaceSlug: "research-space",
+ spaceName: "Research Space",
+ spaceRoot: "wiki-root/spaces/research-space",
+ billingCode: "plugin-llm-wiki:default:research-space",
+ });
+ });
+
+ it("uses selected existing agent and project bindings for new operations", async () => {
+ const harness = createTestHarness({ manifest });
+ const agent = existingAgent();
+ const project = existingProject();
+ harness.seed({ agents: [agent], projects: [project] });
+ await plugin.definition.setup(harness.ctx);
+
+ const selectedAgent = await harness.performAction<{ source: string; agentId: string }>("select-managed-agent", {
+ companyId: COMPANY_ID,
+ agentId: agent.id,
+ });
+ const selectedProject = await harness.performAction<{ source: string; projectId: string }>("select-managed-project", {
+ companyId: COMPANY_ID,
+ projectId: project.id,
+ });
+
+ expect(selectedAgent).toMatchObject({ source: "selected", agentId: agent.id });
+ expect(selectedProject).toMatchObject({ source: "selected", projectId: project.id });
+ expect(harness.dbExecutes.filter((execute) => execute.sql.includes("wiki_resource_bindings"))).toHaveLength(2);
+
+ harness.ctx.db.query = async <T = Record<string, unknown>>(sql: string, params?: unknown[]) => {
+ harness.dbQueries.push({ sql, params });
+ if (sql.includes("wiki_resource_bindings") && params?.[2] === "agent") {
+ return [{ resolved_id: agent.id, metadata: { source: "selected-existing" } }] as T[];
+ }
+ if (sql.includes("wiki_resource_bindings") && params?.[2] === "project") {
+ return [{ resolved_id: project.id, metadata: { source: "selected-existing" } }] as T[];
+ }
+ if (sql.includes("wiki_operations")) return [{ count: "0" }] as T[];
+ return [];
+ };
+
+ const result = await harness.performAction<{
+ issue: { assigneeAgentId: string | null; projectId: string | null };
+ }>("create-operation", {
+ companyId: COMPANY_ID,
+ operationType: "lint",
+ title: "Lint selected wiki",
+ });
+
+ expect(result.issue.assigneeAgentId).toBe(agent.id);
+ expect(result.issue.projectId).toBe(project.id);
+ });
+
+ it("starts query sessions, records run ids, and forwards session events to plugin streams", async () => {
+ const harness = createTestHarness({ manifest });
+ harness.seed({ agents: [wikiMaintainerAgent()] });
+ const streamEvents: unknown[] = [];
+ harness.ctx.streams.emit = (_channel, event) => {
+ streamEvents.push(event);
+ };
+ await plugin.definition.setup(harness.ctx);
+
+ const result = await harness.performAction<{
+ operationId: string;
+ querySessionId: string;
+ sessionId: string;
+ runId: string;
+ channel: string;
+ }>("start-query", {
+ companyId: COMPANY_ID,
+ question: "Which files own wiki behavior?",
+ });
+
+ expect(result.querySessionId).toBe(result.operationId);
+ expect(result.channel).toBe(`llm-wiki:query:${result.operationId}`);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_query_sessions"))).toBe(true);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("run_ids"))).toBe(true);
+
+ harness.simulateSessionEvent(result.sessionId, {
+ runId: result.runId,
+ seq: 1,
+ eventType: "chunk",
+ stream: "stdout",
+ message: "Keep wiki behavior in the plugin.",
+ payload: null,
+ });
+ harness.simulateSessionEvent(result.sessionId, {
+ runId: result.runId,
+ seq: 2,
+ eventType: "done",
+ stream: "system",
+ message: "Run completed",
+ payload: null,
+ });
+ await new Promise((resolve) => setTimeout(resolve, 0));
+
+ expect(streamEvents).toEqual(expect.arrayContaining([
+ expect.objectContaining({ type: "query.started", operationId: result.operationId }),
+ expect.objectContaining({ type: "agent.event", message: "Keep wiki behavior in the plugin." }),
+ expect.objectContaining({ type: "query.done", answer: "Keep wiki behavior in the plugin." }),
+ ]));
+ expect(harness.dbExecutes.some((execute) =>
+ execute.sql.includes("wiki_query_sessions") && execute.params?.includes("completed"),
+ )).toBe(true);
+ });
+
+ it("files a streamed query answer as a page through a hidden file-as-page operation", async () => {
+ const harness = createTestHarness({ manifest });
+ harness.seed({ agents: [wikiMaintainerAgent()] });
+ const writes: Array<{ path: string; contents: string }> = [];
+ harness.ctx.localFolders.writeTextAtomic = async (_companyId, _folderKey, relativePath, contents) => {
+ writes.push({ path: relativePath, contents });
+ return harness.ctx.localFolders.status(COMPANY_ID, "wiki-root");
+ };
+ await plugin.definition.setup(harness.ctx);
+
+ const result = await harness.performAction<{ path: string; operationId: string; page: { revisionId: string } }>(
+ "file-as-page",
+ {
+ companyId: COMPANY_ID,
+ querySessionId: "33333333-3333-4333-8333-333333333333",
+ question: "Where should wiki code live?",
+ answer: "Wiki-specific code lives in the standalone plugin package.",
+ path: "wiki/concepts/plugin-boundaries.md",
+ title: "Plugin Boundaries",
+ },
+ );
+
+ expect(result.path).toBe("wiki/concepts/plugin-boundaries.md");
+ expect(writes[0]).toMatchObject({ path: "wiki/concepts/plugin-boundaries.md" });
+ expect(writes[0]?.contents).toContain("Wiki-specific code lives in the standalone plugin package.");
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_operations"))).toBe(true);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("wiki_page_revisions"))).toBe(true);
+ expect(harness.dbExecutes.some((execute) => execute.sql.includes("filed_outputs"))).toBe(true);
+ });
+});
diff --git a/packages/plugins/plugin-llm-wiki/tests/screenshots/capture.mjs b/packages/plugins/plugin-llm-wiki/tests/screenshots/capture.mjs
new file mode 100644
index 0000000000..4378127abf
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/tests/screenshots/capture.mjs
@@ -0,0 +1,167 @@
+#!/usr/bin/env node
+import { mkdirSync, copyFileSync, existsSync, readFileSync } from "node:fs";
+import { dirname, resolve, extname } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import http from "node:http";
+import esbuild from "esbuild";
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const pkgRoot = resolve(__dirname, "..", "..");
+const outDir = resolve(pkgRoot, "dist", "screenshots");
+const screensDir = resolve(pkgRoot, "screenshots");
+
+mkdirSync(outDir, { recursive: true });
+mkdirSync(screensDir, { recursive: true });
+
+const entry = resolve(__dirname, "entry.tsx");
+
+const repoRoot = resolve(pkgRoot, "..", "..", "..");
+const reactPath = resolve(repoRoot, "node_modules/.pnpm/[email protected]/node_modules/react");
+const reactDomPath = resolve(repoRoot, "node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom");
+
+console.log("Bundling screenshot harness…");
+await esbuild.build({
+ entryPoints: [entry],
+ bundle: true,
+ format: "esm",
+ platform: "browser",
+ target: "es2022",
+ outfile: resolve(outDir, "bundle.js"),
+ jsx: "automatic",
+ loader: { ".tsx": "tsx", ".ts": "ts" },
+ define: { "process.env.NODE_ENV": '"production"' },
+ logLevel: "warning",
+ alias: {
+ "react": reactPath,
+ "react-dom": reactDomPath,
+ "react-dom/client": resolve(reactDomPath, "client.js"),
+ "react/jsx-runtime": resolve(reactPath, "jsx-runtime.js"),
+ },
+});
+
+copyFileSync(resolve(__dirname, "index.html"), resolve(outDir, "index.html"));
+
+const desktopViewport = { width: 1440, height: 920 };
+const mobileViewport = { width: 390, height: 844 };
+
+const desktopTargets = [
+ { slug: "01-wiki-browse", view: "wiki-sidebar", section: null },
+ { slug: "02-wiki-ingest", view: "wiki-sidebar", section: "ingest" },
+ { slug: "03-wiki-query", view: "wiki-sidebar", section: "query" },
+ { slug: "04-wiki-lint", view: "wiki-sidebar", section: "lint" },
+ { slug: "05-wiki-history", view: "wiki-sidebar", section: "history" },
+ { slug: "06-wiki-settings", view: "wiki-sidebar", section: "settings" },
+ { slug: "07-host-settings", view: "settings" },
+ { slug: "09-sidebar-link", view: "sidebar" },
+ { slug: "11-wiki-distillation-settings", view: "wiki-sidebar", section: "settings/distillation" },
+ { slug: "12-wiki-distillation-unconfigured", view: "wiki-sidebar", section: "settings/distillation", search: "unconfigured=1" },
+ { slug: "20-spaces-sidebar", view: "wiki-sidebar", section: null },
+ { slug: "21-spaces-ingest", view: "wiki-sidebar", section: "ingest" },
+ { slug: "21a-spaces-ingest-with-disclaimer", view: "wiki-sidebar", section: "ingest" },
+ { slug: "22-spaces-edit", view: "wiki-sidebar", section: "settings/spaces/team-research", scrollToText: "Paperclip ingestion" },
+ { slug: "22a-spaces-edit-default", view: "wiki-sidebar", section: "settings/spaces/default", scrollToText: "Paperclip ingestion" },
+ { slug: "23-spaces-non-default-route", view: "wiki-sidebar", section: "spaces/team-research" },
+ { slug: "24-spaces-create-modal", view: "wiki-sidebar", section: null, openCreateSpaceModal: true },
+];
+
+const mobileTargets = desktopTargets
+ .filter((target) => !target.openCreateSpaceModal)
+ .map((target) => ({
+ ...target,
+ slug: `mobile/${target.slug}`,
+ // In the production host, the route sidebar lives in the mobile drawer.
+ // The page body should therefore be checked without the desktop sidebar.
+ view: target.view === "wiki-sidebar" ? "wiki" : target.view,
+ viewport: mobileViewport,
+ }));
+
+const targets = [
+ ...desktopTargets.map((target) => ({ ...target, viewport: desktopViewport })),
+ ...mobileTargets,
+];
+
+const playwrightUrl = pathToFileURL(resolve(pkgRoot, "node_modules/playwright/index.mjs")).href;
+const playwrightFallback = resolve(pkgRoot, "..", "..", "..", "node_modules", ".pnpm", "[email protected]", "node_modules", "playwright", "index.mjs");
+let playwrightModuleHref = playwrightUrl;
+if (!existsSync(resolve(pkgRoot, "node_modules/playwright/index.mjs"))) {
+ if (existsSync(playwrightFallback)) {
+ playwrightModuleHref = pathToFileURL(playwrightFallback).href;
+ } else {
+ throw new Error("Cannot locate playwright module");
+ }
+}
+const { chromium } = await import(playwrightModuleHref);
+
+const mimeFor = (ext) => ({
+ ".html": "text/html; charset=utf-8",
+ ".js": "application/javascript; charset=utf-8",
+ ".mjs": "application/javascript; charset=utf-8",
+ ".css": "text/css; charset=utf-8",
+ ".map": "application/json; charset=utf-8",
+})[ext] ?? "application/octet-stream";
+
+const server = http.createServer((req, res) => {
+ const url = new URL(req.url ?? "/", "http://localhost");
+ const requestedPath = url.pathname === "/" ? "/index.html" : url.pathname;
+ const ext = extname(requestedPath);
+ const candidate = ext ? resolve(outDir, "." + requestedPath) : resolve(outDir, "./index.html");
+ try {
+ const body = readFileSync(candidate);
+ res.writeHead(200, { "Content-Type": mimeFor(extname(candidate)) });
+ res.end(body);
+ } catch {
+ res.writeHead(404);
+ res.end("Not found: " + candidate);
+ }
+});
+await new Promise((r) => server.listen(0, "127.0.0.1", r));
+const { port } = server.address();
+const baseUrl = `http://127.0.0.1:${port}`;
+
+const browser = await chromium.launch({ headless: true });
+const context = await browser.newContext({ viewport: desktopViewport, deviceScaleFactor: 2 });
+const page = await context.newPage();
+page.on("console", (msg) => console.log(` [console.${msg.type()}]`, msg.text()));
+page.on("pageerror", (err) => console.error(" [pageerror]", err.message));
+
+for (const target of targets) {
+ const sectionPath = target.section ? `/${target.section}` : "";
+ const search = target.search ? `?${target.search}` : "";
+ const url = `${baseUrl}/PAP/wiki${sectionPath}${search}#${target.view}`;
+ console.log(`→ rendering ${target.slug} (${url})`);
+ await page.setViewportSize(target.viewport);
+ await page.goto(url, { waitUntil: "networkidle" });
+ await page.waitForTimeout(200);
+ if (target.slug === "09-sidebar-link") {
+ await page.addStyleTag({ content: "body { background: var(--sidebar); }" });
+ }
+ if (target.openCreateSpaceModal) {
+ await page.evaluate(() => {
+ const btn = document.querySelector('button[aria-label="Create space"]');
+ if (!btn) throw new Error("Create space button not found in DOM");
+ (btn).click();
+ });
+ await page.waitForSelector('[aria-labelledby="create-space-modal-title"]', { timeout: 5000 });
+ await page.waitForTimeout(150);
+ }
+ if (target.scrollToText) {
+ await page.getByText(target.scrollToText).first().scrollIntoViewIfNeeded();
+ await page.waitForTimeout(100);
+ }
+ const outFile = resolve(screensDir, `${target.slug}.png`);
+ mkdirSync(dirname(outFile), { recursive: true });
+ await page.screenshot({ path: outFile, fullPage: false });
+ const horizontalOverflow = await page.evaluate(() => {
+ const rootOverflow = document.documentElement.scrollWidth - document.documentElement.clientWidth;
+ const bodyOverflow = document.body.scrollWidth - window.innerWidth;
+ return Math.max(rootOverflow, bodyOverflow);
+ });
+ if (horizontalOverflow > 1) {
+ throw new Error(`${target.slug} has ${horizontalOverflow}px horizontal overflow at ${target.viewport.width}px`);
+ }
+ console.log(` saved ${outFile}`);
+}
+
+await browser.close();
+server.close();
+console.log("Done. Screenshots in", screensDir);
diff --git a/packages/plugins/plugin-llm-wiki/tests/screenshots/entry.tsx b/packages/plugins/plugin-llm-wiki/tests/screenshots/entry.tsx
new file mode 100644
index 0000000000..55c66cf169
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/tests/screenshots/entry.tsx
@@ -0,0 +1,6 @@
+import { createRoot } from "react-dom/client";
+import { App } from "./harness.js";
+
+const container = document.getElementById("root");
+if (!container) throw new Error("No #root in harness host");
+createRoot(container).render(<App />);
diff --git a/packages/plugins/plugin-llm-wiki/tests/screenshots/harness.tsx b/packages/plugins/plugin-llm-wiki/tests/screenshots/harness.tsx
new file mode 100644
index 0000000000..6328950015
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/tests/screenshots/harness.tsx
@@ -0,0 +1,1061 @@
+import { useEffect, useState } from "react";
+import { SettingsPage, SidebarLink, WikiPage, WikiRouteSidebar } from "../../src/ui/index.js";
+import type {
+ FileTreeNode,
+ FileTreeBadge,
+ FileTreeProps,
+ IssuesListProps,
+} from "@paperclipai/plugin-sdk/ui";
+
+// ---------------------------------------------------------------------------
+// Bridge mocks. The real SDK runtime hooks read from a global registry; we
+// inline an alternate registry here so the plugin UI can render with canned
+// data inside a screenshot harness.
+// ---------------------------------------------------------------------------
+
+const NOW = "2026-05-01T20:30:00.000Z";
+
+const FOLDER_HEALTHY = {
+ folderKey: "wiki-root",
+ configured: true,
+ path: "/Users/operator/work/wiki/engineering",
+ realPath: "/Users/operator/work/wiki/engineering",
+ access: "readWrite" as const,
+ readable: true,
+ writable: true,
+ requiredDirectories: ["raw", "wiki", "wiki/sources", "wiki/projects", "wiki/entities", "wiki/concepts", "wiki/synthesis"],
+ requiredFiles: ["AGENTS.md", "IDEA.md", "wiki/index.md", "wiki/log.md"],
+ missingDirectories: [],
+ missingFiles: [],
+ healthy: true,
+ problems: [],
+ checkedAt: NOW,
+};
+
+const MANAGED_AGENT = {
+ status: "active",
+ agentId: "agt-c14a-7b2f-4e90",
+ resourceKey: "paperclipai.plugin-llm-wiki:agent:wiki-maintainer",
+ details: { name: "Wiki Maintainer", status: "active", adapterType: "claude_local", icon: "book-open", urlKey: "wiki-maintainer" },
+};
+
+const MANAGED_PROJECT = {
+ status: "active",
+ projectId: "prj-llmw-7e1a",
+ resourceKey: "paperclipai.plugin-llm-wiki:project:llm-wiki",
+ details: { name: "LLM Wiki Operations", status: "in_progress" },
+};
+
+const MANAGED_ROUTINE = {
+ status: "active",
+ routineId: "rtn-llmw-night",
+ resourceKey: "paperclipai.plugin-llm-wiki:routine:nightly-wiki-lint",
+ routine: {
+ id: "rtn-llmw-night",
+ title: "Run LLM Wiki lint",
+ status: "active",
+ cronExpression: "0 3 * * *",
+ enabled: true,
+ assigneeAgentId: "agt-c14a-7b2f-4e90",
+ projectId: "prj-llmw-7e1a",
+ nextRunAt: "2026-05-02T03:00:00Z",
+ lastRunAt: "2026-05-01T03:00:00Z",
+ },
+ details: {
+ title: "Run LLM Wiki lint",
+ status: "active",
+ cronExpression: "0 3 * * *",
+ enabled: true,
+ assigneeAgentId: "agt-c14a-7b2f-4e90",
+ nextRunAt: "2026-05-02T03:00:00Z",
+ lastRunAt: "2026-05-01T03:00:00Z",
+ },
+};
+
+const MANAGED_ROUTINES = [
+ {
+ status: "active",
+ routineId: "rtn-llmw-cursor",
+ resourceKey: "paperclipai.plugin-llm-wiki:routine:cursor-window-processing",
+ routine: {
+ id: "rtn-llmw-cursor",
+ title: "Process LLM Wiki updates",
+ status: "active",
+ cronExpression: "0 */6 * * *",
+ enabled: true,
+ assigneeAgentId: "agt-c14a-7b2f-4e90",
+ projectId: "prj-llmw-7e1a",
+ lastRunAt: "2026-05-01T18:00:00Z",
+ },
+ details: {
+ title: "Process LLM Wiki updates",
+ status: "active",
+ cronExpression: "0 */6 * * *",
+ enabled: true,
+ },
+ },
+ MANAGED_ROUTINE,
+ {
+ status: "active",
+ routineId: "rtn-llmw-index",
+ resourceKey: "paperclipai.plugin-llm-wiki:routine:index-refresh",
+ routine: {
+ id: "rtn-llmw-index",
+ title: "Refresh LLM Wiki index",
+ status: "active",
+ cronExpression: "0 * * * *",
+ enabled: true,
+ assigneeAgentId: "agt-c14a-7b2f-4e90",
+ projectId: "prj-llmw-7e1a",
+ lastRunAt: "2026-05-01T20:00:00Z",
+ },
+ details: {
+ title: "Refresh LLM Wiki index",
+ status: "active",
+ cronExpression: "0 * * * *",
+ enabled: true,
+ },
+ },
+];
+
+const MANAGED_SKILL = {
+ status: "resolved",
+ skillId: "skl-llmw-maintainer",
+ resourceKey: "wiki-maintainer",
+ details: {
+ name: "LLM Wiki Maintainer",
+ key: "plugin/paperclipai-plugin-llm-wiki/wiki-maintainer",
+ description: "Use the LLM Wiki plugin tools to maintain a cited local company wiki.",
+ },
+};
+const MANAGED_SKILLS = [
+ MANAGED_SKILL,
+ { status: "resolved", skillId: "skl-llmw-ingest", resourceKey: "wiki-ingest", details: { name: "Wiki Ingest", key: "plugin/paperclipai-plugin-llm-wiki/wiki-ingest", description: null } },
+ { status: "resolved", skillId: "skl-llmw-query", resourceKey: "wiki-query", details: { name: "Wiki Query", key: "plugin/paperclipai-plugin-llm-wiki/wiki-query", description: null } },
+ { status: "resolved", skillId: "skl-llmw-lint", resourceKey: "wiki-lint", details: { name: "Wiki Lint", key: "plugin/paperclipai-plugin-llm-wiki/wiki-lint", description: null } },
+ { status: "resolved", skillId: "skl-llmw-distill", resourceKey: "paperclip-distill", details: { name: "Paperclip Distill", key: "plugin/paperclipai-plugin-llm-wiki/paperclip-distill", description: null } },
+ { status: "resolved", skillId: "skl-llmw-index", resourceKey: "index-refresh", details: { name: "Index Refresh", key: "plugin/paperclipai-plugin-llm-wiki/index-refresh", description: null } },
+];
+
+const OVERVIEW = {
+ status: "ok",
+ checkedAt: NOW,
+ wikiId: "default",
+ folder: FOLDER_HEALTHY,
+ managedAgent: MANAGED_AGENT,
+ managedProject: MANAGED_PROJECT,
+ managedSkills: MANAGED_SKILLS,
+ operationCount: 128,
+ capabilities: [
+ "api.routes.register",
+ "issues.create",
+ "issues.read",
+ "agents.managed",
+ "projects.managed",
+ "routines.managed",
+ "agent.tools.register",
+ ],
+ prompts: {
+ query: "Answer from the LLM Wiki.\n\nRead wiki/index.md first, inspect relevant pages and raw/source references, cite the pages used, and say when the wiki does not contain enough evidence.",
+ lint: "Lint the LLM Wiki for contradictions, stale claims, orphan pages, missing backlinks, weak provenance, and wiki/index.md / wiki/log.md drift.",
+ },
+ eventIngestion: {
+ enabled: false,
+ sources: { issues: false, comments: false, documents: false },
+ wikiId: "default",
+ maxCharacters: 12000,
+ },
+};
+
+const SETTINGS = {
+ folder: FOLDER_HEALTHY,
+ managedAgent: MANAGED_AGENT,
+ managedProject: MANAGED_PROJECT,
+ managedRoutine: MANAGED_ROUTINE,
+ managedRoutines: MANAGED_ROUTINES,
+ managedSkills: MANAGED_SKILLS,
+ agentOptions: [{ id: "agt-c14a-7b2f-4e90", name: "Wiki Maintainer", status: "active", icon: "book-open", urlKey: "wiki-maintainer" }],
+ projectOptions: [],
+ eventIngestion: OVERVIEW.eventIngestion,
+ capabilities: OVERVIEW.capabilities,
+};
+
+const PAGES = {
+ pages: [
+ { path: "wiki/areas/control-plane.md", title: "Control plane", pageType: "areas", backlinkCount: 5, sourceCount: 2, contentHash: "a1b2c3d4", updatedAt: "2026-05-01T18:00:00Z" },
+ { path: "wiki/areas/plugin-runtime.md", title: "Plugin runtime", pageType: "areas", backlinkCount: 4, sourceCount: 2, contentHash: "b1b2c3d4", updatedAt: "2026-05-01T16:00:00Z" },
+ { path: "wiki/concepts/managed-resources.md", title: "Managed resources", pageType: "concepts", backlinkCount: 7, sourceCount: 2, contentHash: "c1b2c3d4", updatedAt: "2026-05-01T19:30:00Z" },
+ { path: "wiki/concepts/origin-kind.md", title: "Origin kind", pageType: "concepts", backlinkCount: 3, sourceCount: 1, contentHash: "d1b2c3d4", updatedAt: "2026-05-01T15:00:00Z" },
+ { path: "wiki/concepts/heartbeat.md", title: "Agent heartbeat", pageType: "concepts", backlinkCount: 2, sourceCount: 1, contentHash: "e1b2c3d4", updatedAt: "2026-04-30T10:00:00Z" },
+ { path: "wiki/projects/llm-wiki/standup.md", title: "LLM Wiki plugin Standup", pageType: "project-standup", backlinkCount: 1, sourceCount: 3, contentHash: "s1b2c3d4", updatedAt: "2026-05-01T20:00:00Z" },
+ { path: "wiki/projects/llm-wiki/index.md", title: "LLM Wiki plugin", pageType: "projects", backlinkCount: 6, sourceCount: 3, contentHash: "f1b2c3d4", updatedAt: "2026-05-01T17:30:00Z" },
+ { path: "wiki/sources/karpathy-llm-wiki.md", title: "Karpathy LLM Wiki gist (summary)", pageType: "sources", backlinkCount: 3, sourceCount: 1, contentHash: "g1b2c3d4", updatedAt: "2026-05-01T11:30:00Z" },
+ { path: "wiki/index.md", title: "LLM Wiki Index", pageType: "index", backlinkCount: 0, sourceCount: 0, contentHash: "h1b2c3d4", updatedAt: "2026-05-01T19:30:00Z" },
+ { path: "wiki/log.md", title: "LLM Wiki Log", pageType: "log", backlinkCount: 0, sourceCount: 0, contentHash: "i1b2c3d4", updatedAt: "2026-05-01T19:30:00Z" },
+ ],
+ sources: [
+ { rawPath: "raw/karpathy-llm-wiki.md", title: "Karpathy LLM Wiki gist", sourceType: "url", url: "https://gist.github.com/karpathy/.../llm-wiki", status: "captured", createdAt: "2026-05-01T19:00:00Z" },
+ { rawPath: "raw/paperclip-v1-spec.md", title: "Paperclip V1 spec", sourceType: "file", url: null, status: "captured", createdAt: "2026-05-01T18:30:00Z" },
+ { rawPath: "raw/design-doc-2026-04.md", title: "Design doc — April 2026", sourceType: "file", url: null, status: "captured", createdAt: "2026-04-28T14:00:00Z" },
+ ],
+};
+
+const PAGE_CONTENT = {
+ wikiId: "default",
+ path: "wiki/concepts/managed-resources.md",
+ contents: `# Managed Resources
+
+A **plugin-managed resource** is a normal Paperclip resource (agent, routine, project) that a plugin has seeded with suggested defaults. The plugin marks ownership via a stable \`resourceKey\` so that installs, imports, and upgrades can find the resource even when UUIDs differ.
+
+The host treats managed resources as fully editable. The operator can rename, change adapter config, edit instructions, change schedule, etc. The plugin can offer a *reset to plugin defaults* action that re-applies the suggested values.
+
+## Why it matters
+
+- Stable references survive dev resets and re-imports.
+- Plugin upgrades don't clobber operator edits.
+- Operations remain inspectable through native Agents / Routines / Projects pages.
+`,
+ title: "Managed Resources",
+ pageType: "concepts",
+ backlinks: ["wiki/areas/plugin-runtime.md", "wiki/concepts/origin-kind.md", "wiki/projects/llm-wiki/index.md"],
+ sourceRefs: ["raw/karpathy-llm-wiki.md", "raw/paperclip-v1-spec.md"],
+ updatedAt: "2026-05-01T19:30:00Z",
+ hash: "deadbeefcafe1234",
+};
+
+const OPERATIONS = {
+ operations: [
+ { id: "2944aaaaaaaa", operationType: "ingest", status: "running", hiddenIssueId: "ii-2944", hiddenIssueIdentifier: "PAP-OP-2944", hiddenIssueTitle: "Ingest URL: karpathy/llm-wiki gist", hiddenIssueStatus: "in_progress", projectId: "prj-llmw-7e1a", costCents: 1, warnings: [], affectedPages: [], createdAt: "2026-05-01T20:29:48Z", updatedAt: "2026-05-01T20:29:48Z" },
+ { id: "2943bbbbbbbb", operationType: "query", status: "done", hiddenIssueId: "ii-2943", hiddenIssueIdentifier: "PAP-OP-2943", hiddenIssueTitle: "How do plugin-managed routines resolve their default agent…", hiddenIssueStatus: "done", projectId: "prj-llmw-7e1a", costCents: 1, warnings: [], affectedPages: [], createdAt: "2026-05-01T20:25:00Z", updatedAt: "2026-05-01T20:26:30Z" },
+ { id: "2942cccccccc", operationType: "file-as-page", status: "done", hiddenIssueId: "ii-2942", hiddenIssueIdentifier: "PAP-OP-2942", hiddenIssueTitle: "File answer as concepts/routine-agent-resolution.md", hiddenIssueStatus: "done", projectId: "prj-llmw-7e1a", costCents: 0, warnings: [], affectedPages: [{ path: "wiki/concepts/routine-agent-resolution.md" }], createdAt: "2026-05-01T20:25:30Z", updatedAt: "2026-05-01T20:25:35Z" },
+ { id: "2941dddddddd", operationType: "query", status: "done", hiddenIssueId: "ii-2941", hiddenIssueIdentifier: "PAP-OP-2941", hiddenIssueTitle: "Compare managed agent reset vs detach…", hiddenIssueStatus: "done", projectId: "prj-llmw-7e1a", costCents: 1, warnings: [], affectedPages: [], createdAt: "2026-05-01T20:18:00Z", updatedAt: "2026-05-01T20:18:30Z" },
+ { id: "2940eeeeeeee", operationType: "lint", status: "done", hiddenIssueId: "ii-2940", hiddenIssueIdentifier: "PAP-OP-2940", hiddenIssueTitle: "Nightly wiki lint · 17 findings (2 critical)", hiddenIssueStatus: "done", projectId: "prj-llmw-7e1a", costCents: 4, warnings: [
+ { severity: "critical", message: "Contradiction: managed-resources.md vs raw/karpathy-llm-wiki.md (run-time vs install-time resolution)", path: "wiki/concepts/managed-resources.md" },
+ { severity: "critical", message: "Conflicting claim about plugin manifest version", path: "wiki/concepts/origin-kind.md" },
+ { severity: "orphan", message: "people/aaron-norvig.md has no inbound backlinks", path: "wiki/people/aaron-norvig.md" },
+ { severity: "orphan", message: "concepts/sandboxing.md is referenced from raw/ only", path: "wiki/concepts/sandboxing.md" },
+ { severity: "stale", message: "areas/control-plane.md last source observed 41d ago", path: "wiki/areas/control-plane.md" },
+ { severity: "backlink", message: "Missing reverse links: managed-resources.md -> wiki/projects/llm-wiki/index.md" },
+ { severity: "index", message: "index.md does not list 5 pages created in last 24h" },
+ ], affectedPages: [], createdAt: "2026-05-01T18:00:00Z", updatedAt: "2026-05-01T18:02:30Z" },
+ { id: "2939ffffffff", operationType: "ingest", status: "done", hiddenIssueId: "ii-2939", hiddenIssueIdentifier: "PAP-OP-2939", hiddenIssueTitle: "paperclip-v1-spec.md · 3 pages created", hiddenIssueStatus: "done", projectId: "prj-llmw-7e1a", costCents: 2, warnings: [], affectedPages: [{ path: "wiki/areas/control-plane.md" }, { path: "wiki/concepts/managed-resources.md" }, { path: "wiki/concepts/origin-kind.md" }], createdAt: "2026-05-01T18:30:00Z", updatedAt: "2026-05-01T18:32:00Z" },
+ { id: "2934gggggggg", operationType: "ingest", status: "failed", hiddenIssueId: "ii-2934", hiddenIssueIdentifier: "PAP-OP-2934", hiddenIssueTitle: "Internal wiki dump (PDF) · outbound URL not on allowlist", hiddenIssueStatus: "blocked", projectId: "prj-llmw-7e1a", costCents: 0, warnings: [{ message: "outbound URL not on allowlist" }], affectedPages: [], createdAt: "2026-05-01T16:00:00Z", updatedAt: "2026-05-01T16:00:30Z" },
+ ],
+};
+
+const TEMPLATE_IDEA = {
+ path: "IDEA.md",
+ exists: true,
+ hash: "abc123",
+ contents: `# LLM Wiki
+
+A pattern for building personal knowledge bases using LLMs.
+`,
+};
+
+const TEMPLATE_AGENTS = {
+ path: "AGENTS.md",
+ exists: true,
+ hash: "def456",
+ contents: `# LLM Wiki Maintainer
+
+You maintain this wiki through Paperclip plugin tools.
+
+Before answering or editing:
+
+1. Read AGENTS.md.
+2. Read wiki/index.md.
+3. Cite raw sources or source pages for factual claims.
+4. Use proposed patches for substantial rewrites.
+5. Append a short note to wiki/log.md for maintenance changes.
+`,
+};
+
+const HOST_CONTEXT = {
+ companyId: "company-demo",
+ companyPrefix: "PAP",
+ projectId: null,
+ entityId: null,
+ entityType: null,
+ userId: "user-demo",
+ parentEntityId: null,
+};
+
+function fakeData<T>(value: T) {
+ return { data: value, loading: false, error: null, refresh: () => undefined };
+}
+
+const DISTILLATION_CURSOR = {
+ id: "cur-control-plane-1",
+ sourceScope: "project",
+ scopeKey: "prj-control-plane",
+ projectId: "prj-control-plane",
+ projectName: "Control plane",
+ projectColor: "#2563eb",
+ rootIssueId: null,
+ rootIssueIdentifier: null,
+ rootIssueTitle: null,
+ lastProcessedAt: "2026-05-04T15:00:00Z",
+ lastObservedAt: "2026-05-04T18:55:00Z",
+ pendingEventCount: 4,
+ lastSourceHash: "7f3a92041b210def",
+ lastSuccessfulRunId: "run-1",
+};
+
+const DISTILLATION_RUNS = [
+ {
+ id: "run-1",
+ cursorId: "cur-control-plane-1",
+ workItemId: null,
+ projectId: "prj-control-plane",
+ projectName: "Control plane",
+ rootIssueId: null,
+ rootIssueIdentifier: null,
+ sourceWindowStart: "2026-04-30T14:22:00Z",
+ sourceWindowEnd: "2026-05-04T15:01:00Z",
+ sourceHash: "7f3a92041b210def",
+ status: "succeeded",
+ costCents: 12,
+ retryCount: 0,
+ warnings: [],
+ metadata: {},
+ operationIssueId: "ii-op-3201",
+ operationIssueIdentifier: "PAP-OP-3201",
+ operationIssueTitle: "LLM Wiki distillation · Control plane",
+ affectedPagePaths: ["wiki/projects/control-plane/index.md"],
+ createdAt: "2026-05-04T15:01:00Z",
+ updatedAt: "2026-05-04T15:02:14Z",
+ },
+ {
+ id: "run-2",
+ cursorId: "cur-billing-1",
+ workItemId: null,
+ projectId: "prj-billing",
+ projectName: "Billing",
+ rootIssueId: null,
+ rootIssueIdentifier: null,
+ sourceWindowStart: "2026-05-03T08:00:00Z",
+ sourceWindowEnd: "2026-05-04T18:55:00Z",
+ sourceHash: "92d44102be7c08aa",
+ status: "review_required",
+ costCents: 8,
+ retryCount: 0,
+ warnings: ["Touches the Decisions section. Auto-apply policy is 'Status sections only'."],
+ metadata: {},
+ operationIssueId: "ii-op-3204",
+ operationIssueIdentifier: "PAP-OP-3204",
+ operationIssueTitle: "LLM Wiki distillation · Billing",
+ affectedPagePaths: ["wiki/projects/billing/index.md", "wiki/projects/billing/decisions.md"],
+ createdAt: "2026-05-04T18:55:00Z",
+ updatedAt: "2026-05-04T18:56:14Z",
+ },
+ {
+ id: "run-3",
+ cursorId: "cur-routines-1",
+ workItemId: null,
+ projectId: "prj-routines",
+ projectName: "Routine engine",
+ rootIssueId: null,
+ rootIssueIdentifier: null,
+ sourceWindowStart: "2026-05-04T11:00:00Z",
+ sourceWindowEnd: "2026-05-04T18:00:00Z",
+ sourceHash: "ab12dde98c3f0001",
+ status: "running",
+ costCents: 4,
+ retryCount: 0,
+ warnings: [],
+ metadata: {},
+ operationIssueId: "ii-op-3205",
+ operationIssueIdentifier: "PAP-OP-3205",
+ operationIssueTitle: "LLM Wiki distillation · Routine engine",
+ affectedPagePaths: [],
+ createdAt: "2026-05-04T18:58:00Z",
+ updatedAt: "2026-05-04T18:58:00Z",
+ },
+ {
+ id: "run-4",
+ cursorId: "cur-export-1",
+ workItemId: null,
+ projectId: "prj-exports",
+ projectName: "Exports",
+ rootIssueId: null,
+ rootIssueIdentifier: null,
+ sourceWindowStart: "2026-05-03T20:00:00Z",
+ sourceWindowEnd: "2026-05-04T03:00:00Z",
+ sourceHash: "ee01acd482211110",
+ status: "failed",
+ costCents: 0,
+ retryCount: 1,
+ warnings: ["model error: 429", "Source bundle clipped: 6 issues over 48k chars."],
+ metadata: {},
+ operationIssueId: "ii-op-3198",
+ operationIssueIdentifier: "PAP-OP-3198",
+ operationIssueTitle: "LLM Wiki distillation · Exports",
+ affectedPagePaths: [],
+ createdAt: "2026-05-04T03:01:00Z",
+ updatedAt: "2026-05-04T03:01:30Z",
+ },
+];
+
+const DISTILLATION_PAGE_BINDINGS = [
+ {
+ id: "bind-control-plane",
+ pagePath: "wiki/projects/control-plane/index.md",
+ projectId: "prj-control-plane",
+ projectName: "Control plane",
+ rootIssueId: null,
+ lastAppliedSourceHash: "7f3a92041b210def",
+ lastDistillationRunId: "run-1",
+ lastRunStatus: "succeeded",
+ lastRunCompletedAt: "2026-05-04T15:02:14Z",
+ lastRunSourceWindowEnd: "2026-05-04T15:01:00Z",
+ lastRunSourceHash: "7f3a92041b210def",
+ metadata: { sourceRefs: [{ id: "PAP-3416", kind: "issue", title: "Distillation kickoff" }, { id: "PAP-3416#c1", kind: "comment", title: "Comment" }] },
+ updatedAt: "2026-05-04T15:02:14Z",
+ },
+ {
+ id: "bind-billing",
+ pagePath: "wiki/projects/billing/index.md",
+ projectId: "prj-billing",
+ projectName: "Billing",
+ rootIssueId: null,
+ lastAppliedSourceHash: "11abf991a081ddff",
+ lastDistillationRunId: "run-2",
+ lastRunStatus: "review_required",
+ lastRunCompletedAt: "2026-05-04T18:56:14Z",
+ lastRunSourceWindowEnd: "2026-05-04T18:55:00Z",
+ lastRunSourceHash: "92d44102be7c08aa",
+ metadata: {},
+ updatedAt: "2026-05-04T18:56:14Z",
+ },
+];
+
+const DISTILLATION_OVERVIEW = {
+ cursors: [
+ DISTILLATION_CURSOR,
+ {
+ ...DISTILLATION_CURSOR,
+ id: "cur-billing-1",
+ scopeKey: "prj-billing",
+ projectId: "prj-billing",
+ projectName: "Billing",
+ lastProcessedAt: "2026-05-04T18:55:00Z",
+ lastObservedAt: "2026-05-04T18:55:00Z",
+ pendingEventCount: 0,
+ lastSuccessfulRunId: "run-2",
+ },
+ {
+ ...DISTILLATION_CURSOR,
+ id: "cur-routines-1",
+ scopeKey: "prj-routines",
+ projectId: "prj-routines",
+ projectName: "Routine engine",
+ lastProcessedAt: null,
+ lastObservedAt: "2026-05-04T18:00:00Z",
+ pendingEventCount: 11,
+ lastSuccessfulRunId: null,
+ },
+ ],
+ runs: DISTILLATION_RUNS,
+ workItems: [
+ { id: "wi-1", workItemKind: "review", status: "review_required", priority: "high", projectId: "prj-billing", rootIssueId: null, metadata: {}, createdAt: "2026-05-04T18:56:00Z", updatedAt: "2026-05-04T18:56:00Z" },
+ ],
+ pageBindings: DISTILLATION_PAGE_BINDINGS,
+ reviewWorkItems: [
+ { id: "wi-1", workItemKind: "review", status: "review_required", priority: "high", projectId: "prj-billing", rootIssueId: null, metadata: {}, createdAt: "2026-05-04T18:56:00Z", updatedAt: "2026-05-04T18:56:00Z" },
+ ],
+ counts: { cursors: 3, runningRuns: 1, failedRuns24h: 1, reviewRequired: 1 },
+};
+
+const DISTILLATION_OVERVIEW_UNCONFIGURED = {
+ cursors: [],
+ runs: [],
+ workItems: [],
+ pageBindings: [],
+ reviewWorkItems: [],
+ counts: { cursors: 0, runningRuns: 0, failedRuns24h: 0, reviewRequired: 0 },
+};
+
+const DISTILLATION_PROVENANCE = {
+ binding: DISTILLATION_PAGE_BINDINGS[0],
+ runs: [DISTILLATION_RUNS[0]],
+ snapshot: {
+ id: "snap-1",
+ distillationRunId: "run-1",
+ sourceHash: "7f3a92041b210def",
+ maxCharacters: 48000,
+ clipped: false,
+ sourceRefs: [
+ { id: "PAP-3416", kind: "issue", title: "How should we distill?" },
+ { id: "PAP-3416#c1", kind: "comment", title: "Approach: cursors" },
+ { id: "PAP-3416#doc:plan", kind: "document", title: "Plan v3" },
+ ],
+ metadata: { issueCount: 12, commentCount: 8, documentCount: 4 },
+ createdAt: "2026-05-04T15:01:00Z",
+ },
+ cursor: DISTILLATION_CURSOR,
+};
+
+const SPACES = {
+ spaces: [
+ {
+ id: "space-default",
+ companyId: HOST_CONTEXT.companyId,
+ wikiId: "default",
+ slug: "default",
+ displayName: "default",
+ spaceType: "managed",
+ folderMode: "managed_subfolder",
+ rootFolderKey: "wiki-root",
+ pathPrefix: null,
+ configuredRootPath: null,
+ accessScope: "shared",
+ ownerUserId: null,
+ ownerAgentId: null,
+ teamKey: null,
+ settings: {},
+ status: "active",
+ createdAt: "2026-04-12T08:00:00Z",
+ updatedAt: "2026-05-01T12:00:00Z",
+ },
+ {
+ id: "space-team-research",
+ companyId: HOST_CONTEXT.companyId,
+ wikiId: "default",
+ slug: "team-research",
+ displayName: "team-research",
+ spaceType: "managed",
+ folderMode: "managed_subfolder",
+ rootFolderKey: "wiki-root",
+ pathPrefix: "spaces/team-research",
+ configuredRootPath: null,
+ accessScope: "shared",
+ ownerUserId: null,
+ ownerAgentId: null,
+ teamKey: null,
+ settings: {},
+ status: "active",
+ createdAt: "2026-04-22T08:00:00Z",
+ updatedAt: "2026-05-01T11:00:00Z",
+ },
+ {
+ id: "space-customer-feedback",
+ companyId: HOST_CONTEXT.companyId,
+ wikiId: "default",
+ slug: "customer-feedback",
+ displayName: "customer-feedback",
+ spaceType: "managed",
+ folderMode: "managed_subfolder",
+ rootFolderKey: "wiki-root",
+ pathPrefix: "spaces/customer-feedback",
+ configuredRootPath: null,
+ accessScope: "shared",
+ ownerUserId: null,
+ ownerAgentId: null,
+ teamKey: null,
+ settings: {},
+ status: "active",
+ createdAt: "2026-04-25T08:00:00Z",
+ updatedAt: "2026-05-01T10:00:00Z",
+ },
+ ],
+};
+
+function dataResolver(key: string, params?: Record<string, unknown>) {
+ if (key === "overview") return fakeData(OVERVIEW);
+ if (key === "settings") return fakeData(SETTINGS);
+ if (key === "spaces") return fakeData(SPACES);
+ if (key === "space") {
+ const slug = typeof params?.spaceSlug === "string" ? params.spaceSlug : "default";
+ const space = SPACES.spaces.find((s) => s.slug === slug) ?? SPACES.spaces[0];
+ return fakeData({
+ ...space,
+ relativeRoot: space.pathPrefix ?? "",
+ folder: FOLDER_HEALTHY,
+ });
+ }
+ if (key === "pages") return fakeData(PAGES);
+ if (key === "page-content") return fakeData(PAGE_CONTENT);
+ if (key === "operations") {
+ const opType = typeof params?.operationType === "string" ? params.operationType : null;
+ const filtered = opType && opType !== "all"
+ ? OPERATIONS.operations.filter((op) => op.operationType === opType)
+ : OPERATIONS.operations;
+ return fakeData({ operations: filtered });
+ }
+ if (key === "distillation-overview") {
+ const flag = typeof window !== "undefined" ? window.location.search.includes("unconfigured=1") : false;
+ return fakeData(flag ? DISTILLATION_OVERVIEW_UNCONFIGURED : DISTILLATION_OVERVIEW);
+ }
+ if (key === "distillation-page-provenance") {
+ return fakeData(DISTILLATION_PROVENANCE);
+ }
+ if (key === "template" && params?.path === "IDEA.md") return fakeData(TEMPLATE_IDEA);
+ if (key === "template" && params?.path === "AGENTS.md") return fakeData(TEMPLATE_AGENTS);
+ return { data: null, loading: false, error: null, refresh: () => undefined };
+}
+
+function MockFileTree(props: FileTreeProps) {
+ const expanded = new Set(props.expandedPaths ?? []);
+ const badges = props.fileBadges ?? {};
+ const renderNodes = (nodes: FileTreeNode[], depth: number) => (
+ <ul style={{ listStyle: "none", margin: 0, padding: 0 }}>
+ {nodes.map((node) => {
+ const isExpanded = node.kind === "dir" && expanded.has(node.path);
+ const isSelected = node.kind === "file" && node.path === props.selectedFile;
+ const badge = badges[node.path] as FileTreeBadge | undefined;
+ return (
+ <li key={node.path}>
+ <button
+ type="button"
+ onClick={() => {
+ if (node.kind === "dir") props.onToggleDir?.(node.path);
+ else props.onSelectFile?.(node.path);
+ }}
+ style={{
+ display: "flex",
+ alignItems: "center",
+ gap: 6,
+ width: "100%",
+ border: "none",
+ background: isSelected ? "var(--accent, oklch(0.269 0 0))" : "transparent",
+ color: "var(--foreground, oklch(0.985 0 0))",
+ fontSize: 12,
+ textAlign: "left",
+ padding: `4px 8px 4px ${depth * 16 + 12}px`,
+ cursor: "pointer",
+ borderRadius: 4,
+ fontFamily: "ui-sans-serif, system-ui, -apple-system, sans-serif",
+ }}
+ aria-expanded={node.kind === "dir" ? isExpanded : undefined}
+ aria-selected={isSelected || undefined}
+ >
+ <span style={{ width: 12, color: "var(--muted-foreground, oklch(0.708 0 0))" }} aria-hidden>
+ {node.kind === "dir" ? (isExpanded ? "▾" : "▸") : ""}
+ </span>
+ <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
+ {node.kind === "dir" ? `📁 ${node.name}` : node.name}
+ </span>
+ {badge ? (
+ <span
+ style={{
+ fontSize: 10,
+ padding: "1px 6px",
+ borderRadius: 999,
+ background: "color-mix(in oklab, var(--accent, oklch(0.4 0.04 250)) 50%, transparent)",
+ color: "var(--foreground, oklch(0.985 0 0))",
+ textTransform: "uppercase",
+ letterSpacing: "0.04em",
+ }}
+ title={badge.tooltip}
+ >
+ {badge.label}
+ </span>
+ ) : null}
+ </button>
+ {node.kind === "dir" && isExpanded ? renderNodes(node.children, depth + 1) : null}
+ </li>
+ );
+ })}
+ </ul>
+ );
+
+ if (props.loading) {
+ return <div style={{ padding: 12, fontSize: 12, color: "var(--muted-foreground, oklch(0.708 0 0))" }}>Loading…</div>;
+ }
+ if (props.error) {
+ return <div style={{ padding: 12, fontSize: 12, color: "var(--destructive, oklch(0.7 0.2 25))" }}>{props.error.message}</div>;
+ }
+ if (props.nodes.length === 0) {
+ return (
+ <div style={{ padding: 16, fontSize: 12, color: "var(--muted-foreground, oklch(0.708 0 0))" }}>
+ <div style={{ fontWeight: 600, color: "var(--foreground, oklch(0.985 0 0))" }}>{props.empty?.title ?? "No files"}</div>
+ <div>{props.empty?.description ?? "Nothing to show."}</div>
+ </div>
+ );
+ }
+ return <div role="tree" aria-label={props.ariaLabel ?? "Files"}>{renderNodes(props.nodes, 0)}</div>;
+}
+
+function MockIssuesList(props: IssuesListProps) {
+ const isNarrow = typeof window !== "undefined" && window.innerWidth < 700;
+ const rows = OPERATIONS.operations.map((op) => ({
+ id: op.hiddenIssueId ?? op.id,
+ identifier: op.hiddenIssueIdentifier ?? `op-${op.id.slice(0, 6)}`,
+ title: op.hiddenIssueTitle ?? `LLM Wiki ${op.operationType}`,
+ status: op.hiddenIssueStatus ?? op.status,
+ priority: op.operationType === "query" ? "medium" : "low",
+ updatedAt: op.updatedAt,
+ operationType: op.operationType,
+ }));
+ return (
+ <div style={{ display: "grid", gap: 10, padding: 18, fontFamily: "ui-sans-serif, system-ui, -apple-system, sans-serif" }}>
+ <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
+ <strong style={{ fontSize: 14 }}>Issues</strong>
+ <span style={{ fontSize: 11, color: "var(--muted-foreground, oklch(0.708 0 0))" }}>
+ {rows.length} loaded · {props.filters?.originKindPrefix ?? props.projectId ?? "all"}
+ </span>
+ </div>
+ <div style={{ border: "1px solid var(--border, oklch(0.269 0 0))", borderRadius: 8, overflow: "hidden", background: "var(--card, oklch(0.205 0 0))" }}>
+ {rows.map((issue) => (
+ <div
+ key={issue.id}
+ style={{
+ display: "grid",
+ gridTemplateColumns: isNarrow ? "minmax(0, 1fr) auto" : "110px minmax(0, 1fr) 110px 90px",
+ gap: isNarrow ? "6px 10px" : 12,
+ alignItems: "center",
+ padding: "10px 12px",
+ borderBottom: "1px solid var(--border, oklch(0.269 0 0))",
+ fontSize: 13,
+ }}
+ >
+ <span style={{ fontFamily: "ui-monospace, SFMono-Regular, monospace", fontSize: 12, color: "var(--muted-foreground, oklch(0.708 0 0))" }}>{issue.identifier}</span>
+ {isNarrow ? null : <span style={{ minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{issue.title}</span>}
+ {isNarrow ? null : <span style={{ fontSize: 11, color: "var(--muted-foreground, oklch(0.708 0 0))" }}>{issue.operationType}</span>}
+ <span style={{ justifySelf: "end", maxWidth: "100%", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontSize: 11, border: "1px solid var(--border, oklch(0.269 0 0))", borderRadius: 999, padding: "2px 8px" }}>{issue.status}</span>
+ {isNarrow ? (
+ <span style={{ gridColumn: "1 / -1", minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{issue.title}</span>
+ ) : null}
+ {isNarrow ? (
+ <span style={{ gridColumn: "1 / -1", fontSize: 11, color: "var(--muted-foreground, oklch(0.708 0 0))" }}>{issue.operationType}</span>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+function MockMarkdownBlock({ content, className }: { content: string; className?: string }) {
+ return (
+ <div
+ className={className}
+ style={{ whiteSpace: "pre-wrap", fontSize: 13, lineHeight: 1.65 }}
+ >
+ {content}
+ </div>
+ );
+}
+
+function MockMarkdownEditor({
+ value,
+ onChange,
+ placeholder,
+ className,
+}: {
+ value: string;
+ onChange: (value: string) => void;
+ placeholder?: string;
+ className?: string;
+}) {
+ return (
+ <textarea
+ className={className}
+ value={value}
+ placeholder={placeholder}
+ onChange={(event) => onChange(event.currentTarget.value)}
+ style={{
+ width: "100%",
+ minHeight: 260,
+ boxSizing: "border-box",
+ border: "1px solid var(--border, oklch(0.269 0 0))",
+ borderRadius: 8,
+ background: "var(--card, oklch(0.205 0 0))",
+ color: "var(--foreground, oklch(0.985 0 0))",
+ padding: 12,
+ font: "13px ui-sans-serif, system-ui, -apple-system, sans-serif",
+ }}
+ />
+ );
+}
+
+function MockAssigneePicker({
+ value,
+ placeholder,
+ onChange,
+}: {
+ value: string;
+ placeholder?: string;
+ onChange: (value: string, selection: { assigneeAgentId: string | null; assigneeUserId: string | null }) => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={() => onChange("agent:agt-c14a-7b2f-4e90", { assigneeAgentId: "agt-c14a-7b2f-4e90", assigneeUserId: null })}
+ style={{
+ width: "100%",
+ minHeight: 44,
+ border: "1px solid var(--border, oklch(0.269 0 0))",
+ borderRadius: 8,
+ background: "var(--card, oklch(0.205 0 0))",
+ color: "var(--foreground, oklch(0.985 0 0))",
+ padding: "8px 12px",
+ textAlign: "left",
+ font: "13px ui-sans-serif, system-ui, -apple-system, sans-serif",
+ }}
+ >
+ {value ? "Wiki Maintainer" : (placeholder ?? "Select maintainer")}
+ </button>
+ );
+}
+
+type MockManagedRoutinesListProps = {
+ routines: Array<{
+ key: string;
+ title: string;
+ status: string;
+ cronExpression?: string | null;
+ lastRunAt?: string | Date | null;
+ lastRunStatus?: string | null;
+ href?: string | null;
+ managedByPluginDisplayName?: string | null;
+ missingRefs?: Array<{ resourceKind: string; resourceKey: string }>;
+ defaultDrift?: { changedFields: string[] } | null;
+ }>;
+ agents?: Array<{ id: string; name: string }>;
+ projects?: Array<{ id: string; name: string }>;
+ pluginDisplayName?: string | null;
+ runningRoutineKey?: string | null;
+ statusMutationRoutineKey?: string | null;
+ resettingRoutineKey?: string | null;
+ onRunNow?: (routine: { key: string }) => void;
+ onToggleEnabled?: (routine: { key: string }, enabled: boolean) => void;
+ onReset?: (routine: { key: string }) => void;
+};
+
+function MockManagedRoutinesList(props: MockManagedRoutinesListProps) {
+ if (props.routines.length === 0) {
+ return (
+ <div style={{ padding: 16, fontSize: 12, color: "var(--muted-foreground, oklch(0.708 0 0))" }}>
+ No managed routines.
+ </div>
+ );
+ }
+ return (
+ <div
+ style={{
+ display: "grid",
+ gap: 0,
+ border: "1px solid var(--border, oklch(0.269 0 0))",
+ borderRadius: 8,
+ overflow: "hidden",
+ background: "var(--card, oklch(0.205 0 0))",
+ fontFamily: "ui-sans-serif, system-ui, -apple-system, sans-serif",
+ }}
+ >
+ {props.routines.map((routine, index) => (
+ <div
+ key={routine.key}
+ style={{
+ display: "grid",
+ gridTemplateColumns: "minmax(0, 1fr) 110px 110px",
+ gap: 12,
+ alignItems: "center",
+ padding: "10px 14px",
+ borderTop: index === 0 ? "none" : "1px solid var(--border, oklch(0.269 0 0))",
+ fontSize: 13,
+ }}
+ >
+ <div style={{ display: "grid", gap: 2, minWidth: 0 }}>
+ <span style={{ fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
+ {routine.title}
+ </span>
+ <span
+ style={{
+ fontSize: 11,
+ color: "var(--muted-foreground, oklch(0.708 0 0))",
+ fontFamily: "ui-monospace, SFMono-Regular, monospace",
+ }}
+ >
+ {routine.cronExpression ?? "—"}
+ </span>
+ </div>
+ <span
+ style={{
+ justifySelf: "start",
+ fontSize: 11,
+ border: "1px solid var(--border, oklch(0.269 0 0))",
+ borderRadius: 999,
+ padding: "2px 8px",
+ }}
+ >
+ {routine.status}
+ </span>
+ <div style={{ justifySelf: "end", display: "flex", gap: 6 }}>
+ <button
+ type="button"
+ style={{
+ fontSize: 11,
+ padding: "4px 8px",
+ borderRadius: 6,
+ border: "1px solid var(--border, oklch(0.269 0 0))",
+ background: "transparent",
+ color: "var(--foreground, oklch(0.985 0 0))",
+ cursor: "pointer",
+ }}
+ onClick={() => props.onRunNow?.({ key: routine.key })}
+ >
+ Run now
+ </button>
+ <button
+ type="button"
+ style={{
+ fontSize: 11,
+ padding: "4px 8px",
+ borderRadius: 6,
+ border: "1px solid var(--border, oklch(0.269 0 0))",
+ background: "transparent",
+ color: "var(--foreground, oklch(0.985 0 0))",
+ cursor: "pointer",
+ }}
+ onClick={() => props.onReset?.({ key: routine.key })}
+ >
+ Reset
+ </button>
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function MockProjectPicker({
+ value,
+ placeholder,
+ onChange,
+}: {
+ value: string;
+ placeholder?: string;
+ onChange: (projectId: string) => void;
+}) {
+ return (
+ <button
+ type="button"
+ onClick={() => onChange("prj-llmw-7e1a")}
+ style={{
+ width: "100%",
+ minHeight: 44,
+ border: "1px solid var(--border, oklch(0.269 0 0))",
+ borderRadius: 8,
+ background: "var(--card, oklch(0.205 0 0))",
+ color: "var(--foreground, oklch(0.985 0 0))",
+ padding: "8px 12px",
+ textAlign: "left",
+ font: "13px ui-sans-serif, system-ui, -apple-system, sans-serif",
+ }}
+ >
+ {value ? "LLM Wiki Operations" : (placeholder ?? "Project")}
+ </button>
+ );
+}
+
+// Captured at module load so we can flip it before render and trigger
+// re-renders via popstate when the hash/search changes.
+function readHostLocation() {
+ if (typeof window === "undefined") {
+ return { pathname: "/PAP/wiki", search: "", hash: "" };
+ }
+ return { pathname: window.location.pathname, search: window.location.search, hash: window.location.hash };
+}
+
+const hostLocationListeners = new Set<() => void>();
+
+function useHostLocationMock() {
+ const [snapshot, setSnapshot] = useState(readHostLocation);
+ useEffect(() => {
+ const update = () => setSnapshot(readHostLocation());
+ window.addEventListener("popstate", update);
+ window.addEventListener("hashchange", update);
+ hostLocationListeners.add(update);
+ return () => {
+ window.removeEventListener("popstate", update);
+ window.removeEventListener("hashchange", update);
+ hostLocationListeners.delete(update);
+ };
+ }, []);
+ return snapshot;
+}
+
+const sdkUi: Record<string, unknown> = {
+ usePluginData: dataResolver,
+ usePluginAction: () => async () => ({ status: "ok" }),
+ usePluginStream: () => ({ events: [], lastEvent: null, connecting: false, connected: false, error: null, close: () => undefined }),
+ usePluginToast: () => () => null,
+ useHostContext: () => HOST_CONTEXT,
+ useHostNavigation: () => ({
+ resolveHref: (to: string) => `/PAP${to.startsWith("/") ? to : `/${to}`}`,
+ navigate: (to: string) => {
+ const href = `/PAP${to.startsWith("/") ? to : `/${to}`}`;
+ window.history.pushState({}, "", href);
+ hostLocationListeners.forEach((fn) => fn());
+ },
+ linkProps: (to: string) => ({
+ href: `/PAP${to.startsWith("/") ? to : `/${to}`}`,
+ onClick: (event: { preventDefault: () => void }) => {
+ event.preventDefault();
+ const href = `/PAP${to.startsWith("/") ? to : `/${to}`}`;
+ window.history.pushState({}, "", href);
+ hostLocationListeners.forEach((fn) => fn());
+ },
+ }),
+ }),
+ useHostLocation: useHostLocationMock,
+ MarkdownBlock: MockMarkdownBlock,
+ MarkdownEditor: MockMarkdownEditor,
+ FileTree: MockFileTree,
+ IssuesList: MockIssuesList,
+ AssigneePicker: MockAssigneePicker,
+ ProjectPicker: MockProjectPicker,
+ ManagedRoutinesList: MockManagedRoutinesList,
+};
+
+(globalThis as { __paperclipPluginBridge__?: { sdkUi?: Record<string, unknown> } }).__paperclipPluginBridge__ = { sdkUi };
+
+// ---------------------------------------------------------------------------
+// Harness app: chooses which view to render based on a global hash. Playwright
+// flips the hash to switch views and path segments to drive Wiki sections.
+// ---------------------------------------------------------------------------
+
+type ViewKey = "wiki" | "wiki-sidebar" | "settings" | "sidebar";
+
+function useView() {
+ const [view, setView] = useState<ViewKey>(() => readView());
+ useEffect(() => {
+ const handler = () => setView(readView());
+ window.addEventListener("hashchange", handler);
+ return () => window.removeEventListener("hashchange", handler);
+ }, []);
+ return view;
+}
+
+function readView(): ViewKey {
+ if (typeof window === "undefined") return "wiki";
+ const hash = window.location.hash.replace(/^#/, "");
+ if (hash === "settings" || hash === "sidebar" || hash === "wiki-sidebar") return hash;
+ return "wiki";
+}
+
+export function App() {
+ const view = useView();
+ return (
+ <div style={{ height: "100vh", width: "100vw", overflow: "hidden", background: "var(--background, oklch(0.145 0 0))", color: "var(--foreground, oklch(0.985 0 0))" }}>
+ {view === "wiki-sidebar" ? (
+ <div style={{ display: "flex", height: "100vh" }}>
+ <WikiRouteSidebar context={HOST_CONTEXT as never} />
+ <div style={{ flex: 1 }}>
+ <WikiPage context={HOST_CONTEXT as never} />
+ </div>
+ </div>
+ ) : view === "sidebar" ? (
+ <aside style={{ width: 240, background: "var(--sidebar, oklch(0.145 0 0))", padding: 12, height: "100vh", borderRight: "1px solid var(--border, oklch(0.269 0 0))" }}>
+ <SidebarLink context={HOST_CONTEXT as never} />
+ </aside>
+ ) : view === "settings" ? (
+ <SettingsPage context={HOST_CONTEXT as never} />
+ ) : (
+ <WikiPage context={HOST_CONTEXT as never} />
+ )}
+ </div>
+ );
+}
diff --git a/packages/plugins/plugin-llm-wiki/tests/screenshots/index.html b/packages/plugins/plugin-llm-wiki/tests/screenshots/index.html
new file mode 100644
index 0000000000..8167b10c69
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/tests/screenshots/index.html
@@ -0,0 +1,84 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>LLM Wiki UI Harness</title>
+ <style>
+ :root {
+ --background: oklch(0.145 0 0);
+ --foreground: oklch(0.985 0 0);
+ --card: oklch(0.205 0 0);
+ --primary: oklch(0.985 0 0);
+ --primary-foreground: oklch(0.205 0 0);
+ --secondary: oklch(0.269 0 0);
+ --secondary-foreground: oklch(0.985 0 0);
+ --muted: oklch(0.269 0 0);
+ --muted-foreground: oklch(0.708 0 0);
+ --accent: oklch(0.269 0 0);
+ --accent-foreground: oklch(0.985 0 0);
+ --border: oklch(0.269 0 0);
+ --input: oklch(0.269 0 0);
+ --sidebar: oklch(0.145 0 0);
+ }
+ html, body, #root {
+ margin: 0;
+ padding: 0;
+ height: 100%;
+ background: var(--background);
+ color: var(--foreground);
+ font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
+ font-size: 14px;
+ }
+
+ /* Minimal Tailwind utility shim — supports just the classes used by the */
+ /* plugin's WikiRouteSidebar so the screenshot harness renders something */
+ /* visually close to the production host (which compiles real Tailwind). */
+ .w-60 { width: 15rem; }
+ .h-full { height: 100%; }
+ .min-h-0 { min-height: 0; }
+ .border-r { border-right-width: 1px; border-right-style: solid; }
+ .border-t { border-top-width: 1px; border-top-style: solid; }
+ .border-border { border-color: var(--border); }
+ .bg-background { background: var(--background); }
+ .bg-accent { background: var(--accent); }
+ .flex { display: flex; }
+ .flex-col { flex-direction: column; }
+ .flex-1 { flex: 1; }
+ .items-center { align-items: center; }
+ .gap-0\.5 { gap: 0.125rem; }
+ .gap-1 { gap: 0.25rem; }
+ .gap-1\.5 { gap: 0.375rem; }
+ .gap-2 { gap: 0.5rem; }
+ .gap-2\.5 { gap: 0.625rem; }
+ .mb-2 { margin-bottom: 0.5rem; }
+ .mb-3 { margin-bottom: 0.75rem; }
+ .px-2 { padding-left: 0.5rem; padding-right: 0.5rem; }
+ .px-3 { padding-left: 0.75rem; padding-right: 0.75rem; }
+ .py-1 { padding-top: 0.25rem; padding-bottom: 0.25rem; }
+ .py-1\.5 { padding-top: 0.375rem; padding-bottom: 0.375rem; }
+ .py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; }
+ .py-3 { padding-top: 0.75rem; padding-bottom: 0.75rem; }
+ .shrink-0 { flex-shrink: 0; }
+ .text-xs { font-size: 0.75rem; line-height: 1rem; }
+ .text-sm { font-size: 0.875rem; line-height: 1.25rem; }
+ .text-\[11px\] { font-size: 11px; }
+ .text-\[13px\] { font-size: 13px; }
+ .font-medium { font-weight: 500; }
+ .font-semibold { font-weight: 600; }
+ .font-bold { font-weight: 700; }
+ .uppercase { text-transform: uppercase; }
+ .tracking-normal { letter-spacing: 0; }
+ .text-foreground { color: var(--foreground); }
+ .text-foreground\/80 { color: color-mix(in oklab, var(--foreground) 80%, transparent); }
+ .text-muted-foreground { color: var(--muted-foreground); }
+ .truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .rounded-md { border-radius: 0.375rem; }
+ .transition-colors { transition: background-color 150ms, color 150ms; }
+ .overflow-y-auto { overflow-y: auto; }
+ </style>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/bundle.js"></script>
+ </body>
+</html>
diff --git a/packages/plugins/plugin-llm-wiki/tests/wiki-route-sidebar-ui.spec.ts b/packages/plugins/plugin-llm-wiki/tests/wiki-route-sidebar-ui.spec.ts
new file mode 100644
index 0000000000..fd52bfeb68
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/tests/wiki-route-sidebar-ui.spec.ts
@@ -0,0 +1,781 @@
+// @vitest-environment jsdom
+
+import { createElement } from "react";
+import { createRoot, type Root } from "react-dom/client";
+import { act } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { WikiPage, WikiRouteSidebar } from "../src/ui/index.js";
+
+const COMPANY_ID = "11111111-1111-4111-8111-111111111111";
+const EXPANDED_STORAGE_KEY = `paperclipai.plugin-llm-wiki:route-sidebar-expanded:v2:${COMPANY_ID}`;
+
+type BridgeGlobal = typeof globalThis & {
+ __paperclipPluginBridge__?: {
+ sdkUi?: Record<string, unknown>;
+ };
+};
+
+type FileTreeNodeLike = {
+ name: string;
+ path: string;
+ kind: string;
+ children?: FileTreeNodeLike[];
+};
+
+type FileTreePropsLike = {
+ nodes: FileTreeNodeLike[];
+ selectedFile?: string | null;
+ expandedPaths?: ReadonlySet<string> | readonly string[];
+ onToggleDir?: (path: string) => void;
+ onSelectFile?: (path: string) => void;
+};
+
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+function createFileDragEvent(
+ type: string,
+ options: { files?: File[]; relatedTarget?: EventTarget | null } = {},
+) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ Object.defineProperty(event, "dataTransfer", {
+ value: {
+ types: ["Files"],
+ files: options.files ?? [],
+ dropEffect: "none",
+ },
+ });
+ Object.defineProperty(event, "relatedTarget", {
+ value: options.relatedTarget ?? null,
+ });
+ return event;
+}
+
+function toArray(paths: FileTreePropsLike["expandedPaths"]): string[] {
+ if (!paths) return [];
+ return Array.isArray(paths) ? [...paths] : Array.from(paths);
+}
+
+function renderTreeButtons(
+ nodes: FileTreeNodeLike[],
+ options: Pick<FileTreePropsLike, "onSelectFile" | "onToggleDir">,
+): ReturnType<typeof createElement>[] {
+ const buttons: ReturnType<typeof createElement>[] = [];
+ for (const node of nodes) {
+ if (node.kind === "dir") {
+ buttons.push(
+ createElement("button", {
+ key: node.path,
+ type: "button",
+ "data-toggle-dir": node.path,
+ onClick: () => options.onToggleDir?.(node.path),
+ }, node.name),
+ );
+ } else {
+ buttons.push(
+ createElement("button", {
+ key: node.path,
+ type: "button",
+ "data-select-file": node.path,
+ onClick: () => options.onSelectFile?.(node.path),
+ }, node.name),
+ );
+ }
+ buttons.push(...renderTreeButtons(node.children ?? [], options));
+ }
+ return buttons;
+}
+
+describe("WikiRouteSidebar", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ let hostLocation: { pathname: string; search: string; hash: string; state?: unknown };
+ let navigatedTo: { to: string; options?: unknown } | null;
+ let pluginDataCalls: Array<{ key: string; params?: Record<string, unknown> }>;
+ let pluginActionCalls: Array<{ key: string; params?: unknown }>;
+ let spacesRefreshCount: number;
+
+ beforeEach(() => {
+ window.localStorage.clear();
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ hostLocation = {
+ pathname: "/PAP/wiki/page/wiki/concepts/sidebar-navigation.md",
+ search: "",
+ hash: "",
+ };
+ navigatedTo = null;
+ pluginDataCalls = [];
+ pluginActionCalls = [];
+ spacesRefreshCount = 0;
+ (globalThis as BridgeGlobal).__paperclipPluginBridge__ = {
+ sdkUi: {
+ usePluginData: (key: string, params?: Record<string, unknown>) => {
+ pluginDataCalls.push({ key, params });
+ if (key === "spaces") {
+ return {
+ data: {
+ spaces: [
+ {
+ id: "space-default",
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ slug: "default",
+ displayName: "default",
+ spaceType: "managed",
+ folderMode: "managed_subfolder",
+ rootFolderKey: "wiki-root",
+ pathPrefix: null,
+ configuredRootPath: null,
+ accessScope: "shared",
+ ownerUserId: null,
+ ownerAgentId: null,
+ teamKey: null,
+ settings: {},
+ status: "active",
+ createdAt: null,
+ updatedAt: null,
+ },
+ {
+ id: "space-engineering",
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ slug: "engineering",
+ displayName: "Engineering",
+ spaceType: "managed",
+ folderMode: "managed_subfolder",
+ rootFolderKey: "wiki-root",
+ pathPrefix: "spaces/engineering",
+ configuredRootPath: null,
+ accessScope: "shared",
+ ownerUserId: null,
+ ownerAgentId: null,
+ teamKey: null,
+ settings: {},
+ status: "active",
+ createdAt: null,
+ updatedAt: null,
+ },
+ {
+ id: "space-archived",
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ slug: "qa-team-lock",
+ displayName: "QA Team Lock",
+ spaceType: "managed",
+ folderMode: "managed_subfolder",
+ rootFolderKey: "wiki-root",
+ pathPrefix: "spaces/qa-team-lock",
+ configuredRootPath: null,
+ accessScope: "shared",
+ ownerUserId: null,
+ ownerAgentId: null,
+ teamKey: null,
+ settings: {},
+ status: "archived",
+ createdAt: null,
+ updatedAt: null,
+ },
+ ],
+ },
+ loading: false,
+ error: null,
+ refresh: () => {
+ spacesRefreshCount += 1;
+ },
+ };
+ }
+ if (key !== "pages") return { data: null, loading: false, error: null, refresh: () => undefined };
+ return {
+ data: {
+ pages: [
+ {
+ path: "wiki/concepts/sidebar-navigation.md",
+ title: "Sidebar navigation",
+ pageType: "concepts",
+ backlinkCount: 0,
+ sourceCount: 0,
+ contentHash: "abc123",
+ updatedAt: new Date().toISOString(),
+ },
+ ],
+ sources: [],
+ },
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ },
+ usePluginAction: (key: string) => async (params?: unknown) => {
+ pluginActionCalls.push({ key, params });
+ return {};
+ },
+ usePluginToast: () => () => undefined,
+ useHostLocation: () => hostLocation,
+ useHostNavigation: () => ({
+ resolveHref: (to: string) => `/PAP${to.startsWith("/") ? to : `/${to}`}`,
+ navigate: (to: string, options?: unknown) => {
+ navigatedTo = { to, options };
+ },
+ linkProps: (to: string) => ({
+ href: `/PAP${to.startsWith("/") ? to : `/${to}`}`,
+ onClick: () => undefined,
+ }),
+ }),
+ FileTree: (props: FileTreePropsLike) => createElement(
+ "div",
+ {
+ role: "tree",
+ "data-selected-file": props.selectedFile ?? "",
+ "data-expanded-paths": toArray(props.expandedPaths).sort().join("|"),
+ },
+ renderTreeButtons(props.nodes, props),
+ ),
+ },
+ };
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ window.localStorage.clear();
+ delete (globalThis as BridgeGlobal).__paperclipPluginBridge__;
+ });
+
+ it("defaults wiki categories open so local files are visible", () => {
+ act(() => {
+ root.render(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ const tree = container.querySelector("[role='tree']") as HTMLElement;
+ expect(tree.dataset.expandedPaths?.split("|")).toEqual([
+ "wiki",
+ "wiki/concepts",
+ "wiki/entities",
+ "wiki/projects",
+ "wiki/sources",
+ "wiki/synthesis",
+ ]);
+ });
+
+ it("renders Ask before Add Content in the primary sidebar tools", () => {
+ act(() => {
+ root.render(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ const primaryNavText = container.querySelector("nav[aria-label='Wiki primary']")?.textContent ?? "";
+ expect(primaryNavText.indexOf("Ask")).toBeLessThan(primaryNavText.indexOf("Add Content"));
+ });
+
+ it("collapses and expands the active space tree from the space row", () => {
+ act(() => {
+ root.render(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ expect(container.querySelector("[role='tree']")).not.toBeNull();
+
+ act(() => {
+ (container.querySelector("[aria-label='Collapse default space']") as HTMLElement).click();
+ });
+
+ expect(container.querySelector("[role='tree']")).toBeNull();
+
+ act(() => {
+ (container.querySelector("[aria-label='Expand default space']") as HTMLElement).click();
+ });
+
+ expect(container.querySelector("[role='tree']")).not.toBeNull();
+ });
+
+ it("omits redundant shared badges beside space names", () => {
+ act(() => {
+ root.render(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ expect(container.textContent).not.toContain("shared");
+ });
+
+ it("hides archived spaces from the sidebar", () => {
+ act(() => {
+ root.render(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ expect(container.textContent).toContain("Engineering");
+ expect(container.textContent).not.toContain("QA Team Lock");
+ expect(pluginDataCalls).not.toContainEqual({
+ key: "pages",
+ params: { companyId: COMPANY_ID, includeRaw: true, spaceSlug: "qa-team-lock" },
+ });
+ });
+
+ it("refreshes and leaves an archived active space after sidebar archive", async () => {
+ hostLocation = {
+ pathname: "/PAP/wiki/spaces/engineering",
+ search: "",
+ hash: "",
+ };
+ const confirm = vi.spyOn(window, "confirm").mockReturnValue(true);
+ act(() => {
+ root.render(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ act(() => {
+ (container.querySelector("[aria-label='Engineering space menu']") as HTMLButtonElement).click();
+ });
+ const archiveButton = Array.from(container.querySelectorAll("button"))
+ .find((button) => button.textContent?.includes("Archive space"));
+
+ await act(async () => {
+ archiveButton?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+ await Promise.resolve();
+ });
+
+ expect(pluginActionCalls).toContainEqual({
+ key: "archive-space",
+ params: { companyId: COMPANY_ID, spaceSlug: "engineering" },
+ });
+ expect(spacesRefreshCount).toBe(1);
+ expect(navigatedTo).toEqual({ to: "/wiki", options: undefined });
+ confirm.mockRestore();
+ });
+
+ it("persists folder expansion client-side", () => {
+ act(() => {
+ root.render(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ act(() => {
+ (container.querySelector("[data-toggle-dir='raw']") as HTMLButtonElement).click();
+ });
+
+ // Toggled paths are stored under the active space slug ("default::") so
+ // each space remembers its own expansion state. Legacy entries written
+ // before the spaces refactor stay un-prefixed and still resolve to default.
+ expect(JSON.parse(window.localStorage.getItem(EXPANDED_STORAGE_KEY) ?? "[]")).toEqual([
+ "default::raw",
+ "wiki",
+ "wiki/concepts",
+ "wiki/entities",
+ "wiki/projects",
+ "wiki/sources",
+ "wiki/synthesis",
+ ]);
+
+ act(() => {
+ root.unmount();
+ });
+ root = createRoot(container);
+
+ act(() => {
+ root.render(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ const tree = container.querySelector("[role='tree']") as HTMLElement;
+ expect(tree.dataset.expandedPaths).toBe("raw|wiki|wiki/concepts|wiki/entities|wiki/projects|wiki/sources|wiki/synthesis");
+ });
+
+ it("does not select a wiki-link destination from the route", () => {
+ act(() => {
+ root.render(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ const tree = () => container.querySelector("[role='tree']") as HTMLElement;
+ expect(tree().dataset.selectedFile).toBe("");
+ });
+
+ it("keeps sidebar tree selection scoped to sidebar navigation", () => {
+ act(() => {
+ root.render(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ const tree = () => container.querySelector("[role='tree']") as HTMLElement;
+
+ act(() => {
+ (container.querySelector("[data-select-file='wiki/concepts/sidebar-navigation.md']") as HTMLButtonElement).click();
+ });
+
+ expect(navigatedTo).toEqual({
+ to: "/wiki/page/wiki/concepts/sidebar-navigation.md",
+ options: { state: { paperclipWikiSidebarTreePath: "wiki/concepts/sidebar-navigation.md" } },
+ });
+ // The default space stays the active space, so its tree is rendered in the
+ // sidebar; non-default spaces only render their tree once activated.
+ expect(tree().dataset.selectedFile).toBe("wiki/concepts/sidebar-navigation.md");
+
+ hostLocation = {
+ pathname: "/PAP/wiki/page/wiki/entities/paperclip.md",
+ search: "",
+ hash: "",
+ };
+ act(() => {
+ root.render(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ expect(tree().dataset.selectedFile).toBe("wiki/concepts/sidebar-navigation.md");
+
+ act(() => {
+ (container.querySelector("[data-toggle-dir='wiki/concepts']") as HTMLButtonElement).click();
+ });
+
+ expect(tree().dataset.selectedFile).toBe("wiki/concepts/sidebar-navigation.md");
+ expect(tree().dataset.expandedPaths?.split("|")).not.toContain("wiki/concepts");
+ });
+
+ it("warms inactive space pages so sidebar space switches have data ready", () => {
+ act(() => {
+ root.render(createElement(WikiRouteSidebar, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ expect(pluginDataCalls).toContainEqual({
+ key: "pages",
+ params: { companyId: COMPANY_ID, includeRaw: true, spaceSlug: "engineering" },
+ });
+ expect(pluginDataCalls).toContainEqual({
+ key: "page-content",
+ params: { companyId: COMPANY_ID, path: "wiki/concepts/sidebar-navigation.md", spaceSlug: "engineering" },
+ });
+ });
+});
+
+describe("WikiPage", () => {
+ let container: HTMLDivElement;
+ let root: Root;
+ let consoleError: ReturnType<typeof vi.spyOn>;
+ let hostLocation: { pathname: string; search: string; hash: string };
+ let navigatedTo: string | null;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ root = createRoot(container);
+ consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
+ hostLocation = {
+ pathname: "/PAP/wiki/page/wiki/projects/control-plane/index.md",
+ search: "",
+ hash: "",
+ };
+ navigatedTo = null;
+ (globalThis as BridgeGlobal).__paperclipPluginBridge__ = {
+ sdkUi: {
+ usePluginData: (key: string) => {
+ if (key === "overview") {
+ return {
+ data: { folder: { healthy: true }, wikiId: "default" },
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ }
+ if (key === "spaces") {
+ return {
+ data: {
+ spaces: [
+ {
+ id: "space-default",
+ companyId: COMPANY_ID,
+ wikiId: "default",
+ slug: "default",
+ displayName: "default",
+ spaceType: "managed",
+ folderMode: "managed_subfolder",
+ rootFolderKey: "wiki-root",
+ pathPrefix: null,
+ configuredRootPath: null,
+ accessScope: "shared",
+ ownerUserId: null,
+ ownerAgentId: null,
+ teamKey: null,
+ settings: {},
+ status: "active",
+ createdAt: null,
+ updatedAt: null,
+ },
+ ],
+ },
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ }
+ if (key === "settings") {
+ return {
+ data: {
+ folder: {
+ configured: true,
+ path: "/tmp/company-wiki",
+ realPath: "/tmp/company-wiki",
+ access: "readWrite",
+ readable: true,
+ writable: true,
+ requiredDirectories: [],
+ requiredFiles: [],
+ missingDirectories: [],
+ missingFiles: [],
+ healthy: true,
+ problems: [],
+ checkedAt: new Date().toISOString(),
+ },
+ managedAgent: {
+ status: "resolved",
+ source: "managed",
+ agentId: "agent-1",
+ resourceKey: "wiki-maintainer",
+ details: { name: "Wiki Maintainer", status: "idle", adapterType: "claude_local", icon: "book-open", urlKey: "wiki-maintainer" },
+ },
+ managedProject: {
+ status: "resolved",
+ source: "managed",
+ projectId: "project-1",
+ resourceKey: "llm-wiki",
+ details: { name: "LLM Wiki", status: "in_progress" },
+ },
+ managedSkills: [],
+ managedRoutines: [],
+ eventIngestion: {
+ enabled: false,
+ sources: { issues: false, comments: false, documents: false },
+ wikiId: "default",
+ maxCharacters: 12000,
+ },
+ agentOptions: [{ id: "agent-1", name: "Wiki Maintainer", status: "idle", icon: "book-open", urlKey: "wiki-maintainer" }],
+ projectOptions: [{ id: "project-1", name: "LLM Wiki", status: "in_progress", color: "#2563eb" }],
+ capabilities: [],
+ },
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ }
+ if (key === "pages") {
+ return {
+ data: {
+ pages: [
+ {
+ path: "wiki/projects/control-plane/index.md",
+ title: "Control plane",
+ pageType: "projects",
+ backlinkCount: 0,
+ sourceCount: 1,
+ contentHash: "abc123",
+ updatedAt: new Date().toISOString(),
+ },
+ ],
+ sources: [],
+ },
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ }
+ if (key === "page-content") {
+ return {
+ data: {
+ wikiId: "default",
+ path: "wiki/projects/control-plane/index.md",
+ contents: "# Control plane\n\nCurrent project state.",
+ title: "Control plane",
+ pageType: "projects",
+ backlinks: [],
+ sourceRefs: [
+ {
+ kind: "issue",
+ title: "Distillation kickoff",
+ issueId: "issue-1",
+ projectId: "project-1",
+ updatedAt: "2026-05-04T15:01:00Z",
+ issueIdentifier: "PAP-3416",
+ },
+ ],
+ updatedAt: "2026-05-04T15:01:00Z",
+ hash: "def456",
+ },
+ loading: false,
+ error: null,
+ refresh: () => undefined,
+ };
+ }
+ if (key === "distillation-page-provenance") {
+ return { data: null, loading: false, error: null, refresh: () => undefined };
+ }
+ return { data: null, loading: false, error: null, refresh: () => undefined };
+ },
+ usePluginAction: () => async () => ({}),
+ usePluginToast: () => () => undefined,
+ useHostLocation: () => hostLocation,
+ useHostNavigation: () => ({
+ resolveHref: (to: string) => `/PAP${to.startsWith("/") ? to : `/${to}`}`,
+ navigate: (to: string) => {
+ navigatedTo = to;
+ },
+ linkProps: (to: string) => ({
+ href: `/PAP${to.startsWith("/") ? to : `/${to}`}`,
+ onClick: () => undefined,
+ }),
+ }),
+ MarkdownBlock: ({ content }: { content: string }) => createElement("div", {}, content),
+ MarkdownEditor: ({ value }: { value: string }) => createElement("textarea", { value, readOnly: true }),
+ AssigneePicker: () => createElement("div", { "data-testid": "assignee-picker" }),
+ ProjectPicker: () => createElement("div", { "data-testid": "project-picker" }),
+ },
+ };
+ });
+
+ afterEach(() => {
+ act(() => {
+ root.unmount();
+ });
+ container.remove();
+ consoleError.mockRestore();
+ delete (globalThis as BridgeGlobal).__paperclipPluginBridge__;
+ });
+
+ it("renders structured Paperclip source refs as text", () => {
+ act(() => {
+ root.render(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ expect(container.textContent).toContain("PAP-3416 issue - Distillation kickoff");
+ const consoleOutput = consoleError.mock.calls.flat().join("\n");
+ expect(consoleOutput).not.toContain("Objects are not valid as a React child");
+ expect(consoleOutput).not.toContain("Each child in a list should have a unique \"key\" prop");
+ });
+
+ it("prioritizes file drop on the ingest page without recent ingest or cost copy", () => {
+ hostLocation = {
+ pathname: "/PAP/wiki/ingest",
+ search: "",
+ hash: "",
+ };
+
+ act(() => {
+ root.render(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ const text = container.textContent ?? "";
+ expect(text).toContain("Drop files anywhere on this page");
+ expect(text).not.toContain("Recent ingests");
+ expect(text).not.toContain("Why does this take a moment?");
+ expect(text).not.toContain("est. cost");
+
+ const separatorText = container.querySelector("[data-testid='llm-wiki-ingest-manual-separator']")?.textContent ?? "";
+ expect(separatorText).toBe("or");
+ expect(text.indexOf("Drop files anywhere on this page")).toBeLessThan(text.indexOf("Source title"));
+ expect(text.indexOf("Source title")).toBeLessThan(text.indexOf("URL"));
+ expect(text.indexOf("URL")).toBeLessThan(text.indexOf("Paste markdown / text"));
+ });
+
+ it("closes the page drop overlay when a file drag leaves without dropping files", () => {
+ act(() => {
+ root.render(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ const page = container.querySelector("main") as HTMLElement;
+ act(() => {
+ page.dispatchEvent(createFileDragEvent("dragenter"));
+ });
+
+ expect(container.querySelector("[data-testid='llm-wiki-page-drop-overlay']")).not.toBeNull();
+
+ act(() => {
+ page.dispatchEvent(createFileDragEvent("dragleave"));
+ });
+
+ expect(container.querySelector("[data-testid='llm-wiki-page-drop-overlay']")).toBeNull();
+ expect(container.querySelector("[data-testid='llm-wiki-ingest-modal']")).toBeNull();
+ });
+
+ it("keeps staged dropped files in the ingest modal after the drop overlay clears", () => {
+ act(() => {
+ root.render(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ const page = container.querySelector("main") as HTMLElement;
+ const file = new File(["source notes"], "source-notes.md", { type: "text/markdown" });
+
+ act(() => {
+ page.dispatchEvent(createFileDragEvent("dragenter"));
+ page.dispatchEvent(createFileDragEvent("drop", { files: [file] }));
+ });
+
+ expect(container.querySelector("[data-testid='llm-wiki-page-drop-overlay']")).toBeNull();
+ expect(container.querySelector("[data-testid='llm-wiki-ingest-modal']")).not.toBeNull();
+ expect(container.textContent).toContain("source-notes.md");
+ });
+
+ it("lets users close the page drop overlay directly", () => {
+ act(() => {
+ root.render(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ const page = container.querySelector("main") as HTMLElement;
+ act(() => {
+ page.dispatchEvent(createFileDragEvent("dragenter"));
+ });
+
+ const closeButton = container.querySelector("[aria-label='Close ingest drop overlay']") as HTMLButtonElement;
+ expect(closeButton).not.toBeNull();
+
+ act(() => {
+ closeButton.click();
+ });
+
+ expect(container.querySelector("[data-testid='llm-wiki-page-drop-overlay']")).toBeNull();
+ });
+
+ it("navigates settings tabs to their URL subpaths", () => {
+ hostLocation = {
+ pathname: "/PAP/wiki/settings",
+ search: "",
+ hash: "",
+ };
+
+ act(() => {
+ root.render(createElement(WikiPage, {
+ context: { companyId: COMPANY_ID, companyPrefix: "PAP" },
+ } as never));
+ });
+
+ act(() => {
+ (Array.from(container.querySelectorAll("button")).find((button) => button.textContent?.includes("Distillation")) as HTMLButtonElement).click();
+ });
+
+ expect(navigatedTo).toBe("/wiki/settings/distillation");
+ });
+});
diff --git a/packages/plugins/plugin-llm-wiki/tsconfig.json b/packages/plugins/plugin-llm-wiki/tsconfig.json
new file mode 100644
index 0000000000..a697519ed9
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/tsconfig.json
@@ -0,0 +1,27 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "lib": [
+ "ES2022",
+ "DOM"
+ ],
+ "jsx": "react-jsx",
+ "strict": true,
+ "skipLibCheck": true,
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true,
+ "outDir": "dist",
+ "rootDir": "."
+ },
+ "include": [
+ "src",
+ "tests"
+ ],
+ "exclude": [
+ "dist",
+ "node_modules"
+ ]
+}
diff --git a/packages/plugins/plugin-llm-wiki/vitest.config.ts b/packages/plugins/plugin-llm-wiki/vitest.config.ts
new file mode 100644
index 0000000000..649a293ef9
--- /dev/null
+++ b/packages/plugins/plugin-llm-wiki/vitest.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["tests/**/*.spec.ts"],
+ environment: "node",
+ },
+});