Repository navigation
Description
Sub-issue of #2514.
Goal
A self-improvement loop for agents: Cortex watches what agents actually did, learns guidelines
that would have steered them better, and transparently injects those guidelines into future
trajectories — so agents get better over time without anyone editing a prompt by hand.
Three stages:
- Capture agent trajectories — what was sent, what came back, which tools were called, what succeeded or failed
- Learn guidelines — distil recurring failure and success patterns into instructions that steer the agent better
- Transparently insert those guidelines into future requests, without the agent's cooperation
This is one of the "smarts" that plugs into Cortex: the proxy already sits on every inference
request, already parses it, and already rewrites it. A learning loop is the natural next plugin.
Why Cortex is the right place
Cortex is the only component that sees every request across every agent and session on the
machine, decrypted and parsed, with no agent cooperation required. Three properties the loop needs:
- It already rewrites requests.
tool-pruneandcontext-guruboth mutate the outbound body
viaWritesRequestBody, and the pipeline explicitly supports chained writers, each seeing
pctx.Bodyas the previous left it. Guideline injection is the same mechanism - It already prices outcomes.
inference-parsersettles a cost record per request, so a
guideline's effect can be measured in cost and tokens, not just vibes - It is agent-agnostic. Claude Code, Bob, OpenCode and anything else speaking a parsed protocol
benefit without per-agent integration
Stage 1 is mostly built — do not rebuild it
core/session/archive is already a trajectory store. Per-session zstd-compressed JSONL
segments, named by the time they opened, with:
replay.go—ReplaySince(cutoff, fn)walks every archived event at or after a cutoff, skipping
tunnel rows, stamped with the session's current id. This is the training-set readerretention.go,clear.go,delete.go— retention policy, so a learning corpus does not grow foreverformat.go,meta.go,prior.go— the on-disk contract and session metadata
Plus core/session has history.go, fold.go, title.go and agent.go; cortex#901 ✅ persists
sessions across restarts, and cortex#949/#950 ✅ differentiate concurrent sessions and aggregate per
session and model.
So stage 1 is largely a question of whether the archive captures the right fields for learning
(tool outcomes, errors, retries, user corrections), not whether capture exists. Start by reading
the archive format and naming what is missing.
Stage 2 — the hard part
Learning guidelines from trajectories is the genuinely open research, and the issue should not
pretend otherwise. Available in-tree:
core/llmclient— an OpenAI-compatible chat-completions client with JSON-from-prose
extraction, built for exactly this ("policy judges, content scorers, intent matchers"). Its
in-tree reference consumer is IBAC'sjudge.go, which already runs an LLM judge over
outbound traffic — the closest existing precedent for an LLM-in-the-loop plugincore/redact— relevant because a learning corpus is a retained corpus
Open questions worth settling before code:
- What is a guideline? A text snippet appended to the system prompt, a structured rule, a
few-shot example, or a tool-selection hint? This determines everything downstream - What signal says "better"? Task success is not observable from the proxy. Proxy-visible proxies
exist — error rates, retry loops, tool-call churn, cost per session, user corrections mid-session —
but each is indirect, and picking one is a research decision, not an implementation detail - Where does learning run? Inline per request is too slow; a batch job over the archive is the
obvious shape and fitsReplaySince's "startup, before any listener" contract - Per-user, per-project, or shared? A guideline learned from one developer's trajectories may be
wrong for another, and sharing them is an export of decrypted traffic (see below) - How are bad guidelines rolled back? A learned instruction that makes the agent worse must be
detectable and revertible. This argues for shadow evaluation before enforcement — the shape
cortex#1021 already proposes for model comparison
Stage 3 — injection, with an honest reading of "transparently"
Mechanically straightforward: a WritesRequestBody plugin chained with tool-prune and
context-guru, declaring RequiresAny: ["inference-parser"] as context-guru does.
But "transparently" cuts two ways, and this is worth deciding deliberately rather than
inheriting. Transparent to the agent is the point — no cooperation needed. Transparent to the
user is a different claim: a proxy silently editing the instructions an agent receives changes its
behaviour in ways the user did not author and cannot see. Cortex's pitch is transparency, so a
hidden steering layer is in tension with the product's own argument.
A defensible position: injection is visible and inspectable (agentop shows which guidelines
were applied to a session), opt-in, and revertible. Invisible-by-default would be the wrong
default for this specific tool.
Prior art to build on: altk-evolve
AgentToolkit/altk-evolve already implements
stages 2 and 3. Apache-2.0, Python, active (132 stars, pushed 2026-10-23). It describes itself as
"a system designed to help agents improve over time by learning from their trajectories," and its
reported result is +8.9 points overall on AppWorld, with a 74% relative increase on hard
multi-step tasks.
It should be evaluated before we write a learning loop of our own. The parts that map onto this
issue:
| Our stage | altk-evolve |
|---|---|
| 2 — learn guidelines | save_trajectory(trajectory_data, task_id, owner_id) — saves a trajectory and generates new guidelines. Also ingests via Phoenix trace observability (creation_mode: auto-phoenix) |
| 3 — retrieve for a task | get_relevant_guidelines(task, top_k, core_support) — "the always-on guideline core plus a task-relevant dosage"; get_entities(task, entity_type="guideline"); get_guidelines_with_attribution(task) returns the entity IDs behind the prompt |
Three things it answers that §"Stage 2 — the hard part" lists as open:
- Guidelines do not blindly accumulate. "Conflict Resolution" updates prior guidelines when new
information contradicts them, via LLM-based adjudication — our rollback question in a different form - Provenance is stamped per entity —
creation_mode(auto-phoenix/auto-mcp/manual) and
source_task_id. That is most of whatagentopwould need to show why a guideline applied - Attribution is a first-class call, so "which guidelines shaped this request" is answerable
rather than reconstructed
Retrieval quality is backend-dependent: the filesystem default does plain text matching, while
pgvector or milvus extras enable semantic vector search. Retention policies, publish/unpublish
sharing and user facts are also already there.
What adopting it would and would not settle
Would settle: the guideline representation, generation, conflict resolution, retrieval and
attribution — i.e. the research-shaped half.
Would not settle, and these are the real integration questions:
- Cortex is Go; altk-evolve is Python ≥ 3.12. So this is an out-of-process dependency, not a
linked library. It ships an MCP server (evolve-mcp, stdio or--transport sse --port 8201) and
a REST API, which is the plausible seam — the Cortex plugin becomes a thin client, and the
packaging concern in §"Work" shrinks from "16 MiB of Go deps" to "an optional sidecar." That is a
materially better story for build profiles (cortex#721) - Its local API has no authentication — the README says plainly that "any local process can read
and change memories through it." A guideline store is a steering surface, so on a shared or remote
Cortex (epic: Remote Cortex — running Cortex in remote locations #2651, Multi-tenant support for Cortex #2652) that is a privilege-escalation path, not a minor gap.--no-dashboard/
EVOLVE_DASHBOARD=falsereduces the surface - Trajectory format.
save_trajectorytakes a string and the schema is not specified in the
README. The mapping fromcore/session/archive's JSONL events to whatever it expects is unspecified
work, and it is what §"Work"'s first item should measure itself against - Its Lite mode slots directly into Claude Code, Codex and IBM Bob, in-agent — which is a
competing integration path to ours, not a complementary one. Worth being explicit: if Lite mode
already gives our users most of the benefit without Cortex, the argument for a Cortex plugin is
the agent-agnostic, no-cooperation-required part, plus cost measurement. That argument should be
made deliberately rather than assumed - Known rough edges it acknowledges: Phase 1C REST endpoints and UI sharing controls not yet
implemented; MCP cancellation checkpoints provide no rollback
Suggested first step
A spike, not a design: point evolve-mcp at a real core/session/archive corpus, see whether
the generated guidelines are any good on our traffic, and measure the injection effect in cost
(the Pillar 1 metric). That answers "is this the right engine" far cheaper than specifying one.
Gating and provenance (from #2653's review)
Two constraints raised by @jimy-r (comment) that the stages above did not cover. Both are adopted.
Never adopt a guideline without a gate
Stage 3 as first written adopts whatever stage 2 learns. That is the wrong default: a learned
instruction that makes the agent worse would steer every subsequent session, and nothing in the loop
would notice.
Cortex already holds the gate's inputs. inference-parser settles a cost record per request, so
a candidate guideline can be injected on a fraction of sessions and adopted only when it beats the
baseline on cost and on an outcome signal — shadow first, adopt second. This is the same shape
cortex#1021 proposes for model comparison, now applied to the accept/reject step rather than only to
evaluation.
Microsoft Research's SkillOpt (arXiv:2605.23904) is the
closest published precedent for treating a skill document as trainable state. Its gate is
deliberately strict — a candidate is accepted "only when its selection-split score is strictly
greater than the current selection score, so ties are rejected and the deployed skill never silently
drifts" — and its ablations conclude that "held-out gating prevents harmful proposals from
accumulating." Worth reading before designing ours.
Note on a figure circulating with this argument: a collapse from 0.554 to 0.026 under an ungated
loop is not in that paper. We checked the full text — the strings0.554,0.026,52.8,
"ungated" and "degenerate" do not occur, and there is no ungated-vs-gated ablation (the component
ablations vary the edit budget, rejected-edit buffer and slow/meta update, never the gate). The
largest degradation reported is SpreadsheetBench 77.5 → 55.0 from removing metaskill + slow update,
and the only gate remark is counterfactual: "without the gate, a stronger optimizer could just as
easily push larger but harmful rewrites." Cite the paper for the mechanism, not that number.
Treat the guideline store as untrusted
Trajectories contain tool output, fetched web pages included. So a guideline distilled from a
trajectory can carry attacker-authored text, and injection into future requests makes that text
persistent — one poisoned page read once could steer every later session on the machine. This is a
prompt-injection-to-persistence path, and it is the most serious security property of the whole
design.
It compounds the altk-evolve finding above: that store's local REST API has no authentication,
so on a shared or remote Cortex (#2651, #2652) the guideline store is a steering surface any local
process can write.
Mitigations to design in from the start, not retrofit:
- A guideline is untrusted until accepted by a reviewer or a held-out check
- Provenance per guideline — which trajectory, which session, which tool output it derived from
(altk-evolvealready stampssource_task_idandcreation_mode) - Treat tool-output-derived content as lower-trust than model-authored reasoning when distilling
core/redacton the corpus, and a documented answer to "what happens when a guideline turns out
to be poisoned"
Where this sits relative to context-guru
context-guru compacts context to cut cost. This plugin adds context to improve behaviour.
They are opposites on the same hop and will chain, so they need to agree: a guideline that
context-guru then compacts away has no effect, and guideline tokens are a cost context-guru is
trying to remove. Worth coordinating from the start — see also cortex#1417 on attributing savings
when multiple rewriting plugins share a request.
Work
- Gate adoption: shadow a candidate guideline on a fraction of sessions, adopt only on measured improvement (cost + outcome signal); ties rejected
- Treat the guideline store as untrusted — provenance per entry, reviewer or held-out acceptance, and a poisoned-guideline response path
- Evaluate
altk-evolveagainst a real archive corpus before building anything (see above) — decide adopt / adapt / build - Audit
core/session/archiveagainst what learning needs; name the missing fields (tool outcomes, errors, retries, user corrections) - Define "guideline" — representation, scope, lifetime
- Choose the improvement signal from proxy-visible evidence, and state its limits
- Offline learning job over
ReplaySince, usingcore/llmclient(IBAC'sjudge.goas the pattern) - Injection plugin —
WritesRequestBody, chained after context-guru,RequiresAny: ["inference-parser"] - Shadow evaluation before enforcement — measure a guideline's effect before it steers anything (cortex#1021's shape)
- Rollback for guidelines that make things worse
- Visibility in
agentop— which guidelines applied to this session, and why - Packaging decision — this will be heavy (LLM client, corpus, learning job). Note
context-guruandsession-budgetare deliberately in no build profile for exactly this reason (~16 MiB and ~6 MiB of dependencies); see cortex#721 on the bloat-vs-variant tradeoff - Privacy position — a retained learning corpus is decrypted agent traffic at rest. Align with cortex#1321 before anything leaves the machine;
core/redactis the existing tool - Docs: what is learned, from what, how to inspect it, and how to turn it off
Related
- epic: Cortex Local — cost reduction, observability, and stability #2514 — the Cortex Local epic; this is a new "smarts" plugin in Pillar 1/2 territory
- Cortex Local: Context Guru integration with Cortex #2649 — Context Guru integration; the opposite rewrite on the same hop, and the plugin to coordinate with
- cortex#1417 — attributing savings across multiple rewriting plugins
- cortex#1021 — shadow a request against a second model; the evaluation shape this should reuse
- cortex#1321 — the privacy research that gates any corpus leaving the machine
- cortex#721 — plugin architecture: static linking and the bloat-vs-variant tradeoff
core/plugins/contextguruandcore/plugins/ibac/judge.go— the two in-tree precedents- SkillOpt (arXiv:2605.23904) — skill-as-trainable-state with a strict held-out gate; the precedent for the accept/reject step
- AgentToolkit/altk-evolve — Apache-2.0 implementation of stages 2 and 3; evaluate before building
Assisted-By: Claude (Anthropic AI) [email protected]
Metadata
Metadata
Labels
Type
Projects
- StatusShow more project fieldsNew/ToDo
Activity
jimy-r commentedon Oct 24, 2026
One design point before stage 3, because it decides whether this loop helps or harms. As written, stage 3 adopts every learned guideline, and an ungated loop has a measured failure mode. In Microsoft Research's SkillOpt work (arXiv:2605.23904), an ungated self-edit loop on a weak model with a degraded signal collapsed from 0.554 to 0.026 by learning a degenerate answer, while the gated twin rejected each bad edit and stayed flat. That was a single seed, but the lesson transfers.
Cortex already holds the gate's inputs.
inference-parsersettles a cost record per request, so a candidate guideline can be injected on a fraction of sessions and adopted only when it beats the baseline on cost and on an outcome signal.The second risk is provenance. Trajectories contain tool output, fetched web pages included, so a distilled guideline can carry injected text into every future request on the machine. I'd treat the guideline store as untrusted until a reviewer or a held-out check accepts each entry.
I keep this as A skill is editable weights in a reference architecture I maintain.
Drafted with Claude Code and reviewed by me before posting.
mrsabath commentedon Oct 26, 2026
Thanks @jimy-r — both design points land, and I've folded them into the issue.
Gating before adoption. Agreed, and your observation that Cortex already holds the gate's inputs is the useful part:
inference-parsersettles a cost record per request, so a candidate guideline can run on a fraction of sessions and be adopted only if it beats baseline. The issue already pointed at cortex#1021 (shadow a request against a second model) for the evaluation shape; your framing makes the accept/reject step explicit rather than implied, which is the bit that was missing.Provenance, which I think is the stronger of the two. Trajectories contain tool output — fetched pages included — so a distilled guideline can carry injected text into every future request on the machine. That is a prompt-injection-to-persistence path, and the issue did not cover it. It also compounds something we'd already flagged about
altk-evolve: its local REST API has no authentication ("any local process can read and change memories through it"), so on a shared or remote Cortex the guideline store is a steering surface anyone local can write. Treating store entries as untrusted until a reviewer or held-out check accepts them is the right default.One correction on the citation, since the issue will be read as a design record.
I pulled SkillOpt (arXiv:2605.23904) and searched the full text. What it supports is the mechanism: the validation gate is strict — a candidate is accepted "only when its selection-split score is strictly greater than the current selection score, so ties are rejected and the deployed skill never silently drifts" — and the ablations conclude that "held-out gating prevents harmful proposals from accumulating." That is the load-bearing claim and it holds.
The specific collapse figures don't appear in the paper.
0.554,0.026and52.8have no occurrences, nor do "ungated" or "degenerate", and there is no ungated-vs-gated ablation: the component ablations vary the edit budget, the rejected-edit buffer and the slow/meta update, never the gate itself. The largest degradation reported is SpreadsheetBench 77.5 → 55.0 from removing metaskill + slow update. The only gate remark is counterfactual: "without the gate, a stronger optimizer could just as easily push larger but harmful rewrites." I see your own PATTERNS.md flags that number as single-seed, so this may be a provenance drift rather than a misreading — but we'll cite the paper for the mechanism and leave the figure out.Doesn't change the conclusion: an ungated self-edit loop is a bad idea on argument alone, and the paper's own design is the evidence that its authors agree. Credited in the issue.
jimy-r commentedon Nov 1, 2026
You're right, and thanks for checking the full text. I attached the figure to the wrong source. It isn't in the paper. It comes from the SkillOpt repo's results doc for SkillOpt-Sleep, the deployment companion: GPT-5.4-nano on SearchQA with a single-sample reflection signal, no gate 0.554 to 0.026, with gate 0.570 to 0.570.
https://github.com/microsoft/SkillOpt/blob/7bca588b0f4cbcc3b13d8a4d8bfc845afade269b/docs/sleep/RESULTS.md
That also explains why you found no gate ablation in the paper. Citing the paper for the mechanism is the right call for a design record. If the issue ever needs the number, that doc is where it lives. I'm fixing the same attribution in my pattern page.
Drafted with Claude Code and reviewed by me before posting.
feat: Add the evolve plugin, which learns guidelines from coding-agen…