Skip to content

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

Merged
vybe merged 9 commits into
devfrom
feature/1022-retrieval-memory
Oct 31, 2026
Merged

vybe merged 9 commits into
devfrom
feature/1022-retrieval-memory

Conversation

@trinity-ability

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

Copy link
Copy Markdown
Contributor

Summary

  • Everything an agent does leaves extracted, deduplicated facts in the platform DB (agent_memory_facts); the facts most relevant to the incoming request are recalled into the system prompt inside the ent#419 envelope as a third section. Default off (trinity_memory_enabled, Settings → General), per-agent opt-out, fail-open everywhere.
  • Runtime-agnostic by construction: backend seams only — nothing in the agent container, no Claude Code hooks — so Claude Code, Gemini CLI and Codex agents get it identically.
  • One capture seam: event_dispatch_service.spawn_task_terminal_event, beside the pub/sub emit (which 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 services/anthropic_messages.complete, now shared with the MEM-001 summarizer. Credentials redacted before extraction and before storage; every fact passes the ent#419 screen; reconcile ids outside a candidate's neighbour set are refused.
  • Local ONNX embeddings (fastembed, paraphrase-multilingual-MiniLM-L12-v2, 384-d) baked into the backend image under /opt/trinity/models, sha256-pinned, HF_HUB_OFFLINE=1; warmed on a daemon thread, never built on a request.
  • 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).

Replaces the issue's "mem0 OSS" wording per the /autoplan readout on the issue (per-process stores vs two workers, torch weight, PostHog telemetry, graph removed from OSS). Both independent reviews endorsed the thin store behind the same port.

Changes

  • Backend: services/memory_service.py (port), memory_subject.py, memory_embeddings.py, anthropic_messages.py; db/memory_facts.py, db/agent_settings/memory.py; routers/agent_memory.py (# mcp: none), routers/settings/flags.py (GET /api/settings/memory); seams in event_dispatch_service.py, task_execution_service.py, public_chat_service.py, message_router.py, client_portal/service.py, schedule_seat_memory.py + routers/internal.py; user_memory_guard.envelope(retrieved=…, agent_scope=…) + copy-back normaliser; platform_prompt_service.format_user_memory_block(retrieved=) / format_agent_memory_block.
  • Schema: agent_memory_facts + agent_ownership.memory_opt_out on both tracks (SQLite migrations + Alembic 0107/0108, guarded for a fresh PG), BLOB → BYTEA in the PG DDL rewriter, cascade/rename registration in db/agent_cleanup.py.
  • Image: fastembed/onnxruntime/numpy/tokenizers/huggingface-hub pinned (mirrored in tests/requirements-test.txt), model bake with hash check.
  • Frontend: settings/RetrievalMemoryPanel.vue (Settings → General), agent-settings/RetrievalMemoryToggle.vue (Guardrails → Memory), both honest about "off" / "unavailable — reason".
  • Docs: feature-flows/retrieval-memory.md, requirements core-agent.md (MEM-002), architecture backend.md / database.md / api-endpoints.md, a learnings fragment.
  • Tests: tests/unit/test_ent1022_retrieval_memory.py (48), src/frontend/tests/unit/retrievalMemoryPanel.spec.js (5, mounted); _route_census.py entry for the self-fenced status read; test_1028_settings_package.py pin for the new settings route; the ent#695 create-mode golden regenerated for the new column only (diff = memory_opt_out + the regeneration note).

Measured

backend image 1.12 GB → 1.51 GB
model load, offline, --network none, uid 1000 0.8 s
RSS added per worker once loaded ~590 MB (the multilingual vocabulary; lazy, only while the switch is on)
recall calibration (real model) relevant 0.43–0.70, unrelated ≤ 0.15 → threshold 0.30; near-duplicates 0.67–0.95 → reconcile at 0.60

Test Plan

  • cd tests && pytest unit/test_ent1022_retrieval_memory.py -p no:randomly — 47 passed, 1 skipped (real-model check runs where the model is cached)
  • Full unit island: 30,820 passed; 2 failed — test_1920 (fixed: lease moved onto SingleFlightLock, now green) and test_1310…avatar.generate_default_avatars, which fails identically on clean origin/dev (host /data is read-only)
  • npm run test:unit — 417 files, 6,504 tests passed (raw-colour, loading-gate and source-text ratchets included)
  • check_alembic_heads.py — one head (0110; the branch merged dev and re-chained its revisions after dev's 0107_skill_sources_follow_bundled_pin)
  • check_alembic_parity.py origin/dev HEAD — PASS; check_sqlite_upgrade_parity.py origin/dev HEAD — PASS (3 migrations newly recorded on upgrade)
  • pytest unit/test_ent1022_memory_provenance.py unit/test_ent1022_retrieval_memory.py — 74 passed with the real model cached (2 skipped where it is not); test_ent419_memory_poisoning_gates.py + the auth/route/schema guard set — 727 passed, the one pre-existing avatar failure aside
  • tests/unit/ent1022_recency_eval.py inside the rebuilt backend image, --network none, uid 1000, model from /opt/trinity/models — all 7 dated queries pass with the shipped half-life and floor
  • Real backend image built; the ONNX hash check passed; embedder loads and ranks a Ukrainian query against an English fact inside the image with networking disabled
  • Manual: Settings → General → Retrieval memory → on; run a schedule twice; the second run's prompt carries ## What you remember from earlier work
  • Extraction quality, measured (eval_ent1022_extraction_quality.py, Haiku 5.5 extractor, Opus 5.5 judge, 43 gold + 74 real rows + 12 reconcile pairs, ±9 pt noise floor): gold recall 100% / precision 98% / specificity 100% / 0 leaks after one prompt iteration (was 88% / 83%); held-out real rows precision 89%, restated-request facts 13 → 4, transient 7 → 2, 12% fewer facts stored; remaining judge objections are inferred details on long legal/finance transcripts (numbers and open items in the feature flow)

Follow-up in this PR (2026-10-30): provenance, dated lines, recency, Haiku 5.5

Same default-off switch; four additions after the first review of the branch.

  • Provenance journal. agent_memory_fact_events: one append-only 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.updated_by_execution_id is the last run that rewrote or retired the row (execution_id stays the run it was born in). 90-day retention per agent. Owner route GET /api/agents/{name}/retrieval-memory/events?fact_id=&execution_id=&op= (owner + human-only). This is the corpus the extraction prompt gets tuned against: op=screened is what the extractor proposed that never became a fact, op=none beside its neighbour_ids is what reconcile judged a duplicate. SQLite agent_memory_provenance + Alembic 0110_agent_memory_provenance; AGENT_REFS cascade.
  • Dated lines. recall 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 itself. Execution ids never enter the prompt. recall_records returns the records with relevance and score.
  • Recency-weighted ranking. services/memory_ranking.py, a numpy-only leaf: 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 = 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. Picked on a sweep over the dated dataset (tests/unit/fixtures/ent1022_recency_dataset.json, 12 facts / 7 queries incl. a Ukrainian one): 0.7 failed the superseded-deadline case, 0.5 would let a fresh weak match win. The reconcile neighbour search passes no timestamps.
  • Model. claude-haiku-5-5, thinking: disabled + output_config.effort: low (one-shot JSON; max_tokens stays the text budget), and the reader takes the first TEXT block rather than content[0], which is a thinking block on this generation. Not verified against the live API from this machine (the local key's account has no credit); the request shape follows the published Haiku 5.5 migration notes (disabled accepted at low/medium/high).

Deferred (recorded in the feature flow)

BM25/FTS adapter behind the same port pending ent#634; a retention floor for facts; cross-scope beyond the owner; the enterprise Workspace surface for the owner view and the journal (ent#962); backfill of historical chat; an as_of date the extractor reads off the exchange itself (the rendered stamp is the revision date, not the event's).

Fixes abilityai/trinity-enterprise#1022

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

system_settings keys introduced, all additive with a working default: trinity_memory_enabled (default false — the switch, Settings → General), trinity_memory_recency_half_life_days, trinity_memory_daily_retain_limit (ranking / retention tuning, defaults in memory_service), and the per-agent agent_ownership.memory_opt_out column (NULL ⇒ not opted out). Nothing changes for an install that never touches them.

Open-core placement: OSS core, not entitlement-gated — per the ent#172 ruling that retrieval is never gated (governance is the enterprise seam).

User docs: #4118 carries the docs/user-docs/ page for this and the two stacked PRs.

🤖 Generated with Claude Code

… 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]>
@trinity-ability trinity-ability added the ui PR touches the frontend UI — triggers Playwright e2e tests label Oct 30, 2026
@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

✅ Alembic head check clear — merging this PR into dev leaves one head (0107_skill_sources_follow_bundled_pin).

Previously flagged; resolved.

Advisory — this check does not block merge. · head_sha: 17af144543062d59d4795da32f031e248b1eac17 · run

trinity-ability and others added 4 commits October 30, 2026 07:21
…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]>
@github-actions

Copy link
Copy Markdown

⚠️ Live-instance suite skipped — merge conflict against dev.

Resolve by merging dev locally and pushing the result; the next nightly re-tests.

trinity-ability and others added 3 commits October 30, 2026 13:39
…o image-internal env reads are documented (trinity-enterprise#1022)

validate-pr WARNs on PR #4102: the environment half of the dependency-pin test raised PackageNotFoundError on a checkout without fastembed (CI installs it; the Dockerfile ↔ requirements half still runs), and TRINITY_MEMORY_EMBEDDING_MODEL / FASTEMBED_CACHE_PATH were read by memory_embeddings.py but named nowhere outside the Dockerfile.

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

looks_like_email's domain runs overlapped on the dot, so a long dotted value
in the owner route's `user_email` query blocked the event loop (~2 s at 32 KB).
Same anchored shape and 320-char cap as client_portal.normalize_client_email.

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

vybe commented Oct 31, 2026

Copy link
Copy Markdown
Contributor

merge-train pushed two commits to this branch:

  • A merge of current dev. There were no conflicts, and the Alembic check still reports one head (0110_agent_memory_provenance).
  • 09ab8378b, which fixes CodeQL alert 461 (py/polynomial-redos, high) in memory_subject.looks_like_email. The regex now has the same anchored shape and 320-character cap as client_portal.normalize_client_email.

One behaviour change: [email protected], [email protected] and [email protected]. no longer count as email addresses. Tests for the new behaviour are in TestLooksLikeEmail.

@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: all checks green on 09ab837 against the current dev tip, including the CodeQL fix.

@vybe
vybe merged commit d5ae073 into dev Oct 31, 2026
29 checks passed
vybe pushed a commit that referenced this pull request Oct 31, 2026
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 pushed a commit that referenced this pull request Oct 31, 2026
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 pushed a commit that referenced this pull request Oct 31, 2026
…_memory, search box (ent#1028) (#4114)

* 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): search on demand — owner route, agent door + MCP search_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]>

* fix(memory): an owner's search is a look, not a use; a broken embedder 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]>

* fix(memory): the agent search door is agents-only — a human is sent to 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]>

* fix(memory): the agent search door serves only the live turn, and every 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]>

* fix(memory): the search box claims no count on a failed first search 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]>

---------

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 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]>
AndriiPasternak31 added a commit that referenced this pull request Oct 31, 2026
One conflict, src/backend/db/migrations.py: dev (#4091, #4102) and this
branch each added migration functions and appended MIGRATIONS entries after
execution_chat_session_id. Both kept, dev's first, so
platform_alert_subjects_resweep stays last. tests/registry.json auto-merged
with no duplicate rows (617 rows, each file once).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
AndriiPasternak31 added a commit that referenced this pull request Oct 31, 2026
…3254)

dev gained 0107_skill_sources_follow_bundled_pin (#4091) off 0106, then
0108_agent_memory_facts, 0109_agent_ownership_memory_opt_out and
0110_agent_memory_provenance (#4102) on top, so 0107_platform_alert_resweep
forked the Alembic head again. Renamed to 0111_platform_alert_resweep with
down_revision = "0110_agent_memory_provenance", in every place the id
appears: the file and its Revision ID / Revises lines, the migrations.py
"Mirrored by" docstring, the tests/registry.json row,
requirements/security.md (2 lines) and feature-flows/operating-room.md. A
re-chain, not a merge revision: the revision has never been applied
anywhere. The upgrade body is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw
vybe pushed a commit that referenced this pull request Nov 1, 2026
…(closing slice) (#4022)

* fix(operator-queue): run the platform-alert upgrade sweep a second time (#3254)

The #3246 sweep (SQLite platform_alert_subjects / Alembic 0090) ran once,
on the upgrade that carried it. Every emitter #3254 moves onto the seam
kept filing rows with no subject until its move landed, and the seam
cannot see such a row: observe files a second pending row beside it,
clear cannot end it, and the snooze cannot see a person's ending of it.

A data-only pair re-runs the unchanged run_platform_alert_sweep:
SQLite platform_alert_subjects_resweep (appended to MIGRATIONS) and
Alembic 0104_platform_alert_resweep (down_revision 0103). The subject's
existing holder keeps the slot whatever its age (#3255's rule), else the
newest pending row stays; the rest end as one superseded batch by the
platform. Agent-raised and gate rows and the gitignore / problem-report
rows are never touched. No DDL on either track; downgrade is a no-op,
as in 0090.

tests/unit/test_3254_second_sweep.py drives both halves against the
real post-#3246 operator_queue DDL for 18 derivable families, the
fresh-install lifecycle, idempotency, and the Alembic upgrade() on
SQLite and (requires_postgres) on PostgreSQL.

* docs(requirements): mark platform alerts done and name every kind (#3254)

#3254 completes OPS-001-PLATFORM-ALERTS, so the lines that described
the half-moved state become false on its merge:

- requirements/security.md section 26.14: status Partially -> Implemented,
  the ratchet's real name EMITTERS_NOT_YET_ON_SEAM (empty), each lifetime
  class names its kinds, the upgrade sweep in the past tense plus its
  second run, and the Files list gains the moved emitters; the flood alert
  and the #1677 budget bullets name observe as the write path and the
  episode's subject alert_budget:<type>.
- requirements/core-agent.md, github.md, scheduling.md: the problem
  report, gitignore, sync-diverged and poison write paths.
- architecture/backend.md (platform_alerts.py), reliability.md (the two
  backup kinds), workspace.md (the problem report).

Path tokens and status lines only; no requirement text changes meaning.

* docs(feature-flows): the moved alarms report through platform_alerts (#3254)

The flow lines that state the old direct-create write path or a minted
request-id shape, now that every in-repo platform emitter reports
through platform_alerts.observe / clear:

- git-sync-health.md: the two queue rows and the poller tree (sync
  failing, sync diverged, the two git-bloat kinds; row types kept).
- database-backup.md: two kinds keyed by backup_dir, 14-day lifetime,
  ended on the next ok.
- operating-room.md: the flood alert, the #1677 exemption paragraph,
  poison, the seam section's "only four families" (plus the second
  sweep), the flood/episode side effects (operator_queue_sync), and a
  current-path note on the two #1677 revision-history rows.
- effect-idempotency.md, github-sync.md, business-validation.md,
  system-manifest.md: the unguarded-effect, gitignore, validation and
  system-seed write paths.
- user-docs/operations/operating-room.md: sync alerts now end on their own.

* docs(git-sync): a divergence alert outlives a sync-failing freeze (#3254)

The sync_diverged row is filed only while a divergence freeze is in
force, but on the seam it stays for the whole episode: the platform ends
it when diverged_since clears, not when sync_failing takes precedence
over the freeze or the freeze stops. git-sync-health.md (the queue row)
and requirements/github.md ("No item for red-but-not-frozen") now say
both halves.

* docs: seven more write-path statements the #3254 batch makes false (#3254)

Found by review sweeps for the old write-path tokens (this slice's, and
the backup/archive, retention and boot-housekeeping slices'), and folded
into this slice because it is the one that carries the docs:

- architecture/api-endpoints.md (ingestion caps): the third copy of the
  #1677 paragraph and of the flood-alert sentence now name observe as the
  write path, the kind's budgeted_type, the created-only notification and
  the episode's subject alert_budget:<type>.
- architecture/reliability.md (the #1644 blast-radius guard): the
  retention alarm is a platform alert, one row per setting; "delivered"
  means observe returned created/updated/snoozed; the row's lifetime,
  6-hour refresh, note_allowed clear and material keys are stated. The
  sentences that stay true are unchanged.
- requirements/core-agent.md (problem report): a re-rate updates the day's
  pending item in place, the words reach it through observe's keep_text,
  and the click/comment order is decided inside the per-agent create lock
  (update_pending_problem_report and the second attach are gone).
- requirements/roadmap.md: the system-seed alarms report through observe
  (subject system_seed:<kind>) and a later successful seed ends them.
- requirements/infrastructure.md (BKUP-013): the backup alarms report
  through observe as two subjects, db_backup_failure and db_backup_stale,
  each ended by the platform on the next ok.
- migrations/GIT_REMOTE_TOKEN_SCRUB_2026-09.md: the unreadable-workspace
  alarm is one row per agent, updated by each sweep and ended by the
  platform once a sweep can inspect the workspace (no longer one per day).

Path tokens and status lines only.

* docs: six more live lines that still stated the old alert write path (#3254)

Fresh review of the closing slice, each line read against the merged code:

- user-docs operating-room: every platform alert is now a condition (the
  "other platform alerts still file one card per event" sentence is
  gone), and the four kinds that need a person and never expire are named.
- architecture agent-lifecycle and background-services: the divergence
  alert is the `sync_diverged:<agent>` subject on the seam, ended when
  its episode ends, not a `sync-diverged-{agent}-{diverged_since}` id
  collapsed by the request-id conflict target.
- feature-flows operating-room: platform callers report through
  `platform_alerts.observe`; the five budgeted kinds are bounded inside
  its locked create (no `create_bounded_alert` route); the #3246 history
  row says the rest moved with #3254.
- requirements security: the validation notifier is on the seam.
- feature-flows git-sync-health: the maintenance alert ends only on the
  agent's own repack report, and a persisting condition is re-read every
  6 h rather than filed once.

* fix(migrations): chain the #3254 re-sweep after dev's head as 0105 (#3254)

dev gained 0104_agent_sync_state_git_stats_at (#4006), which also revised
0103_a2a_caller_identity. With both on dev the version line had two heads,
and `alembic upgrade head` on PostgreSQL would apply nothing (#2068).

The re-sweep becomes 0105_platform_alert_resweep, revising
0104_agent_sync_state_git_stats_at. The id is renamed everywhere it
appears: the file, its Revision ID / Revises lines, the migrations.py
docstring, the tests/registry.json row, requirements/security.md §26.14
and feature-flows/operating-room.md. The SQLite entry stays last in
MIGRATIONS, after agent_sync_state_git_stats_at. The revision has never
been applied anywhere (the branch is unmerged), so a re-chain is correct
and a merge revision is not needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw

* docs(operator-queue): the snooze silences one episode; the flood, budget, gitignore, backup and archive markers (#3254)

dolho's I1 on this PR: these docs stated the platform-alert snooze as
"the same reading files nothing for 7 days", which #4021's review fix
(the flood, budget and gitignore kinds) and #4017's (the backup and log
archive kinds) narrow to one episode. Each of those kinds now carries an
episode marker that it lists as a material key, so a person's ending
silences re-reads of that episode and a new episode files at once:
queue_flood episode_started_at, alert_budget filled_by, gitignore_untracked
push_id, db_backup_failure / db_backup_stale last_success_at,
log_archive_unwritable last_writable_at.

Also stated, as those branches implement it:
- the flood cooldown is stamped before an episode's first reading only,
  and the 6-hour re-read is OPERATOR_QUEUE_FLOOD_REREAD_SECONDS;
- a stale-backup re-alarm is stamped only when the reading landed, so a
  snoozed one is re-read daily; the weekly gate is not reset by an ok;
- a keyless (pre-upgrade) ending of the inbox collision, a final-ending
  kind, files once more (#4020); for the snoozing kinds it counts as
  unchanged, which leaves an upgrade-day residual of at most 7 days.

Lines: requirements security.md §26.14 (snooze, flood, budget),
infrastructure.md BKUP-013, github.md; architecture reliability.md;
flows operating-room.md, database-backup.md, github-sync.md; and
user-docs operations/operating-room.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw

* fix(migrations): chain the #3254 re-sweep after dev's head as 0107 (#3254)

dev gained 0105_idempotency_claim_token (#3921) and
0106_execution_chat_session_id (#3918) off 0104, so 0105_platform_alert_resweep
forked the Alembic head again. Renamed to 0107_platform_alert_resweep with
down_revision = "0106_execution_chat_session_id", in every place the id
appears: the file and its Revision ID / Revises lines, the migrations.py
"Mirrored by" docstring, the tests/registry.json row, requirements/security.md
section 26.14 (2 lines) and feature-flows/operating-room.md. A re-chain, not
a merge revision: the revision has never been applied anywhere. The upgrade
body is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw

* docs(approvals): every platform heads-up is on the one-row model now (#3254)

approvals.md still said the other platform heads-ups file one row per event
and move onto the model in a later release. With #3254's last slice every
in-repo emitter is on the seam (EMITTERS_NOT_YET_ON_SEAM is empty), so the
sentence now says that, and names the four person-only kinds that never
expire, in the operating-room page's words.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw

* fix(migrations): chain the #3254 re-sweep after dev's head as 0111 (#3254)

dev gained 0107_skill_sources_follow_bundled_pin (#4091) off 0106, then
0108_agent_memory_facts, 0109_agent_ownership_memory_opt_out and
0110_agent_memory_provenance (#4102) on top, so 0107_platform_alert_resweep
forked the Alembic head again. Renamed to 0111_platform_alert_resweep with
down_revision = "0110_agent_memory_provenance", in every place the id
appears: the file and its Revision ID / Revises lines, the migrations.py
"Mirrored by" docstring, the tests/registry.json row,
requirements/security.md (2 lines) and feature-flows/operating-room.md. A
re-chain, not a merge revision: the revision has never been applied
anywhere. The upgrade body is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw

* docs(operator-queue): a new divergence episode files after a person's ending (#3254)

#4016 gives `sync_diverged` the material key `diverged_since`, so a
person's ending snoozes re-reads of the episode they ended and a later
episode files its own row inside the 7 days. Three lines said otherwise:

- user-docs/operations/operating-room.md (Sync Health Alerts): drop
  "unless you dismissed the last one within the past 7 days".
- requirements/github.md (one item per episode): drop "unless a person
  ended the last one inside the 7-day snooze" and name the material key.
- requirements/security.md 26.14 (Snooze): add `sync_diverged`
  `diverged_since` to the episode markers. It stays out of the
  upgrade-day residual list: the pre-move emitter wrote `diverged_since`
  into every row's context, so a person-ended legacy row carries it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw

* docs(operator-queue): name the sync_failing exception to the episode rule (#3254)

The general rule says only the episode a person ended stays quiet. That
holds for every kind with an episode marker, but `sync_failing` has none:
its context (`last_sync_at`, `consecutive_failures`, the error excerpt)
moves on every reading and the priority is always high, so after a
person's ending, a new run of failures inside the 7-day snooze files
nothing, even across a successful sync. The rule now says so, and that
the sync-health dot still turns red.

Kept as its own commit: drop it if #4016 gives `sync_failing` an episode
marker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01HWna79vVmnezQdhpaGRKbw

---------

Co-authored-by: Claude Opus 5.5 <[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.

3 participants