Skip to content

feat(memory): search on demand — owner route, agent door + MCP search_memory, search box (ent#1028) - #4114

Merged
vybe merged 13 commits into
devfrom
feature/1028-memory-search
Oct 31, 2026
Merged

vybe merged 13 commits into
devfrom
feature/1028-memory-search

Conversation

@trinity-ability

@trinity-ability trinity-ability commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-up to #4102 (stacked on feature/1022-retrieval-memory; retarget to dev once that lands). Recall injected the top facts and that was the only read path. The same store, ranking and scope rule are now a door the agent and the owner can open by hand.

  • Service: memory_service.search_records — recall_records without the prompt-block budget and past the recall tail (k ≤ 50), each record carrying the rendered line; every hit journaled as a search row whose candidate_text is the query, so the owner can see what an agent looked up.
  • Owner door: GET /api/agents/{name}/retrieval-memory/search?q=&k=&user_email= — person-only, scope by email like the facts list. Off or unavailable is a named refusal (422 memory_off, 503 memory_unavailable), never an empty answer that reads as "nothing matched"; 422 query_empty / invalid_email.
  • Agent door: POST /api/agents/{name}/retrieval-memory/search {execution_id, query, k} behind MCP search_memory. The scope is read off the execution row by the whose-memory rule (memory_subject.resolve): the person's scope on a person turn, the agent scope on a headless run, 422 memory_no_subject with the reason for an anonymous or group turn. An agent-scoped key may only search its own agent, checked first (ent#840); the route is in AGENT_CALLABLE_SELF.
  • MCP search_memory (tools/memory.ts, client, access.ts self-fence, tests): tells the agent the injected block is the top of this store and when a search is worth it; a refusal's code and message reach it.
  • UI: agent-settings/RetrievalMemorySearch.vue under the Memory toggle (Guardrails → Memory): search box, hits with the (date, source) line and relevance as a percent, one reserved footprint across idle / skeleton / hits / empty / failed, bounded list with its count, earlier hits kept on a failed re-search.

No schema change (search is a new value of the journal's op, a Python tuple, no CHECK).

Test Plan

  • tests/unit/test_ent1028_memory_search.py — 7 passed: service (past the recall tail, journaled with the query, scope-bound, empty when off), owner door (named 422s), agent door (agent scope on a headless run, the person's scope on a person turn with a matching fact in both scopes, refusals in order, k capped by the model). Real SQLite, hash embedder, the real can_user_access_agent.
  • Guards: test_2996_human_only_routes + runtime census, test_1310_auth_wiring, test_models_centralized, test_186, test_2094, ent#1022 ×2, ent#419, ent#637 — 487 passed, 1 pin retargeted (the router now declares its MCP surface).
  • MCP: npm test 1037 passed (tool-description budget included; search_memory 1507 of 2048 chars), tsc --noEmit clean.
  • Frontend: retrievalMemorySearch.spec.js 6 mounted cases; full npm run test:unit 426 files / 6597 passed (raw-colour, loading-gate, source-text ratchets); check:tokens OK.
  • Manual, both themes: Guardrails → Memory → type a query → watch the idle line become the list without the box moving.

Docs

Feature flow retrieval-memory.md (search subsection, API table, frontend, tests), architecture/api-endpoints.md, architecture/mcp-server.md, requirements core-agent.md (MEM-002 search bullet).

Fixes abilityai/trinity-enterprise#1028

Config keys and user docs (Product Quality Bar §11)

No new system_settings or env keys. The search surface rides the #4102 switch (trinity_memory_enabled) and the per-agent opt-out. User docs: #4118.

Review record

/review + /cso --diff ran on this branch (no critical findings; the informational ones landed in commit 3b5ac86ce: an owner's search no longer bumps the recall counter the cap-prune orders by, and a search that fails after the on/available gates is a 503 memory_unavailable on both doors rather than an empty answer). /validate-pr: approve once checks are green.

Deliberate deviations from the issue text: the journal row is op=search carrying the sanitized query text (not a hash) — the owner already sees the facts and the executions, and a readable query makes the journal useful; the two refusals are one memory_no_subject with a reason. Known gap (Product Quality Bar §7): the search box in Agent Settings searches the agent scope; a person's scope is searchable through the owner route's user_email and the agent door, not yet from the UI — it needs the per-person facts view (ent#962) to anchor it.

Ruled (operator, 2026-10-30) and landed in commit cfdfbd8d8: the agent door is agents-only. Any human — the owner included — gets 403 agent_only and is pointed at the owner door, which takes the scope explicitly and holds the owner line; a shared-with user can no longer read a person's scope by naming that person's run. The search box and the MCP tool are unaffected (each already used the right door). Recorded in the feature flow, the API catalog, the requirements and a learnings fragment.

🤖 Generated with Claude Code

trinity-ability and others added 6 commits October 29, 2026 23:36
… recalled into the prompt, default off (Abilityai/trinity-enterprise#1022)

Everything an agent does leaves extracted, deduplicated facts in the platform
DB, and the facts most relevant to the incoming request are put back in front
of it inside the ent#419 envelope as a third section. Runtime-agnostic by
construction: backend seams only, nothing in the agent container, no harness
hooks.

- ONE capture seam: `event_dispatch_service.spawn_task_terminal_event` (every
  CAS-won terminal), beside the pub/sub emit that returns early without a
  subscriber. The subject is read off the execution row by the write tool's
  "whose memory" rule, lifted into `services/memory_subject.py` and shared with
  `routers/public_memory.py`; the agent scope is an explicit trigger allowlist.
- Scopes: `(agent_name, user_email)`; `''` is the agent scope, which the
  agent's owner shares. Every other person has their own; recall never
  crosses scopes, and a run started by another agent or person never reads
  the shared scope.
- Extract + reconcile (ADD/UPDATE/DELETE/NONE) on the platform key through
  the one Anthropic call now shared with the summarizer; credentials redacted
  before extraction and before storage; every fact passes the ent#419 screen;
  reconcile ids outside the candidate's neighbour set are refused.
- Local ONNX embeddings (fastembed, multilingual MiniLM, 384-d) baked into the
  backend image under /opt/trinity/models, sha256-pinned, offline at runtime;
  warmed on a daemon thread, never built on a request. +~390 MB image,
  ~590 MB RSS per worker while the switch is on.
- Brakes: per-agent daily attempt budget, per-scope SingleFlightLock lease,
  per-process semaphore, 2,000-fact scope cap, partial unique index on the
  live text hash (both engines).
- Recall is async under a worker thread; usage counters make production the
  readout corpus for ent#634.
- Both migration tracks (SQLite + Alembic 0107/0108, guarded for a fresh PG);
  `agent_memory_facts` registered for cascade delete and rename.
- Routes under /api/agents/{name}/retrieval-memory (status self-fenced; opt-out,
  owner view and forget are person-only), GET /api/settings/memory (admin).
- Settings → General card and a per-agent Guardrails row, both honest about
  "off" and "unavailable — reason".
- Default off: `trinity_memory_enabled`; per-agent `memory_opt_out`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…er 0107_skill_sources_follow_bundled_pin so the version-line keeps one head (#2068)

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…d ranking, Haiku 5.5 (Abilityai/trinity-enterprise#1022)

Follow-up on PR #4102, all behind the same default-off switch.

Provenance. `agent_memory_fact_events` is an append-only journal: one row per
add / update / delete / none / screened / prune / recall / forget, keyed to the
execution that did it, with the candidate the extractor proposed, the text it
replaced and the neighbour ids the reconciler was shown. `agent_memory_facts`
gains `updated_by_execution_id` (the last run that rewrote or retired the row;
`execution_id` stays the run it was born in). Together they answer "where did
this fact come from and why does it read like this", and they are the corpus
the extraction prompt is tuned against. 90-day retention per agent at the next
retain. Owner route `GET /api/agents/{name}/retrieval-memory/events`
(fact_id / execution_id / op filters, owner + human-only). Both migration
tracks: SQLite `agent_memory_provenance`, Alembic `0110_agent_memory_provenance`;
cleanup parity via `AGENT_REFS`.

Dated lines. `recall` now returns what the prompt sees —
`(2026-10-21, scheduled run) …` — the fact's last revision date and the kind of
run it came from, so the model can weigh staleness; execution ids stay out of
the prompt. `recall_records` returns the records with relevance and score.

Ranking. `services/memory_ranking.py`, a leaf (numpy only): relevance (cosine)
gates at 0.30; recency `0.6 + 0.4 × 0.5^(age_days / half_life)` over
`updated_at` only re-orders the survivors. Half-life 30 days, operator knob
`trinity_memory_recency_half_life_days` (0 = plain cosine). Floor 0.6 is
gate / 0.5: a fact at cosine ≥ 0.5 never scores below the gate line at any
age, so a fresh weak match cannot overtake an old strong one, while the newer
wording of a superseded fact ranks first when the old wording matches ~1.2×
better. Chosen on a sweep over the dated dataset
`tests/unit/fixtures/ent1022_recency_dataset.json`: 0.7 failed the superseded
case, 0.5 would let the fresh weak match win. The reconcile neighbour search
passes no timestamps (plain cosine). `tests/unit/ent1022_recency_eval.py`
scores the dataset with recency on and off; it ran inside the rebuilt backend
image with `--network none` as uid 1000 and passed all seven queries.

Model. `anthropic_messages` pins `claude-haiku-5-5`, sends
`thinking: disabled` + `output_config.effort: low` (one-shot JSON extraction;
`max_tokens` stays the text budget) and reads the first TEXT block instead of
`content[0]`, which is a thinking block on this generation.

Tests: `test_ent1022_memory_provenance.py` (31) + the existing module (43),
74 passed with the real model where cached; the dataset case is skipped where
it is not.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…cs, production path (Abilityai/trinity-enterprise#1022)

A paid, by-hand eval of the two prompts, never collected by CI (no `test_`
prefix): 43 synthetic hand-labelled exchanges + 12 reconcile pairs in
`fixtures/ent1022_extraction_gold.json`, optionally plus a file of real
execution rows. It drives the production path unchanged — `build_transcript`
→ `_extract` → the screen, and `_reconcile`, through `anthropic_messages.complete`
with its real request body — and records the returned model and the spend.
A different model judges recall against the gold, grounding and worth of every
extracted fact, instruction/link/credential content and what was missed;
forbidden substrings and the screen are checked deterministically. Metrics are
atomic (recall, precision, specificity on expect-empty cases, leak fail-on-any,
format, hallucination, missed), with results.jsonl, per-case traces, an
errors sidecar that never scores a harness failure as zero, resume, and a
report. `MEMORY_EVAL_DRY_RUN=1` proves the harness end to end without a call
(117 cases incl. 74 real rows graded in 0.14 s; clamp, redaction and the
screen verified on the way through).

Not yet run against the model: no funded Anthropic key is available on this
machine (both local keys report "credit balance too low").

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…ccepts an OAuth token

Ran tests/unit/eval_ent1022_extraction_quality.py for real (Haiku 5.5 extractor,
Opus 5.5 judge, 43 gold + 74 real rows + 12 reconcile pairs). First prompt: gold
recall 100% / precision 88% / specificity 83%, real rows precision 89%. The two
systematic defects — the request restated as its own fact beside the outcome, and
routine no-op runs stored as facts — are addressed in the prompt (an attempt is
one entry; a run that found nothing new is not worth remembering; attribute
carefully; the agent-scope line no longer says "record what was asked").
Retrained on gold only: precision 98%, specificity 100%, recall held. Held-out
real rows: restated requests 13 → 4, transient 7 → 2, 12% fewer facts stored,
headline precision unchanged; the numbers and the open items are in the feature
flow.

The harness sends a Claude subscription OAuth token (sk-ant-oat…) as a Bearer
with the OAuth beta and the one-line identity system the gateway requires; the
prompt under test stays in the user message and the report names the auth shape.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…_memory, search box (trinity-enterprise#1028)

Recall injected the top facts and that was the only read path. The same store,
ranking and scope rule are now a door the agent and the owner can open by hand:

- `memory_service.search_records`: `recall_records` without the prompt-block
  budget and past the recall tail (k ≤ 50), each record carrying the rendered
  `line`; every hit journaled as a `search` row whose candidate_text is the
  query, so the owner can see what was looked up.
- `GET /api/agents/{name}/retrieval-memory/search` — the owner door
  (person-only, scope by email like the facts list; 422 query_empty /
  invalid_email / memory_off, 503 memory_unavailable — a named refusal, never
  an empty answer that reads as "nothing matched").
- `POST /api/agents/{name}/retrieval-memory/search` — the agent door behind
  MCP `search_memory`: the scope read off the execution row by the whose-memory
  rule (the person's scope on a person turn, the agent scope on a headless run,
  422 memory_no_subject with the reason otherwise); an agent key searches only
  its own agent, checked first (ent#840); listed in AGENT_CALLABLE_SELF.
- MCP `search_memory` (memory.ts, client, access policy, tests) tells the agent
  the injected block is the top of this store and when a search is worth it.
- `agent-settings/RetrievalMemorySearch.vue` under the Memory toggle: one
  reserved footprint across idle / skeleton / hits / empty / failed, bounded
  list, earlier hits kept on a failed re-search; a jsdom-mounted spec.

Tests: test_ent1028_memory_search.py (7, real SQLite + hash embedder, driven
at the service and both doors), memory.test.ts (+4), the route census,
retrievalMemorySearch.spec.js (6); full frontend unit 6597 green, MCP 1037
green. The ent#1022 header pin now asserts the declared surface.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@trinity-ability trinity-ability added the ui PR touches the frontend UI — triggers Playwright e2e tests label Oct 30, 2026
trinity-ability and others added 2 commits October 30, 2026 13:44
…r is a 503, not an empty answer (trinity-enterprise#1028)

/review findings on PR #4114: an owner typing in the search box bumped the recall counter the cap-prune orders by, sheltering whatever they searched for (now only a search inside an execution counts); a search that failed after the on/available gates returned 200 [] which the UI renders as 'Nothing matched' (now MemorySearchError → 503 memory_unavailable on both doors, exception class only). Router docstring and the journal op list name the two search routes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…o the owner door (trinity-enterprise#1028)

Operator ruling on PR #4114. The agent door derives its scope from the execution the caller names, and admitting human principals through assert_agent_access let anyone the agent is merely shared with read any person's facts by naming that person's run — the read the owner door refuses them. Now 403 agent_only for any human (the owner included; the GET door is theirs), the aauth_agent_only shape. Tests drive the door with the agent's own key and pin the refusal; feature flow, API catalog, requirements and a learnings fragment record the rule.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@vybe
vybe changed the base branch from feature/1022-retrieval-memory to dev October 31, 2026 00:33
Merged from the fork commit on #4102's branch so the squash does not echo as
add/add. The result's diff against dev is this PR's own delta.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@vybe

vybe commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

merge-train retargeted this PR to dev after #4102 landed, and pushed 50cc559a7, a merge of dev. The merge used the fork commit on #4102's branch as its base, so the diff against dev is exactly this PR's own 21 files. The only change it brings in from #4102's later commits is the looks_like_email hardening: [email protected]-shaped values and anything over 320 characters now get invalid_email from the search door.

@vybe

vybe commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

merge-train: this PR came off the train. It stays open and is retargeted to dev at 50cc559a7, and it rides the next train once fixed. Findings come from an independent /validate-pr + /review; the first was reproduced again over real HTTP.

Critical: the agent door reads another person's memory by naming their run. routers/agent_memory.py, search_retrieval_memory_agent_endpoint

  • The handler goes from db.get_execution(body.execution_id) to memory_subject.resolve(execution) with no viewer decision and no check that the run is live. The caller doesn't name an email, but choosing the execution_id chooses the scope.
  • Reproduced with a real agent key during a shared-with user's turn: GET /executions/{other person's run} returns 404, as ent#926 intends, while POST …/retrieval-memory/search with that run's id returns 200, scope=person, and the other person's fact.
  • This is the read the agents-only ruling meant to close: a shared-with user can get it by asking the agent.
  • This is also why regression diff is red: test_ent875_exec_control_routes::test_every_router_read_of_an_execution_row_has_a_viewer_decision names this handler. Don't clear it by adding the handler to READ_SITES. The fix is to bind the named run to the live turn. Plain row_is_viewers probably refuses a public visitor's own run (reasoned, not run), and concurrent turns need a design decision.
  • The other red test, test_subprocess_pgroup, passes locally and isn't touched here, so it looks like a flake.

Critical: unmet criterion, "every search is journaled". services/memory_service.py:333 (if picked:). A zero-hit search returns 200 and leaves 0 journal rows, so a fishing search is invisible to the owner. memory.ts and architecture/mcp-server.md both say every search is recorded. fact_id is nullable, so this needs no schema change.

Open question, blocked on a product ruling: should the search journal keep the readable query text for 90 days, as this PR does, rather than the query hash the issue's acceptance criteria specify?

Warnings, none blocking on their own

  • Nothing exercises the owner door over HTTP: changing OwnedAgentByName to AuthorizedAgentByName, or deleting the GET decorator, stays green.
  • scope reports person on the owner's own turn while the hits come from the agent scope.
  • Journal rows carry no actor.
  • A raw embedder error, including a file path, reaches the caller in the 503.
  • A first failed search shows "0 facts" beside the error.
  • Hits survive an agent switch at component level.
  • The PR body's /review and /cso record has no posted evidence and is contradicted by the first critical.

The write door has the same no-liveness shape (public_memory.py:79-84). It's already on dev, predates this PR, and deserves its own issue.

The failing reproduction is available from the merge-train run on request.

@vybe vybe added the status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815) label Oct 31, 2026
@vybe

vybe commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

Product ruling from the operator, given on the merge-train report, 2026-10-31: keep the readable query text in the search journal for 90 days, as the PR does, rather than the query hash in the acceptance criteria. The ruling lifts the hold on that question only. The agent-door leak and the zero-hit journaling gap still need fixing, so status-needs-fix stays.

trinity-ability and others added 2 commits October 30, 2026 18:35
…ry search is journaled (trinity-enterprise#1028)

An agent key could read another person's scope by naming that person's
FINISHED run — the read `GET /executions/{id}` refuses (ent#926). The named
run must now be `running`, and no other live turn on the agent may resolve to
a different scope (422 `memory_turn_not_live` / `memory_turn_ambiguous`; the
ledger is the fact, never the request). Both read sites are declared in the
ent#875 guard with that rule as their reason.

A search that matched nothing leaves one journal row with no fact, so a
fishing search is visible to the owner; an owner-door row carries the actor.
The answer's `scope` is the scope that answered (the owner's own turn is the
agent scope). The embedder 503 names the condition, not the loader's text.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…and starts over on an agent switch; the tool text names the live-turn rule

The failed face of the results region was falling into the list branch ("0
facts" beside the error). AgentDetail keeps the instance across agents, so a
switch clears the query, the hits and the error. `search_memory`'s description
says the execution_id must be the turn the agent is in and names the two new
refusals (1750 of 2048 chars); the feature flow, API catalog, MCP catalog and
requirements carry the rule.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@vybe

vybe commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

merge-train pushed the fixes for the two critical findings (the PR is authored by our own account, so there is no author to send it back to), in two commits:

  • b04e4c3ee — the agent door serves only the live turn, and every search is journaled. The named run must be running (422 memory_turn_not_live), and no other live turn on the agent may resolve to a different scope (422 memory_turn_ambiguous, the ent#926 ledger rule, fail-closed; an unreadable ledger counts as ambiguous). Both read sites are declared in the ent#875 guard with that rule as their reason, so the red regression diff is addressed by binding the read, not by exempting it. A zero-hit search leaves one journal row with no fact_id; an owner-door row carries the actor. Also from the warnings: the answer's scope says which scope answered (the owner's own turn is agent), and the embedder 503 names the condition instead of the loader's text.
  • ac05aedde — the search box shows no "0 facts" beside a first failed search and starts over on an agent switch; search_memory's description names the live-turn rule and both refusals (1750 of 2048 chars); feature flow, API catalog, MCP catalog and requirements updated.

Verified locally: test_ent1028_memory_search 15 passed (5 new), test_ent875_exec_control_routes + the auth/census/model guards 416 passed, frontend npm run test:unit 6599 passed (2 new specs), MCP npm test 1068 passed and tsc --noEmit clean.

Ruled by the operator (2026-10-31): the journal keeps the readable query text, recorded on ent#1028. The write door has the same no-liveness gap on dev; filed as #4121.

@vybe

vybe commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

merge-train: an independent review of the fix delta (50cc559a7..ac05aedde) found no critical findings and confirmed the leak is closed for every ordering it tried (a finished run, a live run of another person, queued/pending rows, an unreadable ledger, cross-agent ids). Three cosmetic notes left for a follow-up, not blocking: a live anonymous visitor on a busy public-link agent will make memory_turn_ambiguous common for that turn's duration (worth a sentence in the flow); the memory_turn_not_live message says "has finished" for a queued row too; the search box's agent-switch reset does not discard a response already in flight for the previous agent (a captured agentName check after the await would close it). Merging.

@vybe vybe removed the status-needs-fix PR has an unaddressed review/validation finding; cleared by the author's next push (#2815) label Oct 31, 2026

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

merge-train: Tier 1 green on ac05aed against dev; the fix delta independently reviewed with no critical findings.

@vybe
vybe merged commit 5355a6b into dev Oct 31, 2026
30 checks passed
vybe pushed a commit that referenced this pull request Oct 31, 2026
Six files overlapped with the memory-search PR, all additively: the router
and models carry both the extract-preview and the two search routes (the
`# mcp:` header from #4114 kept), the three docs carry both sections, and
`tests/registry.json` was rebuilt from the stages (dev's entries plus this
branch's one).

Co-Authored-By: Claude Fable 5.1 <[email protected]>
vybe pushed a commit that referenced this pull request Oct 31, 2026
…parsed extractor answer is a failure, not an empty preview

The in-flight step-aside resolved the PLATFORM's credential, so an agent the
operator flagged off the instance key was billed to it on a 429 (found by the
delta review). The fallback is the agent's own key arm now. `resolve` runs off
the event loop in `request` (its one-derivation read touches the cached Redis
snapshot). A 200 whose body is not a JSON array reports `unparsed`, and the
preview returns 502 for it instead of `facts: []`. The compatibility skip says
`no_api_key` only when a key is missing AND would be used. #4114's search
tests import the gateway, not the module it replaced.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
vybe pushed a commit that referenced this pull request Oct 31, 2026
…the agent, the model follows the credential (ent#1027) (#4115)

* feat(memory): retrieval memory — facts captured at the terminal seam, recalled into the prompt, default off (Abilityai/trinity-enterprise#1022)

Everything an agent does leaves extracted, deduplicated facts in the platform
DB, and the facts most relevant to the incoming request are put back in front
of it inside the ent#419 envelope as a third section. Runtime-agnostic by
construction: backend seams only, nothing in the agent container, no harness
hooks.

- ONE capture seam: `event_dispatch_service.spawn_task_terminal_event` (every
  CAS-won terminal), beside the pub/sub emit that returns early without a
  subscriber. The subject is read off the execution row by the write tool's
  "whose memory" rule, lifted into `services/memory_subject.py` and shared with
  `routers/public_memory.py`; the agent scope is an explicit trigger allowlist.
- Scopes: `(agent_name, user_email)`; `''` is the agent scope, which the
  agent's owner shares. Every other person has their own; recall never
  crosses scopes, and a run started by another agent or person never reads
  the shared scope.
- Extract + reconcile (ADD/UPDATE/DELETE/NONE) on the platform key through
  the one Anthropic call now shared with the summarizer; credentials redacted
  before extraction and before storage; every fact passes the ent#419 screen;
  reconcile ids outside the candidate's neighbour set are refused.
- Local ONNX embeddings (fastembed, multilingual MiniLM, 384-d) baked into the
  backend image under /opt/trinity/models, sha256-pinned, offline at runtime;
  warmed on a daemon thread, never built on a request. +~390 MB image,
  ~590 MB RSS per worker while the switch is on.
- Brakes: per-agent daily attempt budget, per-scope SingleFlightLock lease,
  per-process semaphore, 2,000-fact scope cap, partial unique index on the
  live text hash (both engines).
- Recall is async under a worker thread; usage counters make production the
  readout corpus for ent#634.
- Both migration tracks (SQLite + Alembic 0107/0108, guarded for a fresh PG);
  `agent_memory_facts` registered for cascade delete and rename.
- Routes under /api/agents/{name}/retrieval-memory (status self-fenced; opt-out,
  owner view and forget are person-only), GET /api/settings/memory (admin).
- Settings → General card and a per-agent Guardrails row, both honest about
  "off" and "unavailable — reason".
- Default off: `trinity_memory_enabled`; per-agent `memory_opt_out`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* feat(memory): provenance journal, dated recall lines, recency-weighted ranking, Haiku 5.5 (Abilityai/trinity-enterprise#1022)

Follow-up on PR #4102, all behind the same default-off switch.

Provenance. `agent_memory_fact_events` is an append-only journal: one row per
add / update / delete / none / screened / prune / recall / forget, keyed to the
execution that did it, with the candidate the extractor proposed, the text it
replaced and the neighbour ids the reconciler was shown. `agent_memory_facts`
gains `updated_by_execution_id` (the last run that rewrote or retired the row;
`execution_id` stays the run it was born in). Together they answer "where did
this fact come from and why does it read like this", and they are the corpus
the extraction prompt is tuned against. 90-day retention per agent at the next
retain. Owner route `GET /api/agents/{name}/retrieval-memory/events`
(fact_id / execution_id / op filters, owner + human-only). Both migration
tracks: SQLite `agent_memory_provenance`, Alembic `0110_agent_memory_provenance`;
cleanup parity via `AGENT_REFS`.

Dated lines. `recall` now returns what the prompt sees —
`(2026-10-21, scheduled run) …` — the fact's last revision date and the kind of
run it came from, so the model can weigh staleness; execution ids stay out of
the prompt. `recall_records` returns the records with relevance and score.

Ranking. `services/memory_ranking.py`, a leaf (numpy only): relevance (cosine)
gates at 0.30; recency `0.6 + 0.4 × 0.5^(age_days / half_life)` over
`updated_at` only re-orders the survivors. Half-life 30 days, operator knob
`trinity_memory_recency_half_life_days` (0 = plain cosine). Floor 0.6 is
gate / 0.5: a fact at cosine ≥ 0.5 never scores below the gate line at any
age, so a fresh weak match cannot overtake an old strong one, while the newer
wording of a superseded fact ranks first when the old wording matches ~1.2×
better. Chosen on a sweep over the dated dataset
`tests/unit/fixtures/ent1022_recency_dataset.json`: 0.7 failed the superseded
case, 0.5 would let the fresh weak match win. The reconcile neighbour search
passes no timestamps (plain cosine). `tests/unit/ent1022_recency_eval.py`
scores the dataset with recency on and off; it ran inside the rebuilt backend
image with `--network none` as uid 1000 and passed all seven queries.

Model. `anthropic_messages` pins `claude-haiku-5-5`, sends
`thinking: disabled` + `output_config.effort: low` (one-shot JSON extraction;
`max_tokens` stays the text budget) and reads the first TEXT block instead of
`content[0]`, which is a thinking block on this generation.

Tests: `test_ent1022_memory_provenance.py` (31) + the existing module (43),
74 passed with the real model where cached; the dataset case is skipped where
it is not.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* test(memory): extraction-quality eval — gold corpus, LLM-judged metrics, production path (Abilityai/trinity-enterprise#1022)

A paid, by-hand eval of the two prompts, never collected by CI (no `test_`
prefix): 43 synthetic hand-labelled exchanges + 12 reconcile pairs in
`fixtures/ent1022_extraction_gold.json`, optionally plus a file of real
execution rows. It drives the production path unchanged — `build_transcript`
→ `_extract` → the screen, and `_reconcile`, through `anthropic_messages.complete`
with its real request body — and records the returned model and the spend.
A different model judges recall against the gold, grounding and worth of every
extracted fact, instruction/link/credential content and what was missed;
forbidden substrings and the screen are checked deterministically. Metrics are
atomic (recall, precision, specificity on expect-empty cases, leak fail-on-any,
format, hallucination, missed), with results.jsonl, per-case traces, an
errors sidecar that never scores a harness failure as zero, resume, and a
report. `MEMORY_EVAL_DRY_RUN=1` proves the harness end to end without a call
(117 cases incl. 74 real rows graded in 0.14 s; clamp, redaction and the
screen verified on the way through).

Not yet run against the model: no funded Anthropic key is available on this
machine (both local keys report "credit balance too low").

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* feat(memory): extraction prompt tuned on the measured eval; harness accepts an OAuth token

Ran tests/unit/eval_ent1022_extraction_quality.py for real (Haiku 5.5 extractor,
Opus 5.5 judge, 43 gold + 74 real rows + 12 reconcile pairs). First prompt: gold
recall 100% / precision 88% / specificity 83%, real rows precision 89%. The two
systematic defects — the request restated as its own fact beside the outcome, and
routine no-op runs stored as facts — are addressed in the prompt (an attempt is
one entry; a run that found nothing new is not worth remembering; attribute
carefully; the agent-scope line no longer says "record what was asked").
Retrained on gold only: precision 98%, specificity 100%, recall held. Held-out
real rows: restated requests 13 → 4, transient 7 → 2, 12% fewer facts stored,
headline precision unchanged; the numbers and the open items are in the feature
flow.

The harness sends a Claude subscription OAuth token (sk-ant-oat…) as a Bearer
with the OAuth beta and the one-line identity system the gateway requires; the
prompt under test stays in the user message and the report names the auth shape.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* feat(memory): extraction runs on the agent's own runtime inside its container (trinity-enterprise#1027)

Retrieval memory needed the platform Anthropic key to capture anything, so on
a subscription-only install it silently remembered nothing. Who answers an
extraction or reconcile prompt is now one decision, `services/memory_model`:

- `agent`: the agent's own runtime, headless inside its container, through the
  new agent-server door `POST /api/runtime/complete` (`AgentRuntime.complete`:
  prompt on stdin, `--max-turns 1`, a minimal `--system-prompt`, no MCP servers,
  every tool denied, an empty cwd, the process in the registry, bounded
  concurrency; named refusals 503/429/502/504). Its subscription or key pays
  and the transcript never leaves the platform network. Claude Code implements
  it; Gemini and Codex answer `unsupported` for now.
- `platform`: the instance key through `anthropic_messages`, as before.
- `none`: nobody — the run is not captured and both status cards say why.

Knob `trinity_memory_extractor` (Settings → General, BaseSelect): `auto`
(default — the agent when running and not rate-limited, else the key; the only
mode that falls back mid-call), `agent`, `platform`. The per-agent row says
which extractor would answer next. `POST …/retrieval-memory/extract-preview`
(owner, person-only) runs one exchange through the real path and returns the
facts, the screened candidates and who answered, storing nothing — the owner's
prompt-tuning tool and the eval's `MEMORY_EVAL_VIA_BACKEND` path.

Not chosen: the backend calling the Messages API with the stored subscription
token. Measured 2026-10-30, the gateway serves a completion on a setup token
only when the request claims to be Claude Code; impersonation is not a seam.

Tests: test_ent1027_memory_model.py (22; plan matrix, the door's request and
fallback rules, capture through the agent with no platform key, status, the
preview door; 9 go red with the agent path disabled),
test_ent1027_runtime_complete.py (21; command shape, empty cwd, registry,
error mapping), retrievalMemoryPanel/Toggle specs (14 mounted), the ent#1022
status pin retargeted; 532 guard tests green, harness dry run green.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* feat(model): one model door for the backend — the credential follows the agent, the model follows the credential (trinity-enterprise#1027)

Rework of the first build on this branch, on a corrected measurement. On a
real subscription setup token, plain Bearer + the OAuth beta, `claude-haiku-4-5`
answers 200 while Haiku 5.5, Sonnet 4.6 / 5.5 and Opus 4.6 / 5.5 answer 429
`Error` unless the request claims to be Claude Code — a model-specific rule,
not "any backend call". Workspace thread titles had been running on exactly
that allowance in production. So the in-container door is dropped (agent
server back to base) and the real gap is closed: six backend model callers,
four request shapes, two auth strategies, no shared client.

`services/model_gateway` (replaces `anthropic_messages` and the first build's
`memory_model`):
- `resolve(agent_name)` — the credential follows the agent (#2766, #471's one
  derivation): an agent on a subscription runs on its own setup token, an
  api-key-mode agent or a job with no agent behind it on the platform key, an
  unreadable token never borrows the key. The model follows the credential:
  Haiku 4.5 on a subscription, Haiku 5.5 (thinking off, low effort) on the key;
  a caller's model override applies to the key only, and the backend never
  impersonates Claude Code.
- knob `trinity_model_credential`: `auto` (default — the only mode that falls
  back: a rate-limited or 429-answering subscription steps aside to the key),
  `subscription`, `platform_key`. One request shape, one error map, one usage
  log line per answered call.
- migrated: retrieval-memory extract/reconcile, the MEM-001 summarizer (its
  own model pin dropped), Workspace thread titles (`_resolve_title_auth` is the
  gateway's resolver, health record kept), the compatibility AI checks (now
  attributed to the agent under review).

Settings → General: the extractor select becomes the platform-wide credential
knob with subscription wording; the per-agent Memory row says "extracts on
subscription <name>" / "the platform key" / why nothing. The extract-preview
door returns `extractor`, `model`, `subscription`. The eval harness scores the
subscription shape with `MEMORY_EVAL_CREDENTIAL=subscription`.

Tests: test_ent1027_model_gateway.py (24: resolution incl. the #2766 rules
and the knob matrix, both request shapes, the 429 fallback in auto only, the
four callers through the door, status, preview); the title, summarizer and
compatibility suites retargeted to the gateway with their pins intact
(#2766's "never borrow the key" now asserted against the resolver); ent#1022
suites on the gateway; 978 passed across the touched suites + guards; harness
dry run green; frontend specs 42/42 with ratchets and tokens.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* feat(memory): refused text is never a fact; the prompt scored on the subscription shape (trinity-enterprise#1027)

Re-scored on Haiku 4.5 over plain Bearer + OAuth beta — what an agent on a
subscription extracts with now. The first pass stored the attacker's address
from the injection_in_response gold case inside a "flagged and did not act on
it" fact (Haiku 5.5 never did). The prompt now says text the agent refused,
flagged or ignored is not worth remembering at all — an interim "record at most
'flagged X'" wording produced meta-facts the judge rejected on two cases.
Final on the subscription shape: gold recall 100%, precision 92%, specificity
100%, format 100%, zero leaks; reconcile 10 of 12 (a negated UPDATE where a
DELETE was wanted, a NONE carrying an ignored id). The report names the
extractor's auth shape per credential kind.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* docs(model): the migrated callers' own docs describe the gateway path (trinity-enterprise#1027)

The compatibility flow, the MEM-001 summarizer steps and the thread-title health section still described their pre-gateway shape — a private httpx call on the platform key. They now name services/model_gateway and the credential-follows-the-agent rule, with the model each caller actually sends.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(model): a Credential never prints its token; the knob refuses a fourth word; the compatibility skip names the real reason (trinity-enterprise#1027)

/review + /cso --diff findings on PR #4115: the frozen dataclass's default repr carried 'secret' (now repr=False); 'trinity_model_credential' accepted any string and read it as auto (now a named 422 on the generic settings route); the compatibility checks reported no_api_key for a subscription agent whose token cannot be read, sending an admin to add a key that would not be used (now no_credential with the gateway's reason, and a panel line for it); the rate-limit read went through a getattr default that only test fakes needed; dead httpx imports in ai_checks and the title generator; the panel copy still described the dropped in-container door; the registry entry described the first build.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(model): the token is read before the rate limit, the limit is the one derivation, titles log usage, the preview names who answered (trinity-enterprise#1027)

Three merge-train findings. The rate-limit check ran before the token read,
so a limited subscription with an unreadable token borrowed the platform key
in `auto`; the token comes first now, whatever the limit says. "Rate-limited"
was the bare 2h failure-row predicate; it is now
`subscription_headroom_service.rate_limited_now_cached`, the one derivation
(#2157/#447) in which a fresh provider verdict wins both ways, so the gateway
agrees with the Subscriptions card. Thread titles leave the same usage line as
every other caller (`log_usage` after their own `send`).

Also: `use_platform_api_key = False` answers nobody (#471's key arm); an
upstream error body is scrubbed before it is logged; `request(report=)` says
who actually answered, so the owner's preview reports the key after a 429
fallback and a 502 `extractor_failed` on an upstream failure instead of
`facts: []`; the compatibility skip and the title health record name the
gateway's reason rather than sending an admin to add a key the agent would
not use; the eval harness reads `subscription`, not the dropped `runtime`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* docs(model): the knob is named for what it moves; the title notice quotes the cause; the flow carries the gate rules and the Gemini/Codex ruling

"Extraction runs on" understated a platform-wide knob that also moves titles,
summaries and the compatibility checks. The Workspace title notice quotes the
health record's reason instead of always saying "add a key". The feature flow,
API catalog and backend catalog carry the token-first rule, the one rate-limit
derivation, the `use_platform_api_key` arm, the preview's honest report, and
the operator's 2026-10-31 ruling (trinity-enterprise#1038) on the Gemini/Codex gap.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* test(model): pin the hand-offs the merge-train found unpinned

The compatibility report's `agent_name` to `run_ai`, the summarizer's and
reconcile's `agent_name` to the gateway, and the preview route's registration
behind `OwnedAgentByName` + `require_person`. Each goes red when its line is
deleted (checked by mutation before this commit).

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* test(model): the route pin compares its gates by name, not Depends identity (order-dependent under the full suite)

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* fix(model): the live 429 fallback honours use_platform_api_key; an unparsed extractor answer is a failure, not an empty preview

The in-flight step-aside resolved the PLATFORM's credential, so an agent the
operator flagged off the instance key was billed to it on a 429 (found by the
delta review). The fallback is the agent's own key arm now. `resolve` runs off
the event loop in `request` (its one-derivation read touches the cached Redis
snapshot). A 200 whose body is not a JSON array reports `unparsed`, and the
preview returns 502 for it instead of `facts: []`. The compatibility skip says
`no_api_key` only when a key is missing AND would be used. #4114's search
tests import the gateway, not the module it replaced.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

---------

Co-authored-by: trinity-ability <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
vybe pushed a commit that referenced this pull request Nov 6, 2026
…id in the Workspace (Abilityai/trinity-enterprise#962) (#4276)

## Summary
The UI half of the owner's view of a person's memory. It is stacked on #4275 and targets that PR's branch; GitHub retargets it to `dev` once #4275 merges.

- **Agent Settings → Guardrails → Memory → Person memory** lists everyone the agent keeps memory about. Each row shows the verified email, the channel identity an access request captured (shown as the channel reported it), counts and the last change. The list is bounded, with a stated total and Load more.
- **The person dialog** is a wide `BaseModal`:
  - Notes and Summary, shown as plain text (the summary carries its stated limit).
  - History, paged by cursor, with Undo on the latest write of each section behind `ConfirmDialog` (Cancel focused). After an Undo the list is re-read to the same length.
  - Facts: the person's retrieval-memory facts, each with a journal disclosure, Forget behind `ConfirmDialog`, and search scoped to the person. For the owner's own row, which is the agent scope, there's a pointer to the agent-scope search instead of a list.
  - One post-flush watcher moves focus back to Close when Undo or Forget disables or removes the control that had it.
- **The person's Workspace memory panel** gets Load more, in a bounded list.
  - Every change, conversation or scheduled run, shows the lines it added (`+`) and removed (`−`) against the version before. A rewrite that changed nothing reads "No change to the text".
  - The undoable change explains what Undo does.
  - A write someone else undid reads "Undone by an operator of this agent", without saying who.
- **Search row:** `RetrievalMemorySearch`'s Search button is now the normal size and stretches to the field's height, in both search boxes. The component also gains a `user-email` prop for the person scope.

## Changes
- **New:** `stores/personMemory.js`, `components/agent-settings/PersonMemorySection.vue`, `PersonMemoryModal.vue` and `utils/lineDiff.js` (a whole-line LCS).
- **Changed:** `GuardrailsPane.vue` (one mount), `RetrievalMemorySearch.vue`, `portal/PortalAgentMemory.vue` and `stores/clientPortal.js` (cursor paging, re-read to the shown length).
- **Docs:** `architecture/frontend.md`, `feature-flows/public-agent-links.md` and `retrieval-memory.md` (the #4102/#4114 deferral closed), the MEM-001 requirement, and the `/cso --diff` report for both PRs.

## Test Plan
- [x] `personMemory.mount.spec.js` (13 tests, mounted): the list's states, Undo and Forget behind the confirm, plain-text rendering, person-scoped search, the focus re-home, cursor paging, the owner's agent-scope row, the memory-off reason.
- [x] `portalAgentMemory.spec.js`: the operator line, Load more, re-read to the shown length, and the diff rows (first write, cleared notes, identical rewrite, scheduled run, undone row, the Undo explanation, screen-reader prefixes).
- [x] `memoryLineDiff.spec.js` (7 tests) and `retrievalMemorySearch.spec.js` (search row).
- [x] Reverting each guarded line in turn (9 of them) turns its test red: the focus watcher, the two confirms, notes rendered as markup, unscoped search, the operator line, the re-read length, the Undo explanation on every row, whitespace counted as a change.
- [x] The raw-colour, loading-gate, source-text and contrast ratchets pass, and `npm run check:tokens` is OK (101 specs).
- [x] Eyeballed on a local instance in light and dark mode, as owner and as the person, including the search row and the diff rows.

Part of Abilityai/trinity-enterprise#962 (closed by #4275 + this PR).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ui PR touches the frontend UI — triggers Playwright e2e tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants