Cortex¶
Over a few weeks the #growth channel settles some things. Churn is reported
monthly unless someone asks for weekly. The Team plan is the one under watch.
"Active" means a user who ran a report in the last 28 days. Then Carol opens a
new thread and asks what drove the Team churn?. Her session's board is
empty, and the bot still answers with the channel's definitions.
The board covers one conversation. Memory across conversations belongs to the app, and in the team bot each channel is an app.
The app on every request¶
Every event names the application that posted it with app_id. The bot posts
#growth messages as growth and #support messages as support. The app
isn't bound to the session: each event carries its own, and the session ids
stay global.
The host is the trust boundary. The bot authenticates with the API key and asserts the app, and the host passes it to the companion's request unchanged. It is stored on the request and on every turn the request writes, and it is never shown to the model. An application that wants separate memory for each of its users posts each user's events under an app id of their own.
The companion's routed request is where an agent could try to act for another
app. The host's /h2a relay looks up the parent request before it forwards
anything:
# src/mash/api/routes/h2a.py
identity = await store.get_request_identity(str(parent.get("request_id")))
if identity is None:
return h2a_error(400, "INVALID_PARENT", "parent request not found")
if identity.agent_id != caller:
return h2a_error(
403, "FORBIDDEN", f"parent request does not belong to agent '{caller}'"
)
for key in ("app_id", "policy_id", "policy"):
if key in body and body.get(key) != getattr(identity, key):
return h2a_error(
403, "FORBIDDEN", f"{key} must match the parent request's"
)
The routed request gets the app read from runtime_request, which records
each request's agent, app and policy from its accepted event. It works for the
same app as the companion request that started it.
Conversation search¶
Every hosted agent gets two runtime tools over its stored turns. Both read the app from the request, never from the model's arguments:
search_conversations(query, scope=)runs a keyword search over this agent's turns with Postgres full-text search. Scopesession, the default, covers the current session. Scopeappcovers every session of the app. It returns ranked previews with each turn's session and trace ids.get_full_turn_message(pairs)expands hits, given as session and trace id pairs, into the full turns.
A request with no app gets only scope session. In the team bot the analyst
can search its own answers across every #growth thread, and never a
#support thread. Previews are cheap to put in front of the model, so it
reads those first and pays for full text only on the turns it picks.
Cortex¶
Search finds what one agent said. Cortex is memory the app keeps: a profile every request sees and a set of entries every agent can search, built from every agent's turns in every session of the app.
It is off until the host asks for it:
host = (
HostBuilder()
.agent(AnalystAgent(), metadata=analyst_metadata)
.agent(ResearchAgent(), metadata=research_metadata)
.workflow(WEEKLY_METRICS)
.enable_cortex(profile_max_chars=4000)
.build()
)
enable_cortex() records CortexSettings on the host, registers the built-in
cortex-agent, and registers the cortex-build workflow. The companion
routes to neither; a build runs when the app starts one. Every agent process
imports the same build_host(), so each one sees the setting when it builds
its runtime.
Cortex lives in two tables:
cortex_app: one row per app with theprofile,built_through(thecreated_atof the newest turn the last build covered), aversionthat every write increases, andlast_build, the last build's run id and result.cortex_entry: the facts behind the profile. Each has atopic,content,origin(buildorapp) andsources, the agent, session and trace it came from.
What an agent sees¶
On a host with Cortex, the context load appends the app's profile to the system prompt:
# src/mash/runtime/engine/steps.py: load_request_context
cortex = runtime.get_cortex()
if cortex is not None and app_id:
# Recorded on mash.context_load.end with the rendered prompt, so a
# recovered request sees the profile the request originally saw.
system_prompt = append_context_block(
system_prompt, await cortex.profile_block(app_id)
)
The block opens with APP MEMORY and is capped at profile_max_chars, with a
[profile truncated] marker past it. An empty profile adds nothing.
Each request also gets search_cortex, a read-only tool over the app's
entries. An app_id the model puts in the arguments is ignored, and the
output does not include the app id. These reads run in the agent's process,
which holds the database credentials. The agent's code runs in the policy's
sandbox, which has no database access.
Everything in an app can read every conversation in it this way. Separate memory means separate apps.
Building it¶
Nothing writes Cortex when a request completes. A build runs when something starts it, under the app it builds:
curl -X POST http://127.0.0.1:8000/api/v1/workflow/cortex-build/run \
-H "Content-Type: application/json" \
-d '{"app_id": "growth", "policy_id": "growth", "input": {"limit": 200}}'
cortex-build is a three-step workflow:
flowchart LR
T[("memory_turns\nruntime_event_log")] --> C["collect\n(code)"]
U[("cortex_app\ncortex_entry")] --> C
C --> K{"new turns?"}
K -- no --> W["write\n(code)"]
K -- yes --> A["curate\ncortex-agent"] --> W
W -->|"one transaction,\nversion check"| U
collect loads the app's Cortex and its turns since built_through, across
every agent and session, oldest first. It leaves out workflow turns and failed
requests. In a thread those are the board's entries, each with the user's own
message and the reply of the agent that answered. For each turn it reads the
tools the turn ran from the event log, arguments from execute_tool.start and
results from execute_tool.end. It clips messages to 4000 characters,
arguments to 500 and results to 1000, keeps 20 tool calls per turn, and stops
adding turns at 60000 characters; the rest wait for the next run. Results of
search_cortex itself are dropped, so memory is never built from memory.
curate sends the bundle to cortex-agent, a tool-less agent whose
structured output is a new profile, a list of upserts and a list of
deletes. Its prompt tells it to keep facts the user stated or confirmed,
merge duplicates, delete build entries the new turns contradict, and cite each
entry's sources. With no new turns the step passes the bundle through and the
model never runs. Curate is a code step that submits one agent request, so it
can skip the model and carry the version collect read through to write.
write applies the result in one transaction:
# src/mash/agents/cortex/store.py: CortexStore.apply_build
if last_build.get("run_id") == run_id:
return dict(last_build["result"])
if int(row["version"]) != base_version:
raise CortexConflictError(
f"cortex for app '{app_id}' changed since the build read it"
)
The version check makes the build a compare-and-set. If the app edited its
Cortex while the model was curating, the run fails and a rerun starts from a
fresh read. The last_build check covers a write retried after its
transaction committed: it finds its own run id and returns the stored result.
The result reports turns_covered, entries_written, entries_deleted and
remaining. A caller reruns until remaining is 0. The team bot can run a
build when a thread goes quiet, or once a night per channel.
What the app controls¶
The app reads and changes its Cortex under /api/v1/cortex/apps/{app_id}:
| Route | Does |
|---|---|
GET /cortex/apps/{app_id} |
Profile, watermark, version, entry count |
GET /cortex/apps/{app_id}/entries |
Entries newest first, with q, origin, limit, after |
POST /cortex/apps/{app_id}/entries |
Create an entry from topic and content |
PATCH /cortex/apps/{app_id}/entries/{entry_id} |
Change an entry's topic or content |
DELETE /cortex/apps/{app_id}/entries/{entry_id} |
Delete one entry |
DELETE /cortex/apps/{app_id} |
Delete the app's whole Cortex |
An entry the app creates or edits gets origin: app and is pinned. The
curator sees pinned entries as fixed facts, and apply_build skips any upsert
or delete that targets one. The team bot can write "Active = ran a report in
the last 28 days" from its admin settings once, and no build changes it.
The profile has no route. Builds write it from the turns and the entries, pinned ones included, so the app shapes it by editing entries and running a build. Deletes are permanent for turns already built: the watermark is past them, so the next build does not learn the fact again from the same conversation. Deleting the whole Cortex removes the row and its watermark, and the next build starts from the app's first turn.
cortex-agent picks its provider like masher's agents, and
CORTEX_AGENT_<PROVIDER>_MODEL overrides the model.
The app decides what agents remember. The policy decides what they can touch, and that's the next post.
Next: Policies: Sandbox and Browser.