Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/cortex/blob/main/spec/CORTEX-API.md # cortex aien-dev/cortex Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `cortex / spec / CORTEX-API.md` 192 lines · 13798 bytes Raw Blame History Source # Cortex wire contract (Omega Cortex = cortex-rs 0.1.0 on the wire) The Omega server answers every request of cortex-rs 0.1.0 with the same bytes, apart from the `/health` runtime field (below). "Same" is defined and checked by the parity gate (spec/PARITY.md); edge behaviour measured on the live binary, including every error text, is in spec/ORACLE-OBSERVED.md. This file is the summary a client needs. ## Server ``` cortex [--host 127.0.0.1] [--port 18080] --log PATH [--encoder-url URL] [--tokens FILE] cortex-import SRC.db OUT.log ``` - `--log PATH`: the append-only Cortex log (format: spec/BUILD-CONTRACT.md). It replaces cortex-rs `--db-path`; the server refuses `--db-path` and tells you to import the SQLite store once with `cortex-import`. The importer reads a cortex-rs database (main file plus WAL, read-only) and writes a new log; take the source with `sqlite3 'file:DB?mode=ro' '.backup COPY'` first. - `--encoder-url URL`: the embedding service used by recall, as in cortex-rs. When it does not answer, recall runs on lexical and metadata scores only, like cortex-rs. - Every write is appended and flushed before the 201 answer; after a crash the log replays up to the last complete record and a torn tail is cut (checked by tests/load/run.sh with kill -9). ## Authentication - `/health`, `/status` and CORS preflights need no token. Every `/api/cortex/*` route needs `Authorization: Bearer `. - The token is `CORTEX_TOKEN` from the environment; when unset or blank, `$HOME/.config/cortex/token`, re-read on every request. No token configured: 503 `{"error":"Service unavailable: Cortex authentication token unconfigured on host"}`. Missing or wrong token: 401 `{"error":"Unauthorized: invalid or missing Cortex bearer token"}`. The comparison is constant-time. ## Routes method, path input success GET `/health`, GET `/status` (HEAD too) — 200 `{"runtime":"native-arm64-omega","service":"cortex-rs","space":"atlas-memory","status":"ok","version":"0.1.0"}` POST `/api/cortex/write` JSON, `kind` = `entity` / `claim` / `retract` (fields below) 201 `{"recorded":true,"receipt":{"id","operation","targetType","targetId","committedAt"}}` GET `/api/cortex/search` query string `q` (or `query`), `space`, `limit` (default 12, max 50), `include_retracted` 200 `{"results":[entity + lexicalScore, graphScore, semanticScore, score],"degraded":[],"elapsedMs":…}` POST `/api/cortex/search` JSON with the same fields same as GET POST `/api/cortex/recall` JSON `query`, `space`, `limit` (default 5, max 20), `tokenBudget` (default 1200) 200 `{"results":[{"entity","finalScore","componentScores":{"lexical","semantic","confidenceRecency","graph"}}],"degraded":[],"elapsedMs":…}` GET `/api/cortex/get` `id` or `name`, optional `space` 200 entity; 400 `Missing id or name parameter`; 404 `Entity not found` POST `/api/cortex/traverse` JSON `subjectId`, `space` 200 `{"claims":[…]}` (claim keys sorted) POST `/api/cortex/delete` Omega extension, see below 200 `{"deleted":N}` Write inputs (camelCase): - entity: `id`?, `space` (default `atlas-memory`), `entityType` (default `discovery`), `canonicalName`, `content`, `aliases`, `metadata` (default `{}`), `confidence` (default 1.0), `validFrom`?, `validTo`?, `externalId`?. An entity with the same `space` and `canonicalName` is updated under its existing id and its revision increases; otherwise `id` (or a new UUID) is used. - claim: `id`?, `space`, `subjectEntityId`, `predicate`, `objectEntityId`?, `literalValue`?, `confidence`, `metadata`. - retract: `targetType` (`entity` / `claim`), `targetId`, `reason`?. Entity objects: `id, spaceId, spaceSlug, entityType, canonicalName, content, aliases, metadata, confidence, revision, retracted, validFrom, validTo, createdAt`. Search: the query, with double quotes removed, is matched as one FTS5 phrase (bm25 order); when that gives nothing, a substring match on name or content follows (score 0.7); an empty query lists the newest entities (score 0.4). Operators such as `OR`, `NOT` or `*` are not interpreted, which is what the live binary does (spec/ORACLE-OBSERVED.md). Errors from body and query parsing are axum's: 400/422 with a text/plain message (415 without a JSON content type, 413 above 2,097,152 bytes), byte-identical to cortex-rs (spec/ORACLE-OBSERVED.md). CORS: any OPTIONS answers 200 with `access-control-allow-methods: *` and `access-control-allow-headers: *`; `access-control-allow-origin` is echoed only for `http://127.0.0.1:18095` and `http://localhost:18095`. Every answer carries `vary: origin, access-control-request-method, access-control-request-headers`. The live cortex-rs binary also allowed two non-loopback origins; the Omega server does not. ## Differences from cortex-rs (intentional) - `/health` and `/status` report `"runtime":"native-arm64-omega"` (cortex-rs: `native-arm64-rust`). The parity gate masks exactly this value. - POST `/api/cortex/delete` (not in cortex-rs; not in the parity corpus). Hard delete for data that must leave the disk, such as a visitor's "forget me": body `{"targetType":"entity", "targetId":ID}`removes one entity,`{"space":SLUG}` removes a space with its entities and claims. The answer is `{"deleted":N}` (live entities removed; 0 when nothing matched). The server then rewrites the log with the current state only, so the deleted bytes are gone from the file. Same authentication as the other routes. cortex-rs can only retract (the row stays on disk). - `--tokens FILE` (not in cortex-rs). Extra tokens limited to some spaces, one `TOKEN SPACE[,SPACE...]` per line (blank lines and `#` lines skipped). A scoped token may only touch the spaces listed: a request naming another space, or naming none, gets 403 `{"error":"Forbidden: token scope does not cover this space"}`. The main token keeps full access. Without `--tokens` the server behaves exactly like cortex-rs. - Loopback-only CORS origins (above). - Company Brain (`/api/cortex/brain/*`, `--brain-export`; not in cortex-rs, not in the parity corpus), below. The only change to a cortex-rs route: POST `/api/cortex/write` answers 409 `{"error":"Brain entries are append-only: write them through /api/cortex/brain/write"}` for an entity whose `entityType` starts with `brain.`, or whose id or (space, `canonicalName`) names a stored Brain entry. Retract and hard delete work on Brain entries as on any entity. ## Company Brain (Omega extension) A memory that agents read before a task and write to after it, stored as ordinary entities in the same append-only log and FTS index (om/brain.om). There is no second store and no second server. ### Entries An entry is atomic, dated and owned: `id` (A-Z a-z 0-9 `.` `_` `-`, not starting with `.`; unique in its space), `space` (default `brain`), `kind` (`decision`, `rule`, `case`, `change`, or the structured kinds `contract` and `party`), `date` (UTC calendar date `YYYY-MM-DD`, proleptic Gregorian; default today in UTC), `owner` (non-empty text), `body` and an optional `supersedes` (the id of a live entry of the same space). It is stored as one ENTITY record: `canonicalName` = id, `entityType` = `brain.` + kind, `validFrom` = date, `content` = body, `metadata` = `{"owner":O}` or `{"owner":O,"supersedes":S}`, confidence 1.0. Entries are never rewritten: a correction is a new entry that supersedes the wrong one. The wrong one stays readable and its `supersededBy` names the correction. An entry can be superseded once; the next correction supersedes the newer entry. "Live" means stored, not retracted and not superseded. Entry object: `{"id","space","kind","date","owner","supersedes","supersededBy","retracted","body"}` (`body` is null for a retracted entry). ### Routes All are POST with a JSON body, the same bearer token and space scopes as `/api/cortex/*`. Body parsing errors are the same axum texts as the other routes (400/422 text/plain). Errors raised by the Brain are JSON `{"error":TEXT}`: 404 unknown entry, 409 conflict (duplicate id, already superseded, append-only guard), 422 invalid field, 413 query larger than the FTS replica, 500 answer larger than the 16 MiB output buffer. path input success `/api/cortex/brain/write` `id`?, `space`?, `kind`, `owner`, `date`?, `body`, `supersedes`? 201 `{"recorded":true,"entry":ENTRY}`; appended and fsync'd before the answer (default `id`: a new UUID) `/api/cortex/brain/read` `task`, `space`?, `limit`? (default 10) 200 `{"space","task","supported","entries":[{"rank","score","entry"}],"citations":[{"id","date"}]}`; with no match `supported` is false, both lists are empty and `note` says nothing is cited `/api/cortex/brain/get` `id`, `space`? 200 `{"entry":ENTRY}`, superseded and retracted entries included `/api/cortex/brain/confirm` `id` (a live, unconfirmed contract record), `owner`, `date`?, `newId`?, `space`? 201: a new entry that supersedes it with `confirmed: yes`; default id `-c` (smallest k from 1 not in use) `/api/cortex/brain/alerts` `date`, `days`, `taxId`?, `space`? 200 `{"space","date","days","alerts":[{"id","entryDate","owner","docType","registryId","dateKind","keyDate","daysLeft","parties":[{"taxId","counterparty"}]}]}` `/api/cortex/brain/records` `registryId`?, `taxId`?, `space`? 200 `{"space","records":[{"confirmed","entry"}]}`: live contract records by entry date, then id `/api/cortex/brain/import` `text` (an export file), `owner`, `date`?, `space`? 200 `{"recorded":false,"changed":false,"entry"}` when kind and body equal the stored entry (or its correction); else 201 `{"recorded":true,"changed":true,"entry"}`: a new entry `-c` superseding the file's entry `/api/cortex/brain/usage` `alarmPercent`? (default 50), `space`? 200: fill and fixed capacity of the store (entities, claims, spaces, dictionary, short-string bytes, content bytes, FTS tokens, FTS rows), the number of Brain entries, `supersedeIndexMismatches` (entries where the live supersede index differs from a full rebuild; null while the index is stale), `ftsIndexMismatches` (differences between the incremental FTS index, kept by every write, and a rebuild from the rows: term lists, per-term row counts, per-space row lists; om/fts.om `fts_icheck`), and `alarms`: the quantities at or above `alarmPercent` of their capacity Read before: the task text is split into tokens (runs of letters, digits, `.` `_` `-` and bytes 128..255), each token becomes a quoted FTS5 string, and the strings are joined with `OR`. The FTS replica ranks the live entries of the space by bm25 (`score` = -bm25, higher is better). `citations` lists the id and date of exactly the entries returned, in rank order: every cited id is a stored entry, and an answer with no entry cites nothing. No language model is involved. Which entries are superseded is kept in a live index: built from the log on the first request after a start, updated by every Brain write, and rebuilt on the next request after any retract or hard delete. ### Structured records A `contract` or `party` body is one `key: value` per line (blank lines allowed), checked on write (422 names the line): - contract: exactly one `doc_type:` (`contract`, `amendment`, `extension`, `tender`, `call`, `framework_agreement`); at most one `registry_id:`, `subject:` and `confirmed:` (`yes`/`no`); any number of `party: TAXID`, `note:` and `date: KIND YYYY-MM-DD` lines with KIND `hard_expiry`, `on_completion`, `submission_deadline`, `extension` or `start` (`date: on_completion -` records an on-completion clause without a date). The key dates are a set: each line keeps its own kind. - party: exactly one `name:`, one or more `tax_id:` lines (several tax IDs, one counterparty), `note:`. The human gate: a contract written through `brain/write` is stored with `confirmed: no` (a body saying `confirmed: yes` is refused with 422). It becomes confirmed only by `brain/confirm` or by importing a hand-corrected export file that says `confirmed: yes`; both write a superseding entry owned by the person who confirmed. `registry_id` links tender, contract and amendment (`records` with `registryId`); `taxId` filters match any tax ID of the same live party record. Alerts: every key date of a live, confirmed contract record whose kind is not `start` and that has a date, with `date <= keyDate <= date + days` (integer day numbers since 1970-01-01, proleptic Gregorian calendar; both ends included, so day `days` is in and day `days + 1` is out), ordered by key date, record id and line. `daysLeft` = keyDate - date. Unconfirmed records never appear. ### Plain files ``` cortex --log PATH --brain-export DIR ``` opens the log read-only (it never cuts, compacts or writes it, so it can run beside the server), creates DIR (which must not exist) and writes every stored, not retracted entry, superseded ones included, to `DIR////.txt`: ``` id: ID space: SPACE kind: KIND date: YYYY-MM-DD owner: OWNER supersedes: ID (only when set) superseded_by: ID (only when superseded) BODY (the stored bytes, unchanged) ``` It prints `brain-export: files N`; exit 0 ok, 2 DIR exists or cannot be made, 3 the log cannot be read or an entry cannot be a path (named on stderr), 4 write error. The output depends only on the stored entries, so the same log always gives the same tree. Importing every file of an unchanged export changes nothing, and a second export has the same tree hash (tests/brain/run.sh). A person corrects an entry by editing its file and posting it to `brain/import`: only the header lines `id`, `space` and `kind` and the body are read.