Repository navigation
feat(model): one model door for the backend — the credential follows the agent, the model follows the credential (ent#1027) - #4115
Conversation
… 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]>
…ontainer (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]>
…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]>
…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]>
… (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]>
…built from the three stages)
…ory-agent-runtime
…ourth 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]>
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]>
|
merge-train: this PR came off the train despite green checks. merge-train retargeted it to Critical: an unreadable token borrows the platform key when the subscription is also rate-limited. Critical: unmet criterion, the rate-limit gate. Critical: unmet criterion, titles have no usage line. Open question, blocked on a product ruling: on a subscription-only install, should Gemini and Codex agents capture no memory, titles or summaries, as this PR ships, or is an in-container runtime door still owed for them? Warnings
Conflict to expect: this PR conflicts with #4114 in six files. A trial merge showed every hunk is additive, so keeping both sides resolves them, and #4114's |
|
Product ruling from the operator, 2026-10-31: ship the Gemini/Codex gap as is; follow-up filed as https://github.com/Abilityai/trinity-enterprise/issues/1038. The hold on that question is lifted. The three critical findings still need fixing before this merges; merge-train is taking them now, since the PR is authored by our own account. |
… 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]>
…otes 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]>
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]>
|
merge-train pushed the fixes for the three critical findings and the warnings (the PR is authored by our own account), in three commits:
Verified locally: Still open, not fixed here: the |
…entity (order-dependent under the full suite) Co-Authored-By: Claude Fable 5.1 <[email protected]>
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]>
…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]>
|
merge-train: |
Summary
Follow-up to #4102 (stacked on
feature/1022-retrieval-memory; retarget todevonce that lands). Retrieval memory needed the platform Anthropic key to capture anything, so a subscription-only install silently remembered nothing. The investigation found the wider gap: the backend had six model callers, four request shapes, two auth strategies and no shared client (the MEM-001 summarizer, the compatibility AI checks, retrieval memory, the Settings key test, the enterprise referee, and Workspace thread titles — the last already on the agent's subscription token). This PR makes one door and moves the platform callers onto it.Corrected measurement (the first build on this branch went the other way). On a real subscription setup token, plain Bearer + the OAuth beta:
claude-haiku-4-5-20251001ErrorThe rule is model-specific. Thread titles have been riding the Haiku 4.5 allowance in production. So the in-container door from the first commit is dropped (the agent server is byte-identical to base again) and the seam is built on the shipped precedent.
services/model_gateway(replacesanthropic_messagesand the first build'smemory_model):trinity_model_credential(Settings → General):auto(default, the only mode that falls back: a rate-limited or 429-answering subscription steps aside to the platform key),subscription,platform_key. One request shape, one error map, one bounded usage log line per answered call (purpose, kind, model, tokens, latency)._resolve_title_authis the gateway's resolver; the bug: Workspace thread titles use the instance Anthropic API key over the agent's own subscription #2766 health record and failure detail kept); the compatibility AI checks (now attributed to the agent under review). The enterprise referee keeps its own configured provider keys; the Settings key test is a credential check, not a model call.Surfaces: the Settings panel's select is now the platform-wide credential knob with subscription wording and honest status; the per-agent Memory row reads "extracts on subscription lilu-max" / "extracts on the platform key" / "nothing captured — ";
POST /api/agents/{name}/retrieval-memory/extract-preview(owner, person-only) runs one exchange through the real path and returns the facts, the screened candidates and who answered (extractor,model,subscription), storing nothing — the owner's prompt-tuning tool and the eval's live path. The harness scores the subscription shape withMEMORY_EVAL_CREDENTIAL=subscription.Side finding, not fixed here:
subscription_headroom_service.check_tokensends Haiku 5.5 on a setup token and reads the resulting 429 asrate_limitedfor a healthy token.No schema change (
trinity_model_credentialis a plain system setting).Test Plan
tests/unit/test_ent1027_model_gateway.py— 24 passed: resolution (a subscription agent uses its own token even when a key exists; an unreadable token never borrows the key in any mode; a rate-limited subscription steps aside inautoonly; the knob matrix; a db failure reads as nobody; the plan never carries the secret), the request (the platform-key one-shot shape; the plain subscription shape pinned to its model with the caller's override ignored; the 429 fallback inautoonly; failures as None; the first TEXT block; tools pass through), the four callers through the door (memory captures on the subscription with no platform key; the summarizer; titles following the agent with the health record ok; the compatibility checks), status on both cards, the preview door.test_2766_title_auth_follows_agent(now asserts "never borrow the key" against the gateway's resolver and that the gateway usesderive_auth_mode),test_3533,test_ent473,test_ent79(the pre-bug: Workspace thread titles use the instance Anthropic API key over the agent's own subscription #2766 precedence docstring corrected),test_3402,test_ent419,test_compatibility_checks, both ent#1022 suites.retrievalMemoryPanel.spec.js(+5) andretrievalMemoryToggle.spec.js(4) — 42/42 with the raw-colour, loading-gate and source-text ratchets;check:tokensOK.MEMORY_EVAL_CREDENTIAL=subscription, Opus 5.5 judge): the first pass stored the attacker's address from the injection gold case inside a "flagged and did not act on it" fact (Haiku 5.5 never did), so the prompt gained one rule — refused/flagged/ignored text is not worth remembering at all. Final on this shape: gold recall 100%, precision 92%, specificity 100%, format 100%, zero leaks; held-out real rows (before that rule) precision 84%, ungrounded 7%; reconcile 10/12 (a negated UPDATE where a DELETE was wanted, a NONE carrying an ignored id). Platform-key shape (Haiku 5.5) unchanged from feat(memory): retrieval memory — captured at the terminal seam, recalled into the prompt, default off (abilityai/trinity-enterprise#1022) #4102's numbers: gold 98% precision. The two are different extractors and are documented as separate baselines in the feature flow.Docs
Feature flow
retrieval-memory.md("Which credential", capture steps, API table, tests),architecture/backend.md(model_gateway.py— a new platform model call goes here, never a freshhttpxcall),architecture/api-endpoints.md(preview), requirementscore-agent.md(MEM-002 capture + which-credential bullets), learnings fragment2026-10-30-subscription-token-model-gate.md.Fixes abilityai/trinity-enterprise#1027
User docs
#4118 carries the
docs/user-docs/page for the credential setting (trinity_model_credential, named above) together with the two memory PRs.Review record
/review+/cso --diffran on this branch (no critical findings; the hardening items landed in commit3800a465e: aCredentialnever prints its token,trinity_model_credentialrefuses a fourth word with a named 422, the compatibility skip saysno_credentialwith the gateway's reason instead of sending an admin to add a key that would not be used, dead imports and the stale "inside its container" copy removed)./validate-pr: approve.Two choices stated as deliberate: thread titles call
model_gateway.senddirectly rather thanrequestso the title-health record keeps the upstream status and reason (no second 429 fallback, no usage log line — the title path has its own); the owner extract-preview door has no UI or MCP caller by design — its consumer is the eval harness's via-backend mode, and it stores nothing.🤖 Generated with Claude Code