cortex
aien-dev/cortex
Brought by drakestapleton
| 1 | # Cortex wire contract (Omega Cortex = cortex-rs 0.1.0 on the wire) |
| 2 | |
| 3 | The Omega server answers every request of cortex-rs 0.1.0 with the same bytes, apart from the |
| 4 | `/health` runtime field (below). "Same" is defined and checked by the parity gate (spec/PARITY.md); |
| 5 | edge behaviour measured on the live binary, including every error text, is in |
| 6 | spec/ORACLE-OBSERVED.md. This file is the summary a client needs. |
| 7 | |
| 8 | ## Server |
| 9 | |
| 10 | ``` |
| 11 | cortex [--host 127.0.0.1] [--port 18080] --log PATH [--encoder-url URL] [--tokens FILE] |
| 12 | cortex-import SRC.db OUT.log |
| 13 | ``` |
| 14 | |
| 15 | - `--log PATH`: the append-only Cortex log (format: spec/BUILD-CONTRACT.md). It replaces cortex-rs |
| 16 | `--db-path`; the server refuses `--db-path` and tells you to import the SQLite store once with |
| 17 | `cortex-import`. The importer reads a cortex-rs database (main file plus WAL, read-only) and writes |
| 18 | a new log; take the source with `sqlite3 'file:DB?mode=ro' '.backup COPY'` first. |
| 19 | - `--encoder-url URL`: the embedding service used by recall, as in cortex-rs. When it does not answer, |
| 20 | recall runs on lexical and metadata scores only, like cortex-rs. |
| 21 | - Every write is appended and flushed before the 201 answer; after a crash the log replays up to the |
| 22 | last complete record and a torn tail is cut (checked by tests/load/run.sh with kill -9). |
| 23 | |
| 24 | ## Authentication |
| 25 | |
| 26 | - `/health`, `/status` and CORS preflights need no token. Every `/api/cortex/*` route needs |
| 27 | `Authorization: Bearer <token>`. |
| 28 | - The token is `CORTEX_TOKEN` from the environment; when unset or blank, `$HOME/.config/cortex/token`, |
| 29 | re-read on every request. No token configured: 503 |
| 30 | `{"error":"Service unavailable: Cortex authentication token unconfigured on host"}`. |
| 31 | Missing or wrong token: 401 `{"error":"Unauthorized: invalid or missing Cortex bearer token"}`. |
| 32 | The comparison is constant-time. |
| 33 | |
| 34 | ## Routes |
| 35 | |
| 36 | | method, path | input | success | |
| 37 | |---|---|---| |
| 38 | | GET `/health`, GET `/status` (HEAD too) | — | 200 `{"runtime":"native-arm64-omega","service":"cortex-rs","space":"atlas-memory","status":"ok","version":"0.1.0"}` | |
| 39 | | POST `/api/cortex/write` | JSON, `kind` = `entity` / `claim` / `retract` (fields below) | 201 `{"recorded":true,"receipt":{"id","operation","targetType","targetId","committedAt"}}` | |
| 40 | | 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":…}` | |
| 41 | | POST `/api/cortex/search` | JSON with the same fields | same as GET | |
| 42 | | 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":…}` | |
| 43 | | GET `/api/cortex/get` | `id` or `name`, optional `space` | 200 entity; 400 `Missing id or name parameter`; 404 `Entity not found` | |
| 44 | | POST `/api/cortex/traverse` | JSON `subjectId`, `space` | 200 `{"claims":[…]}` (claim keys sorted) | |
| 45 | | POST `/api/cortex/delete` | **Omega extension**, see below | 200 `{"deleted":N}` | |
| 46 | |
| 47 | Write inputs (camelCase): |
| 48 | - entity: `id`?, `space` (default `atlas-memory`), `entityType` (default `discovery`), |
| 49 | `canonicalName`, `content`, `aliases`, `metadata` (default `{}`), `confidence` (default 1.0), |
| 50 | `validFrom`?, `validTo`?, `externalId`?. An entity with the same `space` and `canonicalName` is |
| 51 | updated under its existing id and its revision increases; otherwise `id` (or a new UUID) is used. |
| 52 | - claim: `id`?, `space`, `subjectEntityId`, `predicate`, `objectEntityId`?, `literalValue`?, |
| 53 | `confidence`, `metadata`. |
| 54 | - retract: `targetType` (`entity` / `claim`), `targetId`, `reason`?. |
| 55 | |
| 56 | Entity objects: `id, spaceId, spaceSlug, entityType, canonicalName, content, aliases, metadata, |
| 57 | confidence, revision, retracted, validFrom, validTo, createdAt`. |
| 58 | |
| 59 | Search: the query, with double quotes removed, is matched as one FTS5 phrase (bm25 order); when that |
| 60 | gives nothing, a substring match on name or content follows (score 0.7); an empty query lists the |
| 61 | newest entities (score 0.4). Operators such as `OR`, `NOT` or `*` are not interpreted, which is what |
| 62 | the live binary does (spec/ORACLE-OBSERVED.md). |
| 63 | |
| 64 | Errors from body and query parsing are axum's: 400/422 with a text/plain message (415 without a JSON |
| 65 | content type, 413 above 2,097,152 bytes), byte-identical to cortex-rs (spec/ORACLE-OBSERVED.md). |
| 66 | |
| 67 | CORS: any OPTIONS answers 200 with `access-control-allow-methods: *` and |
| 68 | `access-control-allow-headers: *`; `access-control-allow-origin` is echoed only for |
| 69 | `http://127.0.0.1:18095` and `http://localhost:18095`. Every answer carries |
| 70 | `vary: origin, access-control-request-method, access-control-request-headers`. The live cortex-rs |
| 71 | binary also allowed two non-loopback origins; the Omega server does not. |
| 72 | |
| 73 | ## Differences from cortex-rs (intentional) |
| 74 | |
| 75 | 1. `/health` and `/status` report `"runtime":"native-arm64-omega"` (cortex-rs: `native-arm64-rust`). |
| 76 | The parity gate masks exactly this value. |
| 77 | 2. **POST `/api/cortex/delete`** (not in cortex-rs; not in the parity corpus). Hard delete for data |
| 78 | that must leave the disk, such as a visitor's "forget me": body `{"targetType":"entity", |
| 79 | "targetId":ID}` removes one entity, `{"space":SLUG}` removes a space with its entities and claims. |
| 80 | The answer is `{"deleted":N}` (live entities removed; 0 when nothing matched). The server then |
| 81 | rewrites the log with the current state only, so the deleted bytes are gone from the file. |
| 82 | Same authentication as the other routes. cortex-rs can only retract (the row stays on disk). |
| 83 | 3. **`--tokens FILE`** (not in cortex-rs). Extra tokens limited to some spaces, one |
| 84 | `TOKEN SPACE[,SPACE...]` per line (blank lines and `#` lines skipped). A scoped token may only |
| 85 | touch the spaces listed: a request naming another space, or naming none, gets 403 |
| 86 | `{"error":"Forbidden: token scope does not cover this space"}`. The main token keeps full access. |
| 87 | Without `--tokens` the server behaves exactly like cortex-rs. |
| 88 | 4. Loopback-only CORS origins (above). |
| 89 | 5. **Company Brain** (`/api/cortex/brain/*`, `--brain-export`; not in cortex-rs, not in the parity |
| 90 | corpus), below. The only change to a cortex-rs route: POST `/api/cortex/write` answers 409 |
| 91 | `{"error":"Brain entries are append-only: write them through /api/cortex/brain/write"}` for an |
| 92 | entity whose `entityType` starts with `brain.`, or whose id or (space, `canonicalName`) names a |
| 93 | stored Brain entry. Retract and hard delete work on Brain entries as on any entity. |
| 94 | |
| 95 | ## Company Brain (Omega extension) |
| 96 | |
| 97 | A memory that agents read before a task and write to after it, stored as ordinary entities in the |
| 98 | same append-only log and FTS index (om/brain.om). There is no second store and no second server. |
| 99 | |
| 100 | ### Entries |
| 101 | |
| 102 | An entry is atomic, dated and owned: `id` (A-Z a-z 0-9 `.` `_` `-`, not starting with `.`; unique in |
| 103 | its space), `space` (default `brain`), `kind` (`decision`, `rule`, `case`, `change`, or the |
| 104 | structured kinds `contract` and `party`), `date` (UTC calendar date `YYYY-MM-DD`, proleptic |
| 105 | Gregorian; default today in UTC), `owner` (non-empty text), `body` and an optional `supersedes` (the id |
| 106 | of a live entry of the same space). It is stored as one ENTITY record: `canonicalName` = id, |
| 107 | `entityType` = `brain.` + kind, `validFrom` = date, `content` = body, `metadata` = |
| 108 | `{"owner":O}` or `{"owner":O,"supersedes":S}`, confidence 1.0. Entries are never rewritten: a |
| 109 | correction is a new entry that supersedes the wrong one. The wrong one stays readable and its |
| 110 | `supersededBy` names the correction. An entry can be superseded once; the next correction |
| 111 | supersedes the newer entry. "Live" means stored, not retracted and not superseded. |
| 112 | |
| 113 | Entry object: `{"id","space","kind","date","owner","supersedes","supersededBy","retracted","body"}` |
| 114 | (`body` is null for a retracted entry). |
| 115 | |
| 116 | ### Routes |
| 117 | |
| 118 | All are POST with a JSON body, the same bearer token and space scopes as `/api/cortex/*`. Body |
| 119 | parsing errors are the same axum texts as the other routes (400/422 text/plain). Errors raised by |
| 120 | the Brain are JSON `{"error":TEXT}`: 404 unknown entry, 409 conflict (duplicate id, already |
| 121 | superseded, append-only guard), 422 invalid field, 413 query larger than the FTS replica, 500 answer |
| 122 | larger than the 16 MiB output buffer. |
| 123 | |
| 124 | | path | input | success | |
| 125 | |---|---|---| |
| 126 | | `/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) | |
| 127 | | `/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 | |
| 128 | | `/api/cortex/brain/get` | `id`, `space`? | 200 `{"entry":ENTRY}`, superseded and retracted entries included | |
| 129 | | `/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 `<id>-c<k>` (smallest k from 1 not in use) | |
| 130 | | `/api/cortex/brain/alerts` | `date`, `days`, `taxId`?, `space`? | 200 `{"space","date","days","alerts":[{"id","entryDate","owner","docType","registryId","dateKind","keyDate","daysLeft","parties":[{"taxId","counterparty"}]}]}` | |
| 131 | | `/api/cortex/brain/records` | `registryId`?, `taxId`?, `space`? | 200 `{"space","records":[{"confirmed","entry"}]}`: live contract records by entry date, then id | |
| 132 | | `/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 `<id>-c<k>` superseding the file's entry | |
| 133 | | `/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 | |
| 134 | |
| 135 | Read before: the task text is split into tokens (runs of letters, digits, `.` `_` `-` and bytes |
| 136 | 128..255), each token becomes a quoted FTS5 string, and the strings are joined with `OR`. The FTS |
| 137 | replica ranks the live entries of the space by bm25 (`score` = -bm25, higher is better). `citations` |
| 138 | lists the id and date of exactly the entries returned, in rank order: every cited id is a stored |
| 139 | entry, and an answer with no entry cites nothing. No language model is involved. Which entries are |
| 140 | superseded is kept in a live index: built from the log on the first request after a start, updated |
| 141 | by every Brain write, and rebuilt on the next request after any retract or hard delete. |
| 142 | |
| 143 | ### Structured records |
| 144 | |
| 145 | A `contract` or `party` body is one `key: value` per line (blank lines allowed), checked on write |
| 146 | (422 names the line): |
| 147 | - contract: exactly one `doc_type:` (`contract`, `amendment`, `extension`, `tender`, `call`, |
| 148 | `framework_agreement`); at most one `registry_id:`, `subject:` and `confirmed:` (`yes`/`no`); any |
| 149 | number of `party: TAXID`, `note:` and `date: KIND YYYY-MM-DD` lines with KIND `hard_expiry`, |
| 150 | `on_completion`, `submission_deadline`, `extension` or `start` (`date: on_completion -` records an |
| 151 | on-completion clause without a date). The key dates are a set: each line keeps its own kind. |
| 152 | - party: exactly one `name:`, one or more `tax_id:` lines (several tax IDs, one counterparty), `note:`. |
| 153 | |
| 154 | The human gate: a contract written through `brain/write` is stored with `confirmed: no` (a body |
| 155 | saying `confirmed: yes` is refused with 422). It becomes confirmed only by `brain/confirm` or by |
| 156 | importing a hand-corrected export file that says `confirmed: yes`; both write a superseding entry |
| 157 | owned by the person who confirmed. `registry_id` links tender, contract and amendment |
| 158 | (`records` with `registryId`); `taxId` filters match any tax ID of the same live party record. |
| 159 | |
| 160 | Alerts: every key date of a live, confirmed contract record whose kind is not `start` and that has |
| 161 | a date, with `date <= keyDate <= date + days` (integer day numbers since 1970-01-01, proleptic |
| 162 | Gregorian calendar; both ends included, so day `days` is in and day `days + 1` is out), ordered by |
| 163 | key date, record id and line. `daysLeft` = keyDate - date. Unconfirmed records never appear. |
| 164 | |
| 165 | ### Plain files |
| 166 | |
| 167 | ``` |
| 168 | cortex --log PATH --brain-export DIR |
| 169 | ``` |
| 170 | |
| 171 | opens the log read-only (it never cuts, compacts or writes it, so it can run beside the server), |
| 172 | creates DIR (which must not exist) and writes every stored, not retracted entry, superseded ones |
| 173 | included, to `DIR/<space>/<kind>/<date>/<id>.txt`: |
| 174 | |
| 175 | ``` |
| 176 | id: ID |
| 177 | space: SPACE |
| 178 | kind: KIND |
| 179 | date: YYYY-MM-DD |
| 180 | owner: OWNER |
| 181 | supersedes: ID (only when set) |
| 182 | superseded_by: ID (only when superseded) |
| 183 | |
| 184 | BODY (the stored bytes, unchanged) |
| 185 | ``` |
| 186 | |
| 187 | It prints `brain-export: files N`; exit 0 ok, 2 DIR exists or cannot be made, 3 the log cannot be |
| 188 | read or an entry cannot be a path (named on stderr), 4 write error. The output depends only on the |
| 189 | stored entries, so the same log always gives the same tree. Importing every file of an unchanged |
| 190 | export changes nothing, and a second export has the same tree hash (tests/brain/run.sh). A person |
| 191 | corrects an entry by editing its file and posting it to `brain/import`: only the header lines `id`, |
| 192 | `space` and `kind` and the body are read. |