# ContextNest Community Server

Self-hosted context governance server. Nests are versioned knowledge vaults
of markdown documents with tags, wiki-links ([[Title]]), and steward
governance. This file is the complete interaction manual for agents.

## Authentication

Every request (except this file and /health): `Authorization: Bearer cnst_<api-key>`.
Keys are minted in the web UI (Connect dialog → Generate Key). A key is
either user-level (sees every nest the user can read) or scoped to one nest.
Servers in "open" auth mode need no key.

## Start here

1. `GET https://nest.promptowl.ai/index` — your grounded nest index (markdown; `?format=json` for JSON).
   One entry per accessible nest: name, id, permission, document count, and
   the per-nest URLs below.
2. Pick a nest id, then retrieve with the API or MCP.

## Links for people

Everything else in this file is an address for agents and programs. When a
person asks for a link, give them the web app's address, never an API or MCP
URL (those answer a browser with JSON or an error):

- a nest: `https://nest.promptowl.ai/nest/<nest-id>` (singular `/nest/`; the API is `/nests/`)
- one document: `https://nest.promptowl.ai/nest/<nest-id>?doc=<node-id>` with the node id
  URL-encoded (`nodes/gtm/plan` → `?doc=nodes%2Fgtm%2Fplan`)

`/index`, `nest_index` and the document tools return these ready-made
(`web_url`, "Web link"). Opening one goes through the same access rules as
everything else: the person must be signed in and able to read it.

## Deterministic retrieval API

Same inputs → same context, every time. The primary call:

```
POST https://nest.promptowl.ai/nests/<nest-id>/context
Content-Type: application/json
{ "selector": "#gtm", "hops": 2, "max_tokens": 4000, "include_drafts": false }
```

Returns `{ context, nodes[], trace }` — assembled markdown plus a trace with
`hops_used` and `nodes_traversed` so you can audit exactly what was pulled.

Selector grammar:
- `#tag` — nodes carrying a tag
- `type:document` — nodes of a type
- `[[Title]]` — a node by exact title
- `scope:team` — nodes by visibility scope
- Combine: `+AND`, `|OR`, `-NOT` (e.g. `#gtm+type:document-#draft`)

Graph-hop logic: `hops` is the traversal depth over wiki-links from the
selector matches. `hops: 0` = exactly the matches; `hops: 1` = matches plus
directly linked nodes; `hops: 2` (default) and up walk the link graph
further out. For an exact set with no expansion, OR the selectors together
(`[[A]]|[[B]]`) and pass `hops: 0`.

Skip logic — what retrieval excludes and why:
- Draft/unapproved documents are skipped unless `include_drafts: true`
  (and public/read-only callers always get approved content only).
- `max_tokens` is a budget: documents that don't fit are skipped, and the
  trace reports `truncated_by_budget` so silence never means "complete".
- Documents are deduped by id when a title match and a selector match overlap.

Other read endpoints (all under `https://nest.promptowl.ai/nests/<nest-id>`):
- `POST /query` — `{ "query": "<selector>", "hops": N }`; matches + snippets, no bodies
- `GET /search?q=<terms>` — full-text search
- `GET /overview` — node count, types, tags
- `GET /nodes` — list; `GET /nodes/<node-id>?format=markdown` — one document
- `GET /nodes/<node-id>?format=raw` — direct consumption path: the node BODY as plain text (no JSON envelope; add `&frontmatter=1` for the stored YAML block)
- `GET /export?format=markdown` — whole nest as one markdown file (optional `selector`, `max_tokens`)
- `GET /graph` — ontology graph (nodes, links, tags, stewards)
- `GET /folders` — folder tree; `GET /nodes?folder=<path>` — one folder level
- `POST /table-query` — exact rows from a table node: `{ "table": "[[Title]]", "query": "where <col> <op> <value> [select cols] [limit N]" }`
- `GET /nodes/<node-id>/versions` — history (who, when, approval state); `/versions/<n>` — one version
- `GET /nodes/<node-id>/comments` — review threads (anchored quotes, replies, open/resolved)

Write endpoints (need write permission):
- `POST /nodes` — `{ "title", "content", "tags"?, "type"?, "folder"? }`
  - `content` is markdown. To post an HTML page (deck, dashboard, report), send
    `"type": "artifact"` and put the raw HTML document in `content`, with no
    markdown code fence around it; it renders as a page in the web app. Over MCP:
    `context_create` with the same `type` and `content`.
  - The response carries `web_url`, the document's link for people.
- `PATCH /nodes/<node-id>` — `{ "content"? , "append"?, "tags"?, "title"? }`
- `DELETE /nodes/<node-id>`; `POST /nodes/<id>/request-deletion` when you lack delete rights
- `POST /nodes/<id>/move` — `{ "folder" }`; history and comments follow
- `POST /nodes/<id>/revert` — `{ "targetVersion" }` restores a past version as a new one
- `POST /nodes/<id>/comments` — leave or reply to a review comment
- Governance: `POST /nodes/<id>/submit-review`, `/approve`, `/reject`, `/cancel-review`
- `GET /review-queue` — what is waiting on a steward in this nest

## Your inbox (server-level)

- `GET https://nest.promptowl.ai/me/work` — reviews waiting on you, handoffs, and open threads that @mention you, across every nest (MCP: `context_my_work`)
- `GET https://nest.promptowl.ai/me/drafts` — your documents never submitted for review
- `GET https://nest.promptowl.ai/me/notifications` — watcher and review notifications

## Say who you are: `client`

Every write body and every MCP tool call takes an optional
`client` object — `{ "agent": "claude-code", "session_id": "s-9f2" }`, plus any
custom scalar keys. A write that seals a version records it on that version
(`GET /nodes/<id>/versions` and `context_versions` serve it back); every call
records it on this server's activity trace, which is how a READ gets attributed.

Send it. Nothing requires it and no call is refused for omitting it, but a vault
serving several agents cannot otherwise tell which of you wrote what. It is a
label, never an identity claim: it is not authenticated, grants nothing, and is
never part of a hash. Bounded — scalar values up to 512 chars, at most 16 custom
keys beyond `agent` and `session_id`.

## MCP (Model Context Protocol)

Streamable HTTP, stateless. Two endpoints:

- `https://nest.promptowl.ai/mcp` — server-level, one connection for everything.
  Tools: `nest_index` (call first), then:
  - Fan-out reads (omit `nest` to search/list ALL nests): `context_search`,
    `context_list`, `context_query`, `context_overview`
  - Targeted reads (`nest` required): `context_get`, `context_resolve`, `context_comments`, `context_versions`,
    `context_boards`, `context_board_items`, `context_pull_log` (recorded retrievals and what each handed over)
  - Writes (`nest` required): `nest_create`, `context_create`, `context_update`,
    `context_delete`, `context_archive`, `context_unarchive`, `context_move`, `context_submit_review`,
    `context_request_access` (ask for write access when a write is refused),
    `context_task_log` (log what you did on a task: working / done / blocked),
    `context_bulk_update` (one change over up to 100 nodes)
  - Feed: `context_stream` (every document version across your nests, people and agents)
  - First run: `context_onboarding`, `context_onboarding_update`, `context_distill` (fill a nest from a public site or repo)
  - Control room (workflow plane on): `context_agent_ledger_org`, `context_agent_rollups_org`
- `https://nest.promptowl.ai/nests/<nest-id>/mcp` — per-nest, the full toolset. Same names as the
  server-level tools without the `nest` argument, plus:
  - read: `context_init` (operating instructions plus the nest's always-include documents — call first), `context_instructions_history`, `context_export`, `context_table_query`, `context_versions`
  - write: `context_update`, `context_table_rows` (change table rows by key), `context_delete`, `context_move`, `context_request_deletion`, `context_request_access`, `context_bulk_update`
  - boards: `context_boards`, `context_board_items` (a board as a sortable, grouped list)
  - review: `context_submit_review`, `context_approve`, `context_reject`, `context_review_queue`, `context_my_drafts`
  - comments: `context_comment` (a document, or `channel` to post in a channel), `context_resolve_comment`, `context_promote_thread` (turn a thread into a decision or task node)
  - people: `context_stewards`, `context_assign_steward`, `context_share_nest`, `context_grant`, `context_nest_teams` (list, share, unshare teams)
  - sharing: `context_public_link_create` (name `access_mode`), `context_public_links`, `context_public_link_update`, `context_public_link_revoke`
  - your queue: `context_my_work` (reviews, tasks, mentions, saved; `for_agent` for threads that tag you), `context_stream`
  - memory: `context_remember` (a message or thread becomes a node, reviewed like any draft), `context_correct`, `context_decisions`
  - team chat (when `TEAM_CHAT_ENABLED` is on): `context_channels`, `context_channel_read` (`since` for only what is new), `context_message`, `context_message_read`, `context_channel_search`, `context_channel_knowledge`, `context_channel_watch`, `context_conversations`, `context_conversation_read`, `context_channel_members`, `context_chat_preferences`, `context_presence`
  - agents in chat (same switch): `context_ask_nest`, `context_agents`, `context_handoff`, `context_hire_catalog`, `context_hire_agent`, `context_hired_agents`, `context_agent_recommendations`, `context_agent_webhooks`
  - control room (workflow plane on): `context_agent_register`, `context_agent_run_start`, `context_agent_run_step`, `context_agent_run_close`, `context_agent_ledger`, `context_agent_ledger_trace`, `context_agent_ledger_export`, `context_agent_rollups`
  - admin: `context_instructions_update` (owner/admin: replace CONTEXT.md), `context_deletion_queue`, `context_resolve_deletion`, `context_access_requests`, `context_resolve_access_request`, `context_unsynced_list`, `context_sync_folder`
  - `workflow_*` (runs, edges, edge types) when the nest's workflow plane is on
  - metacognition (owner/admin, when `FEATURE_METACOGNITION` is on too; not on
    `https://nest.promptowl.ai/mcp`): `context_metacognition_list`, `context_metacognition_suggest`
    (a starting config read off the agent document), `context_metacognition_preview`
    (validates a config and saves nothing: show the person the returned `summary`),
    `context_metacognition_configure` (saves it), `context_metacognition_run`, `context_metacognition_remove`; stats via
    `workflow_runs_list { agent, agent_stats: true }`
  Sharing a slice is one call: `context_grant` with
  `{ "email", "target_type": "document" | "folder", "target", "role": "read" | "write" }`
  — `target` is a node id (`nodes/win-loss-log`) or a folder prefix
  (`nodes/gtm/deals`). The recipient reaches exactly that document, or
  everything under that folder, and nothing else in the nest. Owner/admin only.

Both endpoints answer `initialize` with `instructions`: the nest's CONTEXT.md
(per-nest) and the approved text of its **always-include** documents — the
standing rules for any work in the nest, filtered to what these credentials can
read. Most clients put them in the system prompt; follow them.

Claude Code / Cursor / VS Code connect natively via HTTP with the
`Authorization: Bearer` header. Claude Desktop needs the mcp-remote bridge:

```
npx -y mcp-remote https://nest.promptowl.ai/mcp --header "Authorization: Bearer <api-key>"
```

## From the ctx CLI

The `ctx` CLI (`@promptowl/contextnest-cli` 2.2+) reads a hosted nest the
same way it reads a local vault: register the MCP endpoint as a vault alias,
then pass `--vault <alias>` to `query`, `read`, `list`, `search`. The key
is read from the environment variable named by `--bearer-env` — never put it
on the command line.

```
export CONTEXTNEST_API_KEY=<api-key>
# every nest these credentials can read, through the server-level endpoint
ctx vault add contextnest --url https://nest.promptowl.ai/mcp --bearer-env CONTEXTNEST_API_KEY
ctx vault list                                  # lists contextnest/<nest> for each nest
ctx search "pricing" --vault contextnest        # reads span every nest
ctx update nodes/x --tags a,b --vault contextnest/<nest>   # a write names one nest
# or pin one nest by its own endpoint
ctx vault add mynest --url https://nest.promptowl.ai/nests/<nest-id>/mcp --bearer-env CONTEXTNEST_API_KEY
```

Servers in "open" auth mode: drop `--bearer-env`. Pushing a local folder up
is `ctx push --server https://nest.promptowl.ai --nest <nest-id>` with the same env var set.

## npm packages

- `@promptowl/contextnest-community` — this server
- `@promptowl/contextnest-engine` — vault storage + selector/graph engine

## Conventions

- Node ids are paths: `nodes/<slug>` or nested `nodes/<folder>/<slug>`.
- Tags are `#lowercase`. Wiki-links are `[[Exact Title]]`.
- Every write is versioned and hash-chained; governed nests route writes
  through steward review before they become AI-visible.
